var blankSelectHTML = '<select><option>- Select -</option></select>';
var noSelectHTML = '<span>--</span>';
var selects = [ "#buy-type", "#buy-color", "#buy-weight", "#buy-size", "#buy-packaging", "#buy-quantity" ];


function completeSelects() {
	alert('You must select all the options in order to add this product to your cart.');
	return false;
}

function resetSelectsBelowSelect(id) {
	var startIdx = jQuery.inArray(id, selects);
	
	for ( var i = startIdx+1 ; i < selects.length ; i++ ) {
		$( selects[i] + ' select').replaceWith(noSelectHTML);
	}
	
	$('#rightcol-buynow input.btn-add-to-cart').bind('click.complete', completeSelects);

	
	$('#buy-price-label strong').html('');	
}


function initializeSelects() {
	$('#buy-type span').replaceWith(blankSelectHTML);
	
	$('#rightcol-buynow input.btn-add-to-cart').bind('click.complete', completeSelects);

	$.each(typeHeaders, function(i,n) {
		$('#buy-type select').append('<option value="' + n + '">' + n + '</option>');
	});
	$.each(prodHeaders, function(i,n) {
		$('#buy-type select').append('<option value="' + n + '">' + n + '</option>');
	});

	var changeFun = function(select) {
		var selected = $('option:selected', select);
		var selectedId = '#'+$(select).parent().attr('id');
		
		if ( selected.text() != '- Select -' ) {
			// if they selected an option...
			var nextIdx = jQuery.inArray(selectedId,selects)+1;
			if ( nextIdx < 5 ) {
				// if the select on which they have chosen is one of the first 5 selects
				if ( $( selects[nextIdx] + ' select' ).length > 0 ) {
					// check if they are just changing something which has already been selected
					resetSelectsBelowSelect(selectedId);
				}
			
				// set up our next list to populate
				$( selects[nextIdx] + ' span').replaceWith(blankSelectHTML);
				$( selects[nextIdx] + ' select').bind('change', function() {
					changeFun(this);
				});

				// put together our products tree 'query' which we will be eval'd later
				var prodString = "products";
				$('.sg-buy-form select option:selected').each( function() {
					if ( $(this).text() != '- Select -' ) {
						prodString += "['" + $(this).text() + "']";
					}
				});
	
				var ctr = 0;
				for (var ix in eval(prodString) ) {
					// populate our new list
					var newOpt = document.createElement('option');
					newOpt.setAttribute('value', ix);
					$(newOpt).html(ix);
					$( selects[nextIdx] + ' select').append(newOpt);
					ctr++;
				}
				if ( ctr == 1 ) {
					// if there's only 1 item in the new list, select it and trigger the change event to call this .function again
					$( selects[nextIdx] + ' select option:last').attr('selected','selected');
					$( selects[nextIdx] + ' select' ).trigger('change');
				}
			}
			else if ( nextIdx == 5 ) {
				// Packaging has been selected, prepare Quantity dropdown

				// we're at the last select:
				$( selects[nextIdx] + ' span').replaceWith(blankSelectHTML);
				$( selects[nextIdx] + ' select').bind('change', function() {
					changeFun(this);
				});

				for ( var j = 1 ; j < 11 ; j++ ) {
					var newOpt = document.createElement('option');
					newOpt.setAttribute('value', j);
					$(newOpt).html(j);
					$( selects[nextIdx] + ' select').append(newOpt);
				}
			}
			else {
				// Quantity was selected
				
				// get price & id
				var prodString = "products";
				$('.sg-buy-form select option:selected').each( function(index) {
					if ( index == 5 ) {
						// break out of the each at the Qty select because we don't want to add that to our to-be-eval'd prodString
						return false;
					}
		
					if ( $(this).text() != '- Select -' ) {
						prodString += "['" + $(this).text() + "']";
					}
				});

				var price = eval(prodString+"['price']");
				var id = eval(prodString+"['id']");
				
				var qty = $('#buy-quantity select option:selected').text();

				// prepare price for displaying
				price = eval(price + " * " + qty);

				// put price in page:
				var formattedPrice = $.format_money(price/100);
				$('#buy-price-label strong').html(formattedPrice);

				// modify form to add product to cart with values
				$('#rightcol-buynow input#item-id-action').attr('value',id);
				$('#rightcol-buynow input#qty-action').attr('value', qty);

				// let them add it to cart
				$('#rightcol-buynow input.btn-add-to-cart').unbind('click.complete');
			}
		}
		else {
			// otherwise they selected - Select -
			resetSelectsBelowSelect(selectedId);
		}
	};

	$('.sg-buy-form select').bind('change', function() {
		changeFun(this);
	});

}

function populateDropdowns( productType, color, weight, size) {
	var scrollTop = $(window).scrollTop();
	var scrollTime = 300+scrollTop/25;

	if ( scrollTop < 150 ) {
		scrollTime = 0;
	}

	// scroll to the top over 300 ms unless they have
	// scrolled less than 150px, in which case scroll up instantly
	// and populate the dropdowns
	$.scrollTo( "#top", scrollTime, { onAfter: function() {
			highlight($('#highlight-field'), '#6699cc', 1000);
			selectValFromDropdownI(productType, 0);
			selectValFromDropdownI(color, 1);
			selectValFromDropdownI(weight, 2);
			selectValFromDropdownI(size, 3);
			selectValFromDropdownI('1', 5);
		}
	});
}

function highlight(element, color, speed) {
	if (speed == null) speed = "fast";
	var e;
	var position;
	element.each(function() {
	    e = $(this);
	    position = e.css('position');
	    if (position != 'absolute')
	        e.css('position', 'relative');
		e.css('z-index','1000');
	    e.append($("<div>")
	        .css({
	            backgroundColor: color,
	            position: 'absolute',
	            top: -12,
	            left: -20,
	            zIndex: -1,
	            display: "none",
	            width: e.width()+40,
	            height: e.height()+20
	        }).fadeIn(speed/3).fadeOut(speed, function() { $(this).remove(); e.css('position', position); })
	
	      );
	});
}

function selectValFromDropdownI(val, i) {
		var optionsFound = $( selects[i] + " select option");
		optionsFound = jQuery.grep(optionsFound, function(el) {
			return $(el).attr('value') == val;
		});		
		$(optionsFound[0]).attr('selected','selected');
		$( selects[i] + ' select' ).trigger('change');
}


$(document).ready(function(){	
	initializeSelects();	
});
