/*
 * cencuestas.js
 * Marcelo Gutierrez
 */
var cencuestas = new Class({
	Implements: [Events, Options]
	         	,
	options : {
		formId:'encuesta1'
		,containerId : 'contenedor-encuesta'
		,voteAction: 'cencuestas.mostrar.php'
		,loadAction: 'cencuestas.mostrar.php'
        ,historyUrl:''	
	}
	,initialize: function(options){
		this.setOptions(options);
		
		this.options.form = new Element('form', {id: this.options.formId, name: this.options.formId}); 
		this.options.form.wraps($(this.options.containerId));
		this.doAction();
	}
	,doAction: function(mode)
	{
		mode = mode || 'load';
		var form = this.options.form;
		
		if(mode=='load')
			form.action = this.options.loadAction;
		else
			form.action = this.options.voteAction;
		
		var Div=$(this.options.containerId);
		var yo = this;
		var oReq = new Request(
		{
			url:form.action
			,method:'post'
			,onSuccess:function(responseText,responseXML)
			{
				Div.innerHTML = responseText;
				$$('#'+yo.options.containerId+' a.enc-voto').each(function(el){
					el.addEvent('click',function(){
						if(el.rel=='')
							return;
						yo.options.form.iIdEncuestaDet.value = el.rel;
						yo.options.form.modo.value = 'vot';
						yo.doAction('vote');	
					})
				});
                
                $$('#'+yo.options.containerId+' a.btn-resultados').each(function(el){
					el.addEvent('click',function(){
						if(el.rel=='')
							return;
						yo.options.form.iIdEncuestaDet.value = el.rel;
						yo.options.form.modo.value = 'res';
						yo.doAction('vote');
					})
				});
                
                $$('#'+yo.options.containerId+' a.btn-volver').each(function(el){
					el.addEvent('click',function(){
						if(el.rel=='')
							return;
						yo.options.form.iIdEncuestaDet.value = el.rel;
						yo.options.form.modo.value = '';
						yo.doAction();
					})
				});
                var irHist = $('encuesta-ir-historial');
                if(irHist!=null)
                    irHist.href=yo.options.historyUrl;              
			}
			,onFailure:function(e)
			{
				alert('Ohh no... Ha ocurrido un problema en la solicitud enviada!!');
				Div.innerHTML = '';
			}
			,onComplete:function(){}
			,onRequest:function()
			{
				Div.innerHTML = '<span class="loader-small">Actualizando...</span>';
			}
		}
		);
		oReq.send(form.toQueryString());
	}
});
