window.history.forward(1);

var debugmode=true;

function changeCursor(elementID)
{
    var element = document.getElementById(elementID);
    element.style.cursor='pointer';
}

// Handle an AJAX Error.
A4J.AJAX.onError = function(req,status,message)
{
    // Events to take place when an AJAX Error occurs.
    window.location = "./errorPage.xhtml"
};

// Handle session expiration
A4J.AJAX.onExpired = function(loc,expiredMsg)
{
    // Events to take place when a session expires.
    window.location = "./errorPage.xhtml"
};

var lockOutCount = 0;

// Check to see if we can send ajax request, or if there is one already in progress.
function canSendAjax()
{
    if (lockOutCount > 0)
    {
        if (debugmode) {
            window.status="[please wait]";
            document.title ="[please wait]";
        }
        return false;
    }
    else
    {
        lockOutCount ++;
        setCursorStyle('wait');
        if (debugmode) {
            window.status="[working]";
            document.title ="[working]";
        }
        return true;
    }
}

// Finish with the Ajax lock.
function releaseAjax()
{
    setCursorStyle('default');
    if (debugmode) {
        window.status="[ready]";
        document.title ="[ready]";
    }
    lockOutCount = 0;
}

// Set the cursor style at the start and end of AJAX requests.
function setCursorStyle(newStyle)
{
    var bodyElement = document.getElementById('pageBody');
    bodyElement.style.cursor=newStyle;
}


// There is an a4j function defined in the platoLayout.xhtml file which submits an
// ajax polling request to the server. This code starts that off every 2 minutes.
function doPolling()
{
    setTimeout('doPolling()', 120000);
    sendPollRequest();
}

//setTimeout('doPolling()', 120000);

// Opens a RichFaces modal popup window.
function openModalPopup(elementID)
{
    Richfaces.showModalPanel(elementID);
}

// Closes a RichFaces modal popup window.
function closeModalPopup(elementID)
{
    Richfaces.hideModalPanel(elementID);
}

function enableButton(elementID)
{
    enableDisableField(elementID, false, false);
}

function checkExpectedCompletionDate()
{
    var currentDate = document.getElementById('assumeExpectedCompletionDateInputDate').value;
    if(currentDate.value == ' ')
        alert("Validation error: expected completion date value required");
    else
        alert("Current date = " + currentDate);
}

// function called when the simple hip creation page is entered to determine which fields should be
// enabled and which disabled.
function enterSimpleHipCreationPage()
{
    var searchFieldValue = document.getElementById('mainForm:simpleSearchVendorName').value;
    if ((searchFieldValue != null) && (searchFieldValue != ''))
    {
        // Something in the search field - disable all the others.
        enableDisableAndClearField('mainForm:simpleVendorName', true, true);
        enableDisableAndClearField('mainForm:simpleVendorStreet', true, true);
        enableDisableAndClearField('mainForm:simpleVendorTown', true, true);
        enableDisableAndClearField('mainForm:simpleVendorCity', true, true);
        enableDisableAndClearField('mainForm:simpleVendorCounty', true, true);
        enableDisableAndClearField('mainForm:simpleVendorPostcode', true, true);
        enableDisableAndClearField('mainForm:simpleVendorPhone', true, true);
        enableDisableAndClearField('mainForm:simpleVendorMobile', true, true);
        enableDisableAndClearField('mainForm:simpleVendorFax', true, true);
        enableDisableAndClearField('mainForm:simpleVendorEmail', true, true);
        enableDisableAndClearField('mainForm:simpleVendorToken', true, true);
        enableDisableAndClearField('mainForm:simpleVendorPassword', true, true);
        enableDisableAndClearField('mainForm:simpleVendorComments', true, true);

        enableDisableAndCheckField('mainForm:logonInfo:0', true, false);
        enableDisableAndCheckField('mainForm:logonInfo:1', true, false);
        enableDisableAndCheckField('mainForm:logonInfo:2', true, false);
    }
    else
    {
        if ((!isEmpty('mainForm:simpleVendorName')) ||
            (!isEmpty('mainForm:simpleVendorStreet')) ||
            (!isEmpty('mainForm:simpleVendorTown')) ||
            (!isEmpty('mainForm:simpleVendorCity')) ||
            (!isEmpty('mainForm:simpleVendorCounty')) ||
            (!isEmpty('mainForm:simpleVendorPostcode')) ||
            (!isEmpty('mainForm:simpleVendorPhone')) ||
            (!isEmpty('mainForm:simpleVendorMobile')) ||
            (!isEmpty('mainForm:simpleVendorFax')) ||
            (!isEmpty('mainForm:simpleVendorEmail')) ||
            (!isEmpty('mainForm:simpleVendorToken')) ||
            (!isEmpty('mainForm:simpleVendorPassword')) ||
            (!isEmpty('mainForm:simpleVendorComments')) ||
            (isChecked('mainForm:logonInfo:0')) ||
            (isChecked('mainForm:logonInfo:1')) ||
            (isChecked('mainForm:logonInfo:2')))
            {
            enableDisableAndClearField('mainForm:simpleSearchVendorName', true, true);
        }
    }
}

// Is The field empty or not.
function isEmpty(fieldID)
{
    var searchFieldValue = document.getElementById(fieldID).value;
    if ((searchFieldValue == null) || (searchFieldValue == ''))
    {
        return true;
    }
    else
    {
        return false;
    }
}

// Is The field empty or not.
function isChecked(fieldID)
{
    return document.getElementById(fieldID).checked;
}

// enables or Disables the entry fields on the create hip simple page based on the var param.
function setSimpleEntryFields(disabledState)
{
    document.getElementById('mainForm:simpleVendorName').disabled = disabledState;
    document.getElementById('mainForm:simpleVendorStreet').disabled = disabledState;
    document.getElementById('mainForm:simpleVendorTown').disabled = disabledState;
    document.getElementById('mainForm:simpleVendorCity').disabled = disabledState;
    document.getElementById('mainForm:simpleVendorCounty').disabled = disabledState;
    document.getElementById('mainForm:simpleVendorPostcode').disabled = disabledState;
    document.getElementById('mainForm:simpleVendorPhone').disabled = disabledState;
    document.getElementById('mainForm:simpleVendorMobile').disabled = disabledState;
    document.getElementById('mainForm:simpleVendorFax').disabled = disabledState;
    document.getElementById('mainForm:simpleVendorEmail').disabled = disabledState;
    document.getElementById('mainForm:simpleVendorToken').disabled = disabledState;
    document.getElementById('mainForm:simpleVendorPassword').disabled = disabledState;
    document.getElementById('mainForm:logonInfo:0').disabled = disabledState;
    document.getElementById('mainForm:logonInfo:1').disabled = disabledState;
    document.getElementById('mainForm:logonInfo:2').disabled = disabledState;
    document.getElementById('mainForm:simpleVendorComments').disabled = disabledState;
}

// Disables the entry fields on the create hip simple page.
function disableEnableSimpleEntryFields()
{
    var searchFieldValue = document.getElementById('mainForm:simpleSearchVendorName').value;
    if ((searchFieldValue == null) || (searchFieldValue == ''))
    {
        setSimpleEntryFields(false);
    }
    else
    {
        setSimpleEntryFields(true);
    }
}

// Disables the search fields on the create hip simple page.
function disableSimpleSearchField()
{
    enableDisableField('mainForm:simpleSearchVendorName', true);
}

// Enable or disable a field by id.
function enableDisableAndClearField(fieldID, disabledState, clearField)
{
    document.getElementById(fieldID).disabled = disabledState;
    if (clearField)
    {
        document.getElementById(fieldID).value = '';
    }
    if(!disabledState)
    {
        document.getElementById(fieldID).style.backgroundColor="#FFFFFF"; // white
    }
    else
    {
        document.getElementById(fieldID).style.backgroundColor="#D4D0C8"; // lightgrey
    }
}

function enableDisableField(fieldID, disabledState)
{
    document.getElementById(fieldID).disabled = disabledState;
    if(!disabledState)
    {
        document.getElementById(fieldID).style.backgroundColor="#FFFFFF";
    }
    else
    {
        document.getElementById(fieldID).style.backgroundColor="#D4D0C8";
    }
}

// Enable or disable a field by id and set its checked state.
function enableDisableAndCheckField(fieldID, disabledState, checkState)
{
    enableDisableField(fieldID, disabledState);
    document.getElementById(fieldID).checked = checkState;
}

// Called to set the enabled state of fields on the property hip creation page.
function configurePropertyHipCreationPage()
{

    // If property hold type is not "Leasehold" then disable leasehold fields.
    var propertyHoldType = document.getElementById('mainForm:propertyHoldingType').value;
    try
    {
        if (propertyHoldType == 2)
        {
            // It is a leasehold.
            enableDisableField('mainForm:propertyLeaseTerm', false);
            enableDisableField('mainForm:propertyLeaseDate', false);
            document.getElementById("mainForm:propertyLeaseTermText").className = "smallText";
            document.getElementById("mainForm:propertyLeaseTerm").className = "fullWidth";
            document.getElementById("mainForm:propertyLeaseDateText").className = "smallText";
            document.getElementById("mainForm:propertyLeaseDate").className = "fullWidth";
            document.getElementById("mainForm:propertyLeaseDateButton").className = "smallText";
        }
        else
        {
            enableDisableAndClearField('mainForm:propertyLeaseTerm', true, true);
            enableDisableAndClearField('mainForm:propertyLeaseDate', true, true);
            document.getElementById("mainForm:propertyLeaseTermText").className = "hidden";
            document.getElementById("mainForm:propertyLeaseTerm").className = "hidden";
            document.getElementById("mainForm:propertyLeaseDateText").className = "hidden";
            document.getElementById("mainForm:propertyLeaseDate").className = "hidden";
            document.getElementById("mainForm:propertyLeaseDateButton").className = "hidden";
        }
    }
    catch (e)
    {
    // Do nothing - these fields may not be shown on this page. If not, just ignore.
    }

    // If property possession is Occupied then enable details field.
    var propertyPossessionType = document.getElementById('mainForm:propertyPossessionType').value;

    if (propertyPossessionType == 'false')
    {
        // It is Occupied.
        //enableDisableField('mainForm:propertyOccupationDetails', false);
        document.getElementById("mainForm:propertyOccupationDetailsText").className = "smallText";
        document.getElementById("mainForm:propertyOccupationDetails").className = "percent99Width";
    }
    else
    {
        //enableDisableAndClearField('mainForm:propertyOccupationDetails', true, true);
        document.getElementById("mainForm:propertyOccupationDetailsText").className = "hidden";
        document.getElementById("mainForm:propertyOccupationDetails").className = "hidden";
    }
}

function configureOrderHipPage2()
{


    // If property seller status is Other then enable details field.
    var propertySellerStatus= document.getElementById('mainForm:propertySellerStatus').value;
    if (propertySellerStatus == 4)
    {
        // It is Other.
        enableDisableField('mainForm:propertySellerStatusDetails', false);
        document.getElementById("mainForm:propertySellerStatusDetailsText").className = "smallText";
        document.getElementById("mainForm:propertySellerStatusDetails").className = "fullWidth";
    }
    else
    {
        enableDisableAndClearField('mainForm:propertySellerStatusDetails', true, true);
        document.getElementById("mainForm:propertySellerStatusDetailsText").className = "hidden";
        document.getElementById("mainForm:propertySellerStatusDetails").className = "hidden";
    }

}

function configureSaleStatementPage()
{

    // If property possession is Occupied then enable details field.
    var propertyPossessionType = document.getElementById('mainForm:propertyPossessionType').value;

    if (propertyPossessionType == 'false')
    {
        // It is Occupied.
        //enableDisableField('mainForm:propertyOccupationDetails', false);
        document.getElementById("mainForm:propertyOccupationDetailsText").className = "smallText";
        document.getElementById("mainForm:propertyOccupationDetails").className = "percent99Width";
    }
    else
    {
        //enableDisableAndClearField('mainForm:propertyOccupationDetails', true, true);
        document.getElementById("mainForm:propertyOccupationDetailsText").className = "hidden";
        document.getElementById("mainForm:propertyOccupationDetails").className = "hidden";
    }

    // If property seller status is Other then enable details field.
    var propertySellerStatus= document.getElementById('mainForm:propertySellerStatus').value;
    if (propertySellerStatus == 4)
    {
        // It is Other.
        enableDisableField('mainForm:propertySellerStatusDetails', false);
        document.getElementById("mainForm:propertySellerStatusDetailsText").className = "smallText";
        document.getElementById("mainForm:propertySellerStatusDetails").className = "fullWidth";
    }
    else
    {
        enableDisableAndClearField('mainForm:propertySellerStatusDetails', true, true);
        document.getElementById("mainForm:propertySellerStatusDetailsText").className = "hidden";
        document.getElementById("mainForm:propertySellerStatusDetails").className = "hidden";
    }


    // If property hold type is not "Leasehold" then disable leasehold fields.
    var propertyHoldType = document.getElementById('mainForm:propertyHoldingType').value;
    try
    {
        if (propertyHoldType == 2)
        {
            // It is a leasehold.
            enableDisableField('mainForm:propertyLeaseTerm', false);
            enableDisableField('mainForm:propertyLeaseDate', false);
            document.getElementById("mainForm:propertyLeaseTermText").className = "smallText";
            document.getElementById("mainForm:propertyLeaseTerm").className = "fullWidth";
            document.getElementById("mainForm:propertyLeaseDateText").className = "smallText";
            document.getElementById("mainForm:propertyLeaseDate").className = "fullWidth";
            document.getElementById("mainForm:propertyLeaseDateButton").className = "smallText";
        }
        else
        {
            enableDisableAndClearField('mainForm:propertyLeaseTerm', true, true);
            enableDisableAndClearField('mainForm:propertyLeaseDate', true, true);
            document.getElementById("mainForm:propertyLeaseTermText").className = "hidden";
            document.getElementById("mainForm:propertyLeaseTerm").className = "hidden";
            document.getElementById("mainForm:propertyLeaseDateText").className = "hidden";
            document.getElementById("mainForm:propertyLeaseDate").className = "hidden";
            document.getElementById("mainForm:propertyLeaseDateButton").className = "hidden";
        }
    }
    catch (e)
    {
    // Do nothing - these fields may not be shown on this page. If not, just ignore.
    }




}

function clearAddressDetails()
{
    document.getElementById('mainForm:postcodeFinder').value = '';
    document.getElementById('mainForm:propertyName').value = '';
    document.getElementById('mainForm:propertyStreet').value = '';
    document.getElementById('mainForm:propertyTown').value = '';
    document.getElementById('mainForm:propertyCity').value = '';
    document.getElementById('mainForm:propertyCounty').value = '';
    document.getElementById('mainForm:propertyPostcode').value = '';
}

function iconDim(element)
{
    setCursorStyle('default');
}

function iconBright(element)
{
    setCursorStyle('pointer');
}

function printpage()
{
    window.print();
}

/*
Please note the following:-
    * The letters Q, V and X are not used in the first position.
    * The letters I, J and Z are not used in the second position.
    * The only letters to appear in the third position are A, B, C, D, E, F, G, H, J, K, S, T, U and W.
    * The only letters to appear in the fourth position are A, B, E, H, M, N, P, R, V, W, X and Y.
    * The second half of the Postcode is always consistent numeric, alpha, alpha format and the letters C, I, K, M, O and V are never used.

These conventions may change in the future if operationally required.

*GIR 0AA is a Postcode that was issued historically and does not conform to current rules on valid Postcode formats, It is however, still in use.
*/
function checkPostCode(toCheck)
{
    // Permitted letters depend upon their position in the postcode.
    var alpha1 = "[abcdefghijklmnoprstuwyz]";                       // Character 1
    var alpha2 = "[abcdefghklmnopqrstuvwxy]";                       // Character 2
    var alpha3 = "[abcdefghjkstuw]";                                // Character 3
    var alpha4 = "[abehmnprvwxy]";                                  // Character 4
    var alpha5 = "[abdefghjlnpqrstuwxyz]";                          // Character 5

    // Array holds the regular expressions for the valid postcodes
    var pcexp = new Array ();

    // Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA
    pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1,2})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));

    // Expression for postcodes: ANA NAA
    pcexp.push (new RegExp ("^(" + alpha1 + "{1}[0-9]{1}" + alpha3 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));

    // Expression for postcodes: AANA  NAA
    pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1}" + alpha4 +"{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));

    // Exception for the special postcode GIR 0AA
    pcexp.push (/^(GIR)(\s*)(0AA)$/i);

    // Standard BFPO numbers
    pcexp.push (/^(bfpo)(\s*)([0-9]{1,4})$/i);

    // c/o BFPO numbers
    pcexp.push (/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);

    // Overseas Territories
    pcexp.push (/^([A-Z]{4})(\s*)(1ZZ)$/i);

    // Load up the string to check
    var postCode = toCheck;

    // Assume we're not going to find a valid postcode
    var valid = false;

    // Check the string against the types of post codes; test & exec are built-in methods of the Javascript RegExp Object Reference.
    for ( var i=0; i<pcexp.length; i++) {
        if (pcexp[i].test(postCode)) {

            // The post code is valid - split the post code into component parts
            pcexp[i].exec(postCode);

            // Copy it back into the original string, converting it to uppercase and inserting a space between the inward and outward codes
            postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();

            // If it is a BFPO c/o type postcode, tidy up the "c/o" part
            postCode = postCode.replace (/C\/O\s*/,"c/o ");

            // Load new postcode back into the form element
            valid = true;

            // code is valid so break from loop
            break;
        }
    }

    // Return with either the reformatted valid postcode or the original invalid postcode.
    if (valid) {
        return postCode;
    } else return false;
}

function validatePropertyPostcode()
{
    var postcode = "";
    var postcodeAuto = false;

    if(document.getElementById('mainForm:postcodeFinder').value != "")
    {
        postcode = document.getElementById('mainForm:postcodeFinder').value;
        postcodeAuto = true;
    }
    else
    {
        postcode = document.getElementById('mainForm:propertyPostcode').value;
    }

    if(postcode.length == 0)
    {
        alert('Please supply a postcode.');
        return false;
    }
    // checkPostCode(postcode) returns either a properly formatted valid postcode, or false if invalid.
    var postcodeResult = checkPostCode(postcode);

    if(postcodeResult == false)
    {
        alert('Postcode entered is invalid. Please try again.');
        return false;
    }
    else
    {
        if(postcodeAuto)
        {
            document.getElementById('mainForm:postcodeFinder').value = postcodeResult;
        }
        else
        {
            document.getElementById('mainForm:propertyPostcode').value = postcodeResult;
        }
        return true;
    }
}

function validatePostcode(elementID)
{
    var postcode = "";

    if(document.getElementById(elementID).value != "")
    {
        postcode = document.getElementById(elementID).value;
    }

    if(postcode.length == 0)
    {
        alert('Please supply a postcode.');
        return false;
    }

    // checkPostCode(postcode) returns either a properly formatted valid postcode, or false if invalid.
    var postcodeResult = checkPostCode(postcode);

    if(postcodeResult == false)
    {
        alert('Postcode entered is invalid. Please try again.');
        return false;
    }
    else
    {
        document.getElementById(elementID).value = postcodeResult;
        return true;
    }
}

function validateBranchPostcode(componentId)
{
    var postcode = "";

    postcode = document.getElementById(componentId).value;
    // for the editBranchPopup, check for empty postcode field
    if(postcode.length == 0 && componentId == 'editBranchPopupForm:branchPopupPostcode')
    {
        alert('Please supply a postcode.');
        return false;
    }
    else if(postcode.length != 0)
    {
        // checkPostCode(postcode) returns either a properly formatted valid postcode, or false if invalid.
        var postcodeResult = checkPostCode(postcode);

        if(postcodeResult == false)
        {
            alert('Postcode entered is invalid. Please try again.');
            return false;
        }
        else
        {
            document.getElementById(componentId).value = postcodeResult;
            return true;
        }
    }
    else return true;
}

// called from findSupplierPopup
function checkSupplierSelected(element)
{
    if(document.getElementById(element).value == '')
    {
        alert('No supplier selected.\nPlease use the Search or Find Nearest buttons.');
        return false;
    }
    else return true;
}

function checkLeaseDateEntered(parentNode)
{
    var date = parentNode + ':leaseStartDate';
    var dateHidden = parentNode + ':leaseStartDateHidden';

    if(document.getElementById(dateHidden).value == 'true' && document.getElementById(date).value == '')
    {
        alert('Please enter a lease start date (dd/mm/yyyy).');
        return false;
    }
    else return true;
}

// this function validates the user input on the newHipProviderConfirm page; specifically the inputText fields for provider commission exc. vat,  provider commission inc. vat & the grand total.
function validateUserInput()
{
    var hasReadTAndC = document.getElementById('mainForm:readTAndC').checked;

    if (hasReadTAndC == true)
    {
        return true;
    }
    else
    {
        alert("Please confirm that you have read and agree to the Terms and Conditions.");
        return false;
    }
}

// called from findNewSupplierPopup, prevents IE & FF from closing popup window when Enter key is pressed in an inputText component
function noenter(evt)
{
    var evt = (evt) ? evt : ((window.event) ? event : null);

    return !(evt && evt.keyCode == 13);
}

function stopRKey(evt) {
    var evt = (evt) ? evt : ((event) ? event : null);
    var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
    if ((evt.keyCode == 13) && ((node.type=="text") || (node.type=="password"))) {
        return false;
    }
}



function helpTextChanged()
{
    document.getElementById('viewComponentPopupForm:helpTextChanged').value = true;
}


function copyurl(id){
    var hipcurl = document.getElementById(id).value;
    window.clipboardData.setData('Text', hipcurl);
}


