// Javascript Main Library File
// Written by H. del Risco

// Create cookie and save value, will not set expiration if 'expires' is null
function setCookie(name, value, expires)
{
	document.cookie = name + "=" + escape(value) + "; path=/" + ((expires == null) ? "" : "; expires=" + expires.toGMTString());
}

// Create cookie with default expiration and save value
function setCookieExp(name, value, expires)
{
	var exp = new Date()
	exp.setTime(exp.getTime() + (20 * 60 * 1000));
	document.cookie = name + "=" + escape(value) + "; path=/" + "; expires=" + exp.toGMTString();
}

// Get cookie value
function getCookieValue(name)
{
	var cval = null;
	var valname = name + "=";
	var cookies = document.cookie;
	if (cookies.length > 0)
	{
		// get start of cookie value string
		var begin = cookies.indexOf(valname);
		if (begin != -1)
		{
			// find end of string and retrieve it
			begin += valname.length;
			var end = cookies.indexOf(";", begin);
			if (end == -1)
				end = cookies.length;
			cval = unescape(cookies.substring(begin, end));
      }
   }

   return cval;
}

// delete cookie by setting as expired
function deleteCookie(name)
{
   document.cookie = name + "=; expires=Thu, 01-Jan-70 00:00:01 GMT" + "; path=/";
}

// refresh order cookies if available
function refreshOrderCookies()
{
	var items;
	
	// refresh member information
	items = getCookieValue("ONE800GCMEMBERINFO");
	if(items != null && items.length != 0)
		setCookieExp("ONE800GCMEMBERINFO", items);

	// refresh order information
	items = getCookieValue("ONE800GCORDERINFO");
	if(items != null && items.length != 0)
		setCookieExp("ONE800GCORDERINFO", items);

	// refresh order items
	items = getCookieValue("ONE800GCORDERS");
	if(items != null && items.length != 0)
		setCookieExp("ONE800GCORDERS", items);

	// refresh address information
	items = getCookieValue("ONE800GCADDRINFO");
	if(items != null && items.length != 0)
		setCookieExp("ONE800GCADDRINFO", items);

	// refresh recipients list
	items = getCookieValue("ONE800GCRECIPIENTS");
	if(items != null && items.length != 0)
		setCookieExp("ONE800GCRECIPIENTS", items);
}

// refresh sign-in cookie if available
function refreshSigninCookie()
{
	var items;
	
	// refresh member information
	items = getCookieValue("ONE800GCMEMBERINFO");
	if(items != null && items.length != 0)
		setCookieExp("ONE800GCMEMBERINFO", items);
}

// check if signed-in
function isSignin()
{
	var items;
	var bSignin = false;
	
	// get member information
	items = getCookieValue("ONE800GCMEMBERINFO");
	if(items != null && items.length != 0)
		bSignin = true;
	return bSignin;
}

// delete order cookies if available, leave recipients
function deleteOrderCookies()
{
	// delete order information
	deleteCookie("ONE800GCORDERINFO");

	// delete order items
	deleteCookie("ONE800GCORDERS");

	// delete address information
	deleteCookie("ONE800GCADDRINFO");
	
	// delete address information
	deleteCookie("ONE800GCRECIPIENTS");
}

// strip leading and trailing spaces from given field, return new string
function fldTrim(fld)
{
	var chr;
	var count;
	var str = "";

	// skip past any leading blanks
	for (count = 0; count < fld.value.length; count++)
	{
		chr = fld.value.substring (count, count+1);
		if(chr != ' ')
	        break;
	}

	// check if any characters left
	if (count < fld.value.length)
	{
		var strIdx = count;

		// skip past any leading blanks
		for (count = (fld.value.length - 1); count > strIdx; count--)
		{
			chr = fld.value.substring (count, count+1);
			if(chr != ' ')
	    	    break;
		}
		str = fld.value.substring(strIdx, count+1);
	}

	// return trimmed string
	return str;
}

// check if valid name string, must have trimmed
// Ex: JohnABC, del monte, O'reilly, smith-barney
function fldIsValidName(fld)
{
	var chr;
	var rc = false;

	// check all characters, spaces allowed
	for (var count = 0; count < fld.value.length; count++)
	{
		chr = fld.value.substring (count, count+1);
		if(chr < 'A' || chr > 'Z')
		{
			if(chr < 'a' || chr > 'z')
			{
				// allow space, single quote and dash
				if(chr != ' ' && chr != '-' && chr != "'" && chr != ".")
					break;
			}
		}
	}

	if(count && count >= fld.value.length)
		rc = true;
	return rc;
}

// check if valid unsigned number, must have removed leading or trailing spaces
// Ex: 23, 22.475
function fldIsValidNumber(fld)
{
	var chr;
	var period = false;
	var rc = false;

	// check all characters
	for (var count = 0; count < fld.value.length; count++)
	{
		chr = fld.value.substring (count, count+1);
		if(chr < '0' || chr > '9')
		{
			// allow period
			if(chr != '.')
				break;
			else
			{
				if(period)
			        break;
				else
					period = true;
			}
		}
	}

	if(count && count >= fld.value.length)
		rc = true;
	return rc;
}

// check if valid unsigned integer, must have removed leading or trailing spaces
// Ex: 23, 0, 1456
function fldIsValidInteger(fld)
{
	var chr;
	var rc = false;

	// check all characters
	for (var count = 0; count < fld.value.length; count++)
	{
		chr = fld.value.substring (count, count+1);
		if(chr < '0' || chr > '9')
			break;
	}

	if(count && count >= fld.value.length)
		rc = true;
	return rc;
}

// check if valid zip code, must have removed leading or trailing spaces
// Ex: 12345, 12345-6789, 12345 6789, 123456789
function fldIsValidZipCode(fld)
{
	var chr;
	var dashCnt = 0;
	var dashIdx = 0;
	var spaceCnt = 0;
	var spaceIdx = 0;
	var rc = false;

	// check all characters
	for (var count = 0; count < fld.value.length; count++)
	{
		chr = fld.value.substring (count, count+1);
		if(chr < '0' || chr > '9')
		{
			if(chr == '-')
			{
				dashCnt++;
				dashIdx = count;
			}
			else
			{
				if(chr == ' ')
				{
					spaceCnt++;
					spaceIdx = count;
				}
				else
					break;
			}
		}
	}

	if(count && count >= fld.value.length)
	{
		if(dashCnt == 0 && spaceCnt == 0)
		{
			if(fld.value.length == 5 || fld.value.length == 9)
				rc = true;
		}
		else
		{
			if(dashCnt == 1)
			{
				if(spaceCnt == 0 && dashIdx == 5 && fld.value.length == 10)
					rc = true;
			}
			else
			{
				if(spaceCnt == 1)
				{
					if(dashCnt == 0 && spaceIdx == 5 && fld.value.length == 10)
						rc = true;
				}
			}
		}
	}

	return rc;
}

// remove non-numeric values from string
function stripNonNumeric(strIn)
{
	var chr;
	var strOut = "";

	// check all characters
	for (var count = 0; count < strIn.length; count++)
	{
		chr = strIn.substring (count, count+1);
		if(chr >= '0' && chr <= '9')
			strOut = strOut + chr;
	}

	return strOut;
}

// check if text contains internally used delimiters
function containsDelimiters(strTxt)
{
	var chr;
	var bContains = false;

	// check all characters
	for (var count = 0; count < strTxt.length; count++)
	{
		chr = strTxt.substring (count, count+1);
		if(chr == "|" || chr == "~" || chr == "\\" || chr == "-" || chr == '"')
		{
			bContains = true;
			break;
		}
	}

	return bContains;
}

function isValidEmailAddress(emailAddr)
{
	var bValid = false;
	//[Start] Ravi S Veluvali : 26-Dec-07 : Added code to use Regular functions and validate email address instead of old one which is failing when you entere 2 '@' in address.
	var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	bValid = filter.test(emailAddr);

	/*if(emailAddr.indexOf(".", 0) != -1 && emailAddr.indexOf("@", 0) != -1 && emailAddr.indexOf(' ', 0) == -1)
		bValid = true;*/
	//[End] Ravi S Veluvali : 26-Dec-07 : Added code to use Regular functions and validate email address instead of old one which is failing when you entere 2 '@' in address.
	
	return bValid;
}

// validate date fields
function validate_date(date_field, desc) {
        if (!date_field.value)  
                return true;
        var in_date = stripCharString(date_field.value," ");
        in_date = in_date.toUpperCase();
        var date_is_bad = 0;  
        if (!allowInString(in_date,"/0123456789T+-"))
                date_is_bad = 1; // invalid characters in date
        if (!date_is_bad) { 
                var has_rdi = 0;
                if (in_date.indexOf("T") >= 0){ 
                        has_rdi = 1;
                }
                if (!date_is_bad && has_rdi && (in_date.indexOf("T") != 0)) { 
                        date_is_bad = 2; // relative date index character is not in first position
                }
                if (!date_is_bad && has_rdi && (in_date.length == 1)) { 
                        var d = new Date();
						var return_month = parseInt(d.getMonth() + 1).toString();
						return_month = (return_month.length==1 ? "0" : "") + return_month; 
						var return_date =  parseInt(d.getDate()).toString();
						return_date = (return_date.length==1 ? "0" : "") + return_date; 
				        in_date = return_month + "/" + return_date + "/" + get_full_year(d);		
                        has_rdi = 0; // date doesn't have rdi char anymore (will also cause failure of add'l rdi checks, which is a good thing)
                }
                if (!date_is_bad && has_rdi && (in_date.length > 1) && !(in_date.charAt(1) == "+" || in_date.charAt(1) == "-")) {
                        date_is_bad = 3; // length of rdi string is greater than 1 but second char is not "+" or "-"
                }
                if (!date_is_bad && has_rdi && isNaN(parseInt(in_date.substring(2,in_date.length),10))) {
                        date_is_bad = 4; // rdi value is not a number
                }
                if (!date_is_bad && has_rdi && (parseInt(in_date.substring(2,in_date.length),10) < 0)) {
                        date_is_bad = 5; // rdi value is not a positive integer
                }
                if (!date_is_bad && has_rdi) {
                        var d = new Date();
                        ms = d.getTime();
                        offset = parseInt(in_date.substring(2,in_date.length),10);
                        if(in_date.charAt(1) == "+") {
                                ms += (86400000 * offset);
                        } else {
                                ms -= (86400000 * offset);
                        }
                        d.setTime(ms);
						var return_month = parseInt(d.getMonth() + 1).toString();
						return_month = (return_month.length==1 ? "0" : "") + return_month; 
						var return_date =  parseInt(d.getDate()).toString();
						return_date = (return_date.length==1 ? "0" : "") + return_date; 
				        in_date = return_month + "/" + return_date + "/" + get_full_year(d);	
                        has_rdi = 0;
                }
        } 
        if (!date_is_bad) {
                var date_pieces = new Array();
                date_pieces = in_date.split("/");
                if (date_pieces.length == 2) {
                        var d = new Date();
                        in_date = in_date + "/" + get_full_year(d);
                        date_pieces = in_date.split("/");
                }
                if (date_pieces.length != 3 || parseInt(date_pieces[0],10) < 1 || parseInt(date_pieces[0],10) > 12 
                                || parseInt(date_pieces[1],10) < 1 || parseInt(date_pieces[1],10) > 31 
                                || (date_pieces[2].length != 2 && date_pieces[2].length != 4)) {
                        date_is_bad = 6;  // date is not in format of m[m]/d[d]/yy[yy]
                }
        }
        if (date_is_bad) {
                alert(desc + " must be in the format of mm/dd/yy, mm/dd/yyyy, t, t+n or t-n.");
                date_field.focus();
                return (false);
        }
        
        var ms = Date.parse(in_date);
        var d = new Date();
        d.setTime(ms);
		var return_date = d.toLocaleString();
		var return_month = parseInt(d.getMonth() + 1).toString();
		return_month = (return_month.length==1 ? "0" : "") + return_month; 
		var return_date =  parseInt(d.getDate()).toString();
		return_date = (return_date.length==1 ? "0" : "") + return_date; 
        return_date = return_month + "/" + return_date + "/" + get_full_year(d);
        date_field.value = return_date;
        return true;
}

// normalize the year to yyyy
function get_full_year(d) {
		var y = ""
		if (d.getFullYear() != null)
		{
			y = d.getFullYear();
			if (y < 1970) y+= 100;		
		} else
		{	
	        y = d.getYear();
	        if (y > 69  && y < 100) y += 1900;
	        if (y < 1000) y += 2000;
		}
        return y;
}

function stripCharString (InString, CharString)  {
        var OutString="";
   for (var Count=0; Count < InString.length; Count++)  {
        var TempChar=InString.substring (Count, Count+1);
      var Strip = false;
      for (var Countx = 0; Countx < CharString.length; Countx++) {
        var StripThis = CharString.substring(Countx, Countx+1)
         if (TempChar == StripThis) {
                Strip = true;
            break;
         }
      }
      if (!Strip)
        OutString=OutString+TempChar;
   }
        return (OutString);
}
function allowInString (InString, RefString)  {
        if(InString.length==0) return (false);
        for (var Count=0; Count < InString.length; Count++)  {
        var TempChar= InString.substring (Count, Count+1);
      if (RefString.indexOf (TempChar, 0)==-1)  
        return (false);
   }
   return (true);
}