MJL.event.add(window, "load", function() {
    // 画像とテキスト (based on jQuery)
    'jQuery' in window && (function($) {
        jQuery.noConflict();
        // 画像とテキストの並列処理を行う関数を返す高階関数
        function getImgParallelStyler(side, space) {
            space = isNaN(space) ? 15 : space; // カラム間の空白 (単位:px)
            return function() {
                // img 要素を複数格納する要素
                var block = $('div.image:first-child', this),
                // 対象 img 要素群のうち、最大の横幅 (単位:px)
                    width = Math.max.apply(Math, $.makeArray(
                        block.find('p.image img').map(function() {
                            return $(this).width();
                        })
                    ));
                block.css('width', width+'px'); // 画像幅を強制
                $('div.column', this).css(      // 別カラムの margin を調整
                    'margin-'+side, block.outerWidth()+space+'px'
                );
            };
        }
        // 実行
        $('.image-parallel.image-l').each(getImgParallelStyler('left'));
        $('.image-parallel.image-r').each(getImgParallelStyler('right'));
    })(jQuery);

    MJL.enable.flash("flash");
    MJL.enable.window("popup", {width : 800, height : 600});
    MJL.enable.tab("tabs");
    MJL.enable.styleSwitcher("styleSwitcher");
    MJL.enable.rollover("roll", {disable : "unroll", active : "active"});
    MJL.enable.heightEqualizer("equalizer");
    MJL.enable.heightEqualizer("equalizer-2", {groupBy : 2});
    MJL.enable.heightEqualizer("equalizer-3", {groupBy : 3});
    MJL.enable.heightEqualizer("equalizer-4", {groupBy : 4});
    MJL.enable.heightEqualizer("equalizer-5", {groupBy : 5});
    MJL.enable.heightEqualizer("equalizer-inner-box", {
        collect : function(parent) {
            return MJL.getElementsByClassName(parent, "equalizer-inner");
        }
    });
    MJL.enable.heightEqualizer("nav-local-main", {
        collect : function(parent) {
            return MJL.convArray(parent.getElementsByTagName("span"));
        }
    });
    MJL.enable.heightEqualizer("list-index-02", {
        collect : function(parent) {
            return MJL.getElementsByClassName(parent, "box-inner-01");
        }
    });
    MJL.enable.heightEqualizer("list-index-04", {
        collect : function(parent) {
            return MJL.getElementsByClassName(parent, "hdg-list-index-04");
        }
    });
    MJL.enable.heightEqualizer("list-index-04", {
        collect : function(parent) {
            return MJL.getElementsByClassName(parent, "box-inner-01");
        }
    });
    MJL.enable.heightEqualizer("merit-list-01", {
        collect : function(parent) {
            return MJL.getElementsByClassName(parent, "doc-catchcopy-01");
        }
    });
    MJL.enable.heightEqualizer("merit-list-01", {
        collect : function(parent) {
            return MJL.getElementsByClassName(parent, "box-inner-01");
        }
    });
    MJL.enable.heightEqualizer("merit-list-02", {
        collect : function(parent) {
            return MJL.getElementsByClassName(parent, "doc-catchcopy-01");
        }
    });
    MJL.enable.heightEqualizer("merit-list-02", {
        collect : function(parent) {
            return MJL.getElementsByClassName(parent, "box-inner-02");
        }
    });
    MJL.enable.heightEqualizer("flow-list-01", {
        collect : function(parent) {
            return MJL.getElementsByClassName(parent, "box-inner-01");
        }
    });
    MJL.enable.heightEqualizer("flow-list-02", {
        collect : function(parent) {
            return MJL.getElementsByClassName(parent, "box-inner-01");
        }
    });
    MJL.enable.heightEqualizer("flow-list-03", {
        collect : function(parent) {
            return MJL.getElementsByClassName(parent, "box-inner-01");
        }
    });
    MJL.enable.heightEqualizer("flow-list-04", {
        collect : function(parent) {
            return MJL.getElementsByClassName(parent, "box-inner-01");
        }
    });
}, false);


// ----------------------------------------------------------------------------
// Extend Scripts
// ----------------------------------------------------------------------------
(function() {
    // GET リクエスト パラメタ取得
    var getParam = 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] || '');
        }
        getParam = function() {
            return ret;
        };
        return ret;
    };

    // ------------------------------------------------------------------------
    // Non-MJL
    // ------------------------------------------------------------------------
    'jQuery' in window && (function($) {
        jQuery.noConflict();
        // ----------------------------
        // グローバルナビゲーション アクティブ化
        // ----------------------------
        window.setNav = function() {
            $('#nav-global').each(function() {
                // body 要素の class 属性値からカテゴリ情報を取得
                // 例: <body class="category-top-campaign">
                //     メイン: "top"
                //     サブ:   "campaign"
                var category = (document.body.className || '').match(
                        //                  メイン       サブ
                        /(?:^|\s)category-([^\s-]+)(?:-([^\s]+))?(?:\s|$)/
                    ) || [],
                    main     = category[1] || '', // メインカテゴリ
                    sub      = category[2] || '', // サブカテゴリ
                    imgCond, imgRep, root, subRoot;
                // カテゴリが適切に取得できたら実行
                if (main) {
                    // アクティブ画像
                    imgCond = /(\.[^\.]+)$/;                // 置換条件
                    imgRep  = '_o$1';                       // 置換文字列
                    // 対象要素
                    root    = $(this);                      // 基点要素
                    subRoot = root.find('.nav-subsection'); // サブカテゴリ
                    // メインカテゴリ アクティブ化
                    root.find(
                        '.nav-section li.nav-section-'+main+''
                    ).addClass('selected').find('img').each(function() {
                        // 画像アクティブ化
                        this.src = this.src.replace(imgCond, imgRep);
                    });
                    // サブカテゴリ アクティブ化
                    subRoot.find(        // 無関係のサブカテゴリは非表示
                        'dd:not(.nav-subsection-'+main+')'
                    ).hide();
                    sub && subRoot.find( // サブカテゴリをアクティブ化
                        'li.nav-subsection-'+main+'-'+sub
                    ).addClass('selected');
                }
            });
        };


        $(function() {
            // スタイルスイッチャ挿入
            $('#font-control').prepend('<dl><dt><img src="/shared/images/str-aside/font-img-01.gif" alt="文字サイズ" width="63" height="12" /></dt><dd><ul class="styleSwitcher roll"><li><a href="#font-s"><img src="/shared/images/str-aside/font-btn-s.gif" alt="小" width="22" height="22" /></a></li><li><a href="#font-m"><img src="/shared/images/str-aside/font-btn-m.gif" alt="中" width="21" height="22" /></a></li><li><a href="#font-l"><img src="/shared/images/str-aside/font-btn-l.gif" alt="大" width="21" height="22" /></a></li></ul></dd></dl>');
            // ストライプテーブル
            $('table.stripe > tbody > tr:nth-child(2n)').addClass('even');

            // ------------------------
            // 新規ウインドウ用「閉じる」ボタン挿入
            // ------------------------
            $('body.insert-btn-01 #str-main').append(
                $('<p class="doc-align-c roll"></p>').append(
                    $('<input type="image" src="/shared/images/contents-mod/btn-close-01.gif" alt="閉じる" />').click(function() {
                        window.close();
                        return false;
                    })
                )
            );

            // ------------------------
            // ページ内遷移 スクロールアニメーション
            // ------------------------
            (function() {
                // スクロールスピード
                var duration   = 500,
                    // スクロール対象要素
                    //   * Standard モード: ルートノード (html 要素)
                    //   * Quirks モード:   body 要素
                    scrollRoot = $(
                        // BUG Webkit: レンダリングモードに関わらず
                        //             body 要素を使わなければならない
                        MJL.ua.webkit ? document.body : document.documentElement
                    ),
                    // ハッシュ先頭の '#' 削除条件
                    hashCond   = /^#/;
                $('.nav-pagetop a').click(function() {
                    var node   = this,
                        hash   = node.hash.replace(hashCond, ''),
                        target = $('#'+hash),
                        ret    = true,
                        offset;
                    if (0 < target.length) {
                        offset = target.offset();
                        scrollRoot.animate({
                            scrollTop  : offset.top,
                            scrollLeft : offset.left
                        }, duration, function() {
                            window.location.hash = node.hash;
                        });
                        ret = false;
                    }
                    return ret;
                });
            })();

            // ------------------------
            // 中間ページ
            // ------------------------
            $('#link-internal, #link-external').each(function() {
                // 自動遷移までの時間 (単位: ms)
                var interval = 3000,
                    param    = getParam(),
                    uri      = param.uri;
                // 与 URI チェック
                if (!/^(?:\/|https?:\/\/)/.test(uri)) {
                    uri = "";
                }
                // 各種設定
                $('#page-name').empty().text(param.name); // ページ名表示
                $('#page-link').attr('href', uri);        // 遷移先設定
                $('#page-close').click(function() {       // 「閉じる」ボタン
                    window.close();
                    return false;
                });
                // 指定時間後に自動遷移
                if (uri && !('noref' in param)) {
                    setTimeout(function() {
                        window.location.href = uri;
                    }, interval);
                }
            // ------------------------
            // ログイン＆中間ページ＆元ウインドウ遷移制御
            // ------------------------
            // ログイン遷移制御設定 JSON ファイル データ構造:
            //   cond
            //     対象 a 要素の href 属性値。文字列。先頭からマッチする。
            //     例: "http://example.com/" が指定されている場合:
            //         マッチする: 
            //           * "http://example.com/"
            //           * "http://example.com/foo/"
            //           * "http://example.com/foo/index.html"
            //         マッチしない:
            //           * "http://example.com"      (末尾のスラッシュがない)
            //           * "http://www.example.com/" ("www." が挟まっている)
            //   uri
            //     遷移先の URI。文字列。
            //
            // JSON ファイル例 (先頭にある条件が最優先で処理される):
            // [
            //     {
            //         "cond" : "http://example.com/foo/",
            //         "uri"  : "http://example.com/bar/"
            //     },
            //     {
            //         "cond" : "http://example.com/test.html",
            //         "uri"  : "http://example.com/baz/error.html"
            //     }
            // ]
            // ------------------------
            }).length > 0 || (function() {
                var cond   = /([^\/?#]+)\//,
                    windir = getFirstDir(window.location.pathname),
                    data   = null,
                    ndata  = 0;
                // 設定ファイル ロード
                function load() {
                    $.ajax({
                        url      : '/shared/js/login.json',
                        timeout  : 10000,
                        dataType : 'json',
                        async    : false,  // 遷移直前に実行するため同期が必須
                        cache    : false,  // 即反映が原則
                        success  : function(origin) {
                            data  = origin;
                            ndata = data.length || 0;
                            // 正規表現に変換 (文字列先頭からのマッチのみ)
                            for (var d = 0; d < ndata; d++) {
                                data[d].cond = new RegExp('^'+data[d].cond);
                            }
                        }
                    });
                }
                // root 直下のディレクトリ名だけ取得
                function getFirstDir(path) {
                    return (path.match(cond) || [])[1] || '';
                }
                // 元ウインドウ取得
                function getOpener() {
                    var opener = window.opener,
                        hostname;
                    // 同一ドメインポリシに反する場合はアクセス不能
                    try {
                        hostname = opener.location.hostname;
                    } catch (e) {
                        hostname = null;
                    }
                    // 同一ホストでなければ許可しない
                    return (
                        opener   &&
                        hostname &&
                        window.location.hostname === hostname
                    ) ? opener : null;
                }
                // 設定
                $('a, area').each(function() {
                    var node = this,
                        obj  = $(node),
                        uri  = node.href; // 元の遷移先
                    // 全ての対象要素を走査すると無駄が多いため
                    // click 時に初めて遷移制御を実行
                    obj.click(function() {
                        var opener = getOpener(),
                            ret    = true,
                            d;
                        // 未変更なら適宜処理
                        if (!obj.data('uriChanged')) {
                            //
                            // ログイン 遷移制御
                            //
                            if (!data) { load(); }
                            // 線形探索
                            for (d = 0; d < ndata; d++) {
                                if (data[d].cond.test(uri)) {
                                    // 遷移先をエラーページに変更
                                    node.href = data[d].uri;
                                    break;
                                }
                            }
                            //
                            // 中間ページ 遷移制御
                            //
                            $([
                                {
                                    cond : '.external:not([href^="javascript:"])',
                                    uri  : 'http://www.rakuten-bank.co.jp/link/external.html'
                                },
                                {
                                    cond : '.internal:not([href^="javascript:"])',
                                    uri  : 'http://www.rakuten-bank.co.jp/link/internal.html'
                                }
                            ]).each(function() {
                                var after = this.uri;
                                obj.filter(this.cond).each(function() {
                                    // 遷移先を中間ページに変更
                                    this.href = after+'?name='+encodeURIComponent(
                                        this.title || '???'
                                    )+'&uri='+encodeURIComponent(
                                        this.href || ''
                                    );
                                });
                            });
                        }
                        //
                        // 元ウインドウ 遷移制御
                        //
                        if (opener && getFirstDir(node.pathname) !== windir) {
                            opener.focus();
                            opener.location.href = node.href;
                            ret = false;
                        }
                        // 変更済とする
                        obj.data('uriChanged', true);
                        // 遷移実行
                        return ret;
                    });
                });
            })();

            // ------------------------
            // 検索ワード 自動変更
            // ------------------------
            $('#i_search_input').each(function() {
                var interval = 9000, // 切替時間
                    target   = $(this);
                // 設定
                $.ajax({
                    url      : '/shared/js/word-search.json', 
                    dataType : 'json',
                    cache    : false,
                    timeout  : 10000,
                    success  : function(data) {
                        var ndata = data.length || 0,
                            // 検索フォーム Cookie
                            cookie = new MJL.Cookie('WORD_SEARCH', {
                                fileUnit : false
                            }),
                            // 前回表示項目
                            //   Cookie 経由の値はチェック
                            d = parseInt(cookie.get('item'), 10) || 0,
                            // キーワード表示
                            show = function() {
                                // 疑似循環連結リスト化
                                d = d < ndata ? d : d % ndata;
                                target.val(data[d]);
                                cookie.set('item', ++d);
                            },
                            // インターバル ID
                            id = null,
                            // 自動切替 設定
                            setChanger = function() {
                                if (null === id && !$.trim(target.val())) {
                                    id = setInterval(show, interval);
                                }
                            },
                            // 自動切替 解除
                            delChanger = function() {
                                if (null !== id) {
                                    target.val('');
                                    clearInterval(id);
                                    id = null;
                                }
                            };
                        // ブラウザネイティブの補完は無視
                        target.val('');
                        // 自動切替 開始
                        setChanger();
                        target.focus(delChanger).blur(setChanger);
                        show();
                    }
                });
            });

            // ------------------------
            // モーダルビューア
            // ------------------------
            (function() {
                var targets = $('.preview-01');
                if (0 < targets.length) {
                    function load() {
                        targets.attr('rel', 'modalview').colorbox({
                            transition    : 'fade',
                            opacity       : 0.5,
                            initialWidth  : 538,
                            initialHeight : 404,
                            close         : '閉じる',
                            next          : '次へ',
                            previous      : '前へ',
                            title         : function() {
                                return $(this).closest('.segment').find(':header')
                                              .clone().contents() || "";
                            },
                            onOpen : function() {
                                $('html').css('overflow', 'hidden');
                            },
                            onClosed : function() {
                                $('html').css('overflow', '');
                            }
                        });
                        $('#cboxLoadingGraphic').text("Loading");
                    }
                    if ("colorbox" in $.fn) {
                        load();
                    } else {
                        $.getScript('/shared/js/jquery.colorbox.js', load);
                    }
                }
            })();
        });
    })(jQuery);


    // ------------------------------------------------------------------------
    // MJL 2.1.x ONLY
    // ------------------------------------------------------------------------
    "MJL" in window && /^2\.1\.\d+$/.test(MJL.version) && (function() {
        // --------------------------------
        // 最優先タブ アクティブ ID を URI 内パラメタから取得
        // --------------------------------
        MJL.Tab.prototype._ACTIVE_ID_RULES.unshift(function() {
            return getParam().tab || "";
        });

        // --------------------------------
        // 新規ウインドウの対象に area 要素を追加
        // --------------------------------
        MJL.Window.prototype._TYPES.area = MJL.Window.prototype._TYPES.a;
    })();
})();
