function showDirections() {
   var from = "from:";
   var to = "";
   for(var i = 1; i < markers.length; i++) {
      var spoint = markers[i].getPoint();
      //to: @47.441220, 0.718210 to: @45.250390, 1.536460 to:lyon
      to += " to: @" + spoint.lat() + ", " + spoint.lng();
      }
   if(markers.length > 1) {
      from = from + " @" + markers[0].getPoint().lat() + ", " + markers[0].getPoint().lng();
      setDirections(from, to);
      }
   }
function setDirections(fromAddress, toAddress) {
   var locale = "fr";
   var directionsPanel = document.getElementById("route");
   if (directionsPanel != null) {
      directionsPanel.clear;
      dirn = new GDirections(map, directionsPanel);
      }
   else dirn = new GDirections(map);
   GEvent.addListener(dirn, 'load', window.GMap_DirectionLoad);
   GEvent.addListener(dirn, 'error', window.handleErrors);
   dirn.load(fromAddress + " " + toAddress, {
      "locale" : locale, "getSteps" : "true" }
   );
   }
   
   
function GMap_DirectionLoad() {
   var arg = 'GMap_DirectionLoad|' + GetRouteDetails(dirn);
   __DoCallBack(gMap_Js, arg);
   }   
function GetRouteDetailsXml(d) {
   var result = "";
   //derails for each route
   for (var i = 0; i < d.getNumRoutes(); i++) {
      var route = d.getRoute(i);
      var routestr = "";
      var geocode = route.getStartGeocode();
      var point = route.getStep(0).getLatLng();
      for (var j = 0; j < route.getNumSteps(); j++) {
         var step = route.getStep(j);
         var str = "";
         // details for each step
         str += wrap("lat", step.getLatLng().lat());
         str += wrap("lng", step.getLatLng().lng());
         str += wrap("distance", step.getDistance().meters);
         //str += wrap("description",step.getDescriptionHtml());
         routestr += wrap("step", str);
         }
      result += wrap("route", routestr);
      }
   return result;
   }
function GetRouteDetails(d) {
   var result = "";
   //derails for each route
   for (var i = 0; i < d.getNumRoutes(); i++) {
      var route = d.getRoute(i);
      var routestr = "";
      var geocode = route.getStartGeocode();
      var point = route.getStep(0).getLatLng();
      for (var j = 0; j < route.getNumSteps(); j++) {
         var step = route.getStep(j);
         var str = "";
         // details for each step
         str += step.getLatLng().lat() + ",";
         str += step.getLatLng().lng() + ",";
         //str += wrap("description",step.getDescriptionHtml());
         routestr += str;
         }
      result += routestr;
      }
   //alert(result);
   return result;
   }





//Show all the locations at the appropriate zoom level
function centerAndZoomOnBounds(bounds){
    var center = bounds.getCenter();
    var newZoom = map.getBoundsZoomLevel(bounds);
    if (map.getZoom() != newZoom){
        map.setCenter(center, newZoom);
    }else{
        map.panTo(center);
    }
}

// Create a tabbed marker and set up the event window
// Accepts a variable number of tabs, passed in the arrays htmls[] and labels[]
function createTabbedMarker(point,labels,htmls) {
    var marker = new GMarker(point);
    
    GEvent.addListener(marker, "click", function() {
        // adjust the width so that the info window is large enough for this many tabs
        if (htmls.length > 2) {
            htmls[0] = '<div style="width:'+5*88+'px">' + htmls[0] + '</div>';
        }
        var tabs = [];
        for (var i=0; i<htmls.length; i++) {
            tabs.push(new GInfoWindowTab(labels[i],htmls[i]+labels[i]));
        }
        marker.openInfoWindowTabsHtml(tabs);
    });
    return marker;
}
	
// A function to create the marker and set up the event window
function createMarkerByPoint(point, address, title, url,icontype,img) {
    var marker = new GMarker(point,gicons[icontype]);
    img = "<img hspace='0' align='left' vspace='0' style='width: 80px; height: 80px;margin-right:5px' src='"+ img + "'/>"
    var html = img + "<a class='infoevenement' href='" + url +"'>" + title + "</a><br/>" + address;
    // The info window version with the "to here" form open
    to_htmls[markerCount] = html + '<br/><br/>Itineraires: <b>Vers ce lieu</b> - <a href="javascript:fromhere(' + markerCount + ')">A partir de ce lieu</a>' + '<br/>Lieu de depart:<form action="http://maps.google.fr/maps" method="get" target="_blank" rel="nofollow">' + '<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br/>' + '<INPUT value="Envoyer" TYPE="SUBMIT">' + '<input type="hidden" name="daddr" value="' + address + '"/>';
    // The info window version with the "to here" form open
    from_htmls[markerCount] = html + '<br/><br/>Itineraires: <a href="javascript:tohere(' + markerCount + ')">Vers ce lieu</a> - <b>A partir de ce lieu</b>' + '<br/>Lieu d&apos;arrivee:<form action="http://maps.google.fr/maps" method="get"" target="_blank" rel="nofollow">' + '<input type="text" SIZE=40 MAXLENGTH=40 name="daddr" id="daddr" value="" /><br/>' + '<INPUT value="Envoyer" TYPE="SUBMIT">' + '<input type="hidden" name="saddr" value="' + address + '"/>';
    // The inactive version of the direction info
    html = html + '<br/><br/>Itineraires: <a href="javascript:tohere(' + markerCount + ')">Vers ce lieu</a> - <a href="javascript:fromhere(' + markerCount + ')">A partir de ce lieu</a>';

    html = html+ "<br/><br/><a class='infoevenement' href='" + url +"'> Toute l'info sur " + title + "</a>";
    html="<div style='width:250px;min-height:70px'>" + html + "</div>"
    GEvent.addListener(marker, "click", function(){marker.openInfoWindowHtml(html);});
    gmarkers[markerCount] = marker;
    htmls[markerCount] = html;
    markerCount++;
    
    bounds.extend(point);
    
    return marker;
}


// A function to create the marker and set up the event window
function createMarkerByAddress(address, html,icontype,submarkers) {
    //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++) {
            //in this version, we add only one marker for each address
            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 , "#", icontype);
                submarkers.push(marker);
            }
            showMarkers(submarkers);
        }
        //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);
        }
    }
    );
}


//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";
        }
    }
    );
}

function getDataFromviaFrance(id,max,type,submarkers){
    //Read the data from viafrance
    var url = "../GetPlaceList.aspx?id=" +id+"&max="+max+"&type="+type;
    var request = GXmlHttp.create();
    request.open("GET", url, true);
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            var xmlDoc = GXml.parse(request.responseText);
            // obtain the array of markers and loop through it
            var markers = xmlDoc.documentElement.getElementsByTagName("marker");
            for (var i = 0; i<markers.length; i++) {
                // obtain the attribues of each marker
                var lat = parseFloat(markers[i].getAttribute("lat"));
                var lng = parseFloat(markers[i].getAttribute("lng"));
                var point = new GLatLng(lat,lng);
                var title = markers[i].getAttribute("title");
                //var label = markers[i].getAttribute("label");
                var url = markers[i].getAttribute("url");
                var img = markers[i].getAttribute("image");
                var address = markers[i].getAttribute("address1")+ "<br/>" +markers[i].getAttribute("address2");
                // create the marker and add it to sub-markers array
                //createMarkerByAddress(address,label,type,submarkers);
                var marker = createMarkerByPoint(point, address, title ,url, type,img);
                submarkers.push(marker);
            }
            
            showMarkers(submarkers);
        }
    }
    request.send(null);
}


//initialize the map
function loadGoogleMap(){
    if (GBrowserIsCompatible()) {
        var htmls = [];
        var i = 0;
        var gmarkers = [];
        //create a map
        map = new GMap2(document.getElementById("gmappanel"));
        
        
        bounds = new GLatLngBounds();
        
        //add map controls and set center
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        
        
        
        var marker = createMarkerByPoint(new GLatLng(latX, lngY), address, html,"#","",image);
        map.setCenter(new GLatLng(latX, lngY), 14);
        map.addOverlay(marker);
    }
    // display a warning if the browser was not compatible
    else {
        alert("Sorry, the Google Maps API is not compatible with this browser");
    }
}
//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.";
}

function setDirectionHtml(){
    
}


//zoom in and out the map
function mapZoomIn(){
    map.zoomIn();
}
function mapZoomOut(){
    map.zoomOut();
}


// functions that open the directions forms
function tohere(i){
    gmarkers[i].openInfoWindowHtml(to_htmls[i]);
}

function fromhere(i){
    gmarkers[i].openInfoWindowHtml(from_htmls[i]);
}

function showMarkers(markers){
    for (var i = 0; i < markers.length; i++) {
        map.addOverlay(markers[i]);
    }
    centerAndZoomOnBounds(bounds);
}

function hideMarkers(markers){
    for (var i = 0; i < markers.length; i++) {
        map.removeOverlay(markers[i]);
    }
}

//function to show the additional marker
function toogleMarkers(checkbox){
    if(checkbox.checked){
        if(submarkers[checkbox.value].length==0){
            getDataFromviaFrance(placeid,document.getElementById("number").value,checkbox.title,submarkers[checkbox.value]);
            showMarkers(submarkers[checkbox.value]);
        }
        else{
            showMarkers(submarkers[checkbox.value]);
        }
    }
    else{
        hideMarkers(submarkers[checkbox.value]);
    }
}


//function to refresh the marker
function refresh(){
    var checkboxs = ["hotel","resto","bar","shopping","visit","event"];
    var max = document.getElementById("number").value;
    for (var i = 0; i < checkboxs.length; i++) {
        var checkbox = document.getElementById(checkboxs[i]);
        if(checkbox.checked){
            hideMarkers(submarkers[checkbox.value]);
            submarkers[checkbox.value]=new Array();;
            getDataFromviaFrance(placeid,max,checkbox.title,submarkers[checkbox.value]);
            showMarkers(submarkers[checkbox.value]);
        }
    }
    
}

//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=[];


//array of markers 
var submarkers = new Array();
submarkers[0] = new Array();
submarkers[1] = new Array();
submarkers[2] = new Array();
submarkers[3] = new Array();
submarkers[4] = new Array();
submarkers[5] = new Array();


//array of icons
var gicons=[];
gicons["hotel"] = new GIcon(G_DEFAULT_ICON,"../WebFeatures/Images/gicon/hotel.gif");
gicons["resto"] = new GIcon(G_DEFAULT_ICON,"../WebFeatures/Images/gicon/restaurant.gif");
gicons["bar"] = new GIcon(G_DEFAULT_ICON,"../WebFeatures/Images/gicon/bar.gif");
gicons["shopping"] = new GIcon(G_DEFAULT_ICON,"../WebFeatures/Images/gicon/shopping.gif");
gicons["visit"] = new GIcon(G_DEFAULT_ICON,"../WebFeatures/Images/gicon/patrimoine.gif");
gicons["event"] = new GIcon(G_DEFAULT_ICON,"../WebFeatures/Images/gicon/event.gif");


