function updateQty(sku_id, qty){

	jQuery('#update_sku_id').val(sku_id);
	jQuery('#update_sku_qty').val(qty);
	
	document.cart_form.STEP.value=1;
	document.cart_form.submit();
}

function updateQty2(sku_id){
	var qty = jQuery('#qty_'+sku_id).val();
	updateQty(sku_id, qty);
}

function editItemOptions(){
	alert('implement me!');
}

function removeItem(sku_id){
	updateQty(sku_id, 0);
	/*
	var reply = confirm('Do you really want to remove this item?');
	if(reply == true){
		updateQty(sku_id, 0);
	}*/
}

function toggleItemOptions(sku_id){
	if(jQuery('#edit_'+sku_id).html() == 'Edit'){
		jQuery('#sku_option_row_'+sku_id).show();
		jQuery('#edit_'+sku_id).html('Cancel');
		
		if (!(jQuery.browser.msie && jQuery.browser.version < 7)) {
			jQuery("select").selectbox();
		}
		
	}else{
		jQuery('#sku_option_row_'+sku_id).hide();
		jQuery('#edit_'+sku_id).html('Edit');
	}
	
}

function changeProductOptions(sku_id,product_id,color_key,size_key){
	var qty = jQuery('#qty2_'+sku_id).val();

	jQuery('#update_sku_id').val(sku_id);
	jQuery('#update_sku_qty').val(qty);
	jQuery('#update_product_id').val(product_id);
	
	//color and size
	var color_el = $('color_select_'+sku_id);
	var color_value = color_el.options[color_el.selectedIndex].value;
	jQuery('#choiceName_'+color_key).val(color_value);
	
	var size_el = $('size_select_'+sku_id);
	var size_value = size_el.options[size_el.selectedIndex].value;
	jQuery('#choiceName_'+size_key).val(size_value);
	
	document.cart_form.STEP.value=2;
	document.cart_form.submit();
}


function populateProductOptions(context, json_page, product_id, subfix) {
	var json_sku_info = '';

	/* 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.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 */
							$('in_stock_span_'+product_id).hide();
                            $('add_to_cart_span_'+product_id).hide();
                            $('in_stock_span_'+product_id).innerHTML='Out of stock';
                            $('in_stock_span_'+product_id).show();
							//$('submit_link').onclick = '';
						}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_'+subfix).options.length = 0;
							$('size_select_'+subfix).options.length = 0;
							
							if(json_sku_info[0].COLOR != null){		
								jQuery('#color_select_'+subfix).append(jQuery("<option></option>").attr("value",json_sku_info[0].COLOR_ID).text(json_sku_info[0].COLOR));
							}
							if(json_sku_info[0].SIZE != null){
								jQuery('#size_select_'+subfix).append(jQuery("<option></option>").attr("value",json_sku_info[0].SIZE_ID).text(json_sku_info[0].SIZE));
							}
						}
					}else{
						/* smart dropdown logic */
						//$('color_select_'+subfix).onchange = function(){handle_sku_states2(json_sku_info, context, subfix)};	
						//$('size_select_'+subfix).onchange = function(){handle_sku_states2(json_sku_info, context, subfix)};
						handle_initial_dropdowns2(json_sku_info, context, subfix);						
						
						jQuery('#color_select_'+subfix).change(
							function(objEvent) {
								handle_sku_states2(json_sku_info, context, subfix);
							}
						);
						jQuery('#size_select_'+subfix).change(
							function(objEvent) {
								handle_sku_states2(json_sku_info, context, subfix);
							}
						);
					}
                    
                                        
                	/* Expose shopping cart form */
					//$('product_add_to_cart_div').style.display = '';
					
					/* re-render the dropdowns with the styled look-n-feel */
					if (!(jQuery.browser.msie && jQuery.browser.version < 7)) {
						jQuery("select").selectbox();
						
						//need to re-bind the onChange event.
						jQuery('#color_select_'+subfix).change(
							function(objEvent) {
								handle_sku_states2(json_sku_info, context, subfix);
							}
						);
						jQuery('#size_select_'+subfix).change(
							function(objEvent) {
								handle_sku_states2(json_sku_info, context, subfix);
							}
						);
					}
					
					/* Used by dressing room */
					if(jQuery('#buy_product_div_' + subfix) != null){ jQuery('#buy_product_div_' + subfix).hide(); }

				    gaTrackingOOSEvent();
      		}
    });
	
}

/* Enables/disables the add to cart functionality based on the inventory of the selected color/size combo */
var optionStockArr = new Array();
/* Enables/disables the add to cart functionality based on the inventory of the selected color/size combo */
function handle_sku_states2(json_string, context, subfix){
        var color_selected_index = $('color_select_'+subfix).options.selectedIndex;
        var size_selected_index = $('size_select_'+subfix).options.selectedIndex;
        var color_selected_value = $('color_select_'+subfix).options[$('color_select_'+subfix).options.selectedIndex].value;
        var size_selected_value = $('size_select_'+subfix).options[$('size_select_'+subfix).options.selectedIndex].value;
        var color_selected_text = $('color_select_'+subfix).options[$('color_select_'+subfix).options.selectedIndex].text;
        var size_selected_text = $('size_select_'+subfix).options[$('size_select_'+subfix).options.selectedIndex].text;

        /* Tells zoomify player to update images to newly selected color */
    	if(typeof selectVariation == 'function'){
        	selectVariation(color_selected_text);
    	}




        var foundMatchedSku = false;
        var imageSwapped = false;        
  		optionStockArr['milly_'+subfix] = false;

        for(var x = 0; x < json_string.length; x++){
                var color_value = json_string[x].COLOR;
                var size_value = json_string[x].SIZE;

                if(!imageSwapped && (color_value == color_selected_text)){
                        /* Tells dressing room to update images to newly selected color */
                        if(typeof show_dressing_room_images == 'function'){
                                show_dressing_room_images(json_string[x].IMAGE1, json_string[x].IMAGE2, json_string[x].IMAGE3, json_string[x].IMAGE4, json_string[x].IMAGE5);
                                imageSwapped = true;
                        }
                }

                if(color_value == color_selected_text && size_value == size_selected_text){
                        if(json_string[x].INSTOCK == "true"){
                                $('in_stock_span_'+subfix).innerHTML='In stock';
                                $('in_stock_span_'+subfix).show();                               
  								optionStockArr['milly_'+subfix] = true;
  								foundMatchedSku = true;
                        }else{
                                $('in_stock_span_'+subfix).innerHTML='Out of stock';
                                $('in_stock_span_'+subfix).show();
                                $('add_to_cart_span_'+subfix).hide();                             
                        }
                        //foundMatchedSku = true;


                }
        }
        var inStock = true;

		for(i in optionStockArr){
        	if(optionStockArr[i]==false){
                 	inStock = false;
        	}
		}

        if(color_selected_value != 'select' && size_selected_value != 'select'){
                if($('add_to_cart_span_' + subfix) != null){ $('add_to_cart_span_' + subfix).show(); }

                if(!foundMatchedSku){

                        $('in_stock_span_'+subfix).innerHTML='Out of Stock';
                        $('in_stock_span_'+subfix).show();

                        if($('add_to_cart_span_' + subfix) != null) $('add_to_cart_span_' + subfix).hide(); else  $('button_add_to_cart_span').hide();

                }else{
                        if($('add_to_cart_span_' + subfix) != null) {
                                $('add_to_cart_span_' + subfix).show();
                        } else  {
	                        	if($('button_add_to_cart_span'))
	                    		{
	                    			$('button_add_to_cart_span').show();
	                    		}
								if(inStock){
         							$('button_in_stock_span').show();
                                    $('button_out_of_stock_span').hide();
								}else{
									$('button_out_of_stock_span').show();
                                    $('button_in_stock_span').hide();
								}

                        }
                }
        }
        gaTrackingOOSEvent();
}



/* Initilizes the content the of the dropdowns via a JSON_string */
function handle_initial_dropdowns2(json_string, context, subfix){
	var color_group = {};
	var size_group = {};
	var sorted_color_options = new Array();
	var sorted_size_options = new Array();

	
	var color_counter = 0;
	var size_counter = 0;
	var needs_sorting = false;
	var available_size = "";
	var instock = true;
	
	for(var x = 0; x < json_string.length; x++){
		var color_value = json_string[x].COLOR;
		var size_value = json_string[x].SIZE;

		/* Make sure color dropdown exists, color option isn't already in dropdown, and color dropdown wasn't preselected */
		if(color_value != null && color_group[color_value] == null){
			$('color_span_'+subfix).style.display = '';
			needs_sorting = true;
			color_group[color_value] = '1';
			var opt = document.createElement('option');
			opt.text = json_string[x].COLOR;
			//if(json_string[x].INSTOCK == 'true'){			
			opt.value = json_string[x].COLOR_ID;
			sorted_color_options[color_counter] = new Array(2);
			sorted_color_options[color_counter][0] = json_string[x].COLOR_PRIORITY;
			sorted_color_options[color_counter++][1] = opt;
			//}		
		}
		if(size_value != null && size_group[size_value] == null) {      
            $('size_span_'+subfix).style.display = '';
            needs_sorting = true;
            size_group[size_value] = '1';
            var opt = document.createElement('option');
            opt.text = json_string[x].SIZE;
                        
            //if(json_string[x].INSTOCK == 'true' && sizeMatched(available_size, opt.text) == 'true' ){
                   opt.value = json_string[x].SIZE_ID;
                   sorted_size_options[size_counter] = new Array(2);
                   sorted_size_options[size_counter][0] = json_string[x].SIZE_PRIORITY;
                   sorted_size_options[size_counter++][1] = opt;
                   available_size = available_size + ";" + json_string[x].SIZE;
             //}
        }
		
		if(!json_string[x].INSTOCK)
		{
			instock = false;
		}

	}
	
	if((available_size == "") && (!instock)) {
         $('in_stock_span_'+subfix).hide();
         $('add_to_cart_span_'+subfix).hide();
         $('color_span_'+subfix).hide();
         $('size_span_'+subfix).hide();
         $('in_stock_span_'+subfix).innerHTML='Out of stock';
         $('in_stock_span_'+subfix).show();
    }
	
		
	if(needs_sorting){
		sorted_color_options.sort(sort_sku_options);
		sorted_size_options.sort(sort_sku_options);
		
		for(var a = 0; a < sorted_color_options.length; a++){
			//$('color_select_'+subfix).options.add(sorted_color_options[a][1]);
			jQuery('#color_select_'+subfix).append(jQuery("<option></option>").attr("value",sorted_color_options[a][1].value).text(sorted_color_options[a][1].text));
		}
		for(var b = 0; b < sorted_size_options.length; b++){
			//$('size_select_'+subfix).options.add(sorted_size_options[b][1]);
			jQuery('#size_select_'+subfix).append(jQuery("<option></option>").attr("value",sorted_size_options[b][1].value).text(sorted_size_options[b][1].text));
		}
	}
	
	if(sorted_color_options.length == 1){
		/* pre-select the only color */
		jQuery('#color_select_'+subfix +' option:nth-child(2)').attr('selected', 'selected');
	}
}

function sizeMatched(available_size, json_string_SIZE) {
        var output = 'true';
        available_size_array = available_size.split(";");
        for( var i=0; i<available_size_array.length; i++) {
                var pos = available_size_array[i];
                if( pos == json_string_SIZE){
                        output = 'false';
                }
        }
        return output;
}


function sort_sku_options(a,b){
	if (a[0] < b[0])return -1;
	if (a[0] > b[0])return 1;
	return 0 ;
}


function toggleGiftMessage(showGiftMessage){
	if(showGiftMessage){
		jQuery('#gift_message').show();
	}else{
		jQuery('#gift_message').hide();
		jQuery('#gift_message').val('');
	}
	
}

function applyPromoCode(success_checkout, context_path){
	jQuery('#promo_code').val(jQuery('#promo_code_input').val());
    document.cart_form.STEP.value = '7';//APPLY_PROMO_CODE_STEP
    
    if(success_checkout != ''){
    	document.cart_form.success_checkout.value = success_checkout;
    	document.cart_form.failure.value = '/shopping_cart/ajax/apply_promo_code_response_ajax.jsp';
    
    	/* If customer is applying promo code in the billing section, we have to make this request AJAX
    	so the customer doesn't lose their un-submitted billing info. */
    	
    	// 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) {
				$('apply_promo_div').innerHTML = transport.responseText;
				
				/* Make sure to reset the success and failure params on the shopping cart form */
				document.cart_form.STEP.value = '5';//APPLY_BILLING_STEP				
				document.cart_form.success_checkout.value = context_path + '/shopping_cart/order_placed.jsp';
				document.cart_form.failure.value = '/shopping_cart/billing.jsp';
			},
			postBody: get_form_values('cart_form')
		});
    }else{
    	document.cart_form.submit();
    }
}


function applyGiftCard(context_path){
	//jQuery('#promo_code').val(jQuery('#promo_code_input').val());
    document.cart_form.STEP.value = '11';//APPLY_GIFT_CARD_STEP
    
   
	document.cart_form.success_checkout.value = context_path+'/shopping_cart/ajax/apply_gift_card_response_ajax.jsp';
	document.cart_form.failure.value = '/shopping_cart/ajax/apply_gift_card_response_ajax.jsp';

	/* If customer is applying promo code in the billing section, we have to make this request AJAX
	so the customer doesn't lose their un-submitted billing info. */
	
	// 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) {
			$('gift-card-div').innerHTML = transport.responseText;
			
			/* Make sure to reset the success and failure params on the shopping cart form */
			document.cart_form.STEP.value = '5';//APPLY_BILLING_STEP				
			document.cart_form.success_checkout.value = context_path + '/shopping_cart/order_placed.jsp';
			document.cart_form.failure.value = '/shopping_cart/billing.jsp';
			
			reloadCartSummarynAndMore(context_path);
			
		},
		postBody: get_form_values('cart_form')
	});

}

function removeGiftCard(num, context_path){

	$('gift_card_number_'+num).value = '';
	$('num_gift_cards').value = $('num_gift_cards').value - 1; 
	//$('gift_card_number_field').value = '';
	applyGiftCard(context_path);

}

function reloadCartSummarynAndMore(context_path){
	new Ajax.Request(context_path + '/shopping_cart/inc/cart_summary.jsp', {
		method: 'post',
		onSuccess: function(transport) {
			$('cart_summary').innerHTML = transport.responseText;
			
			if ($('hide_billing').value != $('billing_hidden').value){
				location.reload(true);
			}
		}
	});
}

function validateCart(){
	var result = true;
	jQuery('.item_qtys').each(
			function(){
				if(this.value == '0'){
					jQuery('#qty_error').html('please remove your item instead of setting it to 0');
					jQuery('#qty_error').show();
					result = false;
				}
			}
	);
	
	return result;
}

function closePopup(popupId){
	jQuery('#'+popupId).hide();
}

function openPopup(popupId){
	jQuery('#'+popupId).show();
}

function printOrder(){
	window.open(contextPath+'/shopping_cart/print_order.jsp', 'print_order', 'width=740,height=750,scrollbars=1');
	
}

var removeSkuId = 0;
function showRemovePopup(skuId){
	removeSkuId = skuId;
	jQuery('#remove_confirm').show();
}

function changeEmpty(el, value){
	if(el.value == ''){
		el.value = value;
	}
}

function emptyText(el, value){
	if(el.value == value){
		el.value = '';
	}
}

function limitLength(el, length){
	if(el.value.length > length){
		el.value = el.value.substr(0,length);
	}
	
	jQuery('#gift_message_length').html(el.value.length);
}
