
jQuery(function($){
if ($.datepicker) {
	$.datepicker.regional['fr'] = {
		clearText: 'Effacer', clearStatus: 'Effacer la date sélectionnée',
		closeText: 'Fermer', closeStatus: 'Fermer sans modifier',
		prevText: '&#x3c;Préc', prevStatus: 'Voir le mois précédent',
		prevBigText: '&#x3c;&#x3c;', prevBigStatus: '',
		nextText: 'Suiv&#x3e;', nextStatus: 'Voir le mois suivant',
		nextBigText: '&#x3e;&#x3e;', nextBigStatus: '',
		currentText: 'Courant', currentStatus: 'Voir le mois courant',
		monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin',
		'Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
		monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun',
		'Jul','Aoû','Sep','Oct','Nov','Déc'],
		monthStatus: 'Voir un autre mois', yearStatus: 'Voir une autre année',
		weekHeader: 'Sm', weekStatus: '',
		dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
		dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
		dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
		dayStatus: 'Utiliser DD comme premier jour de la semaine', dateStatus: '\'Choisir\' le DD d MM',
		dateFormat: 'dd/mm/yy', firstDay: 1,
		initStatus: 'Choisir la date', isRTL: false};
	$.datepicker.setDefaults($.datepicker.regional['fr']);
}
});


var protoHome = {
	
	newsCurrent: 1,
	
	/**
	 * Initialisation
	 */
	init: function () {
		// Lance le diaporama des nouveautés / coup de coeur
		this.toggleNews();
		
		// Initialisation des calendriers
        $.datepicker.setDefaults($.extend($.datepicker.regional['fr']));
		$("#oSejoursDateDepart").datepicker({
			minDate: 1,
			maxDate: '+600D',
		});
		
		// Initialiasation sur changement de pays
		$("#oGitesPays").change(function() { protoHome.changePays('Gites'); });
		$("#oLocationsPays").change(function() { protoHome.changePays('Locations'); });
		
		// Initialisation du formulaire vols secs
		this.initVolsSecs();
	},
	
	
	/**
	 * Initiatialisation du formulaire des Vols Secs
	 */
	initVolsSecs: function () {
        // Si aller simple on desactive la date de retour
        $("#oVolsTrajetType").change(function() {
            if ($(this).val() == 1) $("#oVolsDateRetour").attr("disabled", true).css("background-color", 'silver');
            if ($(this).val() == 0) $("#oVolsDateRetour").attr("disabled", false).css("background-color", 'white');
        });
        
	    // Initialisation des calendriers
	    $("#oVolsDateDepart").datepicker({
            minDate: 1,
            maxDate: '+300D',
            onSelect: function() { $("#oVolsDateRetour").datepicker("option", {minDate: $(this).datepicker("getDate")}); }
        });
        $("#oVolsDateRetour").datepicker({
            minDate: 3,
            maxDate: '+300D'
        });
        
        // Initialise les autocomplétion de la ville de départ
        $("#oVolsCodeDepart").val('');
        $("#oVolsVilleDepart").autocomplete('volsec-airport.ajax.php', {
            minChars: 2,
            width: 320,
            selectFirst: true,
            max:50,
            extraParams: { search:'areoport' },
            parse: function(datas) {
                return $.map(eval(datas), function(row) {
                    return { 'data': row, 'value': row.ville, 'result': row.ville }
                });
            },
            formatItem: function(row) {
                return '<img src="'+row.drapeau+'.png" alt=""/> '+row.ville+' <i>('+row.pays+')</i>';
            }
        }).result(function(event, row) { $("#oVolsCodeDepart").val(row.code); });

        // Initialise les autocomplétion de la ville d'arrivée
        $("#oVolsCodeArrive").val('');
        $("#oVolsVilleArrive").autocomplete('volsec-airport.ajax.php', {
            minChars: 2,
            width: 320,
            selectFirst: true,
            max:50,
            extraParams: { search:'areoport' },
            parse: function(datas) {
                return $.map(eval(datas), function(row) {
                    return { 'data': row, 'value': row.ville, 'result': row.ville }
                });
            },
            formatItem: function(row) {
                return '<img src="'+row.drapeau+'.png" alt=""/> '+row.ville+' ('+row.pays+')';
            }
        }).result(function(event, row) { $("#oVolsCodeArrive").val(row.code); });
    },
    
    
    /**
     * Validation du formulaire des Vols Secs
     */
    submitVols: function () {
        if ($("#oVolsCodeDepart").val() == '') { alert('Veuillez saisir et sélectionner une ville de départ.'); return false; }
        if ($("#oVolsCodeArrive").val() == '') { alert('Veuillez saisir et sélectionner une ville d\'arrivée.'); return false; }
        var regdate = /^[0-3][0-9]\/[0-1][0-9]\/20[0-9]{1,2}$/gi;
        if (!$("#oVolsDateDepart").val().match(regdate)) { alert('Veuillez saisir une date de départ valide.'); return false; }
        if (!$("#oVolsDateRetour").val().match(regdate) && $("#oVolsTrajetType").val() == 0) { alert('Veuillez saisir une date de retour valide.'); return false; }
    },
    
		
	/**
	 * Affiche le formulaire concerné en changeant le css des onglets
	 * 
	 * @param formulaire : nom du formulaire à ouvrir 
	 */
	openSearch: function (formulaire) {
		$("#forms div:visible").fadeOut('normal', function() {
			$(".tabs li.select").removeClass('select');
			$("#oTab"+formulaire).addClass('select');
			$("#oForm"+formulaire).fadeIn('slow');
		});
	},
	
	
	/**
	 * change la région en fonction du pays 
	 */
    changePays: function(obj) {
		//alert(obj);
	    pays = $("#o"+obj+"Pays").val();
	    if (regions[obj][pays] == undefined) return;
	    optionsRegion = '<option value="">&nbsp;</option>';
	    $.each(regions[obj][pays], function(i, val) {
	        optionsRegion+= '<option value="'+i+'">'+val+'</option>';
	    });
	    $("#o"+obj+"Region").html(optionsRegion);
	},

	
	/**
	 * Affiche le diaporama des nouveautés / Coups de coeur
	 */
	toggleNews: function () {
		$("#coupdecoeur"+this.newsCurrent).fadeOut('slow');
		this.newsCurrent = (this.newsCurrent % 3) + 1;
		$("#coupdecoeur"+this.newsCurrent).fadeIn('slow');
		setTimeout("protoHome.toggleNews();", 3000);
	},
	
	
	/**
	 * Valide le formulaire d'inscription à la newsletter
	 */	
	submitNewsletter: function() {
		var regemail = /^\w[\w+\.\-]*@[\w\-]+\.\w[\w+\.\-]*\w$/gi;
		if (!$("#fnewsletter input[name='email']").val().match(regemail)) {
			alert('Merci de saisir un email valide.');
			return false;
		}
		$.get("/account.ajax.php", $("#fnewsletter").serialize(), function(retour) {
			$("#fnewsletter p").html(retour);
 		});
		return false;
	}
	
};



/** ***********************************************************************************************
 * 
 * Classe de la page des homes pour chaque type d'offre
 * 
 * @class protoHome2
 * 
 */
var protoHome2 = {
		
	/**
	 * Initialisation
	 */
	init: function () {
		// Lance le diaporama des nouveautés / coup de coeur
		this.toggleNews();
		
		// Chargement des photos
		pre = new Array();
		pre[1]= new Image; pre[1].src = '/images/monde-1.png';
		pre[2]= new Image; pre[2].src = '/images/monde-2.png';
		pre[3]= new Image; pre[3].src = '/images/monde-e.png';
		pre[4]= new Image; pre[4].src = '/images/monde-f.png';
		pre[5]= new Image; pre[5].src = '/images/monde-s.png';
		pre[6]= new Image; pre[6].src = '/images/monde-o.png';
		
		// Preparation de l'infobulle sur la carte du monde
		$("map *").tooltip({
			delay: 200,
			track: true,
			showURL: false,
			id: "cartetooltip" });
		
		// Initialise les formulaires
		$("#oDateDepart").datepicker({
			minDate: 1,
			maxDate: '+600D',
		});
	},
	
	
	/**
	 * Affiche le diaporama des nouveautés / Coups de coeur
	 */
	toggleNews: function () {
		$("#coupdecoeur"+this.newsCurrent).fadeOut('slow');
		this.newsCurrent = (this.newsCurrent % 3) + 1;
		$("#coupdecoeur"+this.newsCurrent).fadeIn('slow');
		setTimeout("protoHome.toggleNews();", 3000);
	},
	
	
	/**
	 * Affiche la carte du rollover
	 */
	swapMap: function(image) {
		$("#oCarte").attr('src', '/images/'+image);
	},


	/**
	 * Affiche le layer de la liste des pays
	 */
	showContinent: function(continent) {
		$("#oDivCarte"+continent).fadeIn("normal");
	},

	
	/**
	 * Cache le layer de la liste des pays
	 */
	hideContinent: function(continent) {
		$("#oDivCarte"+continent).fadeOut("fast");
	},
	
	
	/**
	 * change la région en fonction du pays 
	 */
    changePays: function() {
	    pays = $("#fPays").val();
	    if (regions[pays] == undefined) return;
	    optionsRegion = '<option value="">&nbsp;</option>';
	    $.each(regions[pays], function(i, val) {
	        optionsRegion+= '<option value="'+i+'">'+val+'</option>';
	    });
	    $("#fRegion").html(optionsRegion);
	}
	
};



/** ***********************************************************************************************
 * 
 * Classe de la page des homes qui affiche une carte google
 * 
 * @class protoHomeCarte
 * 
 */
var protoHomeCarte = {

	isForm: false,

	/**
	 * Initialisation de la page
	 */
	init: function() {
		// Lance le diaporama des nouveautés / coup de coeur
		protoHome.toggleNews();
		
		// Initialise Google Maps
		// Test si le navigateur est compatible
		if (!GBrowserIsCompatible() || ($.browser.msie && parseInt($.browser.version) <= 6)) {
			//alert('Nous sommes désolés, mais votre navigateur est incompatible avec notre carte intéractive.');
			$("#mapq").html('Nous sommes désolés, mais votre navigateur est incompatible avec notre carte intéractive.');
		} else {
			oMap = new GMap2(document.getElementById("mapq"));
			oMap.addControl(new GSmallMapControl());
			oMap.enableDoubleClickZoom();
			oMap.enableContinuousZoom();
			oMap.setCenter(new GLatLng(49.837982, 14.0625), 3);
			GEvent.addListener(oMap, 'infowindowclose', function() {
				protoHomeCarte.isForm = false;
			});
			GEvent.addListener(oMap, 'infowindowopen', function() {
				protoHomeCarte.isForm = true;
			});
			GEvent.addListener(oMap, 'moveend', function() {
				if (protoHomeCarte.isForm) return;
				zone = oMap.getBounds();
				sw = zone.getSouthWest();
				ne = zone.getNorthEast();
				//alert(sw.lat());
				$.getJSON("/home.ajax.php", {select: 'carte', code: $("#fType").val(), zoom: oMap.getZoom(), coord: sw.lat()+'x'+sw.lng()+'x'+ne.lat()+'x'+ne.lng()}, function (retour) {
					//alert(retour.markers.length);
					oMap.clearOverlays();
					for (var i = 0; i < retour.markers.length; i++) {
						protoHomeCarte.createMarker(retour.markers[i].lat, retour.markers[i].lon, retour.markers[i].lib, retour.markers[i].code);
					}
				});
			});
		}
	},

	changePays: function () {
		$.getJSON("/home.ajax.php", {select: 'pays', code: $("#fType").val(), subdiv: $("#fPays").val()}, function (retour) {
			var option = ''; //alert(retour);
			if (retour.region.length > 1) {
				for (var i = 0; i < retour.region.length; i++) {
					option+= '<option value="'+retour.region[i].val+'">'+retour.region[i].lib+'</option>';
				}
				$("#fRegion").attr("disabled", "");
				$("#fProvince").attr("disabled", "true"); $("#fProvince").html('<option value="">&nbsp;</option>');
				$("#fRegion").html(option);
			}
			protoHomeCarte.moveMap(retour.latitude, retour.longitude, 5, retour.libelle, $("#fPays").val());
		});
	},

	changeRegion: function () {
		$.getJSON("/home.ajax.php", {select: 'region', code: $("#fType").val(), subdiv: $("#fRegion").val()}, function (retour) {
			var option = ''; //alert(retour);
			if (retour.province.length > 1) {
				for (var i = 0; i < retour.province.length; i++) {
					option+= '<option value="'+retour.province[i].val+'">'+retour.province[i].lib+'</option>';
				}
				$("#fProvince").attr("disabled", "");
				$("#fProvince").html(option);
			}
			protoHomeCarte.moveMap(retour.latitude, retour.longitude, 7, retour.libelle, $("#fRegion").val());
		});
	},

	changeProvince: function () {
		$.getJSON("/home.ajax.php", {select: 'province', code: $("#fType").val(), subdiv: $("#fProvince").val()}, function (retour) {
			protoHomeCarte.moveMap(retour.latitude, retour.longitude, 9, retour.libelle, $("#fProvince").val());
		});
	},
	
	changeType2: function () {
		$.getJSON("/home.ajax.php", {select: 'type2', code: $("#fType2").val()}, function (retour) {
 			var option = '';
			for (var i = 0; i < retour.tarif.length; i++) {
				option+= '<option value="'+retour.tarif[i].val+'">'+retour.tarif[i].lib+'</option>';
			}
			$("#fTarif").html(option);
			option = '';
			for (var i = 0; i < retour.pays.length; i++) {
				option+= '<option value="'+retour.pays[i].val+'">'+retour.pays[i].lib+'</option>';
			}
			$("#fPays2").html(option);
		});
	},

	changeType: function () {
		$.getJSON("/home.ajax.php", {select: 'type', code: $("#fType").val()}, function (retour) {
 			var option = '';
			for (var i = 0; i < retour.pays.length; i++) {
				option+= '<option value="'+retour.pays[i].val+'">'+retour.pays[i].lib+'</option>';
			}
			$("#fPays").html(option);
			$("#fRegion").attr("disabled", "true"); $("#fRegion").html('<option value="">&nbsp;</option>');
			$("#fProvince").attr("disabled", "true"); $("#fProvince").html('<option value="">&nbsp;</option>');
		});
	},

	moveMap: function (latitude, longitude, zoom, libelle, subdiv) {
		protoHomeCarte.isForm = true;
		var point = new GLatLng(latitude, longitude);
		oMap.setCenter(point, zoom);
		oMap.clearOverlays();
		var marker = this.createMarker(latitude, longitude, libelle, subdiv);
		marker.openInfoWindowHtml(this.getInfoWindows($("#fType").val(), latitude, longitude, libelle, subdiv));
	},

	zoomIn: function (latitude, longitude) {
		oMap.closeInfoWindow();
		oMap.setCenter(new GLatLng(latitude, longitude), oMap.getZoom() + 2);
	},

	createMarker: function (latitude, longitude, libelle, subdiv) {
		var point = new GLatLng(latitude, longitude);
		var marker = new GMarker(point);
		oMap.addOverlay(marker);
		GEvent.addListener(marker, "click", function() {
			this.openInfoWindowHtml(protoHomeCarte.getInfoWindows($("#fType").val(), latitude, longitude, libelle, subdiv));
		});
		return marker;
	},

	getInfoWindows: function (type, latitude, longitude, libelle, subdiv) {
		var message = '<div class="gmaphome">Annonces <b>'+libelle+'</b><br/>';
		message+= '<a href="/carte.html?type='+type+'&subdiv='+subdiv+'">Visualisez toutes les annonces<br/>sur la carte en cliquant sur ce lien.</a>';
		if (oMap.getZoom() < 8)
			message+= '<br/><small>ou bien zoomez en double cliquant</small>';
			//message+= '<br/>ou bien <a href="javascript:oProtoHomeCarte.zoomIn('+latitude+','+longitude+')">Zoomez</a>';
		message+= '</div>';
		return message;
	},

	submitForm: function () {
		// Validation du formulaire de la page d'accueil
		if ($("#fPays").val() == '') {
			alert('Veuillez sélectionner un pays.');
			return false;
		}
		return true;
	}

};



/** ***********************************************************************************************
*
* Classe de la page de la liste des annonces
* 
* @class protoListe
* 
*/
var protoListe = {

    /**
     * Initialisation
     */
    init: function() {
        // Si cookies on affiche l'affichage choisi
        if ($.cookie("otop_affliste") != null) {
            obj = $.cookie("otop_affliste").split(',');
            this.show(obj[0], obj[1]);
        }
    },


    /**
     * Change l'ordre des annonces et redirige sur la nouvelle page
     */
    changeOrder: function() {
        document.location.href = $("#oOrder").val();
        //alert($("#oOrder").val()); 
    },


    /**
     * Cache un affichage et affiche l'autre
     */
    show: function(objshow, objhide) {
        $("#"+objhide).hide();
        $("#"+objshow).show();
        // Sauvegarde le choix dans un cookie
        $.cookie("otop_affliste", objshow+','+objhide, { path: '/' });
    }

};



/** ***********************************************************************************************
 *
 * Classe de la page de la fiche d'une annonce
 * 
 * @class protoFiche
 * 
 */
var protoFiche = {

	/**
	 * Initialisation
	 */
	init: function () {
	
		// Initialisation de la visualisation des photos
		$("#images a").lightBox({
			overlayBgColor: '#000',
			overlayOpacity: 0.7,
			containerBorderSize: 10,
			imageLoading: '/olix/jquery/plugins/lightbox-0.5/images/lightbox-ico-loading.gif',
			imageBtnClose: '/olix/jquery/plugins/lightbox-0.5/images/lightbox-btn-close.gif',
			imageBtnPrev: '/olix/jquery/plugins/lightbox-0.5/images/lightbox-btn-prev.gif',
			imageBtnNext: '/olix/jquery/plugins/lightbox-0.5/images/lightbox-btn-next.gif',
			imageBlank: '/olix/jquery/plugins/lightbox-0.5/images/lightbox-blank.gif',
			containerResizeSpeed: 400,
			txtImage: 'Image',
			txtOf: 'de'
		});
		
		// Initialise Google Maps
		if ($("#geomap").length > 0 && GBrowserIsCompatible()) {
			if ($.browser.msie && parseInt($.browser.version) <= 6) return;
			oMap = new GMap2(document.getElementById("geomap"));
			oMap.addControl(new GSmallMapControl());
			oMap.addControl(new GMapTypeControl());
			oMap.addControl(new GScaleControl());
			var oControl = new GOverviewMapControl(new GSize(160,120));
			oMap.addControl(oControl);
			oMap.setCenter(oPoint, 8);
			//var oIcone = new GIcon();
			//oIcone.shadow = '<?=$var_config['url_root']?>images/otop/ico-<?=$t?>.gif';
			//oIcone.image = '<?=$var_config['url_root']?>images/otop/ico-<?=$t?>.gif';
			//oIcone.iconSize = new GSize(24, 24);
			//oIcone.shadowSize =n ew GSize(24, 24);
			//oIcone.iconAnchor = new GPoint(11, 11);
			//oIcone.infoWindowAnchor = new GPoint(16, 0);
			var oMarker = new GMarker(oPoint); //, oIcone
			GEvent.addListener(oMarker, "click", function() {
				oMarker.openInfoWindowHtml(sAdresse);
			});
			oMap.addOverlay(oMarker);
			oMarker.openInfoWindowHtml(sAdresse);
		}
	
		// Initialise les boites de dialogue de contact et envoi à un ami
		if ($("#dialogContact").length > 0) {
			$("#dialogContact").dialog({
				autoOpen: false,
				modal: true,
				overlay: { "background-color": 'black', opacity: 0.7 },
				resizable: false,
				width: 660 , height: 600,
				show: 'scale', hide: 'scale',
				buttons: { "Annuler": function() { $(this).dialog("close"); },
				           "Envoyer": this.submitFormContact }
			});
		}
		$("#dialogContactEnvoi").dialog({
			autoOpen: false,
			modal: true,
			overlay: { "background-color": 'black', opacity: 0.3 },
			resizable: false,
			width: 320,
			hide: 'scale'
		});
		$("#dialogEnvoiAmi").dialog({
			autoOpen: false,
			modal: true,
			overlay: { "background-color": 'black', opacity: 0.3 },
			resizable: false,
			width: 600, height:370,
			show: 'scale', hide: 'scale',
			buttons: { "Annuler": function() { $(this).dialog("close"); },
					   "Envoyer": this.submitFormEnvoiAmi }
		});
	},
	
	
	/**
	 * Affiche le layer contenant le calendrier
	 */
	openCalendar: function (div) {
		$('#'+div).slideToggle('slow');
	},
	
	
	/**
	 * Insère l'offre dans le panier
	 * @param int    flux : Identifiant du flux
	 * @param string code : Reference du produit
	 */
	insertPanier: function(flux, code) {
		$.get("/account-selection.ajax.php", {'action':1, 'flux':flux, 'code':code}, function(retour) {
			$("#oPanier").html('Cette annonce a été ajoutée à ma sélection');
 		});
	},

	removePanier: function(flux, code) {
		$.get("/account-selection.ajax.php", {'action':0, 'flux':flux, 'code':code}, function(retour) {
			$("#oPanier").html('Cette annonce a été retirée de ma sélection');
 		});
	},
	
	
	/**
	 * Affiche la boite de dialogue du formulaire de contact
	 */
	openDialogContact: function() {
		$.get("/fiche-contact.ajax.php?submited=2&produit="+$("#formBooking input[name='produit']").val());
		$("#dialogContact").dialog("open");
	},
	
	
	/**
	 * Soumission du formulaire dde contact à un annonceur
	 */
	submitFormContact: function() {
		// Vérification du formulaire
		var formok = true;
		$("#formBooking :input").each(function(i, element) { $(element).css({"background-color": '#ffffff'}); });
		if ($("#formBooking input[name='nom']").val() == '') { formok = false; $("#formBooking input[name='nom']").css({"background-color": '#ff9999'}); }
		if ($("#formBooking input[name='ville']").val() == '') { formok = false; $("#formBooking input[name='ville']").css({"background-color": '#ff9999'}); }
		var regemail = /^\w[\w+\.\-]*@[\w\-]+\.\w[\w+\.\-]*\w$/gi;
		if (!$("#formBooking input[name='email']").val().match(regemail)) { formok = false; $("#formBooking input[name='email']").css({"background-color": '#ff9999'}); }
		if ($("#formBooking textarea[name='message']").val() == '') { formok = false; $("#formBooking textarea[name='message']").css({"background-color": '#ff9999'}); }
		if ($("#formBooking input[name='captcha']").val() == '') { formok = false; $("#formBooking input[name='captcha']").css({"background-color": '#ff9999'}); }
		if (!formok) { alert('Veuillez remplir tous les champs indiqués en rouge'); return false; }

		// Ouvre la boite de dialogue d'information et envoi le message
		$("#dialogContactEnvoi").html('<div><img src="/images/carte-loading.gif" style="vertical-align:middle;"/> &nbsp; &nbsp; &nbsp; Envoi du message ...</div>');
		$("#dialogContactEnvoi").dialog("open");
		$.ajax({
			type: "GET",
			url: "/fiche-contact.ajax.php?"+$("#formBooking").serialize(),
			dataType: "text",
			error: function() {
				$("#dialogContactEnvoi").html('<div style="color:red;">Erreur lors de l\'envoi du message.<br\>Merci de réessayer<\/div>');
				setTimeout(function() { $("#dialogContactEnvoi").dialog("close"); }, 2000);
			},
			success: function(retour) {
				if (retour == 'OK') {
					$("#dialogContactEnvoi").html('<div style="color:green;">Message envoyé avec succès<\/div>');
					setTimeout(function() { $("#dialogContactEnvoi").dialog("close"); $("#dialogContact").dialog("close"); }, 2000);
				} else if (retour == 'ERROR') {
					$("#dialogContactEnvoi").html('<div style="color:red;">Erreur lors de l\'envoi du message<br\>Merci de réessayer<\/div>');
					setTimeout(function() { $("#dialogContactEnvoi").dialog("close"); }, 2000);
				} else {
					$("#dialogContactEnvoi").dialog("close");
					error = retour.split(',');
					for (i = 0; i < error.length; i++) {
						$("#formBooking :input[name='"+error[i]+"']").css({"background-color": '#ff9999'});
						$("#formBooking textarea[name='"+error[i]+"']").css({"background-color": '#ff9999'});
					}
					alert('Veuillez remplir tous les champs indiqués en rouge');
				}
			}
		});
	},
	
	
	/**
	 * Affiche la boite de dialogue du formulaire d'envoi à un ami
	 */
	openDialogEnvoiAmi: function() {
		$("#dialogEnvoiAmi").dialog("open");
	},
	
	
	/**
	 * Soumission du formulaire d'envoi à un ami
	 */
	submitFormEnvoiAmi: function() {
        // Vérification du formulaire
        var formok = true;
        $("#formEnvoiAmi :input").each(function(i, element) { $(element).css({"background-color": '#ffffff'}); });
        var regemail = /^\w[\w+\.\-]*@[\w\-]+\.\w[\w+\.\-]*\w$/gi;
        if (!$("#formEnvoiAmi input[name='email']").val().match(regemail)) { formok = false; $("#formEnvoiAmi input[name='email']").css({"background-color": '#ff9999'}); }
        if (!$("#formEnvoiAmi input[name='email2']").val().match(regemail)) { formok = false; $("#formEnvoiAmi input[name='email2']").css({"background-color": '#ff9999'}); }
        if (!formok) { alert('Veuillez remplir tous les champs indiqués en rouge'); return false; }
        // Ouvre la boite de dialogue d'information et envoi le message
        $("#dialogContactEnvoi").html('<div><img src="/images/carte-loading.gif" style="vertical-align:middle;"/> &nbsp; &nbsp; &nbsp; Envoi du message ...</div>');
        $("#dialogContactEnvoi").dialog("open");
        $.ajax({
            type: "GET",
            url: "/fiche-envoiami.ajax.php",
            data: $("#formEnvoiAmi").serialize(),
            dataType: "text",
            error: function() {
                $("#dialogContactEnvoi").html('<div style="color:red;">Erreur lors de l\'envoi du message.<br\>Merci de réessayer<\/div>');
                setTimeout(function() { $("#dialogContactEnvoi").dialog("close"); }, 2000); },
            success: function(retour) {
                if (retour == 'OK') {
                    $("#dialogContactEnvoi").html('<div style="color:green;">Message envoyé avec succès<\/div>');
                    setTimeout(function() { $("#dialogContactEnvoi").dialog("close"); $("#dialogEnvoiAmi").dialog("close"); }, 2000);
                } else {
                    $("#dialogContactEnvoi").html('<div style="color:red;">Erreur lors de l\'envoi du message<br\>Merci de réessayer<\/div>');
                    setTimeout(function() { $("#dialogContactEnvoi").dialog("close"); }, 2000);
                }}
        });
    }

};



/** ***********************************************************************************************
*
* Classe de la page de résultats des vols secs
* 
* @class protoVolsec
* 
*/
var protoVolsec = {

    /**
     * Initialisation de la page
     */
    init: function () {
        // Initialisation des calendriers
        $.datepicker.setDefaults($.extend($.datepicker.regional['fr']));
        
        // Initialise les autocomplétion de la ville de départ
        $("#formVolsec input[name='ville_depart']").autocomplete('/volsec-airport.ajax.php', {
            minChars: 2,
            width: 320,
            selectFirst: true,
            max:50,
            extraParams: { search:'areoport' },
            parse: function(datas) {
                return $.map(eval(datas), function(row) {
                    return { 'data': row, 'value': row.ville, 'result': row.ville }
                });
            },
            formatItem: function(row) {
                return '<img src="'+row.drapeau+'.png" alt=""/> '+row.ville+' <i>('+row.pays+')</i>';
            }
        }).result(function(event, row) { $("#formVolsec input[name='code_depart']").val(row.code); });

        // Initialise les autocomplétion de la ville d'arrivée
        $("#formVolsec input[name='ville_arrive']").autocomplete('/volsec-airport.ajax.php', {
            minChars: 2,
            width: 320,
            selectFirst: true,
            max:50,
            extraParams: { search:'areoport' },
            parse: function(datas) {
                return $.map(eval(datas), function(row) {
                    return { 'data': row, 'value': row.ville, 'result': row.ville }
                });
            },
            formatItem: function(row) {
                return '<img src="'+row.drapeau+'.png" alt=""/> '+row.ville+' ('+row.pays+')';
            }
        }).result(function(event, row) { $("#formVolsec input[name='code_arrive']").val(row.code); });

        // Si aller simple on desactive la date de retour
        $("#formVolsec select[name='trajet_type']").change(function() {
            if ($(this).val() == 1) $("#formVolsec input[name='date_retour']").attr("disabled", true).css("background-color", 'silver');
            if ($(this).val() == 0) $("#formVolsec input[name='date_retour']").attr("disabled", false).css("background-color", 'white');
        });

        //Initialise les dates    
        $("#formVolsec input[name='date_depart']").datepicker({
            minDate: 1,
            maxDate: '+300D',
            onSelect: function() { $("#formVolsec input[name='date_retour']").datepicker("option", {minDate: $(this).datepicker("getDate")}); }
        });
        $("#formVolsec input[name='date_depart']").css('background', "url('/images/input-calendar.png') right center no-repeat");
        $("#formVolsec input[name='date_retour']").datepicker({
            minDate: 3,
            maxDate: '+300D'
        });
        $("#formVolsec input[name='date_retour']").css('background', "url('/images/input-calendar.png') right center no-repeat");

        //Initialise le nombre de passagers adulte par defaut
        $("#formVolsec select[name='nb_adulte']").val(1);
        
        //$("#formVolsec").submit(this.submitVols);
        
        this.loadVolsec();
    },

    
    /**
     * Validation du formulaire : vérifie les champs saisis
     */
    submitVols: function () {
        if ($("#oVolsCodeDepart").val() == '') { alert('Veuillez saisir et sélectionner une ville de départ.'); return false; }
        if ($("#oVolsCodeArrive").val() == '') { alert('Veuillez saisir et sélectionner une ville d\'arrivée.'); return false; }
        var regdate = /^[0-3][0-9]\/[0-1][0-9]\/20[0-9]{1,2}$/gi;
        if (!$("#oVolsDateDepart").val().match(regdate)) { alert('Veuillez saisir une date de départ valide.'); return false; }
        if (!$("#oVolsDateRetour").val().match(regdate) && $("#oVolsTrajetType").val() == 0) { alert('Veuillez saisir une date de retour valide.'); return false; }
    },

    
    /**
     * Recherche des vols et affiche le résultat
     */
    loadVolsec: function() {
        $.ajax({
            type:       "GET",
            url:        "/volsec-search.ajax.php",
            data:       $("#formVolsec").serialize(),
            dataType:   "html",
            error:      function() {
                            alert('Une erreur de connexion est intervenue.\nMerci de reessayer à nouveau.');
                        },
            success:    function(retour) {
                            //alert(retour);
                            if (retour == 'ERROR') {
                                alert('Une erreur de connexion est intervenue.\nMerci de reessayer à nouveau.');
                            } else {
                                $("#resultat").html(retour).show();
                                $("#loading").fadeOut('slow');
                            }
                        }
        });
    }

};




