var inStoreRadioSel = false;
var inStoreValidation = false;

String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

function callUpdate(obj1,obj2)
{
	/*
		Calling JSP : Shoppingcart.jsp on click of update button
					   to uncheck all the checkboxes.
		
	*/	
	if(isSessionExpired())
	{
		displaySessionTimeOut();
		return false;
	}	
	document.getElementById("qtyErrorHolder").style.display='none';
	var checkboxLength=obj2.length;
	
	   if(parseInt(checkboxLength) > 1)
   		{
   			for(var i=0; i<checkboxLength; i++)
	   		{
   				obj2[i].checked=false;
   			}
   		}
   		else
   		{
   			obj2.checked=false;
   		}
   	
   	
				for (i=0; i<document.cartItems.elements.length; i++)
				{
				  //Identify the text element		
				 	
					if (document.cartItems.elements[i].type=="text" && document.cartItems.elements[i].id !="couponId")
					{ 	
					 	var val=document.cartItems.elements[i].value;	
					 	if(null!=val && val!="")
						{
							var tempVal=val.trim();
							if(tempVal=="")
							{	
								document.cartItems.elements[i].value=tempVal;
								document.getElementById("qtyErrorHolder").style.display='block';
								return false;
							}
							else
							{
								document.cartItems.elements[i].value=tempVal;
								var valLength=parseInt(tempVal.length);
								if(valLength > 0 && valLength < 3)
						 		{ 		
						 			for (var j = 0; j < valLength; j++) 
									{
										var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?~_"; 
														   			 
								  		if (iChars.indexOf(tempVal.charAt(j)) != -1 || isNaN(tempVal)) 
								  		{	  
								  			document.getElementById("qtyErrorHolder").style.display='block';
								  		  	return false; 
										}
								  	}
								 }
							}
						}
						else
						{
							document.getElementById("qtyErrorHolder").style.display='block';
							return false;
						}
			 		}
			 	}
 	
 
 	
 	//Only when the user clicks the proceed to checkout button.
 	if(obj1.id!="update")
 	{
 	
			 	var checkoutPage="";		
				if(obj1.id == "registeredUserCheckout")
				{
				  //Registered user's checkout page.
					checkoutPage=document.cartItems.regUserSuccessURL.value;
					
				}
				else if(obj1.id == "guestCheckout")
				{
				  //Guest user's checkout page.
					checkoutPage=document.cartItems.guestUserSuccessURL.value;
				}
				
				var totalCnt=0;
				
				for (i=0; i<document.cartItems.elements.length; i++)
				{
				  //Identify the text element				
					if (document.cartItems.elements[i].type=="text" )
					{  	
							 //For the quantity field max length will be 2
						 	 if(parseInt(document.cartItems.elements[i].value.length)>0 && parseInt(document.cartItems.elements[i].value.length)<3)
						 	 {
						 	 	
								totalCnt=parseInt(totalCnt)+parseInt(document.cartItems.elements[i].value);	
							 }
					}
				} 
					   			  
				if(totalCnt<=50 && totalCnt>0)
				{
				 				document.cartItems.successURL.value=checkoutPage;
				}
				else
				{
				 				document.cartItems.successURL.value=document.cartItems.successSecureURL.value;
				}
						
				
	 }
	 else
	 {	 //When the user clicks back button from the checkout page then the success url needs to be reset.
	 		document.cartItems.successURL.value=document.cartItems.successSecureURL.value;
	 }
  
}
 
/* Function called while selecting the nick name in checkout delivery option page*/
function displayaddress()
	{
			
			var requestURL=document.getElementById("URL").value;
			var staticnickName="nickName=";
			var nickName=document.getElementById("nickName").value;
			var URL=requestURL+"?"+staticnickName+nickName;
			window.location=URL;
			window.reload();
	}

	/* Function for displaying lightbox in checkout delivery option*/
function displayCheckoutLightBox(){
 var deliveryPostalCode = null;	
 var storeId =null;
 if(document.getElementById("cartStoreId")){
 storeId=document.getElementById("cartStoreId").value;}
 if(document.getElementById("Pcode")){
deliveryPostalCode=document.getElementById("Pcode").value;
//checking for any spaces in the postal code. if exists then remove the spaces
deliveryPostalCode = (deliveryPostalCode.toString()).replace(" ","");
document.getElementById("Pcode").value=deliveryPostalCode;
	}
 var	contextPath=document.getElementById("contextPath").value;
 var	 url=contextPath+"jsp/lightbox_content/checkoutDeliveryOptionLightBox.jsp";
 var	 lightboxUrl=contextPath+"/jsp/lightbox_content";	
	 PopupController.openPopup(url,1234,lightboxUrl);

}
/**
	Function added for diaplying the light box from CheckoutDeliveryOption page 
*/
	function callLightFromDeliveryOption()
	{
 			if(!isSessionExpired())
 			{	
 				var validationSuccess = false;
	            var sessionPostalCode = document.getElementById("sessionPostalCode").value;
	            var deliveryPostalCode = null;	            
	            var selectedRadioVal = null;
	            //get the selected radio val
				selectedRadioVal = getSelectedOption();
	            //do validation
	            if(selectedRadioVal == "ship to address"){
					if(document.getElementById("Pcode")){
						deliveryPostalCode=document.getElementById("Pcode").value;
						//checking for any spaces in the postal code. if exists then remove the spaces
						deliveryPostalCode = (deliveryPostalCode.toString()).replace(" ","");
						deliveryPostalCode=deliveryPostalCode.toUpperCase();
						document.getElementById("Pcode").value=deliveryPostalCode;
						
					}
					validationSuccess = validateShipToAddress();	            	
	            }
	            else{
					if(document.getElementById("storePCode")){
						deliveryPostalCode=document.getElementById("Pcode").value;
					}	            
	            	validationSuccess = validateInStorePickUp();
	            }
	            
				if(validationSuccess){
							document.shippingform.saveAddressProceed.click();
				}
			}
			else
			{
				displaySessionTimeOut();
				return false;
			}
			
			
	}
		/**
			function to validate the delivery instructions to 230 chars
		*/
		
			
	function validateCharSize()
	{

		if(!isSessionExpired())
		{
			var delInstr=document.getElementById("delInstr").value;
			delInstr=trim(delInstr);
			document.getElementById("delInstr").value=delInstr;
			if(delInstr.length>230){
			document.getElementById("errordelInstruction").style.display='block';
			return false;
		}}else{
			displaySessionTimeOut();
			return false;
		}
	}

/// function to trim the given string

	function trim(str) {
	  var newstr;
	  newstr = str.replace(/^\s*/, "").replace(/\s*$/, ""); 
	  newstr = newstr.replace(/\s{2,}/, " "); 
	  return newstr;
	} 




/// function to getSelectedOption
function getSelectedOption(){
	            var selectedRadioVal = null;
	            //get the selected radio val
	            var radArr = document.getElementsByName("shippingAddress");
				for(i=0; i<radArr.length; i++){
					if(radArr[i].checked){
						selectedRadioVal = radArr[i].value;
						break;
					}
				}
				return selectedRadioVal;

}

		//function for Instore pick-up validation
		function validateInStorePickUp(){
	
		// declaring a variable to store the result of  first name validation
			var fnameValid = true;
		// declaring a variable to store the result of  last name validation	
			var lnameValid = true;
		// declaring a variable to store the result of  store id  validation	
			var storeIdValid = true;
			var storeId = document.getElementById("cartStoreId").value;
			var storeRadioSel =  document.getElementsByName("storeSel");
			var k=0;
			//checking for store selected by the user  by iterating through all the stores
			for(k=0;k<storeRadioSel.length;k++){
			// if user selects a store then assign that store to the store id variable
			       if(storeRadioSel[k].checked==true){
			       	storeId= storeRadioSel[k].value;
			       	document.getElementById("cartStoreId").value=storeId;
			}
			}
			var fname = document.getElementById("fname").value;
			var lname = document.getElementById("lname").value;
			//checking for firstname whether it is valid r not
			/* 
			  passing two variables to the function 
			  1. fname which is the value checking for validation
			  2. "fname" which is a constant string used to display the 
			     error message dynamically in the jsp page by passing 
			     this to the div tag
			
			*/
			
			fnameValid =validateName(fname,"firstname");	
			// checking for last name whether it is valid r not
			lnameValid = validateName(lname,"lastname");
			// checking whether store id is empty or not         
			if(storeId == null || storeId == ""){	
				document.getElementById("storeIdEmpty").style.display='block';
				document.getElementById("storeIdEmpty").style.color='red';
				document.getElementById("errormessage1").style.display='none';
				storeIdValid = false;
			} //if store id is not empty hide the div tag which displays the storeid error message
			else if(storeId != null || storeId != ""){
			document.getElementById("storeIdEmpty").style.display='none';
			}
			
			
			// declaring a result variable 
			var result=(fnameValid && lnameValid && storeIdValid);
			if(!result)
			{
			// if result is false then display the 
			document.getElementById("errormessage2").style.display='block';
			document.getElementById("errormessage2").style.color='red';
			document.getElementById("errormessage1").style.display='none';
			}else{
			document.getElementById("errormessage2").style.display='none';
			}
			inStoreValidation = result;
			return result;
		}
		
//function to check for the  name either empty or valid name 
				function validateName(name,errorMsg){
				// checking whether name is empty r not
				if(name==null||name== ""){
							errorMsg=errorMsg+"Empty";
							document.getElementById(errorMsg).style.display='block';
							document.getElementById(errorMsg).style.color='red';
							return false;
				}
				// checking whether name is a valid name or not
				else if(!isValidName(name)) 
				{
					     	var errorMsgPrev=errorMsg+"Empty";	
						   	document.getElementById(errorMsgPrev).style.display='none';
						    errorMsg=errorMsg+"Invalid";
							document.getElementById(errorMsg).style.display='block';
							document.getElementById(errorMsg).style.color='red';
							return false;
				}
				//if name is not empty hide the div tag which displays the name is empty error message
				if(name!=null||name!= ""){
				
							errorMsgPrev=errorMsg+"Empty";	
							document.getElementById(errorMsgPrev).style.display='none';
				}
				//if name is not empty hide the div tag which displays the name is invalid error message
			   if(isValidName(name)) {
							 errorMsg=errorMsg+"Invalid";
							 document.getElementById(errorMsg).style.display='none';
							 return true;
				}
				}
				
// checking whether the name contains any non alphabetical characters are not by calling the IsAlpha method 				

		function isValidName(fname)
		{
		 for (i=0;i<fname.length;i++)
		{
     // getting each character 		
			var check = fname.charAt(i);
		// and checking for the non aphabetical character
			if(!isSpecialChar(check)){
		
			return false;
			 
		}
		}
		return true;
		}
// function which checks whether it has non alphabetical characters		
function isSpecialChar(){
	var argv = isSpecialChar.arguments;
	var aString = argv[0];
	var regexLetter  = /[!@#$%^&*()+=\[\]\;,/{}|\":<>?~]/; 
	
	if (aString.length != 0){
		var indexLimit = aString.length;
		var character = ' ';
		for (var i=0; i<indexLimit; i++){
			 character = aString.charAt(i);	
		if(regexLetter .test(character)){
		
		return false;	 
		}
	}}
	return true;
}

//function for Ship To Address validation
function validateShipToAddress(){
	var valdnRes = true;
	var nickName=null;
    var addressMode=null;
	if(document.getElementById("nickName")){
		nickName=document.getElementById("nickName").value;	
	}	
	if(document.getElementById("addressmode")){
		addressMode=document.getElementById("addressmode").value;	
	}	
	if(nickName==""&&addressMode==null ){					
		document.getElementById("errormessage1").style.display='block';
		document.getElementById("errormessage1").style.color='red';
		document.getElementById("errormessage2").style.display='none';
		valdnRes = false;
	}
	return valdnRes;
}
//function when In Store Pick Up is selected
function inStorePickUpSelected(){

	if(!inStoreRadioSel){
		//get the radio
	
		 var fname = document.getElementById("fname").value;
		 var lname = document.getElementById("lname").value;
		    fname="";
			lname="";
		document.getElementById("fname").value=fname;
		document.getElementById("lname").value=lname;
		var radio = document.getElementById('inStorePickUpRadio');	
		radio.checked = true;
		inStoreRadioSel = true;
		var provinceDD = document.getElementById("provinceDD");	
		provinceDD.disabled = false;
		var cityDD = document.getElementById("cityDD");
		cityDD.disabled = true;			//added for citydisable
		ajaxHandler.clearInStorePickUpDiv();
		clearShipToAddrDiv();			
		var nickNameDD = document.getElementById("nickName");
		if(nickNameDD != null){
			nickNameDD.selectedIndex=0;
			nickNameDD.disabled = true;
		}
		var shiptoAddr = document.getElementById('nickName');
		if(shiptoAddr != null){
			shiptoAddr.disabled = true;
		}
	}
	//isInStorePickUpSelected = true;
	disableNewAddrLinkDiv();
}
function initial(){

if(document.getElementById("fname"))
document.getElementById("fname").value='';
if(document.getElementById("lname"))
document.getElementById("lname").value='';
	
	var shipToAddrDD = document.getElementById('shipToAddrRadio'); 
	if(shipToAddrDD != null){
		shipToAddrDD.checked = true;
	
		
	//	fname="";
	//	lname="";
	//	document.getElementById("fname").value=fname;
	//	document.getElementById("lname").value=lname;
	}
}
function disableNewAddrLinkDiv(){
	var NewAddrLinkDiv = document.getElementById('NewAddrLinkDiv');
	var tempNewAddrLinkDiv = document.getElementById('tempNewAddrLinkDiv');
	if(NewAddrLinkDiv != null){
		tempNewAddrLinkDiv.innetHTML = NewAddrLinkDiv.innerHTML; 
		NewAddrLinkDiv.innerHTML = '';
	} 
}
function enableNewAddrLinkDiv(){
	var NewAddrLinkDiv = document.getElementById('NewAddrLinkDiv');
	var tempNewAddrLinkDiv = document.getElementById('tempNewAddrLinkDiv');
	if(NewAddrLinkDiv != null){
		NewAddrLinkDiv.innerHTML = tempNewAddrLinkDiv.innetHTML; 
		tempNewAddrLinkDiv.innetHTML = '';
	}
}
function disableShiptoAddr(){
		var shipToAddrRadio = document.getElementById('shipToAddrRadio');
		shipToAddrRadio.checked = false;
		var nickNameDD = document.getElementById("nickName");
		if(nickNameDD != null){
			nickNameDD.selectedIndex=0;
			nickNameDD.disabled = true;
		}
		disableNewAddrLinkDiv()
}

//function when a Store is selected for Pick Up
function storeSelected(selectedStore){
	var storeIdElem = document.getElementById("cartStoreId");
	storeIdElem.value = selectedStore;
}
//function when Ship To Address is selected
function shipToAddrSelected(){
    //clear the session values
	var radiobuttonShiptoAddress = document.getElementById('radiobuttonShiptoAddress');	
     radiobuttonShiptoAddress.click();
	var title= document.getElementById("Title");
	if(title!=null)
	{
			clearValues();
	}
	   var fname=document.getElementById('fname');
	    var lname=document.getElementById('lname');
	    fname.value="";
	    lname.value="";
	    fname.disabled=true;
	    lname.disabled=true;
	if(inStoreRadioSel){
		//get the radio
		var radio = document.getElementById('shipToAddrRadio');	
		radio.checked = true;
		inStoreRadioSel = false;
		ajaxHandler.clearInStorePickUpDiv();
		var provinceDD = document.getElementById("provinceDD");	
		provinceDD.selectedIndex = 0;
		provinceDD.disabled = true;	
		var cityDD = document.getElementById("cityDD");	
		cityDD.selectedIndex = 0;
		cityDD.disabled = true;	
		var nickName = document.getElementById('nickName');
		if(nickName != null){
			nickName.disabled = false;
		}	
		enableNewAddrLinkDiv();
		showShipToAddrDiv();
	}
	//isShipToAddrSelected = true;	
}
function clearShipToAddrDiv(){
			var div = document.getElementById('shipToAddrDiv');
			var tempDiv = document.getElementById('shipToAddrDetails');
			if(div != null){
				tempDiv.innerHTML = '';
				tempDiv.innerHTML = div.innerHTML;
				div.innerHTML = '';
			}
			div = document.getElementById('shipToAddrDiv2');
			if(div != null){
				div.innerHTML = '';
			}
					
	}
	
	function showShipToAddrDiv(){
		var div = document.getElementById('shipToAddrDiv');
		var tempDiv = document.getElementById('shipToAddrDetails');	
			if(div != null){								
				div.innerHTML = tempDiv.innerHTML;
				tempDiv.innerHTML = '';
			}			
	
	}	
/** 
funtion added for the Instock item  in the addItemtoCart page
*/
	
	
function openInstockLightBox()
 { 
    var	contextPath=document.getElementById("contextPath").value;
   	var	 url=contextPath+"/jsp/lightbox_content/instockLightBox.jsp";
	 var	 lightboxUrl=contextPath+"/jsp/lightbox_content";	
	PopupController.openPopup(url,1234,lightboxUrl);
	return false;
}	


/** 
funtion added for the estimated Order Delivery date in the addItemtoCart page
*/
	
	
function openEstimatedOrderDelivery()
 { 
   		var	contextPath=document.getElementById("contextPath").value;
 		var	 url=contextPath+"jsp/lightbox_content/OrderDeliveryDateLightBox.jsp";
		 var	 lightboxUrl=contextPath+"/jsp/lightbox_content";	
	PopupController.openPopup(url,1234,lightboxUrl);
	return false;
}	

/** 
funtion added for the Estimated Availabilty Date  in the addItemtoCart page
*/
function openEstimatedAvailabilityLightBox()
{ 

      	var	contextPath=document.getElementById("contextPath").value;
 		var	 url=contextPath+"/jsp/lightbox_content/estAvaliblityDateLightBox.jsp";
		var	 lightboxUrl=contextPath+"/jsp/lightbox_content";	
		PopupController.openPopup(url,1234,lightboxUrl);
   	return false;
}	
function displayRelatedFeeLightBox()
{
if(!isSessionExpired())
		{
	
 var	contextPath=document.getElementById("contextPath").value;
 var	 url=contextPath+"jsp/lightbox_content/relatedFeeLightBox.jsp";
 var	 lightboxUrl=contextPath+"/jsp/lightbox_content";	
	 PopupController.openPopup(url,1234,lightboxUrl);
}else{

	displaySessionTimeOut();
	return false;

}}


      
  function openAmountApplicableLightbox()
{
var contextPath=document.getElementById("contextPath").value;
PopupController.openPopup(contextPath+'/jsp/lightbox_content/paymentAmountAppLightBox.jsp',12345,contextPath+'/jsp/lightbox_content');
return false;
}
    



/**
	Function added for diaplying the Brick Card Options on PaymentOptions page 
*/
	
		function showBrickCardDetails(currentObject)
	{
	   
		var obj = currentObject;

		if(!currentObject)
		{
			currentObject = document.getElementById('payment_method');
			
		}
		 
		if(currentObject.value=="brickCard")
		{
		   if(document.getElementById("errorContainer")){
		   
		   	document.getElementById("disableContinueButton").style.display='block';
			document.getElementById("enableContinueButton").style.display='none';
		   }
		   else{
		  
		   	document.getElementById("disableContinueButton").style.display='none';
			document.getElementById("enableContinueButton").style.display='block';
		   
		   }
			document.getElementById("BrickCardOptions").style.display='block';
			document.getElementById("CreditCardOptions").style.display='none';	
		}
		else
		{
			document.getElementById("BrickCardOptions").style.display='none';
			document.getElementById("CreditCardOptions").style.display='block';
			document.getElementById("disableContinueButton").style.display='none';
			document.getElementById("enableContinueButton").style.display='block';
		}
		if(obj)
		{    
			document.getElementById("CVVNumber").value="";
			document.getElementById("CardNo").value="";
			document.getElementById("CardHolder").value="";
		    
			var current = new Date();
			var curMonth = current.getMonth();
			for(i=0;i<document.getElementById("ExpDate").options.length;i++)
			{
				if(document.getElementById("ExpDate").options[i].value==curMonth)
				{
					document.getElementById("ExpDate").options.selectedIndex=++i;
					break;
				}
			}
		}
		document.getElementById("CardHolder").focus();		
	}
	

	
/**
	Function added for diaplying the New Address in Payment and Billing Page
*/
	function displayNewAddress()
	{
		document.getElementById("NewAddress").style.display='block';
	}
	
	/**
	 Open warranty options light box
	*/
function openWarrantyOption()
{ 	 
	if(isSessionExpired())
	{
		displaySessionTimeOut();
	  	return false;
	}
 	var qty=document.addItem.quantity.value;
 	var	totalQty=document.addItem.totalQty.value;
  	var result=parseInt(qty) +parseInt(totalQty); 
  	var valLength=parseInt(qty.length);

	 /**
	   Checking for the special character
	 */

	if(valLength > 0 && valLength < 3)
	{
		for (var j = 0; j < valLength; j++) 
		{
			var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?~_"; 
			if (iChars.indexOf(qty.charAt(j)) != -1 || isNaN(qty)) 
  			{	 
  				document.getElementById("qtyErrorHolder").style.display='block';
	  			document.getElementById("qtyConvErrorHolder").style.display='none';
	  			document.addItem.quantity.value="1";
  			  	return false; 
			}
  		}
	}
	if( parseInt(qty) == 0 || valLength == 0)
	{  
		document.getElementById("qtyErrorHolder").style.display='block';
	  	document.getElementById("qtyConvErrorHolder").style.display='none';
	  	document.addItem.quantity.value="1";
  		return false; 
	}
	else if(parseInt(qty)>50)
	{
	 document.getElementById("qtyErrorHolder").style.display='block';
	  document.getElementById("qtyConvErrorHolder").style.display='none';
	  document.addItem.quantity.value="1";
  	  return false; 
	}
	else if(result>50)
	{
    	document.addItem.quantity.value=1;
		openMaxCntLightBox();
     	return false;
	}
	else
	{
		var prdID=document.getElementById("prdID").value;
		var skuID=document.getElementById("catRefID").value;	
		var qty=document.getElementById("quantity").value;	
		var contextPath=document.getElementById("contextPath").value;
		var parentPage=document.addItem.parentPage.value;	
		//Parent page is used for "continue shopping" button in cart page	
		var url=contextPath+"/jsp/lightbox_content/warrantyOptions.jsp?itemID="+prdID+'&skuID='+skuID+'&qty='+qty+"&parentPage="+parentPage;
		var lightboxUrl=contextPath+"/jsp/lightbox_content";
		PopupController.openPopup(url,1234,lightboxUrl);	
		return false;
	}
}

/**
	 Open warranty options light box in shopping cart page.
	*/
function openCartWarrantyOption(ciID)
 { 	
	 var prdName=ciID+"_prdID";
	 var prdID=document.getElementById(prdName).value; 
	 var catRefName=ciID+"_catRefID";
	 var skuID=document.getElementById(catRefName).value; 
	 var qty=document.getElementById(ciID).value;  
	 var contextPath=document.getElementById("contextPath").value;
	 var url=contextPath+"/jsp/lightbox_content/cartWarrantyOptions.jsp?itemID="+prdID+'&skuID='+skuID+'&qty='+qty+'&ciID='+ciID;
	 var lightboxUrl=contextPath+"/jsp/lightbox_content";	
	 PopupController.openPopup(url,1234,lightboxUrl);	
	 
 }

/**
	Called when the product have already warranty attached.
*/
function addWithWarranty()
{	
   
	if(isSessionExpired())
	{
	 	displaySessionTimeOut();
	 	return false;
	}
	
	var qty=document.addItem.quantity.value;
	var	totalQty=document.addItem.totalQty.value
  	var result=parseInt(qty) +parseInt(totalQty);
  	var valLength=parseInt(qty.length);

	 /**
	   Checking for the special character
	 */

	if(valLength > 0 && valLength < 3)
	{
		for (var j = 0; j < valLength; j++) 
		{
			var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?~_"; 
			if (iChars.indexOf(qty.charAt(j)) != -1 || isNaN(qty)) 
  			{	 
  				document.getElementById("qtyErrorHolder").style.display='block';
	  			document.getElementById("qtyConvErrorHolder").style.display='none';
	  			document.addItem.quantity.value="1";
  			  	return false; 
			}
  		}
	}
	if( parseInt(qty) == 0 || valLength == 0)
	{  
		document.getElementById("qtyErrorHolder").style.display='block';
	  	document.getElementById("qtyConvErrorHolder").style.display='none';
	  	document.addItem.quantity.value="1";
  		return false; 
	}
	else if(parseInt(qty)>50)
	{
	  document.getElementById("qtyErrorHolder").style.display='block';
	  document.getElementById("qtyConvErrorHolder").style.display='none';
	  document.addItem.quantity.value="1";
  	  return false; 
	}
  	else if(parseInt(result) > 50)
  	{  
     	document.addItem.quantity.value=1;
   	 	openMaxCntLightBox();
     	return false;
  	}
  	
  	else
  	{
	  	prdID=document.getElementById("prdID").value;
		skuID=document.getElementById("catRefID").value;	
		qty=document.getElementById("quantity").value;
		wtySku=document.getElementById("wtySku").value; 	
		parentPage=document.addItem.parentPage.value;
		var contextPath=document.getElementById("contextPath").value; 	
		
	  	//Parent page is used for "continue shopping" button in cart page
		var url=contextPath+"/jsp/checkout/shopping/addItemToCartWithWty.jsp?skuID="+skuID+"&pID="+prdID+"&qty="+qty+"&wtyID="+wtySku+"&parentPage="+parentPage;
		window.location= url;
		return false;
  	}   
}
/* Function called while clicking the Enter New Address link in Billing Info page*/

function displayNewBillingAddress()
{
		div = document.getElementById('shipToAddrDiv2');
			if(div != null){
				div.innerHTML = '';
			}
		document.getElementById("nickName").options.selectedIndex=0;
		document.getElementById("NewAddress").style.display='block';		
}


/* Function called to display the light box for payment terms in Payment Info page*/

function displayPaymentTermsLightBox()
{
	var contextPath = document.getElementById('contextPath').value;
	PopupController.openPopup(contextPath+'/jsp/lightbox_content/paymentTermsLightBox.jsp',12345,contextPath+'/jsp/lightbox_content');
}

function displayCvvLightBox()
{
	var contextPath = document.getElementById('contextPath').value;
	PopupController.openPopup(contextPath+'/jsp/lightbox_content/cvvInformationLightBox.jsp',12345,contextPath+'/jsp/lightbox_content');
}

function displayAddress()
{	
	if(!isSessionExpired())
	{
		document.getElementById("subDiv").click();
	}
	else
	{
		displaySessionTimeOut();
		return false;
	}
}

function displayBillingAddress()
{
	if(!isSessionExpired())
	{
		document.forms[0].linkClicked.value="yes";	
		displayAddress();
	}
	else
	{
		displaySessionTimeOut();
		return false;
	}
}

/* Function called to display the Credit Card Expiration Years Payment Info page*/
function addYearOptions()
{	
	var selectbox = document.getElementById('ExpYear');
	var current = new Date();
	var currYear = current.getFullYear();	
	
	for(i=currYear;i<=currYear+18;i++)
	{
		var a ="";
		a = a + i;
		var optn = document.createElement("OPTION");
		optn.value = i;	
		optn.text = a.substring(2,4);
		selectbox.options.add(optn);
	}
}
	
/* Function called to clear the Address values when the Enter New Address Link is clicked in Billing Info page*/
function clearValues()
{
	 
	document.getElementById("Title").selectedIndex=0;
	
	if(document.getElementById("fname"))
	
		document.getElementById("fname").value='';
	if(document.getElementById("firstName"))
		document.getElementById("firstName").value='';
	if(document.getElementById("lname"))
		document.getElementById("lname").value='';
	if(document.getElementById("lastName"))
		document.getElementById("lastName").value='';
	if(document.getElementById("Aline3"))	
	document.getElementById("Aline3").value='';
	if(document.getElementById("PoBox"))
	document.getElementById("PoBox").value='';
	document.getElementById("Aline1").value='';
	document.getElementById("Aline2").value='';	
	document.getElementById("City").value='';
	document.getElementById("Pcode").value='';
	document.getElementById("Province").selectedIndex=0;
	document.getElementById("Phone").value='';
	document.getElementById("altNumber").value='';	
}

function checkCardType(obj)
{
	if(!isSessionExpired())
	{
		if(document.getElementById('PoBox'))
		{
			document.getElementById('postalBox').value=document.getElementById('PoBox').value;
		}
		if(document.getElementById('payment_method').value=='The_BRICK_Card')
		{		
			document.getElementById('CreditCardOptions').innerHTML='';
		}
		return true;
	}
	else
	{
		displaySessionTimeOut();
		return false;
	}
}

/*Function to confirm whether the user really wants to cancel the order. */
function confirmOrderCancel(obj)
{
	if(!isSessionExpired())
	{
		PopupController.openPopup(obj+'/jsp/lightbox_content/cancelOrderConfirmationLightBox.jsp',12345,obj+'/jsp/lightbox_content');
	}
	else
	{
		displaySessionTimeOut();
		return false;
	}
}
var timer = 0;
setInterval('incrementTimer()',1000);

function incrementTimer()
{
	++timer;
}

/* This function is to display the Session Expiry light box. */
function displaySessionTimeOut()
{
	var contextPath = document.getElementById('contextPath').value;
	PopupController.openPopup(contextPath+'/jsp/lightbox_content/sessionTimeoutLightBox.jsp',12345,contextPath+'/jsp/lightbox_content');
}

/* This function actually checks the session expiry based on the sessionTimeout. */
function isSessionExpired()
{
	var sessionTimeout = 1800;
	
	if(document.getElementById('sessionTimeout'))
	{
		sessionTimeout = parseInt(document.getElementById('sessionTimeout').value);
	}	
	
	if(timer>=sessionTimeout)
	{ 
		
		return true;	
	}
	else
	{
	
		return false;
	}			
}

function disableButtons()
{
	 $('#enableSubmit').hide();
	 $('#disableSubmit').show(); 
	 $('#enablePrevious').hide();
	 $('#disablePrevious').show();
	 $('#enableCancel').hide();
	 $('#disableCancel').show();  
			
	 return checkSessionExpiry();
	
}

/* This function is called to check the session expiry when the user interacts with the application. */
function checkSessionExpiry()
{

	if(isSessionExpired())
	{
		displaySessionTimeOut();
		return false;
	}
	else
	{
		return true;
	}
}

/*This function will be called to check whether the session exists when the browser is refreshed or back button is clicked*/
window.onunload=function(){
	
	var sessionTimeout = 1800;

	if(document.getElementById('sessionTimeout'))
	{
		sessionTimeout = parseInt(document.getElementById('sessionTimeout').value);
	}
	if(timer>=sessionTimeout)
	{
		var contextPath = document.getElementById('contextPath').value;
		window.open(contextPath+"/jsp?sessionExpired=Y","_parent");
	}
}

var qtyChangeFlag= "false";
	function setQtyChangeFlag()
	{
		qtyChangeFlag = "true";

	}

	function checkQuantity(){

		if(isSessionExpired())
		{	
			displaySessionTimeOut();
			return false;
		}
		if(qtyChangeFlag=="true")
		{
			var uurl= document.getElementById('url').value;
			window.location.href = uurl;
			return false;
		}
		return true;
 	
 	}
 // function called when user clicks on add warranty link in shoppingcart.jsp	
 	function checkForNegativeQuantity(){

		if(isSessionExpired())
		{	
			displaySessionTimeOut();
			return false;
		}
		//function to check for special characters entered in the quantity field in shopping cart page
			for (i=0; i<document.cartItems.elements.length; i++)
					{
					  //Identify the text element		
					 	
						if (document.cartItems.elements[i].type=="text" && document.cartItems.elements[i].id !="couponId")
						{ 	
						 	var val=document.cartItems.elements[i].value;	
						 	if(null!=val && val!="")
							{
								var tempVal=val.trim();
								if(tempVal=="")
								{	
									document.cartItems.elements[i].value=tempVal;
									document.getElementById("qtyErrorHolder").style.display='block';
									return false;
								}
								else
								{
									document.cartItems.elements[i].value=tempVal;
									var valLength=parseInt(tempVal.length);
									if(valLength > 0 && valLength < 3)
							 		{ 		
							 			for (var j = 0; j < valLength; j++) 
										{
											var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?~_"; 
															   			 
									  		if (iChars.indexOf(tempVal.charAt(j)) != -1 || isNaN(tempVal)) 
									  		{	  
									  			document.getElementById("qtyErrorHolder").style.display='block';
									  		  	return false; 
											}
									  	}
									 }
								}
							}
							else
							{
								document.getElementById("qtyErrorHolder").style.display='block';
								return false;
							}
				 		}}
			 		
		return true;
 	
 	}
 	

function removeRepeatedTitles()
{
	for(var i=0;i<document.getElementById("Title").options.length;i++)
	{
		var title1 = document.getElementById("Title").options[i].text;
		for(var j=i+1;j<document.getElementById("Title").options.length;j++)
		{
			var title2 = document.getElementById("Title").options[j].text;
			if(title1 == title2)
			{
				document.getElementById("Title").remove(j);
			}
		}
	}

}
// setting the focus on the error field . function called in deliveryoption,createaddress,payment and billing pages
function setFocusOnErrorField(option)
{

   var paymentErrorFlag=false;
   var shippingMethod="";
   if(option=='payment')
      shippingMethod=document.getElementById('shippingMethod').value;
	
   if(option=='payment'){
   
   if( $("#CardHolder").is(".errorFld") )
	   {
	 	  paymentErrorFlag=true;
		  $('#CardHolder').focus();
		 }
	else if($('#CardNo').is(".errorFld"))
		 {
		   paymentErrorFlag=true;
			$('#CardNo').focus();
		 }
     else if($('#CVVNumber').is(".errorFld"))
		 {
		   paymentErrorFlag=true;
			$('#CVVNumber').focus();
		 }
	else if(shippingMethod!='In-store Pick-up')
		 {
		 if($('#email').is(".errorFld")){
		   paymentErrorFlag=true;
			$('#email').focus();
		 }
		 }
   
   }

   
   if(!paymentErrorFlag){

   
 	 if($('#Nname').is(".errorFld"))
		 {
			$('#Nname').focus();
		 }

	else if( $("#firstName").is(".errorFld") )
		 {
		  $('#firstName').focus();
		 }
	else if($('#lastName').is(".errorFld"))
		 {
			$('#lastName').focus();
		 }
	else if($('#FName').is(".errorFld"))
		 {
			$('#FName').focus();
		 }
	else if($('#LName').is(".errorFld"))
		 {
			$('#LName').focus();
		 }	 
	else if($('#Apt').is(".errorFld"))
		 {
			$('#Apt').focus();
		 }	 
     else if($('#Aline3').is(".errorFld"))
		 {
			$('#Aline3').focus();
		 }
	else if($('#Aline1').is(".errorFld"))
		 {
			$('#Aline1').focus();
		 }
	else if($('#City').is(".errorFld"))
		 {
			$('#City').focus();
		 }
	else if($('#Pcode').is(".errorFld"))
		 {
			$('#Pcode').focus();
		 }
	else if($('#POBox').is(".errorFld"))
		 {
			$('#POBox').focus();
		 }	 
	else if($('#PoBox').is(".errorFld"))
		 {
		
			$('#PoBox').focus();
		 }	
	else if($('#Phone').is(".errorFld"))
		 {
			$('#Phone').focus();
		 }	 
	else if($('#altNumber').is(".errorFld"))
		 {
			$('#altNumber').focus();
		 }
	else if($('#AltPhone').is(".errorFld"))
		 {
			$('#AltPhone').focus();
		 }	 	
	else if(shippingMethod=='In-store Pick-up')
		 {
			 if($('#email').is(".errorFld")){
			  paymentErrorFlag=true;
			 $('#email').focus();
		 		}
		 }	 
}
}
// setting the focus on the error field . function called in registration edit pages
function setFocusOnEditRegErrorField()
{

   if( $("#FName").is(".errorFld") )
	   {
	 	
		  $('#FName').focus();
		}
	else if($('#LName').is(".errorFld"))
		 {
		
			$('#LName').focus();
		 }
     else if($('#email').is(".errorFld"))
		 {
		  
			$('#email').focus();
		 }
	else if($('#ConfEmail').is(".errorFld"))
		 {
		
			$('#ConfEmail').focus();
		 }
     else if($('#registerPostalCodeTextbox').is(".errorFld"))
		 {
		  
			$('#registerPostalCodeTextbox').focus();
		 }	 

}
// setting the focus on the error field . function called in registration content page
function setFocusOnRegErrorField()
{

   if( $("#FName").is(".errorFld") )
	   {
	 	
		  $('#FName').focus();
		}
	else if($('#LName').is(".errorFld"))
		 {
		
			$('#LName').focus();
		 }
     else if($('#Email').is(".errorFld"))
		 {
		  
			$('#Email').focus();
		 }
	else if($('#ReEmail').is(".errorFld"))
		 {
		
			$('#ReEmail').focus();
		 }
     else if($('#Pwd').is(".errorFld"))
		 {
		  
			$('#Pwd').focus();
		 }	 
	else if($('#RePwd').is(".errorFld"))
		 {
		  
			$('#RePwd').focus();
		 }
   else if($('#registerPostalCodeTextbox').is(".errorFld"))
		 {
		  
			$('#registerPostalCodeTextbox').focus();
		 }		 
}
