//Global Variables
    var lastEmailAddressFound = null;


//can be called if you want to give the user the option to confirm the submitting
//of the form.
function confirmSubmit( frmReference, confirmationMessage ) {
    if (confirm(confirmationMessage)) {
        frmReference.submit();
        return true;
    } else {
        return false;
    }
}

//this function can be called if there is a struts error.
//called from primary_layout.jsp (/tiles/Template).
function showInvalidFieldsAlert() {
    alert("Either one or more mandatory fields are empty or the information provided is invalid." +
        "\nAddional information can be displayed by placing the mouse cursor over a highlighted field.");
}

var expandAllState = false;

// functionality for the "View Graph" button on invoice view.
function toggleGraph(graphDivID, thisObj) {
    switch(document.getElementById(graphDivID).style.display) {
        case "block": document.getElementById(graphDivID).style.display = "none";
        thisObj.lastChild.nodeValue = "View Graphs";
        break;
        case "none" : document.getElementById(graphDivID).style.display = "block";
        thisObj.lastChild.nodeValue = "Hide Graphs";
        break;
        default : document.getElementById(graphDivID).style.display = "block";
        thisObj.lastChild.nodeValue = "Hide Graphs";
        break;
    }
}

// functionality for the "Expand All" button on invoice view.
function expandAll() {
    var divCollection = document.getElementById("dataList").getElementsByTagName("DIV");

    if(expandAllState == false) {
        for(x=0; x<divCollection.length; x++) {
            divCollection[x].style.display = "block";
            graphButton = divCollection[x].getElementsByTagName("button");
            if(graphButton.length > 0) {
                graphButton[0].lastChild.nodeValue = "Hide Graphs";
            }

            expandAllState = true;
            document.getElementById("expandAllButton").lastChild.nodeValue="Close All";
        }
    } else {
        for(x=0; x<divCollection.length; x++) {
            divCollection[x].style.display = "none";
            graphButton = divCollection[x].getElementsByTagName("button");
            if(graphButton.length > 0) {
                graphButton[0].lastChild.nodeValue = "Show Graphs";
            }

            expandAllState = false;
            document.getElementById("expandAllButton").lastChild.nodeValue="Expand All";
        }
    }
}

//Populate all text fields, select boxes, check boxes and radio buttons on all forms for the document.
function pop(){
    for(i=0; i<document.forms.length; i++) {
        for(j=0; j<document.forms[i].length; j++) {
            //alert("Element " + j + " is of type: " + document.forms[i][j].type);
            var element = document.forms[i][j];
            processElement(element);
        }
    }
}

//Populate all text fields, select boxes, check boxes and radio buttons on all forms for the document.
function pop2(){
    for(i=0; i<document.forms.length; i++) {
        for(j=0; j<document.forms[i].length; j++) {
            //alert("Element " + j + " is of type: " + document.forms[i][j].type);
            var element = document.forms[i][j];
            processElement2(element);
        }
    }
}


//performs a case-insensitive string comparison
function stringContains(str,stringToFind){
    var found = false;
    if(str!=null && str.length>0){
        if(str.toUpperCase().indexOf(stringToFind.toUpperCase())>=0){
            found = true;
        }
    }

    return found;
}

//populate field based on its id name and type.
function processElement(element){
    if(element.type!="hidden" && (element.type == "text" || element.type == "textarea" || element.type == "password")) {
        if(stringContains(element.id,"DATE")){
            element.value = "31/12/2007";
        }else if(stringContains(element.id,"PHONE")){
            element.value = "(08) 9123 4567";
        }else if(stringContains(element.id,"FAX")){
            element.value = "(08) 9123 4567";
        }else if(stringContains(element.id,"EMAIL")){
            element.value = "test@westernpower.com.au";
        }else if(stringContains(element.id,"PAY")){
            element.value = "12345";
        }else if(stringContains(element.id,"ABN")){
            element.value = "1234";
        }else if(stringContains(element.id,"MOBILE")){
            element.value = "040 812 4567";
        }else if(stringContains(element.id,"SUBURB")){
            element.value = "Subiaco";
        }else if(stringContains(element.id,"POSTCODE")){
            element.value = "1234";
        }else if(stringContains(element.id,"NUMBER") ||
            stringContains(element.id,"QUANTITY") ||
            stringContains(element.id,"QTY") ||
            stringContains(element.id,"NO") ||
            stringContains(element.id,"TOT") ||
            stringContains(element.id,"HOURS") ||
            stringContains(element.id,"WEEKLY") ||
            stringContains(element.id,"ANNUAL") ||
            stringContains(element.id,"AMP") ||
            stringContains(element.id,"KVA") ||
            stringContains(element.id,"KW") ||
            stringContains(element.id,"FREQ")
        ) {
                //element.value = "1";
                var popNumericRef = getId("popNumericValue");
                var newNumericValue = parseInt(popNumericRef.value) + 1;
                element.value = popNumericRef.value;
                alert("popNumericValue: " + popNumericRef.value);
                popNumericRef.value = newNumericValue;

        }else if(stringContains(element.id,"INTERNATIONAL")){
            element.value = "12 Hill St. Indonesia";
        }else if(stringContains(element.id,"RETAILER")){
            element.value = "Western Power";
        }else{
            element.value = "test";
        }
    }else if(element.type == "select-one" || element.type == "select-multiple") {
        if(element.options.length > 1){  //&& !((element.id).toUpperCase().indexOf("SUBSTATION")>=0)  )
            element.options[1].selected = true;
        }
    }else if(element.type == "radio"){
        element.checked = true;
    }else if(element.type == "checkbox"){
        element.checked = true;
    }
}

//check if a specific element is hidden
function checkIfHidden(element){
    return element.style.display=="none" || element.style.visibility=="hidden";
}

//determine if a field is visible on the page.
//Assumes that fields are buried no more than 3 levels deep.
function isHidden(element){
    var firstParent = element.parentNode;
    var secondParent = firstParent.parentNode;
    var thirdParent = secondParent.parentNode;
    var hidden = false;
    if(checkIfHidden(element) || checkIfHidden(firstParent) || checkIfHidden(secondParent) || checkIfHidden(thirdParent)){
            hidden = true;
    }
    //alert(element.id + " hidden:" + hidden);
    return hidden;
}

//test whether value is numeric
function isNumeric2(elementValue){
    //alert("testing: " + elementValue);
    var retVal = true;
    elementValue = trim(elementValue);

    if(isNaN(elementValue) || elementValue==""){
        retVal = false;
    }
    return retVal;
}

//returns next incrementing number for autopopulating function pop2();
//starts at 1000 if value hasn't been set.
function getNextPopNumericValue(){
    var popNumericRef = getId("popNumericValue");
    var newNumericValue = "";
    if(isNumeric2(popNumericRef.value)){
        newNumericValue = parseInt(popNumericRef.value) + 1;
    }else{
        newNumericValue = 1000;
    }
    popNumericRef.value = newNumericValue;
    return newNumericValue;
}

function getNextPopDateValue(){

}

//populate field based on its id name and type for debugging purposes - each field must be populated with a unique value.
//whether this function works depends on the validation rules of the application.
//eg. numbers will be inserted into firstName field etc.
//application specific rules can be added.
//eg. name="one","two", etc.
//NB: this function wont work if a form is saved and then continued!
function processElement2(element){
    var firstParentElement = element.parent;
    var lastRadioButtonGroupName = "";
    var currentRadioButtonGroupName = "";

    if(element.type == "select-one" || element.type == "select-multiple") {         //drop downs
        if(element.options.length > 1){  //&& !((element.id).toUpperCase().indexOf("SUBSTATION")>=0)  )
            element.options[1].selected = true;
        }
    }else if(element.type == "radio"){                                              //radio
        //@todo - only populate radio button if not selected.
/*
        currentRadioButtonGroupName = element.name;
        if(currentRadioButtonGroupName!=lastRadioButtonGroupName){
            for(k=0; k<document.forms[i][j].)
        }
        lastRadioButtonGroupName = currentRadioButtonGroupName;
*/
        element.checked = true;
    }else if(element.type == "checkbox"){                                           //checkbox
            element.checked = true;
    }else if(!isHidden(element) && element.type!="hidden" && (element.type == "text" || element.type == "textarea" || element.type == "password")) { //text
        if(stringContains(element.id,"DATE")){
            element.value = "31/12/2012";
        }else if(stringContains(element.id,"EMAIL")){
            //populate pairs of email addresses with the same value.
            if(lastEmailAddressFound==null){
                element.value = "" + getNextPopNumericValue() + "@westernpower.com.au";
                lastEmailAddressFound = element.value;
            }else{
                element.value = lastEmailAddressFound;
                lastEmailAddressFound = null;
            }
        }else if(stringContains(element.id,"MOBILE")){
            element.value = "000000" + getNextPopNumericValue();
        }else if(stringContains(element.id,"startsFrequency")){     //motor page - startsFrequency
            element.value = "999";
        }else {
            if(element.value==""){                                  //set value only if blank
                element.value = getNextPopNumericValue();           //normal incrementing number
            }
        }
    }
    //alert("value:" + element.value);
}

//Validate Dispatch Commitment Submission Form
function validateDispatchCommitmentSubmissionForm(form){
    return true;
}

//Validate dispatch Instruction Acknowledgement Form
function validateDispatchInstructionAcknowledgementForm(form){
    return true;
}

//validate DispatchFuelChangeForm
function validateDispatchFuelChangeForm(form){
    return true;
}
//validate Dispatch Load Forecast Form (Wind Farms)
function validateDispatchLoadForecastForm(form){
    return true;
}

//maxLength - restrict the number of characters entered into a textarea input.
//param fieldRef -  field reference of textarea.
//param maximumLength - maximum number of characters allowed in textarea.
//usage - onkeyup="maxLength(this,250)"
function maxLength(fieldRef,maximumLength){
    if(fieldRef!=null){
        if(fieldRef.value.length>maximumLength){
            alert("This field can only contain a maximum of " + maximumLength + " characters.");
            fieldRef.value = fieldRef.value.substring(0,maximumLength);
        }
    }
}

//trim leading and trailing whitespace
//be sure to pass in a string, not a reference
function trim(str) {
    return str.replace(/^\s*/, '').replace(/\s*$/, '');
}

//set and unset error status of form fields.
//field - the field to set or remove the error status.
//msg - the error message to set. If msg is null, error status of field is removed.
function setError(field, msg){
    if(msg!=""){
        field.style.backgroundColor="#FF6600";
    }else{
        field.style.backgroundColor="#FFFFFF";
    }
    field.title=msg;
    field.alt=msg;
}

//hide the wizard status message box if javascript is enabled, and display the message as an alert.
function handleStatusMessage(statusMessage){
    //only hide if statusMessageDiv exists
    if(document.getElementById("statusMessageDiv")!=null){
        hide("statusMessageDiv");
    }
    alert(statusMessage);
}

// setStyleByClass: given an element type and a class selector,
// style property and value, apply the style.
// args:
//  t - type of tag to check for (e.g., SPAN)
//  c - class name
//  p - CSS property
//  v - value
var ie = (document.all) ? true : false;
function setStyleByClass(t,c,p,v){
    var elements;
    if(t == '*') {
        // '*' not supported by IE/Win 5.5 and below
        elements = (ie) ? document.all : document.getElementsByTagName('*');
    } else {
        elements = document.getElementsByTagName(t);
    }
    for(var i = 0; i < elements.length; i++){
        var node = elements.item(i);
        for(var j = 0; j < node.attributes.length; j++) {
            if(node.attributes.item(j).nodeName == 'class') {
                if(node.attributes.item(j).nodeValue == c) {
                    eval('node.style.' + p + " = '" +v + "'");
                }
            }
        }
    }
}

//helper to retrieve value from selected item in a drop down.
function getSelectedValue(dropDownElement){
    return dropDownElement.options[dropDownElement.selectedIndex].value;
}


//helper to set an elements style 'display' to 'block', so it appears on the page;
function show(elementId){
    //alert("about to show: " + elementId);
    getId(elementId).style.display = "block";
}

//helper to set an elements style 'display' to 'none', so it doesn't appear on the screen;
// @TODO - modify this function so that if 'true' is passed in, all fields contained inside the div are reset.
//       hide(elementId, true)
function hide(elementId){
    //alert("about to hide: " + elementId);
    getId(elementId).style.display = "none";
}

//helper to set an elements style 'display' to 'block', so it appears on the page;
function showIfExists(elementId){
    if(document.getElementById(elementId)!=undefined){
        getId(elementId).style.display = "block";
    }
}

//helper to set an elements style 'display' to 'none', so it doesn't appear on the screen;
//also, if field being hidden is a div, and it contains a field with the same name minus the "Div", it will be reset.
function hideIfExists(elementId){
    //alert("hideIfExists called for " + elementId);
    if(document.getElementById(elementId)!=undefined){ //don't use getId() here, as it checks to see whether id exists.
        var elementRef = getId(elementId);
        elementRef.style.display = "none";

        //if elementId is a div reference, then attempt to reset the value of the field it contains.
        //assumes that each div contains a single field with the same name minus the "Div" at the end.
        //eg. gpoDiv contains the gpo field.
        var divValue = elementId.substring(elementId.length-3, elementId.length);
        if(divValue == "Div"){
            var fieldId = elementId.substring(0, elementId.length-3);
            element = document.getElementById(fieldId);
            if(element!=undefined){
                resetField(fieldId);
            }
        }
    }
    //alert("<-- hideIfExists");
}

function resetIfExists(elementId){
    var element = document.getElementById(elementId);
    if(element!=undefined){
        resetField(elementId);
    }
}

//return true if item is checked.
//assumes element is a checkbox, or radio button.
function isChecked(elementId){
    return getId(elementId).checked;
}

// uncheck a checkbox or radio button
function uncheck(checkboxElement){
    getId(checkboxElement).checked=false;
}

//set drop down to the first item in the list.
function resetDropDown(dropDownElement){
    getId(dropDownElement).selectedIndex = 0;
}


function resetAustralianAddress(partyType){
    var stateCode =         partyType + ".stateCode";
    var unitNumber =        partyType + ".unitNumber";
    var lotNumber =         partyType + ".lotNumber";
    var houseNumber =       partyType + ".houseNumber";
    var streetName =        partyType + ".streetName";
    var streetSuffixName =  partyType + ".streetSuffixName";
    var suburbPostcode =    partyType + ".suburbPostcode";
    var suburbName =        partyType + ".suburbName";
    var postCode =          partyType + ".postCode";
    var nearestCorner =     partyType + ".nearestCorner";

    resetIfExists(stateCode);
    resetIfExists(unitNumber);
    resetIfExists(lotNumber);
    resetIfExists(houseNumber);
    resetIfExists(streetName);
    resetIfExists(streetSuffixName);
    resetIfExists(suburbPostcode);
    resetIfExists(suburbName);
    resetIfExists(postCode);
    resetIfExists(nearestCorner);

}

//-------------------------------------------------------------
//function specific to the addressFields.jsp page
function toggleAddressType(dropDown, partyType){
    //alert("toggleAddressType called");
    var selectedCountry = getSelectedValue(dropDown);
    if(selectedCountry=="AU" || selectedCountry==""){
        showIfExists(partyType + ".australianAddressDiv");
        hideIfExists(partyType + ".internationalAddressDiv");
        hideIfExists(partyType + ".gpoAddressDiv");
        hideIfExists(partyType + ".gpoSuburbPostcodeDiv");
    }else if(selectedCountry=="GPO"){
        showIfExists(partyType + ".gpoAddressDiv");
        showIfExists(partyType + ".gpoSuburbPostcodeDiv");
        hideIfExists(partyType + ".australianAddressDiv");      resetAustralianAddress(partyType);
        hideIfExists(partyType + ".internationalAddressDiv");
    }else if(selectedCountry=="OS"){
        showIfExists(partyType + ".internationalAddressDiv");
        hideIfExists(partyType + ".australianAddressDiv");      resetAustralianAddress(partyType);
        hideIfExists(partyType + ".gpoAddressDiv");
        hideIfExists(partyType + ".gpoSuburbPostcodeDiv");
    }
}



function toggleSameAddress(sameAddressCheckBox, partyType){
//alert("-->toggleSameAddress");
    if(sameAddressCheckBox.checked){
        hide(partyType + ".addressDiv");

        //@todo: write function to dynamically reset a list of fields stored in a String array, depending on element type.
        var gpoAddress = document.getElementById(partyType + ".gpoAddress"); if(gpoAddress!=null) gpoAddress.value="";
        var internationalAddress = document.getElementById(partyType + ".internationalAddress"); if(internationalAddress!=null) internationalAddress.value="";
        var lotNumber = document.getElementById(partyType + ".lotNumber"); if(lotNumber!=null) lotNumber.value="";
        var houseNumber = document.getElementById(partyType + ".houseNumber"); if(houseNumber!=null) houseNumber.value="";
        var postCode = document.getElementById(partyType + ".postCode"); if(postCode!=null) postCode.value="";
        var streetName = document.getElementById(partyType + ".streetName"); if(streetName!=null) streetName.value="";
        var streetSuffixName = document.getElementById(partyType + ".streetSuffixName"); if(streetSuffixName!=null) streetSuffixName.value="";
        var suburbName = document.getElementById(partyType + ".suburbName"); if(suburbName!=null) suburbName.value="";
        var unitNumber = document.getElementById(partyType + ".unitNumber"); if(unitNumber!=null) unitNumber.value="";

        var addressType = document.getElementById(partyType + ".addressType"); if(addressType!=null) resetDropDown(partyType + ".addressType");
        var stateCode = document.getElementById(partyType + ".stateCode"); if(stateCode!=null) resetDropDown(partyType + ".stateCode");

    }else{
        show(partyType + ".addressDiv");
    }
}

function toggleSameAddressRO(sameAddress, partyType){
//alert("-->toggleSameAddressRO");
    //alert("Same address? " + sameAddress);
    if(sameAddress == "Y"){
        hide(partyType + ".addressDiv");
    }else{
        show(partyType + ".addressDiv");
    }
}

//show or hide the address fields depending on the addressType
function toggleAddressFields(partyType){
//alert("-->toggleAddressFields")
    var addressTypeTmp = document.getElementById(partyType + ".addressType");
    if(addressTypeTmp!=null){
        toggleAddressType(addressTypeTmp, partyType);
    }
}

// -------------------------------------------------------------
//called everytime page loads.
var currentYear = new Number(new Date().getFullYear());
var tmpDate = new Date();
var currentDate = tmpDate.getDate() + "/" + (tmpDate.getMonth()+1) + "/" + tmpDate.getFullYear();
var userSelect = 0;
//alert("not detecting browser");
detectBrowser(); //must detect browser. Allows correct display in both IE and NS. //doesn't work when running locally tomcat.

// -------------------------------------------------------------
// HELP BUTTON POPUPS
// function for toggling the help snippets when rollover the ? icons.

function toggleHelp(thisObj)
{
    var isIE = navigator.userAgent.indexOf("MSIE") != -1;
    var iFrames = thisObj.getElementsByTagName("iframe");
    var oIframe = iFrames[0];
    var oDoc = (isIE) ? oIframe.contentWindow : oIframe.contentDocument;
    if (oDoc.document)
    {
        oDoc = oDoc.document;
    }
    if(isIE){oIframe.style.display = (oIframe.style.display == "block") ? "none":"block";}
    //oIframe.style.height = (oDoc.body.clientHeight) + "px";
    return true;
}

//helper for calendar
//get date n months from now
//used with currentDate
function getMonthsAhead(monthAhead){
    var tmpDate = new Date();
    var day = "01";
    var month = tmpDate.getMonth()+monthAhead+1; //month is 0 indexed
    var year = tmpDate.getFullYear();
    if(month>12){
    month = month - 12;
    year++;
    }
    if(month<10){
      month = "0" + month;
    }
    var currentDate = day + "/" + month + "/" + year;
    //alert("currentDate: " + currentDate);
    return currentDate;
}

//fieldName - name of field to set read only
//isReadOnly - set read only if true, editable if false
function setReadOnly(fieldName, isReadOnly){
    getId(fieldName).readOnly = isReadOnly;
}

//show div if radioButton/checkbox is checked - else hide the div
//elementName - radiobutton or checkbox
//divName - name of div to show/hide
function showDivIfChecked(elementName, divName){
    var isCheckedValue = isChecked(elementName);
    if(isCheckedValue){
        show(divName);
    }else{
        hide(divName);
    }
    return isCheckedValue;
}

//store scroll position of page in specified field
function storeScrollPosition(fieldName){
    var pos = getId(fieldName);
    if(isIE || isFirefox){
        pos.value = document.documentElement.scrollTop; //IE 6 only - with strict html
    }else if(isNetscape){
        pos.value = document.body.scrollTop; //mozilla
    }
}

//restore scroll position
function restoreScrollPosition(fieldName){
    var pos = getId(fieldName);
    if(isIE || isFirefox){
        document.documentElement.scrollTop = pos.value; //IE 6, FireFox - with strict html
    }else if(isNetscape){
        document.body.scrollTop = pos.value; //mozilla Netscape
    }
}

//cancel enter key presses to prevent accidental form submissions, or
//to prevent incorrect function being performed if form has more than one button.
function cancelEnterKeyPresses(e){
    var retVal = false;
    var code;
    if (!e) {
        var e = window.event;
    }

    if (e.keyCode) {     //IE
        code = e.keyCode;
    }else if (e.which) { //Mozilla
        code = e.which;
    }

    if(code==13){
        alert("Enter key pressed");
        retVal = true;
    }
    return retVal;
}

//set style of specified element
function setStyle(elementId, classToSet){
    getId(elementId).className=classToSet;
}

function resetFieldByReference(element){
    if(element!=undefined){
        //alert("resetFieldByReference: " + element.id);
        if(element.type=="text" || element.type=="textarea" || element.type=="password") {
            element.value = "";
        }else if(element.type=="radio" || element.type=="checkbox"){
            element.checked=false;
        }else if(element.type == "select-one") {
            if(element.options.length > 0) {
                for(k=0; k<element.options.length; k++) {
                    if(element.options[k].selected) {
                        element.options[k].selected = false;
                    }
                }
                //highlight the first element for drop down select list boxes only.
                element.options[0].selected = true;
            }
        }else if(element.type == "select-multiple") {
            if(element.options.length > 0) {
                for(k=element.options.length-1; k>=0; k--) {
                    //delete all elements in multi-select list boxes
                    element.options[k] = null
                }
            }
        }
    }
}

//bug fixed - reset() is a reserved function name
function resetField(fieldName){
    var element = getId(fieldName);
    resetFieldByReference(element);
}

function toggleBillingPeriods(obj) {
    var childULCollection = obj.getElementsByTagName("UL");
    switch(childULCollection[0].style.display) {
        case "block":
            childULCollection[0].style.display = "none";
            break;

        case "none":
            childULCollection[0].style.display = "block";
            break;
        default:
            childULCollection[0].style.display = "block";
            break;
    }
}

function toggleServices(serviceObj) {
    switch(document.getElementById(serviceObj).style.display) {
        case "block":
            document.getElementById(serviceObj).style.display = "none";
            break;
        case "none":
            document.getElementById(serviceObj).style.display = "block";
            break;
        default:
            document.getElementById(serviceObj).style.display = "block";
            break;
    }
}

