  var map;
  var index = 0;
  var types = [];
  var markers = [];
  var markindex = 0;
  var infopanel;
  var message;
  var titre;
  var urlpath = "./serviceconsulat.php";
  var respjson =[];
  var startzoom =4;

var iconeVert = new GIcon();
iconeVert.image = "./catimages/vert.png";
iconeVert.shadow = "./catimages/ombre.png";
iconeVert.iconSize = new GSize(15, 20);
iconeVert.shadowSize = new GSize(22, 20);
iconeVert.iconAnchor = new GPoint(6, 20);
iconeVert.infoWindowAnchor = new GPoint(4, 1);

var LatitudeCarteClick ;
var LongitudeCarteClick;

function entitymarker(lat,lng,title,type,marker,info) {
    this.lat = lat;
    this.lng = lng;
    this.title = title;
    this.type = type;
    this.marker = marker;
    this.info = info;
}



  function onLoad() {
      if (GBrowserIsCompatible()) {
	 // infopanel = document.getElementById("infopanel");
	//  message = document.getElementById("message");
	  map = new GMap2 (document.getElementById("map"));
       //   titre = document.getElementById("sidebar-list");
       //   pages = document.getElementById("pagecountry");

          map.addControl(new GMapTypeControl());
	map.addControl(new GLargeMapControl());
//	map.addControl(new GOverviewMapControl(new GSize(70,80)));

        //  map.addControl(new GLargeMapControl());
 	 // map.addControl(new GMapTypeControl());
	 // map.addControl(new GScaleControl());
	  map.setCenter(new GLatLng(54,-2.94), startzoom);

	//  showcountrylist(1);

        var point = new GLatLng(48.644638,3.944336 );
        var markertomove = new GMarker(point,{icon: iconeVert, draggable:true});
        map.addOverlay(markertomove);

        GEvent.addListener(markertomove, 'dragstart', function() {
	map.closeInfoWindow();
	});

        GEvent.addListener(markertomove, 'drag', function(point) {
	   AfficheGPS(markertomove);
	});

        GEvent.addListener(markertomove, 'dragend', function(point) {
          AfficheGPS(markertomove);

          var str = '<a href="#" onClick="showcountrylist();" > Donnee </a>';

          //markertomove.openInfoWindowHtml(str);
          recentrerCarte();

	});

 	var focusPoint = function() {

		markertomove.openInfoWindowHtml('<a href="#" onClick="showcountrylist();" > Donnee </a>');
 		return false;
	}

       GEvent.addListener(markertomove, 'click', focusPoint);

      }
  }
 function recentrerCarte(){
	<!-- /** Apr&egrave;s un d&eacute;lai de 1000 ms on centre la carte nomm&eacute;e "MaCarte" sur le point ayant pour latitude "LatitudeCarteClick" et longitude "LongitudeCarteClick" **/ -->
	window.setTimeout(function(){map.panTo(new GLatLng(LatitudeCarteClick, LongitudeCarteClick));}, 8);
}
  // Afficher les coordonnees :lat & lng
function AfficheGPS(a_marker){

   	var center = a_marker.getPoint();

	LatitudeCarteClick = center.lat();

 	LongitudeCarteClick = center.lng();    
 	
 	var lat = document.getElementById('idLatitude');
        lat.value  = LatitudeCarteClick;

 	var lng = document.getElementById('idLongitude');
        lng.value  = LongitudeCarteClick;

 }


  function showentitylist(indice) {
      index = 0;
      types = [];
      markindex=0;
      message.innerHTML = 'Choisir une categorie';
      infopanel.innerHTML = '';
      var request = GXmlHttp.create();
      request.open('GET',urlpath+'?m=entitylist&country='+indice, true);
      request.onreadystatechange = function() {
	  if (request.readyState == 4) {
	      var xmlsource = request.responseText;
	      var respjson = eval(xmlsource);
	      var i=0;

	      for (id in respjson) {
                    types.push(respjson[id].typename);
                    //types[i] =respjson[id].typename;
                    infopanel.innerHTML = infopanel.innerHTML +
                    '<div id="addmarker"><a href="#" onClick="loadentity(' + i +','+indice+ ');">' +
                    respjson[id].typename +
                    '</a></div><div id="hidemarker">' +
                    '<a href="#" onClick="clearmarkers(' +
		    "'" + respjson[id].typename + "'" +
		    ');">Cacher ' +
		    respjson[id].typename +
                    '</a></div><br/><br/>';
                    i++;
	    }
	  }
      }
      request.send(null);
  }

  function showcountrylist(pageNo) {

      var req = GXmlHttp.create();
      req.open('GET',urlpath+'?m=countrylist&page='+pageNo, true);
      req.onreadystatechange = function() {
	  if (req.readyState == 4) {
	      var xmlsource = req.responseText;
	      var params = xmlsource.split('^');
	      var respjson = eval(params[1]);
              var menu = params[0].split('&');
              var j=0;
              titre.innerHTML='';
              pages.innerHTML='';
              for(j=0;j<2;j++){
                 var cntitem= (menu[j]).split('=');
                 var Nextpage; if(cntitem[1]==''){Nextpage=pageNo;}else{Nextpage=cntitem[1];}
                 if(j==1){break;}
              } 
                pages.innerHTML +=' pages: ';
                for(var k=0;k<2;k++){u=k+1;pages.innerHTML +='<li><a href="#" onClick="showcountrylist('+u+'); ">'+u+' </a></li>';}

	      for (ind in respjson) {

                    titre.innerHTML +='<img src="./img/'+respjson[ind].code+'.png" />&nbsp;<a href="#" onClick="showentitylist('+respjson[ind].Id +');">'
                    +respjson[ind].country +
                    '</a><br /><br />';


	    }
	  }
      }
      req.send(null);
  }

  function movemap(index) {
      map.panTo(new GLatLng(markers[index].lat,markers[index].lng));

  }

function clearmarkers(type) {
    var keeplist = [];
    for (var i=0;i<markers.length;i++) {
        if (markers[i].type == type) { 
            map.removeOverlay(markers[i].marker);
        } else {
            keeplist.push(markers[i]);
        }
    }
    markers = [];
    for (var i=0;i<keeplist.length;i++) {
        markers.push(keeplist[i]);
    }
}

function addmarker(x,y,title,tel,info,icon,type) {

    var point = new GPoint(parseFloat(x),parseFloat(y));
    var marker = new GMarker(point,icon);
    var focuspoint =function(){
      marker.openInfoWindowHtml('<div id="InfoWind1">'+title+'</div><div id="InfoWind2">'+info+'</div><div id="InfoWind3">Tel:'+tel+'</div>');
      return false;
    }
    GEvent.addListener(marker,'click',focuspoint);
    map.addOverlay(marker);
    markers.push(new entitymarker(y,x,title,type,marker,info));
 
    infopanel.innerHTML = infopanel.innerHTML +
        '<a href="#" onClick="movemap(' + markindex + ');">' +
        title +
        '</a><br/><br/>';
    markindex++;
}


  function show_adresse(lat,lng,type) {
      points=[];
    //  markers =[];

      var entitytype = type;
      var baseIcon = new GIcon();
      baseIcon.iconSize = new GSize(21,31);
      baseIcon.shadow = "./img/shadow.png";
      baseIcon.iconAnchor = new GPoint(0,10);
      baseIcon.infoWindowAnchor = new GPoint(50,20);
      baseIcon.image = "./img/hotels.png";

      var bounds = new GLatLngBounds();
      var points = [];


            var j=0;

               addmarker(parseFloat(lng),
                  parseFloat(lat),'' , '' ,'' ,
                  baseIcon,
                  entitytype);
                  bounds.extend(new GLatLng(markers[j].lat, markers[j].lng));

              j++;

          // map.setCenter(lat,lng, map.getBoundsZoomLevel(4));
           map.recenterOrPanToLatLng(new GLatLng(lat, lng));
            //recenterandzoom(markers);

  }


  function loadentity(index,service) {
      points=[];
    //  markers =[];
      message.innerHTML = types[index];
      var entitytype = types[index];
      var baseIcon = new GIcon();
      baseIcon.iconSize = new GSize(21,31);
      baseIcon.shadow = "./img/shadow.png";
      baseIcon.iconAnchor = new GPoint(0,10);
      baseIcon.infoWindowAnchor = new GPoint(50,20);
      baseIcon.image = "./img/" + types[index].toLowerCase() + ".png";
      infopanel.innerHTML = '';
      var bounds = new GLatLngBounds();
      var points = [];
      var request = GXmlHttp.create();
      request.open('GET',urlpath+'?m=getmarkers&country='+service+'&entity='+types[index], true);
      request.onreadystatechange = function() {
	  if (request.readyState == 4) {
            var respmarkers = eval(request.responseText);
            var j=0;
            for(id in respmarkers){
               addmarker(parseFloat(respmarkers[id].lng),
                  parseFloat(respmarkers[id].lat),
                  respmarkers[id].titre,
                  respmarkers[id].tel,
		  respmarkers[id].addra,
                  baseIcon,
                  entitytype);
                  bounds.extend(new GLatLng(markers[j].lat, markers[j].lng));
		  points.push(new GPoint(parseFloat(respmarkers[id].lng),
                                         parseFloat(respmarkers[id].lat)));
              j++;
            }
           map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
            //recenterandzoom(markers);
	    infopanel.innerHTML = infopanel.innerHTML +
	    '<br/>' +
	    '<a href="#" onClick="showentitylist('+service+')"><h3>Retour au '+types[index]+'</h3></a><br/>';

	  }
      }
      request.send(null);
  }


// populate the category select list via AJAX
function retrieveCategorySelect()
{
    document.getElementById('cat_select_tbl').style.display = '';
    var url = 'inventory_process.php?retrieve_category_select';

    httpObj = createXMLHTTPObject();
    httpObj.open('GET', url, true);
    httpObj.onreadystatechange = function()
    {
        if (httpObj.readyState == 4)
        {
            document.getElementById('cat_select_cell').innerHTML =httpObj.responseText;

            // assign select list's event handler 
            document.getElementById('cat_select').onchange = retrieveItemSelect;
        }
    }

    httpObj.send(null);
}

// populate the item select list for the selected category via AJAX
function retrieveItemSelect()
{
    var url = 'inventory_process.php?retrieve_item_select' +
        '&nocache=' + (new Date()).getTime();

    window.httpObj = createXMLHTTPObject();
    window.httpObj.onreadystatechange = function()
    {
        if (window.httpObj.readyState == 4)
        {
            document.getElementById('country_name').innerHTML =
                window.httpObj.responseText;

            // assign select list's event handler
            document.getElementById('item_select').onchange = showCategoryForms;
        }
    }

    window.httpObj.open('GET', url, true);
    window.httpObj.send(null);
}

// display the category's form and possibly a synced item list
function showCategoryForms()
{
  // hide the category select list
  document.getElementById('cat_select_tbl').style.display = 'none';
    document.getElementById('cat_form_tbl').style.display = 'none';

    var select = document.getElementById('cat_select');

    document.getElementById('item_form_tbl').style.display = '';
}




// submit the item form via AJAX
function submitItemForm()
{

    // prepare the url and data
    var url = 'inventory_process.php?Lat='+LatitudeCarteClick+'&Lng='+LongitudeCarteClick+'&save_item&nocache=' +
        (new Date()).getTime();
          var select1 = document.getElementById('cat_select');
          var select2 = document.getElementById('item_select');

    var data = 'type=' + select1.options[select1.selectedIndex].value +
        '&country='+parseInt(select2.options[select2.selectedIndex].value)+
        '&tel=' +  escape(document.getElementById('tel').value) +
        '&titre=' + document.getElementById('item_name').value +
        '&description=' + document.getElementById('item_description').value;

    window.httpObj = createXMLHTTPObject();
    window.httpObj.onreadystatechange = function()
    {
        if (window.httpObj.readyState == 4)
        {
         resetCategoryForm();
        }
    }

    // set headers and send content
    window.httpObj.open('POST', url, true);
    window.httpObj.setRequestHeader('Content-type',
        'application/x-www-form-urlencoded');
    window.httpObj.setRequestHeader('Content-length', data.length);
    window.httpObj.setRequestHeader('Connection', 'close');
    window.httpObj.send(data);
   
}
// reset the category form
function resetCategoryForm()
{
    // hide sub forms
    document.getElementById('cat_form_tbl').style.display = 'none';
    document.getElementById('cat_select_tbl').style.display = 'none';
    document.getElementById('item_form_tbl').style.display = 'none';

}


  function onLoad_main() {
      if (GBrowserIsCompatible()) {
	 // infopanel = document.getElementById("infopanel");
	//  message = document.getElementById("message");
	  map = new GMap2 (document.getElementById("map"));
       //   titre = document.getElementById("sidebar-list");
       //   pages = document.getElementById("pagecountry");

          map.addControl(new GMapTypeControl());
	map.addControl(new GLargeMapControl());

	  map.setCenter(new GLatLng(54,-2.94), startzoom);

      }
  }
