/**
 * Permet d'afficher des points sur une carte
 * google map. Les donnees sont issues de sitra.
 * Je me suis appuye sur le plugin GMAP3 pour ecrire cette classe
 * @author Cedric Duffournet <cellog@php.net>
 * @company Noe interctive
 * @v 1.0
 */
  
/*(function($)
{
    var default = {
        
    }
    $.fn.noeSitraGoogleMap = function(options){

    }
})(jQuery)  
var noeSitraGooglemap = {   

    options : {
        zoom: 14,
        center: '',
        mapTypeId: google.maps.MapTypeId.ROADMAP
    },
    construct(div)          
  
}*/


  var commune;
  var allListe = new Array();
  var communeSelected="";
  var listSelected = new Array();
  //liste des markers affiche sur la map
  var listMarkerDisplay = new Array();
  var bound;
  var filterHotel = new Array();
  var triHotel = 'prix';
  var mapInitialized = false;
  var mapInitializedPopup = false;
  var mapGeolocInitialized = false;
  var fitTheBound = false;
  
  if(!forcePopupMap || imprimeMap)
  {
    var popupMap = false;
  }
  else
  {
    var popupMap = true;  
  }
  var defaultLatitude = '45.9036';
  var defaultLongitude = '6.10389';
  
    jQuery(document).ready(function($) {
    
    $('.buttonSearchSitra').click(function()
    {
          displayMarker();
          return false;
    })

    $('.btnRelancerRechercheHotel').click(function()
    {
          displayMarker();
          return false;
    })
    
    
    $('.tri').click(function()
    {
          if(jQuery(this).attr('rel') == 'etoile')
          {
              jQuery('#triPrix').removeClass('triSelected');
          }
          
          if(jQuery(this).attr('rel') == 'prix')
          {
              jQuery('#triEtoile').removeClass('triSelected');
          }
          triHotel = jQuery(this).attr('rel');
          jQuery(this).addClass('triSelected');
          
          rechargeSelection();
          //alert(jQuery(this).attr('rel'));
          return false;
    })
        
  });
  
  $(function() {
		$( "#tabs" ).tabs();
	});
	
	
	
	function initLocalisationSitraFiche(pLatitude, pLongitude)
	{
	       
	        if(pLatitude)
	        {
	             latitudeGeolocSitra = pLatitude;
	        }
	        
	        if(pLongitude)
	        {
	             longitudeGeolocSitra = pLongitude;	             
	        }
          mapGeolocInitialized = true;	       
          $('#cartePopup').gmap3(
            { action : 'init', 
              options:{
              mapTypeId : google.maps.MapTypeId.ROADMAP,
              center:{lat: latitudeGeolocSitra,lng: longitudeGeolocSitra}, 
              zoom: 15,
              scrollwheel: false
              }
            },
            {action: 'addMarker',
            latLng:[latitudeGeolocSitra, longitudeGeolocSitra],
            marker:{
                options:{
                            icon: new google.maps.MarkerImage("http://www.haute-savoie-sous-traitance.com//images/carte/generericMarker.png")                                 
                        }
                }
            },
            {
              action:'setStyledMap',
              id:'style1',
              style:[
                      {
                          featureType:'poi.business',
                          stylers: [
                                { visibility: "off" }
                          ]                      
                      }
                    ]
            }
                    
          );
	}
	
	
	function rechargeSelection()
	{
	
    var longitudeReference = '';
    var latitudeReference = '';
    if(popupMap)
    {
        longitudeReference = defaultLongitude;
        latitudeReference = defaultLatitude;
    }
                	
	   var filter = new Object();
	   filter = getFilterHotel();
	   //parametre a envoye au fichier php (la commune et la liste des selections)
      var myObject = {
            commune:communeSelected,
            typeid:'11145',
            triHotel:triHotel,
            triHotel:triHotel,
            popupMap:popupMap,
            longitude:longitudeReference,
            latitude:latitudeReference
            
      };
      
      var paramFilter = $.param(filter);
      var params = $.param(myObject);
        //recuperation de la liste des markeurs
        $.ajax({
            url:'/genereLocalisationJson.php',
            data:params+'&'+paramFilter,
            success:function(data){              
              $('#listResultatHotel').html(data.listHtml);
              
            }
          });
                        
	}
	  
  /**
  * initialisation de la map
  */
  $(function(){
      if(!popupMap && !imprimeMap)
      {
        initMap();
      }

  });
  
  function initMap()
  {
  
      ///alert(defaultLatitude);
      //alert('default latitude ->'+defaultLatitude);
            
      $('#carte').gmap3(
        { action : 'init', 
          options:{
          mapTypeId : google.maps.MapTypeId.ROADMAP,
          center:{lat: defaultLatitude,lng: defaultLongitude}, 
          zoom: 10,
          scrollwheel: false          
          },
                                      
          events:{
            click: function(map, latLng){
                $('#carte').gmap3({ action:'clear', name:'overlay'})
            }
          }
        },
        {
          action:'setStyledMap',
          id:'style1',
          style:[
                  {
                      featureType:'poi.business',
                      stylers: [
                            { visibility: "off" }
                      ]                      
                  }
                ]
        }
      );
      
      mapInitialized = true;
            
  } 
  
  function initMapPopup(latitude, longitude)
  {
      popupMap = true;

      if(initialLatitude =='')
      {
        defaultLatitude = latitude;
      }
      else
      {
         defaultLatitude = initialLatitude;
         //alert(initialLatitude);
      }
      if(initialLongitude =='')
      {
        defaultLongitude = longitude;
      } 
      else
      {
        defaultLongitude = initialLongitude;      
      }
      
      initMap();
      
      displayMarker();
      
      $('#carte').gmap3(
          {action: 'addMarker',
          latLng:[defaultLatitude, defaultLongitude],
          marker:{
              options:{
                          icon: new google.maps.MarkerImage("http://www.haute-savoie-sous-traitance.com/images/carte/generericMarker.png")                                 
                      }
              }
          }
      ); 
            
      mapInitializedPopup = true;
  }
  
  
  /**
  * Recuperation des listes seletionnes
  */
  function getListSelected()
  {
      var listeSelected = new Array();
      var i = 0;
      var y=0;
      
      $("div.listSelection input:checkbox").each(function() {
          if(jQuery(this).is(':checked'))
          {
             listeSelected[i] = $(this).val();
             i++;
          }
          allListe[y] = $(this).val();
          y++
      });

      return listeSelected;
  }
  
  
  
  /**
  * Recuperation de la commune
  */
  function getCommuneSelected()
  {
      
      var commune  =$("#comboCommune").val();
      return commune;
  }
  

  
  function deleteAllLayer()
  {
      
      $("#carte").gmap3(
          { action:'clear', 
          name:'marker'},
          { action:'clear', 
            name:'overlay'},
          { action:'clear', 
          name:'cluster'}
            
      );
  }
  
  function displayMarker()
  {
  
     
     
     fitTheBound = false;
     //on supprime l'ensemble des marker
     deleteAllLayer();
     
     //on vide le contenu des div qui contiennent les resultat
     $('#listResultatHotel').html('');
     $('#nbrReponseHotel').html('0')
    
    
     $('#listResultatRestaurant').html('');
     $('#nbrReponseRestaurant').html('0')
    
     $('#listResultatEvenement').html('');
     $('#nbrReponseEvenement').html('0');
    
     $('#listResultatTourisme').html('');
     $('#nbrReponseTourisme').html('0')
                   
     
     
     //on inisialise le bound
     bound = new google.maps.LatLngBounds();
     //recuperation de la communes selectionnee
     communeSelected = getCommuneSelected();
    
     //recuperaiton de la liste des selections selectionne
     listSelected = getListSelected();
      
      
    
     //alert(listSelected.length);
     
     if(communeSelected!=""  && listSelected.length >0 && !popupMap)
     {
          $("#loadingCarte").show();
          $("#tabs").css('display', 'block');
          $("#tabsCarte").css('background-color',"#eceaea");
          recursiveDisplayMarker(0);
     }
     else
     {
          if($("#tabs"))
          {
              $("#tabs").css('display', 'none');
          }
          
          if($("#tabsCarte"))
          {
              
              $("#tabsCarte").css('background-color', 'transparent');
          }
          
          if(listSelected.length >0 && popupMap)
          {
              $("#loadingCarte").show();
              recursiveDisplayMarker(0);          
          }          
     }
  }
  
  
  
  function recursiveDisplayMarker(indiceSelection)
  {
  
            

        var lastSelection = false;
        var filter = new Object();
        var longitudeReference = '';
        var latitudeReference = '';
        ///////////////////////////////////////
        // AFFICHAGE DES LISTES EN BAS DE CARTE
        
        //liste hotel
        if(listSelected[indiceSelection] == '11145')
        {
            //getListHotel();
            //recuperation du filtre etoile
            filter = getFilterHotel();
        }
         
        //liste restaurant
        if(listSelected[indiceSelection] == '11154')
        {
            filter = getFilterRestaurant();
            //getListRestaurant();
        }
        //liste evenement
        if(listSelected[indiceSelection] == '11155')
        {
            filter = getFilterEvenement();
        }

        //liste office de tourisme
        if(listSelected[indiceSelection] == '11156')
        {
            getListOffice();
        }

        if(popupMap)
        {
            longitudeReference = defaultLongitude;
            latitudeReference = defaultLatitude;
        }

        //parametre a envoye au fichier php (la commune et la liste des selections)
        var myObject = {
              commune:communeSelected,
              typeid:listSelected[indiceSelection],
              triHotel:triHotel,
              popupMap:popupMap,
              longitude:longitudeReference,
              latitude:latitudeReference
        };
        
        var paramFilter = $.param(filter);
        var params = $.param(myObject);
        
        
        
        if(indiceSelection == listSelected.length-1)
        {
              lastSelection = true;
        }
        
        //recuperation de la liste des markeurs
        $.ajax({
            url:'/genereLocalisationJson.php',
            data:params+'&'+paramFilter,
            success:function(data){
              /*if(console.log)
              {
                console.log('success request');
              }*/
              //on regarde si on a bien des donnees a afficher
              //if(data.listMarker)
              //{ 
                  //console.log(data);
                  display(data.listMarker, listSelected[indiceSelection], lastSelection);
              //}
              
              if(listSelected[indiceSelection] == '11145')
              {
                
                  $('#listResultatHotel').html(data.listHtml);
                  $('#nbrReponseHotel').html(data.nbrReponse)
              }
              
              
              if(listSelected[indiceSelection] == '11154')
              {
              
                  $('#listResultatRestaurant').html(data.listHtml);
                  $('#nbrReponseRestaurant').html(data.nbrReponse)
              }
              
              if(listSelected[indiceSelection] == '11155')
              {
              
                  $('#listResultatEvenement').html(data.listHtml);
                  $('#nbrReponseEvenement').html(data.nbrReponse)
              }
              
              
              if(listSelected[indiceSelection] == '11156')
              {
              
                  $('#listResultatTourisme').html(data.listHtml);
                  $('#nbrReponseTourisme').html(data.nbrReponse)
              }
              
                                              
              //on resgarde si on a bien traite toute les listes, si c'est pas le cas, on relance notre fonction
              if(indiceSelection != listSelected.length-1)
              {
                    indiceSelection++;
                    recursiveDisplayMarker(indiceSelection);
              }
              else
              {
                         $("#loadingCarte").hide();              
              }

            }
          });
                  
  }
  
  
  function getFilterHotel()
  {
      var aFilter = new Object();
      $("div#filtreHotel input:checkbox").each(function() {
          if(jQuery(this).is(':checked'))
          {
             aFilter[jQuery(this).val()] = 1;
             //i++;
          }
      });
      aFilter['typeHotel'] = $("#comboTypeHotel option:selected").val();      
      //console.log(aFilter);
      return aFilter;
  } 
  
  
  
  function getFilterRestaurant()
  {
      var aFilter = new Object();
      
      $("div#filtreRestaurant input:checkbox").each(function() {
          if(jQuery(this).is(':checked'))
          {
             aFilter[jQuery(this).val()] = 1;
          }
      });
      
      aFilter['typeRestaurant'] = $("#comboTypeRestaurant option:selected").val();      
      //console.log(aFilter);
      return aFilter;
                  
      return aFilter;
  }
  
  
  
  function getFilterEvenement()
  {
      var aFilter = new Object();
      var dayDebut = '';
      var dayFin = '';
      var month = '';
      
      dayDebut = $("#jourDebut option:selected").val();
      dayFin = $("#jourFin option:selected").val();
      month = $("#mois option:selected").val();
      
      aFilter['dayDebut'] = dayDebut;
      aFilter['dayFin'] = dayFin;
      aFilter['month'] = month;
      
      return aFilter;
  }
  
  //ajout des kml    
  function addKml()
  {
  
     //var map = $('#carte').gmap3('get')   
     //communeSelected = getCommuneSelected();
     //var listeSelected = getListSelected();
     //deleteAllLayer();
    
      //alert(listeSelected);
      var myObject = {
          commune:communeSelected
      };
      
      var params = $.param(myObject);
      var nbrListe = listeSelected.length;
      var date = new Date();  
      var traitedList;
      
      for(var i = 0; i < nbrListe; i++)
      {
          var currentList = listeSelected[i];
          
          if(currentList == '11145')
          {
             //getListHotel(); 
          }
          
          if(currentList == '11154')
          {
             //getListRestaurant(); 
          }
          
          if(currentList == '11155')
          {
             getListEvenement(); 
          }   
          
          if(currentList == '11156')
          {
             getListOffice(); 
          }
            
          var communeSelected = getCommuneSelected();
          
          var myObject = {
              commune:communeSelected,
              typeid:currentList
          };
          var params = $.param(myObject);      
          $.ajax({
            url:'/genereLocalisationJson.php',
            data:params,
            success:function(data){
              traitedList = currentList;
              display(data.listMarker, traitedList);
            }
          });
                  
                                     
          //alert(currentList);
          /*$('#carte').gmap3(
            { action: 'addKmlLayer',
              url: 'http://www.haute-savoie-sous-traitance.com/genereLocalisation.php?typeid='+currentList+'&'+params+'&time='+date.getTime(),
              tag:currentList,
              options:{
                suppressInfoWindows: true
              },
                        
              events:{
                click: function(kml, event){
                    console.log(event);
                    $(this).gmap3(
                      { action:'clear', name:'overlay'},
                      { action:'panTo', args:[event.latLng]},
                      { action:'addOverlay',
                        latLng: event.latLng,
                        content:  '<div class="customInfoWindow">'+
                                  '<div class="customInfoWindow" style="padding:0; width:230px; background-color:#efefef">'+
                                  '<div style="font-size:12px; line-height:14px;margin:0;">'+
                                    event.featureData.description+
                                    '<div style="width:210px;background-color:#efefef;height:20px;border-top:1px solid #4d4d4f;padding:10px 10px 10px 10px;display:block;float:left;">'+
                                    '<a href="#" rev="ficheid='+event.featureData.id+'" rel="/voirFicheSitra.php"  onclick="showMyFloatBox(this,\'fiche\');return false;" style="float:right" >En savoir plus</a></div></div></div></div>',
                        offset: {
                          x:-100,
                          y:-100
                        }
                      }
                    );

                  }

                }
              }              

          );*/    
      }
      
    }
    
    
    
    function calculateBound(markerList,fitBound)
    {
        var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
        
         for(var i in markerList)
         {
                myLatlng = new google.maps.LatLng(markerList[i].lat, markerList[i].lng);
                bound.extend(myLatlng);
                fitTheBound = true;
                //console.log(markerList[i]);
         } 
         
         if(fitBound && fitTheBound)
         {
            //console.log(markerList);
            var map = $('#carte').gmap3('get');     
            map.setCenter(bound.getCenter());
            map.fitBounds(bound);                
         }
    }
    
    
    
    function calculateBoundSt(markerList,fitBound)
    {
        var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
        var boundSt = new google.maps.LatLngBounds();
          
         for(var i in markerList)
         {
                myLatlng = new google.maps.LatLng(markerList[i].lat, markerList[i].lng);
                boundSt.extend(myLatlng);
                //console.log(markerList[i]);
         } 
         
         if(fitBound)
         {
            var map = $('#carteSt').gmap3('get');     
            map.setCenter(boundSt.getCenter());
            map.fitBounds(boundSt);                
         }    
    }
    
    
    function display(markerList,listId,lastSelection)
    {
            calculateBound(markerList, lastSelection);
            
            
            //alert(markerList);
            if(markerList)
            {
              
              $('#carte').gmap3(
              {
                    action:'addMarkers',
                    markers:markerList,
                    radius:100,
                    clusters:{
                      // This style will be used for clusters with more than 0 markers
                      0: {
                        content: '<div class="cluster clust'+listId+'"></div>',
                        width: 29,
                        height: 36
                      },
                      // This style will be used for clusters with more than 20 markers
                      20: {
                        content: '<div class="cluster clust'+listId+'"></div>',
                        width: 29,
                        height: 36
                      },
                      // This style will be used for clusters with more than 50 markers
                      50: {
                        content: '<div class="cluster clust'+listId+'"></div>',
                        width: 29,
                        height: 36
                      }
                    },
                    cluster:{
                    events:{
                      mouseover:function(cluster,event,data)
                      {
                          //console.log(data);
                          $(this).gmap3(
                              {action:'clear', name:'overlay'},
                              {action:'addOverlay',
                               latLng:data.latLng,
                               content:'<div class="clusterOver">'+clusterResultatCarte + '<strong>'+data.markers.length+'</strong>'+clusterResultat+'</div>'
                              }
                          );
                          //console.log(data);
                      },
                      mouseout:function(){
                          $(this).gmap3(
                              {action:'clear', name:'overlay'});                          
                      }
                    }
                    },
                    marker: {
                      options: {
                        icon: new google.maps.MarkerImage("http://www.haute-savoie-sous-traitance.com/images/carte/"+listId+'.png')
                      },
                      events:{
                          click:function(marker, event,data)
                          {
                               $(this).gmap3(
                                { action:'clear', 
                                  name:'overlay'},
                                { action:'panTo', 
                                  args:[marker.getPosition()]},
                                { action:'addOverlay',
                                  latLng: marker.getPosition(),
                                  content:data.description,
                                  offset:{x:-100,
                                          y:-100},
                                  zindex:500
                                  
                                }

                                                        
                              );
                              /*var map = $('#carte').gmap3('get');
                              
                              
          var test =   $("#carte").gmap3({action:'get', name:'cluster'}); 
          console.log(test.getPanes());*/
                                
                          }
                      }
                          
                    },
                    callback:function(marker)
                    {
                        //alert('test');
                        //console.log(marker);
                        /*var map = $('#carte').gmap3('get');
                        
                        for(var i in marker)
                        {
                            bound.extend(marker[i].getPosition());
                        } 
                        map.setCenter(bound.getCenter());
                        map.fitBounds(bound);*/
                        
                        //console.log(marker);
                        //alert('test');
                    }                                  
              }
            );
            

          } 
            //console.log(data.listMarker);          
    }
    
    
    function getListHotel()
    {
        var communeSelected = getCommuneSelected();
        var myObject = {
            commune:communeSelected,
            typeid:11145
        };
        var params = $.param(myObject);     
        
        $.ajax({type: "POST",
                 url:'/admin/module_sitra/ajaxDataHotel.php',
                 data:params,
                 success:function(msg)
                 {
                      $('#listResultatHotel').html(msg);
                 }
              });
    }
    
    function getListRestaurant()
    {
        var communeSelected = getCommuneSelected();
        
        var myObject = {
            commune:communeSelected,
            typeid:11154
        };
        var params = $.param(myObject);     
        
        $.ajax({type: "POST",
                 url:'/admin/module_sitra/ajaxDataRestaurant.php',
                 data:params,
                 success:function(msg)
                 {
                      $('#listResultatRestaurant').html(msg);
                 }
              });
    }    
    
    
    function getListEvenement()
    {
        var communeSelected = getCommuneSelected();
        
        var myObject = {
            commune:communeSelected,
            typeid:11155
        };
        var params = $.param(myObject);     
        
        $.ajax({type: "POST",
                 url:'/admin/module_sitra/ajaxDataEvenement.php',
                 data:params,
                 success:function(msg)
                 {
                      $('#listResultatEvenement').html(msg);
                 }
              });          
    }
  
  
    function getListOffice()
    {
        var communeSelected = getCommuneSelected();
        
        var myObject = {
            commune:communeSelected,
            typeid:11156
        };
        var params = $.param(myObject);     
        
        $.ajax({type: "POST",
                 url:'/admin/module_sitra/ajaxDataOffice.php',
                 data:params,
                 success:function(msg)
                 {
                      $('#listResultatOffice').html(msg);
                 }
              });          
    }  
    
    
    
    
    function localiserSt(idSelected)
    {
          //alert('test');
          
          

          //console.log(idSelected);
                          
          $('#carteSt').gmap3(
            { action : 'init', 
              options:{
              mapTypeId : google.maps.MapTypeId.ROADMAP,
              center:{lat: defaultLatitude,lng: defaultLongitude}, 
              zoom: 10,
              scrollwheel: false
              },
                                          
              events:{
                click: function(map, latLng){
                    $('#carteSt').gmap3({ action:'clear', name:'overlay'})
                }
              }
            },
            {
              action:'setStyledMap',
              id:'style1',
              style:[
                      {
                          featureType:'poi.business',
                          stylers: [
                                { visibility: "off" }
                          ]                      
                      }
                    ]
            }
          );
          

          $("#carteSt").gmap3(
              { action:'clear', 
              name:'marker'},
              { action:'clear', 
                name:'overlay'},
              { action:'clear', 
              name:'cluster'}
                
          );
                          
          
          //alert('test');
          $.ajax({
                url:'/genereLocalisationSousTraitant.php',
                data:idSelected,
                dataType: "json",
                type: "POST",
                success:function(data){
                    //$("#carteSt").html(data);
                    
                    //  console.log(data.listMarker);
                    $('#carteSt').gmap3(
                    {
                          action:'addMarkers',
                          markers:data.listMarker,
                          radius:100,
                          clusters:{
                            // This style will be used for clusters with more than 0 markers
                            0: {
                              content: '<div class="cluster clustSt"></div>',
                              width: 29,
                              height: 36
                            },
                            // This style will be used for clusters with more than 20 markers
                            20: {
                              content: '<div class="cluster clustSt"></div>',
                              width: 29,
                              height: 36
                            },
                            // This style will be used for clusters with more than 50 markers
                            50: {
                              content: '<div class="cluster clustSt"></div>',
                              width: 29,
                              height: 36
                            }
                          },
                          cluster:{
                          events:{
                            mouseover:function(cluster,event,data)
                            {
                                //console.log(data);
                                $(this).gmap3(
                                    {action:'clear', name:'overlay'},
                                    {action:'addOverlay',
                                     latLng:data.latLng,
                                     content:'<div class="clusterOver">'+clusterResultatCarte + '<strong>'+data.markers.length+'</strong>'+clusterResultat+'</div>'
                                    }
                                );
                                //console.log(data);
                            },
                            mouseout:function(){
                                $(this).gmap3(
                                    {action:'clear', name:'overlay'});                          
                            }
                          }
                          },                                      
                          marker: {
                            options: {
                              icon: new google.maps.MarkerImage("http://www.haute-savoie-sous-traitance.com/images/carte/pictoSt.png")
                            },
                            events:{
                                click:function(marker, event,data)
                                {
                                     $(this).gmap3(
                                      { action:'clear', 
                                        name:'overlay'},
                                      { action:'panTo', 
                                        args:[marker.getPosition()]},
                                      { action:'addOverlay',
                                        latLng: marker.getPosition(),
                                        content:data.description,
                                        offset:{x:-100,
                                                y:-100},
                                        zindex:500
                                        
                                      }
                                    );
                                }
                            }
                                
                          }                                 
                    }
                  );
                  calculateBoundSt(data.listMarker,true);
                  
                  //FIN SUCCESS  
                  }
                })
                  
            
    }
    
    
    function printInfoWindow()
    {
        $(".containerInfoWindow").printElement();
        return false;
    }
    
    function printListSelection(divToPrint)
    {
        $(divToPrint).printElement();
        return false;
    }
    
    
    function zoomOnMarker(pCarte,pLatitude, pLongitude)
    {
             var myLatlng = new google.maps.LatLng(pLatitude, pLongitude);
             $(pCarte).gmap3(
                {action: 'setCenter', args:[myLatlng]}
             );
             var myMap = $(pCarte).gmap3('get');
             myMap.setZoom(20);
             return false;
    }
