// for user blog page.
function myblogRewrite() { 
    // todo
    var el1 = document.getElementById('myblog-header-right');
    if (el1) el1.style.visibility = 'visible';
    var el2 = document.getElementById('myblog-header-right-no-login');
    if (el2) el2.style.visibility = 'visible';
}
myblogRewrite();

// onclick="blogIntroductionInProfileNoLogin()"
function blogIntroductionInProfileNoLogin(){
    var msgArea = document.getElementById('blog-introduction-msg-area-no-login');
    msgArea.style.display = 'block';
}

(function () {
    if (typeof window.console === "undefined") {
         window.console = {};
    }
    if (typeof window.console.log !== "function") {
         window.console.log = function () {};
    }
})();


// for Nice etc. Appendix Data Rewrite.
var blogAppendixAjaxLoader = function (_arg_api, _arg_obj, _arg_loop, opts) {

    var _uri = '';
    var _myblogjs = document.getElementById('myblog-js').getAttribute('src');

    if ( _myblogjs.indexOf(location.hostname)  > 0){
        // directory 
        if (/([^/]+)\//.exec(location.pathname) !== null && /([^/]+)\//.exec(location.pathname)[1] ) { 
            _uri = '/' + /([^/]+)\//.exec(location.pathname)[1];  // ディレクトリブログ
        }
    } else{
        // domain do nothing.
    }

    var _article_id = _myblogjs.match(/article_id=(\d+)/);

    var article_id;
    if (_article_id) {
        article_id = _article_id[1]; //記事idの取得
    } else {
        return; // 取得できなかったので、終わる
    }

    var obj = document.getElementById(_arg_obj); //  niceの出力先
    if (obj === null) { 
	return;        // 記事ページ以外は何もしないで終了
    }

    if (obj && _arg_loop.indexOf('.') === 0 && opts.is_trackback == 1) {
        var list = obj.getElementsByTagName('div');   
        for (var i=0; i<list.length; i++) {
            if (list[i].className.match('trackback')) {
                list[i].setAttribute('id', 'myblog-trackback-list-area');
                _arg_loop = 'myblog-trackback-list-area';
            }
        }
    }

    if (obj.getAttribute('rendered')) { // 書き出し後かチェック
        return;
    }

    var offset = 0;

    if (obj.getAttribute('rendered-offset')) { // 書き出しオフセット
        offset = parseInt( obj.getAttribute('rendered-offset') );
    } else {
        obj.setAttribute('rendered-offset', 0);
    }

    // util
    var isIE = /msie|trident/i.test(navigator.userAgent);
    var isOpera = /opera/i.test(navigator.userAgent);
    var isSafari = /safari/i.test(navigator.userAgent);

    // util
    var str_area = function(_val) {
        var _str_area = _arg_loop;
        var retval = _str_area;
        if ( _val > 0 ) retval += _val;
        return retval;
    };

    var window_size = 0;
    if (!isSafari && !isOpera) {
        window_size = document.documentElement.clientHeight || document.body.clientHeight || document.body.scrollHeight;
    } else {
        window_size = window.innerHeight;
    }

    var scroll_state = document.documentElement.scrollTop || document.body.scrollTop;
    var obj_top = obj.getBoundingClientRect().top;
    var area = document.getElementById( str_area(offset) );

    if (!area && opts.is_trackback) {
        var append_obj = document.createElement("div");
        append_obj.setAttribute('id', str_area(0));
        area = append_obj;
        obj.appendChild( append_obj );
    }

    var area_top = area.getBoundingClientRect().top;
    area.setAttribute('class', 'myblog-nice-list-area');

    var _burst = 0; // is fire?

    if (
        window_size - obj_top > 0 && offset === 0
    ) {
        _burst = 1;
    }

    if (
        window_size - area_top > 0 && offset > 0
    ) {
        _burst = 1;
    }

    if ( offset >= opts.max_cnt ) { // 表示最大件数 + 1
        _burst = 0;
        obj.setAttribute('rendered', 1); // 書いたことを記録する

        // visible readmore ?
        var eleOBefore = document.getElementById( str_area( (offset - 2) ) ),
            listOBefore = eleOBefore.getElementsByTagName('li'),
            elePrevious = document.getElementById( str_area( (offset - 1) ) ),
            listPrevious = elePrevious.getElementsByTagName('li');

        if (/comment/.test(_arg_api)) { _uri += '/list_comment/' + article_id + '/' }
        if (/nice/.test(_arg_api))    { _uri += '/list_nice/' + article_id + '/' }
        if (/tb/.test(_arg_api))      { _uri += '/list_tb/' + article_id + '/' }
        if (listPrevious.length == listOBefore.length) { // 前と1つ前の要素が同数である場合は、続きを表示できる しきい値と同数の場合も表示されてしまうが、やむ得ない
          area.insertAdjacentHTML('afterend', '<div id="' + _arg_obj + '-readmore" class="' + _arg_obj + '-readmore"><a href="' + _uri + '" target="_blank" rel="nofollow">続きを表示する</a></div>');
        }
    }

    if ( _burst ){
        var request = new XMLHttpRequest();
        _uri += _arg_api + '/' + article_id + '/' + offset;

        request.open('GET', _uri , true);
        request.onreadystatechange = function() {
            if (this.readyState === 4) {
                if (this.status >= 200 && this.status < 400) {
                    // Success!
                    resp = this.responseText;
                    if ( resp === 'finished' ) {
                        obj.setAttribute('rendered', 1); // 書いたことを記録する
                    }else{
                        // レスポンス遅延等により既にDOMが存在した場合は何もしない
                        var eleCurrent = document.getElementById( str_area( (offset) ) ),
                        listCurrent = eleCurrent.getElementsByTagName('li');
                        if (listCurrent.length > 0) {
                            return;
                        }

                        area.innerHTML = resp;
                        var next_obj = offset + 1;
                        obj.setAttribute('rendered-offset', next_obj);
			if (opts.ul_wrap == 1) {
			    area.insertAdjacentHTML('afterend', '<ul id="' + str_area(next_obj) + '"></ul>');
			} else {
			    area.insertAdjacentHTML('afterend', '<div id="' + str_area(next_obj) + '"></div>');
			}
                    }
                } else {
                    // Error :(
                    //area.innerHTML = '';
                }
            }
        };
        request.send();
        request = null;
    }

    setTimeout(function() {
        blogAppendixAjaxLoader(_arg_api, _arg_obj, _arg_loop, opts);
    }, 750); //loop

};

var blogAppendixAjaxLoaderParent = function(){
    blogAppendixAjaxLoader('/show_nice', 'nice', 'myblog-nice-list-area', { max_cnt : 3, is_trackback : 0, ul_wrap : 1 });
    // commentは現状ajax対象外
    // blogAppendixAjaxLoader('/show_comment', 'comments', 'myblog-comment-list-area', { max_cnt : 2, is_trackback : 0, ul_wrap : 0 });

    if ( document.getElementById('trackback') ){ // old // nice:table, comment:div, trackback:div
      blogAppendixAjaxLoader('/show_tb', 'trackback', '.trackback', { max_cnt : 2, is_trackback : 1, ul_wrap : 0 });
    } else { // new // nice:li, comment:div, trackback:parent-none,div
      blogAppendixAjaxLoader('/show_tb', 'trackback-write', 'myblog-trackback-list-area', { max_cnt : 2, is_trackback : 1, ul_wrap : 0 });
    }
}

if( window.addEventListener ) {
    window.addEventListener( 'load', blogAppendixAjaxLoaderParent, false );
} else if( window.attachEvent ) {
    window.attachEvent( 'onload', blogAppendixAjaxLoaderParent);
} else {
    window.onload = blogAppendixAjaxLoaderParent;
}
