	$(document).ready(function() {
		
		var t;
		$('.select_citta').click(function(){
			clearTimeout(t);
			$('.lista_citta').slideDown();
		});
		$('.lista_citta, .select_citta').hover(
			function(){ clearTimeout(t) },
			function(){
				t = setTimeout("$('.lista_citta').slideUp()", 600);
			}
		);
		
		$('.homepage ul.mainlist').each(function(){ 
			$(this).find('li:first').addClass('first');
			$(this).find('li:last').addClass('last');
		});
		
		calcolaTwitterMiniUrl();
		
		$('.maxibox_wrapper').prepend('<div class="maxibox_header"></div>').append('<div class="maxibox_footer"></div>');
		$('.superbox_wrapper').prepend('<div class="superbox_header"></div>').append('<div class="superbox_footer"></div>');
		
		$('h6#aggiungi_relatore').click(function(){
			$('#aggiungi_relatore_wrapper').toggle();
		});
		$('h6#aggiungi_dispensa').click(function(){
			$('form').clearForm();
			$('input[type=file]').val('');
			$('#descrizione').html('');
			$('#aggiungi_dispensa_wrapper').toggle();
		});
		$('.show_dispensa_item').click(function(){
			var id = $(this).attr('id').split('_')[2];
			if ($(this).hasClass('open')){
				$(this).removeClass('open')
				$('#dispensa_'+id).slideUp(200);
			} else {
				$(this).addClass('open')
				$('#dispensa_'+id).slideDown(500);
			}
		});
		
		$('.minibox_wrapper').hover(
			function(){ $(this).addClass('hover'); },
			function(){ $(this).removeClass('hover'); }
		);
		
		$('.req label').append(' <span>*</span>');
		
		$('a.corso_anteprima').hover(
			function(){ $(".anteprima", this).animate({opacity: 0.5}, 300); $(".show_full", this).fadeIn(300); },
			function(){ $(".anteprima", this).animate({opacity: 1  }, 300); $(".show_full", this).fadeOut(300); }
		);
	
		$('a[rel*=facebox]').facebox();
		
		$("a[rel^=fancy]").fancybox({
			'zoomSpeedIn':	300,
			'zoomSpeedOut':	300
		});
		$("a[rel^=ajax_fency]").fancybox({
			'zoomSpeedIn':	300,
			'zoomSpeedOut':	300,
			'hideOnContentClick': false,
			'width': 632,
			'height': 330,
			'autoDimensions': false
		});
		
		$('.expander').expander({
			slicePoint: 300, 
			expandText: '[+]',
			userCollapseText: '[-]',
		    expandEffect:     'fadeIn',
		    expandSpeed:      '1000'
		});
		
		$('textarea#riassunto').keyup(function(){
			var val = $(this).val();
			if (val.length > 250){
				val = val.substr(0, 250);
				$(this).val(val);
			}
		});
		
		
		$("a.aggiungi_orario").click(function(){
			return aggiungiOrario($(this), 2);
		});
		
		$('a.aggiungi_filtro').click(function(){
			return aggiungiFiltro($(this), 2);
		});
		
		$("a.aggiungi_testo").live('click', function(){
			var arr = $(this).attr('id').split('_');
			val = arr[arr.length-1];
			var domanda1 = $("input#testo_"+(arr[arr.length-2] == 'p' ? 'p_' : '')+(val-1)).val();
			var domanda2 = $("#evento_"+(arr[arr.length-2] == 'p' ? 'p_' : '')+(val-1)+' option:selected').val();
			var domanda3 = $("#partecipante_"+(arr[arr.length-2] == 'p' ? 'p_' : '')+(val-1)+' option:selected').val();
			if (domanda1 || domanda2 || domanda3){
				if (arr[arr.length-2] == 'p'){
					genera_form_testo_partecipante($("form#print_attestato_form input[name=evento_id]").val(), val);
					$(this).hide();
				} else {
					genera_form_testo(val);
					$(this).hide();
				}
			}
			return false;
		});
		
		$("a.elimina_testo").live('click', function(){
			var arr = $(this).attr('id').split('_');
			val = parseInt(arr[arr.length-1]);
			var obj = $("div#testo_"+(arr[arr.length-2] == 'p' ? 'p_' : '')+val);
			obj.fadeOut(600);
			obj.remove();
			alert('rimosso '+val);
			if (val > 1){
				if (arr[arr.length-2] == 'p'){
					$('a#aggiungi_testo_p_'+val).show();
				} else {
					$('a#aggiungi_testo_'+val).show();
				}
			}
			return false;
		});
		
		$('.elimina_dispensa').click(function(){
			if (window.confirm('Sei sicuro di voler cancellare questa dispensa?')){
				var id = $(this).attr('id').split('_')[2];
				$.get('index2.php', {page: 'gestione', task: 'elimina_dispensa', id: id}, function(data){
					if (data.indexOf("OK") == -1){
						alert('Errore nell\' esecuzione. Prova nuovamente.');
					} else {
						$('#dispensa_'+id).parent().parent().fadeOut(1000);
					}
				});
			}
		});
		
		$('.elimina_iscritto').click(function(){
			if (window.confirm('Sei sicuro di voler eliminare questo iscritto dall evento?')){
				var id = $(this).attr('id').split('_')[2];
				$.get('index2.php', {page: 'gestione', task: 'elimina_iscritto', id: id}, function(data){
					if (data.indexOf("OK") == -1){
						alert('Errore nell\' esecuzione. Prova nuovamente.');
					} else {
						$('#iscritto_'+id).fadeOut(1000);
					}
				});
			}
			return false;
		})
		
		$('.modifica_dispensa').click(function(){
			var val = $(this).attr('id').split('_')[2];
			$.getJSON('http://www.rolandacademy.it/index2.php?page=gestione&task=getDispensa', {id: val}, function(data){
				$('form').clearForm();
				$('#id_dispensa').val(val);
				$('#aggiungi_dispensa_wrapper').show();
				$('h6#aggiungi_dispensa').hide();
				$('#modifica_dispensa').show().find('span').html('"'+data.titolo+'"');
				// $('#file_wrapper_1').hide();
				$('#titolo').val(data.titolo);
				$('#embed').val(data.embed);
				$('#descrizione').val(data.descrizione);
				if (data.files.length > 0){
					var j = 0;
					for (var i = 0; i < data.files.length; i++){
						if (! data.files[i].filename) continue;
						j++;
						var file = '<div id="file_da_eliminare_'+data.files[i].id+'">'+data.files[i].filename+' &nbsp;&nbsp;&nbsp;&nbsp;';
						file += '<a href="http://www.rolandacademy.it/'+data.files[i].filename+'" target="_blank">Visualizza</a>&nbsp;&nbsp;';
						file += '<a href="javascript:void(0)" class="elimina_file" id="elimina_file_'+data.files[i].id+'">Elimina</a><br/>';
						$('#file_wrapper_2').append(file);
					}
					if (j > 0){
						$('#file_wrapper_2').show();
					}
				}
				$('.elimina_file').click(function(){
					var the_id = $(this).attr('id').split('_')[2];
					$.get('http://www.rolandacademy.it/index2.php?page=gestione&task=elimina_file', {id: the_id}, function(data){
						if (data == "OK"){ 
							alert('File eliminato con successo');
							$('#file_da_eliminare_'+the_id).fadeOut();
						} else {
							alert('Non riesco a cancellare il file.');
						}
					})
				});
				$('#invia').hide();
				$('#invia_modifica').show();
			});
		});
		
		$("input[name^=tipo_filtro_]").live('change', function(){
			var val = $(this).attr('id').split('_');
			val = val[val.length-1];
			if ($(this).val() == 'text' || $(this).val() == 'textarea'){
				$("span#variabili_wrapper_"+val).fadeOut(1000);
			} else {
				$("span#variabili_wrapper_"+val+":hidden").fadeIn(1000);
			}
		});
		
		
		$('textarea.wysiwyg').tinymce({
			// Location of TinyMCE script
			script_url : '/js/tiny_mce/tiny_mce.js',

			// General options
			theme : "advanced",
			plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist",

			// Theme options
			theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
			theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
			theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
			theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_statusbar_location : "bottom",
			theme_advanced_resizing : true,

			// Example content CSS (should be your site CSS)
			content_css : "../css/style.css",

			// Drop lists for link/image/media/template dialogs
			template_external_list_url : "lists/template_list.js",
			external_link_list_url : "lists/link_list.js",
			external_image_list_url : "lists/image_list.js",
			media_external_list_url : "lists/media_list.js"
		});
		
		$('form').bind('form-pre-serialize', function(e) {
			if (typeof(tinyMCE)!="undefined")
		    tinyMCE.triggerSave();
		});
		
		/*
		// $('textarea.wysiwyg').markItUp(myMIUSettings);
		$('textarea.wysiwyg').rte({
					controls_rte: rte_toolbar,
					controls_html: html_toolbar
				});
		*/
		
		$('.condivisione input[type=text]').focus(function(){
			$(this).select();
		}).click(function(){
			$(this).focus();
			$(this).select();
		});
		
		$("#slider").easySlider({
			auto: false,
			continuous: true 
		});
		
		$(".padella").hover(
			function(){ $(".popup_padella", this).fadeIn(600); },
			function(){ $(".popup_padella", this).fadeOut(300); }
		);
		
		$('.expandable').expander({
			slicePoint: 300, 
			widow: 4, 
			expandText: '[leggi tutto]',
			expandSpeed: 800,
			userCollapseText: '[leggi meno]'
		});
		
		$(document).bind('reveal.facebox', function() {
			// if (GBrowserIsCompatible()) {
				initialize();
				initialize_2();
				// var map = new GMap2(document.getElementById("map_canvas"));
				// map.setCenter(new GLatLng(-8.67569, 115.164625), 13);
			// }
			
			$('#aggiungi_luogo_form').ajaxForm({ 
		        target:        '#output',   // target element(s) to be updated with server response 
		        beforeSubmit:  showRequestLuogo,  // pre-submit callback 
		        success:       showResponseLuogo  // post-submit callback 
			});
			
			$('#aggiungi_logo_form').ajaxForm({ 
		        beforeSubmit:  showRequestCaricaLogo,  // pre-submit callback 
		        success:       showResponseCaricaLogo  // post-submit callback 
			});
			
			$('#form_modifica_evento').ajaxForm({ 
		        beforeSubmit:  showRequestModificaEvento,  // pre-submit callback 
		        success:       showResponseModificaEvento  // post-submit callback 
			});
			
		});
		
		$('#form_crea').ajaxForm({ 
	        target:        '#output_corsi',   // target element(s) to be updated with server response 
	        beforeSubmit:  showRequestCreaCorso,  // pre-submit callback 
	        success:       showResponseCreaCorso  // post-submit callback 
		});
		
		$('#form_iscrizione').ajaxForm({ 
	        beforeSubmit:  showRequestIscrizione,  // pre-submit callback 
	        success:       showResponseIscrizione  // post-submit callback 
		});
		
		$('#form_richiesta_questionari').ajaxForm({
	        beforeSubmit:  showRequestRichiestaQuestionario,  // pre-submit callback 
	        success:       showResponseRichiestaQuestionario  // post-submit callback 
		});
		
		$('#form_compilazione').ajaxForm({
	        beforeSubmit:  showRequestCompilazioneQuestionario,  // pre-submit callback 
	        success:       showResponseCompilazioneQuestionario  // post-submit callback 
		});
		
		$('#form_modifica_iscrizione').ajaxForm({ 
	        target:        '#output_iscrizione',   // target element(s) to be updated with server response 
	        beforeSubmit:  showRequestModificaIscrizione,  // pre-submit callback 
	        success:       showResponseModificaIscrizione  // post-submit callback 
		});
		
		$('#form_modifica_corso').ajaxForm({ 
	        beforeSubmit:  showRequestModificaCorso,  // pre-submit callback 
	        success:       showResponseModificaCorso  // post-submit callback 
		});
		
		$('#form_crea_questionario').ajaxForm({ 
	        target:        '#output_questionario',   // target element(s) to be updated with server response 
	        beforeSubmit:  showRequestCreaQuestionario,  // pre-submit callback 
	        success:       showResponseCreaQuestionario  // post-submit callback 
		});
		
		$('#send_to_a_friend').ajaxForm({ 
	        target:        '#output_send_to_a_friend',   // target element(s) to be updated with server response 
	        beforeSubmit:  showRequestSendToAFriend,  // pre-submit callback 
	        success:       showResponseSendToAFriend  // post-submit callback 
		});
		
		
		$('#aggiungi_sconto_form').ajaxForm({ 
	        target:        '#output',   // target element(s) to be updated with server response 
	        beforeSubmit:  showRequestSconto,  // pre-submit callback 
	        success:       showResponseSconto  // post-submit callback 
		});
		
		$('#aggiungi_utente_form').ajaxForm({ 
	        beforeSubmit:  showRequestUtente,  // pre-submit callback 
	        success:       showResponseUtente  // post-submit callback 
		});
		
		$('#modifica_utente_form').ajaxForm({ 
	        beforeSubmit:  showRequestEditUtente,  // pre-submit callback 
	        success:       showResponseEditUtente  // post-submit callback 
		});
		
		$('#aggiungi_relatore_form').ajaxForm({ 
	        beforeSubmit:  showRequestRelatore,  // pre-submit callback 
	        success:       showResponseRelatore  // post-submit callback 
		});
		
		$('#aggiungi_dispensa_form').ajaxForm({ 
	        beforeSubmit:  showRequestDispensa,  // pre-submit callback 
	        success:       showResponseDispensa  // post-submit callback 
		});
		
		$('#modifica_relatore_form').ajaxForm({ 
	        beforeSubmit:  showRequestEditRelatore,  // pre-submit callback 
	        success:       showResponseEditRelatore  // post-submit callback 
		});
		
		$('#aggiungi_dealer_form').ajaxForm({ 
	        beforeSubmit:  showRequestDealer,  // pre-submit callback 
	        success:       showResponseDealer  // post-submit callback 
		});
		
		$('#modifica_dealer_form').ajaxForm({ 
	        beforeSubmit:  showRequestEditDealer,  // pre-submit callback 
	        success:       showResponseEditDealer  // post-submit callback 
		});
		
		$('#form_attestato').ajaxForm({ 
	        beforeSubmit:  showRequestUploadAttestato,  // pre-submit callback 
	        success:       showResponseUploadAttestato  // post-submit callback 
		});
		
		$('#iscrizione_newsletter').ajaxForm({ 
	        beforeSubmit:  showRequestIscrizioneNewsletter,  // pre-submit callback 
	        success:       showResponseIscrizioneNewsletter  // post-submit callback 
		});
		
		$("_form#form_cerca input#key").change(function(){
			var the_form = $("form#form_cerca");
			var the_url = the_form.attr('action').split('/');
			var new_url = '';
			for (var i = 0; i < the_url.length - 1; i++){
				new_url += the_url[i] + '/';
			};
			the_form.attr('action', new_url+$(this).val());
			alert(new_url+$(this).val());
		});

		$('form#form_crea #titolo').blur(function(){
			manageUrlUniqueness($(this).val(), 'corso', '');
		});
		
		$('form#form_crea_questionario select#evento').change(function(){
			$('#loading_img').show();
			location.href='http://www.rolandacademy.it/gestione/questionario/'+$('option:selected',this).val();
		});
		
		$('select#selezione_corso').change(function(){
			$("input[name=corso]").val($(this).val());
			if ($(this).hasClass('totale')){
				updateEventiTotali($(this).val());
			} else {
				updateEventiDisponibili($(this).val());
			}
		});
		
		$('select#selezione_evento').change(function(){
			if ($(this).hasClass('gestione_iscritti')){
				window.location.href='http://www.rolandacademy.it/gestione/iscritti/'+$('#selezione_corso').val()+'/'+$('#selezione_evento').val();
			} else if ($(this).hasClass('gestione_sconti')){
				$("input#evento").val($(this).val());
			} else {
				$("input[name=evento]").val($(this).val());
				
				var corso = $("input[name=corso]").val();
				var evento = $("input[name=evento]").val();
				if ( ! $(this).hasClass('disabled')){
					$.get("index2.php?page=iscrizione&task=redirect_on_scelta_evento", { corso: corso, evento: evento },
						function(data){
							window.location.href=data;
						}
					);
				}
			}
		});
		
		$('select#selezione_evento_tmp').change(function(){
			$("input[name=evento]").val($(this).val());
		});
		
		$('#lista_iscritti select#selezione_evento').change(function(){
			var corso = $("input[name=corso]").val();
			var evento = $("input[name=evento]").val();
			$.get("index2.php?page=gestione&task=redirect_on_scelta_evento", { corso: corso, evento: evento },
				function(data){
					window.location.href=data;
				}
			);
		});
		
		$('#lista_attestati select#selezione_evento').change(function(){
			var corso = $("input[name=corso]").val();
			var evento = $("input[name=evento]").val();
			$.get("index2.php?page=gestione&task=redirect_on_scelta_attestato", { corso: corso, evento: evento },
				function(data){
					window.location.href=data;
				}
			);
		});
		
		$('.stampa').click(function(){
			$.get($(this).attr('href'), '',
				function(data){
					$('body').append('<iframe name="print_frame" width="0" height="0" frameborder="0" src="about:blank"></iframe>');
					window.frames["print_frame"].document.body.innerHTML=data;
					window.frames["print_frame"].focus();
					window.frames["print_frame"].print();
					$("iframe").remove();
				}
			);
			$(this).delay(3000);
			return false;
		});
		
		$('a[id^=accetta_]').live('click', function(){
			var val = $(this).attr('id').split('_');
			var evento = val[val.length-2];
			val = val[val.length-1];
			accetta_nega(1, evento, val, $(this).attr('id').substr(8, $(this).attr('id').length), $(this).attr('href'));
		});
		
		$('a[id^=nega_]').live('click', function(){
			var val = $(this).attr('id').split('_');
			var evento = val[val.length-2];
			val = val[val.length-1];
			accetta_nega(0, evento, val, $(this).attr('id').substr(5, $(this).attr('id').length), $(this).attr('href'));
		});
		
		function accetta_nega(toggle, evento, val, id, url){
			$.get("index2.php?page=gestione&task=toggle_accettazione_iscritto", { iscritto: val, evento: evento, accettato: toggle, id_completo: id, url: url },
				function(data){
					$('#accettazione_'+val).html(data);
				}
			);
		}
		
		$("input#ck_aggiornamento_prov").change(function(){
			var val = $(this).is(':checked');
			if (val) $("#blocco_province").css('display', 'inline');
			else	 $("#blocco_province").css('display', 'none');
		})
		
		$('#controllo_url').click(function(){controllaUrlCorso();});
		
		$('#controllo_url_evento').click(function(){controllaUrlEvento();});
		
		$('#controllo_codice_sconto').click(function(){
			var url = $('form#aggiungi_sconto_form #codice');
			if (url.val() == ''){
				alert('inserisci un codice o premi il pulsante del generatore');
			}
			manageUrlUniqueness(url.val(), 'sconto', '');
		});
		
		$('.toggle_add_sconto').click(function(){
			$('#add_sconto').toggle();
		});
		
		$('#controllo_url_relatore').click(function(){
			var url = $('form#aggiungi_relatore_form #url');
			if (url.val() == ''){
				alert('inserisci un url o premi il pulsante del generatore');
			}
			manageUrlUniqueness(url.val(), 'relatore', '');
		});
		
		$("a[id^=toggle_promozione_]").click(function(){
			alert('ciao');
			var val = $(this).attr('id').split('_');
			val = val[val.length-1];
			$.get("index2.php?page=gestione&task=toggle_sconto", { sconto: val },
				function(data){
					$('span#enabled_'+val).html(data);
					if (data == 'abilitato'){
						$('a#toggle_promozione_'+val).html('<img src="http://www.rolandacademy.it/images/icons/bulb_on.png" />');
					} else {
						$('a#toggle_promozione_'+val).html('<img src="http://www.rolandacademy.it/images/icons/bulb_off.png" />');
					}
				}
			);
		});
		
		
		$('#controllo_username').click(function(){
			var url = $('form#aggiungi_utente_form #username');
			if (url.val() == ''){
				alert('inserisci uno username');
			}
			manageUrlUniqueness(url.val(), 'username', '');
		});
		
		$("a[id^=toggle_utente_]").live('click', function(){
			var val = $(this).attr('id').split('_');
			val = val[val.length-1];
			$.get("index2.php?page=gestione&task=toggle_utente", { utente: val },
				function(data){
					$('span#enabled_'+val).html(data);
				}
			);
		});
		
		
		jQuery(function(a){a.datepicker.regional.it={closeText:"Chiudi",prevText:"&#x3c;Prec",nextText:"Succ&#x3e;",currentText:"Oggi",monthNames:["Gennaio","Febbraio","Marzo","Aprile","Maggio","Giugno","Luglio","Agosto","Settembre","Ottobre","Novembre","Dicembre"],monthNamesShort:["Gen","Feb","Mar","Apr","Mag","Giu","Lug","Ago","Set","Ott","Nov","Dic"],dayNames:["Domenica","Luned&#236","Marted&#236","Mercoled&#236","Gioved&#236","Venerd&#236","Sabato"],dayNamesShort:["Dom","Lun","Mar","Mer","Gio","Ven","Sab"],dayNamesMin:["Do","Lu","Ma","Me","Gio","Ve","Sa"],dateFormat:"dd/mm/yy",firstDay:1,isRTL:false};a.datepicker.setDefaults(a.datepicker.regional.it)});
		$(".datepicker").datepicker({ regional: 'it', dateFormat: 'dd/mm/yy', minDate: 0, showOn: 'button', buttonImage: 'images/calendar.gif', buttonImageOnly: false });
		$(".timepicker").timepickr({ convention: 24, trigger: 'click' });
		$("#giorno_inizio").datepicker({ regional: 'it', dateFormat: 'dd/mm/yy', minDate: 0, showOn: 'button', buttonImage: 'images/calendar.gif', buttonImageOnly: false });
		$("#giorno_fine").datepicker({ regional: 'it', dateFormat: 'dd/mm/yy', minDate: 0, showOn: 'button', buttonImage: 'images/calendar.gif', buttonImageOnly: false });
		$("#data_nascita").datepicker({ regional: 'it', dateFormat: 'dd/mm/yy', minDate: -(365*90), showOn: 'button', buttonImage: 'images/calendar.gif', buttonImageOnly: false, changeMonth: true, changeYear: true });
		$("#scadenza").datepicker({ regional: 'it', dateFormat: 'dd/mm/yy', minDate: 0, showOn: 'button', buttonImage: 'images/calendar.gif', buttonImageOnly: false, changeMonth: true, changeYear: true });
		
		/*
		$("input#provincia").autocomplete("index2.php?page=iscrizione&task=get_province_by_search", {
			formatItem: function(data, i, n, value) {
				return value.split(",")[1];
			},
			formatResult: function(data, value) {
				return value.split(",")[1];
			}
		});
		$("input#provincia").result(function(event, data, formatted) {
			if (data){ $("input#provincia_hidden").val((''+data).split(",")[0]); }
		});
		*/
		
		/*
		updateMacchinePossedute();
		$("span.macchina_aggiunta").live('click', function(){
			var id = $(this).attr('id').split("_")[2];
			rimuoviMacchinaDallaLista(id);
		});
		
		getMacchinePossedute();
		*/
		
		/*
		updateProvinceDisponibili();
		$("span.provincia_aggiunta").live('click', function(){
			var id = $(this).attr('id').split("_")[2];
			rimuoviProvinciaDallaLista(id, $(this).attr("id"));
		});
		*/
		
		$("form [id$=_error]").css('color', 'red').css('font-size', '10px');
		$("form#form_crea input#url").keyup(function(){
			var val = $(this).val();
			$("form#form_crea #url_evento_span").html(val == '' ? 'nome-del-corso' : val);
		});
		$("form#form_crea select#url").change(function(){
			var val = $(this).val();
			$("form#form_crea #url_evento_span").html(val == '' ? 'nome-del-corso' : val);
		});
		
		$('a.elimina_luogo').click(function(){
			var val = $(this).attr('id').split('_');
			val = val[val.length-1];
			if (window.confirm('Sei sicuro di voler cancellare questo luogo?')){
				rimuoviLuogo(val);
			}
		});
		
		$('a.modifica_luogo').click(function(){
			var val = $(this).attr('id').split('_');
			val = val[val.length-1];
			preModificaLuogo(val);
		});
		
		$('#altri_partecipanti_button a').click(function(){
			var partecipanti = $("#altri_partecipanti").children().size();
			var max_partecipanti = $("#max_partecipanti_per_azienda").val();
			if (max_partecipanti == '') max_partecipanti = 0;
			aggiungiPartecipante(partecipanti, max_partecipanti);
		});
		
		$('.rimuovi_collega a').live('click', function(){
			var val = $(this).parent().attr('id').split('_');
			val = val[val.length-1];
			$('#partecipante_'+val).remove();
			return false;
		});
		
		$('#genera_codice_sconto').click(function(){
			var chars = "0123456789abcdefghiklmnopqrstuvwxyz";
			var string_length = 10;
			var stringa = '';
			for (var i=0; i<string_length; i++) {
				var rnum = Math.floor(Math.random() * chars.length);
				stringa += chars.substring(rnum,rnum+1);
			}
			var codice = $('form#aggiungi_sconto_form #codice');
			codice.val(stringa);
			manageUrlUniqueness(stringa, 'sconto', '');
		});
		
		$('#genera_url_relatore').click(function(){
			var chars = "0123456789abcdefghiklmnopqrstuvwxyz";
			var string_length = 10;
			var stringa = '';
			for (var i=0; i<string_length; i++) {
				var rnum = Math.floor(Math.random() * chars.length);
				stringa += chars.substring(rnum,rnum+1);
			}
			var codice = $('form#aggiungi_relatore_form #url');
			codice.val(stringa);
			manageUrlUniqueness(stringa, 'relatore', '');
		});
		
		
		$('#lista_promozioni_wrapper a[id^=elimina_promozione_]').click(function(){
			var val = $(this).attr('id').split('_');
			val = val[val.length-1];
			if (window.confirm('Sei sicuro di voler cancellare questa promozione?')){
				rimuoviPromozione(val);
			}
		});
		
		$('a.elimina_corso').click(function(){
			var val = $(this).attr('id').split('_');
			val = val[val.length-1];
			if (window.confirm('Sei sicuro di voler cancellare questo corso?')){
				rimuoviCorso(val);
			}
		});
		
		$('a.elimina_evento').click(function(){
			var val = $(this).attr('id').split('_');
			val = val[val.length-1];
			if (window.confirm('Sei sicuro di voler cancellare questo evento?')){
				rimuoviEvento(val);
			}
			return false;
		});
		
		$('#lista_promozioni_wrapper a.modifica_sconto').click(function(){
			var val = $(this).attr('id').split('_');
			val = val[val.length-1];
			modificaSconto(val);
			return false;
		});
		
		$('#lista_utenti_wrapper a[id^=elimina_utente_]').click(function(){
			var val = $(this).attr('id').split('_');
			val = val[val.length-1];
			if (window.confirm('Sei sicuro di voler eliminare questo utente?')){
				rimuoviUtente(val);
			}
		});
		
		$('#lista_utenti_wrapper a[id^=modifica_utente_]').click(function(){
			var val = $(this).attr('id').split('_');
			val = val[val.length-1];
			modificaUtente(val);
		});
		
		$('#lista_relatori_wrapper a[id^=nascondi_relatore_]').click(function(){
			var val = $(this).attr('id').split('_');
			val = val[val.length-1];
			if (window.confirm('Sei sicuro di voler nascondere questo relatore?')){
				nascondiRelatore(val);
			}
		});
		
		$('#lista_relatori_wrapper a.modifica_relatore').click(function(){
			var val = $(this).attr('id').split('_');
			val = val[val.length-1];
			modificaRelatore(val);
		});
		
		$('a.modifica_dealer').click(function(){
			var val = $(this).attr('id').split('_');
			val = val[val.length-1];
			modificaDealer(val);
		});
		
		$('#lista_dealers_wrapper a[id^=elimina_dealer_]').click(function(){
			var val = $(this).attr('id').split('_');
			val = val[val.length-1];
			if (window.confirm('Sei sicuro di voler nascondere questo relatore?')){
				eliminaDealer(val);
			}
		});
		
		$("a.show_extrainfo").click(function(){
			var val = $(this).attr('id').split('_');
			val = val[val.length-1];
			var div = $("div#extrainfo_"+val);
			if (div.hasClass('hidden')){
				div.slideDown(600).removeClass('hidden');
				$(this).html('Nascondi le informazioni aggiuntive').attr('title', 'Nascondi le informazioni aggiuntive');
			} else {
				div.slideUp(600).addClass('hidden');
				$(this).html('Mostra le informazioni aggiuntive').attr('title', 'Mostra le informazioni aggiuntive');
			}
		});
		
		
	});
	
	function aggiungiFiltro(obj, num){
		var domanda = $("input#domanda_"+(num-1)).val();
		if (domanda){
			genera_form_filtro(num, num+1);
			$(obj).hide();
		}
		return false;
	}
	
	function eliminaFiltro(val){
		var obj = $("div#filtro_"+val);
		var obj_n = $("div#filtro_"+(val+1)).text();
		obj.fadeOut(600);
		obj.remove();
		if (obj_n != ''){
		} else {
			$("a#aggiungi_filtro_"+val).show();
		}
		return false;
	}


/************************************************************/
/****                   Funzioni Form                    ****/
/************************************************************/

	function loadnext (divout, divin){
		if (validate_iscrizione(divout, divin)){
			$("div.step_" + divout).hide();
			$("div.step_" + divin).fadeIn(400);
		}
	}
	
	
	function validate_iscrizione(id, out) {
		if (out < id) return true;
		var ret = true;
		
		$("form [id$=_error]").hide().removeClass('error');
		
		if (id == 1){
			var corso = $('input[name=corso]'); 
		    var evento = $('input[name=evento]');
			if ($('input#password_dealer').length > 0){
				var v1 = SHA1('][roland][academy]['+$('input#password_dealer').val()+'][roland][academy][');
				var v2 = $('input#password_dealer_hidden').val();
				if (v1 != v2){
					$('#password_dealer_error').fadeIn(1000);
					ret = false;
				}
			}
			if ( ! corso.fieldValue()[0]) {
				$('#selezione_corso_error').fadeIn(1000);
				ret = false; 
			}
			if ( ! evento.fieldValue()[0]) { 
				$('#selezione_evento_error').fadeIn(1000);
				ret = false; 
			}
			var sn = $('#serial_number');
			if (sn.length > 0 && ! valida_sn(sn.fieldValue()[0])){
				$('#serial_number_error').fadeIn(1000);
				ret = false;
			}
		} else if (id == 2){
			var provincia = $('input[name=provincia_hidden]');
			if (provincia.val() == ''){
			/*
			20101028 - gg
				$('#provincia_hidden_error').fadeIn(1000);
				ret = false;
			*/
			}
			var piva = $('input[name=partita_iva]');
			if (piva.val().length > 0 && ! valida_partita_iva(piva.fieldValue()[0])){
				$('#partita_iva_error').fadeIn(1000);
				ret = false;
			}
		} else if (id == 3){
			var cf = $('input#codicefiscale');
			if ($('input#codicefiscale').val() != ""){
				if ( ! valida_cf(cf.fieldValue()[0])){
					$('#codicefiscale_error').fadeIn(1000);
					ret = false;
				}
			}
			var email = $('input[name=email]');
			if ( ! valida_mail(email.fieldValue()[0])){
				$('#email_error').fadeIn(1000);
				ret = false;
			}
			if ($('input#sconto').val() != ""){
				var pox_sc = $('#pox_sc').html().split(",");
				var ret1 = false;
				for (var ip = 0; ip < pox_sc.length; ip++){
					if (pox_sc[ip] == $('input#sconto').val()){
						ret1 = true;
						break;
					}
				}
				if (!ret1){
					$('#sconto_error').fadeIn(1000);
					ret = false;
				}
			}
		} else if (id == 4){
		} else if (id == 5){
		} else if (id == 6){
			
		} else {
			return false;
		}
		
		var testi = $('form#form_iscrizione .step_'+id+' input[type=text]');
	    var autorizzazioni = $('form#form_iscrizione .step_'+id+' input[type=checkbox]');
		
		testi.each(function(){
			if ($(this).parent().hasClass("req")){
				if ( ! $(this).fieldValue()[0]) { 
					$('#'+$(this).attr('id')+'_error').fadeIn(500);
					ret = false; 
				}
			}
		});
		
		autorizzazioni.each(function(){
			if ($(this).parent().hasClass("req")){
				if ( ! $(this).is(":checked")) { 
					$('#'+$(this).attr('id')+'_error').fadeIn(500);
					ret = false; 
				}
			}
		});
		
		return  ret;
	}
	

	function showRequestSendToAFriend(formData, jqForm, options) { 
	    var queryString = $.param(formData); 
		var ret = true;
		if ($('form #me_name').val() == ''){
			alert('Inserire il tuo nome');
			ret = false;
		} else if ( ! valida_mail($('form #me_email').val())){
			alert('Inserire il tuo indirizzo email valido');
			ret = false;
		} else if ($('form #friend_name').val() == ''){
			alert('Inserire il nome del tuo amico');
			ret = false;
		} else if ( ! valida_mail($('form #friend_email').val())){
			alert('Inserire indirizzo email valido del tuo amico');
			ret = false;
		} 
		$('.loading_img').fadeIn(100);
	    return ret;
	}
	
	function showResponseSendToAFriend(responseText, statusText)  {
		if (statusText == 'success'){
			$('input#friend').val('');
			$('.loading_img').fadeOut(100);
			$('form#send_to_a_friend input[type=text]').val('');
			setTimeout('_fadeOut(\'#output_send_to_a_friend\', 2000)', 6000);
		}
	}

	function showRequestLuogo(formData, jqForm, options) { 
	    var queryString = $.param(formData); 
	    // alert('About to submit: \n\n' + queryString); 
	    return true; 
	}
	
	function showResponseLuogo(responseText, statusText)  {
		if (statusText == 'success'){
			updateLuoghi();
			alert('Luogo aggiunto con successo. Puoi gia\' trovarlo nella select');
		}
	    // alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + 
	    //     '\n\nThe output div should have already been updated with the responseText.'); 
	}
	
	
	function showRequestCreaCorso(formData, jqForm, options) { 
		var ret = true;
		for (var i=0; i < formData.length; i++) { 
       		if (formData[i].name == "invia" && (formData[i].value == "crea evento" || formData[i].value == "crea corso ed evento")) {
       			if ($('select#luogo').val() == ""){
	            	alert('Seleziona il luogo dove si terra\' l\'evento');
					ret = false;
       			}
       			if ($('input#tipo_creazione').val() == "corso"){
       				if ( ! $('#titolo').val()){
	            		alert('inserisci tutti i dati del corso a cui associare l\'evento');
						ret = false;
       				}
       			} else {
       				if ( ! $('#url').val()){
	            		alert('seleziona un corso a cui associare l\'evento');
						ret = false;
       				}
       				if ( ! $('#url_evento').val()){
	            		alert('Specifica tutti i dati dell\'evento');
						ret = false;
       				}
       			}
        	} 
    	} 
    	/*
		if ($('input#titolo').length > 0 && $('input[name=url_evento]').val() == ''){
			alert('seleziona un corso a cui associare l\'evento');
			ret = false;
		}
		*/
	    return ret; 
	}
	
	function showResponseCreaCorso(responseText, statusText)  {
		if (statusText == 'success'){
			$("#form_crea_wrapper").hide("fast");
			updateListaCorsi();
			
			creaEventoGoogleCalendar($('#url').val(), $("#url_evento").val());
			
			alert('Corso creato con successo');
		}
	}
	
	function creaEventoGoogleCalendar(corso, evento){
		var url = "index2.php?page=gestione&task=get_orari_by_corso_evento_json";

		$.getJSON(url, { corso: corso, evento: evento }, function(j){
			if (j != null && j.length > 0){
			for (var i = 0; i < j.length; i++) {
				creaEvento(j[i].titolo, j[i].descrizione, j[i].from, j[i].to, j[i].luogo, j[i].coordinate);
			}
			}
		});
	}
	
	function showRequestCreaQuestionario(formData, jqForm, options) { 
	    var queryString = $.param(formData);
	    return true; 
	}
	
	function showResponseCreaQuestionario(responseText, statusText)  {
		if (statusText == 'success'){
			$("#form_crea_wrapper").fadeOut("fast");
			$("#output_questionario").fadeIn("slow");
		}
	}
	
	
	function showRequestIscrizione(formData, jqForm, options) {
	    var queryString = $.param(formData);
		var ret = true;
		$("form [id$=_error]").hide();
		
		var corso = $('input[name=corso]'); 
	    var evento = $('input[name=evento]');
	    var email = $('input[name=email]');
	    var testi = $('form#form_iscrizione input[type=text]');
	    var autorizzazioni = $('form#form_iscrizione input[type=checkbox]');
		
		if ( ! corso.fieldValue()[0]) {
			corso.addClass('error');
			$('#selezione_corso_error').fadeIn(500);
			ret = false; 
		}
		if ( ! evento.fieldValue()[0]) { 
			evento.addClass('error');
			$('#selezione_evento_error').fadeIn(500);
			ret = false; 
		}
		if ( ! valida_mail(email.fieldValue()[0])){
			email.addClass('error');
			$('#email_error').fadeIn(500);
			ret = false;
		}
		testi.each(function(){
			if ($(this).parent().hasClass("req")){
				if ( ! $(this).fieldValue()[0]) { 
					$(this).addClass('error');
					$('#'+$(this).attr('id')+'_error').fadeIn(500);
					ret = false; 
				}
			}
		});
		
		autorizzazioni.each(function(){
			if ($(this).parent().hasClass("req")){
				if ( ! $(this).is(":checked")) { 
					$(this).addClass('error');
					$('#'+$(this).attr('id')+'_error').fadeIn(500);
					ret = false; 
				}
			}
		});
		
		return  ret;
	}
	
	function showResponseIscrizione(responseText, statusText)  {
		if (statusText == 'success'){
			alert('Iscrizione avvenuta con successo');
			location.href = 'http://www.rolandacademy.it';
		}
	}
	
	function showRequestModificaIscrizione(formData, jqForm, options) {
	    var queryString = $.param(formData);
		var ret = true;
		$("form [id$=_error]").hide();
		
		
		var corso = $('input[name=corso]'); 
	    var evento = $('input[name=evento]');
	    var email = $('input[name=email]');
	    var testi = $('form#form_modifica_iscrizione input[type=text]');
	    var autorizzazioni = $('form#form_modifica_iscrizione input[type=checkbox]');
		
		if ( ! corso.fieldValue()[0]) {
			corso.addClass('error');
			$('#selezione_corso_error').fadeIn(500);
			ret = false; 
		}
		if ( ! evento.fieldValue()[0]) { 
			evento.addClass('error');
			$('#selezione_evento_error').fadeIn(500);
			ret = false; 
		}
		if ( ! valida_mail(email.fieldValue()[0])){
			email.addClass('error');
			$('#email_error').fadeIn(500);
			ret = false;
		}
		testi.each(function(){
			if ($(this).parent().hasClass("req")){
				if ( ! $(this).fieldValue()[0]) { 
					evento.addClass('error');
					$('#'+$(this).attr('id')+'_error').fadeIn(500);
					ret = false; 
				}
			}
		});
		
		autorizzazioni.each(function(){
			if ($(this).parent().hasClass("req")){
				if ( ! $(this).is(":checked")) { 
					evento.addClass('error');
					$('#'+$(this).attr('id')+'_error').fadeIn(500);
					ret = false; 
				}
			}
		});
		if (!ret){
			alert('si e\' verificato un errore');
		}
		
		return  ret;
	}
	
	function showResponseModificaIscrizione(responseText, statusText)  {
		if (statusText == 'success'){
			if (responseText.indexOf("http") != -1){
				document.location.href=responseText;
			} else {
				alert(responseText);
			}
		}
	}
	
	function showRequestRichiestaQuestionario(formData, jqForm, options) {
	    var queryString = $.param(formData);
		var ret = true;
		$("#loading_img_richiesta").fadeIn();
		
		return  ret;
	}
	
	function showResponseRichiestaQuestionario(responseText, statusText)  {
		if (statusText == 'success'){
			$("#loading_img_richiesta").fadeOut();
			$("#form_richiesta_questionari").append(responseText);
		}
	}
	
	function showRequestCompilazioneQuestionario(formData, jqForm, options) {
		var ret = true;
		if (!window.confirm('Hai compilato correttamente il questionario?')) ret = false;
		return  ret;
	}
	
	function showResponseCompilazioneQuestionario(responseText, statusText)  {
		if (statusText == 'success'){
			$("#output_iscrizione").html(responseText);
			$('form#form_compilazione').hide();
			$('#lista_dei_file').fadeIn();
		}
	}
	
	function showRequestModificaCorso(formData, jqForm, options) {
	    var queryString = $.param(formData);
		var ret = true;
		
		var corso = $('input[name=titolo]');
		
		if ($('input[name=titolo]').val() == '') {
			alert('Specifica un titolo');
			ret = false;
		}
		
		return  ret;
	}
	
	function showResponseModificaCorso(responseText, statusText)  {
		if (statusText == 'success'){
			document.location.href=responseText;
		}
	}
	
	function showRequestCaricaLogo(formData, jqForm, options) {
		var ret = true;
		if ($('input#file').val() == '' || $('input#filename').val() == ''){
			alert('Inserisci tutti i dati');
			ret = false;
		}
		return  ret;
	}
	
	function showResponseCaricaLogo(responseText, statusText)  {
		if (statusText == 'success'){
			alert('Logo caricato con successo');
		} else {
			alert('Errore nel caricamento dell\'allegato');
		}
	}
	
	function showRequestModificaEvento(formData, jqForm, options) {
	    var queryString = $.param(formData);
		var ret = true;
		
		// ... TODO da implementare il controllo sulla modifica dell'evento
		
		return  ret;
	}
	
	function showResponseModificaEvento(responseText, statusText)  {
		if (statusText == 'success'){
			document.location.href=responseText;
		}
	}
	
	function showRequestSconto(formData, jqForm, options) { 
	    var queryString = $.param(formData);
	    return true; 
	}
	
	function showResponseSconto(responseText, statusText)  {
		if (statusText == 'success'){
			document.location.reload();
		}
	}
	
	function showRequestUtente(formData, jqForm, options) { 
	    var queryString = $.param(formData);		
		var ret = true;
		$("form [id$=_error]").hide();
		
		var username = $('input[name=username]'); 
	    var password = $('input[name=password]');
	    var password2 = $('input[name=password2]');
	    var email = $('input[name=email]');
		
		if ( ! username.fieldValue()[0]) {
			$('#username_error').fadeIn(500);
			ret = false; 
		}
		if ( ! password.fieldValue()[0] ||  ! password2.fieldValue()[0] || password.fieldValue()[0] != password2.fieldValue()[0]) { 
			password.addClass('error');
			$('#password_error').fadeIn(500);
			ret = false; 
		}
		if ( ! valida_mail(email.fieldValue()[0])){
			email.addClass('error');
			$('#email_error').fadeIn(500);
			ret = false;
		}
	    return ret;
	}
	
	function showResponseUtente(responseText, statusText)  {
		if (statusText == 'success'){
			if (responseText != ''){
				$('#lista_utenti_wrapper').append(responseText);
			}
		}
	}
	
	function showRequestRelatore(formData, jqForm, options) { 
	    var queryString = $.param(formData);
		var ret = true;
		$("form [id$=_error]").hide();
		
		var nome = $('input[name=nome]'); 
	    var cognome = $('input[name=cognome]');
	    var email = $('input[name=email]');
		
		if ( ! nome.fieldValue()[0]) {
			email.addClass('error');
			$('#nome_error').fadeIn(500);
			ret = false; 
		}
		if ( ! cognome.fieldValue()[0]) { 
			email.addClass('error');
			$('#cognome_error').fadeIn(500);
			ret = false; 
		}
		if ( ! valida_mail(email.fieldValue()[0])){
			email.addClass('error');
			$('#email_error').fadeIn(500);
			ret = false;
		}
	    return ret;
	}
	
	function showResponseRelatore(responseText, statusText)  {
		if (statusText == 'success'){
			if (responseText != ''){
				document.location.reload();
			}
		}
	}
	
	function showRequestDispensa(formData, jqForm, options) { 
		var ret = true;
		$("form [id$=_error]").hide();
		
		var titolo = $('input#titolo'); 
		if ( ! titolo.fieldValue()[0]) {
			titolo.addClass('error');
			$('#titolo_error').fadeIn(500);
			ret = false; 
		}
	    return ret;
	}
	
	function showResponseDispensa(responseText, statusText)  {
		if (statusText == 'success'){
			if (responseText != ''){
				document.location.reload();
			}
		}
	}
	
	function showRequestDealer(formData, jqForm, options) { 
	    var queryString = $.param(formData);
		var ret = true;
		$("form [id$=_error]").hide();
		
		var nome = $('input[name=nome]'); 
	    var cognome = $('input[name=cognome]');
	    var email = $('input[name=email]');
		
		if ( ! nome.fieldValue()[0]) {
			email.addClass('error');
			$('#nome_error').fadeIn(500);
			ret = false; 
		}
		if ( ! cognome.fieldValue()[0]) { 
			email.addClass('error');
			$('#cognome_error').fadeIn(500);
			ret = false; 
		}
		if ( ! valida_mail(email.fieldValue()[0])){
			email.addClass('error');
			$('#email_error').fadeIn(500);
			ret = false;
		}
	    return ret;
	}
	
	function showResponseDealer(responseText, statusText)  {
		if (statusText == 'success'){
			window.location.reload();
		}
	}
	
	function showRequestEditUtente(formData, jqForm, options) { 
	    var queryString = $.param(formData);		
		var ret = true;
		$("form [id$=_error]").hide();
		
	    var password = $('input[name=password]');
	    var password2 = $('input[name=password2]');
	    var email = $('input[name=email]');
		
		if (password.fieldValue()[0] != password2.fieldValue()[0]) { 
			password.addClass('error');
			$('#password_error').fadeIn(500);
			ret = false; 
		}
		if ( ! valida_mail(email.fieldValue()[0])){
			email.addClass('error');
			$('#email_error').fadeIn(500);
			ret = false;
		}
	    return ret;
	}
	
	function showResponseEditUtente(responseText, statusText)  {
		if (statusText == 'success'){
			window.location.reload();
		}
	}
	
	function showRequestEditRelatore(formData, jqForm, options) { 
	    var queryString = $.param(formData);
		var ret = true;
		$("form [id$=_error]").hide();
		
	    var nome = $('input[name=nome2]'); 
	    var cognome = $('input[name=cognome2]');
	    var email = $('input[name=email2]');
		
		if ( ! nome.fieldValue()[0]) {
			email.addClass('error');
			$('#nome2_error').fadeIn(500);
			ret = false; 
		}
		if ( ! cognome.fieldValue()[0]) { 
			email.addClass('error');
			$('#cognome2_error').fadeIn(500);
			ret = false; 
		}
		if ( ! valida_mail(email.fieldValue()[0])){
			email.addClass('error');
			$('#email2_error').fadeIn(500);
			ret = false;
		}
	    return ret;
	}
	
	function showResponseEditRelatore(responseText, statusText)  {
		if (statusText == 'success'){
			window.location.reload();
		}
	}
	
	function showRequestEditDealer(formData, jqForm, options) { 
	    var queryString = $.param(formData);
		var ret = true;
		$("form [id$=_error]").hide();
		
	    var nome = $('input[name=nome2]'); 
	    var cognome = $('input[name=cognome2]');
	    var email = $('input[name=email2]');
		
		if ( ! nome.fieldValue()[0]) {
			email.addClass('error');
			$('#nome2_error').fadeIn(500);
			ret = false; 
		}
		if ( ! cognome.fieldValue()[0]) { 
			email.addClass('error');
			$('#cognome2_error').fadeIn(500);
			ret = false; 
		}
		if ( ! valida_mail(email.fieldValue()[0])){
			email.addClass('error');
			$('#email2_error').fadeIn(500);
			ret = false;
		}
	    return ret;
	}
	
	function showResponseEditDealer(responseText, statusText)  {
		if (statusText == 'success'){
			window.location.reload();
		}
	}
	
	function showRequestUploadAttestato(formData, jqForm, options) { 
	    var queryString = $.param(formData);
		var ret = true;
		
	    var immagine = $('input[name=attestato_image]');
		
		if ( ! immagine.fieldValue()[0]) {
			alert('specifica un\'immagine');
			ret = false; 
		}
	    return ret;
	}
	
	function showResponseUploadAttestato(responseText, statusText)  {
		if (statusText == 'success'){
			$("#image_wrapper").html('Immagine: <img src="'+responseText+'" />');
		}
	}
	
	function showRequestIscrizioneNewsletter(formData, jqForm, options) { 
	    var queryString = $.param(formData);
		var ret = true;
		
		$("#loading_newsletter").show();
		
	    var email = $('input#email');
		
		if (email.val() == ""){
			alert('specifica il tuo indirizzo email');
			ret = false;
		} else {
			if ( ! valida_mail(email.val())) {
				alert('inserisci un indirizzo email corretto');
				ret = false; 
			}
		}
		if ( ! ret){
			$("#loading_newsletter").hide();
		}
	    return ret;
	}
	
	function showResponseIscrizioneNewsletter(responseText, statusText)  {
		if (statusText == 'success'){
			$("#loading_newsletter").hide();
			$("#iscrizione_newsletter_wrapper").html(responseText);
		}
	}
	
	function _fadeOut(obj, time){
		$(obj).fadeOut(time).html('').show();
	}
	
	function toggleList(obj1, obj2){
		if ((obj2).hasClass('open')){
			obj1.removeClass('open');
			obj2.slideUp(300).removeClass('open');
		} else {
			obj1.addClass('open');
			obj2.slideDown(300).addClass('open');
		}
	}
	
	/**
	 * Controlla che il campo url della form sia corretto e univoco
	 */
	function manageUrlUniqueness(nome, tipo, extra){
		$.get("index2.php?page=gestione&task=url_unique", { id: nome, tipo: tipo, extra: extra },
			function(data){
				if (tipo == 'corso'){
					$("form#form_crea #url").val(data);
					$("#controllo_url").removeClass().addClass('positive');
					$("form#form_crea #url_evento_span").html(data == '' ? 'nome-del-corso' : data);
				} else if (tipo == 'evento'){
					$("form#form_crea #url_evento").val(data);
					$("#controllo_url_evento").removeClass().addClass('positive');
				} else if (tipo == 'sconto'){
					$("form#aggiungi_sconto_form #codice").val(data);
					$("#controllo_codice_sconto").removeClass().addClass('positive');
				} else if (tipo == 'relatore'){
					$("form#aggiungi_relatore_form #url").val(data);
					$("#controllo_url_relatore").removeClass().addClass('positive');
				} else if (tipo == 'username'){
					$("form#aggiungi_utente_form #username").val(data);
					$("#controllo_username").removeClass().addClass('positive');
				}
			}
		);
	}
	
	/**
	 * Aggiunge una nuova riga nella form degli orari
	 */
	function genera_form_orario(val){
		$.get("index2.php?page=gestione&task=generate_form_orario", { id: val },
			function(data){
				$("#lista_degli_orari").append(data);
				$(".datepicker").datepicker({ regional: 'it', dateFormat: 'dd/mm/yy', minDate: 0, showOn: 'button', buttonImage: 'images/calendar.gif', buttonImageOnly: false });
				$(".timepicker").timepickr({ convention: 24, trigger: 'click' });
				$('a#aggiungi_orario_'+(val - -1)).click(function(){
					return aggiungiOrario($(this), (val - -1));
				});
			}
		);
	}
	
	function aggiungiOrario(obj, val){
		var giorno = $("input#giorno_"+(val-1)).val();
		var ora_1 = $("input#ora_iniziale_"+(val-1)).val();
		var ora_2 = $("input#ora_finale_"+(val-1)).val();
		if (giorno && ora_1 && ora_2){
			genera_form_orario(val);
			$(obj).hide();
		}
		return false;
	}
	
	/**
	 * Aggiunge una nuova riga nella form dei filtri
	 */
	function genera_form_filtro(val, num){
		$.get("index2.php?page=gestione&task=generate_form_filtro", { id: val },
			function(data){
				$("#lista_dei_filtri").append(data);
				$('a#aggiungi_filtro_'+num).click(function(){
					return aggiungiFiltro($(this), num);
				});
				$("a#elimina_filtro_"+(num-1)).click(function(){
					return eliminaFiltro(num-1);
				});
			}
		);
	}
	
	function genera_form_testo(val){
		$.get("index2.php?page=gestione&task=generate_text_for_attestato", { id: val },
			function(data){
				$("#lista_dei_testi").append(data);
			}
		);
	}
	
	function genera_form_testo_partecipante(evento, val){
		$.get("index2.php?page=gestione&task=generate_parametro_partecipante_for_attestato", { evento: evento, id: val },
			function(data){
				$("#lista_dei_parametri_partecipante").append(data);
			}
		);
	}
	
	function updateMacchinePossedute(){
		var url = "index2.php?page=iscrizione&task=get_prodotti_by_search";
		// url = "http://www.rolanddg.it/rolandacademy/prodotti.php"
		// alert(url);
		$("input#macchine_possedute").autocomplete(url, {
			width: 320,
			max: 20,
			highlight: false,
			scroll: true,
			scrollHeight: 300,
			formatItem: function(data, i, n, value) {
				return '<img src="' + value.split(",")[2] + '" alt="'+value.split(",")[1]+'" height="30"/> ' + value.split(",")[1];
			},
			formatResult: function(data, value) {
				return value.split(",")[1];
			}
		});
		$("input#macchine_possedute").result(function(event, data, formatted) {
			if (data){
				$("input#macchine_possedute").val('');
				aggiungiMacchinaAllaLista(data);
			}
		});
	}
	
	
	function getMacchinePossedute(){
		var url = "index3.php?page=gestione&task=get_prodotti_by_array";
		
		// alert(url);
		$("span[id^=macchine_possedute_]").each(function(){
			var val = $(this).attr('id').split('_');
			val = val[val.length-1];
			var lista = $(this).attr('class').split('_');
			lista = lista[1];
			
			$.getJSON(url, { array: lista }, function(j){
				var options = '';
				for (var i = 0; i < j.length; i++) {
					if (i > 0) options += ", ";
					options += '<a href="'+j[i].url+'" target="_blank">' + j[i].nome + '</a>';
				}
				$("span#macchine_possedute_"+val).html(options);
			});
		});
	}
	
	function aggiungiMacchinaAllaLista(val){
		var stringa = val+'';
		var macchine_possedute = $("input#macchine_possedute_hidden").val();
		
		if (in_array(stringa.split(",")[0], macchine_possedute.split(","))) return;
		
		macchine_possedute += macchine_possedute == '' ? '' : ',';
		macchine_possedute += stringa.split(",")[0];
		$("input#macchine_possedute_hidden").val(macchine_possedute);
		
		var obj = ' <span id="macchina_aggiunta_'+stringa.split(",")[0]+'" class="macchina_aggiunta"><span>'+stringa.split(",")[1]+'</span></span> ';
		$("#lista_macchine_possedute").append(obj).children(':last').hide().fadeIn(2000);
		// alert('Aggiungo ['+stringa.split(",")[1]+'] alla lista delle macchine possedute');
	}
	
	function rimuoviMacchinaDallaLista(val){
		var macchine_possedute = $("input#macchine_possedute_hidden").val();
		var theArray = macchine_possedute.split(",");
		for (var i = 0, j = 0, tmp = ''; i < theArray.length; i++){
			if (theArray[i] != val){
				tmp += (j++ == 0 ? '' : ',') + theArray[i];
			}
		}
		$("span#macchina_aggiunta_"+val).fadeOut(500).remove();
		$("input#macchine_possedute_hidden").val(tmp);
	}
	
	
	function updateProvinceDisponibili(){
		var url = "index2.php?page=iscrizione&task=get_province_by_search";
		$("input[id^=province_disponibili]").autocomplete(url, {
			width: 320,
			max: 10,
			highlight: false,
			scroll: true,
			scrollHeight: 100,
			formatItem: function(data, i, n, value) {
				return value.split(",")[1];
			},
			formatResult: function(data, value) {
				return value.split(",")[1];
			}
		});
		$("input[id^=province_disponibili]").result(function(event, data, formatted) {
			if (data){
				var append = '';
				if ($(this).attr('id') != 'province_disponibili'){
					append = '2';
				}
				$("input#province_disponibili"+append).val('');
				aggiungiProvinciaAllaLista(data, append);
			}
		});
	}
	
	function aggiungiProvinciaAllaLista(val, append){
		var stringa = val+'';
		var province_selezionate = $("input#aggiornamento_province"+append+"_hidden").val();
		
		if (in_array(stringa.split(",")[0], province_selezionate.split(","))) return;
		
		province_selezionate += province_selezionate == '' ? '' : ',';
		province_selezionate += stringa.split(",")[0];
		$("input#aggiornamento_province"+append+"_hidden").val(province_selezionate);
		
		var obj = ' <span id="provincia_aggiunta_'+stringa.split(",")[0]+'" class="provincia_aggiunta">'+stringa.split(",")[1]+'</span> ';
		$("#lista_province"+append).append(obj).children(':last').hide().fadeIn(2000);;
		// alert('Aggiungo ['+stringa.split(",")[1]+'] alla lista delle macchine possedute');
	}
	
	function rimuoviProvinciaDallaLista(val, id){
		obj = $('#'+id).parent().parent().find("input[id^=aggiornamento_province]");
		var province_selezionate = obj.val();
		var theArray = province_selezionate.split(",");
		for (var i = 0, j = 0, tmp = ''; i < theArray.length; i++){
			if (theArray[i] != val){
				tmp += (j++ == 0 ? '' : ',') + theArray[i];
			}
		}
		$("span#provincia_aggiunta_"+val).remove();
		obj.val(tmp);
	}
	
	
	function rimuoviLuogo(val){
		$.get("http://www.rolandacademy.it/index2.php?page=gestione&task=delete_luogo", { luogo: val }, function(data){
			if (data == 'OK'){
				$('div#luogo_'+val).fadeOut(1000);
			}
		});
	}
	
	function preModificaLuogo(val){
		$.get("http://www.rolandacademy.it/index2.php?page=gestione&task=pre_edit_luogo", { luogo: val }, function(data){
			// $.facebox(data);
			$('#aggiungi_luogo').html(data);
			initialize();
			initialize_2();
			$('#aggiungi_luogo').show();
		});
	}
	
	
	function rimuoviPromozione(val){
		$.get("http://www.rolandacademy.it/index2.php?page=gestione&task=delete_sconto", { sconto: val }, function(data){
			if (data == 'OK'){
				$('#lista_promozioni_wrapper div#promozione_'+val).fadeOut(1000);
			}
		});
	}
	
	function rimuoviUtente(val){
		$.get("http://www.rolandacademy.it/index2.php?page=gestione&task=delete_utente", { utente: val }, function(data){
			if (data == 'OK'){
				$('#lista_utenti_wrapper div#utente_'+val).fadeOut(1000);
			}
		});
	}

	function rimuoviCorso(val){
		$.get("http://www.rolandacademy.it/index2.php?page=gestione&task=delete_corso", { corso: val }, function(data){
			if (data == 'OK'){
				$('#corso_'+val).fadeOut(1000);
			}
		});
	}
	
	function rimuoviEvento(val){
		$.get("http://www.rolandacademy.it/index2.php?page=gestione&task=delete_evento", { evento: val }, function(data){
			if (data == 'OK'){
				alert('Evento eliminato');
				$('#elimina_evento_'+val).parent().fadeOut();
			}
		});
	}
	
	function modificaUtente(val){
		$.getJSON("http://www.rolandacademy.it/index2.php?page=gestione&task=pre_edit_utente", { utente: val }, function(j){
			$("#the_username").html(j.username);
			$("input#username").val(j.username);
			$("input#password").val('');
			$("input#password2").val('');
			$("input#email").val(j.email);
			if (parseInt(j.enabled) > 0){
				$("input#abilitato").attr('checked', 'checked');
			} else {
				$("input#disabilitato").attr('checked', 'checked');
			}
			$('div#aggiungi_utente').hide();
			$('div#modifica_utente').show();
		});
	}
	
	function nascondiRelatore(val){
		$.get("http://www.rolandacademy.it/index2.php?page=gestione&task=nascondi_relatore", { relatore: val }, function(data){
			if (data == 'OK'){
				$('#lista_relatori_wrapper div#relatore_'+val).fadeOut(1000);
			}
		});
	}
	
	function modificaRelatore(val){
		$.getJSON("http://www.rolandacademy.it/index2.php?page=gestione&task=pre_edit_relatore", { relatore: val }, function(j){
			$("input#id").val(j.id);
			$("input#nome2").val(j.nome);
			$("input#cognome2").val(j.cognome);
			$("input#email2").val(j.email);
			$("input#video2").val(j.video);
			$("input#facebook2").val(j.facebook);
			$("input#twitter2").val(j.twitter);
			$("input#skype2").val(j.skype);
			$("input#data_nascita2").val(j.data_nascita);
			$("#descrizione2").html(j.descrizione);
			// $(".rte-zone, #descrizione2").remove();
			// $("#descrizione2_wrapper").append('<textarea name="descrizione2" class="wysiwyg2" rows="8" cols="40" id="descrizione2">'+j.descrizione+'</textarea>');
			// $("textarea#descrizione2").val(j.descrizione);
			if (j.fotografia != ''){
				$('div#fotografia_place').html('<a href="'+j.url_fotografia+'" rel="fancybox"><img src="'+j.fotografia+'" alt="'+j.nome+' '+j.cognome+'" width="120" height="120"/></a>').find('a').fancybox({ 'hideOnContentClick':false, 'showCloseButton': true, 'width': 520, 'height' :320,'type' : 'swf' });
			}
			$('div#aggiungi_relatore').hide();
			$('div#modifica_relatore').show();
			/*
			$('#descrizione2').rte({
				controls_rte: rte_toolbar,
				controls_html: html_toolbar
			});
			*/
		});
	}
	
	function modificaSconto(val){
		$.getJSON("http://www.rolandacademy.it/index2.php?page=gestione&task=pre_edit_sconto", { sconto: val }, function(j){
			$('.toggle_add_sconto').html('Modifica il codice promozionale '+j.codice);
			$('form').clearForm();
			$('#label_codice_wrapper').hide();
			$("input#id").val(j.id);
			$("input#attivazioni").val(j.quantita);
			var scadenza = j.scadenza.split("/");
			if (scadenza.length > 0){
				var giorno = scadenza[0].substring(0,1) == '0' ? scadenza[0].substring(1,2) : scadenza[0];
				var mese = scadenza[1].substring(0,1) == '0' ? scadenza[1].substring(1,2) : scadenza[1];
				var anno = scadenza[2];
				$("input#scadenza").datepicker("setDate", new Date(parseInt(anno), parseInt(mese)-1, parseInt(giorno)));
			}
			$("input#valore").val(j.valore);
			$("input#corso").val(j.corso_url);
			$("input#evento").val(j.evento_url);
			$("select#tipo option").attr('selected', false);
			$("select#tipo option[value="+j.tipo+"]").attr('selected', true);
			$("select#selezione_corso option").attr('selected', false);
			$("select#selezione_corso option[value="+j.corso_url+"]").attr('selected', true);
			$("select#selezione_evento").attr('disabled', false).removeClass('disabled');
			$("select#selezione_evento option").remove();
			for (var i = 0; i < j.eventi.length; i++){
				var evento = j.eventi[i];
				var selected = evento.id == j.evento ? 'selected="selected"' : "";
				$("select#selezione_evento").append('<option value="'+evento.url+'" '+selected+'>'+evento.data_formattata+' - '+evento.luogo+'</option>');
			}
			$("textarea#descrizione").val(j.descrizione);
			$("#invia_sconto_wrapper").hide();
			$("#modifica_sconto_wrapper").show();
			
			$('#add_sconto').slideDown();
		});
	}
	
	function modificaDealer(val){
		$.getJSON("http://www.rolandacademy.it/index2.php?page=gestione&task=pre_edit_dealer", { dealer: val }, function(j){
			$('form').clearForm();
			$("input#id").val(j.id);
			$("input#nome2").val(j.nome);
			$("input#azienda2").val(j.azienda);
			$("input#cognome2").val(j.cognome);
			$("input#email2").val(j.email);
			$("input#aggiornamento_province2_hidden").val(j.province);
			$("span#lista_province2").html(j.lista_province);
			$('div#aggiungi_dealer').parent().parent().hide();
			$('div#modifica_dealer').show();
		});
	}
	
	function eliminaDealer(val){
		$.get("http://www.rolandacademy.it/index2.php?page=gestione&task=elimina_dealer", { dealer: val }, function(data){
			if (data == 'OK'){
				$('#lista_dealers_wrapper div#dealer_'+val).fadeOut(1000);
			}
		});
	}
	
	
	function aggiungiPartecipante(partecipanti, max){
		if (partecipanti >= max){
			alert('Non puoi aggiungere altri partecipanti, hai raggiunto il limite');
		} else {
			$.get("http://www.rolandacademy.it/index2.php?page=gestione&task=pre_add_partecipante", { partecipanti: partecipanti }, function(data){
				$('#altri_partecipanti').append(data);
			});
		}
	}
	
	
	

/************************************************************/
/****                   Funzioni Corsi                  ****/
/************************************************************/

	function updateListaCorsi(){
		$.get("http://www.rolandacademy.it/index2.php?page=gestione&task=get_lista_corsi", "", function(data){
			$("#corsi_wrapper").html(data);
		});
	}

/************************************************************/
/****                   Funzioni Luoghi                  ****/
/************************************************************/

	function updateLuoghi(){
		$.getJSON("http://www.rolandacademy.it/index2.php?page=gestione&task=get_luoghi", "", function(j){
			var options = '<option value="">Seleziona il luogo in cui si terr&agrave; il corso</option>';
			var current = '';
			for (var i = 0; i < j.length; i++) {
				current = (i < (j.length - 1)) ? '' : ' selected="selected" ';
				options += '<option value="' + j[i].optionValue + '" ' + current + '>' + j[i].optionDisplay + '</option>';
			}
			$("select#luogo").html(options);
		});
	}

/************************************************************/
/****                   Funzioni Iscrizione              ****/
/************************************************************/

	function updateEventiDisponibili(val){
		var esiste = $('#lista_iscritti');
		var append = '';
		if (val == ''){
			var options = '<option value="">Non ci sono eventi per questo corso</option>';
			$("select#selezione_evento").html(options);
			$("select#selezione_evento").attr("disabled","disabled");
		} else {
			$('.loading').show();
			$.getJSON("index2.php?page=iscrizione&task=get_eventi&corso="+val, {}, function(j, k){
				if (j.length > 0){
					var options = '<option value="">Seleziona un evento</option>';
					for (var i = 0; i < j.length; i++) {
						append = '';
						if (esiste){
							append = ' ('+j[i].iscritti+' iscritti)';
						}
						var data = j[i].data;
						data = data.replace("Jan", "Gen").replace("May", "Mag").replace("Jun", "Giu").replace("Jul", "Lug").replace("Aug", "Ago").replace("Sep", "Set").replace("Oct", "Ott").replace("Dec", "Dic");
						options += '<option value="' + j[i].optionValue + '">' + data + ' - ' + j[i].luogo + append + '</option>';
					}
				} else {
					var options = '<option value="">Non ci sono eventi per questo corso</option>';
				}
				$("select#selezione_evento").html(options);
				$("select#selezione_evento").removeAttr("disabled");
				$('.loading').hide();
			});
		}
	}
	
	function updateEventiTotali(val){
		var esiste = $('#lista_iscritti');
		var append = '';
		if (val == ''){
			var options = '<option value="">Non ci sono eventi per questo corso</option>';
			$("select#selezione_evento").html(options);
			$("select#selezione_evento").attr("disabled","disabled");
		} else {
			$('.loading').show();
			$.getJSON("index2.php?page=iscrizione&task=get_eventi_totali&corso="+val, {}, function(j, k){
				if (j.length > 0){
					var options = '<option value="">Seleziona un evento</option>';
					var giorni = "";
					for (var i = 0; i < j.length; i++) {
						append = '';
						if (esiste){
							append = ' ('+j[i].iscritti+' iscritti)';
						}
						var data = j[i].data;
						if (giorni == "" && j[i].differenza_giorni <= 0) {
							options += '<option value="">-----------</option>';
						}
						var giorni = j[i].differenza_giorni <= 0 ? "[terminato] " : "";
						data = data.replace("Jan", "Gen").replace("May", "Mag").replace("Jun", "Giu").replace("Jul", "Lug").replace("Aug", "Ago").replace("Sep", "Set").replace("Oct", "Ott").replace("Dec", "Dic");
						options += '<option value="' + j[i].optionValue + '">' + giorni + data + ' - ' + j[i].luogo + append + '</option>';
					}
				} else {
					var options = '<option value="">Non ci sono eventi per questo corso</option>';
				}
				$("select#selezione_evento").html(options);
				$("select#selezione_evento").removeAttr("disabled");
				$('.loading').hide();
			});
		}
	}


/************************************************************/
/****                   Funzioni GMap                    ****/
/************************************************************/
	var map;
	var geocoder;
	var address;

	function initialize() {
		/*
		map = new GMap2(document.getElementById("map_canvas"));
		map.setCenter(new GLatLng(42.904,13.892), 13);
		map.setUIToDefault();
		GEvent.addListener(map, "click", getAddress);
		geocoder = new GClientGeocoder();
		*/
		
		var myLatlng = new google.maps.LatLng(42.904,13.892);
		var myOptions = {
		  zoom: 13,
		  center: myLatlng,
		  mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
		
	}

	var infowindow;
	var geocoder;
	var map;
	function initialize_2() {
		/*
		map2 = new GMap2(document.getElementById("map_canvas_2"));
		map2.setCenter(new GLatLng(42.904,13.892), 13);
		map2.setUIToDefault();
		GEvent.addListener(map2, "click", getAddress);
		geocoder = new GClientGeocoder();
		*/
		
	    geocoder = new google.maps.Geocoder();
		var myLatlng = new google.maps.LatLng(42.904,13.892);
		var myOptions = {
		  zoom: 13,
		  center: myLatlng,
		  mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
		infowindow = new google.maps.InfoWindow({ content: '', position: myLatlng });
		infowindow.open(map);
		google.maps.event.addListener(map, 'click', function(event) {
			var new_lat_lng = new google.maps.LatLng(event.latLng.lat(), event.latLng.lng());
			map.setCenter(new_lat_lng);
			infowindow.setPosition(new_lat_lng);
			infowindow.setContent('<b>Lat/Long:</b> ' + event.latLng.lat() + "," + event.latLng.lng());
		});
	}
	
	
	function codeAddress(address) {
	    if (geocoder) {
	      geocoder.geocode( { 'address': address}, function(results, status) {
	        if (status == google.maps.GeocoderStatus.OK) {
	          map.setCenter(results[0].geometry.location);
			infowindow.setPosition(results[0].geometry.location);
			infowindow.setContent('<b>Lat/Long:</b> ' + results[0].geometry.location.lat() + "," + results[0].geometry.location.lng());
	        } else {
	          alert("Non trovo l'indirizzo richiesto. Motivo: " + status);
	        }
	      });
	    }
	  }

	function getAddress(overlay, latlng) {
		if (latlng != null) {
			address = latlng;
			geocoder.getLocations(latlng, showAddress);
		}
	}

	function showAddress(response) {
		map.clearOverlays();
		if ( ! response || response.Status.code != 200) {
			// alert("Status Code:" + response.Status.code);
		} else {
			place = response.Placemark[0];
			point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
			marker = new GMarker(point);
			map.addOverlay(marker);
			marker.openInfoWindowHtml('<b>Lat/Long:</b> ' + place.Point.coordinates[1] + "," + place.Point.coordinates[0]);
		}
	}
	
	
    function showAddress2(address) {
		if (geocoder) {
			geocoder.getLatLng( address, function(point) {
            	if ( ! point) {
            		// alert(address + " not found");
            	} else {
					map.setCenter(point, 13);
					var marker = new GMarker(point);
					map.addOverlay(marker);
					marker.openInfoWindowHtml(address+'<br/><br/><b>Lat/Long:</b> ' + point.lat() + "," + point.lng());
				}
			});
		}
	}

/***************************************************************
             Funzioni Google Calendar
****************************************************************/
	
	google.load("gdata", "1");
	
	// google.setOnLoadCallback(getMyFeed);
	
	var myService;
	var scope = "http://www.google.com/calendar/feeds";

	function setupMyService() {
	  myService = new google.gdata.calendar.CalendarService('test');
	}

	function getMyFeed() {
	  setupMyService();

	  myService.getEventsFeed(feedUrl, handleMyFeed, handleError);
	}
	
	function handleMyFeed(myResultsFeedRoot) {
	  alert("This feed's title is: " + myResultsFeedRoot.feed.getTitle().getText());
	}

	function handleError(e) {
	  alert("There was an error!");
	  alert(e.cause ? e.cause.statusText : e.message);
	}
	
	function doLogin(){
		if ( ! google.accounts.user.checkLogin(scope)){
			var token = google.accounts.user.login(scope);
		}
	}
	
	function doLogout() {
	  if (google.accounts.user.checkLogin(scope)) {
	    google.accounts.user.logout();
	  }
	}
	
	function handleInfo(data) {
	    var response = eval(data.currentTarget.responseText);

	    alert('Target: ' + response.Target + "\n" + 
	          'Scope: ' + response.Scope + "\n" +
	          'Secure: ' + response.Secure);
	}

	function doGetInfo() {
	  if (google.accounts.user.checkLogin(scope)) {
	    google.accounts.user.getInfo(handleInfo);
	  }
	}
	
	function creaEvento(titolo, descrizione, from, to, luogo, coordinate){
		
		doLogin();
		
		// Create the calendar service object
		var calendarService = new google.gdata.calendar.CalendarService('RolandAcademy');

		// Create an instance of CalendarEventEntry representing the new event
		var entry = new google.gdata.calendar.CalendarEventEntry();
			entry.setTitle(google.gdata.Text.create(titolo));
			entry.setContent(google.gdata.Text.create(descrizione));

		// Create a When object that will be attached to the event
		var when = new google.gdata.When();
			var startTime = google.gdata.DateTime.fromIso8601(from);
			var endTime = google.gdata.DateTime.fromIso8601(to);
			when.setStartTime(startTime);
			when.setEndTime(endTime);
			entry.addTime(when);
		
		// Set the calendar location
		var where = new google.gdata.Where();
			where.setLabel(coordinate);
			where.setValueString(coordinate);
			entry.addLocation(where);

		// The callback method that will be called after a successful insertion from insertEntry()
		var callback = function(result) {
		  alert('Aggiunto l\'evento "'+titolo+'" su Google Calendar!');
		}

		// Error handler will be invoked if there is an error from insertEntry()
		var handleError = function(error) {
		  alert(error);
		}

		// Submit the request using the calendar service object
		calendarService.insertEntry(feedUri, entry, callback, handleError, google.gdata.calendar.CalendarEventEntry);
	}


/************************************************************/
/****                   Funzioni Twitter                 ****/
/************************************************************/

	function calcolaTwitterMiniUrl(){
		var obj = $('#right a.twitter');
		if (obj.length > 0){
			url = 'http://api.bit.ly/v3/shorten?login=rolandacademy&format=json&apiKey=R_06216acbcf3d36e758877cc6b36d1029&longUrl='+location.href;
			url = 'proxy.php?url='+escape(url);
			$.getJSON(url, '', function(j, textStatus){
				if (j.status_txt == "OK"){
					obj.attr('href', obj.attr('href')+escape(j.data.url));
				}
			});
		}
	}


/************************************************************/
/****                   Funzioni Comuni                  ****/
/************************************************************/

	
	function valida_mail(email){
		var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		return reg.test(email);
	}
	
	function valida_partita_iva (val){
		if (val.length < 1) return true;
		if (val.length != 11) return false;
		validi = "0123456789";
		for ( i = 0; i < 11; i++ ){
			if( validi.indexOf( val.charAt(i) ) == -1 ) return false;
		}
		s = 0;
		for( i = 0; i <= 9; i += 2 )
			s += val.charCodeAt(i) - '0'.charCodeAt(0);
		for( i = 1; i <= 9; i += 2 ){
			c = 2*( val.charCodeAt(i) - '0'.charCodeAt(0) );
			if( c > 9 )  c = c - 9;
			s += c;
		}
		if ( ( 10 - s%10 )%10 != val.charCodeAt(10) - '0'.charCodeAt(0) ) 
			return false;
		return true;
	}
	
	function valida_sn(sn){
		
		// test AA12345
		var reg = /^([A-Za-z]{2})+([0-9]{5})$/;
		rtest = reg.test(sn);
		if( rtest ) return true;
		
		// test AAA1234
		var reg = /^([A-Za-z]{3})+([0-9]{4})$/;
		rtest = reg.test(sn); 
		if( rtest ) return true;
		
		return false;
	}
	
	function valida_cf(email){
		var reg = /^[A-Za-z]{6}\d{2}[A-Za-z]\d{2}[A-Za-z]\d{3}[A-Za-z]$/;
		return reg.test(email);
	}
	

	function in_array(element, theArray){
		var res = false;
		for (var e = 0; e < theArray.length; e++){
			if (theArray[e] == element){
				res = true;
				break;
			}
		}
		return res;
	}
	
	function SHA1 (msg) {

		function rotate_left(n,s) {
			var t4 = ( n<<s ) | (n>>>(32-s));
			return t4;
		};

		function lsb_hex(val) {
			var str="";
			var i;
			var vh;
			var vl;

			for( i=0; i<=6; i+=2 ) {
				vh = (val>>>(i*4+4))&0x0f;
				vl = (val>>>(i*4))&0x0f;
				str += vh.toString(16) + vl.toString(16);
			}
			return str;
		};

		function cvt_hex(val) {
			var str="";
			var i;
			var v;

			for( i=7; i>=0; i-- ) {
				v = (val>>>(i*4))&0x0f;
				str += v.toString(16);
			}
			return str;
		};


		function Utf8Encode(string) {
			string = string.replace(/\r\n/g,"\n");
			var utftext = "";

			for (var n = 0; n < string.length; n++) {

				var c = string.charCodeAt(n);

				if (c < 128) {
					utftext += String.fromCharCode(c);
				}
				else if((c > 127) && (c < 2048)) {
					utftext += String.fromCharCode((c >> 6) | 192);
					utftext += String.fromCharCode((c & 63) | 128);
				}
				else {
					utftext += String.fromCharCode((c >> 12) | 224);
					utftext += String.fromCharCode(((c >> 6) & 63) | 128);
					utftext += String.fromCharCode((c & 63) | 128);
				}

			}

			return utftext;
		};

		var blockstart;
		var i, j;
		var W = new Array(80);
		var H0 = 0x67452301;
		var H1 = 0xEFCDAB89;
		var H2 = 0x98BADCFE;
		var H3 = 0x10325476;
		var H4 = 0xC3D2E1F0;
		var A, B, C, D, E;
		var temp;

		msg = Utf8Encode(msg);

		var msg_len = msg.length;

		var word_array = new Array();
		for( i=0; i<msg_len-3; i+=4 ) {
			j = msg.charCodeAt(i)<<24 | msg.charCodeAt(i+1)<<16 |
			msg.charCodeAt(i+2)<<8 | msg.charCodeAt(i+3);
			word_array.push( j );
		}

		switch( msg_len % 4 ) {
			case 0:
				i = 0x080000000;
			break;
			case 1:
				i = msg.charCodeAt(msg_len-1)<<24 | 0x0800000;
			break;

			case 2:
				i = msg.charCodeAt(msg_len-2)<<24 | msg.charCodeAt(msg_len-1)<<16 | 0x08000;
			break;

			case 3:
				i = msg.charCodeAt(msg_len-3)<<24 | msg.charCodeAt(msg_len-2)<<16 | msg.charCodeAt(msg_len-1)<<8	| 0x80;
			break;
		}

		word_array.push( i );

		while( (word_array.length % 16) != 14 ) word_array.push( 0 );

		word_array.push( msg_len>>>29 );
		word_array.push( (msg_len<<3)&0x0ffffffff );


		for ( blockstart=0; blockstart<word_array.length; blockstart+=16 ) {

			for( i=0; i<16; i++ ) W[i] = word_array[blockstart+i];
			for( i=16; i<=79; i++ ) W[i] = rotate_left(W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1);

			A = H0;
			B = H1;
			C = H2;
			D = H3;
			E = H4;

			for( i= 0; i<=19; i++ ) {
				temp = (rotate_left(A,5) + ((B&C) | (~B&D)) + E + W[i] + 0x5A827999) & 0x0ffffffff;
				E = D;
				D = C;
				C = rotate_left(B,30);
				B = A;
				A = temp;
			}

			for( i=20; i<=39; i++ ) {
				temp = (rotate_left(A,5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff;
				E = D;
				D = C;
				C = rotate_left(B,30);
				B = A;
				A = temp;
			}

			for( i=40; i<=59; i++ ) {
				temp = (rotate_left(A,5) + ((B&C) | (B&D) | (C&D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff;
				E = D;
				D = C;
				C = rotate_left(B,30);
				B = A;
				A = temp;
			}

			for( i=60; i<=79; i++ ) {
				temp = (rotate_left(A,5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff;
				E = D;
				D = C;
				C = rotate_left(B,30);
				B = A;
				A = temp;
			}

			H0 = (H0 + A) & 0x0ffffffff;
			H1 = (H1 + B) & 0x0ffffffff;
			H2 = (H2 + C) & 0x0ffffffff;
			H3 = (H3 + D) & 0x0ffffffff;
			H4 = (H4 + E) & 0x0ffffffff;

		}

		var temp = cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4);

		return temp.toLowerCase();

	}
	
	function controllaUrlCorso(){
		var url = $('form#form_crea #url');
		if (url.val() == ''){
			alert('specifica un indirizzo da associare al corso');
		} else {
			manageUrlUniqueness(url.val(), 'corso', '');
		}
	}
		
	function controllaUrlEvento(){
		var url1 = $('form#form_crea #url');
		var url = $('form#form_crea #url_evento');
		if (url.val() == ''){
			alert('specifica un indirizzo da associare all\'evento');
		}
		manageUrlUniqueness(url.val(), 'evento', url1.val());
	}
