var json_sku_info = '';

function show_add_to_cart_section(context, json_page, product_id) {

	/* Grab the latest state of infomation for the skus as a JSON string */
    new Ajax.Request(json_page, {
            method: 'get',
            parameters: {product_id: product_id},
            onSuccess: function(transport) {
                    json_sku_info = transport.responseJSON;
                    //alert(json_sku_info);
					
					/* Maintain state based on the sku info in the JSON string */
                    if (json_sku_info[0].SOONITEM == 'true' || json_sku_info[0].NOT_SELLABLE == 'true'){
						if($('buy-btn')) {
	                    	$('buy-btn').style.display = 'none';
	                    	$('buy-btn').onclick = '';
						}
                    	$('product-detail-banner').src=context+'/images/shop/banners/coming_soon_detail_banner.png';
						$('product-detail-banner').style.display = '';
					}else if(json_sku_info.length == 1){
						
						/* If there's only 1 sku, we don't need to use the smart dropdown logic */
						if(json_sku_info[0].INSTOCK != 'true'){
							/* If it's out of stock, we show the out of stock button and banner */
							$('buy-btn').style.display = 'none';															
							$('buy-btn').onclick = '';
							$('so-btn').style.display = '';
							if (json_sku_info[0].TYPE == 'LIMITED'){
								$('product-detail-banner').src=context+'/images/shop/banners/sold_out_detail_banner.png';
								$('product-detail-banner').style.display = '';
							}
							else{
								$('product-detail-banner').src=context+'/images/shop/banners/out_of_stock_detail_banner.png';
								$('product-detail-banner').style.display = '';
							}
						}else{		
							/* We don't need to expose the dropdowns, just quietly populate the dropdown with the designated
							values and marked them as the selected options */
							$('color_select').options.length = 0;
							$('size_select').options.length = 0;
							if(json_sku_info[0].COLOR != null){								
								//var opt = document.createElement('option');
								//opt.text = json_sku_info[0].COLOR;
								//opt.value = json_sku_info[0].COLOR_ID;
								//$('color_select').options.add(opt);
								$('color_select').insert(new Element('option', {value: json_sku_info[0].COLOR_ID}).update(json_sku_info[0].COLOR));								
							}
							if(json_sku_info[0].SIZE != null){
								//var opt = document.createElement('option');
								//opt.text = json_sku_info[0].SIZE;
								//opt.value = json_sku_info[0].SIZE_ID;
								//$('size_select').options.add(opt);
								 $('size_select').insert(new Element('option', {value: json_sku_info[0].SIZE_ID}).update(json_sku_info[0].SIZE));
							}
							if(json_sku_info[0].ALMOSTGONE == 'true'){
								$('product-detail-banner').src=context+'/images/shop/banners/almost_gone_detail_banner.png';
								$('product-detail-banner').style.display = '';
							}
							
							if($('casepack')) {
								$('casepack').style.display = '';
							}
						}
						
						/* Expose shopping cart form */
						$('product_add_to_cart_div').style.display = '';
						
					}else{
						var last_color = '';
						var moreThanOneColor = false;
						var atLeastOneInstock = false;										
						for(var x = 0; x < json_sku_info.length; x++){
							var color_value = json_sku_info[x].COLOR;
							if (last_color == '' || last_color == color_value){
								last_color = color_value;
							}else{
								moreThanOneColor = true;
							}
							if(json_sku_info[x].INSTOCK == 'true'){
								atLeastOneInstock = true;
							}										
						}
						if (moreThanOneColor){
							// new design shouldn't have more color. different colors will be seperated into differeent products
							$('product-detail-banner').src='/images/shop/banners/more_colors_detail_banner.png';
							$('product-detail-banner').style.display = '';
						}
						if (!atLeastOneInstock){
							$('buy-btn').style.display = 'none';															
							$('buy-btn').onclick = '';
							$('so-btn').style.display = '';
							$('product-detail-banner').src=context+'/images/shop/banners/out_of_stock_detail_banner.png';
							$('product-detail-banner').style.display = '';
						} else {
						
							//render the dropdown options
							handleProductOptionChange(json_sku_info);
                            jQuery.jNice.SelectUpdate(jQuery('#color_select'));
                            jQuery.jNice.SelectUpdate(jQuery('#size_select'));
							
							//add listener to update option onchange
	                        jQuery('.skuOptions').change(function(){handleProductOptionChange(json_sku_info)});
	                        
	                        $('color-select').style.display = '';
							$('size-select').style.display = '';	

							if($('casepack')) {
								$('casepack').style.display = '';
							}
						}
						
						$('wish_list_sku_id').value = ''; // force user to select a combo to add to wish list
						
						/* Expose shopping cart form */
						$('product_add_to_cart_div').style.display = '';
					}
                    
            }
    });
}

//returns an array of choice name
//("color", "size", "width", "height")
function getSkuOptions() {
	var skuOptions = new Array();
	var skuOptionsSelect = jQuery('.skuOptions');
	var skuOptionsArray = jQuery.makeArray(skuOptionsSelect);
	for(a = 0; a < skuOptionsArray.length; a++) {
		skuOptions[a] = skuOptionsArray[a].id.replace(/_select(.*)/, '');
	}
	return skuOptions;
}

function sort_sku_options(a,b){
	inta = parseInt(a);
	intb = parseInt(b);
	if (inta < intb) return -1;
	if (inta > intb) return 1;
	return 0 ;
}

// given the JSON string which includes the size/color combinations
// and corresponding Sku IDs, it will return the Sku ID
// for the given color and size
function get_sku_id(json, color_value_id, size_value_id) {
	for (var x = 0; x < json.length; x++) {
		var jsonEntry = json[x];
		
		if (jsonEntry.COLOR_ID == color_value_id && jsonEntry.SIZE_ID == size_value_id) {
			return jsonEntry.SKU_ID;
		}
	}
	
	return 0;
}

/*
 * This function will populate and render the dropdown options.  Only include "In Stock" options.
 */
function handleProductOptionChange(json_string, do_not_call_myself_again) {
	
	//get a list of sku options (color, size, height, width)
	var fields = getSkuOptions();
	
	//key = field::field_id
	//array keeping track of sku options value already included to be rendered in select dropdown
	var optionsRendered = new Array();
	
	//array initialized to hold possible sku option value for each sku option(s)
	var dropDownHolder = new Array();
	for(k = 0; k < fields.length; k++) {
		dropDownHolder[fields[k]] = new Array();
	}
	
	//parse json to determine available sku option values
	for(var x = 0; x < json_string.length; x++){
		
		var jsonEntry = json_string[x];
		for(i = 0; i < fields.length; i++) {
			
			var fieldValue = jsonEntry[fields[i].toUpperCase() + "_ID"];
			var fieldText = jsonEntry[fields[i].toUpperCase()];
			var fieldPriority = jsonEntry[fields[i].toUpperCase() + "_PRIORITY"];
			var fieldValueRef = jsonEntry[fields[i].toUpperCase + "_VALUE_REF"];
			
			//if we have this field option in the dropdown list, skip
			if(optionsRendered[fields[i] + '::' + fieldValue] != '1') {
				
				//check to see if this sku option value is available option based on already selected values or if no option value is select for sku option.
				for(f = 0; f < fields.length; f++) {
					
					if(
						(fields[f] == fields[i] || jQuery('#' + fields[f] + '_select').attr("selectedIndex") <= 0 || 
								jQuery('#' + fields[f] + '_select').attr("selectedIndex") == undefined)
	                        || (jsonEntry[fields[f].toUpperCase() + "_ID"] == jQuery('#' + fields[f] + '_select' + ' :selected').val())
	                   ) {
						
						if(f == fields.length -1) {
							
							if(jsonEntry['INSTOCK'] == 'true') {
								
								var displayFieldText = fieldText;
								
								dropDownHolder[fields[i]][dropDownHolder[fields[i]].length] = new Array(2);
								dropDownHolder[fields[i]][dropDownHolder[fields[i]].length - 1][0] = fieldPriority;
								dropDownHolder[fields[i]][dropDownHolder[fields[i]].length - 1][1] = '<option value="' + fieldValue + '" label="' + displayFieldText + '">' + displayFieldText + '</option>';
								
								optionsRendered[fields[i] + '::' + fieldValue] = 1;
							}
							
						}
						
					} else {
						break;
					}
					
				}
			}
		}
		
	}
	
	var product_options_changed = false;
	
	//unbind change event listener, otherwise every time we add or remove options, this function will get triggered.
	jQuery('.skuOptions').unbind('change');

	for(q = 0; q < fields.length; q++) {

    	var selectedOption = jQuery('#' + fields[q] + '_select' + ' :selected');
    	jQuery('#' + fields[q] + '_select').find('option').remove().end();
    	jQuery('#' + fields[q] + '_select').append('<option value="select">Select ' + fields[q].toLowerCase().charAt(0).toUpperCase() + fields[q].toLowerCase().replace("_", " ").substring(1) + '</option>');

    	//get possible option value(s) for sku option
    	dropDownHolder[fields[q]].sort(sort_sku_options);
        
    	//populate options value(s) for sku option
    	for(var a = 0; a < dropDownHolder[fields[q]].length; a++){
    		jQuery('#' + fields[q] + '_select').append(dropDownHolder[fields[q]][a][1]);
    	}
    	
    	//highlight user selected option value for sku option
		jQuery('#' + fields[q] + '_select').find("option[value='" + selectedOption.val() + "']").attr("selected","selected");
		
		//if there is only one option, select it as the default
		if(jQuery('#' + fields[q] + '_select').find('option').size() == 2) {
			jQuery('#' + fields[q] + '_select option:last').attr("selected", "selected");
			product_options_changed = true;
		}

		jQuery.jNice.SelectUpdate(jQuery('#' + fields[q] + '_select'));
    }

	// if color/size options are chosen, get the sku_id and set it into the "wish_list_sku_id" hidden field.
	// short term solution for ie7 bug.
	if ($('size_select').options.length == 2) {
		$('size_select').options.selectedIndex = 1;
	}

	// these are the selected ChoiceValue IDs, so find the corresponding Sku ID
	// and set into "wish_list_sku_id" hidden field.
	var selected_size_id = $('size_select').options[$('size_select').selectedIndex].value;
	var selected_color_id = $('color_select').options[$('color_select').selectedIndex].value;
	var selected_sku_id = get_sku_id(json_string, selected_color_id, selected_size_id);

	if (selected_sku_id > 0) {
		jQuery('#wish_list_sku_id').val(selected_sku_id);
	} else {
		jQuery('#wish_list_sku_id').val('');
	}
	
	//re-bind change event listener
    jQuery('.skuOptions').change(function(){handleProductOptionChange(json_string)});

    //if an option only has one possible choose, we will select it and recalculate all the options again.
    if(product_options_changed && !do_not_call_myself_again) {
    	handleProductOptionChange(json_string, true);
    }
}

function sku_instock_check(context, key){
	if ($('color_select').options[$('color_select').selectedIndex].value != 'select' &&
		$('size_select').options[$('size_select').selectedIndex].value != 'select')
	{
		new Ajax.Request(context+'/templates/ajax/sku_instock_check.jsp',
		  {
		    method:'get',
		    parameters: {product_id: key, color: $('color_select').options[$('color_select').selectedIndex].value, size: $('size_select').options[$('size_select').selectedIndex].value},
		    onSuccess: function(transport){
		    	var json = transport.responseJSON;
		      if (json.instock == 'false'){
			      $('message').innerHTML = "Out of stock. Please select another color/size.";
		      }else{
		    	  $('message').innerHTML = "";
		      }
		      $('wish_list_sku_id').value=json.sku_id;
		    },
		    onFailure: function(){  }
		  });
	}else{
		 $('message').innerHTML = "";
	 	$('wish_list_sku_id').value = '';
	}
}


function submit_checkout_form(context_path){
	// Validate customer has selected all necessary options
	
	//short term solution for ie7 bug.
	if($('size_select').options.length == 2)
        $('size_select').options.selectedIndex = 1;

	
	if ($('color_select').options[$('color_select').selectedIndex].value == 'select' ||
		$('size_select').options[$('size_select').selectedIndex].value == 'select')
	{
		alert('Please select all options.');
		return false;
	}
	
	if ($('message').innerHTML.indexOf('Out of stock') >= 0)
	{
		alert('Option selected is out of stock.');
		return false;
	}
	
	if( $('qty').value > 0 ){

	}else{
		alert('Please enter a quantity');
		return false;
	}
	
	// POST - async post because the user does NOT get taken to the shopping cart by design
	new Ajax.Request(context_path + '/servlet/Cart', {
		method: 'post',
		onSuccess: function(transport) {
			if (transport.getHeader("ACDC_ERROR") == 't') {
				$('checkout_message').style.display = '';
				$('checkout_message').innerHTML = '<strong>Your item cannot be added to cart.</strong>';
			} else {
				window.location = context_path + '/shopping/show_cart';
			}
		},
		postBody: get_form_values('checkout_form')
	});
	
	
}




function submit_checkout_casebuy_form(context_path, quantity){
	// Validate customer has selected all necessary options	
	//short term solution for ie7 bug.
	if($('size_select').options.length == 2)
        $('size_select').options.selectedIndex = 1;

	
	if ($('color_select').options[$('color_select').selectedIndex].value == 'select' ||
		$('size_select').options[$('size_select').selectedIndex].value == 'select')
	{
		alert('Please select all options.');
		return false;
	}
	
	if ($('message').innerHTML.indexOf('Out of stock') >= 0)
	{
		alert('Option selected is out of stock.');
		return false;
	}	
	
	// POST - async post because the user does NOT get taken to the shopping cart by design
	new Ajax.Request(context_path + '/servlet/Cart', {
		method: 'post',
		onSuccess: function(transport) {
			if (transport.getHeader("ACDC_ERROR") == 't') {
				$('checkout_message').style.display = '';
				$('checkout_message').innerHTML = '<strong>Your item cannot be added to cart.</strong>';
			} else {
				window.location = context_path + '/shopping/show_cart';
			}
		},
		postBody: get_form_buycase_values('checkout_form', quantity)
	});
	
	
}





//used for the case buy, click once, 12 items will be passed.
function get_form_buycase_values(form_id, quantity) {
	var str = "";
	var form = $(form_id);
	
	for (var i = 0; i < form.elements.length; i++) {
		switch (form.elements[i].type) {
			case "text":
				if(form.qty.name == 'quantity') {
					str += form.elements[i].name +
					"=" + quantity + "&";
				} else {
					str += form.elements[i].name +
					"=" + escape(form.elements[i].value) + "&";
				}
				break;
			case "hidden":
				str += form.elements[i].name +
				"=" + escape(form.elements[i].value) + "&";
				break;      
			case "button":
				str += form.elements[i].name +
				"=" + escape(form.elements[i].value) + "&";
				break;      
			case "select-one":
				str += form.elements[i].name +
				"=" + form.elements[i].options[form.elements[i].selectedIndex].value + "&";
				break;
			case "radio":
				if (form.elements[i].checked) {
					str += form.elements[i].name +
					"=" + escape(form.elements[i].value) + "&";
				}
				
				break;
			case "textarea":
				str += form.elements[i].name +
				"=" + escape(form.elements[i].value) + "&";
				break;
			case "password":
				str += form.elements[i].name +
				"=" + escape(form.elements[i].value) + "&";
				break;
			case "checkbox":
				if (form.elements[i].checked) {
					str += form.elements[i].name +
					"=" + escape(form.elements[i].value) + "&";
				}
				
				break;
		}
	}
	
	str = str.substr(0,(str.length - 1));
	return str;
}






//if not logged in, show the login box.
function add_to_saved_items(logged_in_check_page) {
	if ($('wish_list_sku_id').value == ''){
		alert('Please select all options.');
	}else{
		new Ajax.Request(logged_in_check_page, {
			method: 'get',
			parameters: {randid: Math.random()},
			onSuccess: function(transport) {
				var json = transport.responseJSON;
							
				if (json.logged_in == 'true') {
					$('add_to_saved_items').submit();
				} else {
					alert('Please login to add item to your wish list.');
				}
			}
		});
	}
}

