/*
	Config
*/
var votingOptions = {
	// url
	voteUrl: '/dinamiche/Vote',
	getVotingUrlTemplate: new Template('/dinamiche/GetVote?cti=#{cti}&cii=#{cii}&sii=#{sii}'),
	
	// update voting statistics every N seconds (-1 to disable)
	updateInterval: 60,
	
	// cookie name
	cookieNameTemplate: new Template('auto_voto_#{cti}_#{cii}_#{sii}'),
	
	// cookie expire time in milliseconds
	cookieExpireTime: 5 * 60 * 1000
};

var pollingOptions = {
	// url
	pollUrl: '/dinamiche/Poll',
	getPollUrlTemplate: new Template('/sondaggi/ris_#{pi}.json'),

	// html ids and classnames
	totaleVotiId: 'poll_totale',
	precentageIdTemplate: new Template('poll_perc_#{pi}_#{ai}'),
	barIdTemplate: new Template('poll_bar_#{pi}_#{ai}'),
	formIdTemplate: new Template('form_sondaggio_#{pi}'),
	errorIdTemplate: new Template('msg_sondaggio_#{pi}'),
	btnVotaIdTemplate: new Template('btn_poll_vota_#{pi}'),
	radioInputName: 'ai',
	
	// bar max length (in pixels)
	barMaxLength: 500,

	// update polling statistics every N seconds (-1 to disable)
	updateInterval: 60,
	
	// cookie name
	cookieNameTemplate: new Template('auto_poll_#{pi}'),
	
	// cookie expire time in milliseconds
	cookieExpireTime: 5 * 60 * 1000,
	
	// messages
	thanksForVotingMsg: "Grazie per aver votato!",
	noAnswerSelectedMsg: "Selezionare una risposta del sondaggio",
	alreadyVotedMsg: "Attenzione! Hai gi\u00e0 votato per questo sondaggio"
};

/*
	Class Voting
*/
var Voting = Class.create();
Voting.prototype = {
	initialize: function (contentTypeId, contentItemId, subItemId, votaDivId, risDivId, textDivId, readOnly, ynFlag) {
		this.options = votingOptions;
		this.updater = null;
		this.overloadedTypeId = null;
		this.overloadedItemId = null;
		this.overloadedSubItemId = null;
		
		if (contentTypeId != undefined && contentItemId != undefined && subItemId != undefined && votaDivId != undefined) {
			this.apply(contentTypeId, contentItemId, subItemId, votaDivId, risDivId, textDivId, readOnly, ynFlag);
		}
	},
	
	overload: function (contentTypeId, contentItemId, subItemId) {
		this.overloadedTypeId = contentTypeId;
		this.overloadedItemId = contentItemId;
		this.overloadedSubItemId = subItemId;
	},
	
	apply: function (contentTypeId, contentItemId, subItemId, votaDivId, risDivId, textDivId, readOnly, ynFlag) {
		this.contentTypeId = contentTypeId;
		this.contentItemId = contentItemId;
		this.subItemId = subItemId;
		this.votaElm = $(votaDivId);
		this.risElm = risDivId ? $(risDivId) : null;
		this.liTextElm = textDivId ? $(textDivId) : null;
		this.ynFlag = ynFlag;
		
		if (!this.votaElm) {
			return;
		}
		
		if (this.ynFlag) {
			this.elms = $A([
				this.votaElm.getElementsByClassName('out_Vote_Si')[0],
				this.votaElm.getElementsByClassName('out_Vote_No')[0]
			]);
		} else {
			this.elms = $A([
				this.votaElm.getElementsByClassName('li_one')[0],
				this.votaElm.getElementsByClassName('li_two')[0],
				this.votaElm.getElementsByClassName('li_three')[0],
				this.votaElm.getElementsByClassName('li_four')[0],
				this.votaElm.getElementsByClassName('li_five')[0]
			]);
		}
		
		this.getVotingUrl = this.options.getVotingUrlTemplate.evaluate({
			cti: this.contentTypeId,
			cii: this.contentItemId,
			sii: this.subItemId
		});
				
		this.votes = null;
		this.minCount = 0;
		this.noAnchor = true;
		this.voting = false;
		this.voteHandlers = $A();
		
		if (readOnly) {
			this.vote = 'n/a';
		} else {
			this.vote = null;
		}
		this.getUserVote();		
		this.updateVoting(true);
		
		if (this.options.updateInterval > 0 && this.updater == null) {
			this.updater = 
				new PeriodicalExecuter(this.updateVoting.bind(this), this.options.updateInterval);
		}
	},
	
	updateVoting: function (initialize) {
		if (this.voting) return;
		
		new Ajax.Request(this.getVotingUrl, {
			onSuccess: function (transport) {
				eval(transport.responseText); // defines votes
				if (votes.ok) {
					this.votes = votes;
					if (this.vote != null && this.vote != 'n/a') {
						if (this.votes['count' + this.vote] < this.minCount) {
							this.votes['count' + this.vote] = this.minCount;
						}
					}
					this.draw();
				}
			}.bind(this),
			onFailure: function () {
				if (initialize) {
					this.draw();
				}
			}.bind(this)
		});
	},
	
	doVote: function (userVote) {
		if (this.voting) return;		
		this.voting = true;
		
		var params = $H({
			cti: this.contentTypeId,
			cii: this.contentItemId,
			sii: this.subItemId,
			vote: userVote
		});

		if (this.overloadedTypeId) {
			params = params.merge({
				cti2: this.overloadedTypeId,
				cii2: this.overloadedItemId,
				sii2: this.overloadedSubItemId
			}); 
		}
		
		new Ajax.Request(this.options.voteUrl, {
			parameters: params,
			onSuccess: function (transport) {
				eval(transport.responseText); // defines votes
				if (votes.ok) {
					this.vote = userVote;
					this.votes['count' + this.vote] = this.votes['count' + this.vote] + 1;
					this.minCount = this.votes['count' + this.vote];
					this.draw();
					this.setCookie();
				} else if (votes.duplicate) {
					if (this.vote == null) {
						this.vote = 'n/a';
					}
					this.draw();
				}
			}.bind(this),
			onComplete: function () {
				this.voting = false;
			}.bind(this)
		}); 
	},
	
	getUserVote: function () {
		var cookieName = this.options.cookieNameTemplate.evaluate({
			cti: this.contentTypeId,
			cii: this.contentItemId,
			sii: this.subItemId
		});
		
		var regexp = new RegExp(cookieName + '=([^ ;]+)');
		var result = regexp.exec(document.cookie);
		
		if (result == null) {
			return null;
		}
		
		var temp = result[1];
		if (temp.indexOf("_") < 0) {
			this.vote = temp;
		} else {
			var aTemp = temp.split("_");
			this.vote = temp[0];
			
			var voteCount = 1;
			try {
				voteCount = parseInt(temp[1]);
			} catch (e) {}
			
			this.minCount = voteCount;
		}
	},
	
	setCookie: function () {
		var cookieName = this.options.cookieNameTemplate.evaluate({
			cti: this.contentTypeId,
			cii: this.contentItemId,
			sii: this.subItemId
		});
		
		var expireDate = new Date();
		expireDate.setTime(expireDate.getTime() + this.options.cookieExpireTime);
		
		var cookieValue = this.vote + "_" + this.minCount;
		
		document.cookie = cookieName + '=' + cookieValue + '; expires=' + expireDate.toGMTString();  
	},
	
	draw: function () {
		if (this.ynFlag) {
			var yesTrg = this.elms[0];
			var noTrg = this.elms[1];
			
			if (this.vote == null) {
				if (this.noAnchor) {
					yesTrg.innerHTML = '<a href="javascript:;" class="btn_Yes" title="Si"></a>';				
					noTrg.innerHTML = '<a href="javascript:;" class="btn_No" title="No"></a>';
				}
			
				yesTrg = yesTrg.firstDescendant();
				noTrg = noTrg.firstDescendant();
				
				if (this.noAnchor) {
					var yesVoteHandler = this.doVote.bind(this, '1');
					var noVoteHandler = this.doVote.bind(this, '2');
					Event.observe(yesTrg, 'click', yesVoteHandler);
					Event.observe(noTrg, 'click', noVoteHandler);
					this.voteHandlers.push(yesVoteHandler);
					this.voteHandlers.push(noVoteHandler);
				}
				
				this.noAnchor = false;
			} else {
				if (!this.noAnchor) {
					// removing anchors and handlers
					for (var i = 0; i < this.elms.length; i++) {
						var elm = this.elms[i];
						Event.stopObserving(elm.firstDescendant(), 'click', this.voteHandlers[i]);
						elm.innerHTML = '' + (i + 1);
					}
					this.voteHandlers.clear();
				}

				yesTrg.innerHTML = '<div class="btn_Yes"></div>';				
				noTrg.innerHTML = '<div class="btn_No"></div>';

				yesTrg = yesTrg.firstDescendant();
				noTrg = noTrg.firstDescendant();
				
				this.noAnchor = true;
			}
			
			yesTrg.innerHTML =
				'<span class="lbl_Text">S\u00ec</span><span>' + this.votes.count1 + '</span>';
			noTrg.innerHTML =
				'<span class="lbl_Text">No</span><span>' + this.votes.count2 + '</span>';
					
			if (this.vote != null) {
				if (this.vote == 'yes') {
					yesTrg.addClassName('selected');
					noTrg.removeClassName('selected');
				} else if (this.vote == 'no') {
					noTrg.addClassName('selected');
					yesTrg.removeClassName('selected');
				}
			}
		} else {
			// div vota
			if (this.vote == null) {
				if (this.noAnchor) {
					// adding anchors and handlers
					for (var i = 0; i < this.elms.length; i++) {
						var elm = this.elms[i];
						elm.innerHTML = '<a href="javascript:;" title="Punteggio ' + (i + 1) + '">' + (i + 1) + '</a>';
						var handler = this.doVote.bind(this, '' + (i + 1));
						Event.observe(elm.firstDescendant(), 'click', handler);
						this.voteHandlers.push(handler);
					}
					this.noAnchor = false;
				}
			} else {
				if (!this.noAnchor) {
					// removing anchors and handlers
					for (var i = 0; i < this.elms.length; i++) {
						var elm = this.elms[i];
						Event.stopObserving(elm.firstDescendant(), 'click', this.voteHandlers[i]);
						elm.innerHTML = '' + (i + 1);
					}
					this.voteHandlers.clear();
					this.noAnchor = true;
				}

				if (this.liTextElm) {
					this.liTextElm.show();
				}

				if (this.vote != 'n/a') {
					this.votaElm.firstDescendant().addClassName('Vote_' + this.vote);
				}
			}
			
			// div risultati
			if (this.votes != null) {
				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.firstDescendant().addClassName('Vote_' + ((doubleMean - 1) / 2) + '_05');
					} else {
						this.risElm.firstDescendant().addClassName('Vote_' + (doubleMean / 2));
					}
				}
			}
		}
	}
}

/*
	Class Poll
*/
var Poll = Class.create();
Poll.prototype = {
	initialize: function (pollId, results, voteUrl, resultsUrl) {
		this.options = pollingOptions;
		this.pollId = pollId;
		
		this.results = results;
		this.updater = null;
		
		this.getPollUrl = this.options.getPollUrlTemplate.evaluate({
			pi: this.pollId
		});
		this.resultsUrl = resultsUrl;
		this.voteUrl = voteUrl;

		this.formId = this.options.formIdTemplate.evaluate({
			pi: this.pollId
		});
		this.errorId = this.options.errorIdTemplate.evaluate({
			pi: this.pollId
		});
		this.btnVotaId = this.options.btnVotaIdTemplate.evaluate({
			pi: this.pollId
		});
		
		if (this.results) {
			this.updatePoll();
			
			if (this.options.updateInterval > 0) {
				this.updater = 
					new PeriodicalExecuter(this.updatePoll.bind(this), this.options.updateInterval);
			}
		} else {		
			this.radioInput = $A($(this.formId)[this.options.radioInputName]);
			Event.observe(this.btnVotaId, 'click', this.doVote.bind(this));
		}
		
		if ($(this.errorId)) {
			var params = document.location.href.toQueryParams();
			if (params.ok) {
				this.showError(this.options.thanksForVotingMsg, true);
			} else if (params.na) {
				this.showError(this.options.noAnswerSelectedMsg);
			} else if (params.sv) {
				this.showError(this.options.alreadyVotedMsg);
			}
		}
	},
	
	updatePoll: function () {
		new Ajax.Request(this.getPollUrl, {
			onSuccess: function (transport) {
				eval(transport.responseText); // defines polls
				this.polls = polls;
				this.draw();
			}.bind(this)
		});
	},
	
	draw: function () {
		var totalVotes = 0;
		this.polls.answers.pluck('count').each(function (count) {
			totalVotes += count;
		});
		
		$(this.options.totaleVotiId).innerHTML = "" + totalVotes;
		
		this.polls.answers.each(function (answer) {
			if (totalVotes == 0) {
				answer.perc = 0;
			} else {
				answer.perc = Math.round(1000 * answer.count / totalVotes) / 10;
			}
			
			var percId = this.options.precentageIdTemplate.evaluate({ 
				pi: this.pollId,
				ai: answer.answerId
			});
			var barId = this.options.barIdTemplate.evaluate({ 
				pi: this.pollId,
				ai: answer.answerId
			});
			
			$(percId).innerHTML = answer.perc + '%';
			$(barId).style.width = (answer.perc * this.options.barMaxLength / 100) + 'px';
		}.bind(this));		
	},

	setCookie: function (value) {
		var cookieName = this.options.cookieNameTemplate.evaluate({
			pi: this.pollId
		});
		
		var expireDate = new Date();
		expireDate.setTime(expireDate.getTime() + this.options.cookieExpireTime);
		
		document.cookie = cookieName + '=' + value + '; expires=' + expireDate.toGMTString();  
	},

	// return true on ok (no cookie)
	checkCookie: function () {
		var cookieName = this.options.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.radioInput.find(function (radio) { return radio.checked; });

		if (!vote) {
			if ($(this.errorId)) {
				this.showError(this.options.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;
		}
		
		new Ajax.Request(this.options.pollUrl, {
			parameters: {
				pi: this.pollId,
				ai: vote.value
			},
			onSuccess: function (transport) {
				eval(transport.responseText); // defines poll
				if (poll.ok || poll.duplicate) {
					this.setCookie(vote.value);
					document.location.href = this.resultsUrl + "?ok=true";
				}
			}.bind(this),
			onComplete: function () {
				this.voting = false;
			}.bind(this)
		});
	},
	
	showError: function (msg, ok) {
		$(this.errorId).innerHTML = msg;
		$(this.errorId).show();
		$(this.errorId).scrollTo();
	}
};

function SelectPollImage(pollId, answerPosition) {
	$('form_sondaggio_' + pollId)['ai'][answerPosition].checked = 'checked';
}

