var ajax_main_script = "ajax.php";

Array.prototype.in_array = function(p_val) {
	for(var i = 0, l = this.length; i < l; i++) {
		if(this[i] == p_val) {
			return true;
		}
	}
	return false;
}


/*
	Effettua la chiamata AJAX utilizzando JQuery e JSON.
	Autore:	Cristian Zuddas
	Data:	2007-11-19

	Params:
		query_str			string			Parametri da passare allo script che gestisce le risposte AJAX
		is_admin			bool			TRUE significa che questa funzione e' stata richiamata dal CMS
		func_success		function		Funzione da richiamare in caso di successo; deve avere un parametro nel quale viene inserito il risultato JSON della richiesta. Esempio: function(oResponse) {...}
		func_error			function		Opzionale, funzione da richiamare in caso di errore. Se viene passato un valore il cui tipo non e' "function", ne viene presa una di default
		func_complete		function		Opzionale, funzione da richiamare una volta completata la richiesta, sia in caso di successo sia in caso di errore. Se viene passato un valore il cui tipo non e' "function", ne viene presa una di default

	Note:
		Deve essere definita una variabile "ajax_main_script" (string) che contiene il nome/URL
		dello script gestore delle risposte.
*/
function doAjax(query_str, is_admin, func_success, func_error, func_complete) {
	if (typeof func_success=='function') {
		var url = ajax_main_script;
		if (is_admin) {
			url = '../'+url;
		}

		if (typeof func_error!='function') {
			func_error = function() {
										alert(lng00003);
									};
		}

		if (typeof query_str!='string')
			query_str = '';

		$.ajax({
			type: "POST",
			url: url,
			data: query_str,
			dataType: "json",
			success: func_success,
			error: func_error,
			complete: func_complete
		});
	}
	else {alert('doAjax error: success function is not defined.');}
}

function getE(id) {
	return document.getElementById(id);
}

mw=null;
function openWindowDimBars(FileName,w,h,barre) {
	myWindow=window.open(FileName,'','toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars='+barre+',resizable=0,top=10,left=10,width='+w+',height='+h);
	return myWindow;
}

function confirmLink(theLink, confirmMsg) {
	if (typeof(window.opera) != 'undefined') {
		return true;
	}

	var is_confirmed = confirm(confirmMsg);

	return is_confirmed;
}

var testresults;
function checkemail(email_addr) {
	var filter=/^[\'+\\./0-9A-Z^_\`a-z{|}~\-]+@[a-zA-Z0-9_\-]+(\.[a-zA-Z0-9_\-]+){1,3}$/i;
	if (filter.test(email_addr)) {
		testresults = true;
	}
	else {
		testresults = false;
	}

	return(testresults);
}

function isFunction(a) {
	return typeof a == 'function';
}
function isObject(a) {
	return (a && typeof a == 'object') || isFunction(a);
}

/*
	Inserisce dinamicamente un filmato Flash.
	Per scavalcare il blocco di IE 6, che altrimenti ne richiede l'attivazione manuale.
*/
function print_flash_movie(nomefile, width, height, version) {
	var str;

	str = ('<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=' + version + '" WIDTH="' + width + '" HEIGHT="' + height + '">');
	str = str + ('<PARAM NAME=movie VALUE="' + nomefile + '">');
	str = str + ('<PARAM NAME=quality VALUE=high>');
	str = str + ('<PARAM NAME=wmode VALUE=opaque>');
	str = str + ('<embed src="' + nomefile + '" quality=high wmode=opaque');
	str = str + ('swLiveConnect="FALSE" WIDTH="' + width + '" HEIGHT="' + height + '" border="0" TYPE="application/x-shockwave-flash"');
	str = str + ('PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer"></embed></OBJECT>');

	document.write(str);
}

// modulo di registrazione al rally - onSubmit
function registration_onsubmit() {
	if (
			getE('cognome').value=='' || getE('nome').value=='' || getE('nazionalita').value=='' || getE('indirizzo').value=='' || getE('cap').value=='' || getE('citta').value=='' || getE('nazione').value=='' ||
			getE('tel_cellulare').value=='' || getE('email').value=='' || getE('edizione').value=='' || getE('societa_appartenenza').value=='' || getE('ente_affilizione').value=='' ||
			getE('numero_tessera').value=='' || getE('categoria').value=='' || getE('veicolo_seguito').value=='' ||
			parseInt(getE('data_nascita_dd').value)<1 || parseInt(getE('data_nascita_mm').value)<1 || parseInt(getE('data_nascita_yy').value)<1 || parseInt(getE('provincia').value)<1 ||
			parseInt(getE('pagamento').value)<1 || (!getE('sesso_1').checked && !getE('sesso_2').checked) || !getE('privacy').checked
	) {
		alert(lng00001);
		return false;
	}

	if (!checkemail(getE('email').value)) {
		alert(lng00002);
		return false;
	}

	return true;
}

/*
	scheda dell'inserzione - paginazione della photogallery.
	il parametro "verso" e' un booleano che indica se si deve scorrere di una foto in avanti (TRUE)
	oppure indietro (FALSE) rispetto a quella attuale, che e' registrata nel DIV con id "photogallery_page".
*/
function insertion_photogallery(verso) {
	if (isObject(getE('gallery_immagine'))) {
		var p = parseInt(getE('photogallery_page').innerHTML)+1;		// se "verso = true"
		if (!verso) {
			p = parseInt(getE('photogallery_page').innerHTML)-1;
		}

		doAjax(
			'a_ajax=1&page_id='+encodeURIComponent(getE('insert_code').innerHTML)+'&l='+encodeURIComponent(getE('idlingua').innerHTML)+'&p_scroll='+p,
			false,
			function(oResponse) {
				if (oResponse['act']!=undefined) {
					getE('photogallery_page').innerHTML = parseInt(oResponse['act'].p);		// aggiorna il valore della pagina attuale
					egal.skipTo(parseInt(oResponse['act'].p));

					// visualizza la foto attuale
					getE('gallery_immagine').src = oResponse['act'].zoom;
					getE('gallery_thumb2').src = oResponse['act'].thumb;
					getE('media_num').innerHTML = lng00007.replace('[rep_1]', parseInt(oResponse['act'].p)+1).replace('[rep_2]', parseInt(oResponse['act'].pics_num));

					// immagine per il download
					if (oResponse['act'].download!=null && oResponse['act'].download_size!=null) {
						getE('link_download').href = 'downloader.php?params='+oResponse['act'].download;
						getE('peso_txt').innerHTML = oResponse['act'].download_size;
						getE('peso_div').className = 'peso';
						getE('bt_download').className = 'bt_download';
					}
					else {
						getE('peso_div').className = 'hidden';
						getE('bt_download').className = 'hidden';
					}

					// didascalia
					if (oResponse['act'].txt!=null && oResponse['act'].txt.length>0) {
						getE('gallery_dida_main').innerHTML = oResponse['act'].txt;
					}
					else {
						getE('gallery_dida_main').innerHTML = '';
					}


					// thumb della foto precedente
					if (oResponse['prev']!=undefined) {
						getE('box_thumb1').innerHTML = '<a id="gallery_thumb_link1" href="#" onclick="return insertion_photogallery(false);"><img id="gallery_thumb1" src="'+oResponse['prev']+'" alt="'+lng00004+'" title="'+lng00004+'" /></a>';
						getE('box_thumb1').className = 'thumb_galleria_1';
						getE('div_gallery_prev_main').innerHTML = '<a id="tgallery_prev" class="freccia_left_show" href="#" onclick="return insertion_photogallery(false);" title="'+lng00006+'"><span>'+lng00006+'</span></a>';
						getE('div_gallery_prev_main').className = 'freccia_left_show';
					}
					else {
						getE('box_thumb1').className = 'hidden';
						getE('div_gallery_prev_main').className = 'hidden';
					}


					// thumb della foto successiva
					if (oResponse['next']!=undefined) {
						getE('box_thumb3').innerHTML = '<a id="gallery_thumb_link3" href="#" onclick="return insertion_photogallery(true);"><img id="gallery_thumb3" src="'+oResponse['next']+'" alt="'+lng00004+'" title="'+lng00004+'" /></a>';
						getE('box_thumb3').className = 'thumb_galleria_3';
						getE('div_gallery_next_main').innerHTML = '<a id="tgallery_next" class="freccia_right_show" href="#" onclick="return insertion_photogallery(true);" title="'+lng00005+'"><span>'+lng00005+'</span></a>';
						getE('div_gallery_next_main').className = 'freccia_right_show';
					}
					else {
						getE('box_thumb3').className = 'hidden';
						getE('div_gallery_next_main').className = 'hidden';
					}
				}
			},
			null, null
		);
	}

	return false;
}

function scorri(verso) {
	if (verso == 'r') {
		var scroll = parseInt(getE('scroll').innerHTML)+1;
	}
	else
	{
		scroll = parseInt(getE('scroll').innerHTML)-1;
	}
		doAjax(
			'a_ajax=2&s='+encodeURIComponent(getE('id_tappa').innerHTML)+'&l='+encodeURIComponent(getE('idlingua').innerHTML)+'&scroll='+scroll,
			false,
			function(oResponse) {
				if (oResponse['centr']!=undefined) {
					//getE('photogallery_page').innerHTML = parseInt(oResponse['act'].p);
					//egal.skipTo(parseInt(oResponse['act'].p));
					getE('scroll').innerHTML = parseInt(oResponse['centr'].p);
					egal.skipTo(parseInt(oResponse['centr'].p));

					getE('gallery_immagine').src = oResponse['centr'].big;
					getE('gallery_thumb2').src = oResponse['centr'].thumb;
					getE('media_num').innerHTML = lng00007.replace('[rep_1]', parseInt(oResponse['centr'].p)+1).replace('[rep_2]', parseInt(oResponse['centr'].num_foto));

					if (oResponse['centr'].parametri_down!=null && oResponse['centr'].peso!=null) {
						getE('link_download').href = 'downloader.php?params='+oResponse['centr'].parametri_down;
						getE('peso_txt').innerHTML = oResponse['centr'].peso;
						getE('peso_div').className = 'peso';
						getE('bt_download').className = 'bt_download';
					}
					else {
						getE('peso_div').className = 'hidden';
						getE('bt_download').className = 'hidden';
					}

					if (oResponse['centr'].didascalia!=null && oResponse['centr'].didascalia.length>0) {
						getE('gallery_dida_main').innerHTML = oResponse['centr'].didascalia;
					}
					else {
						getE('gallery_dida_main').innerHTML = '';
					}

					if (oResponse['prec']!=undefined) {
						getE('box_thumb1').innerHTML = '<a id="gallery_thumb_link1" href="#" onclick="return scorri(\'l\');"><img id="gallery_thumb1" src="'+oResponse['prec']+'" alt="'+lng00004+'" title="'+lng00004+'" /></a>';
						getE('box_thumb1').className = 'thumb_galleria_1';
						getE('div_gallery_prev_main').innerHTML = '<a id="tgallery_prev" class="freccia_left_show" href="#" onclick="return scorri(\'l\');" title="'+lng00006+'"><span>'+lng00006+'</span></a>';
						getE('div_gallery_prev_main').className = 'freccia_left_show';
					}
					else {
						getE('box_thumb1').className = 'hidden';
						getE('div_gallery_prev_main').className = 'hidden';
					}

					if (oResponse['succ']!=undefined) {
						getE('box_thumb3').innerHTML = '<a id="gallery_thumb_link3" href="#" onclick="return scorri(\'r\');"><img id="gallery_thumb3" src="'+oResponse['succ']+'" alt="'+lng00004+'" title="'+lng00004+'" /></a>';
						getE('box_thumb3').className = 'thumb_galleria_3';
						getE('div_gallery_next_main').innerHTML = '<a id="tgallery_next" class="freccia_right_show" href="#" onclick="return scorri(\'r\');" title="'+lng00005+'"><span>'+lng00005+'</span></a>';
						getE('div_gallery_next_main').className = 'freccia_right_show';
					}
					else {
						getE('box_thumb3').className = 'hidden';
						getE('div_gallery_next_main').className = 'hidden';
					}
				}
			},
			null, null
		);
		return false;
}

function checkDate(year, month, day)
{
	// valori singoli non validi?
	if (isNaN(year) || isNaN(month) || isNaN(day)) {return false;}
	if (day < 1 || day > 31 || month < 1 || month > 12 || year < 1000 || year > 9999) {return false;}

	// incoerenza mesi di 30 giorni
	if (month == 4 || month == 6 || month == 9 || month == 11) {
		return (day <= 30);
	}

	// incoerenza febbraio
	if (month == 2) {
		if (year % 400 == 0) {
			// anno bisestile perche' divisibile per 400
			return (day <= 29);

		} else if (year % 100 == 0) {
			// anno non bisestile perche' divisibile per 100
			return (day <= 28);

		} else if (year % 4 == 0) {
			// anno bisestile perche' divisibile per 4
			return (day <= 29);

		} else {
			// anno non bisestile
			return (day <= 28);
		}
	}

	return true;
}

function checkcap(string) {
	var testresults;
	var filter=/^[0-9]{5}$/i;
	if (filter.test(string)) {
		testresults = true;
	} else {
		testresults = false;
	}
	return testresults;
}

function checkCV(a) {
	var filename = getE('fi_curriculum').value;

		var fileTypes = new Array('.pdf', '.doc');
		var ext = filename.substr(filename.lastIndexOf('.'), filename.length);
		if (fileTypes.in_array(ext))
		{
			return true;
		}
		else
		{
			if(a)
			{
				alert(lng00008);
			}
			return false;
		}

}

function checkPic(a) {
	var filename = getE('fi_foto').value;

		var fileTypes = new Array('.jpg', '.jpeg', '.gif');
		var ext = filename.substr(filename.lastIndexOf('.'), filename.length);
		if (fileTypes.in_array(ext))
		{
			return true;
		}
		else
		{
			if(a)
			{
				alert(lng00009);
			}
			return false;
		}

}

function iscrizione_v()
{
	if (getE('ct_nome').value=="" || getE('ct_cognome').value=="" || getE('ct_indirizzo').value=="" || getE('ct_nciv').value=="" ||
	getE('ct_citta').value=="" || getE('ct_cap').value=="" || getE('ct_stato').value=="" || getE('ct_nazionalita').value=="" ||
	getE('ct_sang').value==0 || getE('ct_luogonascita').value=="" || checkDate(getE('ct_nascita_y').value, getE('ct_nascita_m').value, getE('ct_nascita_d').value) == false ||
	getE('ct_sesso').value==0 || getE('ct_tel_mob').value=="" || checkemail(getE('ct_email').value) == false || getE('ct_profess').value=="" ||
	getE('ct_num_patente').value=="" || getE('ct_luogo_patente').value=="" || checkDate(getE('ct_patente_y').value, getE('ct_patente_m').value, getE('ct_patente_d').value) == false ||
	getE('ct_num_licenza').value=="" || getE('ct_fmn').value=="" || getE('ct_motoclub').value=="" || getE('ct_tessera_fmn').value=="" ||
	getE('ve_ruote_1').value=="" || getE('ve_ruote_2').value=="" || getE('ve_marca').value=="" || getE('ve_tipo').value=="" ||
	getE('ve_cilindrata').value=="" || getE('ve_tempi_1').value=="" || getE('ve_tempi_2').value=="" || getE('ve_targa').value=="" ||
	getE('ve_proprietario').value=="" || getE('ve_telaio').value=="" || getE('ve_motore').value=="" || getE('ve_immatr').value=="" ||
	getE('ve_assic').value=="" || getE('ve_polizza_num').value=="" || checkDate(getE('ve_polizza_y').value, getE('ve_polizza_m').value, getE('ve_polizza_d').value) == false ||
	getE('ve_classe_eu').value==0 || getE('ve_classe_it').value==0 || getE('ve_categoria').value=="" || getE('as_nome').value=="" ||
	getE('as_tel').value=="" || getE('fa_tel').value=="" || getE('fa_nome').value=="" || checkCV(false) == false || checkPic(false) == false ||
	getE('al_tshirt').value==0 || getE('al_pagamento').value==0 || getE('al_ricevuta').value=="" || getE('ct_consenso').value=="" ||
	getE('ct_regolamento').value=="" )

	{
		alert(lng00001);
		return false;
	}

	return true;
}