function createHtmlForInfoTabbed(title, placename, address, city, url, img, strdate, isdetail) {
    var html = "";


    if (img != 'empty') {
        img = "<div class='infocontentimg''><img class='imgcarte' hspace='0' align='left' vspace='0' src='" + img + "'/></div>";
        html += img;
        html += "<div class='infocontenttext'>";
        html += "<a class='infoevenement' href='" + url + "'"
        if (isdetail)
            html += "target='_parent'";
        html += ">" + title + "</a>";
        //if(placename!='empty')
        //html += "<br/>" + placename;
        //html += "<br/>" + address;
        html += "<br/>" + city;
        html += "<br />" + strdate;
        html += "</div>";
    }
    else {
        html += "<br/><a class='infoevenement' href='" + url + "'>" + title + "</a>";
    }

    return AddToDiv(html);
}

function AddToDiv(html) {
    return html;
    html = "<div class='infocontentwrapper'>" + html + "</div>";

}


function showMarkers(markers) {
    //$(".loading").fadeIn("normal");
    for (var i = 0; i < markers.length; i++) {
        map.addOverlay(markers[i]);
    }
    //$(".loading").fadeOut("normal");
}

function ShowMarkerInitial() {
    var latX = "48.853795";
    var lngY = "2.3369433";
    //if there is no marker initial, show the map and center at France
    if (currentmarkers.length < 1) {
        map.setCenter(new GLatLng(latX, lngY), 8);
    }
    else {
        map.setCenter(new GLatLng(latX, lngY), 8);
        showMarkers(currentmarkers);
    }
}

var directions;
function GetDirection(from, to) {
    var panel = document.getElementById("path")
    directions = new GDirections(map, null);
    // ==== Set up the route and avoid highways options ====
    var opts = {};
    opts.getPolyline = true;
    opts.getSteps = true;
    //opts.travelMode = "G_TRAVEL_MODE_WALKING";

    //directions.load("from: " + from + " to: " + to, opts);
    directions.loadFromWaypoints([from, to],opts); 

    //show polyline
    GEvent.addListener(directions, 'load', function() {
        if (currentpolyline)
            map.removeOverlay(currentpolyline);
        currentpolyline = directions.getPolyline();
        map.addOverlay(currentpolyline);

        showRoutes(directions);
    });
}


function showRoutes(directions) {
    //show route
    var numRoutes = directions.getNumRoutes();
    var html = "";
    var ss = 0;
    for (var r = 0; r < numRoutes; r++) {
        var route = directions.getRoute(r);
        var startGeoCode = directions.getGeocode(r); //route.getStartGeocode();
        var endGeoCode = directions.getGeocode(r + 1); //route.getEndGeocode();
        var endLatLng = route.getEndLatLng();
        var routeSummaryHTML = route.getSummaryHtml();
        var routeDistance = route.getDistance();
        var routeDuration = route.getDuration();

        var numSteps = route.getNumSteps();
        html += '<table cellspacing="0" cellpadding="0" id="routeTable_' + r + '">';
        for (var s = 0; s < numSteps; s++) {
            var step = route.getStep(s);
            var stepLatLng = step.getLatLng();
            bounds.extend(stepLatLng);

            var stepPolylineIndex = step.getPolylineIndex();
            var stepDescriptionHTML = step.getDescriptionHtml();
            var stepDistance = step.getDistance();
            var stepDuration = step.getDuration();
            html += '<tr class="stepRow">';
            html += "<td class='stepId'>" + (s + 1) + ".</td>";
            html += "<td class='stepHtml'>" + stepDescriptionHTML + "<br/>" + stepDistance.html + "</td>";
            html += "<td class='nearby'>A proximite    </td>";
            html += "</tr>";
            ss = s;
        }
        html += '</table>';
    }

    $('#path').html(html);

    //show
    showStep(0,ss);
}

//funtion to show the map from an address given
function showAddress(address, html) {
    //client geocoder to get coordinates
    var geo = new GClientGeocoder();
    //execute and set the funtion callback
    geo.getLocations(address, function(result) {
        // If that was successful
        if (result.Status.code == G_GEO_SUCCESS) {
            //loop through the results, placing markers
            for (var i = 0; i < result.Placemark.length; i++) {
                var p = result.Placemark[i].Point.coordinates;

                var marker = createMarkerByPoint(new GLatLng(p[1], p[0]), address, html, "#");
                map.addOverlay(marker);
            }
            // centre the map on the first result
            var p = result.Placemark[0].Point.coordinates;
            map.setCenter(new GLatLng(p[1], p[0]), 14);
        }
        //error occur, decode the error status
        else {
            var reason = "Code " + result.Status.code;
            if (reasons[result.Status.code]) {
                reason = reasons[result.Status.code]
            }
            alert('Could not find "' + address + '" ' + reason);
            //document.getElementById("googlediv").style.display="none";
        }
    }
    );
}

//global variables
//Array for decoding the failure codes
var reasons = [];
var map;
var bounds;
//Array for direction forms
var to_htmls = [];
var from_htmls = [];
var htmls = [];
var markerCount = 0;
var gmarkers = [];
var cached = [];

//array of current marker
var currentmarkers = new Array();

//array of icons
var gicons = [];

//directions
var currentpolyline;
var currentmarker;
var destination;


//create a custom icon for google marker
function createIcon(imageurl, width, height, scale) {
    var icon = new GIcon(G_DEFAULT_ICON);
    icon.image = imageurl;
    width = width * scale / 10;
    height = height * scale / 10;
    icon.iconSize = new GSize(width, height);
    icon.shadowSize = new GSize(0, 0);
    icon.iconAnchor = new GPoint(width / 2, height);
    return icon;
}


//initialize the variables
function setReasons() {
    reasons[G_GEO_SUCCESS] = "Success";
    reasons[G_GEO_MISSING_ADDRESS] = "Missing Address: The address was either missing or had no value.";
    reasons[G_GEO_UNKNOWN_ADDRESS] = "Unknown Address: No corresponding geographic location could be found for the specified address.";
    reasons[G_GEO_UNAVAILABLE_ADDRESS] = "Unavailable Address: The geocode for the given address cannot be returned due to legal or contractual reasons.";
    reasons[G_GEO_BAD_KEY] = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
    reasons[G_GEO_TOO_MANY_QUERIES] = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
    reasons[G_GEO_SERVER_ERROR] = "Server error: The geocoding request could not be successfully processed.";
}

//initialize the map
function loadGoogleMap() {
    if (GBrowserIsCompatible()) {

        gicons["2"] = createIcon("/images/gicon/concert.png", 23, 27, 10);
        gicons["22"] = createIcon("/images/gicon/foireetsalon.png", 23, 27, 10);
        gicons["3"] = createIcon("/images/gicon/exposition.png", 23, 27, 10);
        gicons["4"] = createIcon("/images/gicon/festival.png", 23, 27, 10);
        gicons["11"] = createIcon("/images/gicon/spectacle.png", 23, 27, 10);
        gicons["12"] = createIcon("/images/gicon/sport.png", 23, 27, 10);
        gicons["1"] = createIcon("/images/gicon/bar.png", 23, 27, 10);
        gicons["5"] = createIcon("/images/gicon/accor.png", 23, 27, 10);

        //hotel by group
        //gicons["5-11"] = createIcon("/images/gicon/accor.png", 23, 27, 10);
        gicons["5-476"] = createIcon("/images/gicon/adagio.png", 23, 27, 10);
        gicons["5-477"] = createIcon("/images/gicon/allseason.png", 23, 27, 10);
        gicons["5-478"] = createIcon("/images/gicon/barriere.png", 23, 27, 10);
        //gicons["5-"] = createIcon("/images/gicon/clubmed.png", 23, 27, 10);
        gicons["5-90"] = createIcon("/images/gicon/etaphotels.png", 23, 27, 10);
        gicons["5-156"] = createIcon("/images/gicon/formule1.png", 23, 27, 10);
        //gicons["5-156"] = createIcon("/images/gicon/hotelsf1.png", 23, 27, 10);
        gicons["5-245"] = createIcon("/images/gicon/ibis.png", 23, 27, 10);
        gicons["5-305"] = createIcon("/images/gicon/mercure.png", 23, 27, 10);
        gicons["5-479"] = createIcon("/images/gicon/mgallery.png", 23, 27, 10);
        //gicons["5-"] = createIcon("/images/gicon/motel6.png", 23, 27, 10);
        gicons["5-323"] = createIcon("/images/gicon/novotel.png", 23, 27, 10);
        gicons["5-481"] = createIcon("/images/gicon/pullman.png", 23, 27, 10);
        gicons["5-406"] = createIcon("/images/gicon/sofitel.png", 23, 27, 10);
        //gicons["5-"] = createIcon("/images/gicon/studio6.png", 23, 27, 10);
        gicons["5-483"] = createIcon("/images/gicon/suitehotels.png", 23, 27, 10);
        //gicons["5-"] = createIcon("/images/gicon/villagehotels.png", 23, 27, 10);
        gicons["5-486"] = createIcon("/images/gicon/suitenovotel.png", 23, 27, 10);
        gicons["5-487"] = createIcon("/images/gicon/hotelf1.png", 23, 27, 10);
        
        
        
        gicons["9"] = createIcon("/images/gicon/restaurant.png", 23, 27, 10);
        gicons["10"] = createIcon("/images/gicon/shopping.png", 23, 27, 10);
        gicons["6"] = createIcon("/images/gicon/patrimoine.png", 23, 27, 10);


        //make the map NO transparence
        //  Make the map types semi transparent 
        //G_NORMAL_MAP.getTileLayers()[0].getOpacity = function() { return 1; };
        //G_SATELLITE_MAP.getTileLayers()[0].getOpacity = function() { return 1; };
        //G_HYBRID_MAP.getTileLayers()[0].getOpacity = function() { return 1; };
        //G_HYBRID_MAP.getTileLayers()[1].getOpacity = function() { return 1; };

        var i = 0;
        bounds = new GLatLngBounds();

        //create a map
        map = new GMap2(document.getElementById("map"));
        //map.enableScrollWheelZoom();
        map.setMapType(G_PHYSICAL_MAP);
        map.setUIToDefault();
        map.disableScrollWheelZoom();

        //show the marker initials
        ShowMarkerInitial();
    }
    // display a warning if the browser was not compatible
    else {
        //alert("Sorry, the Google Maps API is not compatible with this browser");
    }
}

function centerAt(latX, lngY, zoom) {
    map.setCenter(new GLatLng(latX, lngY), zoom);
}

function centerAtCity() {
    var latX = '48.853264';
    var lngY = '2.348033';
    //center at Paris
    centerAt(latX, lngY, 12);
}


function centerAndZoomOnBounds(bounds, zoom) {
    map.setCenter(center, zoom);
}


//Show all the locations at the appropriate zoom level
function centerAndZoomOnBounds(bounds) {
    var center = bounds.getCenter();
    var newZoom = map.getBoundsZoomLevel(bounds);
    if (newZoom > 16)
        newZoom = 14;

    if (map.getZoom() != newZoom) {
        map.setCenter(center, newZoom);
    } else {
        map.panTo(center);
    }
}

function resizeGMapTo(newwidth, newheight) {
    $("#map").hide().width(newwidth).height(newheight).fadeIn("slow", function() {
        map.checkResize(); centerAndZoomOnBounds(bounds);
    });
}

//Update map and show makers with an ajax call to url
function updateMap(url, typemarker, clearMap) {
    var request = GXmlHttp.create();
    request.open("GET", url, true);
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (clearMap) {
                clearMarkers();
            }
            //var xmlDoc = GXml.parse(request.responseText);
            createMarkers(request.responseText, typemarker);
            
            centerAndZoomOnBounds(bounds);

        }
    }
    request.send(null);
}


function clearMarkers() {
    for (var i = 0; i < gmarkers.length; i++) {
        map.removeOverlay(gmarkers[i]);
    }
    bounds = new GLatLngBounds();
    //map.clearOverlays();
    gmarkers = [];
}

//Function to create markers from xml data
function createMarkers(xml, typemarker) {
    var xmlDoc = GXml.parse(xml);
    var markers = xmlDoc.documentElement.getElementsByTagName("marker");

    for (var i = 0; i < markers.length; i++) {
        //get attributs from xml data
        var lat = parseFloat(markers[i].getAttribute("lat"));
        var lng = parseFloat(markers[i].getAttribute("lng"));
        var title = markers[i].getAttribute("name");

        var placename = markers[i].getAttribute("placename");
        var address = markers[i].getAttribute("address");
        var city = markers[i].getAttribute("city");
        var url = markers[i].getAttribute("url");
        var img = markers[i].getAttribute("image");
        var strdate = markers[i].getAttribute("strdate");

        //create point and html
        var point = new GLatLng(lat, lng);
        var html = createHtmlForInfoTabbed(title, placename, address, city, url, img, strdate);
        //create marker and setup some attributs
        var marker = createMarker(point, html, markers[i].getAttribute('category'));
        marker.id = markers[i].getAttribute('id');
        marker.name = markers[i].getAttribute('name');
        marker.category = markers[i].getAttribute('category');
        marker.typemarker = typemarker;
        gmarkers.push(marker);
        map.addOverlay(marker);

    }
    
    
}

function createMarkerDetail(xml, typemarker) {
    var xmlDoc = GXml.parse(xml);
    var markers = xmlDoc.documentElement.getElementsByTagName("marker");
    for (var i = 0; i < markers.length; i++) {
        //get attributs from xml data
        var lat = parseFloat(markers[i].getAttribute("lat"));
        var lng = parseFloat(markers[i].getAttribute("lng"));
        var title = markers[i].getAttribute("name");

        var placename = markers[i].getAttribute("placename");
        var address = markers[i].getAttribute("address");
        var city = markers[i].getAttribute("city");
        var url = markers[i].getAttribute("url");
        var img = markers[i].getAttribute("image");
        var strdate = markers[i].getAttribute("strdate");

        //create point and html
        var point = new GLatLng(lat, lng);
        var html = createHtmlForInfoTabbed(title, placename, address, city, url, img, strdate, true);
        //create marker and setup some attributs
        var marker = createMarker(point, html, markers[i].getAttribute('category'));
       
        marker.id = markers[i].getAttribute('id');
        marker.name = markers[i].getAttribute('name');
        marker.category = markers[i].getAttribute('category');
        marker.typemarker = typemarker;
        //currentmarker = marker;
        map.addOverlay(marker);
        GEvent.trigger(marker, 'click');
    }
}

// Function to create a marker and set up the event window
function createMarker(point, html, icontype) {
    var marker = new GMarker(point, gicons[icontype]);
    GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(html); });
    bounds.extend(point);
    
   //alert(gmarkers.length);
  //alert(gmarkers[0].getLatLng());
  // For markers with the same XY, only Hotels stays  (5 is hotel)

    for (var i = 0; i < gmarkers.length; i++) {
 
      for (var j = i+1; j < gmarkers.length; j++) {
     
        if ( gmarkers[i].getLatLng().toString()==gmarkers[j].getLatLng().toString() )
          {
          
     
          if (gmarkers[j].category[0]!="5")
               gmarkers[j].hide();
          else if (gmarkers[j].category[0]=="5")
               gmarkers[i].hide();
          }
    
      }
      
    }
   
    return marker;
}

//Show all markers in the map with typemarker given
//Typemarker is not only bar, hotel but free (hotel, bar...) or incontournable (concert,festival...)
function show(typemarker) {

    for (var i = 0; i < gmarkers.length; i++) {
        if (gmarkers[i].typemarker == typemarker) {
            gmarkers[i].show();
        }
    }
}

//Hide all markers in the map with typemarker given
function hide(typemarker) {

    for (var i = 0; i < gmarkers.length; i++) {
        if (gmarkers[i].typemarker == typemarker) {
       
            gmarkers[i].hide();
        }
    }
}

//Display buble info window for marker with id given
//gmarkers is an array which contains all markers on the map
function showInfo(id) {
    for (var i = 0; i < gmarkers.length; i++) {
        if (gmarkers[i].id == id) {
            GEvent.trigger(gmarkers[i], "click");
        }
    }
}


//show checkboxes for google map
//this function should be called when document is ready
function showCheckboxes() {
    $("#mapCheckboxesanchor").append($("#mapCheckboxes"));
    $("#mapCheckboxes").show();
}


function makeSidebar() {
    return;
    var html = "";
    for (var i = 0; i < gmarkers.length; i++) {
        if (!gmarkers[i].isHidden()) {
            html += '<a class="showInfo" id="' + gmarkers[i].id + '" href="#">' + gmarkers[i].name + '<\/a><br>';
        }
    }
    $("#sidebar").html(html);
}


