/*
 * Set up some universal variables
 */

// Variable(s) to hold screen size

var screenHeight = screen.availHeight - 50;
var screenWidth = screen.availWidth - 5;

// Variable added to string in element id to determine if it should be
// included in the validation routine

var VALIDATE_ITEM = "VALIDATE";


/*
 * Function getProcessWindow() creates a window of a fixed size to display the target page
 * Used primarily as the window for processing information by the user
 *
 * RAC 15/06/2001 - added "left=0,top=0" to ensure that the new process window is completely
 *          displayed to users, and not half-off the screen
 */
function getProcessWindow(url,name,x,y)
{
        processWindow = open(url,name,"resizable=yes,scrollbars=yes,status=yes,width=" + screenWidth + ",height=" + screenHeight + ",left=" + (!x ? "0" : x) + ",top=" + (!y ? "0" : y));
        processWindow.focus();
}

/*
 * Function getLookupWindow() creates a window of a fixed size to display the target page
 * Used primarily to display a lookup view for the user
 */
function getLookupWindow(url,name)
{
    // Default lookup sizes

    var lookupWidth = 550;
    var lookupHeight = 250;

    // Get half window size

    var halfWidth = lookupWidth/2;
    var halfHeight = lookupHeight/2;

    // Get half screen size

    var h2 = screenHeight/2;
    var w2 = screenWidth/2;

    // Get starting corner position for window

    var winX = w2 - halfWidth;
    var winY = h2 - halfHeight;


    lookupWindow = open(url,name,"resizable=yes,scrollbars=yes,status=yes,width=" + lookupWidth + ",height=" + lookupHeight + ",left=" + winX + ",top=" + winY);
    lookupWindow.focus();
}


/*
 * Function getNewWindow() will be a more generic version of the getLookupWindow() and getProcessWindow()
 * in order to reduce confusion over which function to use.
 *
 * At the most basic level, the url and name parameters must be entered.
 * If the width and height parameters are not entered, then the new window will resort to full screen.
 * If the params parameter is not entered, then the default window will be resizeable, have scrollbars, and have a status bar.
 */
function getNewWindow(url,name,width,height,pw,ph,params)
{
    var w = ( !width || width == 0 ? ( !pw ? screenWidth : screenWidth/pw) : width );
    var h = ( !height || height == 0 ? ( !ph ? screenHeight : screenHeight/ph) : height );

    var winX = 0;
    var winY = 0;

    // This is used for positioning the window in the centre of the screen

    if (w < screenWidth && h < screenHeight)
    {
        // Get half the window size based on either the input values or
        // the default lookup parameters

        var halfWidth = w/2;
        var halfHeight = h/2;

        // Get half the screen size

        var h2 = screenHeight/2;
        var w2 = screenWidth/2;

        // Get starting corner position for the window

        winX = Math.round(w2 - halfWidth);
        winY = Math.round(h2 - halfHeight);
    }

    var p = (!params ? "resizable=yes,scrollbars=yes,status=yes" : params);

    newWindow = open(url,name,(p + ",width=" + w + ",height=" + h + ",left=" + winX + ",top=" + winY));
    newWindow.focus();
}

function NewWindow(mypage, myname, w, h, scrollbars, statusbar, menubar) {
    var screenHeight = screen.availHeight; // - 50;
    var screenWidth = screen.availWidth; // - 5;

    var winl = (screen.width - w) / 2;
    var wint = (screen.height - h) / 2;
    winprops = "height=" + h
             + ",width=" + w
             + ",top=" + wint
             + ",left=" + winl
             + ",scrollbars=" + scrollbars
             + ",statusbar=" + statusbar
             + ",menubar=" + menubar;
    win = window.open(mypage,myname,winprops);
    if (parseInt(navigator.appVersion) >= 4) {
        win.window.focus();
    }
}
function openBasicWindow(url) {
    window.open(url, "", "resizable=yes,scrollable=yes,status=yes");
}


/*
 * Function getHelpWindow() creates a window that is one third the width of the screen
 * but full height on the left-hand-side of the screen
 */
function getHelpWindow(url)
{
    var thirdWidth = Math.round(w/3);
    var fullHeight = h;

    helpWindow = open(url,"HELPWIN","resizable=yes,scrollbars=yes,status=yes,width=" + thirdWidth + ",height=" + fullHeight + ",left=0,top=0");
    helpWindow.focus();
}


/*
 * Function goItem() is used to to guide the caret to the specified item - this only
 * appears to work for IE
 */
function goItem(item)
{
    item.focus();
    item.select();
}


/*
 * !! FOR USE WITH POPUPS !!
 * Function confirm() is called from a button to ask the user if they are sure they wish to continue.
 * This has primarily been set up for where a single element is on a page, ie. the UserError logging
 * page.  If there is nothing in this element, then the function uses the buttons name and id string
 * to build the message.
 *
 * To close the window, redirect the user to the /lookupjsp/CloseIt.jsp page.
 */
function confirmOK(e,btn)
{
    var ok;

    if (e.value.length > 0)
    {
        ok = confirm("Are you sure ?");
    }
    else
    {
        alert("Unable to " + btn.value.toLowerCase() + " because " + btn.id + ".");
        ok = false;
    }

    return ok;
}


/*
 * Function lpad() is used to left-pad the specified string with the specified character
 * to the specified length
 */
function lpad(val,chr,spaces)
{
    if (val.length < spaces)
    {
        PAD_LOOP:
        for (i = 0 ; i < spaces ; i++ )
        {
            val = chr + val;

            if (val.length >= spaces)
            {
                break PAD_LOOP;
            }
        }
    }

    return val;
}

/*
 * Function dateChecker() checks the input element for validity, based on the UK format entered
 * and throws an alert in certain conditions, returning the user to the failed item using
 * the goItem() function above.  Usually called with 'this'.
 *
 * RAC 27/11/2001 : Added check after Date.parse to cater for 01/01/1970 dates.  Since this is the
 *                  base date that all dates are calculated from, there appears to be a problem, therefore,
 *                  we check to see if the user entered this date as the ONLY workaround to the parse failing.
 */
function dateChecker(e)
{
    // Set basic variables
    var val = e.value;
    var ok = false;
        var currDate;
        var minAge;

        var foreword = "!!WARNING!!\n\nThe date entered cannot be processed for the following reasons:\n";
        var message = "";

    // If the item's value is not null or is of correct length, then parse,
    // otherwise, if there is no entry, set ok top true to prevent errors.
    // If both conditions fail, ok is set to false by default
    if (val != null && val.length > 0)
    {
        // Pick out the date, month, and year items from the item string
        div1 = val.indexOf("/",0);
        div2 = val.indexOf("/",div1+1);

        date = lpad(val.substring(0,div1),"0",2);
        month = lpad(val.substring(div1+1,div2),"0",2);
        year = val.substring(div2+1,val.length);
        fullYear = lpad(year, (year >= 50 ? "19" : "20"), 4);

        e.value = date + "/" + month + "/" + fullYear;

        // Re-arrange the date information for American format in order
        // for parsing to work correctly
        dfltFormat = month + "/" + date + "/" + fullYear;

        if (Date.parse(dfltFormat) || dfltFormat == "01/01/1970")
        {
            // If parsing is successful create a new Date object
            var newDate = Date.parse(dfltFormat);
            currDate = new Date(newDate == null ? 0 : newDate);

            // Get the date, month, and year items for comparison below
            tempDate = currDate.getDate();
            tempMonth = (currDate.getMonth() + 1);
            tempYear = currDate.getFullYear();

            // If newly parsed date matches the details of entered date,
            // set ok to true
            if (tempDate == date && tempMonth == month && tempYear == fullYear)
            {
                ok = true;
            }
        }
    }
    else if (val == null || val.length == 0)
    {
        ok = true;
    }


    // Check that ok is not false.  If it is, throw an alert to the user
    if (!ok)
    {
        goItem(e);
        message += "\n- A valid date format must be used (DD/MM/YYYY).";
    }


    // Create a new Date object based on present system date and ensure date
    // entered is not later, otherwise, throw an alert at the user
        today = new Date();

        if (currDate >= today)
        {
            goItem(e);
            message += "\n- Date is after today.";
            ok = false;
        }


        // Check to see if the current item is a DOB element and if so, check that
        // the candidate is not younger than 16.  If so, throw an alert to the user
    minAge = new Date((today.getFullYear() - 16), today.getMonth(), today.getDate());

    if (e.name == "DOB" && currDate > minAge)
    {
        goItem(e);
        message += "\n- Candidate is under 16 years of age. Ensure date is correct.";
    }

    if (message != null && message.length > 0)
    {
        alert(foreword + message);
    }

        // Return the ok variable
    return ok;
}


/*
 * Function numberChecker() is used to ensure that the value entered into a numerical
 * field is a valid number.
 */
function numberChecker(e)
{
    var ok = true;

    if (isNaN(new Number(e.value)))
    {
        ok = false;
    }

    return ok;
}


/*
 * Function confirmChoice() is called by relevant buttons to ask the user if they are
 * sure they want to continue with the action.
 */
function confirmChoice(element)
{
    choice = confirm("Are you sure you want to " + element.value.toLowerCase() + " ? ");
    return choice;
}

/*
 * Function exitRegistration() is used to remove the current registration from the transaction.
 */
/*function exitRegistration()
{
    okExit = confirm("Exiting now will ignore this candidate's registration.\n\nContinue ?");

    if ( okExit )
    {
        location.replace("/CRCS/servlet/regmaintinit?OPTION=cancelRegistration");
    }
}*/

/*
 * Function exitCertTransaction() is used to return the user to the Launchpad if they
 * want to quit the transaction, otherwise, it attempts to commit the changes
 */
function exitCertTransaction(page)
{
    okExit = confirm("Do you wish to save current details?");

    location.replace("/CRCS/servlet/certmaint?OPTION=resetBean&DELETE_ALL=" + !okExit + "&PAGE_CALL=" + page);

    okExit = confirm("/CRCS/servlet/certmaint?OPTION=resetBean&DELETE_ALL=" + !okExit + "&PAGE_CALL=" + page);
}


/*
 * Function clearFields() ensures that the specified fields are emptied of their values
 * and calls the disableElement() function to allow/disallow editing.
 */
function clearAndEnableElements()
{
    var args = clearAndEnableElements.arguments;
    var call = "disableElement(";

    for (var i = 0 ; i < (args.length - 1) ; i += 2 )
    {
        args[i].value = "";

        call += (i > 0 ? "," : "") + "document.forms[0]." + args[i].name + "," + args[i+1];
    }

    call += ")";

    eval(call);
}


/*
 * Function disableElement() sets the 'disabled' status of the entered item to true
 * to prevent the user entering information.  Usually called with 'this'.
 *
 * RAC 05/12/2001 : Added check in if() statement to ensure that element is available
 *                  before testing the type.
 */
function disableElement()
{
    var a = disableElement.arguments;

    for (var i = 0 ; i < (a.length - 1) ; i += 2 )
    {
        var e = a[i];

        if (e && e.type != "hidden")
        {
            e.disabled = a[i+1];

            if(a[i+1])
            {
                e.style.background = "#CCCCFF";
            }
            else
            {
                e.style.background = "#EEEEFF";
            }
        }
    }
}


/*
 * Function remoteElementDisable() provides a check for the onBlur() event of the first specified element (e1)
 * to check if something has been entered or not.  If it contains a code, then disable the second
 * specified element (e2), set its background colour, and jump to the third specified element (e3) if
 * the fourth parameter (jump) is set to true.
 *
 * NOTE:
 * If disabling items, always have a hidden field that matches it if the value is to be returned to a
 * servlet for action - a disabled field will return a null.
 */
function remoteElementDisable(e1,e2,e3,bool)
{
    if (e1.value.length > 0)
    {
        disableElement(e2,true);

        /*if (bool)
        {
            goItem(e3);
        }*/
    }
    else
    {
        disableElement(e2,false);

        /*if (bool)
        {
            goItem(e2);
        }*/
    }
}



/*
 * Function setMenuItem() is used to auto-select a specific option in a drop-down list.  Generally, this
 * would be called from the onBlur() event of a text element
 */
/*function setMenuItem(srcItem, tgtItem, option)
{
    if (srcItem.value.length > 0)
    {
        for ( i = 0 ; i < tgtItem.options.length ; i ++ )
        {
            if ( tgtItem.options[i].value == option )
            {
                tgtItem.selectedIndex = i;
            }
        }
    }
}*/



/*
 * Function checkSubmission() is used to determine if the user has already submitted the form
 */
function checkSubmission()
{
    var submitOK = true;

    if (isSubmitted)
    {
        submitOK = false;
        alert("Please wait...\n\nSubmission is in progress.  Click 'OK' to allow results to be displayed.");
    }
    else
    {
        isSubmitted = true;
    }

    return submitOK;
}


/*
 * Function setRadioButton() is used to find and select the specified radio button value in the specified
 * radio item.  This is done by cycling through element/value pairs, ie
 *
 *      setRadioButton(<radio element>,<value>,<radio element>,<value>,...);
 */
function setRadioButton()
{
    var a = setRadioButton.arguments;

    for (var x = 0 ; (x < a.length - 1) ; x += 2)
    {
        var radio = a[x];

        RADIO_LOOP:
        for (var i = 0 ; (radio && i < radio.length) ; i++ )
        {
            if (radio[i].value == a[x+1])
            {
                radio[i].checked = true;
                break RADIO_LOOP;
            }
        }
    }
}

