/***************************************************************************************
****************************************************************************************
** Twyford School - js file ************************************************************
****************************************************************************************
***************************************************************************************/


// Image Functions
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}


// Retrieve an element on the page
function GetElement(id) {
	var element = document.getElementById(id);
	return element;
}


// Checks if a control with the passed ID exists on the page
function CheckExists(id) {
	if(document.getElementById(id) != null) {
		return true;
	}
	else {
		return false;
	}

}


// Validates an email address using a regular expression
function CheckEmail(email) {
	var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid
	var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/; // valid
	if (!reg1.test(email) && reg2.test(email)) { // if syntax is valid
		return true;
	}
	else {
		return false;
	}
}


// Function to update the total for an order form
function ChangeTotal(dropdownVal, hdnVal) {
	var newNo = document.getElementById(dropdownVal);
	var oldNo = document.getElementById('hdn' + dropdownVal);
	var price = document.getElementById(hdnVal);
	var total = document.getElementById('txtTotal');
	
	if((newNo.value * 1) > (oldNo.value * 1)) {
		total.value = (total.value * 1) + (((newNo.value * 1) - (oldNo.value * 1)) * (price.value * 1));
		oldNo.value = newNo.value;
	}
	else if((newNo.value * 1) < (oldNo.value * 1)) {
		total.value = (total.value * 1) - (((oldNo.value * 1) - (newNo.value * 1)) * (price.value * 1));
		oldNo.value = newNo.value;
	}
	
	if((newNo.value * 1) > 0) {
		newNo.style.background='lightyellow';
	}
	
	// Update amount
	document.getElementById('hdnAmount').value = total.value;
}


// Validate a form
function ValidateForm(frmName) {
	var required;
	var required2;
	var requiredMessage = ""
	var blnValid = true;
	var blnValidCtrl = true;
	var blnValidate = true;
	var config=/config/gi;
	var ctrls = GetElement(frmName).elements;
	
	ResetFormColours(frmName);
	ResetFCKeditorBackgrounds(frmName);
	
	// Check there are fields to validate
	if(CheckExists('required')) { required = GetElement('required').value.split(','); }
	
	// Loop through the required array, and using this loop through the form controls to validate
	for(var a = 0; a < required.length; a++) {
		required2 = required[a].split('/');
		blnValidate = true;
		for(var b = 0; b < required2.length; b++) {
			if(blnValidate) {
				for(var c = 0; c < ctrls.length; c++) {
					if(ctrls[c].id == required2[b]) {
						if(ctrls[c].type != "hidden") {
							blnValidCtrl = true;
							// Validate the control according to it's type
							if((ctrls[c].type == "text") || (ctrls[c].type == "textarea")) {
								if(ctrls[c].value == "") {
									blnValidCtrl = false;
								}
							}
							else if(ctrls[c].type == "select-one") {
								if(ctrls[c].selectedIndex == 0) {
									blnValidCtrl = false;
								}
							}
							// Now perform validation response
							if(blnValidCtrl == false)
							{
								// Check if there are any other controls part of this controls' validation
								var blnGrrr = false;
								for(var d = (b + 1); d < required2.length; d++) {
									for(var e = 0; e < ctrls.length; e++) {
										if(ctrls[e].id == required2[d]) {
											if(ctrls[e].type != "hidden") {
												if((ctrls[e].type == "text") || (ctrls[e].type == "textarea")) {
													if(ctrls[e].value != "") {
														blnGrrr = true;
													}
												}
												else if(ctrls[e].type == "select-one") {
													if(ctrls[e].selectedIndex > 0) {
														blnGrrr = true;
													}
												}
											}
											else if((ctrls[e].type == "hidden") && (ctrls[e].id.substring(0, 3).toUpperCase() == "FCK") && (!ctrls[e].id.match(config))) {
												if(ValidateFCKeditor2(ctrls[e].id)) {
													blnGrrr = true;
												}
											}
										}
									}
								}
								if(!blnGrrr) {
									blnValid = false;
									ctrls[c].style.backgroundColor="mistyrose";
								}
							}
							else {
								blnValidate = false;
								ctrls[c].style.backgroundColor="white";
							} 
						}
						else if((ctrls[c].type == "hidden") && (ctrls[c].id.substring(0, 3).toUpperCase() == "FCK") && (!ctrls[c].id.match(config))) {
							if(ValidateFCKeditor(ctrls[c].id) == false) {
								// Check if there are any other controls part of this controls' validation
								var blnGrrr = false;
								for(var d = (b + 1); d < required2.length; d++) {
									for(var e = 0; e < ctrls.length; e++) {
										if(ctrls[e].id == required2[d]) {
											if(ctrls[e].type != "hidden") {
												if((ctrls[e].type == "text") || (ctrls[e].type == "textarea")) {
													if(ctrls[e].value != "") {
														blnGrrr = true;
													}
												}
												else if(ctrls[e].type == "select-one") {
													if(ctrls[e].selectedIndex > 0) {
														blnGrrr = true;
													}
												}
											}
											else if((ctrls[e].type == "hidden") && (ctrls[e].id.substring(0, 3).toUpperCase() == "FCK") && (!ctrls[e].id.match(config))) {
												if(ValidateFCKeditor2(ctrls[e].id)) {
													blnGrrr = true;
												}
											}
										}
									}
								}
								if(!blnGrrr) {
									blnValid = false;
								}
								else {
									blnValidate = false;
									ResetFCKeditorBackground(ctrls[c].id);
								}
							}
							else {
								blnValidate = false;
							}
						}
					}
				}
			}
		}
	}
	
	// Perform any further validation
	if(blnValid) {
		if(CheckExists('email')) {
			var email = GetElement('email');
			if(CheckEmail(email.value) == false) {
				blnValid = false;
				email.style.backgroundColor="mistyrose";
				if(CheckExists('emailMessage')) {
					if(requiredMessage.length > 0) { requiredMessage += "\n" }
					requiredMessage += GetElement('emailMessage').value
				}
			}
			else {
				email.style.backgroundColor="white";
			}
		}
	}
	
	// If there's a required message to show...
	if(requiredMessage.length > 0) {
		alert("Please correct the below errors: \n" + requiredMessage);
	}

	return blnValid;
}


function ResetForm(frmName) {
	var config=/config/gi;
	var ctrls = GetElement(frmName).elements;
	// Loop through the form controls and reset
	for(var a = 0; a < ctrls.length; a++) {
		if(ctrls[a].type != "hidden") {
			if((ctrls[a].type == "text") || (ctrls[a].type == "textarea")) {
				ctrls[a].value = "";
			}
			else if(ctrls[a].type == "select-one") {
				if(CheckExists(ctrls[a].id)) {
					if(GetElement(ctrls[a].id + "_Reset").value=="1") {
						ctrls[a].selectedIndex == 0;
					}
				}
				else {
					ctrls[a].selectedIndex == 0;
				}
			}
			ctrls[a].style.backgroundColor="white";
		}
		else if((ctrls[a].type == "hidden") && (ctrls[a].id.substring(0, 3).toUpperCase() == "FCK") && (!ctrls[a].id.match(config))) {
			ResetFCKeditor(ctrls[a].id);
		}
	}
}


function ResetFormColours(frmName) {
	var ctrls = GetElement(frmName).elements;
	// Loop through the form controls and reset
	for(var a = 0; a < ctrls.length; a++) {
		if(ctrls[a].type != "hidden") {
			ctrls[a].style.backgroundColor="white";
		}
	}
}


/*************************
** FCK Editor functions **
*************************/
// Validates an FCK Editor instance
function ValidateFCKeditor(id) {
	var oEditor = FCKeditorAPI.GetInstance(id);
	var oDOM = oEditor.EditorDocument;
	var strFCKEditorText = "";
	var blnValid = true;
	
	// Retrieve the text
	if (document.all) { // If I.E.
		strFCKEditorText = oDOM.body.innerText;
	}
	else {
		var r = oDOM.createRange();
		r.selectNodeContents(oDOM.body);
		strFCKEditorText = r.toString();
	}
	
	// Now perform validation response
	if(strFCKEditorText == "") {
		blnValid = false;
		oDOM.body.style.cssText = "background-color:mistyrose;";
	}
	else {
		oDOM.body.style.cssText = "background-color:white;";
	}
	
	return blnValid;
}


// Validates an FCK Editor instance without setting the background of the control
function ValidateFCKeditor2(id) {
	var oEditor = FCKeditorAPI.GetInstance(id);
	var oDOM = oEditor.EditorDocument;
	var strFCKEditorText = "";
	var blnValid = true;
	
	// Retrieve the text
	if (document.all) { // If I.E.
		strFCKEditorText = oDOM.body.innerText;
	}
	else {
		var r = oDOM.createRange();
		r.selectNodeContents(oDOM.body);
		strFCKEditorText = r.toString();
	}
	
	// Now perform validation response
	if((strFCKEditorText == "") || (strFCKEditorText == " ")) { // Google Chrome seems to add additional space on FCK load
		blnValid = false;
	}
	
	return blnValid;
}


// Reset FCK Editor instance
function ResetFCKeditor(id) {
	FCKeditorAPI.GetInstance(id).SetData('');
}


// Reset FCK Editor instance background
function ResetFCKeditorBackground(id) {
	var oEditor = FCKeditorAPI.GetInstance(id);
	var oDOM = oEditor.EditorDocument;
	oDOM.body.style.cssText = "background-color:white;"; //Reset the background color
}


// Reset all the FCKEditors in a form
function ResetFCKeditors(frmName) {
	var ctrls = GetElement(frmName).elements;
	var config=/config/gi;
	// Loop through the controls and reset all the FCK Editors.
	// FCK Editor IDs must start with 'FCK' to help identify them
	for(var a = 0; a < ctrls.length; a++) {
		if((ctrls[a].type == "hidden") && (ctrls[a].id.substring(0, 3).toUpperCase() == "FCK") && (!ctrls[a].id.match(config))) {
			ResetFCKeditor(ctrls[a].id);
		}
	}
}


// Reset all the FCKEditor(s) background colours
function ResetFCKeditorBackgrounds(frmName) {
	var ctrls = GetElement(frmName).elements;
	var config=/config/gi;
	// Loop through the controls and reset all the FCK Editors.
	// FCK Editor IDs must start with 'FCK' to help identify them
	for(var a = 0; a < ctrls.length; a++) {
		if((ctrls[a].type == "hidden") && (ctrls[a].id.substring(0, 3).toUpperCase() == "FCK") && (!ctrls[a].id.match(config))) {
			var oEditor = FCKeditorAPI.GetInstance(ctrls[a].id);
			var oDOM = oEditor.EditorDocument;
			oDOM.body.style.cssText = "background-color:white;";
		}
	}
}


/****************************
** Page specific functions **
****************************/
// Displays/Hides Controls as appropriate
function ShowHideControls(frmName, value) {
	//	1:  Admission enquiry
	//	2:  Prospectus request
	// 	3:  Pre-Prep enquiry
	//	4:  Old Twyfordian enquiry
	//	5:  Old Twyfordian - Your Memories
	// 	6:  Old Twyfordian - Your News
	//	7:  General enquiry
	//	8:  Website feedback
	//	9:  Report problem with the Website
	//	10: Report/Record Card enquiry
	if(value > 0) {
		ResetFormColours(frmName);
		// Old Twyfordian Memories / News
		if((value == 5) || (value == 6)) {
			// Hide general enquiry controls. Show OT controls
			GetElement('trFullName').style.display="none";
			GetElement('trEnquiryLabel').style.display="none";
			GetElement('trEnquiry').style.display="none";
			GetElement('trFirstName').style.display="";
			GetElement('trLastName').style.display="";
			GetElement('spnTelNoNote').style.display="";
			GetElement('spnAddressNote').style.display="";
			GetElement('trYearsAttended').style.display="";
			GetElement('trNewsLabel').style.display="";
			GetElement('trNews').style.display="";
			GetElement('trMemoriesLabel').style.display="";
			GetElement('trMemories').style.display="";
			GetElement('trOTNote').style.display="";
			// Clear controls
			GetElement('FullName').value="";
			ResetFCKeditor('FCK_Enquiry');
			// Amend validation
			GetElement('required').value="FirstName,LastName,email,FCK_OTNews/FCK_OTMemories";
		}
		else {
			// Show general enquiry controls. Hide OT controls
			GetElement('trFullName').style.display="";
			GetElement('trEnquiryLabel').style.display="";
			GetElement('trEnquiry').style.display="";
			GetElement('trFirstName').style.display="none";
			GetElement('trLastName').style.display="none";
			GetElement('spnTelNoNote').style.display="none";
			GetElement('spnAddressNote').style.display="none";
			GetElement('trYearsAttended').style.display="none";
			GetElement('trNewsLabel').style.display="none";
			GetElement('trNews').style.display="none";
			GetElement('trMemoriesLabel').style.display="none";
			GetElement('trMemories').style.display="none";
			GetElement('trOTNote').style.display="none";
			// Clear controls
			GetElement('FirstName').value="";
			GetElement('LastName').value="";
			ResetFCKeditor('FCK_OTNews');
			ResetFCKeditor('FCK_OTMemories');
			// Amend validation
			GetElement('required').value="ddEnquiryType,FullName,email,FCK_Enquiry";
		}
	}
}
