﻿var mapMarkerCollection = new Hashtable();
var mapPointsCollection = new Hashtable();
var map;

function ActivateMapView(){

    map = loadMap("map");

    $("body").bind("unload", function() {
        GUnload();
    });

    if(jsonData!='undefined')
    {
        if (jsonData.locations.length > 0) {

            ShowPropertiesInMap(jsonData);
        }
    }

}

function loadMap(target) {
    if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById(target));
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        mapHomePoint = new GLatLng(42.2660227, -89.0396905);
        map.setCenter(mapHomePoint, 13);
        mapMarkerManager = new MarkerManager(map);

        // === create the context menu div ===
//        contextmenu = document.createElement("div");
//        contextmenu.style.visibility = "hidden";
//        contextmenu.style.background = "#ffffff";
//        contextmenu.style.border = "1px solid #8888FF";

//        map.getContainer().appendChild(contextmenu);

//        // === listen for singlerightclick ===
//        GEvent.addListener(map, "singlerightclick", function(pixel, tile) {
//            // store the "pixel" info in case we need it later
//            // adjust the context menu location if near an egde
//            // create a GControlPosition
//            // apply it to the context menu, and make the context menu visible
//            clickedPixel = pixel;
//            var x = pixel.x;
//            var y = pixel.y;
//            if (x > map.getSize().width - 120) { x = map.getSize().width - 120 }
//            if (y > map.getSize().height - 100) { y = map.getSize().height - 100 }
//            var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x, y));
//            contextmenu.innerHTML = '<a href="javascript:zoomIn();"><div class="context">&nbsp;&nbsp;Zoom in&nbsp;&nbsp;<\/div><\/a>'
//                            + '<a href="javascript:zoomOut();"><div class="context">&nbsp;&nbsp;Zoom out&nbsp;&nbsp;<\/div><\/a>'
//                            + '<a href="javascript:zoomInHere(' + clickedPixel + ');"><div class="context">&nbsp;&nbsp;Zoom in here&nbsp;&nbsp;<\/div><\/a>'
//                            + '<a href="javascript:zoomOutHere(' + clickedPixel + ');"><div class="context">&nbsp;&nbsp;Zoom out here&nbsp;&nbsp;<\/div><\/a>'
//                            + '<a href="javascript:centreMapHere(' + clickedPixel + ');"><div class="context">&nbsp;&nbsp;Centre map here&nbsp;&nbsp;<\/div><\/a>';
//            pos.apply(contextmenu);
//            contextmenu.style.visibility = "visible";
//        });

//        // === If the user clicks on the map, hide the context menu ===
//        GEvent.addListener(map, "click", function() {
//            contextmenu.style.visibility = "hidden";
//        });

        return map;
    }
}

function ShowPropertiesInMap(proximityLocations) {

    for (var i = 0; i < proximityLocations.locations.length; i++) {
        var point = new GLatLng(proximityLocations.locations[i].latitude, proximityLocations.locations[i].longitude);
        var markerId = point.lat();
        mapPointsCollection.put(markerId, point);

        var marker = createMarker(point, proximityLocations.locations[i]);
        proximityLocations.locations[i].marker = marker;
        mapMarkerCollection.put(markerId, proximityLocations.locations[i]);
        map.addOverlay(marker);

        AddLocationToSearchResultList(proximityLocations.locations[i]);
    }

    map.setCenter(new GLatLng(proximityLocations.locations[0].latitude, proximityLocations.locations[0].longitude), 13);
}

function AddLocationToSearchResultList(locationData) {
    var markerId = locationData.latitude;
    /*var item = "<div class='MapSearchSearchResult' id='loc_" + locationData.propertyId + "' onclick='PanToMarker(" + markerId + ")'>";
    item += "<h2>" + locationData.name + "</h2>";
    item += "<br>" + locationData.address;
    item += "</div>";*/
    var row = '<tr style="border:solid 1px #8F9394;">' +
                '<td style="width: 50%" align="left" valign="top">' +
                    "<a href='#' style='color:Black;' onclick='PanToMarker("+markerId+");EnableDisableDiv();'>{ADDRESS}<a>" +
                 '</td>' +
                 '<td style="width: 15%" align="right" valign="top">' +
                    '{BEDS}' +
                 '</td>' +
                 '<td style="width: 15%" align="right" valign="top">' +
                    '{BATHS}' +
                 '</td>' +
                 '<td style="width: 20%" align="right" valign="top">' +
                    '${PRICE}' +
                 '</td>' +
             '</tr>';
     row = row.replace("{BEDS}", locationData.beds);
     row = row.replace("{BATHS}", locationData.beds);
     row = row.replace("{ADDRESS}", locationData.address);
     row = row.replace("{PRICE}", locationData.price);
     $("#searchResults").append(row);
                 
     var item = "<div class='MapSearchSearchResult' id='loc_" + locationData.propertyId + "' onclick='PanToMarker(" + markerId + ")'>";
     item += "<h2>" + locationData.name + "</h2>";
     item += "<br><span>" + locationData.address + "</span>";
     item += "</div>";
     $("#mapViewProperties").append(item);
     
}

function PanToMarker(markerId) {
    var marker = mapMarkerCollection.get(markerId).marker;
    var markerTab = mapMarkerCollection.get(markerId).tabs;

    map.panTo(mapPointsCollection.get(markerId));
    marker.openInfoWindowTabs(markerTab);
}

function createMarker(point, locationData) {

    var icon_image;
    var current_price = locationData.price.replace(/,/g, '');

    if (locationData.officeId == "84180" || locationData.officeId == "84404")
        icon_image = "conlon.png";
    else
        icon_image = "price1.png";
    /*else if (current_price > 0 && current_price <= 250000)
        icon_image = "price1.png";
    else if (current_price > 250000 && current_price <= 500000)
        icon_image = "price2.png";
    else if (current_price > 500000 && current_price <= 900000)
        icon_image = "price3.png";
    else if (current_price > 900000)
        icon_image = "price4.png";*/
        
    var map_icon = new GIcon(G_DEFAULT_ICON, conlon_base_url + "image/property-types/" + icon_image);
    map_icon.iconSize = new GSize(22, 26);

    var markerOptions = {
        icon: map_icon,
        draggable: false,
        bouncy: false
    };

    var marker = new GMarker(point, markerOptions);
    var markerId = locationData.latitude;
    var obj;

    //Create the tabs for the marker pop-up
    $.ajax({
        url: conlon_base_url + "private/marker-templates/infoTemplate.html",
        type: "GET",
        success: function(message) {
            message = message.toString();
            message = message.replace(/{ConlonBasePath}/g, conlon_base_url);

            myregexp = new RegExp("(<table id='propertyInfoTab'[^>]*>[\u0000-\uFFFF]+?</table>)");
            var markerHtml = myregexp.exec(message)[0];
            markerHtml = markerHtml.replace(/{Price}/g, locationData.price);
            markerHtml = markerHtml.replace("{Beds}", locationData.beds);
            markerHtml = markerHtml.replace("{Baths}", locationData.baths);
            markerHtml = markerHtml.replace("{Area}", locationData.area);
            markerHtml = markerHtml.replace("{Address}", locationData.address);
            markerHtml = markerHtml.replace(/{Name}/g, locationData.name);
            markerHtml = markerHtml.replace("{Picture}", locationData.picture);
            markerHtml = markerHtml.replace("{PropertyId}", markerId);

            myregexp = new RegExp("(<table id='propertyRemarksTab'[^>]*>[\u0000-\uFFFF]+?</table>)");
            var markerRemarks = myregexp.exec(message)[0];
            markerRemarks = markerRemarks.replace(/{Name}/g, locationData.name);
            markerRemarks = markerRemarks.replace(/{Price}/g, locationData.price);
            markerRemarks = markerRemarks.replace("{Remarks}", locationData.remarks);

            myregexp = new RegExp("(<table id='propertyToolsTab'[^>]*>[\u0000-\uFFFF]+?</table>)");
            var markerTools = myregexp.exec(message)[0];
            markerTools = markerTools.replace(/{Name}/g, locationData.name);
            markerTools = markerTools.replace(/{Price}/g, locationData.price);
            markerTools = markerTools.replace("{Latitude}", locationData.latitude);
            markerTools = markerTools.replace("{Longitude}", locationData.longitude);
            markerTools = markerTools.replace("{Address}", locationData.urladdress);
            markerTools = markerTools.replace("{Location}", markerId);
            markerTools = markerTools.replace("{Zip}", locationData.zip);
            markerTools = markerTools.replace("{PropertyId}", markerId);

            var letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'];
            myregexp = new RegExp("(<table id='tblPhotoGallery'[^>]*>[\u0000-\uFFFF]+?</table>)");
            var markerGallery = myregexp.exec(message)[0];
            markerGallery = markerGallery.replace(/{Name}/g, locationData.name);
            markerGallery = markerGallery.replace(/{Price}/g, locationData.price);
            var gallery;
            if (locationData.photoCount > 0) {
                gallery = '<div class="GalleryItem"><a href="#" onclick="ShowBigPicture(\'{BigImage}\')"><img src="{src}" /></a></div>';
                gallery = gallery.replace("{src}", conlon_base_url + "private/WebServices/getListingThumb.aspx?file=/userfiles/property-images/" + locationData.mls + "/" + locationData.mls + ".jpg" + "&w=60&h=50");
                gallery = gallery.replace("{BigImage}", conlon_base_url + "userfiles/property-images/" + locationData.mls + "/" + locationData.mls + ".jpg");

                for (var i = 0; i < locationData.photoCount - 1; i++) {
                    gallery = gallery + '<div class="GalleryItem"><a href="#" onclick="ShowBigPicture(\'{BigImage}\')"><img src="{src}" /></a></div>';
                    gallery = gallery.replace("{src}", conlon_base_url + "private/WebServices/getListingThumb.aspx?file=/userfiles/property-images/" + locationData.mls + "/" + locationData.mls + letters[i] + ".jpg" + "&w=60&h=50");
                    gallery = gallery.replace("{BigImage}", conlon_base_url + "userfiles/property-images/" + locationData.mls + "/" + locationData.mls + letters[i] + ".jpg");
                }
            }
            else
                gallery = "No images available";
                
            markerGallery = markerGallery.replace("{Gallery}", gallery);

            var tabs = [];
            tabs[0] = new GInfoWindowTab("Quick Info", markerHtml);
            tabs[1] = new GInfoWindowTab("Remarks", markerRemarks);
            tabs[2] = new GInfoWindowTab("Photos", markerGallery);
            tabs[3] = new GInfoWindowTab("Tools", markerTools);
            marker.bindInfoWindowTabs(tabs);
            locationData.tabs = tabs;
        }
    });

    //alert( mapMarkerCollection[markerId].name );

    /*GEvent.addListener(marker, "click", function() {
    //marker.openInfoWindowHtml(markerHtml);
    marker.openInfoWindow();
    });*/

    return marker;
}

function lnkStreeView_Click(lat, lng) {
    OpenPopup(conlon_base_url + 'map_search/street-view.aspx?lat=' + lat + "&lng=" + lng, 'StreetView', 550, 220, 'resizable=no,scrollbars=no,toolbar=no,location=no,directories=no,status=no,menubar=no');
}

function lnkDirections_Click(startPoint) {
    OpenPopup(conlon_base_url + 'map_search/car-trip.aspx?loc=' + startPoint, '', 750, 600, 'resizable=no,scrollbars=no,toolbar=no,location=no,directories=no,status=no,menubar=no');
}

function lnkViewDetails_Click(markerId) {
    var location = mapMarkerCollection.get(markerId);
    //window.open(conlon_base_url + 'property-details.aspx?pid=' + location.propertyId, '', '');
    window.location = conlon_base_url + 'realestate-properties/' + location.mls + ".aspx";
    //setTimeout("DisplayRecentlyViewedItems()", 3000);
}

function ShowLegend() {
    OpenPopup(conlon_base_url + 'map_search/map-legend.htm', 'MapLegend', 212, 223, 'resizable=no,scrollbars=no,toolbar=no,location=no,directories=no,status=no,menubar=no');
}

function ShowBigPicture(imageUrl) {
    OpenPopup(imageUrl, 'BigPicture', 344, 237, 'resizable=no,scrollbars=no,toolbar=no,location=no,directories=no,status=no,menubar=no');
}