/************
True Form Validator is licensed under BSD License which is provided below:

BSD License

Copyright © 2009, Amit Sengupta, TrueLogic.org, amit@truelogic.org
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of the Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 


********************************************************************/


					// validation types
	var VALIDATE_FOR_EMPTY = "_v1_";
	var VALIDATE_FOR_INTEGER = "_v2_";
	var VALIDATE_FOR_FLOAT = "_v3_";
	var VALIDATE_FOR_SPACES = "_v4_";
	var VALIDATE_FOR_DATE = "_v5_";
	var VALIDATE_FOR_COMBO_SELECTED = "_v6_";
	var VALIDATE_FOR_ALPHA_START = "_v7_";
	var VALIDATE_FOR_ONLY_ALPHA = "_v8_";
	var VALIDATE_FOR_EMAIL = "_v9_";

					// validation error messages
	var MSG_FOR_EMPTY = "Field cannot be empty";
	var MSG_FOR_INTEGER = "Field is not a valid integer";
	var MSG_FOR_FLOAT = "Field is not a valid number";
	var MSG_FOR_SPACES = "Field cannot contain embedded spaces";
	var MSG_FOR_DATE = "Field is not a valid date";
	var MSG_FOR_COMBO_SELECTED = "A value must be selected from dropdown";
	var MSG_FOR_ALPHA_START = "Field must start with an alphabet";
	var MSG_FOR_ONLY_ALPHA = "Field must contain only alphabets";
	var MSG_FOR_EMAIL = "Email id is invalid";

	var tfv_error_msgs = Array();		// default empty array for field error messages
							
									// date formats - make only one of them as current
	var DATE_FORMAT_YYYY_MM_DD = "^[0-9]{4}-[0-9]{2}-[0-9]{2}$";
	var DATE_FORMAT_YY_MM_DD = "^[0-9]{2}-[0-9]{2}-[0-9]{2}$";
	var DATE_FORMAT_MM_DD_YYYY = "^[0-9]{2}-[0-9]{2}-[0-9]{4}$";
	var DATE_FORMAT_DD_MM_YYYY = "^[0-9]{2}-[0-9]{2}-[0-9]{4}$";
	var DATE_FORMAT_MM_DD_YY = "^[0-9]{2}-[0-9]{2}-[0-9]{2}$";
	var DATE_FORMAT_DD_MM_YY = "^[0-9]{2}-[0-9]{2}-[0-9]{2}$";

	var CURRENT_DATE_FORMAT = DATE_FORMAT_MM_DD_YY;
	var YEAR_POS = 2, MONTH_POS = 0, DAY_POS = 1;
	var YEAR_FULL = false;
	var CURRENT_DATE_ERROR = "Date must be in mm-dd-yy format";

	function tfv_validate(frm) {
		var i, maxFields;
		var fld, pattern, match;

		maxFields = frm.elements.length;
		for(i=0; i < maxFields; i++) {
			fld = frm.elements[i];
			if (fld.type  == "text" || fld.type == "password") {
				pattern = VALIDATE_FOR_EMPTY;
				regex = new RegExp(pattern);
				match = regex.exec(fld.name);
				if (match != null) {
					if (trim(fld.value) == '') {
						if (tfv_error_msgs[fld.name])
							alert(tfv_error_msgs[fld.name]);
						else
							alert(MSG_FOR_EMPTY);
						fld.focus();
						return false;
					}
				}

				pattern = VALIDATE_FOR_INTEGER;
				regex = new RegExp(pattern);
				match = regex.exec(fld.name);
				if (match != null) {
					if (isNaN(fld.value) || fld.value.indexOf(".") > -1) {
						if (tfv_error_msgs[fld.name])
							alert(tfv_error_msgs[fld.name]);
						else
							alert(MSG_FOR_INTEGER);
						fld.focus();
						return false;
					}
				}

				pattern = VALIDATE_FOR_FLOAT;
				regex = new RegExp(pattern);
				match = regex.exec(fld.name);
				if (match != null) {
					if (isNaN(fld.value) || fld.value.indexOf(".") == -1) {
							if (tfv_error_msgs[fld.name])
							alert(tfv_error_msgs[fld.name]);
						else
							alert(MSG_FOR_FLOAT);
						fld.focus();
						return false;
					}
				}

				pattern = VALIDATE_FOR_SPACES;
				regex = new RegExp(pattern);
				match = regex.exec(fld.name);
				if (match != null) {
					var f = trim(fld.value);
					if (f.indexOf(' ') > -1) {
						if (tfv_error_msgs[fld.name])
							alert(tfv_error_msgs[fld.name]);
						else
							alert(MSG_FOR_SPACES);
						fld.focus();
						return false;
					}
				}

				pattern = VALIDATE_FOR_DATE;
				regex = new RegExp(pattern);
				match = regex.exec(fld.name);
				if (match != null) {
					if (!validateDate(fld.value)) {
						if (tfv_error_msgs[fld.name])
							alert(tfv_error_msgs[fld.name]);
						else
						if (CURRENT_DATE_ERROR)
							alert(CURRENT_DATE_ERROR);
						else
							alert(MSG_FOR_DATE);
						fld.focus();
						return false;
					}
				}

				pattern = VALIDATE_FOR_ALPHA_START;
				regex = new RegExp(pattern);
				match = regex.exec(fld.name);
				if (match != null) {
					if (!isAlphaStart(fld.value)) {
						if (tfv_error_msgs[fld.name])
							alert(tfv_error_msgs[fld.name]);
						else
							alert(MSG_FOR_ALPHA_START);
						fld.focus();
						return false;
					}
				}
				pattern = VALIDATE_FOR_ONLY_ALPHA;
				regex = new RegExp(pattern);
				match = regex.exec(fld.name);
				if (match != null) {
					if (!isOnlyAlpha(fld.value)) {
						if (tfv_error_msgs[fld.name])
							alert(tfv_error_msgs[fld.name]);
						else
							alert(MSG_FOR_ONLY_ALPHA);
						fld.focus();
						return false;
					}
				}

				pattern = VALIDATE_FOR_EMAIL;
				regex = new RegExp(pattern);
				match = regex.exec(fld.name);
				if (match != null) {
					if (!isValidEmail(fld.value)) {
						if (tfv_error_msgs[fld.name])
							alert(tfv_error_msgs[fld.name]);
						else
							alert(MSG_FOR_EMAIL);
						fld.focus();
						return false;
					}
				}


			} //			if (fld.type  == "text") {
			else 
			if (fld.type == "select-one" || fld.type == "select-multiple") {
				pattern = VALIDATE_FOR_COMBO_SELECTED;
				regex = new RegExp(pattern);
				match = regex.exec(fld.name);
				if (match != null) {
					if (fld.selectedIndex <= 0) {
						if (tfv_error_msgs[fld.name])
							alert(tfv_error_msgs[fld.name]);
						else
							alert(MSG_FOR_COMBO_SELECTED);
						fld.focus();
						return false;
					
					}
				}
			
			} 

				
		}

		return true;
	}

	function trim(s) {
		var s1 = s.replace(/^\s+/g,"");		// remove leading spaces
		var s2 = s1.replace(/\s+$/g, "");	// remove trailing spaces

		return s2;
	}


	function isAlphaStart(s)
	{
		var valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUWXYZ";
		var alpha = s.substring(0,1);

		if(valid.indexOf(alpha) > -1)
			return true;
		else
			return false;
	}

	function isOnlyAlpha(s)
	{
		var valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUWXYZ";

		for(i =0; i < s.length; i++) {
			if(valid.indexOf(s.substring(i,i+1)) ==-1) {
				return false;
			}
		}
		
		return true;
	}

	function validateDate(d) {
		var bValid = true;
		var regex = new RegExp(CURRENT_DATE_FORMAT);
		var match = regex.exec(d);
		if (match == null) {
			bValid = false;
			return bValid;
		}
		else {
			var text = d;
			var bDone = false;
			var p1 = Array();
			p1[0] = '';
			p1[1] = '';
			p1[2] = '';
			var y=0, m=0, dt=0;
			p1[0] = d.substring(0, d.indexOf("-"));
			d = d.substring(d.indexOf("-")+1);
			p1[1] = d.substring(0, d.indexOf("-"));
			d = d.substring(d.indexOf("-")+1);
			p1[2] = d;

		    y = p1[YEAR_POS];
			m = p1[MONTH_POS];
			dt =  p1[DAY_POS];

			
			if (!YEAR_FULL && (parseInt(y,10) > 00 && parseInt(y,10) < 99)) {
			}
			else if (!YEAR_FULL) {
				bValid = false;

			}
			if (YEAR_FULL && (parseInt(y,10) > 1000 && parseInt(y,10) < 5099)) {
			}
			else if (YEAR_FULL){
				bValid = false;
			}
			if (!bValid) {
				alert("Invalid year");
				return bValid;
			}

			if (parseInt(m,10) < 1 || parseInt(m,10) > 12) {
				alert("Invalid month");
				bValid = false;
			}
			if (parseInt(m,10) ==1 || parseInt(m,10) == 3 || parseInt(m,10) == 5 || parseInt(m,10) == 7 || parseInt(m,10) == 8 || parseInt(m,10) ==10 || parseInt(m,10) ==12) {
				if (parseInt(dt,10) < 1 || parseInt(dt,10) > 31) {
				   alert("Invalid date for month");
  				   bValid =false;
				}
			}
			else if (parseInt(m,10)== 2 || parseInt(m,10) == 4 || parseInt(m,10) ==6 || parseInt(m,10) == 9 || parseInt(m,10) == 11) {
				if (parseInt(m,10) == 2 && parseInt(y,10) % 4 == 0 && parseInt(dt,10) > 29) {
					 bValid = false;
				}
				else if (parseInt(m,10) ==2 && parseInt(y,10) % 4 > 0 && parseInt(dt,10) > 28) {
					bValid = false;
				}
				else if (parseInt(dt,10) > 30) {
				    bValid = false;

				}
			
			    if (!bValid)
				   alert("Invalid date for month");

			}

		}

		return bValid;
	}



	function isValidEmail(str) {
		var at="@";
		var dot=".";
		var lat=str.indexOf(at);
		var lstr=str.length;
		var ldot=str.indexOf(dot);

		if (str.indexOf(at)==-1){
		   return false;
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false;
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false;
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    return false;
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return false;
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    return false;
		 }
		
		 if (str.indexOf(" ")!=-1){
		    return false;
		 }

 		 return true;					
	}


