/*
Author: Mathieu Laurent
Modified: Belhomme Nick
Copyright: Skynet Belgacom
This file handles the Quickpoll Javascript functions
all javascript must be in this file and not embedded in html
please use the dom of the html
*/

function Skynet_JS_Quickpoll() {

	var select_box = ".quickpoll_box";
	var select_form_box = ".quickpoll_form";
	var select_result_box = ".quickpoll_result";
	var cookie_prefix = "qpa_";
	var qp_id_prefix = "quickpoll_id_";

	this.init = function()
	{
		jQuery(select_box).each(function() {
			var qpId = getId(jQuery(this));
			var cookie_name = cookie_prefix + qpId;
			var jEltForm = jQuery(select_form_box,jQuery(this));
			var jEltResult = jQuery(select_result_box,jQuery(this));
			if ( readCookie(cookie_name) == '1' ) {
				jEltForm.hide();
				jEltResult.show();
			} else {
				jEltForm.show();
				jEltResult.hide();
				jQuery('form',jQuery(this)).submit( function() {
					vote(jQuery(this),qpId);
					return false;
				});
			}
		});
	}

	function vote(jElt, qpId) {
		var answerId = jElt.find('input[name=answer]:checked').val();
		var jEltBox = jQuery(jElt).parents(select_box,jElt);
		var jEltForm = jQuery(select_form_box,jEltBox);
		var jEltResult = jQuery(select_result_box,jEltBox);

		if ( answerId == undefined ) {
			return false;
		} else {
	        jQuery.ajax({
	            url: "/ajax/quickpoll",
	            data: "answer_id=" + answerId + "&quickpoll_id=" + qpId,
	            success: function(message){
					jEltForm.hide();
					jEltResult.show();
	                },
	            dataType: "json"});
			return false;
		}
	}

	function getId(jElt) {
		var id = jElt.attr('id');
		return id.substring(qp_id_prefix.length,id.length);
	}

	function readCookie(name) {
		var start = document.cookie.indexOf( name + "=" );
		var len = start + name.length + 1;
		if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
			return null;
		}
		if ( start == -1 ) return null;

		var end = document.cookie.indexOf( ';', len );
		if ( end == -1 ) end = document.cookie.length;
		return unescape( document.cookie.substring( len, end ) );
	}

};

jQuery(function() {
	var qp = new Skynet_JS_Quickpoll();
	qp.init();
});