﻿var currentZoom = 3;
var map;
var currentBounds = null;
var request = true;
var clusterIcon;
var clubImg, eventImg, spotImg, clusterImg, clubEventImg, spotEventImg;
var overlayCleared = false;
var firstLoad;
var safeMapBounds;
var displayMarkers;
var geo;
var locHasChanged;
var infoWindowsOpen;
var needUpdateMarkers;

var overlays = [];

// Global variable holding the one Info Window object
var infoWindow = new google.maps.InfoWindow();

$(document).ready(function () {

    if ($("#" + mapMode).length)
        InitMap();
    
    infoWindowsOpen = false;
    needUpdateMarkers = false;

    geo = new google.maps.Geocoder();

    if ($("#" + cbEvent).is(':checked')) {
        $(".viewEvents").STshow('fast');
    }
    else {
        $(".viewEvents").hide();
    }

    $("#" + cbEvent).click(function () {
        if ($("#" + cbEvent).is(':checked')) {
            $(".viewEvents").STshow('fast');
        }
        else {
            $(".viewEvents").hide();
        }
    });

    $('#' + tbZoomOn).blur(function () {
        if (this.value == '') {
            this.value = ResourceManager.GetString("search_FilterLocation");
        }
    });

    $('#' + tbZoomOn).focus(function () {

        if (this.value == ResourceManager.GetString("search_FilterLocation"))
            this.value = '';

        $('#' + ddlDistanceLimit).attr("disabled", false);
    });

    $("#" + refreshMap).click(function () {
        SetCenter(false);
        StartSearch(false);
        return false;
    });

    $('#' + ddlDistanceLimit).change(function () {
        locHasChanged = true;
    });

    $("#hideShowFilter").click(function () {
        if ($("#filterContent").is(':visible')) {
            $("#filterContent").hide();
            $("#hideShowFilter").html(ResourceManager.GetString("search_ShowFilter"));
        }
        else {
            $("#filterContent").STshow('fast');
            $("#hideShowFilter").html(ResourceManager.GetString("search_HideFilter"));
        }
        return false;
    });

    $("#" + showListMap).click(function () {
        setTimeout(function () {
            updateGridSport();
            $('#gridContent').jqmShow();
        }, 0);
        return false;


    });

    $('#linkWhatIsClub').tipTip({ defaultPosition: "right", fadeIn: 0, maxWidth: "450px" });
    $('#linkWhatIsSpot').tipTip({ defaultPosition: "right", fadeIn: 0, maxWidth: "450px" });
    $('#linkWhatIsEvent').tipTip({ defaultPosition: "right", fadeIn: 0, maxWidth: "450px" });

    if (($("#" + tbZoomOn).val() == '') ||
        ($("#" + tbZoomOn).val() == ResourceManager.GetString("search_FilterLocation"))) {
        locHasChanged = false;
    }
    else
        locHasChanged = true;

    $("#" + tbZoomOn).change(function () {
        locHasChanged = true;
    });

    $(".filterContent input").keypress(function (e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {

            StartSearch(false);
            return false;
        } else {
            return true;
        }
    });

    $('#gridContent').jqm({ modal: false });
    $('#errorAddress').jqm({ modal: false });
    $('#noMatch').jqm({ modal: false });

    if (document.getElementById("mapListSpot") != null) {
        StartSearch(true);
    }




});

function UpdateLatLongFromAddress() {

    if (!locHasChanged ||
        ($("#" + tbZoomOn).val() == '') ||
        ($("#" + tbZoomOn).val() == ResourceManager.GetString("search_FilterLocation"))) {
        $("#" + hfLatitude).val('');
        $("#" + hfLongitude).val('');
        __doPostBack('ctl00$STC$btnRefreshGrid', '');            
        return false;               
    }

    var addr = $("#" + tbZoomOn).val() + ", " + $("#" + hfSearchLoc).val();
    locHasChanged = false;

    geo.geocode({ address: addr }, function(result, status) {

        if (status == google.maps.GeocoderStatus.OK && result[0]) {
            var lat = result[0].geometry.location.lat();
            var lng = result[0].geometry.location.lng();
            $("#" + hfLatitude).val(lat);
            $("#" + hfLongitude).val(lng);
            __doPostBack('ctl00$STC$btnRefreshGrid', '');
            return false;
        }        
        else {
            $('#errorAddress').jqmShow();
            locHasChanged = true;
            return false;
            //__doPostBack('ctl00$STC$btnRefreshGrid', '');
        }
    });  

}

function InitMap() {

    var mapOptions = {
         zoom: 10,
         center: new google.maps.LatLng(0, 0),
         mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById("mapListSpot"), mapOptions);
    SetCenter(true);
    displayMarkers = false;
   
}

function SetCenter(doInit) {
   
    if ($("#" + rbAllCountries).is(':checked')) {
        map.setCenter(new google.maps.LatLng(20, 10));
        map.setZoom(2);
        if (doInit)
            InitAfterSetCenter();
        return;
    }
    else {
        
        if ((searchedZoom != null) && (searchedZoom != 0)) {
            currentZoom = searchedZoom;
            map.setCenter(new google.maps.LatLng(searchedCenterLat, searchedCenterLong));
            map.setZoom(currentZoom);
            if (doInit)
                InitAfterSetCenter();
            return;
        }
        currentZoom = 5;

        geo.geocode(searchedLocation, function(result, status) {

            if (status == google.maps.GeocoderStatus.OK && result[0]) {
                map.setCenter(result[0].geometry.location);
                map.setZoom(currentZoom);
                if (doInit)
                    InitAfterSetCenter();
            }
            else
            { 
                SetCenterCountry(doInit);
            }            
        });
        
    }
}

function InitAfterSetCenter() {


    google.maps.event.addListener(map, 'zoom_changed', function() {
        currentBounds = null;
        currentZoom = map.getZoom();        
    });

    google.maps.event.addListener(map, 'bounds_changed', function() {         
        updateMarkers();
    });

    google.maps.event.addListener(map, 'infowindowclose', function() {
        infoWindowsOpen = false;
        if (needUpdateMarkers)
            updateMarkers();
    });

    google.maps.event.addListener(map, 'infowindowopen', function() {
        infoWindowsOpen = true;
    });

    clusterIcon = "/images/gfx/icon/pointeur_cluster.png";
    clubImg = "/images/gfx/icon/pointeur_club.png";    
    eventImg = "/images/gfx/icon/pointeur_event.png";    
    spotImg = "/images/gfx/icon/pointeur_spot.png";    
    clubEventImg = "/images/gfx/icon/pointeur_club_event.png";    
    spotEventImg = "/images/gfx/icon/pointeur_spot_event.png";
    clubSpotImg = "/images/gfx/icon/pointeur_club.png";
    
    boundary = true;
    firstLoad = true;
    safeMapBounds = null;

}

function StartSearch(init) {
    displayMarkers = true;
    
    clearOverlays();
    overlays = [];
    safeMapBounds = null;
    currentBounds = null;
    firstLoad = true;
    
    var city = $("#" + tbZoomOn).val();

    if (city == ResourceManager.GetString("search_FilterLocation"))
        city = '';

    if (city == '') {
        $("#" + hfLatitude).val('');
        $("#" + hfLongitude).val('');
    }

    if ((searchedZoom != null) && (searchedZoom != 0) && (city == '')) {
        if ($("#" + rbAllCountries).is(':checked')) {
            map.setCenter(new google.maps.LatLng(20, 10));
            map.setZoom(2);
        }
        else {
            map.setCenter(new google.maps.LatLng(searchedCenterLat, searchedCenterLong));
            map.setZoom(searchedZoom);
        }
    }

    if (!locHasChanged || (city == '')) {
        if (!init)
            updateMarkers();
        return;
    }

    var addr = $("#" + tbZoomOn).val() + "," + $("#" + hfSearchLoc).val();
    locHasChanged = false;

    geo.geocode({ address: addr }, function(result, status) {

            if (status == google.maps.GeocoderStatus.OK && result[0]) 
            {            
                var lat = result[0].geometry.location.lat();
                var lng = result[0].geometry.location.lng();
                $("#" + hfLatitude).val(lat);
                $("#" + hfLongitude).val(lng);

                var zoom = 6;
                if ($('#' + ddlDistanceLimit).val() == '10')
                    zoom = 11;
                else if ($('#' + ddlDistanceLimit).val() == '50')
                    zoom = 9;
                else if ($('#' + ddlDistanceLimit).val() == '100')
                    zoom = 8;
                
                map.setCenter(new google.maps.LatLng(lat, lng));
                map.setZoom(zoom);
                updateMarkers();
                return false;
            }        
            else {
                $('#errorAddress').jqmShow();
                $("#" + hfLatitude).val('empty');
                $("#" + hfLongitude).val('empty');
                locHasChanged = true;
                return false;
            }
    });  
   
    
}

function SetCenterCountry(doInit) {
    
    currentZoom = 5;

    geo.geocode({ address: searchedLocation }, function(result, status) {
    
            if (status == google.maps.GeocoderStatus.OK && result[0]) {     
                  map.setCenter(result[0].geometry.location);
                  map.setZoom(currentZoom);
                  if (doInit)
                    InitAfterSetCenter();
            }
            else
            {
                 map.setCenter(new google.maps.LatLng(40, -30));
                 map.setZoom(2);
                  if (doInit)
                    InitAfterSetCenter();
            }  
          });

    
}

// return true if the marker was find or false if not
function checkMarker(latitude, longitude) {
    for (var i = 0; i < overlays.length; i++) {
        if ((overlays[i].position.lng() == longitude)
                && (overlays[i].position.lat() == latitude))
            return true;
    }

    return false;
}

function updateMarkers() {
    //GLog.write("updateMarkers");
    if (!displayMarkers)
        return;

    if (infoWindowsOpen) {
        needUpdateMarkers = true;
        return;
    }

    needUpdateMarkers = false;
    
    //create the boundry for the data to provide
    //initial filtering
    var mapBounds = map.getBounds();
    var southWest = mapBounds.getSouthWest();
    var northEast = mapBounds.getNorthEast();

    overlayCleared = false;
    
    
    // if we have a window without cluster then we can zoom and move in it without server call
    if (safeMapBounds != null) {
        if (safeMapBounds.contains(southWest) && safeMapBounds.contains(northEast))
            return;
    }
    else
        overlayCleared = true;

    

    // technique : we calculate a bit more than we need so the user can move on the site a bit without server call
    if (currentBounds != null) {
    
        if (currentBounds.contains(southWest) && currentBounds.contains(northEast))
            return;

        currentBounds = scaleBounds(mapBounds, 15);
        //remove the existing points
        overlayCleared = true;
        
//        //loop through each of the points in memory and remove those that
//        //aren't going to be shown  
//        for (var i = 0; i < map.overlays.length; i++) {
//            if (!mapBounds.contains(map.overlays[i].getPoint())) {
//                var marker = map.overlays[i];
//                map.removeOverlay(marker);
//            }
//        }
    }
    else {
        currentBounds = scaleBounds(mapBounds, 15);

        //remove the existing points
        overlayCleared = true;
    }
   

    var pastEvent = "";
    if ($("#" + cbPastEvent).is(':checked')) {
        pastEvent = $("#" + ddPastEvents).val();
    }
    var nextEvent = "";
    if ($("#" + cbNextEvent).is(':checked')) {
        nextEvent = $("#" + ddNextEvents).val();
    }

    var param = '{"neLat":"' + currentBounds.getNorthEast().lat() + 
                '","neLong":"' + currentBounds.getNorthEast().lng() +
                '","swLat":"' + currentBounds.getSouthWest().lat() +
                '","swLong":"' + currentBounds.getSouthWest().lng() +
                '","centerLat":"' + $("#" + hfLatitude).val() +
                '","centerLng":"' + $("#" + hfLongitude).val() +
                '","distanceLimit":"' + $('#' + ddlDistanceLimit).val() +                
                '","tribeURL":"' + tribeURL +
                '","searchClub":"' + $("#" + cbClub).is(':checked') +
                '","searchSpot":"' + $("#" + cbSpot).is(':checked') +
                '","searchEvent":"' + $("#" + cbEvent).is(':checked') +
                '","searchAllCountries":"' + $("#" + rbAllCountries).is(':checked') +
                '","zoomLevel":"' + currentZoom +
                '","filterName":"' + $("#" + tbName).val() +
                '","minDateEvents":"' + pastEvent +
                '","maxDateEvents":"' + nextEvent +               
                '","culture":"' + currentCulture +
                '"}';

    $("#loading").STshow();
    
    $.ajax({
        type: "POST",
        url: "/WebServices/SportTribeWebService.asmx/SiteSearch",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: param,
        //processData: false,
        error: function(xhr, message) { },//alert(xhr.responseText); ,
        success: function(json) { populateMap(json); }
    }); 
}

function populateMap(jsonText) {
    
    $("#loading").hide();
    //GLog.write("server call end");
    if (infoWindowsOpen) {
        needUpdateMarkers = true;
        return;
    }
    
    if (overlayCleared) {
        clearOverlays();
        $("#siteGridContainer").html("");
    }
       
    if (jsonText.d == "") {
        $('#noMatch').jqmShow();
        return;
    }  

    var jsonObj = eval('(' + jsonText.d + ')');
    
    var lat, lng, point, iconTxt, icon;

    var sites;
    var clusters;
    var clustersMaxLoc;

       
    if (jsonObj.searchResult.length == 1) //only sites
    {
        if (jsonObj.searchResult[0].sites) {
            sites = jsonObj.searchResult[0].sites;
        }
    }
    
    if (jsonObj.searchResult.length == 2) //only cluster and maxloc
    {  
        if (jsonObj.searchResult[0].clusters) {
            clusters = jsonObj.searchResult[0].clusters;
            clustersMaxLoc = jsonObj.searchResult[1].clustersMaxLoc;
        }
    }
    
    if (jsonObj.searchResult.length == 3) //both
    {
        sites = jsonObj.searchResult[0].sites;
        clusters =  jsonObj.searchResult[1].clusters;
        clustersMaxLoc = jsonObj.searchResult[2].clustersMaxLoc;
    }

    if (firstLoad) 
    {
       var hasSite=false;
       if ((sites) && (sites.length >= 1))
       {
            hasSite = true;
       }      
      
       if ( (clusters) && (clusters.length >= 1)) 
       {
            hasSite = true;
        }

        if (!hasSite) {
            $('#noMatch').jqmShow();
            firstLoad = false;
            return;
        }     
        
    }
    
    firstLoad = false;

    if (sites) {
        for (var i = 0; i < sites.length; i++) {
            // obtain the attribues of each marker

            var site = sites[i];

            lat = parseFloat(site.latStr);
            lng = parseFloat(site.lngStr);

            //check if the point already exist in the map
            if (!overlayCleared) {
                if (checkMarker(lat, lng))
                    continue;
            }

            point = new google.maps.LatLng(lat, lng);
            iconTxt = site.icon;

            switch (iconTxt) {
                case "club":
                    icon = clubImg;
                    break;
                case "spot":
                    icon = spotImg;
                    break;
                case "event":
                    icon = eventImg;
                    break;
                default:
                    icon = spotImg;
            }

            if ((iconTxt.indexOf("club") != -1) && (iconTxt.indexOf("event") != -1))
                icon = clubEventImg;

            if ((iconTxt.indexOf("spot") != -1) && (iconTxt.indexOf("event") != -1))
                icon = spotEventImg;

            if ((iconTxt.indexOf("club") != -1) && (iconTxt.indexOf("spot") != -1))
                icon = clubSpotImg;

            if ((iconTxt.indexOf("club") != -1) && (iconTxt.indexOf("spot") != -1) && (iconTxt.indexOf("event") != -1))
                icon = clubSpotEventImg;

            // create the marker
            var completeHtml;

            if (site.SingleSite) {
                completeHtml = "<div>";
                completeHtml += CreateInfoWindow(site, site.locationID);
                completeHtml += "</div>";
                createMarker(point, completeHtml, icon);                
            }
            else {
                var tabInfoWindowHtml;
                var listTab = new Array();

                for (var j = 0; j < site.sameLocSite.length; j++) {
                    var sameLocSite = site.sameLocSite[j];
                    tabInfoWindowHtml = "<div class=\"normalTab\">";
                    tabInfoWindowHtml += CreateInfoWindow(sameLocSite, site.locationID);
                    tabInfoWindowHtml += "</div>";

                    var title;
                    if (sameLocSite.TypeStr == "event")
                        title = ResourceManager.GetString("siteDetails_Event");
                    else if (sameLocSite.TypeStr == "spot")
                        title = ResourceManager.GetString("siteDetails_Spot");
                    else
                        title = ResourceManager.GetString("siteDetails_Club");
                    tab = new Object;
                    tab.Title = title;
                    tab.Html = tabInfoWindowHtml;
                    listTab[j] = tab;
                }

                var currentPos = site.sameLocSite.length;

                if (site.events) {
                    tabInfoWindowHtml = "<div class=\"listTab\">";
                    tabInfoWindowHtml += ResourceManager.GetString("search_InfoWindow_multiEvent", site.events.length);
                    tabInfoWindowHtml += "<br/>";
                    tabInfoWindowHtml += "<a href=\"#\" onclick=\"$('#eventGrid"+ site.locationID +"').jqmShow();return false;\"> " + ResourceManager.GetString("search_InfoWindow_multiSiteDetail") + "</a>";
                    tabInfoWindowHtml += "</div>";

                    var eventGrid = "<div id=\"eventGrid" + site.locationID + "\" class=\"siteGrid jqmWindow\" style=\"width:350px;\">";
                    eventGrid += "<div style=\"float:right\">";
                        eventGrid += "<a class=\"jqmClose\" href=\"#\">";
                        eventGrid += "<img src=\"/images/gfx/button/pop_close.gif\" alt=\"close\" style=\"border:0\"/>";
                        eventGrid += "</a>";
                        eventGrid += "</div><div class=\"siteGridContent\">";
                        for (var e = 0; e < site.events.length; e++) {
                            eventGrid += "<div class=\"sameLocGridContent\"><div>";
                            eventGrid += CreateInfoWindow(site.events[e], site.locationID);
                            eventGrid += "</div></div>";
                            eventGrid += "<hr>";                     
                    }
                    eventGrid += "</div></div>";

                    $("#siteGridContainer").append(eventGrid);

                    tab = new Object;
                    tab.Title = ResourceManager.GetString("siteDetails_Event");
                    tab.Html = tabInfoWindowHtml;
                    listTab[currentPos] = tab;
                    currentPos++;                    
                }

                if (site.clubs) {

                    tabInfoWindowHtml = "<div class=\"listTab\">";
                    tabInfoWindowHtml += ResourceManager.GetString("search_InfoWindow_multiClub", site.clubs.length);
                    tabInfoWindowHtml += "<br/>";
                    tabInfoWindowHtml += "<a href=\"#\" onclick=\"$('#clubGrid" + site.locationID + "').jqmShow();return false;\"> " + ResourceManager.GetString("search_InfoWindow_multiSiteDetail") + "</a>";
                    tabInfoWindowHtml += "</div>";

                    var clubGrid = "<div id=\"clubGrid" + site.locationID + "\" class=\"siteGrid jqmWindow\" style=\"width:350px;\">";
                    clubGrid += "<div style=\"float:right\">";
                    clubGrid += "<a class=\"jqmClose\" href=\"#\">";
                    clubGrid += "<img src=\"/images/gfx/button/pop_close.gif\" alt=\"close\" style=\"border:0\"/>";
                    clubGrid += "</a>";
                    clubGrid += "</div><div class=\"siteGridContent\">";
                    for (var c = 0; c < site.clubs.length; c++) {
                        clubGrid += "<div class=\"sameLocGridContent\"><div>";
                        clubGrid += CreateInfoWindow(site.clubs[c], site.locationID);
                        clubGrid += "</div></div>";
                        clubGrid += "<hr>";
                    }
                    clubGrid += "</div></div>";

                    $("#siteGridContainer").append(clubGrid);
                    tab = new Object;
                    tab.Title = ResourceManager.GetString("siteDetails_Club");
                    tab.Html = tabInfoWindowHtml;
                    listTab[currentPos] = tab;                    
                }

                // create the marker
                
                createTabMarker(point, listTab, icon);                
            }
        } // for each site
    } //if

    if (clusters) {

        for (var i = 0; i < clusters.length; i++) {
            // obtain the attribues of each marker

            var cluster = clusters[i];

            lat = parseFloat(cluster.latStr);
            lng = parseFloat(cluster.lngStr);

            //check if the point already exist in the map
            if (!overlayCleared) {
                if (checkMarker(lat, lng))
                    continue;
            }

            point = new google.maps.LatLng(lat, lng);
            var completeHtml;
            completeHtml = "<div>";
            completeHtml += "<div class=\"cluster\">";
            completeHtml += ResourceManager.GetString("search_InfoWindow_ClusterTitle", cluster.NbLoc)
            completeHtml += "<br/>";
            completeHtml += "<a href=\"#\" onclick=\"ZoomOnCluster(" + lat + "," + lng + ");\">" + ResourceManager.GetString("search_InfoWindow_ClusterZoomDetail") + " </a>";
            completeHtml += "<div/>";
            completeHtml += "</div>";
            AddClusterMarker(point, completeHtml, cluster.NbLoc);          
            
        }

        safeMapBounds = null;        
    }
    else {
        safeMapBounds = map.getBounds();
    }
    
    $('.siteGrid').jqm({ modal: false });
    
    //GLog.write("server call end");

}

function ZoomOnCluster(lat, lng) {

    infoWindow.close();
	infoWindowsOpen=false;
	map.setCenter(new google.maps.LatLng(lat, lng));
	map.setZoom(currentZoom + 1);
	
}

function CreateInfoWindow(site,locationID) {
    var infoWindowHtml;
    
    infoWindowHtml = "<div class=\"infoWindow";

    if (site.TypeStr == "event")
        infoWindowHtml += " isEvent\">";
    else if (site.TypeStr == "spot")
        infoWindowHtml += " isSpot\">";
    else
        infoWindowHtml += " isClub\">";

    infoWindowHtml += "<div class=\"info\">";
    infoWindowHtml += "<span class=\"infoTitle\">" + ResourceManager.GetString("search_InfoWindow_Name") + "</span>";
    infoWindowHtml += "<span class=\"infoContent\"><span class=\"nameSite\">" + site.Name + "</span>";
    infoWindowHtml += "<a class=\"moreInfo linkDetail\" href=\"" + site.SiteURL + "\">" + ResourceManager.GetString("search_InfoWindow_ViewDetails") + "</a>";
    infoWindowHtml += "</span>";
    infoWindowHtml += "</div>";

    infoWindowHtml += "<div class=\"info\">";
    infoWindowHtml += "<span class=\"infoTitle\">" + ResourceManager.GetString("search_InfoWindow_Sport") + "</span>";
    infoWindowHtml += "<span class=\"infoContent listSport\">" + site.ListSportStr + "</span>";
    infoWindowHtml += "</div>";

    if (site.TypeStr == "event") {
        infoWindowHtml += "<div class=\"info\">";
        infoWindowHtml += "<span class=\"infoTitle\">" + ResourceManager.GetString("search_InfoWindow_NextOccurence") + "</span>";
        infoWindowHtml += "<span class=\"dateEvent\">" + site.EventDate + "</span>";
        infoWindowHtml += "<div class=\"clear\"></div>";
        infoWindowHtml += "<span class=\"infoTitle\">" + ResourceManager.GetString("search_InfoWindow_Repeat") + "</span>";
        infoWindowHtml += "<span class=\"dateEvent\">" + site.Repeat + "</span>";
        infoWindowHtml += "</div>";
    }

    infoWindowHtml += "<div class=\"info\">";
        infoWindowHtml += "<span class=\"infoTitle\">" + ResourceManager.GetString("search_InfoWindow_Address") + "</span>";
        infoWindowHtml += "<span class=\"infoContent addressSite\">" + site.Address +"</span>";
    infoWindowHtml += "</div>";

    infoWindowHtml += "<div class=\"description\">" + site.Teaser + "</div>";

    if (site.TypeStr == "club") {
        infoWindowHtml += "<a class=\"addSameLocation\" href=\"Add?organizerID=" + site.SiteID + "\">" + ResourceManager.GetString("search_InfoWindow_AddEventClub") + "</a>";
    }
    

    infoWindowHtml += "</div>";
    
    return infoWindowHtml;

}


function createTabMarker(point, tabs_array, icon) {

    // create the html tabbed

    // create the UL section
    var htmlTabs = "<ul class=\"tabs\">";

    htmlTabs += "<li class=\"active\"><a href=\"#tab0\">" + tabs_array[0].Title + "</a></li>";
    for (var i = 1; i < tabs_array.length; i++) {        
        htmlTabs += "<li class=\"\"><a href=\"#tab" + i + "\">" + tabs_array[i].Title + "</a></li>";
    }
    htmlTabs += "</ul>";
    htmlTabs += "<div class=\"clear\"></div>";
    // create the div section
    htmlTabs += "<div class=\"tabContainer\">";
    htmlTabs += "<div class=\"tab_content\" id=\"tab0\" style=\"display: block;\">";
    htmlTabs += tabs_array[0].Html + "</div>";

    for (var i = 1; i < tabs_array.length; i++) {
        htmlTabs += "<div class=\"tab_content\" id=\"tab" + i + "\" style=\"display: none;\">";
        htmlTabs += tabs_array[i].Html + "</div>";
    }

    htmlTabs += "</div>";


    var marker = addMarker(map, point, icon);
    marker.isTab = true;
    marker.Tabs = tabs_array;

    google.maps.event.addListener(marker, "click", function () {

        openInfoWindow(map, point, htmlTabs);
        infoWindowsOpen = true;

        google.maps.event.addListener(infoWindow, 'domready', function () {
                   
            // tab related http://www.sohtanaka.com/web-design/examples/tabs/
            //Default Action
            $(".tab_content").hide(); //Hide all content
            $("ul.tabs li:first").addClass("active").show(); //Activate first tab
            $(".tab_content:first").STshow(); //Show first tab content

            //On Click Event
            $("ul.tabs li").click(function () {
                $("ul.tabs li").removeClass("active"); //Remove any "active" class
                $(this).addClass("active"); //Add "active" class to selected tab
                $(".tab_content").hide(); //Hide all tab content
                var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
                $(activeTab).fadeIn(); //Fade in the active content
                return false;
            });
        });

    });
    
}

function createMarker(point, html, icon) {
    
    var marker = addMarker(map,point,icon);
    marker.htmlStr = html;

    google.maps.event.addListener(marker, "click", function() {
        
        openInfoWindow(map,point,html);
        infoWindowsOpen = true;
        
    });
    
}


function AddClusterMarker(point, html, nbSite) {
    
    var marker = new MarkerWithLabel({
       position: point,
       map: map,
       draggable: false,
       labelContent: nbSite,
       labelAnchor: new google.maps.Point(8, 21),
       labelClass: "labels", // the CSS class for the label
       labelInBackground: false,
       icon: clusterIcon
     });
    overlays.push(marker);
    
    google.maps.event.addListener(marker, "click", function() {
        
        openInfoWindow(map,point,html);
        infoWindowsOpen = true;
        
    });
    
}

// Scales a bounds object
function scaleBounds(tmpBounds, scale) {
    var tmpCoords = boundsToCoords(tmpBounds);
    var heightSquale;
    var widthSquale;

    heightSquale = (tmpCoords.north - tmpCoords.south) * (scale / 100);
    if (tmpCoords.east > tmpCoords.west)
        widthSquale = (tmpCoords.east - tmpCoords.west) * (scale / 100);
    else // we are at the pacific meridiant
        widthSquale = ((180 - tmpCoords.west) + (180 + tmpCoords.east)) * (scale / 100);

    tmpCoords.north = tmpCoords.north + heightSquale;
    tmpCoords.south = tmpCoords.south - heightSquale;
    tmpCoords.east = tmpCoords.east + widthSquale;
    tmpCoords.west = tmpCoords.west - widthSquale;

    if (tmpCoords.north > 85) {
        tmpCoords.north = 85
    }
    if (tmpCoords.south < -85) {
        tmpCoords.south = -85
    }

    if (tmpCoords.east > 180) {
        tmpCoords.east = -180 + (tmpCoords.east - 180)
    }

    if (tmpCoords.west < -180) {
        tmpCoords.west = 180 + (tmpCoords.west + 180)
    }


    var newBounds = new google.maps.LatLngBounds(new google.maps.LatLng(tmpCoords.south, tmpCoords.west),
                                          new google.maps.LatLng(tmpCoords.north, tmpCoords.east));

    return (newBounds);
}

// converts a bounds to coordinates, sort of V1 minx, maxx... style
function boundsToCoords(tmpBounds) {
    var north = tmpBounds.getNorthEast().lat();
    var east = tmpBounds.getNorthEast().lng();
    var south = tmpBounds.getSouthWest().lat();
    var west = tmpBounds.getSouthWest().lng();

    return { north: north, east: east, west: west, south: south };

}

function parseBool(strBool) {
    if (strBool == "true")
        return true;
    return false;
}

function addMarker(theMap, latLng,image) {
    
    var marker = new google.maps.Marker({
        position: latLng,
        map: theMap,
        icon: image
    });
    // Add Marker to Overlays collection
    overlays.push(marker);
    return marker;
}

function clearOverlays() {
    for (var n = 0, overlay; overlay = overlays[n]; n++) {
        overlay.setMap(null);
    }
    // Clear overlays from collection
    overlays = [];
}

function openInfoWindow(map, latLng, content) {
    
    infoWindow.setPosition(latLng);
    infoWindow.setContent(content);
    infoWindow.open(map);
}


function updateGridSport() {
    var mapBounds = map.getBounds();

    $("#gridSport").html("");

    buildGridHeader();

    for (var i = 0; i < overlays.length; i++) {        
            if (mapBounds.contains(overlays[i].position)) {
                addMarkerToGridSport(overlays[i]);
            }
    }
    
   

    // add special list
    $("#siteGridContainer").find(".sameLocGridContent").each(function (index) {
        //alert($(this).html());
        addGridSportLine($(this).html());
    });

    $("#gridSport tbody tr:odd").addClass('odd');
}

function buildGridHeader() {

    var header;

    if ($("#" + cbEvent).is(':checked')) {
        header = "<tr><th>" + ResourceManager.GetString("search_GridResultName") + "</th> <th>" + ResourceManager.GetString("search_GridResultAddress") + "</th><th>" + ResourceManager.GetString("search_GridResultEventNextOcc") + "</th><th>" + ResourceManager.GetString("search_GridResultSport") + "</th></tr>";
    }
    else {
        header = "<tr><th>" + ResourceManager.GetString("search_GridResultName") + "</th> <th>" + ResourceManager.GetString("search_GridResultAddress") + "</th><th>" + ResourceManager.GetString("search_GridResultSport") + "</th></tr>";
    }

    $("#gridSport").append(header);
}

function addMarkerToGridSport(marker) {
    // tab marker
    if (marker.isTab) {
        for (i = 0; i < marker.Tabs.length; i++) {
            if (marker.Tabs[i].Html.indexOf("normalTab") != -1)
                addGridSportLine(marker.Tabs[i].Html);
        }
    }
    else {
        // create the marker
        addGridSportLine(marker.htmlStr);
    }


}

function addGridSportLine(line) {

    if (line == null)
        return;

    if ($(".cluster", line).length > 0)
        return;

    var row = "<tr> <td class='tdName'>" +
                        "<div>";
    if ($(".isEvent", line).length > 0)
        row = row + "<img src='/images/gfx/icon/pointeur_event.png' alt='event'/>";
    else if ($(".isClub", line).length > 0)
        row = row + "<img src='/images/gfx/icon/pointeur_club.png' alt='club'/>";
    else if ($(".isSpot", line).length > 0)
        row = row + "<img src='/images/gfx/icon/pointeur_spot.png' alt='spot'/>";

    row = row + "<a href='" +
                            $(".linkDetail", line).attr('href') + "'>" +
                                $(".nameSite", line).html() +
                        "</a></div>" +
                         "<div>" +
                            $(".description", line).html() +
                        "</div>" +
                    "</td>" +
                "<td class='tdAddress'>" + $(".addressSite", line).html() + "</td>";

    if ($("#" + cbEvent).is(':checked')) {
        if ($(".dateEvent", line).html() == null)
            row = row + "<td class='tdDate'></td>";
        else
            row = row + "<td class='tdDate'>" + $(".dateEvent", line).html() + "</td>";
    }

    row = row + "<td class='tdSport'>" + $(".listSport", line).html() + "</td></tr>";

    $("#gridSport").append(row);

}