var searchForm;
SearchForm = function(UrlResult) {
    this.tab_panel_checkbox = new Array();
    //url vers laquelle va Ãªtre envoyÃ©e la requÃ¨te
    this.UrlRechercheDispo = UrlResult;
    this.form = document.forms[0];
    this.ouvre_dans_popup = true;
}

function DesactiveZones(CbTous) {
	if (CbTous.checked) {
		for (var i = 1; i <= 5; i++) {
			document.getElementById('destinationCb' + i).checked = false;
		}
	}
}

//Mode ou l'on saisie le lieux via une textbox qui suggÃ¨re des solutions
//IdHiddenFieldTerritoire : champ cachÃ© contenant le code administratif cherchÃ© (cas ou on saisi une rÃ©gion)
//IdTextBoxLieux : champ texte ou l'utilisateur saisi sa recherche
//AffichePageLieuxIntermediaire : si a vrai, les suggestion prÃ©cises apparaitront dans une autre page, sinon dans une light box
//IdTbLat : text box qui contient le gps de latitude recherchÃ©
//IdTbLon : text box qui contient le gps de longitude recherchÃ©
//IDDivSuggestion : cadre qui contient les suggestion "simple"
//IDDivDetails : cadre qui contient les suggestion dÃ©taillÃ©e
//IDSamePlace : champ cachÃ© qui dÃ©termine si oui ou non on doit rafraichir les informations de latitude et longitude et admincode
SearchForm.prototype.SetMode1 = function(IdHiddenFieldTerritoire, IdTextBoxLieux, IdTbLat, IdTbLon, IDDivSuggestion, IDDivDetails, UrlRedirection, Filtre) {
    //champ cachÃ© qui va contenir les codes administratifs
    //alert("HIF : " +IdHiddenFieldTerritoire);
    //alert(" / val : " + document.getElementById(IdHiddenFieldTerritoire).value);
    this.hf_territoire = document.getElementById(IdHiddenFieldTerritoire);
    this.IsSamePlace = this.hf_territoire.value.trim != '';
    //text box qui contient le texte de recherche de lieux
    this.tb_lieux = document.getElementById(IdTextBoxLieux);
    this.est_auto_complete_lieux = typeof (this.tb_lieux) != "undefined" && this.tb_lieux != null;
    //champs qui vont contenir la latitude / longitude
    this.tb_lat = document.getElementById(IdTbLat);
    this.tb_lon = document.getElementById(IdTbLon);
    if (this.est_auto_complete_lieux) {
        this.tb_lieux.onfocus = SetAsNotSamePlace;
        if (document.addEventListener) {
            this.tb_lieux.addEventListener('keyup', GetAutoCompleteList, false);
        } else if (document.attachEvent) {
            this.tb_lieux.attachEvent('onkeyup', GetAutoCompleteList, false);
        }
        //        this.AutoComplete = new Ajax.Autocompleter(IdTextBoxLieux,IDDivSuggestion);
        //      
        //          this.AutoComplete.options.ignoreCase = true ;
        //          this.AutoComplete.getUpdatedChoices = GetAutoCompleteList;
        this.div_suggestion = document.getElementById(IDDivDetails);
        //Oui ou non le choix des leixu se fait sur une page intermÃ©diaire
        this.detailPage = UrlRedirection.trim() != '';
        this.UrlRedirectLieux = UrlRedirection;
    }
    this.filtreMode1 = ( Filtre) ? Filtre : "";
    this.estMode1 = true;
}
//Mode ou l'utilisateur selectionne parmis plusieurs ville / zones
//IdHiddenFieldTerritoire : champ cachÃ© contenant le code administratif cherchÃ© (cas ou on saisi une rÃ©gion)
//IdTbLat : text box qui contient le gps de latitude recherchÃ©
//IdTbLon : text box qui contient le gps de longitude recherchÃ©
SearchForm.prototype.SetMode2 = function(IdHiddenFieldTerritoire, IdTbLat, IdTbLon) {
    //champ cachÃ© qui va contenir les codes administratifs
    this.hf_territoire = document.getElementById(IdHiddenFieldTerritoire);
    //champs qui vont contenir la latitude / longitude
    this.tb_lat = document.getElementById(IdTbLat);
    this.tb_lon = document.getElementById(IdTbLon);
    this.estMode2 = true;
}
SearchForm.prototype.SetSuperOS = function(IDSelectSOS) {
    this.select_sos = document.getElementById(IDSelectSOS);
}
//Retourne vrai si l'on considÃ¨re que la recherche ufi de l'utilisateur n'a pas changÃ©
SearchForm.prototype.IsSamePlace = function() {

    return (typeof (this.samePlace) == "undefined" || this.samePlace.value == 'true');
}
//Va chercher des suggestion de lieux Ã  l'utilisateur

SearchForm.prototype.SearchPlace = function() {
    if (this.tb_lieux.value.trim() != '') {
        this.ShowWait();
        this.InteruptRequest(this.requete_lieux);
        this.requete_lieux = PageMethods._staticInstance.GetCompletionList(this.tb_lieux.value, 10, "",this.filtreMode1, OnComplete2, OnTimeOut2, OnError2);
    }
    else {
        AutoComplete_HideDropdown(this.tb_lieux.id);
    }
}
SearchForm.prototype.InteruptRequest = function(request) {
    if (request) {
        var exec = request.get_executor();
        if (exec.get_started()) {
            exec.abort();
        }
    }
}
//Passe le curseur en mode attente
SearchForm.prototype.ShowWait = function() {
    document.body.style.cursor = 'wait';
}
//EnlÃ¨ve le mode attente du curseur
SearchForm.prototype.HideWait = function() {
    document.body.style.cursor = 'default';
}
//Affiche les suggestions
SearchForm.prototype.ShowPlaces = function(result) {
    this.HideWait();
    //alert(this.tb_lieux.id);

    AutoComplete_Create(this.tb_lieux.id, result);
    AutoComplete_ShowDropdown(this.tb_lieux.id);
}
//Affiche des suggestions plus dÃ©taillÃ©es
SearchForm.prototype.ShowPlacesDetails = function(result) {
    this.HideWait();
    this.result_temp = result;
    if (result.length <= 1) {
        if (result.length == 0) {
            setLatLonTB("", "");
        }
        else {
            if (result[0].admin_code == "") {
                setLatLonTB(result[0].gps_latitude, result[0].gps_longitude);
            }
            else {
                this.setAdminCode(result[0]);
            }
        }
        this.DoCallBackRequest(false);
    }
    else {
        var obj = { data: result };
        this.div_suggestion.innerHTML = template_detail_all.process(obj);
        this.div_suggestion.style.display = "block";
        this.DoCallBackRequest(true);
    }
}
//Affecte la fonction de call back
SearchForm.prototype.SetCallback = function(callback) {
    if ((typeof (callback) != "undefined") && (callback != null)) {
        this.callBackRequest = callback;
    }
}
//vÃ©rifie que l'on peut faire la requÃ¨te
//retourne 1 si le lieux ou le camping doit Ãªtre saisi
//retourne 2 si le lieux est inconnu
//retourne 3 si le camping est inconnu
SearchForm.prototype.VerifRequest = function(form) {

    var val_sos = this.GetValueSOS();
    if (!this.IsPlaceSearchCorrect() && !this.IsCampingSearchCorrect() && val_sos == '') {
        alert(tradPage.GetTrad('camping_ou_lieux'));
        return;
    }
    if (this.select_sos && val_sos != '') {
        this.SetVal(this.tb_lat, "");
        this.SetVal(this.tb_lon, "");
        this.SetVal(this.hf_territoire, "");
        this.SetVal(this.champIDCamping, "");
        this.DoRequest();
        this.DoCallBackRequest(false);
    }
    else if (this.IsCampingSearchCorrect() && this.RechercheCampActive) {
        this.VerifCampingExisteAvantRequete();
    }
    else if (this.IsPlaceSearchCorrect() && this.estMode1) {
        this.SetVal(this.champIDCamping, "");
        this.VerifLieuxExisteAvantRequete();
    }
    else if (this.estMode2 && this.hf_territoire.value != "") {
        this.DoRequest();
        this.DoCallBackRequest(false);
    }
    else {
        this.SetVal(this.tb_lat, "");
        this.SetVal(this.tb_lon, "");
        this.SetVal(this.hf_territoire, "");
        this.SetVal(this.champIDCamping, "");
        this.DoRequest();
        this.DoCallBackRequest(false);
    }
}
SearchForm.prototype.GetValueSOS = function() {
    if (this.select_sos) {
        return this.select_sos.value;
    }
    return '';
}
SearchForm.prototype.SetVal = function(tb, valeur) {
    if (tb)
        tb.value = valeur;
}
SearchForm.prototype.IsCampingSearchCorrect = function() {
    return !this.RechercheCampActive || this.tb_nom_camping.value.trim() != '';
}
SearchForm.prototype.IsPlaceSearchCorrect = function() {
    return !this.estMode1 || !this.est_auto_complete_lieux || this.tb_lieux.value.trim() != '';
}
//envoi la requÃ¨te
SearchForm.prototype.DoRequest = function() {
    var l = this.tab_panel_checkbox.length;
    for (var i = 0; i < l; i++) {
        if (!this.tab_panel_checkbox[i].EcireDansHiddenField()) return false;
    }
    if (this.DoitRedirigerDetailCamp) {
        this.form.action = this.UrlRedirectionCamp;
    }
    else if (this.DoitRedirigerDetailLieux) {
        this.form.action = this.UrlRedirectLieux
    }
    else {
        this.form.action = this.UrlRechercheDispo;
    }
    this.form.target = (this.ouvre_dans_popup) ? "rechercheSkin3" : "";
    this.form.submit();
}
//execute la fonction en callback
SearchForm.prototype.DoCallBackRequest = function(arg,arg2) {
    if ((this.callBackRequest != null) && (typeof (this.callBackRequest) != "undefined")) {
        this.callBackRequest(arg, arg2);
    }
}
//Initialise les cahmps cachÃ©s de lieux selon la selection
SearchForm.prototype.setAdminCode = function(lieux) {
    if (this.hf_territoire && lieux.admin_code && lieux.admin_code != '') {
        this.hf_territoire.value = lieux.admin_code;
        this.tb_lat.value = "";
        this.tb_lon.value = "";
    }
    else {
        setLatLonTB(lieux.gps_latitude, lieux.gps_longitude);
    }
    this.DoRequest();
}
SearchForm.prototype.setLatLon = function(lat, lon) {
    this.tb_lat.value = lat;
    this.tb_lon.value = lon;
    this.hf_territoire.value = "";
    this.DoRequest();
}
//ferme la fenetre de detail
SearchForm.prototype.CloseDetails = function() {
    this.div_suggestion.style.display = "none";
}
SearchForm.prototype.VerifLieuxExisteAvantRequete = function() {
    this.ShowWait();
    if (this.IsSamePlace) {
        this.DoRequest();
    }
    else {
        this.ShowWait();
        this.RetourVerifPlace(SJAX("GetCompletionList", { "prefixText": this.tb_lieux.value, "count": 10, "contextKey": "", "filtre": this.filtreMode1 }, OnComplete2Verif));
        //PageMethods.GetCompletionList(this.tb_lieux.value,10,"",OnComplete2Verif,OnTimeOut2,OnError2);
    }
}
SearchForm.prototype.RetourVerifPlace = function(result) {
    this.HideWait();
    if (!result) {
        //alert('error');
        return;
    }
    if (result.length > 0) {
        if (this.detailPage) {
            this.DoitRedirigerDetailLieux = true;
        }
        else {
            this.ShowWait();
            PageMethods.GetDetails(this.tb_lieux.value, this.filtreMode1, OnComplete1, OnTimeOut1, OnError1);
            return;
        }
        this.DoRequest();
    }
    else {
        if (this.callBackRequest)
            this.DoCallBackRequest(false, false);
        else
            alert(tradPage.GetTrad('lieux_inconnu'));
    }
}
SearchForm.prototype.ActiverSelectCamping = function(IDChampIDCamp, UrlRedirection, IDTbLat, IDTbLon) {
    this.UrlRedirectionCamp = UrlRedirection;
    this.champIDCamping = document.getElementById(IDChampIDCamp);
    this.tb_lat = document.getElementById(IDTbLat);
    this.tb_lon = document.getElementById(IDTbLon);
}
SearchForm.prototype.SetCampingAndRequest = function(id, lat, lon) {
    this.champIDCamping.value = id;
    this.tb_lat.value = lat;
    this.tb_lon.value = lon;
    this.DoRequest();
}
SearchForm.prototype.ActiverRechercheCamping = function(IDTBNomCamping, IDDivSuggestionCamping, IDChampIDCamp, UrlRedirection, IDTbLat, IDTbLon) {
	/*
	alert('IDTBNomCamping : ' + IDTBNomCamping);
    this.tb_nom_camping = document.getElementById(IDTBNomCamping);
    this.tb_nom_camping.onfocus = SetAsNotSameCamp;
    this.div_suggestion_camping = document.getElementById(IDDivSuggestionCamping);
    if (document.addEventListener) {
        this.tb_nom_camping.addEventListener('keyup', GetAutoCompleteCamp, false);
    } else if (document.attachEvent) {
        this.tb_nom_camping.attachEvent('onkeyup', GetAutoCompleteCamp, false);
    }
    //    this.AutoCompleteCamp = new Ajax.Autocompleter(IDTBNomCamping,IDDivSuggestionCamping);
    //    this.AutoCompleteCamp.getUpdatedChoices = GetAutoCompleteCamp;
    this.RechercheCampActive = true;
    this.UrlRedirectionCamp = UrlRedirection;
    this.champIDCamping = document.getElementById(IDChampIDCamp);
    this.tb_lat = document.getElementById(IDTbLat);
    this.tb_lon = document.getElementById(IDTbLon);
    this.IsSameCamp = this.champIDCamping.value.trim() != '';
    */
}
SearchForm.prototype.GetCampings = function() {
    if (this.IsSameCamp) {
        this.DoRequest();
    }
    else {
        if (this.tb_nom_camping.value.trim() != '') {
            this.InteruptRequest(this.requete_camp);
            this.ShowWait();
            this.requete_camp = PageMethods._staticInstance.GetCampings(this.tb_nom_camping.value, document.getElementById('engineNum').value, OnCompleteCamp, OnTimeOutCamp, OnErrorCamp);
        }
        else {
            AutoComplete_HideDropdown(this.tb_nom_camping.id);
        }
    }
}
SearchForm.prototype.VerifCampingExisteAvantRequete = function() {
    this.ShowWait();
    this.RetourVerifCamp(SJAX("GetCampings", { "prefix": this.tb_nom_camping.value, "num_moteur": document.getElementById('engineNum').value }, OnCompleteCamp2));
    //PageMethods.GetCampings(this.tb_nom_camping.value,document.getElementById('engineNum').value,OnCompleteCamp2,OnTimeOutCamp,OnErrorCamp);
}
SearchForm.prototype.SetPopup = function(ouvre_dans_popup) {
    this.ouvre_dans_popup = ouvre_dans_popup;
}
SearchForm.prototype.RetourVerifCamp = function(result) {
    this.HideWait();
    if (!result)
        return;
    if (result.length > 0) {
        if (result.length > 1) {
            this.DoitRedirigerDetailCamp = true;
        }
        else {
            this.champIDCamping.value = result[0].id_camping;
            this.tb_lat.value = result[0].gps_latitude;
            this.tb_lon.value = result[0].gps_longitude;
        }
        this.DoRequest();
    }
    else {
        alert(tradPage.GetTrad('camping_inconnu'));
    }
}
SearchForm.prototype.MontrerCamps = function(liste_camp) {
    this.HideWait();
	var data = new Array();
    for (var i = 0; i < liste_camp.length; i++) {
        data.push(liste_camp[i].nom_camp);
    }
    AutoComplete_Create(this.tb_nom_camping.id, data);
    AutoComplete_ShowDropdown(this.tb_nom_camping.id);
}
//Fonction appelÃ©e en callback des pagemethods qui font paserelle avec le searchForm
function GetAutoCompleteList(event) {
    // Mozilla
    if (arguments[1] != null) {
        event = arguments[1];
    }
    var mauvaise_touche = ";13;27;38;9;40;"
    var keyCode = event.keyCode;
    if (mauvaise_touche.indexOf(";" + keyCode + ";") < 0)
        searchForm.SearchPlace();
}
function GetAutoCompleteCamp(event) {
    // Mozilla
    if (arguments[1] != null) {
        event = arguments[1];
    }
    var mauvaise_touche = ";13;27;38;9;40;"
    var keyCode = event.keyCode;
    if (mauvaise_touche.indexOf(";" + keyCode + ";") < 0)
        searchForm.GetCampings();
}
function OnComplete2(result) { searchForm.ShowPlaces(result); }
function OnComplete2Verif(result) { searchForm.RetourVerifPlace(result); }
function OnTimeOut2(result) { }
function OnError2(result) { }
function OnComplete1(result) { searchForm.ShowPlacesDetails(result); }
function OnTimeOut1(result) { alert("Time out"); }
function OnError1(result) { alert("There is an error!"); }
function sendRequest(button, callBack) { searchForm.SetCallback(callBack); searchForm.VerifRequest(); }
function OnCompleteCamp(result) { searchForm.MontrerCamps(result); }
function OnCompleteCamp2(result) { searchForm.RetourVerifCamp(result); }
function OnTimeOutCamp(result) { }
function OnErrorCamp(result) { }
function SetAsNotSameCamp() {
    searchForm.IsSameCamp = false;
}
function SetAsNotSamePlace() {
    searchForm.IsSamePlace = false;
}
TradPage = function() {
    this.traductions = Array();
}
TradPage.prototype.AddTrad = function(clef, valeur) {
    this.traductions[clef] = valeur;
}
TradPage.prototype.GetTrad = function(clef) {
    if (this.traductions[clef])
        return this.traductions[clef];
    return 'TRAD ' + clef;
}
var tradPage = new TradPage();

//va contenir les paramÃ¨tre pour remplir les champs hidden correspondant au checkbox.
function addPanelCheckBox(id_div,id_h,au_moin_un,coche_tout,nom){
    if(document.getElementById(id_h)){
        var obj = new PanelCheckbox(id_h,id_div,au_moin_un,coche_tout,nom);
        searchForm.tab_panel_checkbox.push(obj);
    }
}
PanelCheckbox = function(idHiddenFieldValue,className,mustCheckOne,checkAll,libelle){
    //champ hidden qui va contenir les valeur des checkbox cochÃ©e, concatÃ©nÃ©es
    this.hidden = document.getElementById(idHiddenFieldValue);
    //class css des checkbox
    this.className = className;
    //si a vrai, au moin une case de la hierarchie doit Ãªtre cochÃ©e
    this.checkOne = mustCheckOne;
    //si a vrai, coche toutes les cases quand aucune ne sont cochÃ©es
    this.checkAll = checkAll;
    this.libelle = libelle;
}
PanelCheckbox.prototype.EcireDansHiddenField = function(){
    if(this.hidden){
        this.hidden.value = '';
        var tab_cb = getElementsByClassName(this.className,"input",document);
        var l = tab_cb.length;
        var j = 0;
        for(var i = 0;i<l;i++){
            var cb = tab_cb[i];
            if((cb.type == "checkbox" || cb.type == "radio") && cb.checked){
                this.hidden.value += (j==0) ? "" : "|";
                this.hidden.value += cb.value;
                j++;
            }            
        }
        if(j == 0 && tab_cb.length > 0 ){
            if(this.checkOne){                
                return false;
            }
            else{
                if(this.checkAll){
                    for(var i = 0;i<l;i++){
                        var cb = tab_cb[i];
                        cb.checked = true ;                        
                    }
                    this.EcireDansHiddenField();
                }
            }
        }
    }
    return true ;
}
HierarchieCheckBox = function(prefix,inverse){
    this.prefix = prefix;
    this.inverse = inverse;
}
HierarchieCheckBox.prototype.CheckChild = function(parent,checkParent){    
        for(var i = 1;dgbi(this.prefix+i);i++){
            var elt = dgbi(this.prefix+i);
            if(!this.inverse){
                elt.disabled = (checkParent) ? !checkParent : !parent.checked;           
            }
            else{
                elt.disabled = (checkParent) ? checkParent : parent.checked;                                
            }
            checkChild(elt,parent.checked);
            if(elt.disabled){                
                elt.checked = false ;            
            }
        }
}
//va contenir les paramÃ¨tre pour activer / desactiver certaine checkbox 
var tab_hierarchie_checkbox = new Array();
//si inverse a false alors les cases enfant sont activÃ©e si le parent est cochÃ©
function addHierarchie(id_parent,prefix_id_enfants,inverse){
    eval("tab_hierarchie_checkbox['"+id_parent+"']=new HierarchieCheckBox('"+prefix_id_enfants+"',"+inverse+");");   
}

function checkChild(parent,checkParent){    
    eval("var obj = tab_hierarchie_checkbox['"+parent.id+"'];");
    if(obj)
    obj.CheckChild(parent,checkParent);
}
var bouton_form;

function setLatLonTB(lat,lon){
   searchForm.setLatLon(lat,lon);
}
function dgbi(id){
    return document.getElementById(id);
}
function onsortfinished_mygmap(){
    document.getElementById("nb_campings").innerHTML = (mapgoogle.nbMarkers);
}
var tab_checked_services = new Array();
var tab_territoire = "";
function InitGMap(){
    mapgoogle = new MyGMap("div_map");  
    mapgoogle.initInput("tb_lat","tb_lon");
    mapgoogle.sortfinished = onsortfinished_mygmap;
}
function eventhandler_territoire(cb)  
{
checkChild(cb);
 tab_territoire.addOrDelete(value,cb.checked); 
    if(typeof(mapgoogle) != "undefined"){
        value = cb.value;
        mapgoogle.SortTerritories(tab_territoire);
    }
    return true ;
}  

function eventhandler_service(cb)  
{    
 value = cb.value;
       
tab_checked_services.addOrDelete(value,cb.checked);    
    if(typeof(mapgoogle) != "undefined"){
        SortCamp(); 
    }
    return true ;
}         

var tab_checked_type = new Array();
var tab_checked_sub = new Array();
function eventhandler_product_type(cb){ 
	//alert("EPT !");
    checkChild(cb);
    value = cb.value;
    if(parseInt(value)){
    	//alert("ST ? / " + value)
        tab_checked_sub.addOrDelete(value,cb.checked); 
    }
    else{
    	//alert("Type ? / " + value)
        tab_checked_type.addOrDelete(value,cb.checked);             
    } 
    if(typeof(mapgoogle) != "undefined"){
        SortCamp(); 
    }
    return true ;
}
var tab_checked_domain = new Array();
function eventhandler_domain(cb,value){
tab_checked_domain.addOrDelete(value,cb.checked);
    if(typeof(mapgoogle) != "undefined"){
        SortCamp();
    }
}
Array.prototype.addOrDelete = function(value,mustAdd){
    if(this.indexOf(value)>= 0){
        if(!mustAdd){
            this.splice(this.indexOf(value),1);
        }            
    }
    else{
        if(mustAdd){
            this.push(value);
        }
    }
}
String.prototype.addOrDelete = function(value,mustAdd){
    if(this.indexOf(value)>= 0){
        if(!mustAdd){
            return this.replace(value,"");
        }            
    }
    else{
        if(mustAdd){
            return this+value;
        }
    }
}
function SortCamp(){
    if(typeof(mapgoogle) != "undefined")
        mapgoogle.SortAll(tab_checked_services,tab_checked_type,tab_checked_sub,tab_checked_domain,tab_territoire,rate);
}
var rate = 0 ;
function filtreRating(rate2){
    rate = parseInt(rate2);
    SortCamp();
}
/*
	Developed by Robert Nyman, http://www.robertnyman.com
	Code/licensing: http://code.google.com/p/getelementsbyclassname/
*/

var getElementsByClassName = function (className, tag, elm){
	if (document.getElementsByClassName) {
		getElementsByClassName = function (className, tag, elm) {
			elm = elm || document;
			var elements = elm.getElementsByClassName(className),
				nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
				returnElements = [],
				current;
			for(var i=0, il=elements.length; i<il; i+=1){
				current = elements[i];
				if(!nodeName || nodeName.test(current.nodeName)) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	else if (document.evaluate) {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = "",
				xhtmlNamespace = "http://www.w3.org/1999/xhtml",
				namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
				returnElements = [],
				elements,
				node;
			for(var j=0, jl=classes.length; j<jl; j+=1){
				classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
			}
			try	{
				elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
			}
			catch (e) {
				elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
			}
			while ((node = elements.iterateNext())) {
				returnElements.push(node);
			}
			return returnElements;
		};
	}
	else {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = [],
				elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
				current,
				returnElements = [],
				match;
			for(var k=0, kl=classes.length; k<kl; k+=1){
				classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
			}
			for(var l=0, ll=elements.length; l<ll; l+=1){
				current = elements[l];
				match = false;
				for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
					match = classesToCheck[m].test(current.className);
					if (!match) {
						break;
					}
				}
				if (match) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	return getElementsByClassName(className, tag, elm);
};

var KmlDispoIsLoaded = false; 
function ShowMapDispo(guid,id){
    InitGMAP(); 
    if(!KmlDispoIsLoaded){
        var mapgoogleDispo = new MyGMap('gmapdispo');
        mapgoogleDispo.geoXml.opts.icon = "./style/camping2.png";        
        var url = './get_kml_result.aspx?g='+guid;
        mapgoogleDispo.loadKML(url);
    }
    showSelect(id);
}
function showSelect(select){
    for(var i = 0;i<mapgoogleDispo.geoXml.markers.length;i++){
        var m =mapgoogleDispo.geoXml.markers[i];
        if(m.data.EstablishmentID == select){
            m.setImage("./style/camping3.png");
            var icon2 = new GIcon(m.getIcon());
            icon2.iconSize = new GSize(24,24);
            var opts = {icon:icon2,title:m.getTitle()};
            var m_temp = new GMarker(m.getLatLng(),opts);
            mapgoogleDispo.map.setCenter(m_temp.getLatLng());
            mapgoogleDispo.map.addOverlay(m_temp);
            mapgoogleDispo.map.removeOverlay(m);
            GEvent.trigger(m_temp,"click");
         }
    }
}
//function clickMarker(){
//    this.openInfoWindow(this.data.EstablishmentName)
//}

//classe permettant de gÃ©rer un selecteur de date par drop down list
DropDownDate = function(prefix,suffixe,IDChampResultat){
    this.jour = document.getElementById(prefix+'jour'+suffixe);
    this.mois = document.getElementById(prefix+'mois'+suffixe);
    this.annee = document.getElementById(prefix+'annee'+suffixe);
    this.est_mode_tb_only = typeof(this.jour) == "undefined";
    this.resultat = document.getElementById(IDChampResultat);   
}
DropDownDate.prototype.SetJour = function(val){    
    this.selectValue('jour',val);       
}
DropDownDate.prototype.SetMois = function(val){    
    this.selectValue('mois',val);
}
DropDownDate.prototype.SetAnnee = function(val){
    this.selectValue('annee',val);
}
DropDownDate.prototype.selectValue   = function (nom_select, itemValue)
{
    var ListBox = this.GetControl(nom_select);
	if (ListBox)
	{
		var nbOptions = ListBox.options.length;
        for(i=0;i < nbOptions; i++)
        {
            if(ListBox[i].value == itemValue)
			{
	            ListBox[i].selected = "selected";
	            break;
            }
        }
	}
	else{
	    this.SetPartie(nom_select,itemValue);
	}
}
DropDownDate.prototype.MajResultat = function(){
    this.resultat.value=this.GetDate();
}
DropDownDate.prototype.GetDate = function(){
    return this.VerifTailleComposant('jour',this.GetValueJour())+"/"+this.VerifTailleComposant('mois',this.GetValueMois())+"/"+this.VerifTailleComposant('annee',this.GetValueAnnee());
}
DropDownDate.prototype.VerifTaille = function(){
    return this.GetDate().length == 10;
}
DropDownDate.prototype.IsDate = function(){    
        var aiDays = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
        var iDay = this.GetValueJour();
        var iMonth = this.GetValueMois();
        var iYear = this.GetValueAnnee();
        if (iDay < 1 || iMonth < 1 || iYear < 0)
			return 0;
        if (iMonth > 12)
			return 0;

        iYear += iYear < 100 ? iYear > 10 ? 1900 : 2000 : 0;
        aiDays[1] += (iYear % 4 ? 0 : iYear % 100 ? 1 : iYear % 400 ?
        iYear == 200 ? 1 : 0 : 1);

        return (iDay <= aiDays[iMonth - 1]);
}
DropDownDate.prototype.IsSupToday = function(){
    var today = new Date();
    return this.GetValueAnnee() > today.getFullYear() ||
           (this.GetValueAnnee() == today.getFullYear() && this.GetValueMois() > (today.getMonth() + 1)) ||
           (this.GetValueAnnee() == today.getFullYear() && this.GetValueMois() == (today.getMonth() + 1) && this.GetValueJour() > today.getDate()) ;
}
DropDownDate.prototype.SetDate = function (){
    if(this.resultat.value != ''){
        var infos = this.resultat.value.split('/');
        this.SetJour(infos[0]);
        this.SetMois(infos[1]);
        this.SetAnnee(infos[2]);
    }
}
DropDownDate.prototype.GetValueAnnee = function(){
   return this.GetIntValue('annee');
}
DropDownDate.prototype.GetValueMois = function(){
   return this.GetIntValue('mois'); 
}
DropDownDate.prototype.GetValueJour = function(){
   return this.GetIntValue('jour'); 
}
DropDownDate.prototype.GetIntValue = function(nom_select){
    var select = this.GetControl(nom_select);
    if(select){
        if(select.value == '')
            return -1;
        return parseInt(select.value,10);
    }
    else{
        return this.GetPartie(nom_select);
    }
}
DropDownDate.prototype.GetControl = function(nom){
    if(this.est_mode_tb_only){
        return false;
    }
    return this[nom];
}
DropDownDate.prototype.GetPartie = function (nom){
    var tab_split = this.resultat.value.split('/');
    switch(nom){
        case 'annee' : return parseInt(tab_split[2],10);
        case 'mois' : return parseInt(tab_split[1],10);
        case 'jour' : return  parseInt(tab_split[0],10);
    } 
    return '';
}
DropDownDate.prototype.SetPartie = function (nom,valeur){
    var annee = (nom != 'annee') ? this.GetPartie('annee') : valeur;
    var mois = (nom != 'mois') ? this.GetPartie('mois') : valeur;
    var jour = (nom != 'jour') ? this.GetPartie('jour') : valeur;
    this.resultat.value = this.VerifTailleComposant('jour',jour)+"/"+this.VerifTailleComposant('mois',mois)+"/"+this.VerifTailleComposant('annee',annee);
}
DropDownDate.prototype.VerifTailleComposant = function(nom,val){
val = val.toString();
    if(val.toString().trim() == '') return '';
    var nb_char = 0;
     switch(nom){
        case 'annee' : nb_char = 4;
        case 'mois' : nb_char = 2;
        case 'jour' :nb_char = 2;
    } 
    while(val.length < nb_char){
        val = '0'+val;
    }
    return val;
}
//classe permettant de gÃ©rer la selection d'un sÃ©jour via des DropDownDate
SelectSejour = function (prefix,IDChampResultatDeb,IDChampResultatFin){
    this.debut = new DropDownDate(prefix,'Arrivee',IDChampResultatDeb);
    this.fin = new DropDownDate(prefix,'Depart',IDChampResultatFin);
    this.debut.SetDate();
    this.fin.SetDate();
    this.SetEcouteur(this.debut.mois);
    this.SetEcouteur(this.debut.annee);
}
SelectSejour.prototype.SetEcouteur = function(list){
    if(list){
        list.selectSejour = this;
        list.onchange =AjusteDate;
    }
}
SelectSejour.prototype.VerifDate = function(){
        if ( !this.debut.VerifTaille() ||  !this.fin.VerifTaille() )
        {
			return 1;
        }
		else
		{
            if (!this.debut.IsDate())  return 6;
            if (!this.fin.IsDate())  return 7;            
	        if (!this.IsDateSupInf()) return 4;
	        if (!this.fin.IsSupToday()) return 5;
		}
		this.debut.MajResultat();
		this.fin.MajResultat();
		return -1;           
}
SelectSejour.prototype.IsDateSupInf = function(){
 return this.fin.GetValueAnnee() > this.debut.GetValueAnnee() ||
           (this.fin.GetValueAnnee() == this.debut.GetValueAnnee() &&  this.fin.GetValueMois() > ( this.debut.GetValueMois())) ||
           (this.fin.GetValueAnnee() == this.debut.GetValueAnnee() &&  this.fin.GetValueMois() == ( this.debut.GetValueMois()) && this.fin.GetValueJour() > this.debut.GetValueJour()) ;
}
SelectSejour.prototype.AjusteDates = function(){
    if(this.debut.annee.value != ""){
       if(this.fin.GetValueAnnee() < this.debut.GetValueAnnee()){
            this.fin.SetAnnee(this.debut.GetValueAnnee());
       }
    }
    if(this.debut.mois.value != ""){
       if(this.fin.GetValueMois() < this.debut.GetValueMois() && (this.debut.annee.value == "" || this.fin.GetValueAnnee() <= this.debut.GetValueAnnee())){
                this.fin.SetMois(this.debut.GetValueMois());
       }
    }
}
function AjusteDate(){
    this.selectSejour.AjusteDates();
}
var url_result = 'default.aspx';
var url_detail_lieux = 'details_ufi.aspx';
var url_detail_camp = 'details_camp.aspx';//]]>

var language='FR';

/*function eventhandler_service(obj) {
}
function eventhandler_product_type(obj) {
}
*/

function checkRegroupements(){
	if (document.getElementById('destinationCb1').checked==true || document.getElementById('destinationCb2').checked==true || document.getElementById('destinationCb3').checked==true || document.getElementById('destinationCb4').checked==true || document.getElementById('destinationCb5').checked==true) {
		document.getElementById('destinationCb0').checked=false;
	}
	if(document.getElementById('destinationCb1').checked==false && document.getElementById('destinationCb2').checked==false && document.getElementById('destinationCb3').checked==false && document.getElementById('destinationCb4').checked==false && document.getElementById('destinationCb5').checked==false) {
		document.getElementById('destinationCb0').checked=true;
	}
}

function mapOpen() {
	window.open('http://maps.google.fr/maps/ms?hl=fr&ie=UTF8&lr=lang_fr&msa=0&msid=107031086511963346941.00045cd223f966420e6a3&ll=45.082674,0.730656&spn=1.687195,4.943848&z=8','_blank','toolbar=0, location=0, directories=0, menuBar=0, scrollbars=0, resizable=1');
	popupImage.document.close()
}

var isResult='';
var isPageDispo='dispo';

function changePrix(prixMax){
	document.getElementById('tb_price_max').value=prixMax;
	if(prixMax==150){
		document.getElementById('tb_price_min').value=0;
	}
	if(prixMax==300){
		document.getElementById('tb_price_min').value=150;
	}
	if(prixMax==500){
		document.getElementById('tb_price_min').value=300;
	}
	if(prixMax==800){
		document.getElementById('tb_price_min').value=500;
	}
	if(prixMax==5000){
		document.getElementById('tb_price_min').value=800;
	}
}

function selItemListBox(ListBox, itemValue) {
	if (ListBox) {
		var nbOptions = ListBox.options.length;
		for(i=0;i <= nbOptions; i++) {
			if(ListBox[i].value == itemValue){
				ListBox[i].selected = "selected";
				//document.getElementById('h_territoire').value=ListBox[i].value;
				break;
			}
		}
	}
}

function closeopen() {
	if (window.opener && !window.opener.closed) { 
		window.close();
	}
}

function checkForm(oForm) {

	var TP1=document.getElementById('TP1');
	var TP2=document.getElementById('TP2');
	var TP2ST1=document.getElementById('TP2ST1');
	var TP2ST2=document.getElementById('TP2ST2');
	var TP2ST3=document.getElementById('TP2ST3');
	var TP2ST4=document.getElementById('TP2ST4');
	var TP2ST5=document.getElementById('TP2ST5');
	var TP2ST6=document.getElementById('TP2ST6');
	var TP3=document.getElementById('TP3');
	var productTypes=document.getElementById('productTypes');
	productTypes.value = '';
	var sousProductTypes=document.getElementById('sousProductTypes');
	sousProductTypes.value = '';

	if(TP1.checked)
		productTypes.value+='E|';
	if(TP2.checked){
		productTypes.value+='L|';
		if(TP2ST1){
			if(TP2ST1.checked){
				sousProductTypes.value+='3|2|';
			}
		}
		if(TP2ST2){
			if(TP2ST2.checked){
				sousProductTypes.value+='1|';
			}
		}
		if(TP2ST3){
			if(TP2ST3.checked){
				sousProductTypes.value+='4|10|';
			}
		}
		if(TP2ST4){
			if(TP2ST4.checked){
				sousProductTypes.value+='9|';
			}
		}
		if(TP2ST5){
			if(TP2ST5.checked){
				sousProductTypes.value+='11|';
			}
		}
		if(TP2ST6){
			if(TP2ST6.checked){
				sousProductTypes.value+='5|6|7|8|';
			}
		}
	}

	if(TP3){
		if(TP3.checked){
			productTypes.value+='C|';
		}
	}

	if(isResult.length>0 || isPageDispo.length>0){
		var PerigordVert=document.getElementById('destinationCb1');
		var PerigordBlanc=document.getElementById('destinationCb2');
		var PerigordPourpre=document.getElementById('destinationCb3');
		var PerigordNoir=document.getElementById('destinationCb4');
		var PerigordNatu=document.getElementById('destinationCb5');
		var idsRegroupements=document.getElementById('idsRegroupements');
		if(PerigordVert.checked){
			idsRegroupements.value+='670|';
		}
		if(PerigordBlanc.checked){
			idsRegroupements.value+='691|';
		}
		if(PerigordPourpre.checked){
			idsRegroupements.value+='672|';
		}
		if(PerigordNoir.checked){
			idsRegroupements.value+='671|';
		}
		if(PerigordNatu.checked){
			idsRegroupements.value+='673|';
		}
	}

	var l = searchForm.tab_panel_checkbox.length;

	for(var i = 0;i<l;i++){
		if(!searchForm.tab_panel_checkbox[i].EcireDansHiddenField()) 
			return false;
	}

	codeError = selectSejour.VerifDate();
	if (codeError > 0) {
		var msg = "";
		switch(codeError) {
			case 1 :
				msg = "Votre date est incorrecte";
				break;
			case 2:
				msg = "La date d'arrivée est incorrecte";
				break;
			case 3:
				msg = "La date de départ est incorrecte";
				break;
			case 4:
				msg = "la date de fin de la période doit être strictement supérieure à la date de début";
				break;
			case 5:
				msg = "La date de début de séjour doit être supérieure ou égale à la date du jour";
				break;
			case 6:
				msg = "Votre date est incorrecte";
				break;
			case 7:
				msg = "La date de départ est incorrecte";
				break;
		}

		if (msg != "") alert(msg);
		return false;
	}

	var arrivalDate=document.getElementById('cal1Date1').value;
	var departureDate=document.getElementById('cal1Date2').value;
	var productTypes=document.getElementById('productTypes').value;
	//alert("productTypes : " + productTypes);
	var enginNum= document.getElementById('engineNum').value;
	var language='FR';
	
	oForm.action = 'disponibilites.php'
	oForm.method='GET'
	oForm.submit();
	return;
	

	if(isPageDispo.length==0 && isResult==0){
		if(language=='FR'){
			//var actionFormulaire='http://localhost:1097/dordogne/?arrivalDate='+arrivalDate+'&departureDate='+departureDate+'&productTypes='+productTypes+'&engineNum='+enginNum+'&displayProductInfo=true&withSO=true';
			var actionFormulaire='http://www.campidor.com/FR/disponibilites.html?arrivalDate='+arrivalDate+'&departureDate='+departureDate+'&productTypes='+productTypes+'&engineNum='+enginNum+'&displayProductInfo=true&withSO=true';
		}
		if(language=='ES'){
			var actionFormulaire='http://www.campidor.com/ES/disponibilidad.html?arrivalDate='+arrivalDate+'&departureDate='+departureDate+'&productTypes='+productTypes+'&engineNum='+enginNum+'&displayProductInfo=true&withSO=true';
		}
		if(language=='NL'){
			var actionFormulaire='http://www.campidor.com/NL/beschikbaarheid.html?arrivalDate='+arrivalDate+'&departureDate='+departureDate+'&productTypes='+productTypes+'&engineNum='+enginNum+'&displayProductInfo=true&withSO=true';
		}
		if(language=='EN'){
			var actionFormulaire='http://www.campidor.com/EN/availability.html?arrivalDate='+arrivalDate+'&departureDate='+departureDate+'&productTypes='+productTypes+'&engineNum='+enginNum+'&displayProductInfo=true&withSO=true';
		}
		if(language=='DE'){
			var actionFormulaire='http://www.campidor.com/AL/verfugbarkeit.html?arrivalDate='+arrivalDate+'&departureDate='+departureDate+'&productTypes='+productTypes+'&engineNum='+enginNum+'&displayProductInfo=true&withSO=true';
		}

		document.getElementById("basicForm").arrivalDate.value =arrivalDate ;
		document.getElementById("basicForm").departureDate.value =departureDate ;
		document.getElementById("basicForm").productTypes.value =productTypes ;
		document.getElementById("basicForm").engineNum.value =enginNum ;

		document.getElementById("basicForm").action = actionFormulaire;
		document.getElementById("basicForm").target = "_top";
		document.getElementById("basicForm").submit();
	} else {
		sendRequest(oForm);
	}
}

searchForm = new SearchForm(url_result);
searchForm.SetPopup(false);

function init() {
	searchForm.tab_panel_checkbox.push(new PanelCheckbox("h_sub_type", "cbSubType", false, false, "sous type"));
	tradPage.AddTrad('camping_ou_lieux',"Vous devez sélectionner un camping ou un lieu");
	tradPage.AddTrad('lieux_inconnu',"Ce lieu est inconnu.");
	tradPage.AddTrad('camping_inconnu',"Ce camping n'existe pas.");
	selectSejour = new SelectSejour('','cal1Date1','cal1Date2');
	searchForm.SetMode1('h_territoire','tb_lieux','tb_lat','tb_lon','VarRetour','div_detail_all','toto.aspx');
	searchForm.SetSuperOS('idos');
	searchForm.ActiverRechercheCamping('tb_nom_camping','DivRetourCamp','id_etablissements',url_detail_camp,'tb_lat','tb_lon','VarRetour');

	var priceMax='';
	var priceList=document.getElementById('priceSelect');
	if (priceMax.length>0) {
		selItemListBox(priceList,priceMax);
	}

	var qualityMin='';
	var qualityList=document.getElementById('qualitySelect');

	if (qualityMin.length>0) {
		selItemListBox(qualityList,qualityMin);
	}

	if (document.getElementById("bt_page_1")) {
		document.getElementById('bt_page_1').className="boutonPageEnCours";
		document.getElementById('bt_page_B1').className="boutonPageEnCours";
	}

	if (document.getElementById('bouton_precedent')) {
		document.getElementById("bouton_precedent").className="bouton_navigationInactif";
		document.getElementById("bouton_precedentB").className="bouton_navigationInactif";
		document.getElementById("flechegauche").className="flecheGrise";
		document.getElementById("flechegaucheB").className="flecheGrise";
	}

	if(document.getElementById('numPage')) {
		pageToDisplay=document.getElementById('numPage').value;
		nbPageTotal=document.getElementById('nbPages').value;
		cachepagemoteur(nbPageTotal);
		pagemoteur(pageToDisplay,nbPageTotal);
	}

}


