var RateManager = function(){
	
	var prefixList = [""];
	var requestUrl = "/rate_manager";
	
	function showTools(e){
		var el = $(this);
		el.find("DIV.rate-info").hide();
		el.find('DIV.rate-view').show();
		el.find("DIV.rate-info").html(this.attributes.agree.nodeValue+" за, "+this.attributes.not_agree.nodeValue+" против");
		setTimeout(function(){ el.find("DIV.rate-info").show('fast'); }, 500);
	}
	
	function hideTools(e){
		$(this).find('DIV.rate-view').hide();
	}
	
	return{
		init: function(){
			$("DIV.rate-container").mouseover(showTools);
			$("DIV.rate-container").mouseout(hideTools);
		},
		
		sendRequest: function(id, type, rate){
			var params = {action: "createRating", id: id, type: type, rate: rate};
			$.ajax({
				type: "POST",
				url: requestUrl,
				data: params,
				dataType: "json",
				params: params,
				success: function(data, status){
					RateManager.onSuccess(this, data);
				},
				error: function (XMLHttpRequest, textStatus, errorThrown) {
					
				}
			});
		},
		
		onSuccess: function(request, data){
			var baseId = "rate_"+request.params.type.toLowerCase()+"_"+request.params.id;
			var ln = prefixList.length;
			for(var i=0; i<ln; i++){
				var containerId = (prefixList[i] == "")? baseId : prefixList[i]+"_"+baseId;
				var container = $("#"+(containerId));
				if(container.length){
					container[0].attributes.agree.nodeValue = data.agree;
					container[0].attributes.not_agree.nodeValue = data.not_agree;
					container.find('DIV.rating').html(data.rate);
					container.find('DIV.rating').removeClass('green');
					container.find('DIV.rating').removeClass('grey');
					container.find('DIV.rating').removeClass('red');
					if(data.rate <0) {
						container.find('DIV.rating').addClass('red');	
					}
					if(data.rate ==0) {
						container.find('DIV.rating').addClass('grey');	
					}
					if(data.rate >0) {
						container.find('DIV.rating').addClass('green');	
					}
					container.find('DIV.rate-up').remove();
					container.find('DIV.rate-down').remove();
					var rateView = container.children("DIV.rate-view");
					rateView.removeClass('rate-view-active');
					rateView.addClass('rate-view-inactive');
					rateView.hide();
				}
			}
		},
		
		addUsablePrefix: function(prefix){
			prefixList[prefixList.length] = prefix;
		},
		
		setRequestUrl: function(url){
			requestUrl = url;
		}
	}
}();

$(document).ready(function(){
   RateManager.init();
});


