var u = 0;
var VILLAGES_PER_PAGE = 10;
var sorting = {
	REGION: "region",
	ALPHA: "alpha",
	PRICE: "price",
	DESTINATION: "destination"
}

var affichage = {
	DISPOS_ONLY: "dispos_only",
	DISPOS_PRICES: "dispos_prices"
}

var current_page = 1;
var loaded = false;
var villages = [];
var prices = {};
var localize_previews = {};
var messages = {};

var localized = [
    [ /^us/,
		{	day: /^\d{2}\/(\d{2})\/\d{4}$/,
			month:/^(\d{2})\/\d{2}\/\d{4}$/,
			year: /^\d{2}\/\d{2}\/(\d{4})$/
		}
	],
	[ /^dk/,
		{	day: /^(\d{2})\/\d{2}\/\d{4}$/,
			month:/^\d{2}\/(\d{2})\/\d{4}$/,
			year: /^\d{2}\/\d{2}\/(\d{4})$/
		}
	],
	[ /^fi/,
		{	day: /^(\d{2})\/\d{2}\/\d{4}$/,
			month:/^\d{2}\/(\d{2})\/\d{4}$/,
			year: /^\d{2}\/\d{2}\/(\d{4})$/
		}
	],
	[ /^fr/,
		{	day: /^(\d{2})\/\d{2}\/\d{4}$/,
			month:/^\d{2}\/(\d{2})\/\d{4}$/,
			year: /^\d{2}\/\d{2}\/(\d{4})$/
		}
	],
	[ /^de/,
		{	day: /^(\d{2})\/\d{2}\/\d{4}$/,
			month:/^\d{2}\/(\d{2})\/\d{4}$/,
			year: /^\d{2}\/\d{2}\/(\d{4})$/
		}
	],
	[ /^gr/,
		{	day: /^(\d{2})\/\d{2}\/\d{4}$/,
			month:/^\d{2}\/(\d{2})\/\d{4}$/,
			year: /^\d{2}\/\d{2}\/(\d{4})$/
		}
	],
	[ /^it/,
		{	day: /^(\d{2})\/\d{2}\/\d{4}$/,
			month:/^\d{2}\/(\d{2})\/\d{4}$/,
			year: /^\d{2}\/\d{2}\/(\d{4})$/
		}
	],
	[ /^nl/,
		{	day: /^(\d{2})\/\d{2}\/\d{4}$/,
			month:/^\d{2}\/(\d{2})\/\d{4}$/,
			year: /^\d{2}\/\d{2}\/(\d{4})$/
		}
	],
	[ /^no/,
		{	day: /^(\d{2})\/\d{2}\/\d{4}$/,
			month:/^\d{2}\/(\d{2})\/\d{4}$/,
			year: /^\d{2}\/\d{2}\/(\d{4})$/
		}
	],
	[ /^pl/,
		{	day: /^(\d{2})\/\d{2}\/\d{4}$/,
			month:/^\d{2}\/(\d{2})\/\d{4}$/,
			year: /^\d{2}\/\d{2}\/(\d{4})$/
		}
	],
	[ /^pt/,
		{	day: /^(\d{2})\/\d{2}\/\d{4}$/,
			month:/^\d{2}\/(\d{2})\/\d{4}$/,
			year: /^\d{2}\/\d{2}\/(\d{4})$/
		}
	],
	[ /^ru/,
		{	day: /^(\d{2})\/\d{2}\/\d{4}$/,
			month:/^\d{2}\/(\d{2})\/\d{4}$/,
			year: /^\d{2}\/\d{2}\/(\d{4})$/
		}
	],
	[ /^es/,
		{	day: /^(\d{2})\/\d{2}\/\d{4}$/,
			month:/^\d{2}\/(\d{2})\/\d{4}$/,
			year: /^\d{2}\/\d{2}\/(\d{4})$/
		}
	],
	[ /^se/,
		{	day: /^(\d{2})\/\d{2}\/\d{4}$/,
			month:/^\d{2}\/(\d{2})\/\d{4}$/,
			year: /^\d{2}\/\d{2}\/(\d{4})$/
		}
	],
	[ /^en/,
		{	day: /^(\d{2})\/\d{2}\/\d{4}$/,
			month:/^\d{2}\/(\d{2})\/\d{4}$/,
			year: /^\d{2}\/\d{2}\/(\d{4})$/
		}
	],
	[ /^ca/,
		{	day: /^\d{4}\/\d{2}\/(\d{2})$/,
			month:/^\d{4}\/(\d{2})\/\d{2}$/,
			year: /^(\d{4})\/\d{2}\/\d{2}$/
		}
	],
	[ /^cn/,
		{	day: /^\d{4}\/\d{2}\/(\d{2})$/,
			month:/^\d{4}\/(\d{2})\/\d{2}$/,
			year: /^(\d{4})\/\d{2}\/\d{2}$/
		}
	],
	[ /^jp/,
		{	day: /^\d{4}\/\d{2}\/(\d{2})$/,
			month:/^\d{4}\/(\d{2})\/\d{2}$/,
			year: /^(\d{4})\/\d{2}\/\d{2}$/
		}
	],
	[ /^kr/,
		{	day: /^\d{4}\/\d{2}\/(\d{2})$/,
			month:/^\d{4}\/(\d{2})\/\d{2}$/,
			year: /^(\d{4})\/\d{2}\/\d{2}$/
		}
	],
	[ /^tw/,
		{	day: /^\d{4}\/\d{2}\/(\d{2})$/,
			month:/^\d{4}\/(\d{2})\/\d{2}$/,
			year: /^(\d{4})\/\d{2}\/\d{2}$/
		}
	]
]

var $jq = jQuery.noConflict();
$jq(document).ready(function(){
	init();
});
function goConnect() {
	var i=0;
	searchform.departure = {date:$('resa_datedepartRMC'),delta:$('delta-depart'),duration:$('duration'),durationHidden:$('durationHidden')};
    searchform.villageType = {adults:$('type_3'),childcare:$('type_2'), noChildcare:$('type_1')};
    searchform.lang = $('with-lang');
	searchform.comfort = {villas_luxe:$('confort_1'),villages_5T:$('confort_2'),villages_4T:$('confort_3'),villages_3T:$('confort_4'),villages_2T:$('confort_5')};
	if ($('budget')) {
		searchform.budget = filter(function (node) {return (node.type.toLowerCase() == 'radio')}, $('budget').getElementsByTagName('input'));
	}
    searchform.childcares = {from_4_to_23:$('encadrement_1'),from_2_to_3:$('encadrement_2'),from_4_to_12:$('encadrement_3'),over_12:$('encadrement_4')};
    searchform.activities = filter(function (node) {return (node.type.toLowerCase() == 'checkbox' || node.type.toLowerCase() == 'radio')}, $('activities').getElementsByTagName('input'));

    // village type
    connect('type_3', 'onclick', doRepeatedFilterVillages);
    connect('type_2', 'onclick', doRepeatedFilterVillages);
    connect('type_1', 'onclick', doRepeatedFilterVillages);
    connect('confort_1', 'onclick', doRepeatedFilterVillages);
	connect('confort_2', 'onclick', doRepeatedFilterVillages);
	connect('confort_3', 'onclick', doRepeatedFilterVillages);
	connect('confort_4', 'onclick', doRepeatedFilterVillages);
	connect('confort_5', 'onclick', doRepeatedFilterVillages);
    // childcare
    connect('encadrement_1', 'onclick', doRepeatedFilterVillages);
    connect('encadrement_2', 'onclick', doRepeatedFilterVillages);
    connect('encadrement_3', 'onclick', doRepeatedFilterVillages);
    connect('encadrement_4', 'onclick', doRepeatedFilterVillages);
    // Budget
	if (searchform.budget) {
		connect('budget_1', 'onclick', doRepeatedFilterVillages);
		connect('budget_2', 'onclick', doRepeatedFilterVillages);
		connect('budget_3', 'onclick', doRepeatedFilterVillages);
		connect('budget_4', 'onclick', doRepeatedFilterVillages);
		connect('budget_5', 'onclick', doRepeatedFilterVillages);
	}
    // activities
    for(var i=1; i<=68; ++i) { // !!! NOTE GLA : 68 en dur !!!
        try {
            connect('activity-'+i, 'onclick', doRepeatedFilterVillages);
        } catch (e) {
            // If error, do nothing
            // This thing should probably be improved...
        }
    }

    connect('type_3', 'onclick', handleChildCare);
    connect('type_2', 'onclick', handleChildCare);
    connect('type_1', 'onclick', handleChildCare);
	
	// should the children block be hidden ?
	// if Adult Resorts OR Without Children Care are selected, THEN hide Children Care block
	if ( ($('type_1') && $('type_1').checked) || ($('type_3') && $('type_3').checked) ) {
		$jq('#children').hide();
	}
	
	// bloc dispo : manage adult resorts disabling
	connect('resa_nbenfants', 'onchange', handleAdultResorts);
	

    for(var i=1; i<=0; ++i) {
        connect('birthdate-'+i, 'onchange', checkCareRanges);
        connect('birthdate-'+i, 'onblur', checkCareRanges);
    }
	
    connect('compare-0', 'onclick', doComparaison);
    connect('compare-1', 'onclick', doComparaison);

    loaded = true;
    if(document.locationFilter) {
        signal(document, "loaded_document", document.locationFilter.region, document.locationFilter.country, document.locationFilter.lower, document.locationFilter.upper);
        disconnectAll(document, "loaded_document");
        document.locationFilter = null;
    }
    var qs = window.location.href.split("?")[1];

    if(qs) {
		var noParam = true;
       	var args = parseQueryString(qs);
		
		if (args.zone != null && args.enc != '') {
			noParam = false;
		}
		
		// Encadrement ('encadrement-4-23', 'encadrement-2-3', 'encadrement-4-12', 'encadrement-12plus')
		if ( (args.enc != null && args.enc != '') || (args.ENC != null && args.ENC != '') ){
			args.enc = transformEncParams(args.enc);
			var tabl = args.enc.split('/');
			var j = 0;
			while ( tabl[j]!= null  &&  typeof $(tabl[j]) != 'undefined'  && $(tabl[j]) != null ){
				$(tabl[j]).checked = true;
				j++;
			}
			noParam = false;
		}
	
		// Activite (ex pour Tennis : 'activity-28')
		if ( (args.act != null && args.act != '') || (args.ACT != null && args.ACT != '') ) {
			var tab = args.act.split('/');
			var i = 0;
			while ( tab[i]!= null ){
				$(tab[i]).checked = true;
				valAct = args.act;	
				i++;
			}
			noParam = false;
		}
	
		// Type de village ('adults-only', 'with-childcare')
		if ( (args.typev != null && args.typev != '') ){
			var typeVillage = "" + args.typev;
			typeVillage = transformTypeVillageParams(typeVillage);
			var tab = typeVillage.split('/');
			var i = 0;
			while ( tab[i]!= null ){
				if (typeof ($(tab[i])) != 'undefined') {
					$(tab[i]).checked = true;
				}
				i++;
			}
			noParam = false;
		}
		
		// Type de village ('adults-only', 'with-childcare')
		if (args.conf != null && args.conf != ''){
			var conf = args.conf;
			conf = transformConfParams(conf);
			var tabl = conf.split('/');
			var j = 0;
			while ( tabl[j]!= null  &&  typeof $(tabl[j]) != 'undefined'  && $(tabl[j]) != null ){
				$(tabl[j]).checked = true;
				j++;
			}
			noParam = false;
		}
		
		// si onvient du bloc Recherche
		if (args.from  ||  args.FROM){
			noParam = false;
			(typeof $('budget_1') != 'undefined'  &&  $('budget_1') != null  &&  $('budget_1').checked)?setComboWithTransport():'';
			(typeof $('budget_2') != 'undefined'  &&  $('budget_2') != null  &&   $('budget_2').checked)?setComboWithTransport():'';
			(typeof $('budget_3') != 'undefined'  &&  $('budget_3') != null  &&   $('budget_3').checked)?setComboWithTransport():'';
			(typeof $('budget_4') != 'undefined'  &&  $('budget_4') != null  &&  $('budget_4').checked)?setComboWithTransport():'';
		}
      	if(noParam){
			getFullList();
		} else {
			doFilterVillages();
		}
    } else {
      	getFullList();
    }

	if (getElementsByTagAndClassName('div','type_favorite')){
		if (villages_collection.hasFavorite){
			for (var i=0; i<getElementsByTagAndClassName('div','type_favorite').length;i++){
				var o=getElementsByTagAndClassName('div','type_favorite')[i];
				o.getElementsByTagName('img')[0].src=villages_collection.favorite;
			}
		}else{
			for (var i=0; i<getElementsByTagAndClassName('div','type_favorite').length;i++){
				var o=getElementsByTagAndClassName('div','type_favorite')[i];
				o.className += " displayNn";
			}
		}
	}
}

// transform the old param' values to the new values
function transformEncParams(params) {
	if (typeof params != 'undefined'  && params != null) {
		params = params.replace('-4-23', '_1');
		params = params.replace('-2-3', '_2');
		params = params.replace('-4-12', '_3');
		params = params.replace('-12plus', '_4');
	}
	return params;
}

// transform the old param' values to the new values
function transformTypeVillageParams(params) {
	if (typeof params != 'undefined'  && params != null) {
		params = params.replace('adults-only', 'type_3');
		params = params.replace('with-childcare', 'type_2');
		params = params.replace('indifferent', '');
	}
	return params;
}

// transform the old param' values to the new values
function transformConfParams(params) {
	if (typeof params != 'undefined'  && params != null) {
		if (params == '5') params = params.replace('5', 'confort_1/confort_2'); 
		if (params == '4') params = params.replace('4', 'confort_1/confort_2/confort_3');
		if (params == '3') params = params.replace('3', 'confort_1/confort_2/confort_3/confort_4');
		if (params == '2') params = params.replace('2', 'confort_1/confort_2/confort_3/confort_4/confort_5');
	}
	return params;
}

var searchform = {}
var tridentTemplate = IMG({src:"/2007/DotCom/images/rechercher/picto/picto-trident.gif",alt:"#"});
var villageTemplate = LI({'class':"Bmargin"},
	DIV({'class':"block ct_village_rmc noresize"},
	SPAN({'class':"topCorners"},
		SPAN({ 'class':"tl"}),
		SPAN({ 'class':"tr"})),
    DIV({'class':"ct_village_rmc_inside"},
		DIV({'class':"body ct_village_rmc_body"},
			DIV(null,
				DIV({'class':"floatL RmarginSm imgZone handler"},
					A({href:"#", onclick:'return false;'},"#{PH-VISU}")),
				DIV({'class':"moreDetailZone floatR"},
					DIV({'class':"head txtC texte_22 taille9 colorWhite upper bold"},
					"#{PH-DEST}"),
					DIV({'class':"body"},
						UL({'class':"Nmargin bold LpaddingLg"},
							LI(null,">",A({href:"#",'class':"Nunder handler"},"#{PH-LABEL-PREVIEW}"),
							LI(null,">",A({href:"#{PH-LINK-FICHE}",'class':"Nunder"},"#{PH-LABEL-DETAILS}"))))),
					DIV({'class':"foot BpaddingSm groupCheckLeft"},
						DIV({'class':"fline LpaddingLg"},
							INPUT({type:"checkbox",id:"compare",'class':"check checkbox",name:"comparaison", value:'#{PH-VILLAGE-ID}'}),
							LABEL({'for':"compare",'class':"Lmargin2 taille9"},"#{PH-LABEL-COMPARE}")),
						A({'class':"btn lien_16 LmarginLg",href:"#{PH-LINK-BOOK}"},
							SPAN({'class':"taille9 lineHeight17 LNpadding"},"#{PH-LABEL-BOOK}")))),
				DIV({'class':"infoVillage"},
					createDOM('h2',{'class':"taille14 bold TNmargin"}, 
						A({'class':"Nunder", href:"#{PH-LINK-FICHE}"}, "#{PH-H4}")),
					SPAN({'class':"bold Dblock Bpadding2"},"#{PH-H5}"),
					createDOM('P',{'class':'Nmargin lineHeight12 BpaddingSm'},"#{PH-PRICE}"),
					DIV({'class':"Tpadding13"},
						SPAN({'class':"floatL RmarginSm"},
							"#{PH-TRIDENTS}"
							),
						UL({ 'class':"pictos_targets LmarginSm"}),
						UL({ 'class':"pictos_activities"}),
						UL({ 'class':"pictos_experiences"})))),
			DIV({'class':'ct_village_rmc_infos clear'},
				DIV({'class':"floatL RmarginSm imgZone handler"},"#{PH-POINTSFORTS}"),
				DIV({ 'class':"otherView Tpadding"},
					DIV({ 'class':"block blockBorderGreyBright"},
						SPAN({ 'class':"topCorners"},
							SPAN({ 'class':"tl"}),
							SPAN({ 'class':"tr"})),
						DIV({ 'class':"blockBorderInside"},
							DIV({ 'class':"body paddingSm"},
								H3({'class':"taille12 u_color"},"#{PH-LABEL-TITLE}"),
								UL({ 'class':"Nmargin"},
									LI(null,"#{PH-POINTSFORTS-0}"),
									LI(null,"#{PH-POINTSFORTS-1}")))),
						SPAN({ 'class':"bottomCorners"},
							SPAN({ 'class':"bl"}),
							SPAN({ 'class':"br"}))))))),
	SPAN({ 'class':"bottomCorners"},
		SPAN({ 'class':"bl"}),
		SPAN({ 'class':"br"}))));                                   

var titleVillageClosed = createDOM('h1',{'class':'BmarginSm TpaddingLg Bpadding txtC upper cufon-light color bgWhite taille17'},"#{PH-VILLAGECLOSED}");
var recent_filter = null;
var current_village_list = null;
var location_filter = null;
var top_pagination = null;
var bottom_pagination = null;
var is_button = false;
var dommed = false;
var doPaginate = true;

function partition(lst, predicate) {
	var l1 = [];
	var l2 = [];
	var len = lst.length;
	for(var i=0; i<len; ++i) {
		var res = predicate(lst[i]);
		if(res) {
			l1.push(lst[i]);
		}else{
			l2.push(lst[i]);
		}
	}
	return [l1, l2];
}
function getFlashURL() {
    var flashdiv = document.getElementById('carte_du_monde');

    var flash = document.getElementsByTagName('embed')[1];
    if(!flash) {
        flash = filter(function (node) {
            return ("movie" == node.getAttribute('name').toLowerCase()) || ("src" == node.getAttribute('name').toLowerCase());
        },flashdiv.getElementsByTagName('param'))[0];
        if(!flash) return null;
        return flash.getAttribute('value');
    }
    return flash.src;
}
function getFlashURLComponents() {
    var url = getFlashURL();
    if(!url) return null;
    var params = {};
    var uri = url.split('?')[0];
    var paramsStrings = url.split('?')[1].split('&');
    for(var i=0; i<paramsStrings.length; ++i) {
        var items = paramsStrings[i].split('=');
        params[items[0]] = items[1];
    }
    return [uri, params];
}
function buildURI(url, params) {
    var paramStrings = [];
    for(param in params) {
        paramStrings.push(param + "=" + params[param]);
    }
    return url + '?' + paramStrings.join('&');
}
function resetFlashURL() {
    var tmp = getFlashURLComponents();
    if(!tmp) return;
    var flash_url = tmp[0];
    var flash_params = tmp[1];
    flash_params.actif = '0,0';
    var uri = buildURI(flash_url, flash_params);
    var carte = $('carte_du_monde');
    var parent = carte.parentNode;
    parent.removeChild(carte);
    var div = DIV({'id':'carte_du_monde'});
    parent.appendChild(div);
    var f = new FlashObject(uri, "carte_du_monde", "740", "233", "8", "#FFFFFF");
    f.addParam("wmode","transparent");
    f.write("carte_du_monde");
}
function getFullList() {
    newSearch();
    resetFlashURL(); 
 	prices_collection.load({'transport': "false"}, displayAllVillages, villages);
}
function setCurrentSeason(village) {
    var cs = null;
    
    if(village.currentSeason){return village;}
    if(currentSeason(village)) {
        cs = currentSeason(village);
    } else if(village.isWinter && village.winter) {
        cs = "winter";
        village.winter.season = "winter";
    } else if(village.summer) {
        cs = "summer";
        village.summer.season = "summer";
    } else if(village.winter) {
        cs = "winter";
        village.winter.season = "winter";
    }
    village.currentSeason = village[cs];
    var newVillage = {
        name: village.name,
        id: village.id,
        vendu: village.vendu,
        isWinter: village.isWinter,
        summer: village.summer,
        winter: village.winter,
        currentSeason: village[cs]
    }
    return village;
}
function displayAllVillages(villages) {
    recent_filter = null;
    location_filter = null;
    villages_list = villages;
	var indexes = [];
	for (var i=0;i<villages_list.length; i++) {
		if (villages_list[i].currentSeason != null  &&  villages_list[i].winter != null  &&  villages_list[i].summer != null
		&& villages_list[i].winter.typeV != villages_list[i].summer.typeV) {
			if (i>0  &&  villages_list[i-1].id != villages_list[i].id) {
				indexes.push(i);
			}
		}
	}
	
	for (var i=0; i<indexes.length; i++) {
		var index = indexes[i];
		var dupVillage = new Object();
		$jq.extend(true, dupVillage, villages_list[index+i]);
		// jquery ne type les objets
		// c'est pourquoi on recrée les objets date (pour comparaison des date quand on fait des recherches avec date de dispo)
		dupVillage.currentSeason.from = new Date(villages_list[index+i].summer.from);
		dupVillage.currentSeason.to = new Date(villages_list[index+i].summer.to);
		dupVillage.summer.from = new Date(villages_list[index+i].summer.from);
		dupVillage.summer.to = new Date(villages_list[index+i].summer.to);
		dupVillage.winter.from = new Date(villages_list[index+i].winter.from);
		dupVillage.winter.to = new Date(villages_list[index+i].winter.to);
		if (dupVillage.currentSeason != null  &&  dupVillage.winter != null  &&  dupVillage.summer != null
		&& dupVillage.winter.typeV != dupVillage.summer.typeV) {
			if (dupVillage.currentSeason.typeV != dupVillage.summer.typeV) {
				dupVillage.currentSeason = dupVillage.summer;
				dupVillage.currentSeason.season = 'summer';
				delete dupVillage.winter;
				delete villages[index+i].summer;
			} else if (dupVillage.currentSeason.typeV != dupVillage.winter.typeV){
				dupVillage.currentSeason = dupVillage.winter;
				dupVillage.currentSeason.season = 'winter';
				delete dupVillage.summer;
				delete villages[index+i].winter;
			}
		}
		villages_list.splice(index+i+1, 0, dupVillage);
	}
	
	var e0 = $('mainRechercheVillage');
	e0.style.display = '';
	// Eliminate villages without prices from the list
    villages_list = filter(function (village) {
        try {
            getCostFor(village.id);
        } catch(e) {
            return false;
        }
        return true;
    }, villages_list);
    try {
        var villagesDOMs = generateVillagesDOM(villages_list);
        current_village_list = zip(villages_list, map(getCostFor, map(function (village) {return village.id}, villages_list)), villagesDOMs);
    } catch(e) {
        if(is_button) {
            setEmptyVillageList();
            return;
        }
    }
	
    paginate(1);

	if (isOpenPop('chargement')){
		closePop('chargement');
	}
	if (current_village_list.length <= 0) {
		displayEmptyPage();
	} else {
		undoDisplayEmptyPage();
	}
}

function toggleCartouches(){
// selecteur complexe $$(selecteur)
// bout de code dupliqué de la méthode launch() Dans Module.js
// ceci sert à plier/déplier les cartouches
	var i=0, l=Module.modules.length, module, elms, elm;
	for(;i<l;i++){
		module = Module.modules[i];
		elms = $$(module[1]);
		for(var j=0, m=elms.length;j<m;j++){
			elm = elms[j];
			new window[module[0]](elm);
		}
	}
// FIN Selecteur
}


function generateAllVillagesDOM(villages) {
    var output = [];
	var village;
    for(var i=0,len=villages.length; i<len; ++i) {
        village = villages[i];
        var villageDOM = villageTemplate.cloneNode(true);
		villageDOM.firstChild.setAttribute('id', 'village_'+i); // attribuer un id au premier DIV de ce LI
        // Fill the cloned template with informations from the village
        var filledDom = fillDOMWith(villageDOM, village);

        if(filledDom) {
            output.push(filledDom);
        }
    }
	setTransportSortVisibility(village);
    return output;
}



// ajouter l'option

var saveElmPrice = null;
function setTransportSortVisibility(village){
	if (villages && villages.length>0 && village) {
		if (getCostFor(village.id)) {
			// affichage du dropDownList Avec/Sans Transport
			document.getElementById('with-transport_TOP').style.display = 'block';
			document.getElementById('with-transport_BOTTOM').style.display='block';
			// ajout de l'élement Prix à la dropDownList de tri par Destination/Prix
			var sel = document.getElementById('selectSort_TOP');
			if(sel.options[1].value != 'price') {
				sel.insertBefore(saveElmPrice, sel.options[1]);
				var sel = document.getElementById('selectSort_BOTTOM');
				elm2 = saveElmPrice.cloneNode(true);
				sel.insertBefore(elm2, sel.options[1]);
			}
		}else {
			document.getElementById('with-transport_TOP').style.display='none';
			document.getElementById('with-transport_BOTTOM').style.display='none';
			// enlever l'option
			var sel = document.getElementById('selectSort_TOP');
			var opt = sel.getElementsByTagName('option')[1];
			if(opt.value != 'destination') {
				saveElmPrice = opt;
				sel.removeChild(opt);
				var sel = document.getElementById('selectSort_BOTTOM');
				var opt = sel.getElementsByTagName('option')[1];
				sel.removeChild(opt);
			}
		}
	}
}

function checkCareRanges(e) {
    try {
        var ages = getTravelers();
    } catch (e) {
        return;
    }
    if(ages[4]) {
        $('encadrement-4-23').checked = true;
    } else {
        $('encadrement-4-23').checked = false;
    }
    if(ages[3]) {
        $('encadrement-2-3').checked = true;
    } else {
        $('encadrement-2-3').checked = false;
    }
    if(ages[2]) {
        $('encadrement-4-12').checked = true;
    } else {
        $('encadrement-4-12').checked = false;
    }
    if(ages[1]) {
        $('encadrement-12plus').checked = true;
    } else {
        $('encadrement-12plus').checked = false;
    }
}

var saved_ageOptions;
function handleChildCare(e) {
    if(searchform.villageType.adults.checked || searchform.villageType.noChildcare.checked) {
		var inputs_children = $jq('#children input');
		saved_ageOptions = "";
		for (var i=0;i<inputs_children.length; i++) {
			if ( inputs_children[i].checked == true) {
				inputs_children[i].checked = false;
				saved_ageOptions += inputs_children[i].name;
			}
			inputs_children[i].disabled = true;
		}
		($('children')) ? $jq('#children').slideUp("slow"):'';
    } else {
		var inputs_children = $jq('#children input');
		inputs_children;
		for (var i=0;i<inputs_children.length; i++) {
			inputs_children[i].disabled = false;
			if (saved_ageOptions.indexOf(inputs_children[i].name) >= 0 ) {
				inputs_children[i].checked = true;
			}
		}
		($('children')) ? $jq('#children').slideDown("slow"):'';
    }
	doFilterVillages(null, true);
}

// bloc dispo : manage adult resorts disabling
// if children selected : disable adult resorts 
// else enable adult resorts
function handleAdultResorts() {
	// disable villages adults if children Number > 0 in availabitlity block
	var elemt = searchform.villageType.adults;
	if ($('resa_nbenfants')  &&  $('resa_nbenfants').value > 0) {
		elemt.checked = false;
		elemt.disabled = true;
		($('children')) ? $jq('#children').slideDown("slow"):'';
	} else {
		elemt.checked = true;
		elemt.disabled = false;
		($('children')) ? $jq('#children').slideUp("slow"):'';
 	}
}


function filterVillageList() {
    var f = new Filter();
    // Start by filtering on the date: if that one doesn't work, there is no point in trying others.
    if(getIsoCurrentDate()) { 
        f.addPredicate(FilterBy.dates(getIsoCurrentDate(), getDecimalInteger(searchform.departure.duration.value), getDecimalInteger(searchform.departure.delta.value)));
    }

	var types = getTypes();
	if (types != 'undefined' && types != null) {
		f.addPredicate(FilterBy.typeOfVillage(types));
	}

	// NEW
	var comfort = getComfort();
    if(comfort != 'undefined'  && comfort != null) {
        f.addPredicate(FilterBy.confort(comfort));
    }
	if (searchform.budget) {
		f.addPredicate(FilterBy.budget(getBudget()));
	}

    var care_ranges = getChildCareRanges();
   
    if(care_ranges) {
        f.addPredicate(FilterBy.childrenCare(care_ranges));
    }

    var checked_activities = filter(function (node) {return node.checked}, searchform.activities);
    var activities_ids = map(function (node) {return /^activity-(\d+)$/.exec(node.id)[1]; }, checked_activities);
    f.addPredicate(FilterBy.activities(activities_ids));

    recent_filter = f;

    // We mustn't memoize the location filter into the recent filter list (or the location filters will start stacking)
    // it's memoized in the location_filter global.
    var filter_loc = new Filter(f);
    if(location_filter) { filter_loc.addPredicate(location_filter); };

    return filter_loc.apply(villages);
}


function displayPriceFor(id) {
    if(previews.prefixPosition) {
        return decode_utf8_browser(previews.currency) + String(getCostFor(id));
    } else {
        return String(getCostFor(id)) + previews.currency;
    }
}


function fillDOM(dom) {
	var html = dom.innerHTML;
	var repl = {
		'#{PH-VILLAGECLOSED}': previews.villageClosed
	}
	html = html.replace(/(#[{][^}]+})/g, function (ph) { return repl[ph]; } );
	dom.innerHTML = html;
	if(!dommed) {
		dommed = true;
	}
	return dom;
}

function generateVillagesDOM(villages) {
    var output = [];
	var village;
    for(var i=0,len=villages.length; i<len; ++i) {
        village = villages[i];
        var villageDOM = villageTemplate.cloneNode(true);
        // Fill the cloned template with informations from the village
        var seasonedVillage = {
            name: village.name,
            id: village.id,
            vendu: village.vendu,
            favorite: village.favorite,
            isWinter: village.isWinter,
            summer: village.summer,
            winter: village.winter,
            currentSeason: village[currentSeason(village)]
        }
        seasonedVillage.currentSeason.season = currentSeason(village);

		villageDOM.firstChild.setAttribute('id', 'village_'+i);
		
		var codPeriode = "";
		if (seasonedVillage.currentSeason.pe != village.defaultSaison) {
			codPeriode = seasonedVillage.currentSeason.pe;
		}
        var filledDom = fillDOMWith(villageDOM, seasonedVillage, codPeriode);
        output.push(filledDom);
    }
	setTransportSortVisibility(village);
    return output;
}

function insertVillagesBefore(baseNode, villages) {
    var parent = baseNode.parentNode.parentNode;
	parent = parent.getElementsByTagName('ul')[2];
	var position;
	var villageCldDOM = titleVillageClosed.cloneNode(true);
	var stop=false;
    for(var i=0,len = villages.length; i<len ; ++i) {
		// IE doesn't like my DOM, gotta go through innerHTML
		var test = LI({'class':villages[i].className});
		parent.appendChild(test);
		test.innerHTML = villages[i].innerHTML;

		if (!stop && getElementsByTagAndClassName('div', 'ct_village_rmc_inside', villages[i])[0].className.match(/.*journeyHighlight\b/)){
			var filledDom = fillDOM(villageCldDOM);
			parent.insertBefore(filledDom,test);
			stop=!stop;
			cufonize();
		}
    }
}

function addLocationFilter(region, country, lower, upper) {
    if(!loaded) {
        connect(document, "loaded_document", addLocationFilter);
        document.locationFilter = {
            "region": region,
            "country": country,
            "lower": lower,
            "upper": upper
        };
        return;
    }
    // MSIE fires the flash before the page is loaded...
    var f = new Filter(recent_filter);

    location_filter = FilterBy.location(region, country, parseInt(lower, 10), parseInt(upper,10)); 

    if(current_village_list) {
        f.addPredicate(location_filter);

        var v = f.apply(villages);
        if(getCurrentDate()) {
            prices_collection.load({'DATEDEP':getIsoCurrentDate(), 'duration':0, 'delta':0, 'transport': (($('with-transport').value!='without')?"true":"false")}, displayVillages, v);
        } else {
            prices_collection.load({'transport': ($('with-transport').checked?"true":"false")}, displayVillages, v);
        }
        displayVillages(v);
    }
}

function doRepeatedFilterVillages(e) {
    doFilterVillages(null, true);
}

function doFilterVillages(e, noButton) {
    if(!noButton) {
		is_button = true;
	}
    // BEWARE: duplicate code between this and addLocationFilter, keep in sync!
    if(e) {
        // If triggered via an event, stop the bubbling
        // and prevent the default action
        e.stop();
    }
	openPopLoadRMC('chargement');
	
	var v = filterVillageList();
	if (getIsoCurrentDate()) {
		prices_collection.load({'DATEDEP':getIsoCurrentDate(), 'duration':0, 'delta':0, 'transport': (($('with-transport').value!='without')?"true":"false")}, displayVillages, v);
	} else {
		var v = filterVillageList();
		prices_collection.load({'transport': "false"}, displayVillages, v);
	}
}

function reloadFilter() {
	var v = filterVillageList();
	if (getIsoCurrentDate()) {
		prices_collection.load({'DATEDEP':getIsoCurrentDate(), 'duration':0, 'delta':0, 'transport': (($('with-transport').value!='without')?"true":"false")}, displayVillages, v);
	} else {
		prices_collection.load({'transport': "false"}, displayVillages, v);
	}
}

function setEmptyVillageList() {
    current_village_list = null;
    for(var i=0, len=villages.length; i<len; ++i) {
        if(villages[i].selected) {
            villages[i].selected = false;
        }
    }
    updateVillagesCount(0);
}
function displayEmptyPage() { 
	var e0 = $('cartouchesDiv');
	e0.style.display = 'none';
	var div1 = $('village-search-form').getElementsByTagName('div')[0];
	div1.style.display='none';
	// cacher les boutons inutiles

	$('compare-1').style.display = 'none';

	if (typeof $('archiver_down') != 'undefined'  &&  $('archiver_down') != null ) {
		$('archiver_down').style.display = 'none';
	}
	
	if (isOpenPop('chargement')){
		closePop('chargement');
	}
}
function undoDisplayEmptyPage() { 
	var e0 = $('cartouchesDiv');
	e0.style.display = '';
	var div1 = $('village-search-form').getElementsByTagName('div')[0];

	div1.style.display='';
	// afficher les boutons qui ont été cachés
	$('compare-1').style.display = '';

	if (typeof $('archiver_down') != 'undefined'  &&  $('archiver_down') != null ) {
		$('archiver_down').style.display = '';
	}

   	if (isOpenPop('chargement')){
		closePop('chargement');
	}
}

function sortVillagesBy(sort_criteria, direction) {
	var invert = (direction == -1)?-1:1;
	switch(sort_criteria) {
        case "price":
            // Travel cost is stored as villageDate[1] in the current_village_list list.
            current_village_list.sort(function (a, b) {
                return invert * compare(a[1], b[1]);
            });
            break;
		case "region":	
			current_village_list.sort(function (a, b){
				return invert * compare(a[0].currentSeason.region,b[0].currentSeason.region);
			});
            break;
		case "destination":
			current_village_list.sort(function (a, b){
				return invert * compare(a[0].currentSeason.region,b[0].currentSeason.region);
			});
    }
    paginate(1);
}
function displayVillages(villages_list) {
    // sync displayAllVillages
	// Eliminate villages without prices from the list
	var e0 = $('mainRechercheVillage');
	e0.style.display = '';
        villages_list = filter(function (village) {
            try {
 				var cost_vi = getCostFor(village.id);
                if (cost_vi == undefined) {
               	return false;
                }
            } catch(e) {
                return false;
            }
            return true;
        }, villages_list);
    try {
        var villagesDOMs = generateVillagesDOM(villages_list);
        current_village_list = zip(villages_list, map(getCostFor, map(function (village) {return village.id}, villages_list)), villagesDOMs);
		var v = current_village_list;
		sortVillagesBy($('selectSort_TOP').value);
    } catch(e) {
            setEmptyVillageList();
            return;
    } 
	defaultVillageSort();
    
	if (isOpenPop('chargement')){
		closePop('chargement');
	}
	if (current_village_list.length <= 0) { 
		displayEmptyPage();
	} else {
		undoDisplayEmptyPage();
	}
	return current_village_list;
}
function defaultVillageSort(){
	if (villages_collection.sorting == sorting.REGION) {
		sortVillagesBy('region');
	} else {
		paginate(1);
	}
}
function createPageSwitcher(switchObject, current_page, total_pages) {
    var list = switchObject.getElementsByTagName('UL')[0];
    if(!list) return;

    for(var i=list.childNodes.length-1; i>=0;--i) {
        removeElement(list.childNodes[i]);
    }
    for(var i=1; i<=total_pages; ++i) {
        if(i == current_page) {
            list.appendChild(
                LI({'class':'Dinline bold'}, A({'class':'Nunder', href:'#', onclick:'paginate('+i+');return false;'}, i), (i != total_pages)?SPAN({'class':'taille8'},' - '):"")
            );
        } else {
            list.appendChild(
                LI({'class':'Dinline'}, A({'class':'Nunder', href:'#', onclick:'paginate('+i+');return false;'}, i), (i != total_pages)?SPAN({'class':'taille8'},' - '):"")
            );
        }
    }
}
function displayVillagesOnSinglePage() {
	doPaginate = !doPaginate;
	$('singlePage').style.display = (doPaginate)? '':'none';
	$('multiplePage').style.display = (doPaginate)? 'none':'';
	$('singlePage_BOTTOM').style.display = (doPaginate)? '':'none';
	$('multiplePage_BOTTOM').style.display = (doPaginate)? 'none':'';
    defaultVillageSort();
}
function paginate(page) {
    if(page) {
        var p = parseInt(page);
        current_page = (p>0)?p:1;
    }
    if(!top_pagination || !bottom_pagination) {
        top_pagination = document.getElementById('paginateTop');
        bottom_pagination = document.getElementById('paginateBottom');
    }

	// on ne garde que les villages à afficher
	// on le fait ici pour la paignation
	var villages = [];
	var villagesToDisplay = "";
	for(var i=0,len = current_village_list.length; i<len ; ++i) {
		if (villagesToDisplay.indexOf(current_village_list[i][0].id+"_"+current_village_list[i][0].currentSeason.typeV) < 0) {
			villagesToDisplay += current_village_list[i][0].id+"_"+current_village_list[i][0].currentSeason.typeV;
			villages.push(current_village_list[i]);
		}
	}
	updateVillagesCount(villages.length);
	
	var parts = partition(villages , function (village) {
		return prices[village[0].id][5];
	});
	var openVillages = parts[0];
	var closedVillages = parts[1];
	
	
	var partitionedList = openVillages.concat(closedVillages);

	if(doPaginate) {
		var paginated_list = partitionedList.slice((current_page-1)*VILLAGES_PER_PAGE, current_page*VILLAGES_PER_PAGE);
		createPageSwitcher(top_pagination, current_page, Math.ceil(partitionedList.length/VILLAGES_PER_PAGE));
		createPageSwitcher(bottom_pagination, current_page, Math.ceil(partitionedList.length/VILLAGES_PER_PAGE));
	} else {
		var paginated_list = partitionedList;
		createPageSwitcher(top_pagination, 1, 0);
		createPageSwitcher(bottom_pagination, 1, 0);
	}

	removeVillagesBefore(bottom_pagination);
	insertVillagesBefore(bottom_pagination,map(function (v) { return v[2];}, paginated_list));
    setCheckCheckedCheckBox();
	toggleCartouches();
}

// this function removes all villages between the Top_Pagination and Bottom_Pagination elements
// it takes an argument : the Bottom_pagination element
function removeVillagesBefore(switchObject){
    var list = switchObject.parentNode.parentNode.getElementsByTagName('UL')[2];
    if(!list) return;
    for(var i=list.childNodes.length-1; i>=0;--i) {
        removeElement(list.childNodes[i]);
    }
}

function getBudget(){
	if (!searchform.budget[1].checked  && !searchform.budget[2].checked  &&  !searchform.budget[3].checked  &&  !searchform.budget[4].checked) {
		// aucun budget n'a été selectionné
		if (searchform.budget[0].checked) {$jq('#budgetError').slideUp("slow");}
		return -1;
	}
	if ($('resa_datedepartRMC') ) {
		if ($('resa_datedepartRMC').value) {
			var tab = $('resa_datedepartRMC').value.split("/");
			if (isNaN(tab[0]) || isNaN(tab[1]) || isNaN(tab[2])) {
				$jq('#budgetError').slideDown("slow");
				var dateDuJour = DomUtils.getFormattedTodayDate2(formatDate, delay, hours);
				searchform.departure.date.value = dateDuJour;
				validationControleRecherche();
				closePop('chargement'); // closing waiting div
				doFilterVillages();
			}
		}
	}
	var range = -1;
	if (searchform.budget[1].checked) range = 1;
	if (searchform.budget[2].checked) range = 2;
	if (searchform.budget[3].checked) range = 3;
	if (searchform.budget[4].checked) range = 4;
	
	return range;
}

function hideBudgetErrorDiv() {
	if (searchform.budget) {
		var errorDiv = document.getElementById('budgetError');
		errorDiv.style.display='none';
	}
}

function setComboWithTransport(){
	$('with-transport_TOP').selectedIndex = 1;
	$('with-transport_BOTTOM').selectedIndex = 1;
	$('with-transport').value = $('with-transport_TOP').value;
}

function setComboWithoutTransport(){
	$('with-transport_TOP').selectedIndex = 0;
	$('with-transport_BOTTOM').selectedIndex = 0;
	$('with-transport').value = $('with-transport_TOP').value;
}

function getChildCareRanges() {
    if( searchform.childcares.from_4_to_23.checked
        || searchform.childcares.from_2_to_3.checked
        || searchform.childcares.from_4_to_12.checked
        || searchform.childcares.over_12.checked) {
        var care_ranges = ( searchform.childcares.from_4_to_23.checked?encadrements.FROM_4_TO_23_MONTH:0)
                            | (searchform.childcares.from_2_to_3.checked?encadrements.FROM_2_TO_3_YEARS:0)
                            | (searchform.childcares.from_4_to_12.checked?encadrements.FROM_4_TO_12_YEARS:0)
                            | (searchform.childcares.over_12.checked?encadrements.ABOVE_12_YEARS:0)
        return care_ranges;
    }
    return 0;
}

function getTypes() {
    if( searchform.villageType.adults.checked
        || searchform.villageType.noChildcare.checked
        || searchform.villageType.childcare.checked) {
        var types = (   searchform.villageType.adults.checked?typesVillages.RESERVE_ADULTE:0)
                            | (searchform.villageType.noChildcare.checked?typesVillages.SANS_ENCADREMENT_ENFANT:0)
                            | (searchform.villageType.childcare.checked?typesVillages.AVEC_ENCADREMENT_ENFANT:0)
        return types;
    }
    return -1;
}

function getComfort() {
    if( searchform.comfort.villas_luxe.checked
        || searchform.comfort.villages_5T.checked
        || searchform.comfort.villages_4T.checked
        || searchform.comfort.villages_3T.checked
        || searchform.comfort.villages_2T.checked) {
		var comfort = (   searchform.comfort.villas_luxe.checked?32:0)
                      | (searchform.comfort.villages_5T.checked?16:0)
                      | (searchform.comfort.villages_4T.checked?8:0)
                      | (searchform.comfort.villages_3T.checked?4:0)
                      | (searchform.comfort.villages_2T.checked?2:0)					
		return comfort;
    }
    return 0;
}

function clearDisplayedVillagesBetween(from, to) {
    while(from.nextSibling != to) {
        removeElement(from.nextSibling);
    }
}

function setVisuImage(name, image, template) {
    return '<img class="mediaFullSize" alt="'+name+'" title="'+messages.titles.visu+'" src="'+image+'">'
}

function setPointFortImage(name, image, template) {
    return '<img alt="'+name+'" title="'+messages.titles.strongPoint+'" src="'+image+'" class="mediaFullSize points_forts">'
}

function setfavoriteImage(name, image, template) {
    return image?'<img alt="'+name+'" src="'+image+'" class="favorite">':'';
}

function setDeparture(price,villageId,departurePhrase){
	var retour='';
	if (villages_collection.sorting==sorting.ALPHA){
		switch(villages_collection.vimode){
			case affichage.DISPOS_PRICES:
				retour = price + " <strong>" + villageId + "</strong>" + departurePhrase;
				break;
			case affichage.DISPOS_ONLY:
				retour = ' '+departurePhrase;
				break;
		}
	} else {
		retour = ' '+departurePhrase;
	}
	
	return retour;
}
function putVillageType(node, villageType) {
    var tpe = "";
    switch(villageType) {
        case typesVillages.RESERVE_ADULTE:
            tpe = messages.villageTypes.adultsonly;
            break;
        case typesVillages.SANS_ENCADREMENT_ENFANT:
            tpe = messages.villageTypes.nochildcare;
            break;
        case typesVillages.AVEC_ENCADREMENT_ENFANT:
            tpe = messages.villageTypes.withchildcare;
            break;
    }
    return tpe;
}
function getVillagePlaisirClass(plaisir) {
    switch(plaisir) {
        case plaisirs.VIVRE_EXCEPTIONNEL: return "mea_search_village_vivre_lexceptionnel";
        case plaisirs.SE_RESSOURCER: return "mea_search_village_ressourcer";
        case plaisirs.SE_DEPENSER: return "mea_search_village_depenser_depasser";
        case plaisirs.GOUTER_A_TOUT: return "mea_search_village_gouter_atout";
        case plaisirs.DECOUVRIR: return "mea_search_village_decouvrir";
        case plaisirs.VIVRE_200: return "mea_search_village_vivre200";
    }
    return "";
}
function setPointsForts(pointsForts, id) {
    var list = [[],[]];

    for(var i=0; i<(pointsForts.length); i+=2) {
        if(pointsForts[i]) {
            list[0].push('<li><span>> '+pointsForts[i]);
        }
        if(pointsForts[i+1]) {
            list[1].push('<li><span>> '+pointsForts[i+1]);
        }
    }
    return list[id].join("");
}

function updateVillagesCount(cnt) {
    var village = null;
    var pre_village = null;
    switch(cnt) {
        case 0:
            pre_village = messages.villagesCount.none.pre;
            village = messages.villagesCount.none.post;
            break;
        case 1:
            pre_village = messages.villagesCount.one.pre;
            village = messages.villagesCount.one.post;
            break;
        default:
            pre_village = messages.villagesCount.multiple.pre;
            village = messages.villagesCount.multiple.post;
            break;
    }

  var d = document.getElementById('mainInside');
    var t = getElementsByTagAndClassName('h1','BmarginSm',d)[0];
    replaceChildNodes(t, pre_village, STRONG(null, cnt?cnt:"0", village), decode_utf8_browser(messages.villagesCount.fittingcriteria) );
    d.style.display='block';
}

function getCostFor(id) {
    var v = computeCost(getTravelers(), prices[id]);
    return v;
}

function computeCost(bodies, prices) {
    return sum(map(function (body_count, price) {if(Boolean(price) == price) { return price} else { return body_count*price;}}, bodies, prices));

}

function getDateFromString(dateStr, format) { 
		var dateStr_slices = dateStr.split("/");
		if (format == 'MM/dd/yyyy') {
			var d = new Date(dateStr_slices[2], dateStr_slices[0], dateStr_slices[1]);
			d.setMonth(d.getMonth()-1);
			return d;
		}
		if (format == 'yyyy/MM/dd') {
			var d = new Date(dateStr_slices[0], dateStr_slices[1], dateStr_slices[2]);
			d.setMonth(d.getMonth()-1);
			return d;
		}
		if (format == 'yyyy/dd/MM') {
			var d = new Date(dateStr_slices[0], dateStr_slices[2], dateStr_slices[1]);
			d.setMonth(d.getMonth()-1);
			return d;
		}
		var d = new Date(dateStr_slices[2], dateStr_slices[1], dateStr_slices[0]);
		d.setMonth(d.getMonth()-1);
		return d;
}

function getTravelers() {
    var counts = [0,0,0,0,0];
    var errors = 0;
    var adultsCount = parseInt($('resa_nbadultes').options[$('resa_nbadultes').selectedIndex].value);
    counts[0] = adultsCount;
    var childrenCount = parseInt($('resa_nbenfants').options[$('resa_nbenfants').selectedIndex].value);
    for(var i=1;i<=childrenCount; ++i) { 
        var dates = getBirthDate(document.getElementsByName('birthdate-'+i)[1].value);
        if(dates) {
            var int_dates = map(parseInt,dates);
            var birthdate = new Date(int_dates[3], int_dates[2], int_dates[1]);
            var date_dep = getDateFromString(searchform.departure.date.value);
			var age = date_dep.getFullYear() - birthdate.getFullYear();
			if (date_dep.getMonth() < birthdate.getMonth() || (date_dep.getMonth() == birthdate.getMonth() && date_dep.getDate() < birthdate.getDate())) {
				age--;
			}
            if(age < 2) {
                ++counts[4];
            } else if(age < 4) {
                ++counts[3];
            } else if(age < 12) {
                ++counts[2];
            } else if(age < 18) {
                ++counts[1];
            } else {
                ++counts[0];
            }
        } else {
            errors++;
        }
    }
    if(errors > 0) {
        throw new Error(errors);
    }
    //console.log(counts);
    return counts;
}

function getBirthDate(dateString) {
    var locale = getLocale();
    var def = {
        day: /(\d{2})\/\d{2}\/\d{4}/,
        month: /\d{2}\/(\d{2})\/\d{4}/,
        year: /\d{2}\/\d{2}\/(\d{4})/
    }

    for(var i=0; i<localized.length; ++i) {
        if(localized[i][0].test(locale)) {
            def = localized[i][1];
            break;
        }
    }

    var d = dateString.match(def.day);
    var m = dateString.match(def.month);
    var y = dateString.match(def.year);
    if(d && m && y && validDate(d[1],m[1],y[1])) {
        return [null, d[1], m[1], y[1]];
    } else {
        return null;
    }
}

function getArrivalDate(village) {
    // Special version of "village": has a currentSeason attribute to use instead of currentSeason(village)
    var current_arrival = getCurrentDate();
    var current_departure = getDepartureDateFor(current_arrival);
    if(!current_departure) { return null; }
    // Test if the current arrival/departure dates are within the village's available dates.
    if(isVillageOpen(village, current_arrival, current_departure)) {
        return current_arrival;
    } else {
        var from = village.currentSeason.from;
        var to = village.currentSeason.to;
        var max_delta = parseInt(searchform.departure.delta.value);

        if((compare(current_arrival, from) == -1) && (compare(current_departure, to) < 1)) {
            // If the arrival date isn't within range
            for(var i=1; i<=max_delta; ++i) {
                current_arrival = getCurrentDate();
                current_arrival.setDate(current_arrival.getDate() + i);
                // go forward in time, and test until we manage to find a date that fits
                if(isVillageOpen(village, current_arrival, getDepartureDateFor(current_arrival))) {
                    return current_arrival;
                }
            }
        } else if((compare(current_arrival, from) > -1) && (compare(current_departure, to) == 1)) {
            // else if the departure date isn't within range
            for(var i=1; i<=max_delta; ++i) {
                // go backwards in time, and test until we manage to find a date that fits
                current_arrival = getCurrentDate();
                current_arrival.setDate(current_arrival.getDate() - i);
                if(isVillageOpen(village, current_arrival, getDepartureDateFor(current_arrival))) {
                    return current_arrival;
                }
            }
        }
        return null;
    }
}

function getDepartureDateFor(date) {
    if(!date) return null;
    var out = new Date(date.getFullYear(), date.getMonth(), date.getDate());
    out.setDate(out.getDate() + parseInt(searchform.departure.duration.value));

    return out;
}

function formatDay(d) {
    if(d >= 10) {
        return d;
    } else {
        return "0" + d;
    }
}

function formatMonth(m) {
    if((m+1) >= 10) {
        return (m+1);
    } else {
        return "0" + (m+1);
    }
}

function printDate(date) {
    // Print the date in a dd/mm/aaa format
    return formatDay(date.getDate()) + "/" + formatMonth(date.getMonth()) + "/" + date.getFullYear();
}

function display_list_scaffold(doIt) {
    var scaffold_items = getElementsByTagAndClassName('div','type_infos');
    var p = scaffold_items[0];
    do { p = p.previousSibling; }while(p.nodeName.toUpperCase() != 'P');
    scaffold_items = scaffold_items.concat(get_tds(getElementsByTagAndClassName('td','right')[0]));
    var except = $('new-research-button');
    for(var i=0,len=scaffold_items.length; i<len; ++i) {
        if(scaffold_items[i] != except) {
            scaffold_items[i].style.display = doIt?'':'none';
        }
        p.style.fontSize = doIt?'':'120%';
    }
}

function display_compare_villages(doIt) {
    if(!top_pagination || !bottom_pagination) {
        var paginations = getElementsByTagAndClassName('table','pages');
        top_pagination = paginations[0];
        bottom_pagination = paginations[1];
    }
    top_pagination.style.display = doIt?'':'none';
    bottom_pagination.style.display = doIt?'':'none';

    if(!doIt) {
        var inpts = filter(function (node) {
            return node.type == "checkbox";
        }, top_pagination.parentNode.getElementsByTagName('input'));
        map(function (node) {
            node.parentNode.style.visibility = "hidden";
        }, inpts);
    }
}

function display_pagination(doIt) {
    if(!top_pagination || !bottom_pagination) {
        var paginations = getElementsByTagAndClassName('table','pages');
        top_pagination = paginations[0];
        bottom_pagination = paginations[1];
    }
    top_pagination.getElementsByTagName('ul')[0].style.display = doIt?'':'none';
    bottom_pagination.getElementsByTagName('ul')[0].style.display = doIt?'':'none';
}

function get_tds(base_td) {
    var tds = filter(function (node) {
        return node.parentNode.parentNode.parentNode == base_td
                || node.parentNode.parentNode.parentNode.parentNode == base_td;
    }, base_td.getElementsByTagName('td'));
    return tds;
}

function validDate(d, m, y) {
    d = parseInt(d, 10);
    m = parseInt(m, 10);
    y = parseInt(y, 10);
    var dte = new Date(y, m-1, d);
    return (dte.getFullYear() == y
            && dte.getMonth() == m-1
            && dte.getDate() == d);
}

function getBirthError(count) {
    switch(parseInt(count)) {
        case 1: return messages.errors.birthdate.single;
        default: return count + messages.errors.birthdate.multiple;
    }
}

function checkCheckedCheckBox(e) {
    var id = e.src().value; 
    var village = filter(function (village) { return village[0].id == id; }, current_village_list)[0][0];

    var inpts = filter(function (node) {
		return node.type == "checkbox";
    }, top_pagination.parentNode.parentNode.getElementsByTagName('input'));

    village.selected = e.src().checked;

    var selected_villages = filter(function (village) { return village[0].selected}, current_village_list);
    var disable = (selected_villages.length >= 3);
    map(function (node) {
        if(!isSelectedVillage(node.value, selected_villages)) {
            node.disabled = disable;
        } else {
            node.checked = true;
        }
    }, inpts);
}

function setCheckCheckedCheckBox() {
    var inpts = filter(function (node) {
        return node.type == "checkbox";
    }, top_pagination.parentNode.parentNode.getElementsByTagName('input'));
    var selected_villages = filter(function (village) {return village[0].selected;}, current_village_list);
    var disable = (selected_villages.length >= 3);
    map(function (node) {
        if(!isSelectedVillage(node.value, selected_villages)) {
            node.disabled = disable;
        } else {
            node.checked = true;
        }
        connect(node, 'onclick', checkCheckedCheckBox);
    }, inpts);
}

function isSelectedVillage(id, selected_villages) {
    return filter(function (village) { return id == village[0].id; }, selected_villages).length != 0;
}

function newSearch() {
    $('village-search-form').reset();
    resetFlashURL();
    setEmptyVillageList();
    return false;
}

function afficheAide(e,id){
	var o = e.src();
	o.className = o.className.match(/\baideOn\b/)?o.className.replace(/aideOn/g,''):o.className+' aideOn';
	if (id==null || id==''){
		var table = gotoParent(o,'table');
		var blockAide = table.getElementsByTagName('DIV');
		
		for (var i=1;i<table.rows.length;i++){
			table.rows[i].className = table.rows[i].className.match(/\bdisplayNn\b/)?table.rows[i].className.replace(/displayNn/g,'') :table.rows[i].className+" displayNn";
		}
	}else{
		$(id).className = $(id).className.match(/\bdisplayNn\b/)?$(id).className.replace(/displayNn/g,''):$(id).className+' displayNn';
	}
	o.blur();
}

function afficheAffiche(e,id){
	var o = e.src();
	o.className = o.className.match(/\baideOn\b/)?o.className.replace(/aideOn/g,''):o.className+' aideOn';
	$(id).className = $(id).className.match(/\bdisplayNn\b/)?$(id).className.replace(/displayNn/g,''):$(id).className+' displayNn';
	
	
	var o = e.src();
	var table = gotoParent(o,'table');
	var blockAide = table.getElementsByTagName('DIV');

	for (var i=1;i<table.rows.length;i++){
		table.rows[i].className = table.rows[i].className.match(/\bdisplayNn\b/)?table.rows[i].className.replace(/displayNn/g,'') :table.rows[i].className+" displayNn";
	}
	o.blur();
}

function showChargement(visible){
	var charge = $('chargement'); 
	charge.className = visible?charge.className+' show':charge.className.replace(/show/g,'');
}

function sortVillages(element) {
	sortVillagesBy(element[element.selectedIndex].value);
	$('selectSort_TOP').selectedIndex = element.selectedIndex;
	$('selectSort_BOTTOM').selectedIndex = element.selectedIndex;
}

function displayPriceWithTransport(element){
	$('with-transport').value = element.value;
	sortVillagesBy($('selectSort_TOP').value);
	$('with-transport_TOP').selectedIndex = element.selectedIndex;
	$('with-transport_BOTTOM').selectedIndex = element.selectedIndex;
	doFilterVillages();
}

function isValidDate(date) {
	return !isNaN(date.split("/")[0]) && !isNaN(date.split("/")[1]) && !isNaN(date.split("/")[2]);
}

function fillDOMWith(dom, village, codPeriode) {
	var p = prices;
	var price = prices[village.id];
	var valide = price[5];
	!prices[(village.id)][5]?addElementClass(getElementsByTagAndClassName('div', 'ct_village_rmc_inside', dom)[0], " journeyHighlight"):addElementClass(getElementsByTagAndClassName('div', 'ct_village_rmc_inside', dom)[0], "");
 var departure = getArrivalDate(village);
 var departure_phrase = "";
	if(prices[(village.id)][5]) {
        if (getCostFor(village.id) != 0) {
			var participants = previews.pour + ' ' 
								+ (($('resa_nbadultes') && $('resa_nbadultes').value>0)?$('resa_nbadultes').value + ' ' +previews.adultes:'') + ' ' 
								+ (($('resa_nbenfants') && $('resa_nbenfants').value>0)?$('resa_nbenfants').value+' '+previews.children:'');
			departure_phrase = departure?" " + previews.date + " " + printDate(departure):'';
			departure_phrase += (villages_collection.duree && departure)?" " + previews.duration + " " + prices[village.id][6] + " " + previews.durationDate:'';
			if (villages_collection.sorting==sorting.ALPHA){
				switch(villages_collection.vimode){
					case affichage.DISPOS_PRICES: 
					departure_phrase =  previews.price + "<strong> " + displayPriceFor(village.id) + "</strong> " + participants + ' ' + departure_phrase;
					break;
				}
			}
		} else {
			departure_phrase = "";
		}
	} else {
		departure_phrase = "";
	}
	var ficheUrl = '/cm/villagesHeading.do?';
	var bookingUrl = '/cm/startBooking.do?';
	var qs = window.location.href.split("?")[1];
	if(qs) {
		var args = parseQueryString(qs);
		ficheUrl += 'PAYS=' + args.PAYS + '&LANG=' + args.LANG + '&CODLSC=' + village.id;
		if (codPeriode != null  &&  codPeriode != "") 
			ficheUrl += '&CODPER=' + codPeriode;
		
		if (args.PAYS != '196' && args.LANG != 'HE') {
			bookingUrl += 'PAYS=' + args.PAYS + '&LANG=' + args.LANG + '&preVillage=' + village.id + '&preCity=&nbAdults='
						 + $('resa_nbadultes').value + '&nbChildren=' + $('resa_nbenfants').value;
			($('resa_datedepartRMC') && $('resa_datedepartRMC').value && isValidDate($('resa_datedepartRMC').value)) ? bookingUrl+='&preDate='+$('resa_datedepartRMC').value : '';
			if ($('resa_nbenfants')  &&  $('resa_nbenfants').value>0) {
				var ddn = "&ddn=";
				for (var i=1; i<=$('resa_nbenfants').value; i++) {
					(i>1) ? ddn += ',' : '';
					ddn += document.getElementsByName('birthdate-'+i)[1].value;

				}
				bookingUrl += ddn;
			}
		} else {
			var bookingUrl = '/cm/bookingRequest.do?';
			bookingUrl += 'PAYS=' + args.PAYS + '&LANG=' + args.LANG + '&village=' + village.id 
					+ '&nbEnfants=' + $('resa_nbenfants').value 
					+ '&nbParticipants=' + (parseInt($('resa_nbadultes').value) + parseInt($('resa_nbenfants').value));
			($('resa_datedepartRMC') && $('resa_datedepartRMC').value && isValidDate($('resa_datedepartRMC').value)) ? bookingUrl+='&dateDeDebut='+$('resa_datedepartRMC').value : '';
			if ($('resa_nbenfants')  &&  $('resa_nbenfants').value>0) {
				var ddn = "&dateDeNaissance=";
				for (var i=1; i<=$('resa_nbenfants').value; i++) {
					(i>1) ? ddn += ',' : '';
					ddn += document.getElementsByName('birthdate-'+i)[1].value;
				}
				bookingUrl += ddn;
			}
		}
	}
    var html = dom.innerHTML;
    var repl = {
        '#{PH-H4}': (village.favorite?setfavoriteImage(village.name, villages_collection.favorite):'') + " " + decode_utf8_browser(village.name),
        '#{PH-H5}': decode_utf8_browser(village.currentSeason.preview.localization),
        '#{PH-DEPARTURE}': decode_utf8_browser(departure_phrase),
        '#{PH-TRIDENTS}': setVisuTridents(village.currentSeason.tridents, decode_utf8_browser((village.currentSeason.pictos && village.currentSeason.pictos.confort) ? village.currentSeason.pictos.confort : "")),
        '#{PH-VISU}': setVisuImage(village.name, prices[(village.id)][5]?village.currentSeason.preview.imgClosed:village.currentSeason.preview.imgClosed.replace('155x90','155x90_gris')),
        '#{PH-POINTSFORTS}': setPointFortImage(village.name, prices[(village.id)][5]?village.currentSeason.preview.imgOpen:village.currentSeason.preview.imgOpen.replace('155x90','155x90_gris')),
        '#{PH-POINTSFORTS-0}': decode_utf8_browser(setPointsForts(village.currentSeason.preview.strongPoints, 0)),
        '#{PH-POINTSFORTS-1}': decode_utf8_browser(setPointsForts(village.currentSeason.preview.strongPoints, 1)),
        '#{PH-LABEL-PREVIEW}': decode_utf8_browser(previews.preview),
        '#{PH-LABEL-DETAILS}': decode_utf8_browser(previews.details),
        '#{PH-LABEL-COMPARE}':  decode_utf8_browser(previews.compare),
        '#{PH-LABEL-BOOK}': decode_utf8_browser(previews.book),
        '#{PH-LINK-BOOK}': bookingUrl,
        '#{PH-LABEL-TITLE}': decode_utf8_browser(previews.title),
        '#{PH-DEST}': decode_utf8_browser(village.currentSeason.dest),
		'#{PH-LINK-FICHE}': ficheUrl,
		'#{PH-PRICE}': decode_utf8_browser(departure_phrase),
		'#{PH-VILLAGE-ID}': decode_utf8_browser(village.id)
	}

	var html_encoded_repl = {
        '#{PH-LINK-BOOK}': bookingUrl,
        '#{PH-LINK-FICHE}' : ficheUrl
    }
    html = html.replace(/(#{[^}]+})/g, function (ph) { return repl[ph]; } );
    html = html.replace(/(#%7B[^%]+%7D)/g, function (ph) {return html_encoded_repl[decodeURI(ph)]; });

    dom.innerHTML = html;
	addElementClass(dom, village.currentSeason.couleur);
	if (village.currentSeason.pictos) {
		dom = addPictos(village.currentSeason.pictos.cible, dom, 'cible');
		dom = addPictos(village.currentSeason.pictos.activites, dom, 'activites');
		dom = addPictos(village.currentSeason.pictos.produits, dom, 'produits');
	}
    if(!dommed) {
        dommed = true;
    }
	dom.id = village.id
	
	return dom;
}

function setVisuTridents(tridents, name) {
    return '<img class="tridentImg tipBox Vmiddle" title="'+name+'" alt="'+tridents+' - '+name+'" src="/2010/js/px.gif">';
}

function addPictos(listeElm, dom, type) {
	if (!listeElm || listeElm.length == 0) return dom;
	for (var i=0; i<listeElm.length;i++) {
		if (listeElm[i].cssClass  &&  listeElm[i].title) {
			if ( type=='activites') {
				var li = LI({'class':"activity " +listeElm[i].cssClass + " tipBox", alt:""+listeElm[i].title, title:""+listeElm[i].title},""+listeElm[i].title);
				var parent = getElementsByTagAndClassName('ul', 'pictos_activities', dom)[0];
				parent.appendChild(li);
			} else if (type=='produits') {
				var li = LI({'class':"experience " + listeElm[i].cssClass + "  tipBox", alt:""+listeElm[i].title, title:""+listeElm[i].title},""+listeElm[i].title);
				var parent = getElementsByTagAndClassName('ul', 'pictos_experiences', dom)[0];
				parent.appendChild(li);
			} else if (type=='cible') {
				var li = LI({'class':"target " + listeElm[i].cssClass + "  tipBox", alt:""+listeElm[i].title, title:""+listeElm[i].title},""+listeElm[i].title);
				var parent = getElementsByTagAndClassName('ul', 'pictos_targets', dom)[0];
				parent.appendChild(li);
			}
		}
	}
	return dom;
}


function openInsidePopupArchiv(popupId) {
	if (typeof(window['ouverture']) != "undefined") {
		// Fermeture d'une popup deja ouverte
		if (ouverture != false) {
			closeInsidePopup(ouverture);
		}
		// Enregistrement du nom de la popup ouverte
		ouverture = popupId;
	}
	openPop(popupId);
}

function closeInsidePopup(popupId) {
	closePop(popupId || "insidePopup");
}

function openActivitiesTabs() { 
	var li_elements = $('activities').getElements('li.item');//activities
	for (var k=0; li_elements.length && li_elements[k]; k++) {
		var ongletInputs = li_elements[k].getElements('input');
		var wasOpened = false;
		for (var i=0; i<ongletInputs.length; i++) {
			if (ongletInputs[i].checked ) { // si une case est cachée on ouvre l'onglet correspondant
				clubmedInstances.searchEngineVillagePrice.toggle.items[k].open();
				wasOpened = true;
				break;
			}
		}
		if (!wasOpened) { // fermer l'onglet s'il n'y a aucune activité cochée
			clubmedInstances.searchEngineVillagePrice.toggle.items[k].close();
		}
	}
}

function isOpenPop(popId){
	var pop = document.getElementById(popId);
	if (pop && pop.style.display == 'block'){
		return true;
	}
	return false;
}

function validateDateDispo() {
	var error = [];
	var formatDate = clubmedInstances.reservationEngine.datas.dates.formatDate;
	var departDate = clubmedInstances.reservationEngine.resa_datedepartRMC.value;
	if (!DomUtils.checkDateFormat(departDate, formatDate)) {
		// controle date depart
		error.push(DomUtils.isEmptyToReplace(clubmedInstances.reservationEngine.datas.errors["LIB_BR_error_dateDep_2010"], "LIB_BR_error_dateDep_2010"));
	}
	// controle date enfant
	var numDatesEnfantsNotOk = clubmedInstances.reservationEngine.root.getElements('.dateEnfant input').filter(function(inp) {
		if($jq(inp).closest('.dateEnfant').css('display')!="none"){
			dtn = formatageDate(inp.value);
			var dateNaissance = getDateFromFormat(dtn, formatDate);
			var ddp = getDateFromFormat(departDate, formatDate);
			if (ddp==0) {
				return false;
			}
			if(!DomUtils.checkDateFormat(inp.value, formatDate) ){
				return true;
			}
			if (!isKid(dateNaissance, ddp)) {
				return true;
			}
		}
	}).length;
	if (numDatesEnfantsNotOk>0) {
		error.push(DomUtils.isEmptyToReplace(clubmedInstances.reservationEngine.datas.errors["LIB_BR_error_ddnEnfants_2010"], "LIB_BR_error_ddnEnfants_2010"));
	}
	// si pas d'erreur, on cache la div d'erreur.
	clubmedInstances.reservationEngine.formTip.hide();


	if (error.length>0) { // erreur pas de submit
		clubmedInstances.reservationEngine.formTip.text = error.join('<br/>\n');
		clubmedInstances.reservationEngine.formTip.show();
		return false;
	}
	return true;
}
