/**
 * Aides interactives du formulaire de recherche du site Arcadim
 * @author christian@konfiture.com
 */

var RECHERCHE_MAX_VILLES = 5;

function htmlCommentToVille(str)
	{
		var pStart = str.indexOf('<!--');
		var pEnd = str.indexOf('//-->');

		if ( pStart == -1 || pEnd == -1 || pStart > pEnd )
			return;

		var params = str.substring(pStart + 4, pEnd).trim();
		var params = params.split('|');

		if ( params.length != 3 )
			return;

		var ville =
			{
				id: params[0],
				nom: params[1],
				cp: params[2]
			};

		return ville;
	}

function villeToListeItem(ville)
	{
		// <li class="selection-item" id="selection-ville-352"><strong>Arras</strong> (62000) <a class="supprimer" rel="selection-ville-352" href="http://localhost/arcadim/site/modifier-selection.php?supprville=352"><span>Supprimer</span></a></li>
		// var pattern = '<li class="selection-item" id="selection-ville-{id}"><strong>{nom}</strong> ({cp}) <a class="supprimer" rel="selection-ville-{id}" href="http://localhost/arcadim/site/modifier-selection.php?supprville={id}"><span>Supprimer</span></a></li>';
		return '<li class="selection-ville-' + ville.id
			+ '"><input type="hidden" name="ville_selection[]" value="' + ville.id + '" /><strong>' + ville.nom
			+ '</strong> (' + ville.cp + ') <a class="supprimer" title="Supprimer ' + ville.nom + '(' + ville.cp + ')" rel="selection-ville-'
			+ ville.id + '" href="http://localhost/arcadim/site/modifier-selection.php?supprville='
			+ ville.id + '"><span>Supprimer</span></a></li>';
	}

function ajoutVilleSansDoublon(ville, liste)
	{
		var doublon = '.selection-ville-' + ville.id;

    if (RECHERCHE_MAX_VILLES != 0)
    {
      var nbVilles = $(liste).find('li').length;
      if (nbVilles == RECHERCHE_MAX_VILLES)
      {
        arcadimMsgBox.show({type: 'message', title: 'Attention !', message: RECHERCHE_MAX_VILLES + ' villes maximum par recherche.<br />Merci de votre compréhension.'});
        return false;
      }
    }

		if ( $(liste).find(doublon).length == 0 )
    {
			$(liste).append( villeToListeItem(ville) );
      return true;
    }
    else
      return false;

	}

function openSecteur(nom, href)
	{
		var dlgVilles = $('#liste-villes-dialog');

		dlgVilles
			.dialog(
				{
					autoOpen: false,
					title: nom,
					modal: true,
					show: 'clip',
					hide: 'clip',
					resizable: false,
					maxHeight: '400px',
					buttons:
						{
							'Ajouter': function()
								{
									$(this).find('input:checkbox').each( function()
										{
											if ($(this).attr('checked'))
												{
													var paramStr = $(this).attr('value');

													var params = paramStr.split('|');

													if ( params.length != 3 )
														return;

													var ville =
														{
															id: params[0],
															nom: params[1],
															cp: params[2]
														};
													ajoutVilleSansDoublon(ville, '#selection-villes-carte');
												}
										});
									$(this).dialog('close');
								},
							'Annuler': function()
								{
									$(this).find('widget-body').empty();
									$(this).dialog('close');
								}
						},
					open: function()
						{
							var pane = $(this).parents('.ui-dialog').first().find('.ui-dialog-buttonpane');
							pane.find('button:contains("Ajouter")').button(
									{
										icons:
											{
												primary: 'ui-icon-check'
											}
									});
							pane.find('button:contains("Annuler")').button(
									{
										icons:
											{
												primary: 'ui-icon-close'
											}
									});
						}
				})
		; // $('#liste-villes-dialog')

		$('#select-all')
			.click( function(event)
				{
					event.preventDefault();
					$('#liste-villes-dialog').find('input:checkbox').each( function()
						{
							if ( ! $(this).attr('disabled'))
									$(this).attr('checked', true);
						});
				})
		; // $('select-all')

		$('#select-none')
			.click( function(event)
				{
					event.preventDefault();
					$('#liste-villes-dialog').find('input:checkbox').attr('checked', false);
				})
		; // $('select-none')

		var msgHnd = arcadimMsgBox.show({type: 'loading', title: nom, message: 'Chargement des villes <br />Veuillez patienter...'});

		$.ajax(
			{
				cache: true,
				type: 'GET',
				url: href,
				dataType: 'text',
				success: function(data, status, xhr)
					{
						msgHnd.dialog('close');
						dlgVilles.find('.widget-body').html(data);
						dlgVilles.dialog('open');
					},
				error: function(data, status, xhr)
					{
						msgHnd.dialog('close');
					}
			});

	}

function checkFields(event)
	{
		var errors = false;
		var messages = new Array();

		var form = $('#formulaire-recherche');
		form.find('input').removeClass('error');

		var emailReg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

		if ($('#widget-recrute').length == 0)
			{
				// Formulaire recherche classique
				var hasEmail = form.find('#alerte-email').length > 0;

				var isEmpty = form.find('#critere-type-bien input:checked').length == 0;
				isEmpty = isEmpty && (form.find('#critere-ville #selection-villes li').length == 0);
				isEmpty = isEmpty && (form.find('#critere-ville #saisie-ville').val() == '');
				isEmpty = isEmpty && (form.find('#criteres-prix-min').val() == '');
				isEmpty = isEmpty && (form.find('#criteres-prix-max').val() == '');

				if ( hasEmail )
					isEmpty = isEmpty && (form.find('#alerte-email').val() == '');

				if ( isEmpty )
					{
						event.preventDefault();
						arcadimMsgBox.error({message:'Veuillez saisir au moins un critère&nbsp;!'});
						return false;
					}

				if ( hasEmail && ! emailReg.test(form.find('#alerte-email').val()) )
					{
						errors = true;
						messages.push('L\'adresse email spécifiée est de de format invalide.');
						form.find('#alerte-email').addClass('error');
					}

				var prixmin = parseInt(form.find('#criteres-prix-min').val().stripNonNumeric());
				var prixmax = parseInt(form.find('#criteres-prix-max').val().stripNonNumeric());

				if ( prixmin != 'NaN' && prixmax != 'NaN' && prixmin > prixmax )
					{
						errors = true;
						messages.push('Le prix minimum ne peut être supérieur au prix maximum&nbsp;!');
						form.find('#criteres-prix-min, #criteres-prix-max').addClass('error');
					}

				if ( (prixmin != 'NaN' && prixmin < 0) || (prixmax != 'NaN' && prixmax < 0) )
					{
						errors = true;
						messages.push('Le prix d\'un bien ne peut être négatif&nbsp;!');
					}

				if (prixmin != 'NaN' && prixmin > 100000000)
					{
						errors = true;
						messages.push('Vous venez de gagner à la loterie, tant mieux pour vous, mais le site Arcadim ne traite pas ce genre de demandes&nbsp;!');
						form.find('#criteres-prix-min').addClass('error');
					}

				if (prixmax != 'NaN' && prixmax > 100000000)
					{
						errors = true;
						messages.push('Vous venez de gagner à la loterie, tant mieux pour vous, mais le site Arcadim ne traite pas ce genre de demandes&nbsp;!');
						form.find('#criteres-prix-max').addClass('error');
					}
			}
		else
			{
				// Formulaire recrutement
				if ( form.find('#nom').val() == '' )
					{
						errors = true;
						messages.push('Nom et prénom obligatoires');
					}
				if ( form.find('#email').val() == '' || ! emailReg.test(form.find('#email').val()) )
					{
						errors = true;
						messages.push('Adresse email invalide');
					}
				if ( form.find('#telephone').val() == '' )
					{
						errors = true;
						messages.push('Numéro de téléphone obligatoire');
					}
			}


		if ( errors )
			{
				arcadimMsgBox.error({message: messages.join('</p><p>')});
				return false;
			}
		else
			{
				$('#formulaire-recherche').submit();
			}

		return true;
	}

function ieDebugHelpers()
	{
		$('#carte-helper-dialog').css('display', 'none');
		$('#liste-villes-dialog').css('display', 'none');
		$('#carte-helper-dialog').css('visibility', 'visible');
		$('#liste-villes-dialog').css('visibility', 'visible');
	}

$(document).ready( function()
	{
		if ( ie && ie < 8 )
			{
				$('#carte-helper-dialog').css('visibility', 'hidden');
				$('#liste-villes-dialog').css('visibility', 'hidden');
				setTimeout('ieDebugHelpers()', 500);
			}
		else
			{
				$('#carte-helper-dialog').css('display', 'none');
				$('#liste-villes-dialog').css('display', 'none');
			}
		

		$('#formulaire-recherche a#soumission-formulaire').click(function(event) {

			event.preventDefault();
			checkFields();

			if ($('#widget-recrute').length > 0)
				{
					arcadimMsgBox.show({type: 'loading', title: 'Envoi...', message: 'Envoi de votre candidature...\nVeuillez patienter.'});
				}
		})
		



		$('a[rel=carte]').click( function(event)
				{
					event.preventDefault();
					$('#carte-helper-dialog')
						.dialog(
							{
								autoOpen:false,
								width: '880px',
								height: 'auto',
								modal: true,
								show: 'clip',
								hide: 'clip',
								title: 'Sélection de villes',
								resizable: false,
								zIndex: 9999,
								buttons:
									{
										'Valider votre sélection': function()
											{
												var html = $('#selection-villes-carte').html();
												$('#selection-villes')
													.html(html)
													.find('a').tooltip(tooltipOpts);
												$(this).dialog('close');
											},
										'Annuler': function()
											{
												$(this).dialog('close');
											},
										'Vider votre sélection actuelle': function()
											{
												$('#selection-villes-carte').empty();
											}
									},
								open: function()
									{
										var html = $('#selection-villes').html();
										$(this).find('#selection-villes-carte').first().html(html);
										$('#selection-villes-carte a').tooltip(tooltipOpts);
										var pane = $(this).parents('.ui-dialog').first().find('.ui-dialog-buttonpane');
										pane.find('button:contains("Valider")').button(
											{
												icons:
													{
														primary: 'ui-icon-check'
													}
											});
										pane.find('button:contains("Annuler")').button(
											{
												icons:
													{
														primary: 'ui-icon-close'
													}
											});
										pane.find('button:contains("Vider")').button(
											{
												icons:
													{
														primary: 'ui-icon-trash'
													}
											});
									}
							})
						.dialog('open');
				});

		$('#carte-helper-dialog map *').tooltip(tooltipOpts);

		$('img[usemap]').maphilight(
		{
			fillColor: '00457d',
			fillOpacity: '0.1',
			stroke: false,
			fade: true
		});

		$('a.supprimer')
			.live( 'click', function(event)
				{
					event.preventDefault();
					$(this).parents('li')
						.first()
						.fadeOut( function()
							{
								$(this).empty().remove();
							});
				})
		; // $('a.supprimer')

		$('area')
			.click(function(event)
				{
					event.preventDefault();
					var href = $(this).attr('href');
					var nom = $(this).attr('title');
					openSecteur(nom, href);
				})
		; // $('#secteurs area')

		var ajaxCache = {};

		$('#saisie-ville')
			.click( function(event)
				{
					$(this).focus().val('').select();
				})
			.autocomplete(
				{
					minLength: 2,
					open: function(event, ui)
						{
							$('.ui-autocomplete').fadeOut(0);
							$('.ui-autocomplete').fadeIn();
						},
					source: function(request, response)
						{
							var termHash = request.term.toLowerCase();

							if ( ajaxCache[termHash] != undefined )
								{
									var data = ajaxCache[termHash];
									response(data);
								}
							else
								{
									$.get('/ajax/villes/autocomplete/'+request.term, { }, function(data)
										{
											if ( data != undefined )
												{
													ajaxCache[termHash] = data;
													response(data);
												}
										});
								}


						},
					select: function(event, ui)
						{
							var ville = htmlCommentToVille(ui.item.label);

							if ( ville == 'undefined' )
								return;

							ajoutVilleSansDoublon(ville, '#selection-villes');

							$('.ui-autocomplete').fadeOut();
							setTimeout(function() { $('#saisie-ville').select().focus(); }, 50);
						}
				})
		; // $('#saisie-ville')

		var	rangePrixStart = $('#criteres-prix input').first().val();
		var	rangePrixStop = $('#criteres-prix input').last().val();
		var	rangeSurfaceSart = $('#criteres-surface input').first().val();
		var	rangeSurfaceStop = $('#criteres-surface input').last().val();

		var prixMin = 0;
		var	prixMax = 800000;
		var	surfaceMin = 0;
		var	surfaceMax = 1000;
		
		$('#slider-prix')
			.slider({
				range: true,
				min: prixMin,
				max: prixMax,
				step: 10000,
				values: [ rangePrixStart, rangePrixStop ],
				slide: function(event, ui){
					$('#criteres-prix-max').val( ui.values[1] );
					$('#criteres-prix-min').val( ui.values[0] );

					var	thePrixMax = ui.values[1] == prixMax ? '+ de 800 000' : ui.values[1].formatNumber();

					$(this).parent().find('p').html('Prix entre <strong>' + ui.values[0].formatNumber() + '</strong> et <strong>' + thePrixMax + '</strong> euros' );
				}
			})
			.parent().find('p').html('Prix entre <strong>' + $('#slider-prix').slider('values', 0).formatNumber() + '</strong> et <strong>' + $('#slider-prix').slider('values', 1).formatNumber() + '</strong> euros');
		

		$('#slider-surface')
			.slider({
				range: true,
				min: surfaceMin,
				max: surfaceMax,
				step: 10,
				values: [ rangeSurfaceSart, rangeSurfaceStop ],
				slide: function(event, ui) {
					$('#criteres-surface-max').val( ui.values[1] );
					$('#criteres-surface-min').val( ui.values[0] );
					var theSurfaceMax = ui.values[1] == surfaceMax ? '+ de 1 000' : ui.values[1].formatNumber();
					$(this).parent().find('p').html('Surface entre <strong>' + ui.values[0].formatNumber() + '</strong> et <strong>' + theSurfaceMax + '</strong> m²' );
				}
			})
			.parent().find('p').html('Surface entre <strong>' + $('#slider-surface').slider('values', 0) + '</strong> et <strong>' + $('#slider-surface').slider('values', 1) + '</strong> m²' );
		

		/*
		$("#critere-plus-pieces input").click(function(){
			$(this).nextAll('.choix').attr('checked', true);
		});
		*/
		if ($('.home-picto').length == 0) {

			var plus = $('#criteres-plus');
			plus.appendTo('#formulaire-recherche .widget-body');

			var details = $('#details');
			details.appendTo('#formulaire-recherche .widget-body')
				.css('marginTop', '10px');
			

			if (ie == 7) {
				$('#formulaire-recherche #critere-ville legend').html('Spécifiez les localités ou les<br/>codes postaux de votre recherche');
			}

			if ($('#criteres-plus-actifs').val() == 'no') {
				if (ie == 7) {
					plus.fadeOut(10);
				} else
					plus.slideUp();
			} else {
				if (ie == 7) {
					/*
					plus.fadeOut(20, function() {
						plus.fadeIn(20, function() {
							Cufon.refresh();
						})
					});
					$('#formulaire-recherche .actions').fadeOut(10, function() {
						$(this).fadeIn(30, function() {
							Cufon.refresh();
						})
					});
					*/
				}
				
				details
					.addClass('expanded')
					.find('.button-text').text('Moins de critères');
				if (ie != 7)
					Cufon.replace('#details');
			}

			details
			.click(function(event) {

				event.preventDefault();
				if (details.hasClass('expanded')) {

					details.removeClass('expanded');
					$('#criteres-plus-actifs').val('no');
					if (ie == 7) {
						plus
							.fadeOut(200, function() {
								details.find('.button-text').text('Plus de critères');
								/*
								Cufon.replace('#details');
								Cufon.replace('#formulaire-recherche .actions .button');
								*/
							});
						
					} else {
						plus
							.slideUp(500, function() {
								details.find('.button-text').text('Plus de critères');
								Cufon.replace('#details');
							});
					}

				} else {
					$('#criteres-plus-actifs').val('yes');
					if (ie == 7) {
						plus
							.fadeIn(200, function() {
								details.find('.button-text').text('Moins de critères');
								/*
								Cufon.replace('#details');
								*/
								details.addClass('expanded');
							});
						
					} else {
						plus
							.slideDown(500, function() {
								details.find('.button-text').text('Moins de critères');
								Cufon.replace('#details');
								details.addClass('expanded');
							});
					}
				}
			});
		}

	});
