// JavaScript Document
var prerate = new Boolean();

function clearDefault(el) {
  if (el.defaultValue==el.value) el.value = "";
}

function set_rating(rating, id){
	if(rating < 0) rating = 0;
	if(rating > 5) rating = 5;
	filledStars = Math.round(rating);
	cont = document.getElementById('rating_'+id);	
	cont.onmouseout = function(){set_rating(rating, id);};
	cont.innerHTML = '';
	var randu = Math.floor((3)*Math.random()) + 4; // Rating filler
	for(i=1; i<=5; i++){
		prerate = true;
		star = i<=filledStars?"<div class=\"star_full\"></div>":"<div class=\"star_empty\"></div>";
		if (rating==0&&i==5&&randu==5) star = "<div class=\"star_empty\"></div>"; // Rating filler
		else if (rating==0) star = "<div class=\"star_full\"></div>"; // Rating filler
		var a = document.createElement('a');
		a.setAttribute('href', 'javascript:void(0)');
		a.setAttribute('value', i);
		a.setAttribute('postid', id);
		a.onmouseover = function(){if(prerate){preRate(this);}};
		a.onclick = doRate;
		a.innerHTML = star;
		cont.appendChild(a);
	}
}
			
function preRate(el){
	prerate = false;
	num = el.getAttribute('value');
	if(num <= 0) return false;
	cont = el.parentNode;
	if(!cont) return false;
	stars = cont.getElementsByTagName('a');
	if(num > stars.length) num = stars.length;
	for(i=0; i<stars.length; i++){
	
		star = i<num?"<div class=\"star_full\"></div>":"<div class=\"star_empty\"></div>";
		var a = stars[i];
		try {
			a.innerHTML = star;
		} catch(e) {
			alert("Error: " + e.description);
		}
		
	}
	return;
}
			
function doRate(){
	if(this.nodeName != 'A') return console.log(this.nodeName);
	id = this.getAttribute('postid');
	rate = this.getAttribute('value');
	new Ajax.Request(
	"/index.php",
		{
			method: 'post',
			parameters: $H(
				{
					'cmd': 'rate',
					'post_id': id,
					'rate': rate
				}
			),
			
			onSuccess: function(req){
				obj=req.responseJSON;
				set_rating(obj.rating, id);
						
			}
		}
	);
	return;
}

