/*
*	eliformValidater class(sort of class, javascript is classless, grrrr)
*
*	Usage, include this file in on the page it is going to be used on.
*	<script type="text/javascript" src="/js/eliformValidater.js"></script>
*	Then instantiate it just before the </form> tag of the form you're going to validate.
*	<script type="text/javascript">$eliFormValidater = new eliformValidater('eliHandlerForm');</script>
*	Don't forget to add onSubmit="return($eliFormValidater.validate());" to the opening form tag
*
*/
function eliFormValidater($formName){
	//try and create a dom object for the form we want to validate
	if (this.$form = document.getElementById($formName)) {
		//we've created a dom object sucessfully, lets create all the functions for our javascript 'class' to use.
		//a list of checkboxes that if present must have one selected
		this.$brochureListArray = ['postalBrochureVentures', 'postalBrochureTours', 'postalBrochureTefl', 'postalBrochureCareerbreak','dlBrochureVentures', 'dlBrochureTours', 'dlBrochureTefl', 'dlBrochureCareerbreak'];
		//the class prefix for input classes so we can add a prefix to stop confusion between existing classes
		this.$classPrefix = 'eliForm-';
		/*
		*	eliformValidater::validate
		*	validates a form based on the class types of the input within it.
		*
		*	eliForm-required - makes an input compulsary
		*	eliForm-email - validates an input as an email address
		*	eliForm-number - validates an input to a number
		*/
		this.validate = function(){
			$formError = false;
			$elementFocusSet = false;
			//looping through the forms elements
			for(i=0; i< this.$form.elements.length; i++)
			{
				if (this.$form.elements[i].id) {
					//reset all our variables for each iteration
					$required = false;//required class flag
					$email = false;//email class flag
					$number = false;//number class flag
					$elementError = false;//error validating this element flag
					$type = this.$form.elements[i].type//element type
					//get the class for the element and break it up on space
					$brokenUpString=this.$form.elements[i].className.split(" ");
					for($j=0; $j<$brokenUpString.length; $j++)
					{
						if ($brokenUpString[$j] == this.$classPrefix+'required') {
							$required = true;
						} else if ($brokenUpString[$j] == this.$classPrefix+'email') {
							$email = true;
						} else if ($brokenUpString[$j] == this.$classPrefix+'number') {
							$number = true;
						}
					}
					//we want to do different things based on the type of element we're looking at.
					switch($type)
					{
						case 'text': //text feild
							if ($required == true && this.$form.elements[i].value.length <= 0) {
								if ($elementToUpdate = document.getElementById(this.$form.elements[i].id+'Msg')) {
									$elementToUpdate.innerHTML = 'Required.';
								}
								$elementError = true;
							} else if($email == true){
								if (this.validateEmail(this.$form.elements[i].value) != true) {
									$elementError = true;
								}
							} else if ($number == true) {
								if (this.validateNumber(this.$form.elements[i].value) != true) {
									$elementError = true;
								}
							}
							break;
						case 'select-one'://select feild
							if ($required == true && this.$form.elements[i].value == ''){
								if ($elementToUpdate = document.getElementById(this.$form.elements[i].id+'Msg')) {
									$elementToUpdate.innerHTML = 'Required.';
								}
								$elementError = true;
							}
							break;
						case 'checkbox':
							if ($required == true && this.$form.elements[i].checked == false){
								if ($elementToUpdate = document.getElementById(this.$form.elements[i].id+'Msg')) {
									$elementToUpdate.innerHTML = 'Required.';
								}
								$elementError = true;
							}
							break;
						case 'textarea':
							if ($required == true && this.$form.elements[i].value.length <= 0) {
								if ($elementToUpdate = document.getElementById(this.$form.elements[i].id+'Msg')) {
									$elementToUpdate.innerHTML = 'Required.';
								}
								$elementError = true;
							}
						default:
					}
					if ($elementError == true) {
						//we've had an element error, so light it up.
						if ($elementToUpdate = document.getElementById(this.$form.elements[i].id)) {
							$elementToUpdate.style.backgroundColor="#FF0000";
							if (!$elementFocusSet) {
								$elementToUpdate.focus();
							}
							if ($elementToUpdate.type == 'checkbox') {
								$elementToUpdate.parentNode.style.border="1px solid #FF0000";
							}
						}
						//set the flag so we know there has been an error whilst processing the form.
						$formError = true;
					} else {
						//no element error means it's passed so we want to re colour it white.
						if ($elementToReset = document.getElementById(this.$form.elements[i].id)) {
							$elementToReset.style.backgroundColor="#FFFFFF";
							if ($elementToReset.type == 'checkbox') {
								$elementToReset.parentNode.style.border = "";
							}
							//$elementToReset.style.border="1px solid #C6C6C6";
							if ($elementToResetMsgSpan = document.getElementById($elementToReset.id+'Msg')) {
								$elementToResetMsgSpan.innerHTML = '';
							}
						}
					}
				}
			}
			//we want to check the $formError variable here
			if ($formError == true) {
				//there was a form error
				if (this.checkBrochureSelected() == false) {
					//brochure fields were present and not selected, tut tut.
					alert('Please select a brochure.');
					if (document.getElementById("areaBrochure")) {
						this.highlightArea(document.getElementById("areaBrochure"));
					}
				}
				return(false);
			} else {
				//check to see if brochures needed selecting
				if (this.checkBrochureSelected() == false) {
					//brochure fields were present and not selected, tut tut.
					alert('Please select a brochure.');
					if (document.getElementById("areaBrochure")) {
						this.highlightArea(document.getElementById("areaBrochure"));
					}
					return(false);
				} else {
					return(true);
				}
			}
		}

		/**
		* 	eliformValidater::highlightArea
		*	highlight area
		*	prototype & scriptaculous required
		*/
		this.highlightArea = function($elementId){
			new Effect.Highlight($elementId, {
				startcolor: '#ffff99', endcolor: '#ffffff', restorecolor: '#ffffff'
			});
		}

		/*
		*	eliformValidater::validateEmail
		*	returns a boolean on the validaty of an email address.
		*/
		this.validateEmail = function($email){
			$emailFilter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
			if ($emailFilter.test($email)) {
				return true;
			} else {
				return false;
			}
		}

		/*
		*	eliformValidater::validateNumber
		*	returns a boolean on the validaty of a number.
		*/
		this.validateNumber = function($number){
			$numericFilter = /^[0-9\(\)\-\ ]*$/;
			if ($numericFilter.test($number)) {
				return true;
			} else {
				return false;
			}
		}

		/*
		*	eliformValidater::updateRegionChoices
		*	updates the region choice input field based on the country code selected in eliCountryCode.
		*	if the AJAX.Request brings back data we convert it from JSON to an Array() using eval()
		*/
		this.countryFieldId = 'strUserAddressCountry';
		this.regionFieldId = 'strUserAddressRegion';
		this.countyFieldId = 'strUserAddressCounty';

		this.updateRegionChoices = function(){
			//check there's an eliRegionSpan otherwise there's no point continuing
			if ($eliRegionSpan = document.getElementById(this.regionFieldId+'Span')) {
				//check that eliCountrycode exists and we can get a value from it
				if ($countryCode = document.getElementById(this.countryFieldId).options[document.getElementById(this.countryFieldId).selectedIndex].value) {
					//call in the AJAX
					if ($eliRegion = document.getElementById(this.regionFieldId)) {
						$eliRegionClass = $eliRegion.className;
					} else {
						$eliRegionClass= '';
					}
					new Ajax.Request('/ajax/autoCompleteForm.ajax.php?getFormComponant=regions&countryCode='+$countryCode,
					  {
					    method:'get',
					    onSuccess: function(transport){
					    //sucessfull response from the AJAX call
						$response = transport.responseText || null;
						 //if we've got an output we want to process it
						 if ($response != null) {
							 $currentValue = '';
							 if (document.getElementById('strUserAddressRegion')) {
							 	if (document.getElementById('strUserAddressRegion').value != '') {
							 		$currentValue = document.getElementById('strUserAddressRegion').value;
								}
							 }
							$regionListArray = eval('(' + $response + ')');
							$regionListHtml = '';
							//loop through the array and generate html
							for($j=0; $j<$regionListArray.length; $j++)
							{
								$selected = '';
								if ($currentValue == $regionListArray[$j]) {
									$selected = ' selected';
								}
								$regionListHtml += '<option value="'+$regionListArray[$j]+'"'+$selected+'>'+$regionListArray[$j]+'</option>';
							}
							//fill eliRegionSpan with the result of our AJAX call
							$eliRegionSpan.innerHTML = '<select type="select" name="strUserAddressRegion" id="strUserAddressRegion" class="'+$eliRegionClass+'" title="Enter your region or state" onChange="$eliFormValidater.updateCountyChoices(false);"/><option value="">Please Select</option>'+$regionListHtml+'</select>';
						  } else {
							//response was null, create a normal text input field
							if ($eliRegion = document.getElementById("strUserAddressRegion")) {
								if ($eliRegion.type == 'select-one') {
									//if eliRegion used to be a select field we want to create the text field with blank value
							  		$eliRegionSpan.innerHTML = '<input type="text" name="strUserAddressRegion" id="strUserAddressRegion" class="'+$eliRegionClass+'" title="Enter your region or state" value=""/>';
							  	} else {
									//eliRegion used to be a text field so we want the value out of it.
							  		$eliRegionSpan.innerHTML = '<input type="text" name="strUserAddressRegion" id="strUserAddressRegion" class="'+$eliRegionClass+'" title="Enter your region or state" value="'+document.getElementById('strUserAddressRegion').value+'"/>';
							  	}
								if ($eliCounty = document.getElementById('strUserAddressCounty')) {
									if (eliCountySpan = document.getElementById('strUserAddressCountySpan')) {
										$eliCountySpan.innerHTML = '<input type="text" name="strUserAddressCounty" id="strUserAddressCounty" class="'+$eliCountyClass+'" title="Enter your region or state" value="'+document.getElementById('strUserAddressCounty').value+'"/></select>';
									}
								}
							}
						  }

					    },
					    onFailure: function(){}
					  });
					 //everytime we call this function we want to update the county choices too. it does it's own checking.
					 this.updateCountyChoices(true);
				}
			}
		}
		/*
		*	eliformValidater::updateCountyChoices
		*	updates the county choice input field based on the region selected in eliRegion.
		*	if the AJAX.Request brings back data we convert it from JSON to an Array() using eval()
		*/
		this.updateCountyChoices = function($reset){
			//check there is even an eliRegion input element to update otherwise don't bother.
			if ($eliRegion = document.getElementById(this.regionFieldId)) {
				$regionChoice = null;
				//get the value of the eliRegion input element if it's a select box
				if ($selectedIndex = $eliRegion.selectedIndex) {
					if ($selectedIndexValue = $eliRegion.options[$selectedIndex].value) {
						$regionChoice = $selectedIndexValue;
					}
				}
				if ($eliCounty = document.getElementById('strUserAddressCounty')) {
					$eliCountyClass = $eliCounty.className;
				} else {
					$eliCountyClass= '';
				}
				//check there is an eliCountySpan to update or don't bother carrying on
				if ($eliCountySpan = document.getElementById('strUserAddressCountySpan')) {
					//if we don't have a region choice and the reset flag is false
					if ($reset == false && $regionChoice != null) {
						//bring on the AJAX
						new Ajax.Request('/ajax/autoCompleteForm.ajax.php?getFormComponant=counties&region='+$regionChoice,
						  {
						    method:'get',
						    onSuccess: function(transport){
							  $response = transport.responseText || null;
							  if ($response != null) {
								 $currentValue = '';
								 if (document.getElementById('strUserAddressCounty').value != '') {
								 	$currentValue = document.getElementById('strUserAddressCounty').value;
								 }

							  	$regionListArray = eval('(' + $response + ')');
							  	$regionListHtml = '';
								$selectedElementActive = false;
								for($j=0; $j<$regionListArray.length; $j++)
								{
									$selected = '';
									if ($regionListArray.length == 1) {
										$selected = ' selected';
									} else if($j == 0){
										$regionListHtml += '<option value="">Please Select</option>';
									}else if ($currentValue == $regionListArray[$j]) {
										$selected = ' selected';
									}
									$regionListHtml += '<option value="'+$regionListArray[$j]+'"'+$selected+'>'+$regionListArray[$j]+'</option>';
								}
								//$eliCountySpan.innerHTML = '<select type="select" name="'+this.countryFieldId+'" id="'+this.countryFieldId+'" class="'+$eliRegionClass+'" title="Enter your region or state" onChange="$eliFormValidater.updateCountyChoices(false);"/><option value="">Please Select</option>'+$regionListHtml+'</select>';
								$eliCountySpan.innerHTML = '<select type="select" name="strUserAddressCounty" id="strUserAddressCounty" class="'+$eliCountyClass+'" title="Enter your region or state"/>'+$regionListHtml+'</select>';
							  } else {
								if (document.getElementById(this.countyFieldId).type == 'select-one') {
									$eliCountySpan.innerHTML = '<input type="text" name="strUserAddressCounty" id="strUserAddressCounty" class="'+$eliCountyClass+'" title="Enter your region or state" value=""/></select>';
							  	} else {
									$eliCountySpan.innerHTML = '<input type="text" name="strUserAddressCounty" id="strUserAddressCounty" class="'+$eliCountyClass+'" title="Enter your region or state" value="'+document.getElementById('strUserAddressCounty').value+'"/></select>';
								}
							  }
						    },
						    onFailure: function(){}
						  });
					} else {
						//if eliRegion is a select box it means we've got regions so we want to blank the input of the created text field
						if ($eliRegion = document.getElementById('strUserAddressRegion')) {
							if ($eliCountySpan = document.getElementById('strUserAddressCountySpan')) {
								if ($eliRegion.type == 'select-one') {
									$eliCountySpan.innerHTML = '<input type="text" name="strUserAddressCounty" id="strUserAddressCounty" class="'+$eliCountyClass+'" title="Enter your region or state" value=""/>';
							  	} else {
							  		$eliCountySpan.innerHTML = '<input type="text" name="strUserAddressCounty" id="strUserAddressCounty" class="'+$eliCountyClass+'" title="Enter your region or state" value="'+document.getElementById('strUserAddressCounty').value+'"/>';
							  	}
							}
						}
					}
				}
			}
		}
		/*
		*	eliformValidater::getClassNamesArray
		*	Loops through a string provided and returns an Array() of strings
		*/
		this.getClassNamesArray = function($className){
			$brokenUpString=$className.split(" ");
			$returnArray = new Array();
			for($j=0; $j<$brokenUpString.length; $j++)
			{
				if ($brokenUpString[$j] != '') {
					$returnArray.push($brokenUpString[$j]);
				}
			}
			return ($returnArray);
		}

		/*
		*	eliformValidater::checkBrochureSelected
		*	Checks for the presense of brochure check boxes in the form and checks to see if one is selected
		*/
		this.checkBrochureSelected = function(){
			$brochureSelected = false;
			$brochureElementsFound = false;
			for($j=0; $j< this.$brochureListArray.length; $j++){
				if ($checkboxElement = document.getElementById(this.$brochureListArray[$j])) {
					if ($checkboxElement.type == 'checkbox') {
						$brochureElementsFound = true;
						if ($checkboxElement.checked == true) {
							$brochureSelected = true;
						}
					}
				}
			}
			if ($brochureElementsFound == true && $brochureSelected == true) {
				return(true);
			}else if($brochureElementsFound == true && $brochureSelected == false){
				return(false);
			} else {
				return(true);
			}
		}

		//run code when class is instantiated. Have to do it here so it can use functions already defined.
		if ($eliCountryCode = document.getElementById('strUserAddressCountry')) {
			if ($eliCountryCode.type == 'select-one') {
				$classNamesArray = this.getClassNamesArray($eliCountryCode.className);
				if ($classNamesArray.length > 0) {
					for($i=0; $i< $classNamesArray.length; $i++){
						if ($classNamesArray[$i] == 'ajax') {
							//alert($eliCountryCode.id);
							this.updateRegionChoices();
						}
					}
				}
			}
		}
		for($i=0; $i< this.$form.elements.length; $i++)
		{
			$classNamesArray = this.getClassNamesArray(this.$form.elements[$i].className);
			for($j=0; $j< $classNamesArray.length; $j++){
				if ($classNamesArray[$j] == this.$classPrefix+'required') {
					if ($label = document.getElementById(this.$form.elements[$i].id+'Label')) {
						$LabelContents = $label.innerHTML;
						$label.innerHTML='<em>*</em>'+$LabelContents;
					}
				}
			}
		}
	}
}


