/*
	Voting
*/
var Voting = Class.extend({
	// configuration
	voteUrl: '/dinamiche/Vote',
	getVotingUrlTemplate: new Template('/dinamiche/cached/getVote.jsp?cti=#{cti}&cii=#{cii}'),
	updateInterval: 0,
	cookieNameTemplate: new Template('cds_voto_#{cti}_#{cii}'),
	cookieExpireTime: 5 * 60 * 1000,
	
	// fields
	contentTypeId: null,
	contentItemId: null,
	subItemId: null,
	overloadedTypeId: null,
	overloadedItemId: null,
	overloadedSubItemId: null,
	votaDivId: null,
	risDivId: null,
	textDivId: null,
	readOnly: false,
	
	// internal fields
	getVotingUrl: null,
	updater: null,
	votaElm: null,
	risElm: null,
	liTextElm: null,
	elms: $A(),
	vote: null,
	votes: null,
	noAnchor: true,
	voting: false,
	voteHandlers: $A(),
	
	// methods
	init: function (options) {
		$.extend(this, options);

		this.votaElm = $('#' + this.votaDivId);
		this.risElm = $('#' + this.risDivId);
		this.liTextElm = this.textDivId ? $('#' + this.textDivId) : null;
		
		if (this.votaElm.length == 0 || this.risElm.length == 0) {
			return;
		}
		
		this.elms = $A([
			this.votaElm.find('.OptionYes'),
			this.votaElm.find('.OptionNo'),
			//this.votaElm.find('.li_three'),
			//this.votaElm.find('.li_four'),
			//this.votaElm.find('.li_five')
		]);
		
		this.getVotingUrl = this.getVotingUrlTemplate.evaluate({
			cti: this.contentTypeId,
			cii: this.contentItemId
		});
	
		if (this.readOnly) {
			this.vote = 'n/a';
		}
		this.getUserVote();		
		this.updateVoting(true);
		
		if (this.updateInterval > 0 && this.updater == null) {
			this.updater = new PeriodicalExecuter(this.updateVoting.bind(this), this.updateInterval);
		}
	},
	
	updateVoting: function (initialize) {
		if (this.voting) return;
		$.ajax({
			type: 'POST',
			url: this.getVotingUrl,
			success: function (data) {
				eval(data); // defines votes
				if (votes.ok) {
					this.votes = votes;
					this.draw();
				}
			}.bind(this),
			error: function () {
				if (initialize) {
					this.draw();
				}
			}.bind(this)
		});
	},
	
	doVote: function (userVote) {
		//alert("doVote " + this.voting)
		if (this.voting) return;		
		this.voting = true;
		
		var params = {
			cti: this.contentTypeId,
			cii: this.contentItemId,
			vote: userVote
		};

		if (this.overloadedTypeId) {
			$.extend(params, {
				cti2: this.overloadedTypeId,
				cii2: this.overloadedItemId
			}); 
		}
		
		$.ajax({
			type: 'POST',
			url: this.voteUrl,
			data: params,
			success: function (data) {
				eval(data); // defines votes
				if (votes.ok) {
					this.vote = userVote;
					this.draw();
					this.setCookie();
				} else if (votes.duplicate) {
					if (this.vote == null) {
						this.vote = 'n/a';
					}
					this.draw();
				}
			}.bind(this),
			complete: function () {
				this.voting = false;
			}.bind(this)
		}); 
	},
	
	getUserVote: function () {
		var cookieName = this.cookieNameTemplate.evaluate({
			cti: this.contentTypeId,
			cii: this.contentItemId
		});
		
		var regexp = new RegExp(cookieName + '=([^ ;]+)');
		var result = regexp.exec(document.cookie);
		
		if (result == null) {
			return null;
		}
		
		this.vote = result[1];
	},
	
	setCookie: function () {
		var cookieName = this.cookieNameTemplate.evaluate({
			cti: this.contentTypeId,
			cii: this.contentItemId
		});
		
		var expireDate = new Date();
		expireDate.setTime(expireDate.getTime() + this.cookieExpireTime);
		
		var cookieValue = this.vote;
		
		document.cookie = cookieName + '=' + cookieValue + '; expires=' + expireDate.toGMTString();  
	},
	
	draw: function () {
		// div vota
		//alert("draw this.vote "+this.vote)
		if (this.vote == null) {
			if (this.noAnchor) {
				//alert("this.noAnchor "+this.noAnchor)
				// adding anchors and handlers
				for (var i = 0; i < this.elms.length; i++) {
					var elm = this.elms[i];
					var handler = null;
					if(i == 0){
						elm.html('<a href="javascript:;" title="Si"><img alt="Si" src="/res/img/2010/vote_y.png" /></a><span class="VotoNumber"></span>');
						handler = this.doVote.bind(this, 'yes');
						elm.children().bind('click', handler);
					}else if(i == 1){
						elm.html('<a href="javascript:;" title="No"><img alt="No" src="/res/img/2010/vote_n.png" /></a><span class="VotoNumber"></span>');
						handler = this.doVote.bind(this, 'no');
						elm.children().bind('click', handler);
						this.voteHandlers.push(handler);
					}
				}
				this.noAnchor = false;
			}
		} else {
			if (!this.noAnchor) {
				//alert("this.noAnchor "+this.noAnchor)
				// removing anchors and handlers
				for (var i = 0; i < this.elms.length; i++) {
					var elm = this.elms[i];
					if(elm != null){
						elm.children().unbind('click', this.voteHandlers[i]);
						if(i == 0)
							elm.html('<img alt="Si" src="/res/img/2010/vote_y.png" /><span class="VotoNumber"></span>');
						else elm.html('<img alt="No" src="/res/img/2010/vote_n.png" /><span class="VotoNumber"></span>');
					}
				}
				this.voteHandlers.length = 0;
				this.noAnchor = true;
			}

			if (this.liTextElm) {
				this.liTextElm.html("Grazie per aver votato");
			}
			/*
			if (this.vote != 'n/a') {
				this.votaElm.children().addClass('Vote_' + this.vote);
			}*/
		}
		
		// div risultati
		//alert("all votes "+this.votes)
		if (this.votes != null) {
			//alert(this.vote)
			yesVoteUser = this.vote == 'yes' ? 1 : 0;
			noVoteUser = this.vote == 'no' ? 1 : 0;
			this.elms[0].find("span").html((this.votes.yesCount + yesVoteUser));
			this.elms[1].find("span").html((this.votes.noCount + noVoteUser));
			/*var count1 = parseInt(this.votes.count1);
			var count2 = parseInt(this.votes.count2);
			var count3 = parseInt(this.votes.count3);
			var count4 = parseInt(this.votes.count4);
			var count5 = parseInt(this.votes.count5);
			var countVotes = count1 + count2 + count3 + count4 + count5;
			if (countVotes > 0) {
				var total = count1 + 2 * count2 + 3 * count3 + 4 * count4 + 5 * count5;
				var doubleMean = Math.round(2 * total / countVotes);
				if (doubleMean % 2 == 1) {
					this.risElm.children().addClass('Vote_' + ((doubleMean - 1) / 2) + '_05');
				} else {
					this.risElm.children().addClass('Vote_' + (doubleMean / 2));
				}
			}*/
		}
	}
});


/*
	Class Poll
*/
var Poll = Class.extend({
	
	// url
	pollUrl: '/dinamiche/Poll',
	getPollUrlTemplate: new Template('/sondaggi/ris_#{pi}.json'),
	resultsUrlTemplate: new Template('/Sondaggi/Risultati/#{category}/#{pi}/#{title}'),
	voteUrlTemplate: new Template('/Sondaggi/Vota/#{category}/#{pi}/#{title}'),

	// html ids and classnames
	totaleVotiId: 'poll_totale',
	precentageIdTemplate: new Template('poll_perc_#{ai}'),
	formIdTemplate: new Template('form_sondaggio_#{pi}'),
	//errorIdTemplate: new Template('msg_sondaggio_#{pi}'),
	barIdTemplate: new Template('poll_bar_#{ai}'),
	btnVotaIdTemplate: new Template('btn_poll_vota_#{pi}'),
	totaleVotiIdTemplate: new Template('poll_totale_#{pi}'),
	formId: 'formSondaggio',
	radioInputName: 'ai',
	btnVotaId: 'btn_poll_vota',
	
	radioInputSel: "input[name='ai']:checked",
	
	// bar max length (in pixels)
	barMaxLength: 200,

	// update polling statistics every N seconds (-1 to disable)
	updateInterval: 60,
	
	// cookie name
	cookieNameTemplate: new Template('cds_poll_#{pi}'),
	
	// cookie expire time in milliseconds
	cookieExpireTime: 5 * 60 * 1000,
	
	// messages
	thanksForVotingMsg: "Grazie per aver votato.<br/>Il tuo voto sar\u00e0 conteggiato entro 3 minuti",
	noAnswerSelectedMsg: "Selezionare una risposta del sondaggio",
	alreadyVotedMsg: "Attenzione! Hai gi\u00e0 votato per questo sondaggio",
	
	// internal fields
	updater: null,
	getPollUrl: null,
	formId: null,
	errorId: "error_sondaggio",
	btnVotaId: null,
	results: false,
	
	// methods
	init: function (options) {
		$.extend(this, options);
		
		this.getPollUrl = this.getPollUrlTemplate.evaluate({
			pi: this.pollId
		});
		this.formId = this.formIdTemplate.evaluate({
			pi: this.pollId
		});
		/*this.errorId = this.errorIdTemplate.evaluate({
			pi: this.pollId
		});*/
		this.btnVotaId = this.btnVotaIdTemplate.evaluate({
			pi: this.pollId
		});
		/*this.totaleVotiId = this.totaleVotiIdTemplate.evaluate({
			pi: this.pollId
		});*/
		
		if (this.results) {
			this.updatePoll();			
			if (this.updateInterval > 0) {
				this.updater = new PeriodicalExecuter(this.updatePoll.bind(this), this.updateInterval);
			}
		} else {		
			$('#' + this.btnVotaId).bind('click', this.doVote.bind(this));
		}
		
		if ($('#' + this.errorId) != null && $('#' + this.errorId).length > 0) {
			var params = document.location.href.toQueryParams();
			if (params.ok) {
				this.showError(this.thanksForVotingMsg, true);
			} else if (params.na) {
				this.showError(this.noAnswerSelectedMsg);
			} else if (params.sv) {
				this.showError(this.alreadyVotedMsg);
			}
		}
	},

	
	updatePoll: function () {
		$.ajax({
			url: this.getPollUrl, 
			success: function (data) {
				eval(data); // defines polls
				this.polls = polls;
				this.draw();
			}.bind(this)
		});
	},
	
	draw: function () {
		var totalVotes = 0;
		$.each(this.polls.answers, function(key, value) { 
			//alert("count : " + value.count + " answerId "+ value.answerId);
			totalVotes += value.count;
		});
		
		$('#' + this.totaleVotiId).html("" + totalVotes);
		
		for (var i = 0; i < this.polls.answers.length; i++) {
			var answer = this.polls.answers[i];
			if (totalVotes == 0) {
				answer.perc = 0;
			} else {
				answer.perc = Math.round(1000 * answer.count / totalVotes) / 10;
			}
			
			var percId = this.precentageIdTemplate.evaluate({ 
				pi: this.pollId,
				ai: answer.answerId
			});
			var barId = this.barIdTemplate.evaluate({ 
				pi: this.pollId,
				ai: answer.answerId
			});
			
			$('#' + percId).html(answer.perc + '%');
			$('#' + barId).css({ width : (answer.perc * this.barMaxLength / 100) + 'px'});
		};		
	},
	

	setCookie: function (value) {
		var cookieName = this.cookieNameTemplate.evaluate({
			pi: this.pollId
		});
		
		var expireDate = new Date();
		expireDate.setTime(expireDate.getTime() + this.cookieExpireTime);
		
		document.cookie = cookieName + '=' + value + '; expires=' + expireDate.toGMTString();  
	},

	// return true on ok (no cookie)
	checkCookie: function () {
		var cookieName = this.cookieNameTemplate.evaluate({
			pi: this.pollId
		});
		
		var regexp = new RegExp(cookieName + '=([^ ;]+)');
		var result = regexp.exec(document.cookie);
		
		return result == null;
	},
	
	doVote: function () {
		if (this.voting) return;		
		this.voting = true;
		
		var vote = $('#' + this.formId).find(this.radioInputSel);

		if (vote.length == 0) {
			if ($('#' + this.errorId).length > 0) {
				this.showError(this.noAnswerSelectedMsg);
			} else {
				document.location.href = this.voteUrl + "?na=true";
			}
			this.voting = false;
			return;
		}
		
		if (!this.checkCookie()) {
			document.location.href = this.resultsUrl + "?sv=true";
			this.voting = false;
			return;
		}
		
		var params = {
			pi: this.pollId,
			ai: vote.val()
		};
		
		$.ajax({
			url: this.pollUrl,
			type: 'POST',
			data: params,
			success: function (data) {
				eval(data); // defines poll				
				if (poll.ok || poll.duplicate) {
					this.setCookie(vote.value);
					document.location.href = this.resultsUrl + "?ok=true";
				}
			}.bind(this),
			complete: function () {
				this.voting = false;
				this.draw();
			}.bind(this)
		});
	},
	
	showError: function (msg, ok) {
		if (ok) {
			$('#' + this.errorId).addClass("txt_Info").removeClass("txt_Error");
		} else {
			$('#' + this.errorId).addClass("txt_Error").removeClass("txt_Info");
		}
		$('#' + this.errorId).html(msg);
		$('#' + this.errorId).show();
		scrollToElement('#' + this.errorId);
	}
});

