﻿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;
}

//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
    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) {
    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();

