﻿var arrayOfResult = new Array();
var listCurrent = new Array();
var selectedCampsiteBySearchForm = 0;
var currentPage = 1;
var defaultDate = "dd/mm/jjjj";

function unCheckCb(idCb) {
    if ($(idCb).checked) { $(idCb).checked = false; }
}

//Flash map
function flashMovie(movieName) {
    if (window.document[movieName]) {
        return window.document[movieName];
    }
    else {
        return document.getElementById(movieName);
    }
}

function fromAS(value) {
    searchForm.SetPopup(false);
    $('tb_recherche').value = "";
    $('tb_lat').value = "";
    $('tb_lon').value = "";
    if (value == 'eu_europa') {
        $('territories').value = '';
    }
    else {
        $('territories').value = value;
        if ($('arrivalDate').value == defaultDate || $('departureDate').value == defaultDate) {
            $('arrivalDate').value = "";
            $('departureDate').value = "";
        }
        checkForm(document.forms[0]);
        $('flash-map').innerHTML = $('loading-message').innerHTML;
    }

}

function initHomeCarousel(codeCampagne) {
    var crsl = new Carousel($$('#middle-offers-' + codeCampagne).first(), $$('#middle-offers-' + codeCampagne + ' .offer'), $$('ul#offers-tabs-' + codeCampagne + ' a.carousel-jumper'),
      { auto: true, frequency: 8, duration: 1, circular: true, wheel: false, afterMove: function () {
          crsl.controls.each(function (elm) {
              elm.removeClassName(crsl.options.selectedClassName);
          });
          crsl.controls.each(function (elm) {
              if (elm.rel == crsl.current.id) {
                  elm.addClassName(crsl.options.selectedClassName);
              }
          });
      }
      })

    //onglets
    $$('ul.tabs li a').each(function (elm) {
        Event.observe(elm, 'click', function () {
            $$('div.special-offers-carousel').each(function (tab) {
                tab.hide();
            });
            $$('ul.tabs li').each(function (tabLi) {
                tabLi.className = '';
            });
            elm.up().addClassName('active');
            var tabToDisplay = this.href.split('#');
            $(tabToDisplay[1].sub('#', '')).show();
        });
    });

}

function populateElement(selector, defvalue) {
    if (trim($(selector).value) == "") {
        $(selector).value = defvalue;
        $(selector).addClassName('input_inactive');
    }
    Event.observe(selector, 'focus', function (elm) {
        if ($(selector).value == defvalue) {
            $(selector).value = "";
        }
        $(selector).className = 'dates input_active';
    });
    Event.observe(selector, 'blur', function (elm) {
        if (trim($(selector).value) == "" || trim($(selector).value) == defvalue) {
            $(selector).value = defvalue;
            $(selector).className = 'dates input_inactive';
        }
    });
}

//Supprime les espaces au debut et a la fin d'une chaine
function trim(myString) {
    return myString.replace(/^\s+/g, '').replace(/\s+$/g, '')
}

function initializeThemeForm() {
    calendarCreator.run()
    $('territories').value = '';
    var url_result = '';
    searchForm = new SearchForm(document.forms[0].action);
    selectSejour = new SelectSejour('', 'arrivalDate', 'departureDate');
    searchForm.SetPopup(false);
    searchForm.tab_panel_checkbox.push(new PanelCheckbox("h_sub_type", "cbSubType", false, false, "sous type"));
    populateElement('arrivalDate', defaultDate);
    populateElement('departureDate', defaultDate);
    checkResultsFilter();
}

function initializePromocodeForm() {
    $('territories').value = '';
    var url_result = '';
    searchForm = new SearchForm(url_result);
    selectSejour = new SelectSejour('', 'arrivalDate', 'departureDate');
    searchForm.SetPopup(false);
    searchForm.tab_panel_checkbox.push(new PanelCheckbox("h_sub_type", "cbSubType", false, false, "sous type"));

    populateElement('arrivalDate', defaultDate);
    populateElement('departureDate', defaultDate);
}

function initializeSearchForm() {
    searchForm = new SearchForm(url_result);
    selectSejour = new SelectSejour('', 'arrivalDate', 'departureDate');
    searchForm.SetMode1(id_hf_territoire, id_tb_lieux, 'tb_lat', 'tb_lon', 'VarRetour', 'div_detail_all', url_detail_lieux);
    searchForm.SetSuperOS('idos');
    // searchForm.ActiverRechercheCamping('tb_nom_camping', 'DivRetourCamp', 'id_etablissements', url_detail_camp, 'tb_lat', 'tb_lon', 'VarRetour');
    searchForm.SetPopup(false);
    searchForm.tab_panel_checkbox.push(new PanelCheckbox("h_sub_type", "cbSubType", false, false, "sous type"));

    Event.observe('tb_recherche', 'focus', function (e) {
        if (this.value == 'Regio, Streek, Plaats,...') { this.value = ''; this.className = 'active'; };
    });

    populateElement('arrivalDate', defaultDate);
    populateElement('departureDate', defaultDate);

    checkResultsFilter();
}

function checkResultsFilter() {
    /*Formulaire de recherche*/
    if ($('more-options')) {

        $$('a.toggle').each(function (elm) {

            Event.observe(elm, 'click', function () {

                var monId = elm.id.substring(7, elm.id.length);
                $(monId).toggle();
                changeMoreOptionState(elm.id);
                //new Effect.toggle(monId, 'blind', { afterFinish: changeMoreOptionState(elm.id) });
            });
        });


        $$('a.underToogle').each(function (elm) {

            Event.observe(elm, 'click', function () {

                var txt = elm.innerHTML.substring(3, elm.innerHTML.length);
                var monElm = elm.up(1).down(2);

                if (elm.innerHTML.substring(0, 3) == '[-]') {
                    elm.innerHTML = '[+]' + txt;
                    monElm.hide();

                } else {
                    elm.innerHTML = '[-]' + txt;
                    monElm.show();
                }
            });

        });

    }
    $$('input.dates').each(function (elm) {
        Event.observe(elm, 'blur', function (e) {
            var date1 = $('arrivalDate').value.replace(/-/g, '/');
            var date2 = $('departureDate').value.replace(/-/g, '/');
            $('arrivalDate').value = date1;
            $('departureDate').value = date2;
        });
    });

    function changeMoreOptionState(eId) {

        if ($(eId).className == 'closed toggle') {
            $(eId).className = 'toggled toggle';
        } else {
            $(eId).className = 'closed toggle';
        }
    }
}

function initializeProductSearchForm() {

    searchForm = new SearchForm(url_result);
    selectSejour = new SelectSejour('', 'arrivalDate', 'departureDate');
    searchForm.SetPopup(false);
    //initSearchCookie()
    //initProductSearchCookie();

    var lastSeenPageCookie = getLastSeenPageCookie("lastSeenPage");
    if (lastSeenPageCookie != false) {
        lastSeenPageCookie = parseInt(lastSeenPageCookie);
        formatNumeration(lastSeenPageCookie);
    } else {
        formatNumeration(1);
    }

    populateElement('arrivalDate', defaultDate);
    populateElement('departureDate', defaultDate);
}

function displaySelectedDatesPlanning() {
    var arrivalDate = $('arrivalDate').value;
    var departureDate = $('departureDate').value;
    var planningToDisplay;

    if (arrivalDate != '') {
        if ($('product-planning-left') != null) {
            var mesPlannings = $('product-planning-left').getElementsByTagName('table');
            for (i = 0; i < mesPlannings.length; i++) {
                mesPlannings[i].style.display = "none";
            }
            var planningClass = arrivalDate.split("/")[1].split("0")[1] + "-" + arrivalDate.split("/")[2];
            for (i = 0; i < mesPlannings.length; i++) {
                if (mesPlannings[i].className == "month " + planningClass) {
                    planningToDisplay = i;
                    break;
                } else {
                    planningToDisplay = 0;
                }
            }
            mesPlannings[planningToDisplay].style.display = "block";
        }
    }
    if (departureDate != '') {
        if ($('product-planning-right') != null) {
            var mesPlanningsRight = $('product-planning-right').getElementsByTagName('table');

            for (i = 0; i < mesPlanningsRight.length; i++) {
                mesPlanningsRight[i].style.display = "none";
            }

            var planningClassRight = departureDate.split("/")[1].split("0")[1] + "-" + departureDate.split("/")[2];

            for (j = 0; j < mesPlanningsRight.length; j++) {
                if (mesPlanningsRight[j].className == "month " + planningClassRight) {
                    planningToDisplayRight = j;
                    break;
                } else {
                    planningToDisplayRight = 0;
                }
            }
            mesPlanningsRight[planningToDisplayRight].style.display = "block";
        }
    }
}

function changeSorting() {
    resultsPage = Array();
    displayPage(currentPage);
}
function GetCurrentSorting() {
    if ($('select-sorting-availability-results')) {
        return $('select-sorting-availability-results').getValue();
    }
}
function displayPage(pageValue) {
    var pageValueInt = parseFloat(pageValue);
    currentPage = pageValueInt;
    //Affichage de la page
    var content = resultsPage[pageValue];
    displayPageGMap();
    if (!content) {
        if (nbCamp != 0) {
            $('ajax-results-loading').show();
            //RefreshCookieUrlSearch();
            PageMethods.GetResponsePage(
				keyResult,
				(pageValueInt - 1) * 10,
				pageValueInt * 10,
				GetCurrentSorting(),
				function (result) {
				    resultsPage[pageValue] = result;
				    $('ajax-results-loading').hide();
				    $('search-results-pages').innerHTML = resultsPage[pageValue];
				}
				);
        }
    }
    else {
        $('search-results-pages').innerHTML = content;
    }

    //class btn
    $$('ul.pagination li.numbers ul li a').each(function (elmLiLink) {
        if (elmLiLink.up('li').className == 'page_' + pageValue) {
            elmLiLink.className = 'active';
        }
        else {
            elmLiLink.className = 'link';
        }
    });

    //prev & next
    if (pageValue == '1') {
        $$('ul.pagination li.prev').each(function (elmPrev) {
            //elmPrev.down('a').className = 'active';
            elmPrev.update('<span>< vorige</span>');
            elmPrev.className = 'prev page_1';
        });
    }
    else {
        $$('ul.pagination li.prev').each(function (elmPrev) {
            elmPrev.update("<a class='link' target='_self' href='#results' onclick=\"navigation('prev')\">< vorige</a>");
            //elmPrev.down('a').className = 'link';
            elmPrev.className = 'prev page_' + (pageValueInt - 1);
        });
    }
    if (pageValue == lastPage) {
        $$('ul.pagination li.next').each(function (elmNext) {
            elmNext.update('<span>volgende ></span>');
            //elmNext.down('a').className = 'active';
            elmNext.className = 'next page_' + pageValue;
        });
    }
    else {
        $$('ul.pagination li.next').each(function (elmNext) {
            elmNext.update("<a class='link' target='_self' href='#results' onclick=\"navigation('next')\">volgende ></a>");
            //elmNext.down('a').className = 'link';
            elmNext.className = 'next page_' + (pageValueInt + 1);
        });
    }
    displaySelectedDatesPlanning();
}

function displayPageGMap() {
    if (typeof (mygmap) == "undefined")
        return;
    var indexMin = (currentPage - 1) * 10;
    var indexMax = currentPage * 10;
    mygmap.geoXml.DisplayData(absolutePath + "proxy_kml.aspx?c=" + argumentForKml + "&indexMin=" + indexMin + "&indexMax=" + indexMax);
}


function navigation(direction) {
    if (direction == 'next') {
        formatNumeration(currentPage + 1);
    }
    else {
        formatNumeration(currentPage - 1);
    }
}
//Pagination


function formatNumeration(callPage) {
    currentPage = callPage;
    RefreshPagination(currentPage);
    RefreshCookieUrlSearch();
    setLastSeenPageCookie(currentPage);
    displayPage(currentPage);
    //displayCorrectMonthPLanning(arrivalDate, departureDate);
}

function RefreshPagination(currentPage) {
    var indice = 0;
    var futur_inner = '';
    if (currentPage > 3) {
        futur_inner += '<li class="page_1"><a href="#results" class="link" onclick="formatNumeration(1);">1</a></li>';
        futur_inner += '<li>...</li>';
    }
    for (indice = 1; indice <= lastPage; indice++) {
        if ((currentPage - 2) <= indice && indice <= (currentPage + 2)) {
            if (currentPage == indice) {
                futur_inner += "<li class=\"page_" + indice + "\"><a href=\"\#results\" class=\"active\" onclick=\"formatNumeration(" + indice + ");\">" + currentPage + "</a></li>";
            }
            else {
                futur_inner += "<li class=\"page_" + indice + "\"><a href=\"\#results\" class=\"link\" onclick=\"formatNumeration(" + indice + ");\">" + indice + "</a></li>";
            }
        }
    }
    if ((lastPage - currentPage) > 2) {
        futur_inner += "<li>...</li>";
        futur_inner += "<li class=\"page_" + lastPage + "\"><a href=\"\#results\" class=\"link\" onclick=\"formatNumeration(" + lastPage + ");\">" + lastPage + "</a></li>";
    }
    $$('ul.numbers-list').each(function (elmul) {
        elmul.innerHTML = futur_inner;
    });


    if (currentPage == '1') {
        $$('ul.pagination li.prev').each(function (elmPrev) {
            //elmPrev.down('a').className = 'active';
            elmPrev.update('<span>< vorige</span>');

        });
    }
    else {
        $$('ul.pagination li.prev').each(function (elmPrev) {
            elmPrev.update("<a class='link' target='_self' href='#results' onclick=\"navigation('prev')\">< vorige</a>");
            //elmPrev.down('a').className = 'link';

        });
    }
    if (currentPage == lastPage) {
        $$('ul.pagination li.next').each(function (elmNext) {
            //elmNext.down('a').className = 'active';
            elmNext.update('<span>volgende ></span>');
        });
    }
    else {
        $$('ul.pagination li.next').each(function (elmNext) {
            elmNext.update("<a class='link' target='_self' href='#results' onclick=\"navigation('next')\">volgende ></a>");
            //elmNext.down('a').className = 'link';
        });
    }
}
function RefreshCookieUrlSearch() {
    if (typeof (lastCurrentPage) == "undefined")
        return;
    var withoutAnchorUrl = window.location.href.split('#results')[0];

    if (withoutAnchorUrl.indexOf(".html?") != -1 || withoutAnchorUrl.indexOf(".aspx?") != -1) {
        if (withoutAnchorUrl.indexOf("&page") != -1) {
            var formatedUrl = withoutAnchorUrl.split('&page=')[0];
            urlSearch = { url: formatedUrl + "&page=" + currentPage };
        }
        if (withoutAnchorUrl.indexOf("?page") != -1) {
            var formatedUrl = withoutAnchorUrl.split('?page=')[0];
            urlSearch = { url: formatedUrl + "?page=" + currentPage };
        }
        if (withoutAnchorUrl.indexOf("?page") == -1 && withoutAnchorUrl.indexOf("&page") == -1) {
            urlSearch = { url: withoutAnchorUrl + "&page=" + currentPage };
        }
    }
    else {
        if (withoutAnchorUrl.indexOf("?page") != -1) {
            var formatedUrl = withoutAnchorUrl.split('?page=')[0];
            urlSearch = { url: formatedUrl + "?page=" + currentPage };
        }
        else {
            urlSearch = { url: withoutAnchorUrl + "?page=" + currentPage };
        }
    }
    if (typeof (keyResult) != "undefined") {
        urlSearch.searchKey = keyResult;
    }
    urlSearch.searchSorting = GetCurrentSorting();

    var jar = new CookieJar({
        expires: 86400, // seconds
        path: '/'
    });
    jar.put('urlSearch', urlSearch);
}

function setLastSeenPageCookie(page) {
    var myCookieJar = new CookieJar();
    myCookieJar.put("lastSeenPage", page);
}

function getLastSeenPageCookie(cookieName) {
    var myCookieJar = new CookieJar();
    var cookiePage = myCookieJar.get(cookieName);
    if (cookiePage != "" && cookiePage != null) {
        return cookiePage;
    }
    else {
        return false;
    }
}

function checkFormWithDates(oForm) {
    if ($('arrivalDate').value == '' && $('departureDate').value == '') {
        alert("U dient een datum in te vullen.");
    }
    else { checkDestination(oForm) };
}

function checkTbRecherche(oForm) {
    if ($('tb_recherche').value == '' || $('tb_recherche').value == 'Regio, Streek, Plaats,...') {
        alert('Gelieve een bestemming te kiezen.');
    }
    else { checkForm(oForm) }
}

function checkDestination(oForm) {
    if ($('tb_recherche')) {
        if (($('tb_recherche').value == '' || $('tb_recherche').value == 'Regio, Streek, Plaats,...') && $('territories').value == '' && $('tb_lat').value == '') { alert('Gelieve een bestemming te kiezen.'); }
        else { checkForm(oForm) }
    }
    else { checkForm(oForm) }
}

function checkForm(oForm) {


    $$('input.cb-theme-territory').each(function (elm) {
        if (elm.checked) { $('territories').value += elm.value + '|' };
    });


    //Services
    addPanelCheckBox("cbService", "h_categories", false, false, "services");

    var l = searchForm.tab_panel_checkbox.length;

    for (var i = 0; i < l; i++) {
        if (!searchForm.tab_panel_checkbox[i].EcireDansHiddenField()) { return false; }
    }

    if ($$('input.cb-theme-territory').length > 0 && $('arrivalDate').value == defaultDate && $('departureDate').value == defaultDate) {
        $('departureDate').value = "";
        $('arrivalDate').value = "";
    }

    else {
        
        if ($('arrivalDate').value != '' || $('departureDate').value != '') {
            var date1 = $('arrivalDate').value.replace(/-/g, '/');
            var date2 = $('departureDate').value.replace(/-/g, '/');

            $('arrivalDate').value = date1;
            $('departureDate').value = date2;

            codeError = selectSejour.VerifDate();
            if (codeError > 0) {
                var msg = "";

                switch (codeError) {
                    case 1:
                        msg = "Uw datum is onjuist";
                        break;
                    case 2:
                        msg = "De datum van aankomst is onjuist";
                        break;
                    case 3:
                        msg = "De datum van vertrek is onjuist";
                        break;
                    case 4:
                        msg = "De einddatum van de periode moet na de datum van de beginperiode zijn.";
                        break;
                    case 5:
                        msg = "De begindatum moet later of gelijk zijn aan de datum van vandaag";
                        break;
                    case 6:
                        msg = "Uw datum is onjuist";
                        break;
                    case 7:
                        msg = "De datum van vertrek is onjuist";
                        break;
                }
                if (msg != "")
                    alert(msg);
                return false;
            }
        }
    }

    var deltaInput = $('deltaMax');
    if ($('deltaCb').checked)
    { deltaInput.value = 0; }
    else { deltaInput.value = 10 }
    if ($('idM')) { $('idM').value = $$('input:checked[type="radio"][name="engineNum"]').pluck('value'); }
    document.body.style.cursor = 'wait';
    sendRequest(oForm);
}
// reset search form
function resetSearchForm() {
    if ($('tb_recherche')) $('tb_recherche').value = '';
    $('arrivalDate').value = '';
    $('departureDate').value = '';
    $('deltaCb').checked = false;
    $('personNumber').options[0].selected = 'selected';
    $('productType2').checked = true;
    checkForm(this);
}

function resetSearchFormVerfijn() {
    $('aantal_plaatsen').checked = true;
    $('ANWB_cijfer').checked = true;
    $('services_52').checked = false;
    $('Campingkenmerken').hide();
    $('services_59').checked = false;
    $('services_18').checked = false;
    $('eten_en_driken').hide();
    $('honden_toegelaten').checked = true;
    $('honden').hide();
    $('aan_of_bij_water').checked = true;
    $$('#in_de_natuur .cbService').each(function (elt) {
        elt.checked = false;
    });
    $$('#ligging .cbService').each(function (elt) {
        elt.checked = false;
    });
    $$('#uitzicht .cbService').each(function (elt) {
        elt.checked = false;
    });
    $('services_44').checked = false;
    $$('#afstand_van .cbService').each(function (elt) {
        elt.checked = false;
    });
    $('ligging').hide();
    $('animatie').checked = true;
    $('discotheek').checked = true;
    $('speeltuin').checked = true;
    $('zwembad').checked = true;
    $('recreatie').hide();

    $$('a.toggle').each(function (item) {
        if (item.id != 'toggle_honden') {
            item.removeClassName('toggled');
            item.addClassName('closed');
        }
    });
    checkForm(this);
}

function resetProductSearchForm() {
    $('productTypeL').checked = true;
    $('arrivalDate').value = "";
    if ($('arrivalDate').hasClassName('input_active')) {
        $('arrivalDate').removeClassName('input_active');
    }
    $('departureDate').value = "";
    if ($('departureDate').hasClassName('input_active')) {
        $('departureDate').removeClassName('input_active');
    }
    $('deltaCb').checked = false;
    $('personNumber').value = "";

    resetPlannings();

    var myJar = new CookieJar();
    if (myJar.get("lastSeenPage") != null) {
        myJar.remove("lastSeenPage");
    }
    checkForm();
}



//Résultats de recherche
function initializeSearchResults() {
    //setSearchCookie();
    RefreshCookieUrlSearch();
    var flashvars = {};
    var params = {};
    params.allowscriptaccess = "always";
    params.allownetworking = "all";
    var attributes = {};
    attributes.id = "eu_europa";
    swfobject.embedSWF(absolutePath + "eu_europa.swf", "swf", "244", "300", "9.0.0", false, flashvars, params, attributes);
    //Pagination des resultats - nombres
    $$('div.results ul.tabs li a').each(function (elm) {
        Event.observe(elm, 'click', function () {
            $$('div.results div.tabs-panel').each(function (tab) {
                tab.hide();
            });
            $$('div.results ul.tabs li').each(function (tabLi) {
                tabLi.className = '';
            });
            elm.up().addClassName('active');
            var tabToDisplay = this.href.split('#');
            $(tabToDisplay[1].sub('#', '')).show();
            if (tabToDisplay[1] == "results-map")
                initMyGmap();
        });
    });



    //Pagination des resultats - nombres
    /*$$('ul.pagination li.numbers ul li').each(function (elmLiClicked) {
    Event.observe(elmLiClicked, 'click', function (event) {
    currentPage = elmLiClicked.className.substring(5, 7);
    displayPage(elmLiClicked.className.substring(5, 7));
    }
    )
    });*/

    //Pagination des resultats - prev next
    /*$$('ul.pagination li.next').each(function (elmLiNext) {
    Event.observe(elmLiNext, 'click', function (event) {
    formatNumeration(currentPage + 1);
    });
    });*/

    //Pagination des resultats - prev next
    /*$$('ul.pagination li.prev').each(function (elmLiPrev) {
    Event.observe(elmLiPrev, 'click', function (event) {
    formatNumeration(currentPage - 1);
    });

    });*/


    $$('div#results-map ul.pagination li a').each(function (elm) {
        Event.observe(elm, 'click', function (e) {
            initMyGmap();
        });
    });

    //initialisation de la pagination
    if (typeof (lastCurrentPage) != "undefined") {
        RefreshPagination(lastCurrentPage)
    }
    else {
        RefreshPagination(1);
    }
}

//Establishment pictures
function initializeEstablishmentPictures() {
    //photos
    $$('ul#carousel-content li.slide img').each(function (elm) {
        Event.observe(elm, 'click', function (e) {
            $('main-picture').src = elm.readAttribute('src');
            $('main-picture').alt = elm.readAttribute('alt');
        });
    });
}

function displayProductPrices(productId, pricingID, tableNb) {
    $$('div.div-product-pricing-' + productId + '-' + pricingID).each(function (item) {
        item.hide();
    });
    $('div-pricing-details-product-' + productId + '-' + pricingID + '-' + tableNb).show();
    $$('select.select-' + productId + '-' + pricingID).each(function (element) {
        $A(element.options).each(function (option, index) {
            if (tableNb == option.value)
                element.selectedIndex = index;
        });
    });
}

function displayProductPricing(pricingID, productId) {
    $$('.div-pricing-details-product').each(function (element) {
        element.hide()
    });
    $('div-pricing-details-product-' + productId + '-' + pricingID + '-1').show();
}

function planningSearch(date, obj, nbMois) {
    if (typeof (goCheckForm) != "undefined" && goCheckForm == false) {
        resetPlannings();
    }
    var className = parseInt(date.split("/")[1], 10) + "-" + date.split("/")[2];
    var objetSelect = $(obj).up(4).down('select');
    displayMonths(className, objetSelect);
    planningSearchWithSubmitCheck(date, obj, nbMois, true);


}

function planningSearchNoSubmit(date, obj, nbMois) {
    planningSearchWithSubmitCheck(date, obj, nbMois, false);
}

function planningSearchWithSubmitCheck(date, obj, nbMois, goSubmit) {
    var daddy = getParentElement(obj, 5);
    var idInputDateElement;
    var splitedString = obj.id.split("_");


    //si cliqué sur tableau de gauche représentant la date d'arrivée
    if (daddy.id === "product-planning-left") {
        idParDate = "input-left";
        //je reset les cellules du tableau de droite si aucune date départ n'est choisie
        if ($('departureDate').value == "" || $('departureDate').value == defaultDate) {
            var mesCellulesGauche = $('product-planning-right').getElementsByTagName('a');
            for (i = 0; i < mesCellulesGauche.length; i++) {
                mesCellulesGauche[i].className = "";
            }
        } 

        //je vire la class highlighted si une date d'arrivée avait deja été choisie
        if ($('arrivalDate').value != "") {
            var mesCellulesGauche = $('product-planning-left').getElementsByTagName('a');
            for (i = 0; i < mesCellulesGauche.length; i++) {
                if (mesCellulesGauche[i].hasClassName("highlighted")) {
                    mesCellulesGauche[i].removeClassName("highlighted");
                }
            }
        }

        //attriubution de la bonne classe aux différentes celulles
        for (i = 1; i <= splitedString[1]; i++) { //chaque mois
            var max;
            //je défini le dernier jour du mois qui nécéssite une vérification
            if (i == splitedString[1]) {
                max = splitedString[2];
            }
            else {
                max = 31;
            }
            //pour chaque jour jusqu'a la date d'arrivée
            for (j = 1; j <= max; j++) {
                var divToDisableRight = $("day_" + i + "_" + j + "_right");
                if (divToDisableRight != null) {
                    if (j == max) { //select jour d'arrivéee
                        divToDisableRight.className = "highlighted";
                    }
                    else { //disable les jours avant date d'arrivée
                        divToDisableRight.className = "disabled";
                    }
                }
            }
        }
        $('arrivalDate').value = date;
        $('arrivalDate').removeClassName = "input_inactive";
        $('arrivalDate').addClassName = "input_active";
        changeDepartureMonthIfNeeded(date);
    }

    //si tableau de droite cliqué
    else if (daddy.id === "product-planning-right") {
        idParDate = "input-right";
        
        //je reset les cellules du tableau de gauche si aucune date arrivee n'est choisie
        if ($('arrivalDate').value == "" || $('arrivalDate').value == defaultDate) {
            var mesCellulesGauche = $('product-planning-left').getElementsByTagName('a');
            for (i = 0; i < mesCellulesGauche.length; i++) {
                mesCellulesGauche[i].className = "";
            }
        }


        //je vire la class highlighted si une date de départ avait deja été choisie
        if ($('departureDate').value != "") {
            var mesCellulesDroite = $('product-planning-right').getElementsByTagName('a');
            for (i = 0; i < mesCellulesDroite.length; i++) {
                if (mesCellulesDroite[i].hasClassName("highlighted")) {
                    mesCellulesDroite[i].removeClassName("highlighted");
                }
            }
        } else {
            
        }

        //pour chque mois en partant du dernier
        for (i = nbMois; i >= splitedString[1]; i--) {
            var min;
            if (i == splitedString[1]) {
                min = splitedString[2];
            } else {
                min = 1;
            }
            var j;
            //pour chaque jour en partant du dernier
            for (j = 31; j >= min; j--) {
                var divToDisable = $("day_" + i + "_" + j + "_left");
                if (divToDisable != null) {
                    divToDisable.className = "disabled";
                    if (j == min) {
                        divToDisable.className = "highlighted";
                    }
                }
            }
        }
        $('departureDate').value = date;
        $('departureDate').removeclassName = "input_inactive";
        $('departureDate').addclassName = "input_active";
    }

    obj.className = "highlighted";
    $(idParDate).innerHTML = date;

    if ($('input-left').innerHTML != "" && $('input-right').innerHTML != "") {
        if (goSubmit) {
            checkForm(this);
        }
    }
}

function resetPlannings() {
    if (typeof ($("product-planning")) != "undefined") {
        var mesElements = $$("table.month td");
        for (i = 0; i < mesElements.length; i++) {
            if (mesElements[i].down() != null && mesElements[i].down().className != "") {
                mesElements[i].down().className = "";
            }
            $("input-left").innerHTML = "";
            $("input-right").innerHTML = "";
        }
        if ($('product-planning') != null) {
            var mesSelect = $('product-planning').getElementsByTagName('select');
            var classNameFirstIndex = mesSelect[0].options[0].value;
            for (i = 0; i < mesSelect.length; i++) {
                mesSelect[i].selectedIndex = 0;
            }
            var mesTableaux = $('product-planning').getElementsByTagName('table');
            for (i = 0; i < mesTableaux.length; i++) {
                mesTableaux[i].style.display = "none";
                $$('table.' + classNameFirstIndex).each(function (item) { item.show(); });
            }
        }
    }
    goCheckForm = true;
}

function changeDepartureMonthIfNeeded(date) {
    var selectRight = $("product-planning-right").down(2);

    var clickedDay = parseInt(date.split("/")[0], 10);
    var clickedMonth = parseInt(date.split("/")[1], 10);
    var clickedYear = parseInt(date.split("/")[2], 10);

    var nbDays = getNbDaysInMonth(clickedMonth, clickedYear);

    var stringDate = clickedMonth + "-" + clickedYear;

    //si le jour cliqué est à moins d'une semaine de la fin du mois
    if (clickedDay + 7 > nbDays) {
        var month = clickedMonth + 1;
        stringDate = month + "-" + clickedYear;
        selectRight.value = stringDate;
        displayMonths(stringDate, selectRight);
    }
    else if (selectRight.value != stringDate) {
        selectRight.value = stringDate;
        displayMonths(stringDate, selectRight);
    }
}

function getNbDaysInMonth(month, year) {
    var nbJour = 32 - new Date(year, month, 32).getDate();
    return nbJour;
}

function displayMonths(className, obj) {
    var daddy = getParentElement(obj, 1).id;
    if (daddy === "product-planning-left") {
        displayMonthsWithChangeBothMonthsCheck(className, obj, true);
    } else { displayMonthsWithChangeBothMonthsCheck(className, obj, false); }
}


function displayMonthsWithChangeBothMonthsCheck(className, obj, bothMonthsChangeCheck) {
    var daddy = getParentElement(obj, 1);
    var elmtToDisplay = $(daddy).down('table.' + className);

    if (bothMonthsChangeCheck) {
        $$('table.month').each(function (item) {
            $(item).hide();
        });
        var elmtToDisplayRight = $('product-planning-right').down('table.' + className);
        var mesOptions = $('product-planning-right').getElementsByTagName('select')[0].options;
        for (i = 0; i < mesOptions.length; i++) {
            if (mesOptions[i].value == className) {
                $('product-planning-right').getElementsByTagName('select')[0].selectedIndex = i;
                break;
            }
        }
        elmtToDisplayRight.show();
    }
    else {
        //je récupère tout les tableaux des mois
        $$('table.month').each(function (item) {
            var daddyId = getParentElement(item, 1).id;
            //je cache toutes les tables contenues dans l'élément parent de l'élément cliqué
            if (daddyId === $(daddy).id) {
                $(item).hide();
            }
        });
    }
    //j'affiche le mois voulu
    elmtToDisplay.show();
}


function displayNextMonth() {
    var monthNotToDisplay = 0;
    for (i = 0; i <= $$('table.month').length; i++) {
        if ($$('table.month')[i].visible() == true) {
            $$('table.month')[i].hide();
            monthNotToDisplay = i;
            break;
        }
    }
    for (i = 0; i <= $$('table.month').length; i++) {
        if ($$('table.month')[i].visible() == false) {
            if (i != monthNotToDisplay) {
                $$('table.month')[i].show();
                break;
            }
        }
    }
}


//fonction retourne le n eme parent de l'élement
function getParentElement(element, n) {
    var daddy = $(element).up(n);
    return daddy;
}



//Reviews
function initializeEstablishmentReviews() {
    hideLoading();
    //Pagination des resultats - nombres
    $$('ul.reviews-pagination li.numbers ul li a').each(function (elmLiClicked) {
        Event.observe(elmLiClicked, 'click', function (event) {
            pageToDisplay = elmLiClicked.className.substring(5, 7);
            idsToDisplay = $('idStayType').value;
            callReviews(idE, idsToDisplay, pageToDisplay)
        }
        )
    });

    //Pagination des resultats - prev next
    $$('ul.reviews-pagination li.next a').each(function (elmLiNext) {
        Event.observe(elmLiNext, 'click', function (event) {
            pageToDisplay = elmLiNext.className.substring(5, 7);
            idsToDisplay = $('idStayType').value;
            callReviews(idE, idsToDisplay, pageToDisplay)
        });
    });

    //Pagination des resultats - prev next
    $$('ul.reviews-pagination li.prev a').each(function (elmLiPrev) {
        Event.observe(elmLiPrev, 'click', function (event) {
            pageToDisplay = elmLiPrev.className.substring(5, 7);
            idsToDisplay = $('idStayType').value;
            callReviews(idE, idsToDisplay, pageToDisplay)
        });

    });

}

//Cookies Search
function setSearchCookie() {
    jar = new CookieJar({
        expires: 86400, // seconds
        path: '/'
    });

    search = {
        territories: territories,
        arrivalDate: arrivalDate,
        departureDate: departureDate,
        engineNum: engineNum,
        services: services,
        productTypes: productTypes,
        personNumber: personNumber

    };
    jar.put('userSearch', search);
    userSearch = jar.get('userSearch');
}

//Cookies Search
function setProductSearchCookie() {

    productJar = new CookieJar({
        expires: 86400, // seconds
        path: '/'
    });

    productSearch = {
        arrivalDate: arrivalDate,
        departureDate: departureDate,
        personNumber: personNumber
    };
    productJar.put('userProductSearch', productSearch);

    productSearch = productJar.get('userProductSearch');

}

//initialisation des champs apres une recherche générale
function initSearchCookie() {
    jar = new CookieJar();
    userSearch = jar.get('userSearch');
    if (userSearch != null) {
        if ($('arrivalDate').value == '') {
            populateElement('arrivalDate', defaultDate);
            populateElement('departureDate', defaultDate);
            $('arrivalDate').value = userSearch.arrivalDate;
            $('departureDate').value = userSearch.departureDate;
        }
    }
}

//Cookie Already visited
function isAlreadyExist(cookieName) {
    cpm = jar.get(cookieName);
    return cpm != null;
}

function pushCampsite(campsiteId, campsiteName, campsiteArea) {
    if (!isAlreadyExist('anwb-visited-' + campsiteId)) {
        campsite = { id: campsiteId, name: campsiteName, area: campsiteArea, url: campsiteUrl };
        jar.put('anwb-visited-' + campsiteId, campsite);
        displayCampsite();
    }
}

function displayCampsite() {
    jar = new CookieJar({ expires: 3600 * 24 * 6, path: '/' });
    myHtml = "<h4>Recent bekeken campings</h4><ul>";
    var campsiteTab = new Array();
    campsiteTab = jar.getKeys();
    display = false;

    if (campsiteTab != 'undefined' && campsiteTab != null && campsiteTab.length > 0) {
        var tab = new Array();
        for (i = 0; i < campsiteTab.length; i++) { // nbre de 'camping cookie' à afficher au max
            if (campsiteTab[i].indexOf("anwb-visited-") != -1) {
                tab.push(campsiteTab[i]); ;
            }
        }
        if (tab != 'undefined' && tab != null && tab.length > 0) {
            for (j = tab.length - 1; j > (tab.length - 6) && j >= 0; j--) {
                myName = tab[j].substring(5, tab[j].length);
                cmp = jar.get(myName);
                myHtml += "<li>";
                myHtml += "<a href='" + cmp.url + "'>" + cmp.name + "</a>";
                myHtml += "<p>" + cmp.area + "</p>";
                myHtml += "<a class='campingInfoLink' href='" + cmp.url + "'>campinginfo</a>";
                myHtml += "</li>";
                display = true;
            }
        }
    }
    if ($('visited-campings')) {
        if (display) $("visited-campings").innerHTML = myHtml + "</ul>";
    }
}


// keep product info
function pushProductParams(p_tac, p_spec, p_t, p_m, p_ide, p_idm, p_idp, p_lg) {
    jar = new CookieJar({ expires: 3600, path: '/' });
    productParams = { tac: p_tac, spec: p_spec, t: p_t, m: p_m, ide: p_ide, idm: p_idm, idp: p_idp, lg: p_lg };
    jar.put('anwb-product-params', productParams);
}

function getProductParams(idEstab) {
    jar = new CookieJar({ expires: 3600, path: '/' });
    pparams = jar.get('anwb-product-params');
    if (pparams != null && pparams.ide == idEstab) {
        return "?1=1&idM=" + pparams.idm + "&idE=" + pparams.ide + "&tac=" + pparams.tac + "&spec=" + pparams.spec + "&m=" + pparams.m + "&t=" + pparams.t + "&idP=" + pparams.idp + "&lg=" + pparams.lg;
    }
    return false;
}

//GGmap
function initializeGoogleMap() {
    if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("establisment-map"), { size:
      new GSize(248, 186)
        });

        var icon = new GIcon();
        icon.image = serveurStatic + "anwb/images/ledenvoordeel-small.png";
        icon.iconSize = new GSize(27, 40);
        icon.iconAnchor = new GPoint(6, 20);
        icon.infoWindowAnchor = new GPoint(5, 1);

        map.setCenter(new GLatLng(latitude, longitude), 12);
        var mapControl = new GMapTypeControl();
        map.addControl(mapControl);
        map.addControl(new GLargeMapControl());

        var etablissement = new GLatLng(latitude, longitude);
        var marker = new GMarker(etablissement, icon);
        map.addOverlay(marker);

        //stephane : 2011-06-01, on rajoute le listener dur le clic
        Event.observe('establisment-map-zoom', 'click', function (e) {
            var mygmap = (document.getElementById("establisment-map"));
            //recuperer la taille
            var width = mygmap.style.width;
            if (width == "248px") {
                mygmap.style.width = "496px";
                mygmap.style.height = "372px";
                mygmap.style.right = "248px";
            }
            else {
                mygmap.style.width = "248px";
                mygmap.style.height = "186px";
                mygmap.style.right = "0px";
            }
        });

    }
}

//lightbox product
function getProductLightBox(divType, productId, productName, widthDiv, heightDiv) {
    Modalbox.show($(divType + productId), { width: widthDiv, height: heightDiv, title: productName }); return false;
}





//Pour toutes les pages
Event.observe(window, 'load', function () {
    //camping already visited
    displayCampsite();

    //Anwb popup
    $$('a.popup').each(function (elm) {
        Event.observe(elm, 'click', function (e) {
            window.open(elm.href, 'anwb', 'width=640,height=480,toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=690,height=670,top=10,left=10');
            e.stop();
            return false;

        });
    });

    //Taille sub Menus

    /*Print*/
    if ($('print') != null) {
        Event.observe('print', 'click', function (e) {
            window.print();
        });
    }

    jar = new CookieJar({
        expires: 86400, // seconds
        path: '/'
    });

    /* userSearch = jar.get('userSearch');
    if ($('arrivalDate') && $('arrivalDate').value != '') {
    //Cookie recherche
    if ($('arrivalDate')) { $('arrivalDate').value = userSearch.arrivalDate; }
    if ($('departureDate')) { $('departureDate').value = userSearch.departureDate; }
    if ($('territories')) { $('territories').value = userSearch.territories; }
    }*/
});




//Offres speciales
var type_code = 'L';
function selectZoneCountry(country_code, country_name) {
    $$('li.region-item').each(function (item) { item.down().setStyle({ 'fontWeight': 'normal' }) });
    if (country_code != 'exclusives') {
        $('selected-territories-list').innerHTML = "<li><a href=\"javascript:\" onclick=\"selectZoneCountry('exclusives','')\" target=\"_self\">" + country_name + "</a></li>";
        $('selected-territories').style.display = '';
        $('select-' + country_code).setStyle({ 'fontWeight': 'bold' });
    }
    Element.show('ajax-results-loading');
    callSpecialOffers(country_code, type_code);
}
function selectZone(country_code, country_name, zone_code, zone_name) {
    $('selected-territories-list').innerHTML = "<li><a href=\"javascript:\" onclick=\"selectZoneCountry('exclusives','')\" target=\"_self\">" + country_name + "</a></li><li><a id=\"select-" + country_code + "\" href=\"javascript:\" onclick=\"selectZoneCountry('" + country_code + "', '" + country_name + "');\" target=\"_self\">" + zone_name.replace("__", "'") + "</a></li>";
    $('selected-territories').style.display = '';
    $$('li.region-item').each(function (item) { item.down().setStyle({ 'fontWeight': 'normal' }) });
    $("select-" + country_code + "-" + zone_code).setStyle({ 'fontWeight': 'bold' });
    var maZone = country_code + ";" + zone_code;
    Element.show('ajax-results-loading');
    callSpecialOffers(maZone, type_code);
}
function displayCountry(country_code) {
    $$('.regions-list').each(function (one) {
        if (one.id != ("ul-" + country_code)) {
            if (one.style.display == '') {
                $(one.id).hide();
                $(one.id.substring(3, 5)).down().className = 'closed';
            }
        }
    });
    $("ul-" + country_code).toggle();
    changeCountryState(country_code);
}
function changeCountryState(country) {
    if ($(country).down().className == 'closed')
    { $(country).down().className = 'opened'; }
    else
    { $(country).down().className = 'closed'; }
}

function changeThemeCountryState() {
    if (document.getElementById('all-destinations').style.display == 'none') {
        $('togglePic').src = serveurStatic + 'anwb/images/i_plus.gif';
    }
    else {
        $('togglePic').src = serveurStatic + 'anwb/images/i_min.gif';
    }

}
function callSpecialOffers(terr, type) {
    new Ajax.Updater('offers-list', '/lastminute-offers.aspx',
        { method: 'post', parameters: { zone_code: terr, type_code: type }, onComplete: hideLoading });
    if (terr == 'exclusives' && $('selected-territories')) { Element.hide('selected-territories'); }
}
function recallSelector(type) {
    new Ajax.Updater('special-offers', '/lastminutes.aspx',
        { method: 'post', parameters: { type_code: type }, onComplete: checkTypeCode });
}
function hideLoading() {
    Element.hide('ajax-results-loading');
}
function changeTypeHeb(type) {
    if (type_code != type) {
        type_code = type;
        Element.show('ajax-results-loading');
        Element.hide('offers-list');
        recallSelector(type_code);
        callSpecialOffers('exclusives', type_code);
    }
}
function checkTypeCode() {
    if (type_code == 'E') {
        $('pitch-cb').checked = true;
    }
    else {
        $('accommodation-cb').checked = true;
    }
}

//Code promo
var type_code_promo = 'L';

function callPromotionalCode(type) {
    new Ajax.Updater('promocode', '/promo-results.aspx',
    { method: 'post',
        parameters: { type_code_promo: type },
        onComplete: hideLoadingPromo
    });
}
function callInjectedOffer(type) {
    new Ajax.Updater('promocode', '/injected-results.aspx',
    { method: 'post',
        parameters: { type_code_promo: type },
        onComplete: hideLoadingInjected
    });

}
function changeTypeHebPromo(type) {
    Element.show('ajax-promo-loading');
    Element.hide('contentpromo');
    $('type_code_promo').value = type;
    $('engineNum').value = "";
    callPromotionalCode(type);
}
function changeTypeHebInjected(type) {
    Element.show('ajax-injected-loading');
    Element.hide('contentinjected');
    $('type_code_promo').value = type;
    $('engineNum').value = "";
    callInjectedOffer(type);
}
function hideLoadingPromo() {
    eval($('js_code_promo').innerHTML);
    Element.hide('ajax-promo-loading');
    Element.show('contentpromo');
}
function hideLoadingInjected() {
    eval($('js_injected').innerHTML);
    Element.hide('ajax-injected-loading');
    Element.show('contentinjected');
}
function initializeSearch() {
    initializeThemeForm();
}

// Avis consommateurs
function callReviews(idEstab, idStayType, numPage) {
    Element.show('ajax-results-loading');
    new Ajax.Updater('reviews-ajax', '/establishment-stay-reviews.aspx',
        { method: 'get', parameters: { idE: idEstab, idS: idStayType, numP: numPage }, onComplete: initializeEstablishmentReviews });
}

// OS establishment
function changeEstabTypeHeb(type, idestab) {
    resultsPage.clear();
    if (type_code != type) type_code = type;
    Element.show('ajax-results-loading');
    $$(".offer").each = function (one) {
        Element.hide(one);
    };
    new Ajax.Request('/establishment-special-offers-kampeerplaats.aspx',
  {
      method: 'post', parameters: { type_code: type, idE: idestab, isAjax: true },
      onSuccess: function (transport) {
          document.getElementById('ajax-container').innerHTML = transport.responseText.replace('<form ', '<div ').replace('</form ', '</div ');
          //checkTypeCode();
          $$('.jsToEval').each(function (item) { eval(item.value) })
          if (resultsPage[1]) {
              $("search-results-pages").innerHTML = resultsPage[1];
              formatNumeration(1)
          }
      },
      onFailure: function () { alert('Something went wrong...') }
  });
}


//Centrer un élément
Position.center = function (element) {
    var options = Object.extend({
        zIndex: 999,
        update: false
    }, arguments[1] || {});
    element = $(element)
    if (!element._centered) {
        Element.setStyle(element, { position: 'absolute', zIndex:
options.zIndex
        });
        element._centered = true;
    }
    var dims = Element.getDimensions(element);
    Position.prepare();
    var winWidth = self.innerWidth ||
document.documentElement.clientWidth || document.body.clientWidth || 0;
    var winHeight = self.innerHeight ||
document.documentElement.clientHeight || document.body.clientHeight || 0;
    var offLeft = (Position.deltaX + Math.floor((winWidth - dims.width
) / 2));
    var offTop = (Position.deltaY + Math.floor((winHeight - dims.height
) / 2));
    element.style.top = ((offTop != null && offTop > 0) ? offTop : '0')
+ 'px';
    element.style.left = ((offLeft != null && offLeft > 0) ? offLeft :
'0') + 'px';
    if (options.update) {
        Event.observe(window, 'resize', function (evt) {
            Position.center(element);
        }, false);
        Event.observe(window, 'scroll', function (evt) {
            Position.center(element);
        }, false);
    }
}


//Tooltips
var tooltip = function () {
    var id = 'tt';
    var top = 3;
    var left = 3;
    var maxw = 500;
    var speed = 10;
    var timer = 20;
    var endalpha = 95;
    var alpha = 0;
    var tt, t, c, b, h;
    var ie = document.all ? true : false;
    return {
        show: function (v, w) {
            if (tt == null) {
                tt = document.createElement('div');
                tt.setAttribute('id', id);
                t = document.createElement('div');
                t.setAttribute('id', id + 'top');
                c = document.createElement('div');
                c.setAttribute('id', id + 'cont');
                b = document.createElement('div');
                b.setAttribute('id', id + 'bot');
                tt.appendChild(t);
                tt.appendChild(c);
                tt.appendChild(b);
                document.body.appendChild(tt);
                tt.style.opacity = 0;
                tt.style.filter = 'alpha(opacity=0)';
                document.onmousemove = this.pos;
            }
            tt.style.display = 'block';
            c.innerHTML = v;
            tt.style.width = w ? w + 'px' : 'auto';
            if (!w && ie) {
                t.style.display = 'none';
                b.style.display = 'none';
                tt.style.width = tt.offsetWidth;
                t.style.display = 'block';
                b.style.display = 'block';
            }
            if (tt.offsetWidth > maxw) { tt.style.width = maxw + 'px' }
            h = parseInt(tt.offsetHeight) + top;
            clearInterval(tt.timer);
            tt.timer = setInterval(function () { tooltip.fade(1) }, timer);
        },
        pos: function (e) {
            var u = ie ? event.clientY + document.documentElement.scrollTop : e.pageY;
            var l = ie ? event.clientX + document.documentElement.scrollLeft : e.pageX;
            tt.style.top = (u - h) + 'px';
            tt.style.left = (l + left) + 'px';
        },
        fade: function (d) {
            var a = alpha;
            if ((a != endalpha && d == 1) || (a != 0 && d == -1)) {
                var i = speed;
                if (endalpha - a < speed && d == 1) {
                    i = endalpha - a;
                } else if (alpha < speed && d == -1) {
                    i = a;
                }
                alpha = a + (i * d);
                tt.style.opacity = alpha * .01;
                tt.style.filter = 'alpha(opacity=' + alpha + ')';
            } else {
                clearInterval(tt.timer);
                if (d == -1) { tt.style.display = 'none' }
            }
        },
        hide: function () {
            clearInterval(tt.timer);
            tt.timer = setInterval(function () { tooltip.fade(-1) }, timer);
        }
    };
} ();

//Trucs compliqués
Type.registerNamespace('Sys.Net');

Sys.Net.XMLHttpSyncExecutor = function () {
    if (arguments.length !== 0) throw Error.parameterCount();
    Sys.Net.XMLHttpSyncExecutor.initializeBase(this);

    var _this = this;
    this._xmlHttpRequest = null;
    this._webRequest = null;
    this._responseAvailable = false;
    this._timedOut = false;
    this._timer = null;
    this._aborted = false;
    this._started = false;

    this._responseData = null;
    this._statusCode = null;
    this._statusText = null;
    this._headers = null;

    this._onReadyStateChange = function () {
        if (_this._xmlHttpRequest.readyState === 4) {
            _this._clearTimer();
            _this._responseAvailable = true;

            _this._responseData = _this._xmlHttpRequest.responseText;
            _this._statusCode = _this._xmlHttpRequest.status;
            _this._statusText = _this._xmlHttpRequest.statusText;
            _this._headers = _this._xmlHttpRequest.getAllResponseHeaders();

            _this._webRequest.completed(Sys.EventArgs.Empty);
            if (_this._xmlHttpRequest != null) {
                _this._xmlHttpRequest.onreadystatechange = Function.emptyMethod;
                _this._xmlHttpRequest = null;
            }
        }
    }

    this._clearTimer = function this$_clearTimer() {
        if (_this._timer != null) {
            window.clearTimeout(_this._timer);
            _this._timer = null;
        }
    }

    this._onTimeout = function this$_onTimeout() {
        if (!_this._responseAvailable) {
            _this._clearTimer();
            _this._timedOut = true;
            _this._xmlHttpRequest.onreadystatechange = Function.emptyMethod;
            _this._xmlHttpRequest.abort();
            _this._webRequest.completed(Sys.EventArgs.Empty);
            _this._xmlHttpRequest = null;
        }
    }
}
function Sys$Net$XMLHttpSyncExecutor$get_timedOut() {
    /// <value type="Boolean"></value>
    if (arguments.length !== 0) throw Error.parameterCount();
    return this._timedOut;
}

function Sys$Net$XMLHttpSyncExecutor$get_started() {
    /// <value type="Boolean"></value>
    if (arguments.length !== 0) throw Error.parameterCount();
    return this._started;
}

function Sys$Net$XMLHttpSyncExecutor$get_responseAvailable() {
    /// <value type="Boolean"></value>
    if (arguments.length !== 0) throw Error.parameterCount();
    return this._responseAvailable;
}

function Sys$Net$XMLHttpSyncExecutor$get_aborted() {
    /// <value type="Boolean"></value>
    if (arguments.length !== 0) throw Error.parameterCount();
    return this._aborted;
}

function Sys$Net$XMLHttpSyncExecutor$executeRequest() {
    if (arguments.length !== 0) throw Error.parameterCount();
    this._webRequest = this.get_webRequest();

    if (this._started) {
        throw Error.invalidOperation(String.format(Sys.Res.cannotCallOnceStarted, 'executeRequest'));
    }
    if (this._webRequest === null) {
        throw Error.invalidOperation(Sys.Res.nullWebRequest);
    }

    var body = this._webRequest.get_body();
    var headers = this._webRequest.get_headers();
    this._xmlHttpRequest = new XMLHttpRequest();
    this._xmlHttpRequest.onreadystatechange = this._onReadyStateChange;
    var verb = this._webRequest.get_httpVerb();
    this._xmlHttpRequest.open(verb, this._webRequest.getResolvedUrl(), false); // False to call Synchronously
    if (headers) {
        for (var header in headers) {
            var val = headers[header];
            if (typeof (val) !== "function")
                this._xmlHttpRequest.setRequestHeader(header, val);
        }
    }

    if (verb.toLowerCase() === "post") {
        if ((headers === null) || !headers['Content-Type']) {
            this._xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        }

        if (!body) {
            body = "";
        }
    }

    var timeout = this._webRequest.get_timeout();
    if (timeout > 0) {
        this._timer = window.setTimeout(Function.createDelegate(this, this._onTimeout), timeout);
    }
    this._xmlHttpRequest.send(body);
    var isGecko = (document.addEventListener) ? true : false;
    try {
        if (isGecko) {
            var deserializedResult = Sys.Serialization.JavaScriptSerializer.deserialize(this._xmlHttpRequest.responseText);
            ExecuteCallBackSJAX((deserializedResult) ? deserializedResult.d : null);
            return true;
        }
    }
    catch (e) { return false; }
    this._started = true;
}

function Sys$Net$XMLHttpSyncExecutor$getAllResponseHeaders() {
    /// <returns type="String"></returns>
    if (arguments.length !== 0) throw Error.parameterCount();
    if (!this._responseAvailable) {
        throw Error.invalidOperation(String.format(Sys.Res.cannotCallBeforeResponse, 'getAllResponseHeaders'));
    }

    return this._headers;
}

function Sys$Net$XMLHttpSyncExecutor$get_responseData() {
    /// <value type="String"></value>
    if (arguments.length !== 0) throw Error.parameterCount();
    if (!this._responseAvailable) {
        throw Error.invalidOperation(String.format(Sys.Res.cannotCallBeforeResponse, 'get_responseData'));
    }

    return this._responseData;
}

function Sys$Net$XMLHttpSyncExecutor$get_statusCode() {
    /// <value type="Number"></value>
    if (arguments.length !== 0) throw Error.parameterCount();
    if (!this._responseAvailable) {
        throw Error.invalidOperation(String.format(Sys.Res.cannotCallBeforeResponse, 'get_statusCode'));
    }

    return this._statusCode;
}

function Sys$Net$XMLHttpSyncExecutor$get_statusText() {
    /// <value type="String"></value>
    if (arguments.length !== 0) throw Error.parameterCount();
    if (!this._responseAvailable) {
        throw Error.invalidOperation(String.format(Sys.Res.cannotCallBeforeResponse, 'get_statusText'));
    }

    return this._statusText;
}

function Sys$Net$XMLHttpSyncExecutor$get_xml() {
    /// <value></value>
    if (arguments.length !== 0) throw Error.parameterCount();
    if (!this._responseAvailable) {
        throw Error.invalidOperation(String.format(Sys.Res.cannotCallBeforeResponse, 'get_xml'));
    }

    var xml = this._responseData;
    if ((!xml) || (!xml.documentElement)) {
        xml = new XMLDOM(this._responseData);
        if ((!xml) || (!xml.documentElement)) {
            return null;
        }
    }
    else if (navigator.userAgent.indexOf('MSIE') !== -1) {
        xml.setProperty('SelectionLanguage', 'XPath');
    }

    if ((xml.documentElement.namespaceURI === "http://www.mozilla.org/newlayout/xml/parsererror.xml") &&
        (xml.documentElement.tagName === "parsererror")) {
        return null;
    }

    if (xml.documentElement.firstChild && xml.documentElement.firstChild.tagName === "parsererror") {
        return null;
    }

    return xml;
}

function Sys$Net$XMLHttpSyncExecutor$abort() {
    if (arguments.length !== 0) throw Error.parameterCount();
    if (!this._started) {
        throw Error.invalidOperation(Sys.Res.cannotAbortBeforeStart);
    }

    if (this._aborted || this._responseAvailable || this._timedOut)
        return;

    this._aborted = true;

    this._clearTimer();

    if (this._xmlHttpRequest && !this._responseAvailable) {
        this._xmlHttpRequest.onreadystatechange = Function.emptyMethod;
        this._xmlHttpRequest.abort();

        this._xmlHttpRequest = null;
        var handler = this._webRequest._get_eventHandlerList().getHandler("completed");
        if (handler) {
            handler(this, Sys.EventArgs.Empty);
        }
    }
}

Sys.Net.XMLHttpSyncExecutor.prototype = {
    get_timedOut: Sys$Net$XMLHttpSyncExecutor$get_timedOut,
    get_started: Sys$Net$XMLHttpSyncExecutor$get_started,
    get_responseAvailable: Sys$Net$XMLHttpSyncExecutor$get_responseAvailable,
    get_aborted: Sys$Net$XMLHttpSyncExecutor$get_aborted,
    executeRequest: Sys$Net$XMLHttpSyncExecutor$executeRequest,
    getAllResponseHeaders: Sys$Net$XMLHttpSyncExecutor$getAllResponseHeaders,
    get_responseData: Sys$Net$XMLHttpSyncExecutor$get_responseData,
    get_statusCode: Sys$Net$XMLHttpSyncExecutor$get_statusCode,
    get_statusText: Sys$Net$XMLHttpSyncExecutor$get_statusText,
    get_xml: Sys$Net$XMLHttpSyncExecutor$get_xml,
    abort: Sys$Net$XMLHttpSyncExecutor$abort
}
Sys.Net.XMLHttpSyncExecutor.registerClass('Sys.Net.XMLHttpSyncExecutor', Sys.Net.WebRequestExecutor);
if (typeof (Sys) != 'undefined') {
    Sys.Application.notifyScriptLoaded();
}
var callBackSJAX;
function SetCallBackSJAX(callBack) {
    callBackSJAX = callBack;
}
function ExecuteCallBackSJAX(args) {
    if (callBackSJAX) {
        callBackSJAX(args);
        SetCallBackSJAX(null);
    }
}

function SJAX(methodName, argument, callBack) {
    SetCallBackSJAX(callBack);
    // Instantiate a WebRequest.
    var wRequest = new Sys.Net.WebRequest();
    // Set the request URL.
    wRequest.set_url(PageMethods.get_path() + "/" + methodName);
    // Set the request verb.
    wRequest.set_httpVerb('POST');
    var body = Sys.Serialization.JavaScriptSerializer.serialize(argument);
    wRequest.set_body(body);
    wRequest.get_headers()['Content-Type'] = 'application/json; charset=utf-8';

    var executor = new Sys.Net.XMLHttpSyncExecutor();
    wRequest.set_executor(executor);
    // Execute the request.
    wRequest.invoke();

    if (executor.get_responseAvailable()) {
        return executor.get_object().d;
    }
    return false;
}
// BetterInnerHTML v1.2, (C) OptimalWorks.net

function showOrHideInventory(obj) {
    var daddy = $(obj).up("li");
    var son = $(daddy).down("ul");
    if (son.style.display == "none") {
        son.show();
        obj.className = "toggled";
    }
    else {
        son.hide();
        obj.className = "closed";
    }
}

function highLightCase(month, firstElm, lastElm) {
    if ((lastElm - firstElm) < 0) { var tabLast = 31 }
    else { var tabLast = lastElm }

    for (i = firstElm; i <= tabLast; i++) {
        if ($('day_' + month + '_' + i)) {
            if ($('day_' + month + '_' + i).hasClassName('highlighted')) {
                $('day_' + month + '_' + i).removeClassName('highlighted');
            }
            else {
                $('day_' + month + '_' + i).addClassName('highlighted');
            }
        }
        if (i == 31) { i = 0; tabLast = lastElm; month += 1 }
    }
}

