﻿

    //Enumeration of the Categories 
    var MarkerCategory = new Array( "Discover", "Hotel", "MustSee", "Party", "Resto", "Shop" );

    //GMarkers is a collection of all markers on the map, grouped by category
    //Example: GMarkers[category][i] = marker1;
    //Further more it contains per marker an arrary of keywords and the tripitemid of the tripitem:
    //Example Keywords: GMarkers[category][i]["KeyWordsForHighlight"] = { "Trendy", "Romantic", "Design" };
    //When the cursor moves over a marker on the map, the corresponding keywords in the tagcloud array will be highlighted.
    //Example Keywords: GMarkers[category][i]["TripItemId"] = "eed0aecc-0c7b-4040-9726-3750c6710ff6";
    var GMarkers = new Array();

    //Keywords is a collection of all diffent keywords used on the map by the markers.
    //The index values of the GMarkers Array correspond to the index values of the Keywords array!
    //Example: Keywords["Affordable"]["Hotel"] = { 1,5,6 };
    //This means that the "Affordable" keyword belongs to marker 1,5 and 6 of the Hotel category, in other words:
    //The keyword "Affordable" belows to: GMarkers["Hotel"][1] and GMarkers["Hotel"][5] and GMarkers["Hotel"][6]
    //This way makes it possible to highlight a marker on the map when the mouse cursor hoovers over a keyword in the tagcloud.
    var Keywords = new Array([],[],[]);

    //KeywordList is an array of all keywords used with a certain context.
    //Example: KeywordList = { "Trendy", "A must", "Chines", "Romantic" };
    var KeywordList = new Array();

    //KeywordCount is a collection of how many times a certain keyword is used per category. This is used for the font size in the tagcloud.
    //A keyword in the tagcloud wich is used more frequently will be displayed in a bigger size...
    //Example: KeywordCount[Keyword][Category]
    //Concrete: KeywordCount["Affordable"]["Hotel"] = 5; //The keyword "Affordable" occurs 5 times in the "Hotel" Category
    //Concrete: KeywordCount["Affordable"]["Reso"] = 3; //The keyword "Affordable" occurs 3 times in the "Resto" Category
    var KeywordCount = new Array([]);

    //The TagCloudLinks variable will be come an array eventually. It is used the contain a summary of how many time a certain word is used globally.
    //For instance the keyword "Affordable" is used within the "Hotel" category and the "Resto" category, a sum of the count of both keywords
    //will be stored in the TagCloudLinks collection.
    //Example: KeywordCount["Affordable"]["Hotel"] = 5 and KeywordCount["Affordable"]["Reso"] = 3 : the sum of 3 and 5 will be stored in TagCloudlinks as follows:
    //TagCloudLinks["Affordable"]["Count"] = 8
    //Also the TagCloudLinks contains a collection of the categories wich is used for looking up the markers in the certain categories
    //The categories are saved within the array as 1 string variable, separated by the "|" character.
    //Example: TagCloudLinks["Affordable"]["Categories"] = "Hotel|Resto|Shop|";
    //The function "HighLightMarker" uses the TagCloudLinks["Affordable"]["Categories"] array, in order to ligth up a certain marker.
    var TagCloudLinks;

    //This variable is used to determine the highest number of counts per keyword.
    var MaxCountKeywords = 0;

    //The TripItemCollection is used when a certain TripItemID is provided with this URL:
    //Example: ~/Discover/<languagedir>/index.aspx?TripItemID=eed0aecc-0c7b-4040-9726-3750c6710ff6
    //This collectin contains per TripItemId the keywords, used for the the tagcloud and de makers, showed on the map:
    //Example: TripItemCollection[tripItemId]["Keywords"] & TripItemCollection[tripItemId]["Marker"]
    //Concrete: TripItemCollection["eed0aecc-0c7b-4040-9726-3750c6710ff6"]["Keywords"] = { "Affordable", "Business", "Trendy" };
    //          TripItemCollection["eed0aecc-0c7b-4040-9726-3750c6710ff6"]["Marker"] = new GMarker();    
    var TripItemCollection = new Array();

    //The MyTripCollection works the same way as the TripItemCollection, but this collection contains data concerning a certain MyTrip
    //Also the MyTripId is provided in the url: ~/Discover/<languagedir>/index.aspx?MyTripId=1
    //This collection also holds the Keywords and marker per TripItemId: MyTripCollection[tripItemId]["Keywords"] & MyTripCollection[tripItemId]["Marker"]
    //Concrete: MyTripCollection["eed0aecc-0c7b-4040-9726-3750c6710ff6"]["Keywords"] = { "Affordable", "Business", "Trendy" };
    //          MyTripCollection["eed0aecc-0c7b-4040-9726-3750c6710ff6"]["Marker"] = new GMarker();  
    var MyTripCollection = new Array();

    //The MyTripTripItems is an array of TripItem Ids! This array holds all indexes of the MyTripCollection array!
    //Example: MyTripTripItems = { "eed0aecc-0c7b-4040-9726-3750c6710ff6", "e9bba429-a7e0-4de0-9992-76ecb911dbe0" }
    //  The values in that array are used in the MyTripCollection:
    //  MyTripCollection[MyTripTripItems[0]]["Marker"] = MyTripCollection["eed0aecc-0c7b-4040-9726-3750c6710ff6"]["Marker"]
    //  MyTripCollection[MyTripTripItems[1]]["Marker"] = MyTripCollection["e9bba429-a7e0-4de0-9992-76ecb911dbe0"]["Marker"]
    var MyTripTripItems = new Array();
    
    //TODO these should be set to lowercase
    var UrlTripItemId = RetreiveNumericValue($.jqURL.get('TripItemID'));
    var UrlMyTripId = RetreiveNumericValue($.jqURL.get('MyTripId'));
    var UrlSuggestionId = RetreiveNumericValue($.jqURL.get('suggestion'));
    
    //Wire on body load event using jQuery:
    $(document).ready(function() {
        Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(PageOnLoadWrapper);
        if ((typeof (__skip_gmaps_init_on_pageload) == 'undefined') || !__skip_gmaps_init_on_pageload)
            PageOnLoad(); 
    });

    // raised when: after ajax postback    
    function PageOnLoadWrapper() {
        if ((typeof(__skip_gmaps_init_on_ajax_pageload) !== 'undefined') && __skip_gmaps_init_on_ajax_pageload)
            return;

        PageOnLoad();
    }

    //var kmlParis;
    //var kmlLondon;
    
    // raised when: on page load and after ajax postback (if __skip_gmaps_init_on_ajax_pageload is not true)
    function PageOnLoad() {        
        //if ((typeof (__call_onload_when_gmap_loaded) == 'undefined') || __call_onload_when_gmap_loaded) {
        //    kmlParis = new GGeoXml("http://www.eurostartripplanner.com/_scripts/paris.xml"); // kml must be reachable by Google
        //    kmlLondon = new GGeoXml("http://www.eurostartripplanner.com/_scripts/london.xml"); // kml must be reachable by Google
        //}

        ShowGMap();
        
        // LoadPreviousMarkers();
        
        if (UrlTripItemId != null && UrlTripItemId != "")
            RenderDetailGMap(UrlTripItemId);
            
        if(UrlMyTripId != null && UrlMyTripId != "") {
            RenderMyTripGMap(UrlMyTripId);
         }
          if(UrlSuggestionId != null && UrlSuggestionId != "") {
            RenderSuggestionGMap(UrlSuggestionId);
            
         }

         //if ((typeof (__call_onloaded_when_gmap_loaded) !== 'undefined') && __call_onloaded_when_gmap_loaded)
         //GEvent.addListener(map, "load", gmap_onloaded);
         //    gmap_onloaded();

        //CheckDiscoveryParameter(); // is located within the SubNav control ... invoked here, otherwise ResetSubNavigation would override the selection ...
    }
    
    //Clean up memory.
    $(window).unload(
        function ()
        {
            GMarkers = null;
            Keywords = null;
            KeywordList = null;
            KeywordCount = null;
            TagCloudLinks = null;
            TripItemCollection = null;
            MyTripCollection = null;
            MyTripTripItems = null;
            GUnload();
        });

    function RetreiveNumericValue(input)
    {
        if (input == null)
            return null;
    
        if (input.indexOf("#") >= 0)
            return input.split('#')[0];
        else
            return input;    
    }

    //The GetCookie method is located in the /_scripts/functions.js file
    function GetDestination() {
        if (typeof(__tripplanner_destination) !== 'undefined')
            return __tripplanner_destination;
            
        return GetCookie("Destination", "paris");
    }

    function GetCountry() {
        if (typeof(__tripplanner_country) !== 'undefined')
            return __tripplanner_country;
            
        return GetCookie("Country", "uk");
    }
    
    function GetMapCenter(destination){
            var point;
            switch(_destination.toLowerCase())
            {
                case 'paris':
                    point = new GLatLng(48.856869,2.34125);
                    break;
                default:
                    point = new GLatLng(51.50877,-0.133434);
            }
            map.setCenter(point, 13);
    }

    //The GetCookie method is located in the /_scripts/functions.js file
    function GetLanguage()
    {
        if (typeof(__tripplanner_language) !== 'undefined')
            return __tripplanner_language;
        return GetCookie("Lang", "en");
    }
    
    
    function ShowGMap()
    {
        if (GBrowserIsCompatible()) {
            map = new GMap2(document.getElementById('map'));
            map.addControl(new GLargeMapControl());

            //GetKmlFiles()
            
            if ((typeof (__call_onload_when_gmap_loaded) !== 'undefined') && __call_onload_when_gmap_loaded) {
                gmap_onload();
                //GEvent.addListener(map, "zoomend", function() { GetKmlFiles(); });
            }
            else {
                // lame hack, only handle events and display kmls when not in adv search
                //GEvent.addListener(map, "dragend", function() {
                    //LoadVisibleItems();
                //});
                //GEvent.addListener(map, "zoomend", function() {
                    //LoadVisibleItems();
                //    GetKmlFiles();
                //});
            }

        }
        else
        {
            alert("Sorry, the Google Maps API is not compatible with this browser");
        }
    }

    //var kml_overlays_are_shown = false;
//    function GetKmlFiles() {
//        var zoomlevel = map.getZoom();
//        if (zoomlevel < 12 && !kml_overlays_are_shown) {
//            map.addOverlay(kmlParis);
//            map.addOverlay(kmlLondon);
//            kml_overlays_are_shown = true;
//        }
//        if (zoomlevel >= 12 && kml_overlays_are_shown) {
//            map.removeOverlay(kmlParis);
//            map.removeOverlay(kmlLondon);
//            kml_overlays_are_shown = false;
//        }
//    }
    


    
    function LoadVisibleItems(){
   

        //get coordinates of visible map;
        var bounds = map.getBounds();
        var SW = bounds.getSouthWest();
        var NE = bounds.getNorthEast();
        var SW_Lat= SW.lat();
        var SW_Lng= SW.lng();
        var NE_Lat= NE.lat();
        var NE_Lng= NE.lng();
        
        //First hide em all...
        HideAllMarkers();
        
        for(var i=0; i<MarkerCategory.length; i++ ){
            var category = MarkerCategory[i];
            
            if(SearchWebControl("chk"+category.checked)){
                RenderGMapByCoordinates(category,SW_Lat,SW_Lng,NE_Lat,NE_Lng);
            }else{
                
            }
        }      
    }
    
    
    function LoadAllMarkers()
    {
         
		for (LoadAllMarkersCount=0; LoadAllMarkersCount<MarkerCategory.length; LoadAllMarkersCount++)
            LoadMarkers(SearchWebControl("chk"+MarkerCategory[LoadAllMarkersCount]));
    }

    function LoadMarkers(checkbox)
    {
         
		var checkboxvalue = GetCheckBoxValue(checkbox);
        if (checkbox.checked)
            RenderGMap(checkboxvalue);
        else
        {
            HideMarkers(GMarkers[checkboxvalue]);
            BuildTagCloud();
        }
    }
    
    
        //This function is only called when the user selects a category and then hits the refresh button of the browser but it won't fire when 
    //there are automatic actions are going to be executed (cfr "actions" in querystring).
    function LoadPreviousMarkers()
    {
        if ($.jqURL.get("actions") == null)
        {
            if (IsCategorySelected())
            {
                for (CategoryCount=0; CategoryCount<MarkerCategory.length; CategoryCount++)
                {
                    var Control = SearchWebControl("chk" + MarkerCategory[CategoryCount]);
                    if (Control.checked)
                    {
                       // LoadMarkers(Control);
                     //  LoadVisibleItems();
                    }
                }
            }
        }
    }
    
    function GetCheckBoxValue(checkbox)
    {
        var checkboxid = checkbox.id;
        if (checkboxid.toLowerCase().indexOf("chkhotel") >= 0)
            return "Hotel";
        else if (checkboxid.toLowerCase().indexOf("chkresto") >= 0)
            return "Resto";
        else if (checkboxid.toLowerCase().indexOf("chkdiscover") >= 0)
            return "Discover";
        else if (checkboxid.toLowerCase().indexOf("chkparty") >= 0)
            return "Party";
        else if (checkboxid.toLowerCase().indexOf("chkshop") >= 0)
            return "Shop";
        else if (checkboxid.toLowerCase().indexOf("chkmustsee") >= 0)
            return "MustSee";
        else
            return checkbox.value;            
    }
    
    function RenderDetailGMap(TripItemId) {       
        if(TripItemId != "") {
            var RequestUrl = "/Async/Data.aspx?GetLocationXMLOfTripItem," + TripItemId + "," + GetLanguage() + "," + GetCountry() + "," + GetDestination();

            var request = GXmlHttp.create();
            request.open('GET', RequestUrl, true);

            request.onreadystatechange = function() {
                if (request.readyState == 4) {

                    var xmlDoc = GXml.parse(request.responseText);
                    if (xmlDoc.documentElement != null) {
                        var markers = xmlDoc.documentElement.getElementsByTagName('marker');

                        if (markers.length == 1)
                            HandleDetailMarkers(markers[0]);
                    }
                    else {
                        //alert('documentElement missing: ' + request.responseText);
                    }
                }
            }
            request.send(null);
        }
    }
    
    //This function is called when a detail of a tripitem is requested.
    function HandleDetailMarkers(marker)
    {
        var triptype = marker.getAttribute('triptype');
        var Icon = CreateIcon(triptype, true);
        var tripItemId = marker.getAttribute('tripItemId');
        
        var lat = parseFloat(marker.getAttribute('lat'));
        var lng = parseFloat(marker.getAttribute('lng'));
        var point = new GLatLng(lat,lng);
        
        var html = marker.getElementsByTagName('InfoWindowContent')[0].firstChild.nodeValue;
        var label = marker.getAttribute('label');
        
        var KeyWordsForHighlight = new Array();
        var keywords = marker.getElementsByTagName('keyword');
        for(keywordcounter = 0; keywordcounter<keywords.length; keywordcounter++)
        {
            var keywordXML = keywords[keywordcounter].getAttribute('word');            
            if (!Contains(KeywordList,keywordXML)) KeywordList.push(keywordXML);                
            if (!Contains(KeyWordsForHighlight,keywordXML)) KeyWordsForHighlight.push(keywordXML);
        }
        if (TripItemCollection[tripItemId] == null) TripItemCollection[tripItemId] = new Array();
        
        TripItemCollection[tripItemId]["Keywords"] = KeyWordsForHighlight;
        
        var marker = createMarker(point,label,html,Icon, KeyWordsForHighlight);
        TripItemCollection[tripItemId]["Marker"] = marker;
        AddMarker(map, TripItemCollection[tripItemId]["Marker"]);
        
        map.setCenter(point, 14);
    }

    function RenderMyTripGMap(MyTripId) {
        if (MyTripId != "") {
            var RequestUrl = "/Async/Data.aspx?GetLocationXMLOfMyTrip," + MyTripId + "," + new Date().getTime() + "," + GetLanguage()  + "," + GetCountry() + "," + GetDestination();
            var request = GXmlHttp.create();

            request.open('GET', RequestUrl, true);
            request.onreadystatechange = function() {
                if (request.readyState == 4) {
                    var xmlDoc = GXml.parse(request.responseText);
                    if (xmlDoc.documentElement != null) {
                        var markers = xmlDoc.documentElement.getElementsByTagName('marker');
                        if (markers.length > 0)                            
                            HandleMyTripMarkers(markers, true);
                        
                        if ((typeof (__show_printbutton_when_gmap_loaded) !== 'undefined') && __show_printbutton_when_gmap_loaded) 
                            $('.printbutton').show();
                    }
                    else {
                        //alert('documentElement missing: ' + request.responseText);
                    }
                }
            }
            request.send(null);
        }
    }

    function RenderSuggestionGMap(suggestionId) {
        if (suggestionId != "") {
            var RequestUrl = "/Async/Data.aspx?GetLocationXMLOfSuggestion," + suggestionId + "," + GetLanguage() + "," + GetCountry() + "," + GetDestination();
            var request = GXmlHttp.create();

            request.open('GET', RequestUrl, true);
            request.onreadystatechange = function() {
                if (request.readyState == 4) {
                    var xmlDoc = GXml.parse(request.responseText);
                    if (xmlDoc.documentElement != null) {
                        var markers = xmlDoc.documentElement.getElementsByTagName('marker');
                        if (markers.length > 0)
                            HandleMyTripMarkers(markers, false);
                        else {
                            map.setCenter(GetMapCenter(''));
                            map.setZoom(12);
                        }
                    }
                    else {
                        //alert('documentElement missing: ' + request.responseText);
                    }
                }
            }
            
            request.send(null);
        }
    }

    //This function is called when a "MyTrip" is requested.
    function HandleMyTripMarkers(markers, useNumbers)
    {
        var bounds = new GLatLngBounds;
        for (var i = 0; i < markers.length; i++) {
            var triptype = markers[i].getAttribute('triptype');
    
            var Icon = null;
            if (useNumbers) {
                var number = markers[i].getAttribute('refnr');
                Icon = CreateIconWithNumber(number, triptype);
            }
            else Icon = CreateIcon(triptype, false);
            
            var tripItemId = markers[i].getAttribute('tripItemId');
            if(!Contains(MyTripTripItems,tripItemId))
                MyTripTripItems.push(tripItemId);
            
            var lat = parseFloat(markers[i].getAttribute('lat'));
            var lng = parseFloat(markers[i].getAttribute('lng'));
            var point = new GLatLng(lat, lng);
            
            bounds.extend(point);
            
            var html = markers[i].getElementsByTagName('InfoWindowContent')[0].firstChild.nodeValue;
            var label = markers[i].getAttribute('label');
            
            var KeyWordsForHighlight = new Array();
            var keywords = markers[i].getElementsByTagName('keyword');
            for(keywordcounter = 0; keywordcounter<keywords.length; keywordcounter++)
            {
                var keywordXML = keywords[keywordcounter].getAttribute('word');
            
                if (!Contains(KeywordList,keywordXML))
                    KeywordList.push(keywordXML);
                
                if(!Contains(KeyWordsForHighlight,keywordXML))
                    KeyWordsForHighlight.push(keywordXML);   
            }
            
            if (MyTripCollection[tripItemId] == null)
                MyTripCollection[tripItemId] = new Array();
        
            MyTripCollection[tripItemId]["Keywords"] = KeyWordsForHighlight;
            
            var marker = createMarker(point,label,html,Icon, KeyWordsForHighlight, false);
            MyTripCollection[tripItemId]["Marker"] = marker;
            AddMarker(map, MyTripCollection[tripItemId]["Marker"]);

        }
        map.setCenter(bounds.getCenter());
        map.setZoom(map.getBoundsZoomLevel(bounds));
//        alert(bounds.getCenter().lat() + ", " + bounds.getCenter().lng());
//        var marker2 = new GMarker(bounds.getCenter());
//        map.addOverlay(marker2);
    }

    function RenderGMap(category)
    {    
       
		if (GMarkers[category] == null)
        {
            $("#GMapPreloader").css("display", "block");
            GMarkers[category] = new Array();
            var RequestUrl = "/Async/Data.aspx?GetLocationXML," + category + "," + GetLanguage() + "," + GetCountry() + "," + GetDestination();


            var request = GXmlHttp.create();
            request.open('GET', RequestUrl, true);
            request.onreadystatechange = function() {
                if (request.readyState == 4) {
                    var xmlDoc = GXml.parse(request.responseText);
                    if (xmlDoc.documentElement != null) {
                        var markers = xmlDoc.documentElement.getElementsByTagName('marker');

                        HandleMarkers(markers, category);
                        AddMarkers(map, GMarkers[category]);
                    }
                    else {
                        //alert('documentElement missing: ' + request.responseText);
                    }
                }
            }
            request.send(null);
        }
        else
        {
		   ShowMarkers(GMarkers[category]);
        }

   }
   
   function RenderGMapByCoordinates(category,SW_lat,SW_Lng,NE_Lat,NE_Lng){
    //    $("#GMapPreloader").css("display", "block");
        GMarkers[category] = new Array();
        var RequestUrl = "/Async/Data.aspx?GetByCoordinatesXml," + category + ","  + SW_lat + "," +SW_Lng + "," +NE_Lat+ "," + NE_Lng;
        var request = GXmlHttp.create();
        request.open('GET', RequestUrl, true);
        request.onreadystatechange = function() {
            if (request.readyState == 4) {
                var xmlDoc = GXml.parse(request.responseText);
                var markers = xmlDoc.documentElement.getElementsByTagName('marker');
                HandleMarkers(markers,category);
                AddMarkers(map,GMarkers[category]);
            }
        }
        request.send(null);
   }
    
    //This funtion is used when a user clicked a category checkbo,x Hotel or MustSee or ...
    function HandleMarkers(markers,category)
    {
        for (var i = 0; i < markers.length; i++) {
            var triptype = markers[i].getAttribute('triptype');
            var Icon = CreateIcon(triptype, false);

            var tripItemId = markers[i].getAttribute('tripItemId');
            
            if((TripItemCollection[tripItemId] == null) && (MyTripCollection[tripItemId] == null))
            {
                var lat = parseFloat(markers[i].getAttribute('lat'));
                var lng = parseFloat(markers[i].getAttribute('lng'));
                var point = new GLatLng(lat,lng);
                var html = markers[i].getElementsByTagName('InfoWindowContent')[0].firstChild.nodeValue;
                
                var label = markers[i].getAttribute('label');
                
                var KeyWordsForHighlight = new Array();
                var keywords = markers[i].getElementsByTagName('keyword');
                for(keywordcounter = 0; keywordcounter<keywords.length; keywordcounter++)
                {
                    var keywordXML = keywords[keywordcounter].getAttribute('word');
                    if(!Contains(KeyWordsForHighlight,keywordXML))
                        KeyWordsForHighlight.push(keywordXML);
                    
                    if (!Contains(KeywordList,keywordXML))
                        KeywordList.push(keywordXML);
                        
                    if((KeywordCount[keywordXML] == null) || (typeof(KeywordCount[keywordXML]) == "function"))
                        KeywordCount[keywordXML] = new Array();

                    if(KeywordCount[keywordXML][category] == null)
                        KeywordCount[keywordXML][category] = 1;
                    else
                        KeywordCount[keywordXML][category]++;
                                                
                    if ((Keywords[keywordXML] == null) || (typeof(KeywordCount[keywordXML]) == "function"))
                        Keywords[keywordXML] = new Array();

                    if (Keywords[keywordXML][category] == null)
                            Keywords[keywordXML][category] = new Array();
                    
                    Keywords[keywordXML][category].push(i);
                }
                
                var marker = createMarker(point,label,html,Icon, KeyWordsForHighlight);
                GMarkers[category][i] = marker;

                if (GMarkers[category][i]["KeyWordsForHighlight"] == null)
                    GMarkers[category][i]["KeyWordsForHighlight"] = KeyWordsForHighlight;
                
                if (GMarkers[category][i]["TripItemId"] == null)
                    GMarkers[category][i]["TripItemId"] = tripItemId;
            }
        }
    }
    
    function AddMarkers(map, markers)
    {    
        for (i=0; i<markers.length; i++)
        {
            if (markers[i] != null)
                map.addOverlay(markers[i]);
        }
    }
    
    function AddMarker(map, marker)
    {    
        map.addOverlay(marker);
    }
    
    function ShowMarkers(markers)
    {
        for (i=0; i<markers.length; i++)
        {
            if(markers[i] != null)
                markers[i].show();
        }
    }
    
    function HideMarkers(markers)
    {
        if(markers != null)
        {
            for(i=0; i<markers.length; i++)
            {
                if(markers[i] != null)
                    markers[i].hide();
            }
        }
    }
    
    function HideAllMarkers()
    {
        for(markerCounter=0; markerCounter<MarkerCategory.length; markerCounter++)
        {
            var arrMarkers = GMarkers[MarkerCategory[markerCounter]];
            if (arrMarkers != null)
                HideMarkers(arrMarkers);
        }
    }
    
    //Global function for instantiating GMarker objects. Also sets Click and MouseOver events.
    function createMarker(point,name,html,icon, keywords)
    {
	return createMarker(point, name, html, icon, keywords, true);
    }

    function createMarker(point,name,html,icon, keywords, mouseover)
    {
        var marker = new GMarker(point,icon);
        
        GEvent.addListener(marker, 'click', function() {
            marker.openInfoWindowHtml(html);
        });

	if (mouseover)
	{
	        GEvent.addListener(marker, 'mouseover', function() {
        	    var img = marker.getIcon().image;
	            if(img.indexOf("_h") == -1)
        	        marker.setImage(GetHighLightIcon(img));
	            GetHighLightKeywords(keywords, true);
        	});

	        GEvent.addListener(marker, "mouseout", function() {
        	    var img = marker.getIcon().image;
	            marker.setImage(img);
        	    GetHighLightKeywords(keywords, false);
	        });
        }

        return marker;
    }

    function CreateIconWithNumber(number, triptype)
    {
        var icon = new GIcon();
        icon.iconSize = new GSize(29, 47);
        icon.iconAnchor = new GPoint(0, 20);
        icon.infoWindowAnchor = new GPoint(5, 1);
//        icon.image = '/_images/GoogleMaps/' + ((highlight) ? GetHighLightIcon(GetMarkerIcon(triptype)) : GetMarkerIcon(triptype));
        icon.image = '/Async/MyTripIconGenerator.png.aspx?number=' + number + '&triptype=' + GetCorrectTripTypeString(triptype);
        return icon;
    }
    
    function CreateIcon(triptype, highlight)
    {
        var icon = new GIcon();
        icon.iconSize = new GSize(29, 47);
        icon.iconAnchor = new GPoint(0, 20);
        icon.infoWindowAnchor = new GPoint(5, 1);
        icon.image = '/_images/GoogleMaps/' + ((highlight) ? GetHighLightIcon(GetMarkerIcon(triptype)) : GetMarkerIcon(triptype));
        return icon;
    }
    
    function GetCorrectTripTypeString(triptype)
    {
	if (triptype == 'Party')
	    return 'Nightlife';

	return triptype;
    }

    function GetMarkerIcon(triptype)
    {
        switch(triptype)
        {
            case "Hotel" : default:
                return "Hotel.png";
            case "MustSee" :
                return "MustSee.png";
            case "Discover":
                return "Discover.png";
            case "Resto":
                return "Resto.png";
            case "Party":
                return "Party.png";
            case "Shop":
                return "Shop.png";
        }
    }
    
    //Global function for determining wheter a certain value is already added to an array.
    function Contains(array, search)
    {
        var blnRetValue = false;
        for (arraycount=0; arraycount<array.length; arraycount++)
        {
            if (array[arraycount] == search)
            {
                blnRetValue = true;
                break;
            }
        }
        return blnRetValue;
    }

    //This function renders the HTML for the tagcloud and calculates the number of keywords being used.
    function BuildTagCloud()
    {
        if ($.jqURL.strip().indexOf("index.aspx") > 0)
        {
            MaxCountKeywords = 0;
            TagCloudLinks = new Array();
            document.getElementById("dvTagCloud").innerHTML = "";
            
            var category;
            var keyword;
            for(var catCount = 0; catCount<MarkerCategory.length; catCount++)
            {
                category = MarkerCategory[catCount];
            
                if (SearchWebControl("chk" + category).checked)
                {
                    for(var keywordCount=0; keywordCount<KeywordList.length; keywordCount++)
                    {
                        keyword = KeywordList[keywordCount];
                        
                        if (Keywords[keyword] != null)
                        {
                            if(Keywords[keyword][category] != null)
                            {
                                if((TagCloudLinks[keyword] == null) || (typeof(TagCloudLinks[keyword]) == "function"))
                                    TagCloudLinks[keyword] = new Array();
                            
                                if (TagCloudLinks[keyword]["Categories"] == null)
                                    TagCloudLinks[keyword]["Categories"] = "";
                                
                                TagCloudLinks[keyword]["Categories"] +=  category + "|";
                                
                                if(TagCloudLinks[keyword]["Count"] == null)
                                    TagCloudLinks[keyword]["Count"] = 0;

                                TagCloudLinks[keyword]["Count"] += KeywordCount[keyword][category];
                                
                            }
                            if (TagCloudLinks[keyword] != null && TagCloudLinks[keyword]["Count"] != null && TagCloudLinks[keyword]["Count"] > MaxCountKeywords)
                                MaxCountKeywords = TagCloudLinks[keyword]["Count"];
                        }
                    }
                }
            }
            
            var DetailedTripItem = UrlTripItemId;
            if(DetailedTripItem != null && DetailedTripItem != "")
            {
                if((TripItemCollection[DetailedTripItem] != null))
                {
                    for(TripItemDetailCount=0; TripItemDetailCount<TripItemCollection[DetailedTripItem]["Keywords"].length; TripItemDetailCount++)
                    {
                        var DetailKeyword = TripItemCollection[DetailedTripItem]["Keywords"][TripItemDetailCount];
                        if((TagCloudLinks[DetailKeyword] == null) || (typeof(TagCloudLinks[DetailKeyword]) == "function"))
                            TagCloudLinks[DetailKeyword] = new Array();
                        
                        if (TagCloudLinks[DetailKeyword]["Categories"] == null)
                            TagCloudLinks[DetailKeyword]["Categories"] = "";

                        TagCloudLinks[DetailKeyword]["Categories"] +=  "ConstantMarker|";
                        
                        if(TagCloudLinks[DetailKeyword]["Count"] == null)
                            TagCloudLinks[DetailKeyword]["Count"] = 0;

                        TagCloudLinks[DetailKeyword]["Count"]++;
                        
                        if ( TagCloudLinks[DetailKeyword]["Count"] > MaxCountKeywords)
                            MaxCountKeywords = TagCloudLinks[DetailKeyword]["Count"];
                    }
                }
            }
            
            var MyTripId = UrlMyTripId;
            if(MyTripId != null && MyTripId!= "")
            {
                for (MyTripTripItemsCount=0; MyTripTripItemsCount<MyTripTripItems.length; MyTripTripItemsCount++)
                {
                    var tripItemId = MyTripTripItems[MyTripTripItemsCount];

                    for (tripItemIdKWCount=0;tripItemIdKWCount<MyTripCollection[tripItemId]["Keywords"].length;tripItemIdKWCount++)
                    {
                        var TripItemKeyword = MyTripCollection[tripItemId]["Keywords"][tripItemIdKWCount];
                        
                        if((TagCloudLinks[TripItemKeyword] == null) || (typeof(TagCloudLinks[TripItemKeyword]) == "function"))
                            TagCloudLinks[TripItemKeyword] = new Array();

                        if (TagCloudLinks[TripItemKeyword]["Categories"] == null)
                            TagCloudLinks[TripItemKeyword]["Categories"] = "";

                        TagCloudLinks[TripItemKeyword]["Categories"] +=  "ConstantMarker|";
                        
                        if(TagCloudLinks[TripItemKeyword]["Count"] == null)
                            TagCloudLinks[TripItemKeyword]["Count"] = 0;
                            
                        TagCloudLinks[TripItemKeyword]["Count"]++;
                        
                        if ( TagCloudLinks[TripItemKeyword]["Count"] > MaxCountKeywords)
                            MaxCountKeywords = TagCloudLinks[TripItemKeyword]["Count"];
                    }
                }
            }
            
            var TagCloudHtml = "";
            var keyword;
            for(var keywordHTMLCount=0; keywordHTMLCount<KeywordList.length; keywordHTMLCount++)
            {
                keyword = KeywordList[keywordHTMLCount];
                if ((TagCloudLinks[keyword] != null) && (typeof(TagCloudLinks[keyword]) != "function"))
                {
                    var Procent = (TagCloudLinks[keyword]["Count"] * 100) / MaxCountKeywords;
                    TagCloudHtml += GetTagCloudLink(keyword, Procent);
                }
            }

            if (TagCloudHtml.length >0)
            {
                $("#dvTagCloud").css("display", "block");
                document.getElementById("dvTagCloud").innerHTML = TagCloudHtml;
            }
            else
            {
                $("#dvTagCloud").css("display", "none");
            }
        }
    }
    
    //Returns a single link
    function GetTagCloudLink(keyword, percentage)
    {
        if(IsCategorySelected())
            return "<a id='lnk" + keyword + "' class=\"tagcloud_" + GetTagCloudCSSClass(percentage) + "\" href=\"javascript:SelectedKeyword('" + keyword + "');\" onmouseover=\"HighLightMarkers('" + keyword + "', TagCloudLinks['" + keyword + "']['Categories'], true);\"  onmouseout=\"HighLightMarkers('" + keyword + "', TagCloudLinks['" + keyword + "']['Categories'], false);\">" + keyword + "</a> ";
        else
            return "<a id='lnk" + keyword + "' class=\"tagcloud_" + GetTagCloudCSSClass(percentage) + "\" href=\"javascript:void(0);\" onmouseover=\"HighLightMarkers('" + keyword + "', TagCloudLinks['" + keyword + "']['Categories'], true);\"  onmouseout=\"HighLightMarkers('" + keyword + "', TagCloudLinks['" + keyword + "']['Categories'], false);\">" + keyword + "</a> ";
    }

    //Returns the size of a keyword in the tagcloud.
    function GetTagCloudCSSClass(percentage)
    {
        if (percentage >= 0 && percentage < 25)
            return "1";
        else if (percentage >= 25 && percentage < 50)
            return "2";
        else if (percentage >= 50 && percentage < 75)
            return "3";
        else if (percentage >= 75 && percentage <= 100)
            return "4";
        else
            return "3";
    }
    
    //When mouseover a keyword in the tagcloud, highlight the correct markers on the map.
    function HighLightMarkers(keyword, categories, setOver)
    {
        var arrCategories = categories.substr(0, categories.length - 1).split('|');
        for (i=0; i< arrCategories.length; i++)
            HighLightMarker(keyword, arrCategories[i], setOver);
    }
    
    function HighLightMarker(keyword, category, setOver)
    {
        if(category != "ConstantMarker")
        {
            if (SearchWebControl("chk" + category).checked)
            {
                var arrMarkers = Keywords[keyword][category];
                            
                var markerIndex;
                for(var markerCounter=0; markerCounter<arrMarkers.length; markerCounter++)
                {
                    markerIndex = arrMarkers[markerCounter];
                    var img = ((setOver) ? GetHighLightIcon(GMarkers[category][markerIndex].getIcon().image) :
                                                GMarkers[category][markerIndex].getIcon().image );
                    
                    GMarkers[category][markerIndex].setImage(img);
                }
            }
        }
    }
    
    //This function is called when a keyword is clicked in the tagcloud, it rebuilds the tagcloud.
    function SelectedKeyword(keyword)
    {
        HideAllMarkers();
        var DistinctKeywords = new Array();
        var MaxKeywordCount = 0;
        document.getElementById("dvTagCloud").innerHTML = "";
    
        //Reset keyword counters per keyword:
        for(KeywordListCount=0; KeywordListCount<KeywordList.length; KeywordListCount++)
        {
            var tempKeyword = KeywordList[KeywordListCount];
            if(TagCloudLinks[tempKeyword] != null && TagCloudLinks[tempKeyword]["Count"] != null)
                TagCloudLinks[tempKeyword]["Count"] = 0;
        }
                
        for (CategoryCount=0; CategoryCount<MarkerCategory.length; CategoryCount++)
        {
            if (SearchWebControl("chk" + MarkerCategory[CategoryCount]).checked)
            {
                var category = MarkerCategory[CategoryCount];
            
                var arrMarkers = Keywords[keyword][category];
                if (arrMarkers != null)
                {
                    for (markerIndex=0; markerIndex<arrMarkers.length; markerIndex++)
                    {
                        var MarkerKeywords = GMarkers[category][arrMarkers[markerIndex]]["KeyWordsForHighlight"];
                        for (markerKeywordCount=0; markerKeywordCount<MarkerKeywords.length; markerKeywordCount++)
                        {
                            var tempKeyword = MarkerKeywords[markerKeywordCount];
                            
                            if((TagCloudLinks[tempKeyword] == null) || (typeof(TagCloudLinks[tempKeyword]) == "function"))
                                TagCloudLinks[tempKeyword] = new Array();
                                
                            if(TagCloudLinks[tempKeyword]["Count"] == null)
                                TagCloudLinks[tempKeyword]["Count"] = 1;
                            else
                                TagCloudLinks[tempKeyword]["Count"]++;
                            
                            if (TagCloudLinks[tempKeyword]["Count"] > MaxKeywordCount)
                                MaxKeywordCount = TagCloudLinks[tempKeyword]["Count"];
                            
                            if(!Contains(DistinctKeywords, MarkerKeywords[markerKeywordCount]))
                                DistinctKeywords.push(MarkerKeywords[markerKeywordCount]);
                        }
                        var marker = GMarkers[category][arrMarkers[markerIndex]];
                        marker.show();
                        marker.setImage(marker.getIcon().image);
                    }
                }
            }
        }
        
        var DetailedTripItem = UrlTripItemId;
        if(DetailedTripItem != null && DetailedTripItem != "")
        {
            if((TripItemCollection[DetailedTripItem] != null))
            {
                for(TripItemDetailCount=0; TripItemDetailCount<TripItemCollection[DetailedTripItem]["Keywords"].length; TripItemDetailCount++)
                {
                    var DetailKeyword = TripItemCollection[DetailedTripItem]["Keywords"][TripItemDetailCount];
                    
                    if((TagCloudLinks[DetailKeyword] == null) || (typeof(TagCloudLinks[DetailKeyword]) == "function"))
                        TagCloudLinks[DetailKeyword] = new Array();

                    if(TagCloudLinks[DetailKeyword]["Count"] == null)
                        TagCloudLinks[DetailKeyword]["Count"] = 1;
                    else
                        TagCloudLinks[DetailKeyword]["Count"]++;
                        
                    if (TagCloudLinks[DetailKeyword]["Count"] > MaxKeywordCount)
                        MaxKeywordCount = TagCloudLinks[DetailKeyword]["Count"];
                    
                    if(!Contains(DistinctKeywords, DetailKeyword))
                        DistinctKeywords.push(DetailKeyword);
                }
            }
        }
        
        var MyTripId = UrlMyTripId;
        if(MyTripId != null && MyTripId!= "")
        {
            for (MyTripTripItemsCount=0; MyTripTripItemsCount<MyTripTripItems.length; MyTripTripItemsCount++)
            {
                var tripItemId = MyTripTripItems[MyTripTripItemsCount];

                for (tripItemIdKWCount=0;tripItemIdKWCount<MyTripCollection[tripItemId]["Keywords"].length;tripItemIdKWCount++)
                {
                    var TripItemKeyword = MyTripCollection[tripItemId]["Keywords"][tripItemIdKWCount];
                    
                    if((TagCloudLinks[TripItemKeyword] == null) || (typeof(TagCloudLinks[TripItemKeyword]) == "function"))
                        TagCloudLinks[TripItemKeyword] = new Array();
                        
                    if(TagCloudLinks[TripItemKeyword]["Count"] == null)
                        TagCloudLinks[TripItemKeyword]["Count"] = 1;
                    else
                        TagCloudLinks[TripItemKeyword]["Count"]++;
                        
                    if (TagCloudLinks[TripItemKeyword]["Count"] > MaxKeywordCount)
                        MaxKeywordCount = TagCloudLinks[TripItemKeyword]["Count"];
                        
                    if(!Contains(DistinctKeywords, TripItemKeyword))
                        DistinctKeywords.push(TripItemKeyword);
                }
            }
        }

        var TagCloudHtml = "";
        for (DistinctKeywordsCount=0; DistinctKeywordsCount<DistinctKeywords.length; DistinctKeywordsCount++)
        {
            var tempKeyword = DistinctKeywords[DistinctKeywordsCount];
            var Procent = (TagCloudLinks[tempKeyword]["Count"] * 100) / MaxKeywordCount;
            TagCloudHtml += GetTagCloudLink(tempKeyword,Procent);
        }
        TagCloudHtml += "<a href=\"javascript:LoadAllMarkers();\" class=\"tagcloud_2\" >ShowAll</a>";
        
        document.getElementById("dvTagCloud").innerHTML = TagCloudHtml;
    }
    
    //Get the Highlight icon of a marker. Hightlight icons always contain the suffix "_h".
    //Example: Resto.png --> Resto_h.png
    //         Hotel.png --> Hotel_h.png
    function GetHighLightIcon(img)
    {
        return img.substr(0, img.length - 4) + "_h" + img.substr(img.length - 4);
    }

    //This function is called when mouseover a marker on the map
    function GetHighLightKeywords(keywords, setOver)
    {
        var keywordBgColor = ((setOver) ? "#EFC944" : "" );

        for(var keywordcount=0; keywordcount<keywords.length; keywordcount++)
        {
            if (document.getElementById("lnk" + keywords[keywordcount]) != null)
                document.getElementById("lnk" + keywords[keywordcount]).style.color = keywordBgColor;
        }
    }
    
    //Checks if at least 1 category is chosen.
    function IsCategorySelected()
    {
        var retValue = false;
        for (MarkerCategoryCounter=0; MarkerCategoryCounter<MarkerCategory.length; MarkerCategoryCounter++)
        {
            var control = SearchWebControl("chk" + MarkerCategory[MarkerCategoryCounter]);
            if (control != null && control.checked)
            {
                retValue = true
                break;
            }
        }
        return retValue;
    }


    
    var SearchMarkers = new Array();
    function SearchAddress(searchaddress)
    {
        HidePreviousSearchMarker();
        var input = searchaddress;
        if ((searchaddress != null) && (searchaddress!= ""))
        {
            switch (GetDestination())
            {
                case "london": default:
                    searchaddress = "UK," + searchaddress + ",London";
                    break;
                case "paris":
                    searchaddress = "France," + searchaddress + ",Paris";
                    break;
            }
            showAddress(searchaddress, input);
        }
    }
    
    
    function showAddress(address, input) {
     var geocoder = new GClientGeocoder();
      geocoder.getLatLng(
        address,
        function(point) {
          if (!point) {
            alert(input + " not found");
          } else {
            map.setCenter(point, map.getZoom());
            var marker = new GMarker(point);
            SearchMarkers.push(marker);
            map.addOverlay(marker);
            marker.openInfoWindowHtml(input);
          }
        }
      );
    }
    
    function HidePreviousSearchMarker()
    {
        for(i=0; i<SearchMarkers.length; i++)
        {
            if(SearchMarkers[i] != null)
            {
                SearchMarkers[i].hide();
                SearchMarkers.pop();
            }
        }
    }
