// JavaScript Document

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 = '';
	for(i=1; i<=5; i++){
		star = i<=filledStars?"<div class=\"star_full\"></div>":"<div class=\"star_empty\"></div>";
		var a = document.createElement('a');
		a.setAttribute('href', 'javascript:void(0)');
		a.setAttribute('value', i);
		a.setAttribute('postid', id);
		//a.onmouseover = function(){preRate(this)};
		a.onclick = doRate;
		a.innerHTML = star;
		cont.appendChild(a);
	}
}
			
function preRate(el){
	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>";
		a = stars[i];
		a.innerHTML = star;
	}
}
			
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);
						
			}
		}
	);
}


/* 	END RATING STARS		 */