﻿/// <reference name="MicrosoftAjax.js"/>

var DistanceMeasure = {
    showDistanceMarker: false,
    startMarker: null,
    snapToRoute: null,
    routeOverlay: null,
    routeVertices: [],
    routePixels: [],
    mouseMoveEvent: null
}

var MarkerCollections = {
    GMarkers: [],
    GMarkersCD: [],
    clearArrays: function() {
        this.GMarkers = [];
        this.GMarkersCD = [];
    }
}

function mouseOverList(index, entity) {
    GEvent.trigger(MarkerCollections.GMarkers[index], "mouseOverList", entity.EntityId, entity.MapItemTypeName);
}
function mouseOutList(index, entity) {
    GEvent.trigger(MarkerCollections.GMarkers[index], "mouseOutList", entity.EntityId, entity.MapItemTypeName);
}
function mouseOverListCD(index, entity) {
    GEvent.trigger(MarkerCollections.GMarkersCD[index], "mouseOverList", entity.EntityId, entity.MapItemTypeName);
}
function mouseOutListCD(index, entity) {
    GEvent.trigger(MarkerCollections.GMarkersCD[index], "mouseOutList", entity.EntityId, entity.MapItemTypeName);
}

// This is the failed callback function. // TODO: fix later
function FailedCallback(error) {
    var stackTrace = error.get_stackTrace();
    var message = error.get_message();
    var statusCode = error.get_statusCode();
    var exceptionType = error.get_exceptionType();
    var timedout = error.get_timedOut();

    // Display the error.  
    var RsltElem =
        "Stack Trace: " + stackTrace + "<br/>" +
        "Service Error: " + message + "<br/>" +
        "Status Code: " + statusCode + "<br/>" +
        "Exception Type: " + exceptionType + "<br/>" +
        "Timedout: " + timedout;
    alert(RsltElem);
} 

// Makes Ajax-call for destinations, city and hotel
function makeAjaxCall(enokEntity, catId, delegate) {
    MarkerCollections.clearArrays();
    TUI.BlueSites.Templates.AjaxHandlers.GoogleMaps.GetMapEntitiesByEntity(enokEntity.EntityId, enokEntity.EntityName, enokEntity.MapItemTypeName, catId, delegate, FailedCallback);
}

Type.registerNamespace("BlueSites");

BlueSites.GoogleMapsBase = function(element) {
    BlueSites.GoogleMapsBase.initializeBase(this, [element]);
}

BlueSites.GoogleMapsBase.prototype = {
    initialize: function () {
        BlueSites.GoogleMapsBase.callBaseMethod(this, 'initialize');
        this.set_map(new GMap2(this.get_mapElement()));
        this.get_map().setCenter(new GLatLng(0.0, 0.0), 2);
        this.get_map().setMapType(this.get_mapType());
    },
    dispose: function () {
        BlueSites.GoogleMapsBase.callBaseMethod(this, 'dispose');
    },
    get_map: function () { return this._map; },
    set_map: function (value) { this._map = value; },
    get_mapElement: function () { return this._mapElement; },
    set_mapElement: function (value) { this._mapElement = value; },
    get_mapType: function () { return this._mapType; },
    set_mapType: function (value) { this._mapType = value; },
    get_mapMode: function () { return this._mapMode; },
    set_mapMode: function (value) { this._mapMode = value; },
    get_parentLongitude: function () { return this._parentLongitude; },
    set_parentLongitude: function (value) { this._parentLongitude = value; },
    get_enokEntities: function () { return this._enokEntities; },
    set_enokEntities: function (value) { this._enokEntities = value; },
    get_travelLink: function () { return this._travelLink; },
    set_travelLink: function (value) { this._travelLink = value; },
    get_targetControl: function () { return this._targetControl; },
    set_targetControl: function (value) { this._targetControl = value; },
    get_markerMode: function () { return this._markerMode; },
    set_markerMode: function (value) { this._markerMode = value; },
    get_currentParentID: function () { return (typeof (this._currentParentID) == "undefined") ? 0 : this._currentParentID; },
    set_currentParentID: function (value) { this._currentParentID = value; },
    get_countryId: function () { return (typeof (this._countryId) == "undefined") ? 0 : this._countryId; },
    set_countryId: function (value) { this._countryId = value; },
    isPOI: function (enokEntity) { return (enokEntity.MapItemTypeId > 4) ? true : false; },
    get_baseImageUrl: function () { return oBaseAppSettings.IncludeSiteDirectory + "/Images/BlueSites/GoogleMaps/"; },
    get_currentEnokId: function () { return this._currentEnokId; },
    set_currentEnokId: function (value) { this._currentEnokId = value; },
    get_currentEnokLevel: function () { return this._currentEnokLevel; },
    set_currentEnokLevel: function (value) { this._currentEnokLevel = value; },
    setMapCenter: function (center) { this.get_map().setCenter(center); },
    setMapZoom: function (zoom) { this.get_map().setZoom(zoom); },
    calculateZoomLevelForOneEntity: function (parentEntity) {
        if (parentEntity.DefaultZoomLevel !== 0) {
            this.setMapZoom(parentEntity.DefaultZoomLevel - 1);
        }
        this.setMapCenter(new GLatLng(parentEntity.Latitude, parentEntity.Longitude));
    },
    calculateZoomLevel: function (bounds, currentMapTypeMaxZoomLevel, hotelPoint, defaultZoomLevel, numberOfMarkers) {

        
        // Calculate zoom
        if (this.get_mapMode() == "HotelView") {            
            this.setMapZoom(currentMapTypeMaxZoomLevel - 3);
        }
        else if (defaultZoomLevel !== 0) {            
            this.setMapZoom(defaultZoomLevel - 0);
        }
        else if (numberOfMarkers == 1) {            
            if (this.get_map().getBoundsZoomLevel(bounds) < currentMapTypeMaxZoomLevel) {                
                this.setMapZoom(this.get_map().getBoundsZoomLevel(bounds));
            }
            else {
                this.setMapZoom(currentMapTypeMaxZoomLevel - 2);
            }
        }
        else {
            this.setMapZoom(this.get_map().getBoundsZoomLevel(bounds));
        }

        // Sets center
        if (hotelPoint !== 0 && this.get_currentEnokLevel() == 3) {
            this.setMapCenter(hotelPoint);
        }
        else {
            this.setMapCenter(bounds.getCenter());
        }
    }
}
BlueSites.GoogleMapsBase.registerClass('BlueSites.GoogleMapsBase', Sys.UI.Control);
/**/
BlueSites.GoogleMapsWorldView = function(element) {
    BlueSites.GoogleMapsWorldView.initializeBase(this, [element]);
}

BlueSites.GoogleMapsWorldView.prototype = {
    initialize: function () {
        BlueSites.GoogleMapsWorldView.callBaseMethod(this, 'initialize');
        MarkerCollections.clearArrays();
        this.set_currentParentID(0);
        this.set_countryId(0);
        this.get_map().clearOverlays();
        this.get_map().checkResize();
        this.displayMarkers();

        var 
            menuMapTypeControl = new GMenuMapTypeControl(),
            gScaleControl = new GScaleControl(),
            largeMapControl3D = new GLargeMapControl3D(),
            topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(180, 5));

        this.get_map().addControl(menuMapTypeControl, topRight);
        this.get_map().addMapType(G_PHYSICAL_MAP);
        this.get_map().addControl(gScaleControl, new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10, 40)));
        this.get_map().addControl(largeMapControl3D, new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(5, 50)));

        //Add zoom control
        var 
            thisRef = this,
            boxStyleOpts = { opacity: 0.4, border: "2px solid white" },
            otherOpts = {
                buttonHTML: "<img src='" + oBaseAppSettings.IncludeSiteDirectory + "/Images/BlueSites/GoogleMaps/btn-zoom-area.png' title='" + "Zoom" + "' id='zoom-button' />",
                buttonStyle: { background: 'none' },
                buttonZoomingHTML: "<img src='" + oBaseAppSettings.IncludeSiteDirectory + "/Images/BlueSites/GoogleMaps/btn-zoom-area-active.png' title='" + "Zoom" + "' id='zoom-button' />",
                buttonZoomingStyle: { background: 'none' },
                buttonStartingStyle: { width: '39px', height: '32px' },
                overlayRemoveTime: 0
            };
        var dragZoomControl = new DragZoomControl(boxStyleOpts, otherOpts, {});
        this.get_map().addControl(dragZoomControl, new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(14, 7)));

        GEvent.addListener(this.get_map(), 'click', function (overlay, latlng) {

            if (DistanceMeasure.showDistanceMarker !== true) {
                return;
            }

            DistanceMeasure.routeVertices.push(latlng);
            //TODO fixa maptypen så den är dynamsik
            var pix = G_HYBRID_MAP.getProjection().fromLatLngToPixel(latlng, this.getZoom());
            DistanceMeasure.routePixels.push(pix);

            if (DistanceMeasure.routeVertices.length > 1) {
                thisRef.plotRoute();
                if (!DistanceMeasure.snapToRoute) {
                    DistanceMeasure.snapToRoute = new SnapToRoute(this, DistanceMeasure.startMarker, DistanceMeasure.routeOverlay);
                }
                else {
                    DistanceMeasure.snapToRoute.updateTargets(null, DistanceMeasure.routeOverlay);
                }
            }
            else {
                DistanceMeasure.startMarker = thisRef.createRouteMarker(latlng, 'Start');
                this.addOverlay(DistanceMeasure.startMarker);
            }
        });
        DistanceMeasure.mouseMoveEvent = GEvent.bind(this.get_map(), 'mousemove', this, this.mouseMove);

        //Lägger till "Tillbakaknappen"
        this.get_map().addControl(new ReturnToStartMode(this));
        // Lägger till distance
        this.get_map().addControl(new RouteDrawer(this));

        if (this.get_mapMode() == "WorldView") {
            this.displayMarkers();
        }

        $(".season-select-google-maps").change(function () {
                   
            var json = thisRef.get_enokEntities();
                       
            TUI.BlueSites.Templates.AjaxHandlers.GoogleMaps.GetMapEntitiesByEntityAndSeason(json.Current.EntityId, json.Current.MapItemTypeTag, $(this).val(), function (data) {
               thisRef.set_enokEntities(eval('{(' + data + ')}'));
               thisRef.displayMarkers();
            },
            FailedCallback);      

        });
    },
    dispose: function () { BlueSites.GoogleMapsWorldView.callBaseMethod(this, 'dispose'); },
    get_tuiImageUrl: function () { return this._tuiImageUrl; },
    set_tuiImageUrl: function (value) { this._tuiImageUrl = value; },
    get_catalogueId: function () { return this._catalogueId; },
    set_catalogueId: function (value) { this._catalogueId = value; },
    stringToCurrency: function (n) {
        n = n.replace(/\s/gi, "");
        if (isNaN(n)) { return ("0"); }
        s = n.toString();
        nStart = (s.length - 3);
        while (nStart >= 1) { s = s.substring(0, nStart) + " " + s.substring(nStart, s.length); nStart -= 3; }
        return s;
    },
    mouseMove: function (latlng) {
        if (DistanceMeasure.snapToRoute) {
            var dist = this.stringToCurrency(DistanceMeasure.snapToRoute.getDistAlongRoute().toFixed(0)) + " m";
            $("#distance").text(dist);
        }
    },
    plotRoute: function () {
        if (DistanceMeasure.routeOverlay) {
            this.get_map().removeOverlay(DistanceMeasure.routeOverlay);
        }
        DistanceMeasure.routeOverlay = new GPolyline(DistanceMeasure.routeVertices, 'red', 3, 1);
        this.get_map().addOverlay(DistanceMeasure.routeOverlay);
    },
    createRouteMarker: function (latlng, title) {
        var marker = new GMarker(latlng, { title: title, zIndexProcess: this.setZIndex });
        marker.importance = 20;
        return marker;
    },
    setZIndex: function (marker, b) {
        return GOverlay.getZIndex(marker.getPoint().lat()) + marker.importance * 1000000;
    },
    displayMarkers: function () {
        var 
            json = this.get_enokEntities(),
            marker,
            point,
            hotelPoint = 0,
            numEnok = 0,
            i,
            bounds = new GLatLngBounds(),
            $mapContainer = $("#large-google-map-container");

        if (this.get_currentParentID() === 0) {
            $(String.format("#left-panel {0}", this.getListType())).html("");
        }

        this.set_markerMode("rootLevel");

        var 
            len = json.Items.length,
            item;

        for (i = 0; i < len; i++) {
            item = json.Items[i];
            if (this.get_currentParentID() != item.EntityId) {
                point = new GLatLng(item.Latitude, item.Longitude);
                marker = this.createMarker(point, item, i);
                MarkerCollections.GMarkers.push(marker);

                if (this.get_mapMode() != "WorldView" && !this.isPOI(item)) {
                    bounds.extend(point);
                    numEnok++;
                }
                if (this.get_currentParentID() === 0) {
                    this.createListItem(item, i, point);
                }

                if (this.get_currentEnokId() == item.EntityId) {
                    hotelPoint = point;
                }
                this.get_map().addOverlay(marker);
            }
        }

        if (json.Current) {
            $mapContainer.find("#resort-name").text(json.Current.EntityName);
        }

        if (this.get_mapMode() != "WorldView") {
            if (numEnok > 0) {
                this.calculateZoomLevel(bounds, this.get_map().getCurrentMapType().getMaximumResolution(), hotelPoint, json.Current.DefaultZoomLevel, numEnok);
            }
            else {
                point = new GLatLng(json.Current.Latitude, json.Current.Longitude);
                marker = this.createMarker(point, json.Current);
                MarkerCollections.GMarkers.push(marker);
                this.get_map().addOverlay(marker);
                this.createListItem(json.Current, i, point);
                $mapContainer.find(".num-list").html("1.&nbsp;");
                this.calculateZoomLevelForOneEntity(json.Current);
            }
        }
    },
    displayDestCityMarkers: function (data) {
        var 
            json = Sys.Serialization.JavaScriptSerializer.deserialize(data),
            marker,
            point,
            numEnok = 0,
            i,
            bounds = new GLatLngBounds();

        this.get_map().closeExtInfoWindow();
        this.get_map().clearOverlays();
        $("#resort-name").text(json.parentName);

        this.set_currentParentID(json.parentId); //Kommer ej med i svaret
        this.set_markerMode("subLevel");

        if (this.get_countryId() === 0) {
            this.set_countryId(this.get_currentParentID());
        }

        $(String.format("#left-panel {0}", this.getListType())).addClass("dest-city-list").html("");
        $("#left-panel #heading-container").remove();

        if (json.parentName && this.get_mapMode() == "WorldView") {
            $("#left-panel").prepend(String.format('<div id="heading-container"><div class="flag flag-{1}"></div><h4 class="{0}{1}">{2}</h4><br class="clear" /></div>', "left-panel-heading heading-", this.get_countryId(), json.parentName));
        }

        for (i = 0; i < json.Items.length; i++) {

            point = new GLatLng(json.Items[i].Latitude, json.Items[i].Longitude);
            marker = this.createMarker(point, json.Items[i], i);
            if (!this.isPOI(json.Items[i])) {
                MarkerCollections.GMarkersCD.push(marker);
                bounds.extend(point);
                numEnok++;
                this.createListItem(json.Items[i], i, point);
            }
            this.get_map().addOverlay(marker);
        }

        if (numEnok > 0) {
            this.calculateZoomLevel(bounds, this.get_map().getCurrentMapType().getMaximumResolution(), 0, json.Current.DefaultZoomLevel, numEnok);
        }
        else {
            point = new GLatLng(json.Current.Latitude, json.Current.Longitude);
            marker = this.createMarker(point, json.Current);
            MarkerCollections.GMarkersCD.push(marker);
            this.get_map().addOverlay(marker);
            this.createListItem(json.Current, 0, point);
            $(".num-list").html("1.&nbsp;");
            this.calculateZoomLevelForOneEntity(json.Current);
        }

        if (this.get_mapMode() == "WorldView") {
            this.displayMarkers();
        }
    },
    createMarker: function (point, enokEntity, index) {
        var 
            thisRef = this,
            marker,
            opts,
            sameHotel,
            $mapContainer = $("#large-google-map-container");

        switch (enokEntity.MapItemTypeTag) {
            case "Entry":
                marker = new GMarker(point, { icon: this.createCountryIcon(enokEntity.EntityId), title: enokEntity.EntityName });
                break;
            case "Destination":
                opts = { "icon": this.createDestIcon(), "clickable": true, "labelText": (index + 1), "title": enokEntity.EntityName, "labelOffset": new GSize((index > 8) ? -6 : -3, -5) };
                marker = new LabeledMarker(point, opts);
                break;
            case "City":
                opts = { "icon": this.createCityIcon(), "clickable": true, "labelText": (index + 1), "title": enokEntity.EntityName, "labelOffset": new GSize((index > 8) ? -6 : -2, -32) };
                marker = new LabeledMarker(point, opts);
                break;
            case "Hotel":
                sameHotel = ((enokEntity.EntityId == this.get_currentEnokId()) && (this.get_currentEnokLevel() == 3)) ? true : false;
                opts = { "icon": this.createHotelIcon(sameHotel), "clickable": true, "labelText": (index + 1), "title": enokEntity.EntityName, "labelOffset": new GSize((index > 8) ? -5 : -2, -30), "labelClass": "hotelMarker" };
                marker = new LabeledMarker(point, opts);
                break;
            default:
                marker = new GMarker(point, { icon: this.createPOIMarker(enokEntity.MapItemTypeTag), title: this.getPOIName(enokEntity) });
                break;
        }

        var 
            delegate2 = Function.createDelegate(this, this.displayDestCityMarkers),
            delegate1 = Function.createDelegate(this, function () { makeAjaxCall(enokEntity, this.get_catalogueId(), delegate2); });

        GEvent.addListener(marker, 'click', function () {

            if (DistanceMeasure.showDistanceMarker) {
                return;
            }

            if (thisRef.isPOI(enokEntity)) {
                if (thisRef.getPOIName(enokEntity) == "") {
                    return;
                }
            }

            thisRef.get_map().closeExtInfoWindow();

            if (enokEntity.MapItemTypeName == "Entry") {
                thisRef.set_countryId(0);
            }

            marker.openExtInfoWindow(
                thisRef.get_map(),
                "google-callout-container",
                thisRef.renderInfoWindowContent(enokEntity),
                { beakOffset: 3, paddingX: 150, paddingY: 100 }
            );
            thisRef.get_map().setCenter(marker.getLatLng());
            $('a#zoom-link').click(delegate1);
        });

        if (!sameHotel && !this.isPOI(enokEntity)) {
            GEvent.addListener(marker, 'mouseover', function () {
                $mapContainer.find("#enok-entity-" + enokEntity.EntityId).addClass("enok-list");
                marker.setImage(thisRef.getMarkerImage(enokEntity.MapItemTypeName, true, enokEntity.EntityId));
            });
            GEvent.addListener(marker, 'mouseout', function () {
                $mapContainer.find("a#enok-entity-" + enokEntity.EntityId).removeClass("enok-list");
                marker.setImage(thisRef.getMarkerImage(enokEntity.MapItemTypeName, false, enokEntity.EntityId));

            });
            GEvent.addListener(marker, "mouseOverList", function (id, type) {
                marker.setImage(thisRef.getMarkerImage(type, true, id));
            });
            GEvent.addListener(marker, "mouseOutList", function (id, type) {
                marker.setImage(thisRef.getMarkerImage(type, false, id));
            });
        }
        return marker;
    },
    getPOIName: function (enokEntity) {
        switch (oBaseAppSettings.BrandID) {
            case 17: return enokEntity.NameFI;
            case 2: return enokEntity.NameDK;
            case 4: return enokEntity.NameNO;
            default: return enokEntity.NameSV;
        }
    },
    getPOIText: function (enokEntity) {
        switch (oBaseAppSettings.BrandID) {
            case 17: return enokEntity.TextFI;
            case 2: return enokEntity.TextDK;
            case 4: return enokEntity.TextNO;
            default: return enokEntity.TextSV;
        }
    },
    getCleanEntityName: function (name) {
        switch (oBaseAppSettings.BrandID) {
            case 17: return name.replace("Hotelli ", "").replace("& huoneistohotelli", "").replace("& Huoneistohotelli", "").replace("Huoneistohotelli", "").replace("Hotelli ja huoneistohotelli", "").replace("ja huoneistohotelli", "");
            case 2: return name.replace("Hotel ", "").replace("& lejligheder", "").replace("& Lejligheder", "").replace("Lejligheder", "");
            case 4: return name.replace("Hotell ", "").replace("& leiligheter", "").replace("& Leiligheter", "").replace("Leiligheter", "");
            default: return name.replace("Hotell ", "").replace("& lägenheter", "").replace("& Lägenheter", "").replace("och lägenheter", "").replace("Lägenheter", "");
        }
    },
    createListItem: function (enokEntity, index, point) {
        if (this.isPOI(enokEntity)) {
            return;
        }
        var 
            delegate2 = Function.createDelegate(this, this.displayDestCityMarkers),
            delegate1 = Function.createDelegate(this, function () { makeAjaxCall(enokEntity, this.get_catalogueId(), delegate2); }),
            thisRef = this,
            isCountry = (this.get_markerMode() == "rootLevel" && this.get_mapMode() == "WorldView"),
            entityName = this.getCleanEntityName(enokEntity.EntityName),
            sameHotel = ((enokEntity.EntityId == this.get_currentEnokId()) && (this.get_currentEnokLevel() == 3)) ? true : false,
            clickEntity = String.format("a#enok-entity-{0}", enokEntity.EntityId),
            $mapContainer = (this.getListType() === "ul") ? $("#overview-google-map-container") : $("#large-google-map-container");

        $mapContainer.find("#left-panel " + this.getListType()).append(String.format('<li>{2}<a id="enok-entity-{0}" href="javascript:void(0);" title="{1}">{3}<span class="entity-name">{4}</span></a></li>', enokEntity.EntityId, entityName, isCountry ? '<div class="flag flag-' + enokEntity.EntityId + '"></div>' : "", isCountry ? "" : String.format('<span class="num-list">{0}.&nbsp;</span>', (index + 1)), (sameHotel) ? String.format("<strong>{0}</strong>", entityName) : entityName));

        $(clickEntity).click(function () {
            if (enokEntity.MapItemTypeName == "Entry" || (thisRef.get_mapMode() != "WorldView" && (thisRef.get_markerMode() == "rootLevel"))) {
                MarkerCollections.GMarkers[index].openExtInfoWindow(
                    thisRef.get_map(),
                    "google-callout-container",
                    thisRef.renderInfoWindowContent(enokEntity),
                    { beakOffset: 3, paddingX: 150, paddingY: 100 }
                );
                thisRef.get_map().setCenter(MarkerCollections.GMarkers[index].getLatLng());
                $mapContainer.find('a#zoom-link').click(delegate1);

            }
            else {
                thisRef.get_map().setCenter(MarkerCollections.GMarkersCD[index].getLatLng());
                MarkerCollections.GMarkersCD[index].openExtInfoWindow(
                    thisRef.get_map(),
                    "google-callout-container",
                    thisRef.renderInfoWindowContent(enokEntity),
                    { beakOffset: 3, paddingX: 150, paddingY: 100 }
                 );

                $mapContainer.find('a#zoom-link').click(delegate1);
            }
        }
        );

        $(clickEntity).mouseover
        (
            function () {
                if (enokEntity.MapItemTypeName == "Entry" || (thisRef.get_mapMode() != "WorldView" && (thisRef.get_markerMode() == "rootLevel"))) {
                    mouseOverList(index, enokEntity);
                }
                else {
                    mouseOverListCD(index, enokEntity);
                }
                $(this).removeClass("normal").addClass("bold");
            }
        );
        $(clickEntity).mouseout
        (
            function () {
                if (enokEntity.MapItemTypeName == "Entry" || (thisRef.get_mapMode() != "WorldView" && (thisRef.get_markerMode() == "rootLevel"))) {
                    mouseOutList(index, enokEntity);
                }
                else {
                    mouseOutListCD(index, enokEntity);
                }
                $(this).removeClass("bold").addClass("normal");
            }
        );
    },
    renderInfoWindowContent: function (enokEntity) {
        var 
            start,
            top,
            usp,
            end,
            enokType,
            zoomLink,
            travelLink;
        if (this.isPOI(enokEntity)) {
            start = '<div class="google-callout">';
            top = String.format('<div class="top"><h3>{0}</h3><img src="' + oBaseAppSettings.IncludeSiteDirectory + '/Images/clear.gif" title="{1}" /></a></div><div class="center">', this.getPOIName(enokEntity));
            usp = String.format('<div class="poi-usp">{0}</div><ul>', this.getPOIText(enokEntity));
            end = '</div><div class="bottom"></div></div>';
            return String.format("{0}{1}{2}{3}", start, top, usp, end);
        }
        else {
            enokType = (enokEntity.MapItemTypeName == "Destination") ? "dest" : enokEntity.MapItemTypeName;
            start = '<div class="google-callout">';
            top = String.format('<div class="top"><h3>{0}</h3><img src="' + oBaseAppSettings.IncludeSiteDirectory + '/Images/clear.gif" title="{1}" /></a></div><div class="center">', enokEntity.EntityName);
            usp = String.format('<div class="{5}"><img src="{0}image.enok?e={1}&g={2}&cw=80&h=55&d=generic_charter.jpg" title="{3}" />{4}</div><ul>', this.get_tuiImageUrl(), enokEntity.EntityId, enokType, enokEntity.EntityName, enokEntity.Usp, (enokType == "Hotel") ? "poi-usp" : "usp");
            zoomLink = (enokType != "Hotel" && (enokEntity.EntityId != 58 && enokEntity.EntityId != 75)) ? String.format('<li><a id="zoom-link" href="javascript:void(0)">{0}&nbsp;&raquo;</a></li>', oTUIStrings.zoomTo) : '<li><br /></li>';
            travelLink = String.format('<li><a href="{0}{1}={2}">{3}&nbsp;{4}&nbsp;&raquo;</a></li></ul>', this.get_travelLink(), enokType, enokEntity.EntityId, oTUIStrings.readMore, enokEntity.EntityName);
            end = '</div><div class="bottom"></div></div>';

            return String.format("{0}{1}{2}{3}{4}{5}", start, top, usp, zoomLink, travelLink, end);
        }
    },
    getListType: function () {
        return (this.get_mapMode() == "WorldView") ? "ul" : "ol";
    },
    getMarkerImage: function (type, hover, id) {
        switch (type) {
            case "Entry": return hover ? String.format("{0}Country/Hover/hover-icon-{1}.png", this.get_baseImageUrl(), id) : String.format("{0}Country/icon-{1}.png", this.get_baseImageUrl(), id);
            case "Destination": return hover ? String.format("{0}Dest/icon-dest-hover.png", this.get_baseImageUrl()) : String.format("{0}Dest/icon-dest.png", this.get_baseImageUrl());
            case "City": return hover ? String.format("{0}City/icon-city-hover.png", this.get_baseImageUrl()) : String.format("{0}City/icon-city.png", this.get_baseImageUrl());
            case "Hotel": return hover ? String.format("{0}Hotel/icon-hotel-hover.png", this.get_baseImageUrl()) : String.format("{0}Hotel/icon-hotel.png", this.get_baseImageUrl());
        }
    },
    createCountryIcon: function (id) {
        var icon = new GIcon(G_DEFAULT_ICON);
        icon.image = String.format("{0}Country/icon-{1}.png", this.get_baseImageUrl(), id);
        icon.shadow = String.format("{0}Country/shadow-country.png", this.get_baseImageUrl());
        icon.iconSize = new GSize(30, 29);
        icon.shadowSize = new GSize(49, 36);
        icon.iconAnchor = new GPoint(15, 29);
        icon.imageMap = [0, 22, 0, 23, 1, 23, 1, 24, 10, 24, 10, 25, 11, 25, 11, 26, 12, 26, 12, 27, 13, 27, 13, 28, 14, 28, 14, 29, 15, 29, 15, 28, 16, 28, 16, 27, 17, 27, 17, 26, 18, 26, 18, 25, 19, 25, 19, 24, 29, 24, 29, 23, 30, 23, 30, 1, 29, 1, 29, 0, 1, 0, 1, 1, 0, 1];
        return icon;
    },
    createDestIcon: function () {
        var icon = new GIcon(G_DEFAULT_ICON);
        icon.image = String.format("{0}Dest/icon-dest.png", this.get_baseImageUrl());
        icon.shadow = String.format("{0}Dest/shadow-icon-dest.png", this.get_baseImageUrl());
        icon.iconSize = new GSize(29, 31);
        icon.shadowSize = new GSize(45, 31);
        icon.iconAnchor = new GPoint(15, 15);
        icon.imageMap = [29, 12, 29, 21, 28, 21, 28, 23, 27, 23, 27, 25, 26, 25, 26, 26, 25, 26, 25, 27, 24, 27, 24, 28, 23, 28, 23, 29, 21, 29, 21, 30, 18, 30, 18, 31, 11, 31, 10, 30, 9, 30, 8, 30, 8, 29, 7, 29, 6, 29, 6, 28, 5, 28, 5, 27, 4, 27, 4, 26, 3, 26, 3, 25, 2, 25, 2, 24, 2, 23, 1, 23, 1, 21, 1, 20, 0, 20, 0, 12, 1, 12, 1, 11, 1, 10, 2, 10, 2, 9, 2, 8, 3, 8, 3, 7, 4, 7, 4, 6, 5, 6, 5, 5, 6, 5, 6, 4, 7, 4, 7, 3, 8, 3, 9, 3, 10, 3, 10, 2, 16, 2, 16, 0, 27, 0, 27, 10, 28, 10, 28, 12];
        return icon;
    },
    createCityIcon: function () {
        var icon = new GIcon(G_DEFAULT_ICON);
        icon.image = String.format("{0}City/icon-city.png", this.get_baseImageUrl());
        icon.shadow = String.format("{0}City/shadow-icon-city.png", this.get_baseImageUrl());
        icon.iconSize = new GSize(22, 37);
        icon.shadowSize = new GSize(41, 37);
        icon.iconAnchor = new GPoint(11, 37);
        return icon;
    },
    createHotelIcon: function (isSame) {
        var icon = new GIcon(G_DEFAULT_ICON);
        icon.image = String.format("{0}Hotel/{1}.png", this.get_baseImageUrl(), (isSame) ? "icon-hotel-hover" : "icon-hotel");
        icon.shadow = String.format("{0}Hotel/shadow-icon-hotel.png", this.get_baseImageUrl());
        icon.iconSize = new GSize(29, 33);
        icon.shadowSize = new GSize(46, 33);
        icon.iconAnchor = new GPoint(11, 37);
        icon.imageMap = [15, 32, 15, 31, 16, 31, 16, 30, 17, 30, 17, 29, 18, 29, 18, 28, 26, 28, 26, 27, 27, 27, 28, 27, 28, 26, 28, 25, 29, 25, 29, 3, 28, 3, 28, 2, 28, 1, 26, 1, 26, 0, 3, 0, 3, 1, 2, 1, 1, 1, 1, 2, 1, 3, 0, 3, 0, 25, 1, 25, 1, 26, 1, 27, 2, 27, 2, 28, 10, 28, 11, 28, 11, 29, 12, 29, 12, 30, 13, 30, 13, 31, 14, 31, 14, 32];
        return icon;
    },
    createPOIMarker: function (imageSrc) {
        var icon = new GIcon(G_DEFAULT_ICON);
        icon.image = String.format("{0}POI/{1}.png", this.get_baseImageUrl(), imageSrc);
        icon.shadow = String.format("{0}POI/poi-shadow.png", this.get_baseImageUrl());
        icon.iconSize = new GSize(34, 38);
        icon.shadowSize = new GSize(54, 38);
        icon.iconAnchor = new GPoint(7, 7);
        icon.imageMap = [3, 7, 4, 7, 4, 6, 5, 6, 5, 5, 6, 5, 6, 4, 7, 4, 7, 3, 8, 3, 8, 2, 10, 2, 10, 1, 12, 1, 14, 1, 14, 0, 20, 0, 20, 1, 22, 1, 23, 1, 23, 2, 24, 2, 25, 2, 25, 3, 26, 3, 27, 3, 27, 4, 28, 4, 28, 5, 29, 5, 29, 6, 30, 6, 30, 7, 31, 7, 31, 8, 31, 9, 32, 9, 32, 11, 33, 11, 33, 13, 34, 14, 34, 19, 33, 20, 33, 22, 33, 23, 32, 23, 32, 24, 32, 25, 31, 25, 31, 26, 31, 27, 30, 27, 30, 28, 29, 28, 29, 29, 28, 29, 28, 30, 27, 30, 27, 31, 26, 31, 25, 31, 25, 32, 24, 32, 23, 32, 23, 33, 22, 33, 22, 34, 21, 34, 20, 34, 20, 35, 19, 35, 19, 36, 19, 37, 18, 37, 18, 38, 17, 38, 16, 38, 16, 37, 15, 37, 15, 36, 14, 36, 14, 35, 13, 35, 13, 34, 12, 34, 12, 33, 11, 33, 11, 32, 10, 32, 9, 32, 8, 31, 7, 31, 7, 30, 6, 30, 6, 29, 5, 29, 4, 28, 4, 27, 3, 27, 3, 26, 2, 25, 2, 24, 1, 24, 1, 23, 1, 22, 1, 21, 0, 21, 0, 14, 1, 12, 1, 11, 2, 11, 2, 10, 2, 9, 3, 9, 3, 8];
        return icon;
    }
}
BlueSites.GoogleMapsWorldView.registerClass('BlueSites.GoogleMapsWorldView', BlueSites.GoogleMapsBase);

if (typeof (Sys) !== 'undefined') {
    Sys.Application.notifyScriptLoaded();
}

///// Custom Control
function ReturnToStartMode(mapControl) {
    this._mapControl = mapControl;
}
ReturnToStartMode.prototype = new GControl();


ReturnToStartMode.prototype.initialize = function(map) {
    var 
        container = document.createElement("div"),
        buttonDiv = document.createElement("div");

    this.setButtonStyle_(buttonDiv);
    this.setContainerStyle_(container);
    container.appendChild(buttonDiv);
    buttonDiv.appendChild(document.createTextNode(oTUIStrings.resetMap));
    GEvent.addDomListener(buttonDiv, "click", Function.createDelegate(this, function() {
        MarkerCollections.clearArrays();
        //Måste stänga ExtInfoWindow separat innan det går att ta bort markers.
        this._mapControl.get_map().closeExtInfoWindow();
        this._mapControl.get_map().clearOverlays();
        this._mapControl.set_currentParentID(0);
        this._mapControl.set_countryId(0);
        this._mapControl.displayMarkers();

        $("#heading-container").hide();

        $(String.format("#left-panel {0}", this._mapControl.getListType())).removeClass("dest-city-list");
        if (this._mapControl.get_mapMode() == "WorldView") {
            this._mapControl.get_map().setCenter(new GLatLng(0.0, 0.0), 2);
        }
    }));
    $("#left-panel").append(container);
    return container;
}

ReturnToStartMode.prototype.getDefaultPosition = function() {
    var gSize = new GSize(36, 520);
    if (this._mapControl.get_catalogueId() === 0) {
        gSize = new GSize(25, 520);
    }
    return new GControlPosition(G_ANCHOR_TOP_LEFT, gSize);
}

// Sets the proper CSS for the given button element.
ReturnToStartMode.prototype.setButtonStyle_ = function(button) {
    $(button).attr("class", "custom-button");
}

ReturnToStartMode.prototype.setContainerStyle_ = function(div) {
    $(div).attr("class", "custom-button-container");
}

/////////
function RouteDrawer(mapControl) {
    this._googleMapControl = mapControl;
}
RouteDrawer.prototype = new GControl();


RouteDrawer.prototype.initialize = function(map) {
    var 
        distanceContainer = document.createElement("div"),
        distance = document.createElement("div"),
        button = document.createElement("div");

    this.setButtonStyle_(button);
    this.setContainerStyle_(distanceContainer);
    this.setDistanceStyle_(distance);
    distanceContainer.appendChild(distance);
    distanceContainer.appendChild(button);

    button.appendChild(document.createTextNode(oTUIStrings.strMeasureDistance));
    GEvent.addDomListener(button, "click", Function.createDelegate(this, function() {

        DistanceMeasure.showDistanceMarker = !DistanceMeasure.showDistanceMarker;

        if (DistanceMeasure.showDistanceMarker) {
            var cssImageUrl = "url(" + oBaseAppSettings.IncludeSiteDirectory + "/Images/BlueSites/GoogleMaps/btn-measure-active.png) no-repeat";
            $("#distance-button").html(oTUIStrings.strCancelMeasure).css("background", cssImageUrl).css("color", "#d07300");
            $(".world-map div").css("cursor", "default");
            $("#distance-button").css("cursor", "pointer");
            $("#distance").show();
        }
        else {
            var cssImageUrl = "url(" + oBaseAppSettings.IncludeSiteDirectory + "/Images/BlueSites/GoogleMaps/btn-measure.png) no-repeat";
            DistanceMeasure.routeVertices = [];
            DistanceMeasure.routePixels = [];
            this._googleMapControl.get_map().removeOverlay(DistanceMeasure.routeOverlay);
            this._googleMapControl.get_map().removeOverlay(DistanceMeasure.startMarker);
            DistanceMeasure.snapToRoute = null;
            $(".world-map div").css("cursor", "pointer");
            $("#distance-button").html(oTUIStrings.strMeasureDistance).css("background", cssImageUrl).css("color", "#6688cc");
            $("#distance").hide();
        }

        $("#distance").text("");
    }));
    $(".world-map").append(distanceContainer);
    return distanceContainer;
}

RouteDrawer.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(-35, 110));
}

// Sets the proper CSS for the given button element.
RouteDrawer.prototype.setButtonStyle_ = function(button) {
    $(button).attr("id", "distance-button");
}

RouteDrawer.prototype.setContainerStyle_ = function(div) {
    $(div).attr("class", "custom-button-container");
}

RouteDrawer.prototype.setDistanceStyle_ = function(div) {
    $(div).attr("id", "distance");
    $(div).hide();
}
