/********************************************************************
* 
********************************************************************/

/********************************************************************
* Basic character sets.
********************************************************************/

//important - Characters !, ^ and " are used as delimiters for form filling.


var lowercaseLetters = "abcdefghijklmnopqrstuvwxyz";
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

var alpha 		= lowercaseLetters + uppercaseLetters;
var digits 		= "0123456789";
var sfloat 		= "0123456789.";
var sDate 		= "0123456789/";

var pSetA 		= "`-_";
var pSetB 		= "&~$%*+=|?,.#@:/";	//  removed ! from this charset.
var pSetC		= "{}[]<>()";
var pSetD               = "$@.";
var pSetE               = "/,.#";
var pSetF               = ".";
//var nonEAlpha 	= "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþ";

var whiteSpace            = " \t\r\n";
var singleSpace           = " ";
var singleQuote           = "'";
var doubleQuote			  = '"';
var creditCardDelimiters  = " ";
var emailDelimiters       = ".@";	// removed ! from this charset.
var phoneNumberDelimiters = "()- ";
var ssnDelimiters         = "-";
var zipCodeDelimiters     = "-";



var daysInMonth = new Array(12);
daysInMonth[1] = 31;
daysInMonth[2] = 29;   // must check this
daysInMonth[3] = 31;
daysInMonth[4] = 30;
daysInMonth[5] = 31;
daysInMonth[6] = 30;
daysInMonth[7] = 31;
daysInMonth[8] = 31;
daysInMonth[9] = 30;
daysInMonth[10] = 31;
daysInMonth[11] = 30;
daysInMonth[12] = 31;


/********************************************************************
* Regular Expressions.
********************************************************************/
var emailRE = /[A-Za-z0-9_.]+@[A-Za-z0-9_.]+[.]+(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)/;

/********************************************************************
* Valid character sets for the various fields.
********************************************************************/

var dataSetArray = new Array();
dataSetArray["ALPHA"]           = alpha;
dataSetArray["ALPHAWITHSPACE"]  = alpha + whiteSpace;
dataSetArray["ALPHANUMERIC"]    = alpha + digits; 
dataSetArray["SEARCHSTRING"]    = alpha + digits + pSetA + whiteSpace;
dataSetArray["URL"]             = alpha + digits + pSetA + pSetB +pSetC;
dataSetArray["CREDITCARD"]      = digits + creditCardDelimiters;
dataSetArray["SSN"]             = digits + ssnDelimiters;
dataSetArray["USERID"]	        = alpha + digits + pSetA + pSetB + whiteSpace + pSetC;
dataSetArray["NEWUSERID"]       = alpha + digits + pSetA;
dataSetArray["NUMBER"]          = digits;
dataSetArray["SMALLINT"]          = digits;
dataSetArray["TINYINT"]          = digits;
dataSetArray["FLOAT"]           = sfloat;

// Create maximum number length array (this is for Sybase db note
var maxNumberSize = new Array();

maxNumberSize["SMALLINT"]		= 32767; 
maxNumberSize["TINYINT"]		= 255;

/* Begin MRI */
dataSetArray["NAME"]            = alpha + singleSpace + pSetF;
dataSetArray["USERNAME"]        = alpha + digits + pSetA;
dataSetArray["PASSWORD"]        = alpha + digits + pSetA + pSetD;
dataSetArray["ADDRESS"]         = digits + alpha + singleSpace + pSetE;
dataSetArray["CITY"]            = alpha + singleSpace;
dataSetArray["STATE"]           = alpha + singleSpace;
dataSetArray["ZIP"]             = digits + zipCodeDelimiters;
dataSetArray["COUNTRY"]         = alpha + singleSpace; 
dataSetArray["PHONE"]           = digits + phoneNumberDelimiters;
dataSetArray["EMAIL"]           = alpha + digits + pSetA + emailDelimiters;
dataSetArray["DATE"]            = sDate;
dataSetArray["COMPANYNAME"]     = alpha + digits + singleQuote + singleSpace + pSetC + pSetF;
dataSetArray["CODE"]            = alpha + digits + pSetA;
dataSetArray["STRING"]          = alpha + digits + pSetA + pSetB + whiteSpace + pSetC + singleQuote + doubleQuote;
dataSetArray["TEXT"]          = alpha + digits + pSetA + pSetB + whiteSpace + pSetC + singleQuote + doubleQuote;
dataSetArray["CHAR"]          = alpha + digits;

/* End MRI */

/********************************************************************
* These are some common error messages that are displayed.
********************************************************************/
var AllNullTextField		= "$1$ cannot be blank. Please enter a value.";
var AllWhiteSpaceTextField		= "$1$ cannot be all white spaces. Please enter a valid string ";
var AllNullSelectField		= "Please choose a value for $1$."; 
var AllInvalidCharacter		= "$1$ has invalid characters. Please remove all occurrences " +
				  	  " of the character '$2$'.";
var AllAtLeast1SelectValue	= "$1$: Please choose a value from the list of options " +
				  	  "or enter a value in the 'Other' Field.";
var AllAtMost1SelectValue	= "Your entry in 'Other $1$' will override your selection " +
				  	  "for $1$. If this is not OK, " +
				  	  "hit 'Cancel'.";

var AllMaxTextLength	= "$1$ has exceeded the maximum character length of 255.  Please shorten.";

var AllMaxNumber		= "$1$ has exceeded the maximum number length of $2$.  Please reduce.";

var AllInvalidEmail		= "The $1$ is invalid.  Please enter a valid email address.";

/********************************************************************
* 
********************************************************************/
function elementObj(fullName, validCharSetName, isRequired, myValidate)
{
	this.m_fullName		= fullName;
	this.m_validSet		= validCharSetName;
	this.m_isRequired		= isRequired;	
	this.myValidate 		= myValidate;
	this.validate 		= validate;
	
	function validate(theForm, element)
	{
		var result = true;
		var val = element.value;
		//alert("Value: *" + val + "*");
		var uType = element.type.toUpperCase();
//alert("uType = " + uType);
		//Element types we do not validate currently.

		if( (uType == "CHECKBOX") || (uType == "RADIO") ||
		    (uType == "BUTTON") || (uType == "SUBMIT")  ||
		    (uType == "RESET") || (uType == "HIDDEN"))
			return result;

		if(this.m_isRequired)
		{
			if( ( (uType == "TEXT") || (uType == "TEXTAREA") || (uType == "PASSWORD") ) &&
			    val.length < 1)
			{
				alert(replace(AllNullTextField, "$1$", this.m_fullName));
				result = false;
				element.focus();
				return result;
			}	
			else if( ( (uType == "SELECT-ONE") || (uType == "SELECT-MULTIPLE") ) &&
				   (element.selectedIndex < 1) )
			{
				alert(replace(AllNullSelectField, "$1$", this.m_fullName));
				result = false;
				element.focus();
				return result;
			}

		}

		

		if( ( (uType == "TEXT") || (uType == "TEXTAREA") || (uType == "PASSWORD") ) &&
			val.length > 0)
		{
			if( isWhitespaces(val) )
			{
				if(this.m_isRequired)
					alert(replace(AllWhiteSpaceTextField, "$1$", this.m_fullName) + ".");
				else
					alert(replace(AllWhiteSpaceTextField, "$1$", this.m_fullName) +  "or leave the field empty.");

				element.focus();
				element.select();
				return false;
			}
		}

		// do custom validation first -- currently done only for text strings.

		if (result && this.myValidate) 
		{
			result = this.myValidate(theForm, element, this.m_fullName);
		}

		// Do the generic validation

		if (result && ( (uType == "TEXT") || (uType == "TEXTAREA") || (uType == "PASSWORD") ) )
		{
			result = checkValidChars(val, this.m_validSet, this.m_fullName);
			if (!result){
				element.focus();
				return false;
			}
		}

		if ( (this.m_validSet == "EMAIL") && (this.m_isRequired) )	{
			
			if(val.match(emailRE) == null)	{
				alert(replace(AllInvalidEmail,"$1$", this.m_fullName));
				result = false;
			}
		}

		if ((this.m_validSet == "STRING") && (val.length > 255))
		{
			alert(replace(AllMaxTextLength, "$1$", this.m_fullName));
			result = false;
		}
		
		if(!this.myValidate ) //If there is a custom validation function, focus must be set by the function. 
			element.focus();
		return result;
	}
}


/********************************************************************
* Form Validation Object. Instantiated in each web form.
********************************************************************/
function formValidationObj(theForm, elemObjArray)
{
	this.m_form		= theForm;
	this.m_elemObjs	= elemObjArray;
	this.validate 	= validate;

	function validate()
	{

		var theDoc = this.m_form.elements;
	 	var result = true;

	 	for (var i = 0; i < theDoc.length; i++)
	 	{
//	alert(this.m_elemObjs[theDoc[i].name] + ";;" + theDoc[i].name + ";;" + theDoc[i].name);
//			if(this.m_elemObjs[stripTrailingDigits(theDoc[i].name)] != null) 
//				result = this.m_elemObjs[stripTrailingDigits(theDoc[i].name)].validate(this.m_form, theDoc[i]);
			if(this.m_elemObjs[theDoc[i].name] != null) 
				result = this.m_elemObjs[theDoc[i].name].validate(this.m_form, theDoc[i]);

			if(!result)
			{
				break
			}
		}

		return result;
	}
}

/********************************************************************
* Utility Functions
********************************************************************/
function stripTrailingDigits(string)
{
	for (var i=string.length-1; i>0; i--) 
	{
		if(digits.indexOf(string.charAt(i)) < 0) 
		{
			break
		}
	}

	return string.substr(0, i+1);
}


function checkValidChars(val, valueSet, fullName)
{
	var checkStr = "";
	var validChars = dataSetArray[valueSet];

	var ch;
	var result = true;
//alert(val+"--"+valueSet+"--"+fullName);
//alert("haha");


	// Do maximum number validation based off of Sybase
	if ((valueSet == "SMALLINT") && (val > maxNumberSize[valueSet]))
		result = false;	
	else if ((valueSet == "TINYINT") && (val > maxNumberSize[valueSet]))
		result = false;
		
	if(!result) 
	{
		alert(replace(replace(AllMaxNumber, "$1$", fullName), "$2$", maxNumberSize[valueSet]) );
	}

		
	if(result)	{
		for (var i = 0;  i < val.length;  i++)
		{
			ch = val.charAt(i);
			if (validChars.indexOf(ch) < 0) 
			{
				result = false;
				break;
			}
		}


		if(!result) 
		{
			alert(replace(replace(AllInvalidCharacter, "$1$", fullName), "$2$", ch) );
		}
	
	}


	return result;

}


function replace(theString, searchStr, replaceStr) {

	var i;

	while ((i = theString.indexOf(searchStr)) != -1) {

		theString = theString.substring(0, i)
               			    + replaceStr
               			    + theString.substring(i+searchStr.length);
	}

  return theString;
}

/********************************************************************
* Custom Validation -- Common Functions
********************************************************************/
function exactlyOne(theForm, element, fullName)
{
	var result=true;

	var elementIndex  = element.selectedIndex;
	var otherElement	= theForm["OTHER_" + element.name];
	var otherValue	= otherElement.value;

	var both    = (elementIndex > 0)  && (otherValue != "");
	var neither = (elementIndex == 0) && (otherValue == "");	

	if(both)
	{
		result = confirm(replace(AllAtMost1SelectValue, "$1$", fullName) );
		otherElement.focus();
		otherElement.select();
	}

	if(neither)
	{
		alert(replace(AllAtLeast1SelectValue, "$1$", fullName) );
		result = false;
		otherElement.focus();
	}
	
	return result;

}

function atMostOne(theForm, element, fullName)
{
	var result=true;

	var elementIndex  = element.selectedIndex;
	var otherElement	= theForm["OTHER_" + element.name];
	var otherValue	= otherElement.value;

	var both    = (elementIndex > 0)  && (otherValue != "");
	
	if(both)
		result = confirm(replace(AllAtMost1SelectValue, "$1$", fullName) );

	otherElement.focus();
	otherElement.select();

	return result;

}


/*********************************************************
The following function is moved from CSUtils.js 
********************************************************/

// whitespace characters
var whitespace = " \t\n\r";

function isWhitespaces(s)
{   
    var i;
    if ( (s == null) || (s.length == 0)) return true;

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        if (whitespace.indexOf(s.charAt(i)) == -1) return false;
    }

    // All characters are whitespace.
    return true;
}

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
}