/*
   This script validates form fields for proper values.
   Here's how to use it:

	  Call it from OnSubmit in the form tag with the following: OnSubmit="return checkForm(this.name);"
	  To validate a field include a hidden tag with the same name but append "_validate"
	   	to it then put the type of field it is as the value (see lit of types below).
		You may also add a custom error message for the field by appending
		the error message with a "-" then the message.
		
		Examples:
		With a custom message: 		<input type="hidden" name="FIRST_NAME_validate" value="text-Custom error message goes here.">
		Without a custome message 	<input type="hidden" name="FIRST_NAME_validate" value="text">
				
		The current field types are as follows:
		
		text - regular text field, check for the existance of a value- nothing else
		month - checks for an integer between 1 and 12 (no decimals)
		year - checks for integer (no decimals)
		longYear - checks for integer (no decimals)
	  	dropdown - checks that the first item is not selected
		checkbox - checks for at least one choice (note: all fields must be named the same)
		radio - checks for a selection
		email - checks for proper email syntax
		email_null - checks for proper email syntax, but allows null value
		numeric[(a)|(a,b)] - checks that the value is an integer number
				- (a): checks that the value is lesser than 'a'
				- (a,b): checks that the value is between 'a' and 'b'
		zipcode - checks that the value is a valid US zip code
		file[(ext1[, ext2[, ...]][:size]) - checks the field is not null
				- (ext1[, ext2[, ...]]) - checks the extension of the file is one of 'ext1', 'ext2', etc...
				- (:size) - checks the file is smaller than 'size' bytes
	
	For testing purposes, include a hidden field in your form named "sitesys_test" and
	it will stop the form from submitting.
	
	Modifications History
	**********************
	06/07/2001 - Created 
	06/11/2001 - Added new function to focus on first field that needs fixing
	06/12/2001 - Dash no longer needed when no custom error message is specified
	06/18/2001 - Added email_null type to check for proper email syntax only if a value is provided
	11/05/2001 - Fix Month and Year routine
	09/25/2002 - Add longYear validation
	11/11/2004 - Fix Year to use this year not a hard coded value
	02/11/2007 - Added numeric and zipcode validation
	04/18/2007 - Added file validation
	01/18/2010 - Added enabled loading message alert for wait while upload heavy files
	08/04/2011 - Added telephone number validation (various formats)
*/

// set global params
var focusfield = '';
var bletSubmitGo = true
var today = new Date();
//
function checkForm(formname) {
//to avoid the ENTER without click;	
if (bletSubmitGo==false){return false}


	// create some default parameters for the error message if one is needed
	var final_msg = ""; 
	var intro = "There was a problem with your response.         \n\n"; // create intro 
	var ending = "\nPlease, make the necessary changes and try again.     " // create ending
	
	// define default messages 
	var err_text = "     - Incomplete Form"
	var err_month = "     - Invalid Month"
	var err_day = "     - Invalid Day"
	var err_year = "     - Invalid Year"
	var err_longYear = "     - Invalid Year"
	var err_dropdown = "     - Incomplete Form"
	var err_checkbox = "     - No checkbox selected"
	var err_email = "     - Invalid Email"
	var err_numeric = "     - Invalid number"
	var err_zipcode = "     - Invalid zipcode"
	var err_telephone = "     - Invalid telephone number"
	
	var f = eval("document." + formname + ".elements"); // define the scope to save time
	var vArray = new Array(); // Create an Array to hold fields to be validated
		
	//Check for fields that need to be validated
	for (i=0; i<f.length; i++) {
		if(f[i].name.indexOf('_validate') != -1) {
			if (vArray.length == 0) {
				vCurrent = 0;
			} else {
				vCurrent = vCurrent + 1;
			}
			vArray[vCurrent]  = f[i].name;
		}
		// check for a hidden test to stop form from submitting
		if(f[i].name == 'sitesys_test') {
			var testing = true;
		}
	}

	// Now that we have the validated fields, start checking values
	for (i=0; i<vArray.length; i++) {
		var fposition = vArray[i].indexOf('_validate'); // find the position of "_validate"
		var fname = vArray[i].substring(0, fposition); // extract field name
		var validate = eval("document." + formname + "." + vArray[i] + ".value"); // define scope
		var dash = validate.indexOf('-'); // find the position of the "-"

		if(dash == -1) {
			var type = validate; // if there is no dash set error_msg to blank/default
			var err_msg = '';
		} else {
			var type = validate.substring(0,dash); // get field type

			//Only for numeric check
			var tmp = "numeric";
			if(type.substring(0, tmp.length) == tmp) {
				var n_beg = -65535;
				var n_end = 65535;

				var tmp_1 = type.indexOf('(');
				var tmp_2 = type.indexOf(')');

				if(tmp_1 != -1 && tmp_2 != -1 && tmp_1 < tmp_2)
				{
					var aux_1 = type.substring(tmp_1 + 1, tmp_2);
					var aux_2 = aux_1.split(',');

					type = "numeric";

					if(aux_2.length == 1)
					{
						if(isNumeric(aux_2[0]))
							n_end = aux_2[0];
					}
					else if(aux_2.length == 2)
					{
						if(isNumeric(aux_2[0]) && isNumeric(aux_2[1]))
						{
							n_beg = aux_2[0];
							n_end = aux_2[1];
						}
					}
					
				}
			}
			//End Only for numeric check

			//Only for file check
			tmp = "file";
			var f_size = -1;
			var f_extensions = new Array();

			if(type.substring(0, tmp.length) == tmp)
			{
				var tmp_1 = type.indexOf('(');
				var tmp_2 = type.indexOf(')');

				if(tmp_1 != -1 && tmp_2 != -1 && tmp_1 < tmp_2)
				{

					var aux_1 = type.substring(tmp_1 + 1, tmp_2);
					var aux_2 = aux_1.split(':');

					type = "file";

					if(aux_2.length >= 1 && aux_2.length <= 2)
					{
						var aux_3 = aux_2[0].split(',');

						for(var k = 0; k < aux_3.length; k++)
							if(trim(aux_3[k]).length > 0)
								f_extensions.push(trim(aux_3[k].toLowerCase()));

						if(aux_2.length == 2)
						{
							if(isNumeric(aux_2[1]))
								f_size = aux_2[1];
						}
					}
				}
			}
			//End Only for file check

			var err_msg = validate.substring(dash + 1, validate.length); // get custom error message if any
			var aTempLength = err_msg.split('<br>')
			for (iTempLength=0;iTempLength<aTempLength.length;iTempLength++){
				err_msg = err_msg.replace('<br>','\n')
			}
			aTempLength = err_msg.split('<b>')
			for (iTempLength=0;iTempLength<aTempLength.length;iTempLength++){
				err_msg = err_msg.replace('<b>','')
			}
			aTempLength = err_msg.split('</b>')
			for (iTempLength=0;iTempLength<aTempLength.length;iTempLength++){
				err_msg = err_msg.replace('</b>','')
			}
			
		}	

		var field = eval("document." + formname + "." + fname); // define field scope
		 
		// validate text fields
		if(type == 'text') {
			if(!field.value) {
				if (err_msg == "") {
					final_msg = final_msg + err_text + "\n";
				} else {
					final_msg = final_msg + err_msg + "\n";
				}	
			setCKFocus(field); // run focus function
			}	
		}
		// end text validation
		
		// validate month 
		if(type == 'month') {
			if ((!field.value) || (!isFinite(field.value)) || (field.value.indexOf('.') != -1) || (field.value > 12) || (field.value < 1) || (field.value == '  ') || (field.value == ' ')) {
				if (err_msg == "") {
					final_msg = final_msg + err_month + "\n";
					} else {
						final_msg = final_msg + err_msg + "\n";
				}				
			setCKFocus(field); // run focus function
			}
		}		
		// end month validation
		
		// validate day 
		if(type == 'day') {
			if ((!field.value) || (!isFinite(field.value)) || (field.value.indexOf('.') != -1) || (field.value > 31) || (field.value < 1) || (field.value == '  ') || (field.value == ' ')) {
				if (err_msg == "") {
					final_msg = final_msg + err_day + "\n";
					} else {
						final_msg = final_msg + err_msg + "\n";
				}				
			setCKFocus(field); // run focus function
			}
		}		
		// end month validation

		// validate year
		if(type == 'year') {
			if ((!field.value) || (!isFinite(field.value)) || (field.value.indexOf('.') != -1) || (field.value == '  ') || (field.value == ' ')) {
				if (err_msg == "") {
						final_msg = final_msg + err_year + "\n";
					} else {
						final_msg = final_msg + err_msg + "\n";
				}				
			setCKFocus(field); // run focus function	
			}
		}		
		// end year validation

		// validate longYear
		if(type == 'longYear') {
			//alert(field.value.length)
			iTemp = Val(field.value)
			sTemp = iTemp  + "A"
			//alert(sTemp.length)
			if ((sTemp.length != 5) || (!isFinite(iTemp)) || (sTemp.indexOf('.') != -1) || (iTemp < 1900) || (iTemp > today.getFullYear()) ){
				if (err_msg == "") {
						final_msg = final_msg + err_longYear + "\n";
					} else {
						final_msg = final_msg + err_msg + "\n";
				}				
			setCKFocus(field); // run focus function	
			}
		}		
		// end longYear validation
		
		
		// validate dropdown
		if(type == 'dropdown') {
			if(field[0].selected) {
				if (err_msg == "") {
						final_msg = final_msg + err_dropdown + "\n";
					} else {
						final_msg = final_msg + err_msg + "\n";
				}
			setCKFocus('nofocus'); // run focus function								
			}
		}
		// end dropdown validation
		
		// validate checkbox 
		if(type == 'checkbox'){
			var cempty = true;
			if(!field.length)
			{
				if(field.checked)
					cempty = false;
			}
			else for (c=0;c<field.length;c++) {
				if(field[c].checked) {
					cempty = false;
				}
			}
			if(cempty) {
				if (err_msg == "") {
					final_msg = final_msg + err_checkbox + "\n";
					} else {
						final_msg = final_msg + err_msg + "\n";
				}
			setCKFocus('nofocus'); // run focus function											
			}
		}
		// end checkbox validation
		
		// validate radio
		if(type == 'radio'){
			var rempty = true;
			for (r=0;r<field.length;r++) {
				if(field[r].checked) {
					rempty = false;
				}
			}
			if(rempty) {
				if (err_msg == "") {
					final_msg = final_msg + err_radio + "\n";
					} else {
						final_msg = final_msg + err_msg + "\n";
				}
			setCKFocus('nofocus'); // run focus function											
			}
		}
		// end radio validation
		
		// validate email
		if (type == 'email') {
			var bademail = false
	
			if (!field.value) { 
				bademail = true; 
				} else {
			
				var emailStr = field.value;
				var emailPat=/^(.+)@(.+)$/;
				var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
				var validChars="\[^\\s" + specialChars + "\]";
				var quotedUser="(\"[^\"]*\")";
				var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
				var atom=validChars + '+';
				var word="(" + atom + "|" + quotedUser + ")";
				var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
				var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
				var matchArray=emailStr.match(emailPat);
				
				if (matchArray==null) { 
					bademail = true; 
				} else {
				
						var user=matchArray[1];
						var domain=matchArray[2];
						
						if (user.match(userPat)==null)  { bademail = true; }
						
						var IPArray=domain.match(ipDomainPat);
						if (IPArray!=null) {
						    // this is an IP address
							  for (var i=1;i<=4;i++) {
							    if (IPArray[i]>255) {
									 bademail = true;
							    }
						    }
						}
				
				
						var domainArray=domain.match(domainPat);
						if (domainArray==null)  { bademail = true; }
						
						var atomPat=new RegExp(atom,"g");
						var domArr=domain.match(atomPat);
						var len=domArr.length;
						if (domArr[domArr.length-1].length<2 || 
						    domArr[domArr.length-1].length>3) {
							bademail = true;
						}
						
						if (len<2) {
							bademail = true;
						}
				}	
			}
				
			if(bademail) {
				if (err_msg == "") {
					final_msg = final_msg + err_email + "\n";
					} else {
						final_msg = final_msg + err_msg + "\n";
				}
			setCKFocus(field); // run focus function											
			}
		}
		//end email validation

		// validate email
		if (type == 'email_null') {
			var bademail = false
	
			if (!field.value) { 
				bademail = false; 
				} else {
			
				var emailStr = field.value;
				var emailPat=/^(.+)@(.+)$/;
				var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
				var validChars="\[^\\s" + specialChars + "\]";
				var quotedUser="(\"[^\"]*\")";
				var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
				var atom=validChars + '+';
				var word="(" + atom + "|" + quotedUser + ")";
				var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
				var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
				var matchArray=emailStr.match(emailPat);
				
				if (matchArray==null) { 
					bademail = true; 
				} else {
				
						var user=matchArray[1];
						var domain=matchArray[2];
						
						if (user.match(userPat)==null)  { bademail = true; }
						
						var IPArray=domain.match(ipDomainPat);
						if (IPArray!=null) {
						    // this is an IP address
							  for (var i=1;i<=4;i++) {
							    if (IPArray[i]>255) {
									 bademail = true;
							    }
						    }
						}
				
				
						var domainArray=domain.match(domainPat);
						if (domainArray==null)  { bademail = true; }
						
						var atomPat=new RegExp(atom,"g");
						var domArr=domain.match(atomPat);
						var len=domArr.length;
						if (domArr[domArr.length-1].length<2 || 
						    domArr[domArr.length-1].length>3) {
							bademail = true;
						}
						
						if (len<2) {
							bademail = true;
						}
				}	
			}
				
			if(bademail) {
				if (err_msg == "") {
					final_msg = final_msg + err_email + "\n";
					} else {
						final_msg = final_msg + err_msg + "\n";
				}
			setCKFocus(field); // run focus function											
			}
		}
		//end email validation
				
		//validate number
		if(type == 'numeric') {
			if(	!isNumeric(field.value)	||
				(isNumeric(field.value) && 
				 (parseInt(field.value) < n_beg || parseInt(field.value) > n_end)))
			{
				if (err_msg == "") {
						final_msg = final_msg + err_numeric + "\n";
					} else {
						final_msg = final_msg + err_msg + "\n";
				}
			setCKFocus(field); // run focus function	
			}
		}
		//end validate number

		//validate zipcode
		if(type == 'zipcode') {
			if(!(isNumeric(field.value)	&& trim(field.value).length == 5))
			{
				if (err_msg == "") {
						final_msg = final_msg + err_zipcode + "\n";
					} else {
						final_msg = final_msg + err_msg + "\n";
				}
			setCKFocus(field); // run focus function	
			}
		}
		//end validate zipcode
		
		//validate telephone number
/*
		Other options for validation:
		Por ahora solo valida expresiones del formato 1.
		para permitir mas formatos de validacion de numeros de telefono, agregar el correspondiente if con la condicion de validacion requerida
		Número	 			Expresión regular	 					Formato
		90090					/^\d{1, 9}$/	 					   1: entre 1 y 9 cifras seguidas
		900900900			/^\d{9}$/	 							  2: 9 cifras seguidas
		900-900-900			/^\d{3}-\d{3}-\d{3}$/				   3: 9 cifras agrupadas de 3 en 3 y separadas por guiones
		900 900900			/^\d{3}\s\d{6}$/			  		  	4: 9 cifras, las 3 primeras separadas por un espacio
		900 90 09 00		/^\d{3}\s\d{2}\s\d{2}\s\d{2}$/	 	 5: 9 cifras las 3 primeras separadas por un espacio las siguientes agrupadas de 2 en 2
		(900) 900900		/^\(\d{3}\)\s\d{6}$/	 				6: 9 cifras las 3 primeras encerradas por paréntesis y un espacio de separación respecto del resto
		+34 900900900		/^\+\d{2,3}\s\d{9}$/	 			  7: Prefijo internacional (+ seguido de 2 o 3 cifras) espacio en blanco y 9 cifras consecutivas
*/
		if(type == 'telephone1')
		 {
			if( !(/^\d{1,10}$/.test(trim(field.value))) ) 
			{
				if (err_msg == "") {
						final_msg = final_msg + err_telephone + "\n";
					} else {
						final_msg = final_msg + err_msg + "\n";
				}
				setCKFocus(field); // run focus function	
			}
		}
		//end telephone number
		
		
		//validate file
		if(type == 'file') {
			var b_error = false;

			if(!field.value)
				b_error = true;
			else
			{
				if(f_extensions.length)
				{
					b_error = true;

					for(var k = 0; k < f_extensions.length; k++)
						if(filterFileType(field.value, f_extensions[k]))
						{
							b_error = false;
							break;
						}
				}

				if(f_size != -1)
				{
					if(getFileSize(field.value) > f_size)
						b_error = true;
				}
			}

			if(b_error)
			{
				if (err_msg == "") {
					final_msg = final_msg + err_text + "\n";
				} else {
					final_msg = final_msg + err_msg + "\n";
				}	

				setCKFocus(field); // run focus function
			}
		}
		//end validate file
		
		// add new	
		// end new

	}

	// stop the submission if there are errors and notify the user
	if (final_msg != "") {
		alert(intro + final_msg + ending); // give the user the error
		if(focusfield != "false") {
			var focus_on = eval("document." + formname + "." + focusfield); // define scope
			focus_on.focus(); // focus on first field that needs to be fixed
		 }

		focusfield = ''; // clear out the focus field for next run
		return false; 

	}
	

	
	// check and see if we are testing, if so, then stop the form from submitting
	if(testing) { return false; }
	
	// check for valid file name and valid file extension
	if(document.getElementById('file') && document.getElementById('file').value != ""){
		
		strFile = document.getElementById('file').value;
		
		strFileName = strFile.substring(0, strFile.lastIndexOf("."));
		strFileExtension = (strFile.substring(strFile.lastIndexOf(".")+1)).toLowerCase();
		
		if(!checkFileExt(strFileExtension)){ 
			alert("La extensi\xf3n del archivo es inv\xe1lida.");
			document.getElementById('file').focus();
			return false;
		}
		
		errorMessage = checkFileName(strFileName)
		if(errorMessage != ''){ 
			alert("El nombre de archivo de la foto posee caracteres invalidos. " + errorMessage);
			document.getElementById('file').focus();
			return false;
		}
		
	}
	
	
	//enabled loading message
	loadingmessageScope = eval("document." + formname + ".enabledloadingmessage");
	if(loadingmessageScope.value == 'yes') {
			buttonScope = eval("document." + formname + ".submit");
			buttonScope.style.color = '#64B510';
			buttonScope.style.fontSize = '12px';
			buttonScope.disabled = true;
			if(buttonScope.value != ''){
				buttonScope.value = "Cargando...";
			}
			initLoadingMessage();						
	}
	//end enabled loading message
		
	return true;
	
}


function checkFileExt(strFileExtension){	
	var extAllowed = new Array("jpeg", "jpg", "png");
	for(var k = 0; k < extAllowed.length; k++){
		if(extAllowed[k] == strFileExtension){
			return true;
		}
	}
	return false;
}

function checkFileName(strFileName){
	var errorMessage = "";			
	var checkOK = ":¡!-+[]{}()=_%@" + "0123456789 " + "ABCDEFGHIJKLMNÑOPQRSTUVWXYZÁÉÍÓÚ" + "abcdefghijklmnñopqrstuvwxyzáéíóú";
	
	var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
	var is_firefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
	var is_ie = navigator.userAgent.toLowerCase().indexOf('msie') > -1 || navigator.appName.indexOf("Microsoft") != -1;
	var is_opera = navigator.userAgent.toLowerCase().indexOf('opera') > -1 || navigator.appName.indexOf("opera") != -1;
	var is_safari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;
	
	if(is_chrome || is_ie || is_opera || is_safari){
		tmp = strFileName.split("\\");
		strFileName = tmp[tmp.length-1];
	}
	
	for(i=0;i<strFileName.length;i++){
		ch = strFileName.charAt(i);
		for(j=0;j<checkOK.length;j++){
			if(ch == checkOK.charAt(j)) break; // continue checked the rest of chars
		}
		if(j == checkOK.length){
			errorMessage = "Caracter '" + ch + "' en la posicion " + i;
			break;
		}
	}

	return errorMessage; 
}

function setCKFocus(field) {
	if(focusfield == '') {
		if (field == 'nofocus') {
			focusfield = "false";
		} else {
			focusfield = field.name;
		} 
	}	
}

function Val(sString){
	bFlag = true;
	sResult = "";
	for (i=0; i<=sString.length-1; i++){
		if (bFlag){
			sTemp = sString.substring(i,i+1);
			if (sTemp >= "0" && sTemp <= "9"){
				sResult = sResult + sTemp;
			}
			else {
				bFlag = false;
			}
		}
	}
	return sResult*1
}

function isNumeric(sString)
{
	bFlag = false;
	var iTmp;

	sString = trim(sString);

	for (i=0; i<=sString.length-1; i++) {
		iTmp = parseInt(sString.substring(i,i+1));
		if(!(iTmp >= 0 && iTmp <= 9)) {
			break;
		}

		if(i == sString.length - 1)
			bFlag = true;
	}
	return bFlag;
}

function trim(sThisValue) {
		sThis = rtrim(sThisValue)
		sThis = ltrim(sThis)
      return sThis.replace(/\s+/gi,' ')
}

function ltrim(sThisL) {
      return sThisL.replace(/^\s*/,'')
}
function rtrim(sThisR) {
      return sThisR.replace(/\s*$/,'')
}

function filterFileType(file, ext)
{
	if(file.toLowerCase().indexOf('.' + ext) == -1)
	{
		return false;
	}

	return true;
}

function getFileSize(file)
{
	var oas = new ActiveXObject("Scripting.FileSystemObject");

	var e = oas.getFile(file);

	var f = e.size;

	return f;
}

// enabled loading message

	loadingMessageTime = 15; // seconds loading message reminder is shown
				
	var ns = (document.layers);
	var ie = (document.all);
	var w3 = (document.getElementById && !ie);
	var calunit = ns? "" : "px"
	loadingMessageCount = 0;

	function initLoadingMessage(){

		if(!ns && !ie && !w3)
			return;	
				
		if(ie){
			loadingMessageDiv = eval('document.all.loadingMsg.style');
		}else if(ns){
			loadingMessageDiv = eval('document.layers["loadingMsg"]');
		}else if(w3){ 
			loadingMessageDiv = eval('document.getElementById("loadingMsg").style');
		}
	
		if (ie||w3){
			loadingMessageDiv.visibility = "visible";
		}else{
			loadingMessageDiv.visibility = "show";
		}

		showLoadingMessage();
	}

	function showLoadingMessage(){
		if(loadingMessageCount < loadingMessageTime * 10){		
				// loadingMessageCount+=1; 				// comment to no close message
			if(ie){
				documentWidth = truebody().offsetWidth/2 + truebody().scrollLeft - 20;
				documentHeight = truebody().offsetHeight/2 + truebody().scrollTop - 20;
			}else if(ns){
				documentWidth = window.innerWidth/2 + window.pageXOffset - 20;
				documentHeight = window.innerHeight/2 + window.pageYOffset - 20;
			}else if(w3){
				documentWidth = self.innerWidth/2 + window.pageXOffset - 20;
				documentHeight = self.innerHeight/2 + window.pageYOffset - 20;
			}

			loadingMessageDiv.left = documentWidth - 100 + calunit;
			loadingMessageDiv.top = documentHeight - 100 + calunit;
			setTimeout("showLoadingMessage()", 100);
		}else closeLoadingMessage();
	}

	function closeLoadingMessage(){
		if(ie||w3){
			loadingMessageDiv.display = "none";
		}else{
			loadingMessageDiv.visibility = "hide";
		}
	}

	function truebody(){
		return (document.compatMode && document.compatMode!="BackCompat") ? document.documentElement : document.body;
	}

	function closeMessage(){
		messageObj.close();	
	}				

