function close_modal(){
	$('#modal-screen').hide();
	$('#modal-dialog').fadeOut("slow"); 
	
}

function showModalDialog(content){
	$('#modal-screen').show();
	$('#modal-dialog_content').html(content);
	$('#modal-dialog').show();
}

var current_timeslot_page = new Array();
function getNextTimeSlots(shipment_prefix){
	
	if($('#time_slot_pages'+ shipment_prefix +'_' + (current_timeslot_page[shipment_prefix] + 5)).length){
		$('#time_slot_pages'+ shipment_prefix +'_' + current_timeslot_page[shipment_prefix]).hide();
		$('#time_slot_pages'+ shipment_prefix +'_' + (current_timeslot_page[shipment_prefix] + 5)).show();
		current_timeslot_page[shipment_prefix] += 5;
	}

	showNavLinks(shipment_prefix);
}

function getPrevTimeSlots(shipment_prefix){
	
	if($('#time_slot_pages'+ shipment_prefix +'_' + (current_timeslot_page[shipment_prefix] - 5)).length){
		$('#time_slot_pages'+ shipment_prefix +'_' + current_timeslot_page[shipment_prefix]).hide();
		$('#time_slot_pages'+ shipment_prefix +'_' + (current_timeslot_page[shipment_prefix] - 5)).show();
		current_timeslot_page[shipment_prefix] -= 5;
	}

	showNavLinks(shipment_prefix);
}

function showNavLinks(shipment_prefix){
	if($('#time_slot_pages'+ shipment_prefix +'_' + (current_timeslot_page[shipment_prefix] + 5)).length){
		$('#next'+shipment_prefix).show();
	}else{
		$('#next'+shipment_prefix).hide();
	}
	
	if($('#time_slot_pages'+ shipment_prefix +'_' + (current_timeslot_page[shipment_prefix] - 5)).length){
		$('#prev'+shipment_prefix).show();
	}else{
		$('#prev'+shipment_prefix).hide();
	}

}


function changeDeliveryTime(zip_code, contextPath){
	if(zip_code.length == 5 && zip_code != currentZipCode){
		$.get(contextPath + '/ajax/local_delivery.jsp', {'zipCode': zip_code}, 
				function(response){
					$('#local_delivery_content').html(response);
					currentZipCode = zip_code;
				});
	}
}

//deletes a shopping list
function deleteShoppingList(shoppingListId, contextPath){
	
	 var url = contextPath + '/shopping_list/delete_do';
	 $.ajax({
		   type: "POST",
		   url: url,
		   data: "shopping_list_id="+shoppingListId+"&agent_sku_list_type_refcode=SHOPPINGLIST&agent_sku_list_access_refcode=PUBLIC",
		   success: function(response){
		 		window.location = window.location;},
		   error: function(response){alert('error');}

		 });
}


//deletes an item from a shopping list
function deleteItemFromShoppingList(agentSkuListItemId, contextPath){
	 
	 var url = contextPath + '/item/delete_sku_item_do';
	 $.ajax({
		   type: "POST",
		   url: url,
		   data: "agent_sku_list_item_id="+agentSkuListItemId,
		   success: function(response){
		 		window.location = window.location;},
		   error: function(response){alert('error');}

		 });
}
	 

function updateShoppingCartDisplay(contextPath){
	asyncGet( contextPath+'/templates/nav/cart_info.jsp', 'handleUpdateShoppingCartDisplay');
}

function handleUpdateShoppingCartDisplay(response){
	document.getElementById('cartDisplay').innerHTML=response;
}


//create a shopping list just pass the contextpath
//for creating shopping list just pass the contextpath
//with the param workorderToShoppingList and its value
function createShoppingList(workOrderToShoppingList, contextPath){
		if(workOrderToShoppingList > 0){
			contextPath = contextPath+ '/shopping_list/create_do?workorderToShoppingList='+workOrderToShoppingList;
		}else{
			contextPath = contextPath+ '/shopping_list/create_do';
		}
		var url = contextPath;
		var list_name = document.getElementById('newShoppingListName').value;
	 
		$.ajax({
		   type: "POST",
		   url: url,
		   data: "list_name="+list_name+"&agent_sku_list_type_refcode=SHOPPINGLIST&agent_sku_list_access_refcode=PUBLIC",
		   success: function(response){
		 	window.location = window.location;},
		   error: function(response){alert('error');}

		 });	
}



function createShoppingListWithSkuId(sku_id, contextPath){

	contextPath = contextPath+ '/shopping_list/create_do?create_list_sku_id';
	
	var url = contextPath;
	var list_name = document.getElementById('newShoppingListName').value;
 
	$.ajax({
	   type: "POST",
	   url: url,
	   data: "list_name="+list_name+"&agent_sku_list_type_refcode=SHOPPINGLIST&agent_sku_list_access_refcode=PUBLIC&sku_id="+sku_id,
	   success: function(response){
	 	window.location = window.location;},
	   error: function(response){alert('error');}

	 });	
}

//create a shopping list just pass the contextpath
//for creating shopping list just pass the contextpath
//with the param workorderToShoppingList and its value
function addProductToShoppingList(sku_list_id, sku_id, contextPath){
	if(sku_list_id==null){
		createShoppingListWithSkuId(sku_id, contextPath);
	}else{
		var url = contextPath+ '/item/add_sku_item_do?sku_id='+sku_id;
		
	    $.ajax({
			   type: "POST",
			   url: url,
			   data: "quantity=1"+"&sku="+sku_id+"&asl="+sku_list_id+"&agent_sku_list_id="+sku_list_id,
			   success: function(response){
			 	window.location = window.location;},
			   error: function(response){alert('error');}
	
			 });	
	}
}


function promptZipCode(product_id, use_choice){
	var url = contextPath+'/category/ajax/getLoginZipCode.jsp?time='+(new Date()).getTime();
    $.ajax({
		   type: "GET",
		   url: url,
		   success: function(response){
		   				response = response.replace(/[\n\s]*/,'');
		   				
		   				if(response != ''){
							var zipCodePrompt = '<h1 class="modaltitle"></h1>'+
												'<form name="zip_code_form" class="popform" style="text-align: center;">' +
													'<h2 class="title">Will you be shipping to '+ response +'?</h2>'+
													'<input type="hidden" name="product_id" value='+product_id+'>&nbsp;'+
													'<input type="button" value="yes" onclick="addToCart(\''+response+'\','+product_id+', false, '+use_choice+')" />&nbsp;'+ 
													'<input type="button" value="no" onclick="promptZipCode2('+product_id+', '+use_choice+')" />'+ 
												'</form>';
					
							$('#modalContent2').html(zipCodePrompt);
							$('#modalContent2').modal();
						}else{
							promptZipCode2(product_id, use_choice);
						}
		 			},
		   error: function(response){alert('error');}

		 });
	
}

function promptZipCode2(product_id, use_choice){

	var zipCodePrompt = '<h1 class="modaltitle"></h1>'+
							'<form name="zip_code_form" class="popform" style="text-align: center;">' +
							'<h2 class="title">Please Enter Your Shipping Zip Code</h2>'+
							'<input type="text" name="zip_code" onkeypress="return processEnter(event,this.form)">&nbsp;'+
							'<input type="hidden" name="product_id" value='+product_id+'>&nbsp;'+
							'<input type="button" value="submit" onclick="checkZipCode('+use_choice+')" />'+ 
							'</form>';

	$('#modalContent2').html(zipCodePrompt);
	$('#modalContent2').modal();
}

function checkZipCode(use_choice){
	var url = contextPath+'/ajax/check_zip_code.jsp?zip_code='+document.zip_code_form.zip_code.value+'&time='+new Date();
	
	$.ajax({
	   type: "GET",
	   url: url,
	   data: getFormValues(document.zip_code_form),
	   success: function(response){
        			if(response == 'yes')
        				addToCart(document.zip_code_form.zip_code.value,document.zip_code_form.product_id.value,false, use_choice );
        			else{
        				var zipCodePrompt = '<h1 class="modaltitle"></h1>'+
						'<form name="zip_code_form" class="popform" style="text-align: center;">' +
						'<h2 class="title">Click here - <a href="http://www.Kosher.com/usa">www.Kosher.com/usa</a> - to see products available in your zip code</h2>'+
						'</form>';
        				$('#modalContent2').html(zipCodePrompt);
        				$('#modalContent2').modal();
        			}
	  }//end of function
	 });
}

function processEnter(event,ourform) {
    if (event && event.keyCode == 13){
          checkZipCode();
          return false;
    } else{
     	return true;
    }
  }
  
  
function checkMinimumOrder(zip_code, contextPath){
	if(zip_code.length == 5 && zip_code != currentZipCode){

		$.get(contextPath + '/shopping_cart/ajax/check_minimum_order.jsp', {'zipCode': zip_code}, 

				function(response){

					$('#checkout_button_id').html(response);

					currentZipCode = zip_code;

				});

	}
		
}

function addItem(product_id, use_choice){
	
	if(isNaN(document.getElementById('qty_'+product_id).value)){
		alert("The quantity must be a number.");
		return;
	}else if (document.getElementById('qty_'+product_id).value<=0){
		alert("The quantity must be greater than zero.");
		return;
	}
	
	var url = contextPath+'/ajax/is_first_item.jsp?time='+new Date();
	
	$.ajax({
		type: 'GET',
		url: url,
		success: function(response){
					if(response == 'yes')
						promptZipCode(product_id, use_choice);
					else
						addToCart("",product_id, false, use_choice);}
	});
}

function addToCart(zip_code, product_id, outOfStock, use_choice){
	var qty = 'qty_'+product_id;
	var url = contextPath+"/servlet/Cart";
	document.product_form.product_id.value = product_id;

	if(use_choice){
		var option_params= getOptionParams(product_id);
	}else{
		var option_params= '';
	}
	
	if(!outOfStock){
		document.product_form.success.value = "/category/modal/add_to_cart_modal.jsp?product_id="+product_id+"&quantity="+document.getElementById(qty).value+option_params;
		document.product_form.failure.value = "/category/modal/add_to_cart_modal.jsp?product_id="+product_id+"&quantity="+document.getElementById(qty).value+option_params;
	}else{
		document.product_form.success.value = "/category/modal/out_of_stock_modal.jsp?product_id="+product_id;
		document.product_form.failure.value = "/category/modal/out_of_stock_modal.jsp?product_id="+product_id;
	}
		
	var params = getFormValues(document.product_form);
	if(zip_code){
		params += '&zip_code='+zip_code;
	}
	params += '&quantity='+$('#qty_'+product_id).val();
	
	params += option_params;
	
	if(typeof(add_to_cart_method) == "undefined"){ 
		add_to_cart_method = 'POST';
	}
	
	$.ajax({
	   type: add_to_cart_method,
	   url: url,
	   data: params,
	   success: function(response){
					$('#modalContent2').html(response);
		   			$('#modalContent2').modal();
		   			updateShoppingCartDisplay(contextPath);},
	   error: function(response){alert('error');}

	 });			 
}

function addProductToShoppingList2(list_el_id, sku_el_id){
	var sku_list_id = $('#'+list_el_id).val();
	var sku_id = $('#'+sku_el_id).val();

	if(sku_list_id==null){
		createShoppingListWithSkuId(sku_id, contextPath);
	}else{
		var url = contextPath+ '/item/add_sku_item_do?sku_id='+sku_id;
		
	    $.ajax({
			   type: "POST",
			   url: url,
			   data: "quantity=1"+"&sku="+sku_id+"&asl="+sku_list_id+"&agent_sku_list_id="+sku_list_id,
			   success: function(response){
			    fillContent('modalContent2', '/templates/ajax/message.jsp');
			 	},
			   error: function(response){alert('error');}
	
			 });	
	}
}

function fillContent(el_id, uri){
	var url = contextPath+uri;
	var myDate = new Date();
    $.ajax({
	   type: "GET",
	   url: url,
	   data: 'date='+myDate.getTime(),
	   success: function(response){$('#'+el_id).html(response);},
	   error: function(response){alert('error');}

	 });	
}

function preload_cart_images(prefix) {
		var preloadedImagesURI = new Array();
		preloadedImagesURI[0] = '/images/bg.png';
		preloadedImagesURI[1] = '/images/logo.gif';
		preloadedImagesURI[2] = '/images/phone.gif';
		preloadedImagesURI[3] = '/images/chat_bg.png';
		preloadedImagesURI[4] = '/images/search.gif';
		preloadedImagesURI[5] = '/images/nav_bg.gif';
		preloadedImagesURI[6] = '/images/nav_pipe.gif';
		preloadedImagesURI[7] = '/images/pipe.gif';
		preloadedImagesURI[8] = '/images/gradient_2.gif';
		preloadedImagesURI[9] = '/images/submit.gif';
		preloadedImagesURI[10] = '/images/zip_bg.png';
		preloadedImagesURI[11] = '/images/go.png';
		preloadedImagesURI[12] = '/images/mcafee.gif';
		preloadedImagesURI[13] = '/images/autorize.gif';
		preloadedImagesURI[14] = '/images/vaad.gif';
		preloadedImagesURI[15] = '/images/shipping_information.gif';
		preloadedImagesURI[16] = '/images/billing_information.gif';
		preloadedImagesURI[17] = '/images/promotion.gif';
		preloadedImagesURI[18] = '/images/apply.gif';
		preloadedImagesURI[19] = '/images/shipping_information_2.gif';
		preloadedImagesURI[20] = '/images/submit2.gif';
		preloadedImagesURI[21] = '/images/billing_information_2.gif';
		preloadedImagesURI[22] = '/images/payment_information.gif';
		preloadedImagesURI[23] = '/images/submit2.gif';
		preloadedImagesURI[24] = '/images/phone_footer.gif';
		preloadedImagesURI[25] = '/images/newsletter_sign_up.jpg';
		preloadedImagesURI[26] = '/images/go.gif';
		preloadedImagesURI[27] = '/images/proceed_to_checkout_2.gif';
		
		var imageLoadedArr = new Array();
		for(i = 0; i < preloadedImagesURI.length; i++){
			imageLoadedArr[i] = new Image();
			imageLoadedArr[i].src = prefix + preloadedImagesURI[i];
		}
}


function getOptionParams(productId){
	var params = '';
	for(var i = 0; i < optionCount[''+productId]; i++){
	
		var choiceEl = document.getElementById('cn_'+productId+'_'+i);
		var choiceName = 'choiceName_'+choiceEl.name.substr(('cn_'+productId+'_').length, choiceEl.name.length);
		params += '&'+choiceName+'='+choiceEl.options[choiceEl.selectedIndex].value;
	
	}

	return params;
}

function load_user_info(){
	
	var user_cart_unique_id = readCookie('user_cart_unique_id');
	if(user_cart_unique_id){
		
		$.get(contextPath+"/ajax/load_user_info.jsp?user_cart_unique_id="+user_cart_unique_id, function(data){
			if(data.indexOf('loaded') >= 0){
				updateShoppingCartDisplay(contextPath);
			} 
		});

	}else{
		//the random number should be unique enough: random from 1-10 plus current time
		var randomnumber=Math.floor(Math.random()*11);
		var myDate=new Date(); 
		randomnumber += myDate.getTime();
		
		createCookie("user_cart_unique_id",randomnumber,365);
	}
	
}

function checkProductsAvailability(skuIdsStr){
	var url = contextPath+'/category/ajax/in_stock_skus.jsp';
	$.post(url, { sku_ids: skuIdsStr },
			function(response){
				//respones defines skuStatus array
				eval(response);
				
				for (skuId in skuStatus){
	
					if(skuStatus[skuId].indexOf('yes') >= 0){
						$('#add_to_cart_btn_'+skuId).show();
						$('#out_of_stock_info_'+skuId).hide();
					}else{
						$('#out_of_stock_info_'+skuId).show();
						$('#add_to_cart_btn_'+skuId).hide();
					}
				}
			});	
}

function outOfStock(product_id){
	
	var url = contextPath+"/category/ajax/outOfStock.jsp?product_id="+product_id;
	$.ajax({
	   type: "POST",
	   url: url,
	   data: "&product_id"+product_id,
	   success: function(response){
	   		
		   		$('#modalContent3').html(response);
		   		$('#modalContent3').modal();} 

	 });

}


function changeOption(pid){
	var choice_combination = '';
	for(var i = 0; i < optionCount[''+pid]; i++){
		var choiceEl = document.getElementById('cn_'+pid+'_'+i);
		choice_combination += choiceEl.options[choiceEl.selectedIndex].value+'_';
	}
	choice_combination += pid;
	
	selectedSkuPrice = skusPrice[choice_combination];

	var itemUnitValue;
	if(itemsUnitValue[choice_combination]){
		itemUnitValue = itemsUnitValue[choice_combination];
	}else{
		itemUnitValue = '';
	}

	<!-- if it's sale price, get the old price and new price from array, then update them in the spans accordingly -->
	if(oldPrice[choice_combination]){
		//update old price and sale price
		$('#oldprice_'+pid).html(oldPrice[choice_combination]);
		$('#saleprice_'+pid).html(salePrice[choice_combination]);
	}else{
		//update price
		$('#price_'+pid).html(selectedSkuPrice);
	}

	//update item_unit value
	$('#item_unit_'+pid).html(itemUnitValue);

	showAddToCart(skuIds[choice_combination]);
}

