﻿var map;
var modalMap;
var tooltip;
var origCenterX;
var origCenterY;
var mapSize;
var mapWidth;
var mapHeight;
var bounds = null;
var isShortlist = false;
/**************************/
// set up links
$(document).ready(function() {
$(".mapLink").css("visibility", "visible");
});


// register escape key to close popup map
$(document).keyup(function(event) {
    if (event.keyCode == 27) {
        removeMapPopup();
    }
});
/**************************/


function drawMap(point, zoom, zoomControl, hasMapTypes, isDraggable, shortlistPage) {
    if (!hasMapTypes) {
        map = new GMap2(document.getElementById('map'), { mapTypes: [G_NORMAL_MAP] });
    }
    else {
        map = new GMap2(document.getElementById('map'), { mapTypes: [G_NORMAL_MAP, G_SATELLITE_MAP, G_PHYSICAL_MAP] });
    }
    if (!isDraggable) { map.disableDragging(); }

    switch (zoomControl) {
        case "Small":
            map.addControl(new GSmallZoomControl3D());
            break;
        case "Large":
            map.addControl(new GLargeMapControl3D());
            break;
    }
    map.addControl(new GMapTypeControl());
    map.setCenter(point, zoom);
    origCenterX = map.fromLatLngToDivPixel(map.getCenter()).x;
    origCenterY = map.fromLatLngToDivPixel(map.getCenter()).y;

    tooltip = document.createElement('div');
    map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltip);
    tooltip.style.visibility = 'hidden';
    bounds = new GLatLngBounds();
    mapSize = map.getSize();
    mapWidth = mapSize.width;
    mapHeight = mapSize.height;
    isShortlist = shortlistPage;
}

function createMarker(point, id, title, count, type, hasClick, hasTooltip) {
    var marker = new GMarker(point, {
        icon: GetIcon(type),
        clickable: hasClick 
     });
     if (hasTooltip) {
        marker.tooltip = '<div class="tooltip" id="tip' + id + '">' + title;

        if (type != "House") {
            marker.tooltip += '<br />' + count + ' house';
            if (count > 1) { marker.tooltip += 's'; }
        }
        marker.tooltip += '</div>';
    }
    marker.id = id;
    map.addOverlay(marker);

    if (hasClick) { GEvent.addListener(marker, "click", function() { markerClick(marker, type); }); }
    if (hasTooltip) {
        GEvent.addListener(marker, "mouseover", function() { showTooltip(marker); });
        GEvent.addListener(marker, "mouseout", function() { tooltip.style.visibility = "hidden"; });
    }
    bounds.extend(point);
}

function markerClick(marker,type) {
    tooltip.style.visibility = "hidden";

    switch (type) {
        case "House":
            var url = "/AJAX/ajax_mapHouseInfoWindow.aspx?houseID=" + marker.id + "&shortlist=" + isShortlist;
            jQuery.get(url, function(data) {
                marker.openInfoWindowHtml(data);
            });
            break;

        case "Location":
            var locationURL = "";
            var locationQS = "";
            var qs = window.location.search.substring(1);
            var qsSplit = qs.split("&");
            var keySplit;
            for (var i = 0; i < qsSplit.length; i++) {
                keySplit = qsSplit[i].split("=");
                if (keySplit[0] != "location") {
                    locationQS += "&" + qsSplit[i];
                }
            }
            locationQS += "&location=" + marker.id;
            locationURL = window.location.pathname + "?" + locationQS.substring(1);
            window.location = locationURL;
            break;

        case "Region":
            var regionURL = "";
            var regionQS = "";
            var qs = window.location.search.substring(1);
            var qsSplit = qs.split("&");
            var keySplit;
            for (var i = 0; i < qsSplit.length; i++) {
                keySplit = qsSplit[i].split("=");
                if (keySplit[0] != "region") {
                    regionQS += "&" + qsSplit[i];
                }
            }
            regionQS += "&region=" + marker.id;
            regionURL = window.location.pathname + "?" + regionQS.substring(1);
            window.location = regionURL;
            break;
    }
}

function GetIcon(type) {
    var icon = new GIcon();
    icon.image = "/Images/Maps/pin" + type + ".png";
    icon.iconSize = new GSize(20, 19);
    icon.iconAnchor = new GPoint(11, 19)
    icon.infoWindowAnchor = new GPoint(20, 10);
    icon.transparent = "/Images/Maps/pinTrans.png";
    if (type == "House") {
        icon.shadow = "/Images/Maps/houseShadow.png";
        icon.shadowSize = new GSize(26, 13);
    }
    else {
        icon.shadow = "/Images/Maps/pinShadow.png";
        icon.shadowSize = new GSize(20, 13);
    }
    return icon;
}

function showTooltip(marker) {
    var newCenterX = map.fromLatLngToDivPixel(map.getCenter()).x;
    var newCenterY = map.fromLatLngToDivPixel(map.getCenter()).y;
    var diffX = newCenterX - origCenterX;
    var diffY = newCenterY - origCenterY;

    tooltip.innerHTML = marker.tooltip;
    var thePoint = marker.getPoint();
    var markerPixel = map.fromLatLngToDivPixel(thePoint);

    // reposition if too close to edge
    // need 65 px space either side of marker (tooltip is 130px wide)
    if (markerPixel.x - diffX > (mapWidth-65)) {
        var tipX = (mapWidth -132) + diffX;
    }
    else if (markerPixel.x - diffX < 65) {
        var tipX = diffX;
    }
    else {
        var tipX = markerPixel.x - 65;
    }

    // reposition if too close to top
    // need height of marker plus height of tip plus height of controls
    var theTip = document.getElementById("tip" + marker.id);
    var tipHt = theTip.offsetHeight + 27;

    if ((markerPixel.y - diffY) < (tipHt + 52)) {
        var tipY = markerPixel.y;
    }
    else {
        var tipY = markerPixel.y - tipHt;
    }

    var tipGSize = new GSize(tipX, tipY);
    var tipPos = new GControlPosition(G_ANCHOR_TOP_LEFT, tipGSize);
    tipPos.apply(tooltip);
    tooltip.style.visibility = "visible";
}

function extendBounds() {
    var sw = bounds.getSouthWest();
    var ne = bounds.getNorthEast();

    var swPixel = map.fromLatLngToDivPixel(sw);
    var sw_X = swPixel.x;
    var sw_Y = swPixel.y;
    var swPixelNew = new GPoint(sw_X - 40, sw_Y + 10);
    var swNew = map.fromDivPixelToLatLng(swPixelNew)
    bounds.extend(swNew);

    var nePixel = map.fromLatLngToDivPixel(ne);
    var ne_X = nePixel.x;
    var ne_Y = nePixel.y;
    var nePixelNew = new GPoint(ne_X + 10, ne_Y - 50);
    var neNew = map.fromDivPixelToLatLng(nePixelNew)
    bounds.extend(neNew);

    var bdZoom = map.getBoundsZoomLevel(bounds);
    if (bdZoom < 19) {
        map.setZoom(bdZoom);
    }
    map.setCenter(bounds.getCenter());
}

var isIe6 = $.browser.msie && ($.browser.version == "6.0");

function toggleAnnoyingObjects_Map(state) {
	if (isIe6) {
		$("select").css({ visibility: state });
	}
}

function DrawModalMap(point, zoom, modalWidth, modalHeight, type, id, title, hasTitleLink, hasMarker, hasClick, shortlistPage) {
    isShortlist = shortlistPage;

    var db = document.body;
    var dde = document.documentElement;
    var docHeight = Math.max(db.scrollHeight, dde.scrollHeight, db.offsetHeight, dde.offsetHeight, db.clientHeight, dde.clientHeight);
    var docWidth = Math.max(db.scrollWidth, dde.scrollWidth, db.offsetWidth, dde.offsetWidth, db.clientWidth, dde.clientWidth);

    var WindowSize = getWindowSize();
    var WindowScroll = getScrollXY();
    var innerLeft = 0;
    var innerTop = 0;

    if (WindowSize[0] > modalWidth) {
        //window width - map width, divided by two, less map window padding
        innerLeft = ((WindowSize[0] - modalWidth) / 2) - 10;
    }
    if (WindowSize[1] > modalHeight) {
        //window height - map height, divided by two, less extra height
        innerTop = ((WindowSize[1] - modalHeight) / 2) - 30;
    }
    var mapX = WindowScroll[0] + innerLeft;
    var mapY = WindowScroll[1] + innerTop;

    $(document.body).prepend('<div class="mapShade lightboxClose" style="opacity: 0.7;filter:alpha(opacity=70);"></div>');
    var overlay = $(".mapShade");
    
    var isIe6 = $.browser.msie && ($.browser.version == "6.0");
    if (isIe6) {
    	//overlay.show();
    	$("#mapOverlayOuter").show();
    	overlay.css("filter", "alpha(opacity=70)");
    	overlay.css("height", docHeight + "px");
    } else {
		overlay.css( {opacity: "0.7"} );
	}
	
    var strHTML = "<div class='mapOverlayOuter' style='top:" + mapY + "px; left:" + mapX + "px; height:" + (modalHeight + 50) + "; width:" + (modalWidth + 20) + "px;' >";
    strHTML += "<div class='mapOverlayInner'>";
    strHTML += "<h1 class='mapPopupTitle'>";
    if (hasTitleLink) { strHTML += "<a href='/Browse/House.aspx?houseID=" + id + "'>"; }
    strHTML += escapeHTML(title);
    if (hasTitleLink) { strHTML += "</a>"; }
    strHTML += "</h1>";
    strHTML += "<a href='javascript:void(0);' class='mapPopupClose' style='font-size:13px' onclick='removeMapPopup();'>Close window</a>";
    strHTML += "<div id='modalMap' style='width: " + modalWidth + "px; height: " + modalHeight + "px;'></div>";
    strHTML += "</div>";
    strHTML += "</div>";
	
    var div = document.createElement('div');
    div.id = "mapPopup";
    div.innerHTML = strHTML;
    document.body.appendChild(div);

    modalMap = new GMap2(document.getElementById('modalMap'), { mapTypes: [G_NORMAL_MAP, G_SATELLITE_MAP, G_PHYSICAL_MAP] });
    modalMap.addControl(new GSmallZoomControl3D());
    modalMap.addControl(new GMapTypeControl());
    modalMap.setCenter(point, zoom);

    //add the marker
    if (hasMarker) {
        var marker = new GMarker(point, {
            icon: GetIcon(type),
            clickable: hasClick
        });
        marker.id = id;
        modalMap.addOverlay(marker);
        if (hasClick) { GEvent.addListener(marker, "click", function() { modalMarkerClick(marker, type); }); }
    }

    $(document).keyup(function(e) {
    	if (e.keyCode == 27) {
    		removeMapPopup();
    	}
    });

    toggleAnnoyingObjects_Map("hidden");

    $(".mapShade").click(function() { removeMapPopup(); });
    
    return false;
}

function removeMapPopup() {
	var div = document.getElementById("mapPopup");

	var isIe6 = $.browser.msie && ($.browser.version == "6.0");
	if (isIe6) {
		$(".mapShade").hide();
		$("#mapOverlayOuter").hide();
		$(".mapShade").remove();
	} else {
		$("#mapOverlayOuter").hide();
		$(".mapShade").remove();
	}
	toggleAnnoyingObjects_Map("visible");

    if (div) { div.parentNode.removeChild(div); }
}

function getWindowSize() {
    var myWidth = 0, myHeight = 0;
    if (typeof (window.innerWidth) == 'number') {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }
    return [myWidth, myHeight];
}

function getScrollXY() {
    var scrOfX = 0, scrOfY = 0;
    if (typeof (window.pageYOffset) == 'number') {
        scrOfY = window.pageYOffset;
        scrOfX = window.pageXOffset;
    } else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
        scrOfY = document.body.scrollTop;
        scrOfX = document.body.scrollLeft;
    } else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
        scrOfY = document.documentElement.scrollTop;
        scrOfX = document.documentElement.scrollLeft;
    }
    return [scrOfX, scrOfY];
}

function saveLinkClicked(event) {
    event.preventDefault();

    var link = $(event.target);
    var parentParagraph = link.parent();

    jQuery.get(link.attr("href"), function() {
        parentParagraph.html("Saved to <a href='/Shortlist/'>Shortlist</a>");
    });

    parentParagraph.html("Saving...");
}

function InfoWindowSaveToShortlist(houseID,link){
    var parentParagraph = $(link).parent();
    var url = "/Shortlist/AddToShortlist.aspx?houseID=" + houseID + "&type=ajax";

    jQuery.get(url, function(data) {
        if (data == "added") {
            parentParagraph.html("Saved to <a href='/Shortlist/'>Shortlist</a>");
        }

        // update the shortlist count
        if ($(".shortlist").length > 0) {
            // append the count
            $(".shortlist").append("<span>1</span>");

            // update the class
            $(".shortlist").attr("class", "shortlistnum");
        }
        else {
            // update the class
            var countSpan = $(".shortlistnum span");
            if (countSpan.length > 0) {
                var currentCount = parseInt(countSpan.html());
                countSpan.html(currentCount + 1);
            }
        }

    });

    parentParagraph.html("Saving...");
}

function modalMarkerClick(marker,type) {
    switch (type) {
        case "House":
            var url = "/AJAX/ajax_mapHouseInfoWindow.aspx?houseID=" + marker.id + "&shortlist=" + isShortlist;
            jQuery.get(url, function(data) {
                marker.openInfoWindowHtml(data);
            });
            break;
    }
}

// encodes html using the browsers own encoder
function escapeHTML(str) {
    var div = document.createElement('div');
    var text = document.createTextNode(str);
    div.appendChild(text);
    return div.innerHTML;
};