/* funzioni per il rating [marzia 2008 02 06] */


var cookiesOpt = {
	expireTime: 30 * 60 * 1000, // millisecondi
	//expireTime: 1 * 60 * 1000, // millisecondi
	cookieName: new Template('t5info_votingCookie_#{uuid}')
};

var manageRating = Class.create();

manageRating.prototype = {
	initialize:function (hasVoted, projectId, contentType, contentId, title, urlpath, readonly){
		/* formato currentcontent: {uuid: id del contenuto, numVotes: numero voti corrente}*/
		this.currentContent = {
			projectId: projectId, 
			contentType: contentType, 
			contentId: contentId, 
			title: title,
			urlpath: urlpath,
			numVotes: 0,
			hasVoted: hasVoted
		};
		
		this.isTest = false;

		if (readonly != undefined) this.readonly = readonly;
			else this.readonly = false;
		this.results = {};
		
		// gli array che contengono i descrittori per gli eventi
		if(!readonly){
			this.eventClick = new Array();
			this.eventOver = new Array();
			this.eventOut = new Array();
			this.checkCookies();
		}
		
		this.getCurrentVotes(this.currentContent.numVotes);
		if(!this.currentContent.hasVoted && (!readonly))
			this.enableStars();
	},
	
	starHover: function(index){
		for(i = 0; i <= index; i++)
			$$('#vote img')[i].src = '/informativos/formula1/res/images/ico_star_orange.png';
	},

	starOut: function(index){
		for(i = 0; i <= index; i++)
			$$('#vote img')[i].src = '/informativos/formula1/res/images/ico_star_grey.png';
	},

	submitRating: function(index){
		/* index e' l'indice della stellina che e' stata cliccata */
		/* valore del rating = index */
		if (this.currentContent.hasVoted)	{}
		else {
			/* servlet per il submit dei voti */
			new Ajax.Request('/Commenti/VotingInserter?ran='+Math.random(), { 
				method: 'post', 
				parameters: {
					project_id: this.currentContent.projectId, 
					content_type_id: this.currentContent.contentType,
					content_item_id: this.currentContent.contentId, 
					voto: index, /* da 1 a 5 */
					freeText1: this.currentContent.title,
					freeText2: this.currentContent.urlpath
				} 
			});
			/* fine della servlet */
			var rating = this;
			
			if ( rating.results.numeroVoti == 0 || rating.results.numeroVoti == NaN || rating.results.numeroVoti == undefined)
				rating.results.numeroVoti = 1;
			else rating.results.numeroVoti++;
			
			this.currentContent.hasVoted = 1;
			this.updateCookies();
			this.disableStars();
			$('num_votes').update(rating.results.numeroVoti + " votos");				
		}
	},
	
	getCurrentVotes: function(cookieVotes){
		/* prendo il valore corrente dei voti e lo inserisco nell'html. Prendo la media dei voti e determino la grandezza del div che "colora" le stelline. */

		var rating = this;
		new Ajax.Request('/Commenti/voting/basicGetVoti.jsp?ran=' + Math.random(), { 
			method: 'get',
			parameters: { 
				project_id: this.currentContent.projectId,
				content_type_id: this.currentContent.contentType,
				content_item_id: this.currentContent.contentId 
			},
			onSuccess: function(response) {

				/* FORMATO DEL PACCHETTO RICEVUTO: 
					<voti projecId="5" contentTypeId="detail" contentItemId="25" >
						<PROJECTID>5</PROJECTID>
						<CONTENTTYPEID>detail</CONTENTTYPEID>
						<CONTENTITEMID>25</CONTENTITEMID>
						<TITLE>Una compa&ntilde;&iacute;a "espa&ntilde;ola" construir&aacute; la mayor planta solar del mundo</TITLE>
						<VOTO_01>2</VOTO_01>
						<VOTO_02>1</VOTO_02>
						<VOTO_03>1</VOTO_03>
						<VOTO_04>1</VOTO_04>
						<VOTO_05>1</VOTO_05>
						<VOTO_06>0</VOTO_06>
						<VOTO_07>0</VOTO_07>
						<VOTO_08>0</VOTO_08>
						<VOTO_09>0</VOTO_09>
						<VOTO_10>0</VOTO_10>
						<TOTALE>1</TOTALE> 
  					<avg>4.0</avg> 
					</voti>
				*/
				/* Modificato Daniele 7/3/2008
				var voti = new Array(10);
				voti[0] = parseInt(response.responseXML.getElementsByTagName('VOTO_01')[0].firstChild.nodeValue);// numero di persone che hanno votato 1
				voti[1] = parseInt(response.responseXML.getElementsByTagName('VOTO_02')[0].firstChild.nodeValue);
				voti[2] = parseInt(response.responseXML.getElementsByTagName('VOTO_03')[0].firstChild.nodeValue);
				voti[3] = parseInt(response.responseXML.getElementsByTagName('VOTO_04')[0].firstChild.nodeValue);
				voti[4] = parseInt(response.responseXML.getElementsByTagName('VOTO_05')[0].firstChild.nodeValue);
				voti[5] = parseInt(response.responseXML.getElementsByTagName('VOTO_06')[0].firstChild.nodeValue);
				voti[6] = parseInt(response.responseXML.getElementsByTagName('VOTO_07')[0].firstChild.nodeValue);
				voti[7] = parseInt(response.responseXML.getElementsByTagName('VOTO_08')[0].firstChild.nodeValue);
				voti[8] = parseInt(response.responseXML.getElementsByTagName('VOTO_09')[0].firstChild.nodeValue);
				voti[9] = parseInt(response.responseXML.getElementsByTagName('VOTO_10')[0].firstChild.nodeValue);
				
				rating.results = rating.getAverageVote(voti);
				if (!rating.readonly){
					if (rating.results.numeroVoti > cookieVotes)
						$('num_votes').update(rating.results.numeroVoti + " votes");	
					else $('num_votes').update(cookieVotes + " votes");	
				
					$$('.star_rating')[0].setStyle({width: rating.results.vtWidth + 'px'});
				}else {
					$$('#star' + rating.currentContent.contentId + ' .num_votes')[0].update(rating.results.numeroVoti + "votes");
					//$$('#star' + rating.currentContent.contentId + ' .star_rating')[0].setStyle({width: rating.results.vtWidth + 'px'});
				}
				*/

				var tot_stars = 5; // numero totale delle stelline nella votazione
				var bgWidth = 80; // la dimensione del div background con le stelline grigie
				var numeroVoti = parseInt(response.responseXML.getElementsByTagName('TOTALE')[0].firstChild.nodeValue);
				var average = parseFloat(response.responseXML.getElementsByTagName('avg')[0].firstChild.nodeValue);
				// la dimensione del div che contiene le stelline rosse:
				var vtWidth = Math.floor((average * bgWidth)/tot_stars);
				
				var results = {
					vtWidth : vtWidth,
					numeroVoti: numeroVoti
				}
				rating.results = results;
				
				if (!rating.readonly){
					if (rating.results.numeroVoti > cookieVotes)
						$('num_votes').update(rating.results.numeroVoti + " votos");	
					else $('num_votes').update(cookieVotes + " votos");	
				
					$$('.star_rating')[0].setStyle({width: rating.results.vtWidth + 'px'});
				}else {
					$$('#star' + rating.currentContent.contentId + ' .num_votes')[0].update(rating.results.numeroVoti + "votos");
				}
			}
		});

	},
	
	getAverageVote: function(voti) {
		var tot_stars = 5; // numero totale delle stelline nella votazione
		var valoreVoti = 0;
		var numeroVoti = 0;
		var bgWidth = 0; // la dimensione del div background con le stelline grigie
		var vtWidth = 0; // la dimensione del div che contiene le stelline rosse
		var average = 0;
		
		for(var i = 0; i < tot_stars; i++){
			valoreVoti = valoreVoti + (voti[i] * (i+1));
			numeroVoti = numeroVoti + voti[i];
		}
		
		if(numeroVoti != 0)
			average = Math.round(valoreVoti / numeroVoti);
		else average = 0;	// media tra 1 e 5	
		// calcolo la dimensione del div che colora le stelline.
		if (bgWidth == 0 || bgWidth == undefined) {
			// la dimensione che dovrebbe avere presa dal css. Questo nel caso non venga recuperata per qualche motivo.
			bgWidth = 80; 
		}
		vtWidth = Math.floor((average * bgWidth)/tot_stars);
		var results = {
			vtWidth : vtWidth,
			numeroVoti: numeroVoti
		}
		return results;
	},
	
	enableStars: function() {
		// abilito le stelle e aggancio gli eventi
		$$('#vote img').each(function(star, pos){
			// aggancio i descrittori
			this.eventClick[pos] = this.submitRating.bind(this, pos +1);
			this.eventOver[pos] = this.starHover.bind(this, pos);
			this.eventOut[pos] = this.starOut.bind(this, pos);
			// aggancio gli eventi
			Event.observe(star, 'click', this.eventClick[pos]);
			Event.observe(star, 'mouseover', this.eventOver[pos]);
			Event.observe(star, 'mouseout', this.eventOut[pos]);
			star.setStyle({cursor: 'hand', cursor: 'pointer'});
		}.bind(this));
	},
	
	disableStars: function(){
		$$('#vote img').each(function(star, pos){
			Event.stopObserving (star, 'click', this.eventClick[pos]);
			Event.stopObserving (star, 'mouseover', this.eventOver[pos]);
			Event.stopObserving (star, 'mouseout', this.eventOut[pos]);
			star.setStyle({cursor: 'normal'});
			star.src = '/informativos/formula1/res/images/ico_star_grey.png';
		}.bind(this));
	},
	
	updateCookies: function(){
		//window.alert(parseInt($('num_votes').firstChild.nodeValue));
		/* se l'utente ha gia' votato, non devo fare niente. Altrimenti devo creare il "biscottino" */
		if(!this.hasVoted){
			var cookieName = cookiesOpt.cookieName.evaluate(this.currentContent);	
			var expireDate = new Date();
			expireDate.setTime(expireDate.getTime() + cookiesOpt.expireTime);
			document.cookie = cookieName + '=' + (parseInt($('num_votes').firstChild.nodeValue) + 1) +  '; expires=' + expireDate.toGMTString();			
		}
			
	},

	checkCookies: function(){
		// verifica che sia possibile votare per il contenuto verificando che sia presente il cookie e ritorna un booleano
		var cookieName = cookiesOpt.cookieName.evaluate(this.currentContent);	
		var regexp = new RegExp(cookieName + '=([^ ;]+)');
		var result = regexp.exec(document.cookie);
		
		// result 1 contiene il numero di voti che ho salvato nel cookie
		this.currentContent.hasVoted = !(result == null);	
		if (this.currentContent.hasVoted)
			this.currentContent.numVotes =  result[1];
		else this.currentContent.numVotes = 0;
	}
}