/*
Copyright© 2005 FourChain. All Rights Reserved.

NOTE: This file when changed has to be updated in the "../FourChain/CustomerSignUp/newjs" and "../FourChain/newjs" folders

-----------------------------------------------------------

Project Name		:	FourChain
File Name			:	Validation.js
Description			:	This file contains data validation functions.
Author				:	Moiz Moinuddin
Creation Date		:	July 27, 2005
Included in Files	:	AddUser.asp
						DisplayUser.asp
						createstnd.asp

Modified By			:	Yasir Amin
Modified on			:	October 5, 2005
Modi. Comments		:	Added more validation functions (i.e. integer validation and text area maxlength functions
						Also added functions for date validation

Modified By			:	Yasir Amin
Modified on			:	October 31, 2005
Modi. Comments		:	Added more validation functions

-----------------------------------------------------------
*/

<!--

var VALIDATION_EMAIL = "email";


/****************************************************************************************************
                              INTERACTIVE VALIDATION FUNCTIONS
                          (Perform other checks. Provides alerts)
 ****************************************************************************************************/
function Validate (ValidationFor, HTMLControl, IsOptional, ToAlert)
{
	var validationResult = false;
	var specificValResult = false;
	var message = "Invalid input.";

	if ( IsOptional )
	{
		if ( TextControl.value == "" )
			validationResult = true;
	}
	else
	{
		switch ( ValidationFor.toLowerCase() )
		{
			case VALIDATION_EMAIL:
				specificValResult = CheckEmail(TextControl.value);
				break;
		}		
		validationResult = specificValResult;
	}

	if ( !validationResult && ToAlert )
	{
		switch ( ValidationFor.toLowerCase() )
		{
			case VALIDATION_EMAIL:
				message = "Invalid Email Address.";
				break;
		}
		alert(message);
		HTMLControl.focus();
		if ( HTMLControl.type != "select-one" || HTMLControl.type != "select-multiple" )
			HTMLControl.select();
	}
	return validationResult;
}

/****************************************************************************************************
                                  BASIC VALIDATION FUNCTIONS
                        (Non-interactive. Does only intended validation.)
 ****************************************************************************************************/
// ----------------------------------------------------------------- CheckEmail ---------------------
function ValidateEmail (TextToValidate)
{
	var emailExp = /^[^ @\f\n\r\t\v]+@(([a-zA-Z0-9][a-zA-Z0-9\.\-]*\.[a-zA-Z]{2,})|(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))$/;
	var emailAddress = TextToValidate;
	var matches = emailAddress.match(emailExp);
	if ( matches != null )
		return true;
	else
		return false;
}

function isvalidemailid(f) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(f);
} 


// Validates the UserID whether it contains any spaces or special character
function fnValidateUserID(strUserID)
{
	// Trim the spaces on the side
	strUserID=trim(strUserID);
		
	// Check all values for spaces
	for (var intCounter=0; intCounter < strUserID.length; intCounter++)
	{
		// ID's don't usually contain spaces and special characters
		if (strUserID.charAt(intCounter) == ' ' || strUserID.charAt(intCounter) == '\\' || strUserID.charAt(intCounter) == '*'
		|| strUserID.charAt(intCounter) == '/' || strUserID.charAt(intCounter) == '!' || strUserID.charAt(intCounter) == '#'
		|| strUserID.charAt(intCounter) == '$' || strUserID.charAt(intCounter) == '%' || strUserID.charAt(intCounter) == '~'
		|| strUserID.charAt(intCounter) == '^' || strUserID.charAt(intCounter) == '(' || strUserID.charAt(intCounter) == ')'
		|| strUserID.charAt(intCounter) == '&' || strUserID.charAt(intCounter) == '+' || strUserID.charAt(intCounter) == '-'
		|| strUserID.charAt(intCounter) == '{' || strUserID.charAt(intCounter) == '}' || strUserID.charAt(intCounter) == '['
		|| strUserID.charAt(intCounter) == ']' || strUserID.charAt(intCounter) == ',' || strUserID.charAt(intCounter) == '\''
		|| strUserID.charAt(intCounter) == ';' || strUserID.charAt(intCounter) == ':' || strUserID.charAt(intCounter) == '\"'
		|| strUserID.charAt(intCounter) == '<' || strUserID.charAt(intCounter) == '>' || strUserID.charAt(intCounter) == '|'
		|| strUserID.charAt(intCounter) == '=' || strUserID.charAt(intCounter) == '`' || strUserID.charAt(intCounter) == '?'
		|| strUserID.charAt(intCounter) == '\n' || strUserID.charAt(intCounter) == '\r' || strUserID.charAt(intCounter) == '\t')
		{
			// Special characters found
			return false;
		}
	}
		
	// No special character found
	return true;
}

// This function checks whether the
// Return valures are true and false 
function fnIsInteger(strValue)
{
	var intCounter=0;
	
	// Checking all the values to see that they are all digits
	for (intCounter = 0; intCounter < strValue.length; intCounter++)
	{   
		// Check that current character is number.
       	var charValue = strValue.charAt(intCounter);
       	
       	// Check in the digits range
       	if (charValue < "0" || charValue > "9")
		{
			// If not a digit no need to proceed ahed
			return false;
		}
    }
    	
    // All characters are numbers.
	return true;
}

/******************************************************************************************************************
********************************** End of Multiline Textbox maxlength functions ***********************************
********************************** These functions are IE and Mozilla Competable **********************************
******************************************************************************************************************/

// This is a Mozilla related competability function (Will only run when We are validating textarea in Mozilla)
function fnMaxLengthCorrection(strValue)
{
	// Check to see if the value exists
	if (strValue)
	{
		// If the length of sting is not 0
		if (strValue.length != 0)
		{
			// Will contain the total number of new line chars
			var intNewLine=0;
				
			// Run till the end of loop
			for(var intCounter=0; intCounter < strValue.length; intCounter++)
			{	
				// Checking for the newLine char
				if (strValue.charAt(intCounter) == '\n')
				{
					// Increment the value
					intNewLine++;
				}
			}
				
			// Return the number of values to add to Maxlength
			return intNewLine;
		}
	}
	
	// return 0 if the parameter does not exist or the string length is 0
	return 0;
}
			
// This function should be called on the keypress event of the multiline textbox function
function doKeypress(event, maxLength)
{
	// This holds the control value length
	var intControlValueLength=0;
				
	// this will hold the char code of the keypressed in the Mozilla browser
	var chrCode=0;
				
	// Save as int
	maxLength = parseInt(maxLength);
			
	// If the browser is Internet Explorer
	if (fnGetBrowser() == "MSIE")
	{}
	// Comments are made to Fix one Error on standard page
	// Sarkar
	// on 12-Jun-2009
	
//	{
//		// Get the char whose key was pressed
//		chrCode=event.keyCode;
//				
//		// Get the length
//		intControlValueLength=event.srcElement.value.length;
//				
//		// If there is only one more char left to be inserted and the enter key is pressed then do not go ahead
//		if (((intControlValueLength + 1) == maxLength) && (chrCode == 13) )
//		{
//			// The event should not be allowed
//			event.returnValue = false;
//						
//			// Do not proceed ahead
//			return;
//		}
//	}
	// Else if netscape
	else if (fnGetBrowser() == "NETSCAPE")
	{
		// Get the char whose key was pressed
		chrCode=event.which;
					
		// In case of Mozilla add the number of character found to the current length of the control value
		intControlValueLength=event.target.value.length + fnMaxLengthCorrection(event.target.value);
					
		// If there is only one more char left to be inserted and the enter key is pressed then do not go ahead
		if (((intControlValueLength + 1) == maxLength) && (chrCode == 13) )
		{
			// the event should not be allowed
			event.preventDefault(true);
						
			// Do not proceed ahead
			return;
		}
				
	}

	if(maxLength && intControlValueLength > maxLength-1)
	{
		// If the browser is Internet Explorer
		if (fnGetBrowser() == "MSIE")
		{	
			event.returnValue = false;
		}
					
		// If netscape
		else if (fnGetBrowser() == "NETSCAPE")
		{
			// Check that the char code of the keypressed is not 0
			if (chrCode != 0)
			{
				if (chrCode != 8)
				{
					event.preventDefault(true);
				}
			}
		}
	}
}

// This function should be called on the before paste event of the multiline textbox function
function doBeforePaste(event, maxLength)
{
	// If maxlength and browser is IE
	if(maxLength && fnGetBrowser() == "MSIE")
	{
		event.returnValue = false;
	}
}

// This function should be called on the paste event of the multiline textbox function
function doPaste(event, maxLength)
{
	// if maxlength and browser is IE
	if(maxLength && fnGetBrowser() == "MSIE")
	{
		event.returnValue = false;
		maxLength = parseInt(maxLength);
		var oTR = document.selection.createRange();
		var iInsertLength = maxLength - event.srcElement.value.length + oTR.text.length;
		var sData = window.clipboardData.getData("Text").substr(0,iInsertLength);
		oTR.text = sData;
	}
}
			
// This will check the text on various events
function CheckText(event, maxLength)
{
	// Only check this for Netscape
	if(maxLength && fnGetBrowser() == "NETSCAPE")
	{
		// Save as integer
		maxLength = parseInt(maxLength);
					
		// This contains the length corrected length of the textarea
		var intTotalChars=event.target.value.length + fnMaxLengthCorrection(event.target.value);
					
		// If the value in the control is greater then maxLength then
		if (intTotalChars > maxLength)
		{
			// Trim the chars other than 
			var strNewValue = event.target.value.substr(0, maxLength);
						
			// Will hold the new value length
			var intNewValueLength=strNewValue.length - 1;
						
			// If NewLine Char has been found then
			if (strNewValue.charAt(intNewValueLength) == '\n')
			{
				strNewValue=strNewValue.substr(0, intNewValueLength);
			}
						
			// Set the value in the text area control
			event.target.value=strNewValue;
		}
					
	}
}

/******************************************************************************************************************
********************************** End of Multiline Textbox maxlength functions ***********************************
******************************************************************************************************************/



/******************************************************************************************************************
************************************** Date validation functions **************************************************
******************************************************************************************************************/


function fnStripCharsInBag(strValue, strBag)
{
	var intCounter=0;
	
	// The value to be returned
    var strReturnValue = "";
	
	// Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (intCounter = 0; intCounter < strValue.length; intCounter++)
	{   
		// Get the char at the index
        var charValue = strValue.charAt(intCounter);
        
        if (strBag.indexOf(charValue) == -1)
		{
			strReturnValue = strReturnValue + charValue;
		}
    }

	// Return the string
	return strReturnValue;
}


// Claculates the days in feburary (according to leap year)
function fnDaysInFebruary (strYear)
{
	// February has 29 days in any year evenly divisible by four,
	// EXCEPT for centurial years which are not also divisible by 400.
	return (((strYear % 4 == 0) && ( (!(strYear % 100 == 0)) || (strYear % 400 == 0))) ? 29 : 28 ); 
}

function fnDaysArray(intMaxValue)
{
	// The loop counter
	var intCounter=0;
	
	for (intCounter = 1; intCounter <= intMaxValue; intCounter++)
	{
  		this[intCounter] = 31;
  		if (intCounter==4 || intCounter==6 || intCounter==9 || intCounter==11)
		{
			this[intCounter] = 30;
		}
  		
		if (intCounter==2)
		{
			this[intCounter] = 29;
		}
	} 
		
	// Return value
	return this;
}




// The main date validation function which returns the error string (Formatted according to Owais's validation document)
// and empty if there is no error
function fnIsValidDate(strDate, strDateFieldsSeperator)
{
	// The total number of days in month
	var arrDaysInMonth = fnDaysArray(12);
	
	// Get seperator positions
 	var intSeperatorPosition1=strDate.indexOf(strDateFieldsSeperator);
 	var intSeperatorPosition2=strDate.indexOf(strDateFieldsSeperator,intSeperatorPosition1 + 1);
 	
 	// Get Date fields
 	var strMonth=strDate.substring(0,intSeperatorPosition1);
 	var strDay=strDate.substring(intSeperatorPosition1 + 1,intSeperatorPosition2); 
 	var strYear=strDate.substring(intSeperatorPosition2 + 1);
 	
 	// Save the orignal year
 	var strOrignalYear=strYear;
 	
	if (strDay.charAt(0) == "0" && strDay.length > 1)
	{
		strDay=strDay.substring(1);
	}
 
	if (strMonth.charAt(0) == "0" && strMonth.length > 1)
	{
		strMonth=strMonth.substring(1);
	}
 	
 	
	for (var intCounter = 1; intCounter <= 3; intCounter++)
	{
  		if (strYear.charAt(0) == "0" && strYear.length > 1)
		{
			strYear=strYear.substring(1);
		}
 	}
 
	// Convert all values to integer
	var intMonth=parseInt(strMonth);
 	var intDay=parseInt(strDay); 
 	var intYear=parseInt(strYear);
 	
 	
 	// Perform validation on date
	if ((intSeperatorPosition1 == -1 || intSeperatorPosition2 == -1) || (strDate.indexOf(strDateFieldsSeperator, intSeperatorPosition2 + 1) != -1 || fnIsInteger(fnStripCharsInBag(strDate, strDateFieldsSeperator))== false))
	{
		// Not a valid date
		return false;
 	}
	
	if (strMonth.length < 1 || intMonth < 1 || intMonth > 12)
	{
		// Not a valid date
		return false;
	}
	
	if (strDay.length<1 || intDay<1 || intDay>31 || (intMonth==2 && intDay > fnDaysInFebruary(intYear)) || intDay > arrDaysInMonth[intMonth])
	{
		// Not a valid date
		return false;
	}
	
	// Two digit year validation
	if (strOrignalYear.length == 2)
	{
		// Check that it is -1 and 100
		if(intYear < 0 || intYear > 99)
		{
			// Not a valid date
			return false;
		}
	}
	else if (strOrignalYear.length == 4)
	{
		// Check the date range
		if (intYear < 1900 || intYear > 2100)
		{
			// Not a valid date
			return false;
		}
	}
	
	// Else if it is of some other length
	else
	{
		// Else not a valid date
		return false;
	}

	
	// Valid date
	return true;
}


// This function is used to get the form object.
// This is used for mozilla compatibility (Also works fine with IE)
function fnGetFormObject(strFormID)
{
	// Return the form object this is used for 
	return document.getElementById(strFormID);		
}

// This will return the browser name as to which brower is being used
function fnGetBrowser()
{
	var strDetect = navigator.userAgent.toLowerCase();
	
	// Set to empty string that unknown browser
	var strBrowser="";

	if (fnIsBrowser("msie", strDetect))
	{
		strBrowser = "MSIE";
	}
	else if (fnIsBrowser("firefox", strDetect))
	{
		strBrowser = "NETSCAPE";
	}
	else if (fnIsBrowser("mozilla", strDetect))
	{
		strBrowser = "NETSCAPE";
	}
	
	// Return the browser name
	return strBrowser;
}


// This is a helper function used in the GetBrowser function
function fnIsBrowser(strBrowserName, strDetect)
{
	return (strDetect.indexOf(strBrowserName) + 1);
}

// -->
