/**
 * Script part for ContestVote Snippet.
 * Enables the Poll to be updated via AJAX
 * This was written to work with the mootools library that comes with MODx
 *
 * @author banal
 * @version 0.2 (2008-02-08)
 */
var ContestVoteAjax = new Class({
	initialize: function(identifier, url){
		if(typeof identifier != 'string' || typeof url != 'string'){
			LertAlert('E\' stato rilevato un errore: prego ricaricare la pagina.');
			return;
		};

		this.url = url;
		this.identifier = identifier;
		this.handlers = new Array();

		this.pollxhr = new Request({
			url: this.url,
			method: 'post',
			onSuccess: this.callbackHandler.bind(this),
			onRequest: this.callbackHandler.bind(this),
			headers: {"Content-type": "application/x-www-form-urlencoded; charset=utf-8"}
		});
		/*this.pollxhr = new XHR({
			method: 'post',
			onSuccess: this.callbackHandler.bind(this),
			onRequest: this.callbackHandler.bind(this),
			headers: {"Content-type": "application/x-www-form-urlencoded; charset=utf-8"}
		});*/

		if($(identifier)){
			$(identifier + 'ajx').value = '1';
		};
	},

	/** register a button to fire a ajax request */
	registerButton: function(button){
		if(button == 'submit' || button == 'result' || button == 'vote'){
			if(!$(this.identifier + button)){ return; };

			$(this.identifier + button).onclick = function(event){
				var poster = new Event(event || window.event);
				var targ = poster.target;
				var issubm = (targ.id.indexOf('submit') >= 0);
				if (issubm && !VerifyEmail()) return false;
				if (issubm && !ExtCheck()) return false;
				if($(this.identifier + 'form').getElements('input[name=poll_choice]').get('checked').some(
						function(item,index){return item==true;}) || !issubm)
				{
					var event = new Event(event).stopPropagation();
					event.preventDefault();
					this.pollxhr.send($(this.identifier +'form').toQueryString() + '&' + button + '=1');
				}
				else{LertAlert('Devi assegnare il tuo voto selezionando una preferenza.');}
				return false;
			}.bind(this);
		};
	},

	/** register a callback method that will be called upon request and upon success */
	registerCallback: function(callback){
		if(typeof callback == 'function')
			this.handlers.push(callback);
	},

	/** distributes response from XHR object to the registered callbacks */
	callbackHandler: function(response){
		if(response == undefined){
			this.handlers.each(function(func){
				func(false, this.identifier);
			}.bind(this));
		} else {
			this.handlers.each(function(func){
				func(response, this.identifier);
			}.bind(this));
		}
	}
});

function filterGeneri(generi){
	$$('#contestvoteTbl tbody tr').each(function(item,index){
		if(!item.hasClass('gnr'+generi))
			item.setStyle('display','none');
		});
	$$('#clearFilter').setStyle('display', 'block');
}
function filterGeneriSel(){
	var gnr = $('gnrfilter').value;
	if (gnr > 0) filterGeneri(gnr);
}
function filterRegione(regione){
	$$('#contestvoteTbl tbody tr').each(function(item,index){
		if(!item.hasClass('rgn'+regione))
			item.setStyle('display','none');
		});
	$$('#clearFilter').setStyle('display', 'block');
}
function filterRegioneSel(){
	var rgn = $('rgnfilter').value;
	if (rgn > 0) filterRegione(rgn);
}
function filterElement(elemname, tclass){
	var t = $(elemname);
	var reg = new RegExp('.*(' + t.value + ').*', 'i');
	if (t.value != ''){
		$$('.'+tclass).each(function(item,index){
			if (!reg.test(item.get('html'))){
				$(item).getParent('tr').setStyle('display','none');
			}
		});
		$$('#clearFilter').setStyle('display', 'block');
	}
}
function doFilterAllOnEnter(event){
	event = event || window.event;
	if (event.keyCode == 13){
		var event = new Event(event).stopPropagation();
		event.preventDefault();
		doFilterAll();
	}
}
function doFilterAll(){
	filterClear(false);
	filterElement('grfilter', 'mgroup');
	filterElement('sngfilter', 'msong');
	filterRegioneSel();
	filterGeneriSel();
}
function filterClear(dropsel){
	if (dropsel != false) dropsel = true;
	$$('#clearFilter').setStyle('display', 'none');
	$$('#contestvoteTbl tbody tr').setStyle('display','');
	if (dropsel){
		$('gnrfilter').selectedIndex = 0;
		$('rgnfilter').selectedIndex = 0;
		$('grfilter').value = '';
		$('sngfilter').value = '';
	}
}
function VerifyEmail() {
	if (document.contestvoteform.v_mail){
		var email = document.contestvoteform.v_mail.value;
		var email_reg_exp = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-]{2,})+\.)+([a-zA-Z0-9]{2,})+$/;
		if (!email_reg_exp.test(email) || (email == "") || (email == "undefined")) {
			LertAlert("L\'indirizzo email che hai inserito non sembra essere valido: controllalo bene, potresti aver commesso errori di battitura.");
			document.contestvoteform.v_mail.select();
			return false;
		}
		if (isNotMailInWhiteList(email)){
			LertAlert("Spiacenti, l\'indirizzo email che hai inserito non fa parte dei servizi ammessi. Devi utilizzare un tuo indirizzo di posta elettronica che sia in grado di ricevere e inviare email, con regolare procedura di registrazione non anonima ed in lingua italiana. Esempi: google.com, libero.it, alice.it, ...");
			document.contestvoteform.v_mail.select();
			return false;
		}
	}
	return true;
}
function ExtCheck(){
	if ($('newslettercheck').get('checked')){
		if ($('rgnsel').selectedIndex == 0){
			LertAlert('Seleziona la tua regione di appartenenza.');
			return false;
		}
	}
	return true;
}
function LertAlert(message){
	if (typeof(Lert) != "undefined"){
		var ok = new LertButton('OK', function() {
		/*do OK stuff*/
		});
		var notify = new Lert(
			message,
			[ok],
			{
				defaultButton:ok,
				icon:'/assets/templates/sziget08/lert/i/dialog-information.png'
			});
		notify.display();
	} else {
		alert(message);
	}
}

var ContestVote_DefaultCallback = function(response, id){
	if(response == false){
		/*$(id + "submit").disabled = true;*/
	} else {
		if (response.indexOf('cverror:') >= 0){
			LertAlert(response.substr(40));
		} else if (response.indexOf('voted:') >= 0){
			LertAlert('Perfetto, il tuo voto &egrave; stato registrato! Grazie per aver espresso la tua preferenza, ogni voto &egrave; un prezioso contributo, in quanto &egrave; l\'unico che puoi inviare con il tuo indirizzo email. Puoi tornare quando vuoi e visualizzare i risultati correnti immettendo l\'indirizzo email che hai appena utilizzato per votare.');
			$(id).set('html', response);
		} else {
			$(id).set('html', response);
		}
	}
}
