
var okAction = null;
var cancelAction = null;

function playOkAction() {
	// gets called by the popup to once the ok/apply button is pressed.
	// it executes the js code stored as a string in the okAction variable.
	//alert("playing playokaction()");
	enableLinks();
	eval(okAction);
	okAction = null;
}

function playCancelAction() {
	// gets called by the popup to once the cancel button is pressed.
	// it executes the js code stored as a string in the cancelAction variable.
	//alert("playing cancelAction");
	enableLinks();
	eval(cancelAction);
	cancelAction = null;
}

function showErrorAlert(/*String*/errorType, /*String*/errorMsg, /*String*/myOkAction, /*String*/myCancelAction) {
	// displays an alert if of errorType == error or a confirmation box if errorType == note.
	// determine error string to use..
	var myMsg = "BASIX Alert: ";
	switch (errorMsg) {
		case 'general':
			myMsg += "There are errors on the page (see the notes in the bottom left corner of the page).\nSelect OK to continue and address these errors later;\nor Cancel to address these errors now.";
			break;
		case '':
			myMsg += "There are errors on the page (see the notes in the bottom left corner of the page).\nSelect OK to continue and address these errors later;\nor Cancel to address these errors now.";
			//myMsg = "There are errors on the page.  Please check the notes in the bottom left corner of the page.";
			break;
		case 'onCalculate':
			myMsg += "There are errors on the page (see the notes in the bottom left corner of the page).\nThese errors need to be fixed before the project can be calculated.";
			break;
		case 'crossVentCheck':
			myMsg += "Please note that Cross ventilation is not permissible in this project's postcode.  See help for more information.";
			break;
		case 'createCertificate':
			myMsg += "Are you sure you wish to generate a certificate for this project?\nPlease note that the Certificate will open in a new window.";
			break;
		case 'createReport':
			myMsg += "Are you sure you wish to generate a report for this project?\nPlease note that the Report will open in a new window.";
			break;
		case 'removeDwellings':
			myMsg += "Are you sure you wish to remove the selected dwellings?";
			break;
		case 'mandatoryCheck':
			myMsg += "Please complete all mandatory fields.";
			break;
		case 'deleteProject':
			myMsg += "Are you sure you wish to delete this project? Once a project has been deleted it can not be restored.";
			break;
		case 'copyProject':
			myMsg += "Are you sure you want to make a copy of this project?";
			break;
		case 'notCopyProject':
			myMsg += "This project cannot be copied as it is incompatible with the latest version of BASIX.";
			break;
		case 'dtcFull':
			myMsg += "This option is not currently available. Please select simulation or the DTC (rapid) option.";
			break;
		case 'pressCalculate':
			myMsg += "The project must be calculated before this page can be displayed.";
			break;
		case 'maxDwellings':
			myMsg += "BASIX Alert: The default limit on the number of dwellings you can enter on the BASIX multi-unit tool is set at 50 separate houses, 50 attached houses and 100 units.\nIf you would like to enter a larger project, please contact the Help Desk on 1300 650 908, and access will be arranged for you."
			break;
		default:
			myMsg = errorMsg;
	}
	
	if (okAction == null) {
		// setup actions
		okAction = myOkAction;
		cancelAction = myCancelAction;
		
		// check if document has been opened (ie. an opener exists) if so then it is a popup of some description with the modal effect on which will need to be disabled.
		if (currentlyInPopUp()) {
			unsetModal();
			// setup modal effect when returning to popup
			okAction += "setModal();";
			cancelAction += "setModal();";
		}
		// alert or confirm error string..
		if (errorType == "error") {
			alert(myMsg);
			eval(myOkAction);
			return false;
		} else {
			if (errorType == "note" || errorType == "okCancel") {
				//showErrorAlert('confirm', myMsg, 'return true;', 'return false;');
				if (myCancelAction == "") {
					myCancelAction = "return false;";
				}
				if (confirm(myMsg)) {
					playOkAction();
					return true;
				} else {
					playCancelAction();
					return false;
				}
			} else {
				alert("please specify valid error type");
				return false;
			}
		}
	}
}

function mandatoryCheck() {
	
	//return true; //For debugging/development
	
// Scans through all form fields on the page looking for enabled fields that have the classname of "mandatory".
// It then checks each of these mandatory fields that they have a value depending of the type of the field object.
	var myForm = document.basix_form;
	var errorFound = false;
	var tempFound = false;
	var i=0, j=0;
	for (i=0; i < myForm.elements.length; i++) {
		if (myForm.elements[i].disabled == false && myForm.elements[i].className.indexOf("mandatory") != -1) {
			// field is marked as a mandatory field.
			switch (myForm.elements[i].type) {
				// depending on type of field..
				case 'text':
					if (myForm.elements[i].className.indexOf("textflt") != -1) {
						// field content is of type float.. check to see if value of 0 or more exists.
						if (myForm.elements[i].value == "" || !(parseFloat(myForm.elements[i].value) >= 0)) {
							errorFound = true;
						}
					} else {
						//alert("checking " + myForm.elements[i].id + ".");
						if (myForm.elements[i].value == "") {
							errorFound = true;
						}
					}
					break;
				case 'select':
				case 'select-one':
					if (myForm.elements[i].options.selectedIndex == 0) {
						errorFound = true;
					}
					break;
				case 'radio':
			/*		tmpFound = false;
					var btn = myForm.elements[i];
					for (var k in btn) {
						if (btn[k].checked == "1") {
							tmpFound = true;
						}
					}
				/*	alert(myForm.elements[i].checked);
   					if (!myForm.elements[i].checked == "1") {
						errorFound = true;
						alert("error");
					}*/
/*					if (!tmpFound) errorFound = true;*/
					break;
				default:
			
			}
		}
	}
	if (errorFound) {
		if (parent) {
			// must be on main window..
			parent.frames[1].addNote("Please ensure all mandatory fields are filled in.", "normal");
		} else {
			// must be in a popup..
			addNote("Please ensure all mandatory fields are filled in.", "normal");
		}
		//return showErrorAlert("error");
		return false;
	} else {
		return true;
	}
}

function checkZeroFirst(myStr) {
	// need to check for strings of length greater than 2 instead of 1, since when a field contains a zero and the user tabs to it, the field data
	// is highlighted.  When the user presses to over-write the highlighted value, it is returned to this function as not being a string of length=1,
	// but being a string of length 2.  The remove_char() function needs to cater for this.
	if (myStr.length > 2 && myStr.indexOf("0") == 0) {
		return true;
	} else {
		return false;
	}
}

function checkDecimalPlaces(myStr) {
	// need to restrict to 2 decimal places at most..
	if (myStr.search(/^[0-9]*(\.[0-9]{0,2})?$/) != -1) { // removes any occurence of all characters except digits and the decimal point
		return true;
	} else {
		return false;
	}
}

//Ensure only numeric values entered. Doesn't allow values beginnning with zero other than zero itself.
function validate_numeric_sf(e, myObj) {
	var key;
	if (window.event || !e.which) {
		key = e.keyCode;
	} else if (e) {
		key = e.which;
	}
	var keyChar = String.fromCharCode(key);
	if ((key >=35 && key <=40) || key==8 || key==9) { // allow functional keys eg. arrows, home, end, del, decimal point... etc.
		return true;
	}
	if ((key > 47 && key < 58) || key == 46) {  // allow numeric keys
		if (!checkZeroFirst(myObj.value + keyChar) && checkDecimalPlaces(myObj.value + keyChar)) {
			return true;
		} else {
			return false;
		}
	}
	if (key == 99 || key == 118 || key == 67 || key == 86) { // allow c and v in for copy and paste functionality - any c and v characters can be removed by the remove_char function added to the onkeyup event and the onblur event.
		//return checkDecimalPlaces(myObj.value + keyChar);
		if (!checkZeroFirst(myObj.value + keyChar) && checkDecimalPlaces(myObj.value + keyChar)) {
			return true;
		} else {
			return false;
		}
	} else {
		// deny all other keys
		return false;
	}
}


// to remove all but numerical values and the decimal point, in case user attempts to paste in other characters 
function remove_char(myField) { 
	var myFieldStr = myField.value.substr(-1,(myField.value.length));
	myField.value = myField.value.replace(/[^0-9.]+/,""); // removes any occurence of all characters except digits and the decimal point
}

//Ensure only numeric values entered. Doesn't allow values beginnning with zero other than zero itself.
function validate_integer_sf(e, myObj) {
	var key;
	if (window.event || !e.which) {
		key = e.keyCode;
	} else if (e) {
		key = e.which;
	}
	var keyChar = String.fromCharCode(key);
	if ((key >=35 && key <=40) || key==8 || key==9)  // allow functional keys eg. arrows, home, end, del... etc.
		return true;
	if (key > 47 && key < 58) // allow numeric keys
		return (!checkZeroFirst(myObj.value + keyChar));
	if (key == 99 || key == 118 || key == 67 || key == 86) { // allow c and v in for copy and paste functionality - any c and v characters can be removed by the remove_char function added to the onkeyup event and the onblur event.
		return (!checkZeroFirst(myObj.value + keyChar));	
	} else {
		// deny all other keys
		return false;
	}
}

//Ensure only numeric values entered, includes values begining with zero
function validate_numbers_sf(e, myObj) {
	var key;
	if (window.event || !e.which) {
		key = e.keyCode;
	} else if (e) {
		key = e.which;
	}
	var keyChar = String.fromCharCode(key);
	if ((key >=35 && key <=40) || key==8 || key==9)  // allow functional keys eg. arrows, home, end, del... etc.
		return true;
	if (key > 47 && key < 58) // allow numeric keys
		return true;
	if (key == 99 || key == 118 || key == 67 || key == 86) { // allow c and v in for copy and paste functionality - any c and v characters can be removed by the remove_char function added to the onkeyup event and the onblur event.
		return true;
	} else {
		// deny all other keys
		return false;
	}
}

function validate_phoneNumbers_sf(e, myObj) {
	if (validate_numbers_sf(e, myObj)) {
		return true;
	} else {
		// check if character is an additional space character, "(", "), or "+"...
		var key;
		if (window.event || !e.which) {
			key = e.keyCode;
		} else if (e) {
			key = e.which;
		}
		var keyChar = String.fromCharCode(key);
		if (key == 32 || key == 40 || key == 41 || key == 43) {
			return true;
		} else {
			return false;
		}
	}
}

// to remove all but numerical values, in case user attempts to paste in other characters 
function integerField_remove_char(myField) { 
	var myFieldStr = myField.value.substr(-1,(myField.value.length));
	myField.value = myField.value.replace(/[^0-9]+/,""); // removes any occurence of all characters except digits
}

// to remove all but phone number values, in case user attempts to paste in other characters 
function phoneNumber_remove_char(myField) { 
	var myFieldStr = myField.value.substr(-1,(myField.value.length));
	myField.value = myField.value.replace(/[^(0-9)^( )^\(^\)^\+]+/,""); // removes any occurence of all characters except digits, +, (, ) or a space.
}

function checkLength(e, myFieldObj, myLength) {
	// Acts as maxLength attribute. Used with an onkeypress event.
	// Written for textarea fields which do not cater for maxLength.
	var key;
	if (window.event || !e.which) {
		key = e.keyCode;
	} else if (e) {
		key = e.which;
	}
	if ((key >=35 && key <=40) || key == 8 || key == 9 || key == 46)  // allow functional keys eg. arrows, home, end, delete... etc.
		return true;
	if (myFieldObj.value.length > myLength)
		// if greater than maximum length, deny key to be written out.
		return false;
	else
		// allow key.
		return true;
}

function minLength(myFieldObj, myLength) {
	if (myFieldObj.value.length < myLength) {
		return true; // return true for length of value is less than myLength
	} else {
		return false;
	}
}

function displayMandatory(myFieldId, isMandatory) {
// make or remove a field as being mandatory.
// change the classname of the field object and add "mandatory" class to className if isMandatory == true else remove "mandatory" from the className.
// hide or show the mandatory div tag with the * indicating whether it is mandatory or not.
	var myFieldObj = document.getElementById(myFieldId);
	if (isMandatory) {
		// add mandatory..
		if (myFieldObj.className.indexOf("mandatory") == -1) {  // if not already mandatory.
			if (myFieldObj.className == "") {
				myFieldObj.className = "mandatory";
			} else {
				myFieldObj.className += " mandatory";
			}
			// show * div..
			show(myFieldId + "_star");
		}
	} else {
		// remove mandatory..
		if (myFieldObj.className.indexOf("mandatory") != -1) {  // only if currently mandatory.
			myFieldObj.className = myFieldObj.className.replace(/[ ]*mandatory/g, ''); // remove " mandatory" from the class name
			// hide * div..
			hide(myFieldId + "_star");
		}
	}
}

function makeMandatory(mySelectBox, myMandatoryFieldId, myValueArray) {
// will make the form element, myMandatoryFieldId, mandatory if the current selected value of the dropdown is in the myValueArray..
// if current selected value not in array, then make the myMandatoryFieldId not mandatory.
// if myValueArray element begins with a "!" character then treat as for all values but not that one.
	for (var i=0; i < myValueArray.length; i++) {
		if (myValueArray[i].substr(0,1) == "!") {
			if (myValueArray[i].substr(1) == mySelectBox.options[mySelectBox.options.selectedIndex].value) {
				displayMandatory(myMandatoryFieldId, false);
			} else {
				displayMandatory(myMandatoryFieldId, true);
				break;
			}
		} else {
			if (myValueArray[i] == mySelectBox.options[mySelectBox.options.selectedIndex].value) {
				// if exists in value array then make mandatory..
				displayMandatory(myMandatoryFieldId, true);
				break;
			} else {
				// if does not exist in value array then remove mandatory if exists..
				displayMandatory(myMandatoryFieldId, false);
			}
		}
	}
}

function either(currentFieldName, otherFieldName) {
	// reset the otherFieldName form field if the currentFieldName has content.
	var currentFieldObj = document.basix_form.elements[currentFieldName];
	var otherFieldObj = document.basix_form.elements[otherFieldName];
	switch (currentFieldObj.type) {  // depending on type of field object..
		case 'select-one':
		case 'select':
			if (currentFieldObj.options.selectedIndex != 0) {
				otherFieldObj.options.selectedIndex = 0;  //reset to default first option in select list.
			}
			break;
		case 'text':
			if (currentFieldObj.value != "") {
				otherFieldObj.value = "0";  //reset to default value of zero (0)
			}
			break;
	}

}

var myPageLinks = new Array();

function disableLinks() {
// loops through all links on the current document and sets all the href attributes to a void javascript call.
// It also keeps record of each link's href attribute value in the global array myPageLinks, to be used when reestablishing the links with function enableLinks().
	for (var i=0; i < document.links.length; i++) {
		myPageLinks[i] = document.links[i].href;
		document.links[i].href = "javascript: void(0);";
	}
}

function enableLinks() {
// if links are currently stored in the global array variable myPageLinks, then
// loop through all links in the current document and reassign the links as per the myPageLinks variable array values.
	if (myPageLinks.length > 0) {
		for (var i=0; i < document.links.length; i++) {
		// for each link in the document associate the first link array value from myPageLinks with the current link's href.
		// Then pop off the first element of the myPageLinks array.
			document.links[i].href = myPageLinks[0];
			myPageLinks.shift();
		}
	}
}