$(function() {
	/* AUTOCOMPLETE */
	$('#localite').autocomplete({
		source: 'controllers/ajax/search.php',
		delay: 200,
		minLength: 3,
		select: function(event, ui) {
			$('#ville').attr('value', ui.item.id);
			$('#recherche_form #nom, #agence').val('');
		}
	});
	
	$('#recherche_form #nom').autocomplete({
		source: 'controllers/ajax/search_agence.php',
		delay: 200,
		minLength: 3,
		select: function(event, ui) {
			$('#agence').attr('value', ui.item.id);
			$('#localite, #ville').val('');
		}
	});
	
	/* SLIDER PRIX */
	$("#slider_prix").slider({ from: 0, to: 1000000, step: 10000, dimension: '&nbsp;€' });
	
	/* SLIDER SURFACE */
	$("#slider_surface").slider({ from: 0, to: 500, step: 10, dimension: '&nbsp;m²' });
	
	/* CAROUSEL ACCUEIL */
	var page = 1;
	var active = false;
	$('#dernieres_annonces_droite, #dernieres_annonces_gauche').click(function(){
		
		if(!active){
			active = true;
			var direction = (($(this).attr('id') == 'dernieres_annonces_droite') ? 'droite' : 'gauche');
			
			if(direction == 'gauche' && page == 1){
				active = false;
				return false;
			}
			page = ((direction == 'gauche') ? page-1 : page+1);
			
			$('#dernieres_annonces_loading').css('visibility', 'visible');
			
			$.ajax({
				type: 'POST',
				url: "controllers/ajax/carousel.php",
				data: 'page='+page,
				dataType : 'json',
				success: function(list_biens){
					if(list_biens.length == 3){
						//On remonte les 3
						$('#dernieres_annonce_'+((direction == 'droite') ? 1 : 3)+' div:first-child').animate({'margin-top': -200, 'opacity': 0});
						$('#dernieres_annonce_2 div:first-child').delay(150).animate({'margin-top': -200, 'opacity': 0});
						$('#dernieres_annonce_'+((direction == 'droite') ? 3 : 1)+' div:first-child').delay(300).animate({'margin-top': -200, 'opacity': 0}, function(){
							window.setTimeout(function() {
								
								$(list_biens).each(function(k, list_bien){
									//Images
									$('#dernieres_annonce_'+(k+1)+' img').attr('src', list_bien['thumb']);
									$('#dernieres_annonce_'+(k+1)+' img').attr('alt', list_bien['alt']);
									//Accroche
									$('#dernieres_annonce_'+(k+1)+' .h5 a').html(list_bien['accroche']);
									$('#dernieres_annonce_'+(k+1)+' .h5 a').attr('href', list_bien['url']);
									//Prix
									$('#dernieres_annonce_'+(k+1)+' .somme').html(list_bien['prix']+' <a href="'+list_bien['url']+'">Détails</a>');
									//Prix
									$('#dernieres_annonce_'+(k+1)+' p').html(list_bien['descriptif_court']);
								});
								
								//On redescend les 3
								$('#dernieres_annonce_'+((direction == 'droite') ? 1 : 3)+' div:first-child').animate({'margin-top': 0, 'opacity': 1});
								$('#dernieres_annonce_2 div:first-child').delay(150).animate({'margin-top': 0, 'opacity': 1});
								$('#dernieres_annonce_'+((direction == 'droite') ? 3 : 1)+' div:first-child').delay(300).animate({'margin-top': 0, 'opacity': 1}, function(){
									$('#dernieres_annonces_loading').css('visibility', 'hidden');
									$('.dernieres_annonces_move').removeAttr('style');
									active = false;
								});
							}, 300);
						});
					} else {
						$('#dernieres_annonces_loading').css('visibility', 'hidden');
						$('.dernieres_annonces_move').removeAttr('style');
						active = false;
					}
				}
			});
		}
		return false;
	});
	
	$('.dernieres_annonces_img').click(function() {
		location.href = $(this).parents('.annonce').find('a').eq(0).attr('href');
	});
	
	/* BOUTONS PARTAGE */
	$('.home_share').hover(
		function(){
			$(this).parents('.menu_content').find('.home_share_buttons').stop(true, true).fadeIn();
		},
		function(){
			$(this).parents('.menu_content').find('.home_share_buttons').stop(true, true).fadeOut();
		}
	);
	
	/* ENVOYER A UN AMI */
	var nom_expediteur = $('#nom_expediteur');
	var nom_destinataire = $('#nom_destinataire');
	var mail_destinataire = $('#mail_destinataire');
	var allFields = $([]).add(nom_expediteur).add(nom_destinataire).add(mail_destinataire);
	var tips = $('.validateTips');
	
	function updateTips( t ) {
		tips
			.text( t )
			.addClass( "ui-state-highlight" );
		setTimeout(function() {
			tips.removeClass( "ui-state-highlight", 1500 );
		}, 500 );
	}
	
	function checkLength( o, n, min, max ) {
		if ( o.val().length > max || o.val().length < min ) {
			o.addClass( "ui-state-error" );
			updateTips( "Le champ " + n + " doit comporter entre " +
				min + " et " + max + " caractères." );
			return false;
		} else {
			return true;
		}
	}
	
	function checkRegexp( o, regexp, n ) {
		if ( !( regexp.test( o.val() ) ) ) {
			o.addClass( "ui-state-error" );
			updateTips( n );
			return false;
		} else {
			return true;
		}
	}
	
	$('#dialog-form').dialog({
		autoOpen: false,
		height: 300,
		width: 500,
		modal: true,
		buttons: {
			'Envoyer': function() {
				var bValid = true;
				allFields.removeClass('ui-state-error');
				
				bValid = bValid && checkLength(nom_expediteur, 'Nom de l\'expéditeur', 1, 70);
				bValid = bValid && checkLength(nom_destinataire, 'Nom du destinataire', 1, 70);
				bValid = bValid && checkLength(mail_destinataire, 'Adresse e-mail de l\'expéditeur', 1, 70);
				bValid = bValid && checkRegexp(mail_destinataire, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "Adresse e-mail de l\'expéditeur non valide. Ex : prenom.nom@hotmail.fr" );
				
				if (bValid) {
					$.ajax({
						type: 'post',
						data: { nom_expediteur: nom_expediteur.val(), nom_destinataire: nom_destinataire.val(), mail_destinataire: mail_destinataire.val(), id: id },
						url: 'controllers/ajax/envoyer_ami.php',
						success: function(retour){
							if(retour == 'true')
								$('#dialog-message').html('<p style="color: green; font-size: 80%;">Votre message a bien été envoyé.</p>');
							else
								$('#dialog-message').html('<p style="color: red; font-size: 80%;">Une erreur est survenue lors de l\'envoi de votre message.</p>');
							
							$( "#dialog-message" ).dialog('open');
						}
					});
					
					$( this ).dialog( "close" );
				}
			},
			'Annuler': function() {
				$(this).dialog('close');
			}
		},
		close: function() {
			allFields.val('').removeClass('ui-state-error');
		}
	});
	
	$( "#dialog-message" ).dialog({
		autoOpen: false,
		modal: true,
		buttons: {
			Fermer: function() {
				$( this ).dialog( "close" );
			}
		}
	});
	
	$('.mail a').click(function() {
		id = $(this).attr('rel');
		$('#dialog-form').dialog('open');
	});
	
	/* CE BIEN M'INTERESSE */
	var nom_expediteur2 = $('#nom_expediteur2');
	var tel_expediteur2 = $('#tel_expediteur2');
	var email_expediteur2 = $('#email_expediteur2');
	var heure = $('#heure');
	var message = $('#message');
	var allFields2 = $([]).add(nom_expediteur2).add(tel_expediteur2).add(email_expediteur2).add(heure).add(message);
	var tips2 = $('.validateTips2');
	
	function updateTips2( t ) {
		tips2
			.text( t )
			.addClass( "ui-state-highlight" );
		setTimeout(function() {
			tips.removeClass( "ui-state-highlight", 1500 );
		}, 500 );
	}
	
	function checkLength2( o, n, min, max ) {
		if ( o.val().length > max || o.val().length < min ) {
			o.addClass( "ui-state-error" );
			updateTips2( "Le champ " + n + " doit comporter entre " +
				min + " et " + max + " caractères." );
			return false;
		} else {
			return true;
		}
	}
	
	function checkRegexp2( o, regexp, n ) {
		if ( !( regexp.test( o.val() ) ) ) {
			o.addClass( "ui-state-error" );
			updateTips2( n );
			return false;
		} else {
			return true;
		}
	}
	
	$('#dialog-form2').dialog({
		autoOpen: false,
		height: 500,
		width: 500,
		modal: true,
		buttons: {
			'Envoyer': function() {
				var bValid = true;
				allFields2.removeClass('ui-state-error');
				
				bValid = bValid && checkLength2(nom_expediteur2, 'Nom/Prénom', 1, 70);
				bValid = bValid && checkLength2(tel_expediteur2, 'Numéro de téléphone', 1, 70);
				bValid = bValid && checkLength2(email_expediteur2, 'Adresse e-mail', 1, 70);
				bValid = bValid && checkRegexp2(email_expediteur2, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "Adresse e-mail non valide. Ex : prenom.nom@hotmail.fr" );
				
				if (bValid) {
					var url = 'controllers/ajax/ce_bien_m_interesse.php';
					if ($(this).dialog('option', 'title') == 'Contacter l\'agence par e-mail') {
						url = 'controllers/ajax/contacter_agence.php';
					}
					
					$.ajax({
						type: 'post',
						data: { nom_expediteur2: nom_expediteur2.val(), tel_expediteur2: tel_expediteur2.val(), email_expediteur2: email_expediteur2.val(), heure: heure.val(), message: message.val(), id: id },
						url: url,
						success: function(retour){
							if(retour == 'true')
								$('#dialog-message2').html('<p style="color: green; font-size: 80%;">Votre message a bien été envoyé.</p>');
							else
								$('#dialog-message2').html('<p style="color: red; font-size: 80%;">Une erreur est survenue lors de l\'envoi de votre message.</p>');
							
							$( "#dialog-message2" ).dialog('open');
						}
					});
					
					$( this ).dialog( "close" );
				}
			},
			'Annuler': function() {
				$(this).dialog('close');
			}
		},
		close: function() {
			allFields2.val('').removeClass('ui-state-error');
		}
	});
	
	$( "#dialog-message2" ).dialog({
		autoOpen: false,
		modal: true,
		buttons: {
			Fermer: function() {
				$( this ).dialog( "close" );
			}
		}
	});
	
	$('.interesse a, a.mail2').click(function() {
		id = $(this).attr('rel');
		$('#dialog-form2').dialog('open');
	});
	
	/* LIGHTBOX PHOTOS */
	Shadowbox.init({
		modal: false,
		continuous: true,
		counterType: 'skip'
	});
	
	/* DPE */
	function dpe_init(){
		
		$('.dpe:not(.active)').each(function(){
			
			var dpeValue = $(this).addClass('active').html(),
				dpe = $(this).empty(),
				interval = 0,
				dpe_print = $('<img class="dpe_print" src="design/images/back_dpe.png" />').appendTo(dpe),
				dpe_left = $('<div class="dpe_left"></div>').appendTo(dpe),
				dpe_right = $('<div class="dpe_right"></div>').appendTo(dpe),
				dpe_cursor = $('<div class="dpe_cursor"></div>').appendTo(dpe_right),
				dpe_cursor_value = $('<div class="dpe_cursor_value">0</div>').appendTo(dpe_cursor);
			
			var dpe_img = new Image();
			dpe_img.src = 'design/images/back_dpe.png';
			
			$(dpe_img).load(function(){
				
				if (dpeValue <= 50)
					dpe_pos = 12;
				else if (dpeValue >= 51 && dpeValue <= 90)
					dpe_pos = 36;
				else if (dpeValue >= 91 && dpeValue <= 150)
					dpe_pos = 62;
				else if (dpeValue >= 151 && dpeValue <= 230)
					dpe_pos = 87;
				else if (dpeValue >= 231 && dpeValue <= 330)
					dpe_pos = 112;
				else if (dpeValue >= 331 && dpeValue <= 450)
					dpe_pos = 137;
				else
					dpe_pos = 161;
				
				dpe_cursor.animate({marginTop: '+='+dpe_pos+'px'}, 1500, function(){
					$(this).animate({width: "+=245px"},1000);
				});
				
				interval = setInterval(function(){
					if (parseInt(dpe_cursor_value.html()) < dpeValue) {
						dpe_cursor_value.html(Math.ceil(parseInt(dpe_cursor_value.html())+(dpeValue/(7*15))));
					}else{
						dpe_cursor_value.html(dpeValue);
						clearInterval(interval);
					}
				}, 5);
			});
		});
	};
	
	dpe_init();
	
	/* RECHERCHE CATALOGUE */
	$('#recherche').click(function() {
		$(this).toggle('slide', {}, 100, function() {
			$('#recherche_form').toggle('slide', {}, 100);
		});
	});
	$('.recherche_form_close').click(function() {
		$('#recherche_form').toggle('slide', {}, 100, function() {
			$('#recherche').toggle('slide', {}, 100);
		});
	});
	
	/* MODIFIER VOTRE RECHERCHE */
	$('.a_modifier_recherche').click(function() {
		$.post('controllers/ajax/recherche_auto_open.php');
	});
	
	/* CATALOGUE */
	$('.photo_preview').click(function() {
		location.href = $(this).parents('.fiche_produit_catalogue').find('h2 a').attr('href');
	});
});
