String.prototype.startsWith = function(value) {
	return (this.substr(0, value.length)==value);
}

String.prototype.endsWith = function(s) {
 return (s == this.substring(this.length - s.length));
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g, "");
}

String.prototype.escapeURL = function() {
	return this.replace(/\'/g,'\'');
}

function resetDefaultValue(field) {
	if (field.value.endsWith('...')) field.value='';
};

function login() {
	$.ajax({
	  type: "GET",
	  dataType: "xml",
	  url: './login.jsp?user='+$('#user').val()+"&password="+$('#password').val()+"&fix="+parseInt(Math.random()*99999),
	  success: function(xml){
	  	if ($("error", xml).text()) {
	  		alert($("error", xml).text());
	  	} else {
		  	window.location.search = window.location.search.replace(/idSlot=[0-9]*/, '');
		  	tb_remove();
	  	}
		}
	});
};

function loadPasswordChange() {
	$('#TB_ajaxContent').load("./viewPasswordChange.jsp?fix="+parseInt(Math.random()*99999), function() {
		tb_show('GESTIONE CREDENZIALI','#TB_inline?height=200&width=400&inlineId=popupwindow',false);
		$('#pass0').focus();
	});
};

function changePassword() {
	$.ajax({
	  type: "GET",
	  dataType: "xml",
	  url: './passwordChange.jsp?old=' + $('#pass0').val() + '&password1=' + $('#pass1').val() + '&password2=' + $('#pass2').val() + '&fix='+parseInt(Math.random()*99999),
	  success: function(xml){
		alert($("message, error", xml).text());
		if ($("message", xml).text()) tb_remove();
	  }
	});
};

function uploadBanner(tform, turi) {
	$.ajaxUpload({
		uploadform: tform,
		url: turi,
		secureuri: false,
		dataType: 'xml',
		success: function (xml) {
			alert($('message', xml).text());
			$(tform).find(':input[name=image]').val($('message', xml).attr('image'));
			$(tform).find(':input[name=link]').val($('message', xml).attr('link'));
		},
		error: function (msg, status, e) {
			alert(e)
		}
	})
};

function deleteBanner(form) {
	var p = $(form).find(':hidden[name=position]').val();
	$.ajax({
		type: "GET",
		dataType: "xml",
		url: './deleteBanner.jsp?position='+p+'&fix='+parseInt(Math.random()*99999),
		success: function(xml){
			if ($('message', xml).attr('deleted') == 'true') {
				$(form).find(':input[name=image]').val('');
				$(form).find(':input[name=link]').val('');
			}
	  		alert($("message, error", xml).text());
		},
		error: function (msg, status, e) {
			alert(e)
		}
	});
};

function searchUser() {
	$('#idUtente').load("./userlist.jsp?id="+$('#search').val()+"&nomeattivita="+$('#nomeattivita').val()+"&fix="+parseInt(Math.random()*99999));
};

function logoff() {
	$.ajax({
	  type: "GET",
	  dataType: "xml",
	  url: './logoff.jsp?fix='+parseInt(Math.random()*99999),
	  success: function(xml){
	  	if ($("error", xml).text()) {
	  		alert($("error", xml).text());
	  	} else {
	  		window.location.search = window.location.search.replace(/idSlot=[0-9]*/, '');
		  	tb_remove();
	  	}
		}
	});
};

function setModelWeek(a) {
	$.ajax({
	  type: "GET",
	  dataType: "xml",
	  url: './setModelWeek.jsp?day='+$(a).attr('class')+'&fix='+parseInt(Math.random()*99999),
	  success: function(xml){
	  	alert($("message, error", xml).text());
		}
	});
};

function addPrenotazioneAdmin(_confirm) {
	var utente = $('#idUtente').val()==null?'':$('#idUtente').val();
	var invoke = './addPrenotazioneAdmin.jsp?idSlot='+$('#idSlot').val()+'&idUtente='+utente+'&descrizione='+$('#descrizione').val().escapeURL()+'&updated='+window.lastPrenotazione+'&fix='+parseInt(Math.random()*99999);
	if (_confirm) {invoke += '&confirm=true';}
	$.ajax({
	  type: "GET",
	  dataType: "xml",
	  url: invoke,
	  success: function(xml){
	  	if ($("error", xml).text()) {
	  		alert($("error", xml).text());
	  		// in caso di errore chiude il popup e ricarico la pagina
	  		tb_remove();
	  		reloadCalendar();
	  		
	  	} else {
	  		if ($("warn", xml).text()) {
	  			if (window.confirm($("warn", xml).text())) {
	  				addPrenotazioneAdmin(true);
	  				return;
	  			}
	  		}
		  	var idSlot = $('message,warn', xml).attr('idSlot');
		  	if (window.location.search.indexOf('idSlot=')>-1) {
		  		window.location.search = window.location.search.replace(/idSlot=[0-9]*/,'idSlot='+idSlot);
		  	} else {
					window.location.search += "&idSlot=" + idSlot;
		  	}
		  	tb_remove();
	  	}
		}
	});
};

function addPrenotazioneAbbonato() {
	var invoke = './addPrenotazioneAbbonato.jsp?idSlot='+$('#idSlot').val()+'&descrizione='+$('#descrizione').val().escapeURL()+'&updated='+window.lastPrenotazione+'&fix='+parseInt(Math.random()*99999);
	$.ajax({
	  type: "GET",
	  dataType: "xml",
	  url: invoke,
	  success: function(xml){
	  	if ($("error", xml).text()) {
	  		alert($("error", xml).text());
	  		// in caso di errore chiude il popup e ricarico la pagina
	  		tb_remove();
	  		reloadCalendar();
	  		
	  	} else {
		  	var idSlot = $('message,warn', xml).attr('idSlot');
		  	if (window.location.search.indexOf('idSlot=')>-1) {
		  		window.location.search = window.location.search.replace(/idSlot=[0-9]*/,'idSlot='+idSlot);
		  	} else {
					window.location.search += "&idSlot=" + idSlot;
		  	}
		  	tb_remove();
	  	}
		}
	});
};

function addPrenotazioneOspite() {
	var invoke = './addPrenotazioneOspite.jsp?idSlot='+$('#idSlot').val()+'&descrizione='+$('#descrizione').val().escapeURL()+'&updated='+window.lastPrenotazione+'&user='+$('#user').val()+"&password="+$('#password').val()+'&fix='+parseInt(Math.random()*99999);
	$.ajax({
	  type: "GET",
	  dataType: "xml",
	  url: invoke,
	  success: function(xml){
	  	if ($("error", xml).text()) {
	  		alert($("error", xml).text());
	  		// in caso di errore chiude il popup e ricarico la pagina
	  		tb_remove();
	  		reloadCalendar();
	  		
	  	} else {
		  	var idSlot = $('message,warn', xml).attr('idSlot');
		  	if (window.location.search.indexOf('idSlot=')>-1) {
		  		window.location.search = window.location.search.replace(/idSlot=[0-9]*/,'idSlot='+idSlot);
		  	} else {
					window.location.search += "&idSlot=" + idSlot;
		  	}
		  	tb_remove();
	  	}
		}
	});	
};

function passwordReset() {
	var utente = $('#idUtente').val()==null?'':$('#idUtente').val();
	var invoke = './passwordReset.jsp?idUtente='+utente+'&fix='+parseInt(Math.random()*99999);
	$.ajax({
	  type: "GET",
	  dataType: "xml",
	  url: invoke,
	  success: function(xml){
			alert($("message, error", xml).text());
	  	if ($("message", xml).text()) tb_remove();
		}
	});
};

function toogleStatoPrenotazioneOspite(p,s) {
	$.ajax({
	  type: "GET",
	  dataType: "xml",
	  url: './toogleStatoPrenotazioneOspite.jsp?idPrenotazione='+p+'&updated='+window.lastPrenotazione+'&fix='+parseInt(Math.random()*99999),
	  success: function(xml){
	  	if ($("error", xml).text()) {
	  		alert($("error", xml).text());
	  	} else {
		  	if (window.location.search.indexOf('idSlot=')>-1) {
		  		window.location.search = window.location.search.replace(/idSlot=[0-9]*/,'idSlot='+s);
		  	} else {
					window.location.search += "&idSlot=" + s;
		  	}
		  	tb_remove();
	  	}
		}
	});
};

function deletePrenotazione() {
	$.ajax({
	  type: "GET",
	  dataType: "xml",
	  url: './deletePrenotazione.jsp?idPrenotazione='+$('#idPrenotazione').val()+'&updated='+window.lastPrenotazione+'&fix='+parseInt(Math.random()*99999),
	  success: function(xml){
	  	if ($("error", xml).text()) {
	  		alert($("error", xml).text());
	  		// in caso di errore chiude il popup e ricarico la pagina
	  		tb_remove();
	  		reloadCalendar();

	  	} else {
		  	var idSlot = $('message', xml).attr('idSlot');
		  	if (window.location.search.indexOf('idSlot=')>-1) {
		  		window.location.search = window.location.search.replace(/idSlot=[0-9]*/,'idSlot='+idSlot);
		  	} else {
					window.location.search += "&idSlot=" + idSlot;
		  	}
		  	tb_remove();
	  	}
		}
	});
};

function deletePrenotazioneOspite() {
	$.ajax({
	  type: "GET",
	  dataType: "xml",
	  url: './deletePrenotazioneOspite.jsp?idPrenotazione='+$('#idPrenotazione').val()+'&updated='+window.lastPrenotazione+'&user='+$('#user').val()+"&password="+$('#password').val()+'&fix='+parseInt(Math.random()*99999),
	  success: function(xml){
	  	if ($("error", xml).text()) {
	  		alert($("error", xml).text());
	  		// in caso di errore chiude il popup e ricarico la pagina
	  		tb_remove();
	  		reloadCalendar();

	  	} else {
		  	var idSlot = $('message', xml).attr('idSlot');
		  	if (window.location.search.indexOf('idSlot=')>-1) {
		  		window.location.search = window.location.search.replace(/idSlot=[0-9]*/,'idSlot='+idSlot);
		  	} else {
					window.location.search += "&idSlot=" + idSlot;
		  	}
		  	tb_remove();
	  	}
		}
	});
};

function annullaPrenotazioni() {
	$.ajax({
	  type: "GET",
	  dataType: "xml",
	  url: './annullaPrenotazioni.jsp?idSlot='+$('#idSlot').val()+'&updated='+window.lastPrenotazione+'&fix='+parseInt(Math.random()*99999),
	  success: function(xml){
	  	if ($("error", xml).text()) {
	  		alert($("error", xml).text());
	  		// in caso di errore chiude il popup e ricarico la pagina
	  		tb_remove();
	  		reloadCalendar();

	  	} else {
		  	var idSlot = $('message', xml).attr('idSlot');
		  	if (window.location.search.indexOf('idSlot=')>-1) {
		  		window.location.search = window.location.search.replace(/idSlot=[0-9]*/,'idSlot='+idSlot);
		  	} else {
					window.location.search += "&idSlot=" + idSlot;
		  	}
		  	tb_remove();
	  	}
		}
	});
};

function ripristinaPrenotazioni() {
	$.ajax({
	  type: "GET",
	  dataType: "xml",
	  url: './ripristinaPrenotazioni.jsp?idSlot='+$('#idSlot').val()+'&updated='+window.lastPrenotazione+'&fix='+parseInt(Math.random()*99999),
	  success: function(xml){
	  	if ($("error", xml).text()) {
	  		alert($("error", xml).text());
	  		// in caso di errore chiude il popup e ricarico la pagina
	  		tb_remove();
	  		reloadCalendar();

	  	} else {
		  	var idSlot = $('message', xml).attr('idSlot');
		  	if (window.location.search.indexOf('idSlot=')>-1) {
		  		window.location.search = window.location.search.replace(/idSlot=[0-9]*/,'idSlot='+idSlot);
		  	} else {
					window.location.search += "&idSlot=" + idSlot;
		  	}
		  	tb_remove();
	  	}
		}
	});
};

function deleteSlot() {
	if (window.confirm('Si è certi di voler eliminare il campo?')) {
		$.ajax({
		  type: "GET",
		  dataType: "xml",
		  url: './deleteSlot.jsp?idSlot='+$('#idSlot').val()+'&fix='+parseInt(Math.random()*99999),
		  success: function(xml){
		  	alert($("message, error", xml).text());
		  	window.location.search = window.location.search.replace(/idSlot=[0-9]*/,'');
			  tb_remove();
			}
		});
	}
};

function addSlot() {
	$.ajax({
	  type: "GET",
	  dataType: "xml",
	  url: './addSlot.jsp?court='+$('#court').val()+'&day='+$('#day').val()+'&attivita='+$('#attivita').val()+'&oraDa='+$('#oraDa').val()+'&fix='+parseInt(Math.random()*99999),
	  success: function(xml){
	  	if ($("error", xml).text()) {
	  		alert($("error", xml).text());
	  	} else {
		  	var idSlot = $('message', xml).attr('idSlot');
		  	if (window.location.search.indexOf('idSlot=')>-1) {
		  		window.location.search = window.location.search.replace(/idSlot=[0-9]*/,'idSlot='+idSlot);
		  	} else {
					window.location.search += "&idSlot=" + idSlot;
		  	}
		  	tb_remove();
	  	}
		}
	});
};

function toggleOspite(obj) {
	if (obj.options[obj.selectedIndex].text.startsWith('ospite')) {
		$('#ospite').fadeIn();
		$('#descrizione').focus();
	} else {
		$('#ospite').fadeOut();
		$('#descrizione').val('');
	}
};

function toggleBanners() {
	if ($('#banners').is(':visible')) {
		$('#banners').slideUp();
	} else {
		$('#banners').slideDown();
	}
};

function reloadCalendar() {
	var uurl = window.location.href.replace(/fix=[0-9]*/,'');
	uurl += ((uurl.indexOf('?')>-1)?'&':'?') + parseInt(Math.random()*99999);
	$.ajax({
	  type: "GET",
	  dataType: "html",
	  url: uurl,
	  success: function(html){
  		$('#calendar').html( $(html).find('#calendar').html() );
  		initEvents();
		}
	});
};

function initEvents() {
	var profilo = $('#calendar').attr('class');
	$('a[class^=act_]').unbind('click').click(function(){
		var entity = $(this).attr('class').split('_')[1];
		var id = $(this).attr('class').split('_')[2];
		$('#popupwindow').load("./view"+profilo+".jsp?entity="+entity+"&id="+id+"&fix="+parseInt(Math.random()*99999), function() {
				// data ultimo aggiornamento "congelata" quando apro il popup
				window.lastPrenotazione = $('#lastPrenotazione').text();
				tb_show(profilo,'#TB_inline?height=400&width=400&inlineId=popupwindow',false);
				$('#TB_ajaxWindowTitle').text($('#ref').remove().text());
				$('#search').focus();
		});
	});
	
	$('a[class^=unknown_]').unbind('click').click(function(){
		$('#popupwindow').load("./viewlogin.jsp?fix="+parseInt(Math.random()*99999), function() {
				tb_show('GESTIONE CREDENZIALI','#TB_inline?height=200&width=400&inlineId=popupwindow',false);
				$('#user').focus();
		});
	});
};

$(document).ready(function() {

	///////////////////////////////
	// INDEX.JSP
	///////////////////////////////

	initEvents();
		
	var targez = $('div[class*=evidenz]');
	if (targez.length) {
		var br = targez.css('background-color');
	  $('body').animate({ scrollTop: targez.offset().top-100 }, 1000, function() {
			targez
				.animate({ backgroundColor:'silver'}, 200)
				.animate({ backgroundColor: br, borderTopColor:'red', borderBottomColor:'red',borderLeftColor:'red', borderRightColor:'red'}, 200);
	  });
	}
	
	// rotazione banner
	var ul = $('#banner ul');
	if (ul.length) {
		ul.css('display', 'block');
		if (ul.find('li').length>1) {
			ul.innerfade({ speed: 2000, timeout: 5000, type: 'sequence', containerheight: '200px' });
		}
	}
	
	if ($('#main').length) {		
		$('#calendar').everyTime(60000, 'maintimer', function() {
			$.ajax({
			  type: "GET",
			  dataType: "text",
			  url: './readLastPrenotazione.jsp?fix='+parseInt(Math.random()*99999),
			  success: function(txt){
			  	// non funziona perche confronta il timestamp di modifica prenotazione con la data della prenotazione
			  	// if (txt.startsWith($('#today').text()) && $('#lastPrenotazione').text()!=txt) {
			  	if ($('#lastPrenotazione').text()!=txt) {
						reloadCalendar();
			  	}
				}
			});
		});
	}
	
	///////////////////////////////
	// CALENDARIO.JSP
	///////////////////////////////
		
	if ($.fn.ajaxForm) {
		
		$('#calendarSlots').ajaxForm(function(xml) {
			var msg = $("message,error", xml).text();
			if (msg) {
				var targez = $('#subtitle').html(msg);
			  $('body').animate({ scrollTop: targez.offset().top-100 }, 1000, function() {
					targez
						.animate({ backgroundColor:'silver' }, 500)
						.animate({ backgroundColor:'#F9F9F9' }, 500);
			  });
			}
		});

		$('#calendarSlots .date a').attr('title','Click per selezionare la settimana modello').click(function(){
			setModelWeek(this);
		});
	}
});