/*************************
* 部活の投票
**************************/
$(function(){

/**
 * 部活への投稿
 */
var Entry = function(id){
    this.init(id);
}
	Entry.prototype = {
	    id:      null, // 投稿ID
	    button:  null, // 投稿ボタン
	    count:   null, // 投稿数
	    init: function(id) {
	        this.id = id;
	    }
	}

/**
 * VIEW
 */
var View = {};
    /**
     * 投稿ボタンのVIEW
     */
	View.Button = {
	    /**
	     * ボタンを投稿付加にするメソッド
	     */
	    disable: function(entry) {
	        entry.button.unbind();
	        entry.button.replaceWith('<img src="/images/club/btn_vote_v.gif" width="81" height="14" alt="これに投票！" class="btn" />');
	    }
	}
	/**
	 * 投稿数のVIEW
	 */
	View.Count = {
	    update: function(entry, count) {
	        entry.count.html(count);
	    }
	}

/**
 * イベントのハンドラ
 */
var Handler = {
    apiUrl: apiUrl,
    token:  token
};
    /**
     * 投票イベントのハンドラ
     */
	Handler.Vote = (function(){
	    /**
	     * 投稿メソッド
	     */
	    var vote = function(entry) {
	        // APIへPOST
	        $.ajax({
	            type: "POST",
	            url:  Handler.apiUrl,
	            data: {
	                entry_id: entry.id,
	                token:    Handler.token
	            },
	            dataType: 'xml',
	            success: function(xml, status) {
	                if($(xml).find('status').text() == 'OK') {
	                    var count = $(xml).find('count').text();
	                    View.Count.update(entry, count); // 投稿数を更新
	                    View.Button.disable(entry);      // ボタンを操作不可に切り替え
	                }
	            },
	            error: function(data){
	               alert('投票出来ませんでした')
	            }
	        });
	        
	    };
	    
	    return {
	        // ハンドラの初期化
	        dispatch: function(){
	           $('table#blockPostCont').find('td[id^="clubEntry"]').each(function(){
		            var obj     = $(this);
		            var matches = obj.attr('id').match(/^clubEntry([0-9]+)$/)
		            var entryId = matches ? matches[1] : null;
		            if(entryId != null) {
		                var entry = new Entry(entryId, true);
		                obj.find('div.itemPostBtnVote a').each(function(){
		                    entry.button = $(this);
		                    entry.button.click(function(){
		                       vote(entry);
		                       return false;
		                    });
		                });
		                obj.find('p.itemPostHeartNum').each(function(){
		                    entry.count = $(this);
		                });
		            }
		        }); 
	        }
	    }
	})();

// ハンドラのディスパッチ
Handler.Vote.dispatch();

});
