﻿
var qtask = null;
var query = null;
var mapExtension = null;
var gOverlays = null;
var flag = false;
var geocoder = new GClientGeocoder();
var xmlhttp;
var assetAddress;
var assetLat;
var assetLon;
var assetName;
var iconList = [];

/*//Takes list passed from Aspx function
function getIconListi(icons) {
    iconList = icons;
}*/

function mycallback(fset) {
    // add the feature set to google map without any style
    gOverlays = mapExtension.addToMap(fset);
}

// Clears map of markers, points and marker overlays
function clearMap() {
    clearOverlays();    
    mapPoints = [];
    mapMarkers = [];
}

//Only clears overlays for markers and not RH polygon boundary
function clearOverlays() {
    for (var i = 0; i < mapMarkers.length; i++) {
        gmap.removeOverlay(mapMarkers[i]);
        gmap.removeOverlay(mapMarkers[i].tooltip);
    }
}

//Clears asset result list and number of results found
function clearList() {
    assetResult = "RESULT";
    $("#totalresult").html("FOUND - 0");
    var htmllist = '';
    htmllist = "<ul id='ul_assetslist'>";
    htmllist += "</ul>";
    $('#assetslist').html(htmllist);
}

//Retrieve data from service and show on map as markers
function loadAsset(searchType, searchKey) {

    clearMap();
    GDownloadUrl("./Controller/SearchFor_Service.ashx?service=" + searchType + "&param=" + searchKey, function(data, responseCode) {
        var xml = GXml.parse(data);
        var markers = xml.documentElement.getElementsByTagName("ASSET");
        
        //Displays markers only if results returned
        if (markers.length == 0) {
            alert("There are no facilities to display on the map.");
        }
        else {
            updateAssetList(markers);
            showMap();

            if (flag == true) {
                getAssetInfo(mapMarkers[0].id, "");
                flag = false;
            }

        }
    });

}

//Get specific asset data based on asset ID
function getAssetInfo(id, markerIndex) {
    xmlhttp = GetXmlHttpObject();
    
    if (xmlhttp == null) {
        alert("Your browser does not support AJAX");
        return;
    }
    
    var assetId = parseInt(id);
    url = "./Controller/SearchFor_Service.ashx?service=byAssetID&param=" + id;
    
    //on ready state, call to populate panel
    xmlhttp.onreadystatechange = popPanel;
    xmlhttp.open("GET", url, true);
    xmlhttp.send(null);

    //Display panel about specific asset
    showPanel();

    //Hide ForAsset div for IE6 purposes
    hideDiv();      
}

//Retrieves xml data request and returns to caller
function GetXmlHttpObject() {
       
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        return new XMLHttpRequest();
    }
    else {
        // code for IE6, IE5
        return new ActiveXObject("Microsoft.XMLHTTP");
    }    
}

//Populate panel with info on specific asset
function popPanel() {
    if (xmlhttp.readyState == 4) {
        var xmlDoc = xmlhttp.responseXML.documentElement;
        var assetID = parseInt(xmlDoc.getElementsByTagName("ID")[0].childNodes[0].nodeValue);
        var image = xmlDoc.getElementsByTagName("IMAGE")[0].childNodes[0].nodeValue;
        var description = xmlDoc.getElementsByTagName("DESCRIPTION")[0].childNodes[0].nodeValue;
        var link = xmlDoc.getElementsByTagName("LINK")[0].childNodes[0].nodeValue;
        
        //Global variables declared earlier
        assetName = xmlDoc.getElementsByTagName("NAME")[0].childNodes[0].nodeValue;
        assetAddress = xmlDoc.getElementsByTagName("ADDRESS")[0].childNodes[0].nodeValue;
        if (assetAddress == "_") { assetAddress = ""; }        
        assetLat = xmlDoc.getElementsByTagName("LATITUDE")[0].childNodes[0].nodeValue;
        assetLon = xmlDoc.getElementsByTagName("LONGITUDE")[0].childNodes[0].nodeValue;

        //Display name and address
        document.getElementById("assettitle").innerHTML = assetName;
        document.getElementById("assetaddress").innerHTML = assetAddress;

        //Call to display description and attribute details
        prepareDescription(description);
        prepareDetails(xmlDoc);

        //Call to display asset photo and links to TRH web pages
        getImage(image);
        getLink(link);
    }    
}

//Displays description of asset in panel
function prepareDescription(paragraph) {

    var description = "<div id=\"paneldescription\" class=\"paneldescription\">" + paragraph + "</div><br /><div id=\"assetlink\" class=\"assetlink\"></div>";
    
    $("#assetdescription").html(description);
}

//Displays list of attribute details on panel
function prepareDetails(xmlDoc) {

    //Get the detail type values from the data if the DETAIL node is not empty
    if (xmlDoc.getElementsByTagName("DETAIL")[0].childNodes[0] != null) {

        //Get the list values from the data
        var x = xmlDoc.getElementsByTagName("TYPE");
        var list = "<ul>";

        for (i = 0; i < x.length; i++) {
            detailtype = xmlDoc.getElementsByTagName("TYPE")[i].childNodes[0].nodeValue;
            if ((detailtype != " ") && (detailtype != "CDATA") && (detailtype != ""))
                list += "<li>" + detailtype + "</li>";
        }
        list += "</ul>";

        $("#attributeslist").html(list);

        //Hide Description on panel
        hideDescription();
    }
    else {
        //Otherwise, clear html list
        $("#attributeslist").html("");
        
        //Show Description on panel
        showDescription();
    }
}

//Updates the asset list returned, including total number found and calls to create markers on the map
function updateAssetList(markers) {
    
    document.getElementById("totalresult").innerHTML = "FOUND - " + markers.length;
    htmllist = "<ul id='ul_assetslist'>";  
    
    for (var i = 0; i < markers.length; i++) {
        var point = new GLatLng(parseFloat(markers[i].getAttribute("LATITUDE")), parseFloat(markers[i].getAttribute("LONGITUDE")));
        var assetID = markers[i].getAttribute("ID");
        var assetName = markers[i].getAttribute("NAME");
        var assetAddress = markers[i].getAttribute("ADDRESS");
        if (assetAddress == "_") { assetAddress = ""; }
        
        point.id = assetID;
        point.assetname = assetName;
        point.name = "<div class='info-window'><b>" + assetName + "</b> <br>" + assetAddress + "</div>";
        htmllist = htmllist + "<li id=\"" + assetID + "\" onmouseout=\"resetMarker(lastSelected)\" onmouseover=\"showMarker(id," + i + ")\" onclick=\"getAssetInfo(id," + i + ")\"><a href='#'><strong>" + assetName + "</strong><br><div style=\"color:#848484;\">" + assetAddress + "</div></a></li>";

        //Calls to create marker and adds to global mapMarkers array
        mapMarkers.push(createAssetMarker(point));
    }
    htmllist = htmllist + "</ul>";

    document.getElementById("assetslist").innerHTML = htmllist;

    if (markers.length == 1) {
        //Show panel if only one facility returned
        getAssetInfo(assetID, 1);
    }
}

/*//Creates asset marker based on set styles
function createAssetMarker(point) {

    // Creates marker icon with shadow (shadowSize should be defined to avoid default shadow placement)
    //var icon = new GIcon(G_DEFAULT_ICON);

    //Creates marker icon without shadow (even if shadowSize is defined)
    var icon = new GIcon("asset");
    
    //NOTE: Image declared must be 32X32 pixels. IE won't display otherwise.

    //If assetIcon.png doesn't exist, use Default.png
    //NOTE: icons folder must only have icons exactly named after the facility types (excluding Highlight and Default)
    //This is necessary to assign an icon.image that actually exists
    if (iconList.match(assetIcon)) {
        icon.image = "images/icons/" + assetIcon + ".png";
    }
    else {
        icon.image = "images/icons/Default.png";
    }
    
    icon.iconSize = new GSize(32, 32);
    icon.shadowSize = new GSize(56, 32);
    icon.iconAnchor = new GPoint(5, 25);
    icon.infoWindowAnchor = new GPoint(15, 25);
    var marker = new GMarker(point, icon);

    var tooltip = new Tooltip(marker, point.assetname, 5);
    marker.tooltip = tooltip;
    marker.id = point.id;

    //On mouse over, calls to change to highlight icon
    GEvent.addListener(marker, "mouseover", function() {
        changeMarker(this);
    });

    //On mouse out, calls to rest to original icon
    GEvent.addListener(marker, "mouseout", function() {
        resetMarker(this);
    });

    //On click, calls to get specific asset info by ID
    GEvent.addListener(marker, "click", function() {
        getAssetInfo(point.id, "");
    });

    return marker;
}

//Changes to highlight icon
function changeMarker(marker) {
    marker.tooltip.show();
    marker.setImage("images/icons/Highlight.png");
    lastSelected = marker;
}

//Returns to original icon, based on asset type
function resetMarker(marker) {

    for (var i = 0; i < mapMarkers.length; i++) {
        mapMarkers[i].tooltip.hide();
    }
    
    //If assetIcon.png doesn't exist, use Default.png
    if (iconList.match(assetIcon)) {
        marker.setImage("images/icons/" + assetIcon + ".png");
    }
    else {
        marker.setImage("images/icons/Default.png");
    }
}*/

//Creates asset marker based on set styles
function createAssetMarker(point) {

    //var icon = genIcon();
    // Creates marker icon with shadow (shadowSize should be defined to avoid default shadow placement)
    //var icon = new GIcon(G_DEFAULT_ICON);

    //Creates marker icon without shadow (even if shadowSize is defined)
    var icon = new GIcon("asset");

    //NOTE: Image declared must be 32X32 pixels. IE won't display otherwise.

    //If assetIcon.png doesn't exist, use Default.png
    //NOTE: icons folder must only have icons exactly named after the facility types (excluding Highlight and Default)
    //This is necessary to assign an icon.image that actually exists
    /*if (iconList.match(assetIcon)) {
    icon.image = "images/icons/" + assetIcon + ".png";
    }
    else {
    icon.image = "images/icons/Default.png";
    }*/

    //Set default colour if none available
    if (iconColour.length != 6) { iconColour = "999999"; }

    //Uses icons generated from the Google Charts API
    icon.image = "http://chart.apis.google.com/chart?cht=mm&chs=32x32&chco=" + iconColour + "," + iconColour + ",000000&ext=.png";
    
    icon.iconSize = new GSize(32, 32);
    icon.shadowSize = new GSize(56, 32);
    icon.iconAnchor = new GPoint(5, 25);
    icon.infoWindowAnchor = new GPoint(15, 25);
    var marker = new GMarker(point, icon);

    var tooltip = new Tooltip(marker, point.assetname, 5);
    marker.tooltip = tooltip;
    marker.id = point.id;

    //On mouse over, calls to change to highlight icon
    GEvent.addListener(marker, "mouseover", function() {
        changeMarker(this);
    });

    //On mouse out, calls to rest to original icon
    GEvent.addListener(marker, "mouseout", function() {
        resetMarker(this);
    });

    //On click, calls to get specific asset info by ID
    GEvent.addListener(marker, "click", function() {
        getAssetInfo(point.id, "");
    });

    return marker;
}

//Changes to highlight icon
function changeMarker(marker) {
    //var icon = genIcon();
    marker.tooltip.show();
    //marker.setImage("images/icons/Highlight.png");
    marker.setImage("http://chart.apis.google.com/chart?cht=mm&chs=32x32&chco=FFFFFF," + iconColour + "," + iconColour + "&ext=.png");

    lastSelected = marker;
}

//Returns to original icon, based on asset type
function resetMarker(marker) {

    for (var i = 0; i < mapMarkers.length; i++) {
        mapMarkers[i].tooltip.hide();
    }

    /*//If assetIcon.png doesn't exist, use Default.png
    if (iconList.match(assetIcon)) {
    marker.setImage("images/icons/" + assetIcon + ".png");
    }
    else {
    marker.setImage("images/icons/Default.png");
    }*/

    marker.setImage("http://chart.apis.google.com/chart?cht=mm&chs=32x32&chco=" + iconColour + "," + iconColour + ",000000&ext=.png");

}

//Displays marker on the map
function showMarker(id, markerIndex) {

    //Only zoom in and centralize on point if scale zoomed in beyond scale level 11
    if (gmap.getZoom() > 11) {
        gmap.panTo(mapMarkers[markerIndex].getLatLng());
    }
    
    GEvent.trigger(mapMarkers[markerIndex], "mouseout");
    GEvent.trigger(mapMarkers[markerIndex], "mouseover");
    
    changeMarker(mapMarkers[markerIndex]);
}

// Show Google map with zoom scale limits
function showMap() {
    // Find boundary points of locations
    var bounds = new GLatLngBounds();
    for (var i = 0; i < mapMarkers.length; i++) {
        gmap.addOverlay(mapMarkers[i]);
        gmap.addOverlay(mapMarkers[i].tooltip);
        bounds.extend(mapMarkers[i].getPoint());
    }

    // Reset centre based on queried locations
    gmap.setCenter(bounds.getCenter());

    //Reset zoom level based on queried locations: If only 1 location, set to zoom level 14
    if (mapMarkers.length == 1) {
        gmap.setZoom(14);        
    }
    else {
        //Don't zoom out further than initial zoom level
        if (gmap.getBoundsZoomLevel(bounds) == 11) {
            gmap.setZoom(11);
        }
        else {
            //Zoom out an additional level to accommodate window widths less than maximized width
            //at a resolutions 1024 X 728 and under
            gmap.setZoom(gmap.getBoundsZoomLevel(bounds) - 1);
        }
    }
}

//Passes to and from addresses to Google Maps Get Directions page
function get_directions_ByCoords() {
    
    //global variables declared earlier
    directionFrom = document.getElementById('from_address').value;
    //directionTo = assetAddress + ",Richmond Hill,ON,CA";
    directionTo = "  -  " + assetAddress + ", Richmond Hill, ON, CA";

    if (assetAddress == "") { directionTo = ""; }
    
    if (assetLat == "" || assetLon == "") {
        alert("This feature has no address to get directions to.");        
    }
    else {
        if ((directionFrom == "") || (directionFrom == "Type Address or Postal Code")) {
            alert("Please enter a valid address or postal code first.");
        }
        else {

            //This removes '()' in asset name.  The asset name is already bracketed below.
            //Additional bracket pairs result in the user having to select the ideal location 
            //from a list on the Google Maps Get Directions page.
            var assetNameMod = assetName;
            assetNameMod = assetNameMod.replace("(", "/ ");
            assetNameMod = assetNameMod.replace(")", " ");
            
            //This format allows Google to search by address, but display the name as the title
            //var directionToGM = assetLat + "," + assetLon + " (" + assetNameMod + ")";
            var directionToGM = assetLat + "," + assetLon + " (" + assetNameMod + directionTo + ")";
            
            //Opens Google Maps page in a new window, passing addresses
            //window.open("http://maps.google.com/maps?saddr=" + directionFrom + "&daddr=" + directionToGM, "getDirectionWindow", "status=1,toolbar=1,menubar=1,scrollbars=1,resizable=1");
            window.open("http://maps.google.com/maps?saddr=" + directionFrom + "&daddr=" + directionToGM, "getDirectionWindow");
        
        }
    }
    return false;
}

//Passes to and from addresses to Google Maps Get Directions page
function get_directions() {

    //global variables declared earlier
    directionFrom = document.getElementById('from_address').value;
    directionTo = assetAddress + ",Richmond Hill,ON,CA";

    if (directionTo == " ,Richmond Hill,ON,CA") {
        alert("This feature has no address to get directions to.");
    }
    else {
        if ((directionFrom == "") || (directionFrom == "Type Address or Postal Code")) {
            alert("Please enter a valid address or postal code first.");
        }
        else {

            //This removes '()' in asset name.  The asset name is already bracketed below.
            //Additional bracket pairs result in the user having to select the ideal location 
            //from a list on the Google Maps Get Directions page.
            var assetNameMod = assetName;
            assetNameMod = assetNameMod.replace("(", "/ ");
            assetNameMod = assetNameMod.replace(")", " ");

            //This format allows Google to search by address, but display the name as the title
            var directionToGM = directionTo + " (" + assetNameMod + ")";

            //Opens Google Maps page in a new window, passing addresses
            window.open("http://maps.google.com/maps?saddr=" + directionFrom + "&daddr=" + directionToGM, "getDirectionWindow", "status=1,toolbar=1,menubar=1,scrollbars=1,resizable=1");
        }
    }
    return false;
}

//Resets panel and calls to close
function hideAndClose() {
    //If description panel is down, return to original hidden position
    hideDescription();

    //reset text value to 'Type Address or Postal Code'
    $("#from_address").val('Type Address or Postal Code');

    //call to close panel
    closePanel();
}

//Displays description on panel
function showDescription() {
    $('.assetdescription').slideDown();
    $('#attributeslist').slideUp();
    $('#showattributes_icon').show();
    $('#showdescription_title').show();
    $('#showattributes_title').hide();
    $('#showdescription_icon').hide();
}

//Hides description on panel
function hideDescription() {
    $('.assetdescription').slideUp();
    $('#attributeslist').slideDown();
    $('#showattributes_icon').hide();
    $('#showdescription_title').hide();
    $('#showattributes_title').show();
    $('#showdescription_icon').show();
}

//Displays asset photo on panel
function getImage(image) {
    var photodiv = "";

    //if (image == "None") {
    if (image == "_") {
        //Display default photo
        photodiv = "<img src=\"images/rhill_logo_colour5.bmp\" />";
    }
    else {
        //Display image specific to asset
        //photodiv = "<img src=\"images/Asset_Images/" + image + "\" />";
        photodiv = "<img src=\"Asset_Images/" + image + "\" />";
    }
    document.getElementById("assetphoto").innerHTML = photodiv;
}

//Displays multiple links to TRH web page
function getLinks(links) {
    var linkdiv = "";

    if (links[0].getAttribute('URL') != "_") {
        for (var i = 0; i < links.length; i++) {
            //Display link to Town website specific to asset
            linkdiv += "<a href=\"" + links[i].getAttribute('URL') + "\" target=\"_blank\">" + links[i].getAttribute('NAME') + "</a><div class=\"smallbreak\"></div>";
        }
    }
    
    $("#assetlink").html(linkdiv);
}

//Displays link to TRH web page
function getLink(link) {
    var linkdiv = "";
    //if (link == "None") {
    if (link == "_") {
        //Don't display link
        linkdiv = "";
    }
    else {
        //Display link to Town website specific to asset
        linkdiv = "<a href=\"" + link + "\" target=\"_blank\">Click for more details</a>";
    }
    $("#assetlink").html(linkdiv);
}

//Displays panel, by sliding out from the right
function showPanel() {
    
    $("#panel").fadeIn();
}

//Hides panel, by sliding in to the right (no longer seen, because css overflow set to hidden)
function closePanel() {
    
    $("#panel").fadeOut();   

    //Call to show ForAsset again
    showDiv();
}


function hideDiv() {
    var assetDiv = document.getElementById("ForAsset");
    assetDiv.style.display = "none";
    
}

function showDiv() {
    
    var assetDiv = document.getElementById("ForAsset");
    assetDiv.style.display = "block";
}



