// Form Validation Functions  v1.1.6
// http://www.dithered.com/javascript/form_validation/index.html
// code by Chris Nott (chris@NOSPAMdithered.com - remove NOSPAM)

function getFormErrors(form) {
   var errors = new Array();
   var lables = new Array();

   // loop thru all form elements
   for (var elementIndex = 0; elementIndex < form.elements.length; elementIndex++) {
      var element = form.elements[elementIndex];

      //Added to display errors inline to the fields- Gaurav
      if ( element.errorLabel && element.errorLabel != undefined )
	  {
	  	lables[errors.length] = element.errorLabel;
	  }

      // text and textarea types
      if (element.type == "text" || element.type == "textarea") {
         element.value = trimWhitespace(element.value)

         // required element
         if (element.required  && element.value == '') {
            errors[errors.length] = element.requiredError;
         }

         // maximum length
         else if (element.maxlength && isValidLength(element.value, 0, element.maxlength) == false) {
            errors[errors.length] = element.maxlengthError;
         }

         // minimum length
         else if (element.minlength && isValidLength(element.value, element.minlength, Number.MAX_VALUE) == false) {
            errors[errors.length] = element.minlengthError;
         }

         // validationType (credit card number, email address, zip or postal code, alphanumeric, numeric)
         else if (element.validationType) {
            if (
                  
            		(element.validationType.toLowerCase() == 'email' && isValidEmailStrict(element.value) == false) ||
                  (element.validationType.toLowerCase() == 'url' && isValidURL(element.value) == false) ||
                  (element.validationType.toLowerCase() == 'domain' && isValidDomain(element.value) == false) ||
									(element.validationType.toLowerCase() == 'ipaddress' && isValidIPAddress(element.value, true) == false) ||
                  (element.validationType.toLowerCase() == 'alphanumeric' && isAlphanumeric(element.value, false) == false) ||
									(element.validationType.toLowerCase() == 'alphanumeric_space' && isAlphanumeric(element.value, true) == false) ||
                  (element.validationType.toLowerCase() == 'numeric' && isNumeric(element.value, false) == false) ||
                  (element.validationType.toLowerCase() == 'finite' && isFinite(element.value) == false) ||
                  (element.validationType.toLowerCase() == 'phone' && checkInternationalPhone(element.value) == false) ||
									(element.validationType.toLowerCase() == 'vehregnumber' && isValidVehicleRegistrationNumber(element.value, true) == false) ||
                  (element.validationType.toLowerCase() == 'compare' && compare(element.value, element.compareTo, element.compareType) == false) ||
                  (element.validationType.toLowerCase() == 'alphabetic' && isAlphabetic(element.value, true) == false) ) {
               errors[errors.length] = element.validationTypeError;
            }
         }
         else if ( element.applyUsernameRule == true && checkImpUsernameRule(element.value) == false )
         {
         	errors[errors.length] = element.usernameRuleError;
         }
      }

      // password
      else if (element.type == "password") {
         // required element 
         if (element.required  && element.value == '') {
            errors[errors.length] = element.requiredError;
         }

         // maximum length
         else if (element.maxlength && isValidLength(element.value, 0, element.maxlength) == false) {
            errors[errors.length] = element.maxLengthError;
         }

         // minimum length
         else if (element.minlength && isValidLength(element.value, element.minlength, Number.MAX_VALUE) == false) 		{
            errors[errors.length] = element.minLengthError;
         }

         // confirm password mismatch
         else if (element.passwordmatch && (element.value != element.passwordmatch.value) ) {
         		errors[errors.length] = element.passwordmatchError;
         }
         
         else if ( element.applyPasswordRule == true && checkImpPasswordRules(element.value, element.usernameField) == false )
         {
         		errors[errors.length] = element.passwordRuleError;
         }
      }

      // file upload
      if (element.type == "file") {

         // required element
         if (element.required  && element.value == '') {
            errors[errors.length] = element.requiredError;
         }
         else if (element.validationType.toLowerCase() == 'file_ext' && checkFileExtension(element.value, element.allowedExtensions) == false)
         {
         	errors[errors.length] = element.validationTypeError;
         }
      }

      // select
      else if (element.type == "select-one" || element.type == "select-multiple" || element.type == "select") {

      	// required element
         if (element.required && element.selectedIndex == 0) {
            errors[errors.length] = element.requiredError;
         }

		 // disallow empty value selection
         else if (element.disallowEmptyValue && element.options[element.selectedIndex].value == '') {
            errors[errors.length] = element.disallowEmptyValueError;
         }

      }

      // radio buttons
      else if (element.type == "radio") {
         var radiogroup = form.elements[element.name];

         // required element
         if (radiogroup.required && radiogroup.length) {
            var checkedRadioButton = -1;
            for (var radioIndex = 0; radioIndex < radiogroup.length; radioIndex++) {
               if (radiogroup[radioIndex].checked == true) {
                  checkedRadioButton = radioIndex;
                  break;
               }
            }
            if (checkedRadioButton == -1 && !radiogroup.tested) {
               errors[errors.length] = radiogroup.requiredError;
               radiogroup.tested = true;
            }
         }

         radiogroup = null;
      }
				// checkbox
      else if (element.type == "checkbox" && element.value != '') {
        if (element.required) {
            errors[errors.length] = element.requiredError;
         }
         
      }
      else if (element.type == "textarea") {
      	if (element.checkMaxLength && element.value.length > element.maxLength) {
            errors[errors.length] = element.maxLengthError;
         }

      }
      //alert ("Type: "+element.type + "\nName: "+ element.name + "\nelementIndex: "+elementIndex+"\nMessage: "+element.minLengthError);
   }
   //Added to send back error label and error msg- Gaurav
   var returnArray = new Array();
   returnArray[0] = errors;
   returnArray[1] = lables;

   return returnArray;
}

// Check that the number of characters in a string is between a max and a min
function isValidLength(string, min, max) {
	if (string.length < min || string.length > max) return false;
	else return true;
}

// Check that an email address is valid based on RFC 821 (?)
function isValidEmail(address) {
	if (address != '' && address.search) {
      if (address.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1) return true;
      else return false;
	}

   // allow empty strings to return true - screen these with either a 'required' test or a 'length' test
   else return true;
}

// Check that an domain name is valid based on RFC 821 (?)
function isValidDomain(domainName) {
	domainRegExp = /^[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
      return domainRegExp.test(domainName);
	}


function isValidIPAddress(ipaddr) {
   var re = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
   if (re.test(ipaddr)) {
      var parts = ipaddr.split(".");
      if (parseInt(parseFloat(parts[0])) == 0) { return false; }
      for (var i=0; i<parts.length; i++) {
         if (parseInt(parseFloat(parts[i])) > 255) { return false; }
      }
      return true;
   } else {
      return false;
   }
}

function isValidVehicleRegistrationNumber(registrationNumber) {
   var vehRegExp	=	/^([A-Z|a-z]{2}\s{1}\d{2}\s{1}[A-Z|a-z]{1,2}\s{1}\d{1,4})?([A-Z|a-z]{3}\s{1}\d{1,4})?$/; 
   if (vehRegExp.test(registrationNumber)) {
     return true;
   } else {
      return false;
   }
}



// Check that an URL is valid
function isValidURL(str){
	urlRegExp = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
	return urlRegExp.test(str);
}

// Check that an email address has the form something@something.something
// This is a stricter standard than RFC 821 (?) which allows addresses like postmaster@localhost
function isValidEmailStrict(address) {
	if (isValidEmail(address) == false) return false;
	var domain = address.substring(address.indexOf('@') + 1);
	if (domain.indexOf('.') == -1) return false;
	if (domain.indexOf('.') == 0 || domain.indexOf('.') == domain.length - 1) return false;
	return true;
}

// Check that a string contains only letters and numbers
function isAlphanumeric(string, ignoreWhiteSpace) {
	if (string.search) {
		if ((ignoreWhiteSpace && string.search(/[^\w\s]/) != -1) || (!ignoreWhiteSpace && string.search(/\W/) != -1)) return false;
	}
	return true;
}

// Check that a string contains only letters
function isAlphabetic(string, ignoreWhiteSpace) {
	if (string.search) {
		if ((ignoreWhiteSpace && string.search(/[^a-zA-Z\s]/) != -1) || (!ignoreWhiteSpace && string.search(/[^a-zA-Z]/) != -1)) return false;
	}
	return true;
}

// Check that a string contains only numbers
function isNumeric(string, ignoreWhiteSpace) {
	if (string.search) {
		if ((ignoreWhiteSpace && string.search(/[^\d\s]/) != -1) || (!ignoreWhiteSpace && string.search(/\D/) != -1)) return false;
	}
	return true;
}

// Remove characters that might cause security problems from a string
function removeBadCharacters(string) {
	if (string.replace) {
		string.replace(/[<>\"\'%;\)\(&\+]/, '');
	}
	return string;
}

// Remove all spaces from a string
function removeSpaces(string) {
	var newString = '';
	for (var i = 0; i < string.length; i++) {
		if (string.charAt(i) != ' ') newString += string.charAt(i);
	}
	return newString;
}

// Remove leading and trailing whitespace from a string
function trimWhitespace(string) {
	var newString  = '';
	var substring  = '';
	beginningFound = false;

	// copy characters over to a new string
	// retain whitespace characters if they are between other characters
	for (var i = 0; i < string.length; i++) {

		// copy non-whitespace characters
		if (string.charAt(i) != ' ' && string.charCodeAt(i) != 9) {

			// if the temporary string contains some whitespace characters, copy them first
			if (substring != '') {
				newString += substring;
				substring = '';
			}
			newString += string.charAt(i);
			if (beginningFound == false) beginningFound = true;
		}

		// hold whitespace characters in a temporary string if they follow a non-whitespace character
		else if (beginningFound == true) substring += string.charAt(i);
	}
	return newString;
}

// Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 10;

function isInteger(s)
{   var i;
    for (i = 0; i < s.length; i++)
    {
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}
function trim(s)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not a whitespace, append to returnString.
    for (i = 0; i < s.length; i++)
    {
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (c != " ") returnString += c;
    }
    return returnString;
}
function stripCharsInBag(s, bag)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function checkInternationalPhone(strPhone){
	var bracket=3
	strPhone=trim(strPhone)
	if(strPhone.indexOf("+")>1) return false
	if(strPhone.indexOf("-")!=-1)bracket=bracket+1
	if(strPhone.indexOf("(")!=-1 && strPhone.indexOf("(")>bracket)return false
	var brchr=strPhone.indexOf("(")
	if(strPhone.indexOf("(")!=-1 && strPhone.charAt(brchr+2)!=")")return false
	if(strPhone.indexOf("(")==-1 && strPhone.indexOf(")")!=-1)return false
	s=stripCharsInBag(strPhone,validWorldPhoneChars);
	return (isInteger(s));
	//return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}

function compare(val, compareToEl, compareType){
	var compareToElVal = document.getElementById(compareToEl).value;
	return (compareType=="gteq")?(val>=compareToElVal):((compareType=="lteq")?(val<=compareToElVal):
								((compareType=="gt")?(val>compareToElVal):(val<compareToElVal)));
}

function checkFileExtension(file, allowedExts)
{
	if ( file != "" )
	{
		repFilePath = file.replace('\\','/');
	  	var sep = repFilePath.indexOf("/");
		var dotPos = repFilePath.indexOf(".");
		/*if((iExt < 0 ) || (iDot < 0))
		{
		   alert("Invalid File Path for Upload! ext :"+iExt+ 'Idot :'+iDot+'  --path :'+filePath);
		   return false;
		}*/
	
	     if ( dotPos > 0 )
	     {
	         var aUpload = file.split(".");
	         var type = aUpload[aUpload.length-1].toLowerCase();
	         if (  allowedExts.indexOf(type.toLowerCase()) == -1 )
	          {
	             var msg = "Sorry, only JPG,GIF & PNG files are allowed!";
	             var title = "Error";
	             return false; 
	         }
	
	  	}
	  	else
	  	{
	  		//alert("Invalid File Path for Upload! ext :"+iExt+ 'Idot :'+iDot+'  --path :'+filePath);
	  		return false;
	  	}
	  	//return true;
	}
	else
	{
		return true;
	}

}

/**
 * Function used to clear error fields in the form
 * It accepts variable number of arguments(error field id's) and clear
 * @param string
 * @return
 */
function clearInnerHTML(string) {
	  for (i=0; i < arguments.length; i++) {
		  if ( typeof(document.getElementById(arguments[i])) != "undefined" && document.getElementById(arguments[i]) != null )
		  {
			  document.getElementById(arguments[i]).innerHTML = '';
		  }
	  }
	}

/**
 * function used to check whether username follows our predefined username rules
 * @param string username
 * @return bool
**/
function checkImpUsernameRule(username)
{
	username = trimWhitespace(username);
	//regular expression to validate username rules
	var regex = new RegExp("[A-Za-z]{1,1}[a-zA-Z\\d]{5,}");
	//if ( username.search && username.search(/[A-Za-z]{1,1}[a-zA-Z\d]{5,}/) != -1))
	if ( username.search && username.search(regex) != -1)
	{
		return true;
	}
	return false;
}

/**
 * function used to check whether password follows our predefined password rules
 * @param string password
 * @param String username_field_id
 * @return bool
**/
function checkImpPasswordRules(password, usernameField)
{
	var usernameField = $("#"+usernameField)[0];
	if ( usernameField.value && password.search && password.search(usernameField.value) == -1 )
	{
		//var passLen = password.length;
		//regular expression to validate password rules
		//var regex = new RegExp("[a-zA-Z]*\\d*[!@#$%\\^&\\*\\(\\)\\-\\+=~`\\|\\\\\\[\\]{}:;'\"\\.>,<\\?/_]*(([a-zA-Z]+[!@#$%\\^&\\*\\(\\)\\-\\+=~`\\|\\\\\\[\\]{}:;'\"\\.>,<\\?/_]+\\d+)|([!@#$%\\^&\\*\\(\\)\\-\\+=~`\\|\\\\\\[\\]{}:;'\"\\.>,<\\?/_]+[a-zA-Z]+\d+)|([a-zA-Z]+\d+[!@#$%\\^&\\*\\(\\)\\-\\+=~`\\|\\\\\\[\\]{}:;'\"\\.>,<\\?/_]+)|(\\d+[a-zA-Z]+[!@#$%\\^&\\*\\(\\)\\-\\+=~`\\|\\\\\\[\\]{}:;'\"\\.>,<\\?/_]+)|([!@#$%\\^&\\*\\(\\)\\-\\+=~`\\|\\\\\\[\\]{}:;'\"\\.>,<\\?/_]+\\d+[a-zA-Z]+)|(\\d+[!@#$%\\^&\\*\\(\\)\\-\\+=~`\\|\\\\\\[\\]{}:;'\"\\.>,<\\?/_]+[a-zA-Z]+))+[a-zA-Z]*\\d*[!@#$%\\^&\\*\\(\\)\\-\\+=~`\\|\\\\\\[\\]{}:;'\"\\.>,<\\?/_]*");
		
		var pwdRegex	=	/^([a-zA-Z0-9-,._!#$\£:;&^]{6,16})$/

		 if(!pwdRegex.test(password)) {
			return false;
		 }
		 return true;
	}
	/*else if ( usernameField.value )
	{
		return "username found";
	}
	else if ( typeof usernameField.value == "undefined" )
	{
		return "invalid username field";
	}
	else if ( !string.search )
	{
		return "search function undefined";
	}*/
	
}
