//validateInputScript.js - © 2006 - last modified 25.06.2006 by Philip Sparke of sunny-properties.com
onerror=handleErr;
var txt="", errorDetailedMessage="", inerror=0;

// create new Error objects
mandatoryFieldError = new Error ("Field cannot be blank or left empty!");
passwordError = new Error ("The confirmation Password you entered does not match the first password entered,\n please re-enter both, the case of each character entered must be the same!");
formReSubmissionError = new Error ("An attempt has been made to automatically re-submit a form without specifying the formID!");
internalASPError = new Error ("Internal ASP code error encountered!");
emailAddressError = new Error ("The confirmation Email Address you entered does not match the first Email Address entered,\n please re-enter both, the case of each character entered must be the same!");

function handleErr(msg,url,l)
{
	txt="There was an JS error on this page.\n\n";
	txt+="Error: '" + msg + "'\n";
	txt+="URL: '" + url + "'\n";
	txt+="Line: '" + l + "'\n\n";
	txt+="Please e-mail the above information to the web master at: \n\n";
	txt+="webmaster@sunny-properties.com \n\n";
	txt+="Click OK to continue.\n\n";
	alert(txt);
	return true;
}

function mainExceptionHandler(e)
{
	alert (e.message+"\n"+errorDetailedMessage);
	inerror=-1;
}

function ValidateInputString(stringToBeValidated, numberOrString, formFieldID, debugOption)
{
	//This function attempts to check for and then remove banned words from a form's input field (stringToBeValidated)
	//numberOrString signifies whether this is a text or number field
	//id is the id of the field form
	//debugOption ('xxx') determines whether debug information is alerted to the user
	errorDetailedMessage = "(jsf01): ";
	//Declaring varibales
	var re, rawInputString, rawInputStringUC, cleanString, testString, exitLoop, stringLength;
	var bannedKeyWords, arrayLength, arrayIndex, nonSpaceCharFound;
	//Here we execute the code within a try
	try
	{
		if ( (numberOrString == null)||(numberOrString == "")||(formFieldID == null)||(formFieldID == "") )
		{
			if (numberOrString == null)
			{
				numberOrString = "NULL";
			}
			if (formFieldID == null)
			{
				formFieldID = "NULL";
			}
			errorDetailedMessage = errorDetailedMessage + "stringToBeValidated:["+stringToBeValidated+"];numberOrString:["+numberOrString+"];formFieldID:["+formFieldID+"]";
			throw internalASPError;
		}
		else
		{
			if (debugOption == "Yes")
			{
				alert("stringToBeValidated:["+stringToBeValidated+"];numberOrString:["+numberOrString+"];formFieldID:["+formFieldID+"]");
			}
		}

		//Here we check if field entry is manadatory depending on the type of data expected
		if ( ( (stringToBeValidated == null) || ( stringToBeValidated == "") ) && ( (numberOrString == "numberMandatory") || (numberOrString == "currencyMandatory")||(numberOrString == "stringMandatory") ) )
		{
			errorDetailedMessage = errorDetailedMessage + "Field '" + formFieldID.substring(3,formFieldID.length) + "' must be completed, it is mandatory as are all fields marked with an * ";
			throw mandatoryFieldError;
			//return "MandatoryError";
		}
		else
		{
			bannedKeyWords = Array('"', "'", "*", "%", "SELECT", "DELETE", "TRUNCATE", "UPDATE", "INSERT", "=", "EXECUTE", "CUNT", "FUCK", "FUCKING", "BASTARD", " PRICK ", "SHIT", "OLD FART", "FARTTING", " ARSE", "ARSEHOLE", "WANKER", "FUCKER", "SWINE", "BLOODY", "FRIGGING", "PISS", "BUGGER");
			arrayLength = bannedKeyWords.length;
			if ( (debugOption == "Yes")||(debugOption == "IO") )
			{ 
				alert("Entering ValidateInputString with stringToBeValidated:["+stringToBeValidated+"],numberOrString:["+numberOrString+"],array length:["+arrayLength.toString()+"]");
			}
			rawInputStringUC = stringToBeValidated.toUpperCase();
			rawInputString = stringToBeValidated;
			arrayIndex = arrayLength; //Number of keyword strings in Array to check for
			//Loop through each word in array and replace evry occurence of banned word in field as required with " "
			//Then we remove extra spaces that were genereated as required
			while (arrayIndex > 0)
			{
				testString = bannedKeyWords[arrayIndex-1];//banned word to check
				if(debugOption == "IO")
				{ 
					alert("bannedKeyWords[" + (arrayIndex-1).toString() + "];current banned word:["+testString+"]");
				}
				while (rawInputStringUC.indexOf (testString,0) >= 0 )
				{
					rawInputString = ( rawInputString.substring (0,rawInputStringUC.indexOf (testString,0)) + rawInputString.substring (rawInputStringUC.indexOf (testString,0)+testString.length, rawInputStringUC.length) );
					rawInputStringUC = ( rawInputStringUC.substring (0,rawInputStringUC.indexOf (testString,0)) + rawInputStringUC.substring (rawInputStringUC.indexOf (testString,0)+testString.length, rawInputStringUC.length) );
				}
				arrayIndex -= 1;
			}
			//re = new RegExp(" ");
			//cleanString = rawInputString.replace(/ /, "");
			//Here we remove extra speaces previously generated as required
			stringLength = rawInputString.length;
			exitLoop = 0;
			nonSpaceCharFound = 0;
			if(debugOption == "Yes")
			{ 
				alert("rawInputString:["+rawInputString+"]"); //field prior to space removal
			}
			
			while (exitLoop <= (stringLength -1))
			{
				if(debugOption == "Yes")
				{ 
					alert("rawInputString.charCodeAt("+exitLoop+")["+rawInputString.charCodeAt(exitLoop)+"]");
				}

				if (rawInputString.charCodeAt(exitLoop) != 32)
				{
					nonSpaceCharFound += 1;
					//alert("nonSpaceCharFound("+nonSpaceCharFound+"]");
				}
				else if ( (rawInputString.charCodeAt(exitLoop) == 32) && (nonSpaceCharFound == 0) )
				{
					rawInputString = rawInputString.replace(/ /, "");
					stringLength = rawInputString.length;
					//alert("stringLength["+stringLength+"]");
				}
				exitLoop += 1;
			}
			cleanString = "";
			if ((numberOrString == "number")||(numberOrString == "numberMandatory"))
			{
				//We are not processing a string so remove all characters which are not numbers!
				stringLength = rawInputString.length;
				exitLoop = 0;
				while (exitLoop <= (stringLength -1))
				{
					if(debugOption == "Yes")
					{ 
						alert("Number-rawInputString.charCodeAt("+exitLoop+")["+rawInputString.charCodeAt(exitLoop)+"]");
					}
					//if number between ascii 48 and 57
					if ((rawInputString.charCodeAt(exitLoop) >= 48) && (rawInputString.charCodeAt(exitLoop) <= 57))
					{
						cleanString += rawInputString.charAt(exitLoop);
					}
					exitLoop += 1;
				}
				//If after cleaning we check to see if what we have left is indeed a number and if not we enter a zero
				if (isNaN(cleanString))
				{
					cleanString = "0";
				}
			}
			else if ((numberOrString == "currency")||(numberOrString == "currencyMandatory"))
			{
				//We are not processing a string so remove all characters which are not numbers or periods(.)!
				stringLength = rawInputString.length;
				exitLoop = 0;
				decimalpointcount = 0;
				while (exitLoop <= (stringLength -1))
				{
					if (debugOption == "Yes")
					{
						alert("currency-rawInputString.charCodeAt("+exitLoop+")["+rawInputString.charCodeAt(exitLoop)+"]");
					}
					//if number between ascii 48 and 57 or period(.)
					if ( ( (rawInputString.charCodeAt(exitLoop) >= 48) && (rawInputString.charCodeAt(exitLoop) <= 57) ) || (rawInputString.charCodeAt(exitLoop) == 46) )
					{
						//if (.) and at position string_length - 2 (i.e. 200234.00) then ok
						if(((exitLoop == (stringLength -3)) || (exitLoop == (stringLength -2))) && (rawInputString.charCodeAt(exitLoop) == 46) && decimalpointcount < 1 )
						{
							decimalpointcount += 1;
							cleanString += rawInputString.charAt(exitLoop);
						}
						else if (rawInputString.charCodeAt(exitLoop) != 46)
						{
							cleanString += rawInputString.charAt(exitLoop);
						}
					}
					//alert("currency-rawInputString.charCodeAt("+exitLoop+")["+rawInputString.charCodeAt(exitLoop)+"]");
					exitLoop += 1;
				}
				if (isNaN(cleanString))
				{
					cleanString = "0";
				}
			}
			else if ((numberOrString == "decimal")||(numberOrString == "decimalMandatory"))
			{
				//We are not processing a string so remove all characters which are not numbers or periods(.)!
				stringLength = rawInputString.length;
				exitLoop = 0;
				while (exitLoop <= (stringLength -1))
				{
					if (debugOption == "Yes")
					{
						alert("currency-rawInputString.charCodeAt("+exitLoop+")["+rawInputString.charCodeAt(exitLoop)+"]");
					}
					//if number between ascii 48 and 57 or period(.)
					if ( ( (rawInputString.charCodeAt(exitLoop) >= 48) && (rawInputString.charCodeAt(exitLoop) <= 57) ) || (rawInputString.charCodeAt(exitLoop) == 46) )
					{
						cleanString += rawInputString.charAt(exitLoop);
					}
					exitLoop += 1;
				}
				if (isNaN(cleanString))
				{
					cleanString = "0.0";
				}
			}
			else
			{
				cleanString = rawInputString;
			}
			
			if ( (debugOption == "Yes")||(debugOption == "IO") )
			{ 
				alert("Exting ValidateInputString with cleanString:["+cleanString+"],numberOrString:["+numberOrString+"]");
			}
			return cleanString;
		}
	}
	catch (e)
	{
		// catch all thrown errors and forward ion to customised exception handler
		mainExceptionHandler(e); 
	}
	
}

function ValidateFormInputText(formID, numberOrString, debugOption)
{
	//This function attempts to check for and then remove banned words from every field of a form (referenced by formID)
	//numberOrString signifies whether this is a text or number field
	//debugOption ('xxx') determines whether debug information is alerted to the user
	errorDetailedMessage = "(jsf02): ";
	//Declaring varibales
	var	formObject, CollectionOfFormObjectElements, totalNumberOfElements;
	var cleanInputText, indexCounter, stringObjectName;
	//Here we execute the code within a try statement
	try
	{
		if ( (numberOrString == null)||(numberOrString == "")||(formID == null)||(formID == "") )
		{
			if (numberOrString == null)
			{ 
				numberOrString = "NULL";
			}
			if (formID == null)
			{
				formID = "NULL";
			}
			errorDetailedMessage = errorDetailedMessage + "numberOrString:["+numberOrString+"];formID:["+formID+"]";
			throw internalASPError;
		}
		else
		{
			if(debugOption == "Yes")
			{
				alert("numberOrString:["+numberOrString+"];formID:["+formID+"]");
			}
		}
		formObject = document.getElementById(formID);
		CollectionOfFormObjectElements = formObject.elements;
		totalNumberOfElements = CollectionOfFormObjectElements.length;
		indexCounter = totalNumberOfElements - 1;
		while(indexCounter >= 0)
		{
			if(debugOption == "Yes") { alert("formID:["+formID+"]"+(CollectionOfFormObjectElements(indexCounter).name).substring(0,3).toUpperCase()) };
			if (((CollectionOfFormObjectElements(indexCounter).id).substring(0,3)).toUpperCase() == "NUM")
			{
				numberOrString = "number";
			}
			else if (((CollectionOfFormObjectElements(indexCounter).id).substring(0,3)).toUpperCase() == "NMA")
			{
				numberOrString = "numberMandatory";
			}
			else if (((CollectionOfFormObjectElements(indexCounter).id).substring(0,3)).toUpperCase() == "CUR")
			{
				numberOrString = "currency";
			}
			else if (((CollectionOfFormObjectElements(indexCounter).id).substring(0,3)).toUpperCase() == "CMA")
			{
				numberOrString = "currencyMandatory";
			}
			else if (((CollectionOfFormObjectElements(indexCounter).id).substring(0,3)).toUpperCase() == "DEC")
			{
				numberOrString = "decimal";
			}
			else if (((CollectionOfFormObjectElements(indexCounter).id).substring(0,3)).toUpperCase() == "DMA")
			{
				numberOrString = "decimalMandatory";
			}
			else if (((CollectionOfFormObjectElements(indexCounter).id).substring(0,3)).toUpperCase() == "STR")
			{
				numberOrString = "string";
			}
			else if (((CollectionOfFormObjectElements(indexCounter).id).substring(0,2)).toUpperCase() == "DT")
			{
				numberOrString = "string";
			}
			else
			{
				numberOrString = "stringMandatory";
			}
			if(debugOption == "Yes")
			{
				alert((CollectionOfFormObjectElements(indexCounter).type));
			}
			if ( (((CollectionOfFormObjectElements(indexCounter).type).toUpperCase()) == "TEXT") || (((CollectionOfFormObjectElements(indexCounter).type).toUpperCase()) == "TEXTAREA" ) )
			{
				if(debugOption == "Yes") { alert ("Before:" + (CollectionOfFormObjectElements(indexCounter).value))  };
								//ValidateInputString(stringToBeValidated, numberOrString, formFieldID, debugOption)
				cleanInputText = ValidateInputString(CollectionOfFormObjectElements(indexCounter).value, numberOrString, (CollectionOfFormObjectElements(indexCounter).id), debugOption);
				//if (cleanInputText == "MandatoryError") {break};
				CollectionOfFormObjectElements(indexCounter).value = cleanInputText;
				if(debugOption == "Yes") { alert ("After:" + (CollectionOfFormObjectElements(indexCounter).value)) };
			}
			indexCounter = indexCounter - 1;
		}
		if ((cleanInputText != "MandatoryError" )&&(inerror!=-1))
		{
			//All field data entered as required and clean of banned words so submit form
			formObject.submit();
		}
		else
		{
			inerror = 0;
		}
	}
	catch (e)
	{
		// catch all thrown errors and forward ion to customised exception handler
		mainExceptionHandler(e); 
	}
}

function disableControlByID(dependentControlID, dependentControlValue, disableControlID, debugOption)
{
	//This function will disable control specified by disableControlID when the value (dependentControlValue)
	//of the specified dependentControlID is encountered
	//id is the id of the field form
	//debugOption ('xxx') determines whether debug information is alerted to the user
	errorDetailedMessage = "(jsf05): ";
	//Declaring varibales
	var	dependentControlObject, OptionsOfDependentControlObject, disableControlObject, OptionsOfDisableControlObject;
	//Here we execute the code within a try statement
	try
	{
		if ( (dependentControlID == null)||(dependentControlID == "" )||(dependentControlValue == null)||(dependentControlValue == "" )||(disableControlID == null)||(disableControlID == "") )
		{
			if (dependentControlID == null)
			{
				dependentControlID = "NULL";
			}
			if (dependentControlValue == null)
			{
				dependentControlValue = "NULL";
			}
			if (disableControlID == null)
			{
				disableControlID = "NULL";
			}
			errorDetailedMessage = errorDetailedMessage + "dependentControlID:["+dependentControlID+"];dependentControlValue:["+dependentControlValue+"];disableControlID:["+disableControlID+"]";
			throw internalASPError;
		}
		else
		{
			if (debugOption == "Yes")
			{
				alert("dependentControlID:["+dependentControlID+"];dependentControlValue:["+dependentControlValue+"];disableControlID:["+disableControlID+"]");
			}
			dependentControlObject = document.getElementById(dependentControlID);
			OptionsOfDependentControlObject = dependentControlObject.options;
			disableControlObject = document.getElementById(disableControlID);
			OptionsOfDisableControlObject = disableControlObject.options;
		}
		
		if ((OptionsOfDependentControlObject[dependentControlObject.selectedIndex].text.substring(0,10)).toUpperCase() == dependentControlValue.toUpperCase())
		{
			disableControlObject.selectedIndex = 2;
			if ( (OptionsOfDisableControlObject[0].text == "" ) || (OptionsOfDisableControlObject[0].text == null ) )
			{
				OptionsOfDisableControlObject[0].text = OptionsOfDisableControlObject[2].text;
			}
		
			if ( (OptionsOfDisableControlObject[1].text == "" ) || (OptionsOfDisableControlObject[1].text == null ) )
			{
				OptionsOfDisableControlObject[1].text = OptionsOfDisableControlObject[2].text;
			}
		
			disableControlObject.disabled = false;
		}
		else
		{
			disableControlObject.selectedIndex = 0;
			OptionsOfDisableControlObject[0].text = "" ;
			disableControlObject.disabled = true;
		}
		if (debugOption == "Yes")
		{
			alert("disable control(" + disableControlID +"); Currently selected index =(" + disableControlObject.selectedIndex.toString() + ")");
			alert("value: of currently disabled(" + OptionsOfDisableControlObject[disableControlObject.selectedIndex].text +")");
		}
	}
	catch (e)
	{
		// catch all thrown errors and forward ion to customised exception handler
		mainExceptionHandler(e); 
	}
}

function verifyPassword(passwordID1,passwordID2,debugOption)
{
	//This verifies that the password and confirmation password fields match
	errorDetailedMessage = "(jsf06): ";
	//Declare varibales
	var	passwordObject1, passwordObject2;
	//Here we execute the code within a try statement
	try
	{
		passwordObject1 = document.getElementById(passwordID1);
		passwordObject2 = document.getElementById(passwordID2);
		
		if (debugOption == "Yes")
		{
			alert("Text for (" + passwordID1 + ") = (" + passwordObject1.value + ")\nText for (" + passwordID2 + ") = (" + passwordObject2.value + ")");
		}
		if (passwordObject1.value != passwordObject2.value)
		{
			passwordObject1.value = "" ;
			passwordObject2.value = "" ;
			passwordObject1.focus();
			throw passwordError;
		}
	}
	catch (e)
	{
		// catch all thrown errors and forward ion to customised exception handler
		mainExceptionHandler(e); 
	}
}

function verifyEmailAddress(emailAddressID1,emailAddressID2,debugOption)
{
	//This verifies that the password and confirmation password fields match
	errorDetailedMessage = "(jsf07): ";
	//Declare varibales
	var	emailAddressObject1, emailAddressObject2;
	//Here we execute the code within a try statement
	try
	{
		emailAddressObject1 = document.getElementById(emailAddressID1);
		emailAddressObject2 = document.getElementById(emailAddressID2);
		
		if (debugOption == "Yes")
		{
			alert("Text for (" + emailAddressID1 + ") = (" + emailAddressObject1.value + ")\nText for (" + emailAddressID2 + ") = (" + emailAddressObject2.value + ")");
		}
		if (emailAddressObject1.value != emailAddressObject2.value)
		{
			emailAddressObject1.value = "" ;
			emailAddressObject2.value = "" ;
			emailAddressObject1.focus();
			throw emailAddressError;
		}
	}
	catch (e)
	{
		// catch all thrown errors and forward ion to customised exception handler
		mainExceptionHandler(e); 
	}
}

function reSubmitFormAfterFormOptionChange(formID, debugOption, formInputIDToChange, newValue)
{
	//This function attempts to re-Submit a form (referenced by formID)
	//after an option has been changed
	//debugOption ('xxx') determines whether debug information is alerted to the user
	errorDetailedMessage = "(jsf08): ";
	//Declaring varibales
	var	formObject, formInputControlObject
	//Here we execute the code within a try statement
	try
	{
		if ( (formID == null)||(formID == "") )
		{
			if (formID == null)
			{
				formID = "NULL";
			}
			errorDetailedMessage = errorDetailedMessage + "formID:["+formID+"]";
			throw formReSubmissionError;
		}
		else if ( (formInputIDToChange == null)||(formInputIDToChange == "") )
		{
			if (formInputIDToChange == null)
			{
				formInputIDToChange = "NULL";
			}
			errorDetailedMessage = errorDetailedMessage + "formInputIDToChange:["+formInputIDToChange+"]";
			throw formReSubmissionError;
		}
		else
		{
			formInputControlObject = document.getElementById(formInputIDToChange)
			if (debugOption	== "Yes")
			{
				alert("formID:["+formID+"], formInputIDToChange:[" + formInputIDToChange + "], newValue:[" + newValue + "]");
			}
			formObject = document.getElementById(formID);
			formInputControlObject.value =  newValue;
			if(inerror!=-1)
			{
				formObject.submit();
			}
			else
			{
				inerror = 0;
			}
		}
	}
	catch (e)
	{
		// catch all thrown errors and forward ion to customised exception handler
		mainExceptionHandler(e); 
	}
}
//document.write(ValidateInputString("This is just to check that fucking sql characters such %, *, =, can be bloody well removed with words like Select, uPdate, INSERT, ExEcUtE and insert. ","string","IO"));
function DisplaySelectedImage(formID, imageSelectID, imageID, debugOption)
{
	//This function attempts to check for and then remove banned words from every field of a form (referenced by formID)
	//numberOrString signifies whether this is a text or number field
	//debugOption ('xxx') determines whether debug information is alerted to the user
	errorDetailedMessage = "(jsif09): ";
	//Declaring varibales
	var	formObject, ImageObject, CollectionOfFormObjectElements, totalNumberOfElements, imageSelectIDIndexValue;
	var cleanInputText, indexCounter, stringObjectName, displayImageIDIndexValue, newImagePath;
	//Here we execute the code within a try statement
	imageSelectIDIndexValue = -1;
	displayImageIDIndexValue = -1;
	try
	{
		if ( (formID == null)||(formID == "") )
		{
			if (formID == null)
			{
				formID = "NULL";
			}
			errorDetailedMessage = errorDetailedMessage + "formID:["+formID+"]";
			throw internalASPError;
		}
		else
		{
			if(debugOption == "Yes")
			{
				alert("formID:["+formID+"]");
				alert("document["+imageID+"].src:["+document[imageID].src+"]");
				
				totalNumberOfElements = document.images.length;
				indexCounter = totalNumberOfElements - 1;
				while(indexCounter >= 0)
				{
					if ( document.images[indexCounter].name == imageID )
					{
						alert("document.imageID["+indexCounter+"].name:["+document.images[indexCounter].name+"]");
						alert("document.imageID["+indexCounter+"].id:["+document.images[indexCounter].id+"]");
						alert("document.imageID["+indexCounter+"].src:["+document.images[indexCounter].src+"]");
						alert("document.imageID["+indexCounter+"].value:["+document.images[indexCounter].value+"]");
						alert("document.imageID["+indexCounter+"].alt:["+document.images[indexCounter].alt+"]");
						alert("document.imageID["+indexCounter+"].width:["+document.images[indexCounter].width+"]");
						alert("document.imageID["+indexCounter+"].height:["+document.images[indexCounter].height+"]");
					}
					indexCounter = indexCounter - 1;
				}
			}
		}
		formObject = document.getElementById(formID);
		CollectionOfFormObjectElements = formObject.elements;
		totalNumberOfElements = CollectionOfFormObjectElements.length;
		indexCounter = totalNumberOfElements - 1;
		while(indexCounter >= 0)
		{
			if(debugOption == "Yes") { alert("formID:["+formID+"]; Type:["+ (CollectionOfFormObjectElements(indexCounter).type) + "]; Name: [" + (CollectionOfFormObjectElements(indexCounter).name) + "]") };
			if ( ( CollectionOfFormObjectElements(indexCounter).id ) == imageSelectID ) //"ImageRef"
			{
			 	imageSelectIDIndexValue = indexCounter;
				if(debugOption == "Yes") { alert("imageSelectIDIndexValue:["+imageSelectIDIndexValue+"]") };
				newImagePath = CollectionOfFormObjectElements(imageSelectIDIndexValue).value;
				if(debugOption == "Yes") { alert("newImagePath:["+newImagePath+"]; ImageID:[" + imageID + "]") };
				//ImageObject = document.getElementById(imageID);
				document[imageID].src = newImagePath;
				//if(debugOption == "Yes") { alert("ImageObject.scr:["+ImageObject.scr+"]") };
				if(debugOption == "Yes") { alert("document.[imageID].src:["+document[imageID].src+"]") };
			}
			indexCounter = indexCounter - 1;
		}
	}
	catch (e)
	{
		// catch all thrown errors and forward ion to customised exception handler
		mainExceptionHandler(e); 
	}
}

