//version 3.1 RS

if(!Array.prototype.push){
	Array.prototype.push = function(objElementToAdd){
		this[this.length]=objElementToAdd;
	};
}

//this adds function and data members to the form object, must call this before 
//you can use addValidator() and validate()
function fv_makeFormValidating(objForm) {
			
	objForm.arrElementsToValidate = new Array();
	objForm.arrValidators=new Array();
	objForm.arrValidatorErrorMessages=new Array();
	objForm.arrOtherArguments=new Array();
		
	objForm.strErrorMessagesHeader="Unable to submit the form for the following reasons:";		
		
	//objFormElement: may be a string or the actual form element object
	//objValidatorFunction: function that, when passed a form element object, will return
	//						true or false if the form element passes or does not pass a specific test
	//strErrorMessage: Error Message to display to user if the form element does not pass
	//				   the validator function's test.
	objForm.addValidator=function(str_objFormElement, objValidatorFunction, strErrorMessage){		
		if(arguments.length < 3){
			alert('FormValidator Error: At least 3 parameters must be passed to the addValidator function.')
			return;
		}
		objFormElement=fv_getFormElementObj(this, str_objFormElement);		
		objForm.arrElementsToValidate.push(objFormElement);
		objForm.arrValidators.push(objValidatorFunction);
		objForm.arrValidatorErrorMessages.push(strErrorMessage);		
		objForm.arrOtherArguments.push(fv_sliceArray(arguments,3));		
	};

	//goes through all of this form's validators and either returns true if each of these
	//returned true, or informs the user of the problems found.						
	objForm.validate = function (){
		var doesValidate=true; //true if everything so far has validated
		this.arrErrorMessages=new Array();
		this.failedFormElements=new Array();
		
		for(var i=0; i<this.arrElementsToValidate.length; i++){			
			if(!this.arrValidators[i](this.arrElementsToValidate[i], this.arrOtherArguments[i])){			
				//don't give an error message to the same form element twice				
				if(!fv_inArray(this.failedFormElements, this.arrElementsToValidate[i])){ 
					this.failedFormElements.push(this.arrElementsToValidate[i])
					this.arrErrorMessages.push(this.arrValidatorErrorMessages[i]);	
				}
												
				//only set focus to first element that doesn't validate
				if(doesValidate){ fv_giveFormElementFocus(this.arrElementsToValidate[i]);}
				doesValidate=false;			
			}
		}
		
																		
		if(this.arrErrorMessages.length>0){
			this.displayFormErrorMessages(this.arrErrorMessages);
		}
		
		return doesValidate;
	}
	
	objForm.displayFormErrorMessages=function(arrErrorMessages){
		var strErrorMessages;
		strErrorMessages='';
		for(var i=0; i<arrErrorMessages.length; i++){
			strErrorMessages=strErrorMessages + '- ' + arrErrorMessages[i]+'\n'
		}
		if(this.strErrorMessagesHeader!=''){
			alert(this.strErrorMessagesHeader+'\n\n' + strErrorMessages);
		} else {
			alert(strErrorMessages);
		}
	}		
	
}

function fv_getFormElementObj(objForm, str_objFormElement){
	if(typeof(str_objFormElement)=="object") return str_objFormElement
	if(!objForm[str_objFormElement]){
		alert('FormValidator Error: Form element \'' + str_objFormElement + '\' does not exist.');
		return null;
	}
	return objForm[str_objFormElement];	
}

function fv_getFormElementValue(objFormElement){	

	//recursively handle form element group (such as radio buttons)
	if(objFormElement.length && !objFormElement.type){
		var strValue;
		for(var i=0; i<objFormElement.length; i++){
			strValue=fv_getFormElementValue(objFormElement[i]);
			if (strValue !=''){return fv_trim(strValue);}
		}
		return '';
	}

	if(objFormElement.type){
		if(objFormElement.type=="select-one"||objFormElement.type=="select-multiple"){
			if(objFormElement.options&&objFormElement.selectedIndex>=0){
				if(objFormElement.options[objFormElement.selectedIndex].value!='')
				   return fv_trim(objFormElement.options[objFormElement.selectedIndex].value);
				else
				   return fv_trim(objFormElement.options[objFormElement.selectedIndex].text);
			} else{
				return '';
			}
		} else if(objFormElement.type=="checkbox"||objFormElement.type=="radio"){
			if(objFormElement.checked==true)
				return fv_trim(objFormElement.value);
			else
				return '';
		}
	}
	//else
	return fv_trim(objFormElement.value);
}

function fv_setFormElementValue(objFormElement, strValue){
	if(objFormElement.type){
		if(objFormElement.type=="select-one"||objFormElement.type=="select-multiple"){
			if(objFormElement.options&&objFormElement.selectedIndex>=0){
				  objFormElement.options[objFormElement.selectedIndex].value=strValue;
   			      objFormElement.options[objFormElement.selectedIndex].text=strValue;
				  return;
			}
		}		
	}
	//else
	objFormElement.value=strValue;
}

function fv_giveFormElementFocus(objFormElement){
	if (objFormElement.disabled == 1) return;

	try {
		if(objFormElement.type && objFormElement.type=="text")
			objFormElement.select();
		if(objFormElement.length)
			objFormElement[0].focus();
		else
			objFormElement.focus();
	} catch (e) {
	}

}

function fv_inArray(arrArray, objToFind){
	for(var j=0; j<arrArray.length; j++){
		if(arrArray[j]==objToFind){
			return true;
		}
	}	
	return false;
}

function fv_checkNotInArray(objFormElement, arrOtherArguments) {
	var strValue = fv_getFormElementValue(objFormElement);
	return !fv_inArray(arrOtherArguments[0], strValue);
}

function fv_sliceArray(arrIn, intFirstIndex){
	var arrOut = new Array();
	for(var i=intFirstIndex; i<arrIn.length; i++){
		arrOut.push(arrIn[i]);
	}
	return arrOut;	
}

function fv_trim(strRef)
{
	if (strRef==null || typeof(strRef) == "undefined") return "";
	var str = strRef;
	while ( str != " " && str.substr(0,1)==" " && (str = str.substr(1,str.length-1)) ) ;		
	while ( str != " " && str.substr(str.length-1,1)==" " && (str = str.substr(0,str.length-1)) ) ;	
	if (str == " ") return "";
	else return str;
}

//validator functions: feel free to add more

function fv_checkHasValue(objFormElement){	
	return (fv_getFormElementValue(objFormElement))!='';
}

function fv_checkPostalCode(objFormElement){
	var strValue;	
	strValue=fv_getFormElementValue(objFormElement);
	strValue=strValue.toUpperCase();		
	strValue=strValue.replace(/\s/g, '');
	if(strValue=='') {return true;}
	//if(strValue.length!=6){return false;}	
	if (strValue.length==6) {
		var regularExpression= /^[a-zA-Z][0-9][a-zA-Z] [0-9][a-zA-Z][0-9]$/;
		strValue=strValue.substring(0,3) + " " + strValue.substring(3,6);
		if(regularExpression.test(strValue)){
			fv_setFormElementValue(objFormElement, strValue);				
			return true;
		}
	} else if (strValue.length==5 || strValue.length==10) {
		var regularExpression = /(^\d{5}$)|(^\d{5}-\d{4}$)/
		if(regularExpression.test(strValue)){
			fv_setFormElementValue(objFormElement, strValue);				
			return true;
		}
	}
	//else
	return false;
}

function fv_checkPositiveIntegerOrBlank(objFormElement)
{
	var answerBoolean=new Boolean(true);

	if (fv_checkHasValue(objFormElement))
	{
		answerBoolean=fv_checkInteger(objFormElement);
		if (answerBoolean)
		{
			answerBoolean = fv_checkIsNegative(objFormElement);
		}
	}
	else
	{
		answerBoolean=new Boolean(true);
	}
		
	return answerBoolean;
}

function fv_checkPositiveMoneyAmountOrBlank(objFormElement)
{
	var answerBoolean=new Boolean(true);

	if (fv_checkHasValue(objFormElement))
	{
		answerBoolean=fv_checkMoneyAmount(objFormElement);
		if (answerBoolean)
		{
			answerBoolean = fv_checkIsNegative(objFormElement);
		}
		
	}
	else
	{
		answerBoolean=new Boolean(true);
	}
		
	return answerBoolean;
}


function fv_checkInteger(objFormElement){
	var regularExpression= /^-?[0-9]+$/;
	return regularExpression.test(fv_getFormElementValue(objFormElement));
}

function fv_checkMoneyAmount(objFormElement){
	var regularExpression= /^-{0,1}[0-9]+(\.[0-9]([0-9]{0,1})){0,1}$/;
	return regularExpression.test(fv_getFormElementValue(objFormElement));	
}

function fv_checkEmail(objFormElement){
	var strValue;	
	strValue=fv_getFormElementValue(objFormElement);
	if(strValue=='') {return true;}
	//var regularExpression = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
	//source:http://www.breakingpar.com/bkp/home.nsf/Doc!OpenNavigator&87256B280015193F87256C40004CC8C6
	//old one used:
	//var regularExpression= /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
	var regularExpression = /^(((([\w\!\#\$\%\&\'\*\+\-\/\=\?\^_\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^_\`\{\|\}\~]+)|(\"".+\""))@(((([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}))|(\[(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\])))$/;
	return regularExpression.test(strValue);
}

/*function fv_checkFolder(objFormElement) {
	var strValue;
	strValue = fv_getFormElementValue(objFormElement);
	if (strValue == '')
		return false;
	var regularExpression = /^\w[^\\/:\*\?<>\|]+(?:\/[^\\/:\*\?<>\|]+)*(?:[^\/]*$)/;
	return regularExpression.test(strValue);
}*/

function fv_checkModelName(objFormElement) {
var strValue;
strValue = fv_getFormElementValue(objFormElement);
if (strValue != 'Select a Model:'){
	var temp;
	temp=strValue.split(' ');
	strValue=temp[0];
	var regularExpression = /^[A-Za-z0-9]+$/;
		return regularExpression.test(strValue);
}
}

function fv_checkIsNegative(objFormElement){
var strValue;
strValue = fv_getFormElementValue(objFormElement);
if (strValue < 0)
return false;
else
return true;
}

function fv_checkAlphaNum(objFormElement) {
	var strValue;
	strValue = fv_getFormElementValue(objFormElement);
	var regularExpression = /^[A-Za-z0-9]+$/;
	return regularExpression.test(strValue);
}

function fv_checkPhoneNumber(objFormElement) {
	var strValue;
	strValue = fv_getFormElementValue(objFormElement);

	if (strValue == '')
		return true;
	var regularExpression = /^(([^0-9A-Zx]*1)?[^0-9A-Zx]*[2-9A-Z]([^0-9A-Zx]*[0-9A-Z]){2}[^0-9A-Zx]*[2-9A-Z]([^0-9A-Zx]*[0-9A-Z]){6}[^0-9A-Zx]*(x[^0-9A-Zx]*([0-9A-Z][^0-9A-Zx]*)+)?)$/;
	return regularExpression.test(strValue);
}

function fv_checkEitherHasValue(objFormElement, otherArguments) {
	for(var i=0; i<otherArguments.length; i++) {
		if(fv_checkHasValue(fv_getFormElementObj(objFormElement.form, otherArguments[i])))
			return true;
	}	
	return false;
}

function fv_checkCompanyDomain(objFormElement, CompanyID) {
	if (gbl_DoActionWebService('Company/CheckCompanyDomain.aspx?CompanyID=' + CompanyID + '&Domain=' + fv_getFormElementValue(objFormElement)) == '222')
		return true;
	else
		return false;
}
			
function fv_checkRegionDomain(objFormElement, RegionID) {
	if (gbl_DoActionWebService('Company/CheckRegionDomain.aspx?RegionID=' + RegionID + '&Domain=' + fv_getFormElementValue(objFormElement)) == '223')
		return true;
	else
		return false;
}
			
function fv_checkLogin(objFormElement) {
	var strValue = fv_getFormElementValue(objFormElement);
	var re = /^[a-zA-Z0-9_\.]+$/;
	return (fv_checkEmail(objFormElement) || re.test(strValue));
}

function fv_checkMaxLength(objFormElement, maxlength) {
	return (fv_getFormElementValue(objFormElement).length > maxlength) ? false : true;
}

function fv_checkMinLength(objFormElement, minlength) {
	return (fv_getFormElementValue(objFormElement).length < minlength) ? false : true;
}

function fv_checkLength(objFormElement, LengthArguments) {
	return (fv_checkMinLength(objFormElement, LengthArguments[0]) && fv_checkMaxLength(objFormElement, LengthArguments[1]));
}

function fv_checkMinValue(objFormElement, minvalue) {
	return (fv_getFormElementValue(objFormElement)*1 < minvalue) ? false : true;
}

function fv_checkMaxValue(objFormElement, maxvalue) {
	return (fv_getFormElementValue(objFormElement)*1 > maxvalue) ? false : true;
}

function fv_checkValue(objFormElement, ValueArguments) {
	return (fv_checkMinValue(objFormElement, ValueArguments[0]) && fv_checkMaxValue(objFormElement, ValueArguments[1]));
}

function fv_checkMatch(objFormElement, otherArguments){
	return fv_getFormElementValue(fv_getFormElementObj(objFormElement.form, otherArguments[0])) == fv_getFormElementValue(fv_getFormElementObj(objFormElement.form, otherArguments[1]))
}

function fv_checkGreaterThan(objFormElement, otherArguments) {
	return (fv_getFormElementValue(objFormElement) > otherArguments[0]);
}

function fv_checkNotZeroEmpty(objFormElement) {
	var strValue = fv_getFormElementValue(objFormElement);
	if ((strValue == '0') || (strValue == 0) || (strValue == ''))
		return false;
	else
		return true;
}

function fv_checkUniqueLogin(objFormElement) {
	if (gbl_DoActionWebService('User/CheckUserLogin.aspx?desiredlogin=' + fv_getFormElementValue(objFormElement)) == '760')
		return true;
	else
		return false;
}

function fv_checkUniqueCompanyID(objFormElement) {
	if (gbl_DoActionWebService('Company/CheckCompanyID.aspx?desiredcompanyid=' + fv_getFormElementValue(objFormElement)) == '221')
		return true;
	else
		return false;
}

function fv_checkIPAddress(objFormElement) {
	var strValue;
	strValue = fv_getFormElementValue(objFormElement);
	if (strValue == '')
		return true;
	var re = /^(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$/;
	return re.test(strValue);
}

function fv_checkDomain(objFormElement) {
	var strValue;
	strValue = fv_getFormElementValue(objFormElement);
	if (strValue == '')
		return true;
	//var re = /^(http(s)?\:\/\/)?(([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6})$/
	var re = /^(([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)*[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?)$/
	return re.test(strValue);
}

function fv_checkInternetAddress(objFormElement) {
	var strValue;
	strValue = fv_getFormElementValue(objFormElement);
	if (strValue == '')
		return true;
	var re = /^(http(s)?\:\/\/)?(([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6})$/
	return re.test(strValue);
}

function fv_checkPortNumber(objFormElement) {
	var strValue;
	strValue = fv_getFormElementValue(objFormElement);
	if (strValue == '')
		return true;
	if (fv_checkInteger(objFormElement))
		if (strValue.length <= 5)
			if (strValue[0] != '0')
				if (strValue <= 65535)
					return true;
	return false;
}

//specific for Contact US
function fv_checkVINValue(objFormElement){
	var strValue;
	strValue=fv_getFormElementValue(objFormElement);
	if (strValue=='')
	{	return true;	}
	if (strValue.length!=17 && strValue !='')
	{		return false;	}
	else
	{return true;}
	 
}

function fv_checkHexValue(objFormElement) {
	var strValue = fv_getFormElementValue(objFormElement);
	if (strValue == '')
		return true;
	var re = /^#?[0-9a-fA-F]{6}$/
	return re.test(strValue);
	
}

//get filename extension from given filename
function getFileExtension (strFilename) {
	var point = -1;
	var leftover = strFilename;
	
	point = leftover.indexOf('.');
	if (point==-1) return "";
	while (point!=-1) {
		leftover = leftover.substring(point+1,leftover.length);
		point = leftover.indexOf('.');
	}
	return leftover;
}

//check if given file is included in an array of filetype
//use function "getFileExtension", case in-sensative
function fv_checkFileType(strFileName, aryAllowedType) {
	var ext = getFileExtension(strFileName)
	for(var i=0; i<aryAllowedType.length; i++){
		if(aryAllowedType[i].toLowerCase() == ext.toLowerCase())
			return true;
	}	
	return false;
}

//check if file type is "jpg/jpeg/gif/doc/pdf"
function fv_checkFileType_1(objFormElement) {
	var strFileName = fv_trim(fv_getFormElementValue(objFormElement));
	if (strFileName== "")	return true; //blank filename allowed

	var aryAllowedType = new Array("jpg","jpeg","gif","doc","pdf")
	return fv_checkFileType(strFileName, aryAllowedType)
}

//check if start date is less than or equal end date
function compareDate(startDate,endDate) {
	var dt1 = new Date(Date.parse(startDate));
	var dt2 = new Date(Date.parse(endDate));
	if (dt1.valueOf() <= dt2.valueOf())
		return true;
	else {
		alert ('End date must not be ealier than start date.');
		return false;
	}
}

//check if a form field is blank or in correct money format
function fv_checkNullOrCorrectMoney(objFormElement) {
	var v1 = fv_trim(fv_getFormElementValue(objFormElement));
	if (v1=="")
		return true;
	else
		return fv_checkMoneyAmount(objFormElement);
}

