﻿// JScript File
// TW Map Api Key = "ABQIAAAACpVVepRB_8LlWZS5c-WAKxSARb386zDFOwsQec9aq2PMEB-MjRSnLy0amVttuel5Fpyb928Fh0DQig"
var map = null;
//var gSearch = null;
var veLatLongArray = null;
var defaultLocation = new GLatLng(54.495567521874065,-4.526367187500011);
var mapZoomLevel, initialRequest, ajaxRequest, markers, loadingElement;
var topRight, bottomLeft;

function initialiseMap()
{
    veLatLongArray = Array();
    mapZoomLevel = 5;
    initialRequest = true;
    ajaxRequest = false;
    
    setupMap();
    getLatLongs();
}

function setupMap()
{
    if(map == null)
    {
        map = new GMap2(document.getElementById('myMap'), {size:new GSize(452, 370)});
        map.setCenter(defaultLocation, mapZoomLevel);
//        map.setUIToDefault();
        
       gMapUiOpts = map.getDefaultUI();
//        gMapUiOpts = new GMapUIOptions(new GSize(400,300));
        gMapUiOpts.maptypes.physical = false;
//        
        map.setUI(gMapUiOpts);
        markers = new Array();
    }
}

function getLatLongs()
{
    showLoading();
    
    var width = map.getSize().width;
    var height = map.getSize().height;
    
    var topLeft, bottomRight;

    topLeft = map.fromDivPixelToLatLng(new GPoint(0,0)).toString();
    bottomRight = map.fromDivPixelToLatLng(new GPoint(width,height)).toString();
    
    //strip parenthesises
    topLeft = topLeft.substr(1, topLeft.length - 2);
    bottomRight = bottomRight.substr(1, bottomRight.length - 2);
    
    CallWebService(map.getZoom(), width, height, topLeft, bottomRight);
}

var newStartupNodes = new Array();

function IncomingPinsJson(data)
{
    var serverData = getPinsArray(data);
    
    if(serverData != null)
    {
        var pinsCount = serverData["pins"].length;
        
        for(var i = 0; i < pinsCount; i++)
        {
            var pinData = serverData["pins"][i];
            
            addPin(pinData["lat"], pinData["long"], pinData["title"], pinData["description"], pinData["url"], pinData["image"]);
            
            newStartupNodes[i] = new GLatLng(pinData["lat"], pinData["long"]);
        }
        
        if(initialRequest)
        {
            initialRequest = false;
            captureZoomAndPan();
            setMapView(startupNodes);
        }
        else if(ajaxRequest)
        {
            ajaxRequest = false;
            setMapView(newStartupNodes);
        }
        
        hideLoading();
    }
}

function setMapView(pins)
{
    var n, e, s, w;
    
    for(var i = 0; i < pins.length; i++)
    {
        var pinLat, pinLng;
        
        pinLat = pins[i].lat();
        pinLng = pins[i].lng();
    
        if(!n) n = pinLat;
        if(!s) s = pinLat;
        if(!e) e = pinLng;
        if(!w) w = pinLng;
        
        if(pinLat > n) n = pinLat;        
        if(pinLat < s) s = pinLat;        
        if(pinLng > e) e = pinLng;        
        if(pinLng < w) w = pinLng;    
    }
    
    var bounds = new GLatLngBounds(new GLatLng(s, w), new GLatLng(n, e));
    
    map.setZoom(map.getBoundsZoomLevel(bounds));
    map.setCenter(bounds.getCenter());
}

function captureZoomAndPan()
{
    GEvent.addListener(map, "moveend", function(oldLevel, newLevel){updateMap();});
}

function updateMap(setZoom)
{
    mapZoomLevel = map.getZoom();
    
    markers.length = 0;
    
    map.clearOverlays();
    veLatLongArray = Array();
    
    if(setZoom)
    {
        map.setZoom(mapZoomLevel);
    }

    getLatLongs();
}

function getPinsArray(data)
{
    var array = null;
    
    if(data.substring(0, 2) == "/*" && data.substring(data.length - 2) == "*/")
    {
        var formattedData = data.substring(2, data.length - 2);
        array = eval("(" + formattedData + ")");
    }
    
    return array;
}

function addPin(lat, lng, title, desc, url, image)
{
    //var theme = getThemeFromHost(location.hostname);
    
    //var redirect = (url.indexOf("DevelopmentRedirect.aspx") != -1);
    
    var cluster = (title == "Multiple developments");
    
    var houseIcon = new GIcon(G_DEFAULT_ICON);
    var imagePath = "/gw/images/";
    
    houseIcon.image = cluster ? imagePath + "multiple_houses.gif" : imagePath + "map_house.gif";
    houseIcon.iconSize = cluster ? new GSize(24, 24) : new GSize(16, 16);
    houseIcon.iconAnchor = new GPoint(5,16);
    houseIcon.shadowSize = new GSize(0, 0);
   
    var loc = new GLatLng(lat, lng);
    
    var pin = new GMarker(loc, {icon:houseIcon});
    
    var infoOverlayHtml = new houseInfoOverlay(pin, generateInfoHtml(title, desc, url, image));
    
    map.addOverlay(pin);
    
    GEvent.addListener(pin, "mouseover", function() { displayHouseOverlay(pin, infoOverlayHtml); });
    GEvent.addListener(pin, "mouseout", function() { hideHouseOverlay(this); });

    markers.push(pin);
    veLatLongArray.push(loc);
}

function displayHouseOverlay(pin, overlay)
{
    if(houseOverlayMarkerTimer)
    {
        clearTimeout(houseOverlayMarkerTimer);
        hideHouseOverlayNow();
    }
    
    if(!pin.overlay)
    {
        pin.overlay = overlay;
        map.addOverlay(overlay);
    }
}

var houseOverlayMarker = null;
var houseOverlayMarkerTimer = null;

function hideHouseOverlay(marker)
{
    houseOverlayMarker = marker;
    houseOverlayMarkerTimer = setTimeout('hideHouseOverlayNow()', 3000);
}

function hideHouseOverlayNow()
{
    map.removeOverlay(houseOverlayMarker.overlay);
    houseOverlayMarker.overlay = null;
    houseOverlayMarkerTimer = null;
}

function generateInfoHtml(title, desc, url, imageSrc)
{
    var cluster = (title == "Multiple developments");

    var outer = document.createElement("div");
    
    var container = document.createElement("div");
    container.className = "pinInfo";
    
    var titleDiv = document.createElement("div");
    titleDiv.className = "VE_Pushpin_Popup_Title";
    
    if(cluster)
    {
        titleDiv.innerHTML = "Developments from: <br/>";
    }
    else
    {  
        titleDiv.innerHTML = "<p>Development from Laing homes:</p><a href=\"" + url +"\" class=\"linkNormal\">"+ (title.indexOf("<li>")>-1 ? title.substring(4) : title) +"</a>";
    }
    
    var bodyDiv = document.createElement("div");
    bodyDiv.className = "VE_Pushpin_Popup_Body";
    
    if(cluster)
    {
        bodyDiv.innerHTML = "<ul>" + unescape(desc) + "</ul>";
    }
    else
    {
        bodyDiv.innerHTML = "<a class=\"linkNormal\" href=\"" + url +"\"><img src=\""+imageSrc+"\"></img></a><br/>"+desc;
    }
    
    container.appendChild(titleDiv);
    container.appendChild(bodyDiv);
    
    outer.appendChild(container);
    
    return outer.innerHTML;
}


///Loading
function showLoading()
{
    //map.addOverlay(new loadingOverlay);
}

function hideLoading()
{
//    map.removeOverlay(loadingElement);
//    loadingElement = null;
}

///Custom overlays
function houseInfoOverlay(_marker, _html) 
{
    this.marker = _marker;
    this.html = _html;
}

houseInfoOverlay.prototype = new GOverlay();
houseInfoOverlay.prototype.initialize = function(map)
                                        {
                                            var div = document.createElement("div");
                                            div.style.position = "absolute";
                                            div.style.height = "auto";
                                            div.style.width = "150px";
                                            div.style.color = "#000";
                                            div.style.backgroundColor = "#FFF";
                                            div.style.padding = "3px";
                                            div.style.border = "solid 1px #676767";
                                            div.innerHTML = this.html;

                                            var left = (map.fromLatLngToDivPixel(this.marker.getLatLng()).x + 15);
                                            var top = (map.fromLatLngToDivPixel(this.marker.getLatLng()).y - 30);

                                            div.style.top = top + "px";
                                            div.style.left = left + "px";
                                            
                                            map.getPane(G_MAP_FLOAT_PANE).appendChild(div);
                                            
                                            this._map = map;
                                            this._div = div;                                                                            
                                        }
houseInfoOverlay.prototype.remove = function()
                                    {
                                        var element = this;
                                        
                                        element._div.parentNode.removeChild(element._div);
                                    }
houseInfoOverlay.prototype.redraw = function(force)
                                    {
                                        var left = (this._map.fromLatLngToDivPixel(this.marker.getLatLng()).x + 15);
                                        var top = (this._map.fromLatLngToDivPixel(this.marker.getLatLng()).y - 30);
                                        
                                        this._div.style.top = top + "px";
                                        this._div.style.left = left + "px";
                                    }                                    

function loadingOverlay() {}
loadingOverlay.prototype = new GOverlay();
loadingOverlay.prototype.initialize = function(_map)
                                      {
                                        var element = getLoadingElement();
                                        
                                        _map.getPane(G_MAP_FLOAT_PANE).appendChild(element);
                                        
                                        this.parentMap = _map;
                                        this.div = element;
                                        
                                        loadingElement = this;
                                      }

loadingOverlay.prototype.remove = function()
                                  {
                                    this.div.parentNode.removeChild(this.div);
                                  }
                                  
loadingOverlay.prototype.redraw = function(force)
                                  {
                                    return;
                                  }

function getLoadingElement()
{
    if(document.getElementById("VELoading") == null)
    {
        var el = document.createElement("div");
        el.setAttribute("id", "VELoading");
        
        var currWidth = map.getSize().width;
        var currHeight = map.getSize().height;
        
        el.style.position = "absolute";
        el.style.top = ((currHeight - 25) / 2) + "px";
        el.style.left = ((currWidth - 105) / 2) + "px";
        el.style.border = "1px solid gray";
        el.style.font = "12px ariel";
        el.style.background = "white";
        el.style.padding = "2px";
        el.style.verticalAlign = "middle";
        el.style.zIndex = "1000";
        el.style.width = "195px";
        el.innerHTML = "<img src='/gw/images/spinner.gif' />&nbsp;Please Wait. Loading data...";
        
        return el;
    }
}