document.addEvent('domready',function() 
{
	change_header(1);
	
	
	$$("#menu a").addEvents({
		mouseenter:function(){
			this.setStyle('background-color', '#2023BB');
		},
		mouseleave: function(){
			this.morph({duration:'500','background-color': '#4e4f53'});	
		}
	});
	
	userAg = navigator.userAgent;
	if ($('shoutbox') && userAg.substring("MSIE") == -1)
		aggiorna_shoutbox();
	
		new DatePicker('input#data_ev',{ pickerClass: 'datepicker_jqui',positionOffset:{x:0,y:-190}});
	
	if($('mappa') != null && $('mappa') != undefined)
		initialize();
		
	if($('div#obx_conte') != null && $('div#obx_conte') != undefined)
		form_attach($('div#obx_conte'));

});

 



/** UTILITA' **/

function trim(str){
    return str.replace(/^\s+|\s+$/g,"");
}

function reset_form(nome_form)
{
	$(nome_form).reset();
	var hidInp = $(nome_form).getElementsByTagName('input');
	for (var i = 1; i < hidInp.length; i++)
	{
		if (hidInp[i].type == 'hidden')
		{	
			hidInp[i--].destroy();
		}
		
	}
}

function popup(msg){
	var overbox = new Element('div#overbox');
	var ofusc = new Element('div#obx_ofusc',{
		events: {click:function(){$('overbox').destroy()}}
		});
	var bordo = new Element('div#obx_bordo');
	var conte = new Element('div#obx_conte');
	conte.setStyles({
		'text-align' : 'center',
		});
	conte.set('html', msg);
	
		overbox.grab(bordo);
	bordo.grab(conte);
	overbox.grab(ofusc);
	$(document.body).grab(overbox);
}

/** SHOUTBOX **/

function canc_mess_shout(id_mess, user)
{	
		var req = new Request({
			url:  'shoutbox_functions.php',
			method: 'get',
			data: 'agg=del&us=' + user + '&mess=' + id_mess,
			async: false,
			onSuccess: function(risposta)
			{
				$('sb_container_messaggi').empty().set('html', risposta);
				reset_form('form_shoutbox');	
			}
		}).send();
}

function check_shout()
{
	var ok = true;
	var msg = document.getElementById('messaggio');
	var titolo = document.getElementById('msg_titolo');
	var destinazione = document.getElementById('msg_target');
	msg_err = 'Sono stati riscontrati i seguenti errori: ';
	
	if (msg == '' || msg == undefined)
	{
		msg_err += '- inserire un messaggio\n';
		ok = false;
	}
	
	if (titolo.length >= 250 || titolo.length >= 250)
	{
		ok = false;
		msg_err += '- il campo titolo non può contenere più di 250 caratteri\n';
	}

	if (ok == true)
	{
		dati = '';
		if (document.getElementById('agg') != null)
		{
			var func = document.getElementById('agg');
			dati = (func.value == 'mod') ? '?agg=mod' : '';
			dati += (func.value == 'mod') ? ('&mess=' + document.getElementById('mess').value) : '';
		}
		//se non ci sono errori inserisco il messaggio e faccio un update tramite request
			var req = new Request.HTML({
				url:  'shoutbox_functions.php' + dati,
				async: false,
				onComplete: function(resTxt)
				{
					$('sb_container_messaggi').empty().adopt(resTxt);
					reset_form('form_shoutbox');
				}
			}).post($('form_shoutbox'));
	
	}
	else return msg;
}

function mod_mess_shout(id_mess)
{
	var mezz = new Element('input', {
		'type' : 'hidden',
		'id' : 'mess',
		'name' : 'mess',
		'value' : id_mess});
		
	var mod = new Element('input', {
		'type' : 'hidden',
		'id' : 'agg',
		'name':'agg',
		'value' : 'mod'});
	reset_form('form_shoutbox');
	$('form_shoutbox').grab(mezz);
	$('form_shoutbox').grab(mod);
	$('msg_titolo').empty().value = get_spec_campo('TITOLO', id_mess);
	$('messaggio').empty().value = get_spec_campo('TESTO', id_mess);
	if (get_spec_campo('COMUNICATI_GENERALI', id_mess) == '1')
		$('msg_target').value = 'STAFF';
	else
		$('msg_target').value = get_spec_campo('DESTINAZIONE', id_mess);
	
}
function aggiorna_shoutbox()
{

		//ogni 30 secondi aggiorna la shoutbox
		var req = new Request({
				url:  'shoutbox_functions.php',
				method: 'get',
				data: 'agg=si',
				async: false,
				onSuccess: function(rsTxt)
				{
					$('sb_container_messaggi').empty().set('html', rsTxt);
				}
			}).send();
			
	userAg = navigator.userAgent;
	if (userAg.substring("MSIE") == -1)
	{	
		var t=setTimeout("aggiorna_shoutbox()",30000); // 30 secondi
	}
}



function get_spec_campo(campo, idcampo)
{
	var req = new Request({
		url:  'request.php',
		method: 'get',
		data: 'type=get_spec&campo=' + campo + '&id=' + idcampo,
		async: false,
		onSuccess: function(riz)
		{
			resp = trim(riz);
		}
	}).send();
	return resp;
}
/** MAPPA CONTATTI **/

function initialize() {
	var latlng = new google.maps.LatLng(45.541119,11.513758);
	var ll = new google.maps.LatLng(45.542217,11.513929);
	var myOptions = {
	zoom: 15,
	center: ll,
	mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	var map = new google.maps.Map(document.getElementById("mappa"),
	myOptions);
	var marker = new google.maps.Marker({
	position: latlng,
	map: map,
	title: "PalladioVicenza"
	});
	var infowindow = new google.maps.InfoWindow({
	content: '<span style="font-weight: bold;">Palladio B.S. Vicenza</span><br />via V. Bellini, 59 <br />36100 Vicenza(VI)'
	});
	infowindow.open(map,marker);
	google.maps.event.addListener(marker, 'click', function() {
	infowindow.open(map,marker);
	});
	
}

/** FUNZIONI LOGIN-LOGOUT-CAMBIO PASSWORD **/

function mostra_login()
{
	if ($('login') != null)
		$('login').setStyles({'display':'block'});
}
function overbox(txt)
{
	var overbox = new Element('div#overbox');
	var ofusc = new Element('div#obx_ofusc',{
		events: {click:function(){$('overbox').destroy()}}
		});
	var bordo = new Element('div#obx_bordo');
	var conte = new Element('div#obx_conte');
	var rqst = new Request.HTML({
		url: 'request.php',
		onRequest:function(){
			conte.empty().set('html',"Caricamento...");
		},
		onComplete:function(rsp){
			conte.empty().adopt(rsp);
			form_attach(conte)
		}}).get({type:txt});
	overbox.grab(bordo);
	bordo.grab(conte);
	overbox.grab(ofusc);
	$(document.body).grab(overbox);
}

function form_attach(conte)
{
$$("[name^=o_form]").addEvent('submit',function(evt){
	evt.stop();
	if(this.method == "get" || this.method == "GET"){
		fs = new Request.HTML({
			url: this.action,
			onRequest:function(){
				conte.empty().set('html',"Caricamento...");
			},
			onComplete:function(rsp){
				conte.empty().adopt(rsp);
				form_attach();
			}
		}).get(this);
	}else{
		fs = new Request.HTML({
			url: this.action,
			onRequest:function(){
				conte.empty().set('html',"Caricamento...");
			},
			onComplete:function(rsp){
				conte.empty().adopt(rsp);
				form_attach();
			}
		}).post(this);
	}
	
});
}


/** FUNZIONI HEADER E MENU **/

function change_header(h)
{
	if (h > 8)
		h = 1;
	l = h + 1;
	if (l > 8)
		l = 1;
	var bg = '/resources/images/header' + h + '.jpg';
	$(document.body).setStyle('background-image','url(' + bg + ')');
	//carico la prossima
	load_img = new Image();
	load_img.src = '/resources/images/header' + l + '.jpg';
	setTimeout("change_header(" + ++h + ")", 60000);	// 10 minuti = 600000   2 minuti = 120000 1 minuto = 60000
}

/** FUNZIONI MODULO TORNEI **/

function check_form_iscrizione()
{
	
	var nome = $('nome').value;
	var cognome = $('cognome').value;
	var email = $('email').value;
	var telefono = $('telefono').value;
	var soc_app = $('soc_app').value;
	var cellulare= $('cellulare').value;
	var squad_iscrizione = $('squad_iscrizione').value;
	var referente = $('referente').value;
	var referente_cellulare = $('cellulare_referente').value;
	var referente_email = $('email_referente').value;
	
	
	corretto = true; 
	var msg = 'Il modulo non è stato completato correttamente:';
	
	/* controllo esistenza campi obbligatori */
	
	if (nome == "" || nome == undefined)
	{
		corretto = false;
		msg += '\n- Il campo nome è obbligatorio';
	}
	
	if (cognome == "")
	{
		corretto = false;
		msg += '\n- Il campo cognome è obbligatorio';
	}
	
	if (telefono == "")
	{
		corretto = false;
		msg += '\n- Il campo telefono è obbligatorio';
	}
	
	if (cellulare == "")
	{
		corretto = false;
		msg += '\n- Il campo cellulare è obbligatorio';
	}
	
	if (squad_iscrizione == "")
	{
		corretto = false;
		msg += '\n- Il campo Squadra è obbligatorio';
	}
	
	if (referente == "")
	{
		corretto = false;
		msg += '\n- Il campo referente è obbligatorio';
	}
	
	if (referente_cellulare == "")
	{
		corretto = false;
		msg += '\n- Il cellulare del referente è obbligatorio';
	}
	
	if (referente_email == "")
	{
		corretto = false;
		msg += '\n- La mail del referente è obbligatoria';
	}
	
	if (email != "")
	{//controllo validità mail
		var rg = /^([\w\.\-_]+)(@[\w\.\-_]+)(\.{1}[a-z]{1,4})$/;
		if (!rg.test(email.toLowerCase()))
		{
			corretto = false;
			msg += '\n- Inserire una mail nel formato corretto';
		}
					
	}
	else
	{
		corretto = false;
		msg += '\n- Il campo mail è obbligatorio';
	}
	
	if (referente_email != "")
	{//controllo validità mail
		var rg = /^([\w\.\-_]+)(@[\w\.\-_]+)(\.{1}[a-z]{1,4})$/;
		if (!rg.test(referente_email.toLowerCase()))
		{
			corretto = false;
			msg += '\n- Inserire una mail per il referente nel formato corretto';
		}
					
	}
	else
	{
		corretto = false;
		msg += '\n- Il campo mail del referente è obbligatorio';
	}
	
	if (corretto == false)
	{
		alert(msg);
	}
	else
	{
		var req = new Request.HTML({
			url: '../../send_mail.php',
			async: false,
			onComplete: function(){
				alert('La tua iscrizione è stata inoltrata con successo.\nTi verrà inviata una mail con il link per la conferma.');
				document.location.href = 'index.php';
			}
			}).post($('form_iscr_tornei'));
	}	
	
}

function change_radio(campo)
{
	var id_iscr = campo.get('id_iscr');
	var azione = campo.value;
	
	if (azione == 'acc')
		mex = "Cliccando su questa voce verrà inviata una mail alla squadra interessata per confermare la sua iscrizione al torneo per questa categoria. Sei sicuro di voler proseguire?";
	else if (azione == 'rif')
		mex = "Cliccando su questa voce verrà inviata una mail alla squadra interessata per rifiutare la sua iscrizione al torneo per questa categoria. Sei sicuro di voler proseguire?";
	else
		mex = "";
	
	/* se clicca "da confermare" eseguo la procedura 
	 * senza chiedere conferma, altrimenti la chiedo e poi procedo	 
	 */
	
	if (mex != "")
	{
		if (confirm(mex))
		{
			var myreq = new Request({
				url:  'request.php',
				method: 'get',
				data: 'type=status_tornei&id_iscr=' + id_iscr + '&azione=' + azione,
				async: false,
				onSuccess: function()
				{
					alert('La mail è stata inviata con successo');
				}
			}).send(); 
			
		}
		else
		{
			campo.checked = false;
		}
	}
	else
	{
		var myreq = new Request({
			url:  'request.php',
			method: 'get',
			data: 'type=status_tornei&messaggio=' + id_iscr + '&azione=da_conf',
			async: false
		}).send(); 
	}
	
	
}
