// JavaScript Document
function ajaxRating( mediaid ){
	this.mediaid = mediaid;
	this.rated = false;
	this.img = $( "ratingspan" );
	this.results = $( "currating" );
	
	/*this.img.setAttribute( "onmousemove", "rEngine.mouseMove( event, this );" );
	this.img.setAttribute( "onclick", "rEngine.ratingSubmit( event, this );" );*/
}

var a = ajaxRating.prototype;

// get a connection
a.getConnection = function(){var conn = new ajaxConnection( this, "/ajax/ratingClient" );conn.initRequestObject();conn.addVariable( "mediaid", this.mediaid );return conn;}

a.processXMLResponse = function( resultXML, action, status ){
	switch( action ){
		case "rate": this.processRateResponse( resultXML, status );
		break;
	}
}

a.mouseMove = function( e, img ){
	if( this.rated ) return;
	
	var offset = ( e.layerX ?  e.layerX : window.event.offsetX );
	var percent = Math.min( offset / img.offsetWidth * 100 );
	var num = 1;
	if( percent >= 80 ) num = 5;
	else if( percent >= 60 ) num = 4;
	else if( percent >= 40 ) num = 3;
	else if( percent >= 20 ) num = 2;
	
	img.className = 'heart-rating hrts' + num;
	//alert( img.classname );
}

a.ratingSubmit = function( e, img ){
	if( this.rated ) return;

	var offset = ( e.layerX ?  e.layerX  : window.event.offsetX );
	var percent = Math.min( offset / img.offsetWidth * 100 );
	var num = 1;
	if( percent >= 80 ) num = 5;
	else if( percent >= 60 ) num = 4;
	else if( percent >= 40 ) num = 3;
	else if( percent >= 20 ) num = 2;
	
	img.className = '';
	img.style.width = 'auto';
	img.onmousemove = null;
	img.onmouseout = null;
	img.innerHTML = 'Thanks for rating!';
	this.rated = true;
	
	var conn = this.getConnection();
	conn.addVariable( "cmd", "rate" );
	conn.addVariable( "rating", num );
	conn.execute();
}

a.forceRating = function( rating ){
	var conn = this.getConnection();
	conn.addVariable( "cmd", "rate" );
	conn.addVariable( "rating", rating );
	conn.execute();
}

a.processRateResponse = function( resultXML, status ){
	if( status == 1 ){
		var node = resultXML.getElementsByTagName( "rating" )[0];
		var rating = node.getAttribute( "value" );
		
		$( "ratingResults" ).innerHTML = "Your rating has been submitted";
		$( "ratingImg" ).src = "/images/stars_" + rating + ".gif";
	}else{
		$( "ratingResults" ).innerHTML = "Your rating could not be submitted";
	}
}
