/**
 * MJL enable インタフェイスの実行
 */
MJL.event.add(window, "load", function(event) {
    MJL.enable.heightEqualizer("equalize", {groupBy:2});
	MJL.enable.heightEqualizer("list_linkbknum", {groupBy:3});
	MJL.enable.heightEqualizer("wrapper", {groupBy:4});
    MJL.enable.rollover("roll", {disable:"unroll"});
    MJL.enable.flash("flash", {version:"7"});
}, 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('/')[3];
                (_href == "") ? _href = "home" : "";// hrefの値がnullの場合、homeと仮想
                if(_pagePath == _href){
                    $('img', this).attr('src', $('img', this).attr('src').replace('.png', '_v.png'));
                    $(this).addClass('unroll');
                }
            }
        }
        elements.each(get());
        return this;
    };
    $(function(){
        $('#globalNav > 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 domain = $(this).attr('href').match(/http:\/\/[^\/]*/)[0];
                var href = $(this).attr('href').replace('index.html','').replace(domain,'');
                
                // 2階層目をラップするDD要素を隠す
                if($(this).parent().next('dd')){ $(this).parent().next('dd').hide() }
                
                // リンク参照先と現在のページパスが一致する場合
                if(pagePath == href){
                    //console.log(pagePath,'|', href);
                    // 1階層目
                    if($(this).parent().is('dt')){
                        $(this).parents('dl').addClass('current');
                        if($(this).parent('dt').next().is('dd')){
                            //$(this).parent('dt').addClass('current');
                            if($(this).parent('dt').next('dd')){$(this).parent('dt').next('dd').show()};
                        }
                    }
                    // 2階層目
                    else if($(this).parent().is('li')){
                        //console.log("第2階層目", this);
                        if($(this).parents('dd')){ $(this).parents('dd').show(); }
                        if($(this).parents('dl')){ $(this).parents('dl').addClass('current'); }
                        $(this).parent('li').addClass('current');
                        $(this).wrap('<span></span>');
                    }
                }
                
                // 3階層目は個別に設定
                if(pagePath.match(/\/service\/marketing\/discovery\//)){
                    if(href == "/service/marketing/discovery/"){
                        $(this).parents('dd').show();
                        $(this).parents('dl').addClass('current');
                        $(this).parent().addClass('current');
                    }
                }
            };
        };
//        elements.each(get());
        return this;
    };
    $(function(){
        $('#localNav dl a').setLocalMenuActive();
        $('ul#extra li a').setLocalMenuActive();
    });
})(jQuery);


/**
 * jQuery setNewIcons
 * NEWマーク表示
 */
(function($){
    var name_space = 'setNewIcons';
    $.fn[name_space] = function(options){
        var elements = $('a, span', this);
        var settings = $.extend({
            new_icon : false
        }, options);
        var icoNew = '<img src="'+ settings.new_icon +'" alt="" />';
        var currentDate = new Date();
        var pass = 720;// passage time （720=1ヶ月）
        var newmarkAttr = elements.attr('title');
        function get(){
            return function(){
                var time = $(this).attr('title').split(":");
                var entryDate = new Date(time[0], time[1]-1, time[2], time[3], time[4], time[5]);
                var now = (currentDate.getTime() - entryDate.getTime())/(60*60*1000); 
                now = Math.ceil(now);
                //console.log( entryDate, now );
                if(now <= pass){
                    $(this).after(icoNew);
                }
            }
        }
        elements.each(get());
        return this;
    };
    $(function(){
        $('.tbl_info').setNewIcons({ new_icon: "/shared/images/new_icon.png" });
    });
})(jQuery);


/**
 * jQuery setFileSize plugin
 * リンク参照先のファイルサイズを取得して表示する
 * 
 */
(function($){
    var name_space = 'setFileSize';
    $.fn[name_space] = function(){
        var elements = $(this);
        var icoPDF = '<img src="/shared/images/pdf_icon.png" alt="" />';
        
        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.after('<span class="pdf">' + icoPDF + '（' + size + unitText + '）</span>');
                    }
                    else{
                        self.after("（" + type + ":" + size + unitText + "）");
                    }
                }
            }
        }
        elements.each(get());
        return this;
    };
    $(function(){
        $('a[@href$=jpg], a[@href$=pdf], a[@href$=zip]').not(':has(img)').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 = $("p.image", obj);
                var img = $("> img", imgBlock);
                img.bind('load', function(){
                    var imgWidth = img.width();
                    if(imgWidth){
                        imgBlock.css("width",imgWidth+"px"); // 画像幅を強制
                        $("div.text", obj).css("margin-"+settings.side, imgBlock[0].offsetWidth+"px");// 別カラムの margin を調整
                    }
                });
            }
        }
        elements.each(getImgParallelStyler());
        return this;
    };
    $(function(){
        $('.image-parallel.image-L').setImgParallelStyler({ side:'left' });
        $('.image-parallel.image-R').setImgParallelStyler({ side:'right' });
    });
})(jQuery);


/**
 * jQuery setStripes
 * ストライプ処理
 * Table か DL要素を対象
 */
(function($){
    var name_space = 'setStripes';
    $.fn[name_space] = function(options){
        var elements = $(this);
        function get(){
            return function(){
                var TR = $(this).find(">tbody>tr");
                var DT = $(this).find("dt");
                var DD = $(this).find("dd");
                if(TR.length > 0){
                    TR.each(function(i){
                        $(this).removeClass("odd").removeClass("even").addClass( (i%2 ? "even" : "odd") );
                    });
                }
                if(DT.length > 0){
                    DT.each(function(i){
                        $(this).removeClass("odd").removeClass("even").addClass( (i%2 ? "even" : "odd") );
                    });
                }
                if(DD.length > 0){
                    DD.each(function(i){
                        $(this).removeClass("odd").removeClass("even").addClass( (i%2 ? "even" : "odd") );
                    });
                }
            }
        }
        elements.each(get());
        return this;
    };
    $(function(){
        $('div.tbl_02 > table').setStripes();
        //$('div.interview > dl').setStripes();
    });
})(jQuery);


/**
 * jQuery setFormActive
 * 
 * 
 */
(function($){
    var name_space = 'setFormActive';
    $.fn[name_space] = function(options){
        var elements = $(this);
        function get(){
            return function(){
                var checkbox = $("input.form_checkbox", this);
                var target = $("input.confirm_btn", this);
                function toggleForm(){
                    //target.attr({"disabled": checkbox.attr("checked") ? false : true});
                    if(checkbox.attr("checked")){
                        target.attr("disabled", false);
                        target.attr("src", target.attr("src").replace('_invalid', ''));
                        target.attr("style", "cursor: pointer");
                    }
                    else{
                        if(target.attr("src").match("_invalid")){
                            target.attr("disabled", true);
                            target.attr("style", "cursor: default");
                        }
                        else{
                            target.attr("disabled", true);
                            target.attr("src", target.attr("src").replace('.png', '_invalid.png'));
                            target.attr("style", "cursor: default");
                        }
                    }
                }
                checkbox.click(toggleForm);
                toggleForm();
            }
        }
        elements.each(get());
        return this;
    };
    $(function(){
        $('form#entry_form').setFormActive();
    });
})(jQuery);

