/**
 * MJL enable インタフェイスの実行
 */
MJL.event.add(window, "load", function(event) {
    MJL.enable.styleSwitcher("style-switcher");
    MJL.enable.heightEqualizer("image-col2", {groupBy:2});
    MJL.enable.heightEqualizer("image-col3", {groupBy:3});
    MJL.enable.heightEqualizer("image-col4", {groupBy:4});
    MJL.enable.heightEqualizer("index-col2", {groupBy:2});
    MJL.enable.heightEqualizer("index-col3", {groupBy:3});
    MJL.enable.heightEqualizer("col2", {groupBy:2});
    MJL.enable.heightEqualizer("map-col2", {groupBy:2});
    MJL.enable.heightEqualizer("col3", {groupBy:3});
    MJL.enable.heightEqualizer("col4", {groupBy:4});
    MJL.enable.rollover("global-nav", {disable:"unroll"});
    MJL.enable.rollover("btn", {disable:"unroll"});
    MJL.enable.rollover("print", {disable:"unroll"});
    MJL.enable.rollover("roll");
}, false);


/**
 * jQuery setGlobalMenuActive plugin
 * グローバルナビゲーション現在地表示の自動化処理
 */
(function($){
    var name_space = 'setGlobalMenuActive';
    $.fn[name_space] = function(options){
        var elements = $(this);
        var pagePath = location.pathname.replace('index.html','').split('#')[0];
        (pagePath == "/") ? pagePath="/home/" : "";// サイトトップの場合、パスを/home/と仮想
        pagePath = pagePath.split("/")[1];
        function get(){
            return function(){
                var href = $('a', this).attr('href').replace('index.html', '').split('/')[1];
                (href == "") ? href = "home" : "";// hrefの値がnullの場合、homeと仮想
                if(pagePath == href){
                    pagePath == "home" ? "" : $('img', this).attr('src', $('img', this).attr('src').replace('.png', '_a.png'));
                }
            }
        }
        elements.each(get());
        return this;
    };
    $(function(){
        $('#global-header ul.global-nav > li').setGlobalMenuActive();
    });
})(jQuery);


/**
 * jQuery setLocalMenuActive plugin
 * ローカルナビゲーションの現在地表示とメニュー開閉の自動化処理
 */
 (function($){
    var name_space = 'setLocalMenuActive';
    $.fn[name_space] = function(options){
        var elements = $(this);
        var pagePath = location.pathname.replace('index.html','').split('#')[0];
        function get(){
            return function(){
                var href = $(this).attr('href').replace('index.html','');
                // 2階層目をラップするDD要素を隠す
                if($(this).parent().next('dd')){ $(this).parent().next('dd').hide() }
                // 3階層目をラップするUL要素を隠す
                if($(this).parent().parent().parent().parent().parent().is('dd')){ $(this).parent().parent().hide(); }
                
                // オプション：.hiddenは子メニューを開かない
                $(".hidden", $(this).parents('dl')).hide();
                
                // リンク参照先と現在のページパスが一致する場合
                if(pagePath == href){
                    // 1階層目
                    if($(this).parent().is('dt')){
                        $(this).parent('dt').addClass('active');
                        if($(this).parent().next().is('dd')){
                            $(this).parent('dt').addClass('open');
                            $(this).parent().next('dd').show();
                            $(this).parent().next('dd').addClass('open');
                        }
                    }
                    // 2階層目
                    else if($(this).parent().parent().parent().is('dd')){
                        //console.log("第2階層目", this);
                        $(this).parents('dd').prev('dt').addClass('active');
                        $(this).parents('dd').addClass('open').show();
                        $(this).parent('li').addClass('active');
                        $(this).next('ul').show();
                    }
                    // 3階層目
                    else if($(this).parent().parent().parent().parent().parent().is('dd')){
                        //console.log("第3階層目", this);
                        // 2階層目をアクティブ表示させる
                        $(this).parent().parent().parent().parent().parent('dd').show();
                        $(this).parent().parent().parent().parent().parent('dd').prev('dt').addClass('active');
                        $(this).parent().parent().parent().parent().parent('dd').prev('dt').addClass('open');
                        $(this).parent().parent().parent().addClass('active');
                        $(this).parent().addClass('active');
                        $(this).parent().parent().show();
                    }
                }
                if(pagePath.match(/\/products\/solutions\/reuse\//)){
                    if(href == "/products/solutions/reuse/"){
                        $(this).parents('dd').prev('dt').addClass('active');
                        $(this).parents('dd').addClass('open').show();
                        $(this).parent('li').addClass('active');
                        $(this).next('ul').show();
                    }
                }
                if(pagePath.match(/\/inquiry.nsf\/reuse/) || pagePath.match(/\/inquiry.nsf\/recycle/) || pagePath.match(/\/inquiry.nsf\/data_delete/)){
                    if(href == "/products/solutions/reuse/"){
                        $(this).parents('dd').prev('dt').addClass('active');
                        $(this).parents('dd').addClass('open').show();
                        $(this).parent('li').addClass('active');
                        $(this).next('ul').show();
                    }
                }
                if(pagePath.match(/\/inquiry.nsf\/ips/) || pagePath.match(/\/inquiry.nsf\/vb/)){
                    if(href == "/products/solutions/ec/"){
                        $(this).parents('dd').prev('dt').addClass('active');
                        $(this).parents('dd').addClass('open').show();
                        $(this).parent('li').addClass('active');
                        $(this).next('ul').show();
                    }
                }
            };
        };
        elements.each(get());
        return this;
    };
    $(function(){
        $('.local-nav dl a').setLocalMenuActive();
        if($('.local-nav li.active ul')){
            $('.local-nav li.active ul').show();
        }
    });
})(jQuery);


/**
 * jQuery setMenuClone plugin
 * グローバルナビゲーションのクローンを作成してフッターに配置
 */
(function($){
    var name_space = 'setMenuClone';
    $.fn[name_space] = function(options){
        var elements = $(this);
        var area_target = $('#global-footer ul.utility-nav');
        function get(){
            return function(){
                var out_html = '<ul class="global-nav">';
                var items = $('>li>a', this);
                items.each(function(){
                    var elm_href = $(this).attr('href'), elm_text = $('>img', this).attr('alt');
                    out_html += '<li><a href="'+elm_href+'">'+elm_text+'</a></li>';
                });
                out_html += '</ul>';
                area_target.before(out_html);
            }
        }
        elements.each(get());
        return this;
    };
    $(function(){
        $('#global-header ul.global-nav').setMenuClone();
    });
})(jQuery);


/**
 * jQuery cssSupport plugin
 * IE6が対応していないCSSをサポートする
 */
(function($){
    var name_space = 'cssSupport';
    $.fn[name_space] = function(options){
        var elements = $(this);
        function get(){
            return function(){
                $("li:first-child", this).addClass("first-child");
            }
        }
        elements.each(get());
        return this;
    };
    $(function(){
        $('#global-footer ul.global-nav').cssSupport();
        $('#global-footer ul.utility-nav').cssSupport();
    });
})(jQuery);


/**
 * jQuery setIcons plugin
 * target="_balnk"、参照先がpdfへのリンクテキストに自動でアイコンを付与する
 * 
 * Attributes:
 * -@options: オプションのハッシュ
 *  -icoBlank: blankアイコン画像のパス
 *  -icoPdf: PDFアイコン画像のパス
 */
(function($){
    var name_space = 'setIcons';
    $.fn[name_space] = function(options){
        var elements = $(this);
        var settings = $.extend({
            blank_icon : false,
            pdf_icon : false,
            mail_icon : false,
            xls_icon : false
        }, options);
        var icoBLANK = '<img src="'+ settings.blank_icon +'" alt="" class="icon">';
        var icoMAIL = '<img src="'+ settings.mail_icon +'" alt="" class="icon">';
        var icoXLS = '<img src="'+ settings.xls_icon +'" alt="" class="icon">';
        function get(){
            return function(){
                $('a[@href$=xls]', this).not(':has(img)').after(icoXLS);
                $('a[@target$=blank]', this).not(':has(img)').not('[@href$=pdf]').not('[@href$=xls]').after(icoBLANK);
                $('a[@href^=mailto:]', this).not(':has(img)').not('[@target$=blank]').not('[@href$=pdf]').after(icoMAIL);
                $('a[@href$=zip]', this).not(':has(img)').parent("li").addClass("download");
            }
        }
        elements.each(get());
        return this;
    };
    $(function(){
        $('#primary').setIcons({ blank_icon: "/compo/img/primary/icon_blank.png", mail_icon: "/compo/img/primary/icon_mail.png", xls_icon: "/compo/img/primary/icon_xls.png" });
        $('#secondary div.beacon').setIcons({ blank_icon: "/compo/img/primary/icon_blank.png", mail_icon: "/compo/img/primary/icon_mail.png", xls_icon: "/compo/img/primary/icon_xls.png" });
    });
})(jQuery);


/**
 * jQuery setFileSize plugin
 * リンク参照先のファイルサイズを取得して表示する
 * 
 */
(function($){
    var name_space = 'setFileSize';
    $.fn[name_space] = function(){
        var elements = $(this);
        var icoPDF = '<img src="/compo/img/primary/icon_pdf.png" alt="" class="icon">';
        
        function ajax(url, type, async){
            /* XMLHttpRequestオブジェクト作成 */
            var xhr = false;
            xhr = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
            /* HTTPリクエスト実行 */
            xhr.open(type, url, async);
            xhr.send(null);
            return xhr;
        }
        function get(){
            return function(){
                var self = $(this), url = this.href, xhrObj = ajax(url, "GET", true);
                /* レスポンスデータ処理 */
                xhrObj.onreadystatechange = function(){
                    if(xhrObj.readyState == 4 && xhrObj.status == 200){
                        var fileSize = xhrObj.getResponseHeader("Content-Length");
                        var fileType = xhrObj.getResponseHeader("Content-Type");
                        fileSize = parseInt(fileSize, 10);
                        var units = [
                            [1024 * 1024 * 1024, 'GB'],
                            [1024 * 1024, 'MB'],
                            [1024, 'KB'],
                            [1, 'bytes']
                        ]
                        for(var i=0; i<units.length; i++){
                            var unitSize = units[i][0];
                            var unitText = units[i][1];
                            if(fileSize >= unitSize){
                                fileSize = fileSize / unitSize;
                                fileSize = Math.ceil(fileSize * 10) / 10;
                                break;
                            }
                        }
                        fileType = fileType.split('/')[1].toUpperCase();
                        return add(fileType, fileSize, unitText);
                    }
                }
                /* タイプ別にファイルサイズを追加 */
                function add(type, size, unitText){
                    if(type == "PDF"){
                        self.append("（" + icoPDF + type + ":" + size + unitText + "）");
                        self.parent("li").addClass("download");
                    }
                    else{
                        self.append("（" + type + ":" + size + unitText + "）");
                    }
                }
            }
        }
        elements.each(get());
        return this;
    };
    $(function(){
        $('a[@href$=jpg], a[@href$=pdf], a[@href$=zip]').setFileSize();
    });
})(jQuery);


/**
 * jQuery setImgParallelStyler plugin
 * 画像とテキストの並列処理
 * 
 * Attributes:
 * -@options: オプションのハッシュ
 *  -side: 画像の位置が、right or left
 */
(function($){
    var name_space = 'setImgParallelStyler';
    $.fn[name_space] = function(options){
        var elements = $(this);
        var settings = $.extend({
            side : false
        }, options);
        if("left" != settings.side && "right" != settings.side){
            throw Error("invalid side type: '"+settings.side+"'");
        }
        function getImgParallelStyler(){
            return function(){
                var obj = $(this);
                var imgBlock = $(".image", obj);
                var img = $("img", imgBlock);
                function resize(){
                    var imgWidth = img.width();
                    if(imgWidth){
                        imgBlock.css("width",imgWidth+"px"); // 画像幅を強制
                        $("div.text", obj).css("margin-"+settings.side, imgBlock[0].offsetWidth+"px");// 別カラムの margin を調整
                    }
                }
                resize();
                img.load(function(){
                    resize();
                });
            }
        }
        elements.each(getImgParallelStyler());
        return this;
    };
    $(function(){
        $('.image-parallel.image-L').setImgParallelStyler({ side:'left' });
        $('.image-parallel.image-R').setImgParallelStyler({ side:'right' });
    });
})(jQuery);


/**
 * jQuery setTableHeadStyler plugin
 * 
 * 
 */
(function($){
    var name_space = 'setTableHeadStyler';
    $.fn[name_space] = function(options){
        var elements = $(this);
        function get(){
            return function(){
                var obj = $(this);
                var thaed = obj.find("thead");
                var tbody_th = obj.find("tbody th")
                if(thaed.length > 0){
                    tbody_th.each(function(i){
                        $(this).css("backgroundColor", "#f2f2f2");
                    });
                }
            }
        }
        elements.each(get());
        return this;
    };
    $(function(){
        $('table').setTableHeadStyler();
    });
})(jQuery);


