﻿//the map object
var map = null;
var threeAutoAddress = null;

//load map    
function Page_Load()
{
    SetMapWidthAndPos();
    
    var height = document.documentElement.clientHeight;
    window.scrollBy(0, height);

    var mapArgs = new ThreeIreland.MapArgs("myMap", new VELatLong(53.428738, -7.734375), 6, VEMapStyle.Road, false, VEMapMode.Mode2D, VEDistanceUnit.Kilometers);
    //debugger;
    map = new ThreeIreland.PublicMap(ThreeIreland.Services.MapService, mapArgs, layersArray, accessMode, enableRequestNBS);
    requestNBS = new ThreeIreland.RequestNBS(map);

    document.getElementById("streetTxt1").onkeydown = keyDown;
    document.getElementById("streetTxt2").onkeydown = keyDown;
    //START - New req 2.1 (16/11/2009): Force ‘postal’ addresses
    document.getElementById("streetTxt3").onkeydown = keyDown;
    document.getElementById("streetTxt4").onkeydown = keyDown;
    //END - New req 2.1 (16/11/2009): Force ‘postal’ addresses
    document.getElementById("countyDdl").onkeydown = keyDown;
    document.getElementById("searchButtonImg").onkeydown = keyDown;
    ShowHideCoverage();
}

function ShowInfoBox()
{
    map._map.HideInfoBox();
    var pixel = map._map.LatLongToPixel(map._map.GetCenter(), map._map.GetZoomLevel());
    map._map.ShowInfoBox(map._selectedShape, new VEPixel(pixel.x - 7, pixel.y));
}

//Set map width and pos dependong on the footer and header
function SetMapWidthAndPos()
{
    if (accessMode == "") //CoveragePublicPage.aspx
    {
        var mapDiv = document.getElementById("myMap");
        mapDiv.style.width = "385px";
        var mainTable = document.getElementById("mainTable_Public");
        mainTable.style.position = "relative"; 
        mainTable.style.left = "75px";
    }
}

/************************/
/* Tile layer selection */
/************************/

//NBS CheckboxChanged
function showCoverage_clicked()
{
    var check = document.getElementById("showCoverage");
    if (check != null)
    {
        if (check.checked)
        {
            if (accessMode == "NBS")
                map._ShowNBSCoverage();
            else if (accessMode == "NBSAgents")
                map._ShowNBSCPESCoverage();
        }
        else
        {
            if (accessMode == "NBS")
                map._HideNBSCoverage();
            else if (accessMode == "NBSAgents")
                map._HideNBSCPESCoverage();
        }
    }
}

//Public CheckboxChanged
function showPublicCoverage_clicked()
{
    var check = document.getElementById("showPublicCoverage");
    if (check != null)
    {
        if (check.checked)
            map._Show3GCoverageInOut();
        else
            map._Hide3GCoverageInOut(); 
    }
}

//DropDownChanged
function showDropDown_changed(value)
{
    LoadLegend(value);
    map._TurnOnTileLayer(value);
}


//OnLoad ShowHideCoverage
function ShowHideCoverage()
{
    var checkNBS = document.getElementById("showCoverage");
    var checkPublic = document.getElementById("showPublicCoverage");
    var check = null;
    if (checkNBS != null)
        check = checkNBS;
    else if (checkPublic != null)
        check = checkPublic;
        
    if (check != null)
    {
        if (check.checked)
        {
            if (accessMode == "NBS")
                map._ShowNBSCoverage();
            else if (accessMode == "NBSAgents")
                map._ShowNBSCPESCoverage();
            else
                map._Show3GCoverageInOut();
        }
        else
        {
            if (accessMode == "NBS") 
                map._HideNBSCoverage();
            else if (accessMode == "NBSAgents")
                map._HideNBSCPESCoverage();
            else
                map._Hide3GCoverageInOut();
        }
    }
    else
    {
        var selectList = document.getElementById("ctl00_ContentPlaceHolder1_selectCoverageLayer");
        if (selectList != null)
        {
            var value = selectList.options[selectList.selectedIndex].value;
            LoadLegend(value);
            map._TurnOnTileLayer(value);
        }
    
    }
}

//In case the page is not CoveragePublicPage load legend in tableLegendTD2
function LoadLegend(legendName)
{
    var innerHTML = "";
    innerHTML += "<b>Layer Legend</b>";
    if (legendName == "ThreeNBSDED") //Coverage NBS
    {
        innerHTML += "<table style='position:relative; top:-1px; #top:0px;'><tr><td style='background-color:#008000;width:10px'></td><td>";
        innerHTML += "NBS live"
        innerHTML += "</td></tr><tr><td style='background-color:#FFBF00;'></td><td >";
        innerHTML += "NBS scheduled";
        innerHTML += "</td></tr><tr><td style='background-color:#FF0000;'></td><td >";
        innerHTML += "NBS planned";
        innerHTML += "</td></tr><tr><td style='background-color:#808080;width:10px'></td><td>";
        innerHTML += "Non-NBS area";
        innerHTML += "</td></tr></table>";
    }
    else if (legendName == "Three3GCoverage")  //3G Coverage
    {
        innerHTML += "<table><tr><td style='background-color:#7EB3E7;width:10px'></td><td>";
        innerHTML += "Indoors"
        innerHTML += "</td></tr><tr><td style='background-color:#0066CF;width:10px'></td><td>";
        innerHTML += "Out and about";
        innerHTML += "</td></tr></table>";
    }
    else if (legendName == "ThreeInOut") //3G In and Out
    {
        innerHTML += "<table><tr><td style='background-color:#7EB3E7;width:10px'></td><td>";
        innerHTML += "Indoors"
        innerHTML += "</td></tr><tr><td style='background-color:#0066CF;width:10px'></td><td>";
        innerHTML += "Out and about";
        innerHTML += "</td></tr></table>";
    }
    else if (legendName == "Three3GFuture") //3G Future
    {
        innerHTML += "<table><tr><td style='background-color:#494897;width:10px'></td><td>";
        innerHTML += "Planned coverage"
        innerHTML += "</td></tr></table>";
    }
    else if (legendName == "Three2GCoverage") //3G Future
    {
        if (accessMode != "")
        {
            innerHTML += "<table><tr><td style='background-color:#FF0000;width:10px'></td><td>";
            innerHTML += "Marginal Coverage"
            innerHTML += "</td></tr><tr><td style='background-color:#FFA500;'></td><td >";
            innerHTML += "Good Coverage"
            innerHTML += "</td></tr><tr><td style='background-color:#008000;width:10px'></td><td>";
            innerHTML += "Very Good Coverage"
            innerHTML += "</td></tr></table>";
        }
        else
        {
            innerHTML += "<table><tr><td style='background-color:#FF0000;width:10px'></td><td>";
            innerHTML += "2G Coverage"
            innerHTML += "</td></tr></table>";
        }
    }
    else
    {
        innerHTML = "";
    }
    document.getElementById("tableLegendTD2").innerHTML = innerHTML;
}

/************************/
/* Search and pins load */
/************************/

//Control enter key press 
function keyDown(e)
{
    var evt = (e) ? e : (window.event) ? window.event : null;
    if (evt)
    {
        var key = (evt.charCode) ? evt.charCode :
			((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
        if (key == "13")
            searchAdd();
    }
}

//Search img clicked
function searchAddress()
{
    searchAdd();
}

//Search engine
function searchAdd()
{
    var street1 = document.getElementById("streetTxt1").value;
    var street2 = document.getElementById("streetTxt2").value;
    var street3 = "";
    var street4 = "";
    //START - New req 2.1 (16/11/2009): Force ‘postal’ addresses
    var street3 = document.getElementById("streetTxt3").value;
    var street4 = document.getElementById("streetTxt4").value;
    //END - New req 2.1 (16/11/2009): Force ‘postal’ addresses
    if ((street1 == "") && (street2 == "") && (street3 == "") && (street4 == ""))
    {
        document.getElementById("searchResults").style.visibility = "hidden";
        alert("Please enter an address line");
    }
    else
    {
        //Show loading message
        var resultsLbl = document.getElementById("blackLabel");
        resultsLbl.innerHTML = "Loading...";
        var resultsPnl = document.getElementById("searchResults");
        resultsPnl.style.visibility = "visible";
        //Call WS
        var countyDDL = document.getElementById("countyDdl");
        var county = countyDDL.options[countyDDL.selectedIndex].value;
        map.SetBuy4NowAddress(street1, street2, street3, street4, county);

        //New req 2.1 (16/11/2009):
        ThreeIreland.Services.AddressLinkService.ValidateAddress4Lines(street1, street2, street3, street4, county, OnValidateSuccess, OnValidateFailed);
        //Before req 2.1: ThreeIreland.Services.AddressLinkService.ValidateAddress(street1, street2, county, OnValidateSuccess, OnValidateFailed);
    }
}

//Successfull
function OnValidateSuccess(result)
{
    if (accessMode == "Buy4Now")
        CancelPinpointAddress();
    //Fill label with results
    var resultsLbl = document.getElementById("blackLabel");
    var innerHTML = "";
    if (result == "")
    {
        innerHTML += "No Results Found. Please enter more detailed search criteria.";
    }
    else
    {
        //START - New req 2.1 (16/11/2009): Force ‘postal’ addresses
        innerHTML += "<strong>Results (select one):</strong><div style=\"margin-top: 6px; overflow: auto; height:90px;\"><ul style=\" margin-left:px; margin-bottom: 0px\">";
        //END - New req 2.1 (16/11/2009): Force ‘postal’ addresses
        //Before req 2.1: innerHTML += "<strong>Results (select one):</strong><ul style=\" margin-left:px; margin-bottom: 0px\">";
        for (var i = 0; i < result.length; i++)
        {
            var address = "";
            for (var j = 0; j < result[i].Address.length; j++)
            {
                address += result[i].Address[j].toUpperCase();
                if (j < (result[i].Address.length - 1))
                    address += ", ";
            }
            var addressRep = address.replace(/'/g, "%");
            var geoAddressId = result[i].GeoAddressId;

            var deliveryPoints = result[i].DeliveryPoints;
            if (geoAddressId.charAt(0) == 'L' && deliveryPoints < 200) 
            {
                deliveryPoints = 2;
            }
            innerHTML += "<li style='text-decoration:underline; cursor:pointer;vertical-align:text-top;' onclick=\"LocateOnMap(" + result[i].Latitude + "," + result[i].Longitude + ", '" + addressRep + "','" + geoAddressId + "'," + deliveryPoints + ")\">";
            innerHTML += address + "</li>"
        }
        innerHTML += "</ul>";
        //START - New req 2.1 (16/11/2009): Force ‘postal’ addresses
        innerHTML += "</div>";
        //END - New req 2.1 (16/11/2009): Force ‘postal’ addresses
    }

    if (accessMode == "Buy4Now") {
        innerHTML += "<div id='DivBuy4NowInstructions1' style='color:#3300FF' style='margin-top: 2px; margin-bottom: 2px;'>"
        innerHTML += "&nbsp;"
        innerHTML += "</div>"
        innerHTML += "<strong>Alternatively, select your exact location:</strong>";
        innerHTML += "<div style=\"text-align:center\">"
        innerHTML += "<input id='ButtonPinpointOnMap' type='button' value='Pinpoint my address' onclick='PinpointAddress();' style='margin-top: 6px; font-family:Tahoma' />";
        innerHTML += "</div>";
        //START - New req 2.2 (16/11/2009): Think before you pin-point
        /*innerHTML += "<div id=\"PinpointPanel\" style=\"visibility:visible; padding-left:5px;\">";
        innerHTML += "<label style=\"font-family:Tahoma; font-size:11px; font-weight:bold; color:#3300FF; text-decoration:underline;cursor: pointer;\" onclick=\"OnPinpointLinkClicked()\">Can't find your location? Click Here</label>";
        innerHTML += "<br /><br />";
        innerHTML += "<label style=\"font-family:Tahoma; font-size:10px;\" >Warning: Choosing the wrong location on the map may result in the incorrect solution being supplied.</label>";
        innerHTML += "</div>"; //end div id="PinpointPanel"*/
        //END - New req 2.2 (16/11/2009): Think before you pin-point
        innerHTML += "<div id='DivBuy4NowInstructions2' style='color:#3300FF'>"
        innerHTML += "<div>"
        resultsLbl.style.height = "";
    }
    resultsLbl.innerHTML = innerHTML;
}

//In case of error, show it on screen
function OnValidateFailed(error)
{

    var stackTrace = error.get_stackTrace();
    var message = error.get_message();
    var statusCode = error.get_statusCode();
    var exceptionType = error.get_exceptionType();
    var timedout = error.get_timedOut();

    // Display the error 
    var RsltElem =
                "Stack Trace: " + stackTrace + "<br/>" +
                "Service Error: " + message + "<br/>" +
                "Status Code: " + statusCode + "<br/>" +
                "Exception Type: " + exceptionType + "<br/>" +
                "Timedout: " + timedout;

    //FILL THE LABEL
    var resultsLbl = document.getElementById("blackLabel");
    resultsLbl.innerHTML = RsltElem;
}

//New req 2.2 (16/11/2009): Think before you pin-point
function OnPinpointLinkClicked() {
    var innerHtmlPinpointPanel = "<strong>Alternatively, select your exact location:</strong>";
    innerHtmlPinpointPanel += "<div  style=\"text-align:center\">"
    innerHtmlPinpointPanel += "<input id='ButtonPinpointOnMap' type='button' value='Pinpoint my address' onclick='PinpointAddress();' style='margin-top: 6px; font-family:Tahoma' />";
    innerHtmlPinpointPanel += "</div>"
    document.getElementById('PinpointPanel').innerHTML = innerHtmlPinpointPanel;
}


//Load a pin in that location
function LocateOnMap(lat, lon, address, geoAddressId, deliveryPoints)
{
    if ((accessMode == "NBSAgents") || (accessMode == "NBS"))
    {
        ThreeIreland.Services.NBSService.NBSLookup(lat, lon, address, accessMode, NBSLookupOnSuccess, Utility.OnFailed);
    }
    else
    {
        var addressParagraph = "<b>";
        //Address
        var array = address.toString().split(',');
        for (var i = 0; i < array.length; i++)
        {
            addressParagraph += array[i].toString().trim() + "<br/>";
        }
        addressParagraph += "</b>";
        var addressRep = addressParagraph.replace(/%/g, "'");
        if (accessMode == "Buy4Now")
        {
            CancelPinpointAddress();

            if (deliveryPoints > 1 && deliveryPoints < 200)
            {
                document.getElementById('DivBuy4NowInstructions1').innerHTML = 'Hover over a building to select your exact address';
                //LOAD PINS
                //START - Error in buy4now for "the hills, herbertstown, limerick" (no buildong in DB but 6 deliverypoins in addresslink: We display the BLUE PIN
                map.LoadPinsOnMapForGeodirectoryIdLatLon(lat, lon, geoAddressId);
                // Prev "the hills.." - map.LoadPinsOnMapForGeodirectoryId(addressRep, address, geoAddressId);
                //END - Error in buy4now for "the hills, herbertstown, limerick" (no buildong in DB but 6 deliverypoins in addresslink
            }
            else
            {
                document.getElementById('DivBuy4NowInstructions1').innerHTML = '&nbsp;';
                //LOAD PIN
                map.LoadPinOnMap(lat, lon, addressRep, address, geoAddressId, deliveryPoints);
            }
        }
        else
        {
            //LOAD PIN
            map.LoadPinOnMap(lat, lon, addressRep, address, geoAddressId);
        }
    }
}

function PinpointAddress()
{
    document.getElementById('ButtonPinpointOnMap').onclick = CancelPinpointAddress;
    document.getElementById('ButtonPinpointOnMap').value = 'Cancel Pinpoint Address';
    document.getElementById('DivBuy4NowInstructions1').innerHTML = '&nbsp;';
    // Prev to Alan - document.getElementById('DivBuy4NowInstructions2').innerHTML = 'Right click on map to pinpoint your address';
    // START - Alan (Search buildings around)
    if (map.buy4NowPinpointUsingBuildingSearch == true)
        document.getElementById('DivBuy4NowInstructions2').innerHTML = 'Right click on map to show buildings in that area';
    else
        document.getElementById('DivBuy4NowInstructions2').innerHTML = 'Right click on map to pinpoint your address';
    map.ButtonPinpointOnMap = document.getElementById('ButtonPinpointOnMap');
    map.DivBuy4NowInstructions2 = document.getElementById('DivBuy4NowInstructions2');
    // END - Alan
    map.PinpointAddress();
}

function CancelPinpointAddress()
{
    var btn = document.getElementById('ButtonPinpointOnMap');
    if (btn != null)
    {
        document.getElementById('ButtonPinpointOnMap').onclick = PinpointAddress;
        document.getElementById('ButtonPinpointOnMap').value = 'Pinpoint Address';
        document.getElementById('DivBuy4NowInstructions2').innerHTML = '&nbsp;';
    }
    map.CancelPinpointAddress();
}

function NBSLookupOnSuccess(result)
{
    var addressParagraph = "<b>";
    //Address
    var array = result.Address.toString().split(',');
    for (var i = 0; i < array.length; i++)
    {
        addressParagraph += array[i].toString().trim() + "<br/>";
    }
    addressParagraph += "</b>";
    var addressRep = addressParagraph.replace(/%/g, "'");
    //Coverage
    var cov = "";
    if (result.Coverage == 0) //"Available"
    {
        cov = "This area is currently covered by the National Broadband Scheme."; //"NBS Live";
    }
    else if (result.Coverage == 1) //"Planned"
    {
        cov = "This area is planned to be covered under the National Broadband Scheme."; //"NBS Planned (after 1/1/2009)";
    }
    else if (result.Coverage == 2) //"PlannedSoon"
    {
        cov = "This area is planned to be covered under the National Broadband Scheme. Service will be available in the coming weeks."; //"NBS Planned (after 1/1/2009)";
    }
    else if (result.Coverage == 3) //"Unavailable"
    {
        cov = "This location is not part of the NBS area";  //"Non-NBS area";
    } 
    else if (result.Coverage == 4) //"QualityCoverage"
    {
        if (accessMode == "NBSAgents")
        {
            cov = "This area is covered by the National Broadband Scheme and the network is already live.";
        }
        else
        {
            cov = "This area is planned to be covered under the National Broadband Scheme. Service will be available in the coming weeks.";  //"QualityCoverage";
        }
    }

    addressRep += "<br/><b>Coverage:</b> " + cov + "<br/>";
    
    //Solution Type
    if (accessMode == "NBSAgents")
    {
        var sol = "";
        if (result.Solution == 0)
            sol = "Home Repeater";
        else if (result.Solution == 1)
            sol = "Standard";
        else if (result.Solution == 2)
            sol = "Satellite";
        //addressRep += "<b>Solution Type</b>:  " + sol + "<br/>";
        var inout = "";
        if(result.Inout == 0)
            inout = "Indoors";
        else if (result.Inout == 1)
            inout = "Out and About";
        else if (result.Inout == 2)
            inout = "No Coverage";
        addressRep += "<b>Existing Mobile Broadband Coverage</b>:  " + inout + "<br/>";
    }

    //LOAD PIN
    map.LoadPinOnMap(result.Latitude, result.Longitude, addressRep, addressParagraph);
}
//Load a pin in that location
function RemoveAddressPin()
{
    map.RemoveAddressPin();
}


/*******************************/
/* Buy4NowMap.aspx */
/*******************************/

function AcceptBuy4Now()
{
    map.AcceptBuy4Now();
}

function AcceptBuy4NowFromBuilding(addressline1, addressline2, adddressline3, addressline4, adddressline5, addressline6, geodirectoryid, latitude, longitude, addressmatched)
{
    map.AcceptBuy4NowFromBuilding(addressline1, addressline2, adddressline3, addressline4, adddressline5, addressline6, geodirectoryid, latitude, longitude, addressmatched);
}

function SetBuildingDescriptionPublic(divid, address1, address2, address3, address4, address5, address6, geodirectory, latitude, longitude, boundingBox)
{
    var desc = map.GetBuildingDescription(address1, address2, address3, address4, address5, address6, geodirectory, latitude, longitude, divid);
    if (boundingBox != null)
    {
        var boundingBoxItems = boundingBox.split('&');
        var rect = new VELatLongRectangle
                (new VELatLong(boundingBoxItems[0], boundingBoxItems[1]),
                 new VELatLong(boundingBoxItems[2], boundingBoxItems[3]),
                 null, null);
        map.ZoomToAddress(latitude, longitude, desc, rect);
    }
    else
        map.ZoomToAddress(latitude, longitude, desc, null);
}


function SetBuildingDescriptionShortPublic(divid, address1, address2, address3, address4, address5, address6, geodirectory, latitude, longitude)
{
    document.getElementById(divid).innerHTML = map.GetBuildingDescriptionShort(address1, address2, address3, address4, address5, address6, geodirectory, latitude, longitude, divid);
}

function ShowBuildingAsRedDot(lat, lon)
{
    map.ShowBuilding(lat, lon);
}

/*******************************/
/* RequestNBSNotification.aspx */
/*******************************/

//Request NBS Notification
function RequestNBSNotification(address) {

    var addressRep = address.replace(/%/g, "'");
    map.RequestNBSNotification();
    requestNBS.SetSubmitted(false);
    requestNBS.SetAddress(addressRep);
}

function ReloadNBSNotification()
{
    var changed = requestNBS.GetDataChanged();
    var submitted = requestNBS.IsSubmitted();
    if (changed & !submitted)
        map.RemakeNBSNotification(requestNBS.GetFirstName(),
            requestNBS.GetSurname(),
            requestNBS.GetMail());
    requestNBS.SetDataChanged(false);
}

//Called from the iFrame (on submit clicked)
function RequestNBSSubmitted()
{
    requestNBS.SetSubmitted(true);
    map.RequestNBSSubmitted(requestNBS.GetAddress(), requestNBS.IsSubmitted());
}

//Called from the iFrame (on cancel clicked)
function RequestNBSCancelled()
{
    CancelRequestNBS(requestNBS.GetAddress());
    requestNBS.CleanData();
}

//Called from the iFrame (on ok clicked)
function RequestNBSOk()
{
    map.CancelRequestNBS(requestNBS.GetAddress(), requestNBS.IsSubmitted());
}

function CancelRequestNBS()
{
    map.CancelRequestNBS(requestNBS.GetAddress(), requestNBS.IsSubmitted());
    requestNBS.SetSubmitted(false);
}

//Called from the iFrame (on text introduced)
function SaveNotificationData(name,surname, mail)
{
    requestNBS.SaveData(name, surname, mail);
}

//**************************************************************************************************************************************
//**************************************************************************************************************************************

//Clean up all objects
function Page_Unload()
{
    if (map != null)
    {
        map.Dispose();
        map = null;
    }
}

//set page event handlers
if (window.attachEvent)
{
    window.attachEvent("onload", Page_Load);
    window.attachEvent("onunload", Page_Unload);
} else
{
    window.addEventListener("DOMContentLoaded", Page_Load, false);
    window.addEventListener("unload", Page_Unload, false);
}

if (typeof (Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
