// 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;
}


//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";
        }
    }
    );
}


//type: event, resto, shopping...
//submarkers: 0 1 2
function getDataFromviaFrance(x,y,max,type,submarkers,showloading,eid){
    //show loading.gif
    if(showloading)
        $(".loading:not(:animated)").fadeIn("normal");
    //Read the data from viafrance
    var url = "../GetPlaceList.aspx?x="+x+"&y="+y+"&max="+max+"&type="+type+"&eid="+eid;
    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");
            //alert(markers.length);
            
            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 name = markers[i].getAttribute("title");
                //var label = markers[i].getAttribute("label");
                var url = markers[i].getAttribute("url");
                var img = markers[i].getAttribute("image");
                var typename = markers[i].getAttribute("typename");
                var itype = markers[i].getAttribute("itype");
                var blocktitle = markers[i].getAttribute("blocktitle");
                var address = markers[i].getAttribute("address1")+ "<br/>" +markers[i].getAttribute("address2");
                // create the marker and add it to sub-markers array
                var marker = createMarkerByPoint(point, address, name ,url, type,img);
                
                //we don't add to the list when there is already the same marker
                if(submarkers.indexOf(marker)==-1 && lat!=currentgmapx && lng!=currentgmapy){
                    submarkers.push(marker);
                }

                //buid the html for showing the result, only when we have 3
                if(markers.length<4){
                    var itemhtml = placehtml;
                    itemhtml = itemhtml.replace("{@X}",lat);
                    itemhtml = itemhtml.replace("{@Y}",lng);
                    
                    while(itemhtml.indexOf("{Name}") > 0){
                        itemhtml = itemhtml.replace("{Name}",name);
                    };
                    
                    itemhtml = itemhtml.replace("{typename}",typename);
                    itemhtml = itemhtml.replace("{itype}",itype);
                    itemhtml = itemhtml.replace("{Url}",url);
                    itemhtml = itemhtml.replace("{Image}",img);
                    itemhtml = itemhtml.replace("{Address}",address);
                    $("#"+itype+"list").html($("#"+itype+"list").html()+itemhtml);
                    $("#"+itype+"list .detailtitle").html(blocktitle);
                }                
            }
            //show the items in google map
            showMarkers(submarkers);

            //hide loading.gif
            if(showloading){
                $(".loading").fadeOut("normal");
                centerAndZoomOnBounds(bounds);
            }
        }
    }
    request.send(null);
}

function ClearGList(){
    $("#restolist ,#barlist ,#shoppinglist ,#visitlist,,#eventlist ").html("<p class='detailtitle'></p>");
}

function AddMarkers(latX, lngY, eid,typemymarker){
    //add the current one
    getData(typemymarker,eid);

    //before add new marker, clear the old one
    submarkers[0] = new Array();
    submarkers[1] = new Array();
    submarkers[2] = new Array();
    submarkers[3] = new Array();
    submarkers[4] = new Array();
    submarkers[5] = new Array();
    map.clearOverlays();
    bounds = new GLatLngBounds();

    //show 3 items for each category
    //$(".loading").fadeIn("normal");
    getDataFromviaFrance(latX,lngY,3,"resto",submarkers[1],false,eid);
    getDataFromviaFrance(latX,lngY,3,"bar",submarkers[2],false,eid);
    getDataFromviaFrance(latX,lngY,3,"shopping",submarkers[3],false,eid);
    getDataFromviaFrance(latX,lngY,3,"event",submarkers[4],false,eid);
    getDataFromviaFrance(latX,lngY,3,"visit",submarkers[5],true,eid);

    //$(".loading").fadeOut("slow");

}


function ShowMarkerInitial(){
    //if there is no marker initial, show the map and center at France
    if(currentmarkers.length<1) {
        var latX="30.83113";
        var lngY="-30.56142";
        map.setCenter(new GLatLng(latX, lngY), 2);
    }
    else{
        var latX="30.83113";
        var lngY="-30.56142";
        map.setCenter(new GLatLng(latX, lngY), 2);
        showMarkers(currentmarkers);
        
        //bounds.extend(point);
        //centerAndZoomOnBounds(bounds);
    }
}

function getData(type, id){
    //Read the data from viafrance
    var url = "../GetPlaceList.aspx?type="+type+"&eid="+id;
    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 name = markers[i].getAttribute("title");
                //var label = markers[i].getAttribute("label");
                var url = markers[i].getAttribute("url");
                var img = markers[i].getAttribute("image");
                var typename = markers[i].getAttribute("typename");
                var itype = markers[i].getAttribute("itype");
                var blocktitle = markers[i].getAttribute("blocktitle");
                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, name ,url, type,img);
                //show the items in google map
                map.setCenter(point, 14);
                map.addOverlay(marker);
                
            }
        }
    }
    request.send(null);
}

function showMarkers(markers){
    //$(".loading").fadeIn("normal");
    for (var i = 0; i < markers.length; i++) {
        map.addOverlay(markers[i]);
    }
    //$(".loading").fadeOut("normal");
    //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<4){
            getDataFromviaFrance(currentgmapx,currentgmapy,document.getElementById("number").value,checkbox.id,submarkers[checkbox.value],true,currentgmapid);
            showMarkers(submarkers[checkbox.value]);
        }
        else{
            showMarkers(submarkers[checkbox.value]);
        }
    }
    else{
        hideMarkers(submarkers[checkbox.value]);
    }
}


////function to refresh the marker
//function refresh(){
//    var checkboxes = ["hotel","resto","bar","shopping","visit","event"];
//    var max = document.getElementById("number").value;
//    for (var i = 0; i < checkboxes.length; i++) {
//        var checkbox = document.getElementById(checkboxes[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=[];


var placehtml="<div y='{@Y}' x='{@X}' class='{itype} glist'><img align='left' style='margin-right: 5px;' class='image70' title='{Name}' alt='{Name}' src='{Image}'/><h3 class='bold'><a href='{Url}'>{Name}</a></h3><p>{typename}</p><br/><span>O&#249; : </span><span class='navyblue'>{Address}</span></div>"

//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 current marker
var currentmarkers = new Array();
var currentgmapid;
var currentgmapx;
var currentgmapy;
//var typemymarker;

//array of icons
var gicons=[];
gicons["hotel"] = new GIcon(G_DEFAULT_ICON,"/Images/gicon/hotel.png");
gicons["resto"] = new GIcon(G_DEFAULT_ICON,"/Images/gicon/resto.png");
gicons["bar"] = new GIcon(G_DEFAULT_ICON,"/Images/gicon/bar.png");
gicons["shopping"] = new GIcon(G_DEFAULT_ICON,"/Images/gicon/shopping.png");
gicons["visit"] = new GIcon(G_DEFAULT_ICON,"/Images/gicon/patrimoine.png");
gicons["event"] = new GIcon(G_DEFAULT_ICON,"/Images/gicon/event.png");



//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.";
}

//zoom in and out the map
function mapZoomIn(){
    map.zoomIn();
}
function mapZoomOut(){
    map.zoomOut();
}

//initialize the map
function loadGoogleMap(){
    if (GBrowserIsCompatible()) {
        var htmls = [];
        var i = 0;
        var gmarkers = [];
        //create a map
        map = new GMap2(document.getElementById("gmapdiv"));
        bounds = new GLatLngBounds();
        //add map controls and set center
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        
        //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");
    }
}


//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);
    }
}

if (!Array.indexOf) {
  Array.prototype.indexOf = function (obj, start) {
    for (var i = (start || 0); i < this.length; i++) {
      if (this[i] == obj) {
        return i;
      }
    }
    
    return -1;
  }
}


function togglemap(){
    $("#gmapwrapper").toggleClass("blockinvisible");
}