Vetstoria.session = new(new Class({
	__construct: function () {

		this.user = {}; // {id, identifier, type, hash}
		this.subuser = {}; // {id, type, hash}
		this.set = false;
		this.subsession_set = false
		this.timer_interval = 600; //in seconds
	},

	/**
	 * Complete frontend session management
	 * @version 1.0
	 */
	init: function () {
		console.log('Vetstoria.session:', 'Session init');

		if (this.is_set(true)) this.get(true);

		console.log('Vetstoria.session.init:', 'session set status :', this.is_set());
		console.log('Vetstoria.session.init:', this.user.type, '/', this.user.id);
		
		if(this.get().type == 'clinic') {
			if(!this.subsession_is_set(true)) {
				console.log('Vetstoria.session : Subsession isn\'t set, setting temporary a defaut subsession');
				//this.switch_subuser(52, 'password', '');
				Vetstoria.usermenu.switch_subuser_facebox(true);
			}
			else{
				this.get_subuser(true);
			}
		}
		
		//Disabled. We will use a javascript push engine's function
		//this.timer_check_validity();
	},

	/**
	 * Check if we are logged.
	 * @deprecated : use is_set()
	 */
	is_logged: function (force) {
		return this.is_set(force);
	},

	/**
	 * Check if we are logged.
	 * @version 1.0
	 */
	is_set: function (force) {
		if (force) {
			this.set = Vetstoria.json_command('session/is_set').data[0].is_set;
		}

		return this.set;
	},

	/**
	 * Check if the subsession is set
	 * @version 1.0
	 */
	subsession_is_set: function (force) {

		if (force) {
			this.subsession_set = Vetstoria.json_command('session/subsession/is_set').data[0].is_set;
		}

		return this.subsession_set;
	},

	/**
	 * Alias of Vetstoria.session.subsession_is_set()
	 * @version 1.0
	 */
	is_subsession_set: function (force) {
		this.subsession_is_set(force);
	},

	/**
	 * get session data
	 * @version 1.0
	 */
	get: function (refresh_) {

		if (!this.set) {
			console.log('Vetstoria.session.get:', 'You have to be logged in to continue...');
			return false;
		}

		if (refresh_) {

			var q = Vetstoria.json_command('session/get');

			if (q.state != 0) {
				console.log('Vetstoria.session.get:', 'Refresh error');
				//Vetstoria.contextualmenu.display_menu();
				//Vetstoria.layout.display_login_msg();
				return false;
			}

			this.user = q.data[0];
			

/*
					if (this.user.type == 'clinic') {
						this.getSubUserID(true);
						console.log('Vetstoria.session.init:',
								'Your sub user id is ', this.subuser_id);
					} else if (this.data.session_type == "petowner") {
						Vetstoria.contextualmenu.get_pet_members();
					}
					
					*/

/*
					Vetstoria.contextualmenu.init();
					Vetstoria.notification.init();
					Vetstoria.privatemessages.get_contextualmenu_messages();
					// Vetstoria.layout.display_login_msg(this.data.session_type);
					*/
		}
		return this.user;
	},
	/**
	 * Check session every 1 min
	 * @version 1.0
	 */
	timer_check_validity: function () {

		if (this.timer_interval < 1) {
			this.timer_interval = 1;
			console.log("Vetstoria.session.timer_check_validity : timer_interval was incorrect. Set to one second.");
		}

		var ptr = this;

		console.log("Vetstoria.session.timer_check_validity : launched (" + (this.timer_interval) + "s)");

		setInterval(function () {
			ptr.check_validity();
		}, this.timer_interval * 1000);
	},

	/**
	 * Check session validity change. This is for the case we login/logout from another tab/window
	 * @version 1.0
	 */
	check_validity: function () {
		console.log("Vetstoria.session.check_validity : checking...");

		var previous_value = Vetstoria.session.is_set(false);
		var new_value = Vetstoria.session.is_set(true);

		if (previous_value != new_value) {
			console.log('Vetstoria.session.check_validity:', 'Session validity changed');

			if (new_value == false) console.log('Vetstoria.session.check_validity:', 'You are not logged in anymore !');

			if (new_value == true) console.log('Vetstoria.session.check_validity:', 'You are now logged in !');

			console.log('Vetstoria.session.check_validity: launching Vetstoria.session.on_session_validity_change()')

			this.on_session_validity_change(previous_value, new_value);

		}
		else {
			//console.log("Vetstoria.session.check_validity: ...no change !");
		}

	},

	/**
	 * this function is launched when a session validity change is detected
	 * @version 1.0
	 */
	on_session_validity_change: function (previous_value, new_value) {
		console.log('Vetstoria.session.on_session_validity_change: redirection to home in 10 sec');
		setTimeout(function () {
			Vetstoria.redirect('home');
		}, 10000);
	},

	/**
	 * @deprecated : bad name
	 */
	reload_session_data: function () {
		return this.timer_check_validity();
	},

	/**
	 * Try to login
	 * @version 1.0
	 */
	login: function (identifier, password, remember_me) {
		console.log('Vetstoria.session:', 'Login...');

		if (this.is_set()) {
			console.log('Vetstoria.session.login:', 'You are already logged in !');
			Vetstoria.session.logout();
		}

		if (!identifier || !password) {
			console.log('Vetstoria.session.login:', 'Error : identifier or password missing');
			return false;
		}

		console.log('Vetstoria.session.login:', 'remember = ' + ((!remember_me) ? false : true));

		var json_data = Vetstoria.json_command('session/login', {
			'identifier': identifier,
			'password': password,
			'remember_me': remember_me
		});

		if (!json_data || json_data.state == 1) {
			console.log('Vetstoria.session.login : error ! password forgot or bug');
			return false;
		}

		this.user = json_data.data[0];

		//Disabling cookie for remembering identified
		//$.cookie("Vetstoria.basic", identifier, { expires : 5, path    : '/' });		

		console.log('Vetstoria.session.login:', 'Login successful');
		console.log('Vetstoria.session.login:', 'Logged as : ' + this.user.id + '');

		this.set = true;

		return true;
	},

	/**
	 * Logout
	 */
	logout: function () {

		console.log('Vetstoria.session:', 'Logout ...');
		
		/*
		$.removeJSONCookie('Vetstoria.session', {
			path: '/'
		});
		*/

		// clean everything
		this.user = {};
		this.subuser = {};
		this.set = false;
		this.subsession_set = false;

		return Vetstoria.json_command('session/logout');

	},

	/**
	 * Switch from one team profile to another Corresponding to the "use
	 * this team profile" use case
	 * @version 1.0
	 */
	switch_subuser: function (subuser_id, password, using_clear_password) {

		console.log('Vetstoria.session : ', ' switch subuser');
		console.log('Vetstoria.session.switch_subuser:', 'subuser_id = ', subuser_id, ', password = ', password, ', using_clear_password = ', using_clear_password);

		if (!subuser_id) return false;
		if (!password) password = '';
		if (!using_clear_password) using_clear_password = '';

		var json = Vetstoria.json_command('session/subsession/switch', {
			'id': subuser_id,
			'password': password,
			'clear_password': using_clear_password
		});

		if(!json) return false;
		
		if (json.state == 1) {
			console.log('Vetstoria.session.switch_subuser:', 'switch error');
			
			if(json.data) console.log(json.data);
			
			return false;
		}

		this.subuser = json.data[0];
		this.subsession_set = true;

		return true;
	},
	
	/**
	 * Get sub user information
	 * @version 1.0
	 */
	get_subuser: function (refresh_) {

		if (!this.set) {
			console.log('Vetstoria.session.get_subuser:', 'You have to be logged in to continue...');
			return false;
		}

		if (refresh_) {

			var q = Vetstoria.json_command('session/subsession/get');

			if (!q || q.state != 0) {
				console.log('Vetstoria.session.get_subuser:', 'Refresh error');
				return false;
			}

			this.subuser = q.data[0];
		}

		return this.subuser;
	},

	/**
	 * get the current sub user id
	 * @version 1.0
	 */
	get_subuser_id: function () {
		if (!this.subsession_is_set()) return false;

		return this.subuser.id;
	},
	/**
	 * get the current sub user type
	 * @version 1.0
	 */
	get_subuser_type: function () {
		if (!this.subsession_is_set()) return false;

		return this.subuser.type;
	},

	/**
	 * @deprecated : bad name
	 */
	getSubUserID: function () {
		return this.get_subuser_id();
	},
	/**
	 * @deprecated : bad name
	 */
	getSubUserType: function () {
		return this.get_subuser_type();
	}

}));
