/*
  --------------
  Module Cartographie -- v 0.3 -- Copyright Altimax F.R
  dernière modif : Nico le 14 octobre 2009
  --------------
*/

/*
  --------------
  VARIABLES
  --------------
*/
var jQ  = jQuery.noConflict();
var url_carto = "";
var map1;
var ZOOM_MAX = 12;
var ZOOM_MIN = 6;
var aMarkers  = new Array();
var aMarkersCommunes  = new Array();
var id_obt_focus  = 0;
var id_menu_focus = 0;
var zoom = 12;

function Config ()
{
  this.lat  = 0;
  this.lng  = 0;
  this.zoom = 2;
  this.kml  = "";
}
var cConfig = new Config();
    

jQ("#texte_loading").ajaxSend(function()
{ 
	loading(true);
});
jQ("#texte_loading").ajaxStop(function()
{ 
	loading(false);
});

/*
  --------------
  FONCTIONS D'INITIALISATION
  --------------
*/
//initialisation de l'interface et des variables en fonction de l'itineraire, puis initialisation de la carte
function init_interface(id_menu) {
  id_menu_focus  = (id_menu !=  undefined) ? id_menu  : id_menu_focus;

  loading(true);
  set_config(4.7187518,45.9898649,zoom);
}//init_interface

function set_config(plat,plng,pzoom) {//initialisation de l'objet de configuration
  
  cConfig.lat = plat;
  cConfig.lng = plng;
  cConfig.zoom  = pzoom;
  cConfig.kml  = quelKML;
  var bGmap = init_gmap();  //initialisation de la carte
  if(bGmap) {
    var bMenu = init_menu_carte(); //initialisation du click sur les menus, si la carte s'est initialisée
    if(bMenu) {
      loading(false);  
    }
  }
  
}//set_config

//Fonction d'affichage de la div de chargement
function loading(bDisplay,texte) {
  if(texte  !=  '' && texte != null) {
    jQ("#texte_loading").html(texte);
  }
	divLoading = document.getElementById("loading");
	if(bDisplay) {
		jQ("#loading").fadeIn("slow");

	}else {
	  jQ("#loading").fadeOut("fast");
	}
}


function init_menu_carte()  {
  //alert(id_menu_focus);
  jQ(".menu-carto").click(function(){
    loading(true,"Chargement des données...");
    var sId = this.id;
    ssMenuId  = sId.split('_')[1];
    if(!jQ(this).hasClass('lien-carto-parent')) {
        jQ('.menu-carto').each(function(){
          jQ(this).removeClass('menu-carto-click');
        });
        
        jQ(this).addClass('menu-carto-click');
        get_tag_jumi(ssMenuId,'',full,true);
  }
    return false;
  });
  
  
  
  jQ("li.carto-parent .lien-carto-parent").click(function(){
    if(jQ(this).hasClass('lien-parent-courant'))
    {
      jQ(this).removeClass('lien-parent-courant');
    }
    else
    {
      jQ(this).addClass('lien-parent-courant');
    }
    
  });
  
 jQ("#btn-beaujolais").click(function(){
  	//id_menu_focus = 0;
	if(jQ(this).hasClass('communesActif'))
    {
     // alert("communeActif");
	  jQ(this).removeClass('communesActif');
	  jQ(this).html('Carte du Beaujolais');
	  full = 0;
	  zoom = 12;
    }
    else
    {
      jQ(this).addClass('communesActif');
	  jQ(this).html('Carte Villefranche');
	  full = 1;
	  zoom = 9;
    }	  
	removeClassMenu();
	//alert(zoom);
	get_tag_jumi(id_menu_focus,zoom,full,false);
	map.setCenter(new GLatLng(45.9898649,4.7187518), zoom);
    return false;
  });
  
  
  
  
  if(id_menu_focus  !=  0)
  {
   //jQ('#sous-menu-carto_'+id_menu_focus).trigger('click');
   get_tag_jumi(id_menu_focus,zoom,full,first);
  }
  return true;
}

function removeClassMenu()
{
	jQ('.menu-carto-click').removeClass('menu-carto-click');
	jQ("#resultat-carte").fadeOut(500);
}

function get_tag_jumi(ssMenuId,nouveauZoom,full,first)
{
  removeMarkers();
  jQ.ajax({
               type: "GET",
               url: "/php/sitra/carte-interactive/ajax/get_tag_jumi.ajax.php",
               data: "id_m="  +ssMenuId+"&full="+full+'&first='+first,
               dataType:"script",
			   beforeSend: function(msg){
				loading(true);
			  },
               success: function(msg){
                loading(false);
              },
              error:  function() {
                loading(false);
                GLog.write("Erreur dans la récupération des données Jumi");
              }
      
      });
      if(nouveauZoom  !=  undefined)
      {
       map.setZoom(nouveauZoom);
      }
      
}

function get_objets_selections(chemin_article,selections, id_article,full,first)
{
  //les selections sitra sont separees par des '::'
  removeMarkers();
   jQ.ajax({
           type: "GET",
           url: "/php/sitra/carte-interactive/ajax/get_objets_selections.ajax.php",
           data: "selections="  +selections+"&chemin_article="+chemin_article+"&lang="+lang+"&id_m="+id_article+"&full="+full+"&first="+first,
           dataType:"script",
           beforeSend: function(msg){
			loading(true);
          },
		   success: function(msg){
			loading(false);
          },
          error:  function() {
            loading(false);
            GLog.write("Erreur dans la récupération des données Jumi");
          }

  });
}



/*
  Fonctions utiles pour la carte gMap
*/
/* tableau de points correspondants aux PoI */
var points = new Array();
var cpt = 0;

var latlngbounds = new GLatLngBounds( );

//initialisation de la gmap
function init_gmap()  {
	
   if (GBrowserIsCompatible()) {
  	 map = new GMap2(document.getElementById('map_carto'));
  	 map.clearOverlays();

	  var bottomRight = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10,10));
	  var topLeft = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10,50));

	   map.getContainer().style.overflow='hidden';
	   map.setCenter(new GLatLng(cConfig.lng,cConfig.lat), cConfig.zoom);
	  ;
	   map.addControl(new GLargeMapControl(),topLeft);
	   map.addControl(new GMapTypeControl(),bottomRight);

	   if(cConfig.kml != '') {
	     var trompeCache = new Date();
	     var ggeo =new GGeoXml(cConfig.kml +"?"+trompeCache.getMilliseconds());
	     map.addOverlay(ggeo);
     } 
    //	map.setMapType(G_SATELLITE_MAP);	  
	}	
  return true;
}//init_gmap


function removeMarkers () {
  for(var i=0;i<aMarkers.length;i++) {
    map.removeOverlay(aMarkers[i]);
  }
}

/*function removeMarkersCommunes () {
  for(var i=0;i<aMarkersCommunes.length;i++) {
    map.removeOverlay(aMarkersCommunes[i]);
  }
}*/

function addCartoMarker  (id,lat,lng,html,lien_detail,texte_loading,cheminIconePerso,nb) { 
  if(texte_loading) {
    //texte qui affiche le nombre de résultats retournés
	jQ("#resultat-carte").empty().html('<strong>'+texte_loading+'</strong>').fadeIn(500);
  }
  
  var markerPerso = {};
  if(cheminIconePerso  !=  "")
  {
    var iconePerso = new GIcon();
    iconePerso.iconSize = new GSize(28, 34);
    iconePerso.iconAnchor = new GPoint(14, 34);
    iconePerso.infoWindowAnchor = new GPoint(14, 17);
    iconePerso.image= cheminIconePerso;
    markerPerso = { icon:iconePerso };
  }
  var mMarker = new GMarker(new GLatLng(lat,lng),markerPerso);
  aMarkers.push(mMarker);
  map.addOverlay(mMarker);
  
  points[cpt] = new GLatLng(lat,lng);
  cpt++;
  //alert(cpt+','+nb);  

  if(cpt == nb)
  {
	map.setCenter(new GLatLng(0,0),0)	
	for ( var i = 0; i < points.length; i++ )
	{
		latlngbounds.extend( points[ i ] );
		//document.write(latlngbounds);
	}
	map.setZoom(map.getBoundsZoomLevel(latlngbounds));
	map.setCenter(latlngbounds.getCenter());
	//map.setCenter( latlngbounds.getCenter( ), map.getBoundsZoomLevel( latlngbounds ) );
	cpt = 0;
  }
  
  GEvent.addListener(mMarker,"click",function() {
    var rand  = Math.round(Math.random()*100);
    mMarker.openInfoWindowHtml("<div class='infowindow_gmap'>"+html+"</div>");
  });
  
    
}



function aucunResultat(msg)
{
	jQ("#resultat-carte").html('<strong>'+msg+'</strong>').fadeIn(500).fadeOut(500).fadeIn(500).fadeOut(500).fadeIn(500).fadeOut(500).fadeIn(500).fadeOut(500).fadeIn(500);	
}


