﻿jar = new CookieJar();
var arrayOfResult = new Array();
var listCurrent = new Array();
var selectedCampsiteBySearchForm = 0;

var currentReviewsPage = 1;
var popUpProductId = '';



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);
    }
}

function changeProductType(productType) {
    $$('ul.products_results').each(function (item) {
        item.hide();
    });
    $('products_results_' + productType).show();
}
//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();
    }
}



function verifMail(mailTest) {
    var reg = new RegExp('^[a-z0-9]+([_|\.|-]{1}[a-z0-9]+)*@[a-z0-9]+([_|\.|-]{1}[a-z0-9]+)*[\.]{1}[a-z]{2,6}$', 'i');
    if (reg.test(mailTest)) {
        submitMail(mailTest);
        return (true);
    }
    else {
        alert('Attention, votre mail n\'est pas valide');
        return (false);
    }
}


function submitMail(mail) {
    new Ajax.Request(
	        "newsletter.aspx",
            {
                method: 'post',
                parameters:
                {
                    methode: 'inscription',
                    mail: mail
                },
                onComplete:
                    function (data) {
                        var response = data.responseText.split('#')[1];
                        var isAlready = data.responseText.split('#')[3]
                        if (response == "save_success") {
                            if (isAlready == '0') {
                                alert('Cet email est déjà inscrit à la newsletter')
                            }
                            else {
                                alert("Votre enregistrement à bien été pris en compte");
                            }
                        }
                        else
                            alert("Une erreur s'est produite lors de votre enregistrement.");
                    }
            });
}


function displayGalery(galery, elmt) {
    $$('a.link_galerie').each(function (item) {
        item.removeClassName('active');
    });
    $('picture_galery_content').innerHTML = galery_textarea[galery];
    elmt.addClassName('active');
}

//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(elm, src) {
    $$('.' + elm).each(function (elt) {
        elt.src = src;
    });
}


//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, '')
}

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 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"));

    $$('input.dates').each(function (elm) {
        populateElement(elm, defaultDate)
        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 checkForm(oForm) {

    //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 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 != "") {
            $('search_message').innerHTML = msg;
            $('search_message').show();
            $$('#search_dates label.date').each(function (item) {
                item.addClassName('warning');
            });
            $$('#search_dates input').each(function (item) {
                Event.observe(item, 'focus', function (event) {
                    $('search_message').hide();
                    $$('#search_dates label.date').each(function (item) {
                        item.removeClassName('warning');
                    });
                });
            });
            return false;
        }
    }


    document.body.style.cursor = 'wait';
    sendRequest(oForm);
}


function checkFormPopUp(productAvailabilitiesUrl) {
    var date1 = $('product_form_popup_arrivalDate').value;
    var date2 = $('product_form_popup_departureDate').value;
    var deltaMax = $('product_form_popup_deltaMax').value;

    if (date1 != defaultDate || date2 != defaultDate) {
        // var date1 = date1.replace(/-/g, '/');
        //var date2 = date2.replace(/-/g, '/');

        EstablishmentSelectSejour = new SelectSejour('', 'product_form_popup_arrivalDate', 'product_form_popup_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 {
            document.location.href = urlProducts + '?engineNum=' + engineNum + '&arrivalDate=' + date1 + '&departureDate=' + date2 + '&deltaMax=' + deltaMax + '&productId=' + popUpProductId;
        }
    }
    else { alert(tradPage.GetTrad('erreur_date1')) }


}

function EstablishmentProductsSubmit() {
    var products_engineNum = $('engineNum').value;
    var products_productTypes = $('products_productTypes').value;
    var products_arrivalDate = $('products_arrivalDate').value;
    var products_departureDate = $('products_departureDate').value;
    var products_deltaMax = $('products_deltaMax').value;
    var products_personNumber = $('products_personNumber').value;

    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');
            new Ajax.Updater('products_availabilities_ajax', '/establishment-products-availabilities-ajax.aspx',
        { method: 'get', parameters: { idE: idEstablishment, idsEstablishments: idEstablishment, engineNum: products_engineNum, arrivalDate: products_arrivalDate, departureDate: products_departureDate, deltaMax: products_deltaMax, productTypes: products_productTypes, personNumber: products_personNumber }, onComplete: initProductsResults });
        }
    }
    else { alert(tradPage.GetTrad('erreur_date1')) }

}

function initProductsResults() {
    hideLoading();
    $$('.jsToEval').each(function (item) { eval(item.value) })
}


//Cookies
function setCookie(name, content) {
    jar = new CookieJar({
        expires: 86400, // seconds
        path: '/'
    });

    jar.put(name, content);
}


//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() {

    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 + 'mediterranees/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 + "mediterranees/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;
}

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');
}

// Avis consommateurs
function callReviews(idEstab, idStayType) {
    Element.show('ajax_results_loading');
    $$('div.stay_type ul li').each(function (item) {
        item.removeClassName('selected');
    });
    $('stay_type_li_' + idStayType).addClassName('selected');
    new Ajax.Updater('reviews_ajax', '/establishment-reviews-ajax.aspx',
        { method: 'get', parameters: { idE: idEstab, idS: idStayType, lg: language }, onComplete: hideLoading });
}


function displayReviewsPage(pageToDisplay, nbPages) {
    if (pageToDisplay <= nbPages && pageToDisplay > 0) {
        $$('ul.reviews_page').each(function (item) {
            item.hide();
            $('reviews_page_' + pageToDisplay).show();
            $$('select.reviews_page_select').each(function (item) {
                item.value = pageToDisplay;
            });
        });
    }

    $$('.next, .prev').each(function (item) {
        item.show();
    });

    if (pageToDisplay == $$('.reviews_page_select')[1].options.length) {
        $$('.next').each(function (item) {
            item.hide();
        });
    }
    else if (pageToDisplay == 1) {
        $$('.prev').each(function (item) {
            item.hide();
        });
    }
    else {
        $$('.next, .prev').each(function (item) {
            item.show();
        });
    }
}

function reviewsNavigation(direction, nbPages) {
    if (direction == 'prev') {
        var pageToDisplay = eval($$('.reviews_page_select')[1].value) - 1;
    }
    if (direction == 'next') {
        var pageToDisplay = eval($$('.reviews_page_select')[1].value) + 1;
    }
    displayReviewsPage(pageToDisplay, nbPages);
}

/*Fancyzoom*/
var tempContent;
var tempRelatedDiv;

Object.extend(String.prototype, {
    // if a string doesn't end with str it appends it
    ensureEndsWith: function (str) {
        return this.endsWith(str) ? this : this + str;
    },

    // makes sure that string ends with px (for setting widths and heights)
    px: function () {
        return this.ensureEndsWith('px');
    }
});

Object.extend(Number.prototype, {
    // makes sure that number ends with px (for setting widths and heights)
    px: function () {
        return this.toString().px();
    }
});

var Window = {
    // returns correct dimensions for window, had issues with prototype's sometimes. this was ganked from apple.
    size: function () {
        var width = window.innerWidth || (window.document.documentElement.clientWidth || window.document.body.clientWidth);
        var height = window.innerHeight || (window.document.documentElement.clientHeight || window.document.body.clientHeight);
        var x = window.pageXOffset || (window.document.documentElement.scrollLeft || window.document.body.scrollLeft);
        var y = window.pageYOffset || (window.document.documentElement.scrollTop || window.document.body.scrollTop);
        return { 'width': width, 'height': height, 'x': x, 'y': y }
    }
}



function getPageSize() {

    var xScroll, yScroll;

    if (window.innerHeight && window.scrollMaxY) {
        xScroll = window.innerWidth + window.scrollMaxX;
        yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
    }

    var windowWidth, windowHeight;

    if (self.innerHeight) {	// all except Explorer
        if (document.documentElement.clientWidth) {
            windowWidth = document.documentElement.clientWidth;
        } else {
            windowWidth = self.innerWidth;
        }
        windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
    }

    // for small pages with total height less then height of the viewport
    if (yScroll < windowHeight) {
        pageHeight = windowHeight;
    } else {
        pageHeight = yScroll;
    }

    // for small pages with total width less then width of the viewport
    if (xScroll < windowWidth) {
        pageWidth = xScroll;
    } else {
        pageWidth = windowWidth;
    }

    return [pageWidth, pageHeight];
}

var FancyZoomBox = {
    directory: 'images',
    zooming: false,
    setup: false,

    init: function (directory) {
        if (FancyZoomBox.setup) return;
        FancyZoomBox.setup = true;

        var ie = navigator.userAgent.match(/MSIE\s(\d)+/);
        if (ie) {
            var version = parseInt(ie[1]);
            Prototype.Browser['IE' + version.toString()] = true;
            Prototype.Browser.ltIE7 = (version < 7) ? true : false;
        }

        var html = '<div id="overlay" style="display:none;"></div><div id="zoom" style="display:none;"> \
                  <table id="zoom_table" style="border-collapse:collapse; width:100%; height:100%;"> \
                    <tbody> \
                      <tr> \
                        <td class="tl" style="background:url(' + FancyZoomBox.directory + '/tl.png) 0 0 no-repeat; width:20px; height:20px; overflow:hidden;" /> \
                        <td class="tm" style="background:url(' + FancyZoomBox.directory + '/tm.png) 0 0 repeat-x; height:20px; overflow:hidden;" /> \
                        <td class="tr" style="background:url(' + FancyZoomBox.directory + '/tr.png) 100% 0 no-repeat; width:20px; height:20px; overflow:hidden;" /> \
                      </tr> \
                      <tr> \
                        <td class="ml" style="background:url(' + FancyZoomBox.directory + '/ml.png) 0 0 repeat-y; width:20px; overflow:hidden;" /> \
                        <td class="mm" style="background:#fff; vertical-align:top; padding:10px;"> \
                          <div id="zoom_content"> \
                          </div> \
                        </td> \
                        <td class="mr" style="background:url(' + FancyZoomBox.directory + '/mr.png) 100% 0 repeat-y;  width:20px; overflow:hidden;" /> \
                      </tr> \
                      <tr> \
                        <td class="bl" style="background:url(' + FancyZoomBox.directory + '/bl.png) 0 100% no-repeat; width:20px; height:20px; overflow:hidden;" /> \
                        <td class="bm" style="background:url(' + FancyZoomBox.directory + '/bm.png) 0 100% repeat-x; height:20px; overflow:hidden;" /> \
                        <td class="br" style="background:url(' + FancyZoomBox.directory + '/br.png) 100% 100% no-repeat; width:20px; height:20px; overflow:hidden;" /> \
                      </tr> \
                    </tbody> \
                  </table> \
                  <a href="#" title="Close" id="zoom_close" style="position:absolute; top:0; left:0;"> \
                    <img src="' + FancyZoomBox.directory + '/closebox.png" alt="Close" style="border:none; margin:0; padding:0;" /> \
                  </a> \
                </div>';

        var body = $$('body').first();
        body.insert(html);

        FancyZoomBox.overlay = $('overlay');
        FancyZoomBox.zoom = $('zoom');
        FancyZoomBox.zoom_table = $('zoom_table');
        FancyZoomBox.zoom_close = $('zoom_close');
        FancyZoomBox.zoom_content = $('zoom_content');
        FancyZoomBox.zoom_close.observe('click', FancyZoomBox.hide);
        FancyZoomBox.middle_row = $A([$$('td.ml'), $$('td.mm'), $$('td.mr')]).flatten();
        FancyZoomBox.cells = FancyZoomBox.zoom_table.select('td');

        // hide zoom if click fired is not inside zoom
        $$('html').first().observe('click', function (e) {

            var click_in_zoom = e.findElement('#zoom'),
            is_calendar = (e.target.up('table')) ? true : false,
            zoom_display = FancyZoomBox.zoom.getStyle('display');

            if (zoom_display == 'block' && !click_in_zoom && !is_calendar) {
                FancyZoomBox.hide(e);
            }
        });

        // esc to close zoom box
        $(document).observe('keyup', function (e) {
            var zoom_display = FancyZoomBox.zoom.getStyle('display');
            if (e.keyCode == Event.KEY_ESC && zoom_display == 'block') {
                FancyZoomBox.hide(e);
            }
        });

        // just use gifs as ie6 and below suck
        if (Prototype.Browser.ltIE7) {
            FancyZoomBox.switchBackgroundImagesTo('gif');
        }
    },

    show: function (e) {
        e.stop();
        if (FancyZoomBox.zooming) return;
        FancyZoomBox.zooming = true;
        var element = e.findElement('a');
        var related_div = element.content_div;
        tempRelatedDiv = related_div;
        tempContent = related_div.innerHTML;
        var arrayPageSize = getPageSize();
        FancyZoomBox.overlay.setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' });
        new Effect.Appear($('overlay'), { duration: 0.2, from: 0.0, to: 0.8 });
        var width = (element.zoom_width || related_div.getWidth()) + 60;
        var height = (element.zoom_height || related_div.getHeight()) + 60;
        var d = Window.size();
        var yOffset = document.viewport.getScrollOffsets()[1];
        // ensure that newTop is at least 0 so it doesn't hide close button
        var newTop = Math.max((d.height / 2) - (height / 2) + yOffset, 0);
        var newLeft = (d.width / 2) - (width / 2);
        FancyZoomBox.curTop = e.pointerY();
        FancyZoomBox.curLeft = e.pointerX();
        FancyZoomBox.moveX = -(FancyZoomBox.curLeft - newLeft);
        FancyZoomBox.moveY = -(FancyZoomBox.curTop - newTop);
        FancyZoomBox.zoom.hide().setStyle({
            position: 'absolute',
            top: FancyZoomBox.curTop.px(),
            left: FancyZoomBox.curLeft.px()
        });


        new Effect.Parallel([
			new Effect.Appear(FancyZoomBox.zoom, { sync: true }),
			new Effect.Move(FancyZoomBox.zoom, { x: FancyZoomBox.moveX, y: FancyZoomBox.moveY, sync: true }),
			new Effect.Morph(FancyZoomBox.zoom, {
			    style: {
			        width: width.px(),
			        height: height.px()
			    },
			    sync: true,
			    beforeStart: function (effect) {
			        // middle row height must be set for IE otherwise it tries to be "logical" with the height
			        if (Prototype.Browser.IE) {
			            FancyZoomBox.middle_row.invoke('setStyle', { height: (height - 40).px() });
			        }
			        FancyZoomBox.fixBackgroundsForIE();
			    },
			    afterFinish: function (effect) {
			        if (related_div.tagName == 'TEXTAREA') {
			            FancyZoomBox.zoom_content.innerHTML = related_div.value;
			            FancyZoomBox.zoom_content.setStyle({ 'background':'url(' + serveurStatic + 'mediterranees/img/loading.png) center center no-repeat' });
			        }
			        else {
			            FancyZoomBox.zoom_content.innerHTML = related_div.innerHTML;
			        }
			        related_div.innerHTML = '';
			        FancyZoomBox.unfixBackgroundsForIE();
			        FancyZoomBox.zoom_close.show();
			        FancyZoomBox.zooming = false;
			        if ($('product_form_popup_arrivalDate')) {
			            populateElement('product_form_popup_arrivalDate', defaultDate);
			            populateElement('product_form_popup_departureDate', defaultDate);
			            calendarCreator.run();
			        }

			    }
			})
		], { duration: 0.5 });
    },

    hide: function (e) {
        e.stop();
        if (FancyZoomBox.zooming) return;
        FancyZoomBox.zooming = true;
        new Effect.Fade($('overlay'), { duration: 0.5 });
        new Effect.Parallel([
			new Effect.Move(FancyZoomBox.zoom, { x: FancyZoomBox.moveX * -1, y: FancyZoomBox.moveY * -1, sync: true }),
			new Effect.Morph(FancyZoomBox.zoom, {
			    style: {
			        width: '1'.px(),
			        height: '1'.px()
			    },
			    sync: true,
			    beforeStart: function (effect) {
			        FancyZoomBox.fixBackgroundsForIE();
			        FancyZoomBox.zoom_content.innerHTML = '';
			        tempRelatedDiv.innerHTML = tempContent;
			        FancyZoomBox.zoom_close.hide();
			        if ($('calendar_container')) { $('calendar_container').hide() };

			    },
			    afterFinish: function (effect) {
			        FancyZoomBox.unfixBackgroundsForIE();
			        FancyZoomBox.zooming = false;
			    }
			}),

			new Effect.Fade(FancyZoomBox.zoom, { sync: true })
		], { duration: 0.5 });
    },

    // switches the backgrounds of the cells and the close image to png's or gif's
    // fixes ie's issues with fading and appearing transparent png's with 
    // no background and ie6's craptacular handling of transparent png's
    switchBackgroundImagesTo: function (to) {
        FancyZoomBox.cells.each(function (td) {
            var bg = td.getStyle('background-image').gsub(/\.(png|gif|none)\)$/, '.' + to + ')');
            td.setStyle('background-image: ' + bg);
        });
        var close_img = FancyZoomBox.zoom_close.firstDescendant();
        var new_img = close_img.readAttribute('src').gsub(/\.(png|gif|none)$/, '.' + to);
        close_img.writeAttribute('src', new_img);
    },

    // prevents the thick black border that happens when appearing or fading png in IE
    fixBackgroundsForIE: function () {
        if (Prototype.Browser.IE7) { FancyZoomBox.switchBackgroundImagesTo('gif'); }
    },

    // swaps back to png's for prettier shadows
    unfixBackgroundsForIE: function () {
        if (Prototype.Browser.IE7) { FancyZoomBox.switchBackgroundImagesTo('png'); }
    }
}

var FancyZoom = Class.create({
    initialize: function (element) {
        this.options = arguments.length > 1 ? arguments[1] : {};
        FancyZoomBox.init();
        this.element = $(element);
        if (this.element) {
            this.element.content_div = $(this.element.readAttribute('href').gsub(/^#/, ''));
            this.element.content_div.hide();
            this.element.zoom_width = this.options.width;
            this.element.zoom_height = this.options.height;
            this.element.observe('click', FancyZoomBox.show);
        }
    }
});

/*End Fancy zoom*/

//Affichage des grilles tarifaires
function displayProductPrices(productId, pricingID, tableNb) {
    $$('div.div_product_pricing_' + productId ).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_product_pricing_'+ productId).each(function (element) {
        element.hide()
    });
    $('div_pricing_details_product_' + productId + '_' + pricingID + '_1').show();
    $$('.link_pricing_' + productId).each(function (element) {
        element.removeClassName('active');
    });
    $('link_pricing_' + pricingID + '_' + productId).addClassName('active');
    
}










//MS
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()) {
        return executor.get_object();
    }
    return false;
}
// BetterInnerHTML v1.2, (C) OptimalWorks.net



