var pcalPentryEditManager = function(websocket) {
	var _ws = websocket;
	var _date;
	var _pentrytype;
	var _uuid;
	var _is_active = false;
	var _pentry = null;

	var _cache;

	var _scroll_top = 0;
	var _scroll_top_body = 0;

	var _messages;

	add_uids_to_event = function(ev) {
		for(var idx in ev.involved)
		{
			ev.involved[idx].uid = generateUID();
			console.log(ev.involved[idx]);
		}
		for(var idx in ev.involved_roles)
		{
			ev.involved_roles[idx].uid = generateUID();

			for(var inv_idx in ev.involved_roles[idx].involved)
				ev.involved_roles[idx].involved[inv_idx].uid = generateUID();
		}

		for(var idx in ev.locations)
		{
			ev.locations[idx].uid = generateUID();
			console.log(ev.locations[idx]);
		}
	}

	_ws.bind("pcal_pentry_edit_event_details_result", function(data) {
		console.log("pcal_pentry_edit_event_details_result");
		console.log(data);

		if(_pentrytype === "tevent") {
			for(idx in data.event.thereafter) {
				if(data.event.thereafter[idx].uuid === _uuid) {
					_pentry = data.event.thereafter[idx];
					_pentry.parent_start = data.event.start;
					break;
				}
			}
		}
		else
			_pentry = data.event;

		add_uids_to_event(_pentry);

		pcal_pentry_edit_manager.intern_complete_start();
	});

	_ws.bind("pcal_pentry_edit_away_details_result", function(data) {
		console.log("pcal_pentry_edit_away_details_result");
		console.log(data);
		_pentry = data.away;

		pcal_pentry_edit_manager.intern_complete_start();
	});

	_ws.bind("pcal_pentry_edit_todo_details_result", function(data) {
		console.log("pcal_pentry_edit_todo_details_result");
		console.log(data);
		_pentry = data.todo;

		for(var idx in _pentry.involved) {
			_pentry.involved[idx].uid = generateUID();
		}

		pcal_pentry_edit_manager.intern_complete_start();
	});

	_ws.bind("pcal_pentry_edit_keep_in_mind_details_result", function(data) {
		console.log("pcal_pentry_edit_keep_in_mind_details_result");
		console.log(data);
		_pentry = data.keep_in_mind;

		pcal_pentry_edit_manager.intern_complete_start();
	});

	_ws.bind("pcal_pentry_edit_vehicle_use_details_result", function(data) {
		console.log("pcal_pentry_edit_vehicle_use_details_result");
		console.log(data);
		_pentry = data.vehicle_use;

		for(var idx in _pentry.involved) {
			_pentry.involved[idx].uid = generateUID();
		}

		 pcal_pentry_edit_manager.intern_complete_start();
	});

	_ws.bind("get_all_vehicles_legacy_result", function(data) {
		console.log('get_all_vehicles_legacy_result')
		_cache["vehicles"] = data.vehicles;
		_cache.vehicles_loaded = true;
		pcal_pentry_edit_manager.intern_complete_start();
	});

	this.get_date = function() { return _date; }

	this.set_date = function(date) {
		_date = date;
		console.log(_date);
	}

	this.is_active = function() {
		return _is_active;
	}

	this.start = function(pentrytype, uuid) {
		this.reset_messages();
		this.reset_cache();

		_is_active = true;
		_pentrytype = pentrytype;
		_uuid = uuid;

		if(uuid === "new")
			_uuid="new_" + generateUID();

		console.log('start', _date, _pentrytype, _uuid);

		if(_pentrytype === "event" || _pentrytype === "tevent") {
			var parent_event_uuid = _uuid;
			console.log(history.state);
			if(history.state.direction === 'day_show_event' || history.state.direction === 'pentry_edit_main')
				parent_event_uuid = history.state.event_uuid;
			console.log('parent_uuid', parent_event_uuid);
			if(_pentrytype === "event" && uuid === "new" && history.state.direction.substr(0,12) !== 'pentry_edit_')
				history.pushState({direction: 'pentry_edit_main', pentrytype: _pentrytype, uuid: _uuid, event_uuid: parent_event_uuid, date: _date.date}, document.title, location.pathname);
			else
				history.replaceState({direction: 'pentry_edit_main', pentrytype: _pentrytype, uuid: _uuid, event_uuid: parent_event_uuid, date: _date.date}, document.title, location.pathname);
		}
		else {
			if(history.state.direction.substr(0,12) === 'pentry_edit_')
				history.replaceState({direction: 'pentry_edit_main', pentrytype: _pentrytype, uuid: _uuid, date: _date.date}, document.title, location.pathname);
			else
				history.pushState({direction: 'pentry_edit_main', pentrytype: _pentrytype, uuid: _uuid, date: _date.date}, document.title, location.pathname);
		}

		var renderdata = {	pentrytype	: _pentrytype,
							date 		: _date,
							uuid 		: _uuid,
							edit_type	: (_uuid.substr(0,4) === "new_" ? "erstellen" : "bearbeiten")
						};

		switch(_pentrytype) {
			case "event":
				renderdata["pentrytype_pretty"] = "Ereignis";
				break;
			case "tevent":
				var pentry = $("[data-pentryuuid="+parent_event_uuid+"]");
				console.log(pentry);
				console.log(pentry.data('pentryname'));
				console.log(pentry.data('eventstart'));
				renderdata["pentrytype_pretty"] = "Folge-Ereignis zu " + pentry.data('pentryname');
				renderdata["eventstart"] = pentry.data('eventstart');
				break;
			case "away":
				renderdata["pentrytype_pretty"] = "Abwesenheit";
				break;
			case "keep_in_mind":
				renderdata["pentrytype_pretty"] = "Zu-Beachten";
				break;
			case "todo":
				renderdata["pentrytype_pretty"] = "Zu-Tun";
				break;
			case "vehicle_use":
				renderdata["pentrytype_pretty"] = "Fahrzeugbenutzung";
				break;
		}
		var html = pentry_edit_template(renderdata);

		$("#pentry_edit_parent").html(html);

		// load the pentry
		pentry_from_storage = sessionStorage.getItem('pcal_pentry_edit_current');
		if(pentry_from_storage !== null) {
			console.log('found pentry in sessionstorage');
			pentry_from_storage = JSON.parse(pentry_from_storage);
			if(pentry_from_storage.uuid === _uuid && pentry_from_storage.pentrytype === _pentrytype)
				_pentry = pentry_from_storage;
		}

		if(!_pentry) {
			console.log('could not load pentry from sessionstorage')
			if(_uuid.substr(0,4) === "new_") {
				console.log('generate new entry')
				_pentry = generate_new();
				if(_pentrytype === 'tevent')
					_pentry.parent_start = renderdata["eventstart"];
			}
			else {
				console.log('loading pentry from server')

				var send_data = {"date": _date.date, "answer_prefix" : "pcal_pentry_edit_" };

				if(_pentrytype === "tevent") {
					send_data["event"] = parent_event_uuid;
					ws.send("event_details", send_data);
				}
				else {
					send_data[_pentrytype] = _uuid;
					ws.send(_pentrytype + "_details", send_data);
				}


				return; // intern_complete_start is in this case called when the loading is complete!
			}

		}

		this.intern_complete_start();
	}

	this.show_edit_main = function() {
		var data = {messages: _messages};
		this.reset_messages();

		if(_pentrytype === "tevent")
			data["event"] = _pentry;
		else
			data[_pentrytype] = _pentry;

		var html;
		switch(_pentrytype) {
			case "event":
				html=edit_event_template(data);
				break;
			case "tevent":
				html=edit_event_template(data);
				break;
			case "away":
				html=edit_away_template(data);
				break;
			case "keep_in_mind":
				html=edit_keep_in_mind_template(data);
				break;
			case "todo":
				html=edit_todo_template(data);
				break;
			case "vehicle_use":
				data.vehicles = _cache.vehicles;
				html=edit_vehicle_use_template(data);
				break;
		}


		$('.noEnterSubmit').keydown(function(e){
			if ( e.which == 13 ) e.preventDefault();
		});

		$("#entryeditnav-form").empty();

		$("#pentry_edit_root").children(".subroot").remove();
		$("#pentry_edit_root").append(html);
		$("#pentry_edit_root > .subroot > .new_flex_one").scrollTop(_scroll_top);
		$("html, body").scrollTop(_scroll_top_body);

		_scroll_top = 0;
		_scroll_top_body = 0;

		switch(_pentrytype) {
			case "event":
			case "tevent":

				$('#form_pentry').validator({
					custom: {
								end_after_start: function(el)
								{
									var start = "";
									console.log(_pentry.pentrytype === "tevent")
									if(_pentry.pentrytype === "tevent")
										start = _pentry.parent_start;
									else
										start =  $('#edit_begin').val();
									var end   = $('#edit_end').val();

									console.log(start);
									console.log(end);

									if(end.length === 0)
										return;

									if (Date.parse("2015-08-31T"+end) <= Date.parse("2015-08-31T"+start))
										return "Das Ende des Ereignisses muss nach dessen Beginn liegen!";
								},
								when_end_then_start: function(el)
								{
									if(_pentry.pentrytype === "tevent")
										return;
									console.log("WHEN END THEN START");

									var start = $('#edit_begin').val().trim();
									var end   = $('#edit_end').val().trim();

									if(end.length > 0 && start.length===0)
										return "Wenn Sie ein Ende angeben, müssen Sie auch einen Beginn angeben!";
								}
							}
				}).on('invalid.bs.validator', function (e) {
					console.log("INVALID");
					console.log(e);
				}).on('valid.bs.validator', function (e) {
					console.log("VALID");
					console.log(e);
				});

				break;
			case "away":
				$('.noDirectInput').keydown(function(e) {
					var target = $(e.currentTarget);
					var form_group = target.closest('.form-group');
					var help_block = form_group.find('.with-errors');
					if(! form_group.hasClass('has-error')) {
						target.closest('.form-group').addClass('has-error');
					}
					if(! help_block.hasClass('has-halieus-error')) {
						help_block.addClass('has-halieus-error');
						help_block.append("<ul class='list-unstyled'><li>Sie müssen den 'Ändern'-Button benutzen!</li></ul>");
					}

					e.preventDefault();
				});
				$('.noDirectInput').keyup(function(e) { e.preventDefault(); });
				$('.noDirectInput').keypress(function(e) { e.preventDefault(); });

				$('.noDirectInput').focusout(function(e) {
					var target = $(e.currentTarget);
					var form_group = target.closest('.form-group');
					var help_block = form_group.find('.with-errors');
					help_block.empty();
					help_block.removeClass('has-halieus-error');
				});


				/* fall though  for validator */
			case "keep_in_mind":
			case "todo":
			case "vehicle_use":
				$('#form').validator().on('invalid.bs.validator', function (e) {
					console.log("INVALID");
					console.log(e);
				}).on('valid.bs.validator', function (e) {
					console.log("VALID");
					console.log(e);
				});

				break;
		}

		$('#form_pentry').on('submit', function(e) {
			console.log('submit');
			e.preventDefault();
			pcal_pentry_edit_manager.commit_pentry();
		});


	}

	this.intern_complete_start = function() {
		_pentry.pentrytype = _pentrytype;
		if(_pentrytype === "tevent") {
			_pentry.parent_event_uuid = history.state.event_uuid;
			console.log('intern_complete_start: prent_event_uuid: ', _pentry.parent_event_uuid)
		}
		this.intern_save_to_storage();
		$("#pentry_edit_parent").show();

		console.log(_cache);
		console.log(_pentrytype)
		if(_pentrytype === "vehicle_use" && _cache.vehicles_loaded === false) {
			console.log('loading vehicles ...')
			_ws.send("get_all_vehicles_legacy",  {});
		}
		else
			this.show_edit_main();
	}

	this.intern_save_to_storage = function() {
		sessionStorage.setItem('pcal_pentry_edit_current', JSON.stringify(_pentry));
	}

	this.intern_save_pentry = function() {
		switch(_pentrytype) {
			case "event":
				_pentry.start = $("#edit_begin").val();
				/* no break here to save common event/tevent-things*/
			case "tevent":
				_pentry.name = $("#edit_name").val(),
				_pentry.name_secondary = $("#edit_name_secondary").val(),
				_pentry.visibility = $("#combo_type").val(),
				_pentry.end = $("#edit_end").val(),
				_pentry.end_is_vague = $("#check_end_is_vague").prop("checked"),
				_pentry.description = $("#area_description").val(),
				_pentry.annotations = $("#area_annotations").val()
				break;
			case "away":
				_pentry.reason = $("#edit_reason").val()
				break;
			case "keep_in_mind":
				_pentry.name = $("#edit_name").val(),
				_pentry.description =  $("#area_description").val()
				break;
			case "todo":
				_pentry.name = $("#edit_name").val(),
				_pentry.description =  $("#area_description").val()
				break;
			case "vehicle_use":
				_pentry.name = $("#edit_name").val(),
				_pentry.description =  $("#area_description").val(),
				_pentry.vehicle_id = $("#combo_vehicle").val()
				break;
		}

		console.log(_pentry);

		this.intern_save_to_storage();
	}

	this.save_and_goto = function(subpage, subpage_data) {
		this.intern_save_pentry();

		console.log('subpage: ', subpage);
		console.log('subbpage_data: ', subpage_data);

		_scroll_top = $("#pentry_edit_root > .subroot > .new_flex_one").scrollTop();
		_scroll_top_body = $("html, body").scrollTop();
		switch(subpage) {
			case "select_pastoralunit":
				ws.send('get_all_pastoralunits', {});
				break;
			case "add_predefined_location":
				var jsondata = { "omitt": [] };
				for(idx in _pentry.locations) {
					var loc = _pentry.locations[idx];
					if(loc.id != "other")
						jsondata.omitt.push(loc.id);
				}
				ws.send('get_all_predefined_locations', jsondata)
				break;
			case "add_location":
				this.intern_present_locationeditor("add", {});
				break;
			case "edit_location":
				this.intern_present_locationeditor("edit", {location: subpage_data.location });
				break;
			case "add_actor":
				var jsondata = 	{ "omitt": [], "date": _date.date, "pentry": _pentry.uuid };

				if(_pentry.pentrytype !== "away") {
					var the_involved = _pentry.involved;
					if(_pentry.pentrytype === "event" || _pentry.pentrytype === "tevent") {
						role = subpage_data.role;
						console.log('ADD ACTOR FOR ROLE '+role);
						the_involved = this.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);
					}
					_cache.role = role;
				}

				_ws.send("get_all_actors", jsondata);
				break;
			case "add_role":
				_cache["roleeditor"]["type"] = "add";
				_cache["roleeditor"]["role"] = "";
				_ws.send("get_predefined_roles");
				break;
			case "edit_role":
				_cache["roleeditor"]["type"] = "edit";
				_cache["roleeditor"]["role"] = subpage_data.role;
				_ws.send("get_predefined_roles");
				break;
			case "add_involved":
				this.intern_present_involvededitor("add", { role: subpage_data.role});
				break;
			case "edit_involved":
				this.intern_present_involvededitor("edit",{ role: subpage_data.role, involved: subpage_data.involved});
				break;
			case "add_parishdbpersongroup":
				_cache["parishdbpersongroupselector"]["role"] = subpage_data.role;
				_ws.send("get_parishdbelems_flat", {});
				break;
		}
	}

	this.show_searchbar = function(functiontocall) {
		$("#entryeditnav-form").append("<div class='input-group'><div class='input-group-addon'><span class='glyphicon glyphicon-search'></span></div><input class='form-control' type='text' placeholder='Suche'  style='display: inline;' oninput='" + functiontocall + "'></input></div>");
	}

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

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

	this.get_involved_from_event = function(event, role_uid) {
		if(role_uid !== '') {
			var role = this.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;
	}

	this.intern_present_subpage = function(name, html) {
		history.pushState({direction: name, pentrytype: _pentrytype, uuid: _uuid, date: _date.date}, document.title, location.pathname);
		$("#pentry_edit_root").children(".subroot").remove();
		$("#pentry_edit_root").append(html);
		$("html, body").scrollTop(0);
		$("#pentry_edit_root").scrollTop(0);
	}

	_ws.bind('get_all_actors_result', function(data) {
		var html;
		console.log('get_all_actors_result', data);
		if(data.result === "OK") {
			var renderdata = { units: data.actors, for_role: _cache.role };
			if(_pentry.pentrytype === "away") {
				renderdata.actual_actor_id = _pentry.involveddb_id;
				renderdata.actual_actor_name = _pentry.name;
			}
			console.log(renderdata);
			html = actorselector_inlay_template(renderdata);
		}
		else
			html = "ERROR";

		delete _cache.role;

		console.log('got actorselector');
		pcal_pentry_edit_manager.intern_present_subpage('pentry_edit_actorselector', html)
	});

	_ws.bind('get_all_pastoralunits_result', function(data) {
		var html;
		console.log(data);
		if(data.result === "OK") 	{
			var renderdata =  { actual_punit_dn : _pentry.punit.dn, actual_punit_name: _pentry.punit.name, pastoralunits: data.pastoralunits };
			console.log(renderdata);
			html = pastoralunitselector_inlay_template(renderdata);
		}
		else
			html = "ERROR";

		console.log('got pastoralunitseclector');
		pcal_pentry_edit_manager.intern_present_subpage('pentry_edit_pastoralunitselector', html);
	});

	_ws.bind('get_all_predefined_locations_result', function(data) {
		console.log(data);
		var html;
		if(data.result === "OK") 	{
			var renderdata = { pentry_edit_base: "PENTRYBASE", units: data.locations };
			console.log(renderdata);
			html = locationselector_inlay_template(renderdata);
		}
		else
			html = "ERROR";
		pcal_pentry_edit_manager.intern_present_subpage('pentry_edit_locationselector', html);
	});

	_ws.bind('get_predefined_roles_result', function(data) {
		console.log(data);
		var html;
		if(data.result === "OK") {
			var role_uid = '';
			var role_name = '';
			if(_cache["roleeditor"]["type"] === 'edit') {
				role_uid = _cache["roleeditor"]["role"];
				role_name = pcal_pentry_edit_manager.get_role_from_uid(_pentry, role_uid).name;
			}

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

			var renderdata = { roles: data.roles, type : _cache["roleeditor"]["type"], role_name : role_name, role_uid  : role_uid, already_defined_roles : already_defined_roles };

			html = roleeditor_inlay_template(renderdata);
		}
		else
			html = "ERROR";
		pcal_pentry_edit_manager.intern_present_subpage('pentry_edit_roleeditor', html);
	});

	this.intern_present_involvededitor = function(type, data) {
		var role = '';

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

		var renderdata = { type: type, involved: involved, for_role: role };
		var html = involvededitor_inlay_template(renderdata);

		this.intern_present_subpage('pentry_edit_involvededitor', html);
	}

	this.intern_present_locationeditor = function(type, data) {
		console.log(data);
		console.log(_pentry.locations);

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

		console.log(location);

		var renderdata = { type : type, location: location };
		var html = locationeditor_inlay_template(renderdata);

		this.intern_present_subpage('pentry_edit_locationeditor', html);
	}

	_ws.bind('get_parishdbelems_flat_result', function(data) {

		var role = '';
		if(_pentrytype === "event" || _pentrytype === "tevent") {
			role = _cache["parishdbpersongroupselector"]["role"]
			console.log('ADD ACTOR FOR ROLE '+role);
		}

		var html;

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

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

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

			var renderdata = { parishdb: data.parishdb, for_role: role }

			html = parishdbpersongroupselector_inlay_template(renderdata);
		}
		else
			html = "ERROR";
		pcal_pentry_edit_manager.intern_present_subpage('pentry_edit_parishdbgroupselector', html);
	});

	this.set_pastoralunit = function(punit) {

		_pentry.punit.dn   = punit.dn;
		_pentry.punit.name = punit.name;
		_messages.other.push({ type: "success", title: "Kontext erfolgreich geändert", message: "Der Kontext wurde erfolgreich auf '" + punit.name + "' geändert." });

		this.intern_save_to_storage();
		// this.show_edit_main();
		history.back();
	}

	this.add_edit_location = function(type, location) {
		switch(type) {
			case 'add':
				location.uid = generateUID();
				_pentry.locations.push(location);
				_messages.locations.push({ type: "success", title: "Ort erfolgreich hinzugefügt", message: "Der Ort '" + location.name + "' wurde erfolgreich hinzugefügt." });
				break;
			case 'edit':
				var loc = this.get_element_of_array_by_uid(_pentry.locations, location.uid);
				if(loc) {
					loc.name = location.name;
					loc.sign = location.sign;

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

		this.intern_save_to_storage();
		//this.show_edit_main();
		history.back();
	}


	this.add_location = function(location) {
		this.add_edit_location('add', location);
	}

	this.edit_location = function(location) {
		this.add_edit_location('edit', location);
	}

	this.add_edit_involved = function(type, involved) {
		if(_pentrytype === "away") {
			// special treatment here!
			_pentry.name = involved.name;
			_pentry.involveddb_id = involved.id;
			_messages.involved['primary'].push({ type: "success", title: "Abwesende Person gesetzt", message: "'" + involved.name + "' wurde erfolgreich als abwesend gesetzt." });
			this.intern_save_to_storage();
			this.show_edit_main();
			return;
		}

		console.log(involved);

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

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

		this.intern_save_to_storage();
		//this.show_edit_main();
		history.back();
	}


	this.add_involved = function(involved) {
		this.add_edit_involved('add', involved);
	}

	this.edit_involved = function(involved) {
		this.add_edit_involved('edit', involved);
	}

	this.event_add_role = function(role) {
		role.uid = generateUID();
		role.involved = [];

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

		_pentry.involved_roles.push(role);

		this.intern_save_to_storage();
		//this.show_edit_main();
		history.back();
	};

	this.event_edit_role = function(role) {

		console.log(role);

		this.get_role_from_uid(_pentry, role.uid).name = role.name;

		console.log(this.get_role_from_uid(_pentry, role.uid));

		this.intern_save_to_storage();
		//this.show_edit_main();
		history.back();
	};

	this.commit_pentry = function() {
		this.intern_save_pentry();

		var data = { date: _date.date };
		if(_pentrytype == "tevent") {
			data["event"] = _pentry.parent_event_uuid;
			data["thereafter"] = _pentry.uuid;
			data["event_data"] = _pentry;
		}
		else {
			data[_pentrytype] = _uuid;
			data[_pentrytype+"_data"] = _pentry;
		}

		console.log(data);

		_ws.send("commit_"+_pentrytype, data);
	}

	this.internal_commit_result = function(data) {
		console.log(data);
		pcal_pentry_edit_manager.finish();
		history.back();
	}

	_ws.bind("commit_away_result", this.internal_commit_result);
	_ws.bind("commit_keep_in_mind_result", this.internal_commit_result);
	_ws.bind("commit_todo_result", this.internal_commit_result);
	_ws.bind("commit_vehicle_use_result", this.internal_commit_result);
	_ws.bind("commit_event_result", this.internal_commit_result);
	_ws.bind("commit_tevent_result", this.internal_commit_result);

	this.finish = function() {
		$("#pentry_edit_parent").hide();
		$("#pentry_edit_parent").empty();
		sessionStorage.removeItem('pcal_pentry_edit_current');
		_is_active = false;
		_pentry = null;
		this.reset_cache();
		this.reset_messages();
	}

	this.reset_messages = function() {
		_messages = {
			other : [],
			locations : [],
			involved : { primary: [] }
		}
	}

	this.reset_cache = function () {
		_cache = {
			roleeditor : {},
			parishdbpersongroupselector: {},
			vehicles : {},
			vehicles_loaded : false
		}
	}

	/* helper functions */
	generateUID = function() {
		return ("0000" + (Math.random()*Math.pow(36,4) << 0).toString(36)).slice(-4)
	}

	generate_new_tevent = function() {
		return {
			uuid: _uuid,
			name : "",
			name_secondary : "",
			visibility : "publ",
			end : "",
			end_is_vague : false,
			locations: [],
			involved : [],
			involved_roles : [],
			description : "",
			annotations : ""
		};
	}

	generate_new = function() {
		switch(_pentrytype) {
			case "event":
				var ev = generate_new_tevent();
				ev.punit = { name : "Rödental St. Hedwig", dn : "eb_bamberg/d_coburg/sb_cosl/p_roedental" };
				ev.start = "";
				return ev;
			case "tevent":
				return generate_new_tevent();
			case "away":
				return { uuid: _uuid, punit : { name : "Rödental St. Hedwig", dn : "eb_bamberg/d_coburg/sb_cosl/p_roedental" }, name: '', involveddb_id: '', reason: ''};
			case "keep_in_mind":
				return { uuid: _uuid, punit : { name : "Rödental St. Hedwig", dn : "eb_bamberg/d_coburg/sb_cosl/p_roedental" }, name: '', description: ''};
			case "todo":
				return { uuid: _uuid, punit : { name : "Rödental St. Hedwig", dn : "eb_bamberg/d_coburg/sb_cosl/p_roedental" }, name: '', description: '', involved: []};
			case "vehicle_use":
				return { uuid: _uuid, punit : { name : "Rödental St. Hedwig", dn : "eb_bamberg/d_coburg/sb_cosl/p_roedental" }, name: '', description: '', involved: [], vehicle_id: "r_pfarrbus"};
			}
	}

	this.deletedialog_handle_show = function(_this_, e){
		$etype = $(e.relatedTarget).attr('data-delete-type');
		$ename = $(e.relatedTarget).attr('data-delete-name');
		_this_.find('.modal-body p').text("Sind Sie sicher, dass Sie \"" + $ename + "\" als " + $etype + " löschen wollen?");

		console.log($etype);

		if($etype === "Dienst") {
			var fieldset = $(e.relatedTarget).closest('fieldset');
			_this_.find('.modal-footer #confirm').data('fieldset', fieldset);
		}
		else {
			// Pass form reference to modal for submission on yes/ok
			var tr = $(e.relatedTarget).closest('tr');

			_this_.find('.modal-footer #confirm').data('tr', tr);
		}
		_this_.find('.modal-footer #confirm').data('delete-type', $etype);
	};

	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;
	}

	this.deletedialog_handle_confirm = function(_this_) {
		console.log('dialog_handle_confirm');

		$('#confirmDelete').modal('hide');

		var my_messages = [];

		$etype = _this_.data('delete-type');
		console.log($etype);
		if($etype === "Dienst") {
			var fieldset = _this_.data('fieldset');
			var uid = fieldset.data('uid');
			fieldset = fieldset.parent();

			var found = remove_from_array_by_uid(_pentry.involved_roles, uid);
			console.log("removeing role; found: ", found, uid);
			var show_no_roles_message = false;
			var f_parent;
			if(fieldset.is(":last-child") && fieldset.is(":first-child")) {
				show_no_roles_message = true;
				f_parent = fieldset.parent();
				console.log(f_parent);
			}
			fieldset.remove();
			console.log(show_no_roles_message)
			if(show_no_roles_message)
				f_parent.append("<p>Keine Dienste angegeben.</p>");
		}
		else {
			var tr = _this_.data('tr');
			var uid = tr.data('uid');

			if($etype === "Ort") {
				var found = remove_from_array_by_uid(_pentry.locations, uid);

				if(found) {
					var tr = $('#confirmDelete').find('.modal-footer #confirm').data('tr');
					if(tr.is(":last-child") && tr.is(":first-child")) {
						var table = tr.closest("table");
						var t_parent = table.parent();
						table.remove();
						t_parent.append("<p>Keine Orte ausgewählt.</p>");
					}
					else
						tr.remove();

					my_messages.push({ type: "success", title: "Entfernen erfolgreich", message: "Der zu entfernende Ort wurde erfolgreich entfernt."});
				}
				else
					my_messages.push({ type: "danger", title: "Ort nicht gefunden", message: "Der zu entfernende Ort konnte nicht entfernt werden, da der angegeben Ort nicht gefunden werden konnte."});

				var html = messageview_inlay_template({messages:  my_messages});
				$('#messageview_locations').append(html);
				my_messages = {};
			}
			else {

				var the_involved = _pentry.involved;
				var role = '';
				if(_pentrytype === "event" || _pentrytype === "tevent") {
					role = tr.data('role');
					the_involved = this.get_involved_from_event(_pentry, role);
				}
				if(role === '')
					role = 'primary';

				if(the_involved === null) {
					console.log('REMOVING FROM ROLE '+ role);
					console.log("WARNING: role not found!");

					my_messages.push({ type: "danger", title: "Dienst nicht gefunden", message: "Der zu entfernende Betroffene konnte nicht entfernt werden, da der angegeben Dienst [" + role + "] nicht gefunden werden konnte."});
					var html=messageview_inlay_template({messages:  my_messages});
					my_messages = {}
					$('#messageview_involved_primary').append(html);
					return;
				}
				var found = remove_from_array_by_uid(the_involved, uid);
				if(found) {
					my_messages.push( { type: "success", title: "Entfernen erfolgreich", message: "Der zu entfernende Betroffene wurde erfolgreich entfernt."});

					var tr = $('#confirmDelete').find('.modal-footer #confirm').data('tr');
					if(tr.is(":last-child") && tr.is(":first-child")) {
						var table = tr.closest("table");
						var t_parent = table.parent();
						table.remove();
						t_parent.append("<p>Keine Beteiligten ausgewählt.</p>");
					}
					else
						tr.remove();
				}
				else
					my_messages.push( { 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."});

				var html = messageview_inlay_template({messages:  my_messages});
				$('#messageview_involved_' + role).append(html);
				my_messages = {};

				console.log(_pentry);
			}
		}
		this.intern_save_to_storage();
	};
}
