/*
	Voting
*/
var Voting = Class.extend({
	// configuration
	voteUrl: '/dinamiche/Vote',
	getVotingUrlTemplate: new Template('/dinamiche/GetVote?cti=#{cti}&cii=#{cii}&sii=#{sii}'),
	updateInterval: 60,
	cookieNameTemplate: new Template('ms_voto_#{cti}_#{cii}_#{sii}'),
	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('.li_one'),
			this.votaElm.find('.li_two'),
			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,
			sii: this.subItemId
		});
	
		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({
			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) {
		if (this.voting) return;		
		this.voting = true;
		
		var params = {
			cti: this.contentTypeId,
			cii: this.contentItemId,
			sii: this.subItemId,
			vote: userVote
		};

		if (this.overloadedTypeId) {
			$.extend(params, {
				cti2: this.overloadedTypeId,
				cii2: this.overloadedItemId,
				sii2: this.overloadedSubItemId
			}); 
		}
		
		$.ajax({
			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,
			sii: this.subItemId
		});
		
		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,
			sii: this.subItemId
		});
		
		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
		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.html('<a href="javascript:;" title="Punteggio ' + (i + 1) + '">' + (i + 1) + '</a>');
					var handler = this.doVote.bind(this, '' + (i + 1));
					elm.children().bind('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];
					elm.children().unbind('click', this.voteHandlers[i]);
					elm.html('' + (i + 1));
				}
				this.voteHandlers.length = 0;
				this.noAnchor = true;
			}

			if (this.liTextElm) {
				this.liTextElm.show();
			}

			if (this.vote != 'n/a') {
				this.votaElm.children().addClass('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.children().addClass('Vote_' + ((doubleMean - 1) / 2) + '_05');
				} else {
					this.risElm.children().addClass('Vote_' + (doubleMean / 2));
				}
			}
		}
	}
});

/**
* initFileUploads
*/
function initFileUploads() {
	var W3CDOM = (document.createElement && document.getElementsByTagName);
	if (!W3CDOM) return;
	var fakeFileUpload = document.createElement('div');
	fakeFileUpload.className = 'fakefile';
	var fakeInput = document.createElement('input');
	fakeInput.className = 'inp_Text';
	fakeFileUpload.appendChild(fakeInput);
	var image = document.createElement('img');
	image.src='/res/imgs/btn_Browse.png';
	fakeFileUpload.appendChild(image);
	var x = document.getElementsByTagName('input');
	for (var i=0;i<x.length;i++) {
		if (x[i].type != 'file') continue;
		if (x[i].parentNode.className != 'fileinputs') continue;
		x[i].className = 'file hidden';
		var clone = fakeFileUpload.cloneNode(true);
		x[i].parentNode.appendChild(clone);
		x[i].relatedElement = clone.getElementsByTagName('input')[0];
		x[i].onchange = x[i].onmouseout = function () {
			this.relatedElement.value = this.value;
		}
	}
} 

/*
	Poll
*/
var Poll = Class.extend({
	// configuration
	pollUrl: '/dinamiche/Poll',
	getPollUrlTemplate: new Template('/sondaggi/ris_#{pi}.json'),
	barMaxLength: 200,
	updateInterval: -1,
	cookieNameTemplate: new Template('ms_poll_#{pi}'),
	cookieExpireTime: 5 * 60 * 1000,	
	totaleVotiIdTemplate: new Template('poll_totale_#{pi}'),
	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}'),
	radioInputSel: "input[name='ai']:checked",
	
	// fields
	pollId: null,
	results: null,
	voteUrl: null,
	resultsUrl: null,
	
	// internal fields
	updater: null,
	getPollUrl: null,
	formId: null,
	errorId: null,
	btnVotaId: null,
	totaleVotiId: null,
	
	// messages
	thanksForVotingMsg: "Grazie per aver votato!",
	noAnswerSelectedMsg: "Selezionare una risposta del sondaggio",
	alreadyVotedMsg: "Attenzione! Hai gi\u00e0 votato per questo sondaggio",
	
	// 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).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;
		for (var i = 0; i < this.polls.answers.length; i++) {
			totalVotes += this.polls.answers[i].count;
		}
		
		$('#' + this.totaleVotiId).prepend("" + 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,
			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;
			}.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);
	}
});

function SelectPollImage(pollId, answerPosition) {
	$("#form_sondaggio_" + pollId + " input[name='ai']").eq(answerPosition).attr('checked', 'checked');
}

function ShowTooltip(event, tooltipDivId) {
	if (currentTooltip != null && currentTooltip != tooltipDivId) {
		$('#' + currentTooltip).fadeOut(600);
	}
	$('#' + tooltipDivId).fadeIn(600);
	currentTooltip = tooltipDivId;
}

function HideTooltip(tooltipDivId) {
	$('#' + tooltipDivId).fadeOut(600);
	currentTooltip = null;
}


function SelectTooltip(tooltipDivId, formId, position) {
	$("#" + formId + " input[name='ai']").eq(position).attr('checked', 'checked');
	$('#' + tooltipDivId).fadeOut(600);
	currentTooltip = null;
}

var currentTooltip = null;

/*
	Rating
*/
var Rating = Class.extend({
	// configuration
	ratingUrl: '/dinamiche/RatingUtente',
	elmsSel: 'span.box_Rate span.box_Vote, div.box_UserProfile span.box_Vote',
	
	// fields
	ratingsCache: {},

	// methods
	init: function (options) {
		$.extend(this, options);
	},
	
	updateRating: function () {
		var elms = $(this.elmsSel);
		for (var i = 0; i < elms.length; i++) {
			var elm = elms.get(i);
			var classNames = elm.className;
			if (classNames.indexOf("Rate_") < 0) {
				// not yet rated
				var classes = classNames.split(" ");
				for (var j = 0; j < classes.length; j++) {
					if (classes[j].startsWith("user_")) {
						var username = classes[j].substring(5);
						var rating = this.ratingsCache[username];
						if (rating == undefined) {
							// ask the server
							this.ratingsCache[username] = -1; // prevent multiple identical requests
							
							$.ajax({
								url: this.ratingUrl,
								data: { autore: username },
								success: function (data) {
									eval(data); // defines range
									
									this.ratingsCache[username] = range;
									this.updateUserRating(username, range);
								}.bind(this)
							});
							
						} else if (rating != -1) {
							this.updateUserRating(username, rating);
						}
					}
				}
			}
		}
	},
	
	updateUserRating: function (username, rating) {
		$("span.box_Vote.user_" + username).addClass("Rate_" + rating).html(rating);
	}
});
var rating = new Rating();
