// This is the CheckoutOrder javascript file for the BRSF
//Date: 04/10/08 Time: 9:17 am      
//Name: Kunal Teckchandnai
//Description: All the inline javascript functions for the CheckoutOrder section of the BRSF should
//			   be included in this CheckoutOrder.js function only  

    cc_types = new Array();        
 
	//JavaScript function applies in the header and body section for clearing the text   
		   
    function ClearText(searchkeyword)
    {

    	document.getElementById(searchkeyword).value='';   
   
	}

	//JavaScript function applies in the header section for setting a default text 

	function GetText(searchtext)
	{
		document.getElementById(searchtext).value='What are you looking for?';
	}

	//JavaScript function applies in the body promotion section for setting a default text 

	function GetPromoText(promotext)
	{
		document.getElementById(promotext).value='enter code';
	}
	
	function isNumberKey(evt)
	{
	     var charCode = (evt.which) ? evt.which : evt.keyCode
	     if (charCode > 31 && (charCode < 48 || charCode > 57))
	        return false;
	 
	     return true;
	}

	
		
	function UpdateTotal(form,rowNo,quantity)      
	{
		  
		validator_reset();
		
  	  	var quantityFieldId = 'quantity_' + rowNo;
  	  	var quantityFieldObj = document.getElementById(quantityFieldId);
		quantityFieldObj.validations.validate();  
		
		
		if(validation_display_errors('')==false){
              
      	  document.getElementById(quantityFieldId).value = quantity;
       }
		
		if(validation_display_errors('')==true){
              
              document.OrderUpdateForm.submit();
       }
		   
	}     
	
	function CheckOut(form,rowNo)   
	{
		
		validator_reset();
		
  	  		var quantityFieldId = 'quantity_' + rowNo;
  	  		var quantityFieldObj = document.getElementById(attributeFieldId);
			quantityFieldObj.validations.validate();  
		
		
		if(validation_display_errors('')==true){
              
              document.OrderUpdateForm.submit();
       }
		   
	}     
	
	function ApplyPromotion(form)  	
	{
	 	form.submit();
		   
	}     
	


	function validateAddressAdd(form) {
 
 
 	  validator_reset();
	  var nickNameObject = document.getElementById('nick_name');
	  if(nickNameObject != null){
	  	 nickNameObject.validations.validate();
	  }
	  form.first_name.validations.validate();
	  form.last_name.validations.validate();
	  form.street_address.validations.validate();
	  form.city.validations.validate();
	  form.zip_postal_code.validations.validate();
	  form.state_province.validations.validate();
	  form.country_region.validations.validate();
		  	
  	  
	  /*Concate phone number and store in form field form1*/
	  	  $('phone1').value = $('area_code').value+$('first_three').value+$('last_four').value+$('ext').value;
	  	  
	  form.phone1.validations.validate();
	  
	  if (validation_display_errors('') == true) {
	   	form.submit();
	  } 
  
   }
   
   
   var addressSelection;
   function validateShippingForm(form,user) {

	 var userType = user;
		if(userType == "G")	{
		
			addressSelection = 'newAddress';
			
			}

		 
 	 	  validator_reset();
 	 	 
 	 	  if ( addressSelection == 'newAddress') {
 	 	 
			var nickNameObject = document.getElementById('nick_name');
			if(nickNameObject != null){
		  		nickNameObject.validations.validate();
		  	}
			  form.first_name.validations.validate();
			  form.last_name.validations.validate();
			  //form.officeAddress.validations.validate();
			  form.street_address.validations.validate();
			  form.city.validations.validate();
			  form.zip_postal_code.validations.validate();
		  	  form.state_province.validations.validate();
		  	  form.country_region.validations.validate();
		  	  form.jurisdiction.validations.validate();
		  	  
		  	  /*Concate phone number and store in form field form1*/
		  	  var phoneAreaCode = form.area_code.value;
//  		  	  alert('phoneAreaCode '+phoneAreaCode);

  		  	  var phonePrefix = form.first_three.value;
//  		  	  alert('phonePrefix '+phonePrefix);
  		  	  
		  	  var phoneSuffix = form.last_four.value;
//		  	  alert('phoneSuffix '+phoneSuffix);
		  	  
		  	  var phoneNumber =  ''+phoneAreaCode + ''+phonePrefix + ''+phoneSuffix
//		  	  alert('phoneNumber '+phoneNumber);
		  	  form.phone1.value = phoneNumber;
		  	  
	  	  	  form.phone1.validations.validate();
	  	  	  
	  	  	  //document.ShippingForm.action = 'AddressAdd';
		      //var urlVar = document.getElementById("URLId");
		      //document.getElementById("URLId").value = "OrderItemUpdate?URL="+urlVar.value;
		      
	  	  	  
		  }

  	  	  if (form.shipModeId && form.shipModeId.validations) {
	  	  	  form.shipModeId.validations.validate();
	  	  }
	  	  	  
		  
		  if (validation_display_errors('') == true) {
	
		  form.submit();
	   }
 
   }
   
   	function validateCatalogAddressAdd(form) {
 
 		alert("form "+form);
 
 	  validator_reset();
	  form.first_name.validations.validate();
	  form.last_name.validations.validate();
	  /*
	  form.street_address.validations.validate();
	  form.city.validations.validate();
	  form.C_state_province.validations.validate();
	  form.zip_postal_code.validations.validate();
	  */
	  if (validation_display_errors('') == true) {
	   	form.submit();
	  } 
  
   }

	
function validatePaymentForm(form)
	{
			
		validator_reset();
			
		form.cc_brand.value = cc_types[form.policyId.value];	
		
		/**********************************************************************************
		* Perform client validation of the Credit Card fields
		**********************************************************************************/
		form.policyId.validations.validate();        
		form.account.validations.validate();
		form.expire_year.validations.validate();  
		form.security_code.validations.validate();     
		
	// This is for validating if CC number follows the correct format depending on the CC brand using Regular Expressions.
	
	/*	if (form.cc_number.value.length >= 13 && form.cc_number.value.substring(0,4) !== 'xxxx')
		{
			// The 'isValidCreditCard' function has all the RegEx rules for valid CC# for respective CC brands
			if (!isValidCreditCard(form.cc_brand.value, form.cc_number.value))
			{
				add_error('CCNumberError','<p><fmt:message key="_ERR_PAY_CARD_NUMBER_INVALID.1005" bundle="${storeErrorMessages}" /></p>');
			}
		}
		form.cc_year.validations.validate();
		form.cc_securityCode.validations.validate();
		
		*/
		// The 'isValidCVVCode' function checks the length of the CVV code based on the CC brand (provided the CC brand and CVV code are not null).
		if (!(form.cc_brand.value == '' || form.security_code.value == '')) {
			if (!isValidCVVCode(form.cc_brand.value, form.security_code.value.length))
			{
				add_error('CCSecurityCodeError','<p>Security code is invalid!</p>');
			}
		}
	

		/**********************************************************************************
		* Display any errors which exist otherwise submit the form
		**********************************************************************************/
		if (validation_display_errors('') == true) 
		{
			form.submit();
		}
	}
	
	function validateBillingForm(form,address)
	{
		validator_reset();
		if ( addressSelection === 'newAddress') {	

			//validate new address form fields
		
		  var nickNameObject = document.getElementById('nick_name');
		  if(nickNameObject != null){
		  	 nickNameObject.validations.validate();
		  }
		  form.first_name.validations.validate();
		  form.last_name.validations.validate();
		  form.street_address.validations.validate();
		  form.city.validations.validate();
	  	  form.state_province.validations.validate();
	  	  form.country_region.validations.validate();
		  form.zip_postal_code.validations.validate();
	  	 
	  	  /*Concate phone number and store in form field form1*/
	  	  $('phone1').value = $('area_code').value+$('first_three').value+$('last_four').value;
  	  	  form.phone1.validations.validate();
  	  	  
  	  	    
  	  	  //document.BillingForm.action = 'AddressAdd';
	      //var urlVar = document.getElementById("URLId");
	      //document.getElementById("URLId").value = "OrderPrepare?URL="+urlVar.value;
	 	}	
		form.cc_brand.value = cc_types[form.policyId.value];	
		
		form.email_address.validations.validate();        
		/**********************************************************************************
		* Perform client validation of the Credit Card fields
		**********************************************************************************/
		form.policyId.validations.validate();        
		form.account.validations.validate();
		form.card_name.validations.validate();
		form.expire_year.validations.validate();  
		form.security_code.validations.validate();     
		
	// This is for validating if CC number follows the correct format depending on the CC brand using Regular Expressions.
	
	/*	if (form.cc_number.value.length >= 13 && form.cc_number.value.substring(0,4) !== 'xxxx')
		{
			// The 'isValidCreditCard' function has all the RegEx rules for valid CC# for respective CC brands
			if (!isValidCreditCard(form.cc_brand.value, form.cc_number.value))
			{
				add_error('CCNumberError','<p><fmt:message key="_ERR_PAY_CARD_NUMBER_INVALID.1005" bundle="${storeErrorMessages}" /></p>');
			}
		}
		form.cc_year.validations.validate();
		form.cc_securityCode.validations.validate();
		
		*/
		// The 'isValidCVVCode' function checks the length of the CVV code based on the CC brand (provided the CC brand and CVV code are not null).
		if (!(form.cc_brand.value == '' || form.security_code.value == '')) {
			if (!isValidCVVCode(form.cc_brand.value, form.security_code.value.length))
			{
				add_error('CCSecurityCodeError','<p>Security code is invalid!</p>');
			}
		}
		
		var creditCardSelectField = document.getElementById('policyId');
		var ccSelectedIndex = creditCardSelectField.selectedIndex;
		var creditCardBrand = creditCardSelectField.options[ccSelectedIndex].text;
		  
		var creditCardNumber = document.getElementById('account').value;
		if(creditCardBrand.startsWith('V') && !(creditCardNumber.startsWith('4'))){
			add_error('CCNumberError','<p>Credit card number and credit card type do not match!</p>');
			add_error('CCTypeError','');
		}
		else if(creditCardBrand.startsWith('M') && !(creditCardNumber.startsWith('5'))){
			add_error('CCNumberError','<p>Credit card number and credit card type do not match!</p>');
			add_error('CCTypeError','');
		}
		else if(creditCardBrand.startsWith('A') && !(creditCardNumber.startsWith('3'))){
			add_error('CCNumberError','<p>Credit card number and credit card type do not match!</p>');
			add_error('CCTypeError','');
		}
		else if(creditCardBrand.startsWith('D') && !(creditCardNumber.startsWith('6'))){
			add_error('CCNumberError','<p>Credit card number and credit card type do not match!</p>');
			add_error('CCTypeError','');
		}		
		

		/**********************************************************************************
		* Display any errors which exist otherwise submit the form
		**********************************************************************************/
		if (validation_display_errors('') == true) 
		{
		   // form.URL.value = 'BrulantCheckoutBillingCmd?URL=OrderReviewView?allocate=*n&backorder=*n&reverse=*n&remerge*n'
		   if (address == 'newAddressRadioButtonChecked'){
				if(validateZipcode()){
					form.submit();
				}
			}else
			{
				form.submit();
			}
		}
	}
	
	
	 
	// This function is used to check if the CVV count is valid for a given CC type 
	// e.g. "AMEX" is 4, "Discover" is 3, "MASTER" is 3 and "VISA" is 3 
	///////////////////////////////////////////////////////////////////////////////
	function isValidCVVCode(ccType, cvvCount) {
		if ((ccType == "AMEX" && cvvCount == 4) || ((ccType == "Discover" || ccType == "Master Card" || ccType == "VISA") && (cvvCount == 3)) ) {
			return true;
		} else {
			return false;
		}
	}
	
	// This function is used to change the card type image 
	function cvcImageChange(form)
	{
		if (form.policyId.selectedIndex == 0)
		{
			form.cvc_Image.src = "/wcsstore/BRSF/static/images/background/credit_card_back.gif";
		}
		else
		{
			var x = form.policyId.selectedIndex;
			var card = form.policyId.options[x].text;
			
			if (card =='American Express Credit Card')
				form.cvc_Image.src = "/wcsstore/BRSF/static/images/background/credit_card_American_Express.gif";
			else
			   	form.cvc_Image.src = "/wcsstore/BRSF/static/images/background/credit_card_back.gif";
		}
	}


// This function is used to toggle "dissabled" on all elements in e1 //
///////////////////////////////////////////////////////////////////////
function disableAllElements(el) {
                try {
                    el.disabled = el.disabled ? true : true;
                    
                }
                catch(E){}
                
                if (el.childNodes && el.childNodes.length > 0) {
                    for (var x = 0; x < el.childNodes.length; x++) {
				
                        disableAllElements(el.childNodes[x]);
                    }
                }
            }
            
// This function is used to toggle "dissabled" on all elements in e1 //
///////////////////////////////////////////////////////////////////////
function enableAllElements(el) {
                try {
                    el.disabled = el.disabled ? false : false;
                    
                }
                catch(E){}
                
                if (el.childNodes && el.childNodes.length > 0) {
                    for (var x = 0; x < el.childNodes.length; x++) {
                        enableAllElements(el.childNodes[x]);
                    }
                }
            }
     
            
// This function to enable fields in Create New Address div //
///////////////////////////////////////////////////////////////////////  
var previousSelectedAddr = null, prevSelectedIndex = null;           
function enableCreateNew() {
	   addressSelection = 'newAddress';
	   document.getElementById('checkout_addresses_id').className="checkout_addresses_wrapper_2";
	   document.getElementById('new_address_radio').checked = true;
       enableAllElements(document.getElementById('new_address_div'));
       document.getElementById('new_address_div').className="module_container";
       document.getElementById('new_address_radio').disabled = false;
       if ($('selectAddressId')) {
			try {
				var selectVar = $('selectAddressId');
				if (selectVar.options.length > 0 && selectVar.selectedIndex > -1) {
	    	   		previousSelectedAddr = selectVar.options[selectVar.selectedIndex].value;
	    	   		prevSelectedIndex = selectVar.selectedIndex;
				}
			} catch (e) {
			}
       
	       $('selectAddressId').disabled = "disabled";
	   }
	   if ($('addressId')) {
		   $('addressId').value = '';
	   }
    //  disableAllElements(document.getElementById('saved_address_div'));
       document.getElementById('saved_address_div').className="module_container last";
     if ($('new_address_radio')) {
       	   $('new_address_radio').checked = true;
       }
		
	var savedAddressRadioObject = document.getElementById('saved_address_radio');
	if(savedAddressRadioObject != null){
    	document.getElementById('saved_address_radio').disabled = false;		
        document.getElementById('saved_address_radio').checked = '';
    }
	    
	   var countrySelectId = document.getElementById('country_region');
	   var stateSelectId = document.getElementById('state_province');
	   if(stateSelectId.selectedIndex != 0 && countrySelectId.selectedIndex != 0){

	    	 fireSelectedAddressChangedEvent(countrySelectId );

		}
	
}    

// This function is used to enable saved address div and disable new address div   //
///////////////////////////////////////////////////////////////////////////////////////////////
function enableSavedAddress(clickedAddressId) {
	   addressSelection = 'savedAddress';
	   document.getElementById('checkout_addresses_id').className="checkout_addresses_wrapper_1";
       validator_reset();
       
       enableAllElements(document.getElementById('saved_address_div'));
       document.getElementById('saved_address_div').className="module_container";
       document.getElementById('saved_address_radio').disabled = false;
       
       var selectVar = document.getElementById('selectAddressId');
       if (selectVar) {
			if (selectVar.options.length > 0 && selectVar.selectedIndex > -1) {
	       		var selectAddr = selectVar.options[selectVar.selectedIndex].value;
    	   		$('selectAddressId').value = selectAddr;
			} else if (previousSelectedAddr != null) {
				$('selectAddressId').value = previousSelectedAddr;
				selectVar.selectedIndex = prevSelectedIndex;
			}
	   } else if (clickedAddressId != null) {
	   		$('addressId').value = clickedAddressId;
	   }
       if ($('saved_address_radio')) {
       	   $('saved_address_radio').checked = true;
       }	   
       
       disableAllElements(document.getElementById('main_formID'));
       document.getElementById('new_address_div').className="module_container last";
       document.getElementById('new_address_radio').disabled = false;
       document.getElementById('new_address_radio').checked = '';
	if(selectVar.options.length > 0 ){
		fireSelectedAddressChangedEvent(selectVar);
	}
}  

// This function is used to enable saved address div and disable new address div   //
///////////////////////////////////////////////////////////////////////////////////////////////
function enableSameAddress() {
	   addressSelection = 'savedAddress';
	   document.getElementById('checkout_addresses_id').className="checkout_addresses_wrapper_1";
       validator_reset();
       enableAllElements(document.getElementById('saved_address_div'));
       if ($('saved_address_radio')) {
	       document.getElementById('saved_address_div').className="module_container";
    	   document.getElementById('saved_address_radio').disabled = false;
	   }
       if ($('shippingAddressId')) {
	       $('addressId').value = $('shippingAddressId').value;
	   }
       disableAllElements(document.getElementById('main_formID'));
       document.getElementById('new_address_div').className="module_container last";
       document.getElementById('new_address_radio').disabled = false;
       document.getElementById('new_address_radio').checked = '';


}  
  
// This function is used unhide div of address selected by user and hide other address divs   //
///////////////////////////////////////////////////////////////////////////////////////////////      
function showSelectedAddress(firstElement, addressId) {

		// hide all of the address div sections
		var addressShowHideDIVs = document.getElementsByClassName('address_selected_wrapper');

		// hide all of the address div sections
		for(var i=0; i < addressShowHideDIVs.length; i++){
			addressShowHideDIVs[i].className = "address_selected_wrapper_hidden";
		}
		
		// show the selected div section
		var selectedDIV = document.getElementById('address_selected_wrapper'+addressId);
		if(selectedDIV !== null ) {
		 selectedDIV.className="address_selected_wrapper";		
		}
}

function CampmorToggle(obj)
{
	var el = document.getElementById(obj);
	if ( el.style.visibility != 'hidden' ) {
		el.style.visibility = 'hidden';
	}
	else {
		el.style.visibility = 'visible';
	}
}

