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++ ) {
            var label = '<label>' + $( selects[i] + ' label' ).html() + '</label>';
	    $( selects[i] ).html( label + noSelectHTML );
	}
	
	$('#rightcol-buynow input.btn-add-to-cart').bind('click.complete', completeSelects);

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


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

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

	var changeFun = function(select) {
		var selected = $('option:selected', select);
		var selectedId = '#' + $(select).attr('id').replace('sel-', '');

		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);
				var selectId = selects[nextIdx];
				var selectId = selectId.replace('#','sel-');
				$( selects[nextIdx] + ' select').attr('id', selectId );
				$( 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() + "']"; //prodString is products['paper type']
					}
				});
				
				var ctr = 0;
				for (var ix in eval(prodString) ) {
				    // populate our new list
					var newOpt = document.createElement('option');
				    if(ix!='color_url'){
					newOpt.setAttribute('value', ix);
					$(newOpt).html(ix);
				    
					if (nextIdx == 1) {
					    var temp_color = eval(prodString+"['" + ix + "']"); //retrieve object contained by ix (in this case, a color)
					    $(newOpt).attr('title', temp_color.color_url);
					}
					$( 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);
			        var selectId = selects[nextIdx].replace( '#', 'sel-' );
				$( selects[nextIdx] + ' select').attr('id', selectId );
				$( 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);
		}
		$( selects[nextIdx] + ' select').msDropDown();
	};

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

        $( '.sg-buy-form select' ).msDropDown();

        //setup select reaction fo Product Type ONLY
        $('#sel-buy-type').change(function(){
            var temp_val = $("#sel-buy-type").val();
                $(".c-promo .visual div").hide();
            if(temp_val.indexOf("SAVOY",0) != -1 && $(".main-savoy").length > 0){
                $(".c-promo .visual .main-savoy").show();
            }
            else if(temp_val.indexOf("ODEON",0) != -1 && $(".main-odeon").length > 0){
                $(".c-promo .visual .main-odeon").show();
            }
            else if(temp_val.indexOf("SHINE",0) != -1 && $(".main-shine").length > 0){
                $(".c-promo .visual .main-shine").show();
            }
            else if(temp_val.indexOf("CT",0) != -1 && $(".main-ct").length > 0){
                $(".c-promo .visual .main-ct").show();
            }
            else{
                $(".c-promo .visual .main").show();
            }
        });
        return;
}

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');
    $(selects[i] + ' select').msDropDown(); //refreshes the dropdown boxes after the real select boxes has been selected
}


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

