MJL.event.add(window, "load", function() {
    MJL.enable.styleSwitcher("styleSwitcher");
    MJL.enable.tab("tabs");
    MJL.enable.flash("flash");
    MJL.enable.heightEqualizer("equalize");
    MJL.enable.heightEqualizer("equalize2col", {groupBy : 2});
    MJL.enable.rollover("roll", {
        disable   : "unroll",
        active    : "active",
        switchers : {
            // 接尾辞 "_c" が付与されている場合は削除
            // (グローバルナビゲーション用)
            on  : {cond : /(?:_c)?(\.[^\.]+)$/, replace : "_o$1"},
            off : {cond : "",                   replace : ""}
        }
    });
}, false);

// BUG IE6: 背景画像がキャッシュされない問題を修正
try { document.execCommand("BackgroundImageCache", false, true); } catch(e) {}


// ----------------------------------------------------------------------------
// not MJL Script
// ----------------------------------------------------------------------------
'jQuery' in window && $(function() {
    // -------------------------------------------------
    // グローバルナビゲーション制御
    // -------------------------------------------------
    (function() {
        var bodyId       = $(document.body).attr('id'),
            // img 要素 src 属性置換条件
            condSrc      = /(\.[a-z]{3})$/,
            // img 要素から category を抽出する置換条件
            condCategory = /(^.+?ng_.+?_)(.+?)(_[0-9]{2}\.gif$)/;
        $('#navGlobal img').each(function(){
            var obj      = $(this),
                category = obj.attr('src').replace(condCategory, '$2'),
                ret      = true;
            // 一致するメインメニューがあればアクティブ化して終了
            if (bodyId === category) {
                obj.attr(
                    'src', obj.attr('src').replace(condSrc, '_c$1')
                ).parents(
                    'li:not(:has(ul))' // ドロップダウンメニュー無しなら
                ).addClass('unroll');  // ロールオーバー無効化
                ret = false;
            }
            // 何もなければ次をチェック
            return ret;
        });
    })();

    // -------------------------------------------------
    // ドロップダウンメニュー制御
    // -------------------------------------------------
    (function() {
        var doc      = $(document),
            idPrefix = '.MGH_DROPDOWN_MENU_'+(new Date()).getTime(),
            active   = 'active';
        // 複数対象の実装を考慮
        $('#ngHotels, #hotelList li.item, #nuHotels').each(function(n) {
            var root     = $(this),                // 基点
                img      = root.find('> a > img'), // ロールオーバー対象
                bindName = 'focusin'+idPrefix+n;   // 特殊 focusin 用イベント名
            // 各種イベントリスナ群
            function show() { // メニュー表示
                if (!root.hasClass(active)) {
                    root.addClass(active);
                    // MJL ロールオーバー アクティブ化
                    img.each(function() {
                        MJL.event.dispatch(this, 'mouseover');
                    });
                }
            }
            function hide() { // メニュー非表示
                if (root.hasClass(active)) {
                    root.removeClass(active);
                    // MJL ロールオーバー 非アクティブ化
                    img.each(function() {
                        MJL.event.dispatch(this, 'mouseout');
                    });
                }
            }
            // イベント設定
            root.focusin(show).focusout(function() { // キーボード制御
                // 基点でのみ影響が及ぶように、イベントの設定は都度実行
                // 基点からフォーカスが外れた場合
                doc.bind(bindName, function(event) {
                    // 基点を含まない要素ノードの focus を確保
                    if (root.has(event.target).length < 1) {
                        hide.apply(this, arguments);
                    }
                    doc.unbind(bindName);
                });
            }).mouseenter(show).mouseleave(hide);    // マウスポインタ制御
        });
    })();

    // -------------------------------------------------
    // フック用クラス追加
    // -------------------------------------------------
    $('.seasonCalendar tr th:last-child, .seasonCalendar tr td:last-child, .listNews01 li:last-child, .listNews02 li:last-child, .listLinkImage01 li:last-child, .listLinkImage02 li:last-child, .col2 > div.line:last-child, .imageDescription01 .line > .item:last-child').each(function(){
        $(this).addClass('lastChild');
    });
    $('.navPage03 li:nth-child(3n+3)').addClass('lastChild');

    // -------------------------------------------------
    // ローカルナビゲーション制御
    // -------------------------------------------------
    (function() {
        var targets   = $('#navLocal > ul a'),
            condIndex = /\/index\.html?/, // index ファイル名除去条件
            condDel   = /[^/]*\/?$/,
            // URI 分割条件
            // based on: http://search.cpan.org/perldoc?URI::Split
            condURI   = /(?:([^:\/?#]+):)?(?:\/\/([^\/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?/,
            path      = location.pathname.replace(condIndex, '/'),
            checks    = [path],
            nchecks, c, check, target;

        // 文字列末尾から 1 ディレクトリずつ削り、URL を収集
        while (path && '/' !== path) {
            path = path.replace(condDel, '');
            checks.push(path);
        }
        nchecks = checks.length;

        // URL と href 属性値の一致を判定
        for (c = 0; c < nchecks; c++) {
            check  = checks[c];
            target = targets.filter(function(){
                return check === (
                    // BUG Trident: this.pathname は href="/foo" の時
                    //              "foo" を返すことがある
                    //                -> href 属性値を手動パース
                    (condURI.exec(this.href) || [])[3] || ''
                ).replace(condIndex, '/');
            });
            if (0 < target.length) {
                target.addClass('current')        // 対象要素を強調
                      .closest('li')              // 祖先で最初の li 要素と
                      .parents('li').andSelf()    // 更に祖先の li 要素をあわせ
                      .addClass('selected').end() // 選択状態を定義し
                      // 最初を除く祖先の li 要素だけに
                      .find('> a').addClass('parentMenu'); // 親メニューを定義
                break;
            }
        }
    })();

    // -------------------------------------------------
    // listLinkImage03
    // -------------------------------------------------
    $('.listLinkImage03, .listLinkImage04').each(function(){
        var obj = $(this);
        $('.item:nth-child(4n+2)', obj).addClass('check');
        $('.item:nth-child(4n+3)', obj).addClass('check');
    });

    // -------------------------------------------------
    // 画像とテキストの横並び
    // -------------------------------------------------
    $('.imageParallel, .imageFloat').each(function(){
        var obj = $(this);
        var imgWidth = $('div.image p.image img', obj).attr('width');
        if (imgWidth > 0) {
        imgWidth = imgWidth + 4;    // 数字は画像の枠線の領域
        $('div.image', obj).css('width', imgWidth);
        }
    });

    // -------------------------------------------------
    // OS&ブラウザ判別
    // -------------------------------------------------
    (function() {
        var agent = navigator.userAgent;
        var macOpera;
        if (agent.indexOf('Mac') >= 0 && agent.indexOf('Opera') >= 0) {
            macOpera = true;
        }
        if(macOpera){
            $('#areaHeader').css('margin-top', '-21px');
        }
    })();

    // -------------------------------------------------
    // マップ表示 切替
    // -------------------------------------------------
    $('#around').each(function() {
        var root     = $(this),    // 基点要素
            offClass = 'panelOff', // 非表示有効化 class 属性値
            // マークアップ
            wrap = '<p class="switch"></p>', // ボタンの親要素
            btn  = {                         // 表示・非表示ボタン
                on   : '<input type="image" src="/shared/images/common/label_map_panel_on.gif" alt="施設名を表示" />',
                off  : '<input type="image" src="/shared/images/common/label_map_panel_off.gif" alt="施設名を非表示" />'
            },
            // jQuery オブジェクト
            on = $(btn.on).click(function() {   // 表示ボタン
                root.removeClass(offClass);
                off.trigger('focus'); // 連続切替ができるようにする
                return false;
            }),
            off = $(btn.off).click(function() { // 非表示ボタン
                root.addClass(offClass);
                on.trigger('focus'); // 連続切替ができるようにする
                return false;
            });
        // 追加
        $('> .map', root).prepend($(wrap).append(on));
        $('> .panel', root).prepend($(wrap).append(off));
    });

    // -------------------------------------------------
    // 予約サイト遷移前 確認メッセージ
    // -------------------------------------------------
    (function() {
        // ロケール別 表示文言
        var texts   = {
                'ja'    : 'ここから先は予約サイト「$1」へ移動します。',
                'en-US' : 'Moving to "$1" for Room Reservation.',
                'en'    : 'Moving to "$1" for Room Reservation.',
                'zh'    : 'Moving to "$1" for Room Reservation.'
            },
            // 部分 URI 取得 正規表現
            // http://foo.com:80/bar/baz/index.html?abc#def
            //   -> http://foo.com:80/bar/
            cond    = /((?:[^:/?#]+:)?(?:\/\/[^\/?#]*)?\/[^\/?#]*\/)/,
            // 部分 URI 置換用 正規表現
            condF   = /^(.+)$/,
            // 既定のロケール
            defLang = 'ja',
            // 文書のロケール (文言切替)
            lang    = document.documentElement.lang || defLang;
        // 対象要素チェック
        function check(event) {
            var node = event.currentTarget,
                uri  = node.action || node.href,
                ret  = true,
                domain;
            if (uri) {
                domain = (cond.exec(uri) || [])[1];
                if (domain) {
                    // キャンセルした場合のみ false (未遷移)
                    ret = window.confirm(domain.replace(
                        condF, texts[lang in texts ? lang : defLang]
                    ));
                }
            }
            return ret; // チェック不能なら true (通常遷移)
        }
        // 対象要素にイベント設定
        /*
				$('.confirmJump').filter('a').click(check).end()
                         .find('a').click(check).end()
                         .filter('form').submit(check).end()
                         .find('form').click(check).end();
				*/
    })();

    // -------------------------------------------------
    // モーダルビューア
    // -------------------------------------------------
    (function() {
        var body   = $(document.body),
            anchor = $('.modalView a, a.modalView'), // 対象要素
            global = $('body.enableModalViewAPI'),   // 対象フック
            // External Interface 経由アクセス用関数の設定
            types  = {
                // 関数名           : 参照先
                'showModalViewCM'   : '/cm/',
                'showModalViewHosp' : '/omotenashi/'
            },
            // iframe キャッシュの是非 (是: true, 非: false)
            cache   = false,
            // ロード済 iframe キャッシュ
            iframes = {
                // 'src 属性値' : jQuery オブジェクト, ...
            },
            // 前に表示した iframe の src 属性値
            before  = '',
            // IE6 判定
            ie6     = $.browser.msie && $.browser.version < 7,
            t, dialog, select;
        // 対象要素・フックが存在する場合のみ実行
        if (0 < anchor.length || 0 < global.length) {
            // jQuery UI 動的ロード
            if (!('ui' in $.fn)) {
                $('head').append('<script type="text/javascript" src="/shared/js/jquery-ui.js"><\/script>');
            }
            // BUG IE6: select 要素は z-index 無効
            if (ie6) {
                select = $('select'); // 該当する場合のみ収集
            }
            // jQuery UI Dialog オブジェクト
            dialog = $(
                '<div id="modal-view"></div>'
            ).hide().appendTo(body).dialog({
                autoOpen  : false,
                draggable : false,
                modal     : true,
                resizable : false,
                width     : 'auto',
                zIndex    : 21000,
                // フェイドイン・フェイドアウト効果設定
                open      : function(event, ui) {
                    // BUG IE6: select 要素は z-index 無効
                    //          show()/hide() では reflow がキツいので表示のみ
                    ie6 && select.css('visibility', 'hidden');
                    $(event.target.parentNode).hide().fadeIn(1000);
                },
                close : function(event, ui) {
                    $(event.target.parentNode).show().fadeOut(250, function() {
                        // DOM ツリーから完全に削除
                        // 一旦削除しないと再生中のコンテンツがバックグラウンド
                        // で再生され続けてしまう
                        iframes[before].remove();
                        // キャッシュ不要なら明示的に削除
                        if (!cache) {
                            iframes[before] = null;
                        }
                        // BUG IE6: select 要素は z-index 無効
                        //          ダイアログが消失した後に表示させ、
                        //          重複しないようにする
                        ie6 && select.css('visibility', '');
                    });
                }
            });
            // オーバレイ click で閉じる
            $('.ui-widget-overlay').live('click', function() {
                // jQuery UI のオーバレイは都度 DOM ツリーに出し入れされる
                // すると IE 等ではイベントハンドラの登録が消失する
                // よって live event で監視させる
                dialog.dialog('close');
            });
            // ダイアログ内コンテンツを設定し、ダイアログ表示
            function active(uri) {
                // body 要素から移管
                dialog.append(iframes[uri]).dialog('open');
                before = uri;
            }
            // ダイアログ表示
            function show(uri) {
                var ret = true;
                // イベントリスナモード
                if ('string' !== typeof uri) {
                    uri = this.href;
                }
                // 通常フロー
                if (uri) {
                    iframe = iframes[uri];
                    if (iframe) { // iframe キャッシュ済
                        active(uri);
                    } else {      // iframe 未キャッシュ
                        iframes[uri] = iframe = $(
                            '<iframe class="modal-view-draw-area" frameborder="0"></iframe>'
                        ).attr('src', uri).load(function() {
                            // リフロー時に load イベントが発生するパターンが
                            // あるため、確実に1回だけ実行させる
                            iframe.unbind('load');
                            // サイズはコンテンツから自動取得
                            var doc = $(this.contentWindow.document);
                            iframe.css({
                                width  : doc.width(),
                                height : doc.height()
                            });
                            // すべて完了したら表示
                            active(uri);
                        // iframe は DOM ツリーに追加しないとコンテンツロード
                        // しないため、まずは突っ込む
                        }).appendTo(body);
                    }
                    ret = false; // cancelBubble, preventDefault させる
                }
                return ret;
            }
            // 対象要素にイベントセット
            anchor.click(show);
            // 同時にグローバルオブジェクトへ External Interface 経由アクセス用
            // 関数を定義
            for (t in types) {
                window[t] = (function(type) {
                    return function() {
                        show(type);
                    };
                })(types[t]);
            }
        }
    })();
});


// ----------------------------------------------------------------------------
// MJL Extension
// ----------------------------------------------------------------------------
(function() {
    // GET リクエスト パラメタ取得
    var getParams = function() {
        var strs  = (location.search || '').substring(1).split('&'), // ? 削除
            nstrs = strs.length,
            ret   = {},
            s, tmp;
        for (s = 0; s < nstrs; s++) {
            tmp = strs[s].split('=');
            ret[decodeURIComponent(tmp[0])] = decodeURIComponent(tmp[1]);
        }
        getParams = function() {
            return ret;
        };
        return ret;
    }

    // 最優先タブ アクティブ ID を URI 内パラメタから取得
    MJL.Tab.prototype._ACTIVE_ID_RULES.unshift(function() {
        return getParams().tab || "";
    });
})();

