/** ankieta */

function Survey(args){
	dojo.safeMixin(this, args);
	this.init();
}

Survey.prototype = {

	init: function(){
		this.events = {};
		this.connect();
	},
	
	result: function(event){
		event.preventDefault();
		this.uri = dojo.query('#ankietaAjax_' + this.ID + ' .surveyViewResults')[0].getAttribute('href');
		this.form = null;
		this.get();
	},
	
	back: function(event){
		event.preventDefault();
		this.uri = dojo.query('#ankietaAjax_' + this.ID + ' .surveyBackToSurvey')[0].getAttribute('href');
		this.form = null; 
		this.get(); 
	},
	
	vote: function(event){
		event.preventDefault();
		this.uri = '/pub/sess/usersurvey';
		this.form = 'usForm_' + this.ID;
		if(this.hasVoted()){
			this.get();
		}
	},
	
	connect: function(){
		this.events.glosuj = dojo.connect(dojo.byId('glosuj_' + this.ID), 'click', this, 'vote');
		this.events.vote = dojo.connect(dojo.byId('viewResults_' + this.ID), 'click', this, 'result');
		this.events.back = dojo.connect(dojo.byId('backToSurvey_' + this.ID), 'click', this, 'back');
	},
	
	disconnect: function() {
		dojo.disconnect(this.events.glosuj);
		dojo.disconnect(this.events.vote);
		dojo.disconnect(this.events.back);
	},
	
	hasVoted: function(){
		var radios = dojo.query('#usForm_' + this.ID + ' input[type="radio"]:checked');
		if(radios.length > 0){
			return true;
		}
		return false;
	},
	
	get: function(){
		var $this = this;
		var bindArgs = {
			url: this.uri,
			handle: function (data, ioArgs) {
					$this.disconnect();
					dojo.byId("ankietaAjax_" + $this.ID).innerHTML = data;
					$this.connect();
			},
			error: function (data) {
				console.error('Wystapil blad: ', data);
			},
			form: this.form
		}
		
		dojo.xhrGet(bindArgs);
	}
}

dojo.addOnLoad(function(){
	dojo.query('div.surveyAnkieta[id^="ankieta_"]').forEach(function(currentNode, currentIndex){
		var s = new Survey({
			node: currentNode, 
			ID: currentNode.getAttribute("id").replace(/ankieta_/i, "")
		});
	});
});

