// Functions:
/* isRequired, validateSelect, validateBtns, validateAmount, validateNum, validateZip, validateEmail
*/

// Define the valid characters. Used by checkValidChars().
var validChars		= "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

// Define the non-sequential order. Used by checkIdentical().
var numSeqStr		= 6;
var strSeq			= new Array();
strSeq[1]			= "abcdefghijklmnopqrstuvwxyz";
strSeq[2]			= "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
strSeq[3]			= "zyxwvutsrqponmlkjihgfedcba";
strSeq[4]			= "ZYXWVUTSRQPONMLKJIHGFEDCBA";
strSeq[5]			= "0123456789";
strSeq[6]			= "9876543210";

var form = document.forms[0];


/********************************************************** /
// **************** Pre Generic form validation *********** /
// Flag form validate 
// - if set flag set to true - than call the actual validate - for future activation of validation of 
// forms outside; otherwise to nothing
/**********************************************************/
var validateFormFlag = false;
function PreValidateForm(vform) {
	if (validateFormFlag) {
		return ValidateForm(vform);
	}
}



/**********************************************************************************************************/
// ********** Generic form validation **********
/**********************************************************************************************************/

function ValidateForm(vform) {

	form = vform;
	
	for( var i=0; i<vform.length; i++ ) {
		fieldName = vform[i].name;
		fieldRequired = vform[i].required;
		fieldMethod = vform[i].method;
		fieldLabel = vform[i].label;
		fieldErrMsg = vform[i].errMsg;
		fieldValue = vform[i].value;
		
		/*
		if (fieldMethod != "") {
			alert(fieldName + " " +  fieldMethod + " " + fieldLabel + " " + fieldErrMsg + " " + fieldValue);
			//DisplayError (fieldName, fieldLabel, fieldErrMsg, true);
		}*/
		
		switch (fieldMethod) {
			case "isFieldEmpty": 
				if(isFieldEmpty(fieldName, fieldLabel, fieldErrMsg, fieldRequired)){ return (false); }
				break;
			case "validateAmount":
				if(validateAmount(fieldName, fieldLabel, fieldErrMsg, fieldRequired)){ return (false); }
				break;
			case "validateCurrency":  //flags to show as currency 
				if(validateAmount(fieldName, fieldLabel, fieldErrMsg, fieldRequired)){ return (false); }
				break;
			case "validatePositiveCurrency":  //flags to validate positive and show as currency 
//				if(validatePositiveAmount(fieldName, fieldLabel, fieldErrMsg, fieldRequired)){ return (false); }
				if(validateRatio(fieldName, fieldLabel, fieldErrMsg, fieldRequired)){ return (false); }
				break;
			case "validatePercent":  //flags to validate Percent 
				if(validateAmount(fieldName, fieldLabel, fieldErrMsg, fieldRequired)){ return (false); }
				break;
			case "validateNonClickableLogo":  //empty routine
				if(validateNothing(fieldName, fieldLabel, fieldErrMsg, fieldRequired)){ return (false); }
				break;
			case "validateNum":
				if(validateNum(fieldName, fieldLabel, fieldErrMsg,fieldRequired)){ return (false); }
				break;
			case "validateZip":
				if(validateZip(fieldName, fieldLabel, fieldErrMsg,fieldRequired)){ return (false); }
				break;
			case "validateEmail":
				if(validateEmail(fieldName, fieldLabel, fieldErrMsg, fieldRequired)){ return (false); }
				break;	
			case "validateSelect":
				if(validateSelect(fieldName, fieldLabel, fieldErrMsg, "", fieldRequired)){ return (false); }
				break;
			case "validateURL":
				if(isFieldEmpty(fieldName, fieldLabel, fieldErrMsg, fieldRequired)){ return (false); }
				break;
			case "validateDate":
				if(validateDate(fieldName, fieldLabel, fieldErrMsg, fieldRequired)){ return (false); }
				break;								
			case "validateBtns":
				if(validateBtns(fieldName, fieldLabel, fieldErrMsg)){ return (false); }
				break;
			default:
				//return false;
		}
	}
	return true;

}


//=====================================================================================================
// ********** UTILITIES **********
//=====================================================================================================

function DisplayError(fieldName, fieldLabel, errorMessage, isSelectable){
  errorMsg = "";
  
  if(( fieldLabel == "" ) || ( fieldLabel == " " )) {
  	errorMsg = errorMessage;
  } else {
    errorMsg = "\"" + fieldLabel +  "\""  + ": " + errorMessage + "";
	//errorMsg = errorMessage + ": \n\t" + "\"" + fieldLabel +  "\"";
  } 
  alert(errorMsg);
  
  if (isSelectable) { 
  	form[fieldName].select();
  }
  return;
}


/**********************************/

function removeCommas(fieldName) {
 newValue = "";
 fieldValue	= form[fieldName].value;
 for (i=0; i < fieldValue.length; i++) {
   letter = fieldValue.charAt(i);
   if(letter != ",") { newValue = newValue + letter; }
 }
 form[fieldName].value = newValue;
}


/**********************************/

function removeLeadingZeros(fieldName) {
 /* to do */
}

/**********************************/

function isDate(day, month, year) {
    	validReturn = true;
    	
    	if( isNaN(day) || (day < 0) || isNaN(month) || (month < 0) || isNaN(year) || (year < 0)) { validReturn = false; }
    	
    	if (month<1 || month>12) { validReturn = false; }
    	
    	if (day<1 || day>31)  { validReturn = false; }
    	
    	if (day==31 && (month==4 || month==6 || month==9 || month==11)) { validReturn = false; }


        if (month==2) {
            if ((year%4==0) && (year%100!=0 || year%400==0)) {
            			if (day>29) { validReturn = false; }

            }else {
				if (day>28) { validReturn = false; }
            }
        }
            
        if (day == "" || month == "" || year == "") { validReturn = false; }
        
        return validReturn;
}


//==================================================================================================
// ********** BEGIN GENERIC VALIDATION FUNCTIONS ***********
//==================================================================================================

	//==========================================================================================
	// ==================================== Check if field is empty 
	//==========================================================================================
function isFieldEmpty ( fieldName, fieldLabel, errorLabel, fieldRequired ) {
	error = false;
	fieldValue	= form[fieldName].value;
	
	if((( fieldValue == "" ) || ( fieldValue == " " )) && (fieldRequired == "1")){
		if (errorLabel == "") {
			errorLabel = "Please enter the required field";
		}
		DisplayError (fieldName, fieldLabel, errorLabel, true);
		error = true;
	}
	return error ;
}


/*
	// ===== Check if an option has been selected ==================== [old version]
function validateSelect_A( fieldName, fieldLabel, errorLabel, checkWhat ) {
	error	= false;
	optSelected	= form[fieldName].selectedIndex;
	fieldValue	= form[fieldName].options[optSelected].value;
	if( fieldValue == checkWhat ) {
		if (errorLabel == "") {
			errorLabel = "Please select one of the options.";
		}
		DisplayError (fieldName, fieldLabel, errorLabel, false);
		error = true;
	}
	return error ;
}
*/


	//==========================================================================================
	// ===== Check if an option has been selected =====
	//==========================================================================================
function validateSelect( fieldName, fieldLabel, errorLabel, checkWhat , fieldRequired ) {
	error	= false;
	optSelected	= form[fieldName].selectedIndex;
	fieldValue	= form[fieldName].options[optSelected].value;
	if(( fieldValue == checkWhat ) && (fieldRequired == "1")){
		if (errorLabel == "") {
			errorLabel = "Please select one of the options.";
		}
		DisplayError (fieldName, fieldLabel, errorLabel, false);
		error = true;
	}
	return error ;
}


	//==========================================================================================
	// ===== Check if a check or radio button has been selected =====
	//==========================================================================================
function validateBtns( fieldName, fieldLabel, errorLabel ) {
	error	= false;
	selection = null;
	thisButton		= form[fieldName];
	if (thisButton.length==null)
	{
		if( thisButton.checked ) {
		   selection = thisButton.value;
		}
	}
	else
	{
		for( var i=0; i<thisButton.length; i++ ) {
			if( thisButton[i].checked ) {
				selection = thisButton[i].value;
			}
		}
	}
	if( selection == null ) {
		if (errorLabel == "") {
			errorLabel = "Please check one of the boxes.";
		}
		DisplayError (fieldName, fieldLabel, errorLabel, false);
		error = true;
	}
	return error;
}


/*
	// ===== Check if a check or radio button has been selected =====
function validateBtns_A( fieldName, fieldLabel, errorLabel ) {
	error	= false;
	selection = null;
	thisButton		= form[fieldName];
	for( var i=0; i<thisButton.length; i++ ) {
		if( thisButton[i].checked ) {
		   selection = thisButton[i].value;
		}
	}
	if( selection == null ) {
		if (errorLabel == "") {
			errorLabel = "Please check one of the boxes.";
		}
		DisplayError (fieldName, fieldLabel, errorLabel, false);
		error = true;
	}
	return error;
}
*/

	//==========================================================================================
	// ===== Check if entry contains only numbers =====
	//==========================================================================================
function validateAmount( fieldName, fieldLabel, errorLabel, fieldRequired ) {
	error	= false;
	removeCommas(fieldName);
	
	fieldValue	= form[fieldName].value;
	fieldLength	= form[fieldName].value.length;
 
	if(isFieldEmpty(fieldName, fieldLabel, errorLabel, fieldRequired)){ return (true); }
	
	if (isNaN (fieldValue)) { 
		if (errorLabel == "") {
			errorLabel = "Please enter a valid number.";
		}
		DisplayError (fieldName, fieldLabel, errorLabel, true);
		error = true;
	}
	
	return error ;
}

	//========= Positive Amounts only version =========================================
function validatePositiveAmount( fieldName, fieldLabel, errorLabel, fieldRequired ) {
	error	= false;
	removeCommas(fieldName);
	
	fieldValue	= form[fieldName].value;
	fieldLength	= form[fieldName].value.length;
 
	if(isFieldEmpty(fieldName, fieldLabel, errorLabel, fieldRequired)){ return (true); }
	
	if (isNaN(fieldValue) || (fieldValue <= 0)) { 
		if (errorLabel == "") {
			errorLabel = "Please enter a valid number.";
		}
		DisplayError (fieldName, fieldLabel, errorLabel, true);
		error = true;
	}
	
	return error ;
}




/***
	// ===== Check if entry contains only numbers ===== [A]
function validateAmount_A( fieldName, fieldLabel, errorLabel ) {
	error	= false;
	removeCommas(fieldName);
	
	fieldValue	= form[fieldName].value;
	fieldLength	= form[fieldName].value.length;
 
	if(isRequired(fieldName, fieldLabel, errorLabel)){ return (true); }
	
	if (isNaN (fieldValue)) { 
		if (errorLabel == "") {
			errorLabel = "Please enter a valid number.";
		}
		DisplayError (fieldName, fieldLabel, errorLabel, true);
		error = true;
	}
	
	return error ;
}
***/


	//==========================================================================================
	// ===== Validate Number =====
	//==========================================================================================
function validateNum( fieldName, fieldLabel, errorLabel,fieldRequired ) {
	error	= false;
	removeCommas(fieldName);
	
	fieldValue	= form[fieldName].value;
	fieldLength	= form[fieldName].value.length;
 
	if(isFieldEmpty(fieldName, fieldLabel, errorLabel, fieldRequired)){ return (true); }

	for( var i = 0; i < fieldLength; i++ ) {
		var ch = fieldValue.substring( i, i + 1 );
		if (( ch < "0" ) || ( ch > "9" )) {
			if (errorLabel == "") {
				errorLabel = "Please enter valid number(s).";
			}
			DisplayError (fieldName, fieldLabel, errorLabel, true);
			error = true;
			break;
		}
	}
	
	return error ;
}

	
	//==========================================================================================
	// ===== Validate Zip =====
	//==========================================================================================
function validateZip( fieldName, fieldLabel, errorLabel , fieldRequired) {
	error	= false;
	
	fieldValue	= form[fieldName].value;
	fieldLength	= form[fieldName].value.length;
 
	
	if (validateNum( fieldName, fieldLabel, errorLabel , fieldRequired)) {
		return true;
	}

	if ((fieldLength > 0) && (fieldLength < 5)){
			if (errorLabel == "") {
				errorLabel = "Please enter a 5-digit zip code.";
			}
			DisplayError (fieldName, fieldLabel, errorLabel, true);
			error = true;
	}
	
	return error ;
}


	//==========================================================================================
	// ===== Validate email address =====
	//==========================================================================================
function validateEmail ( fieldName, fieldLabel, errorLabel,fieldRequired ) {
	errorMsg	= "";
	error = false;
	fieldValue	= form[fieldName].value;
	fieldLength	= form[fieldName].value.length;

	//default errorMsg for required if no errorLabel
	if (errorLabel == "") {
		errorMsg = "Please enter your Email address.";
	} else {
		errorMsg = errorLabel;
	}
	
	if (isFieldEmpty(fieldName, fieldLabel, errorMsg, fieldRequired)) { return (true); }
	
	errorMsg = ""  //null it again
	
	if ( fieldLength > 0 ) {
		if (( errorLabel == "" ) || ( errorLabel == null )) {

			errorLabel1	= "This is not a valid email address.";			// Not valid - can be default
			errorLabel2	= "Missing [ @ ] sign.";						// Missing "@"
			errorLabel3	= "Missing [ . ].";								// Missing "."
			errorLabel4	= "Cannot start with a space.";					// Starts with " "
			errorLabel5	= "Cannot start with [ @ ] sign.";				// Starts with "@"
			errorLabel6	= "Cannot start with [ . ].";					// Starts with "."

			if ( fieldValue.indexOf( "@" ) == -1 ) {
				errorMsg = errorLabel + errorLabel2 ;
			} else if ( fieldValue.indexOf( "." ) == -1 ) {
				errorMsg = errorLabel + errorLabel3;
			} else if ( fieldValue.charAt( 0 ) == " " ) {
				errorMsg = errorLabel + errorLabel4 ;
			} else if ( fieldValue.charAt( 0 ) == "@" ) {
				errorMsg = errorLabel + errorLabel5;
			} else if ( fieldValue.charAt( 0 ) == "." ) {
				errorMsg = errorLabel + errorLabel6;
			}

		} else {

			if (( fieldValue.indexOf( "@" ) == -1 ) || 					// Missing "@"
				( fieldValue.indexOf( "." ) == -1 ) || 					// Missing "."
				( fieldValue.charAt( 0 ) == "@" ) || 					// Starts with "@"
				( fieldValue.charAt( 0 ) == "." ) 						// Starts with "."
				) {
				errorMsg = errorLabel;
			}
		}
	}
	
	if (errorMsg != "") {
		DisplayError (fieldName, fieldLabel, errorMsg, true);
		error = true;
	}
	
	return error;
}


	//==========================================================================================
	//=== Validate Date in the format: MM/DD/YY =================================================
	//==========================================================================================
function validateDate (fieldName, fieldLabel, errorLabel, fieldRequired) {
	
	errorMsg = "";
	error = false;
	fieldValue	= form[fieldName].value;
	fieldLength	= form[fieldName].value.length;
	
	if (isFieldEmpty(fieldName, fieldLabel, errorMsg, fieldRequired)) { return true; }	
	if (fieldValue == ""){ return false; }

	//default errorMsg for required if no errorLabel
	if (errorLabel == "") {
		errorMsg = "Invalid date! \n\nFormat: MM/DD/YYYY";
	} else {
		errorMsg = errorLabel;
	}
	
		
	strDate = fieldValue.split("/");
	
	if (strDate.length < 3) { 
		DisplayError (fieldName, fieldLabel, errorMsg, true);
		return true;
	}
	
	strday   = strDate [1];
	strmonth = strDate [0];
	stryear  = strDate [2];
		
	if (!isDate(strday, strmonth, stryear)) {
			DisplayError (fieldName, fieldLabel, errorMsg, true);
			error = true;
	}
	return error;
}




	//==========================================================================================
	// ===== Validate Nothing =====
	//==========================================================================================
function validateNothing( fieldName, fieldLabel, errorLabel,fieldRequired ) {
	error	= false;
	if(isFieldEmpty(fieldName, fieldLabel, errorLabel, fieldRequired)){ return (true); }
	return error ;
}



/**************************************************************************************************/
/**************************************************************************************************/

/*  TO DO (corrections required):
	// ===== Validate field minimum and maximum length =====
function validateMinMax ( fieldName, fieldLabel, minLength, maxLength ) {
	errorMsg	= "";
	fieldValue	= form[fieldName].value;
	fieldLength	= form[fieldName].value.length;
	if ( fieldLength < minLength ) {
		errorMsg = "\"" + fieldLabel +  "\"  - Please enter at least " + minLength + " characters.";
	} else if (( fieldLength > maxLength ) && ( maxLength > 0 )) {
		errorMsg = "\"" + fieldLabel +  "\"  - Please enter less than " + maxLength + " characters.";
	}
	return errorMsg ;
}


	// ===== Check if entry contains only valid characters =====
function checkValidChars( fieldName, fieldLabel, errorLabel ) {
	errorMsg	= "";
	fieldValue	= form[fieldName].value;
	fieldLength	= form[fieldName].value.length;
	for( var i=0; i<fieldLength; i++ ) {
		if ( validChars.indexOf( fieldValue.charAt( i )) == -1 ) {
			errorMsg = "\"" + fieldLabel +  "\" - " + errorLabel + "";
		}
	}
	return errorMsg ;
}

	// ===== Check if entry contains entirely identical characters =====
function checkIdentical( fieldName, fieldLabel, errorLabel ) {
	errorMsg	= "";
	fieldValue	= form[fieldName].value;
	fieldLength	= form[fieldName].value.length;

	if (( fieldLength > 1 ) && ( isComposedOfChars( fieldValue.charAt( 0 ), fieldValue ))) {
		errorMsg = "\"" + fieldLabel +  "\" - " + errorLabel + "";
	}
	return errorMsg ;
}

function isComposedOfChars( curChar, inString ) {
	return ( indexOfFirstNotIn( curChar, inString ) == -1 );
}

function indexOfFirstNotIn( okayChars, inString ) {
	for ( var i=0; i<inString.length; i++ ) {
		if ( okayChars.indexOf( inString.charAt( i )) == -1 ) {
			return i;
		}
	}
	return -1;
}

	// ===== Check if entry contains entirely sequential characters =====
function checkSequential( fieldName, fieldLabel, errorLabel ) {
	errorMsg	= "";
	fieldValue	= form[fieldName].value;
	fieldLength	= form[fieldName].value.length;

	if ( fieldLength > 1 ) {
		for ( var i = 1; i < ( numSeqStr + 1 ); i++ )  {
			if ( strSeq[i].indexOf( fieldValue ) != -1 ) {
				errorMsg = "\"" + fieldLabel +  "\" - " + errorLabel + "";
			}
		}
	}
	return errorMsg ;
}
*/

// *********** END GENERIC VALIDATION FUNCTIONS ************





// *********** BEGIN STAND-ALONG VALIDATION FUNCTIONS ************

 	// ==== Validate a single form number field within low and hi limits
function ValidateField (field, low_val, hi_val)
{
	var fvalue = field.value;
	//fvalue_array = fvalue.split(",");
	//fvalue_array.length > 2
	
	if ((fvalue == "") || (fvalue == " ") || isNaN (fvalue) || (fvalue < low_val || fvalue > hi_val)) {
		
		alert ("Please, enter a number between " + low_val + " and " + hi_val 
				+ ".\nRemove commas, $ and % signs.");
		field.value = low_val
		field.select ();
	}
}


 	// ==== Validate a single form number field within low and hi limits
function ValidateFieldNotEmpty (field, low_val, hi_val)
{
	var fvalue = field.value;
	//fvalue_array = fvalue.split(",");
	//fvalue_array.length > 2
	
	if ((fvalue == "") || (fvalue == " ")) {
		return true;

	} else if (isNaN (fvalue) || (fvalue < low_val || fvalue > hi_val)) {
		
		alert ("Please, enter a number between " + low_val + " and " + hi_val 
				+ ".\nRemove commas, $ and % signs.");
		field.value = low_val
		field.select ();
	}
}

	// ==============================Validate Ratio - LoanAmount to ValueOfProperty
	
function validateRatio(fieldName, fieldLabel, fieldErrMsg, fieldRequired)
	{
		error	= false;
		var fieldValueAmount;
		var fieldValueProperty;
		

		switch (fieldName) {
			case "x_Amount": 
				fieldValueAmount=form[fieldName].value;
				fieldValueProperty=form["Value_Of_Property"].value;
//				alert(fieldValueAmount + "=" + fieldValueProperty);
				break;
			case "attribute_Amount_To_Borrow":
				fieldValueAmount=form[fieldName].value;
				fieldValueProperty=form["attribute_Value_Of_Property"].value;
//				alert(fieldValueAmount + "=" + fieldValueProperty);
				break;
			default:
				return false;
		}

//		if(isFieldEmpty(fieldName, fieldLabel, errorLabel, fieldRequired)){ return (true); }
	
		//if (isNaN(fieldValueAmount) || (fieldValueAmount <= 0)) 
		//{ 
		//	{
		//	errorLabel = "Please enter a valid number.";
		//	}
		//DisplayError (fieldName, fieldLabel, errorLabel, true);
		//return (true);
		//}
		
		while (fieldValueAmount.indexOf('$') > -1)
		{fieldValueAmount=fieldValueAmount.replace("$","");}

		while (fieldValueAmount.indexOf(',') > -1)
		{fieldValueAmount=fieldValueAmount.replace(",","");}

		while (fieldValueProperty.indexOf('$') > -1)
		{fieldValueProperty=fieldValueProperty.replace("$","");}
		
		while (fieldValueProperty.indexOf(',') > -1)
		{fieldValueProperty=fieldValueProperty.replace(",","");}
		
		if (fieldValueAmount <= 50000) 
		{ 
			{
				errorLabel = "Loan Amount must be greater than 50.000";
			}
			DisplayError (fieldName, fieldLabel, errorLabel, false);
			error = true;
		}
		else
		{
			if ((fieldValueAmount/fieldValueProperty) > 1.00) { 
			{
				errorLabel = "Please re-enter Loan Amount not to exceed Property Value";
				//errorLabel = "Loan Amount may not be more than 135% of Value of Property";				
			}
			DisplayError (fieldName, fieldLabel, errorLabel, false);
			error = true;
			}
		}
		
/*	
		//if (isNaN(fieldValue) || (fieldValue <= 0)) { 
		//	if (errorLabel == "") {
		//		errorLabel = "Please enter a valid number.";
		//	}
		//	DisplayError (fieldName, fieldLabel, errorLabel, true);
		//	error = true;
		//}
*/	
		return error ;
	
	}



// *********** END STAND-ALONG VALIDATION FUNCTIONS ************

/*

	// ===== Check if field is required =====
function isRequired ( fieldName, fieldLabel, errorLabel ) {
	error = false;
	fieldValue	= form[fieldName].value;
	
	if(( fieldValue == "" ) || ( fieldValue == " " )) {
		if (errorLabel == "") {
			errorLabel = "Please enter the required field.";
		}
		DisplayError (fieldName, fieldLabel, errorLabel, true);
		error = true;
	}
	return error ;
}
*/