function dateAdd(startDate, numDays, numMonths, numYears)
{	
	cleanDate = new Date(startDate);	
	var returnDate = new Date(cleanDate.getTime());
	var yearsToAdd = numYears;
	
	var month = returnDate.getMonth() + numMonths;
	if (month > 11)
	{
		yearsToAdd = Math.floor((month+1)/12);
		month -= 12*yearsToAdd;
		yearsToAdd += numYears;
	}
	returnDate.setMonth(month);
	returnDate.setFullYear(returnDate.getFullYear()	+ yearsToAdd);
	returnDate.setTime(returnDate.getTime()+60000*60*24*numDays);

	// Get the month and year
	var month = returnDate.getMonth() + 1;
	var year = returnDate.getYear();

	// Get the day
	var strTemp = returnDate.toString();
	var splitArray = strTemp.split(' ');
	var day = splitArray[2];
	
	// Put together the date in formatted string format
	var strStringDate = month + '/' + day + '/' + year;
	
	return strStringDate;
}

function yearAdd(startDate, numYears)
{
	return DateAdd(startDate, 0, 0, numYears);
}

function monthAdd(startDate, numMonths)
{
	return DateAdd(startDate, 0, numMonths,0);
}

function dayAdd(startDate, numDays)
{
	return DateAdd(startDate, numDays, 0, 0);
}

/* Takes two strings that represents dates, and returns a boolean
   indicating whether or not the first date is after the second date. */
function isFirstDateEarlier(strDelimiter, strFirstDate, strSecondDate)
{
	var month;
	var day;
	var year;
	var splitArray;
	
	// Get the first date
	splitArray = strFirstDate.split(strDelimiter);
	month = splitArray[0];
	day = splitArray[1];
	year = splitArray[2];
	var firstDate = new Date(year, month - 1, day)

	// Get the second date
	splitArray = strSecondDate.split(strDelimiter);
	month = splitArray[0];
	day = splitArray[1];
	year = splitArray[2];
	var secondDate = new Date(year, month - 1, day)
	
	//alert(firstDate + '--------' + secondDate );
	
	if (firstDate <= secondDate)
	{
		return true;
	}
	else
	{
		return false;
	}
}

/* Takes two strings that represents dates, and returns a boolean
   indicating whether or not the first date is after the second date. */
function isFirstDateEarlierEuropean(strDelimiter, strFirstDate, strSecondDate)
{
	var month;
	var day;
	var year;
	var splitArray;
	
	// Get the first date
	splitArray = strFirstDate.split(strDelimiter);
	day = splitArray[0];
	month = splitArray[1];
	year = splitArray[2];
	var firstDate = new Date(year, month - 1, day)

	// Get the second date
	splitArray = strSecondDate.split(strDelimiter);
	day = splitArray[0];
	month = splitArray[1];
	year = splitArray[2];
	var secondDate = new Date(year, month - 1, day)
	
	if (firstDate <= secondDate)
	{
		return true;
	}
	else
	{
		return false;
	}
}

// Trim leading and trailing spaces
function trim(lstr) 
{
    return ltrim(rtrim(stripLineFeed(lstr)));
}

function stripLineFeed(strText)
{
	var strReturnText = strText;
	var flgContinue = true;

    if(strReturnText != null)
    {
	// Only check if the string passed in has a length greater than zero	
	if (strReturnText.length > 0)
	{
		// Loop as long as the last character is either a line feed or a carriage return
		while (flgContinue == true)
		{
			// If the last character is either a backspace or a line feed, strip it off
			if (strReturnText.charAt(strReturnText.length - 1) == '\n' || strReturnText.charAt(strReturnText.length - 1) == '\r')
			{
				strReturnText = strReturnText.substr(0, strReturnText.length - 1);
			}
			else
			{
				// If the last character is not a carriage return or line feed, stop looping
				flgContinue = false;
			}
		}
	}
	}

	return strReturnText;
}
  
//  This function trims all spaces from the left-hand side of a string.
function ltrim(lstr) 
{
	if (lstr != "" && lstr != null) 
	{
		var strlen, cptr, lpflag, chk;
		strlen = lstr.length;
		cptr = 0;
		lpflag = true;

		do 
		{
			chk = lstr.charAt(cptr);
            if (chk != " ") 
            {
				lpflag = false;
			}
            else 
            {
                if (cptr == strlen) 
                {
					lpflag = false;
				}
                else 
                {
					cptr++;
				}
			}
		}
        
        while (lpflag == true)
		if (cptr > 0) 
		{
			lstr = lstr.substring(cptr,strlen);
		}
	}
	
	return lstr;
}

//  This function trims all spaces from the right-hand side of a string.
function rtrim(lstr) 
{
	if (lstr != "" && lstr != null) 
	{
		var strlen, cptr, lpflag, chk;
		strlen = lstr.length;
		cptr = strlen;
		lpflag = true;

		do 
		{
			chk=lstr.charAt(cptr-1);
			if (chk != " ") 
			{
			    lpflag = false;
			}
			else 
			{
				if (cptr == 0) 
				{
					lpflag = false;
				}
				else 
				{
				    cptr--;
				}
			}
		}

        while (lpflag == true)
        if (cptr < strlen) 
        {
			lstr = lstr.substring(0, cptr);
		}
	}
    
    return lstr;
}

// ******************************************************************
// This function accepts a string variable and verifies if it is a
// proper date or not. It validates format matching mm.dd.yyyy, 
// mm-dd-yyyy or mm/dd/yyyy. Then it checks to make sure the month
// has the proper number of days, based on which month it is.

// The function returns true if a valid date, false if not.
// ******************************************************************
function isDate(dateStr) {

    var datePat = /^(\d{1,2})(\/|-|.)(\d{1,2})(\/|-|.)(\d{4})$/;
    var matchArray = dateStr.match(datePat); // is the format ok?

    if (matchArray == null) {
        alert("Please enter date as either mm/dd/yyyy or mm-dd-yyyy.");
        return false;
    }

    month = matchArray[1]; // parse date into variables
    day = matchArray[3];
    year = matchArray[5];

    if (month < 1 || month > 12) { // check month range
        alert("Month must be between 1 and 12.");
        return false;
    }

    if (day < 1 || day > 31) {
        alert("Day must be between 1 and 31.");
        return false;
    }

    if ((month==4 || month==6 || month==9 || month==11) && day==31) {
        alert("Month "+month+" doesn't have 31 days!")
        return false;
    }

    if (month == 2) { // check for february 29th
        var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
        if (day > 29 || (day==29 && !isleap)) {
            alert("February " + year + " doesn't have " + day + " days!");
            return false;
        }
    }
    return true; // date is valid
}

// ******************************************************************
// This function accepts a string variable and verifies if it is a
// proper European date or not. It validates format matching dd.mm.yyyy,
// dd-mm-yyyy, or dd/mm/yyyy. Then it checks to make sure the month
// has the proper number of days, based on which month it is.

// The function returns true if a valid date, false if not.
// ******************************************************************
function isDateEuropean(dateStr) {

    var datePat = /^(\d{1,2})(\/|-|.)(\d{1,2})(\/|-|.)(\d{4})$/;
    var matchArray = dateStr.match(datePat); // is the format ok?

    if (matchArray == null) {
        alert("Please enter date as either dd/mm/yyyy or dd-mm-yyyy or dd.mm.yyyy.");
        return false;
    }

    day = matchArray[1]; // parse date into variables
    month = matchArray[3];
    year = matchArray[5];

    if (month < 1 || month > 12) { // check month range
        alert("Month must be between 1 and 12.");
        return false;
    }

    if (day < 1 || day > 31) {
        alert("Day must be between 1 and 31.");
        return false;
    }

    if ((month==4 || month==6 || month==9 || month==11) && day==31) {
        alert("Month "+month+" doesn't have 31 days!")
        return false;
    }

    if (month == 2) { // check for february 29th
        var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
        if (day > 29 || (day==29 && !isleap)) {
            alert("February " + year + " doesn't have " + day + " days!");
            return false;
        }
    }
    return true; // date is valid
}


/* Takes two strings that represents numbers, and returns a boolean
   indicating whether or not the first number is larger than the second number */
function isFirstNumberLarger(strFirst, strSecond)
{
	var lngFirst = parseFloat(strFirst);
	var lngSecond = parseFloat(strSecond);
	var flgReturnValue = false;
	//alert(lngFirst + "---" + lngSecond);
	// If the first number is greater than the second number
	if (lngFirst > lngSecond)
	{
		flgReturnValue = true;
	}
	
	return flgReturnValue;
}


/*	The isNumeric function validates a string to determine whether or not it contains a numeric value.
	Parameters: lstr - Contains string value to validate
	Returns: true/false  */
function isNumeric(lstr) 
{
	lstr = rtrim(lstr);
	if (lstr != "" && lstr != null) 
	{
		//declare local variables
		var strlen, curptr, setptr, chk, inloop, decflag, minusflag, iserror;
		iserror = false;
		decflag = false;
		minusflag = false;
		strlen = lstr.length;
		curptr = 0;
		chk;
		// first check for space - .
		inloop = true;
		for (curptr = 0; curptr < strlen; curptr++) 
		{
			chk = lstr.charAt(curptr);
			if (chk >= "0" && chk <= "9")
			{
				break;
			}
			
			if (chk == "-") 
			{
				minusflag = true;
				break;
			}
			if (chk == ".") 
			{
				decflag = true;
				break;
			}
			if (chk != " ") 
			{
				return false;
			}
		}
		
		if (curptr >= strlen-1) 
		{
			if (decflag || minusflag || chk == " ") 
			{
				return false;
			}
			else 
			{
				return true;
			}
		}
		setptr = curptr + 1;
		for (curptr = setptr; curptr < strlen; curptr++) 
		{
			chk = lstr.charAt(curptr);
			if (chk < "0" || chk > "9") 
			{
				if (chk != ".") 
				{
					return false;
				}
				else
				{
					if (decflag) 
						{
							return false;
						}
					else 
					{
						decflag = true;
					}
				}
			}
		}
		return true;
	}
	return false;
}

// This routine takes a string parameter and return true/false, indicating whether or not the string represents
// a valid hex color.  The string can optionally have a # sign at the beginning of it.
function isValidHexColor(strHexColor)
{
	var arrHexValues;
	var lngStartingPoint;
	var strChar;
	var i;
	var j;
	var flgValidCharacter;
	var lngNumberOfCharacters;

	// Initialize a string of all valid characters in a hex string
	arrHexValues = new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F");
	
	// The string must be either 6 or 7 characters long, depending on whether the # sign was use
	if (strHexColor.length != 6 && strHexColor.length != 7)
	{ 
		return false;
	}
	
	// If the string is 7 characters long, the first character must be a # sign
	if (strHexColor.length == 7 && strHexColor.charAt(0) != '#')
	{ 
		return false;
	}
	
	// Determine whether to start checking characters with the first or second character, 
	// depending on whether the first character is a pound sign
	if (strHexColor.length == 7)
	{
		lngStartingPoint = 1;
		lngNumberOfCharacters = 7;
	}
	else
	{
		lngStartingPoint = 0;
		lngNumberOfCharacters = 6;
	}

	// Loop through each character of the string (other than the possible initial # sign), and check
	// to see whether each character is a valid hex character.  If not, return false.
	for (i = lngStartingPoint; i < lngNumberOfCharacters; i++)
	{
		strChar = strHexColor.charAt(i);
		strChar = strChar.toUpperCase();
		flgValidCharacter = false;

		// After extracting the next character in the string, loop through the array of valid
		// hex values to see if there's a match.
		for (j = 0; j < arrHexValues.length; j++) 
		{
			if (strChar == arrHexValues[j])
			{
				flgValidCharacter = true;
			}
		}
		
		// If the current character was not in the list of valid hex characters, the flag will be set to 
		// false.  In that case, return false.
		if (flgValidCharacter == false)
		{
			return false;
		}
	}

	// At this point, all conditions have been checked, so it must be a valid hex color string.
	return true;
}

// This function verifies that an email conforms to RFC 822 email address standard
function isValidEmailAddress(strEmail) 
{
    if (strEmail == null || strEmail == "") 
    {
        return false;
    }
    else 
    {
        // Patterns
        var emailPat=/^(.+)@(.+)$/
        var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
        var validChars="\[^\\s" + specialChars + "\]"
        var quotedUser="(\"[^\"]*\")"
        var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
        var atom=validChars + '+'
        var word="(" + atom + "|" + quotedUser + ")"
        var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
        var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")

        var matchArray = strEmail.match(emailPat)
        if (matchArray == null) 
        {
	        return false;
        }

        var user = matchArray[1]
        var domain = matchArray[2]

        // See if "user" is valid 
        if (user.match(userPat) == null) 
        {
            // user is not valid
			return false;
		}

        var IPArray = domain.match(ipDomainPat)
        if (IPArray!=null) 
        {
			// this is an IP address
			for (var i=1;i<=4;i++) 
			{
				if (IPArray[i]>255) 
				{
			        return false;
				}
			}
        }

        // Domain is symbolic name
        var domainArray = domain.match(domainPat)
        if (domainArray == null) 
        {
	        return false;
        }

        // Now we need to break up the domain to get a count of how many atoms it consists of.
        var atomPat = new RegExp(atom,"g")
        var domArr = domain.match(atomPat)
        var len = domArr.length
        if (domArr[domArr.length-1].length < 2 || domArr[domArr.length-1].length > 4) 
        {
           // the address must end in a two, three, or four letter word.
	        return false;
        }

        // Make sure there's a host name preceding the domain.
        if (len < 2) 
        {
	        return false;
        }
    }

    return true;
}

function isAlphaNumeric(strText)
{
	// Check each letter to make sure it's a letter or a number
	for (var i = 0; i < strText.length; i++)
	{
		if ((strText.charAt(i) < '0' || strText.charAt(i) > '9') && (strText.charAt(i) < 'a' || strText.charAt(i) > 'z') && (strText.charAt(i) < 'A' || strText.charAt(i) > 'Z'))
		{
			return false;
		}
	}

	return true;
}

function isValidIPAddress(strIPAddress)
{
	var VALID_FORMAT = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
	if (VALID_FORMAT.test(strIPAddress)) 
	{
		var strParts = strIPAddress.split(".");
		if (parseInt(parseFloat(strParts[0])) == 0) { return false; }
		for (var i = 0; i < strParts.length; i++) 
		{
			if (parseInt(parseFloat(strParts[i])) > 255) { return false; }
		}

		return true;
	}
	else
	{
		return false;
	}
}

function keySupress()
{

	if(event.keyCode == 13)
		return false;
	else
		return true;
}

function startClock()
{
dWatch = 0;
dStarted = new Date();
}
function updateClock(iTimeOutAlert)
{
setTimeout("updateClock('" + iTimeOutAlert + "');", 100);
dNow = new Date();
dWatch = dNow.getTime() - dStarted.getTime();
dClock = Math.round(dWatch/1000);
if (dClock == iTimeOutAlert)
{
alert("Warning!\n\nYour session will expire in 5 minutes.\nSave your work immediately so it is not lost.");
//window.location.href = "loginpage.aspx";
}
}

		
function createElementFunction()
{
    // Detect IE using conditional compilation
    if (/*@cc_on @*//*@if (@_win32)!/*@end @*/false)
    {
        // Translations for attribute names which IE would otherwise choke on
        var attrTranslations =
        {
            "class": "className",
            "for": "htmlFor"
        };

        var setAttribute = function(element, attr, value)
        {
            if (attrTranslations.hasOwnProperty(attr))
            {
                element[attrTranslations[attr]] = value;
            }
            else if (attr == "style")
            {
                element.style.cssText = value;
            }
            else
            {
                element.setAttribute(attr, value);
            }
        };

        return function(tagName, attributes)
        {
            attributes = attributes || {};

            // See http://channel9.msdn.com/Wiki/InternetExplorerProgrammingBugs
            if (attributes.hasOwnProperty("name") ||
                attributes.hasOwnProperty("checked") ||
                attributes.hasOwnProperty("multiple"))
            {
                var tagParts = ["<" + tagName];
                if (attributes.hasOwnProperty("name"))
                {
                    tagParts[tagParts.length] =
                        ' name="' + attributes.name + '"';
                    delete attributes.name;
                }
                if (attributes.hasOwnProperty("checked") &&
                    "" + attributes.checked == "true")
                {
                    tagParts[tagParts.length] = " checked";
                    delete attributes.checked;
                }
                if (attributes.hasOwnProperty("multiple") &&
                    "" + attributes.multiple == "true")
                {
                    tagParts[tagParts.length] = " multiple";
                    delete attributes.multiple;
                }
                tagParts[tagParts.length] = ">";

                var element =
                    document.createElement(tagParts.join(""));
            }
            else
            {
                var element = document.createElement(tagName);
            }

            for (var attr in attributes)
            {
                if (attributes.hasOwnProperty(attr))
                {
                    setAttribute(element, attr, attributes[attr]);
                }
            }

            return element;
        };
    }
    // All other browsers
    else
    {
        return function(tagName, attributes)
        {
            attributes = attributes || {};
            var element = document.createElement(tagName);
            for (var attr in attributes)
            {
                if (attributes.hasOwnProperty(attr))
                {
                    element.setAttribute(attr, attributes[attr]);
                }
            }
            return element;
        };
    }
}

function openWindowWithPost(url,name,keys,values)
{
    var newWindow = window.open(url, name); 
    if (!newWindow) return false;
    var html = "";
    html += "<html><head></head><body><form id='formid' method='post' action='" + url + "'>";
    if (keys && values && (keys.length == values.length))
    for (var i=0; i < keys.length; i++)
    html += "<input type='hidden' name='" + keys[i] + "' value='" + values[i] + "'/>";
    html += "</form><script type='text/javascript'>document.getElementById(\"formid\").submit()</script></body></html>";
    newWindow.document.write(html);
    return newWindow;
}

function postToURL(url, values)
{
    values = values || {};
    var createElement = createElementFunction();

    var form = createElement("form", {action: url,
                                      method: "POST",
                                      style: "display: none"});
    for (var property in values)
    {
        if (values.hasOwnProperty(property))
        {
            var value = values[property];
            
            if (value instanceof Array)
            {
                for (var i = 0, l = value.length; i < l; i++)
                {
                    form.appendChild(createElement("input", {type: "hidden",
                                                             name: property,
                                                             value: value[i]}));
                }
            }
            else
            {
                form.appendChild(createElement("input", {type: "hidden",
                                                         name: property,
                                                         value: value}));
            }
        }
    }
    
    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form);
}

// validates a number without commas
// entry = the value to validate
// numDecDigits = -1 -> validate unlimited decimal digits
//				= 0  -> validate no decimal digits allowed
//				= X  -> validates X number of decimal digits allowed
function validateNumericGeneral(entry, numDecDigits)
{
	var check;
    if (numDecDigits == 0)
        check = new RegExp("^[-+]?([0-9]+)?$");
    else if (numDecDigits > 0)
        check = new RegExp("^[-+]?([0-9]+)(\\.[0-9]{0," + numDecDigits + "})?$");
    else
        check = new RegExp("^[-+]?([0-9]+)(\\.[0-9]*)?$");
        
    // if there is a match, the result will be true
	return (check.exec(entry) != null);
}

// validates a number with 2 decimal digits and commas.  Money symbols are not allowed
function validateNumericMoney(entry)
{
	var check = new RegExp("^[-+]?([0-9]{1,3},([0-9]{3},)*[0-9]{3}|[0-9]+)(\\.[0-9][0-9])?$");
	
	// if there is a match, the result will be true
	return (check.exec(entry) != null);
}

// validates a number with commas
// entry = the value to validate
// numDecDigits = -1 -> validate unlimited decimal digits
//				= 0  -> validate no decimal digits allowed
//				= X  -> validates X number of decimal digits allowed
function validateNumeric(entry, numDecDigits)
{
	var check;
    if (numDecDigits == 0)
        check = new RegExp("^[-+]?([0-9]{1,3},([0-9]{3},)*[0-9]{3}|[0-9]+)?$");
    else if (numDecDigits > 0)
        check = new RegExp("^[-+]?([0-9]{1,3},([0-9]{3},)*[0-9]{3}|[0-9]+)(\\.[0-9]{0," + numDecDigits + "})?$");
    else
        check = new RegExp("^[-+]?([0-9]{1,3},([0-9]{3},)*[0-9]{3}|[0-9]+)(\\.[0-9]*)?$");

	// if there is a match, the result will be true       
	return (check.exec(entry) != null);
}

function stripMaskCharacters(id)
{
	// remove euro, dollar, comma, percent
	var val = document.getElementById(id).value;
	return trim(val.replace("€", "").replace("$", "").replace(",", "").replace("%", ""));
}

function ValidateMilitaryTime(entry, alertText)
{
    //checks and validates valid military time in format 00:00
    var objRegExp  = /^([0-1]?[0-9]|2[0-3])[:][0-5][0-9]$/;
    var  result = objRegExp.test(entry);
    if (result != true)
    {
        alert(alertText);
        return 1;
    }
    else
    {
        return 2;
    }
}

function ValidateTimeFormatOnly(entry, alertText)
{
    //only checks for 00:00 format does not validate time
    
    var objRegExp  = /^\d{1,2}:\d{2}$/;
    var  result = objRegExp.test(entry);
   if (result != true)
   {
        alert(alertText);
        return 1;
   }
   else
   {
        return 2;
   }
}

function ValidateCreditCardNumberFormat(entry, alertText)
{
    //4444-4444-4444-4444 with or with dashes or spaces separating
    var objRegExp  = /^(\d{4}-){3}|(\d{4}){3}d{4}|\d{15,16}|\d{4} \d{2} \d{4} \d{5}| \d{4}-\d{2}-\d{4}-\d{5}$/;
        var  result = objRegExp.test(entry);
   if (result != true)
   {
        alert(alertText);
        return 1;
   }
   else
   {
        return 2;
   }
}

function ValidateSerialNumberFormat(entry, alertText)
{
    //12  3456 789 with or with dashes or spaces separating

   var objRegExp  = /^\d{2} \d{4} \d{3} | \d{2}-\d{4}-\d{3}$/;
        var  result = objRegExp.test(entry);
   if (result != true)
   {
        alert(alertText);
        return 1;
   }
   else
   {
        return 2;
   }
}

function ValidateUSPhone(entry, alertText)
{
//check for valid us phone with or without space between
  //area code   Ex. (999) 999-9999 or (999)999-9999
    var objRegExp  = /^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/;
    var  result = objRegExp.test(entry);
   if (result != true)
   {
        alert(alertText);
        return 1;
   }
   else
   {
        return 2;
   }
    
}

function ValidateUSZip(entry, alertText)
{
//Validates that a string a United
 // States zip code in 5 digit format or zip+4
 // format. 99999 or 99999-9999

    var objRegExp  = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
        var  result = objRegExp.test(entry);
   if (result != true)
   {
        alert(alertText);
        return 1;
   }
   else
   {
        return 2;
   }
}

//function ValidateValueRegEx( entry, strMatchPattern, alertText )
function ValidateValueRegEx( entry, check, alertText )
{
    //Validates that a string a matches
    // a valid regular expression value.
    //var check = new RegExp( strMatchPattern);
   var result = check.test(entry);
   if (result != true)
   {
        alert(alertText);
        return 1;
   }
   else
   {
        return 2;
   }
   
     
     
     
}



