$(function() {
	
	/**
	* Pop-up du moteur de recherche
	*/
	$('#moteur_popup').dialog({ autoOpen: false, resizable: false, modal:true, width: 600 });
	
	/**
	 * Autocomplete FB pour la géolocalisation (sur la home et dans la recherche)
	 * Le remplissage automatique n'est déclenché que s'il y a une valeur présente dans l'input
	 */
	
	var fbac_geo_el = $('#geo_objets_ids.autocomplete') ;
	var fbac_geo_init = function(el, data) {
		data = data || [] ;
		var options = {
			hintText         : "Région, code postal, département, ville, pays, ...",
			noResultsText    : "Aucune ville ne correspond",
			searchingText    : "Recherche...",
			prePopulate      : data,
			preventDuplicates: true,
			theme            : 'facebook'
		} ;
		if (el.hasClass('colocataire'))
			options.tokenLimit = 1 ;
		if (el.parent('div').attr('id') == 'geo_objets_edit') {
			options.onAdd = function() {
				el.closest('form').submit() ;
			} ;
		}
		el.tokenInput('/index/ac-geo', options) ;
	} ;
	if (fbac_geo_el.length > 0) {
		if (fbac_geo_el.val()) {
			$.getJSON('/index/ac-geo-init?ids='+fbac_geo_el.val(), function(data) {
				fbac_geo_init(fbac_geo_el, data) ;
			}) ;
		} else {
			fbac_geo_init(fbac_geo_el) ;
		}
	}
	
	/**
	 * Autocomplete FB pour les métros (sur la home et dans la recherche)
	 * Le remplissage automatique n'est déclenché que s'il y a une valeur présente dans l'input
	 */
	
	var fbac_transport_el = $('#transport_objets_ids.autocomplete') ;
	var fbac_transport_init = function(el, data) {
		data = data || [] ;
		var options = {
			hintText         : "Indiquez une ligne ou une station de métro (Île-de-France seulement)",
			noResultsText    : "Aucune ligne ou station de métro ne correspond",
			searchingText    : "Recherche...",
			prePopulate      : data,
			preventDuplicates: true,
			theme            : 'facebook'
		} ;
		if (el.parent('div').attr('id') == 'transport_objets_edit') {
			options.onAdd = function() {
				el.closest('form').submit() ;
			} ;
		}
		el.tokenInput('/index/ac-transport', options) ;
	} ;
	if (fbac_transport_el.length > 0) {
		if (fbac_transport_el.val()) {
			$.getJSON('/index/ac-transport-init?ids='+fbac_transport_el.val(), function(data) {
				fbac_transport_init(fbac_transport_el, data) ;
			}) ;
		} else {
			fbac_transport_init(fbac_transport_el) ;
		}
	}
	
	/**
	 * Lien caché
	 * Ca épargne à google de passer sur un lien inutile
	 */
	
	$('.afake').click(function(ev) {
		if ($(this).metadata().href) {
			document.location = $(this).metadata().href ;
		}
	}) ;
	
	/**
	 * Sélection du produit dans le formulaire
	 */
	
	$('#home_annonces_moteur #produit').change(function() {
		if ($(this).val().substr(0,7) === 'http://') {
			document.location = $(this).val() ;
		} else {
			$('#home_annonces_moteur_formulaire').load('/index/moteur-'+$(this).val(), function() {
				// Initialisation de la géolocalisation
				fbac_geo_init($('#geo_objets_ids.autocomplete')) ;
				
				// Lien "plus de choix" sur le formulaire
				$('#home_plus_de_choix').click(function() {
					$('#home_annonces_moteur :image[value=criteres]').click() ;
				}) ;
				
				// Affichage de la carte (ou pas)
				if ($('#home_annonces_moteur_formulaire .autocomplete').length > 0)
					$('#home_annonces_moteur_carte').show() ;
				else
					$('#home_annonces_moteur_carte').hide() ;
			}) ;
		}
	}) ;
	$('#home_annonces_moteur #produit').change() ;
	
	/**
	 * Submit du formulaire de la page d'accueil
	 */
	$('#home_annonces_moteur :image').click(function() {
		// popup localisation
		
		var produit = $('#produit').val();
		if ( produit == "vente"  || produit == "location"  || produit == "colocation") {
			if ( $(this).val() != "criteres" && $(this).val()!= "more criteria") {
				var ids = $('#geo_objets_ids.autocomplete').val();
				if (!ids) {
				  $('#moteur_popup').dialog('open');
				  return false;
				}
			}
		}

		$('#home_annonces_moteur_submit').val($(this).val()) ;
		$(this).closest('form').submit() ;
	}) ;
	
	/**
	 * Carte de france sur la home de la version anglaise
	 */
	
	$('#regions area').click(function(ev) {
		var ids = $('#geo_objets_ids.autocomplete').val() + ',' + $(this).attr('id').replace(/regions_/, '') ;
		$('#geo_objets_ids.autocomplete').closest('td').empty().append('<input type="text" class="autocomplete" name="geo_objets_ids" id="geo_objets_ids" size="40" value="'+ids+'" />') ;
		$.getJSON('/index/ac-geo-init?ids='+$('#geo_objets_ids.autocomplete').val(), function(data) {
			fbac_geo_init($('#geo_objets_ids.autocomplete'), data) ;
		}) ;
	}) ;
	
	/***************************************************************************
	*** Points Annonces
	****************************************************************************
	
	/** Carte GMaps **/
	if ($('#map_canvas').length > 0) {

		var options = {
			mapTypeId: google.maps.MapTypeId.HYBRID,
			mapTypeControl: true,
			center : new google.maps.LatLng(
				parseFloat($('#map_canvas').attr('lat')),
				parseFloat($('#map_canvas').attr('lng')) 
			),
			zoom : parseInt($('#map_canvas').attr('zoom'))
		} ;
		
		var map = new google.maps.Map(document.getElementById('map_canvas'), options ) ;
		var marker = new google.maps.Marker({position: map.getCenter(), map: map });
	}

	/***************************************************************************
	 *** Contenu
	 ***************************************************************************/
	
	/** Enquête **/
	
	$('#enquete_ville').autocomplete({
		source: '/index/ac-geo',
		minLength: 2
	}) ;
	
	/** Produits **/
	
	$("#jcarousel-produits").each(function() {
		$(this).jcarousel({start:$(this).metadata().jcarousel_start, scroll:$(this).metadata().jcarousel_scroll}) ;
	}) ;
	
	/***************************************************************************
	 *** Divers
	 ***************************************************************************/
	
	/** on cache les éléments de class 'hide' **/
	$('.hide').hide() ;
	
	/** pagination référencement **/
	if($('.nb-annonces').length > 0)
		$('#pagination-referencement').hide() ;
		
	/** Toggle simple des éléments **/
	$('.toggler').click(function(){
		$('#'+ $(this).metadata().toggled_id).slideToggle() ;
		return false ;
	}) ;
	
	/** popup **/
	$('.popup').click(function(){
		window.open('', $(this).attr('target'), "height = " + $(this).metadata().popup_height + " ,width=" + $(this).metadata().popup_width + " ,scrollbars= " + $(this).metadata().popup_scrollbars) ; 
	}) ;
	
	/** Text area counter **/
	var count = function($textarea){
		$label = $('#label_' + $textarea.attr('id')+'_counter') ;
		maxlength = $textarea.metadata().textarea_counter_max ;
		curlength = $textarea.val().length ;
		remaining = Math.max(maxlength - curlength, 0) ;
		$('.remaining', $label).text(remaining) ;
		$('.curlength', $label).text(curlength) ;
		$label
			.toggleClass('ok', maxlength >= curlength)
			.toggleClass('ko', maxlength <  curlength)
			;
	}
	// Ajout du compteur
	$('.textarea_counter').each(function(){
		
		$label     = $('<p id="label_' + $(this).attr('id')+'_counter"' +'>') ;
		$container = $('<div>').addClass('counter').attr('id', $(this).attr('id')+'_counter') ;
		$(this).wrap($container) ;
		$label.insertBefore($(this)) ;
		texte = "Reste : <span class='remaining'></span> caract&egrave;res (<span class='curlength'></span> / <span class='maxlength'>" + $(this).metadata().textarea_counter_max + "</span>)" ;
		texte = texte + " - Nous n'acceptons pas les abréviations." ; 
		
		// init
		$label.html(texte) ;
		count($(this)) ;
		
		// events
		var interval ; 
		$(this).bind({
			focus: function() {
				$textarea = $(this) ;
				interval = setInterval(function(){
					count($textarea) ;
					}
				, 333) ;
			},
			blur: function() {
				clearInterval(interval) ;
			}
		});
	}) ;
	
	/** Gestion du panier **/
	
	$('.panier-enable').click(function(){
		setPanier(1, $(this).metadata().annonce_id) ;
	}) ;

	$('.panier-disable').click(function(){
		setPanier(0, $(this).metadata().annonce_id) ;
	}) ;

	setPanier = function (panier, annonces_id) {
		$.ajax({
			url:  '/ajax/panier-set.php',
			type :'POST',
			data: {
				panier: panier, 
				annonces_id: annonces_id
			},
			success: function(html) {
				if ($('#annonce_'+annonces_id)) {
					if (panier)
						$('#annonce_resume_'+annonces_id).addClass('annonce-panier') ;
					else
						$('#annonce_resume_'+annonces_id).removeClass('annonce-panier') ;
				}
				if ($('#annonce_detail')) {
					if (panier)
						$('#annonce_detail').addClass('annonce-panier') ;
					else
						$('#annonce_detail').removeClass('annonce-panier') ;
				}
				if (!panier && window.location.pathname.substring(0, 8) == '/panier/') // quand on est dans le panier
					window.location.reload() ;
			}
		}) ;
	} ;
	
	/***************************************************************************
	 *** Espace utilisateur
	 ***************************************************************************/
	
	$('.recherche_update_label_perso').each(function() {
		$(this).editable($(this).attr('href'), {
			type      : 'text',
			cancel    : 'Annuler',
			submit    : 'OK',
			indicator : 'Sauvegarde...',
			tooltip   : 'Cliquer pour modifier',
		}) ;
     }) ;
     
     $('.recherche_update_alerte_iphone').each(function() {
		$(this).editable($(this).attr('href'), {
			type      : 'select',
			data      : $(this).metadata(),
			cancel    : 'Annuler',
			submit    : 'OK',
			indicator : 'Sauvegarde...',
			tooltip   : 'Cliquez pour modifier',
		}) ;
     }) ;
     
     $('.recherche_update_alerte_email').each(function() {
		$(this).editable($(this).attr('href'), {
			type      : 'select',
			data      : $(this).metadata(),
			cancel    : 'Annuler',
			submit    : 'OK',
			indicator : 'Sauvegarde...',
			tooltip   : 'Cliquez pour modifier',
		}) ;
     }) ;
     
}) ;

