/*------------------------------------------------------------------------------------------------
Author        	:Vasu
Date        	:20/11/2001
Company			:Cosmonet Solutions Private LTD. Bangalore. India.
Description    	:JavaScript Validations.
------------------------------------------------------------------------------------------------

Modification Log Begins Here
------------------------------------------------------------------------------------------------
    Date		Person			Modification to be done
(dd/mm/yyyy)
------------------------------------------------------------------------------------------------
13/12/2001		Nithya			Added Maxlength check for Textarea.
13/12/2001		Saravanan G		Added functions to validate date and creditcard.
14/12/2001		Nithya			Included noSpcBwWords in the verify function.
------------------------------------------------------------------------------------------------
Modification Log Ends Here*/

//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)
{
	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 Saravanan G to include Creditcard & Date validations
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	to convert the dateformats to the standard format (mm/dd/yyy)
function convertToStdFormat(dtValue, dtFormat)
{

	var mm;
	var 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;

}

//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],[31],[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 sDate;
}

// 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 ' + dt1.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;
		}
	}
}// END FUNCTION isOrderedDate()


function verify(f)
{
	var msg;
	var empty_fields = '';
	var errors = '';
	var password = '';
	var confirm = '';
	var sValue

	// pwd element will be captured here. If there is no error other than pwd mismatch
	// then put the focus on this element.
	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 == 'select-one')))
		{
			if(e.type == "select-one")
			{
				sValue = e[e.selectedIndex].value;
			}
			else
			{
				sValue = e.value;
			}

			isEmpty = (sValue == null) || (sValue == '') || isblank(sValue)

			if (!e.optional && isEmpty)
			{
				empty_fields += '\n     ' + display;
				if (! errfield)
				{
					errfield = e;
				}
				continue;
			}

			if (!isEmpty)
			{
				if (e.numeric || e.integer || (e.min != null) || (e.max != null))
				{
					if (isNaN(sValue))
					{
						errors += '- The field ' + display + ' must be a number\n';
						if (! errfield)
						{
							errfield = e;
						}
						continue;
					}

					if(e.integer && sValue.indexOf(".") > -1)
					{
						errors += '- The field ' + display + ' must be an integer\n';
						if (! errfield)
						{
							errfield = e;
						}
					}

					var v = eval(sValue);
					if (((e.min != null) && (v < e.min)) || ((e.max != null) && (v > e.max)))
					{
						if (e.min != null)
						{
							errors += '- The field ' + display + ' should be 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;
						}

					}
				}
				if ((e.nosplchar == true) && ( validateSplChars(sValue) == false))
				{
					errors += '- The field ' + display + ' has got special characters. \n'
					if (! errfield)
					{
						errfield = e;
					}
				}
				if ((e.noSpcBwWords == true) && ( spaceBetChars(sValue) == false))
				{
					errors += '-  ' + display + ' should not contain spaces. \n'
					if (! errfield)
					{
						errfield = e;
					}
				}
				if(e.maxlen != null)
				{
					if(sValue.length > e.maxlen)
					{
						errors += '- The field ' + display + ' contains ' + sValue.length + ' characters. Max Length is ' + e.maxlen + '. \n'
						if (! errfield)
						{
							errfield = e;
						}
					}
				}

				if(e.minlen != null)
				{
					if(sValue.length < e.minlen)
					{
						errors += '- The field ' + display + ' contains ' + sValue.length + ' characters. Min Length is ' + e.minlen + '. \n'
						if (! errfield)
						{
							errfield = e;
						}
					}
				}

				if(e.validatepwd != null)
				{
					var e1 = f.elements[0];
					var e2 = f.elements[10];									var e3 = f.elements[11];
					var e4 = f.elements[12];
					var e5 = f.elements[25];

					if(e.value == e1.value || e.value == e2.value ||
					e.value == e3.value || e.value == e4.value ||
					e.value == e5.value){

						errors += '- ' + display + ' matches with login id or name or year of birth.\n'
						if (! errfield)
						{
							errfield = e;
						}

					}
				}


				if(e.password == true)
				{
					password = sValue;
					passwordField = e;
				}

				if(e.confirm == true)
				{
					confirm = sValue;
				}

				if (e.validateEmail == true)
				{
					if ( validateEmail(sValue) == false)
					{
						errors += '- The field ' + display + ' must be a valid email address. \n'
						if (! errfield)
						{
							errfield = e
						}
					}
				}

				if (e.creditCard == true)
				{
					if(isCreditCard(e.value) == false)
					{
						errors += '- The field ' + display + ' must be a valid credit card. \n'
						if (! errfield)
						{
							errfield = e
						}
					}
				}

				if (e.validateDate == true)
				{

					if ( isValidDate(e) == false)
					{
						errors += '- The field ' + display + ' must be a valid date. \n'
						if (! errfield)
						{
							errfield = e
						}
					}
				}
			}
		}
	}

	if (password != confirm)
	{
		errors += '- The password and confirm password 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;
}
