// 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 UpdateTotal(form,theOrderId,theOrderItemId,theCatentryId,mimQtyForPerson,statusCount)  
	{
	 	var quant = document.getElementById('quantity_'+statusCount).value;
			if(quant == 0){			
				//var link =  window.location.hostname  + '/../OrderItemDelete?orderItemId='+theOrderItemId+'&orderId='+theOrderId+'&updatePrices=1&calculationUsageId=-1&calculationUsageId=-2&calculationUsageId=-7&langId=-1&catalogId=10051&storeId=10052&productId='+theCatentryId+'&URL=OrderCalculate?URL=OrderItemDisplay&errorViewName=InvalidInputErrorView'
	            var link =  window.location.hostname  + '/../OrderItemDelete?orderItemId='+theOrderItemId+'&orderId='+theOrderId+'&updatePrices=1&calculationUsageId=-1&calculationUsageId=-2&calculationUsageId=-7&langId=-1&catalogId=10051&storeId=10052&productId='+theCatentryId+'&OrderCalculate?updatePrices=1&calculationUsageId=-1&calculationUsageId=-2&orderItemId*=&quantity*=&URL=OrderItemDisplay&errorViewName=InvalidInputErrorView'
                window.location = link;																																																														
			}
			else if(mimQtyForPerson <= quant){
				form.submit();
			}
			else if(mimQtyForPerson > quant){
				document.getElementById('quantity_'+statusCount).value = mimQtyForPerson;
				document.getElementById('minQtyId').style.display = "block";
				//form.submit();
			}
	}
	     
	
	function UpdateInvitationTotal(form,theOrderId,theOrderItemId,theCatentryId,theShipModeId)  
	{
            form.submit();			
	}     
	
	
	
	function ApplyPromotion(form)  	
	{
	 	
	 	form.submit();
		   
	}     
	


	function validateShippingAddressAdd(form) {
 
 
 	  validator_reset();
	  form.nick_name.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.phone_number.validations.validate();
	  
	  if (validation_display_errors('') == true) {
	   	 form.submit();
	  } 
  
   }
   
   // validate checkout sign in page
   function validateLogonForm(form) {
 
 	  validator_reset();
	  form.logonId.validations.validate();	  
	  
	  if (validation_display_errors('') == true) {
	   	 form.submit();
	  } 
  
   }
   
   	function validateShippingForm(form) {
 	  validator_reset();
 	  
	  form.first_name.validations.validate();
	  form.last_name.validations.validate();
	  form.shipping_street_address.validations.validate();
	  form.shipping_city.validations.validate();
	  form.shipping_zip_postal_code.validations.validate();
  	  form.shipping_phone_number.validations.validate();
  	  
  	  form.billing_street_address.validations.validate();
	  form.billing_city.validations.validate();
	  form.billing_zip_postal_code.validations.validate();
  	  form.billing_phone_number.validations.validate();
  	  
  	  form.cc_brand.value = cc_types[form.policyId.value];	
		
	 /**********************************************************************************
		* Perform client validation of the Credit Card fields
	 **********************************************************************************/
	  form.account.validations.validate();
  	  form.cc_name.validations.validate();
	  form.expire_year.validations.validate();  
	  form.cc_cvc.validations.validate(); 
	  
	  if (!(form.cc_brand.value == '' || form.cc_cvc.value == '')) {
			if (!isValidCVVCode(form.cc_brand.value, form.cc_cvc.value.length))
			{
				add_error('CCSecurityCodeError','<p>Security code is invalid!</p>');
			}
	  }
	  //jh:20090930
	  if(form.policyId.value == '1000005') { //David's Bridal Credit Card
		  if (!form.dbccOfferAgree[0].checked && !form.dbccOfferAgree[1].checked) {
				add_error('DBCCOfferAgreeError','<p>Please chose either \'I agree\' or \'I do not agree\' under \"Consent to Electronic Disclosures\"</p>');
		  }
		  //jh if user checked 'I do not agree' then reset cc to AMEX and clear cc name and number
		  //if (form.dbccOfferAgree[1].checked) {		  
		  //		document.getElementById("policyId").options[0].selected = true;
		  //		document.getElementById("account").value = "";
		  //		document.getElementById("cc_name").value = "";		  				  		
		  //}
		  //jh:20091007
		  if (form.dbccOfferAgree[0].checked && form.dbccOfferTermsContinue.value != 'Y') {
				add_error('DBCCOfferTermsContinueError','<p>Please click \'I Agree\' under Consent to Electronic Disclosures to bring up the David\'s Bridal Credit Card Plans popup window.  Then click Continue in that window.</p>');
		  }
	  }
	  
	  if(form.ServiceCoordinatorNumber.value != ""){
	  	form.ServiceCoordinatorNumber.validations.validate();
	  }
	  
	  if(form.refsource2.value != ""){
	  	form.refsource2.validations.validate();
	  }
	  
	  if (validation_display_errors('') == true) {
	   // document.ShippingForm.action = 'AddressAdd';
	    //document.getElementById("URLId").value = 'OrderItemUpdate?URL=OrderPrepare?URL=OrderCalculate?URL=BillingView?orderItemId*=';
	   	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)
	{
			
		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.cc_cvc.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.cc_cvc.value == '')) {
			if (!isValidCVVCode(form.cc_brand.value, form.cc_cvc.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.URL.value = 'BrulantCheckoutBillingCmd?URL=OrderReviewView?allocate=*n&backorder=*n&reverse=*n&remerge*n'
			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 == "DBI" || ccType == "MASTER" || 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')
				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";
		}
	}


	function jumpThroughPhoneFields(currentBox, nextBoxId, currentBoxLimit, evt)
	{
		if (!isNumberKey(evt))
		{
		    return false;
		}
		else
		{
		    if (!evt)
		    {
		    	var evt = window.event;
		    }
		    
		    var charCode = (evt.which) ? evt.which : evt.keyCode;
		    
			if (charCode >= 48 && charCode <= 57)
			{
			    // do the actions
			    var currentValue = currentBox.value;
			    var currentLength = 0;
			    if (currentValue)
			    {
			        currentLength = currentValue.length;
			    }
			    
			    if (currentLength == currentBoxLimit-1)
			    {
				    var charTyped = String.fromCharCode(charCode);
				    
				    var nextBox = document.getElementById(nextBoxId);
				    
				    currentBox.value += charTyped;
				    nextBox.focus();
				    return false;
			    }
			    else
			    {
			    	return true;
			    }
			}
			else
			{
			    return true;
			}
		}
		
	 }

function enableShippingFields(checkCountry) {
	
		//alert (checkCountry);
		//alert('1 : '+document.getElementById("billing_state").value);
		//document.getElementById("shipping_state").value  = document.getElementById("billing_state").value
		//alert('2 : '+document.getElementById("billing_state").value);
	 if ($('shippingSame') && $('shippingSame').checked == true) {
	
		$('shipping_street_address').value = $('billing_street_address').getValue();
		$('shipping_street_address2').value = $('billing_street_address2').getValue();
		$('shipping_city').value = $('billing_city').getValue();
		if(checkCountry == 'US'){
			$('shipping_state').value = $('billing_state').getValue();
		}	
		$('shipping_zip_postal_code').value = $('billing_zip_postal_code').getValue();
		$('shipping_phone_number').value = $('billing_phone_number').getValue();
		$('shipping_phone2').value = $('billing_phone2').getValue();
		$('shipping_phone3').value = $('billing_phone3').getValue();		
	}
	else {
		$('shipping_street_address').value = "";
		$('shipping_street_address2').value = "";
		$('shipping_city').value = "";
		$('shipping_zip_postal_code').value = "";
		$('shipping_phone_number').value = "";
		$('shipping_phone2').value = "";
		$('shipping_phone3').value = "";
	}
} 

function CheckoutShippingFormSubmit()
	{
		
		var selectShipping=document.getElementById("selectShipping");
		var x=document.getElementById("selectShipping").selectedIndex;
		//alert(x);
		var shipModeId= selectShipping.options[x].value;
  		//alert(shipModeId);
  		
		document.OrderShippingForm.shipModeId.value =shipModeId;
		//alert(document.OrderShippingForm.shipModeId_0.value);		
		document.OrderShippingForm.submit();
	}
	
function submitOrderReviewForm()
	{				
		document.getElementById("processOrder").style.display="block";		
		document.ProcessOrderForm.submit();
	}
	
 
function setCardType(a) 
{	
	//jh:20091006 
	//Change a to be the policyId field value, i.e. 10000005 is Davids Bridal Credit Card
	
	var x=document.getElementById("policyId");
	var row = document.getElementById("captionRow");
	var row1 = document.getElementById("expirationRow");	
	
	for (i=0;i<x.length;i++)
    {
    	//jh if (x.options[i].text == a)
    	if (x.options[i].value == a)
    	{    		
    		x.options[i].selected = true;
    		//jh call displayRow in PaymentForm.jspf
    		displayRow();
    		/*if (a == 'Davids Bridal credit card'){
    			row.style.display = 'none';
    			row1.style.display = 'none';
    			document.getElementById("cc_cvc").value = '333';
    			document.getElementById("expire_month").value = '12';  
    			document.getElementById("expire_year").value = '2012';      			
    			  		
    		}
    		else{
    			row.style.display = '';
    			row1.style.display = '';    		
    			document.getElementById("cc_cvc").value = ''; 
    		}*/
    	}	
    }
	
	
}
function isNumberKey(evt)
{
	var charCode = (evt.which) ? evt.which : evt.keyCode
	if (charCode > 31 && (charCode < 48 || charCode > 57))
		return false;
	return true;
}

//function retrieveInvitaion()
//{
//	alert('Hello!!');
//	var invitationNumber = document.getElementById('cartnumber').value;
//	var orders_id = document.getElementById('WC_OrderItemDisplay_FormInput_orderId_In_ShopCartForm_1').value;
//	alert('invitationNumber  : ' + invitationNumber);
//	alert('orders_id : ' + orders_id);
//    var link =  window.location.hostname  + '/webapp/wcs/stores/servlet/DBIInvitationCmd?toDo=retrieve&orderId='+orders_id+'&reOrderId='+invitationNumber;
//    alert('link '+ link);
//	  window.location = link;
	
//}

function retrieveInvitationShoCartEmptySubmit()
	{			
		document.RetrieveInvitationShopCartEmptyForm.submit();
	}


function retrieveInvitationSubmit()
	{			
		document.RetrieveInvitationForm.submit();
	}
	

function saveInvitationSubmit()
	{			
		document.SaveInvitationForm.submit();
	}
