//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))
     {
		if (dispName != '');
		return false;
     }

     return true;
}


//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);
	}
	else if(dtFormat == "dd/mm/yyyy")
	{
		var dd=dtValue.substring(0,2);
		var mm=dtValue.substring(3,5);
	}
	var sFinal = mm + "/" + dd + "/" + dtValue.substring(6,10);

	return sFinal;

}

///////////////////////////////////////////////////////////////////////////////
// make sure date is in form nn/nn/nnnn
function isValidDate(str) {
	var myStr = StripChars(str, " ");
	if(myStr.length < 1)
	{
		return true;
	}

	var regExpDate = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/
	if (regExpDate.test(myStr) == false)
	{
		return false;
	}
	else
	{
		var idx1 = myStr.indexOf("/")
        var month = myStr.substring(0,idx1);
		if (isNumber(month)==false || month>12)
		{
			return false;
		}

 		idx1 = idx1 + 1;
		var idx2 = myStr.indexOf("/", idx1)
		var day  = myStr.substring(idx1,idx2);
		if (isNumber(day)==false || day>31)
		{
			return false;
		}

  		idx2 = idx2 + 1;
		var year  = myStr.substring(idx2, myStr.length);
		if (isNumber(year)==false || year>2100 || year<1700)
		{
			return false;
		}

		return true;
	}
}

///////////////////////////////////////////////////////////////////////////////
// removes any characters in chars from str
function StripChars( str, chars ) {
  var i;
  var returnString = "";

  for (i = 0; i < str.length; i++) {   
    // Check that current character isn't whitespace.
    var c = str.charAt(i);
		if (chars.indexOf(c) == -1) 
			returnString += c;
  }
  return returnString;
}

///////////////////////////////////////////////////////////////////////////////
function isNumber( inputStr )
{
	for( var i = 0; i < inputStr.length; i++ ) 
	{
		var oneChar = inputStr.substring( i, i+1 )
		if( oneChar < "0" || oneChar > "9" ) {
			return false
		}
	}
	return true
}


// 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;
		}
	}


	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()

//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 ;

	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 == '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.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.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 ( isValidDate(e) == false)
					{
						errors += '- The field ' + display + ' must be a valid date. \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.validateSSN !=null){
					if ( isValidSSN(e) == false){
						errors += '- The field ' + display + ' must be a valid SS 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);
 	errfield.focus()
	if (errfield.type != "select-one")
	{
		errfield.select()
	}
	return false;
}

//------------------------------------------------------------------------------------------------
function isValidSSN(SSN)
{
	var SSNFormat = SSN.format;
	var SSNValue=SSN.value;

	if (SSNFormat == "xxx-xx-xxxx")
	{
		if(SSNValue.length!=11 || SSNValue.charAt(3)!='-' || SSNValue.charAt(6)!='-')
		{
			return false;
		}
	}
	return true;
}