/****************************
 * Invoked on the gift card
 * page to check the balance
 ****************************/
  // onload methods BEGIN 
 var CalculateGiftCardTotal = null; 
 var ExpiryDate = null;
 var FillGCInfo = null;
 var CheckForGCBalanceError = null;
 var AdjustCheckoutUI = null;  
 var AdjustGCError = null;
 var LoadStaticErrorMsgsFromPage = null;
  // onload methods END
  
  // Constants BEGIN
 var ONLOAD_VAL = 'onLoad';
 var CLEAR_ALL = 'ClearAll';
 var CLEAR_PIN = 'ClearPIN';
 var KEEP_GIFT_CARD = 'KeepGiftCard';
 var PLUS_IMG_VAL = '/wcsstore/hdus/en_US/images/layout/btn_+.jpg'
 var MINUS_IMG_VAL = '/wcsstore/hdus/en_US/images/layout/btn_-.jpg'
 var NETSCAPE_VAL = 'Netscape';  //FireFox
 var IE_VAL  = 'Microsoft Internet Explorer'; 
 var OMNITURE_CAPTCHA_ERR_VAL = 'giftcard balance check - captcha error';
 var OMNITURE_SYSTEM_ERR_VAL  = 'giftcard balance check - system error';
 var OMNITURE_USER_ERR_VAL    = 'giftcard balance check - user error';  
 var GIFT_CARD_BALANCE_FORM_NAME    = 'OrderItemAddForm';  
 var CHECKOUT_FORM_NAME    = 'OrderSummaryForm';  
  // Constants END
 
 // Global Variables BEGIN
 var debugVal = 'false';
 var groupCache = {};
 var browserAppName = navigator.appName.toLowerCase(); 
 var isGiftCardSectionCurrentlyVisible = false;
 var isGiftCardTenderActiveValue = 'false'; 
 var formName = '0';
 var omnitureMsg = '';
 var omnitureLinkTrackingObject = null;
 var focusOn = null;
 var focusOnAppliedTable = 'false';

 // Error Messages
 var gcUserErrorMsg = null;
 var gcSystemErrorMsg = null;
 var gcCaptchaErrorMsg = null;
 var gcBalanceErrorMsg = null;
 var duplicateGCErrorMsg = null;
 var nonUSGiftCardErrorMsg = null;
 var gcZeroBalanceErrorMsg = null;

 // Global Variables END

 


/*************************************************************************************************
*  Function:  expiryDate
*	set whether the expiry year and month should be disabled.	
*
*  Parms:
*		NONE
*
*  <!-- Fixed for defect# 6001 -->
**************************************************************************************************/  
function expiryDate()
{
   
  		var cardBrandVal = document.OrderSummaryForm.cardBrand.value ;
		if (cardBrandVal != null && cardBrandVal != "" ){
  			if(cardBrandVal == "HDCON" || cardBrandVal == "HDCOM"){
			document.OrderSummaryForm.cardExpiryYear.disabled = true;
    		document.OrderSummaryForm.cardExpiryMonth.disabled = true;
			}else {
		 	document.OrderSummaryForm.cardExpiryYear.disabled = false;
	    	document.OrderSummaryForm.cardExpiryMonth.disabled = false;
	   		}
		}	
} // expiryDate




	
/*************************************************************************************************
*  Function:  giftCardBalanceInquiry
*		Invoked on the gift card page to check the balance of a giftcard.  This will make an 
*		ajax call to get the giftcard balance
*
*  Parms:
*		NONE
**************************************************************************************************/  
function giftCardBalanceInquiry(obj)
{
	if (debugVal == 'true')
	{
		alert ('ENTERING Function: giftCardBalanceInquiry('+ obj + ')' );
	}
	formName = GIFT_CARD_BALANCE_FORM_NAME;
	var storeId = document.forms[formName].storeId.value;
	var storeIdParam = document.forms[formName].storeId.name;
	var giftCardNbr = document.forms[formName].giftCardNumber.value;
	var giftCardNbrParam = document.forms[formName].giftCardNumber.name;
	var pinNbr = document.forms[formName].pinNumber.value;
	var pinNbrParam = document.forms[formName].pinNumber.name;
	var captchaTxt = document.forms[formName].captchaVerification.value;
	var captchaTxtParam = document.forms[formName].captchaVerification.name;
	
	
	// Clear out the previous balance inquiry results
	document.getElementById('gift-card-details').innerHTML = '';
	
	//Clear out any omniture message that may have been stored
	omnitureMsg = '';
	
	// obj is the "this" object that is passed in from the onClick event.  The omnitureLinkTrackingObject is interrogated in the 
	// callOmniture function.  It is made a global variable to circumvent passing this variable to multiple functions and because this the entry point
	// to checking gift card balances. 
	omnitureLinkTrackingObject = obj; 
	
	
	var errorMsg = null;
	errorMsg = validateGiftCardFields(giftCardNbr, pinNbr, captchaTxt);
	
	if( errorMsg == null || errorMsg.length <= 0)	
	{

		// Show the please wait image
		document.getElementById('gc-entry-please-wait').innerHTML = '<img src="/wcsstore/hdus/en_US/images/pleasewait_3a.gif" width="335" height="65" />';
		document.getElementById('gc-entry-please-wait').style.display = 'block';
		
		// Hide the gift card entry section and button
		document.getElementById('gc-entry-container').style.display = 'NONE';
		document.getElementById('if-you-still-cant-read-image-text').style.display = 'NONE';		
		document.getElementById('gc-entry-button').style.display = 'NONE';
		
		// Made the ajax call - build the name value pairs for the request
		var url = '/webapp/wcs/stores/servlet/GiftCardBalanceInquiry?'+storeIdParam+'='+storeId+'&'+giftCardNbrParam+'='+giftCardNbr+'&'+pinNbrParam+'='+pinNbr+'&'+captchaTxtParam+'='+captchaTxt+'&nextView=GiftCardBalInqView';
		makeHttpRequest(url, 'giftCardBalanceInquiryCallBack');

	}
	else
	{
		// Show the gift card error message
		document.getElementById('gift-card-errors').innerHTML = errorMsg;
		adjustCaptchaUI(KEEP_GIFT_CARD);
		changeCaptcha();  // change the captcha image 
		callOmniture(OMNITURE_USER_ERR_VAL);  //client side validation failed, call omniture passing a user error message		
	}
	
	if (debugVal == 'true')
	{
		alert ('EXITING Function: giftCardBalanceInquiry('+ obj + ')' );
	}
}  // end giftCardBalanceInquiry





/*************************************************************************************************
*  Function:  applyGiftCardCallBack
*		Gets called after a successful return from ajax call to retrieve gift card balance
*		off of the gift card page
*
*  Parms:
*		text - the html that is being rendered back from the ajax call
**************************************************************************************************/ 
function giftCardBalanceInquiryCallBack(text)
{
	if (debugVal == 'true')
	{
		alert ('ENTERING Function: giftCardBalanceInquiryCallBack('+ text + ')' );
	}

	// Hide the please wait image
	document.getElementById('gc-entry-please-wait').innerHTML = '';
	
		
	// Replace the appropriate content
	document.getElementById('gc-entry-container').innerHTML = text;

	adjustGCError('giftCardBalanceInquiryCallBack');
 
	// set the GC container back to visible
	document.getElementById('gc-entry-container').style.display = 'block';
	document.getElementById('if-you-still-cant-read-image-text').style.display = 'block';		
	document.getElementById('gc-entry-button').style.display = 'block';

//"omnitureMsg" is set in validateGiftCardFields() it can be set to space if there are no errors.  This is intentional
//because HD wants to also track successful balance checks.
	callOmniture(omnitureMsg);  
	
	if (debugVal == 'true')
	{
		alert ('EXITING Function: giftCardBalanceInquiryCallBack(text)' );
	}	
}  // end function giftCardBalanceInquiryCallBack




/*************************************************************************************************
*  Function:  applyGiftCard
*		Invoked on the checkout page to apply gift card(s) as payment to the order.  This will make an 
*		ajax call to get the giftcard balance
*
*  Parms:
*		obj -- the "this" object being passed in from the onclick event in HTML
**************************************************************************************************/
function applyGiftCard(obj)
{
	if (debugVal == 'true')
	{
		alert ('ENTERING Function: applyGiftCard()' );
	}
    formName = CHECKOUT_FORM_NAME;
	var storeId = document.forms[formName].storeId.value;
	var storeIdParam = document.forms[formName].storeId.name;
	var giftCardNbr = document.forms[formName].giftCardNumber.value;
	var giftCardNbrParam = document.forms[formName].giftCardNumber.name;
	var pinNbr = document.forms[formName].pinNumber.value;
	var pinNbrParam = document.forms[formName].pinNumber.name;
	var captchaTxt = document.forms[formName].captchaVerification.value;
	var captchaTxtParam = document.forms[formName].captchaVerification.name;
	var lastRemNumber = document.forms[formName].lastRemNumber.value;
	var lastRemNumberParam = document.forms[formName].lastRemNumber.name;	
	var lastRemAmount = document.forms[formName].lastRemAmount.value;
	var lastRemAmountParam = document.forms[formName].lastRemAmount.name;
	 

	// Clear out the previous error messages and hidden fields.	
	document.getElementById('gift-card-errors').innerHTML = '';

	
	//Clear out any omniture message that may have been stored
	omnitureMsg = '';  
	
	// obj is the "this" object that is passed in from the onClick event.  The omnitureLinkTrackingObject is interrogated in thc 
	// callOmniture function.  It is made a global variable to circumvent passing this variable to multiple functions and because this the entry point
	// to applying gift cards. 
	omnitureLinkTrackingObject = obj; 

	
	var errorMsg = null;
	errorMsg = validateGiftCardFields(giftCardNbr, pinNbr, captchaTxt);
	if( errorMsg == null || errorMsg.length <= 0 )	// NO ERRORS
	{
	
		// Hide the gift card entry section and button
		document.getElementById('gc-entry-container').style.display = 'NONE';
		document.getElementById('if-you-still-cant-read-image-text').style.display = 'NONE';		
		document.getElementById('gc-entry-button').style.display = 'NONE';
	
		// Show the please wait image		
		document.getElementById('gc-entry-please-wait').innerHTML = '<img src="/wcsstore/hdus/en_US/images/pleasewait_3a.gif" width="335" height="65" />';
		focuOn = 'lastRowInCCSection';
		document.getElementById('gc-entry-please-wait').style.display = 'block';
		

		// Set up parameters and values for the AJAX call
	    var appliedGiftCardsArray = document.getElementsByName('appliedGiftCardAmounts');	    
		var lengthOfAppliedGiftCardsArray = appliedGiftCardsArray.length;	
		var appliedGiftCardRemainder = 'appliedGiftCardRemainder';
		if ( lengthOfAppliedGiftCardsArray > 0)
		{	
			var appliedGiftCardNbrs = 'appliedGiftCardNbrs';
			var appliedGiftCardAmounts = 'appliedGiftCardAmounts';
			var availableGiftCardAmounts = 'availableGiftCardAmounts';
			
			var encryptedGiftCardNbrs = 'encryptedGiftCardNbrs';	
			var appliedGiftCardReserves = 'giftCardReserves';
			var appliedGCNbrsArray = document.getElementsByName('appliedGiftCardNbrs');	
			var appliedGCAmtsArray = document.getElementsByName('appliedGiftCardAmounts');							
			var availableGCAmtsArray = document.getElementsByName('availableGiftCardAmounts');							
			var appliedGCEncryptedArray = document.getElementsByName('encryptedGiftCardNbrs');
			var appliedGiftCardReservesArray = document.getElementsByName('giftCardReserves');						
		}

		// Build parms for gift cards that have alredy been applied:
		var appliedGiftCardsNbrParmVals = '';
		var appliedGiftCardsAmtParmVals = '';
		var availableGiftCardsAmtParmVals = '';
		var lastRemAmountParmVal = '';
		var appliedGiftCardsEncryptedParmVals = '';
		var appliedGiftCardsReservesParmVals = '';
		
		// if we have applied gift cards, loop thru the applied gift cards table and set up the URL parms.
		for(var i=0;i<lengthOfAppliedGiftCardsArray;i++)
		{   
			appliedGiftCardsNbrParmVals = appliedGiftCardsNbrParmVals + '&' + appliedGiftCardNbrs + "=" + appliedGCNbrsArray[i].value;
			appliedGiftCardsAmtParmVals = appliedGiftCardsAmtParmVals + '&' + appliedGiftCardAmounts + "=" + appliedGCAmtsArray[i].value;
			availableGiftCardsAmtParmVals = availableGiftCardsAmtParmVals + '&' + availableGiftCardAmounts + "=" + availableGCAmtsArray[i].value;			
			appliedGiftCardsEncryptedParmVals = appliedGiftCardsEncryptedParmVals + '&' + encryptedGiftCardNbrs + "=" + appliedGCEncryptedArray[i].value;
			appliedGiftCardsReservesParmVals = appliedGiftCardsReservesParmVals + '&' + appliedGiftCardReserves + "=" + appliedGiftCardReservesArray[i].value;
		}
			
//		// Made the ajax call - build the name value pairs for the request
		var url = '/webapp/wcs/stores/servlet/GiftCardBalanceInquiry?'+storeIdParam+'='+storeId+'&'
																	  +giftCardNbrParam+'='+giftCardNbr
																	  +'&'+pinNbrParam+'='+pinNbr+'&'
																	  +captchaTxtParam+'='+captchaTxt
																	  +appliedGiftCardsNbrParmVals
																	  +appliedGiftCardsAmtParmVals
																	  +availableGiftCardsAmtParmVals
																	  +appliedGiftCardsEncryptedParmVals
																	  +appliedGiftCardsReservesParmVals
																	  +'&'+lastRemNumberParam+'='+lastRemNumber
  																	  +'&'+lastRemAmountParam+'='+lastRemAmount
																	  +'&nextView=AppliedGiftCardsView';																	  
 																  
		makeHttpRequest(url, 'applyGiftCardCallBack');		
		

		if (debugVal == 'true')
		{
			alert ('Function: applyGiftCard(): ' + '\n'+ 'url[' + url + ']');
		}		
		
	}
	else  //there are errors
	{
		// Show the gift card error message
		document.getElementById('gift-card-errors').innerHTML = errorMsg;
		adjustCaptchaUI(KEEP_GIFT_CARD);
		changeCaptcha();  // change the captcha image 
		document.getElementById('gc-entry-button').style.display = 'BLOCK';
		document.getElementById('if-you-still-cant-read-image-text').style.display = 'BLOCK';		
		document.getElementById('gc-entry-container').style.display = 'BLOCK';
		callOmniture(OMNITURE_USER_ERR_VAL);  //client side validation failed, call omniture passing a user error message
	}
	

	
	if (debugVal == 'true')
	{
		alert ('EXITING Function: applyGiftCard()'  );
	}
	
}  // end function applyGiftCard





/*************************************************************************************************
*  Function:  applyGiftCardCallBack
*		Gets called after a successful return from ajax call to retrieve gift card balance
*		when the user presses the "apply gift card" button off of the checkout screen
*
*  Parms:
*		text - the html that is being rendered back from the ajax call
**************************************************************************************************/ 
function applyGiftCardCallBack(text)
{
   
	if (debugVal == 'true')
	{
		alert ('ENTERING Function: applyGiftCardCallBack(text)'  );
		//  For Debug
	    alert ("applyGiftCardCallBack(text) [" + text + "]");		
	}


	// Hide the please wait image
	document.getElementById('gc-entry-please-wait').innerHTML = '';

	document.getElementById('applied-gift-card-section').innerHTML = text;
 	calculateGiftCardTotal();
 	adjustCheckoutUI('applyGiftCardCallBack');
 	
 	changeCaptcha(); 
 		
	 if (isGiftCardTenderActiveValue == "true" )  //Gift Card Tender is active
	 {
	 	// Replace the appropriate content
		document.getElementById('gc-entry-button').style.display = 'block';
		document.getElementById('if-you-still-cant-read-image-text').style.display = 'block';		
		document.getElementById('gc-entry-container').style.display='block';
		
		// we need to check to see if we need to focus on the top of the applied GC table.
		if  (focusOnAppliedTable == 'true')  
		{
			focusOnAnchor('topOfAppliedGiftCardTable');			
		}
		
		
		// Now check if we need to focus on anything else.		
		if (null != focusOn && focusOn.length > 0)
		{
			focusOnAnchor(focusOn);
		}		
	 }
	 else  // Gift Card Tender is not active
	 {	
	  document.getElementById('gc-entry-button').style.display = 'NONE';
      document.getElementById('if-you-still-cant-read-image-text').style.display = 'NONE';		
	  document.getElementById('gc-entry-container').style.display='NONE';  // gc-entry-container is the parent container.
	 } 

 	//"omnitureMsg" is set in validateGiftCardFields() and adjustCheckout() it can be set to space if there are no errors.  This is intentional
	//because HD wants to also track successful balance checks.
	callOmniture(omnitureMsg); 
	
	if (debugVal == 'true')
	{
		alert ('EXITING Function: applyGiftCardCallBack(text)'  );
	}
} // end applyGiftCardCallBack




/*************************************************************************************************
*  Function:  checkForGCBalanceError
*		This function checks to see if a particular erorr message exists when coming back from the server.
*		This error means that the Gift + Credit Card totals do not match the Grand total on the server.  This
*       is considered a severe error and we need to clear out all of the applied GC's and force the user start over. 
*
*  Parms:
**************************************************************************************************/  

function  checkForGCBalanceError()
{
	if (debugVal == 'true')
	{
		alert ('ENTERING Function: checkForGCBalanceError() '  );
	}


	var gcBalanceErrorMsgVal = gcBalanceErrorMsg;
 	var customErrorMessageVal = '';

 	
 	//had to put it inside of a try catch block because sometimes the customErrorMessage is unavailable. 
	try
	{
		var customErrorMessage = document.getElementById('custom-error-message');
		if ( customErrorMessage == null)
		{
		  		customErrorMessageVal = '';
		}
		else
		{
	  		customErrorMessageVal = customErrorMessage.innerHTML;
		}
				

  	}  // end Try
  	catch(err) 
  	{
  		customErrorMessageVal = '';
  	} // end Catch
 	

	// check to see if the sever error message is the GC Balance error message. if so, clear out the necessary fields.
 	if (gcBalanceErrorMsgVal == customErrorMessageVal) 
 	{
		var	appliedGiftCardArray = document.getElementsByName('appliedGiftCardNbrs');

		var tblLength = appliedGiftCardArray.length;
		var outsideCounter = 1;
		// loop thru the applied gift cards table table and delete each row.
		for(var i=0;i<tblLength;i++)
		{	
			if ( outsideCounter < tblLength) // not on last row.  call the delete function and do not adjust totals or UI yet.
			{
 				deleteAppliedGiftCardRow(document.getElementById('appliedGiftCardTable').rows[0],'N');
			}
			else  // on the last row, delete the last row and adjust totals and UI.
 			{
				deleteAppliedGiftCardRow(document.getElementById('appliedGiftCardTable').rows[0],'Y');				
			}
			
			outsideCounter++;

		} // end for		 
		
	  	adjustCaptchaUI(CLEAR_ALL);	  // If the user inputted GC#, PIN or CAPTCHA -- clear it

 	}
 	
 	if (debugVal == 'true')
	{
		alert ('EXITING Function: checkForGCBalanceError()'  );
	}
 }





/*************************************************************************************************
*  Function:  validateGiftCardFields
*		Business validation around gift card fields (GC#, GC Pin#, captcha Text) 
*
*  Parms:
*		giftCardNbr	-	the gift card number that the user is trying to apply
*		pinNbr		-	the pin number of the gift card number that the user is trying to apply
*		captchaTxt	-	the text that the user has entered for what they think the captcha image says
**************************************************************************************************/  
function  validateGiftCardFields(giftCardNbr, pinNbr, captchaTxt)
{
	if (debugVal == 'true')
	{
		alert ('ENTERING Function: validateGiftCardFields(giftCardNbr, pinNbr, captchaTxt)' + giftCardNbr + ',' + pinNbr + ','  + captchaTxt );
	}


 // return null;

  var errorMsg = null;
  var duplicateGCMsgVal = '';	
  var userErrorMsgVal = '<span class="error" > ' + gcUserErrorMsg + '</span>';  
  var nonUSGiftCardErrorMsgVal = '<span class="error" > ' + nonUSGiftCardErrorMsg + '</span>';

  if ( duplicateGCErrorMsg != null)
  {
	  duplicateGCMsgVal = '<span class="error" >' + duplicateGCErrorMsg + '</span>';
  }
  
  
  	// Check that the gift card number is 23 digits
	if( isGiftCardValid(giftCardNbr) )
	{
		// check the pin nbr is 4 digits
		if( isPinNbrValid(pinNbr) )
		{
			// check the captcha is 7 alpha numeric
			if( isCaptchaValid(captchaTxt) )
			{
				if ( isUSGiftCard(giftCardNbr) )
				{
				    var isDuplicateFound = isDuplicateGiftCard(giftCardNbr)
					if ( !isDuplicateGiftCard(giftCardNbr) )
					{
						// validation OK
					}
					else
					{
						// Show the gift card error message
						errorMsg = duplicateGCMsgVal;
					}
				}
				else  // else for isUSGiftCard(giftCardNbr)
				{
					// Show the gift card error message
					errorMsg = nonUSGiftCardErrorMsgVal;
				}
			}  
			else // else for isCaptchaValid(captchaTxt)
			{
				// Show captcha error
				errorMsg = userErrorMsgVal;
			}
		}
		else // else for isPinNbrValid(pinNbr)
		{
			// Show the pin error message
			errorMsg = userErrorMsgVal;

		}
	}
	else  // else for isGiftCardValid(giftCardNbr)
	{
		// Show the gift card error message
		errorMsg = userErrorMsgVal;
	}
	
	if (debugVal == 'true')
	{
		alert ('EXITING Function: validateGiftCardFields(giftCardNbr, pinNbr, captchaTxt)' + giftCardNbr + ',' + pinNbr + ','  + captchaTxt   );
	}
  

  return errorMsg
  
}  // end function validateGiftCardFields





/*************************************************************************************************
*  Function:  isGiftCardValid
*		Quick validation of gift card is US (5th digit = 1). 
*
*  Parms:
*		giftCardNbr	-	the gift card number that the user is trying to apply
**************************************************************************************************/ 
function isGiftCardValid(giftCardNbr)
{
	var REG_EXP = /^\d{23}$/;
	return giftCardNbr.match(REG_EXP);
}  // end function isGiftCardValid

 




/*************************************************************************************************
*  Function:  isUSGiftCard
*		Quick validation of gift card format. 
*
*  Parms:
*		giftCardNbr	-	the gift card number that the user is trying to apply
**************************************************************************************************/
function isUSGiftCard(giftCardNbr)
{
	return ('1' == giftCardNbr.charAt(4));
}  // end function isUSGiftCard




/*************************************************************************************************
*  Function:  isDuplicateGiftCard
*		Quick validation to see if the user already applied the giftcard gift card. 
*
*  Parms:
*		giftCardNbr	-	the gift card number that the user is trying to apply
**************************************************************************************************/ 
function isDuplicateGiftCard(giftCardNbr)
{
//	var appliedGiftCardNbrsArray = document.forms[formName].appliedGiftCardNbrs;
	var appliedGiftCardNbrsArray = document.getElementsByName('appliedGiftCardNbrs');
	var duplicateFound = 'N';

	for(var i=0;i<appliedGiftCardNbrsArray.length;i++)
	{	
		if (giftCardNbr == appliedGiftCardNbrsArray[i].value)				
		{
			duplicateFound = 'Y';
			break;
		}
	}
	return ( 'Y' == duplicateFound );

	
}  // end function isDuplicateGiftCard




/*************************************************************************************************
*  Function:  isPinNbrValid
*		Quick validation of pin number format. 	
*
*  Parms:
*		pinNbr	-	the pin number of the gift card that the user is trying to apply
**************************************************************************************************/
function isPinNbrValid(pinNbr)
{
	var REG_EXP = /^\d{4}$/;
	return pinNbr.match(REG_EXP);
}  // end function isPinNbrValid





/*************************************************************************************************
*  Function: isCaptchaValid 
*		Quick validation of captcha image text
*
*  Parms:
*		captcha	- the text that the user has entered  -- what they think the captcha image says
**************************************************************************************************/
function isCaptchaValid(captcha)
{
	var REG_EXP = /^[A-Za-z0-9]{7}$/;
	return captcha.match(REG_EXP);
}  // end function isCaptchaValid






/*************************************************************************************************
*  Function:  deleteAppliedGiftCardRow
*		User clicked the "Remove gift card" button on the checkout page.
*  		Delete the giftcard from the table and recaluclate the totals.
*
*  Parms:
*		r	- represents the row on the applied gift cards table that they user wants to delete
*		calAndadjustUIAfterDelete	- a flag that tells this function if whether it should adjust the 
*    								  totals and UI.   
										Y = Adjust everything after you delete the row
										Anything else = Do not adjust anything after the deletion

**************************************************************************************************/
function deleteAppliedGiftCardRow(r, calAndadjustUIAfterDelete)
{
	if (debugVal == 'true')
	{
		alert ('ENTERING Function: deleteAppliedGiftCardRow(r, calAndadjustUIAfterDelete ' + r + "," + calAndadjustUIAfterDelete);
	}
	
	// had to set the display to none while deleting to correct IE shifting some of the fields up (but not all)
	// at the end of this function, display is set back to block.
	document.getElementById('gc-entry-container').style.display='none';


	
	var i=r.parentNode.parentNode.rowIndex;
	document.getElementById('appliedGiftCardTable').deleteRow(i);
	
	if ('Y' == calAndadjustUIAfterDelete.toUpperCase() ) // Y is the only value that will recalculate and readjust
	{
		document.forms[formName].gcErrorMsgs.value = '';
		document.getElementById('gift-card-errors').innerHTML ='';
		calculateGiftCardTotal();		
		adjustCheckoutUI('deleteAppliedGiftCardRow');
		
	}
	
	document.getElementById('gc-entry-container').style.display='block';
	
	if (debugVal == 'true')
	{
		alert ('EXITING Function: deleteAppliedGiftCardRow(r, calAndadjustUIAfterDelete ' + r + "," + calAndadjustUIAfterDelete);
	}
	
}  // end function deleteAppliedGiftCardRow




/*************************************************************************************************
*  Function:  changeGiftCardVisibility
*		Determine if the gift card section is visible or not and whether is visibility should be changed
*		This gets called when the user tries to expand or collapse the gift card section
*
*  Parms:
*		NONE
**************************************************************************************************/
function changeGiftCardVisibility()
{
	if (debugVal == 'true')
	{
		alert ('ENTERING Function: changeGiftCardVisibility() '  );
	}

	var section = document.getElementById("giftCardSection");  
	var image = document.getElementById("gc_show_hide_img");  
	var gcAppliedTotalArray = document.getElementsByName('appliedGiftCardAmounts');

	if (gcAppliedTotalArray.length > 0)   // Business rule: if there are "Applied" gift cards, do not allow the user to collapse the section.
	{
		image.style.display = 'NONE'; 
		isGiftCardSectionCurrentlyVisible = true;       	
	}
	else 
	{  
		if ( isGiftCardSectionCurrentlyVisible )  // giftcard section is visible...collapse the section and setup button so that user can expand it.
		{
			section.style.display = 'NONE';  	
			image.src = PLUS_IMG_VAL;        
			isGiftCardSectionCurrentlyVisible = false;        	  	  
		}
		else // giftcard section is NOT visible...show the section and setup button so that user can collapse it.
		{	section.style.display = 'block'; 
			image.src = MINUS_IMG_VAL;
			isGiftCardSectionCurrentlyVisible = true;
		}
	}
	
	
	if (debugVal == 'true')
	{
		alert ('EXITING Function: changeGiftCardVisibility()'  );
	}	
	
}  // end function changeGiftCardVisibility






/*************************************************************************************************
*  Function:  calculateGiftCardTotal
*		Calculate the total applied by the giftcards and adjust the totals on the "Merchandise SubTotal"
*  		accordingly section of the checkup page
*
*  Parms:
*		NONE
**************************************************************************************************/
function calculateGiftCardTotal()
{ 

	if (debugVal == 'true')
	{
		alert ('ENTERING Function: calculateGiftCardTotal()'  );
	}

	var gcAppliedTotalArray;
	var gcAvailableTotalArray;
	var gcNbrsArray;
	var lengthOfAppliedTotalArray; 
	var lengthOfAvailableTotalArray; 
	var appliedGCTotal;
	var availableGCTotal;
	var lastEnteredAvaiableAmt;  //what the available amount of the last card entered is
	var lastEnteredAppliedAmt;   //what we will eventually set the applied amount of the last card entered to
	var grandTotal; 
	var gcTotal = 0;
	var ccTotal = 0;
	var lastRemAmount = 0;	

	gcNbrsArray = document.getElementsByName('appliedGiftCardNbrs');	  
	gcAppliedTotalArray = document.getElementsByName('appliedGiftCardAmounts');
	lengthOfAppliedTotalArray = gcAppliedTotalArray.length;
	gcAvailableTotalArray = document.getElementsByName('availableGiftCardAmounts');
	lengthOfAvailableTotalArray = gcAvailableTotalArray.length;
	
	lastEnteredAvaiableAmt = 0;
	lastEnteredAppliedAmt = 0;	
	var grandTotalInnerHTML = document.getElementById('grandTotal').innerHTML;
	grandTotal = checkNumber(grandTotalInnerHTML);
	gcTotal = 0;
	ccTotal = 0;
	lastRemAmount = 0;	


// loop thru the avaiable amounts on the GC's and build a total. 
	availableGCTotal = 0;   
	for(var i=0;i<lengthOfAvailableTotalArray;i++)
	{	
		if (i == 0)  // on the last GC entered by the user (first row on the table)
		{
		  lastEnteredAvaiableAmt = gcAvailableTotalArray[i].value ;
		}
		var totalOnCurrentGiftCard = checkNumber(gcAvailableTotalArray[i].value);
		availableGCTotal = availableGCTotal + totalOnCurrentGiftCard;
		
	} // end for
	
		
	//figure out what the Gift Card and Credit Card totals are.	
	if ( grandTotal > availableGCTotal ) 
	{	
		gcTotal = availableGCTotal;
		ccTotal = grandTotal - availableGCTotal;
		lastEnteredAppliedAmt = lastEnteredAvaiableAmt;	

	}
	else if ( grandTotal < availableGCTotal )
	{ 
	    // the Grand total is less than all of the Applied GC's.  Only apply what is needed from the last GC that the user has entered
	    // (first GC on the "appliedGiftCardTable"). We also have to change the hidden amount for the GC.

		gcTotal = grandTotal;
		ccTotal = 0;
		lastRemAmount = availableGCTotal - grandTotal;
		lastEnteredAppliedAmt = lastEnteredAvaiableAmt - lastRemAmount;
	
	}
	else  // grandTotal = appliedGCTotal
	{ 
		gcTotal = availableGCTotal;
		ccTotal = 0;
		lastEnteredAppliedAmt = lastEnteredAvaiableAmt
	}
	

	
	//Now that you know what the Gift Card and Credit Card totals are, set the visibile fields ("To Be Paid with..." lines).
	//NOTE: we are looping thru the array because the business wanted the subtotals in 2 different places on the page so we have
	//      to update the DISPLAYED totals in 2 places.
	
	// update To Be Paid with Gift Card(s) lines
//	var displayGiftCardTotalArray = getElementsById('giftCardTotal','Y');
	var displayGiftCardTotalArray = getElementsById('giftCardTotal','Y');
	var displayGCTotal = CurrencyFormatted(gcTotal,'$',',');
	for(var i=0;i<displayGiftCardTotalArray.length;i++)
	{	
		displayGiftCardTotalArray[i].innerHTML = displayGCTotal;	
	}  //end for loop
	
	// update To Be Paid with Credit Card lines	

	var displaycreditCardTotalArray = getElementsById('creditCardTotal','Y');
	var displayCCTotal = CurrencyFormatted(ccTotal,'$',',');
	for(var i=0;i<displaycreditCardTotalArray.length;i++)
	{
		displaycreditCardTotalArray[i].innerHTML = displayCCTotal;		
	}  //end for loop

	
	// set all of the hidden fields
	
	document.forms[formName].totalGC.value = CurrencyFormatted(gcTotal,'','');
	document.forms[formName].totalCC.value = CurrencyFormatted(ccTotal,'','');	
	document.forms[formName].totalOrder.value = CurrencyFormatted(grandTotal,'','');		
	document.forms[formName].lastRemAmount.value = CurrencyFormatted(lastRemAmount,'','');	


	//set the last entered GC to what actually got applied.
	if (lengthOfAvailableTotalArray > 0)
	{	
		gcAppliedTotalArray[0].value = CurrencyFormatted(lastEnteredAppliedAmt,'',''); 
		document.getElementById('giftCardAppliedAmount').innerHTML = CurrencyFormatted(lastEnteredAppliedAmt,'$',',');// first GC on the shown table is the last GC the user entered
	}

	// if there is a remainder, set the GC number that has the remainder (the last one entered)
	if  (lastRemAmount > 0)  
	{
		document.forms[formName].lastRemNumber.value = gcNbrsArray[0].value;
	}
	else  // no remainder ..set the lastRemNumber to space
	{
		document.forms[formName].lastRemNumber.value = '';

		
	}

	
	if (debugVal == 'true')
	{
		alert ('EXITING Function: calculateGiftCardTotal()'  );
	}
	

}  // end function calculateGiftCardTotal








/*************************************************************************************************
*  Function:  adjustCheckoutUI
*		This function will be called whenever we need to adjust the screen based off of user actions
*  		(adding/deleting Gift cards for instance or trying to submit an order and there is an error is antother instance).  
*		It will apply all of the necessary business rules  as dictated by our users.
*
*  Parms:
*		callingMethod	-  	Anyone who calls this function must provide its name.  This is necessary
*  							because we need to know when the call is from onLoad vs Ajax.
**************************************************************************************************/
function adjustCheckoutUI(callingMethod)
{ 


	if (debugVal == 'true')
	{
		alert ('ENTERING Function: adjustCheckoutUI(callingMethod) ' +   callingMethod);
	}



  // the "callingMethod" variable is used to determine whether this method was called from the onLoad 
  // function or not.	
	
  	var DELETE_GC_VAL = 'deleteAppliedGiftCardRow';
	var labelArray = document.getElementsByTagName('label');
	var maxGCsAllowed = document.forms[formName].maxGCsAllowed.value;
	var nbrOfGCsToShowInTable = document.forms[formName].nbrOfGCsToShowInTable.value;
	var totalGC = document.forms[formName].totalGC.value;
	var totalCC = document.forms[formName].totalCC.value;	
	var gcAppliedTotalArray = document.getElementsByName('appliedGiftCardAmounts');
	var gcErrMsg = null;
	var gcErrMsgVal = '';
	var isCCSectionCollapsed = 'false';		
	var appliedGiftCardTable = document.getElementById('applied-gift-card-section'); 

	isGiftCardTenderActiveValue = document.forms[formName].isGiftCardTenderActive.value; 
 



// ===========================================================================================
// Gift Card error Section
// ===========================================================================================
	adjustGCError(callingMethod)
	gcErrMsg = document.forms[formName].gcErrorMsgs;
	if (gcErrMsg != null)
	{
		gcErrMsgVal = gcErrMsg.value;  // gcErrMsgVal is used in multiple places in this function.
	}	
	
	

// ===========================================================================================
// Credit Card Section
// ===========================================================================================
/* 
*  Set Credit Card visibility based on if there is a total needed for CC (totalCC NE 0)
*  When the Credit Card section is collapsed, we must clear out any inputted fields.
*  The user will have to re-input the CC info if CC section gets expanded again
*/	
  if (totalCC > 0) //there is a CC total .. we must have the CC section open.
  {
  	document.getElementById('credit-card-section').style.display='block'; 
  }  // end  if (totalCC > 0)  
  else //CC total == 0 .. we must have the CC section closed and values emptied.
  {	
	isCCSectionCollapsed = 'true';       
    document.getElementById('credit-card-section').style.display='NONE';  //hide the CC section (CC total == 0)

// set focus on Gift card section (since we are collapsing, the GC section move up and we want the users to see the GC section
	focusOn = 'topOfGiftCardSection';


	// If this method is called from the onload section, it means that the user did an action that caused a server refresh (like try to check out), 
	// If it's a server refresh, not not an AJAX call (like Apply or Delete GC's). 
	if (callingMethod != ONLOAD_VAL)  
	// call came from AJAX.  
	//      Clear the contents of only the CC fields, 
	//      Clear the error message and hide it.
	//      Set ALL fields in error back to normal (not only CC fields).
	{

 	  	// empty out any CC section values that the user may have entered	  		  	
	  	document.forms[formName].cardHolderName.value='';
	  	document.forms[formName].cardBrand.selectedIndex=0;
	  	document.forms[formName].cardNumberDisplayValue.value='';
	  	document.forms[formName].cardNumberOriginalDisplayValue.value='';
	  	document.forms[formName].cardNumber.value='';
	  	document.forms[formName].notifyOrderSubmitted.value='';
	  	document.forms[formName].cardExpiryMonth.selectedIndex=0;
	  	document.forms[formName].cardExpiryYear.selectedIndex=0;
	  	document.forms[formName].cardVerificationCode.value='';
	  	document.forms[formName].poNumber.value='';
	  	
	  	//clear and hide the error message
	  	//had to put it inside of a try catch block because sometimes the customErrorMessage is unavailable. If it is unavailable, it's ok
	  	//becuase it's not there so we don't have to clear anything out.
  		var customErrorMessage = document.getElementById('custom-error-message');
	  	try
	  	{
	  		if ( customErrorMessage != null)
	  		{
	  			customErrorMessage.innerHTML = '';	
				customErrorMessage.style.display='NONE';	  		  		 		
	  		}
	  		
	  	}
	  	catch(err) 
	  	{
	  	}
	  					
		// loop thru all of the labels on the the screen remove any "error" class name associated with them.
		// by removing the class name on the label, the label will revert to it's normal "non error" class on the TD.	
		var labelArray = document.getElementsByTagName('label');
	  	for(var i=0;i<labelArray.length;i++)
		{
			if ( labelArray[i].className == 'error' )
			{
				labelArray[i].className = '';					
			}
		}  // end for
		
	}  // end if (callingMethod != ONLOAD_VAL) 
	else // calling method was ONLOAD_VAL...clear out GC error message
	{
		gcErrMsgVal = null;
	}

  }  //end else (CC total == 0)
  

 
// ===========================================================================================
// Gift Card Section
// ===========================================================================================
 
  //set the height of the applied gift card section  (The table of applied gift cards)

	  focusOnAppliedTable = 'false';  
  
	  if (gcAppliedTotalArray.length <= 0) 
	  {
	  	appliedGiftCardTable.style.height='1px'; 
	  	appliedGiftCardTable.overflow='NONE'; 	
 
	  }
	  else if (gcAppliedTotalArray.length <= nbrOfGCsToShowInTable)
	  {
	   	var rowHeight = (gcAppliedTotalArray.length * 43) + 'px';  
	 	appliedGiftCardTable.style.height=rowHeight;  
	  	appliedGiftCardTable.overflow='NONE'; 	 		

	  } 
	  else  // more than number we want to show -- set the div to correct px's
	  {
	  	var rowHeight = (nbrOfGCsToShowInTable * 43) + 'px';  
	 	appliedGiftCardTable.style.height=rowHeight;  
	 	appliedGiftCardTable.overflow='scroll'; 	

	 	if ( isCCSectionCollapsed != 'true' ) // If the Credit card section is collapsed...don't override the current focus
	 	{	
	 		if (callingMethod != ONLOAD_VAL) // if the calling method is from the ONLOAD // this anchor is hidden and we can't set focus
	 		{ 		 	
				focusOnAppliedTable = 'true';
			}		 		
		}  //end if ( isCCSectionCollapsed != 'true' )
	 } // end else ( more than number we want to show )
	
	//Figure out if the user is allowed to collapse the GC section 
	//(rule is that if we have at least one GC that has been applied, user cannot collapse the section)
 
  	if (gcAppliedTotalArray.length > 0)  // we have at least 1 applied gift card
	  { 
	  	// document.getElementById('gc_show_hide_img').style.display='NONE';  	//remove the button from the header if there are applied gift cards
	  	document.getElementById('giftCardSection').style.display='block';  	//the gift card section should be visible
	  	isGiftCardSectionCurrentlyVisible = true;
		focusOn = 'topOfGiftCardSection';       
	  }
	  else  // no GC's applied, now check to see if there is a GC error.  If there is, we need to make GC section visible so that the user sees the error
	  {
	  	if (gcErrMsgVal != null && gcErrMsgVal.length > 0 )  // No applied GC's but there is a GC error, gc section shoud NOT be hidden.
	  	{ 
	  	  // document.getElementById('gc_show_hide_img').src = MINUS_IMG_VAL;  // set the minus image
	  	  // document.getElementById('gc_show_hide_img').style.display='inline'; 
	      document.getElementById('giftCardSection').style.display='block';  
	      isGiftCardSectionCurrentlyVisible = true; 	
	  	}
	  	else  // no applied gift cards and no errors, check to see if we have no applied GC becuase the user deleted the last one (we still want GC section to be visible in this condition)
	  	{
	  		if ( callingMethod == DELETE_GC_VAL)  // no GC's becuase the user deleted the last one -- GC section should be visible.
	  		{
	  	  	  // document.getElementById('gc_show_hide_img').src = MINUS_IMG_VAL;  // set the minus image		
		  	  // document.getElementById('gc_show_hide_img').style.display='inline'; 
		      document.getElementById('giftCardSection').style.display='block';  
      	      isGiftCardSectionCurrentlyVisible = true; 	
	  		}
	  		else // no GC's , no Errors.  Now figure out if the user has inputted any data
	  		{
	  			var gcNbrInput   				= document.forms[formName].giftCardNumber.value;

				// no GC's , no Errors but user has inputted some GC data -- GC section should be visible	
	  			if ( gcNbrInput != null && gcNbrInput.length > 0  )  
	  			{
  				    // document.getElementById('gc_show_hide_img').src = MINUS_IMG_VAL;  // set the minus image		
				    // document.getElementById('gc_show_hide_img').style.display='inline'; 
     			    document.getElementById('giftCardSection').style.display='block';  
			        isGiftCardSectionCurrentlyVisible = true; 	
	  			}
	  			else // no GC's , no Errors, no user Input --  the GC Section should be hidden.
	  			{
                    /*
                    document.getElementById('gc_show_hide_img').src = PLUS_IMG_VAL;  // set the plus image	  			
	      		 	document.getElementById('gc_show_hide_img').style.display='inline'; 
		    	    document.getElementById('giftCardSection').style.display='none';   		  		
                    isGiftCardSectionCurrentlyVisible = false; 
                    */
                    document.getElementById('giftCardSection').style.display='block';  
			        isGiftCardSectionCurrentlyVisible = true; 				    
                }
	  		}
	  	}  // end else (no GC's applied, no errors, check to see if the user deleted the last one.
	  } // end else (no GC's applied, now check if there is a GC error.
  

// ===========================================================================================
// Captcha section
// ===========================================================================================
	 if (totalCC > 0)  //CC still has a total...user can still apply more GC's (as long as they haven't applied more than the max)
	 {
	  	if (gcAppliedTotalArray.length >= maxGCsAllowed)  //if user has applied max number of GC's allowed, hide the captcha section
	  	{
	   	  document.getElementById('captcha-section').style.display='NONE' ; 	
	  	}
	  	else
	  	{
	   	  document.getElementById('captcha-section').style.display='block';	
	  	}
	
	  }  // endif (totalCC > 0)
	  else  // totalCC <= 0
	  {    
	  	  document.getElementById('captcha-section').style.display='NONE';
	  }
	 
	 // If the gift card has an error -- refresh everything except for GC # otherwise refresh all captcha input fields because the GC was good and
	 // got applied
	 if ( gcErrMsgVal  != null && gcErrMsgVal.length > 0 )
	 {
	 	adjustCaptchaUI(KEEP_GIFT_CARD);	     
	 }
	 else  // no errors
	 {
	 	if (callingMethod == ONLOAD_VAL)   // refresh from server, if the user inputted any GC fields, keep everything but the PIN
	 	{
		  	adjustCaptchaUI(CLEAR_PIN);	  // Keep everything but the GC PIN (like CC section is today)    
		}
		else if (callingMethod == DELETE_GC_VAL)   // call coming from the delete GC function, keep everything but the PIN
	 	{
		  	adjustCaptchaUI(CLEAR_PIN);	  // Keep everything but the GC PIN (like CC section is today)    
		}
		else // not coming from server refresh or Delete function, it's coming from the AJAX and no GC errors (means that the GC was applied) ... clear all GC input fields
		{
			adjustCaptchaUI(CLEAR_ALL);	  // Clear everything
		}
		 
	 }  


// ===========================================================================================
// PAID WITH GC / CC ROWS section  and legal jargon for GC's
// ===========================================================================================
	var toBePaidWithGiftCardArray = getElementsById('PaidWithGiftCardRow','Y');
	var toBePaidWithCreditCardArray = getElementsById('paidWithCreditCardRow','Y');
	var legalGCJargonArray = getElementsById('dctm-frag-apply-gc-first','Y');	
	var showHideStyle;
	
	// if totalGC is greater than zero (user has at least one GC applied), show the "To be paid with" lines and GC legal jaron
	if ( totalGC > 0)
	{
	    if ( NETSCAPE_VAL.toLowerCase() == browserAppName )  //ie doesn't know about 'table-row'
	    {
	    	showHideStyle = 'table-row';  
	    }
	    else
	    {
	    	showHideStyle = 'block';
	    }

	}  //endif ( totalGC > 0)
	else
	{
		showHideStyle = 'NONE';
	}
	
	
//NOTE: we are looping thru the array becuase the business wanted the subtotals in 2 different places on the page so we have
//      to hide/show the lines rows in 2 places.
	
	for(var i=0;i<toBePaidWithGiftCardArray.length;i++)
	{	
	  toBePaidWithGiftCardArray[i].style.display=showHideStyle;	
	}
	
	for(var i=0;i<toBePaidWithCreditCardArray.length;i++)
	{	
	  toBePaidWithCreditCardArray[i].style.display=showHideStyle;		
	}
	
	
	for(var i=0;i<legalGCJargonArray.length;i++)
	{	
	  legalGCJargonArray[i].style.display=showHideStyle;		
	}
	

// ===========================================================================================
// GIFT CARD ENTRY section 
// ===========================================================================================
/*
*  We don't want to show gift card entry section if gift card tender is not active  
*  AND we only want to do this if the calling method is "onLoad".  If the call is coming from AJAX (not onLoad)
*  then the setting of visibility is coming from applyGiftCardCallBack();
*/
	if (callingMethod == ONLOAD_VAL)  
	{ 
		if (isGiftCardTenderActiveValue == "true" )  //it is active
		 {
			document.getElementById('gc-entry-container').style.display='block';
		 }
		 else  // it is not active
		 {		
		  document.getElementById('gc-entry-container').style.display='NONE';
		 }
	}
	
	if (debugVal == 'true')
	{
		alert ('EXITING Function: adjustCheckoutUI(callingMethod) ' +   callingMethod);
	}

	

} //end function adjustCheckoutUI





/*************************************************************************************************
*  Function: adjustGCError 
*		Adjusts the gift card error section (sometimes we need to change the error message)  
*       This will also set the appropriate Omniture message.
*
*  Parms:
*		callingMethod	-  	Anyone who calls this function must provide its name.  This is necessary
*  							because we need to know when the call is from onLoad vs Ajax.

**************************************************************************************************/
function adjustGCError(callingMethod)
{
	if (debugVal == 'true')
	{
		alert ('ENTERING Function: adjustGCError(' + callingMethod + ')');
	}
/*
*  If this function was called from onLoad, empty out the gift-card-errors div.  We don't want
*  to show any errors that came from the full screen refresh.  This error section should only
*  display errors when the user tries to "apply gift card"
*/


	var gcErrMsg = null;
	var gcErrMsgVal = null;
		

	gcErrMsg = document.forms[formName].gcErrorMsgs;  
	if (gcErrMsg != null)
	{
		gcErrMsgVal = gcErrMsg.value;
	}

    // If the calling method is coming from onLoad, that means it was a server refresh (like user tried to checkout).  If this is the case
    // we want to clear out any GC errors that may have previously existed.		
	if (callingMethod == ONLOAD_VAL)  
	{
		document.getElementById('gift-card-errors').innerHTML ='';
		gcErrMsgVal = '';
		adjustCaptchaUI(CLEAR_PIN); //keep everything but the PIN (like CC section does today)
	}
	else // not from on load (coming from AJAX).  Check to see if there are any Gift Card Server Error messages and set the error message in the HTML
	{
	   if ( gcErrMsgVal != null && gcErrMsgVal.length > 0 )
	   {

	   		var genericUserMsg  	= gcUserErrorMsg;
	   		var genericSystemMsg	= gcSystemErrorMsg;
	   		var captchaErrorMsg  	= gcCaptchaErrorMsg;
	   		var zeroBalanceError    = gcZeroBalanceErrorMsg;
	   		var zeroBalanceErrorMsg = null;
	   		
	   		if (zeroBalanceError != null)
	   		{
		   		zeroBalanceErrorMsg = zeroBalanceError.value;
	   		}
	   		
  	   		var messageToShow = gcErrMsgVal;

	   		if (gcErrMsgVal == genericUserMsg)  // user error
	   		{

	   			messageToShow = genericUserMsg;
	   			omnitureMsg = OMNITURE_USER_ERR_VAL;

	   		}
	   		else if (gcErrMsgVal ==  captchaErrorMsg)  //Invalid Captcha error
	   		{	 

		   		messageToShow = genericUserMsg;
     			omnitureMsg = OMNITURE_CAPTCHA_ERR_VAL;
		   		
	   		}
	   		else if (gcErrMsgVal ==  zeroBalanceErrorMsg)  //Zero Balance error 
	   		{	 

		   		messageToShow = zeroBalanceErrorMsg;
     			omnitureMsg = OMNITURE_USER_ERR_VAL;
		   		
	   		}
	   		else if (gcErrMsgVal == genericSystemMsg)  //system error
	   		{

	   			messageToShow = genericSystemMsg;
     			omnitureMsg = OMNITURE_SYSTEM_ERR_VAL;
	   		}


	   		document.getElementById('gift-card-errors').innerHTML ='<span class="error">' + messageToShow +  '</span>';
	   		adjustCaptchaUI(KEEP_GIFT_CARD);
	
	   }  //end if ( gcErrMsgVal != null && gcErrMsgVal.length > 0 )
	   else // no GC errors  
	   {	   		
	   		omnitureMsg = '';
	   }
	}  //end else not from on load (coming from AJAX).  Check to see if there are any Gift Card Server Error messages and set the error message in the HTML
  
	if (debugVal == 'true')
	{
		alert ('EXITING Function: adjustGCError(' + callingMethod + ')');
	}
 
}  // end adjustGCError(callingMethod)



/*************************************************************************************************
*  Function: adjustCaptchaUI 
*		Adjusts the capchta section of the page depending on the state that it needs to be in.  This 
*       adjustment occurs after the ajax call to try to apply a gift card or get the balance of a GC
*
*  Parms:
*		stateOfAdjusment	- The state that the function needs to adjust the captcha section for 
*							  either CLEAR_ALL or KEEP_GIFT_CARD.  
**************************************************************************************************/
function adjustCaptchaUI(stateOfAdjusment)
{
	if (debugVal == 'true')
	{
		alert ('ENTERING Function: adjustCaptchaUI(stateOfAdjusment) '  +  stateOfAdjusment);
	}

// The Captcha section on the GC PIP page is not on form 0 so I have to check the page name and adjust it. 
    if (formName == 0) // what it is initially set to and it's called on the initial load of the page)
    {
 		setFormName()
    }
    
//    formName = 'OrderItemAddForm';
  	var giftCardNbr = document.forms[formName].giftCardNumber;
	var pinNbr = document.forms[formName].pinNumber;
	var captchaTxt = document.forms[formName].captchaVerification;


  if (CLEAR_ALL == stateOfAdjusment) 
  {
  	giftCardNbr.value = '';
  	pinNbr.value = '';
  	captchaTxt.value = '';    
  }  
  else if (KEEP_GIFT_CARD == stateOfAdjusment) 
  {
  	pinNbr.value = '';
  	captchaTxt.value = '';  	
  }
   else if (CLEAR_PIN == stateOfAdjusment) 
  {
  	pinNbr.value = '';
  }
 
  else  // some other .. clear everything
  {
  	giftCardNbr.value = '';
  	pinNbr.value = '';
  	captchaTxt.value = '';   	  	
  }
  
	if (debugVal == 'true')
	{
		alert ('EXITING Function: adjustCaptchaUI(stateOfAdjusment) '  +  stateOfAdjusment);
	}
}  // end function adjustCaptchaUI


/*************************************************************************************************
*  Function: setFormName 
*		This function sets the form name of the particular form that needs to be set. This was needed
*		because in Checkout, we could use form[0] but that is not the case for the GC Pip page.  
*       Note: formName is used throughout the function modules.
*
*  Parms:
*		NONE
**************************************************************************************************/
function setFormName()
{
    	if (CI_Page_Name == 'GC_PIP_PAGE') //gift card PIP page
    	{   
    		formName = GIFT_CARD_BALANCE_FORM_NAME;
    	}
    	else if(CI_Page_Name == 'ORDER_SUMMARY' )  // checkout page
    	{
    		formName = CHECKOUT_FORM_NAME
    	}
}



/*************************************************************************************************
*  Function: CurrencyFormatted 
*		This function reads in a number and based upon parameters explained below, will
*       return a number that is formated as currency (2 decimal places to the right)
*  Parms:
*     num 				- the number that needs to be converted
*     currencySymbol 	- the symbol to place at the beginning of the number ('' is valid)
*     currencySeprator 	- the seperator to use when the number becomes greater than 999 ('' is valid)
**************************************************************************************************/
function CurrencyFormatted(num, currencySymbol, currencySeprator) 
{
	if (debugVal == 'true')
	{
		alert ('ENTERING Function: CurrencyFormatted(num, currencySymbol, currencySeprator)' + num + ',' + currencySymbol + ',' + currencySeprator  );
	}


	
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for(var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+ currencySeprator + num.substring(num.length-(4*i+3));

	if (debugVal == 'true')
	{
		alert ('EXITING Function: CurrencyFormatted(num, currencySymbol, currencySeprator)' + num + ',' + currencySymbol + ',' + currencySeprator  ); 
	}

	return (((sign)?'':'-') + currencySymbol + num + '.' + cents);
} // end CurrencyFormatted







/*************************************************************************************************
*  Function:  checkNumber
*		This function takes in a text value and strips all known currency symbols out of it.  It then
*  		checks to see if the stripped number is indeed a number.  If it is a number, it returns itself.  If it is not
*       a number, it returns 0.
*   
*  Parms:
*		number 	- the number which needs to be checked.
**************************************************************************************************/
function checkNumber(number)
{
	if (debugVal == 'true')
	{
		alert ('ENTERING Function: checkNumber(number)' + number  );
	}

	number = number.replace(/\$/g, '').replace(/,/g, '').replace(/\(/g, '-').replace(/\)/g, '').replace('&nbsp;','').replace('&#160;', '');
	
	number = leftTrim(number);
	

	if( isNaN(number) )
	{
	   return (0*1);
	}
	else
	{
	   return (number*1);
	}
		
	if (debugVal == 'true')
	{
		alert ('EXITING Function: checkNumber(number)' + number  );
	}
} // end checkNumber(number)





/*************************************************************************************************
*  Function:  getElementsById
*		This function returns back all elements with the specified id.  This was needed because 
*       FireFox doesn't support getElementsByName if it is an id. 
*   
*  Parms:
*		id	- the id of the element(s) that needs to be returned.
**************************************************************************************************/
function getElementsById(id, useGroupCache)
{
	if (debugVal == 'true')
	{
		alert ('ENTERING Function: getElementsById(' + id + ')'  );
	}
	
	var nodes;
	
	// I had to put in the useGroupCache in because the getelementById will return null if the id is hidden. 
	// but the group cache messes up when you have a growing table of id's.
	if ('Y' == useGroupCache.toUpperCase() )
	{
		if(!groupCache[id])
		{
		groupCache[id] = [];
		}
		nodes = groupCache[id];
		for(var x=0; x<nodes.length; x++)
		{
			if(nodes[x].id != "")
			{
				nodes.splice(x, 1);
				x--;
			}
		}
	}
	else
	{
		nodes = [];
	}



  var tmpNode = document.getElementById(id);
  
  while(tmpNode)
  {
    nodes.push(tmpNode);
    tmpNode.id = "";
    tmpNode = document.getElementById(id);    
  }

  	if (debugVal == 'true')
	{
	  alert( "Total no. of nodes returned:" +nodes.length );
	    for(var i=0; i<nodes.length;i++)
		  {
		  	alert (id + '[' + i + ']' + nodes[i].innerHTML);
		  }
	}
  

  
  	if (debugVal == 'true')
	{
		alert ('EXITING Function: getElementsById(' + id + ')'  );
	}

	return nodes;
} // end getElementsById(id, useGroupCache)




/*************************************************************************************************
*  Function:  popWhereIsMyGiftCardPin
*		This function will open the gift-card-pin layer and set focus to it.
*
*  Parms:
*		None
**************************************************************************************************/
function popWhereIsMyGiftCardPin()
{  
  	if (debugVal == 'true')
	{
		alert ('ENTERING Function: popWhereIsMyGiftCardPin()');
	}

	openLayer('gift-card-pin');
	focusOnAnchor('popupFocusArea');
	
	if (debugVal == 'true')
	{
		alert ('ENTERING Function: popWhereIsMyGiftCardPin()');
	}
	
} // END popWhereIsMyGiftCardPin()






/*************************************************************************************************
*  Function:  focusOnAnchor
*		This function will set focus on an anchor.  Based on browser name
*
*  Parms:
*		anchorName 	-	The name of the anchor that needs focusing set
**************************************************************************************************/

function focusOnAnchor(anchorName)
{
  	if (debugVal == 'true')
	{
		alert ('ENTERING Function: focusOnAnchor(' + anchorName + ')'  );
	}	
	


	if ( NETSCAPE_VAL.toLowerCase() == browserAppName )  
	{
		var anchorsArray = document.anchors;
		var anchorsArrayLength = anchorsArray.length;  
	
		for (var i=0;i<anchorsArrayLength;i++)
		{
			if ( anchorName == anchorsArray[i].name )
			{
				anchorsArray[i].focus();
				break;
			} // end if
		} // end for
	} // end if netscape browser
	else // for all other browsers
	{
		var anchorObject = document.getElementById(anchorName);
		if (anchorObject != null)
		{
		  	anchorObject.focus();
		}
	}
		
	if (debugVal == 'true')
	{
		alert ('EXITING Function: focusOnAnchor(' + anchorName + ')'  );
	}

} // end focusOnAnchor(anchorName)



/*************************************************************************************************
*  Function:  callOmniture
*		This function will set the required omniture fields needed for Giftcard balance and will then
*		call ominture with them
*
*  Parms:
*		msg -- the message to set in omniture.
**************************************************************************************************/
function callOmniture(msg)
{

	if (debugVal == 'true')
	{
		alert ('ENTERING Function: callOmniture(' + msg + ')'  );

	}

	try
	{
		var GIFT_CARD_BALANCE_CHECK_VAL = '>giftcard balance check';
		var origPageName = s.pageName.replace(GIFT_CARD_BALANCE_CHECK_VAL,'');
		

		s.linkTrackVars='prop27,events';  	// tell Omniture what fields that you will be tracking
		s.prop27 = msg;						// set the error message to what was passed in ('<space>' will not produce an error message in Omniture)
		s.linkTrackEvents = 'event10';  	// tell Omniture what events that you will be tracking
		s.events = 'event10';				// set the events to a page event.
	
		s.pageName = origPageName + GIFT_CARD_BALANCE_CHECK_VAL; 	// set the page name for Omniture

//		s.tl(omnitureLinkTrackingObject,'e','giftcard balance check');
		s.t();

	} 
	catch(e)
	{	 
	}
	
	if (debugVal == 'true')
	{
		alert ('EXITING Function: callOmniture(' + msg + ')'  );
	}
	
}   // end callOmniture(msg)


/*************************************************************************************************
*  Function:  gcNumbersOnly(event)
*		This function gets called when the user types data into the GC number or GC PIN fields. 
*		It ultimately calls the nubmersOnly(event) function in utils.js to check if it is indeed 
*       a number.  I just extended that function to allow the user to click additional keys (like insert) 
*       to help them in editing the number
*
*  Parms:
*		event -- The onKeyPress event
**************************************************************************************************/
function gcNumbersOnly(event)
{

// keys that we will allow in addition to numbers -- BEGIN
	var BACK_SPACE = 8;
	var TAB = 9;
	var END_KEY  = 35;
	var HOME_KEY = 36;
	var INSERT = 39;
	var DELETE = 46;
	var LEFT_ARROW = 37;
	var RIGHT_ARROW = 39;

// keys that we will allow in addition to numbers -- END
	var keynum;	
	
	if(event.keyCode)
	{
		keynum = event.keyCode;
	} 
	else if(event.which) 
	{
		keynum = event.which;
	} 
	else if (event.charCode) 
	{
		keynum = event.charCode;
	}	
	
	if ( 	(keynum == BACK_SPACE) 
		|| 	(keynum == TAB) 
		|| 	(keynum == INSERT) 
		|| 	(keynum == DELETE)
		|| 	(keynum == LEFT_ARROW)
		|| 	(keynum == RIGHT_ARROW)
		|| 	(keynum == HOME_KEY)
		|| 	(keynum == END_KEY)


		) 
	{
		return true;
	} 
	else 
	{	
		return numbersOnly(event);
	}
}  // end gcNumbersOnly(event)



/*************************************************************************************************
*  Function:  leftTrim(str)
*		Trim all beginning white space from a string
*
*  Parms:
*		str -- the string that you want lett trimmed
**************************************************************************************************/
function leftTrim(str) 
{
	var i;
	var len = str.length;
	
	for( i=0; i<len; i++ )
	{
		if( str.charCodeAt(i) == 160 )
		{
			str = str.substring(1, str.length );
			i--;   
			len--;
		}
		else
		{
			break;
		}
	}
	
	return str;
}




/*************************************************************************************************
*  Function:  alertGCFields
*		This function was added purely for degbug purposes
*
*  Parms:
*		None
**************************************************************************************************/
function alertGCFields()
{
	if (debugVal == 'true')
	{
		alert ('ENTERING Function: alertGCFields()'  );
	}
	
	var totalGC = document.forms[formName].totalGC.value;
	var totalCC = document.forms[formName].totalCC.value;	
	var totalOrder = document.forms[formName].totalOrder.value;	
	var lastRemNumber = document.forms[formName].lastRemNumber.value;
	var lastRemAmount = document.forms[formName].lastRemAmount.value;
	var maxGCsAllowed = document.forms[formName].maxGCsAllowed.value;
    var nbrOfGCsToShowInTable = document.forms[formName].nbrOfGCsToShowInTable.value;

	var gcNbrsArray = document.getElementsByName('appliedGiftCardNbrs');	  
	var gcAppliedTotalArray = document.getElementsByName('appliedGiftCardAmounts');
	var gcAvailableTotalArray = document.getElementsByName('availableGiftCardAmounts');
	var gcEncryptedGCArray = document.getElementsByName('encryptedGiftCardNbrs');	
	var gcReservedGCArray = document.getElementsByName('giftCardReserves');	
	var arrayLength = gcNbrsArray.length;
	
	var cardHolderName = document.forms[formName].cardHolderName.value;
 	var cardBrand = document.forms[formName].cardBrand.value;
 	var cardNumberDisplayValue = document.forms[formName].cardNumberDisplayValue.value;
	var cardNumberOriginalDisplayValue = document.forms[formName].cardNumberOriginalDisplayValue.value;
	var cardNumber = document.forms[formName].cardNumber.value;
	var notifyOrderSubmitted = document.forms[formName].notifyOrderSubmitted.value;
	var cardExpiryMonth = document.forms[formName].cardExpiryMonth.value;
	var cardExpiryYear = document.forms[formName].cardExpiryYear.value;
	var cardVerificationCode = document.forms[formName].cardVerificationCode.value;
	var poNumber = document.forms[formName].poNumber.value; 
	var gcErrorMsgs = document.forms[formName].gcErrorMsgs.value;  
	
	
	var gcRow = '';
		
	for(var i=0;i<arrayLength;i++)
	{		
	   gcRow = gcRow 
	 + '[' + i + ']  GC#:' + gcNbrsArray[i].value + '\t' 
	 + '    Available Amt:' + gcAvailableTotalArray[i].value + '\t' 	 
	 + '    Applied Amt:' + gcAppliedTotalArray[i].value + '\t' 
 	 + '    Reserved Amt:' + gcReservedGCArray[i].value + '\t'
	 + '    Encrypted:' + gcEncryptedGCArray[i].value + '\n' + '\n' ;

	}

	alert(
	  "totalOrder [" + totalOrder + "]" + "\n" 
	+ "totalGC [" + totalGC + "]" + '\n'  
	+ "totalCC [" + totalCC + "]" + '\n'  + '\n'  
	+ "lastRemNumber [" + lastRemNumber + "]" + "\n"
	+ "lastRemAmount [" + lastRemAmount + "]" + "\n" + "\n"
	+ gcRow + '\n' + '\n'
	+ "isGiftCardTenderActive [" + isGiftCardTenderActiveValue + "]" + "\n"
	+ "maxGCsAllowed [" + maxGCsAllowed + "]" + "\n"
	+ "nbrOfGCsToShowInTable [" + nbrOfGCsToShowInTable + "]" + "\n" + "\n" + "\n" 
	+ "cardHolderName [" + cardHolderName + "]" + "\n"
	+ "cardBrand [" + cardBrand + "]" + "\n"
	+ "cardNumberDisplayValue [" + cardNumberDisplayValue + "]" + "\n"
	+ "cardNumberOriginalDisplayValue [" + cardNumberOriginalDisplayValue + "]" + "\n"
	+ "cardNumber [" + cardNumber + "]" + "\n"
	+ "notifyOrderSubmitted [" + notifyOrderSubmitted + "]" + "\n"
	+ "cardExpiryMonth [" + cardExpiryMonth + "]" + "\n"
	+ "cardExpiryYear [" + cardExpiryYear + "]" + "\n"
	+ "cardVerificationCode [" + cardVerificationCode + "]" + "\n"
	+ "poNumber [" + poNumber + "]" + "\n"		
	+ "gcErrorMsgs [" + gcErrorMsgs + "]" + "\n"	

	);   
	
	if (debugVal == 'true')
	{
		alert ('EXITING Function: alertGCFields()'  );
	}
	
}  //end alertGCFields





	 
/*************************************************************************************************
*  Function:  alertAppliedGCs
*		This function was added purely for degbug purposes
*
*  Parms:
*		None
**************************************************************************************************/
function alertAppliedGCs()
{
	alert(document.getElementById('appliedGiftCardTable').innerHTML);
}

function changeDebugVal(str)
{
	debugVal = str.toLowerCase();
	alert ('debugVal[' + debugVal + ']');
}
