// Require ajax.js

var lastvideodata = null;
function rate(videodataid, rate)
{	
	// Just leave if a rating is already processing
	if(lastvideodata != null) return false;
	
	var detailsobj = document.getElementById('rating_details_' + videodataid);
	try {
		Ajax._init();
	} catch(err) {
		display_message(videodataid, "Votre navigateur ne gère pas l'ajax, vous ne pouvez pas voter ! (" + err + ")", true);
		return false;
	}
	
	lastvideodata = videodataid;
	
	Ajax.query("POST", "/lib/videoratingsystem.php", "videodataid=" + videodataid + "&rate=" + rate, true, callback_rating, callback_error, 10000);
	
	display_message(videodataid, "Enregistrement en cours...", false);
	
	// Just return false to avoid link firing
	return false;
}

/* Handle ajax errors */
function callback_error(error, xmlhttp) {
	var msg = "Enregistrement impossible (" + error + ")";
	if(lastvideodata != null) {
		display_message(lastvideodata, msg, true);
		lastvideodata = null;
	} else {
		alert(msg);
	}
}

/* Handle ajax callback */
function callback_rating(xmlhttp) {
	var videodataid = lastvideodata;
	lastvideodata = null;
	var detailsobj = document.getElementById('rating_details_' + videodataid);
	
	var resp = xmlhttp.responseXML.documentElement;
	var errors = resp.getElementsByTagName('error');
	
	// Detect errors
	if(errors.length > 0) {
		display_message(videodataid, errors.item(0).firstChild.data, true);
		return;
	}
	
	display_message(videodataid, "Votre vote a été enregistré", true);
	var nbratesobj = document.getElementById('nb_rates_' + videodataid);
	var averageobj = document.getElementById('average_rate_' + videodataid);
	var stargroup = document.getElementById('stargroup_' + videodataid).getElementsByTagName('li').item(0);
	
	var nb_rates = resp.getElementsByTagName('nb_rates').item(0).firstChild.data;
	var average_rate = resp.getElementsByTagName('average_rate').item(0).firstChild.data;
	nbratesobj.innerHTML = nb_rates;
	averageobj.innerHTML = average_rate;
	stargroup.style.width = Math.round(24 * average_rate) + 'px';
}

/* Display a message in the appropriate div */
function display_message(videodataid, msg, autoreset) {
	var detailsobj = document.getElementById('rating_details_' + videodataid);
	detailsobj.firstChild.style.display = 'none';
	detailsobj.lastChild.innerHTML = msg;
	
	if(autoreset) { setTimeout("restore_details("+videodataid+")", 2000); }
}

/* Restore text in the appropriate div */
function restore_details(videodataid)
{
	var detailsobj = document.getElementById('rating_details_' + videodataid);
	detailsobj.firstChild.style.display = 'block';
	detailsobj.lastChild.innerHTML = '&nbsp;';
}

