/* Global Variables */

var applicationPath;
var blnRunOnReadyStateComplete = false;
var scrollWindowInterval = null;
var scrollWindowStepSize = 1;


String.prototype.trim = function(chars) {
    return this.ltrim(chars).rtrim(chars);
};
String.prototype.ltrim = function(chars) {
    chars = chars || "\\s";
    return this.replace(new RegExp("^[" + chars + "]+", "g"), "");
};

String.prototype.rtrim = function(chars) {
    chars = chars || "\\s";
    return this.replace(new RegExp("[" + chars + "]+$", "g"), "");
};

Array.prototype.remove = function(from, to) {
    var rest = this.slice((to || from) + 1 || this.length);
    this.length = from < 0 ? this.length + from : from;
    return this.push.apply(this, rest);
};

ArrayRemove = function(array, from, to) {
    var rest = array.slice((to || from) + 1 || array.length);
    array.length = from < 0 ? array.length + from : from;
    return array.push.apply(array, rest);
};

function Trim(strExpression, strChars) {
    debugger;
    if ((typeof (strExpression) == 'undefined') || (strExpression == null)) {
        return '';
    }
    else if (typeof (strExpression) == 'string') {
        return strExpression.trim(strChars);
    }
    else {
        return strExpression.toString().trim(strChars);
    }
};

String.prototype.htmlEncode = function() {
    var encodedHtml = escape(this);
    encodedHtml = encodedHtml.replace(/\//g, "%2F");
    encodedHtml = encodedHtml.replace(/\?/g, "%3F");
    encodedHtml = encodedHtml.replace(/=/g, "%3D");
    encodedHtml = encodedHtml.replace(/&/g, "%26");
    encodedHtml = encodedHtml.replace(/@/g, "%40");

    return encodedHtml;
};

String.prototype.htmlDecode = function() {
    var decodedHtml = this;
    decodedHtml = decodedHtml.replace(/%2F/g, "/");
    decodedHtml = decodedHtml.replace(/%3F/g, "?");
    decodedHtml = decodedHtml.replace(/%3D/g, "=");
    decodedHtml = decodedHtml.replace(/%26/g, "&");
    decodedHtml = decodedHtml.replace(/%40/g, "@");
    decodedHtml = unescape(decodedHtml);
    return decodedHtml;
};


String.prototype.URLEncode = function() {
    var clearString = this;
    var output = '';
    var x = 0;
    clearString = clearString.toString();
    var regex = /(^[a-zA-Z0-9_.]*)/;
    while (x < clearString.length) {
        var match = regex.exec(clearString.substr(x));
        if (match != null && match.length > 1 && match[1] != '') {
            output += match[1];
            x += match[1].length;
        } else {
            if (clearString[x] == ' ')
                output += '+';
            else {
                var charCode = clearString.charCodeAt(x);
                var hexVal = charCode.toString(16);
                output += '%' + (hexVal.length < 2 ? '0' : '') + hexVal.toUpperCase();
            }
            x++;
        }
    }
    return output;
};


String.prototype.URLDecode = function() {
    var output = this;
    var binVal, thisString;
    var myregexp = /(%[^%]{2})/;
    while ((match = myregexp.exec(output)) != null
				 && match.length > 1
				 && match[1] != '') {
        binVal = parseInt(match[1].substr(1), 16);
        thisString = String.fromCharCode(binVal);
        output = output.replace(match[1], thisString);
    }
    return output;
};

function confirmDelete(sName) {
    if (confirm('Are you sure you want to delete ' + sName + '?')) {
        return true;
    }
    else {
        return false;
    }
};


/*********************************************
*General functions
*********************************************/

function fireOnEnter(that, e, strFunction) {
    if (!e) {
        e = window.event;
    }
    var intKeyCode = (e.which ? e.which : e.keyCode);

    if (intKeyCode == 13) {
        eval(strFunction);
        return false;
    }
    return true;
};

function fireOnEscape(that, e, strFunction) {
    if (!e) {
        e = window.event;
    }
    var intKeyCode = (e.which ? e.which : e.keyCode);

    if (intKeyCode == 27) {
        eval(strFunction);
        return false;
    }
    return true;
};

function fireDefaultButton(e, strDefaultButtonId, strCancelButtonId) {
    e = ((!e) ? window.event : e);
    var intKeyCode = (e.which ? e.which : e.keyCode);
    var isFireFox = (!document.frames);

    if ((intKeyCode == 13) && (typeof (strDefaultButtonId) == 'string')) {
        var btnDefaultButton = document.getElementById(strDefaultButtonId);

        if (btnDefaultButton != null) {
            if (btnDefaultButton.disabled != true) {
                if (!isFireFox) {
                    btnDefaultButton.click();
                }
                else {
                    var evt = btnDefaultButton.ownerDocument.createEvent('MouseEvents');
                    evt.initMouseEvent('click', true, true, btnDefaultButton.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
                    clickResponse = btnDefaultButton.dispatchEvent(evt);
                }
                return false;
            }
        }
    }
    else if ((intKeyCode == 27) && (typeof (strCancelButtonId) == 'string')) {
        var btnCancelButton = document.getElementById(strCancelButtonId);

        if (btnCancelButton != null) {
            if (btnCancelButton.disabled != true) {
                if (!isFireFox) {
                    btnCancelButton.click();
                }
                else {
                    var evt = btnCancelButton.ownerDocument.createEvent('MouseEvents');
                    evt.initMouseEvent('click', true, true, btnCancelButton.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
                    clickResponse = btnCancelButton.dispatchEvent(evt);
                }
            }
            return false;
        }
    }

    return true;
};

function txtBoxFocus(e, that, text) {
    if (that.value == text) {
        that.value = '';
    }
};

function txtBoxBlur(e, that, text) {
    if (that.value == '') {
        that.value = text;
    }
};


function maxLength(field, maxlimit) {
    if (field.value.length > maxlimit) {
        field.value = field.value.substring(0, maxlimit);
        //alert('You have reached the maximum ' + maxlimit + ' characters.'); 
        raiseMessage('stoperror', 'You have reached the maximum ' + maxlimit + ' characters.', field.id);
        return (false); // Prevent the keypress occurring 
    }
};


function ResetTimeout() {
    window.parent.document.all.hidCountdown.value = window.parent.document.all.hidTimeout.value;
};

function TimeFormat(sText) {
    var sT = sText.value;
    var lHours = 0;
    var lMins = 0;

    sT = '0000' + sT;
    sT = sT.substr(sT.length - 5, 5);

    if (sT.indexOf(':') == -1) {
        sT = sT.substr(sT.length - 4, 2) + ':' + sT.substr(sT.length - 2, 2);
    }

    lHours = sT.substr(0, 2) / 1;
    lMins = sT.substr(3, 2) / 1;

    if (isNaN(lHours)) {
        lHours = 0;
    } else {
        if (lHours > 23) {
            lHours = 0;
        }
    }

    if (isNaN(lMins)) {
        lMins = 0;
    } else {
        if (lMins > 59) {
            lMins = 0;
        }
    }

    lHours = '00' + lHours;
    lHours = lHours.substr(lHours.length - 2, 2);

    lMins = '00' + lMins;
    lMins = lMins.substr(lMins.length - 2, 2);

    sText.value = lHours + ':' + lMins;
};

function pre_load_images() {

    if (document.images) {
        //Create an image array if there isn't one already
        if (!document.image_array) {
            document.image_array = new Array();
        }
        //Find out how big it is
        var image_count = document.image_array.length;
        //Get an array of the strings passed in to this procedure
        document.argument_array = pre_load_images.arguments;
        //If the string isn't already there, add it
        for (i = 0; i < document.argument_array.length; i++) {
            if (document.argument_array[i].indexOf("#") != 0) {
                //debug_print('pre_load_image : '+document.argument_array[i]);
                document.image_array[image_count] = new Image;
                document.image_array[image_count++].src = document.argument_array[i];
            }
        }
    }
};

function image_restore(e) {
    if (!e) {
        e = window.event;
    }

    var objSrcElement = (e.target) ? e.target : e.srcElement;
    if (document.old_image != '') {
        var image_path = objSrcElement.src;
        if (image_path.substr(image_path.length - 6, 3) == 'on.') {
            objSrcElement.src = document.old_image;
        }
    }
};

function image_swap(e) {
    if (!e) {
        e = window.event;
    }
    var objSrcElement = (e.target) ? e.target : e.srcElement;
    var image_path = objSrcElement.src;
    var image_ext = image_path.substr(image_path.length - 3, 3);
    //If it is currently an off image, change to an on image, and store the old image
    if (image_path.substr(image_path.length - 7, 3) == 'off') {
        document.old_image = image_path;
        image_path = image_path.substr(0, image_path.length - 7) + 'on.' + image_ext;
        objSrcElement.src = image_path;
    }
};

function Print() {
    self.print();
};

// Over class name functions
function Over(That) {
    That.className = That.className + 'Over';

};
function Out(That) {
    if (That.className.substr(That.className.length - 4, 4) == 'Over') {
        That.className = That.className.substr(0, That.className.length - 4);
    }

};

function numeric_keypress(e, that, isFloat, minimum, maximum, onEnterFunction) {
    var intKeyCode = (e.which ? e.which : e.keyCode);
    if ((intKeyCode > 47) && (intKeyCode < 58)) {
        return true;
    }
    if (intKeyCode == 13) {
        if (onEnterFunction) {
            eval(onEnterFunction);
        }
        return false;
    }
    else if (intKeyCode == 43) {
        that.value = parseFloat(that.value) + 1;
        if ((typeof (maximum) != 'undefined') && (maximum != null)) {
            if (parseFloat(that.value) > maximum) {
                that.value = maximum;
            }
        }
        return false;
    }
    else if ((intKeyCode == 95) || (intKeyCode == 45)) {
        that.value = parseFloat(that.value) - 1;
        if ((typeof (minimum) != 'undefined') && (minimum != null)) {
            if (parseFloat(that.value) < minimum) {
                that.value = minimum;
            }
        }
        return false;
    }
    else if ((intKeyCode == 46) || (intKeyCode == 62)) {
        if (isFloat) {
            if (that.value.indexOf('.') > -1) {
                return false;
            }
            return true;
        }
        else {
            return false;
        }
    }
    else if (intKeyCode == 27) {
        that.value = 0;
        return false;
    }

    window.status = 'Invalid keypress ' + intKeyCode;

    return false;
}
//used in wood dash
function currency_keypress(e, that, minimum, maximum, onEnterFunction) {
    var intKeyCode = (e.which ? e.which : e.keyCode);
    var value = toNumericValue(that.value);
    var originalValue = value;

    if ((intKeyCode > 47) && (intKeyCode < 58)) {
        return true;
    }
    if (intKeyCode == 13) {
        if (onEnterFunction) {
            if (originalValue != value) {
                that.value = formatCurrency(value);
            }
            eval(onEnterFunction);
        }
        return false;
    }
    else if (intKeyCode == 43) {
        value = value + 1;
        if ((typeof (maximum) != 'undefined') && (maximum != null)) {
            if (value > maximum) {
                value = maximum;
            }
        }

        if (originalValue != value) {
            that.value = formatCurrency(value);
        }
        return false;
    }
    else if ((intKeyCode == 95) || (intKeyCode == 45)) {
        value = value - 1;
        if ((typeof (minimum) != 'undefined') && (minimum != null)) {
            if (value < minimum) {
                value = minimum;
            }
        }

        if (originalValue != value) {
            that.value = formatCurrency(value);
        }
        return false;
    }
    else if ((intKeyCode == 46) || (intKeyCode == 62)) {
        if (that.value.indexOf('.') > -1) {
            return false;
        }
        return true;
    }
    else if (intKeyCode == 27) {
        that.value = '£0.00';
        return false;
    }

    window.status = 'Invalid keypress ' + intKeyCode;

    return false;
};


//depreciated
function showContextMenu(e, menuId, hidMenuContextId, strCommandArgument) {
    var menu = document.getElementById(menuId);
    var isRightClick;

    if (menu != null) {
        if (!e) {
            e = window.event;
        }

        if (e.which) isRightClick = (e.which == 3);
        else if (e.button) isRightClick = (e.button == 2);

        if ((e.type == 'contextmenu') || (isRightClick)) {
            var hidMenuContext = document.getElementById(hidMenuContextId);


            hidMenuContext.value = strCommandArgument;
            var menuOffset = 2;
            menu.style.left = e.x - menuOffset;
            menu.style.top = e.y - menuOffset;
            menu.style.display = '';
            e.cancelBubble = true;

            return false;
        }
    }

    return true;
};

function toNumericValue(value) {
    var intLength = value.length;
    var newValue = '';
    var currentChar = '';
    var foundDecimalPoint = false;

    for (var intIndex = 0; intIndex < intLength; intIndex++) {
        currentChar = value.charAt(intIndex);

        switch (currentChar) {
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
            case '0':

                newValue += currentChar;
                break;

            case '.':

                if (foundDecimalPoint == false) {
                    newValue += new String(currentChar);
                    foundDecimalPoint = true;
                }
                else {
                    intIndex = intLength;
                }
                break;

        }
    }

    if (newValue == '') {
        return 0;
    }

    return parseFloat(newValue);
};

function formatCurrency(num) {
    num = num.toString().replace(/\£|\,/g, '');
    if (isNaN(num))
        num = '0';

    var sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    var pence = num % 100;
    num = Math.floor(num / 100).toString();

    if (pence < 10)
        pence = '0' + pence;

    return (((sign) ? '' : '-') + '£' + num + '.' + pence);
};


function trapESC(menu) {
    var key = window.event.keyCode;
    if (key == 27) {
        menu.style.display = 'none';
    }
};

// Calculates the object's absolute position, and width and height
function GetAbsPosition(object) {
    var position = new Object;
    position.x = 0;
    position.y = 0;

    if (object) {
        position.x = object.offsetLeft;
        position.y = object.offsetTop;

        if (object.offsetParent) {
            var parentpos = GetAbsPosition(object.offsetParent);
            position.x += parentpos.x;
            position.y += parentpos.y;
        }
    }

    position.cx = object.offsetWidth;
    position.cy = object.offsetHeight;

    return position;
};


function getOffset1(that) {

    //from quirksmode.org
    var curleft = curtop = 0;
    if (that.offsetParent) {
        curleft = that.offsetLeft
        curtop = that.offsetTop
        while (that == that.offsetParent) {
            curleft += that.offsetLeft
            curtop += that.offsetTop
        }
    }
    return [curleft, curtop];
};

/*********************************************
*Parent control id functions
*********************************************/

function getParentId(id) {
    //returns the id of the parent control from a child control id.
    //e.g. 
    var iIndexOf = 0;
    var sCtl = new String();
    sCtl = id;

    while (sCtl.indexOf('_', iIndexOf + 1) != -1) {
        iIndexOf = sCtl.indexOf('_', iIndexOf + 1);
    }

    return sCtl.slice(0, iIndexOf);
};



function getOffset(that) {
    //debug_print('getOffset | '+that.id);
    //from quirksmode.org
    var curleft = curtop = 0;
    if (that.offsetParent) {
        curleft = that.offsetLeft
        curtop = that.offsetTop
        while (that == that.offsetParent) {
            curleft += that.offsetLeft
            curtop += that.offsetTop
        }
    }
    //debug_print('getOffset | curleft | '+curleft);
    //debug_print('getOffset | curtop | '+curtop);
    return [curleft, curtop];
};



/*********************************************
*END MINI DHTML Library functions
*********************************************/


function sDate(thedate) {
    var sMonth = thedate.getMonth();
    switch (sMonth) {
        case 0:
            sMonth = ' January ';
            break;
        case 1:
            sMonth = ' February ';
            break;
        case 2:
            sMonth = ' March ';
            break;
        case 3:
            sMonth = ' April ';
            break;
        case 4:
            sMonth = ' May ';
            break;
        case 5:
            sMonth = ' June ';
            break;
        case 6:
            sMonth = ' July ';
            break;
        case 7:
            sMonth = ' August ';
            break;
        case 8:
            sMonth = ' September ';
            break;
        case 9:
            sMonth = ' October ';
            break;
        case 10:
            sMonth = ' November ';
            break;
        case 11:
            sMonth = ' December ';
            break;
    }
    return thedate.getDate() + sMonth + thedate.getFullYear();
};

function sDateTime(thedate) {

    var sMonth = thedate.getMonth();
    switch (sMonth) {
        case 0:
            sMonth = ' January ';
            break;
        case 1:
            sMonth = ' February ';
            break;
        case 2:
            sMonth = ' March ';
            break;
        case 3:
            sMonth = ' April ';
            break;
        case 4:
            sMonth = ' May ';
            break;
        case 5:
            sMonth = ' June ';
            break;
        case 6:
            sMonth = ' July ';
            break;
        case 7:
            sMonth = ' August ';
            break;
        case 8:
            sMonth = ' September ';
            break;
        case 9:
            sMonth = ' October ';
            break;
        case 10:
            sMonth = ' November ';
            break;
        case 11:
            sMonth = ' December ';
            break;
    }
    return thedate.getDate() + sMonth + thedate.getFullYear() + ' ' + thedate.getHours() + ':' + thedate.getMinutes();
};

function getElementbyClass(rootobj, classname) {
    var temparray = new Array();
    var inc = 0;
    for (i = 0; i < rootobj.length; i++) {
        if (rootobj[i].className == classname)
            temparray[inc++] = rootobj[i];
    }
    return temparray;
};

var tmrReset = null;
var blnFormDisabled = false;

function formDisable(bDisable) {
    document.body.focus();
    formFrameDisable(window, bDisable);
};

function formFrameDisable(main_window, bDisable) {

    if (main_window) {
        var divMainProtect = main_window.document.getElementById('divMainProtect');

        if (divMainProtect == null) {
            divMainProtect = main_window.document.createElement('div');
            divMainProtect.id = 'divMainProtect';
            divMainProtect.className = 'divProtect';
            divMainProtect.style.width = '0';
            divMainProtect.style.height = '0';
            divMainProtect.style.display = 'none';
            divMainProtect.style.top = '0';
            divMainProtect.style.left = '0';
            divMainProtect.style.position = 'absolute';
            /*
            if(main_window.document.getElementById('base'))
            {
            main_window.document.getElementById('base').appendChild(divMainProtect);
            }
            else
            {	//Page has probably not rendered correctly therefore fall back to using body.
            main_window.document.body.appendChild(divMainProtect);
            }
            */
            main_window.document.body.appendChild(divMainProtect);

        }

        if ((bDisable == false) || (bDisable == 'false')) {
            blnFormDisabled = false;
            divMainProtect.style.display = 'none';
            //new Effect.Fade(divMainProtect, {duration: .2, queue: 'end'});
            divMainProtect.style.width = '0';
            divMainProtect.style.height = '0';

            tmrReset = setTimeout('resetProtectSize()', 200)
        }
        else if (blnFormDisabled == false) {
            //divMainProtect.style.width = '100%';
            //divMainProtect.style.height = '100%';
            blnFormDisabled = true;
            var d = $(document.body).getDimensions();
            divMainProtect.style.width = d.width.toString() + 'px'; // getDocumentWidth();
            divMainProtect.style.height = getDocumentHeight(document.body).toString() + 'px'; //d.height.toString() + 'px'; // getDocumentHeight();
            divMainProtect.style.display = 'block';
            //new Effect.Appear(divMainProtect, {duration: .4, queue: 'end'});
        }
    }
};



function zero(value) { value = parseInt(value); return isNaN(value) ? 0 : value; };

function resetProtectSize() {
    var main_window = window;
    var divMainProtect = main_window.document.getElementById('divMainProtect');

    divMainProtect.style.width = '0';
    divMainProtect.style.height = '0';

    tmrReset = null;
};


function getDocumentHeight(body) {
    var innerHeight = (typeof (self.innerHeight) != 'undefined' && !isNaN(self.innerHeight)) ? self.innerHeight : 0;

    if (!document.compatMode || document.compatMode == "CSS1Compat") {
        var topMargin = parseInt(body.style.marginTop, 10) || 0;
        var bottomMargin = parseInt(body.style.marginBottom, 10) || 0;

        return Math.max(body.offsetHeight + topMargin + bottomMargin,
                            document.documentElement.clientHeight,
                            document.documentElement.scrollHeight, zero(self.innerHeight));
    }
    return Math.max(body.scrollHeight, body.clientHeight, zero(self.innerHeight));
};

function getDocumentWidth() {
    //TODO: check browser compatablity
    if ((document.body) && (document.body.scrollWidth))
        return (document.body.scrollWidth) + 'px';
    else
        return '200%'
};

function setText(textbox_id, text) {
    //debug_print('setText |' + textbox_id + ' to ' + text + '');
    if (document.getElementById(textbox_id)) {
        document.getElementById(textbox_id).value = text;
        return true;
    }
    else {
        return false;
    }
};


function toNormalCase(this_string, word_seperator, all_words) {
    /*
    *toNormalCase sets the first letter of one or more words to capital
    *
    * this_string    - string ('')     - The string to be capitalised
    * word_seperator - string (' ')    - Character between words 
    * all_words      - boolean (false) - False capitalises first word only, true capitalises all words
    */
    //Init vars
    var first_letter = new String();
    var other_letters = new String();
    var temp_string = new String();
    //check parameters
    if (word_seperator == null) {
        word_seperator = ' ';
    }
    if (all_words != true) {
        all_words = false
    }
    this_string = this_string.toLowerCase();
    //All words or just the first?
    if (all_words) {
        //Capitalise all words
        var temp_words = new Array();
        temp_words = this_string.split(word_seperator);
        var word_num = 0;
        //Iterate through words
        for (word_num = 0; word_num < temp_words.length; word_num++) {
            first_letter = temp_words[word_num].charAt(0);
            other_letters = temp_words[word_num].substring(1, temp_words[word_num].length);
            first_letter = first_letter.toUpperCase();
            if (temp_string == '') {
                temp_string += first_letter + other_letters
            }
            else {
                temp_string += word_seperator + first_letter + other_letters
            }
        }
    }
    else {
        //Capitalise first word only
        first_letter = this_string.charAt(0);
        other_letters = this_string.substring(1, this_string.length);
        first_letter = first_letter.toUpperCase();
        temp_string = first_letter + other_letters
    }
    return (temp_string);
};

function isMaxLength(that, maxLength) {
    if (that.value.length > maxLength)
        that.value = that.value.substring(0, maxLength - 1)
};

function isValidDecimalPercent(that, min, max) {
    /*
    Returns a boolean based on whether the value passed in is a number and is between the min and max values.
    true - if all criteria were met
    false - if any of the criteria were not met. 
    */
    var return_value = true;
    if (isNaN(that)) {
        return_value = false;
    }
    else {
        if (that > max || that < min) {
            return_value = false;
        }
        if (that.indexOf('.') > -1) {
            var this_value = that.toString();
            var value_array = new Array();
            value_array = this_value.split('.');
            //alert(value_array.length);
            if (value_array.length > 0) {
                var decimal_part = value_array[1].toString();
                //alert(decimal_part);

                if (decimal_part.length > 2) {
                    return_value = false;
                }
            }
        }
    }
    return return_value;
};

function focusFirst() {
    //focus the first text input
    //var els = document.forms[0].elements;
    var els = document.getElementsByTagName('input');
    try {
        for (var i = 0; els.length - 1; i++) {
            if (els[i].type == 'text') {
                if (!els[i].disabled && !els[i].readOnly) {
                    els[i].focus()
                    document.execCommand("selectAll", false);
                    break;
                }
            }
        }
    }
    catch (e) { }
};

function disableContextMenu() {
    return false;
};

function isDate(p_Expression) {
    return !isNaN(new Date(p_Expression)); 	// <<--- this needs checking
};

function closeDatePicker() {
    if (datePickerDivID != '' && datePickerDivID != undefined) {
        var pickerDiv = document.getElementById(datePickerDivID);
        pickerDiv.style.visibility = "hidden";
        pickerDiv.style.display = "none";
        adjustiFrame();
    }
};


function lTrim(str, n) {
    if (n <= 0)
        return "";
    else if (n > String(str).length)
        return str;
    else
        return String(str).substring(0, n);
};
function rTrim(str, n) {
    if (n <= 0)
        return "";
    else if (n > String(str).length)
        return str;
    else {
        var iLen = String(str).length;
        return String(str).substring(iLen, iLen - n);
    }
};

function selectAllText(that) {
    that.select();
};

function padLeft(expression, length, paddingChar) {
    var value = new String(expression);

    if ((paddingChar == undefined) || (paddingChar == null) || (paddingChar.length == 0)) {
        paddingChar = ' ';
    }

    while (value.length < length) {
        value = paddingChar + value;
    }


    return value;
};


function padRight(expression, length, paddingChar) {
    var value = new String(expression);

    if ((paddingChar == undefined) || (paddingChar == null) || (paddingChar.length == 0)) {
        paddingChar = ' ';
    }

    while (value.length < length) {
        value = value + paddingChar;
    }


    return value;
};


function addEvent(elm, evType, fn, useCapture) {
    // cross-browser event handling for IE5+, NS6 and Mozilla
    // By Scott Andrew
    if (elm.addEventListener) {
        elm.addEventListener(evType, fn, useCapture);
        return true;
    }
    else if (elm.attachEvent) {
        var r = elm.attachEvent('on' + evType, fn);
        return r;
    }
    else {
        elm['on' + evType] = fn;
    }
};


/*
Written by Jonathan Snook, http://www.snook.ca/jonathan
Add-ons by Robert Nyman, http://www.robertnyman.com
*/
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)
};

var curelem = '';



function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
    var rv = -1; // Return value assumes failure.
    if (navigator.appName == 'Microsoft Internet Explorer') {
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
            rv = parseFloat(RegExp.$1);
    }
    return rv;
};

MenuHover = function() {

    var objMenus = getElementsByClassName(document.body, 'ul', 'CascadeMenu');
    if (objMenus && objMenus.length == 0) {
        return;
    };
    var browser = getInternetExplorerVersion();
    objMenus.each(function(objMenu) {
        if (browser == 6) {
            // IE6 script to cover <select> elements by creating an Iframe behind the menu
            var ieULs = $(objMenu).getElementsBySelector('ul');
            $(ieULs).each(function(ieUL) {
                var objIFrame = $CE('iframe', { frameborder: '0' }, { position: 'absolute', filter: 'progid:DXImageTransform.Microsoft.Alpha(opacity=0)', display: 'none', zIndex: '-1' });
                ieUL.appendChild(objIFrame);
                Position.clone(ieUL, objIFrame);
                ieUL.style.zIndex = '99';
                objIFrame.show();
            });
        };
        var objItems = $(objMenu).getElementsBySelector('li');
        objItems.each(function(menuitem) {
            menuitem.onmouseenter = function() {
                this.addClassName('MenuItemHover');
            };
            menuitem.onmouseleave = function() {
                this.timer = new Timer(this);
                this.timer.setTimeout("out", 100);
            };
            menuitem.out = function() {
                this.removeClassName('MenuItemHover');
            };
        });
    });
};



/* TIMER IS FOR MENU CASCADE */

// The constructor should be called with
// the parent object (optional, defaults to window).

function Timer() {
    this.obj = (arguments.length) ? arguments[0] : window;
    return this;
};

// The set functions should be called with:
// - The name of the object method (as a string) (required)
// - The millisecond delay (required)
// - Any number of extra arguments, which will all be
//   passed to the method when it is evaluated.

Timer.prototype.setInterval = function(func, msec) {
    var i = Timer.getNew();
    var t = Timer.buildCall(this.obj, i, arguments);
    Timer._set[i].timer = window.setInterval(t, msec);
    return i;
};
Timer.prototype.setTimeout = function(func, msec) {
    var i = Timer.getNew();
    Timer.buildCall(this.obj, i, arguments);
    Timer._set[i].timer = window.setTimeout("Timer.callOnce(" + i + ");", msec);
    return i;
};

// The clear functions should be called with
// the return value from the equivalent set function.

Timer.prototype.clearInterval = function(i) {
    if (!Timer._set[i]) return;
    window.clearInterval(Timer._set[i].timer);
    Timer._set[i] = null;
};
Timer.prototype.clearTimeout = function(i) {
    if (!Timer._set[i]) return;
    window.clearTimeout(Timer._set[i].timer);
    Timer._set[i] = null;
};

// Private data

Timer._set = new Array();
Timer.buildCall = function(obj, i, args) {
    var t = "";
    Timer._set[i] = new Array();
    if (obj != window) {
        Timer._set[i].obj = obj;
        t = "Timer._set[" + i + "].obj.";
    }
    t += args[0] + "(";
    if (args.length > 2) {
        Timer._set[i][0] = args[2];
        t += "Timer._set[" + i + "][0]";
        for (var j = 1; (j + 2) < args.length; j++) {
            Timer._set[i][j] = args[j + 2];
            t += ", Timer._set[" + i + "][" + j + "]";
        }
    }
    t += ");";
    Timer._set[i].call = t;
    return t;
};
Timer.callOnce = function(i) {
    if (!Timer._set[i]) return;
    eval(Timer._set[i].call);
    Timer._set[i] = null;
}
Timer.getNew = function() {
    var i = 0;
    while (Timer._set[i]) i++;
    return i;
};


function compatModalDialog(url, width, height) {
    if (window.showModalDialog) {
        window.showModalDialog(url, window,
			"dialogWidth:" + width + "px;dialogHeight:" + height + "px;edge:Raised;center:1;help:0;resizable:1;maximize:1;status:0");
    }
    else {
        var left = screen.availWidth / 2 - width / 2;
        var top = screen.availHeight / 2 - height / 2;
        document.activeModalWin = window.open(url, "", "status=no,width=" + width + ",height=" + height + ",left=" + left + ",top=" + top);
        window.onfocus = function() { if (document.activeModalWin.closed == false) { document.activeModalWin.focus(); }; };
    }
};

function submitForm(strEmail, strName, strAction) {
    var objEl;

    //Validate name if exists
    if (strName) {
        objEl = document.getElementById(strName);
        if (objEl.value == '') {
            alert('Please enter your name');
            objEl.className = "TagHighLight";
            objEl.focus();
            return false;
        }
        else {
            objEl.className = "";
        }
    }

    //Validate email if exists
    if (strEmail) {
        objEl = document.getElementById(strEmail);
        if (objEl.value == '' || !isEmail(objEl.value)) {
            alert('Please enter a valid email address');
            objEl.className = "TagHighLight";
            objEl.focus();
            return false;
        }
        else {
            objEl.className = "";
        }
    }


    //change action on form and submit
    if (strAction) {
        document.forms['aspnetForm'].action = strAction;
        document.forms['aspnetForm'].submit();
        return false;
    }

};

// add option to select box
function appendToSelect(objselect, value, content) {
    var opt;
    opt = document.createElement("option");
    opt.value = value;
    opt.appendChild(document.createTextNode(content))
    objselect.appendChild(opt);
};

function GetXmlNodeText(node) {
    if (node && node.text) {
        return node.text;
    }
    else if (node && node.textContent) {
        return node.textContent;
    }
    else {
        return '';
    }
};

function getXmlString(xmlDoc) {
    if (typeof (xmlDoc.xml) == 'string') {
        return xmlDoc.xml;
    }
    else {
        //create a new XMLSerializer
        var objXMLSerializer = new XMLSerializer();

        //get the XML string
        return objXMLSerializer.serializeToString(xmlDoc);
    }

};

function isNullOrUndefined(expression) {
    return ((typeof (expression) == 'undefined') || (expression == null));
};


function QuickSearch(strAction) {
    document.forms['aspnetForm'].action = strAction;
    var d = document.getElementById('__VIEWSTATE');
    if (d) {
        d.parentElement.removeChild(d);
    }
    document.forms['aspnetForm'].submit();
};
function QuickSearchEnterSubmit(strAction) {
    if (window.event && window.event.keyCode == 13) {
        QuickSearch(strAction);
    }
    else {
        return true;
    }
};

/* JAVASCRIPT INCLUDE .JS FILE */
var included_files = [];

function include_dom(script_filename) {
    var html_doc = document.getElementsByTagName('head').item(0);
    var js = document.createElement('script');
    js.setAttribute('language', 'javascript');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', script_filename);
    html_doc.appendChild(js);
    return false;
};

function include_once(script_filename) {
    if (!in_array(script_filename, included_files)) {
        included_files[included_files.length] = script_filename;
        include_dom(script_filename);
    }
};

function in_array(needle, haystack) {
    for (var i = 0; i < haystack.length; i++) {
        if (haystack[i] == needle) {
            return true;
        }
    }
    return false;

};



var mobjRepeat;
var mobjItems;
var mintCurrent = 0;
var mstrTitle = '';
var mobjTitle;

AnnouncementsPanel = function() {
    mobjRepeat = getElementsByClassName(document.body, "ul", "Announcements");
    if (mobjRepeat && mobjRepeat.length == 0) {
        return;
    }
    for (var i = 0; i < mobjRepeat.length; i++) {
        mobjItems = mobjRepeat[i].getElementsByTagName("li");
        for (var x = 0; x < mobjItems.length; x++) {
            mobjItems[x].style.display = 'none';
        }
        if (mobjItems) {
            mobjTitle = mobjItems[0];
            mstrTitle = mobjTitle.getElementsByTagName('h1')[0].innerHTML;
        }
    }
    this.timer = new Timer(this);
    this.hideAdd = function() {
        if (mobjItems) {
            new Effect.DropOut(mobjItems[mintCurrent], { duration: 1 });
        }
    }
    this.showAnn = function() {
        if (mobjItems) {
            new Effect.Appear(mobjItems[mintCurrent], { duration: 1 });
            mobjTitle.getElementsByTagName('h1')[0].innerHTML = mstrTitle + ' (' + mintCurrent + '/' + (mobjItems.length - 1) + ')';
            mobjItems[0].innerHTML = mobjTitle.innerHTML;
            new Effect.SlideDown(mobjItems[mintCurrent], { duration: 1 });
            this.timer.setTimeout("nextAnn", 6000);
        }
    }
    this.nextAnn = function() {
        if (mobjItems) {
            this.hideAdd();
            mintCurrent++;
            if (mintCurrent >= mobjItems.length) {
                mintCurrent = 1;
            }
            this.timer.setTimeout("showAnn", 2000);
        }
    }
    if (mobjItems) {
        //always display the header (first list item)
        mobjItems[0].style.display = 'block';
        mintCurrent++;
        this.timer.setTimeout("showAnn", 0);
    }

};


//check if the previous sibling node is an element node
function get_previoussibling(n) {
    if ((typeof (n) != 'undefined') && (n != null)) {
        var x = n.previousSibling;
        while ((x != null) && (x.nodeType != 1)) {
            x = x.previousSibling;
        }
        return x;
    }
    return null;

    /*
    Note: Internet Explorer will skip white-space text nodes that are generated between nodes (e.g. new-line characters), while Mozilla will not. So, in the example below, we have a function that checks the node type of the previous sibling node.

	Element nodes has a nodeType of 1, so if the previous sibling node is not an element node, it moves to the previous node, and checks if this node is an element node. This continues until the previous sibling node (which must be an element node) is found. This way, the result will be correct in both Internet Explorer and Mozilla.

	*/
};


function restoreScrollPosition() {//debugger;
    var hidScrollPositionX = document.getElementById('__SCROLLPOSITIONX');
    var hidScrollPositionY = document.getElementById('__SCROLLPOSITIONY');
    if ((!blnCancelRestoreScrollPosition) && (hidScrollPositionX) && (hidScrollPositionY)) {
        //window.scrollTo(hidScrollPositionX.value, hidScrollPositionY.value);
        if (scrollWindowInterval != null) {
            clearInterval(scrollWindowInterval);
        }

        var cypos = getCurrentYPos();
        var desty = hidScrollPositionY.value;

        scrollWindowStepSize = parseInt((desty - cypos) / 25);
        scrollWindowInterval = setInterval('scrollWindow(' + scrollWindowStepSize + ',' + desty + ')', 10);


    }
    /*else
    {
    window.scrollTo(0, 0);
    }*/
};

var lastYScrollPos = null;
function scrollWindow(scramount, dest) {
    var wascypos = getCurrentYPos();
    var isAbove = (wascypos < dest);

    if (lastYScrollPos != null) {
        if (wascypos != lastYScrollPos) {
            //user has changed the scroll pos so quit.
            clearInterval(scrollWindowInterval);
            return;
        }
    }

    window.scrollTo(0, wascypos + scramount);

    var iscypos = getCurrentYPos();
    var isAboveNow = (iscypos < dest);
    lastYScrollPos = iscypos;

    if ((isAbove != isAboveNow) || (wascypos == iscypos)) {
        // if we've just scrolled past the destination, or
        // we haven't moved from the last scroll (i.e., we're at the
        // bottom of the page) then scroll exactly to the link
        window.scrollTo(0, dest);
        // cancel the repeating timer
        clearInterval(scrollWindowInterval);
        // and jump to the link directly so the URL's right
        //location.hash = anchor;
    }
};

function getCurrentYPos() {
    if (document.body && document.body.scrollTop)
        return document.body.scrollTop;
    if (document.documentElement && document.documentElement.scrollTop)
        return document.documentElement.scrollTop;
    if (window.pageYOffset)
        return window.pageYOffset;
    return 0;
};

function newId() {
    try {
        //This is the prefered method but only works with MS Browsers.
        //The reason for begin prefered is that the microsoft aproach takes more care about being unique.
        if (window.ActiveXObject) {
            var x = new ActiveXObject("Scriptlet.TypeLib");
            if (x) {
                return (x.GUID).substr(1, 36); // Exclude the leading and trailing braces {}
            }
        }
    }
    catch (e) {
        //Failed to create guid.
        // Fall through to generateGuid()...
    }


    //Use alternative method.
    return generateGuid();
};


// generateGuid: Author: Richard Shears. Used by browsers other than IE to generate a guid.
function generateGuid() {
    var strResult = '';

    for (var j = 0; j < 32; j++) {
        if (j == 8 || j == 12 || j == 16 || j == 20) {
            strResult = strResult + '-';
        }
        strResult = strResult + Math.floor(Math.random() * 16).toString(16).toUpperCase();
    }

    return strResult
};

// Create Element:  $CE('a', {href: '#', className: 'someClass'});
// you can also specifiy inline styles as the 3rd parameter
var $CE = function(tagName, attributes, styles) { //short for create element
    var el = document.createElement(tagName);
    if (attributes)
        $H(attributes).each(function(pair) {
            eval("el." + pair.key + "='" + pair.value + "'");
        });
    if (styles)
        $H(styles).each(function(pair) {
            el.style[pair.key] = pair.value;
        });

    return $(el);
};

// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize() {
    var scrollX, scrollY, windowX, windowY, pageX, pageY;
    if (window.innerHeight && window.scrollMaxY) {
        scrollX = document.body.scrollWidth;
        scrollY = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
        scrollX = document.body.scrollWidth;
        scrollY = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        scrollX = document.body.offsetWidth;
        scrollY = document.body.offsetHeight;
    }

    if (self.innerHeight) {	// all except Explorer
        windowX = self.innerWidth;
        windowY = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowX = document.documentElement.clientWidth;
        windowY = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
        windowX = document.body.clientWidth;
        windowY = document.body.clientHeight;
    }

    pageY = (scrollY < windowY) ? windowY : scrollY; // for small pages with total height less then height of the viewport
    pageX = (scrollX < windowX) ? windowX : scrollX; // for small pages with total width less then width of the viewport

    return { pageWidth: pageX, pageHeight: pageY, winWidth: windowX, winHeight: windowY };
}

//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
//
function getPageScroll() {
    var x, y;
    if (self.pageYOffset) {
        x = self.pageXOffset;
        y = self.pageYOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
        x = document.documentElement.scrollLeft;
        y = document.documentElement.scrollTop;
    } else if (document.body) {// all other Explorers
        x = document.body.scrollLeft;
        y = document.body.scrollTop;
    }
    return { x: x, y: y };
}


/* 
MiWeb Client Java Runtime.
The following code is required by the MiWebEngine.
load_page(), runOnReadyStateComplete() Event.observe(window, 'load', load_page, false);
	
*/
function load_page() {
    if (typeof (do_page_load) != 'undefined') {
        do_page_load();
    }
    MenuHover();
    AnnouncementsPanel();
    FormTooltips();

    // This time out is to give the browser chance to load all of the .js files before we go into checking if the browser is in the complete state.
    setTimeout('runOnReadyStateComplete()', 100);

    //Event.observe(document, 'dom:loaded', function() { runOnReadyStateComplete(); });

};



function runOnReadyStateComplete(intRetryCount) {
    var intRestoreScrollDelay = 10;
    if ((typeof (intRetryCount) == 'undefined') || (intRetryCount == null)) {
        intRetryCount = 0;
    }
    intRetryCount = parseInt(intRetryCount, 10);
    if (blnRunOnReadyStateComplete == true) {
        return;
    }
    if (((typeof (mstrAppPath) != 'undefined') && (document.getElementById(mstrFilenameId) != null)) || (intRetryCount > 20)) {
        if (typeof (initialise_page) != 'undefined') {
            initialise_page();
        }
        if (typeof (restoreScrollPosition) != 'undefined') {
            if (typeof (mintRestoreScrollDelay) != 'undefined') {
                intRestoreScrollDelay = mintRestoreScrollDelay;
            }
            setTimeout('restoreScrollPosition()', intRestoreScrollDelay);
        }
        MiWeb.systemReplace();

    }
    else {
        intRetryCount += 1;
        setTimeout('runOnReadyStateComplete(' + intRetryCount.toString() + ')', 100 * intRetryCount);
    }
};
Event.observe(document, 'dom:loaded', function() { load_page(); });

/* Form Tooltips */
var mobjTips = null;
FormTooltips = function() {
    mobjTips = getElementsByClassName(document.body, "a", "formDesc");
    if (mobjTips && mobjTips.length == 0) {
        return false;
    }
    for (var intIndex = 0; intIndex < mobjTips.length; intIndex++) {
        Event.observe(mobjTips[intIndex], 'click', function() {

            var objSpns = getElementsByClassName(this.parentNode.parentNode, "span", "formDesc");
            if (objSpns.length > 0) {
                $(objSpns[0]).toggle();
            }
            else {
                var objSpn = $CE('span', { className: 'formDesc' }, { display: 'none' });
                var objParent = this.parentNode;
                var strTip = this.title;
                objSpn.innerHTML = strTip;
                Element.insert(objParent, { after: objSpn });
                objSpn.show();
            }
        }, false);
    }
};

function _centreDialog(dialog, setTop, setLeft) {
    var objPageSize = null;
    var objPageScroll = null;
    var dialogDimensions;
    var objBox;

    setTop = (typeof (setTop) != 'boolean') ? true : setTop;
    setLeft = (typeof (setLeft) != 'boolean') ? true : setLeft;

    objPageSize = getPageSize();
    objPageScroll = getPageScroll();
    Element.absolutize(dialog);
    dialogDimensions = dialog.getDimensions();
    objBox = { top: objPageScroll.y + ((objPageSize.winHeight - dialogDimensions.height) / 2), left: (objPageSize.winWidth - dialogDimensions.width) / 2 };
    if (objBox.top < 0) {
        objBox.top = 0;
    }
    if (objBox.left < 0) {
        objBox.left = 0;
    }
    if (setTop && setLeft) {
        dialog.setStyle({ top: objBox.top.toString() + 'px', left: objBox.left.toString() + 'px' });
    }
    else if (setTop) {
        dialog.setStyle({ top: objBox.top.toString() + 'px' });
    }
    else if (setLeft) {
        dialog.setStyle({ left: objBox.left.toString() + 'px' });
    }

};


function checkCapsLockState(pEvent, pElementID) {
    var lElement = $(pElementID);
    var lShiftKeyOn = false;
    var lKeyCode = 0;
    var lCapsOn = false;

    if (!pEvent) { pEvent = window.event; }

    if (lElement) {
        if (document.all) {
            // Internet Explorer 4+
            lKeyCode = pEvent.keyCode;
            lShiftKeyOn = pEvent.shiftKey;
        }
        else if (document.layers) {
            // Netscape 4
            lKeyCode = pEvent.which;
            lShiftKeyOn = (lKeyCode == 16) ? true : false;
        }
        else if (document.getElementById) {
            // Netscape 6
            lKeyCode = pEvent.which;
            lShiftKeyOn = (lKeyCode == 16) ? true : false;
        }

        /*
        Upper case letters without the Shift key, CapsLock is on
        OR
        Lower case letters with the Shift key, CapsLock is on
        */
        if ((lKeyCode >= 65 && lKeyCode <= 90) || (lKeyCode >= 97 && lKeyCode <= 122)) {
            lCapsOn = (((lKeyCode >= 65 && lKeyCode <= 90) && !lShiftKeyOn) || ((lKeyCode >= 97 && lKeyCode <= 122) && lShiftKeyOn));
            lElement[lCapsOn ? 'show' : 'hide']();
            lElement.up()[lCapsOn ? 'addClassName' : 'removeClassName']('CapsLockOn');
        }
    }
}



/* 
End Of Section
MiWeb Client Java Runtime.
*/
