//Transformation des combos
var comboPays;
var comboRegions;
var comboDepartements;
var comboVilles;
var comboVillesSB;
var storeVillesSB;
var gridSB;
var toolbar;

function reinitialiserRechercheSuggestBox() {
	$('nomVilleSuggestBox').value = "";
}

function lancerRecherche(debut) {
		
	var nomVilleSuggestBox = $('nomVilleSuggestBox').value;
	var idPays = '';
	var nomRegion = '';
	
	if (nomVilleSuggestBox != '') {		
		
		var nomDepartement = '';
		var nomVille = nomVilleSuggestBox;
		var dateDepart = '';
		var margeErreurDateDepart = '';
		var duree = '';
		var tarif = '';		
		var capacite = '';
		var typeLocation = '';
		
		//reset des valeurs de la recherche avancée
		resetRechercheAvancee();		
	}
	else {	
		
		if (ski == 0) {
			idPays = comboPays.getValue();		
			//rappel: value = id des catégories, label = libellé des catégories
			if ($('nomRegion').value != '') {					
				nomRegion = comboRegions.getRawValue();
			}
		}
		
		var nomDepartement = '';
		if ($('nomDepartement').value != '') {	
			//nomDepartement = $('nomDepartement').options[$('nomDepartement').selectedIndex].text;
			nomDepartement = comboDepartements.getRawValue();
		}
		
		var nomVille = comboVilles.getValue();
		var dateDepart = $('dateDepart').value;
		var margeErreurDateDepart = $('margeErreurDateDepart').value;
		var duree = $('duree').value;
		var tarif = $('tarif').value;
		var capacite = $('capacite').value;
		var typeLocation = $('typeLocation').value;
		
		if ((idPays == "") && (nomRegion == "") && (ski == 0)) {
			alert("Veuillez sélectionner un pays.");
			return;
		}	
		else {	
			if ((idPays == "")  && (ski == 0)) {
				alert("Veuillez sélectionner un pays.");
				return;
			}		
			if ((nomRegion == "") && (ski == 0)) {
				alert("Veuillez sélectionner une région.");
				return;
			}
		}		
	}	
	
	//alert(idPays+"|"+nomRegion+"|"+nomDepartement+"|"+nomVille+"|"+dateDepart+"|"+margeErreurDateDepart+"|"+duree+"|"+tarif+"|"+capacite+"|"+typeLocation);
	
	var url = 'index.php5?module=locations';
	url += '&typeAffichage=nu';
	url += '&debut='+debut;
	url += '&idPays='+idPays;
	url += '&nomRegion='+nomRegion;
	url += '&nomDepartement='+nomDepartement;
	url += '&nomVille='+nomVille;
	url += '&dateDepart='+dateDepart;
	url += '&margeErreurDateDepart='+margeErreurDateDepart;
	url += '&duree='+duree;
	url += '&tarif='+tarif;
	url += '&capacite='+capacite;
	url += '&typeLocation='+typeLocation;
	url += '&ski='+ski;
	
	afficherSpinner();
	new Ajax.Updater('contenu', url, 
					{onComplete: function() { cacherSpinner(); },
					evalScripts: true
					}
	);
}


function choixAjaxPays() {
	var idParent = comboPays.getValue();
	var niveau = 3;
	
	if (idParent == "") {
		majEtatInput();
		return;	
	}
	new Ajax.Updater('divRegion',
					 'index.php5?module=ajax&action=listerCategoriesFils&typeAffichage=nu&idParent='+idParent+'&niveau='+niveau+'&idUnivers='+idUnivers+'&ski='+ski,
					 {onComplete: function() {						 
						 initComboRegions();
						 majEtatInput();						 
						} });
}

function choixAjaxRegion() {
	var idParent = $('nomRegion').value;
	var niveau = 4;
	if (idParent == "") {
		majEtatInput();
		return;	
	}
	new Ajax.Updater('divDepartement',
					 'index.php5?module=ajax&action=listerCategoriesFils&typeAffichage=nu&idParent='+idParent+'&niveau='+niveau+'&idUnivers='+idUnivers+'&ski='+ski,
					 {onComplete: function() {
						 initComboDepartements();
						 majEtatInput(); 
						} });
}

function listerVille() {

	var idCategorie = comboDepartements.getValue();
	if (idCategorie == "") {
		majEtatInput();
		return;	
	}
	new Ajax.Updater('divVille',
					 'index.php5?module=ajax&action=listerVilles&typeAffichage=nu&idCategorie='+idCategorie+'&idUnivers='+idUnivers+'&ski='+ski,
					 {onComplete: function() {
						 initComboVilles();
						 majEtatInput(); 
						} });
}


Ext.onReady(function() { 

	if (tabParamUrl["debut"] == 0) {
		//return;
	}
	
	//define select handler
	var selectHandler = function(myDP, date) {
		//get the text field
		var field = document.getElementById('dateDepart');
		//add the selected date to the field
		field.value = date.format('d/m/Y');
		//hide the date picker
		myDP.hide();		
		majEtatInput();
	};
	
	//create the date picker
	var myDP = new Ext.DatePicker({
					startDay: 1,
					listeners: {'select':selectHandler}
	});
	
	//render the date picker
	myDP.render('calendar');

	//hide date picker straight away
	myDP.hide();
		
	//define click handler
	var clickHandler = function() {
		//show the date picker
		if(myDP.hidden) 
			myDP.show();
		else 
			myDP.hide();
	};
	
	//add listener for button click
	Ext.EventManager.on('openCalendar', 'click', clickHandler);
	
	
	/******************************************************/
	//SLIDER	
	new Ext.Slider({
        renderTo: 'custom-slider',
        width: 180,
        increment: 10,
        minValue: 0,
        maxValue: 4000,
        plugins: new Ext.ux.SliderTip()
    });
	
	
	if (ski == 1) {
		new Ajax.Updater('divDepartement',
					 'index.php5?module=ajax&action=listerCategoriesFils&typeAffichage=nu&niveau=4&idUnivers='+idUnivers+'&ski='+ski,
					 {onComplete: function() {
						 initComboDepartements();
						 majEtatInput(); 
						} });
	}

	if (ski == 0) {
		initComboPays();
		initComboRegions();
		initComboDepartements();
	}	
	
	initComboVilles();	
	initComboVillesSB();	
}); 

function initComboPays() {
	comboPays = new Ext.form.ComboBox({
    	typeAhead: true,
    	triggerAction: 'all',
    	transform:'idPays',
    	width:186,
		ctCls:'combo_recherche',
    	forceSelection:true,
		listeners: {
    		select: function(combo, record, index) {
    			choixAjaxPays();
    		}
  		}

	});
}

function initComboRegions() {
	comboRegions = new Ext.form.ComboBox({
    	typeAhead: true,
    	triggerAction: 'all',
    	transform:'nomRegion',
    	width:186,
		ctCls:'combo_recherche',
    	forceSelection:true,
		disabled:true,
		listWidth:270,
		maxHeight: 230,
		listeners: {
    		select: function(combo, record, index) {
				choixAjaxRegion();
    		}
  		}
	});
}

function initComboDepartements() {
	comboDepartements = new Ext.form.ComboBox({
    	typeAhead: true,
    	triggerAction: 'all',
    	transform:'nomDepartement',
    	width:186,
		ctCls:'combo_recherche',
    	forceSelection:true,
		disabled:true,
		listWidth:270,
		maxHeight: 200,
		listeners: {
    		select: function(combo, record, index) {
				listerVille();
    		}
  		}
	});
}

function initComboVilles() {
	comboVilles = new Ext.form.ComboBox({
    	typeAhead: true,
    	triggerAction: 'all',
    	transform:'nomVille',
    	width:186,
		ctCls:'combo_recherche',
    	forceSelection:true,
		disabled:true,
		listWidth:270,
		maxHeight: 170
	});
}


function saisieVilleSB() {
	
	var ville = $('nomVilleSuggestBox').value;
	
	if (ville == '') {				
		storeVillesSB.proxy.conn.url = 'index.php5?module=ajax&action=listerVillesSuggestBox&typeAffichage=nu&idUnivers='+idUnivers+'&ville=aaaa';
		storeVillesSB.reload(); 
		toolbar.changePage(0);
		gridSB.hide();
	}
	else {
		
		//remmplacement des tous les caractères non alpha-numériques par des tirets 
		//var regExpression=/[^A-Za-z0-9-]+/;
		ville = ville.replace(" ", "-");
		var regex=/^[^0-9a-zA-Z]+g/;
		ville = ville.replace(regex, "-");
		
		storeVillesSB.proxy.conn.url = 'index.php5?module=ajax&action=listerVillesSuggestBox&typeAffichage=nu&idUnivers='+idUnivers+'&ville='+ville+'&ski='+ski;
		storeVillesSB.reload(); 
		//gridSB.expand();
		gridSB.show();
	}
}


function initComboVillesSB() {
		
	storeVillesSB = new Ext.data.JsonStore({	
		totalProperty: 'total',	// total data, see json output
		root: 'results',	// see json output	
		url: 'index.php5?module=ajax&action=listerVillesSuggestBox&typeAffichage=nu&idUnivers='+idUnivers+'&ville=aaaa', 			
        fields: [{name: 'ville', type: 'string'},
				 {name: 'localisation', type: 'string'},
				 {name: 'nb', type: 'string'}]
    });

	storeVillesSB.load({params:{start: 0, limit: 10}});

	toolbar = new Ext.PagingToolbar({
					pageSize: 10,	// data to display
					store: storeVillesSB,
					displayInfo: false		
				  });
	
	gridSB = new Ext.grid.GridPanel({
        store: storeVillesSB,
        columns: [
            {id:'ville',header: "ville", width: 190, sortable: true, dataIndex: 'ville'},   
			{header: "localisation", width: 240, sortable: true, dataIndex: 'localisation'}, 
			{header: "nb", sortable: true, dataIndex: 'nb'}
        ],
        stripeRows: true,
        width:500,
		autoHeight: true,
		maxHeight: 200,
        title:'Paging Grid',
		hideHeaders: true,
		headerAsText: false,
		header: false,
		closable: true,
		bbar: toolbar,
		listeners: {
			rowclick: function(grid, rowIndex, e) {
				//var ville = $('nomVilleSuggestBox').value;
				var villeRecherche = grid.getStore().getAt(rowIndex).get('ville');				
				$('nomVilleSuggestBox').value = villeRecherche;
				gridSB.hide();
				storeVillesSB.removeAll();	
				toolbar.changePage(0);
				lancerRecherche(0);
			}
  		}
    });
	
	//alert('1');	
	gridSB.render('resultatsRechercheSuggestBox');
	gridSB.hide();
}


function resetRechercheAvancee() {

	$('duree').value = "";
	$('dateDepart').value = "";
	$('capacite').value = "";
	$('typeLocation').value = "";
	
	if (ski == 0) {
		comboPays.reset();
		comboRegions.reset();
		comboRegions.setDisabled(true);
	}
	comboDepartements.reset();	
	comboVilles.reset();
	comboDepartements.setDisabled(true);	
	comboVilles.setDisabled(true);
}


function majEtatInput() {
		
	//$('nomRegion').disabled = false;
	if (ski == 0) {
		comboRegions.setDisabled(false);
	}
	comboDepartements.setDisabled(false);
	comboVilles.setDisabled(false);
		
	//valeur du pays
	if ((ski == 0) && ($('idPays').value == "")) {
		//$('nomRegion').disabled = true;
		comboRegions.setDisabled(true);
		comboDepartements.setDisabled(true);
		comboVilles.setDisabled(true);
	}
	
	if ((ski == 0) && ($('nomRegion').value == "")) {
		comboDepartements.setDisabled(true);
		comboVilles.setDisabled(true);
	}
	
	
	if ($('nomDepartement').value == "") {
		comboVilles.setDisabled(true);
	}
	
	
	$('margeErreurDateDepart').disabled = true;
	$('duree').disabled = true;
	
	if ($('dateDepart').value != '') {
		
		if (isDateValide($('dateDepart').value)) {		
			$('margeErreurDateDepart').disabled = false;
			$('duree').disabled = false;
		}
		else {
			alert("La date de départ n'est pas valide.");	
			$('dateDepart').value = '';
		}
	}	
}



/************************************************************************************************/
/* Fonctions appelées depuis les pages de résultats (chemin de progession, navigation par page) 
/************************************************************************************************/

function effacerVille() {
	comboVilles.reset();
	lancerRecherche(0);
}

function effacerDepartement() {
	comboVilles.reset();
	comboDepartements.reset();	
	majEtatInput();
	lancerRecherche(0);
}