// require prototype-1.4.0.js

var DiarySummary = Class.create();
Object.extend(DiarySummary, {
    closedImg: '/images/summary_closed.gif',
    openedImg: '/images/summary_opened.gif',
    //loadingImg: '/images/summary_loading.gif',
    loadingImg: '/images/cinnamon-right.gif',
    errorImg: '/images/summary_error.gif'
});
DiarySummary.prototype = {
    initialize: function(liTag) {
        this.opened = false;
        this.liTag = liTag;
        this.toggleButton = this.createButton();
        this.summaryContainer = this.createSummaryContainer();
        this.contentCache = null;

        this.hide();
        this.liTag.appendChild(this.toggleButton);
        this.liTag.appendChild(this.summaryContainer);
    },

    createButton: function() {
        var btn = document.createElement('img');
        btn.src = DiarySummary.closedImg;
        btn.style.cursor = 'pointer';
        btn.style.marginLeft = '5';
        btn.style.verticalAlign = 'middle';
        Event.observe(btn, 'click', this.toggle.bindAsEventListener(this), false);
        return btn;
    },

    createSummaryContainer: function() {
        var div = document.createElement('div');
        div.className = 'diary-summary';
        return div;
    },

    toggle: function() {
        if (this.opened) {
            this.close();
        } else {
            this.open();
        }
    },

    open: function() {
        if (this.contentCache != null) {
            this.show(this.contentCache);
            return;
        }

        this.show('<img src="' + DiarySummary.loadingImg + '" /> 読み込み中', 'center');
        
        var durl = this.liTag.getElementsByTagName('a')[0].href;
        durl.match(/hatena\.ne\.jp\/(.+)\/(.+)$/);
        var userName = RegExp.$1;
        var date = RegExp.$2;
        var url = [
                   '/', userName, '/rss',
                   '?date=', date,
                   '&word=', Hatena.Diary.encodedKeyword
                  ].join('');
        var self = this;
        new Ajax.Request(url, {
            method: 'get',
            onSuccess: self.onLoadSuccess.bindAsEventListener(this),
            onFailure: self.onLoadFailure.bindAsEventListener(this)
        });
    },

    close: function() {
        this.hide();
    },

    onLoadSuccess: function(req) {
        var rss = req.responseXML;
        var textMatch = req.responseText.match(/<content:encoded><!\[CDATA\[(.*)\]\]><\/content:encoded>/);
        if (!textMatch) {
            this.show('<img src="' + DiarySummary.errorImg + '" /> 内容を取得できませんでした。', 'center');
            return;
        }
        var text = textMatch[1];
        
        var item = rss.getElementsByTagName('item')[0];
        var titleTag = item.getElementsByTagName('title')[0];
        if (titleTag && titleTag.firstChild) {
            var title = titleTag.firstChild.nodeValue;
            if (title && title!="") {
                title = this.highlightText(title);
                text = title + '\t' + text;
            }
        }
        text = this.highlightText( this.clipText(text) );
        text = text.replace('\t', '<br />');
        
        this.contentCache = text;
        this.show(text);
    },

    highlightText: function(text) {
        var re = new RegExp("("+Hatena.Diary.keyword+")", "ig");
        return text.replace(re,
                           function(str, p1) {
                               return '<span class="highlight">'+p1+'</span>';
                           });
    },

    clipText: function(text) {
        text = text.stripTags();
        var re = new RegExp("(.*)(" + Hatena.Diary.keyword + ")(.*)", "i");
        var match = text.match(re);
        if (match && match.length>=4) {
            var pre = match[1];
            if (pre.length>100) {
                pre = pre.substr(pre.length-100); // for IE
            }
            var suf = match[3].substr(0, 100);
            return pre + match[2] + suf;
        } else {
            return text.substr(0, 200);
        }
    },

    onLoadFailure: function(req) {
        this.show('<img src="' + DiarySummary.errorImg + '" /> Load Error', 'center');
    },

    show: function(text, align) {
        if (!align) align = 'left';
        this.opened = true;
        this.toggleButton.src = DiarySummary.openedImg;
        text = [
                '<span class="curve-top"><span></span></span>',
                '<div style="text-align:', align, '">',
                text,
                '</div>',
                '<span class="curve-bottom"><span></span></span>'
               ].join('');
        this.summaryContainer.innerHTML = text;
        Element.show(this.summaryContainer);
    },

    hide: function() {
        this.opened = false;
        this.toggleButton.src = DiarySummary.closedImg;
        this.summaryContainer.innerHTML = '';
        Element.hide(this.summaryContainer);
    }
}

var AllOpenButton = Class.create();
AllOpenButton.prototype = {
    initialize: function(diarySummaryButtons) {
        if (!diarySummaryButtons
            || diarySummaryButtons.length==0
            || !$('all-open')) return;
        this.closedImg = '/images/summary_closed_all.gif';
        this.openedImg = '/images/summary_opened_all.gif';
        this.opened = false;
        this.diarySummaryButtons = diarySummaryButtons;
        this.button = this.createButton();
        Element.setStyle(this.button, {
            verticalAlign: (document.all && !window.opera) ? '-1' : 'text-bottom',
            marginLeft: '5'
        });
        $('all-open').appendChild(this.button);
    },
    createButton: function() {
        var img = document.createElement('img');
        img.src = this.closedImg;
        img.style.cursor = 'pointer';
        Event.observe(img, 'click', this.toggle.bindAsEventListener(this), false);
        return img;
    },
    toggle: function() {
        if (this.opened) {
            this.close();
        } else {
            this.open();
        }
        this.opened = !this.opened
    },
    open: function() {
        this.diarySummaryButtons.each(function(btn){
            btn.open();
        });
        this.button.src = this.openedImg;
    },
    close: function() {
        this.diarySummaryButtons.each(function(btn){
            btn.close();
        });
        this.button.src = this.closedImg;
    }
}

