﻿/// <reference name="MicrosoftAjax.js"/>
Type.registerNamespace("TipsCommunity");

// Base class //
TipsCommunity.GoogleMapBase = function(element) {
    TipsCommunity.GoogleMapBase.initializeBase(this, [element]);   
}

TipsCommunity.GoogleMapBase.prototype = {
    initialize: function() {
        TipsCommunity.GoogleMapBase.callBaseMethod(this, 'initialize');

        this.set_map(new GMap2($(this.get_element()).find('div.map-container').get(0)));
        this.get_map().setCenter(new GLatLng(1, 1), 2);
        this.get_map().setMapType(G_PHYSICAL_MAP);
        this.updateDisplay();
    },
    dispose: function() {
        TipsCommunity.GoogleMapBase.callBaseMethod(this, 'dispose');
        GUnload();
    },
    get_locations: function() { return this._locations; },
    set_locations: function(value) { this._locations = value; },
    get_map: function() { return this._map; },
    set_map: function(value) { this._map = value; },
    get_sortOrder: function() {
        if (typeof (this._sortOrder) == "undefined")
            return "Date";
        else
            return this._sortOrder;
    },
    set_sortOrder: function(value) { this._sortOrder = value; },
    get_viewMode: function() { return this._viewMode; },
    set_viewMode: function(value) { this._viewMode = value; },
    get_categories: function() {
        if (typeof (this._categories) == "undefined") {
            var searchString = "";
            $("div.google-map div.category-list ul li :checkbox:checked").each(function() {
                searchString += "," + this.categoryID;
            });

            if (searchString.charAt(0) == ",")
                return searchString.substring(1, searchString.length);
        }
        else
            return this._categories;
    },
    set_categories: function(value) { this._categories = value; },
    updateDisplay: function() {
    },
    displayNoMarkersFound: function() {
        var currentSearch = this.currentSearch();
        if (typeof (currentSearch) == "undefined")
            return false;

        var buttonSrc = "/TipsCommunity/Includes/Images/Buttons/" + tuiBrandId + "/close.gif";
        $(".google-map-tip-overview").append("<div class='google-no-hits' id='info-box'><p>" + globalResourceTextInstance.tipsFoundNoTipsFor + "</p><p>" + currentSearch + "</p><input type='image' src='" + buttonSrc + "' id='close-button' /></div>");
        $("div#info-box").click(function(e) {
            e.preventDefault();
            $("div#info-box").remove();
            return false;
        });
    },
    currentSearch: function() {
        if (!$("div.google-map-tip-overview .continents").length)
            return "";

        var continentsDrop = $("div.google-map-tip-overview .continents");
        var countryDrop = $("div.google-map-tip-overview .countries");
        var geographicalAreasDrop = $("div.google-map-tip-overview .geographical-areas");
        var citiesDrop = $("div.google-map-tip-overview .cities");
        var searchString;
        if (continentsDrop.get(0).selectedIndex > 1)
            searchString = Sys.Serialization.JavaScriptSerializer.deserialize(continentsDrop.val()).Name;

        if (countryDrop.get(0).selectedIndex > 1)
            searchString += " | " + Sys.Serialization.JavaScriptSerializer.deserialize(countryDrop.val()).Name;

        if (geographicalAreasDrop.get(0).selectedIndex > 1)
            searchString += " | " + Sys.Serialization.JavaScriptSerializer.deserialize(geographicalAreasDrop.val()).Name;

        if (citiesDrop.get(0).selectedIndex > 1)
            searchString += " | " + Sys.Serialization.JavaScriptSerializer.deserialize(citiesDrop.val()).Name;

        return searchString;
    },
    createClusterMarker: function(markerLocation, markerId, url, numberOfTips, html, thisRef) {

        var marker = new GMarker(markerLocation, { icon: this.createSamePointMarkerIcon(numberOfTips), draggable: false, title: globalResourceTextInstance.tipsNumberOfTipsOnLocation + ' ' + numberOfTips });

        GEvent.addListener(marker, 'click', function() {
            thisRef.get_map().setCenter(markerLocation);
            marker.openExtInfoWindow(thisRef.get_map(), "google-callout_window", "<div>Loading...</div>", { ajaxUrl: html, beakOffset: 6, paddingY: 5 });
        });
        GEvent.addListener(thisRef.get_map(), 'extinfowindowclose', function() { });
        return marker;
    },
    createSamePointMarkerIcon: function(numberOfTips) {
        var imgUrl = "/TipsCommunity/Includes/Images/Google/Markers/";

        if (numberOfTips <= 9 && numberOfTips > 0)
            imgUrl = imgUrl + "marker_collection_" + numberOfTips + ".png"
        else
            imgUrl = imgUrl + "marker_collection_9_plus.png"

        var icon = new GIcon(G_DEFAULT_ICON);
        icon.image = imgUrl;
        icon.shadow = "/TipsCommunity/Includes/Images/Google/Markers/marker_collection_shadow.png";
        icon.iconSize = new GSize(42, 33);
        icon.shadowSize = new GSize(42, 33);
        icon.iconAnchor = new GPoint(20, 27);
        icon.imageMap = [18, 1, 17, 1, 17, 2, 15, 2, 15, 3, 14, 3, 14, 4, 13, 4, 13, 5, 12, 5, 12, 7, 11, 7, 11, 15, 12, 15, 12, 17, 13, 17, 13, 18, 14, 18, 14, 19, 15, 19, 15, 20, 16, 20, 16, 21, 19, 21, 19, 25, 18, 25, 18, 27, 20, 27, 20, 26, 21, 26, 21, 25, 22, 25, 22, 24, 23, 24, 23, 22, 27, 22, 27, 21, 29, 21, 29, 20, 30, 20, 31, 20, 31, 19, 32, 19, 32, 18, 33, 18, 33, 17, 34, 17, 34, 15, 35, 15, 35, 7, 34, 7, 34, 5, 33, 5, 33, 4, 32, 4, 32, 3, 31, 3, 31, 2, 29, 2, 29, 1, 27, 1, 27, 0, 19, 0, 19, 1];

        return icon;
    },
    createCategoryMarker: function(markerLocation, name, url, categoryId, locationId, allowDraging) {
        var marker = new GMarker(markerLocation, { icon: this.createSmallMarker(categoryId), draggable: allowDraging, title: name });

        if (url != "") {
            GEvent.addListener(marker, 'click', function() {
                location.href = url;
            });
        }
        /* if(this.get_viewMode() == "ViewLocation")
        {   
        var thisRef= $get(googleMapClientId).control;       
        GEvent.addListener(marker, 'mouseover', function() { 		        
        var url = "/TipsCommunity/Templates/AjaxHandlers/GoogleMapContentProvider.aspx?locationids=" + locationId + "&page=1&count=1";                
        //       thisRef.get_map().setCenter(markerLocation);
        marker.openExtInfoWindow(thisRef.get_map(), "google-callout_window", "<div>Loading...</div>", {ajaxUrl:url, beakOffset: 6, paddingY: 5 });	        
        });
        GEvent.addListener(thisRef.get_map(), 'extinfowindowclose', function(){ });  
        }*/
        return marker;
    },
    createSmallMarker: function(categoryId) {
        var icon = new GIcon(G_DEFAULT_ICON);
        icon.image = this.getCategoryMarkerImageUrl(categoryId);
        icon.shadow = "/TipsCommunity/Includes/Images/Google/Markers/shadow.png";
        icon.iconSize = new GSize(26, 28);
        icon.shadowSize = new GSize(26, 28);
        icon.iconAnchor = new GPoint(12, 22);
        return icon;
    },
    getCategoryMarkerImageUrl: function(categoryId) {
        var markerImage = "";
        if (categoryId == "8")
            markerImage = "/TipsCommunity/Includes/Images/Categories/small-bubble-black.png";
        else if (categoryId == "9")
            markerImage = "/TipsCommunity/Includes/Images/Categories/small-bubble-orange.png";
        else if (categoryId == "10")
            markerImage = "/TipsCommunity/Includes/Images/Categories/small-bubble-purple.png";
        else if (categoryId == "11")
            markerImage = "/TipsCommunity/Includes/Images/Categories/small-bubble-blue.png";
        else if (categoryId == "12")
            markerImage = "/TipsCommunity/Includes/Images/Categories/small-bubble-red.png";
        else if (categoryId == "13")
            markerImage = "/TipsCommunity/Includes/Images/Categories/small-bubble-green.png";
        else if (categoryId == "14")
            markerImage = "/TipsCommunity/Includes/Images/Categories/small-bubble-yellow.png";
        else if (categoryId == "24")
            markerImage = "/TipsCommunity/Includes/Images/Categories/small-bubble-light-blue.png";

        return markerImage;
    },
    loadMarkersOnZoom: function() {

        var thisRef = $get(googleMapClientId).control; // Get a reference back to the control instance that initiated the AJAX request        

        cluster.removeMarkers();
        scheduleMethodInvocation(thisRef, "startloadMarkersOnZoom", 1000, thisRef.get_id());
        cluster.refresh();


    },
    renderLocations: function(result) {

        var LocationsCollectionArray = Sys.Serialization.JavaScriptSerializer.deserialize(result);
        var thisRef = $get(LocationsCollectionArray.GoogleMapClientID).control; // Get a reference back to the control instance that initiated the AJAX request        

        if (LocationsCollectionArray.Result.length == 0) {
            thisRef.displayNoMarkersFound();
            return;
        }

        var marker, markersArray = [];

        for (var j = 0; j < LocationsCollectionArray.Result.length; j++) {
            if (LocationsCollectionArray.Result[j].length == 1) {
                marker = thisRef.createCategoryMarker(new GLatLng(LocationsCollectionArray.Result[j][0].Position.Latitude, LocationsCollectionArray.Result[j][0].Position.Longitude), LocationsCollectionArray.Result[j][0].Name, LocationsCollectionArray.Result[j][0].Url, LocationsCollectionArray.Result[j][0].Category, LocationsCollectionArray.Result[j][0].ID, false);
                markersArray.push(marker);
            }
            else {
                var idArray = new Array();
                for (var i = 0; i < LocationsCollectionArray.Result[j].length; i++) {
                    idArray.push(LocationsCollectionArray.Result[j][i].ID);
                }
                var html = String.format
                (
                    "/TipsCommunity/Templates/AjaxHandlers/GoogleMapContentProvider.aspx?locationids={0}&page=1&count={1}&minified=true",
                    idArray.toString().replace(",", "a"),
                    LocationsCollectionArray.Result[j].length
                );
                var markerLocation = new GLatLng(LocationsCollectionArray.Result[j][0].Position.Latitude, LocationsCollectionArray.Result[j][0].Position.Longitude);
                marker = thisRef.createClusterMarker(markerLocation, LocationsCollectionArray.Result[j][0].Name, LocationsCollectionArray.Result[j][0].Url, LocationsCollectionArray.Result[j].length, html, thisRef);
                markersArray.push(marker);
            }
        }
        cluster = new ClusterMarker(thisRef.get_map(), { markers: markersArray });
        cluster.refresh();
        
        thisRef.get_map().savePosition();        
    }
}

TipsCommunity.GoogleMapBase.registerClass('TipsCommunity.GoogleMapBase', Sys.UI.Control);
// End Base class //

// GoogleMapImageGallery class //
/*
* This class is used by the google map on the startpage
*
*/
TipsCommunity.GoogleMapImageGallery = function(element) {
    TipsCommunity.GoogleMapImageGallery.initializeBase(this, [element]);
}

TipsCommunity.GoogleMapImageGallery.prototype = {
    initialize: function() {
        TipsCommunity.GoogleMapImageGallery.callBaseMethod(this, 'initialize');
        this.get_map().setCenter(new GLatLng(1, 1), 10);
        this.get_map().enableDragging();
        this.get_map().enableDoubleClickZoom();

        var smallZoomControl, mapTypeControl;
        GEvent.addListener(this.get_map(), 'mouseover', function() {
            smallZoomControl = new GSmallZoomControl();
            mapTypeControl = new GMapTypeControl();
            this.addMapType(G_PHYSICAL_MAP);
            this.addControl(mapTypeControl);
            this.addControl(smallZoomControl);
        });
        GEvent.addListener(this.get_map(), 'mouseout', function() {
            this.removeControl(smallZoomControl);
            this.removeControl(mapTypeControl);
        });
    },
    dispose: function() {
        TipsCommunity.GoogleMapImageGallery.callBaseMethod(this, 'dispose');
    },
    setImageGalleryMarkerPosition: function(latitude, longitude, zoomLevel, title) {
        this.get_map().clearOverlays();
        this.get_map().addOverlay(new GMarker(new GLatLng(latitude, longitude), { icon: this.createImageGalleryMarker(), title: title }));
        this.get_map().setCenter(new GLatLng(latitude, longitude), zoomLevel);
    },
    createImageGalleryMarker: function() {
        var icon = new GIcon(G_DEFAULT_ICON);
        icon.image = "/TipsCommunity/Includes/Images/Google/Markers/album-marker.png";
        icon.shadow = "/TipsCommunity/Includes/Images/Google/Markers/album-marker-shadow.png";
        icon.iconSize = new GSize(45, 33);
        icon.shadowSize = new GSize(45, 33);
        icon.iconAnchor = new GPoint(20, 27);
        icon.imageMap = [18, 1, 17, 1, 17, 2, 15, 2, 15, 3, 14, 3, 14, 4, 13, 4, 13, 5, 12, 5, 12, 7, 11, 7, 11, 15, 12, 15, 12, 17, 13, 17, 13, 18, 14, 18, 14, 19, 15, 19, 15, 20, 16, 20, 16, 21, 19, 21, 19, 25, 18, 25, 18, 27, 20, 27, 20, 26, 21, 26, 21, 25, 22, 25, 22, 24, 23, 24, 23, 22, 27, 22, 27, 21, 29, 21, 29, 20, 30, 20, 31, 20, 31, 19, 32, 19, 32, 18, 33, 18, 33, 17, 34, 17, 34, 15, 35, 15, 35, 7, 34, 7, 34, 5, 33, 5, 33, 4, 32, 4, 32, 3, 31, 3, 31, 2, 29, 2, 29, 1, 27, 1, 27, 0, 19, 0, 19, 1];
        return icon;
    }
}

TipsCommunity.GoogleMapImageGallery.registerClass('TipsCommunity.GoogleMapImageGallery', TipsCommunity.GoogleMapBase);
// END GoogleMapImageGallery class //
////////////////////////////////



// GoogleMapsZoomSearchEnabled class //
TipsCommunity.GoogleMapsZoomSearchEnabled = function(element) {
    TipsCommunity.GoogleMapsZoomSearchEnabled.initializeBase(this, [element]);   
}

TipsCommunity.GoogleMapsZoomSearchEnabled.prototype = {
    initialize: function() {
        TipsCommunity.GoogleMapsZoomSearchEnabled.callBaseMethod(this, 'initialize');
            this.get_map().setMapType(G_PHYSICAL_MAP);
            this.get_map().enableDragging();            
            GEvent.addListener(this.get_map(), 'zoomend', this.loadMarkersOnZoom);
            GEvent.addListener(this.get_map(), 'dragend', this.loadMarkersOnZoom);            
      },
      dispose: function() {        
        TipsCommunity.GoogleMapsZoomSearchEnabled.callBaseMethod(this, 'dispose');
      },
      updateDisplay: function() {
        TipsCommunity.GoogleMapsZoomSearchEnabled.callBaseMethod(this, 'updateDisplay');
      },          
      get_currentUserName: function() {
        return this._currentUserName;
      },
      set_currentUserName: function(value) {
        this._currentUserName = value;
      },
      get_numberOfMarkersToDisplay: function() { 
        return 50;
      }  
}

TipsCommunity.GoogleMapsZoomSearchEnabled.registerClass('TipsCommunity.GoogleMapsZoomSearchEnabled', TipsCommunity.GoogleMapBase);

// END GoogleMapsZoomSearchEnabled class //

// GoogleMapsStartPage class //
/*
* This class is used by the google map on the startpage
*
*/
TipsCommunity.GoogleMapsStartPage = function(element) {
    TipsCommunity.GoogleMapsStartPage.initializeBase(this, [element]);   
}

TipsCommunity.GoogleMapsStartPage.prototype = {
    initialize: function() {
        TipsCommunity.GoogleMapsStartPage.callBaseMethod(this, 'initialize');
            this.get_map().setCenter(new GLatLng(51.559771,-5.800781), 2);        
            this.get_map().setMapType(G_PHYSICAL_MAP);
            this.get_map().enableDragging();       
            this.get_map().enableDoubleClickZoom();   
            
            var smallZoomControl; 
            GEvent.addListener(this.get_map(), 'mouseover', function() { 
                smallZoomControl = new GSmallZoomControl();
                this.addControl(smallZoomControl);
            });
            GEvent.addListener(this.get_map(), 'mouseout', function() {                
                this.removeControl(smallZoomControl);
            });    
      },
      dispose: function() {        
        TipsCommunity.GoogleMapsStartPage.callBaseMethod(this, 'dispose');
      },      
      updateDisplay: function() {
        TipsCommunity.GoogleMapsStartPage.callBaseMethod(this, 'updateDisplay');        
        TUI.TipsCommunity.Templates.AjaxHandlers.Google.GetCategorizedTipTargetsByTipLocation(this.get_categories(), currentLocation.ID, 0, 0, 0, 0, 1, this.get_numberOfMarkersToDisplay(), this.get_sortOrder(), this.get_id(), this.renderLocations, FailedCallback);
      }
}

TipsCommunity.GoogleMapsStartPage.registerClass('TipsCommunity.GoogleMapsStartPage', TipsCommunity.GoogleMapsZoomSearchEnabled);
// END GoogleMapsStartPage class //

// GoogleMapsSubSection class //
TipsCommunity.GoogleMapsSubSection = function(element) {
    TipsCommunity.GoogleMapsSubSection.initializeBase(this, [element]);   
}

TipsCommunity.GoogleMapsSubSection.prototype = {
    initialize: function() {
        TipsCommunity.GoogleMapsSubSection.callBaseMethod(this, 'initialize');
            this.get_map().setMapType(G_PHYSICAL_MAP);
            this.get_map().enableDragging();       
            this.get_map().enableDoubleClickZoom();   
            var smallZoomControl;
            GEvent.addListener(this.get_map(), 'mouseover', function() { 
                smallZoomControl = new GSmallZoomControl();
                this.addControl(smallZoomControl);
            });
            GEvent.addListener(this.get_map(), 'mouseout', function() {                
                this.removeControl(smallZoomControl);
            });
            
            if(googleMapZoomLevel > 10)
                this.get_map().setMapType(G_NORMAL_MAP);        
             else
                this.get_map().setMapType(G_PHYSICAL_MAP)   
      },
      dispose: function() {        
        TipsCommunity.GoogleMapsSubSection.callBaseMethod(this, 'dispose');
      },      
      updateDisplay: function() {
        TipsCommunity.GoogleMapsSubSection.callBaseMethod(this, 'updateDisplay');        
        TUI.TipsCommunity.Templates.AjaxHandlers.Google.GetCategorizedTipTargetsByTipLocation(this.get_categories(), currentLocation.ID, 0, 0, 0, 0, 1, this.get_numberOfMarkersToDisplay(), this.get_sortOrder(), this.get_id(), this.renderLocations, FailedCallback);
        this.get_map().setCenter(new GLatLng(currentLocation.Position.Latitude, currentLocation.Position.Longitude), googleMapZoomLevel);  
      }
}

TipsCommunity.GoogleMapsSubSection.registerClass('TipsCommunity.GoogleMapsSubSection', TipsCommunity.GoogleMapsZoomSearchEnabled);
// END GoogleMapsSubSection class //


// GoogleMapsTipOverview class //
TipsCommunity.GoogleMapsTipOverview = function(element) {
    TipsCommunity.GoogleMapsTipOverview.initializeBase(this, [element]);   
}

TipsCommunity.GoogleMapsTipOverview.prototype = {
    initialize: function() {
        TipsCommunity.GoogleMapsTipOverview.callBaseMethod(this, 'initialize');

        this.get_map().addControl(new GOverviewMapControl(tuiBrandId == 17 ? new GSize(213, 213) : new GSize(188, 188)));
        var mapTypeControl, largeMapControl, dragZoomControl;

        GEvent.addListener(this.get_map(), 'move', this.loadMarkersOnZoom);    

        GEvent.addListener(this.get_map(), 'mouseover', function() {
            mapTypeControl = new GMapTypeControl();
            var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, tuiBrandId == 17 ? new GSize(220, 5) : new GSize(193, 5));
            this.addControl(mapTypeControl, topRight);
            this.addMapType(G_PHYSICAL_MAP);

            // add zoom control....
            var boxStyleOpts = { opacity: .2, border: "2px solid white" };
            var otherOpts = { buttonHTML: "<img src='/TipsCommunity/Includes/Images/Google/zoom-control-inactive.png' title='" + globalResourceTextInstance.tipsDragAndZoom + "' />", buttonZoomingHTML: "<img src='/TipsCommunity/Includes/Images/Google/zoom-control-active.png' title='" + globalResourceTextInstance.tipsCloseDragAndZoom + "' />", buttonStartingStyle: { width: '17px', height: '17px' }, overlayRemoveTime: 0 };
            dragZoomControl = new DragZoomControl(boxStyleOpts, otherOpts, {});
            this.addControl(dragZoomControl, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(27, 7)));

            largeMapControl = new GLargeMapControl();
            this.addControl(largeMapControl, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 32)));

            this.enableScrollWheelZoom();
        });
        GEvent.addListener(this.get_map(), 'mouseout', function() {
            this.removeControl(mapTypeControl)
            this.removeControl(largeMapControl)
            this.removeControl(dragZoomControl)
        });

        var arrCheckboxes = this.get_checkBoxList();
        for (key in arrCheckboxes) {
            $addHandlers(arrCheckboxes[key], { "click": this.categoriesChanged }, this);
        }

        var $sortLinks = $('div#special-options ul.sorting');
        $addHandlers($sortLinks.find("a.sort-map-date").get(0), { "click": this.sortOrderDateChanged }, this);
        $addHandlers($sortLinks.find("a.sort-map-rating").get(0), { "click": this.sortOrderRatingChanged }, this);
        $addHandlers($sortLinks.find("a.sort-map-alphabetically").get(0), { "click": this.sortOrderAlphabeticallyChanged }, this);
    },
    zoomAndUpdateMarkers: function(id, position, controlClassName) {
        var zoomLevel = 2;
        switch (controlClassName) {
            case "continents":
                zoomLevel = 3;
                break;
            case "countries":
                zoomLevel = 5;
                break;
            case "geographical-areas":
                zoomLevel = 7;
                break;
            case "cities":
                zoomLevel = 10;
                break;
        }

        cluster.removeMarkers();
        cluster.refresh();
        currentLocation.ID = id;
        if (this.get_map().getZoom() == zoomLevel)
            scheduleMethodInvocation(this, "startUpdateDisplay", 1000, this.get_id());

        this.get_map().setCenter(new GLatLng(position.Latitude, position.Longitude), zoomLevel);
        this.get_map().closeExtInfoWindow();
    },
    sortOrderDateChanged: function() {
        $("div#special-options ul.sorting a.sort-map-date").addClass("active");
        $("div#special-options ul.sorting a.sort-map-rating").removeClass("active");
        $("div#special-options ul.sorting a.sort-map-alphabetically").removeClass("active");
        this.sortOrderChanged("Date");
    },
    sortOrderRatingChanged: function() {
        $("div#special-options ul.sorting a.sort-map-rating").addClass("active");
        $("div#special-options ul.sorting a.sort-map-date").removeClass("active");
        $("div#special-options ul.sorting a.sort-map-alphabetically").removeClass("active");
        this.sortOrderChanged("Rating");
    },
    sortOrderAlphabeticallyChanged: function() {
        $("div#special-options ul.sorting a.sort-map-alphabetically").addClass("active");
        $("div#special-options ul.sorting a.sort-map-rating").removeClass("active");
        $("div#special-options ul.sorting a.sort-map-date").removeClass("active");
        this.sortOrderChanged("Alphabetically");
    },
    sortOrderChanged: function(sortOrder) {
        this.set_sortOrder(sortOrder);
        cluster.removeMarkers();
        cluster.refresh();
        this.updateDisplay();
    },
    get_checkBoxList: function() {
        return $(this.get_element()).find('div.category-list ul li :checkbox').get();
    },
    categoriesChanged: function(e) {
        if ($(e.target).parent().hasClass("all-checkboxes")) {
            $("div.category-list ul li.category-item :checkbox:checked").attr("checked", false);
        }
        else {
            $(".all-checkboxes :checkbox").attr("checked", false);
        }

        var searchString = "";

        $(this.get_checkBoxList()).filter(":checked").each(function() {
            searchString += "," + this.categoryID;
        });

        if (searchString.charAt(0) == ",")
            searchString = searchString.substring(1, searchString.length);

        // Removes content from popup
        $("div#google-callout_window").html("");

        cluster.removeMarkers();
        cluster.refresh()
        this.set_categories = searchString;
        scheduleMethodInvocation(this, "startUpdateDisplay", 1000, this.get_id());
    },
    dispose: function() {
        TipsCommunity.GoogleMapsTipOverview.callBaseMethod(this, 'dispose');
    },
    updateDisplay: function() {
        TipsCommunity.GoogleMapsTipOverview.callBaseMethod(this, 'updateDisplay');

        if (typeof (this.get_categories()) == "undefined") {
            //alert("Ingen category vald");
            return;
        }

        if (this.get_viewMode() == "ViewUser") {
            TUI.TipsCommunity.Templates.AjaxHandlers.Google.GetTipsByAuthor(this.get_currentUserName(), this.get_categories(), currentLocation.ID, 0, 0, 0, 0, 1, this.get_numberOfMarkersToDisplay(), this.get_sortOrder(), this.get_id(), this.renderLocations);
        }
        else if (this.get_viewMode() == "ViewLocation") {
            TUI.TipsCommunity.Templates.AjaxHandlers.Google.GetCategorizedTipTargetsByTipLocation(this.get_categories(), currentLocation.ID, 0, 0, 0, 0, 1, this.get_numberOfMarkersToDisplay(), this.get_sortOrder(), this.get_id(), this.renderLocations, FailedCallback);
        }
        else if (this.get_viewMode() == "ViewTag") {
            TUI.TipsCommunity.Templates.AjaxHandlers.Google.GetTipsByLocationsAndTag(this.get_tagId(), currentLocation.ID, this.get_categories(), 0, 0, 0, 0, 1, this.get_numberOfMarkersToDisplay(), this.get_sortOrder(), this.get_id(), this.renderLocations);
        }
        else {
            //alert(this.get_viewMode());
        }
        
        if (this.get_currentZoomLevel() == 2) {
            this.get_map().setCenter(new GLatLng(24, 38), this.get_currentZoomLevel());
        }
        else {
            this.get_map().setCenter(new GLatLng(currentLocation.Position.Latitude, currentLocation.Position.Longitude), this.get_currentZoomLevel());
        }

    },
    get_tagId: function() {
        return this._tagId;
    },
    set_tagId: function(value) {
        this._tagId = value;
    },
    get_currentZoomLevel: function() {
        return this._currentZoomLevel;
    },
    set_currentZoomLevel: function(value) {
        this._currentZoomLevel = value;
    }
}
TipsCommunity.GoogleMapsTipOverview.registerClass('TipsCommunity.GoogleMapsTipOverview', TipsCommunity.GoogleMapsZoomSearchEnabled);

function bindLocationNavEvents()
{
    $("div.google-map-tip-overview .continents, div.google-map-tip-overview .countries, div.google-map-tip-overview .geographical-areas, div.google-map-tip-overview .cities").change(function()
    { 
        if(this.selectedIndex > 1)
        {        
            $("div#info-box").remove();
            var
                locationID = parseInt(this.value),
                targetDropDownCssClass = $(this).attr('class');
            
            TUI.TipsCommunity.Templates.AjaxHandlers.Google.GetLocation(locationID, 
                function (data) 
                {
                    var
                        googleMapControl = $find(googleMapClientId),
                        location = Sys.Serialization.JavaScriptSerializer.deserialize(data);
                        
                    googleMapControl.zoomAndUpdateMarkers(location.ID, location.Position, targetDropDownCssClass);
                }
            );
        }
    });
}

/*  */
function startUpdateDisplay(clientID)
{
    var thisRef = $get(clientID).control;   
    thisRef.updateDisplay();
}

function startloadMarkersOnZoom(clientID)
{
    var thisRef = $get(clientID).control;   
    
    var bounds = thisRef.get_map().getBounds();
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();    
        
    var coordinates = new Array();
    coordinates[0] = southWest.lat();
    coordinates[1] = southWest.lng();
    coordinates[2] = northEast.lat();
    coordinates[3] = northEast.lng();
 
    if(thisRef.get_viewMode() == "ViewUser") {
       TUI.TipsCommunity.Templates.AjaxHandlers.Google.GetTipsByAuthor(thisRef.get_currentUserName(), thisRef.get_categories(), currentLocation.ID, coordinates[0], coordinates[1], coordinates[2], coordinates[3], 1, thisRef.get_numberOfMarkersToDisplay(), thisRef.get_sortOrder(), thisRef.get_id(), thisRef.renderLocations); 
    }
    else if(thisRef.get_viewMode() == "ViewTag") {                                          
        TUI.TipsCommunity.Templates.AjaxHandlers.Google.GetTipsByLocationsAndTag(thisRef.get_tagId(), currentLocation.ID, thisRef.get_categories(), coordinates[0], coordinates[1], coordinates[2], coordinates[3], 1, thisRef.get_numberOfMarkersToDisplay(), thisRef.get_sortOrder(), thisRef.get_id(), thisRef.renderLocations);
    }
    else {
        TUI.TipsCommunity.Templates.AjaxHandlers.Google.GetCategorizedTipTargetsByTipLocation(thisRef.get_categories(), currentLocation.ID, coordinates[0], coordinates[1], coordinates[2], coordinates[3], 1, thisRef.get_numberOfMarkersToDisplay(), thisRef.get_sortOrder(), thisRef.get_id(), thisRef.renderLocations, FailedCallback);                
    }
}

// End GoogleMapsTipOverview class //


// Profile class //
TipsCommunity.GoogleMapsProfilePage = function(element) {
    TipsCommunity.GoogleMapsProfilePage.initializeBase(this, [element]);   
}

TipsCommunity.GoogleMapsProfilePage.prototype = {
    initialize: function() {
        TipsCommunity.GoogleMapsProfilePage.callBaseMethod(this, 'initialize');

        this.get_map().setMapType(G_PHYSICAL_MAP);
        this.get_map().enableDragging();
        var smallZoomControl;

        GEvent.addListener(this.get_map(), 'mouseover', function() {
            smallZoomControl = new GSmallZoomControl();
            this.addControl(smallZoomControl);
        });
        GEvent.addListener(this.get_map(), 'mouseout', function() {
            this.removeControl(smallZoomControl);
        });
    },
    dispose: function() {
        TipsCommunity.GoogleMapsProfilePage.callBaseMethod(this, 'dispose');
    },
    updateDisplay: function() {
        TipsCommunity.GoogleMapsProfilePage.callBaseMethod(this, 'updateDisplay');

        var LocationsCollectionArray = this.get_locations();
        var marker, markersArray = [];
        var letterArray = new Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "Å", "Ä", "Ö");
        var letterCounter = 0;

        for (var j = 0; j < LocationsCollectionArray.length; j++) {
            if (LocationsCollectionArray[j].length == 1) {
                marker = this.createLabeledCategoryMarker(new GLatLng(LocationsCollectionArray[j][0].Position.Latitude, LocationsCollectionArray[j][0].Position.Longitude), LocationsCollectionArray[j][0].Name, LocationsCollectionArray[j][0].Url, LocationsCollectionArray[j][0].Category, letterArray[letterCounter]);
                markersArray.push(marker);
                letterCounter++;
            }
            else {
                var idArray = new Array();
                for (var i = 0; i < LocationsCollectionArray[j].length; i++) {
                    idArray.push(LocationsCollectionArray[j][i].ID);
                    letterCounter++;
                }
                var html = "/TipsCommunity/Templates/AjaxHandlers/GoogleMapContentProvider.aspx?locationids=" + idArray.toString().replace(",", "a") + "&page=1&count=" + LocationsCollectionArray[j].length;

                var markerLocation = new GLatLng(LocationsCollectionArray[j][0].Position.Latitude, LocationsCollectionArray[j][0].Position.Longitude);
                marker = this.createClusterMarker(markerLocation, LocationsCollectionArray[j][0].Name, LocationsCollectionArray[j][0].Url, LocationsCollectionArray[j].length, html, this);
                markersArray.push(marker);
            }
            
        }
        cluster = new ClusterMarker(this.get_map(), { markers: markersArray });
        cluster.fitMapToMarkers();

        this.get_map().savePosition();

    },
    createLabeledCategoryMarker: function(markerLocation, name, url, categoryId, letter) {
        var opts = { "icon": this.createSmallMarker(categoryId), "clickable": true, "labelText": letter, "title": name, "labelOffset": new GSize(-1, -20) };
        var marker = new LabeledMarker(markerLocation, opts);

        GEvent.addListener(marker, 'click', function() {
            location.href = url;
        });
        return marker;
    }
}
TipsCommunity.GoogleMapsProfilePage.registerClass('TipsCommunity.GoogleMapsProfilePage', TipsCommunity.GoogleMapBase);
// End Profile class //

// World class //
/*
* This class is used by the google map on the startpage
*
*/
TipsCommunity.World = function(element) {
    TipsCommunity.World.initializeBase(this, [element]);
}

TipsCommunity.World.prototype = {
    initialize: function() {
        TipsCommunity.World.callBaseMethod(this, 'initialize');
        this.get_map().setCenter(new GLatLng(21, 0), 2);
        this.get_map().disableDoubleClickZoom();
        this.get_map().disableDragging();    
    },
    dispose: function() {
        TipsCommunity.World.callBaseMethod(this, 'dispose');
    }
}
TipsCommunity.World.registerClass('TipsCommunity.World', TipsCommunity.GoogleMapBase);

// UpdateTip class //
/*
* This class is used by the google map on the startpage
*
*/
TipsCommunity.UpdateTip = function(element) {
    TipsCommunity.UpdateTip.initializeBase(this, [element]);
}

TipsCommunity.UpdateTip.prototype = {
    initialize: function() {
        TipsCommunity.UpdateTip.callBaseMethod(this, 'initialize');

        var LocationsCollectionArray = this.get_locations();
                
        var lat = LocationsCollectionArray.Position.Latitude;
        var lng = LocationsCollectionArray.Position.Longitude;
        
        this.get_map().setCenter(new GLatLng(lat, lng), 10);
        this.get_map().setMapType(G_NORMAL_MAP);
        this.get_map().addControl(new GSmallZoomControl());
        
        var marker = this.createCategoryMarker(new GLatLng(lat, lng), LocationsCollectionArray.Name, "", LocationsCollectionArray.Category, false);
        marker.disableDragging()
        this.get_map().addOverlay(marker);
    },
    dispose: function() {
        TipsCommunity.UpdateTip.callBaseMethod(this, 'dispose');
    }
}
TipsCommunity.UpdateTip.registerClass('TipsCommunity.UpdateTip', TipsCommunity.GoogleMapBase);

// TipTargetListing class //
/*
* This class is used by the google map on the startpage
*
*/
TipsCommunity.TipTargetListing = function(element) {
    TipsCommunity.TipTargetListing.initializeBase(this, [element]);
}

TipsCommunity.TipTargetListing.prototype = {
    initialize: function() {
        TipsCommunity.TipTargetListing.callBaseMethod(this, 'initialize');
        this.get_map().setCenter(new GLatLng(21, 0), 2);
        this.get_map().enableDoubleClickZoom();
        this.get_map().enableDragging();
        this.get_map().addControl(new GSmallZoomControl());
        this.get_map().clearOverlays();
       // alert("hj");
    },
    dispose: function() {
        TipsCommunity.TipTargetListing.callBaseMethod(this, 'dispose');
    }    
}

function showTips(pageNumber, pageSize, sortOrder, categoryIDs) {
 
    var thisRef = $('div.google-map').get(0).control;
    thisRef.set_map(new GMap2($('div.google-map div.map-container').get(0)));
    thisRef.get_map().clearOverlays();
    thisRef.get_map().addControl(new GSmallZoomControl());
    thisRef.get_map().setCenter(new GLatLng(50, 21), 2);
    thisRef.get_map().setMapType(G_PHYSICAL_MAP);
    

    TUI.TipsCommunity.Templates.AjaxHandlers.Google.GetTipsByParentLocation(currentLocation.ID, categoryIDs, pageNumber, pageSize, sortOrder, thisRef.get_id(), thisRef.renderLocations, FailedCallback); 
}

TipsCommunity.TipTargetListing.registerClass('TipsCommunity.TipTargetListing', TipsCommunity.GoogleMapBase);


G_PHYSICAL_MAP.getMinimumResolution = function() { return 2 };

// Gets the previous tiptarget in popup in the map
function prev(id, page, count) {
    $(".google-callout div#inner-content").html("");
    $(".google-callout").load(
        String.format
        (
            "/TipsCommunity/Templates/AjaxHandlers/GoogleMapContentProvider.aspx?locationids={0}&page={1}&count={2}&minified=true div#inner-content",
            id,
            page,
            count
        )
    );
}

// Gets the next tiptarget in popup in the map
function next(id, page, count) {
    $(".google-callout div#inner-content").html("");
    $(".google-callout").load(
        String.format
        (
            "/TipsCommunity/Templates/AjaxHandlers/GoogleMapContentProvider.aspx?locationids={0}&page={1}&count={2}&minified=true div#inner-content",
            id,
            page,
            count
        )
    );
}

// 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); 
} 

if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();


