// 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();			
	}     
	
	
	if(typeof String.prototype.trim !== 'function') {
 		String.prototype.trim = function() {
    	return this.replace(/^\s+|\s+$/g, ''); 
  		}
	}
	
	function ApplyPromotion(form)  	
	{
		var valuePromoCode = form.promoCode.value;
		var valuePromoCode = valuePromoCode.trim();
		form.promoCode.value = valuePromoCode;
		if (valuePromoCode.trim().length > 0) {
	 		if(typeof(parent.cmCreateConversionEventTag)=="function"){parent.cmCreateConversionEventTag("Return Page/"+form.promoCode.value,2,"AddCode");}	 		 	
	   	 	form.submit();
	  	}else{
	  		document.getElementById("promoCodeRequiredMessage").style.display="block";
	  	}  
	}     
	


	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 populateAndValidateShippingForm(form) {


		// CV - Omer Sever - 03/24/2010 - Fixed a problem in prod - Checkbox "Make shipping address the same" should copy the values of billing address to shipping address"
		copyBillingValuesToShipping();



 	  validator_reset();
 	  
	  form.cc_nameoncard.value = form.billing_first_name.value + " " + form.billing_last_name.value;

	  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_first_name.validations.validate();
	  form.billing_last_name.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.billing_email.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 && !form.dbccOfferAgree[2].checked && !form.dbccOfferAgree[3].checked) {
				add_error('DBCCOfferAgreeError','<p>Please choose 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.dbccOfferAgree[2].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>');
		  }
		  
	  }
	  
/* Omer Sever 03/05/2010 - removed due to removal of Service Coordinator from UI
	  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
	//jh:20100114 QC-15236 Add Diners Club card, same as Discover.  ccType is read in from 
	//toolkit_dir/xml/config/payments/edp/groups/default/PaymentMappings.xml
	///////////////////////////////////////////////////////////////////////////////
	function isValidCVVCode(ccType, cvvCount) {
		if ((ccType == "AMEX" && cvvCount == 4) || ((ccType == "DISCOVER" || ccType == "DINERS" || 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) {
	
		$('first_name').value = $('billing_first_name').getValue();
		$('last_name').value = $('billing_last_name').getValue();
		$('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 {
		$('first_name').value = "";
		$('last_name').value = "";
		$('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 changeShippingVisibility() {
	
	if ($('shippingSame') && $('shippingSame').checked == true) {
		document.ShippingForm.shippingSameChecked.value = true;
//		$('tbl_shippingaddress').style.visibility = "hidden";
	} else {
		document.ShippingForm.shippingSameChecked.value = false;
//		$('tbl_shippingaddress').style.visibility = "visible";
	}

} 

function copyBillingValuesToShipping() {
	
	 if ($('shippingSame') && $('shippingSame').checked == true) {
	
		$('first_name').value = $('billing_first_name').getValue();
		$('last_name').value = $('billing_last_name').getValue();
		$('shipping_street_address').value = $('billing_street_address').getValue();
		$('shipping_street_address2').value = $('billing_street_address2').getValue();
		$('shipping_city').value = $('billing_city').getValue();
		$('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();
	}
} 


function clearFields() {
	
 if ($('shippingSame') && $('shippingSame').checked == false) {

        $('first_name').value = "";
        $('last_name').value = "";
        $('shipping_street_address').value = "";
        $('shipping_street_address2').value = "";
        $('shipping_city').value = "";
        $('shipping_state').value = "";
        $('shipping_zip_postal_code').value = "";
        $('shipping_phone_number').value = "";
        $('shipping_phone2').value = "";
        $('shipping_phone3').value = "";
 }
}
function CheckoutShippingFormSubmit()
	{
		var oRadios = document.OrderShippingForm.selectShipping;
	     for(var i = 0; i < oRadios.length; i++) {
	        if(oRadios[i].checked) {
			var shipModeId=oRadios[i].value;
      	  }	
		}
		document.OrderShippingForm.shipModeId.value =shipModeId;
		document.getElementById("updateShipMethodId").style.display="block";
		document.OrderShippingForm.submit();
	}

var placeOrderClickedOnce=0;
function submitOrderReviewForm()
	{		
		if(placeOrderClickedOnce==1){
			return;
		}		
		document.getElementById("processOrder").style.display="block";		
		document.ProcessOrderForm.submit();
		placeOrderClickedOnce=1;
	}
	
function blinkIt() {
 if (!document.all) return;
 else {
   for(i=0;i<document.all.tags('blink').length;i++){
      s=document.all.tags('blink')[i];
      s.style.visibility=(s.style.visibility=='visible')?'hidden':'visible';
   }
 }
}


 
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 setCardTypeByCardName(cardName) 
{	
	//jh:20091006 
	//Change a to be the policyName field value, i.e. DBI is Davids Bridal Credit Card, VISA for Visa
	
	var x=document.getElementById("policyId");
	
	for (i=0;i<x.length;i++)
    {
    	if (x.options[i].policyName == cardName)
    	{    		
    		x.options[i].selected = true;
    		//jh call displayRow in PaymentForm.jspf
    		displayRow();
    	}	
    }
	
	
}
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();
	}

	
// Omer Sever 03/05/2010 - Same as Shipping Address Feature
function enableBillingFields(checkCountry) {
	
	 if ($('billingSame') && $('billingSame').checked == true) {
	
		$('billing_first_name').value = $('first_name').getValue();
		$('billing_last_name').value = $('last_name').getValue();
		$('billing_street_address').value = $('shipping_street_address').getValue();
		$('billing_street_address2').value = $('shipping_street_address2').getValue();
		$('billing_city').value = $('shipping_city').getValue();
		if(checkCountry == 'US'){
			$('billing_state').value = $('shipping_state').getValue();
		}	
		$('billing_zip_postal_code').value = $('shipping_zip_postal_code').getValue();
		$('billing_phone_number').value = $('shipping_phone_number').getValue();
		$('billing_phone2').value = $('shipping_phone2').getValue();
		$('billing_phone3').value = $('shipping_phone3').getValue();		
	}
	else {
		$('billing_first_name').value = "";
		$('billing_last_name').value = "";
		$('billing_street_address').value = "";
		$('billing_street_address2').value = "";
		$('billing_city').value = "";
		$('billing_zip_postal_code').value = "";
		$('billing_phone_number').value = "";
		$('billing_phone2').value = "";
		$('billing_phone3').value = "";
	}
} 

	// Called From: GuestOrderLookupForm.jspf   
	// JS validation check 
    function validateOrderStatusLookupFormCV(form) {
 	  validator_reset();
	  form.orderId.validations.validate();	  
	  form.email.validations.validate();	  
	  
	  if (validation_display_errors('') == true) {
	   	 form.submit();
	  } 
  
    }



