#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('myapp:server');
var http = require('http');

var jsonsrv = require('../lib/jsonsrv');
var pcalutils = require('../lib/pcalutils');

var jade = require('jade');

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Create HTTP server
 */

var server = http.createServer(app);

/**
 * Creatie socket.io
 */
var io = require('socket.io')(server);
var sharedsession = require("express-socket.io-session");

io.use(sharedsession(app.locals.session, {autoSave: true}));

function pentry_from_session(session, data) {
	if(typeof session.cache.days[data.day] === 'undefined')
	{
		console.log('pentry_from_session: day ', data.day, ' not defined!');
		return null;
	}

	switch(data.pentrytype) {
		case "event":
			if(typeof session.cache.days[data.day].events[data.pentry] === 'undefined') {
				console.log('pentry_from_session: event ', data.pentry, ' not defined in day ', data.day, '!');
				return null;
			}
			return session.cache.days[data.day].events[data.pentry];
		case "tevent":
			if(typeof session.cache.days[data.day].events[data.parent_event] === 'undefined') {
				console.log('pentry_from_session: event ', data.parent_event, ' not defined in day ', data.day, '!');
				return null;
			}
			if(typeof session.cache.days[data.day].events[data.parent_event].thereafter[data.pentry] === 'undefined') {
				console.log('pentry_from_session: thereafter ', data.pentry, ' of event ', data.parent_event, ' not defined in day ', data.day, '!');
				return null;
			}
			return session.cache.days[data.day].events[data.parent_event].thereafter[data.pentry];
		case "away":
		case "keep_in_mind":
		case "todo":
		case "vehicle_use":
			if(typeof session.cache.days[data.day][data.pentrytype][data.pentry] === 'undefined') {
				console.log('pentry_from_session: ', data.pentrytype, ' ', data.pentry, ' not defined in day ', data.day, '!');
				return null;
			}
			return session.cache.days[data.day][data.pentrytype][data.pentry];
		default:
			console.log('unknown pentry-type: ', data.pentrytype);
			return null;
	}

	console.log('pentry_from_session: no pentry-type found in data: ', data);
	return null;
}

function event_from_session(session, data) {
	return pentry_from_session(session, data);
	/*if(typeof session.cache.days[data.day] === 'undefined')
	{
		console.log('event_from_session: day ', data.day, ' not defined!');
		return null;
	}
	if(typeof session.cache.days[data.day].events[data.event] === 'undefined')
	{
		console.log('event_from_session: event ', data.event, ' not defined in day ', data.day, '!');
		return null;
	}

	if(data.pentrytype === "tevent")
	{
		if(typeof session.cache.days[data.day].events[data.event].thereafter[data.thereafter] === 'undefined')
		{
			console.log('event_from_session: thereafter ', data.thereafter, ' of event ', data.event, ' not defined in day ', data.day, '!');
			return null;
		}
		return session.cache.days[data.day].events[data.event].thereafter[data.thereafter];
	}

	return session.cache.days[data.day].events[data.event];*/
}

function get_element_of_array_by_uid(array, uid) {
	for(idx in array)  {
		if(array[idx].uid === uid)
			return array[idx];
	}
	return null;
}

generateUID = function() {
	return ("000000" + (Math.random()*Math.pow(36,6) << 0).toString(36)).slice(-6)
}

function get_role_from_uid(event, uid) {
	return get_element_of_array_by_uid(event.involved_roles, uid);
}

function get_involved_from_event(event, role_uid) {
	if(role_uid !== '') {
		var role = get_role_from_uid(event, role_uid);
		if(role)
			return role.involved;
		else {
			console.log("WARNING: get_involved_from_event: Could not find role: " + role_uid);
			return null;
		}
	}

	return event.involved;
}

function remove_from_array_by_uid(array, uid) {
	var found = false;
	var idx;
	for(idx in array) {
		if(array[idx].uid === uid) {
			found = true;
			break;
		}
	}

	if(found)
		array.splice(idx, 1);

	return found;
}

function get_rendered_jsonerror(result, session) {
	var session_ended = false;
	if(result.result === "ERROR_invalid_session") {
		session.destroy();
		session_ended = true;
	}

	messages = result.messages;

	if(session.messages)
		messages = messages.concat(session.messages);

	console.log(messages);

	if(messages.length === 0)
		messages.push({type: "danger", title: "Systemfehler", message: "Es wurde ein Fehler in der Verarbeitung festgestellt, aber keine Fehlermeldung erstellt."});

	session.messages = [];

	return jade.renderFile('views/errorview_inlay.jade', { messages: messages, is_error: true, session_ended: session_ended});
}

function get_rendered_jsonmessage(result, session) {

	messages = result.messages;

	if(session.messages)
		messages = messages.concat(session.messages);

	if(messages.length === 0)
		return "";

	session.messages = [];

	return jade.renderFile('views/errorview_inlay.jade', { messages: messages, is_error: false, session_ended: false});
}

function get_rendered_pcalmessage(message) {
	var messages = [];
	messages.push(message);
	return jade.renderFile('views/messageview_inlay.jade', { messages: messages });
}

function get_rendered_error(error) {
	return jade.renderFile('views/error_inlay.jade', {message: error.message, error: error});
}

function send_rendered_event(socket, data, event) {
	var is_thereafter = false;
	var event_href = "/event/" + data.day + "/" + data.pentry;

	if(data.pentrytype === "tevent") {
		is_thereafter = true;
		event_href = "/tevent/" + data.day + "/" + data.parent_event + "/" + data.pentry;
	}

	jade.renderFile('views/edit_event_main.jade',
			{ 	date: socket.handshake.session.cache.days[data.day].date,
				event: event,
				event_href : event_href,
				is_thereafter : is_thereafter,
				parent_event : (is_thereafter ? socket.handshake.session.cache.days[data.day].events[data.parent_event] : {}),
				edit_type: (event.uuid.substr(0,4) === "new_" ? "erstellen" : "bearbeiten"),
				messages : data.messages,
				pcalview : data.pcalview
			}, function(error, html) {
					if(error)
						socket.emit('get_rendered_pentry_result', { result: "ERROR",  html: get_rendered_error(error) });
					else
						socket.emit('get_rendered_pentry_result', { result: "OK",  html: html });
				});
}

function send_rendered_away(socket, data, away) {
	jade.renderFile('views/edit_away_main.jade',
			{ 	date: socket.handshake.session.cache.days[data.day].date,
				away: away,
				away_href : "/away/" + data.day + "/" + data.pentry,
				edit_type: (away.uuid.substr(0,4) === "new_" ? "erstellen" : "bearbeiten"),
				messages : data.messages
			}, function(error, html) {
					if(error)
						socket.emit('get_rendered_pentry_result', { result: "ERROR",  html: get_rendered_error(error) });
					else
						socket.emit('get_rendered_pentry_result', { result: "OK",  html: html });
				});
}

function send_rendered_keep_in_mind(socket, data, keep_in_mind) {
	jade.renderFile('views/edit_keep_in_mind_main.jade',
			{ 	date: socket.handshake.session.cache.days[data.day].date,
				keep_in_mind: keep_in_mind,
				keep_in_mind_href : "/keep_in_mind/" + data.day + "/" + data.pentry,
				edit_type: (keep_in_mind.uuid.substr(0,4) === "new_" ? "erstellen" : "bearbeiten"),
				messages : data.messages
			}, function(error, html) {
					if(error)
						socket.emit('get_rendered_pentry_result', { result: "ERROR",  html: get_rendered_error(error) });
					else
						socket.emit('get_rendered_pentry_result', { result: "OK",  html: html });
				});
}

function send_rendered_todo(socket, data, todo) {
	jade.renderFile('views/edit_todo_main.jade',
			{ 	date: socket.handshake.session.cache.days[data.day].date,
				todo: todo,
				todo_href : "/todo/" + data.day + "/" + data.pentry,
				edit_type: (todo.uuid.substr(0,4) === "new_" ? "erstellen" : "bearbeiten"),
				messages : data.messages
			}, function(error, html) {
					if(error)
						socket.emit('get_rendered_pentry_result', { result: "ERROR",  html: get_rendered_error(error) });
					else
						socket.emit('get_rendered_pentry_result', { result: "OK",  html: html });
				});
}

function send_rendered_vehicle_use(socket, data, vehicle_use) {
	jade.renderFile('views/edit_vehicle_use_main.jade',
			{ 	date: socket.handshake.session.cache.days[data.day].date,
				vehicles : socket.handshake.session.cache.vehicles,
				vehicle_use : vehicle_use,
				vehicle_use_href : "/vehicle_use/" + data.day + "/" + data.pentry,
				edit_type: (vehicle_use.uuid.substr(0,4) === "new_" ? "erstellen" : "bearbeiten"),
				messages : data.messages
			}, function(error, html) {
					if(error)
						socket.emit('get_rendered_pentry_result', { result: "ERROR",  html: get_rendered_error(error) });
					else
						socket.emit('get_rendered_pentry_result', { result: "OK",  html: html });
				});
}

function send_rendered_pentry(socket, data, pentry) {
	socket.handshake.session.save();
	switch(data.pentrytype)
	{
		case "event":
		case "tevent":
			send_rendered_event(socket, data, pentry);
			break;
		case "away":
			send_rendered_away(socket, data, pentry);
			break;
		case "keep_in_mind":
			send_rendered_keep_in_mind(socket, data, pentry);
			break;
		case "todo":
			send_rendered_todo(socket, data, pentry);
			break;
		case "vehicle_use":
			send_rendered_vehicle_use(socket, data, pentry);
			break;
		default:
			console.log('send_rendered_pentry: unknown pentrytype: ', data.pentrytype);
	}
}

function init_emit_messages(data) {
	data.messages = {
		other : [],
		locations : [],
		involved : { primary: [] }
	}
}

io.on('connection',function(socket){
	console.log('NEW WEBSOCKET-CONNECTION');

	if(typeof socket.handshake.session.sessionuuid === 'undefined') {
		console.log('A socket with sessionID ' + socket.handshake.session.sessionuuid + ' connected!');
		//return; // no furcer proceeding!!!
		socket.emit('invalid_session_data', {data: socket.handshake.session.sessionuuid});
	}

	console.log('A socket with sessionID ' + socket.handshake.session.sessionuuid + ' connected!');

	socket.on('day_goto', function(data) {
		var jsondata =
			{
				"request"		: "get_parishday",
				"format"		: "day",
	 			"date"			: data.date,
				"sessionuuid"   : socket.handshake.session.sessionuuid
			};

		jsonsrv.do_jsonsrv2(jsondata,
			function(result) {
				if(result.result === "OK" || result.result === "OK_invalid_date") {
					var params = pcalutils.do_day_renderparams_from_result(result, socket.handshake.session);

					jade.renderFile('views/daycontent.jade', params, function(error, html) {
									if(error) {
										socket.emit('day_goto_result', { result: "ERROR",  html: get_rendered_error(error), date: result.date.date });
									}
									else
										socket.emit('day_goto_result', { result: "OK",  html: html, date: result.date.date });
								});
				}
				else
					socket.emit('day_goto_result', { result: "ERROR",  html: get_rendered_jsonerror(result, socket.handshake.session), date: data.date });
			},
			function(error) {
				socket.emit('day_goto_result', { result: "ERROR",  html: get_rendered_error(error), date: data.date });;
			});
	});

	/*socket.on('day_goto_timeline', function(data) {
		var jsondata =
			{
				"request"		: "get_parishday",
				"format"		: "timeline",
				"date"			: data.date,
				"sessionuuid"   : socket.handshake.session.sessionuuid
			};

		console.log(data);

		jsonsrv.do_jsonsrv2(jsondata,
			function(result) {
				if(result.result === "OK" || result.result === "OK_invalid_date") {
					var params = pcalutils.do_day_renderparams_from_result(result, socket.handshake.session);

					jade.renderFile('views/timelinecontent.jade', params, function(error, html) {
									if(error) {
										socket.emit('day_goto_result', { result: "ERROR",  html: get_rendered_error(error), date: result.date.date, scrollto: '' });
									}
									else
										socket.emit('day_goto_result', { result: "OK",  html: html, date: result.date.date, scrollto: data.scrollto  });
								});
				}
				else
					socket.emit('day_goto_result', { result: "ERROR",  html: get_rendered_jsonerror(result, socket.handshake.session), date: data.date, scrollto: '' });
			},
			function(error) {
				socket.emit('day_goto_result', { result: "ERROR",  html: get_rendered_error(error), date: data.date, scrollto: '' });;
			});
	});

	socket.on('day_goto_pastoralteam', function(data) {
		var jsondata =
			{
				"request"		: "get_parishday",
				"format"		: "pastoralteam",
				"date"			: data.date,
				"sessionuuid"   : socket.handshake.session.sessionuuid
			};

		console.log(data);

		jsonsrv.do_jsonsrv2(jsondata,
			function(result) {
				if(result.result === "OK" || result.result === "OK_invalid_date") {
					var params = pcalutils.do_day_renderparams_from_result(result, socket.handshake.session);

					jade.renderFile('views/pastoralteamcontent.jade', params, function(error, html) {
									if(error) {
										socket.emit('day_goto_result', { result: "ERROR",  html: get_rendered_error(error), date: result.date.date, scrollto: '' });
									}
									else
										socket.emit('day_goto_result', { result: "OK",  html: html, date: result.date.date, scrollto: data.scrollto  });
								});
				}
				else
					socket.emit('day_goto_result', { result: "ERROR",  html: get_rendered_jsonerror(result, socket.handshake.session), date: data.date, scrollto: '' });
			},
			function(error) {
				socket.emit('day_goto_result', { result: "ERROR",  html: get_rendered_error(error), date: data.date, scrollto: '' });;
			});
	});*/

	socket.on('day_show_event', function(data) {
		var jsondata =
			{
				"request"		: "event_details",
				"sessionuuid"   : socket.handshake.session.sessionuuid,
			    "date"			: data.date,
				"event"			: data.event
			};

		jsonsrv.do_jsonsrv2(jsondata,
			function(result) {
				if(result.result === "OK")
					jade.renderFile("views/timeline_eventdetails.jade", { date: result.date, litinfo: result.litinfo, event: result.event }, function(error, html) {
						if(error) {
							socket.emit('day_show_event_result', { result: "ERROR",  html: get_rendered_error(error), date: result.date.date, event: data.event });
						}
						else
							socket.emit('day_show_event_result', { result: "OK",  html: html, date: result.date.date, event: data.event });
					});
				else
					socket.emit('day_show_event_result', { result: "ERROR",  html: get_rendered_jsonerror(result, socket.handshake.session), date: data.date, event: data.event });
			},
			function(error) {
				socket.emit('day_show_event_result', { result: "ERROR",  html: get_rendered_error(error), date: data.date, event: data.event });;
			});
	});


	socket.on('week_goto', function(data) {
		var jsondata =
			{
				"request"		: "get_parishweek",
	 			"date"			: data.basedate,
				"sessionuuid"   : socket.handshake.session.sessionuuid
			};

		jsonsrv.do_jsonsrv2(jsondata,
			function(result) {
				if(result.result === "OK" || result.result === "OK_invalid_date") {
					var params = pcalutils.do_week_renderparams_from_result(result, socket.handshake.session);

					jade.renderFile('views/weekcontent.jade', params, function(error, html) {
									if(error) {
										socket.emit('week_goto_result', { result: "ERROR",  html: get_rendered_error(error), basedate: result.basedate });
									}
									else
										socket.emit('week_goto_result', { result: "OK",  html: html, basedate: result.basedate });
								});
				}
				else
					socket.emit('week_goto_result', { result: "ERROR",  html: get_rendered_jsonerror(result, socket.handshake.session), basedate: data.date });
			},
			function(error) {
				socket.emit('week_goto_result', { result: "ERROR",  html: get_rendered_error(error), basedate: data.date });;
			});
	});

	socket.on('tevent_move_updown', function(data) {
		var jsondata = 	{
				"request"		: "move_thereafterevent_updown",
				"sessionuuid"   : socket.handshake.session.sessionuuid,
				"date"			: data.date,
				"event"			: data.event,
				"thereafter"	: data.tevent,
				"updown"		: data.updown
			};

		jsonsrv.do_jsonsrv2(jsondata,
			function(result) {
				if(result.result === "OK")
					socket.emit('tevent_move_updown_result', { result: "OK" });
				else
					socket.emit('tevent_move_updown_result', { result: "ERROR" });
			},
			function(error){console.log('ERROR: ', error);});

		console.log(data);
	});

	socket.on('tevent_delete', function(data) {
		console.log('tevent_delete: ', data);
		var jsondata = 	{
				"request"		: "delete_thereafter",
				"sessionuuid"   : socket.handshake.session.sessionuuid,
				"date"			: data.date,
				"event"			: data.event,
				"thereafter"	: data.tevent
			};

		jsonsrv.do_jsonsrv2(jsondata,
			function(result) {
				if(result.result === "OK")
					socket.emit('tevent_delete_result', { result: "OK", event: data.event, tevent: data.tevent });
				else
					socket.emit('tevent_delete_result', { result: "ERROR", event: data.event, tevent: data.tevent });
			},
			function(error){console.log('ERROR: ', error);});
	});

	socket.on('event_delete', function(data) {
		console.log('tevent_delete: ', data);
		var jsondata = 	{
				"request"		: "delete_thereafter",
				"sessionuuid"   : socket.handshake.session.sessionuuid,
				"date"			: data.date,
				"event"			: data.event
			};

		jsonsrv.do_jsonsrv2(jsondata,
			function(result) {
				if(result.result === "OK")
					socket.emit('tevent_delete_result', { result: "OK", event: data.event, tevent: data.tevent });
				else
					socket.emit('tevent_delete_result', { result: "ERROR", event: data.event, tevent: data.tevent });
			},
			function(error){console.log('ERROR: ', error);});
	});

	socket.on('pentry_delete', function(data) {
		console.log('pentry_delete: ', data);
		var jsondata = {
				"request" 		: "pentry_delete",
				"sessionuuid" 	: socket.handshake.session.sessionuuid,
				"date"			: data.date,
				"pentrytype"	: data.pentrytype,
				"uuid"			: data.uuid
			};

		jsonsrv.do_jsonsrv2( jsondata,
			function(result) {
				var resultdata = { uuid: data.uuid, pentrytype: data.pentrytype, date: data.date };
				if(result.result === "OK") {
					resultdata.result = "OK";
					resultdata.message = get_rendered_jsonmessage(result, socket.handshake.session);
				}
				else {
					resultdata.result = "ERROR";
					resultdata.message = get_rendered_jsonerror(result, socket.handshake.session);
				}
				socket.emit('pentry_delete_result', resultdata);
			},
			function(error) {
				socket.emit('pentry_delete_result', {result: "ERROR", message: get_rendered_error(error)});
			});
	});

	socket.on('get_rendered_event', function(data) {
		console.log('get_rendered_event')
		init_emit_messages(data);
		var event = pentry_from_session(socket.handshake.session, data);
		send_rendered_event(socket, data, event);
	});

	socket.on('get_rendered_away', function(data) {
		init_emit_messages(data);
		var away = pentry_from_session(socket.handshake.session, data);
		send_rendered_away(socket, data, away);
	});

	socket.on('get_rendered_keep_in_mind', function(data) {
		init_emit_messages(data);
		var keep_in_mind = pentry_from_session(socket.handshake.session, data);
		send_rendered_keep_in_mind(socket, data, keep_in_mind);
	});

	socket.on('get_rendered_todo', function(data) {
		init_emit_messages(data);
		var todo = pentry_from_session(socket.handshake.session, data);
		send_rendered_todo(socket, data, todo);
	});

	socket.on('get_rendered_vehicle_use', function(data) {
		init_emit_messages(data);
		var vehicle_use = pentry_from_session(socket.handshake.session, data);
		send_rendered_vehicle_use(socket, data, vehicle_use);
	});

	socket.on('render_pastoralunitselector', function(data) {
		var jsondata = {
				"request"		: "get_all_pastoralunits",
				"sessionuuid"   : socket.handshake.session.sessionuuid
			};

		jsonsrv.do_jsonsrv2(jsondata,
			function(result) {
				if(result.result === "OK") 	{
					var event = pentry_from_session(socket.handshake.session, data);
					var html = jade.renderFile("./views/pastoralunitselector_inlay.jade", {
															actual_punit_dn : event.punit.dn,
															actual_punit_name: event.punit.name,
															pastoralunits: result.pastoralunits
					});
					socket.emit('render_pastoralunitselector_result', { result: "OK", html: html});
				}
				else
					socket.emit('render_pastoralunitselector_result', { result: "ERROR", html: ""});
			},
			function(error){console.log('ERROR: ', error);});
	});

	socket.on('pentry_set_pastoralunit', function(data) {
		console.log(data);
		var pentry = pentry_from_session(socket.handshake.session, data);
		init_emit_messages(data);

		if(pentry) {
			pentry.punit.dn   = data.data.punit.dn;
			pentry.punit.name = data.data.punit.name;
			data.messages.other.push({ type: "success", title: "Kontext erfolgreich geändert", message: "Der Kontext wurde erfolgreich auf '" + data.data.punit.name + "' geändert." });
		}
		else
			data.messages.other.push({ type: "danger", title: "Kalendereintrag nicht gefunden", message: "Konnte keinen Kalendereintrag zu dieser Bearbeitung finden. Schwerer Fehler!" });

		send_rendered_pentry(socket, data, pentry);
	});

	socket.on('render_locationselector', function(data) {
		var jsondata =
			{
				"request"	: "get_all_predefined_locations",
				"sessionuuid": socket.handshake.session.sessionuuid,
				"omitt"		: []
			};

		var event = pentry_from_session(socket.handshake.session, data);

		for(idx in event.locations) {
			var loc = event.locations[idx];
			if(loc.id != "other")
				jsondata.omitt.push(loc.id);
		}

		jsonsrv.do_jsonsrv2(jsondata,
			function(result) {
				if(result.result === "OK") 	{
					var html = jade.renderFile("views/locationselector_inlay.jade", {
													pentry_edit_base: "PENTRYBASE",
													units: result.locations
												});
					socket.emit('render_locationselector_result', { result: "OK", html: html});
				}
				else
					socket.emit('render_locationselector_result', { result: "ERROR", html: ""});
			},
			function(error) {
				console.log(error);
			});
	});

	socket.on('render_actorselector', function(data) {
		var jsondata = 	{
				"request"		: "get_all_actors",
				"sessionuuid"	: socket.handshake.session.sessionuuid,
				"omitt"			: [],
				"date"			: data.day,
				"pentry"		: data.pentry
			};

		var role = '';

		var pentry = pentry_from_session(socket.handshake.session, data);

		if(data.pentrytype !== "away") {
			var the_involved = pentry.involved;
			if(data.pentrytype === "event" || data.pentrytype === "tevent") {
				role = data.data.role;
				console.log('ADD ACTOR FOR ROLE '+role);
				the_involved = get_involved_from_event(pentry, role);
			}

			for(a in the_involved) {
				var actor = the_involved[a];
				if(actor.id !== "other" && actor.id !== "dn")
					jsondata.omitt.push(actor.id);
			}
		}

		jsonsrv.do_jsonsrv2(jsondata,
			function(result) {
				if(result.result === "OK") {
					var renderdata = { units: result.actors, for_role: role };
					if(data.pentrytype === "away") {
						renderdata.actual_actor_id = data.data.actual_actor_id;
						renderdata.actual_actor_name = data.data.actual_actor_name;
					}
					var html = jade.renderFile("./views/actorselector_inlay.jade", renderdata);

					socket.emit('render_actorselector_result', {result: "OK", html: html});
				}
				else
					socket.emit('render_actorselector_result', {result: "ERROR", html: ""});
			},
			function(error) {
				console.log(error);
			});
	});

	socket.on('render_parishdbpersongroupselector', function(data) {
		var jsondata = {
				"request" : "get_parishdbelems_flat",
				"sessionuuid"	: socket.handshake.session.sessionuuid
		};

		var role = '';
		if(data.pentrytype === "event" || data.pentrytype === "tevent") {
			role = data.data.role;
			console.log('ADD ACTOR FOR ROLE '+role);
		}

		jsonsrv.do_jsonsrv2(jsondata,
			function(result) {
				if(result.result === "OK") {

					for(idx in result.parishdb) {
						result.parishdb[idx].uid = generateUID();

						if(result.parishdb[idx].type === "group") {
							for(midx in result.parishdb[idx].members)
								result.parishdb[idx].members[midx].uid = generateUID();
						}
					}


					jade.renderFile('./views/parishdbpersongroupselector_inlay.jade',
									{ parishdb: result.parishdb, for_role: role }, function(error, html) {
									if(error) {
										socket.emit('render_parishdbpersongroupselector_result', { result: "ERROR",  html: get_rendered_error(error) });
									}
									else
										socket.emit('render_parishdbpersongroupselector_result', { result: "OK",  html: html });
								});
				}
				else
					socket.emit('render_parishdbpersongroupselector_result', {result: "ERROR", html: ""});
			},
			function(error) {
				console.log(error);
			});
	});

	socket.on('render_locationeditor', function(data) {
		var pentry = pentry_from_session(socket.handshake.session, data);

		console.log(data);
		console.log(pentry.locations);

		if(data.data.type === 'edit') {
			location_uid = data.data.location;
			location = get_element_of_array_by_uid(pentry.locations, location_uid);
		}
		else
			location = { name:"", sign:"", uid:""};

		console.log(location);

		var html = jade.renderFile("./views/locationeditor_inlay.jade", {
											type: data.data.type,
											location: location
									});

		socket.emit('render_locationeditor_result', {result: "OK", html: html});
	});

	socket.on('render_involvededitor', function(data) {
		var role = '';

		var pentry = pentry_from_session(socket.handshake.session, data);

		var the_involved = pentry.involved;
		if(data.pentrytype === "event" || data.pentrytype === "tevent") {
			role = data.data.role;
			console.log('ADD/EDIT FOR ROLE '+role);
			the_involved = get_involved_from_event(pentry, role);
		}
		var involved = {};
		if(data.data.type === 'edit') {
			involved_uid = data.data.involved;
			involved = get_element_of_array_by_uid(the_involved, involved_uid);
		}
		else
			involved = { group:"", forename:"", surname:"", street:"", street_nr:"", postalcode:"", location:"", email:"", telephonenumber:"", uid:""};

		var html = jade.renderFile("./views/involvededitor_inlay.jade", {
											type: data.data.type,
											involved: involved,
											for_role: role
									});

		socket.emit('render_involvededitor_result', {result: "OK", html: html});
	});

	function add_edit_involved(type, data) {
		var pentry = pentry_from_session(socket.handshake.session, data);
		init_emit_messages(data);

		if(pentry) {
			if(data.pentrytype === "away") {
				// special treatment here!
				pentry.name = data.data.involved.name;
				pentry.involveddb_id = data.data.involved.id;
				data.messages.involved['primary'].push({ type: "success", title: "Abwesende Person gesetzt", message: "'" + data.data.involved.name + "' wurde erfolgreich als abwesend gesetzt." });
				send_rendered_away(socket, data, pentry);
				return;
			}

			console.log(data.data.involved);

			var the_involved = pentry.involved;
			var role = '';
			if(data.pentrytype === "event" || data.pentrytype === "tevent") {
				role = data.data.involved.for_role;
				if(role !== '')
					data.messages.involved[role] = [];
				the_involved = get_involved_from_event(pentry, data.data.involved.for_role);
				delete data.data.involved.for_role;
			}
			if(role === '')
				role = 'primary';
			if(the_involved) {
				switch(type) {
					case 'add':
						data.data.involved.uid = generateUID();
						the_involved.push(data.data.involved);
						data.messages.involved[role].push({ type: "success", title: "Betroffenen erfolgreich hinzugefügt", message: "'" + data.data.involved.name + "' wurde erfolgreich hinzugefügt." });
						break;
					case 'edit':
						var inv = get_element_of_array_by_uid(the_involved, data.data.involved.uid);
						if(inv) {
							inv.name = data.data.involved.name;
							inv.group = data.data.involved.group;
							inv.surname = data.data.involved.surname;
							inv.forename = data.data.involved.forename;
							inv.street = data.data.involved.street;
							inv.street_nr = data.data.involved.street_nr;
							inv.postalcode = data.data.involved.postalcode;
							inv.location = data.data.involved.location;
							inv.email = data.data.involved.email;
							inv.telephonenumber = data.data.involved.telephonenumber;

							data.messages.involved[role].push({ type: "success", title: "Betroffenen erfolgreich bearbeitet", message: "'" + data.data.involved.name + "' wurde erfolgreich bearbeitet." });
						}
						else
							data.messages.involved.primary.push({ type: "danger", title: "Betroffener nicht geändert", message: "'" + data.data.involved.name + "' konnte über seine UID keinem Eintrag zugeordnet werden; Bearbeitung verworfen!" });
						break;
				}
			}
			else
				data.messages.involved.primary.push({ type: "danger", title: "Dienst nicht gefunden", message: "'" + data.data.involved.name + "' wurde nicht hinzugefügt, weil der angegebene Dienst nicht gefunden werden konnte!" });
		}
		else
			data.messages.involved.primary.push({ type: "danger", title: "Kalendereintrag nicht gefunden", message: "Konnte keinen Kalendereintrag zu dieser Bearbeitung finden. Schwerer Fehler!" });

		send_rendered_pentry(socket, data, pentry);
	}

	function add_edit_location(type, data) {
		var pentry = pentry_from_session(socket.handshake.session, data);
		init_emit_messages(data);
		if(pentry) {
			switch(type) {
				case 'add':
					data.data.location.uid = generateUID();
					pentry.locations.push(data.data.location);
					data.messages.locations.push({ type: "success", title: "Ort erfolgreich hinzugefügt", message: "Der Ort '" + data.data.location.name + "' wurde erfolgreich hinzugefügt." });
					break;
				case 'edit':
					var loc = get_element_of_array_by_uid(pentry.locations, data.data.location.uid);
					if(loc) {
						loc.name = data.data.location.name;
						loc.sign = data.data.location.sign;

						data.messages.locations.push({ type: "success", title: "Ort erfolgreich bearbeitet", message: "'" + data.data.location.name + "' wurde erfolgreich bearbeitet." });
					}
					else
						data.messages.locations.push({ type: "danger", title: "Ort nicht geändert", message: "'" + data.data.location.name + "' konnte über seine UID keinem Eintrag zugeordnet werden; Bearbeitung verworfen!" });
					break;
			}

		}
		else
			data.messages.locations.push({ type: "danger", title: "Kalendereintrag nicht gefunden", message: "Konnte keinen Kalendereintrag zu dieser Bearbeitung finden. Schwerer Fehler!" });

		send_rendered_pentry(socket, data, pentry);
	}

	socket.on('pentry_add_location', function(data) {
		add_edit_location('add', data);
	});

	socket.on('pentry_edit_location', function(data) {
		add_edit_location('edit', data);
	})

	socket.on('pentry_add_involved', function(data) {
		add_edit_involved('add', data);
	});

	socket.on('pentry_edit_involved', function(data) {
		add_edit_involved('edit', data);
	});

	socket.on('render_roleeditor', function(data) {
		console.log(data);
		var jsondata = {
				"request"		: "get_predefined_roles",
				"sessionuuid"	: socket.handshake.session.sessionuuid,
			};

		jsonsrv.do_jsonsrv2(jsondata,
			function(result) {
				if(result.result === "OK") {
					var event = event_from_session(socket.handshake.session, data);

					var role_uid = '';
					var role_name = '';
					if(data.data.type === 'edit') {
						role_uid = data.data.role;
						role_name = get_role_from_uid(event, role_uid).name;
					}

					var already_defined_roles = [];
					for( idx in event.involved_roles ) {
						if(event.involved_roles[idx].name !== role_name)
							already_defined_roles.push(event.involved_roles[idx].name);
					}

					var html = jade.renderFile("./views/roleeditor_inlay.jade", {
													roles: result.roles,
													type : data.data.type,
													role_name : role_name,
													role_uid  : role_uid,
													already_defined_roles : already_defined_roles
												});

					socket.emit('render_roleeditor_result', { result: "OK", html: html});
				}
				else
					socket.emit('render_roleeditor_result', { result: "ERROR", html: ""});
			},
			function(error) {
				console.log(error);
			});
	});

	socket.on('event_add_role', function(data) {
		var event = event_from_session(socket.handshake.session, data);
		init_emit_messages(data);

		var role = data.data.role;
		role.uid = generateUID();
		role.involved = [];

		console.log('about to add role:')
		console.log(role);

		event.involved_roles.push(role);

		send_rendered_event(socket, data, event);
	});

	socket.on('event_edit_role', function(data) {
		var event = event_from_session(socket.handshake.session, data);
		init_emit_messages(data);

		console.log(data);

		get_role_from_uid(event, data.data.role.uid).name = data.data.role.name;

		console.log(get_role_from_uid(event, data.data.role.uid));

		send_rendered_event(socket, data, event);
	});

	socket.on('event_save', function(data) {
		console.log(data);

		var event = event_from_session(socket.handshake.session, data);

		event.name  = data.data.event.name;
		event.name_secondary = data.data.event.name_secondary;
		event.visibility = data.data.event.visibility;
		event.end = data.data.event.end;
		event.end_is_vague = data.data.event.end_is_vague;
		event.description = data.data.event.description;
		event.annotations = data.data.event.annotations;

		if(data.pentrytype === "event") {
			event.start = data.data.event.start;
		}

		console.log("EVENT SAVED!");
	});

	socket.on('away_save', function(data) {
		console.log('away_save', data);

		var away = pentry_from_session(socket.handshake.session, data);

		away.reason = data.data.away.reason;
	});

	socket.on('keep_in_mind_save', function(data) {
		console.log('keep_in_mind_save',data);

		var keep_in_mind = pentry_from_session(socket.handshake.session, data);

		keep_in_mind.name = data.data.keep_in_mind.name;
		keep_in_mind.description = data.data.keep_in_mind.description;
	});

	socket.on('todo_save', function(data) {
		console.log('todo_save',data);

		var todo = pentry_from_session(socket.handshake.session, data);

		todo.name = data.data.todo.name;
		todo.description = data.data.todo.description;
	});

	socket.on('vehicle_use_save', function(data) {
		console.log('vehicle_use_save',data);

		var vehicle_use = pentry_from_session(socket.handshake.session, data);

		vehicle_use.name = data.data.vehicle_use.name;
		vehicle_use.description = data.data.vehicle_use.description;
		vehicle_use.vehicle_id = data.data.vehicle_use.vehicle_id;
	});

	socket.on('pentry_remove_involved', function(data) {
		var pentry = pentry_from_session(socket.handshake.session, data);

		if(pentry) {
			var the_involved = pentry.involved;
			var role = '';
			if(data.pentrytype === "event" || data.pentrytype === "tevent") {
				role = data.data.role;
				the_involved = get_involved_from_event(pentry, data.data.role);
			}
			if(role === '')
				role = 'primary';

			if(the_involved === null) {
				console.log('REMOVING FROM ROLE '+data.data.role);
				console.log("WARNING: role not found!");
				socket.emit('pentry_remove_involved_result',
					{ result: 'ERROR', role: role, html: get_rendered_pcalmessage( { type: "danger", title: "Dienst nicht gefunden", message: "Der zu entfernende Betroffene konnte nicht entfernt werden, da der angegeben Dienst [" + role + "] nicht gefunden werden konnte."})});
				return;
			}
			var found = remove_from_array_by_uid(the_involved, data.data.involved);
			if(found)
				socket.emit('pentry_remove_involved_result',
					{ result: 'OK', role: role, html: get_rendered_pcalmessage( { type: "success", title: "Entfernen erfolgreich", message: "Der zu entfernende Betroffene wurde erfolgreich entfernt."})});
			else
				socket.emit('pentry_remove_involved_result',
					{ result: 'ERROR', role: role, html: get_rendered_pcalmessage( { type: "danger", title: "Betroffener nicht gefunden", message: "Der zu entfernende Betroffene konnte nicht entfernt werden, da der angegeben Betroffene [" + data.data.involved + "; role: " + role + "] nicht gefunden werden konnte."})});
		}
		else
			socket.emit('pentry_remove_involved_result',
				{ result: 'ERROR', role: role, html: get_rendered_pcalmessage( { type: "danger", title: "Kalendereintrag nicht gefunden", message: "Konnte keinen Kalendereintrag zu dieser Bearbeitung finden. Schwerer Fehler!" } )});

	});

	socket.on('pentry_remove_location', function(data) {
		var pentry = pentry_from_session(socket.handshake.session, data);

		if(pentry) {
			var found = remove_from_array_by_uid(pentry.locations, data.data.location);
			if(found)
				socket.emit('pentry_remove_location_result',
					{ result: 'OK', html: get_rendered_pcalmessage( { type: "success", title: "Entfernen erfolgreich", message: "Der zu entfernende Ort wurde erfolgreich entfernt."})});
			else
				socket.emit('pentry_remove_location_result',
					{ result: 'ERROR', html: get_rendered_pcalmessage( { type: "danger", title: "Ort nicht gefunden", message: "Der zu entfernende Ort konnte nicht entfernt werden, da der angegeben Ort nicht gefunden werden konnte."})});
		}
		else
			socket.emit('pentry_remove_location_result',
				{ result: 'ERROR', html: get_rendered_pcalmessage( { type: "danger", title: "Kalendereintrag nicht gefunden", message: "Konnte keinen Kalendereintrag zu dieser Bearbeitung finden. Schwerer Fehler!" } )});

	});

	socket.on('event_remove_role', function(data) {
		var event = event_from_session(socket.handshake.session, data);

		var found = remove_from_array_by_uid(event.involved_roles, data.data.role);


		socket.emit('event_remove_role_result', { result: (found ? 'OK':'ERROR')})
	});

	socket.on('get_parishday', function(data) {

		var data = {
				"request"		: "get_parishday",
				"sessionuuid"   : socket.handshake.session.sessionuuid,
				"date"			: data.date,
			};

		jsonsrv.do_jsonsrv2(data,
			function(result) {
				if(result.result === "OK") {
					var html = jade.renderFile('views/pentrymove_parishday.jade', { day: result.day });
					socket.emit('got_parishday', { result: "OK",  html: html });
				}
				else
					socket.emit('got_parishday', { result: "ERROR" });
			},
			function(){console.log('ERROR');});

		console.log(data);
	});
});
/*
var pcalpub = io.of('/pcalpub');
pcalpub.use(sharedsession(app.locals.session, {autoSave: true}));
pcalpub.on('connection', function(socket) {
	var tmpfiles = [];

	var uploader = new app.locals.siofu();
	var tmpdir = tmp.dirSync({dir:'/tmp', unsafeCleanup: true});
	tmpfiles.push(tmpdir);
	uploader.dir = tmpdir.name;
	uploader.listen(socket);

	console.log('NEW PCALPUB-WEBSOCKET-CONNECTION');
	console.log('A socket with sessionID ' + socket.handshake.session.sessionuuid + ' connected!');

	// ONE SHOT CONNECTIONS BEGIN
	uploader.on('complete', function(event) {
		event.file.clientDetail.pathName = event.file.pathName;
	});

	socket.on('pcalpub_generate_pdf', function(data) {
		var jsondata = {
			"request"		: "generate_publication_pdf",
			"sessionuuid"	: socket.handshake.session.sessionuuid,
			parishid		: data.parishid,
			factoryid		: data.factoryid,
			date			: data.date,
			durance			: data.durance,
			use_background	: data.use_background
		};

		var prefix = 'pcalpub-';
		if(data.use_background) {
			//var pdf = fs.readFileSync(tmpdir.name+"/"+data.background_pdf);
			var pdf = fs.readFileSync(data.background_pdf);
			jsondata.background_pdf = new Buffer(pdf).toString('base64');
			var idx = data.background_pdf.indexOf('.pdf');
			prefix = data.background_pdf.slice(0,idx)+"-komplett___";
			idx = prefix.lastIndexOf('/');
			prefix = prefix.substr(idx+1);
		}

		jsonsrv.do_jsonsrv2(jsondata,
			function(result) {
				var tmpobj;

				if(result.result === "OK") {
					var buf = new Buffer(result.pdf, 'base64');
					tmpobj = tmp.fileSync({ dir: 'public/pcalpubtmp/', prefix: prefix, postfix: '.pdf' });
					tmpfiles.push(tmpobj);
					fs.writeFileSync(tmpobj.fd, buf);
				}
				else {
					tmpobj = tmp.fileSync({ dir: 'public/pcalpubtmp/', prefix: 'pcalpub___', postfix: '.html' });
					tmpfiles.push(tmpobj);
					fs.writeFileSync(tmpobj.fd, "<html><body>ERROR IN GENERATING HTML</body></html>");
				}

				fs.closeSync(tmpobj.fd);
				// "/pcalpub/files/"+ 11
				socket.emit('pcalpub_generate_pdf_result', { result: 'OK', file: tmpobj.name.substr(6, tmpobj.name.length), title: result.title});
			},
			function(error){
				console.log(error);
				var tmpobj = tmp.fileSync({ dir: 'public/pcalpubtmp/', prefix: 'pcalpub-', postfix: '.html' });
				tmpfiles.push(tmpobj);
				fs.writeFileSync(tmpobj.fd, "<html><body>ERROR CONNECTING TO PFISJSONSRV</body></html>");
				fs.closeSync(tmpobj.fd);
				socket.emit('pcalpub_generate_pdf_result', { result: 'ERROR', file: tmpobj.name.substr(6, tmpobj.name.length), title: ''});
			});

	});

	// ONE SHOT SESSIONS END

	var publicationformats = [];
	var parishid = 0;
	var factoryid = 0;
	var durance = 2;
	var date = (new Date(Date.now())).toISOString().slice(0,10);
	var html = "";
	var timespan = "";
	var parishdb = [];
	var dest_to = [];
	var dest_cc = [];
	var dest_bcc = [];
	var title = "__EMPTY_TITLE__";

	function save_settings(data) {
		publicationformats = data.publicationformats;
		parishid = data.parishid;
		factoryid = data.factoryid;
		durance = data.durance;
		date = data.date;
	}

	socket.on('pcalpub_show_settings', function(data) {
		//var html = jade.renderFile('views/pcalpub_settings.jade', { parishid: data.parishid, factoryid: data.factoryid, durance: data.durance, date: data.date, publicationformats: data.publicationformats });
		var html = jade.renderFile('views/pcalpub_settings.jade', { parishid: parishid, factoryid: factoryid, durance: durance, date: date, publicationformats: publicationformats });
		socket.emit('pcalpub_show_settings_result', {result: "OK", html: html});
	});

	function send_rendered_html_for_email(myhtml, push_state) {
		jade.renderFile('views/pcalpub_html_for_email_edit.jade',
				{
					html: "<html><meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\" /><body>" + myhtml + "</body></html>\r\n",
					parish_name : publicationformats[parishid].name,
					factory_name : publicationformats[parishid].publicationformats[factoryid].name,
					timespan : timespan
				}, function(error, html) {
						if(error) {
							var html = get_rendered_error(error);
							html = "<div class='subroot' style='padding-left: 15px; padding-right: 15px;'>" + html + "</div>";
							socket.emit('pcalpub_generate_html_for_email_result', { result: "ERROR",  html: html, push_state : push_state });
						}
						else
							socket.emit('pcalpub_generate_html_for_email_result', { result: "OK",  html: html, push_state : push_state });
					});
	}

	socket.on('pcalpub_generate_html_for_email', function(data) {
		save_settings(data);

		var jsondata = {
			"request"		: "generate_publication_html",
			"sessionuuid"	: socket.handshake.session.sessionuuid,
			parishid		: data.parishid,
			factoryid		: data.factoryid,
			date			: data.date,
			durance			: data.durance
		};

		jsonsrv.do_jsonsrv2(jsondata,
			function(result) {
				if(result.result === "OK") {
					timespan = result.timespan;
					title = result.title;
					var myhtml = "" + new Buffer(result.html, 'base64');
					send_rendered_html_for_email(myhtml, true);
				}
				else {
					var html = get_rendered_jsonerror(result, socket.handshake.session);
					html = "<div class='subroot' style='padding-left: 15px; padding-right: 15px;'>" + html + "</div>";
					socket.emit('pcalpub_generate_html_for_email_result', { result: "ERROR",  html: html, push_state : true});
				}
			},
			function(error){
				var html = get_rendered_error(error);
				html = "<div class='subroot' style='padding-left: 15px; padding-right: 15px;'>" + html + "</div>";
				socket.emit('pcalpub_generate_html_for_email_result', { result: 'ERROR', html: html, push_state : true });
			});
	});

	socket.on('pcalpub_show_html_for_email', function(data) {
		send_rendered_html_for_email(html, false);
	});

	function send_rendered_emailaddresschooser(push_state) {
		jade.renderFile('views/emailaddresschooser.jade',
				{
					parishdb : parishdb,
					dest_to : dest_to,
					dest_cc : dest_cc,
					dest_bcc : dest_bcc
				}, function(error, html) {
						if(error)
							socket.emit('pcalpub_show_addresschooser_result', { result: "ERROR",  html: get_rendered_error(error), push_state : push_state });
						else
							socket.emit('pcalpub_show_addresschooser_result', { result: "OK",  html: html, push_state : push_state});
					});
	}

	socket.on('pcalpub_show_addresschooser', function(data) {
		console.log(data);
		html = data.html; // save the passed html!!!
		var jsondata = {
			"request"		: "get_parishdbelems_flat_email",
			"sessionuuid"	: socket.handshake.session.sessionuuid
		};

		jsonsrv.do_jsonsrv2(jsondata,
			function(result) {

				if(result.result === "OK") {

					for(idx in result.parishdb) {
						result.parishdb[idx].uid = generateUID();

						if(result.parishdb[idx].type === "group") {
							for(midx in result.parishdb[idx].members)
								result.parishdb[idx].members[midx].uid = generateUID();
						}
					}

					parishdb = result.parishdb;

					send_rendered_emailaddresschooser(true);
				}
				else {
					var html = get_rendered_jsonerror(result, socket.handshake.session);
					html = "<div class='subroot' style='padding-left: 15px; padding-right: 15px;'>" + html + "</div>";
					socket.emit('pcalpub_show_addresschooser_result', { result: "ERROR",  html: html, push_state : true});
				}
			},
			function(error){
				var html = get_rendered_error(error);
				html = "<div class='subroot' style='padding-left: 15px; padding-right: 15px;'>" + html + "</div>";
				socket.emit('pcalpub_show_addresschooser_result', { result: 'ERROR', html: html, push_state : true });
			});
	});

	socket.on('pcalpub_show_addresschooser_from_saved', function(data) {
		send_rendered_emailaddresschooser(false);
	});

	function send_rendered_summary(push_state) {
		jade.renderFile('views/pcalpub_summary.jade',
				{
					dest_to : dest_to,
					dest_cc : dest_cc,
					dest_bcc : dest_bcc,
					parish_name : publicationformats[parishid].name,
					factory_name : publicationformats[parishid].publicationformats[factoryid].name,
					timespan : timespan,
					html : html
				}, function(error, myhtml) {
						if(error)
							socket.emit('pcalpub_show_summary_result', { result: "ERROR",  html: get_rendered_error(error), push_state : push_state});
						else
							socket.emit('pcalpub_show_summary_result', { result: "OK",  html: myhtml, push_state : push_state});
					});
	}

	socket.on('pcalpub_show_summary', function(data) {
		dest_to = data.dest_to;
		dest_cc = data.dest_cc;
		dest_bcc = data.dest_bcc;

		send_rendered_summary(true);
	});

	socket.on('pcalpub_show_summary_from_saved', function(data) {
		send_rendered_summary(false);
	})

	socket.on('pcalpub_generate_publication_send_html2', function(data) {
		jade.renderFile('views/pcalpub_send.jade',
				{
					parish_name : publicationformats[parishid].name,
					factory_name : publicationformats[parishid].publicationformats[factoryid].name,
					timespan : timespan,
				}, function(error, myhtml) {
						if(error)
							socket.emit('pcalpub_generate_publication_send_html2_result', { result: "ERROR",  html: get_rendered_error(error)});
						else
							socket.emit('pcalpub_generate_publication_send_html2_result', { result: "OK",  html: myhtml});
					});
	});

	socket.on('pcalpub_generate_publication_send_html', function(data) {
		var jsondata = {
			"request"		: "generate_publication_send_html",
			"sessionuuid"	: socket.handshake.session.sessionuuid,
			"doctitle" 		: title,
			"html"			: html,
			"dest_to"		: dest_to,
			"dest_cc"		: dest_cc,
			"dest_bcc"		: dest_bcc
		};

		jsonsrv.do_jsonsrv_steppedanswer(jsondata,
			function(step) {
				console.log('STEP RECEIVED', step);
				socket.emit('pcalpub_generate_publication_send_html_step', step);
			},
			function(result) {
				console.log('END RECEIVED', result);
				socket.emit('pcalpub_generate_publication_send_html_result', result);
			},
			function(error){
				var html = get_rendered_error(error);
				socket.emit('pcalpub_show_summary_result', { result: 'ERROR', message: "Beim Senden konnte keine Verbindung zu PfIS aufgebaut werden!", explanation: html });
			});
	});

	socket.on('disconnect', function(data) {
		console.log('socket.io: disconnect');
		console.log(data);
		console.log('SOCKET EXIT');

		for(var i=0; i<tmpfiles.length; ++i) {
			console.log('REMOVING ', tmpfiles[i].name);
			tmpfiles[i].removeCallback();
		}

		tmpfiles = [];
	});

});
*/
/*var emailio = io.of('/email');
emailio.use(sharedsession(app.locals.session, {autoSave: true}));
emailio.on('connection', function(socket) {
	console.log('NEW EMAILIO-WEBSOCKET-CONNECTION');
	console.log('A socket with sessionID ' + socket.handshake.session.sessionuuid + ' connected!');

	socket.on('email_send', function(data) {
		console.log(data);

		var jsondata = {
			"request"		: "email_send",
			"sessionuuid"	: socket.handshake.session.sessionuuid,
			"dest_to"		: data.dest_to,
			"dest_cc"		: data.dest_cc,
			"dest_bcc"		: data.dest_bcc,
			"subject" 		: data.subject,
			"body"			: data.body,
			"body_raw"		: data.body_raw

		};

		jsonsrv.do_jsonsrv2(jsondata,
			function(result) {
				socket.emit('email_send_result', result);
			},
			function(error){
				var html = get_rendered_error(error);
				socket.emit('email_send_result', { result: 'ERROR', message: "Beim Senden konnte keine Verbindung zu PfIS aufgebaut werden!", explanation: html });
			});

	});
});
*/

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

process.on('SIGTERM', function () {
  //server.close(function () {
    process.exit(0);
  //});
});
