var currentId = null;
var VOTES = "votes";
var MEMO = "memo";
var MEMOS = "memos";
var CLICK = "click";

/**
 * bind listeners to methods
 */
Bootstrap.add(function() {
	// digimemos
	$A($(MEMOS).getElementsByTagName("a")).each(function(ele) {
		if(ele.id.startsWith(MEMO)) {
			Event.observe(ele, CLICK, showRating.bind(this, ele), false);
		}
	});
	// ratings
	$A(document.getElementsByClassName("num")).each(function(ele, index) {
		Event.observe(ele, CLICK, rateMemo.bind(this, index + 1), false);
	});
	// close rating
	Event.observe("close_votes", CLICK, hideRating, false);
});

/**
 * displays the rating element below the selected memo
 * 
 * @param target
 * 			the current selected memo
 */
function showRating(target) {
	if(!isNaN(parseInt(currentId = target.id.replace(/memo_/, "")))) {
		$A($(MEMOS).getElementsByTagName("tr")).each(function(ele) {
			if(ele.id == "m_" + currentId) {
				$(MEMOS).insertBefore($(VOTES), ele.nextSibling);
				$("memo_name").innerHTML = target.innerHTML;
				Element.show(VOTES);
				return;
			}
		});
		showMemo(currentId);
	}
}   

/**
 * convenience method for hiding the rating element
 */
function hideRating() {
	Element.hide(VOTES);
}

/**
 * increase the currrent selected memo points with the given rate
 * 
 * @param rate
 * 			the rate to increase
 */
function rateMemo(rate) {
    if(currentId && rate && (rate > 0 && rate <= 10)) {
        AjaxFacade.rateMemo(currentId, rate, function(count) {
        	hideRating();
            if(count > 0) {
                $("s_" + currentId).innerHTML = count;
            }   
        }); 
    }   
} 
