//alert("hai");
/**
	This is the global file to form validation. 

	Author		   M.Velmurugan
	CreatedOn	   August 28, 2004
	

	Form attributes using by the file is as follows
	1)	 valid
	2)	 errname
	3)	 filetype

	Syntax of the each attribute is as follows
	1)	 valid
	-----------
		This attribute is used to define that element is mandatory or not and also to define that element hold only
		integer or real or date or alphanumeric or file or any characters. General syntax of this attribute is
		{1}_{2}
		here 
		{1} -> m | n
		m -> Mandatory
		n ->	Non Mandatory

		{2} -> i | r | d | f | a | s | z | y | t | c | p | x | w |
		
		a ->	Alpha Numerici ->	Integer
		b ->    Alpahnumeric with Ampersand(&)
		C ->    Mobile Phone Validation
		d ->	Date
		e ->    Email Validation
		f ->	File
		g ->    PLR Validation
		l ->	Current Rates Validation
		p ->    Pincode Validation
		q ->    Company Name Validation
		r ->	Real
		s ->	Special Char
		T ->    Telephone Validation
		v ->    File Name Validation
		w ->    Address Validation
		x ->    Name Validation
		y ->    Start with Alphabet
		z ->    Money Value
		
			
	2)	 errname
	---------------
		This attribute is used to display the element name to show in the alert box. It contain any string value.

	3)	 filetype
	--------------
		This attribute is used which type of file can be accepted in file element. Now they are three type of files 
		are declared here those values are

			(1)	image :	 For all the image file.
			(2)	doc   :	 For all the documents.
			(3)	html  : For all the html files.
			(4) zip    : For all  the Zip files
		
*/

/**
	Some of the constants and error message is prefixed here
*/

var MANDATORY_ERROR	 = "* Please [1] the [2].";
var INTEGER_ERROR = "* Please enter only Numeric values in [1].";
var REAL_ERROR = "* Please enter only real values in [1].";
var DATE_ERROR = "* Please enter valid calendar date in [1].";
var ALPHA_ERROR = "* Please enter only alpha numeric  in [1].";
var ALPHAAMP_ERROR ="* [1] accepts only alphabets, numeric, space and &. First character should be an alphabet";
var SPECIAL_ERROR = "* [1] accepts Alphabets,Numeric,Space and Special characters.[1] start with Alphabet.";

var IMAGE_FILE_ERROR = "* [1] accepts only Jpeg/Jpg/Bmp/gif Files.";
var DOC_FILE_ERROR = "* Please choose only Word/Excel document file in [1].";
var HTML_FILE_ERROR = "* Please choose only html file in [1].";
var PDF_FILE_ERROR = "* Please choose only PDF file in [1].";
var ZIP_FILE_ERROR = "* Please choose only Zip file in [1].";


var IMAGE_FILE = /\.(gif|jpeg|jpg|bmp)$/gi;
var DOC_FILE = /\.(doc|xls|DOC|XLS)$/gi;
var HTML_FILE = /\.(htm|html)$/gi;
var PDF_FILE = /\.(pdf|PDF)$/gi;
var ZIP_FILE = /\.(zip|ZIP)$/gi;


var MAX_LENGTH_ERROR = "* Maximum no of character is allowed in [1] is [2].";
var MONEYVALUE_ERROR = " * [1]  Accepts Only Numbers and Two Decimal Points. Ex[XXXXXXXX.XX]."; 
var PLRVALUE_ERROR = " * [1]  Accepts Only Numbers,Hyphen and Two Decimal Points.Ex[XX.XX-XX.XX]"; 
var FIRSTALPHA_ERROR = "* [1] Start with Alphabet.";
var EMAIL_ERROR = "* Invalid Email ID.Accepts only Alphabets,Numbers,Dot,Hyphen,@ and Underscore. \n   Email ID start with Alphabet.EX[XXXXXXXXX@XXXXX.XXX].";
var PHONE_ERROR ="* Invalid Phone Number. Phone Number Accepts Numbers,Hyphen only.Ex[XXX-XXXXXXXX].";
var MOBILE_ERROR = "* Invalid Mobile Number. Mobile Number Accepts Numbers,Hyphen only.Ex[XX-XXXXX-XXXXX].";
var PINCODE_ERROR = "* Invalid Pin Number. Pin Number Accepts Numbers.Ex[XXXXXX] Or [xxx xxx].";
var NAME_ERROR = "* [1] accepts only Alphabets and Space. [1] start with Alphabet.";
var ADDRESS_ERROR = "* Invalid Address. Address Accepts Alphabets,Numbers and some Special characters [# , . / -].";
var COMPANY_ERROR = "* [1] accepts only Alphabets, numbers, spaces and special characters like \n    Dot,hyphen,comma, ',@,(),&. [1] start with Alphabet.";
var FILENAME_ERROR = "* [1] accepts only Alphabets, Numbers and some Special characters [/_ - . /].";

var CURRENTRATES_ERROR = "* [1] accepts only Numbers and some Special characters [- . %].";

var ErrorMessage ="" ;
var ErrorFlag;
var ErrorElement;



/**
	This function takes user form as an input parameter and it traverse one by one form element according 
	to attributes it will pass the control to other functions. If any function returns false then it will display
	alert message to the user and control will return to the caller.
	
	@input	form		user form
	@output	false if it user enters any wrong character or true

*/

function jsfValidateForm(form) {
	var attValid;
	var objElement;
	var controls = jsfChildElements(form);
	ErrorFlag =false;
	ErrorElement = null;
	for(var i = 0; i < controls.length; i++) {
		objElement = controls[i];
		attValid = objElement.getAttribute("valid");
//		alert(attValid);
		if (attValid)  {
			jsfCheckFormElement(objElement, attValid) 
		}
	}

	if(ErrorFlag) {
		alert(ErrorMessage);
		ErrorMessage = '';
		ErrorElement.focus();
		return false;
	}
	return true;
}

function jsfChildElements(inputCtl) {
	if(inputCtl.tagName == "FORM" ) {
		return inputCtl.elements;
	}else {
		arrObject = new Array();
		arrObject = jsfAddObjectToArray(arrObject, inputCtl.getElementsByTagName("INPUT"));
		arrObject = jsfAddObjectToArray(arrObject, inputCtl.getElementsByTagName("SELECT"));
		arrObject = jsfAddObjectToArray(arrObject, inputCtl.getElementsByTagName("TEXTAREA"));
		arrObject = jsfAddObjectToArray(arrObject, inputCtl.getElementsByTagName("hidden"));
		return arrObject;
	}
}

function jsfAddObjectToArray(array, object) {
	for(var i=0; i < object.length; i++) {
		array[array.length] = object[i];
	}
	return array;
}

function jsfClearValues(inputCtl) {
	var controls = jsfChildElements(inputCtl);
	for(var i = 0; i < controls.length; i++) {
		if(controls[i].type == "text" || controls[i].type.match("^select") || controls[i].type.match("^checkbox") || controls[i].type.match("^password")) {
			controls[i].value = "";
		}
	}
}

/**
	This function check the giving form element according to their valid parameter

	@input objElement Form element
	@input	attValid	Attribute in each form element
	@output	false if it user enters any wrong character or true

*/

function jsfCheckFormElement(objElement, attValid) {
	
	if ( attValid.match( /^m/i ) )  {
		if ( !jsfCheckMandatory(objElement) ) {
			return false;
		}
	}
	
	if ( trim(objElement.value) != "" ) {
			
		var result = new String(attValid.match(/_\w$/gi));
		result = result.substr(1, 1);
		//alert(result);
		
		switch (result) {
			
			case "i":
				if ( !jsfCheckInteger(objElement) )
				{
				//	return false;
				}
				break;

			case "r":
				if ( !jsfCheckReal(objElement) )
				{
					//return false;
				}
				break;
			
			case "d":
				if ( !jsfCheckDate(objElement) )
				{
					//return false;
				}
				break;

			case "a":
				if ( !jsfCheckAlphaNumeric(objElement) ) 
				{
					//return false;
				}
				break;

			case "s":
				if ( !jsfCheckSpecialChar(objElement) ) {
					//return false;
				}
				break;

			case "f":
				if ( !jsfCheckFile(objElement) ) 
				{
					//return false;
				}
				break;

			case "z":
					if(!jsfCheckMoneyValue(objElement) ) 
					{
						
						//return false;
					}
					break;
			
			case "y":
					if(!jsfCheckFirstAlphabet(objElement) ) 
					{
						//return false;
					}
					break;
			
			case "e":
					if(!jsfCheckEmail(objElement) ) 
					{
						//return false;
					}
				break;

			case "t":
					if(!jsfCheckPhone(objElement) ) 
					{
						//return false;
					}
				break;


    		case "c":
					if(!jsfCheckMobilePhone(objElement) ) 
					{
						//return false;
					}
				break;

			case "p":
					if(!jsfCheckPincode(objElement) ) 
					{
						//return false;
					}
				break;

			case "x":
					if(!jsfCheckName(objElement) ) 
					{
						//return false;
					}
				break;

			case "w":
					if(!jsfCheckAddress(objElement) ) 
					{
						//return false;
					}
				break;
			case "b":
					if(!jsfCheckAlphaNumericAmp(objElement) ) 
					{
						//return false;
					}
				break;
			case "q":
					if(!jsfCheckCompanyName(objElement) ) 
					{
						//return false;
					}
				break;
			case "v":
				if(!jsfCheckFileName(objElement) ) 
				{
					//return false;
				}
				break;
			case "g":
				if(!jsfCheckPLRValue(objElement) ) 
				{
					//return false;
				}
			break;

			case "l":
				if(!jsfCurrentRates(objElement) ) 
				{
					//return false;
				}
				break;
		}
	
	}

	if ( !jsfCheckMaxLength(objElement) ) {
		//return false;
	}
	if(ErrorFlag && !ErrorElement) ErrorElement = objElement;
	return true;
}

/**
	This function checks whether the given form element contains any value or not

	@input objElement as Form Element
	@output value boolean true if it contains any value otherwise false
*/

function jsfCheckMandatory(objElement) {
	var type="enter";
	if ( trim(objElement.value) == "" ) {
	if(objElement.type.match("^select")) type = "select";
	jsfDisplayErrorMessage(MANDATORY_ERROR, type,objElement.getAttribute("errname"));
	ErrorFlag = true;
	//objElement.focus();
	//return false;
	

	}
	return true;
}


/**
	This function checks the given value in the form is an integer

	@input objElement as Form Element
	@output value boolean true if it is an integer or false
*/

function jsfCheckInteger(objElement) {
	var re = /^[1-9]\d*|^0$/gi
	if ( objElement.value.match(re) != objElement.value ) {
		jsfDisplayErrorMessage(INTEGER_ERROR, objElement.getAttribute("errname"));
		ErrorFlag = true;
	}
	return true;
}

/**
	This function checks the given value in the form is an real

	@input objElement as Form Element
	@output value boolean true if it is an real or false
*/

function jsfCheckReal(objElement) {
	var re = /^[1-9]\d*\.?\d*|^0\.\d+|^0$/gi
	if ( objElement.value.match(re) != objElement.value ) {
		jsfDisplayErrorMessage(REAL_ERROR, objElement.getAttribute("errname"));
		ErrorFlag = true;
	}
	return true;
}

/**
	This function checks the given value in the form is an valid calendar date

	@input objElement as Form Element
	@output value boolean true if it is an valid calendar date or false
*/

function jsfCheckDate(objElement) {
	if ( !jsfCheckDateByValue(objElement.value) ) {
		jsfDisplayErrorMessage(DATE_ERROR, objElement.getAttribute("errname"));
		ErrorFlag = true;
	}
	return true;
}

function jsfCheckDateByValue(strInput) {
	var re = /^((29-0?2-\d{2}([13579][26]|[02468][048]))|((0?[1-9]|[1-2]\d|3[0-1])-(0?[13578]|10|12)-\d{4})|((0?[1-9]|[1-2]\d|30)-(0?[469]|11)-\d{4})|((0?[1-9]|1\d|2[0-8])-0?2-\d{4}))/g;
	strInput = strInput.replace(/\//g,"-");
	if (strInput.match(re) == strInput) {
		return true;
	}
	return false;
}


//	This function checks the given value in the form is alpha numeric character	

function jsfCheckAlphaNumeric(objElement) {
	var re = /^[a-zA-Z0-9\s]*/gi;
	if ( objElement.value.match(re) != objElement.value ) {
		jsfDisplayErrorMessage(ALPHA_ERROR, objElement.getAttribute("errname"));
		ErrorFlag = true;
	}
	return true;
}

/**
	This function checks the given value in the form is special character

	@input objElement as Form Element
	@output value boolean true if it is special char or false
*/

function jsfCheckSpecialChar(objElement) {
	var re = /^[a-zA-Z][\w\W]*/gi;
	if ( objElement.value.match(re) != objElement.value ) {
		jsfDisplayErrorMessage(SPECIAL_ERROR, objElement.getAttribute("errname"));
		ErrorFlag = true;
	}
	return true;
}

/**
	This function checks the given file is in right format according to the file type attribute

	@input objElement as Form Element
	@output value boolean true if it is in correct format or false
*/

function jsfCheckFile(objElement) {

	var fileType = objElement.getAttribute("filetype");
	//alert(fileType);

	switch (fileType) {
		case "image":
			if ( !objElement.value.match(IMAGE_FILE) )  {
				jsfDisplayErrorMessage(IMAGE_FILE_ERROR, objElement.getAttribute("errname"));
				objElement.focus();
				//return false;
				ErrorFlag = true;
			}
			break;
		case "doc":
			if ( !objElement.value.match(DOC_FILE) )  {
				jsfDisplayErrorMessage(DOC_FILE_ERROR, objElement.getAttribute("errname"));
				objElement.focus();
				//return false;
				ErrorFlag = true;
			}
			break;

			case "pdf":
			if ( !objElement.value.match(PDF_FILE) )  {
				jsfDisplayErrorMessage(PDF_FILE_ERROR, objElement.getAttribute("errname"));
				objElement.focus();
				//return false;
				ErrorFlag = true;
			}
			break;
		
		case "html":
			if ( !objElement.value.match(HTML_FILE) )  {
				jsfDisplayErrorMessage(HTML_FILE_ERROR, objElement.getAttribute("errname"));
				objElement.focus();
				ErrorFlag = true;

				//return false;
			}
			break;

			case "zip":
			if ( !objElement.value.match(ZIP_FILE) )  {
				jsfDisplayErrorMessage(ZIP_FILE_ERROR, objElement.getAttribute("errname"));
				objElement.focus();
				ErrorFlag = true;

				//return false;
			}
			break;
	
	}
	return true;
}


/**
	This function check the maximum length of the particular element and it display error when maxlength is exceed.

	@input formElement 
	@output true if it does not exceed maxlength otherwise false
*/

function jsfCheckMaxLength(objElement) {
	var maxLength = objElement.getAttribute("maxlength");
	if ( !maxLength ) {
		maxLength = objElement.getAttribute("maxlen");
	}
	if (maxLength) {
		maxLength = parseInt(maxLength);
		var length = objElement.value.length;
		if (length > maxLength) {
			jsfDisplayErrorMessage(MAX_LENGTH_ERROR, objElement.getAttribute("errname"), maxLength);
			ErrorFlag = true;
		}
	}
	return true;
}


/**
	This function display error message in alert box to the user. This function takes n number of parameters.

	@input errorMsg string which error message has to be displayed
	@params n number of parameter will replace the place holder in the error message

*/

function jsfDisplayErrorMessage(errorMsg) {
	var argv = arguments;
	var argc = arguments.length;
	for ( var i = 0; i < argc ; i++ ) {
		var re = new RegExp("\\["+i+"\\]","g");
		errorMsg = errorMsg.replace(re, argv[i]);
	}
	ErrorMessage += errorMsg + "\n";
	//alert(errorMsg);
	//return true;
}

/**
	This function replaces the leading and trailing whitespaces
	@input strInput any string value
	@output value after removing leading & trailing whitespaces
*/

function trim(strInput) {
	return strInput.replace(/(^\s*|\s*$)/gi,"");
}

/**
	This function reset whole form parsing one by one element
	@input form to be resetted

*/

function jsfClearForm(form) {
	var type, objElement;
	for(var i=0; i < form.elements.length; i++) {
		objElement = form.elements[i];
		type = objElement.type;
		if  (type.match(/text|textarea/) )	{
			objElement.value = "";
		}
		if (type == "select" ) {
			objElement.selectedIndex = 0;
		}
	}
}

/**
	This function check the URL is correctly given or not
	@input URl to be checked
	@return true it the url is correctly formatted, otherwise false
*/

function jsfCheckUrl(url) {
	var re = /[\.\/\\]|http/gi
	if ( url.match(re) ) {
		return true;
	}
	return false;
}


/**
	This function change date to long
*/
function jsfGetLongDate(dd,mm,yy){
	dd=dd.toString()
	mm=mm.toString()
	yy=yy.toString()
	return parseInt(yy+mm+dd)
}
/**
	Extract date from given form date 
*/
function jsfGetFormDate (date) {
	var re = /^(0?\d{1,2})[\/-]0?\d{1,2}[\/-]\d{4}/g
	var arr= re.exec(date);
	var ret = false;
	for (i in arr) {
		if ( i==1) ret = true;
	}
	if (ret) return jsfCheckDateLength( arr[1] );
	return 0;
}

/**	
	Extract month from given form date 
*/
function jsfGetFormMonth (date) {
	var re = /^0?\d{1,2}[\/-](0?\d{1,2})[\/-]\d{4}/g
	var arr= re.exec(date);
	var ret = false;
	for (i in arr) {
		if ( i==1) ret = true;
	}
	if (ret) return jsfCheckDateLength( arr[1] );
	return 0;
}

/**
	Extract year from given form date 
*/

function jsfGetFormYear (date) {
	var re = /^0?\d{1,2}[\/-]0?\d{1,2}[\/-](\d{4})/g
	var arr= re.exec(date);
	var ret = false;
	for (i in arr) {
		if ( i==1) ret = true;
	}
	if (ret) return arr[1];
	return 0;
}
 
 /**
	This function compare two dates
 */
function jsfCompareDate (date1,date2) {
	var date1 = jsfGetLongDate ( jsfGetFormDate(date1), jsfGetFormMonth(date1), jsfGetFormYear(date1));
	var date2 = jsfGetLongDate ( jsfGetFormDate(date2), jsfGetFormMonth(date2), jsfGetFormYear(date2));
	if (date1 == date2) return 0;
	if (date1 > date2) return 1;
	if (date1 < date2) return -1;
}

function jsfCheckDateLength (date) {
	var strDate = date.toString();
	if ( strDate.length == 1) strDate = "0"+strDate;
	return strDate;
}

/* This Function Checks the First Letter Should be Alphabet */

function jsfCheckFirstAlphabet(objElement) 
	{
		var re=/^[a-z]/gi
		if(objElement.value.match(re) != objElement.value)
		{
			jsfDisplayErrorMessage(FIRSTALPHA_ERROR,objElement.getAttribute("errname"));
			ErrorFlag = true;
		}
		return true;
}


/*  This Function Checks the Money Value . The Length is 11 for example (12345678.00) */
function jsfCheckMoneyValue(objElement)
	{
			
		var re = /^[1-9][0-9]{0,7}(\.[0-9]{2})?$/gi
		if(objElement.value.match(re) != objElement.value)
		{
			jsfDisplayErrorMessage(MONEYVALUE_ERROR, objElement.getAttribute("errname"));
			ErrorFlag = true;
		}
	return true;
} 

/*  This Function Checks the Valid Email. */

function jsfCheckEmail(objElement)
	{
		if(!jsfCheckEmailByValue(objElement.value))
		{
			jsfDisplayErrorMessage(EMAIL_ERROR, objElement.getAttribute("errname"));
			ErrorFlag = true;
		}
	return true;
} 


function jsfCheckEmailByValue(value) {
	var re = /^([a-zA-z])*([a-zA-z\.])\w+([\.\-]\w+)*\@\w+([\-\.]\w+)*\.[a-z]{2,4}$/gi	
	
	if(value.match(re) != value)	{
		return false;
	}
	return true;
}

/* This Function checks the valid Phone No. with STD code and Hyphen  */

function jsfCheckPhone(objElement)
	{
		var re = /^\d{2,5}-\d{6,8}/gi
		if(objElement.value.match(re) != objElement.value)
		{
				 
			jsfDisplayErrorMessage(PHONE_ERROR, objElement.getAttribute("errname"));
			ErrorFlag = true;
		}
	return true;
}

/* This Function checks the valid Mobile No. with code and Hyphen  */

function jsfCheckMobilePhone(objElement)
	{
		var re = /^\d{2}-\d{5}-\d{5}/gi
		if(objElement.value.match(re) != objElement.value)
		{
				 
			jsfDisplayErrorMessage(MOBILE_ERROR, objElement.getAttribute("errname"));
			ErrorFlag = true;
		}
	return true;
}

/* This Function checks the valid Address. */

function jsfCheckPincode(objElement)
	{
		var re = /^(\d{6})|(\d{3}\s\d{3})/gi
		if(objElement.value.match(re) != objElement.value)
		{
				 
			jsfDisplayErrorMessage(PINCODE_ERROR, objElement.getAttribute("errname"));
			ErrorFlag = true;
		}
	return true;
}

/* This Function checks the valid Name. */

function jsfCheckName(objElement)
	{
		var re = /^[a-zA-Z][a-zA-Z\s]*/gi
		if(objElement.value.match(re) != objElement.value)
		{
				 
			jsfDisplayErrorMessage(NAME_ERROR, objElement.getAttribute("errname"));
			ErrorFlag = true;
		}
	return true;
}

/* This Function checks the valid Address. */


function jsfCheckAddress(objElement) {
  //  alert(objElement.value);
	var re = /^[0-9a-zA-Z .,/#]+$/gi;
	if ( objElement.value.match(re) != objElement.value ) {
		jsfDisplayErrorMessage(ADDRESS_ERROR, objElement.getAttribute("errname"));
		ErrorFlag = true;
	}
	return true;
}

/* This Function checks the valid AlphaNumeric with Ampersand(&). */
function jsfCheckAlphaNumericAmp(objElement) {
	var re = /^[a-zA-Z][a-zA-Z0-9&\s]*/gi;
	if ( objElement.value.match(re) != objElement.value ) {
		jsfDisplayErrorMessage(ALPHAAMP_ERROR, objElement.getAttribute("errname"));
		ErrorFlag = true;
	}
	return true;
}

/* This Function checks the valid CompanyName with Ampersand(&). */
function jsfCheckCompanyName(objElement) {
	
	var re = /^[a-zA-Z][a-z0-9@\'.\,\&\(\)\-\s]+$/gi;
	if ( objElement.value.match(re) != objElement.value ) {
		jsfDisplayErrorMessage(COMPANY_ERROR, objElement.getAttribute("errname"));
		ErrorFlag = true;
	}
	return true;
}


/* This Function checks the valid File Name. */

function jsfCheckFileName(objElement) {
	 
	var re = /^([a-zA-z0-9])\w+([\\\-\_\.\/\s]\w+)*/gi;
	if ( objElement.value.match(re) != objElement.value ) {
		jsfDisplayErrorMessage(FILENAME_ERROR, objElement.getAttribute("errname"));
		ErrorFlag = true;
	}
	return true;
}




/*  This Function Checks the two numbers and - only. */ 

function jsfCheckPLRValue(objElement)
{
			
		var re = /^[1-9][0-9]{1,2}(\.[0-9]{2})?(\-[1-9][0-9]{1,2}(\.[0-9]{2}))?$/gi

		if(objElement.value.match(re) != objElement.value)
		{
			jsfDisplayErrorMessage(PLRVALUE_ERROR, objElement.getAttribute("errname"));
			ErrorFlag = true;
		}
	return true;
}  


/* This Function checks the valid Current Rates. */

function jsfCurrentRates(objElement) 
{
  
	var re = /^(d*[\%\-])?(\d*[\%])?$/gi

		// re = /^\d{2}-\d{5}-\d{5}/gi
		// re = /^d*[\.\d+]*[\%\-]?\d*[\.\d+]*[\%]?$/gi
		// re = /^[\-]?\d*[\.\d+]*[\%\-]?\d*[\.\d+]*[\%]?$/gi

	if ( objElement.value.match(re) != objElement.value ) {
		jsfDisplayErrorMessage(CURRENTRATES_ERROR, objElement.getAttribute("errname"));
		ErrorFlag = true;
}
	return true;
}


