var LogoutHandler = Class.create();
LogoutHandler.prototype = {
	// true se è stata rilevata una condizione in cui l'unload della pagina dev'essere considerato come chiusura della sessione
	doLogout: false,
	
	// true se l'utente ha confermato la chiusura della pagina
	closing: false,
	
	// true se il browser è stato riconosciuto come MS Internet Explorer
	is_ie: false,

	initialize: function() {
		var agent = navigator.userAgent.toLowerCase();
		this.is_ie = (agent.indexOf('msie') != -1);

		// common handlers
		Event.observe(window, "beforeunload", this.winBeforeUnload.bindAsEventListener(this));
		Event.observe(document, "keypress", this.setDoLogoutFalse.bindAsEventListener(this));
		Event.observe(document, "click", this.setDoLogoutFalse.bindAsEventListener(this));
		window.onunload = this.winUnload.bindAsEventListener(this);
		
		if(this.is_ie) {
			// handlers for MS IE
			Event.observe(document, "mouseout", this.checkMouseOut.bindAsEventListener(this));
			this.doLogout = true;
		} else if(agent.indexOf('gecko') != -1) {
			// handlers for gecko browsers
			Event.observe(document, "mouseout", this.setDoLogoutTrue.bindAsEventListener(this));
			Event.observe(document, "mouseover", this.setDoLogoutFalse.bindAsEventListener(this));
			this.doLogout = true;
		}
	},
	
	checkMouseOut: function(event) {
		if(this.is_ie && (event.clientY < 0))
			this.doLogout = true;
	},
	
	setDoLogoutTrue: function() {
		this.doLogout = true;
	},
	
	setDoLogoutFalse: function() {
		this.doLogout = false;
	},
	
	exit: function(event) {
		//The _exitPath_ variable is rendered by the 
		//jeffs3 servlet in /jeffs3/initialize.js
		var myAjax = new Ajax.Request(
			_exitPath_, 
			{
				method: 'get', 
				asynchronous: false, 
				onComplete: function() {return true;}
			}
		);
	},
	
	winBeforeUnload: function (event) {
		this.closing = false;
		if(this.doLogout && (!this.is_ie || (event.clientY < 0))) {
			this.closing = true;
			event.returnValue = _logoutMessage_;
		}
	},
	
	winUnload: function (event) {
		if(this.closing) {
			this.exit();
		}
	}
}

var _logoutHandler_ = new LogoutHandler();
