﻿// ----------------------------------------------------------------------------------------------------
// JAVASCRIPT LIBRARY FUNCTIONS
// ----------------------------------------------------------------------------------------------------

var myWin;
var background_input_normal;
var background_input_error;
var setElementFocus;

var DialogDisplay = { error: {}, warning: {}, info: {}, wait: {}, notes: {} };
var error_item = '<br />&nbsp;&nbsp;&nbsp;&nbsp;•&nbsp;&nbsp;&nbsp;&nbsp;'
var postcode_format = 'Please enter the postcode using the UK postcode format. <br /><br />The format of UK postcodes is generally:<br />'
postcode_format += '<br />&nbsp;&nbsp;•&nbsp;&nbsp;<b>A9 9AA</b><br />&nbsp;&nbsp;•&nbsp;&nbsp;<b>A99 9AA</b>'
postcode_format += '<br />&nbsp;&nbsp;•&nbsp;&nbsp;<b>A9A 9AA</b><br/>&nbsp;&nbsp;•&nbsp;&nbsp;<b>AA9 9AA</b>'
postcode_format += '<br/>&nbsp;&nbsp;•&nbsp;&nbsp;<b>AA99 9AA</b><br/>&nbsp;&nbsp;•&nbsp;&nbsp;<b>AA9A 9AA</b>'
postcode_format += '<br /><br />where A signifies a letter and 9 a digit. It is a hierarchical system, working from left to right - the first letter or pair of letters represents the area, the following digit or digits represent the district within that area, and so on. Each postcode generally represents a street, part of a street, or a single premises.<br />'
postcode_format += '<br />The part of the code before the space is the outward code while the part after the space is the inward code. The outward code can be split further into the area part (letters identifying one of 124 postal areas) and the district part (usually numbers); similarly, the inward code is split into the sector part (number) and the unit part (letters). Each postcode identifies the address to within 100 properties (with an average of 15 properties per postcode), although a large business may have a single code.'

// ----------------------------------------------------------------------------------------------------
// STRING MANIPULATION/FUNCTIONS
// ----------------------------------------------------------------------------------------------------
String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, "");
}
String.prototype.ltrim = function() {
    return this.replace(/^\s+/, "");
}
String.prototype.rtrim = function() {
    return this.replace(/\s+$/, "");
}

// ----------------------------------------------------------------------------------------------------
function ProperCase(field) {
    field.value = (field.value.substring(0, 1)).toUpperCase() + field.value.substring(1);   //Always Capitalise the first character
    field.value = Capitalize(field.value, ' ');           // caps after each space
    field.value = Capitalize(field.value, '\n');       // Carriage Return Line Feeds for addresses,etc.
    field.value = Capitalize(field.value, '-');          //  Montague-Smith
    field.value = Capitalize(field.value, '/');          //  Ian/Mary
    field.value = Capitalize(field.value, ' / ');        //  Ian / Mary 
    field.value = Capitalize(field.value, ',');          //  40 The Street,Bramley
    field.value = Capitalize(field.value, '.');          //  D.A.Brown
    field.value = Capitalize(field.value, '&');        //  Mr&Mrs
    field.value = Capitalize(field.value, '(');          //  Station Road (North)
    field.value = Capitalize(field.value, 'Mc');      //  McDougal
    field.value = Capitalize(field.value, 'Mac');   //  MacDougal
    field.value = Capitalize(field.value, ' Mc');     //  John McDougal
    field.value = Capitalize(field.value, ' Mac');  //  John McDougal
    field.value = Capitalize(field.value, " O'");    //  O'Brian
    //return field;
}

// ----------------------------------------------------------------------------------------------------
function Capitalize(field, CheckFor) {
    //joining words that will not have the first letter automatically capitalized
    var special_words = ' and of t/as t/a Macclesfield ';

    var o_split = field.split(CheckFor);
    for (i = 0; i < o_split.length; i++) {
        if (special_words.indexOf(o_split[i]) < 0) o_split[i] = (o_split[i].substring(0, 1)).toUpperCase() + o_split[i].substring(1);
    }
    retval = o_split.join(CheckFor);
    return retval;
}

// ----------------------------------------------------------------------------------------------------
function isValidEmail(email) {
    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return filter.test(email);
}

// ----------------------------------------------------------------------------------------------------
function validate_integer(el, ev, minimum, maximum) {
    return validate_field(el, ev, [/^\d+$/], [/^0\d/], minimum, maximum);
}

// ----------------------------------------------------------------------------------------------------
function validate_price(el, ev, minimum, maximum) {
    return validate_field(el, ev, [/^\d+(\.(\d{0,2})?)?$/], [], minimum, maximum);
}

// ----------------------------------------------------------------------------------------------------
function validate_field(el, ev, match_list, no_match_list, minimum, maximum) {
    if (!ev) ev = window.event;
    // preserve the start value for replacement in IE if the
    // user enters an invalid character
    var start_text = el.value;
    // allow backspace, deletion and arrow keys
    var keycode = get_keycode(ev);
    if (keycode == 8 || keycode == 9) {
        return true;
    }
    // the following unusual code correctly distinguises Mozilla 
    // char key presses from non-char keypresses (and also detects
    // when we get an IE keypress) which allows us to process chars
    // locally, but allow the browser to handle arrow/delete keys etc
    // (For some reason, trying to refer to ev.keyCode in the test
    // below breaks the Moz test, so we use document.selection instead
    // which is IE only)
    if (ev.which) {
        // it's a Mozilla keypress - process it here
        ;
    }
    else if (document.selection) {
        // it's an IE keypress - process it here
        ;
    }
    else {
        return true;
    }
    var key = String.fromCharCode(keycode);
    var cur_pos = cursor_pos(el);
    var new_value = insert_at_cursor(el, key);
    // does the new string match one of the 'must match' list ?
    var no_match = true;
    for (var i = 0; i < match_list.length; i++) {
        var regex = match_list[i];
        if (new_value.match(regex)) {
            no_match = false;
            break;
        }
    }
    if (no_match) {
        if (ev.keyCode) {
            // IE support - replace original value to erase illegal char
            // and reset cursor position    
            el.value = start_text;
            set_cursor_pos(el, cur_pos);
            ev.returnValue = false;
        }
        return false;
    }
    // does the new string fail to match the 'must not match' list ?
    for (var i = 0; i < no_match_list.length; i++) {
        var regex = no_match_list[i];
        if (new_value.match(regex)) {
            if (ev.keyCode) {
                // IE support - replace original value to erase illegal char
                // and reset cursor position    
                el.value = start_text;
                set_cursor_pos(el, cur_pos);
                ev.returnValue = false;
            }
            return false;
        }
    }
    if (ev.returnValue != false) {
        if (!isNaN(parseFloat(el.value)))

            if ((typeof minimum != "undefined") && (typeof maximum != "undefined")) {
            if ((parseFloat(el.value) < parseFloat(minimum)) || (parseFloat(el.value) > parseFloat(maximum))) {
                if (ev.keyCode) {
                    // IE support - replace original value to erase illegal char
                    // and reset cursor position    
                    el.value = start_text;
                    set_cursor_pos(el, cur_pos);
                    ev.returnValue = false;
                }
                return false;
            }
        }
    }

    if (ev.keyCode) {
        // IE support - ensure we don't insert the valid character again
        ev.returnValue = false;
        // Safari support 
        if (navigator.vendor) { if (navigator.vendor.toUpperCase().indexOf('APPLE') > -1) ev.returnValue = true };
        // Google Chrome support 
        if (navigator.vendor) { if (navigator.vendor.toUpperCase().indexOf('GOOGLE') > -1) ev.returnValue = true };
    }
    else {
        // Mozilla - just let the browser insert the valid character
        return true;
    }
}

// ----------------------------------------------------------------------------------------------------
function get_keycode(ev) {
    if (ev.keyCode) {
        return ev.keyCode;
    }
    else {
        return ev.which;
    }
}

// ----------------------------------------------------------------------------------------------------
function insert_at_cursor(el, str) {
    // IE support
    var new_value;
    if (document.selection) {
        el.focus();
        var sel = document.selection.createRange();
        sel.text = str;
        new_value = el.value;
        // without the following line, if a number is typed into the box when all the text is selected, the cursor is placed at the beginning of the text
        // i.e. 125000 becomes 000521  
        if (el.value.length == 1) set_cursor_pos(el, 2);
    }
    // Mozilla/Netscape support
    else if (el.selectionStart || el.selectionStart == '0') {
        var start_pos = el.selectionStart;
        var end_pos = el.selectionEnd;
        new_value = el.value.substring(0, start_pos) + str + el.value.substring(end_pos, el.value.length);
    }
    else {
        new_value += str;
    }
    return new_value;
}

// ----------------------------------------------------------------------------------------------------
function set_cursor_pos(el, cur_pos) {
    if (cur_pos == -1) return;
    el.focus();
    var rng = el.createTextRange();
    rng.move("Character", cur_pos - 1)
    rng.select();
}

// ----------------------------------------------------------------------------------------------------
function cursor_pos(el) {
    var i = el.value.length + 1;
    if (el.createTextRange) {
        var cursor = document.selection.createRange().duplicate();
        while (cursor.parentElement() == el
               && cursor.move("character", 1) == 1) {
            --i;
        }
    }
    return (i == el.value.length + 1) ? -1 : i;
}

// ----------------------------------------------------------------------------------------------------
function FormatNumber(num, decimalplaces) {
    try {
        num = parseFloat(num);
        var nStr = new String(num.toFixed(decimalplaces));
        nStr += '';
        x = nStr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
    }
    catch (exception) { AlertError("Format Number", e); }
    return x1 + x2;
}

// ----------------------------------------------------------------------------------------------------
// END OF STRING MANIPULATION/FUNCTIONS
// ----------------------------------------------------------------------------------------------------


// ----------------------------------------------------------------------------------------------------
// ELEMENT / BROWSER FUNCTIONS
// ----------------------------------------------------------------------------------------------------
function getElementText(Element) {
    if (Element.innerText != undefined) { return Element.innerText; }
    if (Element.textContent != undefined) { return Element.textContent; }
    if (Element.text != undefined) { return Element.text; }
    // Default...
    var regExp = /<\/?[^>]+>/gi;
    return Element.innerHTML.replace(regExp, '');
}

// ----------------------------------------------------------------------------------------------------
function setElementText(Element, textContent) {
    if (Element.innerHTML != undefined) { Element.innerHTML = textContent; return; }
    if (Element.innerText != undefined) { Element.innerText = textContent; return; }
    if (Element.textContent != undefined) { Element.textContent = textContent; return; }
    if (Element.text != undefined) { Element.text = textContent; return; }
    return;
}

// ----------------------------------------------------------------------------------------------------
function getElementById(tagName) {
    if (document.getElementById) {
        // Level 1 DOM code - Supported by: Mozilla, Explorer 5+, Opera 5+, Konqueror, Safari, iCab, Ice, OmniWeb 4.5
        if (document.getElementById(tagName) != null)
            return document.getElementById(tagName);
        else if (document.getElementById('ctl00$PageContent$' + tagName) != null)
            return document.getElementById('ctl00$PageContent$' + tagName);
        else if (document.getElementById('ctl00_PageContent_' + tagName) != null)
            return document.getElementById('ctl00_PageContent_' + tagName);
        else if (document.getElementById('ctl00_' + tagName) != null)
            return document.getElementById('ctl00_' + tagName);
    }
    else if (document.all) {
        // Microsoft DOM code - Supported by: Explorer 4+, Opera 6+, iCab, Ice, Omniweb 4.2-
        if (document.all[tagName] != null)
            return document.all[tagName];
        else if (document.all['ctl00$PageContent$' + tagName] != null)
            return document.all['ctl00$PageContent$' + tagName];
        else if (document.all['ctl00_PageContent_' + tagName] != null)
            return document.all['ctl00_PageContent_' + tagName];
        else if (document.all['ctl00_' + tagName] != null)
            return document.all['ctl00_' + tagName];
    }
    else if (document.layers) {
        // Netscape DOM code - Supported by: Netscape 4, Ice, Escape, Omniweb 4.2-
        if (document.layers[tagName] != null)
            return document.layers[tagName];
        else if (document.layers['ctl00$PageContent$' + tagName] != null)
            return document.layers['ctl00$PageContent$' + tagName];
        else if (document.layers['ctl00_PageContent_' + tagName] != null)
            return document.layers['ctl00_PageContent_' + tagName];
        else if (document.layers['ctl00_' + tagName] != null)
            return document.layers['ctl00_' + tagName];
    }
}

// ----------------------------------------------------------------------------------------------------
function setElementbackgroundColor(Element, backgroundColor) {
    //As we are using themes, cannot use CSS as the style is set directly into the HTML by ASP.Net which takes precedent
    //getElementById('txtUsername').className = 'error'
    Element.style.backgroundColor = backgroundColor;
}

// ----------------------------------------------------------------------------------------------------
function ResetAllElementsbackgroundColor() {
    var elem = document.forms[0].elements;
    for (var i = 0; i < elem.length; i++)
        if ((elem[i].type == 'text') || (elem[i].type == 'textarea') || (elem[i].type == 'select-one')) setElementbackgroundColor(elem[i], background_input_normal); //elem[i].style.backgroundColor = background_input_normal;
}

// ----------------------------------------------------------------------------------------------------
function getStyleObjectFromSelector(selectorText) {
    if (document.styleSheets) {
        for (var i = document.styleSheets.length - 1; i >= 0; i--) {
            var styleSheet = document.styleSheets[i];
            var rules;
            if (styleSheet.cssRules) {
                rules = styleSheet.cssRules;
            }
            else if (styleSheet.rules) {
                rules = styleSheet.rules;
            }
            if (rules) {
                for (var j = rules.length - 1; j >= 0; j--) {
                    //if (rules[j].selectorText == selectorText) {
                    if (rules[j].selectorText.toUpperCase() == selectorText.toUpperCase()) {
                        return rules[j].style;
                    }
                }
            }
        }
        alert('getStyleObjectFromSelector: Cannot find: ' + selectorText);
        return null;
    }
    else {
        alert('getStyleObjectFromSelector: document.styleSheets are not supported');
        return null;
    }
}

// ----------------------------------------------------------------------------------------------------
function openwindow(URL, height, width) {

    if (myWin) myWin.close();
    //Set the time out to 2 seconds as the error 'Member not found' appears 
    setTimeout("try {myWin.focus()} catch(e) {};", 2000);
    myWin = window.open(URL, null, 'scrollbars=yes,menubar=no,height=' + height + ',width=' + width + ',resizable=yes,toolbar=no,location=no,status=no');

    if (window.event != null) window.event.returnValue = 0;
}

// ----------------------------------------------------------------------------------------------------
function getRootURL() {
    //    return '/' + window.location.href.split(window.location.hostname)[1].split("/")[1] + '/';

    //    var url = document.location.toString(); //url
    //    var e_url = ''; //edited url
    //    var p = 0; //position
    //    var p2 = 0; //position 2
    //    p = url.indexOf("//");
    //    e_url = url.substring(p + 2);
    //    p2 = e_url.indexOf("/");
    //    return url.substring(0, p + p2 + 3);

    var baseURL = location.href;
    var rootURL = baseURL.substring(0, baseURL.indexOf('/', 7));

    // if the root url is localhost, don't add the directory as cassani doesn't use it
    if (baseURL.indexOf('localhost') == -1) {
        return rootURL + "/";
    }
    else {
        return rootURL + baseURL.substring(baseURL.indexOf('/', 8), baseURL.indexOf('/', baseURL.indexOf('/', 8) + 1)) + '/'
    }
}


// ----------------------------------------------------------------------------------------------------
function BrowserWidth() {
    if (typeof (window.innerWidth) == 'number') {
        //Non-IE
        return window.innerWidth;
    }
    else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        //IE 6+ in 'standards compliant mode'
        return document.documentElement.clientWidth;
    }
    else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        //IE 4 compatible
        return document.body.clientWidth;
    }
    return 0;
}

// ----------------------------------------------------------------------------------------------------
function BrowserHeight() {
    if (typeof (window.innerWidth) == 'number') {
        //Non-IE
        return window.innerHeight;
    }
    else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        //IE 6+ in 'standards compliant mode'
        return document.documentElement.clientHeight;
    }
    else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        //IE 4 compatible
        return document.body.clientHeight;
    }
    return 0;
}

// ----------------------------------------------------------------------------------------------------
function DocumentWidth() {
    if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        //IE 6+ in 'standards compliant mode'
        return document.documentElement.clientWidth;
    }
    else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        //IE 4 compatible
        return document.body.clientWidth;
    }
    return 0;
}

// ----------------------------------------------------------------------------------------------------
function DocumentHeight() {
    if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        return document.documentElement.clientHeight;
    }
    else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        return document.body.clientHeight;
    }
    return 0;
}

// ----------------------------------------------------------------------------------------------------
function scrollTop() {
    if (window.pageYOffset) {
        return window.pageYOffset;
    }
    else if (document.documentElement) {
        return document.documentElement.scrollTop;
    }
    else if (document.body) {
        return document.body.scrollTop;
    }
    return 0;
}

// ----------------------------------------------------------------------------------------------------
function scrollLeft() {
    if (window.pageXOffset) {
        return window.pageXOffset;
    }
    else if (document.documentElement) {
        return document.documentElement.scrollLeft;
    }
    else if (document.body) {
        return document.body.scrollLeft;
    }
    return 0;
}
// ----------------------------------------------------------------------------------------------------
// END OF ELEMENT / BROWSER FUNCTIONS
// ----------------------------------------------------------------------------------------------------

// ----------------------------------------------------------------------------------------------------
// DISPLAY DIALOG
// ----------------------------------------------------------------------------------------------------
function DisplayDialog(error, Dialog) {

    getStyleObjectFromSelector('div.Information').width = '500px';
    getElementById('div_Information').style.display = 'block';
    try {
        getElementById('div_Information_Notes').style.display = 'none';
    } 
        catch (e) { };

    switch (Dialog) {
        case DialogDisplay.error:
            getStyleObjectFromSelector('#div_Information_Box').color = getStyleObjectFromSelector('#div_Information_Box_Error').color;
            getStyleObjectFromSelector('#div_Information_Box .sb-inner').color = getStyleObjectFromSelector('#div_Information_Box_Error').color;
            getStyleObjectFromSelector('#div_Information_Box').backgroundColor = getStyleObjectFromSelector('#div_Information_Box_Error').backgroundColor;
            getStyleObjectFromSelector('#div_Information_Box .sb-inner').backgroundColor = getStyleObjectFromSelector('#div_Information_Box_Error').backgroundColor;
            getElementById('imgIcon').src = getRootURL() + 'Images/Windows-Error.png';
            break;
        case DialogDisplay.warning:
            getStyleObjectFromSelector('#div_Information_Box').backgroundColor = getStyleObjectFromSelector('#div_Information_Box_Warning').backgroundColor;
            getStyleObjectFromSelector('#div_Information_Box .sb-inner').backgroundColor = getStyleObjectFromSelector('#div_Information_Box_Warning').backgroundColor;
            getElementById('imgIcon').src = getRootURL() + 'Images/Windows-Warning.png';
            break;
        case DialogDisplay.info:
            getStyleObjectFromSelector('#div_Information_Box').color = getStyleObjectFromSelector('#div_Information_Box_Info').color;
            getStyleObjectFromSelector('#div_Information_Box .sb-inner').color = getStyleObjectFromSelector('#div_Information_Box_Info').color;
            getStyleObjectFromSelector('#div_Information_Box').backgroundColor = getStyleObjectFromSelector('#div_Information_Box_Info').backgroundColor;
            getStyleObjectFromSelector('#div_Information_Box .sb-inner').backgroundColor = getStyleObjectFromSelector('#div_Information_Box_Info').backgroundColor;
            getElementById('imgIcon').src = getRootURL() + 'Images/Windows-Info.png';
            getStyleObjectFromSelector('div.Information').width = '700px';
            break;
        case DialogDisplay.wait:
            getElementById('div_Information_Box_Close').style.display = 'none';
            getStyleObjectFromSelector('#div_Information_Box').color = getStyleObjectFromSelector('#div_Information_Box_Wait').color;
            getStyleObjectFromSelector('#div_Information_Box .sb-inner').color = getStyleObjectFromSelector('#div_Information_Box_Wait').color;
            getStyleObjectFromSelector('#div_Information_Box').backgroundColor = getStyleObjectFromSelector('#div_Information_Box_Wait').backgroundColor;
            getStyleObjectFromSelector('#div_Information_Box .sb-inner').backgroundColor = getStyleObjectFromSelector('#div_Information_Box_Wait').backgroundColor;
            getElementById('imgIcon').src = getRootURL() + 'Images/Windows-Wait.gif';
            break;
        case DialogDisplay.notes:
            getStyleObjectFromSelector('#div_Information_Box').color = getStyleObjectFromSelector('#div_Information_Box_Info').color;
            getStyleObjectFromSelector('#div_Information_Box .sb-inner').color = getStyleObjectFromSelector('#div_Information_Box_Info').color;
            getStyleObjectFromSelector('#div_Information_Box').backgroundColor = getStyleObjectFromSelector('#div_Information_Box_Info').backgroundColor;
            getStyleObjectFromSelector('#div_Information_Box .sb-inner').backgroundColor = getStyleObjectFromSelector('#div_Information_Box_Info').backgroundColor;
            getStyleObjectFromSelector('div.Information').width = '700px';
            getElementById('div_Information').style.display = 'none';
            getElementById('div_Information_Notes').style.display = 'block';
            getElementById('txtInformation_Notes').value = getElementById('hfldInformation_Notes').value;
            break;
        default: break;
    }

    // Set the modal height to be the whole of the page
    getElementById('div_Disabled').style.height = DocumentHeight() + 'px';
    getElementById('div_Disabled').style.display = 'block';

    getElementById('tblInformation').rows[0].cells[1].innerHTML = error;

    //get width and height of display area
    vpWidth = BrowserWidth();
    vpHeight = BrowserHeight();

    //display the object so that the offset width and height are set
    getElementById('div_Information_Box').style.display = "block";

    var myBorder = RUZEE.ShadedBorder.create({ corner: 8, shadow: 16 });
    myBorder.render(getElementById('div_Information_Box').id);

    //get dialog's width and height
    dialogWidth = getElementById('div_Information_Box').offsetWidth;
    dialogHeight = getElementById('div_Information_Box').offsetHeight;

    //calculate position
    dialogTop = (vpHeight / 2) - (dialogHeight / 2);
    dialogLeft = (vpWidth / 2) - (dialogWidth / 2);

    //incorporate the position of the page in relation to the vertical scroll
    dialogTop += scrollTop();
    dialogLeft += scrollLeft();

    //Position the Dialog
    getElementById('div_Information_Box').style.top = dialogTop + "px";
    getElementById('div_Information_Box').style.left = dialogLeft + "px";

    try {
        switch (Dialog) {
            case DialogDisplay.notes:
                getElementById('txtInformation_Notes').focus();
                break;
            default:
                getElementById('button_Information_Close').focus();
                break;
        }
    }
    catch (e) { };
}

// ----------------------------------------------------------------------------------------------------
function CloseDialogDisplay() {
    getElementById('div_Information_Box').style.display = 'none';
    getElementById('div_Disabled').style.display = 'none';
    getElementById(setElementFocus).focus();
    return false;
}

// ----------------------------------------------------------------------------------------------------
function CloseDialogDisplay_Notes() {
    getElementById('hfldInformation_Notes').value = getElementById('txtInformation_Notes').value;
}
// ----------------------------------------------------------------------------------------------------
// END OF DISPLAY DIALOG
// ----------------------------------------------------------------------------------------------------



// ----------------------------------------------------------------------------------------------------
// POST CODE FUNCTIONS
// ----------------------------------------------------------------------------------------------------
// PostcodeValidation calls PostcodeLookup if the postcode is valid (and Lookup flag set)
// PostcodeLookup requests a response from AJAXRequest.aspx?Request=LookUpPostcode&Postcode=
// A response is sent and is captured in AJAX.js HandleResponse() which calls SendResponse(XmlHttp.responseXML.documentElement);
// SendResponse(Node) (in .aspx file) calls PostcodePopulate which fills txt.._Address
// PostcodeComplete is called when txt.._NameNumber loses focus

// ----------------------------------------------------------------------------------------------------
function PostcodeLength(Postcode) {
    //Do not allow the input of more than 8 characters
    return Postcode.value.length <= 8;
}

// ----------------------------------------------------------------------------------------------------
function PostcodeValidation(Postcode, Address, div_Address, LookUp, DisplayWarningDialog) {
    //var pcodeRegxp = /^([A-PR-UWYZ0-9][A-HK-Y0-9][ACDEFGHJKMNPRTUVXY0-9]?[ABEFGHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJKLN-UW-Z]{2}|GIR 0AA)$/;
    //var pcodeRegxp = /^([A-Z0-9][A-Z0-9][A-Z0-9]?[A-Z0-9]? {1,2}[0-9][A-Z]{2}|GIR 0AA)$/;

    //From http://en.wikipedia.org/wiki/Postal_codes_in_the_United_Kingdom
    //full checking of all the stated BS 7666 postcode format rules
    //var pcodeRegxp = /^(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW]) [0-9][ABD-HJLNP-UW-Z]{2})$/;
    //The BS 7666 rules do not match British Forces Post Office postcodes, which have the format "BFPO NNN" or "BFPO c/o NNN", where NNN is 1 to 4 numerical digits.
    //var pcodeRegxp = /^(GIR 0AA)|((([A-Z-[QVX]][0-9][0-9]?)|(([A-Z-[QVX]][A-Z-[IJZ]][0-9][0-9]?)|(([A-Z-[QVX]][0-9][A-HJKSTUW])|([A-Z-[QVX]][A-Z-[IJZ]][0-9][ABEHMNPRVWXY])))) [0-9][A-Z-[CIKMOV]]{2})$/;
    //Alternative short regular expression from BS7666 Schema is:
    var pcodeRegxp = /^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$/;

    var objAddress = getElementById(Address);
    var objPostcode = getElementById(Postcode);
    setElementFocus = objPostcode.id;
    if (objPostcode.value.trim() != '') {
        objPostcode.value = objPostcode.value.toUpperCase();
        if (!pcodeRegxp.test(objPostcode.value)) {
            if (DisplayWarningDialog) DisplayDialog(postcode_format, DialogDisplay.error);
        }
        else if (LookUp) {
            PostcodeLookup(Postcode, Address, div_Address);
        }
    }
}

// ----------------------------------------------------------------------------------------------------
function PostcodeLookup(Postcode, Address, div_Address) {
    var objAddress = getElementById(Address);
    var objPostcode = getElementById(Postcode);
    var objhfldPostcode = getElementById('hfld' + Postcode.substring(3, Postcode.length));
    //Check if the postcode is not blank, has changed or the address is blank
    if (((objPostcode.value.trim() != '') && (objPostcode.value.trim() != objhfldPostcode.value)) || (objAddress.value.trim() == '')) {
        //If the postcode has changed redisplay the buildings name/number and hide address
        if (objPostcode.value.trim() != objhfldPostcode.value.trim()) {
            var objDiv_Address_NameNumber = getElementById(div_Address + '_NameNumber');
            if (objDiv_Address_NameNumber.style.display == 'none') {
                var objDiv_Address_Address = getElementById(div_Address + '_Address');
                objDiv_Address_NameNumber.style.display = 'block';
                getElementById('txt' + div_Address.substring(4) + '_NameNumber').focus();
                objDiv_Address_Address.style.display = 'none';
                showhide(objDiv_Address_NameNumber.id, true);
            }
        }
        RequestResponse('Request=LookUpPostcode&PostcodeTextbox=' + Postcode + '&AddressTextbox=' + Address + '&Postcode=' + escape(objPostcode.value));
    }
    objhfldPostcode.value = objPostcode.value;
}

// ----------------------------------------------------------------------------------------------------
function PostcodePopulate(Node) {
    var Credits = "", LINE1 = "", LINE2 = "", LINE3 = "", TOWN = "", COUNTY = "", POSTCODE = "", COUNTRY = "";
    var FoundRecord = true;
    var Address = "";
    var Postcode = "";

    try {
        xmlRoot = Node;

        if ((xmlRoot.getElementsByTagName("AddressTextbox").length > 0) && (xmlRoot.getElementsByTagName("AddressTextbox").item(0).childNodes.length)) Address = xmlRoot.getElementsByTagName("AddressTextbox").item(0).firstChild.data;
        if ((xmlRoot.getElementsByTagName("PostcodeTextbox").length > 0) && (xmlRoot.getElementsByTagName("PostcodeTextbox").item(0).childNodes.length)) Postcode = xmlRoot.getElementsByTagName("PostcodeTextbox").item(0).firstChild.data;

        var objAddress = getElementById(Address);
        var objhfldPostcode = getElementById('hfld' + Postcode.substring(3, Postcode.length));
        objhfldPostcode.value = getElementById(Postcode).value;

        if ((xmlRoot.getElementsByTagName("message").length > 0) && (xmlRoot.getElementsByTagName("message").item(0).childNodes.length)) FoundRecord = (xmlRoot.getElementsByTagName("message").item(0).firstChild.text.indexOf('Cannot find record') < 0);
        if ((xmlRoot.getElementsByTagName("credits_display_text").length > 0) && (xmlRoot.getElementsByTagName("credits_display_text").item(0).childNodes.length)) Credits = xmlRoot.getElementsByTagName("credits_display_text").item(0).firstChild.data;
        if ((xmlRoot.getElementsByTagName("line1").length > 0) && (xmlRoot.getElementsByTagName("line1").item(0).childNodes.length)) LINE1 = xmlRoot.getElementsByTagName("line1").item(0).firstChild.data;
        if ((xmlRoot.getElementsByTagName("line2").length > 0) && (xmlRoot.getElementsByTagName("line2").item(0).childNodes.length)) LINE2 = xmlRoot.getElementsByTagName("line2").item(0).firstChild.data;
        if ((xmlRoot.getElementsByTagName("line3").length > 0) && (xmlRoot.getElementsByTagName("line3").item(0).childNodes.length)) LINE3 = xmlRoot.getElementsByTagName("line3").item(0).firstChild.data;
        if ((xmlRoot.getElementsByTagName("town").length > 0) && (xmlRoot.getElementsByTagName("town").item(0).childNodes.length)) TOWN = xmlRoot.getElementsByTagName("town").item(0).firstChild.data;
        if ((xmlRoot.getElementsByTagName("county").length > 0) && (xmlRoot.getElementsByTagName("county").item(0).childNodes.length)) COUNTY = xmlRoot.getElementsByTagName("county").item(0).firstChild.data;
        if ((xmlRoot.getElementsByTagName("postcode").length > 0) && (xmlRoot.getElementsByTagName("postcode").item(0).childNodes.length)) POSTCODE = xmlRoot.getElementsByTagName("postcode").item(0).firstChild.data;
        if ((xmlRoot.getElementsByTagName("country").length > 0) && (xmlRoot.getElementsByTagName("country").item(0).childNodes.length)) COUNTRY = xmlRoot.getElementsByTagName("country").item(0).firstChild.data;
    }
    catch (e) { }

    if (LINE1.trim() != '') objAddress.value = LINE1.trim() + 'CRLF';
    if (LINE2.trim() != '') objAddress.value += LINE2.trim() + 'CRLF';
    if (LINE3.trim() != '') objAddress.value += LINE3.trim() + 'CRLF';
    if (TOWN.trim() != '') objAddress.value += TOWN.trim() + 'CRLF';
    if (COUNTY.trim() != '') objAddress.value += COUNTY.trim() + 'CRLF';
    //Strip off the last new line
    //a new line is \r\n in ie, but just \n in FF.

    if (objAddress.value.length > 1) {
        //if (objAddress.value.substring(objAddress.value.length - 1) == '\n') objAddress.value = objAddress.value.substring(0, objAddress.value.length - 2);
        objAddress.value = objAddress.value.substring(0, objAddress.value.lastIndexOf('CRLF'));
        objAddress.value = objAddress.value.replace(/CRLF/g, '\n');
    }
    return FoundRecord;
}

// ----------------------------------------------------------------------------------------------------
function PostcodeComplete(Address_NameNumber, Address, div_Address) {
    //There are three divs: <div id="div_Address">, <div id="div_Address_NameNumber">, <div id="div_Address_Address">
    // <div id="div_Address_NameNumber"> and <div id="div_Address_Address"> are mutually exclusive
    var objAddress = getElementById(Address);
    var objhfldAddress = getElementById('hfld' + Address.substring(3, Address.length));
    //Check that an address record has been found
    //if (objAddress.value.trim() != '') {
    //Check if the buildings name/number contains a number
    if (Address_NameNumber.value.match(/\d+/)) {
        objAddress.value = Address_NameNumber.value + ' ' + objAddress.value;
    }
    else {
        objAddress.value = Address_NameNumber.value + '\n' + objAddress.value;
    }
    //Strip off the last new line
    if (objAddress.value.length > 1) { if (objAddress.value.substring(objAddress.value.length - 1) == '\n') objAddress.value = objAddress.value.substring(0, objAddress.value.length - 1); }
    Address_NameNumber.value = '';
    getElementById(div_Address + '_NameNumber').style.display = 'none';
    getElementById(div_Address + '_Address').style.display = 'block';
    objAddress.focus();
    //Set the cursor to the end of the text
    objAddress.value = objAddress.value;
}
// ----------------------------------------------------------------------------------------------------
// END OF POST CODE FUNCTIONS
// ----------------------------------------------------------------------------------------------------

function MenuItemClick(NavigateURL) {
    window.location.href = NavigateURL;
}
// ----------------------------------------------------------------------------------------------------

function getAge(comparedate, dateString) {
    var now;
    if (!isDate(comparedate)) now = new Date(); else now = new Date(comparedate.substring(6, 10), comparedate.substring(3, 5) - 1, comparedate.substring(0, 2));
    var yearNow = now.getFullYear();
    var monthNow = now.getMonth();
    var dateNow = now.getDate();

    var dob = new Date(dateString.substring(6, 10), dateString.substring(3, 5) - 1, dateString.substring(0, 2));
    var yearDob = dob.getFullYear();
    var monthDob = dob.getMonth();
    var dateDob = dob.getDate();

    yearAge = yearNow - yearDob;

    if (monthNow >= monthDob)
        var monthAge = monthNow - monthDob;
    else {
        yearAge--;
        var monthAge = 12 + monthNow - monthDob;
    }
    if (dateNow >= dateDob)
        var dateAge = dateNow - dateDob;
    else {
        monthAge--;
        var dateAge = 31 + dateNow - dateDob;
        if (monthAge < 0) {
            monthAge = 11;
            yearAge--;
        }
    }
    return yearAge;
}

// ----------------------------------------------------------------------------------------------------
function isDate(dateString) {
    //var dateRegxp = new RegExp('(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d');
    var dateRegxp = /^(0[1-9]|[12]\d|3[01])\/(0[1-9]|1[012])\/\d{4}$/;
    return dateRegxp.test(dateString);
}

// ----------------------------------------------------------------------------------------------------
function Validate_Date(DatetoValidate, DisplayWarningDialog) {
    setElementFocus = DatetoValidate.id;

    if (!isDate(DatetoValidate.value)) {
        if (DisplayWarningDialog) DisplayDialog('Please enter the date using the following format: dd/mm/yyyy', DialogDisplay.error);
        return false;
    }
    else {
        var day = DatetoValidate.value.substring(0, 2);
        var month = DatetoValidate.value.substring(3, 5) - 1;
        var year = DatetoValidate.value.substring(6, 10);
        var datetocheck = new Date(year, month, day);

        if ((year != datetocheck.getFullYear()) || (month != datetocheck.getMonth()) || (day != datetocheck.getDate())) {
            if (DisplayWarningDialog) DisplayDialog('The date entered is not valid. Please check the date, especially the day of the month and re-enter.', DialogDisplay.error);
            return false;
        }

        return true;
    }
}
// ----------------------------------------------------------------------------------------------------

function validate_date(el, ev, minimum, maximum) {
    //regexpression to be completed
    return validate_field(el, ev);
}
// ----------------------------------------------------------------------------------------------------

function addZero(vNumber) {
    return ((vNumber < 10) ? "0" : "") + vNumber
}

// ----------------------------------------------------------------------------------------------------
function formatDate(vDate, vFormat) {
    var vDay = addZero(vDate.getDate());
    var vMonth = addZero(vDate.getMonth() + 1);
    var vYearLong = addZero(vDate.getFullYear());
    var vYearShort = addZero(vDate.getFullYear().toString().substring(3, 4));
    var vYear = (vFormat.indexOf("yyyy") > -1 ? vYearLong : vYearShort)
    var vHour = addZero(vDate.getHours());
    var vMinute = addZero(vDate.getMinutes());
    var vSecond = addZero(vDate.getSeconds());
    var vDateString = vFormat.replace(/dd/g, vDay).replace(/MM/g, vMonth).replace(/y{1,4}/g, vYear)
    vDateString = vDateString.replace(/hh/g, vHour).replace(/mm/g, vMinute).replace(/ss/g, vSecond)
    return vDateString
}

// ----------------------------------------------------------------------------------------------------
function navigateWithReferrer(url) {
    var fakeLink = document.createElement("a");
    if (typeof (fakeLink.click) == 'undefined')
        location.href = url; // sends referrer in FF, not in IE
    else {
        fakeLink.href = url;
        document.body.appendChild(fakeLink);
        fakeLink.click(); // click() method defined in IE only
    }
}
// ----------------------------------------------------------------------------------------------------

