// Create variables for getting the response from the server. These values are set in GiftCardBalance.jsp
var gcPinVal="";
var	gcNumberVal = "";
var gcBalanceVal = "";
var	responseCode = "";
var	reloadEnabledFlag = "";
var	catentryId = "";
var	storeId = "";
var	catalogId = "";
var errorMessageForResponse = "";
var giftCardMinimumBalance = "";
var giftCardMinimumLimit = "";
var	giftCardMaximumLimit = "";
var ajaxCallInProgress = false;
var passwordRetryCount = 3;

// Function for validating the response code got from server
function validateResponseCode() {
	var gc_responseCode = responseCode;
	if(gc_responseCode == "LOGOFF"){
		var currentUrl = window.location.href;
		var tillDomain = currentUrl.split('shc/s/')[0];
		var logOffUrl = tillDomain + 'shc/s/Logoff?langId=-1&storeId=10151&catalogId=10104&personalizedCatalog=true&URL=SSOLogoffView&rememberMe=false'
		window.location.replace(logOffUrl);
	}	
	// Valid response codes are: 
	// 00 - Successful Balance Inquiry
	// AMOUNTINVALID - The reload amount entered for Add to cart is Invalid. Handled in updateGCDetails() function
	// EXSITINGBALANCEINVALID - Existing balance is Invalid. Handled in updateGCDetails() function
	if(gc_responseCode !="00" && gc_responseCode !="AMOUNTINVALID" && gc_responseCode !="EXSITINGBALANCEINVALID") {
		// Response for Invalid PIN - 45
		var errorMessage= errorMessageForResponse;
		$('div.reloadErrorBalance').text(errorMessage).show();
		$('form#chBalFrm input.num').css({border:'1px solid #cc1a0d',padding:'1px'});
		$('form#chBalFrm input.pin').css({border:'1px solid #cc1a0d',padding:'1px'});
		
		//DHTML LAYER height adjustment, if not available on pg, below degrades.
		if(!$.browser.msie){$('#DHTMLwrap').height($('#DHTMLcontent').height()+8);}
		else{$('#DHTMLwrap').height($('#DHTMLcontent').height()+10);}
		$('div#balBox').hide();	
		$('div.reloadErrorReload').hide();	
		return false;
	} 
	return true;
}

function checkPasswordRetryCount() {
		var gcCookieCount = getCookie("giftCardPasswordRetryCnt");	
		if ( gcCookieCount.length != 0 && gcCookieCount > 0){			
			var giftCardPasswordRetryCnt = parseInt(gcCookieCount)+1;	
			setCookie("giftCardPasswordRetryCnt",giftCardPasswordRetryCnt);	
			if(giftCardPasswordRetryCnt == passwordRetryCount) {
				var errorMessage= "We're sorry, we are unable to process this gift card online at this time.";
				$('div.reloadErrorBalance').text(errorMessage).show();
				$('form#chBalFrm input.num').css({border:'1px solid #cc1a0d',padding:'1px'});
				$('form#chBalFrm input.pin').css({border:'1px solid #cc1a0d',padding:'1px'});
				
				//DHTML LAYER height adjustment, if not available on pg, below degrades.
				if(!$.browser.msie){$('#DHTMLwrap').height($('#DHTMLcontent').height()+8);}
				else{$('#DHTMLwrap').height($('#DHTMLcontent').height()+10);}
				$('div#balBox').hide();
				$('div.reloadErrorReload').hide();
				return false;
			}
		}
		else {
			var giftCardPasswordRetryCnt=1;
			setCookie("giftCardPasswordRetryCnt",giftCardPasswordRetryCnt);	
		}
		return true;	
}

// Functions for Setting and Getting the Cookie Value
function setCookie(cookieName,cookieValue) {
	document.cookie=cookieName+ "=" +escape(cookieValue);
}
 
function getCookie(cookieCount) {
	if (document.cookie.length>0) {
		c_start=document.cookie.indexOf(cookieCount + "=");
	    if (c_start!=-1) { 
		    c_start=c_start + cookieCount .length+1; 
		    c_end=document.cookie.indexOf(";",c_start);
		    if (c_end==-1) 
		    	c_end=document.cookie.length;
    		return unescape(document.cookie.substring(c_start,c_end));
    	} 
  	}
	return "";
} 

function newGCvalidation(gcNum, pin, amount) {
	var gc_numFld = $('form#chBalFrm input.num');
	var gc_pinFld = $('form#chBalFrm input.pin');
	var gc_goBtn = $('form#chBalFrm input.goBtn');
	var gc_errBalanceDiv = $('div.reloadErrorBalance');
	var gc_errCardTxt = 'Please enter a valid Gift Card number.';
	var gc_errPinTxt = 'Please enter a valid PIN number.';
	var gc_errCardPinTxt = 'Please enter a valid Gift Card number and PIN number.';
	var gc_errNoLetters = 'Gift Cards only contain numbers. Please check your entry and try again.';
	var reg = /^[0-9]+$/;
	
	//Validation for the Gift Card Balance Form
	$(gc_goBtn).click(function(){
		// Trim the gift card number before validating it (Both left and right).
		$(gc_numFld).val(ltrim(rtrim($(gc_numFld).val())));
		
		if(!$(gc_numFld).val().match(reg) || $(gc_numFld).val() == ''){
			$(gc_errBalanceDiv).text(gc_errNoLetters).show();
			$(gc_numFld).css({border:'1px solid #cc1a0d',padding:'1px'});
			
			//DHTML LAYER height adjustment, if not available on pg, below degrades.
			$('div#balBox').hide();
			$('div.reloadErrorReload').hide();	
			if(!$.browser.msie){$('#DHTMLwrap').height($('#DHTMLcontent').height()+8);}
			else{$('#DHTMLwrap').height($('#DHTMLcontent').height()+10);}
			
			return false;
		}
		else if(!$(gc_pinFld).val().match(reg) || $(gc_pinFld).val() == ''){
			$(gc_errBalanceDiv).text(gc_errNoLetters).show();
			$(gc_pinFld).css({border:'1px solid #cc1a0d',padding:'1px'});
			
			//DHTML LAYER height adjustment, if not available on pg, below degrades.
			$('div#balBox').hide();
			$('div.reloadErrorReload').hide();	
			if(!$.browser.msie){$('#DHTMLwrap').height($('#DHTMLcontent').height()+8);}
			else{$('#DHTMLwrap').height($('#DHTMLcontent').height()+10);}
			
			return false;
		}
		else if(($(gc_numFld).val().length < 16 && $(gc_pinFld).val().length < 4) || ($(gc_numFld).val() == '' && $(gc_pinFld).val() == '')){
			$(gc_errBalanceDiv).text(gc_errCardPinTxt).show();
			$(gc_numFld).css({border:'1px solid #cc1a0d',padding:'1px'});
			$(gc_pinFld).css({border:'1px solid #cc1a0d',padding:'1px'});
			
			//DHTML LAYER height adjustment, if not available on pg, below degrades.
			$('div#balBox').hide();
			$('div.reloadErrorReload').hide();	
			if(!$.browser.msie){$('#DHTMLwrap').height($('#DHTMLcontent').height()+8);}
			else{$('#DHTMLwrap').height($('#DHTMLcontent').height()+10);}
			
			return false;
		}
		else if(($(gc_numFld).val().length != 16 && $(gc_numFld).val().length != 19)  || $(gc_numFld).val() == ''){
			$(gc_errBalanceDiv).text(gc_errCardTxt).show();
			$(gc_numFld).css({border:'1px solid #cc1a0d',padding:'1px'});
			
			//DHTML LAYER height adjustment, if not available on pg, below degrades.
			$('div#balBox').hide();
			$('div.reloadErrorReload').hide();	
			if(!$.browser.msie){$('#DHTMLwrap').height($('#DHTMLcontent').height()+8);}
			else{$('#DHTMLwrap').height($('#DHTMLcontent').height()+10);}
			
			return false;
		}
		else if(($(gc_pinFld).val().length != 4 && $(gc_pinFld).val().length != 8) || $(gc_pinFld).val() == ''){
			$('div#balBox').hide();
			$('div.reloadErrorReload').hide();	
			$(gc_errBalanceDiv).text(gc_errPinTxt).show();
			$(gc_pinFld).css({border:'1px solid #cc1a0d',padding:'1px'});
			
			//DHTML LAYER height adjustment, if not available on pg, below degrades.
			if(!$.browser.msie){$('#DHTMLwrap').height($('#DHTMLcontent').height()+8);}
			else{$('#DHTMLwrap').height($('#DHTMLcontent').height()+10);}
			
			return false;
		}
		else if(!(($(gc_numFld).val().length == 16 && $(gc_pinFld).val().length == 8) || 
						($(gc_numFld).val().length == 19 && $(gc_pinFld).val().length == 4))){
			$('div#balBox').hide();
			$('div.reloadErrorReload').hide();	
			$(gc_errBalanceDiv).text(gc_errCardPinTxt).show();
			$(gc_numFld).css({border:'1px solid #cc1a0d',padding:'1px'});
			$(gc_pinFld).css({border:'1px solid #cc1a0d',padding:'1px'});
			
			//DHTML LAYER height adjustment, if not available on pg, below degrades.
			if(!$.browser.msie){$('#DHTMLwrap').height($('#DHTMLcontent').height()+12);}
			else{$('#DHTMLwrap').height($('#DHTMLcontent').height()+12);}
			
			return false;
		}
		else {
			var gcCookieCount = getCookie("giftCardPasswordRetryCnt");		
			if ( gcCookieCount.length != 0 && gcCookieCount > 0){			
				var giftCardPasswordRetryCnt = parseInt(gcCookieCount);
				
				// Get the maximum password retry count allowed from the Hidden field
				if(document.getElementById("passwordRetryCount") && document.getElementById("passwordRetryCount").value!="") {
					passwordRetryCount = parseInt(document.getElementById("passwordRetryCount").value);
				}
				if(giftCardPasswordRetryCnt == passwordRetryCount) {
					$(gc_errBalanceDiv).text("We're sorry, we are unable to process this gift card online at this time.").show();
					$(gc_numFld).css({border:'1px solid #cc1a0d',padding:'1px'});
					$(gc_pinFld).css({border:'1px solid #cc1a0d',padding:'1px'});
					
					document.getElementById("gcFldNum").value="";
					document.getElementById("gcFldPin").value="";
					//DHTML LAYER height adjustment, if not available on pg, below degrades.
					$('div#balBox').hide();
					$('div.reloadErrorReload').hide();
					if(!$.browser.msie){$('#DHTMLwrap').height($('#DHTMLcontent').height()+8);}
					else{$('#DHTMLwrap').height($('#DHTMLcontent').height()+10);}
	
					return false;
				}
			}
			
			if(document.getElementById("ajaxFlagForGCBalance") && (document.getElementById("ajaxFlagForGCBalance").value="true")) {
				if(ajaxCallInProgress == false || ajaxCallInProgress == "false") {
					// Indicates an AJax is to be made to retrieve GC balance
					var gcnumber = document.getElementById("gcFldNum");
				    var gcpin = document.getElementById("gcFldPin");
					var fullUrl = location.href;
					var ajaxFlag=document.getElementById("ajaxFlagForGCBalance").value;
					var storeIdFromHiddenField = document.getElementById("storeId").value;
					var catalogIdFromHiddenField = document.getElementById("catalogId").value;
					
					// Getting the Context path
					var index = fullUrl.search("shc/s/");
					var chunkValue = fullUrl.substring(0,index+6);
					var gcAjaxUrl=chunkValue;
					gcAjaxUrl+="GiftCardBalanceInqCmd";
					var params = {
						giftCardNumber : gcnumber.value,
						storeId : storeIdFromHiddenField,
						catalogId : catalogIdFromHiddenField,
						giftCardPin : gcpin.value,
						ajaxFlag : ajaxFlag
					};
					
					// To avoid duplicate Ajax calls
		  			ajaxCallInProgress = true;
					request=$.post(gcAjaxUrl,params,displayResponse);
				}
				return false; 
			} else {
				// Setting the store id in Gift card Inquiry form.
				if(document.getElementById("storeId") && document.getElementById("storeId").value!="") {
					document.forms["giftCardForm"].elements["storeId"].value = document.getElementById("storeId").value;
				} else if(storeId != "") {
					document.forms["giftCardForm"].elements["storeId"].value = storeId;
				} else {
					document.forms["giftCardForm"].elements["storeId"].value = "0";
				}
				// Setting the catalog id in Gift card Inquiry form.
				if(document.getElementById("catalogId") && document.getElementById("catalogId").value!="") {
					document.forms["giftCardForm"].elements["catalogId"].value = document.getElementById("catalogId").value;
				} else if(catalogId != "") {
					document.forms["giftCardForm"].elements["catalogId"].value = catalogId;
				} else {
					document.forms["giftCardForm"].elements["catalogId"].value = "0";
				}
				// Return TRUE so that the form will be submitted
				return true;
			}
		}
	});
	
	// Variables for Add to Cart Validation
	var gc_add2cartBtn = $('form#reloadCard input#gc_add2cart');
	var gc_reloadFld = $('form#reloadCard input.reload');
	var gc_errReloadDiv = $('div.reloadErrorReload');
	
	//Validation for the Gift Card RELOAD Form
	$(gc_add2cartBtn).click(function(){		
		
		// Set these values only after the balance inquiry flow completes. Else the values wont be set.
		// Set gc_existingbalance to zero if existing balance returned from server is empty
		var gc_existingbalance = gcBalanceVal != "" ? parseFloat(gcBalanceVal) : 0;	
		var gc_minimumbalance = parseInt(giftCardMinimumBalance);
		var gc_minimumlimit = parseInt(giftCardMinimumLimit);
		var gc_maximumlimit = parseInt(giftCardMaximumLimit);
		var gc_errReloadTxt1 = 'Please enter an amount greater than $'+gc_minimumlimit;	
		var gc_errReloadTxt2 = 'Gift card balance cannot exceed $'+gc_maximumlimit+'. Please enter a lower amount.';
		var gc_err1 = 'Existing balance is less than minimum balance. The minimum balance required is $'+gc_minimumbalance;
		var gc_err2 = 'Not a valid dollar amount. Please try again';
		// Trim the reload amount before validating it (Both left and right).
		$(gc_reloadFld).val(ltrim(rtrim($(gc_reloadFld).val())));
		
		if(!$(gc_reloadFld).val().match(reg) || $(gc_reloadFld).val() == ''){
			$(gc_errReloadDiv).text(gc_err2).show();
			$(gc_reloadFld).css({border:'1px solid #cc1a0d',padding:'1px'});
			
			//DHTML LAYER height adjustment, if not available on pg, below degrades.
			if(!$.browser.msie){$('#DHTMLwrap').height($('#DHTMLcontent').height()+8);}
			else{$('#DHTMLwrap').height($('#DHTMLcontent').height()+10);}
			
			return false;
		}
		else if(gc_existingbalance < gc_minimumbalance) {	
			$(gc_errReloadDiv).text(gc_err1).show();
			$(gc_reloadFld).css({border:'1px solid #cc1a0d',padding:'0 1px 1px 1px'});
			
			//DHTML LAYER height adjustment, if not available on pg, below degrades.
			if(!$.browser.msie){$('#DHTMLwrap').height($('#DHTMLcontent').height()+8);}
			else{$('#DHTMLwrap').height($('#DHTMLcontent').height()+10);}
			
			return false;
		}else if(parseFloat((gc_reloadFld).val()) < gc_minimumlimit){	
			$(gc_errReloadDiv).text(gc_errReloadTxt1).show();
			$(gc_reloadFld).css({border:'1px solid #cc1a0d',padding:'0 1px 1px 1px'});
			
			//DHTML LAYER height adjustment, if not available on pg, below degrades.
			if(!$.browser.msie){$('#DHTMLwrap').height($('#DHTMLcontent').height()+8);}
			else{$('#DHTMLwrap').height($('#DHTMLcontent').height()+10);}
			
			return false;
		}else if((parseFloat((gc_reloadFld).val())+ (gc_existingbalance))> (gc_maximumlimit)){
			$(gc_errReloadDiv).text(gc_errReloadTxt2).show();
			$(gc_reloadFld).css({border:'1px solid #cc1a0d',padding:'0 1px 1px 1px'});
			
			//DHTML LAYER height adjustment, if not available on pg, below degrades.
			if(!$.browser.msie){$('#DHTMLwrap').height($('#DHTMLcontent').height()+8);}
			else{$('#DHTMLwrap').height($('#DHTMLcontent').height()+10);}
			
			return false;
		}
		else {return true;}
	});
}

function displayResponse(responseText) {  
	var gcResponse = eval('(' + responseText + ')'); 

	// Set the response properties in JAva Script variables
	gcPinVal = gcResponse.gcpinval;
	gcNumberVal = gcResponse.gcnumberval;
	gcBalanceVal = gcResponse.gcbalanceval;
	responseCode = gcResponse.responsecode;
	reloadEnabledFlag = gcResponse.reloadEnabledFlag;
	catentryId = gcResponse.catentryId;
	storeId = gcResponse.storeId;
	catalogId = gcResponse.catalogId;
	ajaxCallInProgress = false;
							
	// Set the error message, minimum and maximum limit, password retry count from Peoperties file
	if(document.getElementById("ERROR_MESSAGE_FOR_RESPONSE_"+responseCode)!=null 
			&& document.getElementById("ERROR_MESSAGE_FOR_RESPONSE_"+responseCode)!=undefined) {
		errorMessageForResponse = document.getElementById("ERROR_MESSAGE_FOR_RESPONSE_"+responseCode).value;
	}
	giftCardMinimumBalance = gcResponse.giftCardMinimumBalance;
	giftCardMinimumLimit = gcResponse.giftCardMinimumLimit;
	giftCardMaximumLimit = gcResponse.giftCardMaximumLimit;
	passwordRetryCount = parseInt(gcResponse.passwordRetryCount);	
	
	// Check for the validity of the response code..
	if(!validateResponseCode()) {
		$('img#cardArt').show();
		document.getElementById("gcFldNum").value="";
		document.getElementById("gcFldPin").value="";
		// Increase the size of the wrapper
		$('#DHTMLwrap').width($('#DHTMLcontent').width()+12);
		$('#DHTMLwrap').height($('#DHTMLcontent').height()+12);
		return;
	}
	renderGCBalReload();
	// Display the date
	var today=new Date();
	$('.dateBucket').html(today.getMonth()+1+'/'+today.getDate()+'/'+today.getFullYear().toString().split('20')[1]);
	$('div.reloadErrorBalance').hide();
	$('div.reloadErrorReload').hide();
	$('img#cardArt').hide();
	
	// Increase the size of the wrapper
	$('#DHTMLwrap').width($('#DHTMLcontent').width()+12);
	$('#DHTMLwrap').height($('#DHTMLcontent').height()+12);
} 
function renderGCBalReload() {
	var gcnumber        = document.getElementById("gcFldNum");
	var gcbalance       = document.getElementById("gcbalance");	
	var gcPin = document.getElementById("gcFldPin");
	
	// Mask the last 4 digits of the Gift card number
	var gcNumberMask =gcNumberVal;
	gcNumberMask= gcNumberMask.substring(0,(gcNumberMask.length-4));
	gcNumberMask=gcNumberMask.concat("****");	
	
	gcnumber.value  = gcNumberMask;
	gcPin.value  = "";
	gcbalance.innerHTML = "$"+gcBalanceVal;
	$('div#balBox').show();
	
	// Hide reload DIV if this is not true
	if(reloadEnabledFlag == "false" || reloadEnabledFlag == false) {
		$('div.reloadCard').hide();
	} else {
		// set the hidden fields
	   	document.forms["reloadCardForm"].elements["existingBalance"].value=gcBalanceVal
	   	document.forms["reloadCardForm"].elements["giftCardNumber"].value=gcNumberVal;
		document.forms["reloadCardForm"].elements["giftCardPinNumber"].value=gcPinVal;
		document.forms["reloadCardForm"].elements["giftCardCatEntryId"].value=catentryId;
		document.forms["reloadCardForm"].elements["giftCardStoreId"].value=storeId;	
		document.forms["reloadCardForm"].elements["giftCardCatalogId"].value=catalogId;
		$('div.reloadCard').show();
		
		// Display error message if this page is being displayed on Add to cart server side validation failure
		// 'AMOUNTINVALID' will be returned as response code if thats the case
		if(responseCode == 'AMOUNTINVALID' || responseCode == 'EXSITINGBALANCEINVALID') {
			var gc_errReloadDiv = $('div.reloadErrorReload');
			var gc_reloadFld = $('form#reloadCard input.reload');
			var errorMessage= errorMessageForResponse;
			$(gc_errReloadDiv).text(errorMessage).show();
			$(gc_reloadFld).css({border:'1px solid #cc1a0d',padding:'1px'});
			
			//DHTML LAYER height adjustment, if not available on pg, below degrades.
			if(!$.browser.msie){$('#DHTMLwrap').height($('#DHTMLcontent').height()+8);}
			else{$('#DHTMLwrap').height($('#DHTMLcontent').height()+10);}
		}
	}
}
$(function(){
	newGCvalidation();
});

// Function to trim the white spaces from the right side of a string 
function rtrim (s){
	
   return s.replace( /\s*$/, "" );
}
// Function to trim the white spaces from the left side of a string
function ltrim ( s ){
	
  return s.replace( /^\s*/, "" );
}

