﻿/// <reference path="../../helper/VeJavaScriptIntellisenseHelper.js" />
/// <reference path="../../jquery/jquery-vsdoc.js" />
/// <reference path="../default.js" />

var map = null;
var customLayer = null;
var counter = 100;
var infoboxOpenTimer = null;
var $infobox;

function LoadMap(lat, lon, zoom, callback) {
    
    if (typeof Microsoft.Maps.Map == 'undefined') {
        counter--;
        if (counter == 0) {
          ProcessFail(null);
          return;
        }
        else {
            setTimeout(function () { LoadMap(lat, lon, zoom, callback); }, 200);
            return;
        }
    }

    GetMapKey(function (e) {
        var mapOptions = {
            credentials: e,
            enableSearchLogo: false,
            enableClickableLogo: false,
            center: new Microsoft.Maps.Location(lat, lon),
            zoom: ConvertZoomLevel(zoom),
            mapTypeId: GetMapTypeId(typeof maptype != 'undefined' ? maptype : '')
        }

        if (typeof GetMapOptions == 'function') {
            mapOptions = GetMapOptions(mapOptions);
        }

        if (typeof mapID == 'undefined') {
            mapID = "iwMap";
        }

        map = new Microsoft.Maps.Map(document.getElementById(mapID), mapOptions);

        Microsoft.Maps.Events.addHandler(map, 'mousewheel', MouseWheelHandler);

        if (typeof InitSpecific != 'undefined') {
            InitSpecific();
        }

        if (typeof InitToolsMap != 'undefined') {
            InitToolsMap();
        }

        if (callback != undefined) {
            eval(callback);
        }
    }, function (e) {
        alert('Beim Laden der Karte ist ein Fehler aufgetreten.');
    });
}

function MouseWheelHandler(e) {
    if (e.targetType == "map") {
        hideInfobox();
    }
}

function GetParameters(link) {
    var strReturn = "";
    var strHref = window.location.href;

    if (typeof link != 'undefined') {
        strHref = link;
    }

    // Url-Parameter
    if (strHref.indexOf("?") > -1) {
        strReturn = unescape(strHref.substr(strHref.indexOf("?")));
    }
    // Koordinaten der Karte
    if (strReturn.toLowerCase().indexOf("mapparam=") < 0 || $("input[id$='mapmode']").val() != '') {
        if ($("input[id$='mapmode']").val() != '') {
            strReturn = removeURLParam(strReturn, "mapparam");
            strReturn = removeURLParam(strReturn, "mm");
        }
        if (strReturn != '' && strReturn != '?') {
            strReturn += '&';
        }
        strReturn += GetMapParam();
    }
    // Fast History
    if (typeof $('#NavigationBox').val() != 'undefined' && $('#NavigationBox').val() != '') {
        if (strReturn != '') strReturn += '&';
        strReturn += 'NavigationBox=' + $('#NavigationBox').val();
    }
    return strReturn;
}

function GetMapParam() {
    var strReturn = "MapParam=" + $("input[id$='bottomLatitude']").val() + "|" +
        $("input[id$='leftLongitude']").val() + "|" +
        $("input[id$='topLatitude']").val() + "|" +
        $("input[id$='rightLongitude']").val() + "|" +
        $("input[id$='centerLatitude']").val() + "|" +
        $("input[id$='centerLongitude']").val() + "|" +
        $("input[id$='zoomLevel']").val();
    if ($("input[id$='mapmode']").val() != '') {
        strReturn += "&mm=" + $("input[id$='mapmode']").val();
    }
    return strReturn;
}

function GetMapTypeId(type) {
    switch (type) {
        case "aerial":
            return Microsoft.Maps.MapTypeId.aerial;
        case "birdseye":
            return Microsoft.Maps.MapTypeId.birdseye;
        case "road":
            return Microsoft.Maps.MapTypeId.road;
        default: 
            return Microsoft.Maps.MapTypeId.auto;
    }
}

function AddErrorLayer(error, customLinkTo) {
    if (customLayer != null) {
        return;
    }

    customLayer = document.createElement("div");
    $(customLayer).addClass("map_overlay");

    if ($.browser.msie) {
        $(customLayer).css("filter", "alpha(opacity=80)");
    } else {
        $(customLayer).css({ "MozOpacity": "0.7", "opacity": "0.8" });
    }

    var customText = document.createElement("h6");
    $(customText).append(String.Format("{0}<div class=\"h_010\">", error));

    var url = removeURLParam(window.location.href, 'display');

    var closeImage = document.createElement("span");
    $(closeImage).addClass("bn_close")
                 .click(function () { RemoveCustomLayer(); });

    var overlayHeader = document.createElement("div");
    $(overlayHeader).addClass("w_max");

    $(overlayHeader).append(closeImage);
    $(customLayer).append(overlayHeader)
                  .append(customText);

    if (customLinkTo == "list") {
        var link = document.createElement("a");
        $(link).attr("href", url)
               .click(function () { window.location.href = url; })
               .addClass('icon_01 no_margin')
               .append("zur Listenansicht wechseln");
        $(customLayer).append(link);
    }
    else if (customLinkTo == "partner") {
        var link = document.createElement("a");
        $(link).attr("href", "#")
               .click(function () {
                   if (typeof bPreviewMode == 'undefined' || bPreviewMode != true) {
                       RemoveCustomLayer();
                       IwAG.Expose.getInstance().KontaktClick();
                   }
                   return false;
               })
               .addClass('icon_01 no_margin')
               .append("Anbieter kontaktieren");
        $(customLayer).append(link);
    }

    $(customLayer).appendTo('#infoBox');
    messageActive = true;
}

function RemoveCustomLayer() {
    if (customLayer != null) {
        $('#infoBox').empty();
        customLayer = null;
    }
}

function displayInfobox(e) {
    stopInfoboxTimer(e);
    RemoveCustomLayer();
    var pin = e.target;

    if (pin != null) {
        activePin = pin;

        var location = pin.getLocation();
        var $divMap = $("#divMap");

        var options = {
            id: 'infoBox1',
            visible: false,
            showPointer: true,
            showCloseButton: false,
            offset: 0,
            zIndex: 999
        };

        if (pin.description == null) {
            if (pin.isClustered)
                LoadClusterPinDescription();
            else
                LoadSinglePinDescription();
        }
        else {
            SetInfoBoxContent(pin);
        }
    }
}

function SetInfoBoxContent(pin) {
    var ib = $('#' + (pin.isClustered ? 'ibMulti' : 'ibSingle'));
    var pinLocation = map.tryLocationToPixel(pin.getLocation(), Microsoft.Maps.PixelReference.control);

    $('#' + (pin.isClustered ? 'ibDescMulti' : 'ibDescSingle')).html(pin.description);
    $infobox = ib.clone().css({ visibility: "visible" }).bind('mouseenter', pinInfoboxMouseEnter).bind('mouseleave', pinInfoboxMouseLeave);
    $('#infoBox').empty().append($infobox);

    var offsetLeft = getOffsetX(pinLocation.x, pin.isClustered);
    var offsetHeight = getOffsetY(pinLocation.y, pin.isClustered);
    var offsetPointer = 0;

    if (pin.isClustered) {
        offsetPointer = pinLocation.y - offsetHeight - 32;
    }
    else {
        offsetPointer = pinLocation.y - offsetHeight - 18;
    }

    if (offsetLeft >= pinLocation.x) {
        if (pin.isClustered) {
            $infobox.find('.ibMultiRightPointer').hide();
            $infobox.css({ left: offsetLeft + "px", top: offsetHeight + "px" }).find('.ibMultiLeftPointer').show().css({ top: offsetPointer });
        }
        else {
            $infobox.find('.ibSingleRightPointer').hide();
            $infobox.css({ left: offsetLeft + "px", top: offsetHeight + "px" }).find('.ibSingleLeftPointer').show().css({ top: offsetPointer });
        }
    }
    else {
        if (pin.isClustered) {
            $infobox.css({ left: offsetLeft + "px", top: offsetHeight + "px" }).find('.ibMultiRightPointer').show().css({ top: offsetPointer });
            $infobox.find('.ibMultiLeftPointer').hide();
        }
        else {
            $infobox.css({ left: offsetLeft + "px", top: offsetHeight + "px" }).find('.ibSingleRightPointer').show().css({ top: offsetPointer });
            $infobox.find('.ibSingleLeftPointer').hide();
        }
    }
}

function hideInfobox(e) {
    $('#infoBox').empty();
    activePin = null;
}

function startInfoboxTimer(e) {
    if ($infobox != null && typeof $infobox.pinTimer != 'undefined' && $infobox.pinTimer != null) {
        clearTimeout($infobox.pinTimer);
    }
    if ($infobox != null) {
        $infobox.pinTimer = setTimeout(hideInfobox, 100);
    }
}

function stopInfoboxTimer(e) {
    if ($infobox != null && typeof $infobox.pinTimer != 'undefined' && $infobox.pinTimer != null) {
        clearTimeout($infobox.pinTimer);
    }
}

function stopInfoboxOpenTimer(e) {
    if (typeof infoboxOpenTimer != 'undefined' && infoboxOpenTimer != null) {
        clearTimeout(infoboxOpenTimer);
    }
}

function startInfoboxOpenTimer(e) {
    if (typeof infoboxOpenTimer != 'undefined' && infoboxOpenTimer != null) {
        clearTimeout(infoboxOpenTimer);
    }
    infoboxOpenTimer = setTimeout(function () { displayInfobox(e); }, 400);
}

function mapViewChange(e) {
    stopInfoboxTimer(e);
    hideInfobox(e);
}
function pinMouseOver(e) {
    startInfoboxOpenTimer(e);
}
function pinMouseOut(e) {
    stopInfoboxOpenTimer(e);
    startInfoboxTimer(e);
}
function pinInfoboxMouseLeave(e) {
    hideInfobox(e);
}
function pinInfoboxMouseEnter(e) {
    stopInfoboxTimer(e);
}

function getOffsetX(pinLocationX, multi) {
    var mapWidth = map.getWidth();
    var infoboxWidth = $('#' + (multi ? 'ibMulti' : 'ibSingle')).width();

    if (mapWidth - infoboxWidth - 20 < pinLocationX) {
        if (multi) {
            return pinLocationX - infoboxWidth - 65;
        }
        return pinLocationX - infoboxWidth - 50;
    }

    if (multi) {
        return pinLocationX + 10;
    }
    return pinLocationX;
}

function getOffsetY(pinLocationY) {
    var mapHeight = map.getHeight();

    // Pin liegt im oberen Karten-Drittel
    if (pinLocationY < mapHeight / 3) {
        // box wird nach unten ausgerichtet
        return pinLocationY - 50;
    }

    var infoboxHeight = $('#infoBox').find('[id^=ibText]').height();

    // Pin liegt im mittleren Karten-Drittel
    if (pinLocationY < mapHeight / 3 * 2) {
        // box wird mittig ausgerichtet
        return pinLocationY + 30 - (infoboxHeight / 2);
    }

    // Pin liegt im unteren Karten-Drittel
    // Infobox würde zu weit über die Karte nach oben hinaus ragen und von css-Klasse "wrapper" abgeschnitten werden
    if (infoboxHeight > mapHeight + 50) {
        // box wird mittig ausgerichtet
        return pinLocationY + 20 - (infoboxHeight / 3 * 2);
    }

    // box wird nach oben ausgerichtet
    return pinLocationY + 30 - infoboxHeight;
}

function ConvertZoomLevel(zoomlevel) {
    if (zoomlevel < 100) {
        try {
            zoomlevel = parseInt(zoomlevel);
        }
        catch (e) { }
        return zoomlevel;
    }

    switch (zoomlevel) {
        case 150:
            return 17;
        case 300:
            return 17;
        case 750:
            return 16;
        case 1500:
            return 15;
        case 4500:
            return 13;
        case 7500:
            return 13;
        case 15000:
            return 11;
        case 30000:
            return 10;
        case 75000:
            return 9;
    }
}

