/*
Module Name : SSRSJS_formValidator
Description : This collection of functions can be used to validate a form for differenct types of inputs. Multiple fields can be passed to be validated for common type
Developer : Tajinder Singh Namdhari
Developed On : 02-05-2008
License : LGPL
Company : SSRSJS Organisation
Website : http://www.ssrsjs.org
*/

/*Procedure to implement SSRSJS_formValidator

Make a call to function on respective event such as 'onKeyUp' event of text field or on change for select 
	Call as :: valiFields(fields,checkFor,clearMsg)
					fields -> Array of fields with values
								e.g. Array('txtFname',txtFname.value,'txtLname',txtLname.value)
					checkFieldsFor -> To validation rule against which fields are going to be validated
								e.g. money, phone,zip ,etc.
					clearMsg -> To specify if the previous error message should be cleared
								spec. 0 for not clearing, 1 for clearing
*/

//Options
var doMsg=0;
var doHlight=1;
var HlightBgColor='#E5F6FD';
var NormalBgColor='#FFFFFF';
var specChars=Array("?","/","*","-","&","^","%","$","#","@","!","~","`","'",";",":",">","<","[","]","{","}","|","\\","(",")","=","+",",",'"',".");

mess="";
function trimIt(trgt)
{
	return trgt.replace(/^\s+|\s+$/g, "");
}

function HighLight(op,trgt)
{
	
	if(trgt!='')
	{
		if(document.getElementById(trgt)==null)
		{	alert("This dosen't exist :: " + trgt);	}
		else	if(document.getElementById(trgt).type!='checkbox')
		{
			if(op==0)
			{
				document.getElementById(trgt).style.backgroundColor=NormalBgColor;
			}
			else if(op==1)
			{
				document.getElementById(trgt).style.backgroundColor=HlightBgColor;
			}
		}
	}
}

function Mod10(ccNumb)
{  // v2.0
	var valid = "0123456789"  // Valid digits in a credit card number
	var len = ccNumb.length;  // The length of the submitted cc number
	var iCCN = parseInt(ccNumb);  // integer of ccNumb
	var sCCN = ccNumb.toString();  // string of ccNumb
	sCCN = sCCN.replace (/^\s+|\s+$/g,'');  // strip spaces
	var iTotal = 0;  // integer total set at zero
	var bNum = true;  // by default assume it is a number
	var bResult = false;  // by default assume it is NOT a valid cc
	var temp;  // temp variable for parsing string
	var calc;  // used for calculation of each digit
	
	// Determine if the ccNumb is in fact all numbers
	for (var j=0; j<len; j++)
	{
		temp = "" + sCCN.substring(j, j+1);
		if (valid.indexOf(temp) == "-1"){bNum = false;}
	}
	
	// if it is NOT a number, you can either alert to the fact, or just pass a failure
	if(!bNum)
	{
		/*alert("Not a Number");*/bResult = false;
	}
	
	// Determine if it is the proper length 
	if((len == 0)&&(bResult))
	{  // nothing, field is blank AND passed above # check
		bResult = false;
	}
	else
	{  // ccNumb is a number and the proper length - let's see if it is a valid card number
		if(len >= 15)
		{  // 15 or 16 for Amex or V/MC
			for(var i=len;i>0;i--)
			{  // LOOP throught the digits of the card
				calc = parseInt(iCCN) % 10;  // right most digit
				calc = parseInt(calc);  // assure it is an integer
				iTotal += calc;  // running total of the card number as we loop - Do Nothing to first digit
				i--;  // decrement the count - move to the next digit in the card
				iCCN = iCCN / 10;                               // subtracts right most digit from ccNumb
				calc = parseInt(iCCN) % 10 ;    // NEXT right most digit
				calc = calc *2;                                 // multiply the digit by two
				// Instead of some screwy method of converting 16 to a string and then parsing 1 and 6 and then adding them to make 7,
				// I use a simple switch statement to change the value of calc2 to 7 if 16 is the multiple.
				switch(calc)
				{
					case 10: calc = 1; break;       //5*2=10 & 1+0 = 1
					case 12: calc = 3; break;       //6*2=12 & 1+2 = 3
					case 14: calc = 5; break;       //7*2=14 & 1+4 = 5
					case 16: calc = 7; break;       //8*2=16 & 1+6 = 7
					case 18: calc = 9; break;       //9*2=18 & 1+8 = 9
					default: calc = calc;           //4*2= 8 &   8 = 8  -same for all lower numbers
				}                                               
				iCCN = iCCN / 10;  // subtracts right most digit from ccNum
				iTotal += calc;  // running total of the card number as we loop
			}  // END OF LOOP
			if ((iTotal%10)==0)
			{  // check to see if the sum Mod 10 is zero
				bResult = true;  // This IS (or could be) a valid credit card number.
			}
			else
			{
				bResult = false;  // This could NOT be a valid credit card number
			}
		}
	}
	// change alert to on-page display or other indication as needed.
	/*if(bResult)
	{
		alert("This IS a valid Credit Card Number!");
	}
	if(!bResult)
	{
		alert("This is NOT a valid Credit Card Number!");
	}*/
	
	return bResult; // Return the results
}

function valiFields(fields,checkFieldsFor,clearMsg,highLightFields)
{
	if(clearMsg == null)
	{	clearMsg=0;	}

	if(doHlight == null)
	{	highLightFields=1;	}
	doHlight = highLightFields;
	
	if(fields.length != checkFieldsFor.length)
	{	alert("Count dosen't match in validFields!");	return false;	}
	
	if(clearMsg!=0)
	{	mess="";	}
		
	var lmt=fields.length;
	for(i=0;i<lmt;i=i+2)
	{
		//alert(fields[i]);
		checkFor = checkFieldsFor[i];
		
		if(checkFor=="req")
		{
			HighLight(0,fields[i]);
			if(trimIt(document.getElementById(fields[i]).value)=="")
			{
				document.getElementById(fields[i]).value=trimIt(document.getElementById(fields[i]).value);
				mess+="Please don't leave " + fields[i+1] + " field blank\n";
				HighLight(1,fields[i]);
			}
		}
		else if(checkFor=="alphanum")
		{
			var currVal=document.getElementById(fields[i]).value;
			var valLmt=currVal.length;
			var currPos=-1;
			var repDone=0;
			
			for(c=0;c<32;c++)
			{
				if(currVal.indexOf(specChars[c])!=-1)
				{
					currVal=currVal.replace(specChars[c],'');
					c--;
					repDone=1;
				}
			}
			if(repDone==1)
			{	document.getElementById(fields[i]).value=currVal;	}
		}
		else if(checkFor=="num")
		{
			HighLight(0,fields[i]);
			if((isNaN(document.getElementById(fields[i]).value)==true)||(document.getElementById(fields[i]).value.indexOf('e')!=-1)||(document.getElementById(fields[i]).value.indexOf('.')!=-1))
			{
				mess+="Please enter valid value for " + fields[i+1] + "\n";
				HighLight(1,fields[i]);
			}
		}
		else if(checkFor=="numrange")
		{
			var currField=fields[i].split("-");
			var field=new Array();
			field.concat(fields);
			HighLight(0,currField[0]);
			if(valiFields(Array(currField[0],fields[i+1]),'num'))
			{
				if((document.getElementById(currField[0]).value!='')&&((parseInt(document.getElementById(currField[0]).value)<parseInt(currField[1]))||(parseInt(document.getElementById(currField[0]).value)>parseInt(currField[2]))))
				{
					mess+="Please enter numeric value for " + field[i+1] + " between " + currField[1] + " to " + currField[2] + "\n";
					HighLight(1,currField[0]);
				}
			}
			fields=new Array();
			fields.concat(field);
		}
		else if(checkFor=="money")
		{
			HighLight(0,fields[i]);
			if((isNaN(document.getElementById(fields[i]).value)==true)||(document.getElementById(fields[i]).value.indexOf('e')!=-1))
			{
				mess+="Please enter valid value for " + fields[i+1] + "\n";
				HighLight(1,fields[i]);
			}
		}
		else if(checkFor=="zip")
		{
			currZip=fields[i].split("-");
			HighLight(0,currZip[0]);
			if(document.getElementById(currZip[0]).value.length<currZip[1])
			{
				mess+="Please enter 5 Digit Zip code for " + fields[i+1] + "\n";
				HighLight(1,currZip[0]);
			}
		}
		else if(checkFor=="phone")
		{
			var currPh=fields[i].split("-");
			HighLight(0,currPh[0]);
			HighLight(0,currPh[1]);
			HighLight(0,currPh[2]);
			//alert(currPh[0]+"-"+currPh[1]+"-"+currPh[2]);
			if(((document.getElementById(currPh[0]).value=="")||(document.getElementById(currPh[1]).value=="")||(document.getElementById(currPh[2]).value==""))||((document.getElementById(currPh[0]).value.length<3)||(document.getElementById(currPh[1]).value.length<3)||(document.getElementById(currPh[2]).value.length<4))||((isNaN(document.getElementById(currPh[0]).value))||(isNaN(document.getElementById(currPh[1]).value))||(isNaN(document.getElementById(currPh[2]).value))||((document.getElementById(currPh[0]).value.indexOf(".")!=-1)||(document.getElementById(currPh[1]).value.indexOf(".")!=-1)||(document.getElementById(currPh[2]).value.indexOf(".")!=-1))||((document.getElementById(currPh[0]).value.indexOf("e")!=-1)||(document.getElementById(currPh[1]).value.indexOf("e")!=-1)||(document.getElementById(currPh[2]).value.indexOf("e")!=-1))))
			{
				mess+="Please enter valid value for " + fields[i+1] + "\n";
				HighLight(1,currPh[0]);
				HighLight(1,currPh[1]);
				HighLight(1,currPh[2]);
			}
		}
		else if((checkFor=="email")||(checkFor=="emailop"))
		{
			HighLight(0,fields[i]);
			currEmail=document.getElementById(fields[i]).value;
			var filter=/^.+@.+\..{2,3}$/
			if(!filter.test(currEmail))
			{
				mess = mess + "Please enter valid " + fields[i+1] + " :" + currEmail + "\n";
				HighLight(1,fields[i]);
			}
		}
		else if(checkFor=="passlen")
		{
			currPass=fields[i].split("-");
			HighLight(0,currPass[0]);
			if(document.getElementById(currPass[0]).value.length<currPass[1])
			{
				mess=mess + "Password should be at least of " + currPass[1] + " characters\n";
				HighLight(1,currPass[0]);
			}
		}
		else if(checkFor=="pass")
		{
			currPass=fields[i].split("-");
			HighLight(0,currPass[0]);
			HighLight(0,currPass[1]);
			if(document.getElementById(currPass[0]).value!=document.getElementById(currPass[1]).value)
			{
				mess=mess + "Passwords do not match\n";
				HighLight(1,currPass[0]);
				HighLight(1,currPass[1]);
			}
		}
		else if(checkFor=="len")
		{
			var currField=fields[i].split('-');
			if((document.getElementById(currField[0]).value.length<currField[1])||(document.getElementById(currField[0]).value.length>currField[2]))
			{
				mess+="Please make sure field " + fields[i+1] + " is having length of " + currField[1] + " to " + currField[2];
				HighLight(1,currField[0]);
			}
		}
		else if(checkFor=="ccard")
		{
			var d=new Date();
			var currCard=fields[i].split('-');
			//					   0 -  1   - 2 - 3  -  4
			//Splitter will be : Name-Number-Sec-Month-Year fields' DOM IDs
			var currCap=fields[i+1].split('-');
			//Splitter will be : Name-Number-Sec-Month-Year fields' Captions
			HighLight(0,currCard[0]);
			HighLight(0,currCard[1]);
			HighLight(0,currCard[2]);
			HighLight(0,currCard[3]);
			HighLight(0,currCard[4]);
			
			if((document.getElementById(currCard[3]).value<(d.getMonth()/1+1))&&(document.getElementById(currCard[4]).value==d.getFullYear()))
			{
				mess+=currCap[3]+" is invalid.\n";
				HighLight(1,currCard[3]);
			}
			
			if(!Mod10(document.getElementById(currCard[1]).value))
			{
				mess+=currCap[1]+" is invalid.\n";
				HighLight(1,currCard[1]);
			}
			
		}
		else if(checkFor=="file")
		{
			var currFile;
			HighLight(0,fields[i]);
			
			if(document.getElementById(fields[i]).value.indexOf('/')!=-1)
			{	currFile=document.getElementById(fields[i]).value.split('/');	}
			else if(document.getElementById(fields[i]).value.indexOf('\\')!=-1)
			{	currFile=document.getElementById(fields[i]).value.split('\\');	}
			alert(currFile);return false;
			len=currFile.length;
			eleend=currFile[len-1].split(".");
			elelen=eleend.length;
			if(eleend[elelen-1].length!=3)
			{
				mess+="Please select an appropriate " + fields[1] + "\n";
				HighLight(1,fields[i]);
			}
		}
		else
		{
			var currFile;
			HighLight(0,fields[i]);
			if(document.getElementById(fields[i]).value.indexOf('/')!=-1)
			{	currFile=document.getElementById(fields[i]).value.split('/');	}
			else if(document.getElementById(fields[i]).value.indexOf('\\')!=-1)
			{	currFile=document.getElementById(fields[i]).value.split('\\');	}
			len=currFile.length;
			eleend=currFile[len-1].split(".");
			elelen=eleend.length;
			if(eleend[elelen-1].toUpperCase()!=checkFor.toUpperCase())
			{
				mess+="Make sure you have selected only ." + checkFor + " file for " + fields[i+1];
				HighLight(1,fields[i]);
			}
		}
	}
	
	if(mess=="")
	{	return true;	}
	else if(checkFor=="phone")
	{	return false;	}
	else if(checkFor=="emailop")
	{	return false;	}
	else if(doMsg==0)
	{	return false;	}
	else
	{	alert(mess);	return false;	}
}

/*
// DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)

// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=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 i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		return false
	}
return true
}

function ValidateForm(){
	var dt=document.frmSample.txtDate
	if (isDate(dt.value)==false){
		dt.focus()
		return false
	}
    return true
 }*/
