/**
 * @author CD
**/
CCVUMap = function(){};
CCVUMap.prototype = {

  map: null,
  gmc: null,
  initialbounds: null,
  labels: null,
  ginfowindow: null,
  glistcontrol: null,
  glisthebergtext: null,
  gtargeticon: null,
  gtarget: null,
  points: null,
  myLatlng: null,
  getJsonPtsUrl: null,

  mapElementId: null,
  formElement: null,
  totalElement: null,
  toggleElement: null,
  ongletElements: null,
  ongletSelector: null,
  filtresElementSelector: null,
  dataNameKey: null,
  dataNameCategorie: null,
  ongletActifClass: null,
  inputNameCategorie: null,
  filtresActifsElement: null,

  groupPicto: null,
  targetPicto: null,

  initialize: function(data) {
    var self = this;
    jQuery.each(data,function(i,e){self[i] = e;});
    CCVUMap.labels = data.labels;

    this.ginfowindow = new google.maps.InfoWindow({});
    this.myLatlng = new google.maps.LatLng(44.39, 6.65);
    this.map = new google.maps.Map(document.getElementById(this.mapElementId), {
      zoom: 9,
      center: this.myLatlng,
      mapTypeControl: true,
      streetViewControl: false,
      navigationControl: true,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    jQuery("a.checkall",this.formElement).click(function(e){
      e.preventDefault();
      jQuery(this).parent().find("input[type=checkbox]").attr({checked:!jQuery(this).hasClass("uncheck")});
      self.getJsonPts();
    });

    jQuery("input[type=checkbox]",this.formElement).click(function(e){
      self.getJsonPts();
    });

    this.toggleElement.click(function(e){
      e.preventDefault();
      var formWidth = self.formElement.width();
      var mapWidth = jQuery("#"+self.mapElementId).width();
      if (self.formElement.is(':visible')) {
        jQuery(self.formElement).hide();
        jQuery("#"+self.mapElementId).width(mapWidth+formWidth);
        self.noResultsElement.width(mapWidth+formWidth);
        jQuery(this).html('&laquo;');
      } else {
        jQuery(self.formElement).show();
        jQuery("#"+self.mapElementId).width(mapWidth-formWidth);
        self.noResultsElement.width(mapWidth-formWidth);
        jQuery(this).html('&raquo;');
      }
      google.maps.event.trigger(self.map,'resize');
    });

    jQuery(this.ongletSelector,this.formElement).click(function(e){
      e.preventDefault();
      jQuery("a."+self.ongletActifClass, self.formElement).removeClass(self.ongletActifClass);
      jQuery(this).addClass(self.ongletActifClass);//jQuery(this).parent().append(jQuery(this).addClass(self.ongletActifClass));
      jQuery(self.filtresElementSelector,self.formElement).hide();
      jQuery(self.filtresElementSelector + " input", self.formElement).attr({disabled:true});
      self.filtresActifsElement = jQuery(self.filtresElementSelector + jQuery(this).data(self.dataNameKey), self.formElement).slideDown();
      jQuery("input[name="+self.inputNameCategorie+"]",self.formElement).val(jQuery("a."+self.ongletActifClass,self.formElement).data(self.dataNameCategorie));
      jQuery(self.filtresElementSelector + jQuery(this).data(self.dataNameKey) + " input", self.formElement).attr({disabled:false});
      self.getJsonPts();
    }).first().click();
  },

  getJsonPts: function() {

    this.noResultsElement.css({
      'width':       jQuery("#"+this.mapElementId).width()+'px',
      'line-height': jQuery("#"+this.mapElementId).height()+'px'
    });

    var checkboxCheched = true;
    jQuery("table.tzr-checkboxtable",this.filtresActifsElement).each(function(i,table){
      if (!jQuery("input[type=checkbox]:checked",table).length) checkboxCheched = false;
    });
    if (!checkboxCheched) {
      if (this.gmc != null) this.gmc.clearMarkers();
      this.noResultsElement.fadeIn();
      this.totalElement.html(0);
      return;
    }
    this.noResultsElement.fadeOut('fast');
    var formData = this.formElement.serializeArray();

    var self = this;
    jQuery.get(this.getJsonPtsUrl,formData,function(data){
      points = jQuery.parseJSON(data);
      if (self.gmc != null) self.gmc.clearMarkers();
      google.maps.event.trigger(self.map,'resize');
      if (points && points.length) {
        self.addLieux(points);
        self.totalElement.html(points.length);
      }
      else {
        try { centerMap(); } catch(e){}
        self.noResultsElement.fadeIn();
        self.totalElement.html(0);
      }
    });
  },

  centerMap: function() {
    this.map.fitBounds(myLatlng);
  },

  addLieux: function(lieux) {
    var regrouppicto =  {
      url: this.groupPicto,
      height: 28,
      width: 28,
      opt_anchor: [8, 0],
      opt_textColor: '#FFFFFF',
      opt_textSize: 9
    };
    var mcostyles = [regrouppicto,regrouppicto,regrouppicto];

    var mco = {gridSize: 25, maxZoom: 15, zoomOnClick:true};
    mco.styles = mcostyles;
    if (this.gmc == null) {
      this.gmc = new MarkerClusterer(this.map, null, mco);
    } else {
      this.gmc.clearMarkers();
    }

    var bounds = new google.maps.LatLngBounds();
    var position = null;
    for (var i = 0; i < lieux.length; i++) {
      var coordx = lieux[i].coordx.split(";");
      if (coordx.length < 2)
        continue;
      var lat = parseFloat(coordx[0]);
      var lng = parseFloat(coordx[1]);
      if (isNaN(lat) || isNaN(lng))
        continue;
      position = new google.maps.LatLng(lat, lng);
      bounds.extend(position);
      var marker = new google.maps.Marker({
        title: lieux[i].titre,
        position: position,
        icon: new google.maps.MarkerImage(
                lieux[i].icon,
                new google.maps.Size(32, 40),
                new google.maps.Point(0,0))
      });
      marker.description = (lieux[i].imageResizer || lieux[i].imageEteResizer ? '<div class="image" style="float:right"><img src="'+(lieux[i].imageEteResizer && site.saison == 'ete' ? lieux[i].imageEteResizer : lieux[i].imageResizer)+'&geometry=140x%3E"></div>' : '')
       + '<div class="titre"><strong>'+lieux[i].titre+'</strong></div>'
       + '<p>'+lieux[i].resume+'</p>'
       + '<p class="adresse">'
       + (lieux[i].adresse ? lieux[i].adresse+'<br>'+lieux[i].cp+' '+lieux[i].ville+'<br>' : '')
       + (lieux[i].tel ? 'Tel: '+lieux[i].tel+'<br>' : '')
       + (lieux[i].fax ? 'Fax: '+lieux[i].fax+'<br>' : '')
       + '</p>'
       + '<a href="'+lieux[i].url+'">'+CCVUMap.labels.carto_voir_detail+'</a>';
      lieux[i].marker = marker;
      var self = this;
      google.maps.event.addListener(marker, 'click', function() {
        self.infoWinH(this);
      });
      this.gmc.addMarker(marker);
    }
    //  map.fitBounds(bounds);
    //setTimeout("map.setZoom(map.getZoom()+2)", 500);
    initialbounds = bounds;
  },

  // Evenement déclenche au click sur un element dans une liste multiple
  mInfoWinH: function(lat, lng, description, iconUrl){
    this.ginfowindow.close();
    this.ginfowindow.setContent('<img src="'+iconUrl+'" alt="" />' + description);
    this.ginfowindow.open(this.map);
    this.ginfowindow.setPosition(new google.maps.LatLng(lat, lng));
    return false;
  },

  // Evenement Declanche au click sur l'icon de l'element
  infoWinH: function(marker) {
    this.ginfowindow.close();
    this.ginfowindow.setContent('<div class="infoWindowContent">'+marker.description+'</div>');
    this.ginfowindow.open(this.map, marker);
    return false;
  },

  setMapType: function(type) {
    this.map.setMapTypeId(google.maps.MapTypeId[type]);
  },

  zoomTo: function(oid, lat, lng) {
    var p = new google.maps.LatLng(lat, lng);
    var m = null;

    if (this.gtargeticon == null)
      this.gtargeticon = new google.maps.MarkerImage(this.targetPicto, new google.maps.Size(20, 20));

    this.gtarget = new google.maps.Marker({
      title:'',
      zIndex:+999,
      position:p,
      map:this.map,
      icon:this.gtargeticon
    });
    var self = this;
    setTimeout(function(){self.gtarget.setMap(null);}, 1500);
    this.map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
    this.map.panTo(p);
    this.map.setZoom(25);
  }
};


