/**
* Genform front manager
* Manage javascript module Genform in front
* @author Altiplano.fr
* @date 09/14/2009
*/

var GfFrontManager = {

/**
* Action to do when the poll form is submitted
* Make a server call to save the vote and display a graph with results
*/
	vote : function(){
		var that = this;

		// Retrieve poll container, this will be the replaced element (replaced by the chart)
		var poll = $('poll');
		var size = poll.getSize();

		// Retrieve form
		var form = poll.getElements('form')[0];
		
		// Retrieve form id 
		var formId = form.genformId.value;
		
		var answers = {};

		var response = "";
		// Retrieve the visitor response to the poll and stock the other response
		for(var i = 0 ; i < form.pollResponse.length ; i++){
			if(form.pollResponse[i].checked)
				response = form.pollResponse[i].value;
			else
				answers[form.pollResponse[i].value] = form.pollResponse[i].value;
		}

		// If we have a response
		if(response){
			// Send response to server with form id
			// Ajax request
			var url = '/genform/poll/save-vote';
			
			poll.empty().addClass('ajax-loading');
			
			var ajaxRequest = new Request.HTML({
				url : url,
				method: 'post',
				encoding: 'uft-8',
				onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript){
					poll.removeClass('ajax-loading');
					// If we have a result generate chart
					if(responseHTML){
						//that.generateChart(poll, res);
						poll.innerHTML = responseHTML;
					}
				},
				data : {
					response: response,
					answers: answers,
					formId: formId
				}
			});

			ajaxRequest.send();		
		}
	},
	
		
	/**
	* Action to do when the a contact form is in ajax mode and has no particulary action to perform
	* Make a server call to send the email
	* @param form The form element
	*/
	send : function(form){
		form.id = 'contactForm';
		$('contactForm').addClass('ajax-loading');

		form.set('send', {onComplete: function(response) {
		  form.removeClass('ajax-loading');
			form.getChildren('fieldset').getChildren('ul').each(function(ul) {
				ul.getChildren('li').each(function(li) {			  
					li.removeClass('error');
					li.getChildren('p').each(function(p){
						p.destroy();
					});
				});
			});
			var messages = eval('(' + response + ')');
		  if(messages['success']){
			  var messageDiv = new Element('div', {
			   'class': 'form-result',
			   'html': '<p>'+messages['successMessage']+'</p>'
			  });	
			  messageDiv.inject(form, 'before');
				form.destroy();
			} else{
				for(var error in messages['errors']){
					var nextSibling = new Element('p');
					nextSibling.inject(error, 'after');
					nextSibling.getParent().addClass('error');
					for(var message in messages['errors'][error])
						nextSibling.set('text', messages['errors'][error][message]);
		    }
		  }
		}});
		//Send the form.
		form.send();
	}
		
};
