﻿var arrayOfResult = new Array();
var listCurrent = new Array();
var selectedCampsiteBySearchForm = 0;
var currentPage = 1;

var fromFlash = false;


function toggleize(elmToToggle, elmLink, class1, class2) {
    $(elmToToggle).toggle();
    if ($(elmToToggle).getStyle('display') == 'none') {
        $(elmLink).removeClassName(class2);
        $(elmLink).addClassName(class1);
    }

    else {
        $(elmLink).removeClassName(class1);
        $(elmLink).addClassName(class2);
    }
}
//Refuser touche entrer
function avoidEnter(event) {
    // Compatibilité IE / Firefox
    if (!event && window.event) {
        event = window.event;
    }
    // IE
    if (event.keyCode == 13) {
        event.returnValue = false;
        event.cancelBubble = true;
    }
    // DOM
    if (event.which == 13) {
        event.preventDefault();
        event.stopPropagation();
    }
}

//affichage d'une serie d'images
function imgLoop(nb, src) {
    var imgStr = "";
    for (i = 1; i <= nb; i++) {
        imgStr += "<img src=\"" + src + "\" alt=\"\" />";
    }
    return imgStr;
}

//affiche une image en grand format
function displayPicture(src) {
    $('main_picture').fade({ duration: 1.0, from: 1, to: 0, afterFinish: function () {
        $('main_picture').src = src;
        $('main_picture').appear({ duration: 1.0 });
    }
    });
}


function checkThemeMenu() {
    var menuWidth = 0;
    $$('#theme_menu_list li').each(function (elt) {
        menuWidth += elt.getWidth();
    });
    if (menuWidth > 890) {
        $$('#theme_menu_navigation a').show();
    }
}

//Affichage de videos
function changePlayerVid(id) {
    var code_player = "%3Cobject width%3D%22335%22 height%3D%22275%22 id%3D%22webtvrhonealpes-tourismefrminiplayer" + id + "%22 classid%3D%22clsid%3AD27CDB6E-AE6D-11cf-96B8-444553540000%22%3E%0D%0A%3Cparam name%3D%22movie%22 value%3D%22http%3A%2F%2Fwebtv.rhonealpes-tourisme.fr%2Fminiplayer%2Fminiplayer.swf%22%3E%3C%2Fparam%3E%0D%0A%3Cparam name%3D%22allowFullScreen%22 value%3D%22true%22%3E%3C%2Fparam%3E%0D%0A%3Cparam name%3D%22allowscriptaccess%22 value%3D%22always%22%3E%3C%2Fparam%3E%0D%0A%3Cparam name%3D%22bgcolor%22 value%3D%22%23445b83%22%3E%3C%2Fparam%3E%0D%0A%3Cparam name%3D%22flashvars%22 value%3D%22id_video%3D" + id + "%26color%3D445b83%26broadcast%3Dpartenaire%26partner_id%3D58%22%3E%3C%2Fparam%3E%0D%0A%3Cparam name%3D%22wmode%22 value%3D%22transparent%22%3E%3C%2Fparam%3E%0D%0A%3Cembed src%3D%22http%3A%2F%2Fwebtv.rhonealpes-tourisme.fr%2Fminiplayer%2Fminiplayer.swf%22 %0D%0A%09type%3D%22application%2Fx-shockwave-flash%22 %0D%0A%09allowscriptaccess%3D%22always%22 %0D%0A%09allowfullscreen%3D%22true%22 %0D%0A%09width%3D%22335%22 %0D%0A%09height%3D%22275%22 %0D%0A%09bgcolor%3D%22%23445b83%22 %0D%0A%09flashvars%3D%22id_video%3D" + id + "%26color%3D445b83%26broadcast%3Dpartenaire%26partner_id%3D58%22%0D%0A%09wmode%3D%22transparent%22%3E%3C%2Fembed%3E%0D%0A%3C%2Fobject%3E%0D%0A%3Cscript type%3D%22text%2Fjavascript%22 %3E%0D%0A%09var addthis_config %3D%7B services_expanded%3A%27email%2C favorites%2C facebook%2C blogger%2C google%2C live%2C digg%2C reddit%2C delicious%2C twitter%2C stumbleupon%27%7D%3B%0D%0A%3C%2Fscript%3E%0D%0A%3Cscript src%3D%22http%3A%2F%2Fs7.addthis.com%2Fjs%2F250%2Faddthis_widget.js%3Fpub%3Dxa-4a939ce20a9a4bca%22 type%3D%22text%2Fjavascript%22%3E%3C%2Fscript%3E%0D%0A%3Cscript type%3D%22text%2Fjavascript%22 %3E%0D%0A%09function setAndClickAddthisButton%28sUrl%2C sTitle%29%0D%0A%09%7B%0D%0A%09%09var element %3D document.getElementById%28%22addthis_bt%22%29%3B%0D%0A%09%09if %28element %21%3D null%29%0D%0A%09%09%7B%0D%0A%09%09%09if %28element.parentNode%29%0D%0A%09%09%09%09var parentContainer %3D element.parentNode%3B%0D%0A%09%09%09else%0D%0A%09%09%09%09var parentContainer %3D element.parentElement%3B%0D%0A%09%09%09%09%0D%0A%09%09%09parentContainer.removeChild%28element%29%3B%0D%0A%09%09%7D%0D%0A%09%09%0D%0A%09%09var addThisButton %3D document.createElement%28%27a%27%29%3B%0D%0A%09%09addThisButton.setAttribute%28%27id%27%2C %27addthis_bt%27%29%3B%0D%0A%09%09addThisButton.setAttribute%28%22style%22%2C %22display%3Anone%3Bposition%3Aabsolute%3B z-index%3A9999%3B%22%29%3B%0D%0A%09%09document.body.appendChild%28addThisButton%29%3B%0D%0A%09%09%0D%0A%09%09addthis.button%28%27%23addthis_bt%27%2C %7B%7D%2C %7Burl%3A sUrl%2C title%3A sTitle%7D%29%3B%0D%0A%09%09%09%0D%0A%09%09document.getElementById%28%22addthis_bt%22%29.onclick%28%29%3B%0D%0A%09%7D%0D%0A%3C%2Fscript%3E"; if (!document.getElementById("webtvrhonealpes-tourismefrminiplayer" + id + "")) $('player_vid').innerHTML = (unescape(code_player));
}


function getFlashMovie(movieName) {
    var isIE = navigator.appName.indexOf("Microsoft") != -1;
    return (isIE) ? window[movieName] : document[movieName];
}

function formSend() {
    var text = document.htmlForm.sendField.value;
    getFlashMovie("ExternalInterfaceExample").sendTextToFlash(text)
}

//Données envoyées par le flash
function getValueFromFlash(str) {
    switch (str) {
        case "FR;01;07":
            url_result = FR_01_07;
            break;
        case "FR;01;26":
            url_result = FR_01_26;
            break;
        case "FR;01;42":
            url_result = FR_01_42;
            break;
        case "FR;01;69":
            url_result = FR_01_69;
            break;
        case "FR;01;38":
            url_result = FR_01_38;
            break;
        case "FR;01;01":
            url_result = FR_01_01;
            break;
		case "FR;01;02":
			url_result = FR_01_02;
			break;
    }
    //alert(url_result);
    $('tb_lat').value = "";
    $('tb_lon').value = "";
    $('territories').name = "";
    searchForm.UrlRechercheDispo = url_result;

    fromFlash = true;

    checkForm(this);
}

//Defilement du menu
function nextMenu(element, elementSize) {
    new Effect.Move($(element), { x: -elementSize, y: 0, mode: 'absolute', transition: Effect.Transitions.sinoidal }); return false;
}
function prevMenu(element, elementSize) {
    new Effect.Move($(element), { x: 0, y: 0, mode: 'absolute', transition: Effect.Transitions.sinoidal }); return false;
}

//texte date par default
function getDefaultDate() {
    switch (language.toLowerCase()) {
        case 'fr':
            var defaultDate = 'jj/mm/aaaa';
            break;
        case 'en':
            var defaultDate = 'dd/mm/yyyy';
            break;
        case 'es':
            var defaultDate = 'dd/mm/aaaa';
            break;
        case 'it':
            var defaultDate = 'gg/mm/aaaa';
            break;
        case 'nl':
            var defaultDate = 'dd/mm/jjjj';
            break;
        case 'de':
            var defaultDate = 'dd/mm/yyyy';
            break;
        case 'ca':
            var defaultDate = 'dd/mm/aaaa';
            break;
        case 'da':
            var defaultDate = 'dd/mm/aaaa';
            break;
        case 'hr':
            var defaultDate = 'dd/mm/gggg';
            break;
        case 'pt':
            var defaultDate = 'dd/mm/aaaa';
            break;
        default: var defaultDate = 'jj/mm/aaaa';
            break;
    }
    return defaultDate;
}

/*input text default text*/
function populateElement(selector, defvalue) {
    if (trim($(selector).value) == "") {
        $(selector).value = defvalue;
        $(selector).addClassName('input_inactive');
    }

    $(selector).observe('focus', function (elm) {
        $(selector).removeClassName('input_inactive');
        $(selector).addClassName('input_active');
        if ($(selector).value == defvalue) {
            $(selector).value = "";

        }

    });

    $(selector).observe('blur', function (elm) {
        if (trim($(selector).value) == "" || trim($(selector).value) == defvalue) {
            $(selector).value = defvalue;
            $(selector).removeClassName('input_active');
            $(selector).addClassName('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, '')
}

//Lecture/Pause slideshow superpoi
function supersPoiPlayPause(btnId) {
    if ($('supers_poi_play_pause').hasClassName('supers_poi_pause')) {

        $('supers_poi_play_pause').removeClassName('supers_poi_pause');
        $('supers_poi_play_pause').addClassName('supers_poi_play');
        supers_poi.stop();
    }
    else {
        $('supers_poi_play_pause').removeClassName('supers_poi_play');
        $('supers_poi_play_pause').addClassName('supers_poi_pause');
        supers_poi.start();

    }
}


function supersPoiNext() {
    supers_poi.stop();
    $('supers_poi_play_pause').removeClassName('supers_poi_pause');
    $('supers_poi_play_pause').addClassName('supers_poi_play');
    supers_poi.next()
}

function supersPoiPrev() {
    supers_poi.stop();
    $('supers_poi_play_pause').removeClassName('supers_poi_pause');
    $('supers_poi_play_pause').addClassName('supers_poi_play');
    supers_poi.prev()
}

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 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"));
}

function initializeSearchForm() {
    //camping already visited
    displayCampsite();

    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.SetPopup(false);

    searchForm.tab_panel_checkbox.push(new PanelCheckbox("h_sub_type", "cbSubType", false, false, "sous type"));

    populateElement('arrivalDate', defaultDate)
    populateElement('departureDate', defaultDate)
    populateElement('tb_nom_camping', trad_sqqpqrhfz8h321sra4h8)
    populateElement('tb_recherche', trad_departement_ville)


    $$('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;
        });
    });

    $$('ul#subTypes li').each(function (elm) {
        Event.observe(elm, 'click', function (e) {
            if($('productType2').checked == false)$('productType2').checked = true;
        });
    });
}

function initializeProductSearchForm() {
    selectSejour = new SelectSejour('', 'products_arrivalDate', 'products_departureDate');
    //initProductSearchCookie();
    populateElement('products_arrivalDate', defaultDate);
    populateElement('products_departureDate', defaultDate);
    formatNumeration(1);
}

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();
            PageMethods.GetResponsePage(
				keyResult,
				(pageValueInt - 1) * 10,
				pageValueInt * 10,
				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>' + trad_precedent + '</span>');
            elmPrev.className = 'prev page_1';
        });
    }
    else {
        $$('ul.pagination li.prev').each(function (elmPrev) {
            var linkStr = "<a class='link' target='_self' href='#results' onclick=\"navigation('prev')\">" + trad_precedent + "</a>";
            if ($(elmPrev).up('ul').hasClassName('top'))
            { elmPrev.update(linkStr.replace(/#results/gi, 'javascript:')); }
            else { elmPrev.update(linkStr); }
            elmPrev.className = 'prev page_' + (pageValueInt - 1);
        });
    }
    if (pageValue == lastPage) {
        $$('ul.pagination li.next').each(function (elmNext) {
            elmNext.update('<span>' + trad_suivant + '</span>');
            //elmNext.down('a').className = 'active';
            elmNext.className = 'next page_' + pageValue;
        });
    }
    else {
        $$('ul.pagination li.next').each(function (elmNext) {
            var linkStr = "<a class='link' target='_self' href='#results' onclick=\"navigation('next')\">" + trad_suivant + "</a>";
            if ($(elmNext).up('ul').hasClassName('top'))
            { elmNext.update(linkStr.replace(/#results/gi, 'javascript:')); }
            else
            { elmNext.update(linkStr) }
            elmNext.className = 'next page_' + (pageValueInt + 1);
        });
    }
}
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;
    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) {
        if ($(elmul).up(1).hasClassName('top'))
        { elmul.innerHTML = futur_inner.replace(/#results/gi, 'javascript:'); }
        else {
            elmul.innerHTML = futur_inner;
        }
    });


    if (currentPage == '1') {
        $$('ul.pagination li.prev').each(function (elmPrev) {
            elmPrev.update('<span>' + trad_precedent + '</span>');
        });
    }
    else {
        $$('ul.pagination li.prev').each(function (elmPrev) {
            var linkStr = "<a class='link' target='_self' href='#results' onclick=\"navigation('prev')\">" + trad_precedent + "</a>";
            if ($(elmPrev).up('ul').hasClassName('top'))
            { elmPrev.update(linkStr.replace(/#results/gi, 'javascript:')); }
            else
            { elmPrev.update(linkStr); }
        });
    }
    if (currentPage == lastPage) {
        $$('ul.pagination li.next').each(function (elmNext) {
            //elmNext.down('a').className = 'active';
            elmNext.update('<span>' + trad_suivant + '</span>');
        });
    }
    else {
        $$('ul.pagination li.next').each(function (elmNext) {
            var linkStr = "<a class='link' target='_self' href='#results' onclick=\"navigation('next')\">" + trad_suivant + "</a>";
            if ($(elmNext).up('ul').hasClassName('top'))
            { elmNext.update(linkStr.replace(/#results/gi, 'javascript:')); }
            else
            { elmNext.update(linkStr); }
        });
    }

    var withoutAnchorUrl = window.location.href.split('#results')[0];

    if (withoutAnchorUrl.indexOf(".html?") != -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 (lastCurrentPage) != "undefined") {
        jar.put('urlSearch', urlSearch);
    }
    else {
        jar.put('urlSearch', '');
    }
    displayPage(currentPage);
}

function checkForm(oForm) {

    /*$$('input.cb-theme-territory').each(function (elm) {
    if (elm.checked) { $('territories').value += elm.value + '|' };
    });*/

    //searchForm = new SearchForm(url_result);
    searchForm.SetPopup(false);



    //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; }
    }

    var search_productTypes = $$('input:checked[type="checkbox"][class="productTypes"]').pluck('value').toString();
    search_productTypes = search_productTypes.replace(/,/gi, '|');
    $('h_productTypes').value = search_productTypes;

    var search_subTypes = $$('input:checked[type="checkbox"][class="subTypes"]').pluck('value').toString();
    search_subTypes = search_subTypes.replace(/,/gi, '|');
    $('h_subTypes').value = search_subTypes;

    if (search_subTypes != '') {
        if ($('productType2').checked == false)
        { $('productType2').checked = true; }
    }

    //Budget
    if ($('aspnetForm')['priceMax'].getValue() == '1000') {
        $('aspnetForm')['priceMax'].name = '';
        $('aspnetForm')['priceMin'].value = '800';
    }

    $$('.filter_destination input').each(function (elm) {
        if (elm.checked) { territories += elm.value + "|" }
    });

    if ($('arrivalDate').value != defaultDate || $('departureDate').value != defaultDate) {
        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 = tradPage.GetTrad('erreur_date1');
                    break;
                case 2:
                    msg = tradPage.GetTrad('erreur_date2');
                    break;
                case 3:
                    msg = tradPage.GetTrad('erreur_date3');
                    break;
                case 4:
                    msg = tradPage.GetTrad('erreur_date4');
                    break;
                case 5:
                    msg = tradPage.GetTrad('erreur_date5');
                    break;
                case 6:
                    msg = tradPage.GetTrad('erreur_date6');
                    break;
                case 7:
                    msg = tradPage.GetTrad('erreur_date7');
                    break;
            }
            if (msg != "")
                alert(msg);
            return false;
        }
    }

    else {
        if (fromFlash == false) {
            msg = tradPage.GetTrad('erreur_date8');
            alert(msg);
            return false;
        }
        else {
            $('arrivalDate').name = "";
            $('departureDate').name = "";
        }

    }

    document.body.style.cursor = 'wait';
    sendRequest(oForm);
}



function resultsFilter() {
    Element.show('ajax_results_loading');
    var resultsFilter_services = $$('input:checked[type="checkbox"][class="results_filter_service"]').pluck('value').toString().replace(/,/gi, '|');
    resultsFilter_qualityMin = $('results_filter_qualityMin').value;
    new Ajax.Request('/Search-ajax.aspx',
  {
      method: 'post', parameters: { engineNum: engineNum, arrivalDate: arrivalDate, departureDate: departureDate, deltaMax: deltaMax, language: language, latitude: latitude, longitude: longitude, personNumber: personNumber, priceMax: priceMax, priceMin: priceMin, productTypes: productTypes, subTypes: subTypes, territories: territories2, qualityMin: resultsFilter_qualityMin, services: resultsFilter_services, isAjax: true },
      onSuccess: function (transport) {
          $('results').innerHTML = '';
          $('results').innerHTML = transport.responseText;
          for (var i = 0; i < resultsPage.length; i++)
          { resultsPage[i] = ''; }
          $$('.jsToEval').each(function (item) { eval(item.value) });
          initializeSearchResults();
          Element.hide('ajax_results_loading');
      },
      onFailure: function () { alert('Something went wrong...') }
  });
}

//Filtrage des themes
function themeFilterSubmit() {
    var territories = "";
    var services = "";
    $$('.filter_destination input').each(function (elm) {
        if (elm.checked) { territories += elm.value + "|" }
    });
    $$('.filter_options input').each(function (elm) {
        if (elm.checked) { services += elm.value + "|" }
    });
    stringThemeFilterUrl = themeUrl;

    if (territories != "") {
        stringThemeFilterUrl += "?territories=" + territories;
        if (services != "") {
            stringThemeFilterUrl += "&services=" + services;
        }
    }
    if (territories == "" && services != "") {
        stringThemeFilterUrl += "?services=" + services;
    }
    Element.show('ajax_results_loading');
    window.location.href = stringThemeFilterUrl + "#results";
}


function EstablishmentProductsSubmit() {
    var products_engineNum = $('engineNum').value;
    var products_arrivalDate = $('products_arrivalDate').value;
    var products_departureDate = $('products_departureDate').value;
    var products_deltaMax = $('products_deltaMax').value;
    var products_productTypes = $$('input:checked[type="checkbox"][name="products_productTypes"]').pluck('value').toString();
    products_productTypes = products_productTypes.replace(/,/gi, '|');
    //    var products_services = "";
    //    if (products_productTypes != 'E' && products_productTypes != 'L') {
    //        products_services = products_productTypes;
    //        products_productTypes = "";
    //    }



    if ($('products_arrivalDate').value != defaultDate || $('products_departureDate').value != defaultDate) {
        var date1 = $('products_arrivalDate').value.replace(/-/g, '/');
        var date2 = $('products_departureDate').value.replace(/-/g, '/');

        $('products_arrivalDate').value = date1;
        $('products_departureDate').value = date2;

        EstablishmentSelectSejour = new SelectSejour('', 'products_arrivalDate', 'products_departureDate');

        codeError = EstablishmentSelectSejour.VerifDate();
        if (codeError > 0) {
            var msg = "";

            switch (codeError) {
                case 1:
                    msg = tradPage.GetTrad('erreur_date1');
                    break;
                case 2:
                    msg = tradPage.GetTrad('erreur_date2');
                    break;
                case 3:
                    msg = tradPage.GetTrad('erreur_date3');
                    break;
                case 4:
                    msg = tradPage.GetTrad('erreur_date4');
                    break;
                case 5:
                    msg = tradPage.GetTrad('erreur_date5');
                    break;
                case 6:
                    msg = tradPage.GetTrad('erreur_date6');
                    break;
                case 7:
                    msg = tradPage.GetTrad('erreur_date7');
                    break;
            }
            if (msg != "")
                alert(msg);
            return false;
        }
        else {
            Element.show('ajax_results_loading');
            productSearchString = url_products + "?engineNum=" + products_engineNum + "&arrivalDate=" + products_arrivalDate + "&departureDate=" + products_departureDate + "&deltaMax=" + products_deltaMax + "&productTypes=" + products_productTypes;
            window.location.href = productSearchString;
        }
    }
    else { alert(tradPage.GetTrad('erreur_date1')) }

}

//Filtrage des événements
function eventFilterSubmit() {
    var Month = '';
    var CategoryID = '';
    var DPT = '';
    var strFilterParams = '?';
    if ($('event_filter_month')) {
        Month = $('event_filter_month').value;
        strFilterParams += 'Month=' + Month + '&';
    }
    if ($('event_filter_categoryId')) {
        CategoryID = $('event_filter_categoryId').value;
        strFilterParams += 'CategoryID=' + CategoryID + '&';
    }
    if ($('event_filter_dpt')) {
        DPT = $('event_filter_dpt').value;
        strFilterParams += 'DPT=' + DPT;
    }

    window.location.href = urlEventSearch + strFilterParams;
}

//Résultats de recherche
function initializeSearchResults() {
    setSearchCookie();
    //Pagination des resultats - nombres
    $$('#results ul.tabs li a').each(function (elm) {
        Event.observe(elm, 'click', function () {
            $$('#results div.establishment_item').each(function (tab) {
                tab.hide();
            });
            $$('#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));
        }
        )
    });

    $$('#results_map ul.pagination li').each(function (elm) {
        Event.observe(elm, 'click', function (e) {
            initMyGmap();
        });
    });

    //initialisation de la pagination
    if (typeof (lastCurrentPage) != "undefined") {
        formatNumeration(lastCurrentPage);
    }
    else {
        formatNumeration(1);
    }
}

//Establishment pictures
function initializeEstablishmentPictures() {
    //photos
    $$('div.thumbs img').each(function (element) {
        Event.observe(element, 'mouseover', function () {
            new Effect.Opacity(element, { duration: 0.2, from: 1.0, to: 0.6 });
        });
        Event.observe(element, 'mouseout', function () {
            new Effect.Opacity(element, { duration: 0.2, from: 0.6, to: 1 });
        });
    });

}



//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() {
    var currentUrl = document.location.href.split('?')[0];
    var stringUrl = currentUrl + strSearchParams + "&services="+services;


    jar = new CookieJar({
        expires: 86400, // seconds
        path: '/'
    });

    search = {
        url: stringUrl
    };

    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 ($('arrivalDate').value == '') {
        $$('input.dates').each(function (elm) {
            elm.className = 'dates active';
        });
        $('arrivalDate').value = userSearch.arrivalDate;
        $('departureDate').value = userSearch.departureDate;

    }
}

//initialisation des champs produits après une recherche produit
function initProductSearchCookie() {
    productJar = new CookieJar();
    productSearch = productJar.get('userProductSearch');
    if (isProductSearch == 'false') {
        if (productSearch != null) {
            $$('input.dates').each(function (elm) {
                elm.className = 'dates active';
            });
            $('arrivalDate').value = productSearch.arrivalDate;
            $('departureDate').value = productSearch.departureDate;
            $('personNumber').value = productSearch.personNumber;

        }
        else {
            initSearchCookie();
        }
    }
    else {
        var stringProductSearchUrl = "arrivalDate=" + productSearch.arrivalDate + "&departureDate=" + productSearch.departureDate + "&personNumber=" + productSearch.personNumber;
        $('li_product').down().href += "?engineNum=741&language=NL&displayProductInfo=true&" + stringProductSearchUrl;
    }
}




//Cookie Already visited
function isAlreadyExist(cookieName) {
    cpm = jar.get(cookieName);
    return cpm != null;
}

function pushCampsite(campsiteId, campsiteName, campsiteArea, campsiteStarsNb) {
    if (!isAlreadyExist('ra_visited_' + campsiteId)) {
        campsite = { id: campsiteId, name: campsiteName, area: campsiteArea, url: campsiteUrl, starsNb: campsiteStarsNb };
        jar.put('ra_visited_' + campsiteId, campsite);
        displayCampsite();
    }
}

function displayCampsite() {
    jar = new CookieJar({ expires: 3600 * 24 * 6, path: '/' });
    myHtml = "<h2>" + trad_kkv1tk8sf54b1spgzccv + "</h2><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("ra_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);
                var starsNb = imgLoop(cmp.starsNb, serveurStatic + 'Rhone-Alpes/img/star.png')
                myHtml += "<li>";
                myHtml += "<a href='" + cmp.url + "' class='name'>" + cmp.name + "</a>";
                myHtml += "<p><span>" + cmp.area + "</span>";
                myHtml += starsNb + "</p>";
                myHtml += "<div class='link'><a class='arrow' href='" + cmp.url + "'>" + maChaine + "</a></div>";
                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 smallMap = new GMap2(document.getElementById("establishment_small_map"), { size:
        //      new GSize(260, 200)
        //        });

        var icon = new GIcon();
        icon.image = serveurStatic + "Rhone-Alpes/img/map-marker.png";
        icon.iconSize = new GSize(32, 37);
        icon.iconAnchor = new GPoint(6, 20);
        icon.infoWindowAnchor = new GPoint(5, 1);

        //        smallMap.setCenter(new GLatLng(latitude, longitude), 12);
        //        var mapControl = new GMapTypeControl();
        //        smallMap.addControl(mapControl);
        //        smallMap.addControl(new GLargeMapControl());

        //        var etablissement = new GLatLng(latitude, longitude);
        //        var marker = new GMarker(etablissement, icon);
        //        smallMap.addOverlay(marker);


        var bigMap = new GMap2(document.getElementById("establishment_big_map"), { size:
      new GSize(520, 400)
        });

        bigMap.setCenter(new GLatLng(latitude, longitude), 8);
        var mapControl = new GMapTypeControl();
        bigMap.addControl(mapControl);
        bigMap.addControl(new GLargeMapControl());

        var etablissement = new GLatLng(latitude, longitude);
        var marker = new GMarker(etablissement, icon);
        bigMap.addOverlay(marker);

    }
}

//lightbox product
function getProductLightBox(divType, productId, productName, widthDiv, heightDiv) {
    Modalbox.show($(divType + productId), { width: widthDiv, height: heightDiv, title: productName }); return false;
}





//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 displayDepartement(deptCode) {
    $$('.dept-item').each(function (one) {
        if (one.id != (deptCode)) {
            one.removeClassName('li-not-selected');
        }
    });
    var deptCodeId = replace(deptCode, ';', '_');
    $(deptCodeId).addClassName('li-selected');
    callSpecialOffers(deptCode);
}

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) {
    //Element.show('ajax_results_loading');
    new Ajax.Updater('special_offers', '/lastminute-offers.aspx',
        { method: 'post', parameters: { zone_code: terr }, onComplete: hideLoading });
}
function recallOfferList(terr) {
    //Element.show('ajax_results_loading');
    var date = $("DateFilter").options[$("DateFilter").selectedIndex].value;
    var typeProd = "";
    if ($("locatif_filter").checked) typeProd = "Locatif";
    if ($("emplacement_filter").checked) typeProd += "-Emplacement";
    if (typeProd == "") typeProd = "Locatif-Emplacement";
    new Ajax.Updater('offer_list', '/lastminutes.aspx',
        { method: 'post', parameters: { zone_code: terr, dateFilter: date, productFilter: typeProd }, onComplete: hideLoading });
}

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 });*/
    document.forms[0].action = "";
    document.forms[0].submit();
}
function changeTypeHebPromo(type) {
    Element.show('ajax-promo-loading');
    Element.hide('contentpromo');
    $('type_code_promo').value = type;
    $('engineNum').value = "";
    callPromotionalCode(type);
}
function hideLoadingPromo() {
    eval($('js_code_promo').innerHTML);
    Element.hide('ajax-promo-loading');
    Element.show('contentpromo');
}
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, lg: language }, onComplete: initializeEstablishmentReviews });
}

// OS establishment
function changeEstabTypeHeb(idestab) {
    var OsProductType = '';
    if ($('productTypeL').checked) { OsProductType += 'L|' }
    if ($('productTypeE').checked) { OsProductType += 'E|' }
    Element.show('ajax_results_loading');
    $$(".offer").each = function (one) {
        Element.hide(one);
    };
    new Ajax.Request('/establishment-special-offers-ajax.aspx',
  {
      method: 'post', parameters: { productTypes: OsProductType, idE: idestab, isAjax: true },
      onSuccess: function (transport) {
          //alert(transport.responseText);
          document.getElementById('ajax_container').innerHTML = transport.responseText.replace('<form ', '<div ').replace('</form ', '</div ');
          for (var i = 0; i < resultsPage.length; i++)
              resultsPage[i] = '';
          $$('.jsToEval').each(function (item) { eval(item.value) })
          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 = 400;
    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) {

            ExecuteCallBackSJAX(Sys.Serialization.JavaScriptSerializer.deserialize(this._xmlHttpRequest.responseText));
            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()) {
		var res = executor.get_object();
		if(res != null && res.d)
			res = res.d;
        return res;
    }
    return false;
}
// BetterInnerHTML v1.2, (C) OptimalWorks.net



