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);
         alert(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, html,icontype) {
    var marker = new GMarker(point,gicons[icontype]);
    // The info window version with the "to here" form open
    to_htmls[markerCount] = html + '<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/>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/>Itineraires: <a href="javascript:tohere(' + markerCount + ')">Vers ce lieu</a> - <a href="javascript:fromhere(' + markerCount + ')">A partir de ce lieu</a>';

    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+"<br/>"+address,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,lat, lng) {
                  var marker = createMarkerByPoint(new GLatLng(lat, lng), address,  html+"<br/>"+address);
                map.addOverlay(marker);
  
            map.setCenter(new GLatLng(lat, lng), 14);
        //error occur, decode the error status
}

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);
            alert(request.responseText);
            // obtain the array of markers and loop through it
            var markers = xmlDoc.documentElement.getElementsByTagName("marker");
            alert(markers.length);
            //for perfomance reason, we get only 5
            for (var i = 0; i<markers.length && i < 5; i++) {
            alert(markers[i].getAttribute("html"));
            //for (var i = 0; i < markers.length; i++) {
                // obtain the attribues of each marker
                //viaResult/Place don't have the lat lng information
                //var lat = parseFloat(markers[i].getAttribute("lat"));
                //var lng = parseFloat(markers[i].getAttribute("lng"));
                //var point = new GLatLng(lat,lng);
                var html = markers[i].getAttribute("html");
                var label = markers[i].getAttribute("label");
                var address = markers[i].getAttribute("address")
                // create the marker and add it to sub-markers array
                createMarkerByAddress(address,label,type,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("leplan"));
        bounds = new GLatLngBounds();
        
        //add map controls and set center
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(20, 0), 10);
        //map.enableScrollWheelZoom();
        showAddress(address,description, lat, lng);
    }
    // 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,2,checkbox.title,submarkers[checkbox.value]);
            showMarkers(submarkers[checkbox.value]);
        }
        else{
            showMarkers(submarkers[checkbox.value]);
        }
    }
    else{
        hideMarkers(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();

//array of icons
var gicons=[];
//gicons["hotel"] = new GIcon(G_DEFAULT_ICON,"../WebFeatures/Images/hotel.jpg");
//gicons["resto"] = new GIcon(G_DEFAULT_ICON,"../WebFeatures/Images/restaurant.jpg");
//gicons["bar"] = new GIcon(G_DEFAULT_ICON,"../WebFeatures/Images/bar-club.jpg");
//gicons["shopping"] = new GIcon(G_DEFAULT_ICON,"../WebFeatures/Images/shopping.jpg");


