﻿// 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(574, 370)});
        map.setCenter(defaultLocation, mapZoomLevel);
        
        gMapUiOpts = map.getDefaultUI();
        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.fromContainerPixelToLatLng(new GPoint(0,0)).toString();
    bottomRight = map.fromContainerPixelToLatLng(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 cluster = (title == "Multiple properties");
    
    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 properties");

    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 = title + "<br/>";
    }
    else
    {  
        titleDiv.innerHTML = "<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+"\" /></a><br/>"+desc;
    }
    
    container.appendChild(titleDiv);
    container.appendChild(bodyDiv);
    
    outer.appendChild(container);
    
    return outer.innerHTML;
}


///Loading
function showLoading()
{
    if(document.getElementById("VELoading")) return;
    
    document.getElementById("myMap").appendChild(getLoadingElement());
}

function hideLoading()
{
    if(!document.getElementById("VELoading")) return;
    
    document.getElementById("myMap").removeChild(document.getElementById("VELoading"));
}

///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 overlayPos = getOverlayPositionRelativeToMapEdges(this.marker, div);

                                            div.style.top = overlayPos.y + "px";
                                            div.style.left = overlayPos.x + "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 overlayPos = getOverlayPositionRelativeToMapEdges(this.marker, this._div);
                                        
                                        this._div.style.top = overlayPos.y + "px";
                                        this._div.style.left = overlayPos.x + "px";
                                    }                                    

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;
    }
}

function getOverlayPositionRelativeToMapEdges(_marker, element)
{
    var divWidth = 150;
    var divHeight = element.offsetHeight;

    var height = map.getSize().height;
    var width = map.getSize().width;
    
    var markerPosX = map.fromLatLngToContainerPixel(_marker.getLatLng()).x;
    var markerPosY = map.fromLatLngToContainerPixel(_marker.getLatLng()).y;
    
    var xPos = map.fromLatLngToDivPixel(_marker.getLatLng()).x + 15;
    var yPos = map.fromLatLngToDivPixel(_marker.getLatLng()).y - 12;
    
    if((markerPosX + divWidth + 100) >= width)
    {
        xPos -= divWidth + 30;
    }
    
    if((markerPosY + divHeight) >= height)
    {
        yPos -= divHeight + 3;
    }
    
    return {x:xPos, y:yPos};
}
