Event.observe(window, 'load', load);

function load() {
    new TextCounter('bbs_res_handlename', 20);
    new TextCounter('bbs_res_body', 500);

    $$('div.bLine>a.btnReply03').each(function (anchor){
        new BbsReturn(anchor.id);
    });

    $$('div.clear>a.btnReply03').each(function (anchor){
        new BbsResReturn(anchor.id);
    });

    var goodUrl = $F('good_url');
    $$('ul.btnGoodBad > li > a[id^=goodBtn]').each(function(btn){
        new GoodComment(goodUrl, btn.id);
    });

    var badUrl = $F('bad_url');
    $$('ul.btnGoodBad > li > a[id^=badBtn]').each(function(btn){
        new BadComment(badUrl, btn.id);
    });

    var violationUrl = $F('violation_url');
    $$('p.date > a.more[id^=violation_]').each(function(anchor){
        new Violation(violationUrl, anchor.id);
    });

    var goodResUrl = $F('good_res_url');
    $$('ul.btnGoodBad2 > li > a[id^=goodBtn]').each(function(btn){
        new GoodComment(goodResUrl, btn.id);
    });

    var badResUrl = $F('bad_res_url');
    $$('ul.btnGoodBad2 > li > a[id^=badBtn]').each(function(btn){
        new BadComment(badResUrl, btn.id);
    });

    var violationResUrl = $F('violation_res_url');
    $$('p.date2 > a.more[id^=violation_]').each(function(anchor){
        new Violation(violationResUrl, anchor.id);
    });

    $$('a[id^=favorite_add_bbs_]').each(function(anchor){
        anchor.observe('click', new FavoriteBbsCreator().execute);
    });

    $$('a[id^=favorite_delete_bbs_]').each(function(anchor){
        anchor.observe('click', new FavoriteBbsEraser().execute);
    });
}

var BbsReturn = Class.create({
    initialize : function(id) {
        this.id = id;
        this.targetId = id.match(/\d+/)[0];
        $(this.id).observe('click', this.execute.bindAsEventListener(this));
    },

    execute : function() {
        this.clearResId();
        this.showTarget();
        this.setTargetId();
    },

    showTarget: function() {
        if(!$('bbs_res_target_row').visible()) {
            $('bbs_res_target_row').show();
        }

        $('bbs_res_is_res').setValue(1);
    },

    clearResId: function() {
        $('bbs_res_bbs_res_id').clear();
    },

    getName : function() {
        return $('uImg').innerHTML.stripTags().strip().match(/(.+)さん$/)[1];
    },

    setTargetId : function() {
        var tpl = new Template('<a href="#section_#{targetId}\">#{targetName}</a>さん');
        var name = this.getName();
        var attribute = { targetId: this.id, targetName: name };
        $('rs_target').update(tpl.evaluate(attribute));
    }
});

var BbsResReturn = Class.create(BbsReturn, {

    execute : function($super) {
        $super();
        this.setResId();
    },

    getName : function() {
        return $('section_' + this.id).select('p.detailCommentAuther')[0].innerHTML.match(/^\d+：(.+)さん$/)[1];
    },

    setResId: function() {
        $('bbs_res_bbs_res_id').setValue(this.targetId);
    }

});
