/******************************************************************************************************************/
/* Autor: Lor (http://www.rentacoder.com/RentACoder/SoftwareCoders/showBioInfo.asp?lngAuthorId=6749250)            */
/* Date: 30/11/2007                                                                                                */
/*                                                                                                                 */
/* Purpose of this file:                                                                                           */
/* - write, read and delete a cookie                                                                               */
/* - add a rating form on an html page, which:                                                                     */
/*      - shows current rating before and after voting,                                                            */
/*      - allows a user to vote only once (managed by a cookie)                                                    */
/*      - shows stats on how previous users voted                                                                  */
/*   the rates go from 0 to 10, by step of 0.5                                                                     */
/*******************************************************************************************************************/

/************************************************************************/
/* customisabled datas                                                  */
/* name of the php script to call                                       */
/************************************************************************/
var php_script = "rate.php";

/************************************************************************/
/* customisabled datas                                                  */
/* images : enter here the path to the full and half stars              */
/************************************************************************/
var star_half = "star2.gif";
var star_full = "star.gif";

/************************************************************************/
/* customisabled datas                                                  */
/* colors: enter here the html colors code to use on the form and popup */
/************************************************************************/
var popup_color      = "#FFD777";	// popup background
var header_color     = "#F99A21";	// table header background of the form and stats table
var body_color       = "#FFBD22";	// table body background of the form and stats table
var border_color     = "#432100";	// border color of the form and stats table
var text_color       = "#000000";	// text color
var link_color       = "#FF0000";	// link color of the form (to open the popup)
var percentage_color = "#FF0000";	// horizontal percentage statistic bars on the popup


/************************************************************************/
/* cookies management                                                   */
/* the three functions below handle the creation, reading and deletion  */
/* of cookies                                                           */
/************************************************************************/

/*
 * creates a cookie, with or without an expiration date
 * name: the name of the cookie
 * value: the value of the cookie
 * days: number of days before expiration, can be null then the cookie won't expire
 */
function createCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

/*
 * reads the content of a cookie
 * name: the name of the cookie
 */
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

/*
 * destroys a cookie
 * name: the name of the cookie
 */
function eraseCookie(name) {
	createCookie(name,"",-1);
}

/************************************************************************/
/* form management                                                      */
/* the functions below handle the display of the rating system          */
/* and the communication with the server                                */
/************************************************************************/

/*
 * writes the rating zone, with the vote results and the vote form if the user hasn't voted yet
 * form_id: the identifier of this rating form, it can be any string with white space but no ' or ", the max length is 20.
 * It must be unique for every database the site is connected to
 */
function includeRateForm(form_id) {
	// tests the cookie existence
	var form_name = "rate_" + form_id;
	var cookie_value = readCookie(form_name);

	var text = "<table align='center' cellpadding='2' cellspacing='0' width='320' style='font-family: verdana,arial,sans-serif;font-size: 11px; border:1px solid " + text_color + "; color: " + text_color + "'>"
		+ "<tr style='background-color: " + header_color + ";'>"
		+ "	<th nowrap style='border-bottom:1px solid " + border_color + ";'>User rating</th>"
		;

	// if the user hasn't voted yet, shows the vote column
	if(cookie_value == null) {
		text += "	<th nowrap width='50%' style='border-bottom:1px solid " + border_color + ";' id='div_" + form_name + "_0'>Vote</th>"
		;
	}

	text += "</tr>"
		+ "<tr style='background-color: " + body_color + "'>"
		+ "	<td nowrap align='center'>"
		+ "		Rating:"
		+ "		<span id='" + form_name + "_results'></span>"
		+ "	</td>"
		;

	// if the user hasn't voted yet, shows the vote column
	if(cookie_value == null) {
		text += "	<td nowrap align='center' id='div_" + form_name + "_1'>"
			+ "		"
			+ "		<form style='display: inline'>"
			+ "		Rate:"
			+ "		<select id='" + form_name + "' style='font-family: verdana,arial,sans-serif;font-size: 11px; color:" + border_color + "'>"
			+ "		<optgroup label='select rating'>"
			;
		for(var i=0; i<=10; i += 0.5) {
			text += "		<option value='" + i + "'" + (i == 5 ? ' selected' : '') + ">" + i + "</option>";
		}
		text += "		</optgroup>"
			+ "		</select>"
			+ "		<input type='submit' onclick=\"submitVote(\'" + form_id + "\'); return false;\" value='Vote!'  style='font-family: verdana,arial,sans-serif;font-size: 11px;color:" + border_color + "' />"
			+ "		</form>"
			+ "		"
			+ "	</td>"
			;
	}

	text += "</tr>"
		+ "</table>"
		;

	// writes the generated rating zone in the html page
	document.write(text);

	// gets the current rating for this particular form
	getVoteResults(form_id);
}

/*
 * initializes the ajax variable which allows us to communicate with the server
 */
function getXmlHttpObject() {
	var xmlHttp;
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	} catch (e) {
		// Internet Explorer
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				alert("Your browser does not support AJAX!");
				return false;
			}
		}
	}
	return xmlHttp;
}

/*
 * sends vote to the server and receive the current vote results
 * form_id: the id of the rating form we are working with
 */
function submitVote(form_id) {
	var xmlHttp = getXmlHttpObject();

	// defines the response-handling function
	xmlHttp.onreadystatechange = function() {
		if(xmlHttp.readyState == 4) { 
			// state = 4 means that we have successfully received the answer from the server
			formatVoteResults(form_id, xmlHttp.responseText);

			// hides the voting zone
			var input = document.getElementById("div_rate_" + form_id + "_0");
			input.innerHTML = "&nbsp;";
			input.style.width = "0";
			input = document.getElementById("div_rate_" + form_id + "_1");
			input.innerHTML = "&nbsp;";

			// creates a cookie to forbid the user to vote again
			createCookie("rate_" + form_id, "voted", 3650);
		}
	}

	// get the chosen rate
	var select = document.getElementById("rate_" + form_id);
	var val = select.value;

	// sends the vote to the server
	xmlHttp.open("GET", php_script + "?action=vote&rand=" + Math.random() + "&id=" + form_id + "&vote=" + val, true);
	xmlHttp.send(null);
}


/*
 * asks for the current vote results
 * form_id: the id of the rating form we are working with
 */
function getVoteResults(form_id) {
	var xmlHttp = getXmlHttpObject();

	// defines the response-handling function
	xmlHttp.onreadystatechange = function() {
		if(xmlHttp.readyState == 4) { 
			// state = 4 means that we have successfully received the answer from the server
			formatVoteResults(form_id, xmlHttp.responseText);
		}
	}

	// sends the question to the server
	xmlHttp.open("GET", php_script + "?action=getresults&rand=" + Math.random() + "&id=" + form_id, true);
	xmlHttp.send(null);
}

/*
 * voteResults contains the results returned by the server. 
 * this functions write the results and the corresponding the starts
 * form_id: the id of the rating form we are working with
 * voteResults: the resukt returned by the server. format is "current rate;nb submited votes"
 */
function formatVoteResults(form_id, voteResults) {
	var split = voteResults.split(";");
	if(split.length == 2) {
		var rate = split[0];
		var nb_vote = split[1];
		var text = "";

		// displays the right amount of stars (between 0 and 5)
		if(rate >= 2) text += "<img src='" + star_full + "'>";
		if(rate >= 4) text += "<img src='" + star_full + "'>";
		if(rate >= 6) text += "<img src='" + star_full + "'>";
		if(rate >= 8) text += "<img src='" + star_full + "'>";
		if(rate == 10) text += "<img src='" + star_full + "'>";
		if(rate%2 >= 1) text += "<img src='" + star_half + "'>";

		// displays the text giving the current rating
		if(nb_vote > 0) {
			text += "&nbsp;<a href='javascript:openStats(\"" + form_id + "\", " + rate + ", " + nb_vote + ");' style='color:" + link_color + "'>" + rate + "</a> (" + nb_vote + " vote" + (nb_vote>1 ? "s" : "") + ")";
		}
		else {
			text += "&nbsp;0 (0 vote)";
		}

		// writes the generated text on the page
		var input = document.getElementById("rate_" + form_id + "_results");
		input.innerHTML = text;
	}
	else {
		// if an error occures, the corresponding text will be writen in place of the voting results
		var input = document.getElementById("rate_" + form_id + "_results");
		input.innerHTML = voteResults;
	}
}

/************************************************************************/
/* statistics managment                                                 */
/* the functions below handle the display of the statistic popup        */
/* and the communication with the server                                */
/************************************************************************/

// window showing the stats
var window_breakdown;

/*
 * this function open a window to show the stats of a given vote
 * form_id: the id of the rating form we are working with
 * rate: the current rating for this particular form
 * nb_vote: the current amount of votes for this particular form
 */
function openStats(form_id, rate, nb_vote) {
	// creates a new window if needed
	if (!window_breakdown || window_breakdown.closed) {
		window_breakdown = window.open("","Breakdown_window","toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=450,height=450,top=50,left=50");
	}

	// clears text on the window
	window_breakdown.document.close();
	window_breakdown.document.open();
	
	// build body

	// header
	var text = "<html>"
		+ "<head><title>Rating breakdown</title></head>"
		+ "<body style='font-family: verdana,arial,sans-serif;font-size: 11px; color:" + text_color + "; background-color:" + popup_color + "'>"

		+ "<hr />"
		+ "<b>Rating Breakdown</b>"
		+ "<hr />"

		+ "<table width='100%' style='font-family: verdana,arial,sans-serif;font-size: 11px; color:" + text_color + "; background-color:" + popup_color + "'>"
		+ "<tr>"
		+ "<td align='center'>"
		+ "Rating: "
		;

	window_breakdown.document.write(text); text = "";

	// shows the stars
	if(rate >= 2) text += "<img src='" + star_full + "'>";
	if(rate >= 4) text += "<img src='" + star_full + "'>";
	if(rate >= 6) text += "<img src='" + star_full + "'>";
	if(rate >= 8) text += "<img src='" + star_full + "'>";
	if(rate == 10) text += "<img src='" + star_full + "'>";
	if(rate%2 >= 1) text += "<img src='" + star_half + "'>";

	// shows the current rating
	text += "&nbsp;" + rate + " (" + nb_vote + " vote" + (nb_vote>1 ? "s" : "") + ")"
		+ "</td>"
		+ "</tr>"
		+ "<tr>"
		+ "<td>"

		// statistic table header
		+ "<table width='400' cellspacing='0' style='font-family: verdana,arial,sans-serif;font-size: 11px; color:" + text_color + "; border:1px solid " + border_color + ";' align='center'>"
		+ "<tr style='background-color: " + header_color + ";'>"
		+ "<td align='center' style='border-bottom:1px solid " + border_color + ";' colspan='2'>Vote</td>"
		+ "<td align='center' style='border-bottom:1px solid " + border_color + ";'>Percentage</td>"
		+ "<td align='center' style='border-bottom:1px solid " + border_color + ";' colspan='2'>Rating</td>"
		+ "</tr>"
		;

	window_breakdown.document.write(text); text = "";

	// statistic table lines
	// the lines are empty for now, we will ask later the server for the statistics
	for(var i=10; i>=0; i-=0.5) {
		text += "<tr style='background-color: " + body_color + ";'>"
			+ "<td width='50' align='right'>&nbsp;<span id='stat_vote_" + form_id + "_" + i + "'></span>&nbsp;</td>"
			+ "<td>&nbsp;</td>"

			+ "<td align='center'>&nbsp;<span id='stat_percentage_" + form_id + "_" + i + "'></span>&nbsp;</td>"

			+ "<td width='50' align='right'>&nbsp;" + i + "&nbsp;</td>"
			+ "<td>&nbsp;</td>"
			+ "</tr>"
			;
		window_breakdown.document.write(text); text = "";
	}

	text += "</table>"

		+ "</td>"
		+ "</tr>"
		+ "</table>"
		+ "</body>"
		+ "</html>"
		;

	// writes the generated text
	window_breakdown.document.write(text);

	// gives the focus to the popup
	window_breakdown.focus();

	// asks the server for the statistics
	getVoteStats(form_id);
}

/*
 * asks for stats for a given form
 * form_id: the id of the rating form we are working with
 */
function getVoteStats(form_id) {
	var xmlHttp = getXmlHttpObject();

	// defines the response-handling function
	xmlHttp.onreadystatechange = function() {
		if(xmlHttp.readyState == 4) { 
			// state = 4 means that we have successfully received the answer from the server

			// the server response has the following format:
			// rate1;nb votes1;rate2;nb votes 2;...;nb votes total
			// there is no "rate;nb vote" couple if nb vote is equal to 0 fot this rate

			var split = xmlHttp.responseText.split(";");
			var arr = new Array();
			var max = 0;
			for(var i=0; i<split.length-1; i+=2) {
				// put in an array all the results returned by the server
				var rate = parseFloat(split[i]);
				var nb = parseFloat(split[i + 1]);
				if(nb > max) max = nb;
			
				arr[rate] = nb;
			}

			var total = split[split.length - 1];
			var tablewidth = 200;

			// computes the width of the statistic bar and writes values on the predinfined zone of the popup
			for(var i=0; i<=10; i+=0.5) {
				var nb = arr[i];
				if(nb == undefined || nb == 0) nb = "0";

				var width = nb * tablewidth / max;
				if(width == 0) width = 1;
				if(width == tablewidth) width = tablewidth - 1;
				
				if(nb == 0) nb = "-";
				
				var output = window_breakdown.document.getElementById("stat_vote_" + form_id + "_" + i);
				output.innerHTML = nb;
				
				output = window_breakdown.document.getElementById("stat_percentage_" + form_id + "_" + i);
				output.innerHTML = "<table height='2' style='display: inline'><tr><td width='"+width+"' style='background-color:" + percentage_color + "'></td><td width='"+(tablewidth - width)+"'></td></tr></table>";
			}
		}
	}

	// sends the question to the server
	xmlHttp.open("GET", php_script + "?action=getstats&rand=" + Math.random() + "&id=" + form_id, true);
	xmlHttp.send(null);
}
