__AutoComplete = new Array();
__ID_AutoComplete = new Array();
isIE = document.all ? true : false;
isGecko = navigator.userAgent.toLowerCase().indexOf("gecko") != -1;
isOpera = navigator.userAgent.toLowerCase().indexOf("opera") != -1;

function AutoComplete_Create(id, data) {
    if (!__AutoComplete[id]) {
        __ID_AutoComplete.push(id);
        __AutoComplete[id] = {
            "data": data,
            "isVisible": false,
            "element": document.getElementById(id),
            "dropdown": null,
            "highlighted": null
        };
        __AutoComplete[id]["element"].setAttribute("autocomplete", "off");
        __AutoComplete[id]["element"].onkeydown = function(e) {
            return AutoComplete_KeyDown(this.getAttribute("id"), e);
        };
        __AutoComplete[id]["element"].onkeyup = function(e) {
            return AutoComplete_KeyUp(this.getAttribute("id"), e);
        };
        __AutoComplete[id]["element"].onkeypress = function(e) {
            if (!e) {
                e = window.event;
            }
            if (e.keyCode == 13 || isOpera) {
                return false;
            }
        };
        __AutoComplete[id]["element"].ondblclick = function() {
            AutoComplete_ShowDropdown(this.getAttribute("id"));
        };
        __AutoComplete[id]["element"].onclick = function(e) {
            if (!e) {
                e = window.event;
            }
            e.cancelBubble = true;
            e.returnValue = false;
        };
        var docClick = function() {
            for (var i = 0; i < __ID_AutoComplete.length; i++) {
                AutoComplete_HideDropdown(__ID_AutoComplete[i]);
            }
        };
        if (document.addEventListener) {
            document.addEventListener("click", docClick, false);
        } else {
            if (document.attachEvent) {
                document.attachEvent("onclick", docClick, false);
            }
        }
        if (arguments[2] != null) {
            __AutoComplete[id]["maxitems"] = arguments[2];
            __AutoComplete[id]["firstItemShowing"] = 0;
            __AutoComplete[id]["lastItemShowing"] = arguments[2] - 1;
        }
        AutoComplete_CreateDropdown(id);
        if (isIE) {
            __AutoComplete[id]["iframe"] = document.createElement("iframe");
            __AutoComplete[id]["iframe"].id = id + "_iframe";
            __AutoComplete[id]["iframe"].style.position = "absolute";
            __AutoComplete[id]["iframe"].style.top = "0";
            __AutoComplete[id]["iframe"].style.left = "0";
            __AutoComplete[id]["iframe"].style.width = "0px";
            __AutoComplete[id]["iframe"].style.height = "0px";
            __AutoComplete[id]["iframe"].style.zIndex = "98";
            __AutoComplete[id]["iframe"].style.visibility = "hidden";
            __AutoComplete[id]["element"].parentNode.insertBefore(__AutoComplete[id]["iframe"], __AutoComplete[id]["element"]);
        }
    } else {
        __AutoComplete[id]["data"] = data;
    }
}
function AutoComplete_CreateDropdown(id) {
    var left = AutoComplete_GetLeft(__AutoComplete[id]["element"]);
    var top = AutoComplete_GetTop(__AutoComplete[id]["element"]) + __AutoComplete[id]["element"].offsetHeight;
    var width = __AutoComplete[id]["element"].offsetWidth;
    __AutoComplete[id]["dropdown"] = document.createElement("div");
    __AutoComplete[id]["dropdown"].className = "autocomplete";
    __AutoComplete[id]["element"].parentNode.insertBefore(__AutoComplete[id]["dropdown"], __AutoComplete[id]["element"]);
    __AutoComplete[id]["dropdown"].style.left = left + "px";
    __AutoComplete[id]["dropdown"].style.top = top + "px";
    __AutoComplete[id]["dropdown"].style.width = width + "px";
    __AutoComplete[id]["dropdown"].style.zIndex = "99";
    __AutoComplete[id]["dropdown"].style.visibility = "hidden";
}
function AutoComplete_GetLeft(element) {
    var curNode = element;
    var left = 0;
    do {
        left += curNode.offsetLeft;
        curNode = curNode.offsetParent;
    } while (curNode.tagName.toLowerCase() != "body");
    return left;
}
function AutoComplete_GetTop(element) {
    var curNode = element;
    var top = 0;
    do {
        top += curNode.offsetTop;
        curNode = curNode.offsetParent;
    } while (curNode.tagName.toLowerCase() != "body");
    return top;
}
var id_timer = null;
var timeout_handler = null;

function AutoComplete_ShowDropdown(id) {
    id_timer = id;
    if (timeout_handler) {
        clearTimeout(timeout_handler);
    }
    timeout_handler = setTimeout("AutoComplete_ShowDropdown_suite()", 100);
}
function AutoComplete_ShowDropdown_suite() {
    var id = id_timer;
    AutoComplete_HideAll();
    var value = __AutoComplete[id]["element"].value;
    if (value.trim() == "") {
        return;
    }
    var toDisplay = new Array();
    var newDiv = null;
    var text = null;
    var numItems = __AutoComplete[id]["dropdown"].childNodes.length;
    while (__AutoComplete[id]["dropdown"].childNodes.length > 0) {
        __AutoComplete[id]["dropdown"].removeChild(__AutoComplete[id]["dropdown"].childNodes[0]);
    }
    for (i = 0; i < __AutoComplete[id]["data"].length; ++i) {
        toDisplay[toDisplay.length] = __AutoComplete[id]["data"][i];
    }
    if (toDisplay.length == 0) {
        AutoComplete_HideDropdown(id);
        return;
    }
    __AutoComplete[id]["dropdown"].valeurs = new Array();
    for (i = 0; i < toDisplay.length; ++i) {
        newDiv = document.createElement("div");
        newDiv.className = "autocomplete_item";
        newDiv.setAttribute("id", "autocomplete_item_" + i);
        newDiv.setAttribute("index", i);
        __AutoComplete[id]["dropdown"].valeurs[i] = toDisplay[i];
        newDiv.style.zIndex = "99";
        if (toDisplay.length > __AutoComplete[id]["maxitems"] && navigator.userAgent.indexOf("MSIE") == -1) {
            newDiv.style.width = __AutoComplete[id]["element"].offsetWidth - 22 + "px";
        }
        newDiv.onmouseover = function() {
            AutoComplete_HighlightItem(__AutoComplete[id]["element"].getAttribute("id"), this.getAttribute("index"));
        };
        newDiv.onclick = function() {
            AutoComplete_SetValue(__AutoComplete[id]["element"].getAttribute("id"));
            AutoComplete_HideDropdown(__AutoComplete[id]["element"].getAttribute("id"));
        };
        newDiv.innerHTML = toDisplay[i];
        __AutoComplete[id]["dropdown"].appendChild(newDiv);
    }
    if (toDisplay.length > __AutoComplete[id]["maxitems"]) {
        __AutoComplete[id]["dropdown"].style.height = (__AutoComplete[id]["maxitems"] * 15) + 2 + "px";
    } else {
        __AutoComplete[id]["dropdown"].style.height = "";
    }
    __AutoComplete[id]["dropdown"].style.left = AutoComplete_GetLeft(__AutoComplete[id]["element"]);
    __AutoComplete[id]["dropdown"].style.top = AutoComplete_GetTop(__AutoComplete[id]["element"]) + __AutoComplete[id]["element"].offsetHeight;
    if (isIE) {
        __AutoComplete[id]["iframe"].style.top = __AutoComplete[id]["dropdown"].style.top;
        __AutoComplete[id]["iframe"].style.left = __AutoComplete[id]["dropdown"].style.left;
        __AutoComplete[id]["iframe"].style.width = __AutoComplete[id]["dropdown"].offsetWidth;
        __AutoComplete[id]["iframe"].style.height = __AutoComplete[id]["dropdown"].offsetHeight;
        __AutoComplete[id]["iframe"].style.visibility = "visible";
    }
    if (!__AutoComplete[id]["isVisible"]) {
        __AutoComplete[id]["dropdown"].style.visibility = "visible";
        __AutoComplete[id]["isVisible"] = true;
    }
    if (__AutoComplete[id]["dropdown"].childNodes.length != numItems) {
        __AutoComplete[id]["highlighted"] = null;
    }
}
function AutoComplete_HideDropdown(id) {
    if (__AutoComplete[id]["iframe"]) {
        __AutoComplete[id]["iframe"].style.visibility = "hidden";
    }
    __AutoComplete[id]["dropdown"].style.visibility = "hidden";
    __AutoComplete[id]["highlighted"] = null;
    __AutoComplete[id]["isVisible"] = false;
}
function AutoComplete_HideAll() {
    for (var i = 0; i < __ID_AutoComplete.length; i++) {
        AutoComplete_HideDropdown(__ID_AutoComplete[i]);
    }
}
function AutoComplete_HighlightItem(id, index) {
    if (__AutoComplete[id]["dropdown"].childNodes[index]) {
        for (var i = 0; i < __AutoComplete[id]["dropdown"].childNodes.length; ++i) {
            if (__AutoComplete[id]["dropdown"].childNodes[i].className == "autocomplete_item_highlighted") {
                __AutoComplete[id]["dropdown"].childNodes[i].className = "autocomplete_item";
            }
        }
        __AutoComplete[id]["dropdown"].childNodes[index].className = "autocomplete_item_highlighted";
        __AutoComplete[id]["highlighted"] = index;
    }
}
function AutoComplete_Highlight(id, index) {
    if (index == 1 && __AutoComplete[id]["highlighted"] == __AutoComplete[id]["dropdown"].childNodes.length - 1) {
        __AutoComplete[id]["dropdown"].childNodes[__AutoComplete[id]["highlighted"]].className = "autocomplete_item";
        __AutoComplete[id]["highlighted"] = null;
    } else {
        if (index == -1 && __AutoComplete[id]["highlighted"] == 0) {
            __AutoComplete[id]["dropdown"].childNodes[0].className = "autocomplete_item";
            __AutoComplete[id]["highlighted"] = __AutoComplete[id]["dropdown"].childNodes.length;
        }
    }
    if (__AutoComplete[id]["highlighted"] == null) {
        __AutoComplete[id]["dropdown"].childNodes[0].className = "autocomplete_item_highlighted";
        __AutoComplete[id]["highlighted"] = 0;
    } else {
        if (__AutoComplete[id]["dropdown"].childNodes[__AutoComplete[id]["highlighted"]]) {
            __AutoComplete[id]["dropdown"].childNodes[__AutoComplete[id]["highlighted"]].className = "autocomplete_item";
        }
        var newIndex = __AutoComplete[id]["highlighted"] + index;
        if (__AutoComplete[id]["dropdown"].childNodes[newIndex]) {
            __AutoComplete[id]["dropdown"].childNodes[newIndex].className = "autocomplete_item_highlighted";
            __AutoComplete[id]["highlighted"] = newIndex;
        }
    }
}
function AutoComplete_SetValue(id) {
    __AutoComplete[id]["element"].value = __AutoComplete[id]["dropdown"].valeurs[__AutoComplete[id]["highlighted"]];
}
function AutoComplete_ScrollCheck(id) {
    if (__AutoComplete[id]["highlighted"] > __AutoComplete[id]["lastItemShowing"]) {
        __AutoComplete[id]["firstItemShowing"] = __AutoComplete[id]["highlighted"] - (__AutoComplete[id]["maxitems"] - 1);
        __AutoComplete[id]["lastItemShowing"] = __AutoComplete[id]["highlighted"];
    }
    if (__AutoComplete[id]["highlighted"] < __AutoComplete[id]["firstItemShowing"]) {
        __AutoComplete[id]["firstItemShowing"] = __AutoComplete[id]["highlighted"];
        __AutoComplete[id]["lastItemShowing"] = __AutoComplete[id]["highlighted"] + (__AutoComplete[id]["maxitems"] - 1);
    }
    __AutoComplete[id]["dropdown"].scrollTop = __AutoComplete[id]["firstItemShowing"] * 15;
}
function AutoComplete_KeyDown(id) {
    if (arguments[1] != null) {
        event = arguments[1];
    }
    var keyCode = event.keyCode;
    switch (keyCode) {
    case 13:
        if (__AutoComplete[id]["highlighted"] != null) {
            AutoComplete_SetValue(id);
            AutoComplete_HideDropdown(id);
        }
        event.returnValue = false;
        event.cancelBubble = true;
        break;
    case 27:
        AutoComplete_HideDropdown(id);
        event.returnValue = false;
        event.cancelBubble = true;
        break;
    case 38:
        if (!__AutoComplete[id]["isVisible"]) {
            AutoComplete_ShowDropdown(id);
        }
        AutoComplete_Highlight(id, -1);
        AutoComplete_ScrollCheck(id, -1);
        return false;
        break;
    case 9:
        if (__AutoComplete[id]["isVisible"]) {
            AutoComplete_HideDropdown(id);
        }
        return;
    case 40:
        if (!__AutoComplete[id]["isVisible"]) {
            AutoComplete_ShowDropdown(id);
        }
        AutoComplete_Highlight(id, 1);
        AutoComplete_ScrollCheck(id, 1);
        return false;
        break;
    }
}
function AutoComplete_KeyUp(id) {
    if (arguments[1] != null) {
        event = arguments[1];
    }
    var keyCode = event.keyCode;
    switch (keyCode) {
    case 13:
        event.returnValue = false;
        event.cancelBubble = true;
        break;
    case 27:
        AutoComplete_HideDropdown(id);
        event.returnValue = false;
        event.cancelBubble = true;
        break;
    case 38:
    case 40:
        return false;
        break;
    default:
        AutoComplete_ShowDropdown(id);
        break;
    }
}
function AutoComplete_isVisible(id) {
    return __AutoComplete[id]["dropdown"].style.visibility == "visible";
}
FormElement = function(IDElement, Length, NiveauObligation, Type) {
    this.element = document.getElementById(IDElement);
    this.length = (Length && Length.trim != "") ? parseInt(Length, 10) : -1;
    this.niveau = NiveauObligation;
    this.type = Type;
    if (this.element.type && this.element.type == "text") {
        this.element.formElement = this;
        this.element.onkeyup = TBValideFormElement;
    }
};

function TBValideFormElement() {
    if (this.formElement) {
        this.formElement.Validate();
    }
}
FormElement.prototype = {
    Validate: function() {
        return this.ValidateLength() && this.ValidateNiveau() && this.ValidateType();
    },
    ValidateLength: function() {
        var val = this.element.value;
        return this.length < 0 || val.length <= this.length;
    },
    ValidateNiveau: function() {
        var val = this.element.value;
        switch (this.niveau) {
        case "Obligatory":
            return val != "";
            break;
        case "Optional":
            return true;
            break;
        case "Forbidden":
            return val == "";
            break;
        }
        return false;
    },
    GetValue: function() {
        if (this.element && this.element.value && this.element.value.trim() != "") {
            var val = this.element.value.trim();
            switch (this.type) {
            case "Single":
                return parseFloat(val);
                break;
            case "Integer":
                return parseInt(val);
                break;
            case "Email":
                return val;
                break;
            case "AlphaNumeric":
                return val;
                break;
            case "Date":
                return val;
                break;
            case "Mouse":
                return val;
                break;
            }
        }
        return "";
    },
    ValidateType: function() {
        var val = this.element.value;
        if (val.trim() == "") {
            return true;
        }
        switch (this.type) {
        case "Single":
            return this.ValidateSingle();
            break;
        case "Integer":
            return this.ValidateInt();
            break;
        case "Email":
            return this.ValidateEmail();
            break;
        case "AlphaNumeric":
            return true;
            break;
        case "Date":
            return this.ValidateDate();
            break;
        case "Mouse":
            return true;
            break;
        }
        return false;
    },
    ValidateInt: function() {
        var test = this.element.value;
        if (test == "") {
            return true;
        }
        var z = "";
        var est_ok = true;
        for (var i = 0; i < test.length; i++) {
            if ((test.substring(i, i + 1) >= "0") && (test.substring(i, i + 1) <= "9")) {
                z = z + test.substring(i, i + 1);
            } else {
                est_ok = false;
            }
        }
        return est_ok;
    },
    ValidateSingle: function() {
        var test = this.element.value;
        z = "";
        var est_ok = true;
        var virgule_ajout = false;
        for (i = 0; i < test.length; i++) {
            var char_test = test.substring(i, i + 1);
            if (((char_test >= "0") && (char_test <= "9")) || (char_test == ".") || (char_test == ",")) {
                if (((char_test == ".") || (char_test == ",")) && !virgule_ajout) {
                    char_test = ",";
                    virgule_ajout = true;
                } else {
                    if (((char_test == ".") || (char_test == ",")) && virgule_ajout) {
                        char_test = "";
                        est_ok = false;
                    }
                }
                z = z + char_test;
            } else {
                est_ok = false;
            }
        }
        this.element.value = z;
        return est_ok;
    },
    ValidateEmail: function() {
        var email = this.element.value;
        invalidChars = " ~'^`\"*+=\\|][(){}$&!#%/:,;<>";
        for (var i = 0; i < invalidChars.length; i++) {
            badChar = invalidChars.charAt(i);
            if (email.indexOf(badChar, 0) > -1) {
                return false;
            }
        }
        lengthOfEmail = email.length;
        if ((email.charAt(lengthOfEmail - 1) == ".") || (email.charAt(lengthOfEmail - 2) == ".")) {
            return false;
        }
        Pos = email.indexOf("@", 1);
        if (email.charAt(Pos + 1) == ".") {
            return false;
        }
        while ((Pos < lengthOfEmail) && (Pos != -1)) {
            Pos = email.indexOf(".", Pos);
            if (email.charAt(Pos + 1) == ".") {
                return false;
            }
            if (Pos != -1) {
                Pos++;
            }
        }
        atPos = email.indexOf("@", 1);
        if (atPos == -1) {
            return false;
        }
        if (email.indexOf("@", atPos + 1) != -1) {
            return false;
        }
        periodPos = email.indexOf(".", atPos);
        if (periodPos == -1) {
            return false;
        }
        if (periodPos + 3 > email.length) {
            return false;
        }
        return true;
    },
    ValidateDate: function() {
        var date = this.element.value;
        var date_split = date.split("/");
        try {
            var aiDays = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
            var iDay = parseInt(date_split[0], 10);
            var iMonth = parseInt(date_split[1], 10);
            var iYear = parseInt(date_split[2], 10);
            if (iDay < 1 || iMonth < 1 || iYear < 0) {
                return false;
            }
            if (iMonth > 12) {
                return false;
            }
            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]);
        } catch (err) {
            return false;
        }
        return false;
    }
};
var meCustomerForm;
CustomerForm = function(infoResa) {
    this.infoResa = infoResa;
    this.tab_tb = new Array();
    this.tab_tb_persons = new Array();
    this.nb_accompanying_person = 0;
};
CustomerForm.prototype = {
    AddTextBox: function(propertyName, IDTb) {
        if (document.getElementById(IDTb)) {
            this[propertyName] = this.GetFormElement(IDTb);
            this.tab_tb.push(propertyName);
        }
    },
    GetFormElement: function(ID, level) {
        if (document.getElementById(ID)) {
            var elem = document.getElementById(ID);
            var form_e = new FormElement(ID, (elem.attributes.maxlength) ? elem.attributes.maxlength.nodeValue : null, (elem.attributes.levelObligationValue) ? elem.attributes.levelObligationValue.nodeValue : "Optional", (elem.attributes.typedata) ? elem.attributes.typedata.nodeValue : "AlphaNumeric");
            if (level) {
                form_e.niveau = level;
            }
            return form_e;
        }
        return null;
    },
    SetForPitch: function(classCBInfoForPitch, IDTbXDmension, IDTbYDimension) {
        this.tab_cb_infos_pitch = $$("."+classCBInfoForPitch);
        this.AddTextBox("x_dimension", IDTbXDmension);
        this.AddTextBox("y_dimension", IDTbYDimension);
    },
    SetForAirport: function(IDSelectAirport, IDTbCommentAirport) {
        this.select_airport = document.forms[0][IDSelectAirport];
        this.AddTextBox("comment_airport", IDTbCommentAirport);
    },
    SetForInfoPerso: function(IDTbSurName, IDTbFirstName, IDTbBirthDate, IDTbAdress, IDTbPostCode, IDTbTown, IDTbCountry, IDTbTel, IDTbFax, IDTbEMail, IDTbSpecialRequest) {
        this.AddTextBox("sur_name", IDTbSurName);
        this.AddTextBox("first_name", IDTbFirstName);
        this.AddTextBox("birth_date", IDTbBirthDate);
        this.AddTextBox("adress", IDTbAdress);
        this.AddTextBox("post_code", IDTbPostCode);
        this.AddTextBox("town", IDTbTown);
        this.AddTextBox("country", IDTbCountry);
        this.AddTextBox("tel", IDTbTel);
        this.AddTextBox("fax", IDTbFax);
        this.AddTextBox("email", IDTbEMail);
        this.AddTextBox("special_request", IDTbSpecialRequest);
    },
    SetAccompanyingPerson: function(BaseSurName, BaseFirstName, BaseBirthDate, IDSelectNbPerson) {
        this.base_sur_name = BaseSurName;
        this.base_first_name = BaseFirstName;
        this.base_birth_date = BaseBirthDate;
        this.select_nb_person = document.getElementById(IDSelectNbPerson);
    },
    SetAcompanyingPerson: function() {
        this.nb_accompanying_person = 0;
        this.tab_tb_person = null;
        if (this.select_nb_person && this.select_nb_person.value != "") {
            this.tab_tb_person = new Array();
            var nb = parseInt(this.select_nb_person.value, 10);
            for (var i = 1; i <= nb; i++) {
                if (document.getElementById(this.base_sur_name + "" + i)) {
                    this.tab_tb_person.push({
                        sur_name: this.GetFormElement(this.base_sur_name + "" + i, "Obligatory"),
                        first_name: this.GetFormElement(this.base_first_name + "" + i, "Obligatory"),
                        birth_date: this.GetFormElement(this.base_birth_date + "" + i, "Obligatory")
                    });
                    this.nb_accompanying_person++;
                }
            }
        }
    },
    GetSelectedAirport: function() {
        if (typeof(this.select_airport) == "undefined") {
            return "";
        }
        if (this.select_airport.value) {
            return this.select_airport.value;
        }
        for (var i = 0; i < this.select_airport.length; i++) {
            if (this.select_airport[i].checked) {
                return this.select_airport[i].value;
            }
        }
        return "";
    },
    Check: function(callBack, callBackWS) {
        if (this.ValidateFields(callBack)) {
            meCustomerForm = this;
            this.callBackWS = callBackWS;
            PageMethods.CheckCustomerFormInformations(this.infoResa.idEngine, this.infoResa.idEtablissement, this.infoResa.isoLanguageCode, this.infoResa.tac, this.infoResa.spec, this.infoResa.crcChoosenOption, this.infoResa.StringIdAssurance, this.GetValue("sur_name"), this.GetValue("first_name"), this.GetDate(this.GetValue("birth_date")), this.GetValue("adress"), this.GetValue("post_code"), this.GetValue("town"), this.GetValue("country"), this.GetValue("tel"), this.GetValue("fax"), this.GetValue("email"), this.nb_accompanying_person, this.GetAccompanyingPersons(), this.GetValue("special_request"), this.GetIdInfoForPitch(), this.GetValue("x_dimension"), this.GetValue("y_dimension"), this.GetSelectedAirport(), this.GetValue("comment_airport"), OnCompleteCF, OnErrorCF, OnTimeoutCF);
        }
    },
    ValidateFields: function(callBack) {
        this.SetAcompanyingPerson();
        var est_ok = true;
        for (var i = 0; i < this.tab_tb.length; i++) {
            if (!this[this.tab_tb[i]].Validate()) {
                if (callBack) {
                    callBack(this[this.tab_tb[i]].element);
                }
                est_ok = false;
            }
        }
        if (this.tab_tb_person) {
            for (var i = 0; i < this.tab_tb_person.length; i++) {
                var elem = this.tab_tb_person[i];
                if (!elem.sur_name.Validate()) {
                    if (callBack) {
                        callBack(elem.sur_name.element);
                    }
                    est_ok = false;
                }
                if (!elem.first_name.Validate()) {
                    if (callBack) {
                        callBack(elem.first_name.element);
                    }
                    est_ok = false;
                }
                if (!elem.birth_date.Validate()) {
                    if (callBack) {
                        callBack(elem.birth_date.element);
                    }
                    est_ok = false;
                }
            }
        } else {
            if (this.select_nb_person) {
                if (callBack) {
                    callBack(this.select_nb_person);
                }
                est_ok = false;
            }
        }
        return est_ok;
    },
    GetValue: function(fieldName) {
        if (this[fieldName]) {
            return this[fieldName].GetValue();
        }
        return "";
    },
    GetAccompanyingPersons: function() {
        var res = new Array();
        if (this.tab_tb_person) {
            for (var i = 0; i < this.tab_tb_person.length; i++) {
                var un_form = this.tab_tb_person[i];
                var un_person = new ControlSkin3.miniserv.accompanyingPersons();
                un_person.surName = un_form.sur_name.element.value;
                un_person.firstName = un_form.first_name.element.value;
                un_person.birthDate = this.GetDate(un_form.birth_date.element.value);
                res.push(un_person);
            }
        }
        return res;
    },
    GetIdInfoForPitch: function() {
        var res = new Array();
        for (var i = 0; i < this.tab_cb_infos_pitch.length; i++) {
            if (this.tab_cb_infos_pitch[i].checked) {
                res.push(this.tab_cb_infos_pitch[i].value);
            }
        }
        return res;
    },
    GetDate: function(chaine) {
        if (chaine && chaine != "") {
            var chaine_split = chaine.split("/");
            return new Date(parseInt(chaine_split[2], 10), (parseInt(chaine_split[1], 10) - 1), parseInt(chaine_split[0], 10));
        }
        return null;
    },
    RetourWS: function(result) {
        if (result.isCorrect == true) {
            document.getElementById("bscrc").value = result.crc;
            document.forms[0].action = domaineSSL + "booking_summary.aspx";
            document.forms[0].submit();
        } else {
            this.callBackWS(result);
        }
    },
    Precedent: function() {
        document.forms[0].action = "options.aspx";
        document.forms[0].submit();
    }
};

function OnCompleteCF(result) {
    meCustomerForm.RetourWS(result);
}
function OnErrorCF() {
    alert("error");
}
function OnTimeoutCF() {
    alert("timeout");
}
function InitInfoResaFormCustomerForm(idEngine, idEtablissement, isoLanguageCode, tac, spec, crcChoosenOption, StringIdAssurance) {
    var inforesa = new InfosResa();
    inforesa.idEngine = idEngine;
    inforesa.idEtablissement = idEtablissement;
    inforesa.isoLanguageCode = isoLanguageCode;
    inforesa.tac = tac;
    inforesa.spec = spec;
    inforesa.crcChoosenOption = crcChoosenOption;
    inforesa.StringIdAssurance = StringIdAssurance;
    return inforesa;
}
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) {
    this.hidden = document.getElementById(idHiddenFieldValue);
    this.className = className;
    this.checkOne = mustCheckOne;
    this.checkAll = checkAll;
    this.libelle = libelle;
};
PanelCheckbox.prototype.EcireDansHiddenField = function() {
	
    if (this.hidden) {
			
        this.hidden.value = "";
        var tab_cb = $$("input."+this.className);
			
        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;
        }
    }
};
var tab_hierarchie_checkbox = new Array();

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) {
    checkChild(cb);
    value = cb.value;
    if (parseInt(value)) {
        tab_checked_sub.addOrDelete(value, cb.checked);
    } else {
        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();
}

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");
        }
    }
}
MyGMap = function(id_div_carte) {
    this.filtresCamp = new Array();
    this.templateContenuBulle = "NOM : ${data.nom}<br/>ETOILE : ${data.rate}<br/>REGION : ${data.region}<br/>PHOTO : ${data.photo}<br/>NUM CAMP ${data.num_camp}<br/>";
    this.mapCircle = null;
    this.div_carte = document.getElementById(id_div_carte);
    this.gmap = new GMap2(this.div_carte);
    this.gmap.addControl(new GMapTypeControl());
    this.gmap.addMapType(G_PHYSICAL_MAP);
    this.gmap.setMapType(G_PHYSICAL_MAP);
    this.gmap.enableScrollWheelZoom();
    this.geoXml = new GeoXml(this);
    this.markerCamps = new Array();
    this.champTitreBulle = "nom";
    this.defaultStyle = new GIcon();
    this.SetClusterer = function(urlImgClusterer, maxVisible, minPerMarker) {
        this.clusterer = new Clusterer(this.gmap);
        this.clusterer.SetMaxVisibleMarkers(maxVisible);
        this.clusterer.SetMinMarkersPerCluster(minPerMarker);
        this.clusterer.SetMaxLinesPerInfoBox(7);
        if (urlImgClusterer) {
            this.clusterer.SetIcon(this.geoXml.makeIcon(urlImgClusterer, null));
        }
    };
    this.SetForcedClusterer = function(data, MaxZoomToMakeCluster) {
        this.clusterer = new Clusterer(this.gmap);
        this.clusterer.MaxZoomToMakeCluster = MaxZoomToMakeCluster;
        this.clusterer.ForcedClusters = data;
    };
    this.SetCenter = function(latitude, longitude, zoom) {
        this.gmap.setCenter(new GLatLng(latitude, longitude), zoom);
    };
    this.GoBestCenter = function () {
        var bou = new GLatLngBounds();
        for (var i = 0; i < this.markerCamps.length; i++) {
            var m = this.markerCamps[i].marker;
            bou.extend(m.getLatLng());
        }
        if (this.markerCamps.length == 1) {
            this.gmap.setCenter(this.markerCamps[0].marker.getLatLng(), 7);
        } else {
            this.gmap.setCenter(bou.getCenter(), this.gmap.getBoundsZoomLevel(bou));
        }
    };
    this.CreateDescription = function(donnee) {
        return this.templateContenuBulle.process({
            data: donnee
        });
    };
    this.GetTitle = function(donnee) {
        return (donnee) ? donnee[this.champTitreBulle] : "";
    };
    this.AddMarker = function(marker, data) {
        this.markerCamps.push(new MarkerCamp(marker, data));
        if (this.clusterer) {
            this.clusterer.AddMarker(marker, marker.getTitle());
        } else {
            this.gmap.addOverlay(marker);
        }
    };
    this.RetourDisplayDataXML = function() {
        this.GoBestCenter();
    };
    this.SetDefaultIcon = function(url, largeur) {
        this.defaultStyle = this.geoXml.makeIcon(url);
        if (largeur) {
            this.largeurIcone = largeur;
        }
    };
    this.EnableSelectionCercle = function(id_champ_rayon, id_tb_latitude, id_tb_longitude) {
        this.longitude = document.getElementById(id_tb_longitude);
        this.latitude = document.getElementById(id_tb_latitude);
        InitMarkerCentre.call(this);
        var that = this;
        GEvent.addListener(this.gmap, "click", function(overlay, point) {
            if (!overlay) {
                if (!that.markerCenter) {
                    that.markerCenter = new GMarker(point, {
                        draggable: true
                    });
                    that.gmap.addOverlay(that.markerCenter);
                } else {
                    that.markerCenter.setLatLng(point);
                }
                that.mapCircle.UpdateCircle();
                setLatLng.call(that, point);
            }
        });
        GEvent.addListener(this.gmap, "move", function() {
            that.mapCircle.dessineCadre();
        });
        this.mapCircle = new MapCircle(this, this.markerCenter, id_champ_rayon);
    };

    function InitMarkerCentre() {
        var point = new GLatLng(this.latitude.value, this.longitude.value);
        if (!this.markerCenter) {
            this.markerCenter = new GMarker(point, {
                draggable: true
            });
            var that = this;
            GEvent.addListener(this.markerCenter, "drag", function() {
                that.mapCircle.UpdateCircle();
                setLatLng.call(that, this.getPoint());
            });
            this.gmap.addOverlay(this.markerCenter);
        } else {
            setLatLng.call(this, point);
        }
    }
    function setLatLng(point) {
        if (this.longitude && this.latitude) {
            this.latitude.value = point.lat();
            this.longitude.value = point.lng();
        }
    }
    this.AddFiltre = function(filtre) {
        this.filtresCamp.push(filtre);
        this.filtresCamp[filtre.cham_filtre] = filtre;
    };
    this.Filtre = function() {
       for (var i = 0; i < this.markerCamps.length; i++) {
            this.markerCamps[i].montrer();
        }
        for (var i = 0; i < this.filtresCamp.length; i++) {
            for (var j = 0; j < this.markerCamps.length; j++) {
                if (!this.filtresCamp[i].EstOK(this.markerCamps[j])) {
                    this.markerCamps[j].cacher();
                }
            }
        }
    };
};
GeoXml = function(myGMap) {
    this.myGMap = myGMap;
    this.stylesGMap = [];

    function manageStyle(styles) {
        var styles_temps = makeArrayIfNot(styles);
        for (var i = 0; i < styles_temps.length; i++) {
            var sid = styles_temps[i].id;
            if (sid) {
                var href = styles_temps[i].iconstyle.icon.href;
                if ( !! href) {
                    this.stylesGMap["#" + sid] = this.makeIcon(href);
                }
            }
        }
    }
    function ImageSize(src) {
        var newImg1 = new Image();
        newImg1.src = src;
        return {
            height: newImg1.height,
            width: newImg1.width
        };
    }
    this.makeIcon = function(href, largeur) {
        var tempstyle = new GIcon();
        var taille = ImageSize(href);
        if (taille.width == 0 || taille.height == 0) {
            taille = {
                width: 32,
                height: 32
            };
        }
        if (taille.width > 32) {
            old_width = taille.width;
            taille.width = 32;
            taille.height = (taille.height * taille.width) / old_width;
        }
        tempstyle.infoWindowAnchor = new GPoint(taille.width / 2, taille.height / 2);
        tempstyle.iconSize = new GSize(taille.width, taille.height);
        tempstyle.iconAnchor = new GPoint(taille.width / 2, taille.height / 2);
        tempstyle.imageMap = [0, 0, (taille.width - 1), 0, (taille.height - 1), (taille.width - 1), 0, (taille.height - 1)];
        tempstyle.image = href;
        tempstyle.shadow = "";
        tempstyle.name = "hey";
        tempstyle.id = "image_style";
        return tempstyle;
    };

    function makeArrayIfNot(objet) {
        if (!objet.length) {
            var array_temp = new Array();
            array_temp.push(objet);
            return array_temp;
        }
        return objet;
    }
    function creerPlacemarks(node) {
        var node_temp = makeArrayIfNot(node);
        var len = node_temp.length;
        for (i = 0; i < len; i++) {
            creerMarker.call(this, node_temp[i]);
        }
    }
    function creerMarker(marker) {
        var coordonnees = marker.point.coordinates.split(",");
        var desc = (marker.description) ? marker.description : "";
        var style = (marker.styleurl) ? this.stylesGMap[marker.styleurl] : this.myGMap.defaultStyle;
        var point = new GLatLng(parseFloat(coordonnees[1]), parseFloat(coordonnees[0]));
        var data = (marker.extendeddata) ? eval("(" + marker.extendeddata + ")") : {};
        var titre_mark = this.myGMap.GetTitle(data);
        var gMarker = new GMarker(point, {
            icon: style,
            title: titre_mark
        });
        gMarker.getIcon().shadow = "";
        gMarker.title = "";
        var desc = this.myGMap.CreateDescription(data);
        var me = this;
        if (!this.onClickMarker) {
            GEvent.addListener(gMarker, "click", function() {
                gMarker.openInfoWindow(desc);
            });
        } else {
            GEvent.addListener(gMarker, "click", function() {
                me.onClickMarker(desc);
            });
        }
        this.myGMap.AddMarker(gMarker, data);
        gMarker.SHData = data;
    }
    this.DisplayData = function(url) {
        var util = new UtilAjax();
        var data = util.GetXmlDataToJson(url);
        if (!data) {
            return;
        }
        var root = data.kml;
        var placemarks = [];
        if (root.document.style) {
            manageStyle.call(this, root.document.style);
        }
        creerPlacemarks.call(this, root.document.placemark);
        this.myGMap.RetourDisplayDataXML();
    };
};
MapCircle = function(mygmap, marker_centre, id_champ_rayon) {
    this.color_ligne = "#000000";
    this.mygmap = mygmap;
    this.marker_centre = marker_centre;
    this.rayon = document.getElementById(id_champ_rayon);

    function getRayon() {
        if (this.rayon) {
            return this.rayon.value * 2;
        }
        return 100;
    }
    function getGMap() {
        return this.mygmap.gmap;
    }
    function encodeSignedNumber(num) {
        var sgn_num = num << 1;
        if (num < 0) {
            sgn_num = ~ (sgn_num);
        }
        return (encodeNumber(sgn_num));
    }
    function encodeNumber(num) {
        var encodeString = "";
        while (num >= 32) {
            encodeString += (String.fromCharCode((32 | (num & 31)) + 63));
            num >>= 5;
        }
        encodeString += (String.fromCharCode(num + 63));
        return encodeString;
    }
    function createPointForEncode(lat, lon, zoom) {
        return {
            Latitude: lat,
            Longitude: lon,
            Level: zoom
        };
    }
    function createEncodingsPoints(points) {
        var encoded_points = "";
        var plat = 0;
        var plng = 0;
        for (i = 0; i < points.length; ++i) {
            var point = points[i];
            var lat = point.Latitude;
            var lng = point.Longitude;
            var late5 = Math.floor(lat * 100000);
            var lnge5 = Math.floor(lng * 100000);
            dlat = late5 - plat;
            dlng = lnge5 - plng;
            plat = late5;
            plng = lnge5;
            encoded_points += encodeSignedNumber(dlat) + encodeSignedNumber(dlng);
        }
        return encoded_points;
    }
    function createEncodingsLevel(points) {
        var encoded_levels = "";
        for (i = 0; i < points.length; ++i) {
            encoded_levels += "P";
        }
        return encoded_levels;
    }
    function getTabFramePoints() {
        var zoom = getGMap.call(this).getZoom();
        var sw = getGMap.call(this).getBounds().getSouthWest();
        var ne = getGMap.call(this).getBounds().getNorthEast();
        var x_min = sw.lng();
        var x_max = ne.lng();
        var y_min = sw.lat();
        var y_max = ne.lat();
        var cadreLine = new Array();
        cadreLine.push(createPointForEncode(y_max, x_max, zoom));
        cadreLine.push(createPointForEncode(y_max, x_min, zoom));
        cadreLine.push(createPointForEncode(y_min, x_min, zoom));
        cadreLine.push(createPointForEncode(y_min, x_max, zoom));
        cadreLine.push(createPointForEncode(y_max, x_max, zoom));
        return cadreLine;
    }
    function dessineCercle(latitude, longitude, rayon) {
        var normalProj = G_NORMAL_MAP.getProjection();
        var zoom = getGMap.call(this).getZoom();
        var centerPt = normalProj.fromLatLngToPixel(this.marker_centre.getPoint(), zoom);
        var latRadius = this.marker_centre.getLatLng().lat() + getRayon.call(this) / 111;
        var radiusPt = normalProj.fromLatLngToPixel(new GLatLng(latRadius, this.marker_centre.getLatLng().lng()), zoom);
        var circlePoints = Array();
        var circlePoints2 = Array();
        with(Math) {
            var radiusDist = floor(sqrt(pow((centerPt.x - radiusPt.x), 2) + pow((centerPt.y - radiusPt.y), 2)));
            radiusB = radiusDist - (min(255, radiusDist) / 2) * 1;
            for (var a = 10; a < 181; a += 10) {
                var aRad = a * 2 * (PI / 180);
                y = centerPt.y + radiusB * sin(aRad);
                x = centerPt.x + radiusB * cos(aRad);
                var l = normalProj.fromPixelToLatLng(new GPoint(x, y), zoom);
                var p2 = createPointForEncode(l.lat(), l.lng(), zoom);
                circlePoints2.push(p2);
            }
            circlePoints2.push(circlePoints2[0]);
            var framePoints = getTabFramePoints.call(this);
            this.parameterCircle = {
                polylines: [{
                    points: createEncodingsPoints(framePoints),
                    levels: createEncodingsLevel(framePoints),
                    color: this.color_ligne,
                    opacity: 1,
                    weight: 2,
                    numLevels: 18,
                    zoomFactor: 2
                },
                {
                    points: createEncodingsPoints(circlePoints2),
                    levels: createEncodingsLevel(circlePoints2),
                    color: this.color_ligne,
                    opacity: 1,
                    weight: 4,
                    numLevels: 18,
                    zoomFactor: 2
                }],
                fill: true,
                color: this.color_ligne,
                opacity: 0.2,
                outline: true
            };
            this.dessineCadre();
        }
    }
    function setEncodedPolygon() {
        if (this.polygoneCercle) {
            getGMap.call(this).removeOverlay(this.polygoneCercle);
        }
        this.polygoneCercle = new GPolygon.fromEncoded(this.parameterCircle);
        getGMap.call(this).addOverlay(this.polygoneCercle);
        var gmap = getGMap.call(this);
        GEvent.addListener(this.polygoneCercle, "click", function(latlng) {
            GEvent.trigger(this.gmap, "click", null, latlng);
        });
    }
    this.dessineCadre = function() {
        if (this.parameterCircle && this.parameterCircle.polylines) {
            var framePoints = getTabFramePoints.call(this);
            var points1 = createEncodingsPoints(framePoints);
            var level1 = createEncodingsLevel(framePoints);
            this.parameterCircle.polylines[0] = {
                points: points1,
                levels: level1,
                color: this.color_ligne,
                opacity: 1,
                weight: 2,
                numLevels: 18,
                zoomFactor: 2
            };
            setEncodedPolygon.call(this);
        }
    };
    this.UpdateCircle = function() {
        if (this.marker_centre) {
            dessineCercle.call(this, this.marker_centre.getLatLng().lat(), this.marker_centre.getLatLng().lng(), getRayon.call(this));
        }
    };
};
MarkerCamp = function(markerGMap, infos_camp) {
    this.marker = markerGMap;
    this.infos = infos_camp;
    this.montrer = function() {
        //this.marker.show();
    };
    this.cacher = function() {
        this.marker.hide();
    };
};
UtilAjax = function() {
    this.GetXmlDataToJson = function(url) {
        if (window.XMLHttpRequest) {
            AJAX = new XMLHttpRequest();
        } else {
            AJAX = new ActiveXObject("Microsoft.XMLHTTP");
        }
        if (AJAX) {
            AJAX.open("GET", url, false);
            AJAX.send(null);
            return xml2json.parser(AJAX.responseText);
        } else {
            return false;
        }
    };
};
FiltreCamp = function(champ_filtre, valeur, doit_avoir_toute_les_valeurs, operateur_compare) {
    this.champ_filtre = champ_filtre;
    this.valeur = valeur;
    this.doit_avoir_tout_les_valeurs = doit_avoir_toute_les_valeurs;
    this.operateur = operateur_compare;
    this.EstOK = function(camp) {
        var donnee = camp.infos[this.champ_filtre];
        if (typeof(donnee) == "object") {
            return ifArrayInArrayShowMarker(this.valeur, donnee, this.doit_avoir_tout_les_valeurs);
        } else {
            if (donnee) {
                return eval("donnee " + this.operateur + " this.valeur  ");
            }
        }
        return true;
    };

    function ifArrayInArrayShowMarker(array, array2, isOr) {
        if (typeof(isOr) == "undefined") {
            isOr = false;
        }
        show = !isOr;
        if (array.length > 0) {
            for (var j = 0; j < array.length && (!isOr || (isOr && !show)); j++) {
                if (!parseInt(array[j])) {
                    if (!isOr) {
                        if (!stringSearch(array[j], array2)) {
                            show = false;
                        }
                    } else {
                        if (stringSearch(array[j], array2)) {
                            show = true;
                        }
                    }
                } else {
                    if (!isOr) {
                        if (!dichotomicSearch(array[j], array2)) {
                            show = false;
                        }
                    } else {
                        if (dichotomicSearch(array[j], array2)) {
                            show = true;
                        }
                    }
                }
            }
            return show;
        }
    }
    function stringSearch(X, list) {
        return list.indexOf(X) >= 0;
    }
    function dichotomicSearch(X, list) {
        var middle, start, end, elt, debut;
        end = list.length;
        start = 0;
        while (start <= end) {
            middle = Math.floor((start + end) / 2);
            elt = list[middle];
            if (X == elt) {
                return true;
            }
            if (parseInt(X) < parseInt(elt)) {
                end = middle - 1;
            } else {
                start = middle + 1;
            }
        }
        return false;
    }
};
Clusterer = function(map) {
    if (!Clusterer.defaultMaxVisibleMarkers) {
        Clusterer.defaultMaxVisibleMarkers = 150;
        Clusterer.defaultGridSize = 5;
        Clusterer.defaultMinMarkersPerCluster = 5;
        Clusterer.defaultMaxLinesPerInfoBox = 10;
        Clusterer.defaultIcon = new GIcon();
        Clusterer.defaultIcon.image = "http://www.acme.com/resources/images/markers/blue_large.PNG";
        Clusterer.defaultIcon.shadow = "http://www.acme.com/resources/images/markers/shadow_large.PNG";
        Clusterer.defaultIcon.iconSize = new GSize(30, 51);
        Clusterer.defaultIcon.shadowSize = new GSize(56, 51);
        Clusterer.defaultIcon.iconAnchor = new GPoint(13, 34);
        Clusterer.defaultIcon.infoWindowAnchor = new GPoint(13, 3);
        Clusterer.defaultIcon.infoShadowAnchor = new GPoint(27, 37);
        GMarker.prototype.setMap = function(map) {
            this.map = map;
        };
        GMarker.prototype.addedToMap = function() {
            this.map = null;
        };
        GMarker.prototype.origOpenInfoWindow = GMarker.prototype.openInfoWindow;
        GMarker.prototype.openInfoWindow = function(node, opts) {
            if (this.map != null) {
                return this.map.openInfoWindow(this.getPoint(), node, opts);
            } else {
                return this.origOpenInfoWindow(node, opts);
            }
        };
        GMarker.prototype.origOpenInfoWindowHtml = GMarker.prototype.openInfoWindowHtml;
        GMarker.prototype.openInfoWindowHtml = function(html, opts) {
            if (this.map != null) {
                return this.map.openInfoWindowHtml(this.getPoint(), html, opts);
            } else {
                return this.origOpenInfoWindowHtml(html, opts);
            }
        };
        GMarker.prototype.origOpenInfoWindowTabs = GMarker.prototype.openInfoWindowTabs;
        GMarker.prototype.openInfoWindowTabs = function(tabNodes, opts) {
            if (this.map != null) {
                return this.map.openInfoWindowTabs(this.getPoint(), tabNodes, opts);
            } else {
                return this.origOpenInfoWindowTabs(tabNodes, opts);
            }
        };
        GMarker.prototype.origOpenInfoWindowTabsHtml = GMarker.prototype.openInfoWindowTabsHtml;
        GMarker.prototype.openInfoWindowTabsHtml = function(tabHtmls, opts) {
            if (this.map != null) {
                return this.map.openInfoWindowTabsHtml(this.getPoint(), tabHtmls, opts);
            } else {
                return this.origOpenInfoWindowTabsHtml(tabHtmls, opts);
            }
        };
        GMarker.prototype.origShowMapBlowup = GMarker.prototype.showMapBlowup;
        GMarker.prototype.showMapBlowup = function(opts) {
            if (this.map != null) {
                return this.map.showMapBlowup(this.getPoint(), opts);
            } else {
                return this.origShowMapBlowup(opts);
            }
        };
    }
    this.map = map;
    this.markers = [];
    this.clusters = [];
    this.timeout = null;
    this.currentZoomLevel = map.getZoom();
    this.maxVisibleMarkers = Clusterer.defaultMaxVisibleMarkers;
    this.gridSize = Clusterer.defaultGridSize;
    this.minMarkersPerCluster = Clusterer.defaultMinMarkersPerCluster;
    this.maxLinesPerInfoBox = Clusterer.defaultMaxLinesPerInfoBox;
    this.icon = Clusterer.defaultIcon;
    //GEvent.addListener(map, "zoomend", Clusterer.MakeCaller(Clusterer.Display, this));
    //GEvent.addListener(map, "moveend", Clusterer.MakeCaller(Clusterer.Display, this));
    //GEvent.addListener(map, "infowindowclose", Clusterer.MakeCaller(Clusterer.PopDown, this));
};
Clusterer.prototype.SetIcon = function(icon) {
    this.icon = icon;
};
Clusterer.prototype.SetMaxVisibleMarkers = function(n) {
    this.maxVisibleMarkers = n;
};
Clusterer.prototype.SetMinMarkersPerCluster = function(n) {
    this.minMarkersPerCluster = n;
};
Clusterer.prototype.SetMaxLinesPerInfoBox = function(n) {
    this.maxLinesPerInfoBox = n;
};
Clusterer.prototype.AddMarker = function(marker, title) {
    if (marker.setMap != null) {
        marker.setMap(this.map);
    }
    marker.title = title;
    marker.onMap = false;
    this.markers.push(marker);
    this.DisplayLater();
};
Clusterer.prototype.RemoveMarker = function(marker) {
    for (var i = 0; i < this.markers.length; ++i) {
        if (this.markers[i] == marker) {
            if (marker.onMap) {
                this.map.removeOverlay(marker);
            }
            for (var j = 0; j < this.clusters.length; ++j) {
                var cluster = this.clusters[j];
                if (cluster != null) {
                    for (var k = 0; k < cluster.markers.length; ++k) {
                        if (cluster.markers[k] == marker) {
                            cluster.markers[k] = null;
                            --cluster.markerCount;
                            break;
                        }
                    }
                    if (cluster.markerCount == 0) {
                        this.ClearCluster(cluster);
                        this.clusters[j] = null;
                    } else {
                        if (cluster == this.poppedUpCluster) {
                            Clusterer.RePop(this);
                        }
                    }
                }
            }
            this.markers[i] = null;
            break;
        }
    }
    this.DisplayLater();
};
Clusterer.prototype.DisplayLater = function() {
    if (this.timeout != null) {
        clearTimeout(this.timeout);
    }
    this.timeout = setTimeout(Clusterer.MakeCaller(Clusterer.Display, this), 50);
};
Clusterer.Display = function(clusterer) {
    var i, j, marker, cluster;
    clearTimeout(clusterer.timeout);
    var newZoomLevel = clusterer.map.getZoom();
    if (newZoomLevel != clusterer.currentZoomLevel) {
        for (i = 0; i < clusterer.clusters.length; ++i) {
            if (clusterer.clusters[i] != null) {
                clusterer.ClearCluster(clusterer.clusters[i]);
                clusterer.clusters[i] = null;
            }
        }
        clusterer.clusters.length = 0;
        clusterer.currentZoomLevel = newZoomLevel;
    }
    var bounds = clusterer.map.getBounds();
    var sw = bounds.getSouthWest();
    var ne = bounds.getNorthEast();
    var dx = ne.lng() - sw.lng();
    var dy = ne.lat() - sw.lat();
    if (dx < 300 && dy < 150) {
        dx *= 0.1;
        dy *= 0.1;
        bounds = new GLatLngBounds(new GLatLng(sw.lat() - dy, sw.lng() - dx), new GLatLng(ne.lat() + dy, ne.lng() + dx));
    }
    var visibleMarkers = [];
    var nonvisibleMarkers = [];
    for (i = 0; i < clusterer.markers.length; ++i) {
        marker = clusterer.markers[i];
        if (marker != null) {
            if (bounds.contains(marker.getPoint())) {
                visibleMarkers.push(marker);
            } else {
                nonvisibleMarkers.push(marker);
            }
        }
    }
    for (i = 0; i < nonvisibleMarkers.length; ++i) {
        marker = nonvisibleMarkers[i];
        if (marker.onMap) {
            clusterer.map.removeOverlay(marker);
            marker.onMap = false;
        }
    }
    for (i = 0; i < clusterer.clusters.length; ++i) {
        cluster = clusterer.clusters[i];
        if (cluster != null && !bounds.contains(cluster.marker.getPoint()) && cluster.onMap) {
            clusterer.map.removeOverlay(cluster.marker);
            cluster.onMap = false;
        }
    }
    if (clusterer.ForcedClusters) {
        clusterer.maxVisibleMarkers = -1;
        clusterer.minMarkersPerCluster = 0;
    }
    if (visibleMarkers.length > clusterer.maxVisibleMarkers) {
        var latRange = bounds.getNorthEast().lat() - bounds.getSouthWest().lat();
        var latInc = latRange / clusterer.gridSize;
        var lngInc = latInc / Math.cos((bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) / 2 * Math.PI / 180);
        if (!clusterer.ForcedClusters) {
            for (var lat = bounds.getSouthWest().lat(); lat <= bounds.getNorthEast().lat(); lat += latInc) {
                for (var lng = bounds.getSouthWest().lng(); lng <= bounds.getNorthEast().lng(); lng += lngInc) {
                    cluster = new Object();
                    cluster.clusterer = clusterer;
                    cluster.bounds = new GLatLngBounds(new GLatLng(lat, lng), new GLatLng(lat + latInc, lng + lngInc));
                    cluster.markers = [];
                    cluster.markerCount = 0;
                    cluster.onMap = false;
                    cluster.marker = null;
                    clusterer.clusters.push(cluster);
                }
            }
            for (i = 0; i < visibleMarkers.length; ++i) {
                marker = visibleMarkers[i];
                if (marker != null && !marker.inCluster) {
                    for (j = 0; j < clusterer.clusters.length; ++j) {
                        cluster = clusterer.clusters[j];
                        if (cluster != null && cluster.bounds.contains(marker.getPoint())) {
                            cluster.markers.push(marker);
                            ++cluster.markerCount;
                            marker.inCluster = true;
                        }
                    }
                }
            }
        } else {
            if (clusterer.MaxZoomToMakeCluster >= clusterer.map.getZoom()) {
                for (j = 0; j < clusterer.ForcedClusters.length; j++) {
                    cluster = new Object();
                    cluster.clusterer = clusterer;
                    cluster.markers = [];
                    cluster.markerCount = 0;
                    cluster.onMap = false;
                    cluster.marker = null;
                    clusterer.clusters.push(cluster);
                    for (i = 0; i < visibleMarkers.length; ++i) {
                        var marker = visibleMarkers[i];
                        for (x = 0; x < clusterer.ForcedClusters[j].length; x++) {
                            if (marker.SHData.num_camp == clusterer.ForcedClusters[j][x]) {
                                cluster.markers.push(marker);
                                ++cluster.markerCount;
                                marker.inCluster = true;
                            }
                        }
                    }
                }
            }
        }
        for (i = 0; i < clusterer.clusters.length; ++i) {
            if (clusterer.clusters[i] != null && clusterer.clusters[i].markerCount < clusterer.minMarkersPerCluster) {
                clusterer.ClearCluster(clusterer.clusters[i]);
                clusterer.clusters[i] = null;
            }
        }
        for (i = clusterer.clusters.length - 1; i >= 0; --i) {
            if (clusterer.clusters[i] != null) {
                break;
            } else {
                --clusterer.clusters.length;
            }
        }
        for (i = 0; i < clusterer.clusters.length; ++i) {
            cluster = clusterer.clusters[i];
            if (cluster != null) {
                for (j = 0; j < cluster.markers.length; ++j) {
                    marker = cluster.markers[j];
                    if (marker != null && marker.onMap) {
                        clusterer.map.removeOverlay(marker);
                        marker.onMap = false;
                    }
                }
            }
        }
        for (i = 0; i < clusterer.clusters.length; ++i) {
            cluster = clusterer.clusters[i];
            if (cluster != null && cluster.marker == null) {
                var xTotal = 0,
                    yTotal = 0;
                for (j = 0; j < cluster.markers.length; ++j) {
                    marker = cluster.markers[j];
                    if (marker != null) {
                        xTotal += (+marker.getPoint().lng());
                        yTotal += (+marker.getPoint().lat());
                    }
                }
                var location = new GLatLng(yTotal / cluster.markerCount, xTotal / cluster.markerCount);
                marker = new GMarker(location, {
                    icon: clusterer.icon
                });
                cluster.marker = marker;
                GEvent.addListener(marker, "click", Clusterer.MakeCaller(Clusterer.PopUp, cluster));
            }
        }
    }
    for (i = 0; i < visibleMarkers.length; ++i) {
        marker = visibleMarkers[i];
        if (marker != null && !marker.onMap && !marker.inCluster) {
            clusterer.map.addOverlay(marker);
            if (marker.addedToMap != null) {
                marker.addedToMap();
            }
            marker.onMap = true;
        }
    }
    for (i = 0; i < clusterer.clusters.length; ++i) {
        cluster = clusterer.clusters[i];
        if (cluster != null && !cluster.onMap && bounds.contains(cluster.marker.getPoint())) {
            clusterer.map.addOverlay(cluster.marker);
            cluster.onMap = true;
        }
    }
    Clusterer.RePop(clusterer);
};
Clusterer.PopUp = function(cluster) {
    var clusterer = cluster.clusterer;
    var html = '<table width="300">';
    var n = 0;
    for (var i = 0; i < cluster.markers.length; ++i) {
        var marker = cluster.markers[i];
        if (marker != null) {
            ++n;
            html += "<tr><td>";
            if (marker.getIcon().smallImage != null) {
                html += '<img src="' + marker.getIcon().smallImage + '">';
            } else {
                html += '<img src="' + marker.getIcon().image + '" width="' + (marker.getIcon().iconSize.width / 2) + '" height="' + (marker.getIcon().iconSize.height / 2) + '">';
            }
            html += "</td><td>" + marker.title + "</td></tr>";
            if (n == clusterer.maxLinesPerInfoBox - 1 && cluster.markerCount > clusterer.maxLinesPerInfoBox) {
                html += '<tr><td colspan="2">...and ' + (cluster.markerCount - n) + " more</td></tr>";
                break;
            }
        }
    }
    html += "</table>";
    clusterer.map.closeInfoWindow();
    cluster.marker.openInfoWindowHtml(html);
    clusterer.poppedUpCluster = cluster;
};
Clusterer.RePop = function(clusterer) {
    if (clusterer.poppedUpCluster != null) {
        Clusterer.PopUp(clusterer.poppedUpCluster);
    }
};
Clusterer.PopDown = function(clusterer) {
    clusterer.poppedUpCluster = null;
};
Clusterer.prototype.ClearCluster = function(cluster) {
    var i, marker;
    for (i = 0; i < cluster.markers.length; ++i) {
        if (cluster.markers[i] != null) {
            cluster.markers[i].inCluster = false;
            cluster.markers[i] = null;
        }
    }
    cluster.markers.length = 0;
    cluster.markerCount = 0;
    if (cluster == this.poppedUpCluster) {
        this.map.closeInfoWindow();
    }
    if (cluster.onMap) {
        this.map.removeOverlay(cluster.marker);
        cluster.onMap = false;
    }
};
Clusterer.MakeCaller = function(func, arg) {
    return function() {
        func(arg);
    };
};
var geoXml;
var map;
var cadre_map;
var path_kml;
var opt_global = {
    messagebox: false,
    nozoom: true,
    icontype: "style",
    noshadow: true
};
var opt_camping = {
    messagebox: false,
    nozoom: true,
    width_icon: 32,
    icontype: "style",
    noshadow: true
};
var opt_geo;
var type_map = "global";
var doit_maj;
var id_camping;
var num_diapo;
var search;
var overview;
var is_recherche = false;
String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, "");
};
String.prototype.contains = function(t) {
    return this.indexOf(t) >= 0 ? true : false;
};

function jeval(str) {
    return eval("(" + str + ")");
}
function loadScript(callbackName) {
    eval(callbackName + "();");
}
function is_def(va) {
    return (typeof(va) != "undefined");
}
if (!Array.indexOf) {
    Array.prototype.indexOf = function(obj) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == obj) {
                return i;
            }
        }
        return -1;
    };
}
function load_googlemap() {
    if (GBrowserIsCompatible()) {
        retaillFenetre();
        map = new GMap2(cadre_map);
        map.tab_id_cpg = new Array();
        map.tab_marker_default = new Array();
        if (type_map != "global") {
            map.setCenter(new GLatLng(lat, lon), zoo);
        } else {
            map.setCenter(new GLatLng(46.890231573594, 4.04296875), 5);
        }
        map.addControl(new GMapTypeControl());
        map.addMapType(G_PHYSICAL_MAP);
        map.enableScrollWheelZoom();
        chargerKML();
        GEvent.addListener(geoXml, "parsed", event_parsed);
    } else {
        alert("Votre navigateur n'est pas compatible avec cette carte");
    }
}
var ecouteurAjoutes;

function event_parsed() {
    if (type_map == "global") {
        maj_nb_camping();
    }
    cacherAttente();
    if (!ecouteurAjoutes) {
        GEvent.clearInstanceListeners(map);
        GEvent.addListener(map, "click", traite_marker);
        //GEvent.addListener(map, "moveend", fin_mouvement);
       // GEvent.addListener(map, "zoomend", traite_zoom);
        //GEvent.addListener(map, "movestart", debut_mouvement);
    }
    if (map.getZoom() == zoom_anc && overlay_temp) {
        map.addOverlay(overlay_temp);
        overlay_temp = null;
    }
}
function aller_orig() {
    map.setCenter(new GLatLng(46.890231573594, 4.04296875), 5);
    closeOverlay();
}
function traite_marker(overlay, point) {
    if (overlay && overlay.openInfoWindow) {
        if (type_map == "global" && (!overlay.title || overlay.title.trim() == "")) {
            var nouvo_zoom = parseInt(map.getZoom()) + 1;
            map.setCenter(new GLatLng(overlay.getLatLng().lat(), overlay.getLatLng().lng()), (nouvo_zoom));
        }
    }
}
var timeout_zoom;

function traite_zoom(oldLevel, newLevel) {
    if (timeout_zoom != null) {
        clearTimeout(timeout_zoom);
    }
    timeout_zoom = setTimeout("traitement_zoom_end(" + oldLevel + ")", 100);
    setDisabled("form_recherche_dispo", (newLevel <= 5));
    var direction = oldLevel > newLevel ? -1 : 1;
    if (newLevel >= 17) {
        direction = -1;
    }
    if (newLevel <= 0) {
        direction = +1;
    }
    var validZoom = [3, 5, 8, 10, 13, 17];
    if (validZoom.indexOf(newLevel) == -1) {
        map.setZoom(newLevel + direction);
        return false;
    }
    overlay_temp = null;
    closeOverlay();
}
function traitement_zoom_end(oldLevel) {
    zoom_anc = oldLevel;
    if (estTransition() != 0) {
        map.clearOverlays();
    }
}
var zoom_anc;

function creer_url_maj_kml() {
    var bound = map.getBounds();
    var xmin = bound.getSouthWest().lng();
    var ymin = bound.getSouthWest().lat();
    var xmax = bound.getNorthEast().lng();
    var ymax = bound.getNorthEast().lat();
    var zoom = map.getZoom();
    var path_aspx = (type_map == "global") ? "./kml/gen_kml.aspx" : "./kml/gen_kml_camp.aspx";
    if (type_map == "global") {
        if (map.getZoom() <= 5) {
            path_kml = path_aspx + "?zoom=" + map.getZoom();
        } else {
            path_kml = path_aspx + "?xmax=" + xmax + "&ymax=" + ymax + "&xmin=" + xmin + "&ymin=" + ymin + "&zoom=" + zoom;
        }
        if (search) {
            path_kml += "&search=" + search;
        }
    } else {
        path_kml = path_aspx + "?xmax=" + xmax + "&ymax=" + ymax + "&xmin=" + xmin + "&ymin=" + ymin + "&zoom=" + zoom + "&id=" + id_camping + "&d=" + num_diapo;
    }
    return path_kml;
}
function chaine_id_cpg() {
    if (map.getZoom() <= 5 && type_map != "global") {
        return "";
    }
    if (map.tab_id_cpg.length <= 0) {
        return "";
    }
    var l = map.tab_id_cpg.length;
    var s = map.tab_id_cpg[0] + "";
    for (var i = l - 1; i > 0; i--) {
        if (map.tab_id_cpg[i]) {
            s += "+" + map.tab_id_cpg[i];
        }
    }
    return s;
}
var timeout_debut_mouvement;

function debut_mouvement() {
    closeOverlay();
    if (timeout_debut_mouvement != null) {
        clearTimeout(timeout_debut_mouvement);
    }
    timeout_debut_mouvement = setTimeout("traitement_debut_mouvement();", 200);
}
function traitement_debut_mouvement(index) {
    zoom_anc = map.getZoom();
}
var timeout_fin_mouvement;

function fin_mouvement() {
    if (timeout_fin_mouvement != null) {
        clearTimeout(timeout_fin_mouvement);
    }
    setTimeout("traitement_fin_mouvement();", 200);
}
var index_fin_mouvement = 0;

function traitement_fin_mouvement(index) {
    if (type_map == "global") {
        if (estTransition() != 0) {
            map.clearOverlays();
            if (estTransition() > 0) {
                geoXml.afficher_temp();
            }
            if (map.getZoom() <= 5) {
                setTabDetails("", "");
            }
        }
        if (estTransition() < 0 && map.tab_marker_default.length != 0) {
            chargerCarteDefaut();
        } else {
            if (map.tab_marker_default.length == 0 || (map.getZoom() > 5)) {
                chargerKML();
            }
        }
    }
}
function estTransition() {
    if (map.getZoom() <= 5 && zoom_anc > 5) {
        return -1;
    }
    if (zoom_anc <= 5 && map.getZoom() > 5) {
        return 1;
    }
    return 0;
}
function chargerCarteDefaut() {
    map.clearOverlays();
    var l = map.tab_marker_default.length;
    for (var i = 0; i < l; i++) {
        var m = map.tab_marker_default[i];
        if (m.taille) {
            var new_taille = (m.taille / 100) * 10 + 14;
            m.getIcon().iconSize = new GSize(new_taille, new_taille);
            m.getIcon().iconAnchor = new GPoint(new_taille / 2, new_taille / 2);
            m.importance = 2;
        }
        map.addOverlay(m);
    }
}
var timer = 0;

function chargerKML() {
    var path_kml = creer_url_maj_kml();
    timer++;
    var s = "";
    if (geoXml) {
        var ch = chaine_id_cpg();
    }
    var tab_mark = new Array();
    if (geoXml == null) {
        geoXml = new GeoXml("geoXml", map, path_kml, opt_geo);
    } else {
        geoXml.url = path_kml;
    }
    geoXml.chaine_id_cpg = ch;
    setTimeout("lancerParseGeoXML(" + timer + ");", 500);
}
function lancerParseGeoXML(id) {
    if (timer == id) {
        montrerAttente();
        geoXml.parse();
    }
}
var div_attente;

function montrerAttente() {
    $("div_attente").style.visibility = "visible";
    $("img_attente").style.visibility = "visible";
}
function cacherAttente() {
    $("img_attente").style.visibility = "hidden";
    $("div_attente").style.visibility = "hidden";
}
function centrerCarteSur(lat, lon, zoom, geonameid) {
    search = geonameid;
    ferme_mpe(i_mpe_recherche);
    if (map.getZoom() == zoom) {
        map.panTo(new GLatLng(lat, lon));
    } else {
        map.setCenter(new GLatLng(lat, lon), zoom);
    }
}
var marker_cercle;

function entourerPoint(lat, lon) {
    var fingerIcon = new GIcon();
    fingerIcon.image = "./style/circle.png";
    fingerIcon.shadow = "";
    fingerIcon.iconSize = new GSize(28, 28);
    fingerIcon.iconAnchor = new GPoint(14, 14);
    fingerIcon.transparent = "";
    fingerIcon.printImage = "";
    fingerIcon.mozPrintImage = "";
    if (!marker_cercle) {
        marker_cercle = new GMarker(new GLatLng(lat, lon), {
            icon: fingerIcon,
            zIndexProcess: importanceOrder
        });
        marker_cercle.importance = 1;
        map.addOverlay(marker_cercle);
    } else {
        marker_cercle.setLatLng(new GLatLng(lat, lon));
        marker_cercle.show();
    }
}
function supprimerEntourage() {
    if (marker_cercle) {
        marker_cercle.hide();
    }
}
function afficheInfoWindowMarker(i) {
    GEvent.trigger(geoXml.tab_marker[i], "click");
}
function importanceOrder(marker, b) {
    return GOverlay.getZIndex(marker.getPoint().lat()) + marker.importance * 1000000;
}
var currentMarker;
var MyOverlay = function(marker, html) {
    this.marker = marker;
    this.html = html;
};

function subGPoints(a, b) {
    return new GPoint(a.x - b.x, a.y - b.y);
}
function addGPoints(a, b) {
    return new GPoint(a.x + b.x, a.y + b.y);
}
function change_pays(val) {
    setTimeout("enable_region(" + (val == "") + ");", 500);
}
function enable_region(oui) {
    document.getElementById(id_ddl_region).disabled = oui;
}
function setMarkerBound(include_hidden) {
    var tab_marker_bound;
    if (typeof(include_hidden) == "undefined") {
        include_hidden = true;
    }
    var b = map.getBounds();
    tab_marker_bound = new Array();
    var l = geoXml.tab_marker.length;
    for (var i = 0; i < l; i++) {
        var m = geoXml.tab_marker[i];
        if (b.contains(m.getPoint()) && (include_hidden || (!include_hidden && !m.isHidden()))) {
            tab_marker_bound.push(m);
        }
    }
    return tab_marker_bound;
}
function reponse_dispo(str_cpg_64, err) {
    if (err != null) {
        alert(err);
    } else {
        var str_id_cpg = "+" + decode64(str_cpg_64) + "+";
        is_recherche = true;
        var tab_marker_bound = setMarkerBound();
        var l = tab_marker_bound.length;
        for (var i = 0; i < l; i++) {
            if (tab_marker_bound[i].camping) {
                var c = tab_marker_bound[i].camping.id;
                if (!str_id_cpg.contains("+" + c + "+")) {
                    tab_marker_bound[i].hide();
                } else {
                    tab_marker_bound[i].show();
                    tab_marker_bound[i].setImage("./style/camping_dispo.png");
                }
            }
        }
    }
    maj_nb_camping();
    cacherAttente();
}
function maj_nb_camping() {
    if (map.getZoom() > 5) {
        var tab_marker_bound = setMarkerBound(!is_recherche);
        var l = tab_marker_bound.length;
        var inner = "<div id='liste_camping'>";
        for (var i = 0; i < l; i++) {
            if (tab_marker_bound[i].camping) {
                inner += TrimPath.processDOMTemplate("liste_cpg_jst", tab_marker_bound[i].camping);
            }
        }
        setTabDetails(l, inner + "</div>");
    } else {
        setTabDetails("", "");
    }
}
function annuler_recherche() {
    var l = geoXml.tab_marker.length;
    for (var i = 0; i < l; i++) {
        geoXml.tab_marker[i].show();
        geoXml.tab_marker[i].setImage("./style/camping.png");
    }
    is_recherche = false;
    maj_nb_camping();
}
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

function encode64(input) {
    var output = "";
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;
    do {
        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);
        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;
        if (isNaN(chr2)) {
            enc3 = enc4 = 64;
        } else {
            if (isNaN(chr3)) {
                enc4 = 64;
            }
        }
        output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4);
    } while (i < input.length);
    return output;
}
function decode64(input) {
    var output = "";
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;
    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
    do {
        enc1 = keyStr.indexOf(input.charAt(i++));
        enc2 = keyStr.indexOf(input.charAt(i++));
        enc3 = keyStr.indexOf(input.charAt(i++));
        enc4 = keyStr.indexOf(input.charAt(i++));
        chr1 = (enc1 << 2) | (enc2 >> 4);
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        chr3 = ((enc3 & 3) << 6) | enc4;
        output = output + String.fromCharCode(chr1);
        if (enc3 != 64) {
            output = output + String.fromCharCode(chr2);
        }
        if (enc4 != 64) {
            output = output + String.fromCharCode(chr3);
        }
    } while (i < input.length);
    return output;
}
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;
};
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 searchForm;
SearchForm = function(UrlResult) {
    this.tab_panel_checkbox = new Array();
    this.UrlRechercheDispo = UrlResult;
    this.form = document.forms[0];
    this.ouvre_dans_popup = true;
};
SearchForm.prototype.SetMode1 = function(IdHiddenFieldTerritoire, IdTextBoxLieux, IdTbLat, IdTbLon, IDDivSuggestion, IDDivDetails, UrlRedirection, Filtre) {
    this.hf_territoire = document.getElementById(IdHiddenFieldTerritoire);
    this.IsSamePlace = this.hf_territoire.value.trim != "";
    this.tb_lieux = document.getElementById(IdTextBoxLieux);
    this.est_auto_complete_lieux = typeof(this.tb_lieux) != "undefined" && this.tb_lieux != null;
    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.div_suggestion = document.getElementById(IDDivDetails);
        this.detailPage = UrlRedirection.trim() != "";
        this.UrlRedirectLieux = UrlRedirection;
    }
    this.filtreMode1 = (Filtre) ? Filtre : "";
    this.estMode1 = true;
};
SearchForm.prototype.SetMode2 = function(IdHiddenFieldTerritoire, IdTbLat, IdTbLon) {
    this.hf_territoire = document.getElementById(IdHiddenFieldTerritoire);
    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);
};
SearchForm.prototype.IsSamePlace = function() {
    return (typeof(this.samePlace) == "undefined" || this.samePlace.value == "true");
};
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();
        }
    }
};
SearchForm.prototype.ShowWait = function() {
    document.body.style.cursor = "wait";
};
SearchForm.prototype.HideWait = function() {
    document.body.style.cursor = "default";
};
SearchForm.prototype.ShowPlaces = function(result) {
    this.HideWait();
    AutoComplete_Create(this.tb_lieux.id, result);
    AutoComplete_ShowDropdown(this.tb_lieux.id);
};
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);
    }
};
SearchForm.prototype.SetCallback = function(callback) {
    if ((typeof(callback) != "undefined") && (callback != null)) {
        this.callBackRequest = callback;
    }
};
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() != "";
};
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();
};
SearchForm.prototype.DoCallBackRequest = function(arg, arg2) {
    if ((this.callBackRequest != null) && (typeof(this.callBackRequest) != "undefined")) {
        this.callBackRequest(arg, arg2);
    }
};
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();
};
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));
    }
};
SearchForm.prototype.RetourVerifPlace = function(result) {
    this.HideWait();
    if (!result) {
        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.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));
};
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);
};

function GetAutoCompleteList(event) {
    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) {
    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();
ShAssurances = function() {
    this.MsgError = "";
    this.InsuranceTotalPrice = -1;
    this.InsuranceIdDetail = "";
    this.CodeError = -1;
    var callBackFunction;
    this.Calculate = function(idMoteur, isoLangue, idAssurance, valide, callback) {
        callBackFunction = callback;
        PageMethods.CheckAssurances(idMoteur, isoLangue, idAssurance, valide, this.MyMethod_Result_Assurances);
    }, this.MyMethod_Result_Assurances = function(ResultString) {
        this.CodeError = Number(ResultString["CodeError"]);
        this.MsgError = ResultString["error"];
        if (this.CodeError == 0) {
            this.InsuranceTotalPrice = formatNumber(MyParseFloat(ResultString["InsuranceTotalPrice"]), 2, true);
            this.InsuranceIdDetail = ResultString["InsuranceIdDetail"];
        }
        callBackFunction(this);
    };

    function MyParseFloat(s) {
        return parseFloat(s, 10);
    }
};

function harmonise_prix_avec_langue(Hmonnaie, Hprix, Hlg) {
    Hlg = Hlg.toLowerCase();
    var result_harmonise = "";
    if (Hlg == "nl") {
        result_harmonise = Hmonnaie + "&#160;" + formatNumber(Hprix, 2, false);
        result_harmonise = replace(result_harmonise, ".", ",");
    } else {
        if ((Hlg == "en") || (Hlg == "de")) {
            result_harmonise = Hmonnaie + "&#160;" + formatNumber(Hprix, 2, false);
        } else {
            result_harmonise = replace(formatNumber(Hprix, 2, false) + "&#160;" + Hmonnaie, ".", ",");
        }
    }
    return (result_harmonise);
}
function replace(string, text, by) {
    var strLength = string.length,
        txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0)) {
        return string;
    }
    var i = string.indexOf(text);
    if ((!i) && (text != string.substring(0, txtLength))) {
        return string;
    }
    if (i == -1) {
        return string;
    }
    var newstr = string.substring(0, i) + by;
    if (i + txtLength < strLength) {
        newstr += replace(string.substring(i + txtLength, strLength), text, by);
    }
    return newstr;
}
function formatNumber(nombre, apresVirgule, GarderEntier) {
    var NB = nombre + "";
    var positionVirgule = NB.indexOf(".");
    if (positionVirgule >= 0) {
        TAB_NB = NB.split(".");
        var partie_decimale = TAB_NB[1] + "";
        if (partie_decimale.length >= apresVirgule) {
            partie_decimale = partie_decimale.substring(0, 2);
        } else {
            for (var z = 0; z < apresVirgule - partie_decimale.length; z++) {
                partie_decimale = partie_decimale + "0";
            }
        }
        NB = TAB_NB[0] + "." + partie_decimale;
    } else {
        if (!GarderEntier) {
            NB = NB + ".00";
        }
    }
    return (NB);
}
var meShOption;
ShOptions = function() {
    this.IdError = -1;
    this.MsgError = "";
    this.RegularShare = -1;
    this.VariableShare = -1;
    this.TotalPrice = -1;
    this.DepositPrice = -1;
    this.BookingFees = -1;
    this.TotalDeposit = -1;
    this.BalanceDue = -1;
    this.BasePrice = -1;
    this.OptionPrice = -1;
    this.Currency = "";
    this.StringChoosenOptions = "";
    this.TotalPers = -1;
    this.IsCancellationInsurance = "";
    var callBackFunction;
    this.Calculate = function(idMoteur, isoLangue, tac, spec, specOption, moos, chaineOption, valide, codePromo, callback) {
        callBackFunction = callback;
        meShOption = this;
        PageMethods.CheckOptions(idMoteur, isoLangue, tac, spec, specOption, moos, chaineOption, valide, codePromo, this.MyMethod_Result_CheckOptions);
    }, this.MyMethod_Result_CheckOptions = function(ResultString) {
        meShOption.IdError = Number(ResultString["errorId"]);
        meShOption.MsgError = ResultString["error"];
        if (meShOption.IdError == 0) {
            var bookingPriceInformations = ResultString["bookingPriceInformations"];
            meShOption.RegularShare = MyParseFloat(bookingPriceInformations["RegularShare"]);
            meShOption.VariableShare = MyParseFloat(bookingPriceInformations["VariableShare"]);
            meShOption.TotalPrice = MyParseFloat(bookingPriceInformations["TotalPrice"]);
            meShOption.DepositPrice = MyParseFloat(bookingPriceInformations["DepositPrice"]);
            meShOption.BookingFees = MyParseFloat(bookingPriceInformations["BookingFees"]);
            meShOption.TotalDeposit = MyParseFloat(bookingPriceInformations["TotalDeposit"]);
            meShOption.BalanceDue = MyParseFloat(bookingPriceInformations["BalanceDue"]);
            meShOption.BasePrice = MyParseFloat(bookingPriceInformations["BasePrice"]);
            meShOption.OptionPrice = MyParseFloat(bookingPriceInformations["OptionPrice"]);
            meShOption.Currency = bookingPriceInformations["Currency"];
            meShOption.StringChoosenOptions = bookingPriceInformations["StringChoosenOptions"];
            meShOption.TotalPers = bookingPriceInformations["TotalPers"];
            meShOption.IsCancellationInsurance = bookingPriceInformations["IsCancellationInsurance"];
            meShOption.crcChoosenOption = bookingPriceInformations.crcChoosenOptions;
            meShOption.CodePromo = bookingPriceInformations["DiscountCodeDetails"];
        }
        callBackFunction(meShOption);
    };

    function MyParseFloat(s) {
        return parseFloat(s, 10);
    }
};
InfosResa = function(idMoteur, idEtablissement, isoLangue, tac, spec, specOption, moos, typeProduit, idProduit, monnaie) {
    this.idMoteur = idMoteur;
    this.isoLangue = isoLangue;
    this.tac = tac;
    this.spec = spec;
    this.specOption = specOption;
    this.moos = moos;
    this.monnaie = monnaie;
    this.idProduit = idProduit;
    this.typeProduit = typeProduit;
    this.idEtablissement = idEtablissement;
};
OptionForm = function(infosResa, ClassSelecteurOption, IdDivPrixTotal, IdDivDeposit, IdDescShareVariable, IdDescShareFixe, IdDivBalance, IdDivFD, IdDivNbPers, IDDivMontant, IDCBAccepte, IDDivAssurance, IDHiddenCrc) {
    this.tab_input_option =$$("."+ClassSelecteurOption);
    if (this.tab_input_option) {
        this.inputs_options = {};
        for (var i = 0; i < this.tab_input_option.length; i++) {
            var un_input = this.tab_input_option[i];
            this.inputs_options[un_input.attributes.id_option.nodeValue] = un_input;
        }
    }
    this.div_prix_total = document.getElementById(IdDivPrixTotal);
    this.div_deposit = document.getElementById(IdDivDeposit);
    this.div_desc_share_variable = document.getElementById(IdDescShareVariable);
    this.div_desc_share_regular = document.getElementById(IdDescShareFixe);
    this.div_balance = document.getElementById(IdDivBalance);
    this.div_fd = document.getElementById(IdDivFD);
    this.div_nb_pers = document.getElementById(IdDivNbPers);
    this.div_montant = document.getElementById(IDDivMontant);
    this.infoResa = infosResa;
    this.shOption = new ShOptions();
    this.tb_crc_choosen_option = document.getElementById(IDHiddenCrc);
    this.id_div_assurance = IDDivAssurance;
    this.cb_accepte = document.getElementById(IDCBAccepte);
};
OptionForm.prototype.ActiverCodePromo = function(IDTBCodePromo, IDDivTextePromo, IDDivPrixPromo, IDDivErrorCodePromo) {
    this.tb_code_promo = document.getElementById(IDTBCodePromo);
    this.div_texte_promo = document.getElementById(IDDivTextePromo);
    this.div_montant_promo = document.getElementById(IDDivPrixPromo);
    this.div_error_promo = document.getElementById(IDDivErrorCodePromo);
};
OptionForm.prototype.MajResultatCodePromo = function(resultatCodePromo) {
    if (typeof(resultatCodePromo) == "undefined") {
        return;
    }
    if (resultatCodePromo.isOK) {
        this.div_texte_promo.innerHTML = resultatCodePromo.message;
        this.div_montant_promo.innerHTML = resultatCodePromo.codePromo.discountAmount;
        this.div_error_promo.innerHTML = "";
    } else {
        this.div_texte_promo.innerHTML = "";
        this.div_montant_promo.innerHTML = "";
        this.div_error_promo.innerHTML = resultatCodePromo.message;
    }
};
OptionForm.prototype.SetPrixDiv = function(div, prix) {
    if (div) {
        div.innerHTML = harmonise_prix_avec_langue(this.infoResa.monnaie, prix, this.infoResa.isoLangue);
    }
};
OptionForm.prototype.SetOptionSelected = function(options_choisies) {
    if (options_choisies == "") {
        return;
    }
    tab_options_choisies = options_choisies.split(";");
    for (var p = 0; p < tab_options_choisies.length; p++) {
        tab_p = tab_options_choisies[p].split("@");
        var un_input = this.inputs_options[tab_p[0]];
        un_input.value = tab_p[1];
    }
};
OptionForm.prototype.MajOutput = function(valide, callbackFunction) {
    this.callbackFunctionMaj = callbackFunction;
    this.shOption.Calculate(this.infoResa.idMoteur, this.infoResa.isoLangue, this.infoResa.tac, this.infoResa.spec, this.infoResa.specOption, this.infoResa.moos, this.GetChaineOption(), valide, this.GetCodePromo(), RetourMajOutput);
};

function RetourMajOutput(result) {
    optionForm.RetourMajOutput(result);
}
OptionForm.prototype.GetCodePromo = function() {
    if (!this.tb_code_promo) {
        return null;
    }
    return this.tb_code_promo.value;
};
OptionForm.prototype.RetourMajOutput = function(result) {
    if (this.shOption.IdError != 0) {
        alert(this.shOption.MsgError);
        return;
    }
    this.SetPrixDiv(this.div_prix_total, this.shOption.TotalPrice);
    this.SetPrixDiv(this.div_deposit, this.shOption.TotalDeposit);
    this.SetPrixDiv(this.div_balance, this.shOption.BalanceDue);
    this.SetPrixDiv(this.div_fd, this.shOption.BookingFees);
    this.div_nb_pers.innerHTML = this.shOption.TotalPers;
    this.SetPrixDiv(this.div_montant, this.shOption.TotalPrice - this.shOption.BookingFees);
    if (this.shOption.VariableShare > 100) {
        if (this.div_desc_share_variable) {
            this.div_desc_share_variable.innerHTML = tradPage.GetTrad("variable_share") + "100%";
        }
    } else {
        if (this.shOption.VariableShare > 0) {
            if (this.div_desc_share_variable) {
                this.div_desc_share_variable.innerHTML = tradPage.GetTrad("variable_share") + this.shOption.VariableShare + "%";
            }
        }
        if (this.shOption.RegularShare > 0) {
            if (this.div_desc_share_regular) {
                this.div_desc_share_regular.innerHTML = tradPage.GetTrad("regular_share");// + this.shOption.RegularShare + this.infoResa.monnaie;
            }
        }
    }
    this.DoCallBackMaj(result);
};
OptionForm.prototype.DoCallBackMaj = function(result) {
    if (this.callbackFunctionMaj) {
        this.callbackFunctionMaj(result);
    }
    this.callbackFunctionMaj = null;
};
OptionForm.prototype.GetChaineOption = function() {
    var res = "";
    for (var i = 0; i < this.tab_input_option.length; i++) {
        var un_input = this.tab_input_option[i];
        if (un_input.value != 0) {
            if (res != "") {
                res += ";";
            }
            res += un_input.attributes.id_option.nodeValue + "@" + un_input.value + "@" + un_input.attributes.prix.nodeValue;
        }
    }
    return res;
};
OptionForm.prototype.NextStep = function() {
    if (!this.cb_accepte.checked) {
        alert(tradPage.GetTrad("doit_cocher"));
        return;
    }
    this.MajOutput("YES", this.GoNextStep);
};
OptionForm.prototype.NextStepPanier = function() {
    if (!this.cb_accepte.checked) {
        alert(tradPage.GetTrad("doit_cocher"));
        return;
    }
    var actionForm = "";
    actionForm = "assurances.aspx?idM=" + this.infoResa.idMoteur + "&tac=" + this.infoResa.tac + "&spec=" + this.infoResa.spec + "&m=" + this.infoResa.moos + "&o=" + this.GetChaineOption() + "&t=" + this.infoResa.typeProduit + "&idP=" + this.infoResa.idProduit + "&idE=" + this.infoResa.idEtablissement;
    var form = document.forms[0];
    form.action = actionForm;
    form.submit();
};
OptionForm.prototype.AddPanier = function() {
    this.MajOutput("NO", this.GoPanier);
};
OptionForm.prototype.GoPanier = function() {
    if (this.shOption.IdError != 0) {
        alert(this.shOption.MsgError);
        return;
    }
    var actionForm = "";
    this.tb_crc_choosen_option.value = this.shOption.crcChoosenOption;
    actionForm = "panier.aspx?actionP=AH&idM=" + this.infoResa.idMoteur + "&tac=" + this.infoResa.tac + "&spec=" + this.infoResa.spec + "&m=" + this.infoResa.moos + "&o=" + this.GetChaineOption() + "&t=" + this.infoResa.typeProduit + "&idP=" + this.infoResa.idProduit + "&idE=" + this.infoResa.idEtablissement;
    var form = document.forms[0];
    form.action = actionForm;
    form.submit();
};
OptionForm.prototype.GoNextStep = function() {
    if (this.shOption.IdError != 0) {
        alert(this.shOption.MsgError);
        return;
    }
    var actionForm = "";
    this.tb_crc_choosen_option.value = this.shOption.crcChoosenOption;
    if (this.shOption.IsCancellationInsurance) {
        actionForm = "assurances.aspx?idM=" + this.infoResa.idMoteur + "&tac=" + this.infoResa.tac + "&spec=" + this.infoResa.spec + "&m=" + this.infoResa.moos + "&o=" + this.GetChaineOption() + "&t=" + this.infoResa.typeProduit + "&idP=" + this.infoResa.idProduit + "&idE=" + this.infoResa.idEtablissement;
    } else {
        actionForm = domaineSSL + "customer_form.aspx?idM=" + this.infoResa.idMoteur + "&tac=" + this.infoResa.tac + "&spec=" + this.infoResa.spec + "&idE=" + this.infoResa.idEtablissement + "&t=" + this.infoResa.typeProduit + "&idP=" + this.infoResa.idProduit;
    }
    var form = document.forms[0];
    form.action = actionForm;
    form.submit();
};
OptionForm.prototype.afficheCGV = function(idAssurance) {
    document.getElementById(this.id_div_assurance + idAssurance).style.display = "block";
    for (var i = 0; i < this.tab_input_option.length; i++) {
        this.tab_input_option[i].style.display = "none";
    }
};
OptionForm.prototype.closeCGV = function(idAssurance) {
    document.getElementById(this.id_div_assurance + idAssurance).style.display = "none";
    for (var i = 0; i < this.tab_input_option.length; i++) {
        this.tab_input_option[i].style.display = "inline";
    }
};
ShTri = function() {
    this.arrayOfEtablissement = new Array();
    this.addEtablissement = function(_id, _nom, _isAnwb, _pays, _region, _departement, _ville, _note) {
        this.arrayOfEtablissement.push(new etablissement(_id, _nom, _isAnwb, _pays, _region, _departement, _ville, _note));
    };

    function etablissement(_id, _nom, _isAnwb, _pays, _region, _departement, _ville, _note) {
        this.Id = _id;
        this.Nom = _nom;
        this.IsANWB = _isAnwb;
        this.Pays = _pays;
        this.Region = _region;
        this.Departement = _departement;
        this.Ville = _ville;
        if ((_note == null) || (_note == "")) {
            this.Note = 0;
        } else {
            this.Note = _note;
        }
    }
    var nomChamp1 = "";
    var nomChamp2 = "";
    var nomChamp3 = "";

    function sortByString(a, b) {
        var x = eval("a." + nomChamp1 + ".toLowerCase()");
        var y = eval("b." + nomChamp1 + ".toLowerCase()");
        if (nomChamp2 != "") {
            return ((x < y) ? -1 : ((x > y) ? 1 : sortByString2(a, b)));
        }
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    }
    function sortByString2(a, b) {
        var x = eval("a." + nomChamp2 + ".toLowerCase()");
        var y = eval("b." + nomChamp2 + ".toLowerCase()");
        if (nomChamp3 != "") {
            return ((x < y) ? -1 : ((x > y) ? 1 : sortByString3(a, b)));
        }
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    }
    function sortByString3(a, b) {
        var x = eval("a." + nomChamp3 + ".toLowerCase()");
        var y = eval("b." + nomChamp3 + ".toLowerCase()");
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    }
    function sortByBool(a, b) {
        var x = eval("a." + nomChamp1 + ".toLowerCase()");
        var y = eval("b." + nomChamp1 + ".toLowerCase()");
        return ((x > y) ? -1 : ((x < y) ? 1 : 0));
    }
    function sortByFloat(a, b) {
        var x = parseFloat(eval("a." + nomChamp1));
        var y = parseFloat(eval("b." + nomChamp1));
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    }
    this.choixDuTri = function(chaineDeTri, idDiv, modulo) {
        if (!modulo) {
            modulo = 10;
        }
        if ((chaineDeTri != null) && (chaineDeTri != "")) {
            var tabSplit = chaineDeTri.split("@");
            var champs = tabSplit[0];
            var tabChamps = champs.split(",");
            if (tabChamps.length == "1") {
                nomChamp1 = tabChamps[0];
                nomChamp2 = "";
                nomChamp3 = "";
                if (tabSplit[2] == "string") {
                    this.arrayOfEtablissement.sort(sortByString);
                } else {
                    if (tabSplit[2] == "bool") {
                        this.arrayOfEtablissement.sort(sortByBool);
                    } else {
                        if (tabSplit[2] == "float") {
                            this.arrayOfEtablissement.sort(sortByFloat);
                        }
                    }
                }
            } else {
                if (tabChamps.length == "2") {
                    nomChamp1 = tabChamps[0];
                    nomChamp2 = tabChamps[1];
                    nomChamp3 = "";
                    this.arrayOfEtablissement.sort(sortByString);
                } else {
                    nomChamp1 = tabChamps[0];
                    nomChamp2 = tabChamps[1];
                    nomChamp3 = tabChamps[2];
                    this.arrayOfEtablissement.sort(sortByString);
                }
            }
            if (tabSplit[1] == "0") {
                this.arrayOfEtablissement.reverse();
            }
            document.getElementById(idDiv).innerHTML = "";
            var chaine = "";
            var numPage = 0;
            var pageMoteurNb = "";
            var resultMoteurNb = "";
            for (var cpt = 0; cpt < this.arrayOfEtablissement.length; cpt++) {
                if ((cpt % modulo) == 0) {
                    if (cpt == 0) {
                        numPage++;
                        pageMoteurNb = "page_moteur_" + numPage;
                        chaine += "<div ID=" + pageMoteurNb + '  class="page_moteur">';
                    } else {
                        numPage++;
                        pageMoteurNb = "page_moteur_" + numPage;
                        chaine += '<div ID="' + pageMoteurNb + '" style="display:none" class="page_moteur">';
                    }
                }
                resultMoteurNb = "result_moteur" + (cpt + 1);
                chaine += "<div id='" + resultMoteurNb + "' class='result_moteur'>" + document.getElementById(this.arrayOfEtablissement[cpt].Id).innerHTML + "</div>";
                if ((cpt % modulo) == (modulo - 1)) {
                    chaine += "</div>";
                }
            }
            if ((cpt % modulo) != (modulo - 1)) {
                chaine += "</div>";
            }
            document.getElementById(idDiv).innerHTML = chaine;
            if (document.getElementById("bt_page_1")) {
                var cpt2 = 1;
                while (cpt2 <= numPage) {
                    if (document.getElementById("bt_page_" + cpt2)) {
                        document.getElementById("bt_page_" + cpt2).className = "boutonPageDispo";
                    }
                    if (document.getElementById("bt_page_B" + cpt2)) {
                        document.getElementById("bt_page_B" + cpt2).className = "boutonPageDispo";
                    }
                    cpt2 = cpt2 + 1;
                }
                if (document.getElementById("bt_page_1")) {
                    document.getElementById("bt_page_1").className = "boutonPageEnCours";
                }
                if (document.getElementById("bt_page_B1")) {
                    document.getElementById("bt_page_B1").className = "boutonPageEnCours";
                }
                if (document.getElementById("bouton_precedent")) {
                    document.getElementById("bouton_precedent").className = "bouton_navigationInactif";
                }
                if (document.getElementById("bouton_precedentB")) {
                    document.getElementById("bouton_precedentB").className = "bouton_navigationInactif";
                }
                if (document.getElementById("flechegauche")) {
                    document.getElementById("flechegauche").className = "flecheGrise";
                }
                if (document.getElementById("flechegaucheB")) {
                    document.getElementById("flechegaucheB").className = "flecheGrise";
                }
            }
        }
    };
};
var TrimPath;
(function() {
    if (TrimPath == null) {
        TrimPath = new Object();
    }
    if (TrimPath.evalEx == null) {
        TrimPath.evalEx = function(src) {
            return eval(src);
        };
    }
    var UNDEFINED;
    if (Array.prototype.pop == null) {
        Array.prototype.pop = function() {
            if (this.length === 0) {
                return UNDEFINED;
            }
            return this[--this.length];
        };
    }
    if (Array.prototype.push == null) {
        Array.prototype.push = function() {
            for (var i = 0; i < arguments.length; ++i) {
                this[this.length] = arguments[i];
            }
            return this.length;
        };
    }
    TrimPath.parseTemplate = function(tmplContent, optTmplName, optEtc) {
        if (optEtc == null) {
            optEtc = TrimPath.parseTemplate_etc;
        }
        var funcSrc = parse(tmplContent, optTmplName, optEtc);
        var func = TrimPath.evalEx(funcSrc, optTmplName, 1);
        if (func != null) {
            return new optEtc.Template(optTmplName, tmplContent, funcSrc, func, optEtc);
        }
        return null;
    };
    try {
        String.prototype.process = function(context, optFlags) {
            var template = TrimPath.parseTemplate(this, null);
            if (template != null) {
                return template.process(context, optFlags);
            }
            return this;
        };
    } catch (e) {}
    TrimPath.tagMaxLength = 16;
    var selfOUT = " var _OUT_arr = []; var _OUT = { write: function(m) { if (m) _OUT_arr.push(m); } }; ";
    var selfOUTResult = "_OUT_arr.join('')";
    TrimPath.replaceAll = function(exstr, ov, value) {
        var gc = ov.replace(/\\/gm, "\\\\").replace(/([\f\b\n\t\r[\^$|?*+(){}])/gm, "\\$1");
        if (gc == null || gc == "") {
            return exstr;
        }
        var reReplaceGene = "/" + gc + "/gm";
        var r = null;
        var cmd = "r=exstr.replace(" + reReplaceGene + ',"' + value + '")';
        eval(cmd);
        return r;
    };
    TrimPath.parseTemplate_etc = {};
    TrimPath.parseTemplate_etc.statementDef = {
        "if": {
            delta: 1,
            prefix: "if (",
            suffix: ") {",
            paramMin: 1
        },
        "else": {
            delta: 0,
            prefix: "} else {"
        },
        "elseif": {
            delta: 0,
            prefix: "} else if (",
            suffix: ") {",
            paramDefault: "true"
        },
        "/if": {
            delta: -1,
            prefix: "}"
        },
        "var": {
            delta: 0,
            prefix: "var ",
            suffix: ";"
        },
        "macro": {
            delta: 1,
            prefixFunc: function(stmtParts, state, tmplName, etc) {
                var macroName = stmtParts[1].split("(")[0];
                return ["var ", macroName, " = function", stmtParts.slice(1).join(" ").substring(macroName.length), "{ " + selfOUT].join("");
            }
        },
        "/macro": {
            delta: -1,
            prefix: " return " + selfOUTResult + "; };"
        },
        "switch": {
            delta: 1,
            prefix: "switch (",
            suffix: ') { case "${this_case_never_run__don`t_use_this_string_in_your_codes!!!}" :',
            paramMin: 1
        },
        "case": {
            delta: 0,
            prefix: "  case ",
            suffix: " :",
            paramMin: 1
        },
        "default": {
            delta: 0,
            prefix: "  default : "
        },
        "/switch": {
            delta: -1,
            prefix: "}"
        },
        "while": {
            delta: 1,
            prefix: "while (",
            suffix: ") {",
            paramMin: 1,
            paramDefault: "false"
        },
        "/while": {
            delta: -1,
            prefix: "}"
        },
        "for": {
            delta: 1,
            prefix: "for ( var for_index=0 ; for_index<",
            suffix: " ; for_index++ ) {",
            paramMin: 1
        },
        "/for": {
            delta: -1,
            prefix: "}"
        },
        "foreach": {
            delta: 1,
            paramMin: 3,
            prefixFunc: function(stmtParts, state, tmplName, etc) {
                if (stmtParts[2] != "in") {
                    throw new etc.ParseError(tmplName, state.line, "bad for loop statement: " + stmtParts.join(" "));
                }
                var iterVar = stmtParts[1];
                var listVar = "__LIST__" + iterVar;
                return ["var ", listVar, " = ", stmtParts[3], ";", "var __LENGTH_STACK__;", "if (typeof(__LENGTH_STACK__) == 'undefined' || !__LENGTH_STACK__.length) __LENGTH_STACK__ = new Array();", "__LENGTH_STACK__[__LENGTH_STACK__.length] = 0;", "if ((", listVar, ") != null) { ", "var ", iterVar, "_ct = 0;", "for (var ", iterVar, "_index in ", listVar, ") { ", iterVar, "_ct++;", "if (typeof(", listVar, "[", iterVar, "_index]) == 'function') {continue;}", "__LENGTH_STACK__[__LENGTH_STACK__.length - 1]++;", "var ", iterVar, " = ", listVar, "[", iterVar, "_index];"].join("");
            }
        },
        "forelse": {
            delta: 0,
            prefix: "} } if (__LENGTH_STACK__[__LENGTH_STACK__.length - 1] == 0) { if (",
            suffix: ") {",
            paramDefault: "true"
        },
        "/foreach": {
            delta: -1,
            prefix: "} }; delete __LENGTH_STACK__[__LENGTH_STACK__.length - 1];"
        },
        "break": {
            delta: 0,
            prefix: "break ",
            suffix: ";"
        },
        "continue": {
            delta: 0,
            prefix: "continue ",
            suffix: ";"
        },
        "exec": {
            delta: 0,
            prefix: "",
            suffix: ";"
        },
        "inline": {
            delta: 1,
            prefix: " _OUT.write( scrubWhiteSpace( (function(){ " + selfOUT + " "
        },
        "/inline": {
            delta: -1,
            prefix: " return " + selfOUTResult + "; })() ) );"
        },
        "minifymacro": {
            delta: 1,
            prefixFunc: function(stmtParts, state, tmplName, etc) {
                var macroName = stmtParts[1].split("(")[0];
                return ["var ", macroName, " = function", stmtParts.slice(1).join(" ").substring(macroName.length), "{ " + selfOUT].join("");
            }
        },
        "/minifymacro": {
            delta: -1,
            prefix: " return scrubWhiteSpace(" + selfOUTResult + "); };"
        }
    };
    TrimPath.parseTemplate_etc.statementTag = function() {
        var rex = "";
        for (var key in TrimPath.parseTemplate_etc.statementDef) {
            if (key.indexOf("/") != 0) {
                rex += ("|" + key);
            }
        }
        rex = rex.substr(1);
        return rex;
    }();
    TrimPath.parseTemplate_etc.modifierDef = {
        "eat": function(v) {
            return "";
        },
        "escape": function(s) {
            return String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
        },
        "capitalize": function(s) {
            return String(s).toUpperCase();
        },
        "default": function(s, d) {
            return s != null ? s : d;
        },
        "transform": function() {
            var s;
            var b;
            var y = "";
            var n = "";
            var rs;
            s = arguments[0];
            if (arguments.length == 2) {
                b = (s != null && s.length > 0);
                y = arguments[1];
            } else {
                if (arguments.length == 3) {
                    b = (s != null && s.length > 0);
                    y = arguments[1];
                    n = arguments[2];
                } else {
                    if (arguments.length == 4) {
                        b = arguments[1];
                        y = arguments[2];
                        n = arguments[3];
                    }
                }
            }
            if (b) {
                y = TrimPath.replaceAll(y, "$this", s + "");
                rs = y;
            } else {
                n = TrimPath.replaceAll(n, "$this", s + "");
                rs = n;
            }
            return rs;
        },
        "times": function(s, t, d) {
            if (t < 1) {
                t = 1;
            }
            if (typeof(d) == "undefined" || d == null) {
                d = "";
            }
            var rs = "";
            for (var i = 0; i < t - 1; i++) {
                rs = rs + s + d;
            }
            rs = rs + s;
            return rs;
        },
        "attribute": function(s, b) {
            var res = "";
            var a;
            for (var attribute in s) {
                var attributeValue = s[attribute];
                a = "";
                if (attributeValue != null && attributeValue.length > 0) {
                    a = attribute + '="' + attributeValue + '" ';
                } else {
                    if (b) {
                        a = attribute + '="" ';
                    }
                }
                res += a;
            }
            return res;
        },
        "minify": function(s) {
            return scrubWhiteSpace(s);
        },
        "inline": function(s) {
            return String(s).replace(/\n/g, "");
        }
    };
    TrimPath.parseTemplate_etc.blockrxDef = {
        "cdata": function(blockText, funcText) {
            emitText(blockText, funcText);
        },
        "minify": function(blockText, funcText) {
            emitText(scrubWhiteSpace(blockText), funcText);
        },
        "eval": function(blockText, funcText) {
            if (blockText != null && blockText.length > 0) {
                funcText.push("_OUT.write( (function() { " + blockText + " })() );");
            }
        }
    };
    TrimPath.parseTemplate_etc.blockrxRex = function() {
        var rex = "";
        for (var key in TrimPath.parseTemplate_etc.blockrxDef) {
            rex += ("|" + key);
        }
        rex = rex.substr(1);
        eval("rex=/^\\{(" + rex + ")$/;");
        return rex;
    }();
    TrimPath.parseTemplate_etc.Template = function(tmplName, tmplContent, funcSrc, func, etc) {
        this.process = function(context, flags) {
            if (context == null) {
                context = {};
            }
            if (context._MODIFIERS == null) {
                context._MODIFIERS = {};
            }
            if (context.defined == null) {
                context.defined = function(str) {
                    return (typeof(context[str]) != undefined);
                };
            }
            for (var k in etc.modifierDef) {
                if (context._MODIFIERS[k] == null) {
                    context._MODIFIERS[k] = etc.modifierDef[k];
                }
            }
            if (flags == null) {
                flags = {};
            }
            var resultArr = [];
            var resultOut = {
                write: function(m) {
                    resultArr.push(m);
                }
            };
            try {
                func(resultOut, context, flags);
            } catch (e) {
                if (flags.throwExceptions == true) {
                    throw e;
                }
                var result = new String(resultArr.join("") + "[ERROR: " + e.toString() + (e.message ? "; " + e.message : "") + "]");
                result["exception"] = e;
                return result;
            }
            return resultArr.join("");
        };
        this.name = tmplName;
        this.source = tmplContent;
        this.sourceFunc = funcSrc;
        this.toString = function() {
            return "TrimPath.Template [" + tmplName + "]";
        };
    };
    TrimPath.parseTemplate_etc.ParseError = function(name, line, message) {
        this.name = name;
        this.line = line;
        this.message = message;
    };
    TrimPath.parseTemplate_etc.ParseError.prototype.toString = function() {
        return ("TrimPath template ParseError in " + this.name + ": line " + this.line + ", " + this.message);
    };
    var parse = function(body, tmplName, etc) {
        body = cleanWhiteSpace(body);
        var funcText = ["var TrimPath_Template_TEMP = function(_OUT, _CONTEXT, _FLAGS) { with (_CONTEXT) {"];
        var state = {
            stack: [],
            line: 1
        };
        var endStmtPrev = -1;
        while (endStmtPrev + 1 < body.length) {
            var begStmt = endStmtPrev;
            begStmt = body.indexOf("{", begStmt + 1);
            while (begStmt >= 0) {
                var endStmt = body.indexOf("}", begStmt + 1);
                var stmt = body.substring(begStmt, endStmt);
                var blockrx = stmt.match(TrimPath.parseTemplate_etc.blockrxRex);
                if (blockrx) {
                    var blockType = blockrx[1];
                    var blockMarkerBeg = begStmt + blockType.length + 1;
                    var blockMarkerEnd = body.indexOf("}", blockMarkerBeg);
                    if (blockMarkerEnd >= 0) {
                        var blockMarker;
                        if (blockMarkerEnd - blockMarkerBeg <= 0) {
                            blockMarker = "{/" + blockType + "}";
                        } else {
                            blockMarker = body.substring(blockMarkerBeg + 1, blockMarkerEnd);
                        }
                        var blockEnd = body.indexOf(blockMarker, blockMarkerEnd + 1);
                        if (blockEnd >= 0) {
                            emitSectionText(body.substring(endStmtPrev + 1, begStmt), funcText);
                            var blockText = body.substring(blockMarkerEnd + 1, blockEnd);
                            for (var bkey in TrimPath.parseTemplate_etc.blockrxDef) {
                                if (blockType == bkey) {
                                    TrimPath.parseTemplate_etc.blockrxDef[bkey](blockText, funcText);
                                }
                            }
                            begStmt = endStmtPrev = blockEnd + blockMarker.length - 1;
                        }
                    }
                } else {
                    if (body.charAt(begStmt - 1) != "$" && body.charAt(begStmt - 1) != "\\") {
                        var offset = (body.charAt(begStmt + 1) == "/" ? 2 : 1);
                        if (body.substring(begStmt + offset, begStmt + TrimPath.tagMaxLength + offset).search(TrimPath.parseTemplate_etc.statementTag) == 0) {
                            break;
                        }
                    }
                }
                begStmt = body.indexOf("{", begStmt + 1);
            }
            if (begStmt < 0) {
                break;
            }
            var endStmt = body.indexOf("}", begStmt + 1);
            if (endStmt < 0) {
                break;
            }
            emitSectionText(body.substring(endStmtPrev + 1, begStmt), funcText);
            emitStatement(body.substring(begStmt, endStmt + 1), state, funcText, tmplName, etc);
            endStmtPrev = endStmt;
        }
        emitSectionText(body.substring(endStmtPrev + 1), funcText);
        if (state.stack.length != 0) {
            throw new etc.ParseError(tmplName, state.line, "unclosed, unmatched statement(s): " + state.stack.join(","));
        }
        funcText.push("}}; TrimPath_Template_TEMP;");
        return funcText.join("");
    };
    var emitStatement = function(stmtStr, state, funcText, tmplName, etc) {
        var parts = stmtStr.slice(1, -1).split(" ");
        var stmt = etc.statementDef[parts[0]];
        if (stmt == null) {
            emitSectionText(stmtStr, funcText);
            return;
        }
        if (stmt.delta < 0) {
            if (state.stack.length <= 0) {
                throw new etc.ParseError(tmplName, state.line, "close tag does not match any previous statement: " + stmtStr);
            }
            state.stack.pop();
        }
        if (stmt.delta > 0) {
            state.stack.push(stmtStr);
        }
        if (stmt.paramMin != null && stmt.paramMin >= parts.length) {
            throw new etc.ParseError(tmplName, state.line, "statement needs more parameters: " + stmtStr);
        }
        if (stmt.prefixFunc != null) {
            funcText.push(stmt.prefixFunc(parts, state, tmplName, etc));
        } else {
            funcText.push(stmt.prefix);
        }
        if (stmt.suffix != null) {
            if (parts.length <= 1) {
                if (stmt.paramDefault != null) {
                    funcText.push(stmt.paramDefault);
                }
            } else {
                for (var i = 1; i < parts.length; i++) {
                    if (i > 1) {
                        funcText.push(" ");
                    }
                    funcText.push(parts[i]);
                }
            }
            funcText.push(stmt.suffix);
        }
    };
    var emitSectionText = function(text, funcText) {
        if (text.length <= 0) {
            return;
        }
        var nlPrefix = 0;
        var nlSuffix = text.length - 1;
        while (nlPrefix < text.length && (text.charAt(nlPrefix) == "\n")) {
            nlPrefix++;
        }
        while (nlSuffix >= 0 && (text.charAt(nlSuffix) == " " || text.charAt(nlSuffix) == "\t")) {
            nlSuffix--;
        }
        if (nlSuffix < nlPrefix) {
            nlSuffix = nlPrefix;
        }
        if (nlPrefix > 0) {
            funcText.push('if (_FLAGS.keepWhitespace == true) _OUT.write("');
            var s = text.substring(0, nlPrefix).replace("\n", "\\n");
            if (s.charAt(s.length - 1) == "\n") {
                s = s.substring(0, s.length - 1);
            }
            funcText.push(s);
            funcText.push('");');
        }
        var lines = text.substring(nlPrefix, nlSuffix + 1).split("\n");
        for (var i = 0; i < lines.length; i++) {
            emitSectionTextLine(lines[i], funcText);
            if (i < lines.length - 1) {
                funcText.push('_OUT.write("\\n");\n');
            }
        }
        if (nlSuffix + 1 < text.length) {
            funcText.push('if (_FLAGS.keepWhitespace == true) _OUT.write("');
            var s = text.substring(nlSuffix + 1).replace("\n", "\\n");
            if (s.charAt(s.length - 1) == "\n") {
                s = s.substring(0, s.length - 1);
            }
            funcText.push(s);
            funcText.push('");');
        }
    };
    var emitSectionTextLine = function(line, funcText) {
        var endMarkPrev = "}";
        var endExprPrev = -1;
        while (endExprPrev + endMarkPrev.length < line.length) {
            var begMark = "${",
                endMark = "}";
            var begExpr = line.indexOf(begMark, endExprPrev + endMarkPrev.length);
            if (begExpr < 0) {
                break;
            }
            if (line.charAt(begExpr + 2) == "%") {
                begMark = "${%";
                endMark = "%}";
            }
            var endExpr = line.indexOf(endMark, begExpr + begMark.length);
            if (endExpr < 0) {
                break;
            }
            emitText(line.substring(endExprPrev + endMarkPrev.length, begExpr), funcText);
            var exprArr = line.substring(begExpr + begMark.length, endExpr).replace(/\|\|/g, "#@@#").split("|");
            for (var k in exprArr) {
                if (exprArr[k].replace) {
                    exprArr[k] = exprArr[k].replace(/#@@#/g, "||");
                }
            }
            funcText.push("_OUT.write(");
            emitExpression(exprArr, exprArr.length - 1, funcText);
            funcText.push(");");
            endExprPrev = endExpr;
            endMarkPrev = endMark;
        }
        emitText(line.substring(endExprPrev + endMarkPrev.length), funcText);
    };
    var emitText = function(text, funcText) {
        if (text == null || text.length <= 0) {
            return;
        }
        text = text.replace(/\\/g, "\\\\");
        text = text.replace(/\n/g, "\\n");
        text = text.replace(/"/g, '\\"');
        funcText.push('_OUT.write("');
        funcText.push(text);
        funcText.push('");');
    };
    var emitExpression = function(exprArr, index, funcText) {
        var expr = exprArr[index];
        if (index <= 0) {
            funcText.push(expr);
            return;
        }
        var parts = expr.split(":");
        funcText.push('_MODIFIERS["');
        funcText.push(parts[0]);
        funcText.push('"](');
        emitExpression(exprArr, index - 1, funcText);
        if (parts.length > 1) {
            funcText.push(",");
            funcText.push(parts[1]);
        }
        funcText.push(")");
    };
    var cleanWhiteSpace = function(result) {
        result = result + "";
        result = result.replace(/\t/g, "    ");
        result = result.replace(/\r\n/g, "\n");
        result = result.replace(/\r/g, "\n");
        result = result.replace(/^(\s*\S*(\s+\S+)*)\s*$/, "$1");
        return result;
    };
    var scrubWhiteSpace = function(result) {
        result = result + "";
        result = result.replace(/^\s+/g, "");
        result = result.replace(/\s+$/g, "");
        result = result.replace(/\s+/g, " ");
        result = result.replace(/^(\s*\S*(\s+\S+)*)\s*$/, "$1");
        return result;
    };
    TrimPath.parseDOMTemplate = function(elementId, optDocument, optEtc) {
        if (optDocument == null) {
            optDocument = document;
        }
        var element = optDocument.getElementById(elementId);
        var content = element.value;
        if (content == null) {
            content = element.innerHTML;
        }
        content = content.replace(/&lt;/g, "<").replace(/&gt;/g, ">");
        return TrimPath.parseTemplate(content, elementId, optEtc);
    };
    TrimPath.processDOMTemplate = function(elementId, context, optFlags, optDocument, optEtc) {
        return TrimPath.parseDOMTemplate(elementId, optDocument, optEtc).process(context, optFlags);
    };
    TrimPath.xmlDoc = null;
    TrimPath.xmlDocFileName = null;
    TrimPath.parseXMLTemplate = function(xmlFileName, nodeName, optEtc) {
        try {
            if (xmlFileName != TrimPath.xmlDocFileName) {
                TrimPath.xmlDoc = createDOMDocument();
                TrimPath.xmlDoc.load(xmlFileName);
                TrimPath.xmlDocFileName = xmlFileName;
            }
            var cdataNode = TrimPath.xmlDoc.selectSingleNode("//" + nodeName).childNodes[0];
            if (cdataNode.nodeType != 4) {
                cdataNode = TrimPath.xmlDoc.selectSingleNode("//" + nodeName).childNodes[1];
            }
            var content = cdataNode.nodeValue;
        } catch (e) {
            throw "the template xml file is wrong";
        }
        return TrimPath.parseTemplate(content, nodeName, optEtc);
    };
    var createDOMDocument = function() {
        var xDoc = null;
        if (typeof ActiveXObject != "undefined") {
            var msXmlAx = null;
            try {
                msXmlAx = new ActiveXObject("Msxml2.DOMDocument.4.0");
            } catch (e) {
                try {
                    msXmlAx = new ActiveXObject("Msxml2.DOMDocument");
                } catch (e) {
                    msXmlAx = new ActiveXObject("Msxml.DOMDocument");
                }
            }
            xDoc = msXmlAx;
        } else {
            if (document.implementation && document.implementation.createDocument) {
                xDoc = document.implementation.createDocument("text/xml", "", null);
            }
        }
        if (xDoc == null || typeof xDoc.load == "undefined") {
            xDoc = null;
        } else {
            xDoc.async = false;
        }
        return xDoc;
    };
})();
xml2json = {
    parser: function(xmlcode, ignoretags, debug) {
        if (!ignoretags) {
            ignoretags = "";
        }
        xmlcode = xmlcode.replace(/\s*\/>/g, "/>");
        xmlcode = xmlcode.replace(/<\?[^>]*>/g, "").replace(/<\![^>]*>/g, "");
        if (!ignoretags.sort) {
            ignoretags = ignoretags.split(",");
        }
        var x = this.no_fast_endings(xmlcode);
        x = this.attris_to_tags(x);
        x = escape(x);
        x = x.split("%3C").join("<").split("%3E").join(">").split("%3D").join("=").split("%22").join('"');
        for (var i = 0; i < ignoretags.length; i++) {
            x = x.replace(new RegExp("<" + ignoretags[i] + ">", "g"), "*$**" + ignoretags[i] + "**$*");
            x = x.replace(new RegExp("</" + ignoretags[i] + ">", "g"), "*$***" + ignoretags[i] + "**$*");
        }
        x = "<JSONTAGWRAPPER>" + x + "</JSONTAGWRAPPER>";
        this.xmlobject = {};
        var y = this.xml_to_object(x).jsontagwrapper;
        if (debug) {
            y = this.show_json_structure(y, debug);
        }
        return y;
    },
    xml_to_object: function(xmlcode) {
        var x = xmlcode.replace(/<\//g, "ï¿½");
        x = x.split("<");
        var y = [];
        var level = 0;
        var opentags = [];
        for (var i = 1; i < x.length; i++) {
            var tagname = x[i].split(">")[0];
            opentags.push(tagname);
            level++;
            y.push(level + "<" + x[i].split("ï¿½")[0]);
            while (x[i].indexOf("ï¿½" + opentags[opentags.length - 1] + ">") >= 0) {
                level--;
                opentags.pop();
            }
        }
        var oldniva = -1;
        var objname = "this.xmlobject";
        for (var i = 0; i < y.length; i++) {
            var preeval = "";
            var niva = y[i].split("<")[0];
            var tagnamn = y[i].split("<")[1].split(">")[0];
            tagnamn = tagnamn.toLowerCase();
            var rest = y[i].split(">")[1];
            if (niva <= oldniva) {
                var tabort = oldniva - niva + 1;
                for (var j = 0; j < tabort; j++) {
                    objname = objname.substring(0, objname.lastIndexOf("."));
                }
            }
            objname += "." + tagnamn;
            var pobject = objname.substring(0, objname.lastIndexOf("."));
            if (eval("typeof " + pobject) != "object") {
                preeval += pobject + "={value:" + pobject + "};\n";
            }
            var objlast = objname.substring(objname.lastIndexOf(".") + 1);
            var already = false;
            for (k in eval(pobject)) {
                if (k == objlast) {
                    already = true;
                }
            }
            var onlywhites = true;
            for (var s = 0; s < rest.length; s += 3) {
                if (rest.charAt(s) != "%") {
                    onlywhites = false;
                }
            }
            if (rest != "" && !onlywhites) {
                if (rest / 1 != rest) {
                    rest = "'" + rest.replace(/\'/g, "\\'") + "'";
                    rest = rest.replace(/\*\$\*\*\*/g, "</");
                    rest = rest.replace(/\*\$\*\*/g, "<");
                    rest = rest.replace(/\*\*\$\*/g, ">");
                }
            } else {
                rest = "{}";
            }
            if (rest.charAt(0) == "'") {
                rest = "unescape(" + rest + ")";
            }
            if (already && !eval(objname + ".sort")) {
                preeval += objname + "=[" + objname + "];\n";
            }
            var before = "=";
            after = "";
            if (already) {
                before = ".push(";
                after = ")";
            }
            var toeval = preeval + objname + before + rest + after;
            eval(toeval);
            if (eval(objname + ".sort")) {
                objname += "[" + eval(objname + ".length-1") + "]";
            }
            oldniva = niva;
        }
        return this.xmlobject;
    },
    show_json_structure: function(obj, debug, l) {
        var x = "";
        if (obj.sort) {
            x += "[\n";
        } else {
            x += "{\n";
        }
        for (var i in obj) {
            if (!obj.sort) {
                x += i + ":";
            }
            if (typeof obj[i] == "object") {
                x += this.show_json_structure(obj[i], false, 1);
            } else {
                if (typeof obj[i] == "function") {
                    var v = obj[i] + "";
                    x += v;
                } else {
                    if (typeof obj[i] != "string") {
                        x += obj[i] + ",\n";
                    } else {
                        x += "'" + obj[i].replace(/\'/g, "\\'").replace(/\n/g, "\\n").replace(/\t/g, "\\t").replace(/\r/g, "\\r") + "',\n";
                    }
                }
            }
        }
        if (obj.sort) {
            x += "],\n";
        } else {
            x += "},\n";
        }
        if (!l) {
            x = x.substring(0, x.lastIndexOf(","));
            x = x.replace(new RegExp(",\n}", "g"), "\n}");
            x = x.replace(new RegExp(",\n]", "g"), "\n]");
            var y = x.split("\n");
            x = "";
            var lvl = 0;
            for (var i = 0; i < y.length; i++) {
                if (y[i].indexOf("}") >= 0 || y[i].indexOf("]") >= 0) {
                    lvl--;
                }
                tabs = "";
                for (var j = 0; j < lvl; j++) {
                    tabs += "\t";
                }
                x += tabs + y[i] + "\n";
                if (y[i].indexOf("{") >= 0 || y[i].indexOf("[") >= 0) {
                    lvl++;
                }
            }
            if (debug == "html") {
                x = x.replace(/</g, "&lt;").replace(/>/g, "&gt;");
                x = x.replace(/\n/g, "<BR>").replace(/\t/g, "&nbsp;&nbsp;&nbsp;&nbsp;");
            }
            if (debug == "compact") {
                x = x.replace(/\n/g, "").replace(/\t/g, "");
            }
        }
        return x;
    },
    no_fast_endings: function(x) {
        x = x.split("/>");
        for (var i = 1; i < x.length; i++) {
            var t = x[i - 1].substring(x[i - 1].lastIndexOf("<") + 1).split(" ")[0];
            x[i] = "></" + t + ">" + x[i];
        }
        x = x.join("");
        return x;
    },
    attris_to_tags: function(x) {
        var d = " =\"'".split("");
        x = x.split(">");
        for (var i = 0; i < x.length; i++) {
            var temp = x[i].split("<");
            for (var r = 0; r < 4; r++) {
                temp[0] = temp[0].replace(new RegExp(d[r], "g"), "_jsonconvtemp" + r + "_");
            }
            if (temp[1]) {
                temp[1] = temp[1].replace(/'/g, '"');
                temp[1] = temp[1].split('"');
                for (var j = 1; j < temp[1].length; j += 2) {
                    for (var r = 0; r < 4; r++) {
                        temp[1][j] = temp[1][j].replace(new RegExp(d[r], "g"), "_jsonconvtemp" + r + "_");
                    }
                }
                temp[1] = temp[1].join('"');
            }
            x[i] = temp.join("<");
        }
        x = x.join(">");
        x = x.replace(/ ([^=]*)=([^ |>]*)/g, "><$1>$2</$1");
        x = x.replace(/>"/g, ">").replace(/"</g, "<");
        for (var r = 0; r < 4; r++) {
            x = x.replace(new RegExp("_jsonconvtemp" + r + "_", "g"), d[r]);
        }
        return x;
    }
};
if (!Array.prototype.push) {
    Array.prototype.push = function(x) {
        this[this.length] = x;
        return true;
    };
}
if (!Array.prototype.pop) {
    Array.prototype.pop = function() {
        var response = this[this.length - 1];
        this.length--;
        return response;
    };
}

