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.window("popup-02", {width : 450, height : 400});
    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");
        }
    });
    MJL.enable.heightEqualizer("merit-list-03", {
        collect : function(parent) {
            return MJL.getElementsByClassName(parent, "box-regular-01");
        }
    });
    MJL.enable.heightEqualizer("list-slide-bnrs-01", {
        collect : function(parent) {
            return MJL.convArray(parent.getElementsByTagName("li"));
        }
    });
}, 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,
                // ホワイトリストに一致しなかった場合の遷移先
                    defaultURI = 'http://www.rakuten-bank.co.jp/?l-id=err',
                    param      = getParam(),
                    paramURI   = param.uri,
                    anchor     = $('#page-link'),
                    setURI     = function(uri) {
                        // 遷移先設定
                        anchor.attr('href', uri);
                        // 指定時間後に自動遷移
                        if (uri && !('noref' in param)) {
                            setTimeout(function() {
                                window.location.href = uri;
                            }, interval);
                        }
                    };
                // 各種設定
                $('#page-name').empty().text(param.name); // ページ名表示
                $('#page-close').click(function() {       // 「閉じる」ボタン
                    window.close();
                    return false;
                });
                // 遷移先チェック (ホワイトリスト)
                $.ajax({
                    url      : '/shared/js/jump.json',
                    dataType : 'json',
                    timeout  : 10000,
                    cache    : false,
                    error    : setURI,
                    success  : function(data) {
                        // 与 URI チェック (前方一致)
                        setURI((new RegExp(
                            '^(?:'+(data || []).join('|')+')'
                        )).test(paramURI) ? paramURI : defaultURI);
                    }
                });
            // ------------------------
            // ログイン＆中間ページ＆元ウインドウ遷移制御
            // ------------------------
            // ログイン遷移制御設定 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(),
                            parentActiveEnabled = !obj.hasClass('nochange'),
                            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 (
                            parentActiveEnabled &&
                            opener              &&
                            getFirstDir(node.pathname) !== windir
                        ) {
                            opener.focus();
                            opener.location.href = node.href;
                            ret = false;
                        }
                        // 変更済とする
                        obj.data('uriChanged', true);
                        // 遷移実行
                        return ret;
                    });
                });
            })();

            // ------------------------
            // 検索ワード 自動変更
            // ------------------------
            $('body:not(.category-koueirace) #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);
                    }
                }
            })();
        });
		
        // ------------------------
        // Campaign Box ローテーションバナー
        // ------------------------
        $(function() {
            var space = 41,
                intervalTimer = 3000;

            $("div.list-slide-bnrs-01").each(function(){
            var bnrsContainer = $(this).children("ul.bnrs"),
                bnrsListArr = [],
                targetNo = 0,
                minWidth = 0, bnrsWidth = 0,
                clickBool = true,
                interval;

                // バナーリスト初期値セット
                $(this).find("ul.bnrs > li").each(function(index){
                    // スライド幅を取得するため、li要素を配列化
                    bnrsListArr.push($(this));
                    $(this).css("width" , $(this).find("img").width() + space);
                    bnrsWidth += $(this).find("img").width() + space;
                });
				
                // li要素の横幅合計値をulに付与
                $(this).find("ul.bnrs").css("width" , bnrsWidth + "px");
				
                // スライドさせるために必要な、コンテナの横幅722pxに届いてるかどうかを判断するためのulの横幅を取得
                minWidth = bnrsWidth - (bnrsListArr[bnrsListArr.length-1].width());
				
                // バナーの数が2個以上で、スライドさせるために必要な横幅を満たしてればスライド開始
                if((bnrsListArr.length > 1) && ($(this).width() < minWidth)){
					
                    // タイマーセット
                    if(clickBool){
                        interval = setInterval(function(){
                            clickBool = false;
                            nextSlide();
                        }, intervalTimer);
					}

                    $(this).find("ul.btns > li.prev > a , ul.btns > li.next > a").click(function(){
                        if(clickBool){
                            clearInterval(interval);
                            interval = null;
                            if($(this).parents("li").hasClass("prev")){
                                nextSlide();
                            }else{
                                targetNo--;
                                if(targetNo < 0){ targetNo = bnrsListArr.length-1; }
                                $(bnrsContainer).prepend(bnrsListArr[targetNo]);
                                $(bnrsContainer).css("left" , bnrsListArr[targetNo].width() * -1);
                                slider(targetNo , "next");
                            }
                        }
                        clickBool = false;
                        return false;
                    });
                }else{
                    $(this).find("ul.btns").css("display" , "none");
                }

                // スライダー処理
                function slider(no , direction){
                    var slideDirection = (direction =="prev") ? -1 : 1,
                        slideTimer = 500;
                        leftPosition = Number($(bnrsContainer).css("left").replace("px" , "")),
                        slideArea = leftPosition + bnrsListArr[no].width() * slideDirection;
					
                    $(bnrsContainer).animate(
                        { left : slideArea },
                        { duration : slideTimer , easing : "swing" ,
                            complete : function(){
                                clickBool = true;
                                if(direction =="prev"){
                                    $(bnrsContainer).append(bnrsListArr[no]);
                                }
                                $(bnrsContainer).css("left" , "0px");
                                if(interval == null){
                                    interval = setInterval(function(){
                                        clickBool = false;
                                        nextSlide();
                                    }, intervalTimer);
                                }
                            }
                        }
                    );
                }
				
                function nextSlide(){
                    slider(targetNo , "prev");
                    targetNo++;
                    if(targetNo > bnrsListArr.length-1){ targetNo = 0; }
                }
            });

        });
		
		// ------------------------
        // 法人サイト専用
        // ------------------------
        $(function() {
            // ローカルナビカレント切り替え
            $("body#business ul.nav-global-01").each(function(){
                var path = window.location.pathname.replace("index\.html" , "");
                $(this).find("li").each(function(){
                    $(this).find("a[href='"+ path +"']").parent("li").addClass("selected");
                    if($(this).parents("ul").hasClass("level2-01")){
                        $(this).parents("ul.level2-01").parent("li").removeClass("selected");
                    }
                });
            });
			
            // ボックスのトグル機能
            $("body#business div.box-toggle-01 .lyt-image").each(function(){
            var imageWidth = $(this).children("div.image").find("img:first-child").width(),
                space = 15 , positioning = ($(this).hasClass("image-l")) ? "left" : "right";
                $(this).find("div.image img").each(function(){
                    imageWidth = Math.max(imageWidth , $(this).width());
                });
                $(this).children("div.image").css({
                    width : imageWidth + space +"px",
                    float : positioning
                });
                if($(this).hasClass("image-parallel")){ $(this).removeClass("image-parallel"); }
            });
            
            $("body#business a.toggle-01").each(function(){
                var boxID = $(this).attr("href").replace("#" , "");
                $("#" + boxID).not(".selected").hide();
                $(this).click(function(){
                    $(".box-toggle-01").hide();
                    $("#" + boxID).show();
                    return false;
                });
            });
        });
    })(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 || "";
        });

        // --------------------------------
        // アクティブタブの click で別ページに遷移
        // タブとタブパネルの関連づけは rel 属性で行う
        //   * 遷移させない: <a href="#パネル id">...</a>
        //   * 遷移させる:   <a href="遷移先 URL" rel="パネル id">...</a>
        // rel 属性に記述する id 属性値には # を付与してはならない
        // --------------------------------
        // アクティブタブ 変更
        MJL.Tab.prototype._EVENTS.click = function(event, id) {
            var aid  = this._getActiveId(),
                item = this.items[aid];
            if (id !== aid) { // タブ切替
                this.active(id);
                MJL.event.preventDefault(event);
            } else {          // 別ページ遷移
                id = decodeURIComponent(MJL.getHash(item.anchor));
                // href 属性値がタブコンテナへの参照なら何もしない
                if (id === aid) {
                    MJL.event.preventDefault(event);
                }
            }
        };

        // a 要素 rel ないし href 属性値から ID を取得
        MJL.Tab.prototype._getIdByHref = function(elem) {
            // rel 属性値を優先
            var id = decodeURIComponent(elem.getAttribute("rel") || "");
            if (!this._isValidId(id)) {
                id = decodeURIComponent(MJL.getHash(elem));
                // ID (ハッシュ値) の不正はありえない
                if (!this._isValidId(id)) {
                    // 「'rel' ないし 'href' 属性値中のハッシュ値 '???' は無効です」
                    throw new Error("Hash value '#"+id+"' in 'rel' or 'href' attribute value is invalid");
                }
            }
            return id;
        };

        // --------------------------------
        // 新規ウインドウの対象に area 要素を追加
        // --------------------------------
        MJL.Window.prototype._TYPES.area = MJL.Window.prototype._TYPES.a;
    })();
})();

