/* The global modal dialog stub */
var g_Modal	= null;
var g_BigModal	= null;


function window_resize(evt) {
	adjustHeight();
}

function adjustHeight() {
	var intWindowHeight	= WindowObject.getInnerDimension().getY();
	var intScrollOffsetY	= WindowObject.getScrollOffset().getY();
	var dynModalBG		= new DynamicLayer('ModalBG');
	var intModalHeight	= dynModalBG.getHeight();

	if(intModalHeight<intWindowHeight)
		dynModalBG.setHeight(intWindowHeight + intScrollOffsetY);
}

function addExtensionsForOpera() {
	/* classes for opera */
	var ModalBG = new CBObject('ModalBG').getObject();
	
	if(typeof(window.opera)!='undefined')
		ModalBG.className='modalOpera';
}

function attachOpacityCSS() {
	/*
	 * CSS for opacity support
	 * Note that this can be directly added to the body.
	 * If you do not care about blindly adhering to standards
	 * you can directly include the rules into Master.css
	 *
	 * Do I care? Yes and no.(visit http://www.sarmal.com/Exceptions.aspx
	 * to learn how I feel about it).
	 */
	var opacityCSS	= document.createElement('link');
	opacityCSS.type	= 'text/css';
	opacityCSS.rel	= 'stylesheet';
	opacityCSS.href	= '/css/opacity.css';
	document.getElementsByTagName('head')[0].appendChild(opacityCSS);
}


/* Triggered when a successful AJAX response comes from the server.*/
function ajax_complete(strResponseText, objResponseXML) {
	g_Modal.show(strResponseText);
	
	/* Re-activate close button. */
	g_Modal.enableClose();
}

/* Triggered when server generates an error. */
function ajax_error(intStatus, strStatusText) {
	g_Modal.show('Errore [' + intStatus + '] [' + strStatusText + '].');

	/* Re-activate close button. */
	g_Modal.enableClose();
}


function InitializeModalPopups() {
	/* Sweep unnecessary empty text nodes. */
	DOMManager.sweep();
	
	/*
	 * Attach supporting css bind required
	 * classes for transparency support in Opera.
	 */
	addExtensionsForOpera();
	
	/* Attach opacity css. */
	attachOpacityCSS();
	
	/* Adjust height. */
	adjustHeight();
	
	/* Re-adjust height on window resize */
	EventHandler.addEventListener(window, 'resize', adjustHeight);
	EventHandler.addEventListener(window, 'scroll', adjustHeight); //aggiunto da me perchè su ff non ridimensionava/spostava su scroll
	
	/* Create the modal dialog */
	g_Modal = new ModalDialog('ModalBG', 'DialogWindow', 'DialogContent', 'DialogActionBtn');
	g_Modal._dragLayer.ignoreLayer('DialogIcon');		//aggiunto da me altrimenti quanto si cercava di scorrere il contenuto non si riusciva e il box veniva trascinato
	g_Modal._dragLayer.ignoreLayer('DialogContent');	//come sopra
}


function showModalPopUp(url, method, fields)
{
	/* create an AJAX request */
	var ajax = _.ajax();
	/*
	 * Note that _.ajax(); is a shorthand notation 
	 * for new XHRequest();
	 * Visit http://sardalya.pbwiki.com/Shortcuts details.
	 */

	/*
	 * You can add as many fields as you like to the post data. 
	 * Normally the server will use this data to create an
	 * output that makes sense which may be an XML, a JSON String
	 * or an HTML String.
	 */
	ajax.removeAllFields();
	
	for (var field in fields) {
		ajax.addField(field, fields[field]);
	}
	
	ajax.oncomplete	= ajax_complete;
	ajax.onerror		= ajax_error;
	
	g_Modal.show('<p class="center"><img src="/images/ajax-loader.gif" alt="Caricamento in corso..." /></p>');
	
	/*
	 * Disable close action if you want to force the user 
	 * to wait for the outcome of the AJAX request.
	 * Although it is generally not recommended 
	 * this may be necessary at certain times.
	 */
	g_Modal.disableClose();

	/* Post data to the server. */
	if (method == 'get')
		ajax.get(url)
	else
		ajax.post(url)

	/* Stop event propagation. */
//	new EventObject(evt).cancelDefaultAction();
}

function changeModalPopUp(url, method, fields) {
	var ajax = _.ajax();
	
	ajax.oncomplete = function(strResponseText, objResponseXML) {
		new LayerObject('DialogContent').changeContent(strResponseText);
	};
	
	ajax.onerror = function(intStatus, strStatusText) {
		new LayerObject('DialogContent').changeContent('Errore [' + intStatus + '] [' + strStatusText + '].');
	}
	
	
	ajax.removeAllFields();
	
	for (var field in fields) {
		ajax.addField(field, fields[field]);
	}
	
	
	if (method == 'get')
		ajax.get(url);
	else
		ajax.post(url);
}

function closeModalPopUp(){
	g_Modal.hide();
}

function PrepareFormFields4Post(f) {
	var fields = new Array();
	
	for (var i=0; i<f.length; i++) {
		try {
			if (
				f[i].type == 'text' ||
				f[i].type == 'textarea' ||
				f[i].type == 'password' ||
				f[i].type == 'select-one' ||
				f[i].type == 'hidden'
			) {
				fields[f[i].name] = escape(f[i].value);
			}
			else if (f[i].type == 'checkbox') {
				//se il checkbox è singolo non è impostato il suo value; in questo caso il suo value è di sistema 'on'.
				//passo 'on' come valore se selezionato
				if (f[i].value=='on') {
					fields[f[i].name] = f[i].checked ? 'on' : '';
				}
				//altrimenti il check fa parte di un'array di checks(che però non posso trattare qui come array); il suo
				//value è definito. passo, dopo tutta l'elaborazione, una stringa con i value dei checkbox selezionati
				//separati da virgola
				else {
					if (f[i].checked) {
						//se non è il primo aggiungo la virgola
						if (fields.contains(f[i].name)) {
							fields[f[i].name] += ',';
							fields[f[i].name] += f[i].value.toString();
						}
						else {
							fields[f[i].name] = f[i].value.toString();
						}
					}
				}		
			}
			else if(f[i].type == 'radio') {
				if(f[i].checked)
					fields[f[i].name] = escape(f[i].value);
			}
		}
		catch(e) {
		}
	}
	
	return fields;
}

/***************************************************************************************/
function disclaimer() {
	showModalPopUp('/htdocs/disclaimer.html', 'get', new Array());
}

function privacy() {
	showModalPopUp('/htdocs/privacy.html', 'get', new Array());
}

function help(doc) {
	showModalPopUp('/htdocs/help.' + doc + '.html', 'get', new Array());
}

function PayPal() {
	window.open('https://www.paypal.com/it/cgi-bin/webscr?cmd=xpt/cps/popup/OLCWhatIsPayPal-outside','olcwhatispaypal','toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=400, height=350');
}

/***************************************************************************************/
function sendEmail(from, to, subject, textbody, htmlbody) {
	var fields = new Array();
	
	fields['from']	= escape(from);
	fields['to']		= escape(to);
	fields['subject']	= escape(subject);
	fields['textbody']	= escape(textbody);
	fields['htmlbody']	= escape(htmlbody);
	
	showModalPopUp('/ajax.sendmail.asp', 'get', fields);
}

function sendEmailDoF(f) {
	var fields = PrepareFormFields4Post(f);
	
	sendEmailDo(fields['from'], fields['to'], fields['subject'], fields['textbody'], fields['htmlbody']);
}

function sendEmailDo(from, to, subject, textbody, htmlbody) {
	var ajax	= _.ajax();
	var fields	= new Array();
	
	fields['from']	= escape(from);
	fields['to']		= escape(to);
	fields['subject']	= escape(subject);
	fields['textbody']	= escape(textbody);
	fields['htmlbody']	= escape(htmlbody);
	
	ajax.oncomplete = function(strResponseText, objResponseXML) {
		if (strResponseText == '1') {
			if (stayInSync) {
				proceed = 1;
				new LayerObject('DialogContent').addContentAfter('Invio email completato con successo.<br />');
			}
			else {
				new LayerObject('DialogContent').changeContent('Invio email completato con successo.<br />');
			}
		}
		else {
			if (stayInSync) {
				proceed = 0;
				new LayerObject('DialogContent').addContentAfter('Errore durante l\'invio dell\'email.<br />');
			}
			else {
				new LayerObject('DialogContent').changeContent('Errore durante l\'invio dell\'email.<br />');
			}
		}
		
		if (!stayInSync) {
			//bottone per la chiusura della finestra modale
			new LayerObject('DialogContent').addContentAfter(
				'<form><p>' +
				'	<input class="btn" type="button" value="Chiudi" onclick="closeModalPopUp();" />' +
				'</p></form>'
			);	
		}
	}
	
	ajax.onerror = function(intStatus, strStatusText) {
		if (stayInSync) {
			proceed = 0;
			new LayerObject('DialogContent').addContentAfter('Errore [' + intStatus + '] [' + strStatusText + '].');
		}
		else {
			new LayerObject('DialogContent').changeContent('Errore [' + intStatus + '] [' + strStatusText + '].');
			
			//bottone per la chiusura della finestra modale
			new LayerObject('DialogContent').addContentAfter(
				'<form><p>' +
				'	<input class="btn" type="button" value="Chiudi" onclick="closeModalPopUp();" />' +
				'</p></form>'
			);	
		}
	}
	
	
	ajax.removeAllFields();
	
	for (var field in fields) {
		ajax.addField(field, fields[field]);
	}
	
	if (!stayInSync)
		ajax.post('/ajax.sendmail.do.asp');
	else
		ajax.postSynchronized('/ajax.sendmail.do.asp');
}

/***************************************************************************************/
function moreInfo(codiceprodotto) {
/*
	var fields = new Array();
	
	fields['idprodotto'] = codiceprodotto;
	
	showModalPopUp('/ajax.prodotti.informazioni-aggiuntive.asp', 'get', fields);
*/	
	var ajax = _.ajax();
	
	g_BigModal	= new ModalDialog('ModalBG', 'DialogWindowB', 'DialogContentB', 'DialogActionBtnB')
	g_BigModal.show('<img src="/images/ajax-loader.gif" alt="Caricamento in corso..." />');
	g_BigModal.moveTo(g_BigModal.getLeft(), 10);
	g_BigModal._dragLayer.ignoreLayer('DialogContentB');
	g_BigModal.disableClose();
	
	adjustHeight();
	
	
	ajax.oncomplete = function(strResponseText, objResponseXML) {
		new LayerObject('DialogContentB').changeContent(strResponseText);
		g_BigModal.enableClose();
	};
	
	ajax.onerror = function(intStatus, strStatusText) {
		new LayerObject('DialogContentB').changeContent('Errore [' + intStatus + '] [' + strStatusText + '].');
		g_BigModal.enableClose();
	};
	
	
	ajax.addField('idprodotto', codiceprodotto);
	ajax.get('/ajax.prodotti.informazioni-aggiuntive.asp')
}

function add2Cart(codiceprodotto, idcorso, act, qta) {
	var ajax	= _.ajax();
	var fields	= new Array();
	
	fields['idprodotto'] = codiceprodotto;
	
	if (idcorso)
		fields['idcorso'] = idcorso;
	else
		fields['idcorso'] = 0;
		
	if (act)
		fields['act']	= act;
	else
		fields['act'] = 0; //0 -> add new qta, 1 -> add qta to existing, 2 -> subtract qta from existing, 3 -> remove, 4 -> replace qta
		
	if (qta)
		fields['qta']	= qta;
	else
		fields['qta']	= 1;
	
	
	ajax.oncomplete = function(strResponseText, objResponseXML) {
		var parts	= strResponseText.split('|');
		var btnID	= 'c_' + parts[1].toString() + (parts.length > 4 ? '_' + parts[3].toString() : '');
		
		if (parts[0] == '1') {
			document.getElementById(btnID).src = myImages['cart_ok'].src;
			
			//ultima modifica chiesta da Andrea: dopo l'inserimento gira alla pagina del carrello
			document.location.href = '/carrello.asp';
		}
		else {
			document.getElementById(btnID).src = myImages['cart_ko'].src;
			var t = setTimeout('document.getElementById(\'' + btnID + '\').src = myImages[\'cart\'].src;', 2000);
		}
	}
	
	ajax.onerror = function(intStatus, strStatusText) {
		alert('Errore [' + intStatus + '] [' + strStatusText + '].');
	}
	
	
	ajax.removeAllFields();
	
	for (var field in fields) {
		ajax.addField(field, fields[field]);
	}
	
	ajax.post('/ajax.cart.manage.asp');
}

function updateCart(codiceprodotto, newqta) {
	var ajax	= _.ajax();
	var fields	= new Array();
	
	fields['act']			= 4; //replace qta
	fields['idprodotto']	= codiceprodotto;
	fields['qta']			= newqta;
	
	ajax.oncomplete = function(strResponseText, objResponseXML) {
		var parts = strResponseText.split('|');
		
		if (parts[0] == '1') {
			var act = parts[parts.length-2];
			
			try {
				if (act=='c') {
					var lblID = 't_' + parts[1].toString();
					
					document.getElementById(lblID).innerHTML		= parts[2];
					document.getElementById('submitcart').disabled		= parseFloat(parts[parts.length - 1])<50;
					document.getElementById('warning').style.visibility	= parseFloat(parts[parts.length - 1])<50 ? 'visible' : 'hidden';
				}
				else if (act=='p') {
					//qui è sempre valido
				}
			}
			catch(e) {
			}
		}
		else {
			alert('Errore. Impossibile aggiornare la quantità.');
		}
	}
	
	ajax.onerror = function(intStatus, strStatusText) {
		alert('Errore [' + intStatus + '] [' + strStatusText + '].');
	}
	
	
	ajax.removeAllFields();
	
	for (var field in fields) {
		ajax.addField(field, fields[field]);
	}
	
	ajax.post('/ajax.cart.manage.asp');
}

function removeFromCart(codiceprodotto) {
	var ajax	= _.ajax();
	var fields	= new Array();
	
	fields['act']			= 3;
	fields['idprodotto']	= codiceprodotto;
	
	ajax.oncomplete = function(strResponseText, objResponseXML) {
		var parts	= strResponseText.split('|');
		var rowID	= 'r_' + parts[1].toString();
		
		if (parts[0] == '1') {
			var act = parts[parts.length-2];
			
			document.getElementById(rowID).style.display = 'none';
			
			try {
				if (act=='c') {
					document.getElementById('rowscart').value		= (parseInt(document.getElementById('rowscart').value) - 1).toString();
					document.getElementById('clearcart').disabled		= (parseInt(document.getElementById('rowscart').value) == 0);
					document.getElementById('submitcart').disabled		= (parseInt(document.getElementById('rowscart').value) == 0 || parseFloat(parts[parts.length - 1])<50);
					document.getElementById('warning').style.visibility	= document.getElementById('submitcart').disabled ? 'visible' : 'hidden';
				}
				
				if (act=='p') {
					document.getElementById('rowsprev').value		= (parseInt(document.getElementById('rowsprev').value) - 1).toString();
					document.getElementById('clearprev').disabled		= (parseInt(document.getElementById('rowsprev').value) == 0);
					document.getElementById('submitprev').disabled	= (parseInt(document.getElementById('rowsprev').value) == 0);
				}
			}
			catch(e) {
			}
		}
		else {
			alert('Errore. Impossibile eliminare il prodotto');
		}
	}
	
	ajax.onerror = function(intStatus, strStatusText) {
		alert('Errore [' + intStatus + '] [' + strStatusText + '].');
	}
	
	
	ajax.removeAllFields();
	
	for (var field in fields) {
		ajax.addField(field, fields[field]);
	}
	
	ajax.post('/ajax.cart.manage.asp');
}

function emptyCart(type) {
	var ajax	= _.ajax();
	var fields	= new Array();
	
	fields['act'] = type=='c' ? 5 : (type=='p' ? 6 : 7);
	
	ajax.oncomplete = function(strResponseText, objResponseXML) {
		var parts = strResponseText.split('|');
		
		if (parts[0] == '1') {
			var act = parts[parts.length-2];
			
			for (var i=1; i<parts.length-2; i++) {
				document.getElementById('r_' + parts[i].toString()).style.display = 'none';
			}
			
			try {
				if (act=='c' ||act=='t') {
					document.getElementById('rowscart').value		= '0';
					document.getElementById('clearcart').disabled		= true;
					document.getElementById('submitcart').disabled		= true;
					document.getElementById('warning').style.visibility	= 'visible';
				}
				
				if (act=='p'  || act=='t') {
					document.getElementById('rowsprev').value		= '0';
					document.getElementById('clearprev').disabled		= true;
					document.getElementById('submitprev').disabled	= true;
				}
			}
			catch(e) {
			}
		}
		else {
			alert('Errore. Impossibile rimuovere gli elementi');
		}
	}
	
	ajax.onerror = function(intStatus, strStatusText) {
		alert('Errore [' + intStatus + '] [' + strStatusText + '].');
	}
	
	
	ajax.removeAllFields();
	
	for (var field in fields) {
		ajax.addField(field, fields[field]);
	}
	
	ajax.post('/ajax.cart.manage.asp');
}

/***************************************************************************************/
function submitHardwareHelpRequestDo(f) {
	var fields = PrepareFormFields4Post(f);
	
	showModalPopUp('/ajax.assistenza.inviarichiesta.asp', 'post', fields);
}

/***************************************************************************************/
function login() {
	try {
		showModalPopUp('/ajax.login.asp', 'get', new Array());
	}
	catch(e) {
		changeModalPopUp('/ajax.login.asp', 'get', new Array());	
	}
}

function loginDo(fields) {
	var ajax = _.ajax();
	
	ajax.oncomplete = function(strResponseText, objResponseXML) {
		if (strResponseText == '1') {
			if (stayInSync) {
				proceed = 1;
				new LayerObject('DialogContent').addContentAfter('Identificazione completata con successo.<br />');
			}
			else {
				closeModalPopUp();
				window.location.reload();
			}
		}
		else {
			if (stayInSync) {
				proceed = 0;
				new LayerObject('DialogContent').addContentAfter('Errore durante il processo di identificazione.<br />');
			}
			else {
				new LayerObject('DialogContent').changeContent(
					'<h1>Login</h1>' +
					'<form>' +
					'	<h2>Dati di accesso errati.</h2>' +
					'	<p>' +
					'		<input class="btn" type="button" value="Recupera password" onclick="javascript:loginForgot();" />' +
					'		<input class="btn" type="button" value="Iscriviti" onclick="javascript:subscribe();" />' +
					'		<input class="btn" type="button" value="Torna indietro" onclick="javascript:login();" />' +
					'	</p>' +
					'</form>'
				);
			}
		}
	};
	
	ajax.onerror = function(intStatus, strStatusText) {
		if (stayInSync) {
			proceed = 0;
			new LayerObject('DialogContent').addContentAfter('Errore [' + intStatus + '] [' + strStatusText + '].');
		}
		else {
			new LayerObject('DialogContent').changeContent('Errore [' + intStatus + '] [' + strStatusText + '].');
		
			//bottone per la chiusura della finestra modale
			new LayerObject('DialogContent').addContentAfter(
				'<form><p>' +
				'	<input class="btn" type="button" value="Chiudi" onclick="closeModalPopUp();" />' +
				'</p></form>'
			);	
		}
	}
	
	
	ajax.removeAllFields();
	
	for (var field in fields) {
		ajax.addField(field, fields[field]);
	}
	
	if (!stayInSync)
		ajax.post('/ajax.login.do.asp');
	else
		ajax.postSynchronized('/ajax.login.do.asp');
}


function loginConfirm() {
	try {
		showModalPopUp('/ajax.login.confirm.asp', 'get', new Array());
	}
	catch(e) {
		changeModalPopUp('/ajax.login.confirm.asp', 'get', new Array());	
	}
}

function loginConfirmDo(fields) {
	var ajax = _.ajax();
	
	ajax.oncomplete = function(strResponseText, objResponseXML) {
		if (strResponseText == '1') {
			if (stayInSync) {
				proceed = 1;
				new LayerObject('DialogContent').changeContent('<h2>Verifica identit&agrave; completata con successo.</h2>');
			}
			else {
				closeModalPopUp();
				window.location.reload();
			}
		}
		else {
			if (stayInSync) {
				proceed = 0;
				new LayerObject('DialogContent').changeContent('<h2>Verifica identit&agrave; fallita.</h2>');
			}
			else {
				new LayerObject('DialogContent').changeContent(
					'<h1>Login</h1>' +
					'<h2>Verifica identit&agrave; fallita.</h2>' +
					'<form>' +
					'	<p>' +
					'		<input class="btn" type="button" value="Torna indietro" onclick="javascript:loginConfirm();" />' +
					'	</p>' +
					'</form>'
				);
			}
		}
	};
	
	ajax.onerror = function(intStatus, strStatusText) {
		if (stayInSync) {
			proceed = 0;
			new LayerObject('DialogContent').addContentAfter('Errore [' + intStatus + '] [' + strStatusText + '].');
		}
		else {
			new LayerObject('DialogContent').changeContent('Errore [' + intStatus + '] [' + strStatusText + '].');
		
			//bottone per la chiusura della finestra modale
			new LayerObject('DialogContent').addContentAfter(
				'<form><p>' +
				'	<input class="btn" type="button" value="Chiudi" onclick="closeModalPopUp();" />' +
				'</p></form>'
			);	
		}
	}
	
	
	ajax.removeAllFields();
	
	for (var field in fields) {
		ajax.addField(field, fields[field]);
	}
	
	if (!stayInSync)
		ajax.post('/ajax.login.confirm.do.asp');
	else
		ajax.postSynchronized('/ajax.login.confirm.do.asp');
}


function loginRequire() {
	try {
		showModalPopUp('/ajax.login.require.asp', 'get', new Array());
	}
	catch(e) {
		changeModalPopUp('/ajax.login.require.asp', 'get', new Array());
	}
}

function loginRequireDo(fields) {
	//questa esegue il login o l'iscrizione silenziosa a seconda della scelta dell'utente
	//il risultato finale deve, in caso di successo, comunque essere un utente loggato
	
	if (fields['reguser']==1) {
		//l'utente si sta identificando tramite username e password
		proceed = 0;
		loginDo(fields);
	}
	else {
		//l'utente sta riempiendo il form (iscrizione silenziosa)
		proceed = 0;
		subscribeDo(fields);
		
		if (proceed==1) {
			//imposto nei campi del form i valori di username e password autogenerati in modo che la seguente abbia
			//sicuramente successo
			fields['username']	= syncFields[7];
			fields['password']	= syncFields[8];
			
			//identifico l'utente appena registrato
			loginDo(fields);
			proceed = 1;
			
			//invio mail avvenuta iscrizione/modifica dati a noi (comunico all'utente un eventuale errore ma non fermo il processo)
			new LayerObject('DialogContent').addContentAfter('Invio email di notifica agli amministratori del sito in corso...<br />');
			sendEmailDo(syncFields[2], syncFields[3], syncFields[4], syncFields[5], syncFields[6]);
			proceed = 1;
		}
	}
}


function loginForgot() {
	changeModalPopUp('/ajax.login.forgot.asp', 'get', new Array());
}

function loginRemember(f) {
	var fields = PrepareFormFields4Post(f);
	
	changeModalPopUp('/ajax.login.remember.asp', 'post', fields);
}

function logout() {
	showModalPopUp('/ajax.logout.asp', 'get', new Array());
}

function logoutDo() {
	changeModalPopUp('/ajax.logout.do.asp', 'get', new Array());
	
	closeModalPopUp();
	window.location.replace('/');
}

/***************************************************************************************/
function subscribe() {
	try {
		closeModalPopUp();
	}
	catch(e) {
	}
	
	window.location.replace('/iscrizione.asp');
}

function subscribeDo(fields) {
	var ajax = _.ajax();
	
	ajax.oncomplete = function(strResponseText, objResponseXML) {
		if (stayInSync) {
			syncFields	= strResponseText.split('|');
			proceed		= parseInt(syncFields[0]);
			
			new LayerObject('DialogContent').addContentAfter(syncFields[1]);
		}
		else
			new LayerObject('DialogContent').changeContent(strResponseText.substring(2));
	};
	
	ajax.onerror = function(intStatus, strStatusText) {
		if (stayInSync) {
			proceed = 0;
			new LayerObject('DialogContent').addContentAfter('Errore [' + intStatus + '] [' + strStatusText + '].');
		}
		else
			new LayerObject('DialogContent').changeContent('Errore [' + intStatus + '] [' + strStatusText + '].');
	};
	
	ajax.removeAllFields();
	
	for (var field in fields) {
		ajax.addField(field, fields[field]);
	}
	
	if (!stayInSync)
		ajax.post('/ajax.iscrizione.inviarichiesta.asp');
	else
		ajax.postSynchronized('/ajax.iscrizione.inviarichiesta.asp');
}

/***************************************************************************************/
function joinEvent(eventid) {
	var fields = new Array();
	fields['idevento'] = eventid.toString();
	
	showModalPopUp('/ajax.eventi-iscrizione.asp', 'post', fields);
}

function joinEventsDo(fields) {
	var ajax = _.ajax();
	
	ajax.oncomplete = function(strResponseText, objResponseXML) {
		if (stayInSync) {
			syncFields	= strResponseText.split('|');
			proceed	= parseInt(syncFields[0]);
			
			new LayerObject('DialogContent').addContentAfter(syncFields[1]);
		}
		else
			new LayerObject('DialogContent').changeContent(strResponseText.substring(2));
	};
	
	ajax.onerror = function(intStatus, strStatusText) {
		if (stayInSync) {
			proceed = 0;
			new LayerObject('DialogContent').addContentAfter('Errore [' + intStatus + '] [' + strStatusText + '].');
		}
		else
			new LayerObject('DialogContent').changeContent('Errore [' + intStatus + '] [' + strStatusText + '].');
	};
	
	
	ajax.removeAllFields();
	
	for (var field in fields) {
		ajax.addField(field, fields[field]);
	}
	
	if (!stayInSync)
		ajax.post('/ajax.eventi-iscrizione.inviarichiesta.asp');
	else
		ajax.postSynchronized('/ajax.eventi-iscrizione.inviarichiesta.asp');
}

/***************************************************************************************/
function requestTraining(title) {
	var fields = new Array();
	fields['title'] = escape(title);
	
	showModalPopUp('/ajax.corsi-richiedi.asp', 'post', fields);
}

function requestTrainingDo(fields) {
	var ajax = _.ajax();
	
	ajax.oncomplete = function(strResponseText, objResponseXML) {
		if (stayInSync) {
			syncFields	= strResponseText.split('|');
			proceed	= parseInt(syncFields[0]);
			
			new LayerObject('DialogContent').addContentAfter(syncFields[1]);
		}
		else
			new LayerObject('DialogContent').changeContent(strResponseText.substring(2));
	};
	
	ajax.onerror = function(intStatus, strStatusText) {
		if (stayInSync) {
			proceed = 0;
			new LayerObject('DialogContent').addContentAfter('Errore [' + intStatus + '] [' + strStatusText + '].');
		}
		else
			new LayerObject('DialogContent').changeContent('Errore [' + intStatus + '] [' + strStatusText + '].');
	};
	
	
	ajax.removeAllFields();
	
	for (var field in fields) {
		ajax.addField(field, fields[field]);
	}
	
	if (!stayInSync)
		ajax.post('/ajax.corsi-richiedi.inviarichiesta.asp');
	else
		ajax.postSynchronized('/ajax.corsi-richiedi.inviarichiesta.asp');
}

/***************************************************************************************/
function requestDemo(product) {
	var fields = new Array();
	fields['prodotto'] = escape(product);
	
	showModalPopUp('/ajax.demo-richiedi.asp', 'post', fields);
}

function requestDemoDo(fields) {
	var ajax = _.ajax();
	
	ajax.oncomplete = function(strResponseText, objResponseXML) {
		if (stayInSync) {
			syncFields	= strResponseText.split('|');
			proceed	= parseInt(syncFields[0]);
			
			new LayerObject('DialogContent').addContentAfter(syncFields[1]);
		}
		else
			new LayerObject('DialogContent').changeContent(strResponseText.substring(2));
	};
	
	ajax.onerror = function(intStatus, strStatusText) {
		if (stayInSync) {
			proceed = 0;
			new LayerObject('DialogContent').addContentAfter('Errore [' + intStatus + '] [' + strStatusText + '].');
		}
		else
			new LayerObject('DialogContent').changeContent('Errore [' + intStatus + '] [' + strStatusText + '].');
	};
	
	
	ajax.removeAllFields();
	
	for (var field in fields) {
		ajax.addField(field, fields[field]);
	}
	
	if (!stayInSync)
		ajax.post('/ajax.demo-richiedi.inviarichiesta.asp');
	else
		ajax.postSynchronized('/ajax.demo-richiedi.inviarichiesta.asp');
}

/***************************************************************************************/
function photoGallery(p) {
	var ajax = _.ajax();
	
	g_BigModal	= new ModalDialog('ModalBG', 'DialogWindowB', 'DialogContentB', 'DialogActionBtnB')
	g_BigModal.setStyle('background-image', 'none');
	g_BigModal.setStyle('background-color', '#FFFFFF');
	g_BigModal.setStyle('border', '1px solid #000000');
	g_BigModal.setStyle('font-size', '12px');
	g_BigModal.setStyle('font-style', 'italic');
	g_BigModal.setStyle('text-align', 'center');
	g_BigModal._contentLayer.setStyle('padding', '0px 0px 0px 0px');
	g_BigModal._dragLayer.ignoreLayer('DialogContentB');
	
	g_BigModal.show('<img src="/images/ajax-loader.gif" alt="Caricamento in corso..." />');
	new LayerObject('DialogTitleB').changeContent('Caricamento in corso...');
	g_BigModal.disableClose();
	
	adjustHeight();
	
	
	ajax.oncomplete = function(strResponseText, objResponseXML) {
		var parts = strResponseText.split('|');
		
		new LayerObject('DialogContentB').changeContent(parts[0]);
		new LayerObject('DialogTitleB').changeContent(parts[1]);
		
		var maxWidth	= parseInt(_.getstyle('pgimg', 'max-width'));
		var maxHeight	= parseInt(_.getstyle('pgimg', 'max-height'));
		var width		= parseInt(parts[2]);
		var height		= parseInt(parts[3]);
		
		if (width>height) {
			if (width>maxWidth) {
				height	= (maxWidth / width) * height;
				width		= maxWidth;
			}
		}
		else {
			if (height>maxHeight) {
				width		= (maxHeight  / height) * width;
				height	= maxHeight;
			}
		}
			
		g_BigModal._contentLayer.resizeTo(width + 20, height + 10);
		g_BigModal.resizeTo(width + 24, height + 50);
		g_BigModal.moveToDeadCentre();
		g_BigModal.enableClose();
	};
	
	ajax.onerror	 = function(intStatus, strStatusText) {
		new LayerObject('DialogContentB').changeContent('Errore [' + intStatus + '] [' + strStatusText + '].');
		g_BigModal.enableClose();
	};
	
	
	ajax.addField('idfoto', p);
	ajax.get('/ajax.photogallery.asp')
}

/***************************************************************************************/
function videoPlayer(t, v, w, h) {
	var obj = '<object id="video" style="width: ' + w.toString() + 'px; height: ' + h.toString() + 'px; margin: 0px; padding: 0px;" classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" type="application/x-oleobject">';
	obj += '<param name="URL" value="' + v + '">';
	obj += '<param name="SendPlayStateChangeEvents" value="True">';
	obj += '<param name="AutoStart" value="True">';
	obj += '<param name="uiMode" value="mini">';
	obj += '<param name="PlayCount" value="1">';
	obj += '</object>';
	
	g_BigModal = new ModalDialog('ModalBG', 'DialogWindowB', 'DialogContentB', 'DialogActionBtnB')
	g_BigModal.setStyle('background-image', 'none');
	g_BigModal.setStyle('background-color', '#FFFFFF');
	g_BigModal.setStyle('border', '1px solid #000000');
	g_BigModal.setStyle('font-size', '12px');
	g_BigModal.setStyle('font-style', 'italic');
	g_BigModal.setStyle('text-align', 'center');
	g_BigModal._contentLayer.setStyle('padding', '0px 0px 0px 0px');
	g_BigModal._dragLayer.ignoreLayer('DialogContentB');
	
	g_BigModal.show(obj);
	new LayerObject('DialogTitleB').changeContent(t);
	
	adjustHeight();
	
	g_BigModal._contentLayer.resizeTo(w, h);
	g_BigModal.resizeTo(w + 24, h + 50);
	g_BigModal.moveToDeadCentre();
}

/***************************************************************************************/
function showVersions(idcategoria) {
	var ajax = _.ajax();
	
	g_BigModal	= new ModalDialog('ModalBG', 'DialogWindowB', 'DialogContentB', 'DialogActionBtnB')
	g_BigModal.show('<img src="/images/ajax-loader.gif" alt="Caricamento in corso..." />');
	g_BigModal.moveTo(g_BigModal.getLeft(), 10);
	g_BigModal._dragLayer.ignoreLayer('DialogContentB');
	g_BigModal.disableClose();
	
	adjustHeight();
	
	
	ajax.oncomplete	= function(strResponseText, objResponseXML) {
		new LayerObject('DialogContentB').changeContent(strResponseText);
		g_BigModal.enableClose();
	};
	
	ajax.onerror		= function(intStatus, strStatusText) {
		new LayerObject('DialogContentB').changeContent('Errore [' + intStatus + '] [' + strStatusText + '].');
		g_BigModal.enableClose();
	};
	
	
	ajax.addField('idcategoria', idcategoria);
	ajax.get('/ajax.prodotti.versioni_prezzi.asp')
}

function showSales() {
	var ajax = _.ajax();
	
	g_BigModal	= new ModalDialog('ModalBG', 'DialogWindowB', 'DialogContentB', 'DialogActionBtnB')
	g_BigModal.show('<img src="/images/ajax-loader.gif" alt="Caricamento in corso..." />');
	g_BigModal.moveTo(g_BigModal.getLeft(), 10);
	g_BigModal._dragLayer.ignoreLayer('DialogContentB');
	g_BigModal.disableClose();
	
	adjustHeight();
	
	
	ajax.oncomplete	= function(strResponseText, objResponseXML) {
		new LayerObject('DialogContentB').changeContent(strResponseText);
		g_BigModal.enableClose();
	};
	
	ajax.onerror		= function(intStatus, strStatusText) {
		new LayerObject('DialogContentB').changeContent('Errore [' + intStatus + '] [' + strStatusText + '].');
		g_BigModal.enableClose();
	};
	
	
	ajax.get('/ajax.prodotti.offerte.asp')
}

/***************************************************************************************/
function showSuperItem() {
	//descrizione della categoria e sotto versioni e prezzi di quella categoria
	var ajax	= _.ajax();
	var idcategoria	= 0;
	
	g_BigModal	= new ModalDialog('ModalBG', 'DialogWindowB', 'DialogContentB', 'DialogActionBtnB')
	
	ajax.oncomplete = function(strResponseText, objResponseXML) {
		//se non c'e niente nella risposta vuol dire che non c'è layer
		if (strResponseText!='') {
			adjustHeight();
			
			var parts = strResponseText.split('|');
			
			//se e un prodotto ho un'ulteriore richiesta da fare per avere il prezzo
			if (parts[0]=='P') {
				g_BigModal.show(parts[2]);
				g_BigModal.moveTo(g_BigModal.getLeft(), 10);
				g_BigModal._dragLayer.ignoreLayer('DialogContentB');
				g_BigModal.disableClose();
				
				//salvo l'id della categoria che serve sia per la richiesta delle versioni e prezzi sia come discriminante
				//al successivo ritorno dalla chiamata seguente in modo che il risultato venga accodato al contenuto
				//esistente invece che sostituito
				idcategoria = parts[1];
			}
			else if (idcategoria==0){
				g_BigModal.show(parts[1]);
				g_BigModal.moveTo(g_BigModal.getLeft(), 10);
				g_BigModal._dragLayer.ignoreLayer('DialogContentB');
				g_BigModal.enableClose();
			}
			else {
				new LayerObject('DialogContentB').addContentAfter(strResponseText);
				g_BigModal.enableClose();
			}
		}
	};
	
	ajax.onerror	 = function(intStatus, strStatusText) {
		g_BigModal.show('Errore [' + intStatus + '] [' + strStatusText + '].');
		g_BigModal.enableClose();
	};
	
	if (_.gcook('hl') == null) {
		_.scook('hl', '1', 0);
		
		ajax.postSynchronized('/ajax.homelayer.asp');
		
		//se é un prodotto ne carico le versioni
		if (idcategoria!=0) {
			ajax.removeAllFields();
			ajax.addField('idcategoria', idcategoria);
			ajax.addField('superprodotto', 1);
			ajax.postSynchronized('/ajax.prodotti.versioni_prezzi.asp');
		}
	}
}

/***************************************************************************************/
//Queste di seguito servono per eseguire task composti da più azioni atomiche susseguenti/dipendenti
var proceed		= 0;
var stayInSync	= false;
var syncFields	= new Array();

function subscribeTask(f) {
	stayInSync = true;
	syncFields	= new Array();
	var fields	= PrepareFormFields4Post(f);
	
	g_Modal.show('Salvataggio dati in corso...<br />');
	g_Modal.disableClose();
	
	//esecuzione iscrizione
	proceed = 0;
	subscribeDo(fields);
	
	//le seguenti dipendono strettamente dal buon fine della precedente
	if (proceed==1) {
		//le seguenti, in caso di errore, non interrompono l'esecuzione del flusso perchè la parte principale (il salvataggio del contatto)
		//è correttamente conclusa; queste sono solo automazioni per comodità degli utenti (auto-identificazione) e nostra (avviso)
		
		//login automatico del nuovo iscritto
		new LayerObject('DialogContent').addContentAfter('Identificazione automatica nuovo iscritto in corso... <br />');
		loginDo(fields);
		
		//invio mail avvenuta iscrizione/modifica dati a noi
		new LayerObject('DialogContent').addContentAfter('Invio email di notifica agli amministratori del sito in corso...<br />');
		sendEmailDo(syncFields[2], syncFields[3], syncFields[4], syncFields[5], syncFields[6]);
	}
	
	//bottone per la chiusura della finestra modale
	new LayerObject('DialogContent').addContentAfter(
		'<form><p>' +
		'	<input class="btn" type="button" value="Chiudi" onclick="closeModalPopUp();" />' +
		'</p></form>'
	);

	g_Modal.enableClose();
	
	proceed	= 0;
	stayInSync	= false;
	syncFields	= new Array();
}


function joinEventsTask(f) {
	stayInSync = true;
	syncFields	= new Array();
	var fields	= PrepareFormFields4Post(f);
	
	new LayerObject('DialogContent').changeContent('Invio richiesta in corso...<br />');
	g_Modal.disableClose();
	
	if (fields['alreadylogged']==0) {
		//l'utente non è identificato
		if (fields['reguser']==1) {
			//l'utente si sta identificando tramite username e password
			proceed = 0;
			loginDo(fields);
		}
		else {
			//l'utente sta riempiendo il form (iscrizione silenziosa)
			proceed = 0;
			subscribeDo(fields);
			
			if (proceed==1) {
				//invio mail avvenuta iscrizione/modifica dati a noi (comunico all'utente un eventuale errore ma non fermo il processo)
				new LayerObject('DialogContent').addContentAfter('Invio email di notifica agli amministratori del sito in corso...<br />');
				sendEmailDo(syncFields[2], syncFields[3], syncFields[4], syncFields[5], syncFields[6]);
				proceed = 1;
			}
		}
	}
	else {
		//l'utente è identificato
		proceed = 1;
	}
	
	//le seguenti dipendono strettamente dal buon fine della precedente
	if (proceed==1) {
		proceed = 0;
		joinEventsDo(fields);
		
		if (proceed==1) {
			//invio mail richiesta partecipazione all'evento a noi
			new LayerObject('DialogContent').addContentAfter('Invio email di richiesta partecipazione ad evento in corso...<br />');
			sendEmailDo(syncFields[2], syncFields[3], syncFields[4], syncFields[5], syncFields[6]);
		}
	}
	
	//bottone per la chiusura della finestra modale
	new LayerObject('DialogContent').addContentAfter(
		'<form><p>' +
		'	<input class="btn" type="button" value="Chiudi" onclick="closeModalPopUp();" />' +
		'</p></form>'
	);
	
	g_Modal.enableClose();
	
	proceed	= 0;
	stayInSync	= false;
	syncFields	= new Array();
}


function requestTrainingTask(f) {
	stayInSync = true;
	syncFields	= new Array();
	var fields	= PrepareFormFields4Post(f);
	
	new LayerObject('DialogContent').changeContent('Invio richiesta in corso...<br />');
	g_Modal.disableClose();
	
	if (fields['alreadylogged']==0) {
		//l'utente non è identificato
		if (fields['reguser']==1) {
			//l'utente si sta identificando tramite username e password
			proceed = 0;
			loginDo(fields);
		}
		else {
			//l'utente sta riempiendo il form (iscrizione silenziosa)
			proceed = 0;
			subscribeDo(fields);
			
			if (proceed==1) {
				//invio mail avvenuta iscrizione/modifica dati a noi (comunico all'utente un eventuale errore ma non fermo il processo)
				new LayerObject('DialogContent').addContentAfter('Invio email di notifica agli amministratori del sito in corso...<br />');
				sendEmailDo(syncFields[2], syncFields[3], syncFields[4], syncFields[5], syncFields[6]);
				proceed = 1;
			}
		}
	}
	else {
		//l'utente è identificato
		proceed = 1;
	}
	
	//le seguenti dipendono strettamente dal buon fine della precedente
	if (proceed==1) {
		proceed = 0;
		requestTrainingDo(fields);
		
		if (proceed==1) {
			//invio mail richiesta partecipazione all'evento a noi
			new LayerObject('DialogContent').addContentAfter('Invio email di richiesta corso personalizzato in corso...<br />');
			sendEmailDo(syncFields[2], syncFields[3], syncFields[4], syncFields[5], syncFields[6]);
		}
	}
	
	//bottone per la chiusura della finestra modale
	new LayerObject('DialogContent').addContentAfter(
		'<form><p>' +
		'	<input class="btn" type="button" value="Chiudi" onclick="closeModalPopUp();" />' +
		'</p></form>'
	);
	
	g_Modal.enableClose();
	
	proceed	= 0;
	stayInSync	= false;
	syncFields	= new Array();
}

function requestDemoTask(f) {
	stayInSync = true;
	syncFields	= new Array();
	var fields	= PrepareFormFields4Post(f);
	
	new LayerObject('DialogContent').changeContent('Invio richiesta in corso...<br />');
	g_Modal.disableClose();
	
	if (fields['alreadylogged']==0) {
		//l'utente non è identificato
		if (fields['reguser']==1) {
			//l'utente si sta identificando tramite username e password
			proceed = 0;
			loginDo(fields);
		}
		else {
			//l'utente sta riempiendo il form (iscrizione silenziosa)
			proceed = 0;
			subscribeDo(fields);
			
			if (proceed==1) {
				//invio mail avvenuta iscrizione/modifica dati a noi (comunico all'utente un eventuale errore ma non fermo il processo)
				new LayerObject('DialogContent').addContentAfter('Invio email di notifica agli amministratori del sito in corso...<br />');
				sendEmailDo(syncFields[2], syncFields[3], syncFields[4], syncFields[5], syncFields[6]);
				proceed = 1;
			}
		}
	}
	else {
		//l'utente è identificato
		proceed = 1;
	}
	
	//le seguenti dipendono strettamente dal buon fine della precedente
	if (proceed==1) {
		proceed = 0;
		requestDemoDo(fields);
		
		if (proceed==1) {
			//invio mail richiesta partecipazione all'evento a noi
			new LayerObject('DialogContent').addContentAfter('Invio email di richiesta demo personalizzata in corso...<br />');
			sendEmailDo(syncFields[2], syncFields[3], syncFields[4], syncFields[5], syncFields[6]);
		}
	}
	
	//bottone per la chiusura della finestra modale
	new LayerObject('DialogContent').addContentAfter(
		'<form><p>' +
		'	<input class="btn" type="button" value="Chiudi" onclick="closeModalPopUp();" />' +
		'</p></form>'
	);
	
	g_Modal.enableClose();
	
	proceed	= 0;
	stayInSync	= false;
	syncFields	= new Array();
}


function loginConfirmTask(f) {
	stayInSync = true;
	syncFields	= new Array();
	var fields	= PrepareFormFields4Post(f);
	
	//new LayerObject('DialogContent').changeContent('Invio richiesta in corso...<br />');
	g_Modal.show('Invio richiesta in corso...<br />');
	g_Modal.disableClose();
	
	proceed = 0
	loginConfirmDo(fields);
	
	if (proceed==1) {
		window.location.href = '/carrello.pagamento.asp';
	}
	
	//bottone per la chiusura della finestra modale
	new LayerObject('DialogContent').addContentAfter(
		'<form><p>' +
		'	<input class="btn" type="button" value="Chiudi" onclick="closeModalPopUp();" />' +
		'</p></form>'
	);
	
	g_Modal.enableClose();
	
	proceed	= 0;
	stayInSync	= false;
	syncFields	= new Array();
}

function loginRequireTask(f) {
	stayInSync	= true;
	syncFields	= new Array();
	var fields	= PrepareFormFields4Post(f);
	
	//new LayerObject('DialogContent').changeContent('Invio richiesta in corso...<br />');
	g_Modal.show('Invio richiesta in corso...<br />');
	g_Modal.disableClose();
	
	proceed = 0
	loginRequireDo(fields);
	
	if (proceed==1) {
		window.location.href = '/carrello.pagamento.asp';
	}
	
	//bottone per la chiusura della finestra modale
	new LayerObject('DialogContent').addContentAfter(
		'<form><p>' +
		'	<input class="btn" type="button" value="Chiudi" onclick="closeModalPopUp();" />' +
		'</p></form>'
	);
	
	g_Modal.enableClose();
	
	proceed		= 0;
	stayInSync	= false;
	syncFields	= new Array();
}