/**
 * aPoll Voting Component
 *
 * @version     $Id: mod_apoll.js 156 2011-01-30 16:33:35Z harrygg $
 * @package     Joomla
 * @copyright   Copyright (C) 2009 - 2010 aFactory. All rights reserved.
 * @license     GNU/GPL, see LICENSE.php
 */

var apollVoteClass = new Class ({

	options: {
		container : '',
		poll_id : 0,
		form : '',
		formOptions : '',
		submitBtn : '',
		loadingDiv : '',
		responseJSON : '',
		showTotal : 1,
		apollRefreshBtn: ''
	},
	Implements: [Options,Events],
	initialize: function(container, options) {
	
		//settings
		this.container = document.id(container);
		this.form = container.getElementsByTagName('form')[0];
		this.poll_id = container.id.substr(10);
		
		this.setOptions(options);
		
		// initialize options and add events to the form if the form exists
		if(this.form) {
			// get the poll options
			this.formOptions = container.getElements('input[type="radio"]');
			this.submitBtn = this.form.getElement('input[type="submit"]');
			this.loadingDiv = container.getElement('div[id^="apoll_loading"]');
			this.showTotal = this.form.getElement('input[name="show_total"]').value;
			
			this.form.addEvents({
				submit: function(e) { 
					if(e) e.stop();
					if(this.checkSelected()){
						this.submitForm(); 
					}
				}.bind(this)
			 
			});		
		// if the form doesn't exist we are showing the results
		} else {
                        var self = this;
			this.apollRefreshBtn = document.id('apoll_refresh_btn_' + this.poll_id);
			this.apollRefreshBtn.addEvent('click', function(e){
				if(e) e.stop();
				self.refreshBtnRequest();
        });		
		
		}
    },
	// METHODS
	// function to check if we have selected an options
	checkSelected : function() {
		var noSelection = true;
		this.formOptions.each(function (e){
            // check if there is a selected option
            if(e.checked == 1) {
					noSelection = false;
				}
        });
		// if no option is selected raise an alert
		if (noSelection) {
			alert(Joomla.JText._('MOD_APOLL_PLEASE_SELECT_AN_OPTION','Please select an option'));
			return false;
		}		
		return true;
	},
	
	// function to send the request
	submitForm : function() {
		var self = this;
		// disable the submit button
		this.submitBtn.disabled = true;
		// add the loading img
		this.loadingDiv.setStyle('display','');
		// set the request 
		this.form.set('send', {
			//onFailure: function() {console.log('Failure');},
			//onComplete: function() {console.log('Setting the form completed')},
			onSuccess: function(response) {
				//DEBUG
				//console.log('Success');
				// parse the txt response to convert it to JSON
				self.responseJSON = JSON.parse(response);
				// draw the XHTML
				self.drawResults();
				//update the results
				self.updateResults();
			}
		});

		this.form.send();
	},
	
	// function to draw the bars on the page
	drawResults : function(responseJSON) {

		this.loadingDiv.setStyle('display','none');
		// prepare the results
		var _html = new Element('div');
		var options = this.responseJSON.options;

		options.each( function(e, i){
			var inner = new Element('div');
			new Element('div', {class : 'apoll_options_text_div'}).inject(inner);
			var apoll_options_container = new Element ('div', {class : 'apoll_options_container'}).inject(inner);
			// create the bar and inject it into the container
			new Element('div', {class:'apoll_bars'}).inject(apoll_options_container);

			inner.inject(_html);
		});

		// empty the container and inject the results
		_html.inject(this.container.empty());
		
		
		// create the total votes text and add it to the DOM if allowed
		if(this.showTotal != 0) {
			new Element('br').inject(this.container);
			new Element('b', {html: Joomla.JText._('MOD_APOLL_TOTAL_VOTES', 'Total votes')}).inject(this.container);
			new Element('span', {id: "apoll_total_votes", html: this.responseJSON.total_votes}).inject(this.container);
		}

		// create the refresh button and inject it
		this.createRefreshBtn();
	
	},
	
	// method to update the results
	updateResults : function() {
		
		var self = this;
		var options = this.responseJSON.options;
		var options_text = this.container.getElements('div.apoll_options_text_div');
		var options_bars = this.container.getElements('div.apoll_bars');

		options.each( function(e, i) {
			var percent = self.calcPercent(e.votes, self.responseJSON.total_votes);
			var width   = percent ? parseInt(percent) + '%' : '2px';

			options_text[i].empty().set('html', e.text + ' - ' + percent  + '%');
			options_bars[i].setStyle('width', width).setStyle('background-color', e.color);
		});

		//update the total votes if they exists
		var total = this.container.getElement('span');
		if(total) {total.set('html', this.responseJSON.total_votes);}
		
		// check for errors and show them. If we are not allowed to show errors there will be no errors at all.
		if(this.responseJSON.error) {
			new Element('span', {class: 'apoll_error_msg', html: Joomla.JText._(this.responseJSON.error)}).inject(this.container);
		}
	
	},
	
	// method to calculate the percentage for given votesh returns float 00.00
	calcPercent : function(votes, totalVotes) {
	    var percent = Math.round(parseFloat(votes*100/totalVotes)*10)/10;
		return percent;
	},
	
	// method to create a refresh-results-button
	createRefreshBtn : function() {
		var self = this;
		//create the refresh button and prepare its logic
		this.apollRefreshBtn = new Element('a', {
			id     : 'apoll_refresh_btn_' + self.poll_id,
			class  : 'apoll_refresh_btn',
			href   : '',
			html   : Joomla.JText._('MOD_APOLL_REFRESH_RESULTS', 'Refresh results'),
			events : {
                            click : function(e){
                                if(e) e.stop();
                                //make the ajax call
                                self.refreshBtnRequest();
                            }
			}
		}).inject(self.container);
	},
	
	// Method to create Request for the refresh button
	refreshBtnRequest : function() {
		var self = this;
		//make the ajax call
		new Request.JSON({
				data: {'option':'com_apoll', 'poll_id' : self.poll_id, 'apoll_option' : 0, 'view' : 'poll', 'format':'json'},
				onRequest: function() {
					// we need to find the created refresh button
					document.id('apoll_refresh_btn_' + self.poll_id).addClass('apoll_loading_img');
				},
				onSuccess: function(responseJSON) {
					// update the results
					self.responseJSON = responseJSON;
					document.id('apoll_refresh_btn_' + self.poll_id).removeClass('apoll_loading_img');
					//update the results
					self.updateResults();
				}
		}).send();	
	}
});



