/*******************************/
/* GLOBAL VARIABLE DECLARATION */
/*******************************/

var sDivision, sStoreNum, sCheckNum, sYear, sCheckDays;		//used to store values of RL parts
var sString1Base10 = 0; 					//used to store converted string1
var sString2Base10 = 0; 					//used to store converted string2
var i = 1; 							//used for certificate failures
//var CHECK_DAYS_OLD = 3; 					//used to determine the life of checkdays
var CHECK_DAYS_OLD = 7; 					//modified on Aug 23, 2006
var MIN_CHECK_NUM = 1;						//minimum check number
var MIN_STORE_NUM = 0;						//min store number
var MAX_STORE_NUM = 2000;					//max store number //changed to 2000 as per Martin Sloan's spec
var validRL = false;						//stores status of RL validity
var strDiv = "02|05|09|17|19|23|25|31";				//valid division numbers
var CalDate = "";						//used to store visit date
var ShortVisitDate = "";
var certcode = "";
var oCertcode = "";						//used to store old certcode
var code1, code2, code3;

//test code: 003uuh000fk1
//test code: 003u uh00 0fk1


function sendmail()
{
	document.form1.action="sendmail.jsp";
	document.form1.submit();
}

function validate()
{
	/*
	if (i==3)
	{
		document.form1.action = "../Email/EmailErrorPage.jsp?callingPage="+document.URL+"";
		document.form1.submit();
	}
	*/

	//check length of certificate
	var result = true;
	code1 = document.form1.tf_code1.value;
	code2 = document.form1.tf_code2.value;
	code3 = document.form1.tf_code3.value;
	certcode = "" + code1 + code2 + code3;
	document.form1.certcheck.value = certcode;
	storecd = "";
	checkcd = "";

	if (certcode.length != 12 || (certcode.substring(0,1) != '0' && certcode.substring(0,1).toUpperCase() != 'O'))
	{	
                if (i!=3)
		{
			if(certcode.length != 12)
			{               
				alert("This appears to be an invalid personal code.  Please check to ensure that the following are verified:\n\n\t- Ensure that the receipt you are attempting to use is no more than 4 days old\n\t- Check that cookies are enabled on your computer\n\t- Check that you are not using a firewall program such as ZoneAlarm\n\t- Confirm that you have properly typed in the code from your receipt");
				if(code1.length != 4)
					document.form1.tf_code1.select();
				else if(code2.length != 4)
					document.form1.tf_code2.select();
				else if(code3.length != 4)
					document.form1.tf_code3.select();
			}
			else if (certcode.substring(0,1) != '0' && certcode.substring(0,1).toUpperCase() != 'O')
			{
				alert("This appears to be an invalid personal code.  Please check to ensure that the following are verified:\n\n\t- Ensure that the receipt you are attempting to use is no more than 4 days old\n\t- Check that cookies are enabled on your computer\n\t- Check that you are not using a firewall program such as ZoneAlarm\n\t- Confirm that you have properly typed in the code from your receipt");
				document.form1.tf_code1.select();
			}
		}
		result = false;
                i+=1;
	}
	else
	{
		//create old certcode variable
		oCertcode = certcode;
		
		//convert and validate record locator
		certcode = convertRLocator(certcode);

		checkcd = reversestring(certcode.substr(8,4));

		storecd = reversestring(certcode.substr(3,4));
		
		//validate certcode
		validRL = validateRecordLocator();

		if(!validateRecordLocator())
		{
			alert("This appears to be an invalid certificate code.  Please check to ensure that the following are verified:\n\n\t- Ensure that the receipt you are attempting to use is no more than 4 days old\n\t- Check that cookies are enabled on your computer\n\t- Check that you are not using a firewall program such as ZoneAlarm\n\t- Confirm that you have properly typed in the code from your receipt");
			document.form1.tf_code1.select();
			document.form1.certcheck.value = oCertcode;
			result = false;
			i+=1;
		}
		else
			result = true;
	}

	if(result || certcode.toUpperCase() == "003UUH000FK1")
	{
		//proceed to survey
		document.form1.action = "readSurveyCookie.jsp?certcode="+ certcode +"&oc="+oCertcode +"&storenum="+storecd +"&check="+checkcd +"&svd="+ ShortVisitDate +"&CalDate="+ CalDate;

		document.form1.submit();
	}
}

function reversestring(inputstr)
{
	// Function to reverse all characters in a string.
	var newString = '';
	for (var i=(inputstr.length - 1); i>=0; i--)
	{
		newString += inputstr.charAt(i);
	}
	return (newString);

}

function calculateJD(calendarDate)
{
	cdDate = new Date(calendarDate)

	//get year
	year = cdDate.getYear()          //added + 1900 10/03/2003
	if (year < 1000 ) {year+=1900}  // modified 10/03/2003
					// year = 1900+cdDate.getYear()
	//get month
	month = cdDate.getMonth() + 1 //getMonth() returns 0-11

	//get date
	day = cdDate.getDate()

	//get time
	hour = cdDate.getHours()
	min = cdDate.getMinutes()
	sec = cdDate.getSeconds()
	univTime = hour+(min/60)+(sec/3600)

	if ((100*year+month-190002.5) >= 0) {sign = 1}
	else {sign = -1}

	with (Math)
	{
		part1 = 367 * year
		part2 = floor((7*(year+floor((month+9)/12)))/4)
		part3 = day+floor((275*month)/9)
		part4 = 1721013.5+(univTime/24)
		part5 = 0.5*sign
		jd = part1-part2+part3+part4-part5+0.5
   	}
   	return jd
}

function calculateCD(julianDate)
{
	with (Math)
	{
		X = parseFloat(julianDate)+0.5
		Z = floor(X)
		F = X - Z
		Y = floor((Z-1867216.25)/36524.25)
		A = Z+1+Y-floor(Y/4)
		B = A+1524
		C = floor((B-122.1)/365.25)
		D = floor(365.25*C)
		G = floor((B-D)/30.6001)
		month = (G<13.5) ? (G-1) : (G-13)
		year = (month<2.5) ? (C-4715) : (C-4716)
		month -= 1 // month in JavaScript is from 0 to 11
		UT = B-D-floor(30.6001*G)+F
		day = floor(UT)
		UT -= floor(UT)
		UT *= 24;
		hour = floor(UT)
		UT -= floor(UT)
		UT *= 60
		minute = floor(UT)
		UT -= floor(UT)
		UT *= 60
		second = round(UT)
	}
	cdDate = new Date(Date.UTC(year, month, day, hour, minute, second))
	return cdDate.toGMTString()
}

function calculateShortCD(julianDate)
{
	with (Math)
	{
		X = parseFloat(julianDate)+0.5
		Z = floor(X)
		F = X - Z
		Y = floor((Z-1867216.25)/36524.25)
		A = Z+1+Y-floor(Y/4)
		B = A+1524
		C = floor((B-122.1)/365.25)
		D = floor(365.25*C)
		G = floor((B-D)/30.6001)
		month = (G<13.5) ? (G-1) : (G-13)
		year = (month<2.5) ? (C-4715) : (C-4716)
		month -= 1 // month in JavaScript is from 0 to 11
		UT = B-D-floor(30.6001*G)+F
		day = floor(UT)
		UT -= floor(UT)
		UT *= 24;
		hour = floor(UT)
		UT -= floor(UT)
		UT *= 60
		minute = floor(UT)
		UT -= floor(UT)
		UT *= 60
		second = round(UT)
	}
	da = new Date(Date.UTC(year, month, day, hour, minute, second))
	
dy = da.getFullYear()
dm = da.getMonth() + 1
dd = da.getDate() + 1
if ( dy < 1970 ) dy = dy + 100;
ys = new String(dy)
ms = new String(dm)
ds = new String(dd)
if ( ms.length == 1 ) ms = "0" + ms;
if ( ds.length == 1 ) ds = "0" + ds;
ShortVisitDate = ms + "/" + ds + "/" + dy

	return ShortVisitDate

}

function calculatePhase(tom, period, today)
{
	var phase
	with (Math)
	{
		phase = (today-tom)/period
		phase = phase-floor(phase)
   	}
	return phase
}

function reverse(inputString)
{
	// Function to reverse all characters in a string.
	var newString = '';
	for (var i=(inputString.length - 1); i>=0; i--)
	{
		newString += inputString.charAt(i);
	}
	return (newString);
}


function replaceIt(sString, sReplaceThis, sWithThis) 
{ 
	if (sReplaceThis != "" && sReplaceThis != sWithThis) 
	{ 
		var counter = 0; 
		var start   = 0; 
		var before  = ""; 
		var after   = ""; 
		while (counter<sString.length) 
		{ 
			start = sString.indexOf(sReplaceThis, counter); 
			if (start == -1) 
			{ 
				break; 
			} 
			else 
			{
				before  = sString.substr(0, start); 
				after   = sString.substr(start + sReplaceThis.length, sString.length); 
				sString = before + sWithThis + after; 
				counter = before.length + sWithThis.length; 
			} 
		} 
	} 
	return sString; 
}

function zeroPad(oString,tLength)
{
	var nString = oString;
	if(oString.length < tLength)
	{
		for(var i=oString.length;i<tLength;i++)
			nString = "0"+nString;
	}
	return nString;
}

function convertRLocator(sRLocator)
{
	var sString1, sString2;
	var sDecryptedCode = sRLocator.toUpperCase();

	/*******************************************************************
		Replace O with 0 because 0 will not exist in RL
		Replace B with 8 because B will not exist in encrypted RL
		Replace I with 1 because I will not exist in RL
	*******************************************************************/

	sDecryptedCode = replaceIt(sDecryptedCode, 'O', '0');
	sDecryptedCode = replaceIt(sDecryptedCode, 'B', '8');
	sDecryptedCode = replaceIt(sDecryptedCode, 'I', '1');

	/*******************************************************************
		Replace Z with the letter O 
		Replace Y with zero (0)
		Replace W with I
		Replace X with B
	*******************************************************************/

	sDecryptedCode = replaceIt(sDecryptedCode, 'Z', 'O');
	sDecryptedCode = replaceIt(sDecryptedCode, 'Y', '0');
	sDecryptedCode = replaceIt(sDecryptedCode, 'W', 'I');
	sDecryptedCode = replaceIt(sDecryptedCode, 'X', 'B');

	sString1 = sDecryptedCode.substring(0, 6);
	sString2 = sDecryptedCode.substring(6);

	/*******************************************************************
		Division 	FirstSet	2nd char 	2 chars
		StoreNum 	FirstSet	4th char	4 chars
	
		CheckNum 	SecondSet	2nd char	4 chars
		Year 	    	SecondSet	6th char	1 char
		CheckDays 	SecondSet	7th char	3 chars
	*******************************************************************/

	sString1Base10 = zeroPad(String(parseInt(sString1, 32)),7);
	sString2Base10 = zeroPad(String(parseInt(sString2, 32)),9);

	//First Set
	sDivision    = String(parseInt(reverse(String(sString1Base10.substring(1, 3))), 10));
	sStoreNum    = String(parseInt(reverse(String(sString1Base10.substring(3))), 10));
	
	//Second Set
	sCheckNum  = reverse(String(sString2Base10.substring(1, 5)));
	sYear      = String(sString2Base10.substring(5, 6));
	sCheckDays = reverse(String(sString2Base10.substring(6)));

	CalDate = calculateCD( parseInt(sCheckDays, 10) -1 + calculateJD(new Date(parseInt('200' + sYear, 10), 0, 1)))
	CalShortDate = calculateShortCD( parseInt(sCheckDays, 10) -1 + calculateJD(new Date(parseInt('200' + sYear, 10), 0, 1)))
	return "" + sString1Base10 + sString2Base10;
}

function validateRecordLocator()
{	
	if(certcode.toUpperCase() == "003UUH000FK1")
		return true;
	else if(validateCheckDays(sCheckDays) && validateDivision(sDivision) && validateCheckNum(sCheckNum) && validateStoreNum(sStoreNum))
		return true;
	else
		return false;
}

function validateCheckDays(vCheckDays)
{
	var iCheckDays = parseInt(vCheckDays,10);	//parse check days into an int
	var currentDOY = getDayOfYear();	//current day of year
	var currentYear= getCurrentYear();	//current year
	var leapyear = false; 			//leap year flag
	
	//get calc for leapyear
	if(sYear%4 == 0)
		leapyear = true;

	//validate year
	if(iCheckDays < 0 || (leapyear && iCheckDays > 366) || (!leapyear && iCheckDays > 365))
		return false;

	//validate age of checkdays
	var ageCD = getTotalDays(currentYear,currentDOY) - getTotalDays(yearConverter(parseInt(sYear)),iCheckDays);
	
	if(ageCD > CHECK_DAYS_OLD)
		return false;
	else
		return true;
}

function validateDivision(vDivision)
{
	if(parseInt(vDivision) < 10)
		vDivision = "0" + vDivision;

	if(strDiv.indexOf(vDivision) < 0) return false;
	else return true;
}

function validateCheckNum(vCheckNum)
{
	if(vCheckNum < MIN_CHECK_NUM) return false;
	else return true;
}

function validateStoreNum(vStoreNum)
{
	if(parseInt(vStoreNum) < MIN_STORE_NUM || parseInt(vStoreNum) > MAX_STORE_NUM) return false;
	else return true;
}

function getDayOfYear()
{
	var today  = new Date();
	var day    = today.getDate();
	var month  = today.getMonth() + 1;
	var year   = yearConverter(today.getYear());
	var doy	   = 0;
	var daysInMonths = new Array();
	
	if(year%4 == 0)	//leapyear
		daysInMonths = new Array(0,31,29,31,30,31,30,31,31,30,31,30,31);
	else		//non-leapyear
		daysInMonths = new Array(0,31,28,31,30,31,30,31,31,30,31,30,31);
	
	//set daysInMonths
	for(var m=1;m<=month;m++)
	{
		doy = doy+daysInMonths[m-1];
	}
	
	return doy+day;
		
}

function yearConverter(y)
{
	var nYear = y;
	if(y < 1900)
		nYear = nYear + 2000;
	else if(y < 2000)
		nYear = nYear + 1900;
	return nYear;
}

function getCurrentYear()
{
	var today = new Date();
	var year  = yearConverter(today.getFullYear());
	return year;
}

function getTotalDays(tYears,doy)
{
	var rYears = tYears%4;				//remainder years
	var lYears = (tYears-rYears)*0.25;		//number of leap years
	var nYears = (tYears-rYears)*0.75+rYears;	//number of regular years (including remainder years)
	
	var totalDays = 0;				//total days in all the years
	totalDays  = (lYears*366)+(nYears*365)+doy	//leapyears x 366 + normalyears x 365 + doy
	return totalDays;
}

function getVisitDate()
{
	return CalDate;
}

function getShortVisitDate()
{
	return CalShortDate;
}


function certcheck()
{
	i = 1;
	var certcode = document.form1.rl_code.value;
	document.form1.tf_code1.value = certcode.substring(0,4);
	document.form1.tf_code2.value = certcode.substring(4,4);
	document.form1.tf_code3.value = certcode.substring(8,4);
	var rlstatus = false;

	if(certcode.length == 12)
	{
		convertRLocator(certcode);
		rlstatus = validateRecordLocator();

		if(rlstatus)
			alert("Cert valid!\n\nString 1: "+sString1Base10 +"\nString 2: "+sString2Base10+"\nDivision: "+sDivision+"\nStore Number: "+sStoreNum+"\nCheck Number: "+sCheckNum+"\nYear: "+sYear+"\nCheck Day: "+sCheckDays+"\nConverted Date: "+CalDate);
		else
			alert("Cert invalid!\n\nString 1: "+sString1Base10 +"\nString 2: "+sString2Base10+"\nDivision: "+sDivision+"\nStore Number: "+sStoreNum+"\nCheck Number: "+sCheckNum+"\nYear: "+sYear+"\nCheck Day: "+sCheckDays+"\nConverted Date: "+CalDate);
	}
	else
		alert("You did not enter a Record Locator.");
}