FH = (function () {
    function _getMeta(n) {
        var _m = document.getElementsByTagName("meta");
        for (i = 0; i < _m.length; i++) {
            try {
                if (_m[i].name == n) { return _m[i].content; }
            } catch (ee) {}
        }
        return "";
    }

    function _pparams(p) {
        var regex = new RegExp("[\\?&#]" + p.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]") + "=([^&#]*)");
        var results = regex.exec(window.location.href);
        return (results == null) ? "" : results[1];
    }


    function _getLang() {
        var _h = document.getElementsByTagName("html")[0];
        try {
            return _h.attributes["xml:lang"].value;
        } catch (ee) {}
        try {
            return _h.attributes.lang.value;
        } catch (ee) {}
        try {
            /\/([a-z]{2}(?:-[a-z]{2})?)\//.exec(document.location); return RegExp.$1;
        } catch (ee) {}
        return "en";
    }

    function _en2gb(l) {
        return (l == 'en') ? 'gb' : l;
    }

    var _log = false;

    return {

        lang: _getLang(),
        rid: _getMeta("X-Accor-rid"),
        brand: _getMeta("X-Accor-brand"),
        mark:  _getMeta("X-Accor-mark"),
        mediatype: _getMeta("X-Accor-mediatype"),
        name: _getMeta("X-Accor-hotel-name"),
        imgpath: _en2gb(_getLang()),

        en2gb: function (l) {
            return (l == 'en') ? 'gb' : l;
        },
        gb2en: function (l) {
            return (l == 'gb') ? 'en' : l;
        },

        log: function (msg) {
            if (_log && window.console) { console.log(msg); }
        },

        loadJs: function (jsurl, _def) {
            var _r = "";
            jQuery.ajax({
                url: jsurl,
                cache: false,
                type: 'get',
                async: false,
                success: function (transport) {
                    _r = transport;
                },
                error: function (transport) {
                    _r = (!_def) ? "" : _def;
                }
            });
            return _r;
        },

        getParam: function (p) {
            return _pparams(p);
        }

    };
}
)();




FH.display = {
    init: function (O, forceWindowOnLoad) {
        jQuery(document).ready(function () {
            O.fh.display.init();
            FH.availabilities.init();
            FH.sendtofriend.init();
            FH.popup.init();
            FH.popins.init();
            FH.currencies.init();
            FH.mapo.closeAvailDates();
        });
    }

};



FH.dyn = {

    init: function (O, forceWindowOnLoad) {
        jQuery(document).ready(function () {
            O.fh.dyn.init();
        });
    },

    callJson: function (beans, success, failure) {
        return jQuery.ajax({
            url: '/bean/getViewBeans.action?httpSessionId=' + jQuery.cookie("JSESSIONID") + '&beans=' + beans + '&lang=' + FH.lang + '&referer=' + escape(window.document.referrer),
            dataType: 'json',
            success: success,
            error: failure
        });
    }

};

FH.context = (function () {
    var _webapps = {
        'businesstravel': {
            'code': 'BUS',
            'mapo': 'BUS',
            'domainelement': 'businesstravel.accorhotels'
        },
        'travelagencies': {
            'code': 'TRV',
            'mapo': 'TRV',
            'domainelement': 'travelagencies.accorhotels'
        },
        'meetings': {
            'code': 'MEE',
            'mapo': 'MEE',
            'domainelement': 'meetings.accorhotels'
        },
        'accorhotels': {
            'code': 'ALL',
            'mapo': 'accor',
            'domainelement': 'accorhotels'
        },
        'sofitel': {
            'code': 'SOF',
            'mapo': 'SOF',
            'domainelement': 'sofitel'
        },
        'suite': {
            'code': 'SUI',
            'mapo': 'SUI',
            'domainelement': 'suite'
        },
        'novotel': {
            'code': 'NOV',
            'mapo': 'NOV',
            'domainelement': 'novotel'
        },
        'mercure': {
            'code': 'MER',
            'mapo': 'MER',
            'domainelement': 'mercure'
        },
        'ibis': {
            'code': 'IBI',
            'mapo': 'IBI',
            'domainelement': 'ibis'
        },
        'etaphotel': {
            'code': 'ETP',
            'mapo': 'ETP',
            'domainelement': 'etap'
        },
        'formule1': {
            'code': 'FOR',
            'mapo': 'formule1',
            'domainelement': 'formule'
        },
        'thalassa': {
            'code': 'THA',
            'mapo': 'THA',
            'domainelement': 'thalassa'
        },
        'allseasons': {
            'code': 'ASE',
            'mapo': 'accor',
            'domainelement': 'all-seasons'
        },
        'pullman': {
            'code': 'PUL',
            'mapo': 'PUL',
            'domainelement': 'pullman'
        },
        'adagio': {
            'code': 'ADG',
            'mapo': 'ADG',
            'domainelement': 'adagio'
        },
        'mgallery': {
            'code': 'MGA',
            'mapo': 'MGA',
            'domainelement': 'mgallery'
        }
    };

    return {

        getWebapp: function () {
            var _h = document.location.host, _w;
            for (_w in _webapps) {
                if (_h.indexOf(_webapps[_w].domainelement) > -1) {
                    return _w;
                }
            }
            return 'accorhotels';
        },

        getSiteOrigine: function () {
            var ret = _webapps[FH.context.webapp].code;
            return (ret) ? ret : 'ALL';
        },
        getMapoContext: function () {
            var ret = _webapps[FH.context.webapp].mapo;
            return (ret) ? ret : 'accor';
        }

    };
})();


FH.context.BUSINESSTRAVEL = "businesstravel";
FH.context.MEETINGS = "meetings";
FH.context.TRAVELAGENCIES = "travelagencies";
FH.context.ACCORHOTELS = "accorhotels";
FH.context.SOFITEL = "sofitel";
FH.context.NOVOTEL = "novotel";
FH.context.MERCURE = "mercure";
FH.context.IBIS = "ibis";
FH.context.ETAPHOTEL = "etaphotel";
FH.context.FORMULE1 = "formule1";
FH.context.SUITE = "suite";
FH.context.THALASSA = "thalassa";
FH.context.ALLSEASONS = "allseasons";
FH.context.PULLMAN = "pullman";
FH.context.ADAGIO = "adagio";
FH.context.MGALLERY = "mgallery";


FH.context.webapp = FH.context.getWebapp();
FH.context.isBusinesstravel = (FH.context.webapp == FH.context.BUSINESSTRAVEL);
FH.context.isMeetings = (FH.context.webapp == FH.context.MEETINGS);
FH.context.isTravelagencies = (FH.context.webapp == FH.context.TRAVELAGENCIES);
FH.context.isAccorhotels = (FH.context.webapp == FH.context.ACCORHOTELS);
FH.context.isSofitel = (FH.context.webapp == FH.context.SOFITEL);
FH.context.isNovotel = (FH.context.webapp == FH.context.NOVOTEL);
FH.context.isMercure = (FH.context.webapp == FH.context.MERCURE);
FH.context.isIbis = (FH.context.webapp == FH.context.IBIS);
FH.context.isEtaphotel = (FH.context.webapp == FH.context.ETAPHOTEL);
FH.context.isFormule1 = (FH.context.webapp == FH.context.FORMULE1);
FH.context.isSuite = (FH.context.webapp == FH.context.SUITE);
FH.context.isThalassa = (FH.context.webapp == FH.context.THALASSA);
FH.context.isPullman = (FH.context.webapp == FH.context.PULLMAN);
FH.context.isAllseasons = (FH.context.webapp == FH.context.ALLSEASONS);
FH.context.isAdagio = (FH.context.webapp == FH.context.ADAGIO);
FH.context.isMgallery = (FH.context.webapp == FH.context.MGALLERY);


/**
Gestion liens maporama.
*/

FH.mapo = (
    function () {

        function _load(_rids) {
            var mapXml = (FH.context.isMeetings || FH.context.isTravelagencies || FH.context.isBusinesstravel) ? 'resa2010pro' : 'common';
            var mapUrl = 'http://accor.maporama.com/idl/' + FH.context.getMapoContext() + '/process.aspx?Lang=' + FH.gb2en(FH.lang) + '&xsl=lh&xml=' + mapXml + '&siteOrigine=' + FH.context.getSiteOrigine() + '&Search=CFH&PB_list=' + _rids;
            jQuery('#iframemapo').attr("src", mapUrl);
        }

        function _create(div) {
            if (FH.mapo.created) {
                return;
            }
            FH.mapo.created = true;
            var i = '<div id="conteneur_mapo">';
            i += '<div id="intitule">';
            i += '<h1><img src="/imagerie/reservation/pict_monde.gif"/><img id="titrecarte" src="/' + FH.imgpath + '/images/reservation/titre_carte.gif"><div id="txt_cliquez"><img src="/imagerie/reservation/fleche_mapo.gif" id="fleche_mapo"/><a >' + I18N._('fh', 'Click here to move to move the map') + '</a></div><a  id="lnk_closemapo"><img src="/imagerie/reservation/pict_clot.gif" id="bt_fermer"/></a></h1>';
            i += '<div id="contiframe">';
            i += '<iframe id="iframemapo" name="iframemapo" scrolling="no" frameborder="0"/>';
            i += '</div>';
            i += '</div>';
            i += '</div>';
            jQuery(div).after(i);
            jQuery('#conteneur_mapo').draggable().hide();
            jQuery('#lnk_closemapo').click(function (e) {
                e.preventDefault();
                e.stopPropagation();
                FH.mapo.toggle();
            });
        }

        return {
            created: false,
            rids: FH.rid,
            toggle: function (_rids) {

                var _conteneur = jQuery('#conteneur_mapo');
                _load(_rids);
                _conteneur.toggle();

            },

            closeAvailDates: function () {
                jQuery("#lnk_map").click(function () {
                    if (jQuery(".popin-calendar").length && jQuery.browser.msie) {
                        jQuery(".popin-calendar .ui-dialog-titlebar a.ui-dialog-titlebar-close").click();
                    }
                });
            },

            init_map: function (lnk, rids, div) {
                jQuery(lnk).attr("href", "#");
                var d = jQuery(div);
                _create(div);

                if (!d) {
                    return;
                }
                if (!lnk) {
                    lnk = jQuery(div);
                }

                jQuery(lnk).click(function (e) {
                    e.preventDefault();
                    e.stopPropagation();
                    FH.mapo.toggle(rids);
                });

                return lnk;
            },

            init_iti: function (div) {
                jQuery(div).attr('href', 'http://accor.maporama.com/idl/' + FH.context.getMapoContext() + '/Partner.aspx?xml=common&xsl=driveme&PBC_1_config=2&PBC_1_list=' + FH.rid + '&Lang=' + FH.imgpath + '&SiteOrigine=' + FH.context.getSiteOrigine());
            }


        };
    }
)();



/**
Gestion de la galerie photo.
*/
FH.gallery = {

    display	: function (div) {
        var so = new SWFObject("/flash/fh/gallery.swf", "galeriePhotos", "632", "360", "8", "#ffffff");
        so.addParam("quality", "best");
        so.addParam("allowScriptAccess", "true");
        so.addParam("wmode", "transparent");
        so.addVariable("lang", FH.lang);
        so.addVariable("rid", FH.rid);
        so.addVariable("mark", FH.mark);
        so.addVariable("brand", FH.brand);
        so.write(document.getElementById(div));

    }

};

/**
Gestion du changmeent d'ipix.
*/
FH.ipix = {

    display	: function (ipixName) {

        var inner  = '<applet name="IpixViewer" height="300" width="400" align="baseline" archive="/java/IpixViewer.jar" code="IpixViewer.class">';
        inner +=		'<param name="Toolbar"   value="large">';
        inner +=   '<param name="SpinStyle" value="flat">';
        inner +=   '<param name="URL"       value="/photos/' + ipixName + '">';
        inner += '</applet>';

        e = jQuery('#virtual-tour').get(0);
        e.removeChild(e.childNodes[0]);// '.remove' '.inner("")' throws errors
        jQuery('#virtual-tour').html(inner);

    }

};

FH.popup = {

    init: function () {
        jQuery(".popup").each(function () {
            var a = jQuery(this);
            jQuery(a.attr("class").split(' ')).each(
                function (i, c) {
                    var xy;
                    if (null != (xy = /p(\d+)-(\d+)(r?)(s?)/i.exec(c))) {
                        var res = (xy[3] == 'r') ? "yes" : "no";
                        var scrol = (xy[4] == 's') ? "yes" : "no";
                        a.click(function (e) {
                            e.preventDefault();
                            e.stopPropagation();
                            window.open(a.attr('href'), 'po' + c.replace('-', '_'), 'scrollbars=' + scrol + ',resizable=' + res + ',width=' + xy[1] + ',height=' + xy[2]);
                        });
                    }
                }
            );
        });
    }

};


FH.sendtofriend = {

    init: function () {
        var lnk = "/" + FH.imgpath + "/send-to-friend/send-to-friend.html#hotelId=" + FH.rid + "&hotelName=" + FH.name + "&brand=" + FH.brand;
        jQuery('#sendtofriend a').attr('href', lnk);
    },
    close: function () {
        jQuery('.ui-dialog-titlebar-close').click();
    }
};

FH.availabilities = {

    init: function () {
        var lnk = "/" + FH.imgpath + "/booking/dispo-calendar.shtml?tarsCode=" + FH.rid + "&lengthOfStay=1";
        jQuery('#lnk_avail').attr('href', lnk);

        jQuery("#lnk_avail").click(function () {
            if ((jQuery("#conteneur_mapo").css("display") != "none") && jQuery.browser.msie) {
                document.getElementById("bt_fermer").click();
            }
        });

    }
};

FH.currencies = (
    function () {

        function _adjust(prices) {
            prices = prices || jQuery(".price");
            //changement d'ordre
            prices.each(
                function () {
                    var c = jQuery(this).find(".currency").html();
                    var cur = jQuery(this).find(".currency");
                    var amo = jQuery(this).find(".amount");
                    var origCur = jQuery(this).find(".origCurrency");
                    var origAmo = jQuery(this).find(".origAmount");

                    if (c == "USD" || c == "GBP" || c == "JPY" || c == "BRL" || (c == "EUR" && FH.lang == "nl")) {
                        jQuery(this).empty().append(cur).append("&nbsp;").append(amo).append(origAmo).append(origCur);
                    } else {
                        jQuery(this).empty().append(amo).append("&nbsp;").append(cur).append(origAmo).append(origCur);
                    }
                    //changement de signe
                    cur.html(cur.html().replace('EUR', "&euro;").replace('USD', "US$").replace('GBP', "&pound;").replace('JPY', "&yen;").replace('BRL', "R$"));
                }
            );
        }

        function _svg(prices) {
            (prices || jQuery(".price")).each(
                function () {
                    var cur = jQuery(this).find(".currency");
                    var amo = jQuery(this).find(".amount");
                    jQuery(this).empty().append(amo).append("&nbsp;").append(cur)
                    .append(amo.clone().removeClass('amount').addClass('origAmount').hide())
                    .append(cur.clone().removeClass('currency').addClass('origCurrency').hide());
                }
            );
        }

        function _revert(prices) {
            prices = prices || jQuery(".price");
            prices.each(
                function () {

                    jQuery(this).find(".currency").html(jQuery(this).find(".origCurrency").html());
                    jQuery(this).find(".amount").html(jQuery(this).find(".origAmount").html());
                }
            );
        }

        function _convert(rates, currency, prices) {
            prices = prices || jQuery(".price");
            prices.each(
                function () {
                    var cur = jQuery(this).find(".currency");
                    var amo = jQuery(this).find(".amount");
                    var origCur = jQuery(this).find(".origCurrency").html();
                    var origAmo = jQuery(this).find(".origAmount").html();
                    if (origCur != '---' && rates[currency] && rates[origCur] && rates[origCur] != 0) {
                        cur.html(currency);
                        amo.html((origAmo / (rates[currency] / rates[origCur])).toFixed(2));
                    } else {
                        _revert(jQuery(this));
                    }
                    if (origCur == currency) {
                        _revert(jQuery(this)); /*evite .00*/
                    }
                }
            );
        }

        return {
            init: function (prices) {
                prices = prices || jQuery(".price");
                _svg(prices);
                _adjust(prices);
            },

            convert: function (rates, currency, prices) {
                prices = prices || jQuery(".price");
                _convert(rates, currency, prices);
                _adjust(prices);
            },

            revert: function (prices) {
                prices = prices || jQuery(".price");
                _revert(prices);
                _adjust(prices);

            }
        };
    }
)();


FH.popins = (

    function () {

        var _currentPopinIframe, _popinsOpeningActions = {
            search: function (popin) {
                popin.find('a.cancel').click(function (e) {
                    e.preventDefault();
                    popin.dialog('close');
                });
            }
        };

        var _popinsClosingActions = {
            search: function (popin) {
                popin.find('a.cancel').unbind('click');
            }
        };

        var _opened = null;

        function _attachLinks(listPopins) {
            listPopins = listPopins || jQuery(".popin");
            //bind on link with class "popin"
            listPopins.each(function (i, elm) {
                //get all popin configs informations
                jQuery(elm.className.split(/\s+/)).each(function (i, cls) {
                    if (cls.indexOf('p-') === 0) {
                        cls += '-';

                        var datas = {
                            modal: cls.indexOf('-m-') > -1,
                            drag: cls.indexOf('-d-') > -1,
                            redim: cls.indexOf('-r-') > -1,
                            iframe: cls.indexOf('-i-') > -1,
                            scrollable: cls.indexOf('-s-') > -1 ? "auto" : "no",
                            ajax: cls.indexOf('-a-') > -1,
                            width: /w:\d+/.test(cls) ? parseInt(cls.match(/w:(\d+)/)[1], 10) : null,
                            height: /h:\d+/.test(cls) ? parseInt(cls.match(/h:(\d+)/)[1], 10) : null,
                            type: cls.match(/type:([^\s-]+)/)[1],
                            ref: cls.match(/ref:([^\s-]+)/)[1]
                        };

                        if (datas.iframe) {
                            datas.redim = false;
                        }
                        datas.url = datas.iframe || datas.ajax ? elm.href : null;
                        //set data popin at this element
                        jQuery(elm).data('popin', datas).click(function (e) {

                            e.preventDefault();

                            var datas = jQuery(this).data('popin');
                            //if url generated by JS
                            if (datas.url != jQuery(this).attr('href')) {
                                datas.url = jQuery(this).attr('href');
                            }

                            // popin declaration
                            if (_isOpen(datas.ref)) {
                                jQuery('div.' + datas.ref).dialog('open');
                            } else {
                                if (datas.ajax) {
                                    jQuery.get(datas.url, function (response) {
                                        _openPopin(jQuery(response).appendTo('#page'), datas);
                                    });
                                } else if (datas.iframe) {
                                    currentPopinIframe = jQuery('<div class="popin' + datas.ref + '"><iframe allowtransparency="true" width="' + datas.width + '" class="popinFhContent" src="about:blank" frameborder="0" scrolling="' + datas.scrollable + '"></iframe></div>').appendTo(document.body).data('popin', datas);
                                    _openPopin(currentPopinIframe, datas);
                                } else {
                                    _openPopin(jQuery('div.' + datas.ref).data('popin', datas), datas);
                                }
                            }
                        });
                    }
                });
            });
        }

        function _isIE6() {
            return (jQuery.browser.msie && jQuery.browser.version == "6.0") ? true : false;
        }

        function _setOpen(ref) {
            _opened['div.' + ref] = true;
        }

        function _setClose(ref) {
            _opened['div.' + ref] = false;
        }

        function _isOpen(ref) {
            return _opened['div.' + ref] === true;
        }

        //set and open jQuery UI dialog
        function _openPopin(popin, datas) {
            popin.dialog({
                modal: datas.modal,
                draggable: datas.drag,
                resizable: datas.redim,
                width: datas.width,
                height: datas.height || 'auto',
                create: function (e) {
                    if (datas.iframe) {//mise en place de la src de l\'iframe
                        jQuery(".popin" + datas.ref + " iframe.popinFhContent").attr('src', datas.url);
                    }
                },
                open: function (e) {
                    scrollTo(0, jQuery("body"));
                    popin.parent().addClass('popin-' + datas.type).addClass('popin-' + datas.ref);
                    popin.dialog("option", "closeText", I18N._('popup', 'Close'));

                    if (_popinsOpeningActions[datas.ref]) {
                        _popinsOpeningActions[datas.ref](popin);
                    }
                    //Explorer 6 hide select
                    if (_isIE6() && datas.modal) {
                        jQuery('.contentContainer select').hide();
                    }
                    _setOpen(datas.ref);
                },
                close: function (e) {
                    if (_popinsClosingActions[datas.ref]) {
                        _popinsClosingActions[datas.ref](popin);
                    }
                    popin.dialog('destroy');
                    if (datas.iframe || datas.ajax) {
                        popin.remove();
                    }
                    _setClose(datas.ref);

                    //Explorer 6 show select
                    if (_isIE6() && datas.modal) {
                        jQuery('.contentContainer select').show();
                    }
                }
            });
        }


        return {
            init: function () {
                _opened = {};
                _attachLinks();
            },

            resizePopinIframe: function (h) {
                if (_currentPopinIframe && _currentPopinIframe.length) {
                    _currentPopinIframe.find('iframe').height(h);
                    _currentPopinIframe.dialog('option', 'position', 'center');
                }
            }
        };
    }
)();

