var populate_table = function($sel, data) {
	
	// Remove old.
	$sel.find('table.variant-attributes tbody tr').remove();
	$uom = '';
	
	// Build the details into the variant table...
	for(d = 0, l = data.attribute.length; d < l; d++) {
		
		if(data.attribute[d].att_fname == 'unit-of-measure') {
			// alter all unit of measures.
			$sel.find('.unit-of-measure').text(data.attribute[d].att_value.toLowerCase() + 's');
			$uom = 'per ' + data.attribute[d].att_value.toLowerCase();
			continue;
		}
		
		new_row = $('<tr />').addClass('attribute').append(
			$('<th />').text(data.attribute[d].att_name),
			$('<td />').text(data.attribute[d].att_value)
		);

		$sel.find('table.variant-attributes tbody').append(new_row);
	}

	// Put the price in (!)...
	// @TODO in Phase2
	// 		 just uncomment the below to put the price in:
	$sel.find('table.variant-attributes tbody').append(
		$('<tr />').addClass('attribute price').append(
			$('<th />').text("Price (" + $uom + ")"),
			$('<td />').html(data.price_string)
		)
	);

}

var bind_livesearch = function() {

	$('input.live-search').kakartLiveSearch({
		overallContainer: '.selectors ul li.last',
		source: '/livesearch/',
		resultsContainer: '.sub-live-search',
		maxResults: 0,
		triggerOnEmpty: false,
		itemTemplate: function(index, item) {
			return '<li>\
						<a href="#" id="v' + item.product_id + '-' + item.variant_id + '">\
							<span class="name">' + item.product_name + '</span>\
							<span class="variant">' + item.value_name + '</span>\
							<span class="type">' + item.product_root_category.substr(0, item.product_root_category.length - 1) + '</span>\
						</a>\
					</li>';
		}
	});
	
	$('input.live-search:not(.populate,.no-blur)').each(function(index) {

		// If it's empty, lets give it a msg.
		if($(this).val() == '') {
			$(this).val($(this).attr('title'));
		}
		
		$(this).blur(function() {
			$(this).val($(this).val() == '' ? $(this).attr('title') : $(this).val());
		});
		
		$(this).click(function() {
			$(this).val($(this).val() == $(this).attr('title') ? '' : $(this).val());
		});
	});
}

$(function() {
	
	// Get the last uri segment - ignore any anchors.
	var $last_uri_biscuit = location.href.split('/').pop();
	if(-1 !== $last_uri_biscuit.indexOf('#')) {
		$last_uri_biscuit = $last_uri_biscuit.match(/([a-z\-\_]+)/i)[0];
	}
	
	var fasttrackCloseTrigger 	= false;
	var fasttrackSampleTrigger	= false;
		
	var SLIDER_CLOSED 			= 235;
	var SLIDER_OPEN				= 620;
	
	$('select#product_id').change(function(data, arbitary) {
		
		var data = data || [];
		var autoset = arbitary || { colourway_id: '0' };
		
		$sel = $(this).parents('div.fast-track');
		
		// Remove the Colourway selector.
		if($(this).val() == '') {

			$sel.find('select#colourway_id').fadeOut(250, function() {
				$(this).find('option:gt(0)').remove();
			});
			
			return;
		}
		
		// Reshow if hidden.
		$sel.find('select#colourway_id:hidden').fadeIn(250);
		
		// If it just changed and the slider is open, we'll go to the 'please select cway'
		// option.  Contract it!		
		if(parseInt($sel.css('width')) == SLIDER_OPEN) {
			
			$sel.find('div.image, div.details, div.buttons').hide();
			$sel.animate({ width: '235px' }, 500, 'easeOutQuint', function() {
				// Closed at this point.
			});
		}
		
		// Remove existing Colourways.
		var original_message = $sel.find('select#colourway_id option:first-child').text();
		$sel.find('select#colourway_id option:first-child').text('Loading...');
		$sel.find('select#colourway_id').find("option:gt(0)").remove();

		// Request list of Colourways.
		$.post('/fasttrack/ajax_get_colourway', $sel.find('select#product_id').serialize(), function(data) {
			
			$sel.find('select#colourway_id option:first-child').text(original_message);
			for(d = 0, l = data.length; d < l; d++) {
				new_option = $('<option />').text(data[d].colourway_name).val(data[d].colourway_id);
				$sel.find('select#colourway_id').append(new_option);				
			}
			
			// If thre is only one
			if(l == 1) {
				$sel.find('select#colourway_id option:last-child').attr('selected', true);
				$sel.find('select#colourway_id').trigger('change');
			}

			if(autoset.colourway_id > 0) {
				$sel.find('select#colourway_id option[value="' + autoset.colourway_id + '"]').attr('selected', true).parent().trigger('change');
			}
		}, 'json');

	});
	
	$('select#colourway_id').change(function() {
		
		$sel = $(this).parents('div.fast-track');
		
		if($(this).val() == '') {
			return;
		}
		
		// Remove any text in this selectors livesearch box.
		$sel.find('input.live-search').val('').blur(function() { $(this).val(''); });
		
		// AJAX POST.
		$.post('/fasttrack/ajax_get_details', $sel.find('select#colourway_id').serialize(), function(data) {
			
			// Are we already open?
			// Closed: 235, Open: 620.
			var current_width = parseInt($sel.css('width'));

			if(current_width == SLIDER_OPEN) {
				
				// Fade out table
				$sel.find('div.details').fadeOut(250, function() {
				
					// Replace Image.
					$sel.find('div.image').fadeOut(250, function() {
						
						$(this).find('#colourway_image').attr('src', data.image);
						
						$(this).fadeIn(250, function() {

							// Repopulate the table.
							populate_table($sel, data);

							// Fade the table back in.
							$sel.find('div.details').fadeIn(250, function() {
								
							});

						});
					});
					
				});
				
			}
			else {
				
				// Change the image.
				$sel.find('#colourway_image').attr('src', data.image);
			
				// Slide it right...
				$sel.animate({ width: '332px' }, 500, 'easeOutQuint', function() {
				
					// Fade the Image in...
					$(this).find('div.image').fadeIn(250, function() {
						
						// Populate the Table
						populate_table($sel, data);
						
						if($last_uri_biscuit == 'samples') {
							
							$.post('/fasttrack/ajax_get_samples', $sel.find('select#product_id').serialize(), function(data) {
								
								if(data.length == 0)
									return;
									
								$sample_table = $sel.find('table.sample-types tbody');
								$sample_select = $sel.find('select#sample_type_id');
								$sample_table.find('tr').remove();
								$sample_select.find('option').remove();
								
								$.each(data, function(i, sample) {
									$sample_table.append('<tr />');
									$tr_pointer = $sample_table.find('tr:last-child');
									$tr_pointer.css({ display: fasttrackSampleTrigger ? 'table-row' : 'none' });
									
									sample_price = parseFloat(sample.sample_price) == 0.0 ? 'FREE' : '&pound;' + sample.sample_price;
									$price_span = $('<span />', { css: { 'float': 'right' }, html: sample_price });
									$tr_pointer.append($('<td />', { html: $('<span />', { html: $('<a />', { href: '#', title: sample.sample_description, text: sample.sample_name, 'class': 'sample-link', id: 'sample_' + sample.sample_id }) }), style: 'background: #f6efe5; padding: 2px 5px;' }));
									$tr_pointer.find('td').append($price_span);
									
									// Append it to the select as well.
									$sample_select.append($('<option />', { value: sample.sample_id, text: sample.sample_name }));
								});

							}, 'json');
						}
						
						
						// Remove any saved value
						$quantity_selector = $sel.find('.quantity-holder input');
						$quantity_selector.val('');
						
						// Then Slide again for the details...
						$sel.animate({ width: '620px' }, 500, 'easeOutQuint', function() {
						
							// Then Fade the details in...
							$(this).find('div.details').fadeIn(250, function() {
							
								// Finally, Fade in the buttons...
								if($('.fast-track-item').length == 1) {
									$('div.remove-row').hide();
								}
								else {
									$('div.remove-row').show();
								}
									
								$sel.parent().find('div.buttons, div.buttons div.add-row').fadeIn(250, function() {
									
									// Allow proceeding.
									$('.proceed-row').show();
									$quantity_selector.focus();
								});
							});
						});
					});
				});				
			}
		}, 'json');
	});
	
	$('.buttons .add-row a').live('click', function() {

		var this_quantity = parseFloat($(this).parents('div.fast-track-item').find('.quantity-input').val());
		if(isNaN(this_quantity) || this_quantity == 0) {
			$(this).parent().parent().parent().find('.err').fadeIn(250);
			$(this).parents('div.fast-track-item').find('.quantity-input').addClass('error');
			return false;
		}
		else {
			
			// Hide Error msg(s).
			$(this).parent().parent().parent().find('.err').hide();
			$(this).parents('div.fast-track-item').find('.quantity_selector').removeClass('error');
			$(this).parents('div.fast-track-item').find('input.live-search').addClass('no-blur');
			
			// Clone the last one.
			$clone = $('.fast-track-item:last').clone(true);
			
			// Update the 'number'.
			$clone.find('span.tab span.number').html($('.fast-track-item').length + 1);
			
			// Remove any existing data & hide.
			$clone.find('select#colourway_id option:gt(0)').remove();
			$clone.find('select#colourway_id').hide();
			$clone.find('input.live-search').val('type in keyword/product code').removeClass('no-blur');
			$clone.find('select#product_id option:eq(0)').attr('selected', true);
			
			// Hide the bits, and reset the size.
			$clone.find('div.image, div.details, div.buttons .add-row').hide();
			$clone.find('.fast-track').css({ width: '235px' });

			
			// Insert
			$('#fasttrack div.proceed-row').before($clone);
			
			// Rebind and reset
			bind_livesearch();
			
			// How many we got.
			if($('.fast-track-item').length > 1) {
				$('div.buttons .remove-row, .proceed-row').fadeIn(250);
			}
			else {
				$('div.buttons .remove-row').fadeOut(250);
			}
			
			// Hide this add button (since there should be a new one now)
			$(this).parent().fadeOut(250);
		}
		
		return false;
	});
	
	$('.buttons .remove-row a').live('click', function() {
		
		make_last_add = false;
		
		// Get the overall parent
		$removal = $(this).parents('.fast-track-item');
		
		// Remove the last row
		$removal.remove();
		
		// Fade the last Add button in (so there is one) ONLY IF the last is 'Open'
		if(parseInt($('div.fast-track-item:last .fast-track').css('width')) == SLIDER_OPEN) {
			$('div.fast-track-item:last .buttons .add-row:hidden').fadeIn(250);
			$('div.fast-track-item:last div.selectors input.live-search').removeClass('no-blur');
		}
		
		// re-number the SPANs.
		$('span.tab span.number').each(function(index) {
			$(this).html(index + 1);
		});
		
		// Hide remove buttons if there is now 1 or less.
		if($('.fast-track-item').length <= 1) {
			$('div.remove-row').fadeOut(250);
		}
		
		return false;
	});
	
	$('.sub-live-search ul li a').live('click', function() {

		$splitter = $(this).attr('id').substr(1).split('-');
		$parent_i = $(this).parents('.fast-track');
		
		$(this).parent().parent().parent().parent().find('input').val($(this).find('span.name').text());
		
		var product_id = $splitter[0];
		var colour_way = $splitter[1];
		
		// Change the product, and auto-load the variant.
		$parent_i.find('select#product_id').val(product_id).trigger('change', { colourway_id: colour_way });
		
		// Hide the live search
		if($parent_i.find('.sub-live-search').is(':visible')) {
			$parent_i.find('.sub-live-search').hide('slide', { easing: 'easeOutQuint', direction: 'up' }, 250, function() {
				// Remove all results in the panel
				//$(this).find('ul li').remove();
			});
		}
		
		return false;
	});
	
	$('.proceed-row a.proceed').click(function() {
		
		// Show the form.
		$('div#fasttrack-personal:hidden').show();
		
		// Hide add/remove buttons
		$('.add-row, .remove-row').hide();
		
		//
		$('.fast-track-item .fast-track').each(function() {
			if(parseInt($(this).css('width')) < SLIDER_OPEN) {
				// This item isn't open, so it is probably not 'complete'.
				$(this).parent().remove();
			}
		});
		
		// Hide the proceed button.
		$('div.proceed-row:visible').hide();
		
		return false;
	});
	
	$('form#fasttrack').submit(function() {
		
		pageTracker._trackPageview('/goals/fast-track');
		return true;
		
		/*
		// Validate the form before it is posted.
		if(!validate($(this))) {
			alert('did not validate');
			return false;
		}
		
		// Validation passed.  Hide it.
		$(this).find('.validation').hide();
		
		// Show that we're sending & hide
		// all the other LIs.
		$(this).find('.aj-block').show();
		$(this).find('#fasttrack-personal li:gt(1)').hide();
		
		// Now send this via AJAX.

		var serialized_form = $(this).serialize() + '&json=1';
		$.post('/products/sample', serialized_form, function(data) {
			
			// Update img
			$('form#fasttrack .aj-block img').attr('src', '/skin/landw/image/icon/email-sent.png').fadeIn(250);
			$('form#fasttrack .aj-block .ajax_msg').html($('<a />').text(data.message).click(resetFastTrackPage = function() {
				
				// Hide self, and reset.
				$('#fasttrack-personal').find('input[type="text"],textarea').val('');
				$('#fasttrack-personal').find('li.validation, li.aj-block').hide();
				$('#fasttrack-personal').hide();
				
				// Reset loader.
				$('form#fasttrack .aj-block img').attr('src', '/skin/landw/image/ajax-loader.gif').show();
				$('form#fasttrack .aj-block .ajax_msg').html('Sending your request to Lewis & Wood&hellip;');
				
				// Remove all but the first item
				$('.fast-track-item:gt(0)').remove();
				
				// With the first one, reset it.
				$first = $('.fast-track-item:eq(0)');
				$first.find('.quantity_selector option:eq(1)').attr('selected', true);
				$first.find('div.image,div.details,div.buttons').hide();
				$first.find('select#product_id option:eq(0)').attr('selected', true);
				$first.find('select#colourway_id').hide();
				$first.find('.fast-track').css({ width: SLIDER_CLOSED + 'px' }).find('input.live-search').removeClass('no-blur');
				$('#fasttrack-personal').find('li:gt(1)').show();
				
				clearTimeout(fasttrackCloseTrigger);
			}));
			
			pageTracker._trackPageview('/goals/fast-track');
			
			fasttrackCloseTrigger = setTimeout(resetFastTrackPage, 4000);
			
		}, 'json');
		
		return false;
		*/
	});
	
	$('.cancel-fasttrack').click(function() {
		
		// Hide the Personal Details stuff
		$('#fasttrack-personal').hide();
		
		// Now, find the last one and bring the +add back!
		$('div.fast-track-item:last .buttons .add-row:hidden').fadeIn(250);
		
		// Fade in the remove buttons!
		if($('.fast-track-item').length > 1) {
			$('div.remove-row').fadeIn(250);
		}
		
		// Re-show the 'next' button
		$('div.proceed-row:hidden').show();
		
		return false;
	});

	$('a.showhide-samples').live('click', function() {
		
		// invert the Sample trigger.
		fasttrackSampleTrigger = !fasttrackSampleTrigger;
		
		$table = $(this).parents('table');
		if($table.find('tbody tr:eq(0)').is(':visible')) {
			$table.find('thead a').text('Show sample types and prices');
			$table.find('tbody tr').hide();
		}
		else {
			$table.find('thead a').text('Hide sample types and prices');
			$table.find('tbody tr').show();
		}
		
		return false;
	});
	
	$('a.sample-link').live('click', function() {
		$sample_id = $(this).attr('id').substr(7);
		$(this).parents('.fast-track').find('#sample_type_id').val($sample_id);
		$(this).parents('.fast-track').find('.quantity-input').val('1').select();
		$('a.showhide-samples').parents('table').find('thead a').text('Show sample types and prices').end().find('tbody tr').hide();
		return false;
	});

	// Bind.
	bind_livesearch();
});
