var error = false // global variable used to check if valid price entered
var inTextArea = false //	variable used by checkEnter to see whether the element is a text area in which the
					   //	enter key was pressed


// ******************************************************************
// This function accepts a string variable and verifies if it is a
// proper date or not. It validates format matching either
// 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{2,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;
        }
    }
    if (year<1000 || year>10000)
    {	return false;
    }
    return true; // date is valid
}


/**********************************************************************************************
A currency formatting function found on the Internet.  
NOTE:	Does not round correctly with many decimal places!  Use math.round to round to two 
		decimals before using
**********************************************************************************************/
function formatCurrency(inAmount) 
	{
	var num = inAmount.toString().replace(/\$|\,|\s/g,'')
	var cents
	var i

	if (isNaN(num)) 
		num = "0"

	cents = Math.floor((num*100+0.5)%100)
	num = Math.floor(num).toString()
	
	if (cents < 10) 
		cents = "0" + cents
	for (i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3)) + ',' + num.substring(num.length-(4*i+3))
	
	return ('$' + num + '.' + cents)
	}


/**********************************************************************************************
Function:		Trim
Author:			Adam Schweitzer
Date:			7/4/01
Description:	Removes a specified character from a string
Input:			String to remove characters from
				The character to remove (default is a space)
Output:			None
Return value:	The trimmed string
Dependencies:	None
Comments:		Called by Validate
**********************************************************************************************/
function Trim (str, chr)
	{
	var result
	var i
	
	result = ""
	
	if (chr == null) // default to remove
		chr = " "
	
	if (chr.length != 1) // error check.  this function only removes 1 character
		{
		alert ("string trim failure")
		return str
		}
		
	for (i=0;i<str.length;i++)
		if (str.charAt (i) != chr)
			result += str.charAt(i)
			
	return result
	}

/**********************************************************************************************
Function:		replaceChar
Author:			Adam Schweitzer
Date:			8/02/01													
Description:	This function provides low-level string manipulation.  It replaces a character
				within a string.
Input:			str - the string
				chr - the character to be placed in the string
				loc - the position the character is to be inserted.  the previous character at 
					  that location is overwritten
Output:			An alert box with the text 'string error', if the location is out of bounds.
Return value:	The string with the replaced character if successful
				The string if not.
Dependencies:	errorMsg1 DIV in form calling this function
**********************************************************************************************/
function replaceChar(str, chr, loc)
	{
	if (loc > str.length)
		{
		alert ("string error")
		return str
		}
	else
		return str.substr (0, loc)  + chr + str.substr ((loc + 1), str.length)
	}	


/**********************************************************************************************
Function:		IsContained
Author:			Adam Schweitzer
Date:			7/3/01
Description:	General function to see if a string contains only certain characters
Input:			String to be checked
				Valid characters
Output:			None
Return value:	1 if the string is composed only of the valid characters
				0 if not
Dependencies:	None
Comments:		Called by IsNumeric and IsAlpha
**********************************************************************************************/
function IsContained (str, validchrs)
	{
	var valid = validchrs
	var i
	i=0

	while (i < str.length && valid.indexOf (str.charAt(i)) != -1)
		i++
	
	if (i!= str.length)
		return 0
	else
		return 1
	}

/**********************************************************************************************
Function:		IsNumeric
Author:			Adam Schweitzer
Date:			7/3/01													(Last Modified: 8/13/01)
Description:	This function checks if a string of text is a (non-negative) number
Input:			String to be checked
Output:			None
Return value:	1 if a number
				0 if not
Dependencies:	IsContained
Comments:		Called by Validate function
**********************************************************************************************/
function IsNumeric (num)
	{
	decimals = num.length - (Trim (num, ".")).length
	
	if (!(decimals == 0 || decimals > 0 || decimals < 0))
		decimals = 0
		
	if (decimals == 1)
		return ((IsContained ("".concat(num), "0123456789.")))
	else if (decimals == 0)
		return ((IsContained ("".concat(num), "0123456789")))
	else
		return 0
	}

/**********************************************************************************************
Function:		IsAlpha
Author:			Adam Schweitzer
Date:			7/3/01
Description:	This function checks if a string of text contains only alphabet characters
Input:			String to be checked
Output:			None
Return value:	1 if an alpha character
				0 if not
Dependencies:	IsContained
Comments:		Called by Validate function
**********************************************************************************************/
function IsAlpha (str)
	{
	return IsContained (str, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
	}

/**********************************************************************************************
Function:		IsPostalCode
Author:			Adam Schweitzer
Date:			7/3/01
Description:	This function checks if a string of text is a valid postal code
Input:			String to be checked
Output:			None
Return value:	1 if a valid postal code
				0 if not
Dependencies:	IsAlpha, IsNumeric, Trim
Comments:		Called by Validate function
**********************************************************************************************/
function IsPostalCode (code)
	{
	var error = false

	code = Trim (code, " ")

	if (code.length == 6)
		{
		for (i=0;i<6;i++)
			{
			if (i%2 == 0)
				{
				if (!(IsAlpha (code.charAt(i))))
					error = true
				}
			else if (!(IsNumeric (code.charAt(i))))
				error = true
			}
		}
	else
		error = true
		
	if (error)
		return 0
	else
		return 1
	}

/**********************************************************************************************
Function:		IsPhoneNumber
Author:			Adam Schweitzer
Date:			7/4/01
Description:	This function checks to see that a phone number entered is valid
Input:			The phone number to be checked
Output:			None
Return value:	1 if a valid phone number
				0 if not
Dependencies:	IsNumeric, IsContained, Trim
Comments:		Called by Validate
**********************************************************************************************/
function IsPhoneNumber (phone)
	{
	var num = Trim (phone)
	var array = num.split ("-")
	var valid = 0
	
	if (array.length == 2)
		{
		if (IsNumeric (array[0]) && array[0].length == 3 
			&& IsNumeric (array[1]) && array[1].length == 4)
			{
			valid = 1
			}
		else if(array[0].substring(0,1)=="(" && array[0].substring(4,5)==")")
		{	if(IsNumeric(array[0].substring(1,4)) && IsNumeric(array[0].substring(5,8)) && array[0].length==8)
			{	valid=1
			}
		}
		}
	else if (array.length == 3)
		{
		if (IsNumeric (array[0]) && array[0].length == 3 
			&& IsNumeric (array[1]) && array[1].length == 3
			&& IsNumeric (array[2]) && array[2].length == 4)
			valid = 1
		}
	else if (array.length == 4)
		{
		if (IsNumeric (array[0]) && array[0].length == 1 
			&& IsNumeric (array[1]) && array[1].length == 3
			&& IsNumeric (array[2]) && array[2].length == 3
			&& IsNumeric (array[3]) && array[3].length == 4)
			valid = 1
		}
	return valid
	}

/**********************************************************************************************
Function:		PriceBlur
Author:			Adam Schweitzer
Date:			7/9/01
Description:	This function formats the text in a price field and is called from the onBlur 
				event handler.  It uses the error global variable if the value entered is not 
				valid, for later error correction.
				variable 
Input:			The name of the field (form_name.field_name)
Output:			Formatted price, if a valid value is in the textbox
Return value:	None
Dependencies:	mdl_DataValidation.js
Comments:		Called by onBlur event handler and AddTax
**********************************************************************************************/
function PriceBlur (field_name)
	{
	with (field_name)
		{
		if (IsNumeric (value) && value != "") 
			{
			value = formatCurrency (value) 
			error = false
			}
		else if (value.charAt(0) == "$")
			{
			value = Trim (value, ",")
			if (IsNumeric (value.substring (1, value.length)))
				error = false
			else
				error = true
			}
		else
			error = true
		}
	}



/**********************************************************************************************
Function:		PriceConverter
Author:			Simon Chen
Date:			
Description:	 
Input:			
Output:			
Return value:	
Dependencies:	mdl_DataValidation.js
Comments:		
**********************************************************************************************/
function PriceConverter(priceToConvert)
{	var tempPrice=Trim(priceToConvert,",");
	tempPrice=Trim(tempPrice,"$");
													
	return formatCurrency(priceToConvert);
}

			
function toConvertPrice(field_name)
{
	with (field_name) 
	{ 
		if (field_name.value != "")
		{
			field_name.value=PriceConverter(field_name.value);
		}
	}
}




/**********************************************************************************************
Function:		inSelectBox
Author:			Adam Schweitzer
Date:			8/30/01
Description:	This function checks if a value is in a select box
Input:			selObj			- the select box
				text			- the text to search for
				caseSensitive	- whether the search is to be case sensitive. not by default
Output:			None
Return value:	True if in select box
				False if not
Dependencies:	None
**********************************************************************************************/
function inSelectBox (selObj, text, caseSensitive)
	{
	var i
	var inBox = false

	for (i=0;i<selObj.length;i++)
		{
		if (selObj[i].text.toUpperCase() == text.toUpperCase())
			inBox = true
		}

	return inBox
	}


/**********************************************************************************************
Function:		checkEnter
Author:			Adam Schweitzer
Date:			7/11/01
Description:	This function submits a form in Netscape when enter is pressed
Input:			The event, form name, the parameter passed to the validate function (if any),
Output:			None
Return value:	True if enter not pressed
				False if enter pressed (Submits form if validated)
Dependencies:	Validate function of form
Comments:		Called by onKeyPress event handler of most forms
**********************************************************************************************/
function checkEnter(e, form_name, val_param)
	{
	var charCode 
	charCode = e.keyCode

//	if ("".concat (e.target).indexOf ("TextArea") == -1 && navigator.appName == "Netscape") // the enter key was not pressed while in a text area
	if (inTextArea == false)
		{
		if (charCode == 13)
			{
			if (val_param == null)
				{
				if (Validate ())
					document.getElementById(form_name).submit()
				}
			else
				{
				if (Validate (val_param))
					document.getElementById(form_name).submit()
				}	
			return false
			}
		}
	}
	
	
/**********************************************************************************************
Function:		checkFieldLimit	
Author:			Simon Chen
Date:			Oct 22, 2001
Description:	checks the field if the length of the contents exceeds that allowable in the database
Input:			form, field and the limit of the field in the database
Output:			true if the value is over the allowable limit and false if it is not over
Return value:	true or false
Dependencies:	
Comments:		
**********************************************************************************************/
function checkFieldLimit(field_value,limit)
{	//alert(field_value);
	if (field_value.length>limit)
	{	return true;
	}
	return false;

}

function checkEnterPress(e)
		{
			var charCode 
			charCode = e.keyCode
		
			if (charCode == 13)
			{
				submitLogin()
				return false
			}
		}

