//Constants - characters to be validated

var SPL_CHAR_BAG = '<>/?,.;:"~`!@#$%^&*()-_=+\\|[]{}' + "'";   //all special chars
var NAME_CHAR_BAG = '<>?"~`!@$%^*=+\\|{}';  //First Name, Last name
var ADDRESS_CHAR_BAG = '<>?~`!@$%^*=+\\|{}';  //address specific special chars for City, State, Country, Title, Address1 and Address2
var PHONE_CHAR_BAG = '<>/?,.;:"~`!@#$%^&*=+\\|{}' + "'"; // for Biz ph, Home ph, Cell and Other ph.
var PWD_CHAR_BAG = '<>/?,.;:~`!@#$%^&*()=+\\|[]{}' + "'" // for User login and passwords
var A_Z_CHAR_BAG = 'abcdefghijklmnopqrstuvwxyz';

function isblank(s)
{
	if ((s==null) || (s==' '))
	{
		return false;
	}
	for (var i = 0; i < s.length; i++) {
		var c = s.charAt(i);
		if ((c!= ' ') && (c != '\n') && (c != '\t')) return false;
	}
	return true;
}

function spaceBetChars(str)
{
	for (var i=0;i<str.length;i++)
	{
		if (str.charAt(i) == " ") return false
	}

	return true;
}

function validateSplChars(str,dispName,charBag)
{
	var j;
	var charBag = '<>/?,;:"~`!#$%^&*()-=+\|[]{}' + "'";
	if (str.length>0 || charBag.length>0)
	{
		//loop for not allowed special chars
		for (j=0;j<charBag.length; j++)
		{
			if (str.indexOf(charBag.charAt(j))>=0)
			{
				if (dispName != '');
				return false;
			}
		}
	}
	return true;
}

function validateEmail(email,dispName)
{
	//check for space
	if (!spaceBetChars(email))
	{
		if (dispName != '');
		return false;
	}

	//check for special chars
	var charBag = '<>/?,;:"~`!#$%^&*()-=+\|[]{}' + "'";
	if (!validateSplChars(email,dispName,charBag)) return false;

     // there must be >= 1 character before @
     var sLength = email.length;
     var lPos = email.indexOf("@");

     //check additional cond for sencond occurance of @	and atleast one occurance of dot
     if ((lPos<=0) || (lPos >= sLength) || (email.indexOf("@",lPos+1)>=0) || (email.indexOf(".",lPos+2)==-1))
     {
		if (dispName != '');
		return false;
     }

     return true;
}

// Added By Santosh Kumar
//function	to validate URL
function validateURL(URL,dispName)
{
	//check for space
	if (!spaceBetChars(URL))
	{
		if (dispName != '')
		return false;
	}
	
	//check for special chars
	//allowed /?&
	var charBag = '<>,;:"~`!#$%^*()-=+\|[]{}' + "'";
	if (!validateSplChars(URL,dispName,charBag)) return false;

     // there must be >= 1 character before @
     var sLength = URL.length;
     var lPos = URL.indexOf(".");
     
     //check additional cond for sencond occurance of @	and atleast one occurance of dot 
     if ((lPos<=0) || (lPos >= sLength)) 
     {
		if (dispName != '');
		return false;
     }

     return true;
}

function isCreditCard(st) {
  // Encoding only works on cards with less than 19 digits
  if (st.length > 19)
    return (false);

  sum = 0; mul = 1; l = st.length;
  for (i = 0; i < l; i++) {
    digit = st.substring(l-i-1,l-i);
    tproduct = parseInt(digit ,10)*mul;
    if (tproduct >= 10)
      sum += (tproduct % 10) + 1;
    else
      sum += tproduct;
    if (mul == 1)
      mul++;
    else
      mul--;
  }
  if ((sum % 10) == 0)
    return (true);
  else
    return (false);

} // END FUNCTION isCreditCard()


function isValidExpDate(dtValue) {
	//validation of creditcard expiry date
	var mm,yy,curDate;

	mm=dtValue.substring(0,2);
	yy='20'+dtValue.substring(2,4);
	
	curDate = new Date();
	cyy=curDate.getYear();

	if (mm>12 || mm<0)
		return (false);
		
	if (yy<curDate.getYear())
		return (false);
		
	if (yy=curDate.getYear()){
		if (mm<curDate.getMonth()+1){
			return (false);	
		}
	}
	return true;
} // END FUNCTION isValidExpDate()

function isValidFormat(dtValue){
	var dd = dtValue.substring(2,3);
	var mm = dtValue.substring(5,6);
	if( dd != "/" || mm != "/" ){
		return false;
	}
}

//function	to convert the dateformats to the standard format (mm/dd/yyy)
function convertToStdFormat(dtValue, dtFormat)
{
	var mm,dd;

	if(dtFormat == "mm/dd/yyyy")
	{
		var mm=dtValue.substring(0,2);
		var dd=dtValue.substring(3,5);
		var sFinal = mm + "/" + dd + "/" + dtValue.substring(6,10);
	}
	else if(dtFormat == "dd/mm/yyyy")
	{
		var dd=dtValue.substring(0,2);
		var mm=dtValue.substring(3,5);
		var sFinal = dd + "/" + mm + "/" + dtValue.substring(6,10);
	}
	return sFinal;

}

//check for a valid date
function isValidDate(dt)
{
	var dtValue=dt.value;
	var dtFormat=dt.format;

	if(dtValue == "")
		return true;

	var sDate=convertToStdFormat(dtValue,dtFormat);

	if(sDate.length!=10 || sDate.charAt(2)!='/' || sDate.charAt(5) !='/')
	{
		return false;
	}

	//1 - > MM/DD/YYYY , 2 - > DD/MM/YYYY

	var mm=parseInt(sDate.substring(0,2),10);
	var dd=parseInt(sDate.substring(3,5),10);

	var year=parseInt(sDate.substring(6,10),10);
	var months = new Array([31],[28],[31],[30],[31],[30],[31],[31],[30],[31],[30],[31]);

	if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0 )
	    months[1]=29;
	if(mm > 12 || isNaN(mm) || mm<=0 || sDate.charAt(1)<'0' || sDate.charAt(1)>'9')
	{
		 return false;
	}
	if( months[mm-1]< dd || isNaN(dd) || dd <=0 || sDate.charAt(4)<'0' || sDate.charAt(4)>'9')
	{
		 return false;
	}

	if(year<1753 || isNaN(year))
	{
		 //alert("Not a valid Year. Should be >= 1753");
		 return false;
	}

	// Uncomment the following code to specify a max value
	// for the year.
	/*if(year>2070 || isNaN(year))
	{
		 alert ("Not a valid Year. Should be <= 2070");
		 return false;
	}
	 return true;*/
}

// Added By Saravanan G
// This function is to compare two dates(Start and End dates).
// It'll return false, if the first date is greater than second one.
// It'll return true, if the first date is lesser than or equal to second one.
function isOrderedDate(dt1,dt2,isCheck)
{
	// If both the fields are empty, it can be allowed.
	if ((dt1.value=='') && (dt2.value==''))
		return true;

	msg = '______________________________________________________\n\n'
	msg += 'The form was not submitted because of the following error(s).\n';
	msg += 'Please correct these error(s) and re submit.\n';
	msg += '______________________________________________________\n\n'

	// If one of the fields has data and the other is empty
	// it is not allowed.
	if (isCheck)
	{
		if ((dt1.value=='') || (dt2.value==''))
		{
			msg = msg + '-Both ' + dt1.display + ' and ' + dt2.display + ' should be filled.';
			alert(msg);
			return false;
		}
	}

	/*if (isValidDate(dt1)==false)
	{
		alert('The field ' + dt1.display + ' must be a valid date. \n');
		return false;
	}

	if (isValidDate(dt2)==false)
	{
		alert('The field ' + dt2.display + ' must be a valid date. \n');
		return false;
	}*/

	var date1=new Date(convertToStdFormat(dt1.value,dt1.format));
	var date2=new Date(convertToStdFormat(dt2.value,dt2.format));

	if (!(isNaN(date1) || isNaN(date2)))
	{
		if (date1 <= date2)
			return true;
		else
		{
			msg = msg + '-' + dt1.display + ' can not be later than ' + dt2.display;
			alert(msg);
			return false;
		}
	}
	else
		return true;
}// END FUNCTION isOrderedDate()

// Added By Mahesh
//function	to validate phone numbers in the format (xxx-xxx-xxxx)
function isValidPhNumber(PhNumber)
{
	var PhNumberFormat = PhNumber.format;
	var PhNumberValue=PhNumber.value;

	if (PhNumberFormat == "xxx-xxx-xxxx")
	{
		if(PhNumberValue.length!=12 || PhNumberValue.charAt(3)!='-' || PhNumberValue.charAt(7)!='-')
		{
			//wrong format
			return false;
		}


		var firstPhNumberValue = new Number(PhNumberValue.substring(0,3),12);
		var secondPhNumberValue = new Number(PhNumberValue.substring(4,7),12);
		var thirdPhNumberValue = new Number(PhNumberValue.substring(8,12),12);


		if(isNaN(firstPhNumberValue) || isNaN(secondPhNumberValue) || isNaN(thirdPhNumberValue))
		{
			//not an integer
			 return false;
		}

	}
	else
		return false;
	return true;
}

function ValidateABA(ABA)
{
var sABA = ABA.value;
var strABAKey = "37137137";
var iResult = 0;
var iPlace = 0;
var iTotal = 0;
var iABADigit = 0;
var iABAKey = 0;
do
{
iABAKey = strABAKey.substr(iPlace,1);
iABADigit = sABA.substr(iPlace,1);
iResult = iResult + (iABAKey * iABADigit);
iPlace ++;
}
while (iPlace <=7)
iPlace = 8;
iABADigit = sABA.substr(iPlace,1);
iTotal = ((iABADigit/1) + (iResult/1)) / 10;

sResult = iTotal + "";
		if ((sABA == "") || (isNaN(sABA)) || (sABA.length !== 9) || (sResult.indexOf(".") != -1))
			return false;
		else
			return true;
}

function verify(f)
{

var msg;
var empty_fields = '';
var errors = '';
var password = '';
var confirm = '';
var passwordField ;
var nValue,nIndex,sSubstr;

	for (var i = 0; i < f.length; i++) {
		var e = f.elements[i];
		var display = e.display;
		var errfield;
		var isEmpty;

		if (!display) {
			display = e.name;
		}

		if (((e.type == 'text') ||
			 (e.type == 'textarea') ||
			 (e.type == 'password') ||
			 (e.type == 'file') ||
			 (e.type == 'hidden') ||
			 (e.type == 'select-one')))
		{

			isEmpty = (e.value == '') || isblank(e.value)

			if (!e.optional && isEmpty)
			{
				empty_fields += '\n     ' + display;
				if (! errfield){
					errfield = e;
				}
				continue;
			}

			if (!isEmpty)
			{


				if(e.currency){

					nValue = new Number(e.value);
					nIndex = e.value.indexOf(".");
					sSubstr = "";
					if (nIndex != -1)
					{
						sSubstr = e.value.substring(nIndex,e.value.length);

						if(sSubstr.length > 3)
						{
							sSubstr = "e";
						}
					}

					if (isNaN(nValue) || nValue < 1 || sSubstr == "e"){

						errors += '- The field ' + display + ' must be a valid amount in $';
						errors += '.\n';
						if (! errfield){
							errfield = e;
						}

					}
				}

				if (e.numeric || (e.min != null) || (e.max != null)) {

					// Modified By Saravanan G
					//var v = parseFloat(e.value);
					var v = new Number(e.value);

					if (isNaN(v) || ((e.min != null) && (v < e.min)) ||
									((e.max != null) && (v > e.max)))
					{
						errors += '- The field ' + display + ' must be a number';

						if (e.min != null)
							errors += ' that is greater than ' + e.min;
						if (e.max != null && e.min != null)
							errors += ' and less than ' + e.max;
						else if (e.max != null)
							errors += ' that is less than ' + e.max;

						errors += '.\n';
						if (! errfield){
							errfield = e;
						}

					}

					else
					{
						if (e.avoidDecimal != null)
						{
							if(e.value.indexOf(".") > -1)
								errors += '- The field ' + display + ' should not contain decimal point.';
						}
					}
				}
				if ((e.nosplchar != null) && ( validateSplChars(e.value) == false)){
						errors += '- The field ' + display + ' has got special characters. \n'
						if (! errfield){
							errfield = e;
						}
				}
				if(e.password != null) {
					password = e.value;
					passwordField = e;
				}

				if(e.confirm != null) {
					confirm = e.value;
				}

				if (e.validateEmail != null) {
					if ( validateEmail(e.value) == false){
						errors += '- The field ' + display + ' must be a valid email id. \n'
						if (! errfield){
							errfield = e
						}
					}
				}

				if (e.checkSpace != null) {
					if ( spaceBetChars(e.value) == false){
						errors += '- The field ' + display + ' should not contain any spaces. \n'
						if (! errfield){
							errfield = e
						}
					}
				}

				if (e.validateURL != null) {
					if ( validateURL(e.value) == false){
						errors += '- The field ' + display + ' must be a valid URL. \n'
						if (! errfield){
							errfield = e
						}
					}
				}

				if (e.creditCard != null) {
					if ( isCreditCard(e.value) == false){
						errors += '- The field ' + display + ' must be a valid credit card. \n'
						if (! errfield){
							errfield = e
						}
					}
				}

				if (e.validateDate !=null){

					if(isValidFormat(e.value) == false){
						errors += 'Date must be in mm/dd/yyyy format '
						if (! errfield){
							errfield = e
						}
					}




					if ( isValidDate(e) == false){
						errors += '- The field ' + display + ' must be a valid date. \n'
						if (! errfield){
							errfield = e
						}
					}
				}

				if (e.validateExpDate !=null){
					if ( isValidExpDate(e.value) == false){
						errors += '- The field ' + display + ' must be a valid expiry date. \n'
						if (! errfield){
							errfield = e
						}
					}
				}

				if (e.dependent !=null){

					if(i%4 == 1){
						var e1 = f.elements[i+1];
					}else{
						var e1 = f.elements[i-1];
					}


					if ( (e.value != "" && e1.value == "") || (e.value == "" && e1.value != "")){
						errors += '- Cheque Number And Pay Date must be  entered. \n'
						if (! errfield){
							errfield = e
						}
					}
				}

				
				if (e.validatePhNumber !=null){
					if ( isValidPhNumber(e) == false){
						errors += '- The field ' + display + ' must be a valid Phone Number. \n'
						if (! errfield){
							errfield = e
						}
					}
				}

				if (e.validateABA !=null){
					if ( ValidateABA(e) == false){
						errors += '- The field ' + display + ' must be a valid ABA Number. \n'
						if (! errfield){
							errfield = e
						}
					}
				}
			}
		}
	}

	if (password != confirm){
		errors += '- The password fields do not match \n'
		if (! errfield)
		{
			errfield = passwordField;
		}
	}


	if (!empty_fields && !errors) return true;

	msg = '______________________________________________________\n\n'
	msg += 'The form was not submitted because of the following error(s).\n';
	msg += 'Please correct these error(s) and re submit.\n';
	msg += '______________________________________________________\n\n'

	if  (empty_fields) {
		msg += '- Please fill in all required fields:\n'
		msg += '- The following field(s) are empty:\n'
				+ empty_fields + '\n';
		if (errors) msg += '\n';
	}

	msg += errors;
	alert(msg);
	if (errfield.type != 'hidden')
	 	errfield.focus()
	if (errfield.type != "select-one")
	{
		errfield.select()
	}
	
	return false;
}
function IsNumeric() 
{
	if (window.event.keyCode < 48 || window.event.keyCode > 58)
		//alert("Enter Numeric value(m)");
		window.event.returnValue = false;
}
