﻿var marketContentBuilder;
var destinationMarker;
var geocoder;
var addressReceivedCallback;

function initialize() {
    map = new GMap2(document.getElementById("google_map"))
    if (map == null) {
        return;
    }
    onunload = function() { GUnload() };

    if (GBrowserIsCompatible()) {
        map.setCenter(new GLatLng(lat, lng), scale);
    }

    marketContentBuilder = new MarketContentBuilder();
    destinationMarker = new DestinationMarker();
}

function refilter() {

    if (map == null) {
        return;
    }

    if (typeof(site) != 'undefined' && site=='orestad') {
        refilter_orestad();
        return;
    }

    map.clearOverlays();
    marker = null;

    if (url != '') {
        url = '';
        return;
    }

    articlesInfo = document.getElementById('filter_articles');
    if (articlesInfo != null) {
        if (articlesInfo.checked) {
            loadPins('/layouts/Pins.aspx?pagetype=largemap&amp;' + site + '=1&amp;shownews=1');
        }
    }

    userInfo = document.getElementById('filter_userinfo');
    if (userInfo != null) {
        if (userInfo.checked) {
            loadPins('/layouts/Pins.aspx?pagetype=largemap&amp;' + site + '=1&amp;showcomments=1');
        }
    }

    eventsInfo = document.getElementById('filter_events');
    if (eventsInfo != null) {
        if (eventsInfo.checked) {
            loadPins('/layouts/Pins.aspx?pagetype=largemap&amp;' + site + '=1&amp;showevents=1');
        }
    }
}

function refilter_orestad() {
    if (map == null) {
        return;
    }


    map.clearOverlays();
    marker = null;

    if (url != '') {
        url = '';
        return;
    }

    eventsInfo = document.getElementById('filter_events');
    if (eventsInfo != null) {
        if (eventsInfo.checked) {
            loadPins('/layouts/Pins.aspx?pagetype=largemap_orestad&amp;orestad=1&amp;showevents=1');
        }
    }

    var req = '/layouts/Pins.aspx?pagetype=largemap_orestad&amp;orestad=1';

    var info = document.getElementById('filter_news');
    if (info != null) {
        if (info.checked) {
            req = req + '&amp;shownews=1';
        }
    }

    info = document.getElementById('filter_articles_business');
    if (info != null) {
        if (info.checked) {
            req = req + '&amp;showbusiness=1';
        }
    }

    info = document.getElementById('filter_sale');
    if (info != null) {
        if (info.checked) {
            req = req + '&amp;showsale=1';
        }
    }

    info = document.getElementById('filter_rent');
    if (info != null) {
        if (info.checked) {
            req = req + '&amp;showrent=1';
        }
    }

    info = document.getElementById('filter_articles_private');
    if (info != null) {
        if (info.checked) {
            req = req + '&amp;showprivate=1';
        }
    }

    info = document.getElementById('filter_userinfo');
    if (info != null) {
        if (info.checked) {
            req = req + '&amp;showcomments=1';
        }
    }
    loadPins(req);





}

function load() {
    if (typeof (initialize) != 'undefined') {
        initialize();
    }
    if (typeof (loadPins) != 'undefined' && url != '') {
        loadPins(url);
    }
    if (typeof (refilter) != 'undefined') {
        refilter();
    }
    if (typeof (adjustControls) != 'undefined') {
        adjustControls();
    }
    if (typeof (addCenterMarker) != 'undefined') {
        addCenterMarker();
    }
}

function zIndexFunction() {
    return 1;
}

function loadPins(url) {
    if (url == '') {
        return;
    }

    if (map == null) {
        return;
    }
    var selectedMarker = null;
    // create XmlHttp request and load
    var request = GXmlHttp.create();

    request.open("GET", url, true);
    request.setRequestHeader("Pragma", "no-cache");
    request.setRequestHeader("Cache-control", "no-cache");

    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            var showWarning = false;
            var googlePins = eval(request.responseText);
            var centerLatMin = 99999, centerLatMax = -99999;
            var centerLngMin = 99999, centerLngMax = -99999;

            if (googlePins.length == 0) {
                return;
            }

            if (googlePins) {
                for (var i = 0; i < googlePins.length; i++) {
                    var lat = googlePins[i][1];
                    var lng = googlePins[i][2];

                    // find min/max marker positions
                    if (lat < centerLatMin) {
                        centerLatMin = lat;
                    }
                    if (lat > centerLatMax) {
                        centerLatMax = lat;
                    }

                    if (lng < centerLatMin) {
                        centerLngMin = lng;
                    }
                    if (lng > centerLngMax) {
                        centerLngMax = lng;
                    }

                    var image = "";
                    switch (googlePins[i][0]) {
                        case 0:
                            image = "/gfx/common/aus2-arrangement_highlight.png";
                            //self item
                            break;
                        case 1:
                            image = "/gfx/common/aus2-marker-nyhed.png";
                            //article
                            break;
                        case 2:
                            image = "/gfx/common/aus2-marker-news.png";
                            //news
                            break;
                        case 3:
                            image = "/gfx/common/aus2-marker-arrangement.png";
                            //event
                            break;
                        case 4:
                            image = "/gfx/common/aus2-marker-kommentar.png";
                            //user data
                            break;
                        case 5:
                            image = "/gfx/common/aus2-marker-podwalk.png";
                            //podwalk
                            break;
                        case 6:
                            image = "/gfx/common/aus2-marker-nyhed.png";
                            //business articles
                            break;
                        case 7:
                            image = "/gfx/common/aus2-marker-nyhed.png";
                            //private articles
                            break;
                        case 8:
                            image = "/gfx/common/aus2-marker-lots-for-sale.png";
                            //sale item
                            break;
                        case 9:
                            image = "/gfx/common/aus2-marker-apartments.png";
                            //rent item
                            break;
                    }

                    if (image != "") {
                        var customIcon = new GIcon();
                        customIcon.image = image;
                        customIcon.shadow = "/gfx/common/aus2-marker-skygge.png";
                        customIcon.iconSize = new GSize(16, 25);
                        customIcon.shadowSize = new GSize(16, 29);
                        customIcon.iconAnchor = new GPoint(8, 25);
                        customIcon.infoWindowAnchor = new GPoint(8, 0);

                        markerOptions = { icon: customIcon, zIndexProcess: zIndexFunction };

                        var marker = createMarkerCustom(
                                                        map,
                                                        new GLatLng(lat, lng),
                                                        markerOptions,
                                                        googlePins[i][3],
                                                        googlePins[i][4],
                                                        googlePins[i][5],
                                                        googlePins[i][6]);

                        //if google map key is not correct, an error occurs
                        try {
                            map.addOverlay(marker);
                        }
                        catch (expt) {
                            showWarning = true;
                        }

                        if (googlePins[i][0] == 0) {
                            selectedMarker = marker;
                        }
                    }
                }
            } //googlePins

            var centerLat = centerLatMin + (centerLatMax - centerLatMin) / 2;
            var centerLng = centerLngMin + (centerLngMax - centerLngMin) / 2;
            var bounds = new GLatLngBounds(new GLatLng(centerLatMin, centerLngMin), new GLatLng(centerLatMax, centerLngMax));
            var zoom = map.getBoundsZoomLevel(bounds);

            // zoom maximum is 14
            if (zoom > 14) {
                zoom = 14;
            }
            map.setCenter(new GLatLng(centerLat, centerLng), zoom);

            if ((typeof (showPopup) != 'undefined') && selectedMarker) {
                GEvent.trigger(selectedMarker, "click");
            }

            if (showWarning) {
                //alert("Google Map markers were not created.");
            }
        } // readyState = 4
    }
    request.send(null);
}

function addDraggable() {
    // return if there already is a marker
    if (marker != null) {
        return;
    }

    if (map == null) {
        return;
    }

    map.disableDoubleClickZoom();
    icon = new GIcon(G_DEFAULT_ICON);
    icon.image = "/gfx/nordhavnen/aus2-blue_marker.png";
    markerOptions = { icon: icon, draggable: true };

    marker = new GMarker(map.getCenter(), markerOptions);

    // hide info window on dragstart
    GEvent.addListener(marker, "dragstart", function() {
        map.closeInfoWindow()
    });

    // update elements on dragend
    GEvent.addListener(marker, "dragend", function() {
    marker.openInfoWindowHtml('<strong>DIT STED PÅ KORTET</strong><br />Flyt markøren til det rigtige sted<br /><br /><a href="/tilfojindhold.aspx?lat=' + marker.getLatLng().lat() + '&lng=' + marker.getLatLng().lng() + '">Klik derefter for at tilføje dit indhold</a>');
    });

    map.addOverlay(marker);
    
    marker.openInfoWindowHtml('<strong>DIT STED PÅ KORTET</strong><br />Flyt markøren til det rigtige sted<br /><br /><a href="/tilfojindhold.aspx?lat=' + marker.getLatLng().lat() + '&lng=' + marker.getLatLng().lng() + '">Klik derefter for at tilføje dit indhold</a>');

}

function entitiesToLiterals(sourcestring) {
    var result = sourcestring;
    result = result.replace("?", "?");
    result = result.replace("o", "o");
    result = result.replace("a", "a");
    result = result.replace("&Aelig;", "?");
    result = result.replace("O", "O");
    result = result.replace("A", "A");
    result = result.replace("E", "E");
    result = result.replace("e", "e");
    result = result.replace("&amp;", "&");
    result = result.replace("&quot;", "\"");

    return result;
}

// closure function for adding an onClick handler to a marker with a simple html info window
function createMarkerSimple(latlang, markerOptions, infoWindowHtml) {
    
    // initialize marker with position and options if specified
    var marker;
    if (markerOptions != null) {
        marker = new GMarker(latlang, markerOptions);
    }
    else {
        marker = new GMarker(latlang);
    }

    // add event listener and return marker
    if (infoWindowHtml) {
        GEvent.addListener(marker, "mouseover", function() {
            marker.openInfoWindowHtml(infoWindowHtml)
        });
    }

    return marker;
}

//closure function for adding an onClick handler to a marker with a custom html info window
function createMarkerCustom(parentMap, latlng, markerOptions, infoHeading, dateTime, infoContent, infoLink) {

    // initialize marker with position and options if specified
    var marker;
    if (markerOptions != null) {
        marker = new GMarker(latlng, markerOptions);
    }
    else {
        marker = new GMarker(latlng);
    }

    // replace html entities with corresponding literals
    infoHeading = entitiesToLiterals(infoHeading);
    infoContent = entitiesToLiterals(infoContent);

    var maxLength = parseInt(jQuery('span[id=TitleTrimCharacterNumber]').text(), 10);
    var maxCommentLength = parseInt(jQuery('span[id=CommentsTrimCharacterNumber]').text(), 10);


    if (infoHeading.length > maxLength) {
        infoHeading = infoHeading.substring(0, maxLength);
        infoHeading = infoHeading + "…";
    }

    if (infoContent.length > maxCommentLength) {
        infoContent = infoContent.substring(0, maxCommentLength); ;
        infoContent = infoContent + "…";
    }

    // add event listener and return marker
    if (infoHeading) {

        GEvent.addListener(marker, "click", function() {
            // if click and another marker is active
            if (parentMap.currentInfoPane && parentMap.currentInfoPane.marker_ != marker) {
                // remove the old one
                parentMap.removeOverlay(parentMap.currentInfoPane);
                parentMap.currentInfoPane = null;
            }


            if (!parentMap.currentInfoPane || parentMap.currentInfoPane.marker_ != marker) {
                parentMap.currentInfoPane = new InfoPane(latlng, infoHeading, dateTime, infoContent, infoLink, marker);
                parentMap.addOverlay(parentMap.currentInfoPane);
            }
            else
                parentMap.currentInfoPane = null;


            
            // if clicked and the info pane is already active
            if (parentMap.currentInfoPane && parentMap.currentInfoPane.marker_ == marker) {
                // parentMap.removeOverlay( parentMap.currentInfoPane );

                // center marker on click
                centerX = Number(parentMap.currentInfoPane.div_.style.left.replace("px", "")) + Number(parentMap.currentInfoPane.div_.style.width.replace("px", "")) / 2;
                centerY = Number(parentMap.currentInfoPane.div_.style.top.replace("px", "")) + Number(parentMap.currentInfoPane.div_.style.height.replace("px", "")) / 2 + 30;

                center = parentMap.fromDivPixelToLatLng({ x: centerX, y: centerY });
                parentMap.panTo(center);
            }

            if (!parentMap.currentInfoPane || parentMap.currentInfoPane.marker_ != marker) {
                parentMap.currentInfoPane = new InfoPane(latlng, infoHeading, dateTime, infoContent, infoLink, marker);
                parentMap.addOverlay(parentMap.currentInfoPane);

                centerX = Number(parentMap.currentInfoPane.div_.style.left.replace("px", "")) + Number(parentMap.currentInfoPane.div_.style.width.replace("px", "")) / 2;
                centerY = Number(parentMap.currentInfoPane.div_.style.top.replace("px", "")) + Number(parentMap.currentInfoPane.div_.style.height.replace("px", "")) / 2 + 30;

                center = parentMap.fromDivPixelToLatLng({ x: centerX, y: centerY });
                parentMap.panTo(center);

            }
        });
    }

    return marker;
}

var directions;

function DrawDirection(from, to) {

    ClearDirections();
    var directionsDiv = jQuery('div.mapMarkerContentDirections:first');
    directionsDiv.show();
    directions = new GDirections(map, directionsDiv.get(0));
    GEvent.addListener(directions, "load", function() { setTimeout("marketContentBuilder.FixDirectionsDivLinks();", 1000); });
    directions.load("from:" + from + " to:" + to);
}

function ClearDirections() {
    if (directions) {
        directions.clear();
    }
}

//callback receives address
function GetAddress(latLng, callback) {
    if (!geocoder) {
        geocoder = new GClientGeocoder();
    }
    addressReceivedCallback = callback;
    geocoder.getLocations(latLng, OnLocationReceived);
}

function OnLocationReceived(response) {
    var address;
    if (response && response.Status.code == 200) {
        address = response.Placemark[0].address;
    }
    if (typeof (addressReceivedCallback) != 'undefined' && address) {
        addressReceivedCallback(address);
    }
}

//InfoPane
function InfoPane(latLng, heading, dateTime, content, detailLink, marker) {
    this.latLng_ = latLng;
    this.heading_ = heading;
    this.marker_ = marker;
    this.content_ = content;
    this.dateTime_ = dateTime;
    this.detailLink_ = detailLink;
}

InfoPane.prototype = new GOverlay();

InfoPane.prototype.initialize = function(map) {

    var markerInfo = new MarkerInfo(this.heading_, this.latLng_, this.dateTime_, this.content_, this.detailLink_, this.marker_);
    var div = marketContentBuilder.BuildMarkerInfoBox(markerInfo);
    map.getPane(G_MAP_FLOAT_PANE).appendChild(div);
    this.map_ = map;
    this.div_ = div;
}

InfoPane.prototype.remove = function() {
    //if (this.div_) {
    //debugger;
    this.div_.parentNode.removeChild(this.div_);
    //}
}

InfoPane.prototype.copy = function() {
    var infoPane = new InfoPane(this.latLng_, this.heading_, this.marker_, this.content_, this.dateTime_, this.detailLink_);
    infoPane.initialize(map);

    return infoPane;
}

InfoPane.prototype.redraw = function(force) {
    if (!force) {
        return;
    }

    var position = this.map_.fromLatLngToDivPixel(this.marker_.getLatLng());
    this.div_.style.left = position.x + 15 + "px";
    this.div_.style.top = position.y - 40 - jQuery(this.div_).height() + "px";
}
