/* 
* Include constants here, use the following prefixes
* AC: Application Constants
* FC: Framework Constants
*/
var FC_NEXT_STATE_NAME='nextState';
var FC_CURRENT_STATE_NAME='state';

/*
 * LW 29/03/2006 TPR: 276859
 * JB 04/01/2007 illegal exception thrown due to unicode apostrophe 
 * Returns URL encoded string for Email This Page
 */
function returnString(emailPageString)
{
	return escape(emailPageString).replace("%u2019","'");
}


/*
* Submits the form named formId.
*/
function submitForm(nextState, htmlFormName)
{
	window.document.forms[htmlFormName].elements[FC_NEXT_STATE_NAME].value=nextState;
	window.document.forms[htmlFormName].submit();	
}

/*
 * Changes the current state of the form prior to submitting it.
 * This supports multiple actions tied to a single form.
 */
function setCurrentState(currentState, htmlFormName)
{
	window.document.forms[htmlFormName].elements[FC_CURRENT_STATE_NAME].value=currentState;
}

/*
 * toggleLayer is used to show/hide div sections
 * whichLayer = id of layer to show/hide
 */
function toggleLayer(whichLayer)
{
    if (document.getElementById)
    {
        // for mozilla firefox and new versions of ie
        var style2 = document.getElementById(whichLayer).style;
        if (style2.display =="block")
            style2.display = "none";
        else
            style2.display = "block";
    }
    else if (document.all)
    {
        // for old ie versions
        var style2 = document.all[whichLayer].style;
        if (style2.display =="block")
            style2.display = "none";
        else
            style2.display = "block";
    }
    else if (document.layers)
    {
        // for nn4
        var style2 = document.layers[whichLayer].style;
        if (style2.display =="block")
            style2.display = "none";
        else
            style2.display = "block";
    }
}

function toggleLayerOn(whichLayer)
{
    if (document.getElementById) //for mozilla firefox and new versions of ie
	    var style2 = document.getElementById(whichLayer).style;
    else if (document.all) // for old ie version
        var style2 = document.all[whichLayer].style;
    else if (document.layers) // for nn4
        var style2 = document.layers[whichLayer].style;
	style2.display = "block";
}

function toggleLayerOff(whichLayer)
{
    if (document.getElementById) //for mozilla firefox and new versions of ie
	    var style2 = document.getElementById(whichLayer).style;
    else if (document.all) // for old ie version
        var style2 = document.all[whichLayer].style;
    else if (document.layers) // for nn4
        var style2 = document.layers[whichLayer].style;
    style2.display = "none";
}

/*
* Function used for rounding a number to "decs" places
* 13/02/2006 - Joseph Sullivan
*/
function roundNumber( num, decs ) 
{
	if( arguments.length < 2 )
		decs = 2;
	return Math.round( num * Math.pow( 10, decs ) ) / Math.pow( 10, decs );
}

/*
* Function is used to calculate the amount of tax paid on petrol purchases
* 13/02/2006 - Joseph Sullivan
*/
function calculateTax()
{
	var price2  = document.fuelTaxCalculator.pumpPrice.value / 100;
	var volume2 = document.fuelTaxCalculator.volume.value;
	//Check that fields only contain numbers	
	if (isNaN(price2) || price2 < 0)  
		toggleLayerOn('pumpPriceValidation');
	else 
		toggleLayerOff('pumpPriceValidation');
		
	if (isNaN(volume2) || volume2 < 0) 			
		toggleLayerOn('volumeValidation');
	else 
		toggleLayerOff('volumeValidation');
		
	var cost2 = price2 * volume2;
	var tax2 = (.381 * volume2  ) + (cost2 / 11);
	var taxSpanId = document.getElementById("tax");
	//If calculated tax not a number then set to 0
	if(isNaN(tax2))
		taxSpanId.innerHTML = '$0.00';
	else
		taxSpanId.innerHTML = '$' + roundNumber(tax2,2);
}


/*
*  Functions used by Merchandise Sales Order 
*  15/02/2006 - Erica Feldmann
*
*  merchSalesOrderChangeTotal - used to change the value of the total
*  at the end of each row in lobbyShop.
*/
function merchSalesOrderChangeTotal(itemId) {


	var dropdown = document.getElementById('dropdown' + itemId);
	var quantity = dropdown.options[dropdown.selectedIndex];

	var price = document.getElementById('price' + itemId);
	var total = quantity.value * price.value;

	var displayTotal = total;
	if (total != 0) displayTotal = '$' + displayTotal.toFixed(2);
	document.getElementById('total' + itemId).innerHTML = displayTotal;

	var oldQuantity = document.getElementById('oldQuantity' + itemId);
	if (oldQuantity.value != quantity.value) {

		total = total - oldQuantity.value * price.value

		var newQuantity = quantity.value;
		document.getElementById('oldQuantity' + itemId).value = quantity.value;
		merchSalesOrderAddToGrandTotal(total);
	}

}

/*
*  15/02/2006 - Erica Feldmann
*
*  merchSalesOrderAddToGrandTotal - used to change the value of the 
*  grand total for lobbyShop.
*/
function merchSalesOrderAddToGrandTotal(itemTotal) {

	var currTotal = document.getElementById('oldTotal');
	var newTotal = currTotal.value * 1 + itemTotal;

	var displayTotal = newTotal;
	if (newTotal != 0) displayTotal = '$' + displayTotal.toFixed(2);

	document.getElementById('grandTotal').innerHTML = displayTotal;
	document.getElementById('oldTotal').value = newTotal;

}



/*
*	Multi-Select object swap via add and remove buttons 
*
*	Joel Rivendell
*/ 

var arrOldValues;

//Removes selected options from the source multi-select object, called from addItems method below
function removeOptFromSource(source, strTemp) {
	var arrIndices;
	
	arrIndices = strTemp.split(",");
	for(var i=arrIndices.length-2;i>-1;i--){
		source.remove(arrIndices[i]); //Remove the indices from top to bottom
	}
}

//Adds selected options from the source multi-select object to the target multi-source object
function addItems(source, target) {
	var strTemp = "";
	
	tgtIndex = target.length;
	
	for (var i = 0; i < source.length; i++){
		if (source.options[i].selected) {
			//Create a new option and add to target
		    var elOptNew = document.createElement('option');
		    var elOptOld = source.options[i]; 
		    elOptNew.text = elOptOld.text;
		     
		    //Add to target
		    try {
		      target.add(elOptNew, null); // standards compliant; doesn't work in IE
		    }
		    catch(ex) {
		      target.add(elOptNew); // IE only
		    }
		    strTemp += i+",";
	    }
	}
	removeOptFromSource(source, strTemp);  
		
}

//Selects all options in multi-select component parameter
function SelectAllList(CONTROL){
	for(var i = 0;i < CONTROL.length;i++){
		CONTROL.options[i].selected = true;
	}
}

//Selects all option text in multi-select component parameter to a hidden parameter value as comma delimiter single string
function transferOptionTextToHidden(CONTROL, HIDDEN){
	var strTemp = "";
	//
	for(var i = 0;i < CONTROL.length;i++){
		if (i < CONTROL.length-1){
			strTemp += CONTROL.options[i].text + ",";
		}
		else {
			strTemp += CONTROL.options[i].text;
		}
	}

	HIDDEN.value = strTemp;
	//alert(HIDDEN.name+" - hidden value is now: "+HIDDEN.value);
}

//Selects all options in multi-select component parameter
function DeselectAllList(CONTROL){
	for(var i = 0;i < CONTROL.length;i++){
		CONTROL.options[i].selected = false;
	}
}


function FillListValues(CONTROL){
	var arrNewValues;
	var intNewPos;
	var strTemp = GetSelectValues(CONTROL);
	
	arrNewValues = strTemp.split(",");
	for(var i=0;i<arrNewValues.length-1;i++){
		if(arrNewValues[i]==1){
			intNewPos = i;
		}
	}

	for(var i=0;i<arrOldValues.length-1;i++){
		if(arrOldValues[i]==1 && i != intNewPos){
			CONTROL.options[i].selected= true;
		}
		else if(arrOldValues[i]==0 && i != intNewPos){
			CONTROL.options[i].selected= false;
		}
	
		if(arrOldValues[intNewPos]== 1){
			CONTROL.options[intNewPos].selected = false;
		}
		else{
			CONTROL.options[intNewPos].selected = true;
		}
	}
}

function GetSelectValues(CONTROL){
	var strTemp = "";
	
	for(var i = 0;i < CONTROL.length;i++){
		if(CONTROL.options[i].selected == true){
			strTemp += "1,";
		}
		else{
			strTemp += "0,";
		}
	}
	return strTemp;
}

function GetCurrentListValues(CONTROL){
	var strValues = "";
	strValues = GetSelectValues(CONTROL);
	arrOldValues = strValues.split(",")
}

/*
*  Functions used by Find Your Nearest 
*  17/02/2006 - Luke White
*
*/
function fynSetHiddenVariables(formName, providerType, subType, combo)
{
	var form = eval("document." + formName);
	if (combo != '')
		var selectedService = combo.options[combo.selectedIndex].value;
	else
		var selectedService = combo;

	form.selectedService.value = selectedService;
	form.providerType.value = providerType;
	form.subCategory.value = subType;
}


function fynCheckRadio(formName, radiogrp, chkValue)
{
	var rgrp = "document." + formName + "." + radiogrp;
	var length = eval("document." + formName + "." + radiogrp + ".length");
	for (i = 0; i < length; i++)
	{
		var value = eval("document." + formName + "." + radiogrp + "[" + i + "]" + ".value");
		if ( value == chkValue)
		{
			var radio = eval("document." + formName + "." + radiogrp + "[" + i + "]");
			radio.checked = true;
		}
	}
}

function fynClearRadios(formName)
{
	var elm;
	var form = eval("document." + formName);
	var elements = form.getElementsByTagName('input');
	
	for( i = 0, elm; elm = elements.item(i++); )
	{
		if (elm.getAttribute('type') == "radio")
		{
			elm.checked = false;
		}
	}
}


/*
*	Function used by Loan application to format a text
* 	input value as a currency.
*	Erica Feldmann
*/
function formatCurrency(formName, textInput, includeDollar, includeCents, includeCommas, totalInput) {

	var num = textInput.value.toString().replace(/\$|\,/g,'');
	if(isNaN(num)) {
		textInput.value=num;
		return;
	}
	
	if (num != "") {
		
		// Replace any commas, dollar signs or spaces that are there already
		var numNoCommas = num;
		while (numNoCommas.indexOf(",") != -1) numNoCommas = numNoCommas.replace(",","");
		while (numNoCommas.indexOf("$") != -1) numNoCommas = numNoCommas.replace("$","")
		while (numNoCommas.indexOf(" ") != -1) numNoCommas = numNoCommas.replace(" ","")
	
		sign = (num == (num = Math.abs(num)));
	
		num = numNoCommas;
	
		var cents = "";
		if (includeCents) {
			num = Math.floor(num*100+0.50000000001);
			cents = num%100;
			num = Math.floor(num/100).toString();
			if(cents<10)
			cents = "0" + cents;
			cents = "." + cents;
		}
		else cents = "";
	
		if (includeCommas) {
			for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
			num = num.substring(0,num.length-(4*i+3))+','+
			num.substring(num.length-(4*i+3));
		}
	
		var dollarSign = "";
		if (includeDollar) dollarSign = "$";
	
		// Set the value of the formatted text
		var formatted = (((sign)?'':'-') + dollarSign + num + cents);
		textInput.value=formatted;
		
	}

	// If adding to a total, add
	if (totalInput != null) {
		addToTotal(formName, textInput, totalInput, includeDollar, includeCents, includeCommas);
	}

}


/*
*	Function used by Loan application to calculate the income and store it in the given 
*	hidden input
*	Erica Feldmann
*/
function calculateIncome(textInput, frequencyInputId, hiddenInputId) {
	calculateIncome(textInput, frequencyInputId, hiddenInputId, null);
}

/*
*	Function used by Loan application to calculate the income and store it in the given 
*	hidden input, given a multiplication factor
*	Erica Feldmann
*/
function calculateIncome(textInput, frequencyInputId, hiddenInputId, factor) {

	// Get the value to add to the total
	num = textInput.value.toString().replace(/\$|\,/g,'');
	
	if (factor == null) {
		var frequencyInput = document.getElementById(frequencyInputId);
		var frequency = frequencyInput.options[frequencyInput.selectedIndex].value;
	
		if (frequency.toLowerCase().match("week") != null) num *= document.getElementById('weekFactor').value;
		else if (frequency.toLowerCase().match("fort") != null) num *= document.getElementById('fortnightFactor').value;
		else if (frequency.toLowerCase().match("month") != null) num *= document.getElementById('monthFactor').value;
	} else {
		num *= factor;
	}

	// Set the value in the given hidden input
	var hiddenInput = document.getElementById(hiddenInputId);
	hiddenInput.value=num;

}


/*
*	Function used by Loan application to add to a total, without a group name
*	Erica Feldmann
*/
function addToTotal(formName, textInput, totalInput, includeDollar, includeCents, includeCommas) {
	addToTotal(formName, textInput, totalInput, includeDollar, includeCents, includeCommas, null);
}

/*
*	Function used by Loan application to add to a total.
*	Erica Feldmann
*/
function addToTotal(formName, textInput, totalInput, includeDollar, includeCents, includeCommas, givenGroupName) {

		// Get the form
		var form = eval('document.' + formName);

		// Get the group name
		var groupName = givenGroupName;
		if (groupName == null) {
			var textInputName = textInput.name;
			var firstUnderscoreIndex = textInputName.indexOf("_");
			var secondUnderscoreIndex = textInputName.indexOf("_", firstUnderscoreIndex + 1);
			groupName = textInputName.substr(0, secondUnderscoreIndex);
		}

		var allInputs = form.elements;
		var groupInputs = new Array();
		var ind = 0;
		for (i=0; i<allInputs.length; i++) {
			var element = form.elements[i];
			var elementName = element.name;
			if (elementName.indexOf(groupName) != -1) {
				groupInputs[ind] = elementName;
				ind++;
			}
		}


		var numbers = new Array(groupInputs.length);

		var total = 0;

		for (i=0; i<groupInputs.length; i++) {

			var value = document.getElementById(groupInputs[i]).value;

			// Replace any commas, dollar signs or spaces that are in the input
			while (value.indexOf(",") != -1) value = value.replace(",","");
			while (value.indexOf("$") != -1) value = value.replace("$","")
			while (value.indexOf(" ") != -1) value = value.replace(" ","")

			// Add value to total
			if (value != "")
				total += value * 1;

		}

		// Set the total
		totalInput.value = total;

		// Now format the total, the same way as the numbe is formatted
		formatCurrency(formName, totalInput, includeDollar, includeCents, includeCommas, null);
}

/*
*	Function used by to disable/enable an input
*	Erica Feldmann
*/
function disableInput(otherInputName, disable) {

	var other = document.getElementById(otherInputName);
	other.disabled = disable;
}


/*
*	Function used by to disable/enable an input
*	Erica Feldmann
*/
/*
*	Function used by to disable/enable an input
*	Erica Feldmann
*/
function disableSubmit(formname) {

	// Find all the img's in this form
	var imgs = document.getElementsByTagName("input");

	// For each img, change the onclick and the onmouseover events.
	for (i=0; i<imgs.length; i++) {
		var img = imgs[i];
		if (img.type == 'image') {
			img.disabled = "true";
			img.onmouseover="function onmousover(event) { this.style.cursor=''; }";
		}
	}
}


/*
*	Function to set the focus to the next input field
*	Erica Feldmann
*/
function focusNextInput(input) {

		// Get the elements of this form, and the index of the selected element
		var elements;
		var index = 0;
		var forms = document.forms;
		for (i=0; i<forms.length; i++) {
			var elements = forms[i].elements;
			for (index=0; index<elements.length; index++) {
				if (elements[index] == input)
					break;
			}
		}

		// Increment index to get to next input
		index++;
		if (index == elements.length) return false;

		// Skip over any hidden/disabled inputs
		for (; index<elements.length; index++) {
			if ((elements[index].type != "hidden") && (elements[index].disabled != true))
				break;
		}

		if (index == elements.length) return false;

		// Set the focus to the next input
		elements[index].focus();
		return false;
}


/*
*	Function to pad member numbers with leading zeros to pass LDAP validation
*	Luke White
*/
function padMemberNumber(memNumField)
{
    var memNum = memNumField.value;
    var memLength = memNum.length;
    if (memLength < 7 && memLength > 0)
    {
        var padding = 7 - memLength;
        for (var i = 0; i < padding; i++)
            memNum = '0' + memNum;
        memNumField.value = memNum;
    }
}

/*
*	Function to find elements in page by class name
*	Luke White
*/
function getElementsByClassName(oElm, strTagName, strClassName){
    var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    strClassName = strClassName.replace(/\-/g, "\\-");
    var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
    var oElement;
    for(var i=0; i<arrElements.length; i++){
        oElement = arrElements[i];      
        if(oRegExp.test(oElement.className)){
            arrReturnElements.push(oElement);
        }   
    }
    return (arrReturnElements)
}
