﻿var areaDropdownClientId = false, townDropdownClientId = false, streetDropdownClientId = false, unitDropdownClientId = false, faultTypeDropdownClientId = false;
var areaIdTextBoxClientId = false, townIdTextBoxClientId = false, streetIdTextBoxClientId = false, unitIdTextBoxClientId = false, btnUpdateClientId = false;
var IsMSIE6 = false, IsMSIE = false, IsSafari = false, IsOpera = false, BrowserCompatibleChecked = false;
var isMobile = false;

function CheckForMSIE6() { if (navigator.userAgent.indexOf('MSIE 6') != -1 && navigator.userAgent.indexOf('compatible') != -1 && navigator.userAgent.indexOf('opera') == -1) IsMSIE6 = true; else IsMSIE6 = false; }
function CheckForMSIE() { if (navigator.userAgent.indexOf('MSIE') != -1 && navigator.userAgent.indexOf('compatible') != -1 && navigator.userAgent.indexOf('opera') == -1) IsMSIE = true; else IsMSIE = false; }
function CheckForSafari() { if (navigator.userAgent.indexOf('AppleWebKit') != -1 && navigator.userAgent.indexOf('opera') == -1) IsSafari = true; else IsSafari = false; }
function CheckForOpera() { if (navigator.userAgent.indexOf('opera') != -1) IsOpera = true; else IsOpera = false; }
function IsBrowserCompatible() { if (BrowserCompatibleChecked == true) return true; BrowserCompatibleChecked = true; CheckForMSIE6(); CheckForMSIE(); CheckForSafari(); CheckForOpera(); return true; }

function processStartUpParams(setCenterAndZoom) {

    var searchField = document.getElementById("tbSearch");

    if (!getQueryVariable("StreetlightId") && getQueryVariable("pCallCentreMode") == "1" && (getQueryVariable("pStreet") || getQueryVariable("pTown") || getQueryVariable("pPostcode") || getQueryVariable("pUnitReference"))) {
        searchField.value = decodeURIComponent(getQueryVariable("pUnitReference"));
        document.getElementById("asStreet").value = decodeURIComponent(getQueryVariable("pStreet"));
        document.getElementById("asTown").value = decodeURIComponent(getQueryVariable("pTown"));
        document.getElementById("asPostcode").value = decodeURIComponent(getQueryVariable("pPostcode"));
        Lookup();
        return;
    }

    if (getQueryVariable("StreetlightId")) ActiveStreetLightId = getQueryVariable("StreetlightId");
    if (getQueryVariable("pUnitReference") && getQueryVariable("pUnitReference").length > 2 && !(getQueryVariable("StreetlightId") && getQueryVariable("pLatitude") && getQueryVariable("pLongitude"))) {
        searchField.value = decodeURIComponent(getQueryVariable("pUnitReference"));
        Lookup();
    } else if (getQueryVariable("pEasting") && getQueryVariable("pNorthing")) {
        setCenterAndZoom(getQueryVariable("pEasting"), getQueryVariable("pNorthing"), true);
    } else if (getQueryVariable("pLatitude") && getQueryVariable("pLongitude")) {
        setCenterAndZoom(getQueryVariable("pLatitude"), getQueryVariable("pLongitude"));
    } else if (getQueryVariable("pPostCode")) {
        searchField.value = decodeURIComponent(getQueryVariable("pPostCode"));
        Lookup();
    } else if (readCookie("PostalCode") && readCookie("PostalCode").indexOf("anon") < 0 && IsAdmin != true) {
        if (getQueryVariable("pCallCentreMode") == "1")
            document.getElementById("asPostcode").value = readCookie("PostalCode");
        else
            searchField.value = readCookie("PostalCode");
        Lookup();
    }

    //    if (navigator.geolocation) {
    //        navigator.geolocation.getCurrentPosition(foundLocation, noLocation);
    //    } else noLocation();
}

function foundLocation(position) {
    var lat = position.coords.latitude;
    var lon = position.coords.longitude;
    var ac = position.coords.accuracy;
    alert('Found location: ' + lat + ', ' + lon + ', ' + ac);
}

function noLocation() {
    alert('Could not find location');
}

var aniItems = new Object();
function ShowFaq(elid) {
    var el = document.getElementById(elid);
    if (el.style.display != "none") animateHideItem(elid); else animateShowItem(elid);
}
function animateHideItem(elid) {
    if (aniItems[elid]) clearTimeout(aniItems[elid]);
    fadeOut(elid);
}
function animateShowItem(elid) {
    aniItems[elid] = setTimeout(function() {
        aniItems[elid] = null;
        fadeIn(elid);
    }, 0);
}
function fade(eID, startOpacity, stopOpacity, duration) {
    var speed = Math.round(duration / 100);
    var timer = 0;
    if (startOpacity < stopOpacity) { // fade in
        for (var i = startOpacity; i <= stopOpacity; i++) {
            setTimeout("setOpacity('" + eID + "'," + i + ")", timer * speed);
            timer++;
        } return;
    }
    for (var i = startOpacity; i >= stopOpacity; i--) { // fade out
        setTimeout("setOpacity('" + eID + "'," + i + ")", timer * speed);
        timer++;
    }
}

function getElm(eID) { return document.getElementById(eID); }
function show(eID) { getElm(eID).style.display = 'block'; }
function hide(eID) { getElm(eID).style.display = 'none'; }
function fadeIn(eID) {
    setOpacity(eID, 0); show(eID); var timer = 0;
    for (var i = 1; i <= 100; i++) {
        setTimeout("setOpacity('" + eID + "'," + i + ")", timer * 5);
        timer++;
    }
}
function fadeOut(eID) {
    var timer = 0;
    for (var i = 100; i >= 1; i--) {
        setTimeout("setOpacity('" + eID + "'," + i + ")", timer * 3);
        timer++;
    }
    setTimeout("hide('" + eID + "')", 310);
}

function setOpacity(eID, opacityLevel) {
    var eStyle = document.getElementById(eID).style;
    eStyle.opacity = opacityLevel / 100;
    eStyle.filter = 'alpha(opacity=' + opacityLevel + ')';
}

var curActiveUnit;
function redirectToForm(unitID, dontRedirect) {
    if (getQueryVariable("pCallCentreMode") == "1" && ActiveStreetLightId) {
        //if(dontRedirect!=true) redirectCarryParams("ReportAccessible.aspx", "StreetlightId=" + sid);
        curActiveUnit = ActiveStreetLightId
        ShowHistoryAlt();
        return true;
    } else return false;
}

function ShowHistoryAlt() {
    document.getElementById("divFaultHistoryAlt").style.display = "block";
    document.getElementById("divFaultHistoryAltData").innerHTML = '<div style="padding: 15px;"><b>Please wait, gathering data... </b><img src="../Images/loading.gif" /></div>';
    var url = AppRoot + '/Public/Services/LightHistory.ashx?unitDetail=1&i=' + ActiveStreetLightId;
    makeRequest(url, '', function(http_response, customData) {
        if (http_response.readyState == 4) {
            if (http_response.status == 200) {
                var d = http_response.responseXML.documentElement;
                var data = d.textContent ? d.textContent : d.text;
                document.getElementById("divFaultHistoryAltData").innerHTML = data;
            }
        }
    });
}

function ShowHistoryA(StreetLightId) {
    if (!StreetLightId || StreetLightId < 1) return;
    document.getElementById("PoppedHistoryData").innerHTML = '<div style="padding: 15px;"><b>Please wait, gathering data... </b><img src="../Images/loading.gif" /></div>';
    var url = AppRoot + '/Public/Services/LightHistory.ashx?count=5&i=' + StreetLightId;
    makeRequest(url, '', function(http_response, customData) {
        if (http_response.readyState == 4) {
            if (http_response.status == 200) {
                var d = http_response.responseXML.documentElement;
                var data = d.textContent ? d.textContent : d.text;
                document.getElementById("PoppedHistoryData").innerHTML = data;
            }
        }
    });
}

function redirectCarryParams(url, insertParams, ignore) {
    //if (IsAdmin == true && url == "TrackFaultReport.aspx") url = "../Public/TrackFaultReport.aspx";
    if (!ignore) ignore = ""; if (!insertParams) insertParams = "";
    var query = insertParams + "&" + window.location.search.substring(1);
    var vars = query.split("&"), done = new Array(), finalurl = "";
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        var found = false;
        for (var j = 0; j < done.length; j++) {
            found = found || (pair[0].toLowerCase() == done[j].toLowerCase()) || ignore.toLowerCase().indexOf(pair[0].toLowerCase()) >= 0;
        }
        if (found != true) {
            finalurl += vars[i] + "&";
            done.push(pair[0]);
        }
    }
    if (finalurl.length > 0) {
        finalurl = finalurl.replace(/&&/g, "&");
        if (finalurl[0] == "&") finalurl = finalurl.substring(1);
        if (finalurl[finalurl.length - 1] == "&") finalurl = finalurl.substring(0, finalurl.length - 1);
    }
    window.location = url + "?" + finalurl;
}

function validateReportFaultForm() {
    var ddl = document.getElementById(faultTypeDropdownClientId);
    if ((ddl.options[ddl.selectedIndex].value == '999' || ddl.options[ddl.selectedIndex].value == '3') && getQueryVariable("pCallCentreMode") != 1) {
        ShowCoverAll('EmergencyHotline');
        return false;
    }
    return true;
}

function MaxMapHeight() {
    IsBrowserCompatible();
    var h = document.getElementById("leftColumn");
    var m = document.getElementById("map");
    var l = document.getElementById("loading");
    //m.parentNode.parentNode.style.height = (h.clientHeight - (IsMSIE ? 28 : 25)) + "px";
    m.parentNode.style.height = (h.clientHeight - (IsMSIE ? 28 : 25)) + "px";
    m.style.height = (h.clientHeight - (IsMSIE ? 53 : 49)) + "px";
    l.style.height = m.style.height;
}

function MaxMap() {
    IsBrowserCompatible();
    var widthOffset = IsMSIE ? 269 : 264; //30 : 7;
    widthOffset = isMobile ? (IsMSIE ? 30 : 2) : widthOffset;
    var heightOffset = IsMSIE ? 58 : 53;
    //document.body.style.margin = "0pt 3px 0pt 0pt";
    document.getElementById("leftColumn").style.margin = "";
    var m = document.getElementById("map");
    m.parentNode.style.height = (document.documentElement.clientHeight - heightOffset + 24) + "px";
    m.style.height = (document.documentElement.clientHeight - heightOffset) + "px";
    //m.parentNode.parentNode.style.width = "100%";
    m.parentNode.style.width = "";
    m.style.width = (document.documentElement.clientWidth - widthOffset) + "px"; //(m.parentNode.clientWidth - widthOffset) + "px";
    var l = document.getElementById("loading");
    l.style.height = m.style.height;
    l.style.width = m.clientWidth + "px";
    MapFullscreen = true;
}

function setCookie(c_name, value, expiredays) {
    var exdate = new Date(); exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) +
((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

function makeRequest(url, parameters, callback) {
    var xmlhttp_request = false;
    if (window.XMLHttpRequest) { // Mozilla, Safari, IE7...
        xmlhttp_request = new XMLHttpRequest();
        if (xmlhttp_request.overrideMimeType) {
            xmlhttp_request.overrideMimeType('text/xml');
        }
    }
    else if (window.ActiveXObject) { // IE6
        try {
            xmlhttp_request = new ActiveXObject("MSXML2.XMLHTTP.3.0");
        } catch (e) {
            try {
                xmlhttp_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) { }
        }
    }
    if (!xmlhttp_request) {
        alert('Cannot create XMLHTTP instance');
        return false;
    }
    xmlhttp_request.onreadystatechange = function() { callback(xmlhttp_request, parameters); }
    xmlhttp_request.open('GET', url, true);
    xmlhttp_request.send(null);
}

function sendData(url, data, callback) {
    var xmlhttp_request = false;
    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        xmlhttp_request = new XMLHttpRequest();
        if (xmlhttp_request.overrideMimeType) {
            xmlhttp_request.overrideMimeType('text/xml');
        }
    } else if (window.ActiveXObject) { // IE
        try {
            xmlhttp_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                xmlhttp_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) { }
        }
    }
    if (!xmlhttp_request) {
        alert('Cannot create XMLHTTP instance');
        return false;
    }
    xmlhttp_request.onreadystatechange = function() { callback(xmlhttp_request, ''); }
    xmlhttp_request.open('POST', url, true);
    xmlhttp_request.send(data);
}

var doneAppLoadSelectUnit = false;
function unitSuccess(http_request, customData) {
    if (http_request.readyState == 4) {
        if (http_request.status == 200) {
            //alert(http_request.responseText);
            var xmldoc = http_request.responseXML;
            var unitList = false;
            var unitDropdown = false;
            if (xmldoc.getElementsByTagName("streetlights").length > 0) { unitList = xmldoc.getElementsByTagName("streetlights")[0]; }
            if (unitList) {
                unitDropdown = document.getElementById(unitDropdownClientId);
                if (unitDropdown) {
                    while (unitDropdown.options.length > 0) {
                        try { unitDropdown.options[0] = null; } catch (e) { };
                    }
                    var rOption = document.createElement("OPTION");
                    rOption.innerHTML = "-- Select a unit --";
                    rOption.value = "";
                    unitDropdown.appendChild(rOption);
                    for (var iUni = 0; iUni < unitList.childNodes.length; iUni++) {
                        var unit = unitList.childNodes[iUni];
                        if (unit.nodeName == "streetlight") {
                            var oOption = document.createElement("OPTION");
                            oOption.innerHTML = unit.getAttribute("unitref") + " - " + unit.getAttribute("Description");
                            oOption.value = unit.getAttribute("id");
                            unitDropdown.appendChild(oOption);
                        }
                    }

                    //process query params
                    if (getQueryVariable("pUnitReference") && doneAppLoadSelectUnit != true) {
                        doneAppLoadSelectUnit = true;
                        selectItem(unitDropdown, getQueryVariable("pUnitReference") + " - ", unitChanged, true);
                    }

                }
                else {
                    //alert('Unit dropdown not defined!');
                }
            }
        } else {
            //alert('There was a problem with the request, please try again.');
        }
    }
}

var doneAppLoadSelectStreet = false;
function streetListSuccess(http_request, customData) {
    if (http_request.readyState == 4) {
        if (http_request.status == 200) {

            var streetDropdown = document.getElementById(streetDropdownClientId);
            if (streetDropdown) {
                while (streetDropdown.options.length > 0) {
                    try { streetDropdown.options[0] = null; } catch (e) { };
                }
            } else {
                //alert('Street dropdown not defined!');
                return;
            }

            var xmldoc = http_request.responseXML;
            var streetList = xmldoc.getElementsByTagName("street");
            if (streetList.length > 0) {
                var rOption = document.createElement("OPTION");
                rOption.innerHTML = "-- Select a street --";
                rOption.value = "";
                streetDropdown.appendChild(rOption);
                for (var iStr = 0; iStr < streetList.length; iStr++) {
                    var street = streetList[iStr];
                    var oOption = document.createElement("OPTION");
                    if (parseInt(getCookie("StreetId")) == parseInt(street.getAttribute("id"))) { oOption.selected = true; changeStreet(street.getAttribute("id")); }
                    oOption.innerHTML = street.getAttribute("name");
                    oOption.value = street.getAttribute("id");
                    streetDropdown.appendChild(oOption);
                }

                //process query params
                if (getQueryVariable("pStreet") && doneAppLoadSelectStreet != true) {
                    doneAppLoadSelectStreet = true;
                    selectItem(streetDropdown, getQueryVariable("pStreet"), streetChanged);
                }

            } else {
                var oOption = document.createElement("OPTION");
                oOption.innerHTML = "No Streets in the selected filter";
                oOption.value = '';
                streetDropdown.appendChild(oOption);
            }

        } else {
            //alert('There was a problem with the request, please try again.');
        }
    }
}

function TownSuccess(http_request, customData) {
    if (http_request.readyState == 4) {
        if (http_request.status == 200) {

            var TownDropdown = document.getElementById(townDropdownClientId);
            if (TownDropdown) {
                while (TownDropdown.options.length > 0) {
                    try { TownDropdown.options[0] = null; } catch (e) { }
                }
            } else {
                //alert('Town dropdown not defined!');
                return;
            }

            var xmldoc = http_request.responseXML;
            var TownList = xmldoc.getElementsByTagName("Town");
            if (TownList.length > 0) {
                var rOption = document.createElement("OPTION");
                rOption.innerHTML = "-- Optionally, Select a Town --";
                rOption.value = "";
                TownDropdown.appendChild(rOption);
                for (var iAr = 0; iAr < TownList.length; iAr++) {
                    var myTown = TownList[iAr];
                    var oOption = document.createElement("OPTION");
                    oOption.innerHTML = myTown.getAttribute("name");
                    oOption.value = myTown.getAttribute("id");
                    TownDropdown.appendChild(oOption);
                }
            } else {
                var oOption = document.createElement("OPTION");
                oOption.innerHTML = "No Towns in the selected area";
                oOption.value = '';
                TownDropdown.appendChild(oOption);
            }
        } else {
            //alert('There was a problem with the request, please try again.');
        }
    }
}

function areaSuccess(http_request, customData) {
    if (http_request.readyState == 4) {
        if (http_request.status == 200) {
            //alert(http_request.responseText);
            var xmldoc = http_request.responseXML;
            var areaList = false;
            var areaDropdown = false;
            if (xmldoc.getElementsByTagName("areas").length > 0) { areaList = xmldoc.getElementsByTagName("areas")[0]; }
            if (areaList) {
                areaDropdown = document.getElementById(areaDropdownClientId);
                if (areaDropdown) {
                    while (areaDropdown.options.length > 0) {
                        try { areaDropdown.options[0] = null; } catch (e) { }
                    }
                    var rOption = document.createElement("OPTION");
                    rOption.innerHTML = "-- Select an Area --";
                    rOption.value = "";
                    areaDropdown.appendChild(rOption);
                    for (var iAr = 0; iAr < areaList.childNodes.length; iAr++) {
                        var myarea = areaList.childNodes[iAr];
                        if (myarea.nodeName == "area") {
                            var oOption = document.createElement("OPTION");
                            if (parseInt(getCookie("AreaId")) == parseInt(myarea.getAttribute("id"))) { oOption.selected = true; changeArea(myarea.getAttribute("id")); }
                            oOption.innerHTML = myarea.getAttribute("name");
                            oOption.value = myarea.getAttribute("id");
                            areaDropdown.appendChild(oOption);
                        }
                    }
                }
                else {
                    //alert('Area dropdown not defined!');
                }
            }

            //process query params
            if (getQueryVariable("pArea")) {
                selectItem(areaDropdown, getQueryVariable("pArea"), areaChanged);
            }
            if (getQueryVariable("pFaultType")) {
                selectItem(document.getElementById(faultTypeDropdownClientId), getQueryVariable("pFaultType"));
            }
            if (getQueryVariable("pUnitReference") && !getQueryVariable("pStreet")) {
                document.getElementById("UnitRef").value = getQueryVariable("pUnitReference");
                UnitRefLookup(true);
            }

        } else {
            //alert('There was a problem with the request, please try again.');
        }
    }
}

function selectItem(dropdown, value, func, startsWith) {
    if (!dropdown) return; if (!value) value = "";
    for (var i = 0; i < dropdown.options.length; i++) {
        var val = dropdown.options[i].innerHTML.toLowerCase().replace(/&amp;/gi, "&").replace(/&lt;/gi, "<");
        if (val == value.toLowerCase() || (startsWith == true && val.indexOf(value.toLowerCase()) == 0)) {
            if (IsMSIE6 == true) {
                setTimeout(function() {
                    dropdown.selectedIndex = i;
                    if (func) func();
                }, 1);
            } else {
                dropdown.selectedIndex = i;
                if (func) func();
            }
            return;
        }
    }
}

function loadAreas() {
    if (IsBrowserCompatible()) {
        var areaDropdown = document.getElementById(areaDropdownClientId);
        if (areaDropdown) {
            while (areaDropdown.options.length > 0) {
                try { areaDropdown.options[0] = null; } catch (e) { };
            }
            var oOption = document.createElement("OPTION");
            oOption.innerHTML = "Please wait...";
            oOption.value = "";
            areaDropdown.appendChild(oOption);
            makeRequest(AppRoot + "/Public/Services/GetAreas.ashx?m=" + getAreaStreetMode(), '', areaSuccess);
        }
        else {
            //alert('Area dropdown not defined!');
        }
    }
    loadTowns();
}

function loadTowns() {
    if (IsBrowserCompatible()) {
        var TownDropdown = document.getElementById(townDropdownClientId);
        if (TownDropdown) {
            while (TownDropdown.options.length > 0) {
                try { TownDropdown.options[0] = null; } catch (e) { };
            }
            var oOption = document.createElement("OPTION");
            oOption.innerHTML = "Please wait...";
            oOption.value = "";
            TownDropdown.appendChild(oOption);
            makeRequest(AppRoot + "/Public/Services/GetTowns.ashx?m=" + getAreaStreetMode(), '', TownSuccess);
        } else {
            //alert('Town dropdown not defined!');
        }
    }
}

function getAreaStreetMode() {
    if (/\/Public\/$/i.test(location.pathname) || /\/Default.aspx$/i.test(location.pathname) || /\/WorkSchedule.aspx$/i.test(location.pathname)) return "1"; else return "0";
}

function areaChanged(e) {
    var me = document.getElementById(areaDropdownClientId)
    var areaId = me.options[me.selectedIndex].value;
    var btnUpdate = document.getElementById(btnUpdateClientId);
    if (btnUpdate) {
        var areaIdTextBox = document.getElementById(areaIdTextBoxClientId);
        if (areaIdTextBox) { areaIdTextBox.value = areaId; }
        btnUpdate.click();
    } else {
        changeArea(areaId);
    }
}

function changeArea(areaId) {
    var areaIdTextBox = document.getElementById(areaIdTextBoxClientId);
    if (areaIdTextBox) { areaIdTextBox.value = areaId; }
    var townIdTextBox = document.getElementById(townIdTextBoxClientId);
    if (townIdTextBox) { townIdTextBox.value = ''; }
    var streetIdTextBox = document.getElementById(streetIdTextBoxClientId);
    if (streetIdTextBox) { streetIdTextBox.value = ''; }
    var unitIdTextBox = document.getElementById(unitIdTextBoxClientId);
    if (unitIdTextBox) { unitIdTextBox.value = ''; }

    var streetDropdown = document.getElementById(streetDropdownClientId);
    if (streetDropdown) {

        if (document.getElementById("divUnitHistory")) document.getElementById("divUnitHistory").style.display = "none";

        var unitDropdown = document.getElementById(unitDropdownClientId);
        if (unitDropdown) {
            while (unitDropdown.options.length > 0) {
                try { unitDropdown.options[0] = null; } catch (e) { };
            }
            var oOption = document.createElement("OPTION");
            oOption.innerHTML = "No Street or Unit Reference Selected";
            oOption.value = "";
            unitDropdown.appendChild(oOption);
        }

        while (streetDropdown.options.length > 0) {
            try { streetDropdown.options[0] = null; } catch (e) { };
        }
        if (areaId != '') {
            var oOption = document.createElement("OPTION");
            oOption.innerHTML = "Please wait...";
            oOption.value = "";
            streetDropdown.appendChild(oOption);
            makeRequest(AppRoot + "/Public/Services/GetStreets.ashx?AreaId=" + areaId + "&m=" + getAreaStreetMode(), '', streetListSuccess);
        }

        var townDropdown = document.getElementById(townDropdownClientId);
        if (townDropdown) {
            while (townDropdown.options.length > 0) {
                try { townDropdown.options[0] = null; } catch (e) { };
            }
            var oOption = document.createElement("OPTION");
            oOption.innerHTML = "Please wait...";
            oOption.value = "";
            townDropdown.appendChild(oOption);
            makeRequest(AppRoot + "/Public/Services/GetTowns.ashx?AreaId=" + areaId + "&m=" + getAreaStreetMode(), '', TownSuccess);
        }

    }
    else {
        //alert('Street dropdown not defined!'); 
    }
}

function townChanged(e) {
    var me = document.getElementById(townDropdownClientId);
    var townId = me.options[me.selectedIndex].value;
    var townIdTextBox = document.getElementById(townIdTextBoxClientId);
    if (townIdTextBox) { townIdTextBox.value = townId; }
    changetown(townId);
}

function changetown(townId) {
    var townIdTextBox = document.getElementById(townIdTextBoxClientId);
    if (townIdTextBox) { townIdTextBox.value = townId; }
    var unitIdTextBox = document.getElementById(unitIdTextBoxClientId);
    if (unitIdTextBox) { unitIdTextBox.value = ''; }
    var townDropdown = document.getElementById(townDropdownClientId);
    if (townDropdown) {

        if (document.getElementById("divUnitHistory")) document.getElementById("divUnitHistory").style.display = "none";

        var unitDropdown = document.getElementById(unitDropdownClientId);
        if (unitDropdown) {
            while (unitDropdown.options.length > 0) {
                try { unitDropdown.options[0] = null; } catch (e) { };
            }
            var oOption = document.createElement("OPTION");
            oOption.innerHTML = "No Street or Unit Reference Selected";
            oOption.value = "";
            unitDropdown.appendChild(oOption);
        }

        var streetDropdown = document.getElementById(streetDropdownClientId);
        if (streetDropdown) {
            while (streetDropdown.options.length > 0) {
                try { streetDropdown.options[0] = null; } catch (e) { };
            }
            var oOption = document.createElement("OPTION");
            oOption.innerHTML = "Please wait...";
            oOption.value = "";
            streetDropdown.appendChild(oOption);

            var areaDropDown = document.getElementById(areaDropdownClientId)
            var areaId = areaDropDown.selectedIndex > 0 ? areaDropDown.options[areaDropDown.selectedIndex].value : "";
            var townName = townId > 0 ? townDropdown.options[townDropdown.selectedIndex].text : "";
            makeRequest(AppRoot + "/Public/Services/GetStreets.ashx?AreaId=" + areaId + "&TownName=" + encodeURIComponent(townName) + "&m=" + getAreaStreetMode(), '', streetListSuccess);
        }
    }
}

function streetChanged(e) {
    var me = document.getElementById(streetDropdownClientId);
    var streetId = me.options[me.selectedIndex].value;
    var btnUpdate = document.getElementById(btnUpdateClientId);
    if (btnUpdate) {
        var streetIdTextBox = document.getElementById(streetIdTextBoxClientId);
        if (streetIdTextBox) { streetIdTextBox.value = streetId; }
        btnUpdate.click();
    } else {
        changeStreet(streetId);
    }
}

function changeStreet(streetId) {
    var streetIdTextBox = document.getElementById(streetIdTextBoxClientId);
    if (streetIdTextBox) { streetIdTextBox.value = streetId; }
    var unitIdTextBox = document.getElementById(unitIdTextBoxClientId);
    if (unitIdTextBox) { unitIdTextBox.value = ''; }
    var unitDropdown = document.getElementById(unitDropdownClientId);
    if (unitDropdown) {

        if (document.getElementById("divUnitHistory")) document.getElementById("divUnitHistory").style.display = "none";

        while (unitDropdown.options.length > 0) {
            try { unitDropdown.options[0] = null; } catch (e) { };
        }
        if (streetId != '') {
            var oOption = document.createElement("OPTION");
            oOption.innerHTML = "Please wait...";
            oOption.value = "";
            unitDropdown.appendChild(oOption);

            var townDropdown = document.getElementById(townDropdownClientId);
            var townId = townDropdown ? townDropdown.options[townDropdown.selectedIndex].value : "";

            makeRequest(AppRoot + "/Public/Services/GetLightUnits.ashx?StreetId=" + streetId + "&TownId=" + townId, '', unitSuccess);
        } else {
            var oOption = document.createElement("OPTION");
            oOption.innerHTML = "No Street or Unit Reference Selected";
            oOption.value = "";
            unitDropdown.appendChild(oOption);
        }
    }
}

function unitChanged(e) {
    var unitDropdown = document.getElementById(unitDropdownClientId);
    var unitIdTextBox = document.getElementById(unitIdTextBoxClientId);
    var streetLigthId = unitDropdown.options[unitDropdown.selectedIndex].value;
    if (unitIdTextBox) unitIdTextBox.value = streetLigthId;

    if (document.getElementById("divUnitHistory")) document.getElementById("divUnitHistory").style.display = unitDropdown.selectedIndex == 0 ? "none" : "";

    ShowHistoryA(streetLigthId);
}

function UnitRefLookup(dontAlert) {
    var areaDropdown = document.getElementById(areaDropdownClientId);
    var townDropdown = document.getElementById(townDropdownClientId);
    var streetDropdown = document.getElementById(streetDropdownClientId);
    var unitDropdown = document.getElementById(unitDropdownClientId);
    var UnitRef = document.getElementById("UnitRef");
    if (!UnitRef) return;

    if (UnitRef.value.length < 1) return dontAlert ? false : alert("Please enter a unit reference or find the unit using the Area and Street dropdowns.");
    if (UnitRef.value.length < 3 && areaDropdown.selectedIndex == 0) return dontAlert ? false : alert("Please enter alteast 3 characters or select 'Area' in addition to this unit reference.");

    streetDropdown.selectedIndex = 0;
    while (unitDropdown.options.length > 0) {
        try { unitDropdown.options[0] = null; } catch (e) { };
    }
    var oOption = document.createElement("OPTION");
    oOption.innerHTML = "Please Wait...";
    oOption.value = "";
    unitDropdown.appendChild(oOption);

    var areaId = areaDropdown.options[areaDropdown.selectedIndex].value;
    var townId = townDropdown ? townDropdown.options[townDropdown.selectedIndex].value : "";
    var url = AppRoot + '/Public/Services/StreetNames.ashx?r=1&n=' + EncodeForURL(UnitRef.value) + '&a=' + areaId + '&t=' + townId;
    makeRequest(url, '', function(http_response, customData) {
        if (http_response.readyState == 4 && http_response.status == 200) {
            var xml = http_response.responseXML;
            var units = xml.documentElement.getElementsByTagName("unit");
            if (units.length > 0) {
                unitDropdown.options[0].innerHTML = "-- Select a unit --";
                for (var i = 0; i < units.length; i++) {
                    var SName = units[i].getAttribute("UnitRef") + " - " + units[i].getAttribute("Desc") + ", " + units[i].getAttribute("StreetName") + ", " + units[i].getAttribute("AreaName");
                    var oOption = document.createElement("OPTION");
                    oOption.innerHTML = SName;
                    oOption.value = units[i].getAttribute("StreetLightId");
                    unitDropdown.appendChild(oOption);
                }
                unitDropdown.selectedIndex = units.length == 1 ? 1 : 0;
                unitChanged();
            } else {
                unitDropdown.options[0].innerHTML = "No Street or Unit Reference Selected";
                alert("No unit was found for the specified reference" + (areaDropdown.selectedIndex > 0 ? " in the selected Area." : "."));
            }
        }
    });
}

function MM_preloadImages() { //v3.0
    var d = document;
    if (d.images) {
        if (!d.MM_p) d.MM_p = new Array();
        var i, j = d.MM_p.length, a = MM_preloadImages.arguments;
        for (i = 0; i < a.length; i++)
            if (a[i].indexOf("#") != 0) {
            d.MM_p[j] = new Image;
            d.MM_p[j++].src = a[i];
        }
    }
}
//MM_preloadImages('images/buttons/btn_bookmrk_sl.gif', 'images/why_use_us_f2.gif', 'images/comprehensive_services_f2.gif', 'images/bookmark_f2.gif');

function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0].toLowerCase() == variable.toLowerCase()) {
            return decodeURIComponent(pair[1]);
        }
    }
    return '';
}

function fadeout(elid, spd) {
    var el = document.getElementById(elid);
    if (el.style.opacity > 0.1) {
        el.style.opacity = el.style.opacity - 0.1;
        el.style.filter = "alpha(opacity=" + (el.style.opacity * 100) + ")";
        el.style.MozOpacity = el.style.opacity;
        setTimeout("fadeout('" + elid + "'," + spd + ");", spd);
    } else {
        el.style.opacity = 0;
        el.style.filter = "alpha(opacity=0)";
        el.style.MozOpacity = 0;
        el.style.display = 'none';
    }
}

function submitenter(myfield, e, func) {
    var keycode;
    if (window.event && window.event.keyCode) keycode = window.event.keyCode;
    else if (e) keycode = e.which;
    else return true;

    if (keycode == 13) {
        try {
            func.call(myfield);
        } catch (e) { }
        return false;
    } else return true;
}

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

var waitIndicator, RunLookup;
function Lookup() {
    //In admin mode this method may be called before the map has initialized. give the map some time load
    if (map == null) {
        if (counter >= 10) { alert("The map is taking too long to load. Press OK when the map has loaded."); counter = 0; }
        setTimeout("Lookup();", 1000); counter = counter + 1; return;
    }

    var tbSearch = document.getElementById("tbSearch");
    var asTown = document.getElementById("asTown");
    var asStreet = document.getElementById("asStreet");
    var asPostcode = document.getElementById("asPostcode");

    var validateQuery = (getQueryVariable("pCallCentreMode") == 1 && IsAdmin != true) ? (tbSearch.value + asStreet.value + asTown.value + asPostcode.value) : tbSearch.value;

    // Validate the user input.
    if (validateQuery.length < 3) { alert('Please enter atleast 3 characters in the search box.'); return; }
    if (validateQuery.indexOf('<') != -1 || validateQuery.indexOf('>') != -1) { alert('Special characters like "<" or ">" are not allowed.'); return; }

    if (!waitIndicator) {
        waitIndicator = document.getElementById("LookupWait");
        waitIndicator.style.display = "block";
        waitIndicator.style.marginLeft = (tbSearch.clientWidth + (isNaN(parseInt(tbSearch.style.marginLeft)) ? 0 : parseInt(tbSearch.style.marginLeft)) - waitIndicator.clientWidth) + "px";
    } else waitIndicator.style.display = "block";
    if (!RunLookup) RunLookup = document.getElementById('RunLookup'); RunLookup.disabled = true;

    var url = '/Public/Services/StreetNames.ashx?' + (getQueryVariable("pCallCentreMode") == 1 && IsAdmin != true ? ('adv=1&s=' + EncodeForURL(asStreet.value) + '&t=' + EncodeForURL(asTown.value) + '&p=' + EncodeForURL(asPostcode.value) + '&ur=' + EncodeForURL(tbSearch.value)) : ('n=' + EncodeForURL(tbSearch.value)));
    if (typeof GDownloadUrl != "undefined") GDownloadUrl(AppRoot + url, LookupDataReturned);
    else makeRequest(AppRoot + url, '', function(http_response, customData) { if (http_response.readyState == 4) LookupDataReturned(http_response.responseXML, http_response.status); });
}

var ResultsPage = 0, StreetSearchResults = [];
function ShowSearchResults() {
    var liHtml = '';
    for (var i = ResultsPage * 8; (i < (ResultsPage * 8) + 8) && (i < StreetSearchResults.length); i++) {
        liHtml += StreetSearchResults[i];
    }
    if (ResultsPage != 0) liHtml += '<a href="javascript:" onclick="PreviousResultsPage();"><b>...Less</b></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
    if (i + 1 < StreetSearchResults.length) liHtml += '<a href="javascript:" onclick="NextResultsPage();"><b>More...</b></a>';
    document.getElementById('ResultsList').innerHTML = liHtml;
}

function NextResultsPage() {
    ResultsPage++;
    ShowSearchResults();
}

function PreviousResultsPage() {
    ResultsPage--;
    ShowSearchResults();
}

function ShowZoomHelp(tooMany, margin) {
    var ZmTemp = document.getElementById('ZoomTemplate');
    FaultIns = document.getElementById('FaultInstructions');
    if (tooMany == true) {
        FaultIns.style.display = 'none';
        if (margin) ZmTemp.style.margin = margin;
        ZmTemp.style.display = '';
        ZmTemp.style.opacity = 1;
        ZmTemp.style.filter = "alpha(opacity=100)";
        ZmTemp.style.MozOpacity = 1;
        setTimeout("fadeout('ZoomTemplate',100);", 5000);
    } else ShowInstructions();
}

function ShowInstructions() {
    ZmTemp = document.getElementById('ZoomTemplate');
    FaultIns = document.getElementById('FaultInstructions');
    ZmTemp.style.display = 'none';
    if (getQueryVariable("pCallCentreMode") == "1") return; //dont show instructions in call centre mode
    FaultIns.style.display = '';
    FaultIns.style.opacity = 1;
    FaultIns.style.filter = "alpha(opacity=100)";
    FaultIns.style.MozOpacity = 1;
    setTimeout("fadeout('FaultInstructions',100);", 8000);
}

function ShowLoadingBar() {
    document.getElementById('loading').style.display = 'block';
    document.getElementById('loading').style.visibility = 'visible';
}

function HideLoadingBar() {
    document.getElementById('loading').style.visibility = 'hidden';
    document.getElementById('loading').style.display = 'none';
}

//var loadingtimeout;
//function ShowLoadingBar() {
//    clearTimeout(loadingtimeout);
//    loadingtimeout = setTimeout(function() {
//        document.getElementById('loading').style.display = 'block';
//        document.getElementById('loading').style.visibility = 'visible';
//        loadingtimeout = setTimeout(HideLoadingBar, 3000);
//    }, 250);
//}

//function HideLoadingBar() {
//    document.getElementById('loading').style.visibility = 'hidden';
//    document.getElementById('loading').style.display = 'none';
//    clearTimeout(loadingtimeout);
//}

function HideElement(elId) {
    var found = false;
    var oElement = document.getElementById(elId);
    if (oElement != null) {
        oElement.style.display = 'none';
        oElement.style.visibility = 'hidden';
        found = true;
    }
    if (!found) {
        var all = document.all ? document.all : document.getElementsByTagName('*');
        if (all != null && all.length != null) {
            for (var di = 0; di < all.length; di++) {
                if (all[di].id == elId) { all[di].style.display = 'none'; all[di].style.visibility = 'hidden'; }
            }
        }
    }
}

function ShowElement(elId) {
    var found = false;
    var oElement = document.getElementById(elId);
    if (oElement != null) {
        oElement.style.display = 'block';
        oElement.style.visibility = 'visible';
        found = true;
    }
    if (!found) {
        var all = document.all ? document.all : document.getElementsByTagName('*');
        if (all != null && all.length != null) {
            for (var di = 0; di < all.length; di++) {
                if (all[di].id == elId) {
                    all[di].style.display = 'block';
                    all[di].style.visibility = 'visible';
                }
            }
        }
    }
}

//parses a date and reformats to mm/dd/yyyy string
function ConvertDate(d) {
    if (d == null) return null;
    var today;
    if (d.constructor == Date) today = d;
    else if (d.constructor == String) { try { today = new Date(d); } catch (e) { return null; } }
    var dd = today.getDate();
    var mm = today.getMonth() + 1; //January is 0!
    var yyyy = today.getFullYear();
    if (dd < 10) { dd = '0' + dd }
    if (mm < 10) { mm = '0' + mm }
    return mm + '/' + dd + '/' + yyyy;
}

//This function encodes a string to be used as a query string param's value
function EncodeForURL(str) {
    if (typeof str != 'string') return str;
    str = encodeURI(str);
    str = str.replace(/&/g, '%26');
    str = str.replace(/#/g, '%23');
    return str;
}

/* convert OS grid reference to geodesic co-ordinates */
function OSGridToLatLong(E, N) {
    var a = 6377563.396, b = 6356256.910;                       // Airy 1830 major & minor semi-axes
    var F0 = 0.9996012717;                                      // NatGrid scale factor on central meridian
    var lat0 = 49 * Math.PI / 180, lon0 = -2 * Math.PI / 180;   // NatGrid true origin
    var N0 = -100000, E0 = 400000;                              // northing & easting of true origin, metres
    var e2 = 1 - (b * b) / (a * a);                             // eccentricity squared
    var n = (a - b) / (a + b), n2 = n * n, n3 = n * n * n;
    var lat = lat0, M = 0;

    do {
        lat = (N - N0 - M) / (a * F0) + lat;

        var Ma = (1 + n + (5 / 4) * n2 + (5 / 4) * n3) * (lat - lat0);
        var Mb = (3 * n + 3 * n * n + (21 / 8) * n3) * Math.sin(lat - lat0) * Math.cos(lat + lat0);
        var Mc = ((15 / 8) * n2 + (15 / 8) * n3) * Math.sin(2 * (lat - lat0)) * Math.cos(2 * (lat + lat0));
        var Md = (35 / 24) * n3 * Math.sin(3 * (lat - lat0)) * Math.cos(3 * (lat + lat0));
        var M = b * F0 * (Ma - Mb + Mc - Md);                               // meridional arc

    } while (N - N0 - M >= 0.00001);                                        // ie until < 0.01mm

    var cosLat = Math.cos(lat), sinLat = Math.sin(lat);
    var nu = a * F0 / Math.sqrt(1 - e2 * sinLat * sinLat);                  // transverse radius of curvature
    var rho = a * F0 * (1 - e2) / Math.pow(1 - e2 * sinLat * sinLat, 1.5);  // meridional radius of curvature
    var eta2 = nu / rho - 1;

    var tanLat = Math.tan(lat);
    var tan2lat = tanLat * tanLat, tan4lat = tan2lat * tan2lat, tan6lat = tan4lat * tan2lat;
    var secLat = 1 / cosLat;
    var nu3 = nu * nu * nu, nu5 = nu3 * nu * nu, nu7 = nu5 * nu * nu;
    var VII = tanLat / (2 * rho * nu);
    var VIII = tanLat / (24 * rho * nu3) * (5 + 3 * tan2lat + eta2 - 9 * tan2lat * eta2);
    var IX = tanLat / (720 * rho * nu5) * (61 + 90 * tan2lat + 45 * tan4lat);
    var X = secLat / nu;
    var XI = secLat / (6 * nu3) * (nu / rho + 2 * tan2lat);
    var XII = secLat / (120 * nu5) * (5 + 28 * tan2lat + 24 * tan4lat);
    var XIIA = secLat / (5040 * nu7) * (61 + 662 * tan2lat + 1320 * tan4lat + 720 * tan6lat);

    var dE = (E - E0), dE2 = dE * dE, dE3 = dE2 * dE, dE4 = dE2 * dE2, dE5 = dE3 * dE2, dE6 = dE4 * dE2, dE7 = dE5 * dE2;
    lat = lat - VII * dE2 + VIII * dE4 - IX * dE6;
    var lon = lon0 + X * dE - XI * dE3 + XII * dE5 - XIIA * dE7;

    var returnCoords = { 'lat': lat * 180 / Math.PI, 'lon': lon * 180 / Math.PI }
    return returnCoords;
}

function hideDropDowns() {
    var dropdowns = document.getElementsByTagName("select");
    for (var i = 0; i < dropdowns.length; i++) {
        dropdowns[i].style.display = "none";
    }
}

function showDropDowns() {
    var dropdowns = document.getElementsByTagName("select");
    for (var i = 0; i < dropdowns.length; i++) {
        dropdowns[i].style.display = "";
    }
}

function ShowCoverAll(optElementName) {
    var CoverAll = document.getElementById('CoverAll');
    CoverAll.className = '';
    if (IsBrowserCompatible() && IsMSIE6) {
        CoverAll.style.height = Math.max(document.documentElement.scrollHeight, document.documentElement.clientHeight) + "px";
        hideDropDowns();
    }
    if (typeof optElementName != "undefined") {
        var optElement = document.getElementById(optElementName);
        if (typeof optElement != "undefined") {
            optElement.className = '';
            try {
                if (optElementName == "HomeTextFull" && typeof document.documentElement != "undefined") {
                    if ((optElement.clientHeight + optElement.offsetTop + optElement.offsetTop) > document.documentElement.clientHeight) {
                        optElement.style.height = (document.documentElement.clientHeight - optElement.offsetTop - optElement.offsetTop) + "px"
                        optElement.style.overflowY = "auto";
                        optElement.style.padding = "0";
                    }
                }
            } catch (ex) { }
        }
    }
}
function ShowPrivacyPolicy() { ShowCoverAll('PrivacyPolicy'); }
function ShowHomeText() { ShowCoverAll('HomeTextFull'); }
function HideCoverAll(optElement) {
    if (typeof optElement != "undefined") document.getElementById(optElement).className = 'Hidden';
    document.getElementById('CoverAll').className = 'Hidden';
    if (IsBrowserCompatible() && IsMSIE6) showDropDowns();
}

//Accessability
function changeSize(size) {
    document.getElementsByTagName('body')[0].style.fontSize = size;
    setCookie('fontsize', size, 100);
    if (typeof MapResize != 'undefined') MapResize();
}

function changeColor(force) {
    var ell = document.getElementById('highvisCss');
    if (ell && force != true) {
        ell.parentNode.removeChild(ell);
        setCookie('highvis', '0', 100);
    } else {
        ell = document.createElement("link");
        ell.setAttribute("id", 'highvisCss');
        ell.setAttribute("rel", "stylesheet");
        ell.setAttribute("type", "text/css");
        ell.setAttribute("href", "../Layout/HighVis.css");
        document.getElementsByTagName('head')[0].appendChild(ell);

        setCookie('highvis', '1', 100);
    }
}

function highlightLinks(sender) {
    var el = document.getElementById('highlightLinksCss');
    if (el) {
        el.parentNode.removeChild(el);
        sender.innerHTML = "Highlight all links";
    } else {
        el = document.createElement("style");
        el.setAttribute("id", 'highlightLinksCss');
        el.setAttribute("type", "text/css");
        el.innerHTML = ".admin_image_map a { border: dashed 1px grey; }";
        document.getElementsByTagName('head')[0].appendChild(el);
        sender.innerHTML = "Undo Highlight all links";
    }
}

