/**
 * On met à jour l'url depuis le formulaire et on initialise l'affichage à chaque mise à jour d'url
 */

var map;
var maptimizeMap;
var geocoder;
var debug;

jQuery(document).ready(function($){
	initHistory();
  $('#geofilter').watermark('Ville, Dpt, Région', {className: 'watermark'});
  $('#valid-filter').hide();
  $('.bloc-filter h2').click(function(){
    $(this).next().toggle();
    $(this).next().next().toggle();
    $(this).parent().toggleClass('open').toggleClass('close');
  });
  $('.bloc-filter .desc-filter').click(function(){
    $(this).prev().toggle();
    $(this).toggle();
    $(this).parent().toggleClass('open').toggleClass('close');
  });
  
  //$('#tags-choice input:checked').parents('div.bloc-filter').addClass('open').removeClass('close').children('p.desc-filter').hide();	
	
	// On ajoute un event show pour initialiser la carte quand on montre la carte
	$('#map-canvas').bind('show',function(e){
		initMap();
	});
	
	// On déclenche l'event au chargement
	$('#map-canvas:visible').trigger("show");
	
	var evt = $.browser.msie ? "click" : "change";
	
	$('#filtering input[type=checkbox]').bind(evt,function(){
		updateFromForm($(this).parents('form'));
	});
	
	// Geoname Search
  var geo_opt = {
    minChars: 2,
    width: 'auto',
    scrollHeight: 300,
    max: 20,
    matchContains: true,
    parse: function(data) {
        var parsed = [];
        data = eval(data);
        for (var i = 0; i < data.length; i++) 
        {
        	parsed[parsed.length] = {
          	data: data[i],
            value: data[i].name,
            result: data[i].name
          };
        }

        return parsed;
    },
    formatItem: function(item) {
      return item.name;
    }
  };
  
  // Pour éviter l'envoi du formulaire en mode carte
  $('#filtering').submit(function(){
  	var frag = $.param.fragment();
  	if (frag.match(/map-canvas/g))
		{
			geocodeAddress();
			return false;
		}
  });

  jQuery('#geofilter')
    .autocomplete('/search-all',geo_opt)
    .result(function(e, data) {
    	var frag = $.param.fragment();
			// reset des précédentes valeurs
    	$('#s_city').val('');
    	$('#s_dpt').val('');
    	$('#s_region').val('');
    	$('#s_cityname').val('');
    	$('#s_regionname').val('');
    	if (data.type == 'city')
    	{
      	$('#s_city').val(data.geonameid);
      	$('#s_cityname').val(data.name);
      }
      else if (data.type == 'dpt')
      {
      	$('#s_dpt').val(data.id);
      }
      else if (data.type == 'region')
      {
      	$('#s_region').val(data.id);
      	$('#s_regionname').val(data.name);
      }
      
      if (frag.match(/map-canvas/g)) // en mode carte
			{
				geocodeAddress();
			}
			else
			{
      	$('#filtering').submit(); // on soumet le formulaire
      }
    }
  );

}); 

function imageURL(img) {
  return "/images/" + img;
};

var Theme = {};
Theme.Default = {
  markerOptions: [
    { icon: new GIcon({ image:            imageURL("maps/pin_turquoise100.png"),
                        iconSize:         new GSize(21, 34),
                        iconAnchor:       new GPoint(11, 34),
                        shadow:           imageURL("maps/shadow50.png"),
                        shadowSize:       new GSize(37, 34),  
                        infoWindowAnchor: new GPoint(12, 34)})
    },
    { icon: new GIcon({ image:            imageURL("maps/pin_orange100.png"),
                        iconSize:         new GSize(21, 34),
                        iconAnchor:       new GPoint(11, 34),
                        shadow:           imageURL("maps/shadow50.png"),
                        shadowSize:       new GSize(37, 34), 
                        infoWindowAnchor: new GPoint(12, 34)})
    },
    { icon: new GIcon({ image:            imageURL("maps/pin_fushia100.png"),
                        iconSize:         new GSize(21, 34),
                        iconAnchor:       new GPoint(11, 34),
                        shadow:           imageURL("maps/shadow50.png"),
                        shadowSize:       new GSize(37, 34), 
                        infoWindowAnchor: new GPoint(12, 34)})
    },
    { icon: new GIcon({ image:            imageURL("maps/pin_gris100.png"),
                        iconSize:         new GSize(21, 34),
                        iconAnchor:       new GPoint(11, 34),
                        shadow:           imageURL("maps/shadow50.png"),
                        shadowSize:       new GSize(37, 34), 
                        infoWindowAnchor: new GPoint(12, 34)})
    },
    { icon: new GIcon({ image:            imageURL("maps/pin_vert100.png"),
                        iconSize:         new GSize(21, 34),
                        iconAnchor:       new GPoint(11, 34),
                        shadow:           imageURL("maps/shadow50.png"),
                        shadowSize:       new GSize(37, 34), 
                        infoWindowAnchor: new GPoint(12, 34)})
    },
    { icon: new GIcon({ image:            imageURL("maps/pin-basic-vert.png"),
                        iconSize:         new GSize(11, 11),
                        iconAnchor:       new GPoint(1, 11),
                        shadow:           imageURL("maps/shadow50.png"),
                        shadowSize:       new GSize(0, 0), 
                        infoWindowAnchor: new GPoint(2, 11)})
    },
    { icon: new GIcon({ image:            imageURL("maps/pin-basic-fushia.png"),
                        iconSize:         new GSize(11, 11),
                        iconAnchor:       new GPoint(1, 11),
                        shadow:           imageURL("maps/shadow50.png"),
                        shadowSize:       new GSize(0, 0), 
                        infoWindowAnchor: new GPoint(2, 11)})
    },
    { icon: new GIcon({ image:            imageURL("maps/pin-basic-turquoise.png"),
                        iconSize:         new GSize(11, 11),
                        iconAnchor:       new GPoint(1, 11),
                        shadow:           imageURL("maps/shadow50.png"),
                        shadowSize:       new GSize(0, 0), 
                        infoWindowAnchor: new GPoint(2, 11)})
    },
    { icon: new GIcon({ image:            imageURL("maps/pin-visited-vert.png"),
                        iconSize:         new GSize(21, 40),
                        iconAnchor:       new GPoint(11, 40),
                        shadow:           imageURL("maps/shadow50.png"),
                        shadowSize:       new GSize(37, 40), 
                        infoWindowAnchor: new GPoint(12, 40)})
    },
    { icon: new GIcon({ image:            imageURL("maps/pin-visited-fushia.png"),
                        iconSize:         new GSize(21, 40),
                        iconAnchor:       new GPoint(11, 40),
                        shadow:           imageURL("maps/shadow50.png"),
                        shadowSize:       new GSize(37, 40), 
                        infoWindowAnchor: new GPoint(12, 40)})
    },
    { icon: new GIcon({ image:            imageURL("maps/pin-visited-turquoise.png"),
                        iconSize:         new GSize(21, 40),
                        iconAnchor:       new GPoint(11, 40),
                        shadow:           imageURL("maps/shadow50.png"),
                        shadowSize:       new GSize(37, 40), 
                        infoWindowAnchor: new GPoint(12, 40)})
    },
  ],
  clusterOptions: [
    {
      icon: new GIcon({ 
        image: imageURL("maps/cluster2.png"),
        iconSize:         new GSize(78, 78),
        iconAnchor:       new GPoint(39, 39),
        infoWindowAnchor: new GPoint(39, 39),
        infoShadowAnchor: new GPoint(39, 39)                             
      }),
      labelClass: 'maptimize_cluster_0', 
      labelOffset: new GSize(-24, -24)
    },
    {
      icon: new GIcon({ 
        image: imageURL("maps/cluster3.png"),
        iconSize:         new GSize(63, 63),
        iconAnchor:       new GPoint(31, 31),
        infoWindowAnchor: new GPoint(31, 31),
        infoShadowAnchor: new GPoint(31, 31)                             
      }),
      labelClass: 'maptimize_cluster_0', 
      labelOffset: new GSize(-24, -24)
    },
    {
      icon: new GIcon({ 
        image: imageURL("maps/cluster4.png"),
        iconSize:         new GSize(48, 48),
        iconAnchor:       new GPoint(24, 24),
        infoWindowAnchor: new GPoint(24, 24),
        infoShadowAnchor: new GPoint(24, 24)                             
      }),
      labelClass: 'maptimize_cluster_0', 
      labelOffset: new GSize(-24, -24)
    },
    {
      icon: new GIcon({ 
        image:"http://betav2.maptimize.com/images/maps/4.png",
        iconSize:         new GSize(56, 56),
        iconAnchor:       new GPoint(28, 28),
        infoWindowAnchor: new GPoint(28, 28),
        infoShadowAnchor: new GPoint(28, 28)                             
      }),
      labelClass: 'maptimize_cluster_0', 
      labelOffset: new GSize(-24, -24)
    },
    {
      icon: new GIcon({ 
        image:"http://betav2.maptimize.com/images/maps/5.png",
        iconSize:         new GSize(53, 53),
        iconAnchor:       new GPoint(26, 26),
        infoWindowAnchor: new GPoint(26, 26),
        infoShadowAnchor: new GPoint(26, 26)                             
      }),
      labelClass: 'maptimize_cluster_0', 
      labelOffset: new GSize(-24, -24)
    },
    
  ],
  createMarker: function(marker) {
    if (marker.getProperty("visited") != true) 
    {
      if (marker.getProperty("type") == 1) {
        return new GMarker(marker.getGLatLng(), Theme.Default.markerOptions[7]);
      }
      if (marker.getProperty("type") == 2) {
        return new GMarker(marker.getGLatLng(), Theme.Default.markerOptions[5]);
      }
      if (marker.getProperty("type") == 3) {
        return new GMarker(marker.getGLatLng(), Theme.Default.markerOptions[6]);
      }
    }
    else
    {
    if (marker.getProperty("type") == 1) {
      return new GMarker(marker.getGLatLng(), Theme.Default.markerOptions[10]);
    }
    if (marker.getProperty("type") == 2) {
      return new GMarker(marker.getGLatLng(), Theme.Default.markerOptions[8]);
    }
    if (marker.getProperty("type") == 3) {
      return new GMarker(marker.getGLatLng(), Theme.Default.markerOptions[9]);
    }
    }
  },  
  createCluster: function(cluster) {
    var total = cluster.getPointsCount();
    var options = Theme.Default.clusterOptions[2];
    if (total > 50)
    {
      options = Theme.Default.clusterOptions[0];
    }
    else if (total <= 50 && total > 10)
    {
      options = Theme.Default.clusterOptions[1];
    }
    
    options.labelText = total;
    return new Maptimize.LabeledMarker(cluster.getGLatLng(), options);
  }
};


/** @author jeremy */
function geocodeAddress(address) 
{
  if (address == null) {
    address = $('#geofilter').val();
  } else {
    address = unescape(address)
  }
  if ($.trim(address) == '') {
    map.returnToSavedPosition();
  } else {
    geocoder.getLocations(address, processGeocoderResponse);
  }
}

/** @author jeremy */
function processGeocoderResponse(response) 
{
  if (!response) {
    showError('Pas de réponse du serveur de géocodage');
  } else if (response.Status.code != 200) {
    switch (response.Status.code) {
    case 400:
      showError("Requête invalide");
      break;
    case 500:
      showError("Erreur sur le serveur de géocodage");
      break;
    case 602:
      showError("Adresse introuvable");
      break;
    case 603:
      showError("Impossible d'afficher l'adresse");
      break;
    default:
      showError(null, response.Status.code);
      break;
    }
  } else {
    $('#geo-errors').hide().html('');
    var results = [];
    window.placemarks = response.Placemark;
    if (response.Placemark.length == 1) 
    {
      place = response.Placemark[0];
      if (checkValidPlace(place)) {
        results.push(place);
      }
    } 
    else 
    {
      $.each(response.Placemark, function(i,place) 
      {
        if (checkValidPlace(place)) {
          results.push(place);
        }
      });
    }
    
    if (results.length == 0) {
      showError("Adresse introuvable en France");
    } else if (results.length == 1) {
      focusMapOnPlace(results[0]);
    } /*else {
      showPlaceChoices(results);
    }*/
  }
}

/** @author jeremy */
function checkValidPlace(place) 
{
  var valid = true;
  // Par défaut un lieu est valide
  if (place.AddressDetails.Country != null && place.AddressDetails.Country.CountryNameCode == "FR") {
    // Le lieu est bien en France
    placeAdminArea = place.AddressDetails.Country.AdministrativeArea;
    if (placeAdminArea != null && placeAdminArea.SubAdministrativeArea != null && placeAdminArea.SubAdministrativeArea.Locality != null) {
      // Il y a une ville
      placeLocality = placeAdminArea.SubAdministrativeArea.Locality;
      if (placeLocality.Thoroughfare != null && placeLocality.Thoroughfare.ThoroughfareName != null ) {
        // il y un nom de rue, c'est donc trop précis
        // valid = false
      }
    }
  } else {
    // Le lieu n'est pas en France
    valid = false;
  }
  return valid;
}

/** @author jeremy */
function focusMapOnPlace(place) 
{
  if (place.AddressDetails.Accuracy >= 5) {
    map.setMapType(G_NORMAL_MAP);
  }

  box = place.ExtendedData.LatLonBox;
  bounds = new GLatLngBounds(new GLatLng(box.south, box.west), new GLatLng(box.north, box.east));
  zoom = map.getBoundsZoomLevel(bounds);
  
  point = new GLatLng(place.Point.coordinates[1],
                      place.Point.coordinates[0]);
  
  map.setCenter(point, zoom);
}

/** @author jeremy */
function showError(text,code) 
{
  if (code != null) {
    html = 'Error ' + code + ' : ' + text;
  } else {
    html = text;
  }
  $('#geo-errors').html("<p class=\"error\">" + html + "</p>").show();
};

function updateFromForm(e)
{
  // placer l'update analytics ici pour compter les maj de la carte.
  var url = window.location.href;
  if (!url.match(/frontend_/g))
  {
    _gaq.push(['_trackPageview', 'searchCarteAjax']);
  }
  
	var frag = $.param.fragment();
	if (frag.match(/map-canvas/g))
	{
	  var b = getBox();
    var center = map.getCenter();
		var c = 'center='+center.lat()+','+center.lng()+'&';
		var to = '#to=map-canvas&zoom='+map.getZoom()+'&'+b+c;
		window.location = to+e.serialize();
	}
	else
	{
		e.submit();
	}	
}

function getBox()
{
  var box = map.getBounds();
  return 'box='+box.getNorthEast().lat() +','+box.getNorthEast().lng()+','+box.getSouthWest().lat()+','+box.getSouthWest().lng()+'&';
}

initMap = function()
{
	map = new GMap2(document.getElementById('map-container'));
	map.setCenter(new GLatLng(46.227638, 2.213749), 5);
	map.savePosition();
  map.setUIToDefault();
  //map.setMapType(G_PHYSICAL_MAP);
  map.disableScrollWheelZoom();
  	
  // Attach maptimize plugin
 	maptimizeMap = new Maptimize.Map(map, {
    onClusterClicked: function(cluster) {
      if (cluster.canExpandOnMap()) {
        var zoom    = map.getZoom(),
            newZoom = map.getBoundsZoomLevel(cluster.getGLatLngBounds());

        if (newZoom >= (zoom + 1)) 
          newZoom = zoom + 2; 
        
        map.setCenter(cluster.getGLatLngBounds().getCenter(), newZoom);

      } else {
        cluster.openPopup();
      }
    },
    theme: Theme.Default    
  });
  maptimizeMap.setMarkerProperties(['type', 'visited', 'price']);
 	  
  GEvent.addListener(map,'zoomend',function(){
    updateFromForm($('#filtering'));
  });
  
  GEvent.addListener(map,'dragend',function(){
    updateFromForm($('#filtering'));
  });
  
  GEvent.addListener(map,'movend',function(){
    updateFromForm($('#filtering'));
  });
  
  GEvent.addListener(map, 'afterRefresh', function() {
    showResultsLoaded(maptimizeMap.getTotalPointsCount());
  });
    
  geocoder = new GClientGeocoder();
  geocoder.setBaseCountryCode('fr');
  var frag = $.param.fragment();
	if (frag.match(/box=/g)) // si on a une box on fait juste un update
	{
    updateConditions();
  }
  else
  {
    updateFromForm($('#filtering'));
  }
}

function initHistory()
{
  var cache = {
    '': $('#result'),
    'map-canvas': $('#map-canvas'),
    'result' : $('#result')
  };
  
  $(window).bind('hashchange', function(e) {   
    var urls = $.deparam.fragment(); 
    var url = urls['to'];
    var target = $('.tab-current').attr('href');
    if (!url) url = 'result';   
    
    // On met à jour les liens de changement de vue pour garder les conditions
 		$('#show-carte').attr('href','#to=map-canvas&'+$('#filtering').serialize());
 		$('#show-result').attr('href','#to=result&'+$('#filtering').serialize());

    if (!target || target.indexOf(url) < 0) // Seulement si il y a un changement de cible
    {     
    	$('li', '#toggle-display').toggleClass('ui-tabs-selected ui-state-active');
    	$('.tab-content').children('div:visible').hide();    
    	    	
    	// On ajoute la classe tab-current pour cacher le lien qui pointe vers le div qu'on va montrer
    	url && $('a[href*="to=' + url + '"]').addClass('tab-current');    
    	
			// On affiche le div cible    
    	if (cache[url]) 
    	{      
      	cache[url].show();
      	$('#map-canvas').trigger("show");            
    	}
    }    
    else if (url == 'map-canvas') // Si pas de changement mais carte en cible, on remet à jour les conditions
    {
    	updateConditions();
    }
  });
  
  $(window).trigger('hashchange');
}

updateConditions = function() {
	var p = $.deparam.fragment();
  var condition = new Maptimize.Condition();
  
  var alltags = {
  	0: ['1','2','3','4','5','6','7'],
  	1: ['8','9','10','11','12'],
  	2: ['13','14','15','16','17'],
  	3: ['18','19','20','21'],
  	4: ['22','23','24','25']
  }; //json à faire générer en PHP pour une meilleure intégration

	// on regarde l'url et vérifie les conditions pour mettre à jour la carte
	//alert(p['s'] && p['s']['prices']);
	// prices
  if (p['s'] && p['s']['prices'])
  {    
    var conditionPrice = new Maptimize.Condition();
  	if (jQuery.inArray('0',p['s']['prices']) >= 0) 
  	{
  		conditionPrice.appendOr("price >= ? AND price <= ?", 0, 50);
  		$('#s_prices_0').attr('checked',true);
  	}
  	else
  	{
  		$('#s_prices_0').attr('checked',false);
  	}
  
  	if (jQuery.inArray('1',p['s']['prices']) >= 0) 
  	{
  		conditionPrice.appendOr("price >= ? AND price <= ?", 50, 75);
  		$('#s_prices_1').attr('checked',true);
  	}
  	else
  	{
  		$('#s_prices_1').attr('checked',false);
  	}
  
  	if (jQuery.inArray('2',p['s']['prices']) >= 0) 
  	{
  		conditionPrice.appendOr("price >= ? AND price <= ?", 75, 100);
  		$('#s_prices_2').attr('checked',true);
 	 	}
 	 	else
  	{
  		$('#s_prices_2').attr('checked',false);
  	}
  
  	if (jQuery.inArray('3',p['s']['prices']) >= 0) 
  	{
  		conditionPrice.appendOr("price >= ? AND price <= ?", 100, 150);
  		$('#s_prices_3').attr('checked',true);
  	}
  	else
  	{
  		$('#s_prices_3').attr('checked',false);
  	}
  	
  	if (jQuery.inArray('4',p['s']['prices']) >= 0)
  	{
  		conditionPrice.appendOr("price >= ?", 150);
  		$('#s_prices_4').attr('checked',true);
  	}
  	else
  	{
  		$('#s_prices_4').attr('checked',false);
  	}
  	
  	if (jQuery.inArray('5',p['s']['prices']) >= 0) 
  	{
  		conditionPrice.appendOr("price = null");
  		$('#s_prices_5').attr('checked',true);
  	}
  	else
  	{
  		$('#s_prices_5').attr('checked',false);
  	}
  }
  else // Sinon reset toutes les checkboxes
  {
  	$("#prices-choice input").attr('checked',false);
  }
  
  // tags
  if (p['s'] && p['s']['tags'])
  {  	
  	$.each(alltags,function(i,e){  	  
  	  if (p['s']['tags'][i])
  	  {
  	    var conditionTag = Maptimize.Condition();
  		  $.each(e,function(j,f){
  			  if (p['s']['tags'][i] && jQuery.inArray(f,p['s']['tags'][i]) >= 0)
  			  {
  				  conditionTag.appendOr("tags HAS "+f);
  				  $('#s_tags_'+i+'_'+f).attr('checked', true);
  			  }
  			  else
  			  {
  				  $('#s_tags_'+i+'_'+f).attr('checked', false);
  			  }
  		  });
  		  condition.appendAnd(conditionTag.toString());    		
		  }
  	});
  }
  else // Sinon reset toutes les checkboxes
  {
  	$("#tags-choice input").attr('checked',false);
  }
  
  // visited
  if (p['s'] && p['s']['visited'])
  {
  	if (jQuery.inArray('0',p['s']['visited']) >= 0)
  	{
  		condition.appendAnd("visited = true");
  		$('#s_visited_0').attr('checked', true);
  	}
  }
  else
  {
  	$('#s_visited_0').attr('checked', false);
  }
  
  // type (voir pour faire une sous condition)
  if (p['s'] && p['s']['ppal_t'])
  {
    var conditionType = new Maptimize.Condition();
  	if (jQuery.inArray('1',p['s']['ppal_t']) >= 0)
  	{
  		conditionType.appendOr("type = ?", 1);
  		$('#s_ppal_t_1').attr('checked',true);
  	}
  	else
  	{
  		$('#s_ppal_t_1').attr('checked',false);
  	}
  	
  	if (jQuery.inArray('2',p['s']['ppal_t']) >= 0)
  	{
  		conditionType.appendOr("type = ?", 2);
  		$('#s_ppal_t_2').attr('checked',true);
  	}
  	else
  	{
  		$('#s_ppal_t_2').attr('checked',false);
  	}
  	
  	if (jQuery.inArray('3',p['s']['ppal_t']) >= 0)
  	{
  		conditionType.appendOr("type = ?", 3);
  		$('#s_ppal_t_3').attr('checked',true);
  	}
  	else
  	{
  		$('#s_ppal_t_3').attr('checked',false);
  	}
  }
  else
  {
    $('#s_ppal_t_1').attr('checked',false);
    $('#s_ppal_t_2').attr('checked',false);
    $('#s_ppal_t_3').attr('checked',false);
  }
  
  // geoloc
  if (p['s'])
  {
    if (p['s']['dpt'])
    {
      resetGeoloc();
      geocodeAddress(p['s']['dpt']);
    }
    else if (p['s']['cityname'])
    {
      resetGeoloc();
      geocodeAddress(p['s']['cityname']);
    }    
    else if (p['s']['regionname'])
    {
      resetGeoloc();
      geocodeAddress(p['s']['regionname']);
    }
  }
  
  // box
  if (p['box'])
  {
  	var box = p['box'].split(',');
  	var bounds = new GLatLngBounds(new GLatLng(box[2], box[3]), new GLatLng(box[0], box[1]));
  }
  
  // center
  if (p['center'])
  {
  	var center = p['center'].split(',');
  	if (bounds)
  	{
  		var zoom = map.getBoundsZoomLevel(bounds); 
  		var point = new GLatLng(center[0],center[1]);  
  		map.setCenter(point, zoom);
  	}
  }
  
  updateTitle();
  if (conditionPrice) condition.appendAnd(conditionPrice.toString());
  if (conditionType) condition.appendAnd(conditionType.toString());
  maptimizeMap.setCondition(condition.toString());  
  maptimizeMap.refresh();
}

function showResultsLoaded(count) 
{
  if (parseInt(count, 10) == 0) {
    text = "Aucune";
  } 
  else 
  {
    text = count;
  }
  $('#results-count').html(text).show();
}

function resetGeoloc()
{
  $('#s_city').val('');
	$('#s_dpt').val('');
	$('#s_region').val('');
	$('#s_cityname').val('');
	$('#s_regionname').val('');
}

function updateTitle()
{
  $('#resume').load('search/searchTitle?'+$('#filtering').serialize());
}
