mixin emaildestinationview(dest_to, dest_cc, dest_bcc, show_add_button, add_action)
	.row
		fieldset#fieldset_to.col-sm-12.col-lg-4
			legend(style="font-size: 120%; margin-bottom: 0px;")
				table(width="100%")
					tr
						td Empfänger
						if show_add_button
							td(align="right")
								button(class="btn btn-primary btn-xs", onclick="#{add_action}") Empfänger hinzufügen
			#destination_to_parent
				if dest_to.length > 0
					table(width='100%', class='table table-condensed', style='margin-bottom: 10px;', id="destination_to")
						each empf in dest_to
							tr(data-addresses="#{empf.addresses}", data-recipient-name="#{empf.recipient_name}")
								td(class="the_email_recipient", width="90%") !{empf.recipient}
								td 
									span(	class="glyphicon glyphicon-trash", 
											aria-hidden="true", 
											style="color: red; padding-right: 10px; padding-left: 10px; cursor: pointer;" 
											data-toggle="modal", 
											data-target="#confirmDelete", 
											data-delete-type="to", data-delete-name="#{empf.recipient_name}")

				else
					p <i>Keine Empfänger in dieser Kategorie angegeben.</i>

		- var display_fieldset_cc = (dest_cc.length > 0 ? "" : "display_none_on_small_devices");
		fieldset(id="fieldset_cc", class=["col-sm-12", "col-lg-4", display_fieldset_cc])
			legend(style="font-size: 120%; margin-bottom: 0px;") Kopie
			#destination_cc_parent
				if dest_cc.length > 0
					table(width='100%', class='table table-condensed', style='margin-bottom: 10px;', id="destination_cc")
						each empf in dest_cc
							tr(data-addresses="#{empf.addresses}", data-recipient-name="#{empf.recipient_name}")
								td(class="the_email_recipient", width="90%") !{empf.recipient}
								td 
									span(	class="glyphicon glyphicon-trash", 
											aria-hidden="true", 
											style="color: red; padding-right: 10px; padding-left: 10px; cursor: pointer;" 
											data-toggle="modal", 
											data-target="#confirmDelete", 
											data-delete-type="cc", data-delete-name="#{empf.recipient_name}")
				else
					p <i>Keine Empfänger in dieser Kategorie angegeben.</i>
					
		- var display_fieldset_bcc = (dest_bcc.length > 0 ? "" : "display_none_on_small_devices");
		fieldset(style="margin-bottom: 10px;", id="fieldset_bcc", class=["col-sm-12", "col-lg-4", display_fieldset_bcc])
			legend(style="font-size: 120%; margin-bottom: 0px;") Blindkopie
			#destination_bcc_parent
				if dest_bcc.length > 0
					table(width='100%', class='table table-condensed', style='margin-bottom: 10px;', id="destination_bcc")
						each empf in dest_bcc
							tr(data-addresses="#{empf.addresses}", data-recipient-name="#{empf.recipient_name}")
								td(class="the_email_recipient", width="90%") !{empf.recipient}
								td 
									span(	class="glyphicon glyphicon-trash", 
											aria-hidden="true", 
											style="color: red; padding-right: 10px; padding-left: 10px; cursor: pointer;" 
											data-toggle="modal", 
											data-target="#confirmDelete", 
											data-delete-type="bcc", data-delete-name="#{empf.recipient-name}")

				else
					p <i>Keine Empfänger in dieser Kategorie angegeben.</i>

mixin email_do_group(elem)
	.panel.panel-info.parishdbelemspane_elem.col-sm-12.col-xs-12.col-lg-6(id="#{elem.uid}", data-elemname="#{elem.name}", data-parishdb="", data-dn="#{elem.dn}", data-elemtype="group")
		.panel-heading
			h4.panel-title #{elem.name}
				p.parishdbelemspane_elem_kontext #{elem.kontext}
		.panel-body(style="padding: 5px;")
			if elem.members_without_email.length > 0
				p(style="color: red; margin-bottom: 0px; font-weight: bold;") Achtung: In dieser Gruppe gibt es Mitglieder ohne eMail-Adresse:
				each member_wo in elem.members_without_email
					div(style="white-space: nowrap; display: inline-block;")
						- var member_title = member_wo.name;
						- if(member_wo.role.length > 0) member_title += " (" + member_wo.role + ")";
						span(class="glyphicon glyphicon-envelope", aria-hidden="true")
						span &nbsp;
						span(style="white-space: nowrap;") #{member_title} &nbsp; &nbsp;
				hr(style="margin-top: 5px; margin-bottom: 5px;")
				//- +do_groupmember(member, elem)
			p(style="color: green; margin-bottom: 0px; font-weight: bold;") Gruppenmitglieder
			each member in elem.members
				div(style="white-space: nowrap; display: inline-block;")
					- var member_title = member.name;
					- if(member.role.length > 0) member_title += " (" + member.role + ")";
					span(class="glyphicon glyphicon-envelope", aria-hidden="true")
					span &nbsp;
					span(style="white-space: nowrap;") #{member_title} &nbsp; &nbsp;
			hr(style="margin-top: 5px; margin-bottom: 5px;")
			- var more_than_one = [];
			- var only_one = [];
			- elem.members.forEach(function(el) { if(el.emailaddresses.length > 1) more_than_one.push(el); else only_one.push(el.emailaddresses[0].address) });
			- var only_one_addresses = only_one.join(';');
			if(more_than_one.length > 0)
				p(style="color: blue; margin-bottom: 0px; font-weight: bold;") Achtung: In dieser Gruppe gibt es Mitglieder mit mehr als einer eMail-Adresse; bitte wählen Sie die zu verwendende aus!
				each member in more_than_one
					- var member_title = member.name;
					- if(member.role.length > 0) member_title += " (" + member.role + ")";
					p(style="margin-bottom: 0px; white-space: nowrap;")
						span(class="glyphicon glyphicon-envelope", aria-hidden="true")
						span &nbsp;
						span(style="text-style: italic;") #{member.name}
					select(style="margin-bottom: 5px;")
						each adr in member.emailaddresses
							option(value="#{adr.address}") #{adr.address}
					.btn-group(style="margin-left: 10px;")
						button(type="button", class="btn btn-default btn-xs dropdown-toggle", data-toggle="dropdown", aria-haspopup="true" aria-expanded="false") Zusätzlich separate eMail versenden <span class="caret"></span>
						ul.dropdown-menu
							each adr in member.emailaddresses
								li
									span(style="font-weight: bold;")  #{adr.address}
									div(style="display: block;")
									button(	type="button", 
											class="btn btn-xs btn-default", 
											aria-hidden="true"
											onclick="add_email_address({'dest': 'to', 'name': '#{member_title}, Gruppe #{elem.name}', 'kontext': '#{elem.kontext}', 'description' : 'Gruppenmitglied, eMail #{adr.description}', 'address': '#{adr.address}'});",
											style="margin-bottom: 10px;"
											) An
									button(	type="button", 
											class="btn btn-xs btn-default", 
											aria-hidden="true"
											onclick="add_email_address({'dest': 'cc', 'name': '#{member_title}, Gruppe #{elem.name}', 'kontext': '#{elem.kontext}', 'description' : 'Gruppenmitglied, eMail #{adr.description}', 'address': '#{adr.address}'});",
											style="margin-bottom: 10px;"
											) Kopie
									button(	type="button", 
											class="btn btn-xs btn-default", 
											aria-hidden="true",
											onclick="add_email_address({'dest': 'bcc', 'name': '#{member_title}, Gruppe #{elem.name}', 'kontext': '#{elem.kontext}', 'description' : 'Gruppenmitglied, eMail #{adr.description}', 'address': '#{adr.address}'});",
											style="margin-bottom: 10px;"
											) Blindkopie
				hr(style="margin-top: 5px; margin-bottom: 5px;")
			button(	class="btn btn-xs btn-default", 
					aria-hidden="true", 
					onclick="add_email_address_group({'dest': 'to', 'name': '#{elem.name}', 'kontext': '#{elem.kontext}', 'description' : 'Gruppe', 'address': '#{only_one_addresses}'}, '#{elem.uid}');"
					) An
			button(	class="btn btn-xs btn-default", 
					aria-hidden="true", 
					onclick="add_email_address_group({'dest': 'cc', 'name': '#{elem.name}', 'kontext': '#{elem.kontext}', 'description' : 'Gruppe', 'address': '#{only_one_addresses}'}, '#{elem.uid}');"
					) Kopie
			button(	class="btn btn-xs btn-default", 
					aria-hidden="true", 
					onclick="add_email_address_group({'dest': 'bcc', 'name': '#{elem.name}', 'kontext': '#{elem.kontext}', 'description' : 'Gruppe', 'address': '#{only_one_addresses}'}, '#{elem.uid}');"
					) Blindkopie

mixin email_do_person(elem)
	.panel.panel-primary.parishdbelemspane_elem.col-sm-12.col-xs-12.col-lg-6(id="#{elem.uid}", data-elemname="#{elem.name}", data-parishdb="", data-dn="#{elem.dn}", data-elemtype="person")
		.panel-heading
			h4.panel-title #{elem.name}
				p.parishdbelemspane_elem_kontext #{elem.kontext}
		.panel-body(style="padding: 5px 15px;")
			table(style="width: 100%; margin-bottom: 2px;", class="table table-condensed")
				thead
					tr
						th 
							span(style="color: grey; font-size: 80%;") Beschreibung
						th
							span(style="color: grey; font-size: 80%;") Adresse
						th
				each eadr in elem.emailaddresses
					tr
						td(width="30%") #{eadr.description}
						td(widht="70%") #{eadr.address}
						td(align="right", style="white-space: nowrap;")
							button(	class="btn btn-xs btn-default", 
									aria-hidden="true", 
									onclick="add_email_address({'dest': 'to', 'name': '#{elem.name}', 'kontext': '#{elem.kontext}', 'description' : '#{eadr.description}', 'address': '#{eadr.address}'});"
									) An
							button(	class="btn btn-xs btn-default", 
									aria-hidden="true", 
									onclick="add_email_address({'dest': 'cc', 'name': '#{elem.name}', 'kontext': '#{elem.kontext}', 'description' : '#{eadr.description}', 'address': '#{eadr.address}'});"
									) Kopie
							button(	class="btn btn-xs btn-default", 
									aria-hidden="true", 
									onclick="add_email_address({'dest': 'bcc', 'name': '#{elem.name}', 'kontext': '#{elem.kontext}', 'description' : '#{eadr.description}', 'address': '#{eadr.address}'});"
									) Blindkopie

mixin email_directinput
	form(class="form-inline", id="form-emailaddresseditor-direct")
		.form-group
			label(for="emailinput", style="font-weight: normal; font-style: italic;") eMail - direkte Eingabe &nbsp;
			input(type="email", class="form-control noEnterSubmit", size="65", id="emailinput", value="peter@halieus.de", placeholder="Gültige eMail-Adresse eingeben, dann Empfangstyp wählen und auf 'Hinzufügen' klicken", required)
		select(class="form-control", id="emailinput_type")
			option(value="to") An
			option(value="cc") Kopie
			option(value="bcc") Blindkopie
		button(type="submit", class="btn btn-default") Hinzufügen

mixin email_scripts(after_email_added_todo, function_update_sendbutton, confirmdelete_id)
	script.
		function set_visibility_according_to_filter(substrRegex, elems) {
			var actual_dn = $("#actual_elem_dn").val();
			var actual_group = $("#actual_elem_group").val();
			
			elems.each(function(index) {
				var txt = $(this).data('elemname');
				
				var show = substrRegex.test(txt);
				if(show === false)
					show = substrRegex.test($(this).find('.parishdbelemspane_elem_kontext').text());

				if(show) {
					$(this).show();
				}
				else {
					$(this).hide();
				}
			});
		}

		function adjust_visible_elems(my_input) {
			console.log(my_input.value);
			
			// regex used to determine if a string contains the substring `q`
			substrRegex = new RegExp(my_input.value, 'i');
			
			set_visibility_according_to_filter(substrRegex, $("[data-parishdb]"));
		}
		
		function add_email_address(data) {
			console.log(data);
			var table_selector = "destination_" + data.dest;
			var the_table = $("#"+table_selector);
			console.log(the_table.length);
			
			$("#fieldset_" + data.dest).removeClass('display_none_on_small_devices');
			
			if(the_table.length === 0) {
				$("#"+table_selector+"_parent").empty();
				$("#"+table_selector+"_parent").append("<table width='100%' class='table table-condensed' style='margin-bottom: 10px;' id='" + table_selector + "'></table>");
				the_table = $("#"+table_selector);
				
				if(data.dest === "to") {
					#{function_update_sendbutton}(true);
					// $("#button_next").prop('disabled', false);
				}
			}
			
			if(data.description === "")
				data.description = "[als Gruppe]";

			var the_delete = '<span class="glyphicon glyphicon-trash" aria-hidden="true" style="color: red; padding-right: 10px; padding-left: 10px; cursor: pointer;" data-toggle="modal", data-target="#confirmDelete", data-delete-type="' + data.dest + '", data-delete-name="' + data.name + '"></span>';
			the_table.append("<tr data-addresses='" + data.address + "' data-recipient-name='" + data.name + "'><td class='the_email_recipient' width='90%;'><p style='margin-bottom: 0px;'>" + data.name + " (" + data.description + ")</p><p class='parishdbelemspane_elem_kontext', style='font-size: 80%;'>(" + data.kontext + ")</p></td><td>" + the_delete + "</td></tr>");
			
			!{after_email_added_todo}
		}
		
		function add_email_address_group(data, elem_uid) {
			var group_elem = $("#"+elem_uid);
			var selects = group_elem.find('select');
			console.log(selects);
			selects.each(function(index) {
				var selected_option = $(this).find("option:selected");
				var val = selected_option.val();
				console.log(val);
				data.address += ";" + val;
			})
			console.log(data);
			add_email_address(data);
		}
		
		$('##{confirmdelete_id}').on('show.bs.modal', function (e) {
			$etype = $(e.relatedTarget).attr('data-delete-type');
			$ename = $(e.relatedTarget).attr('data-delete-name');
			
			var _message = "Sind Sie sicher, dass Sie \"" + $ename + "\" als Anhang löschen wollen?";
			
			switch($etype) {
				case "to": _message = "Sind Sie sicher, dass Sie \"" + $ename + "\" als Empfänger löschen wollen?"; break;
				case "cc": _message = "Sind Sie sicher, dass Sie \"" + $ename + "\" als Empfänger einer Kopie löschen wollen?"; break;
				case "bcc": _message = "Sind Sie sicher, dass Sie \"" + $ename + "\" als Empfänger einer Blindkopie löschen wollen?"; break;
			};
			
			$(this).find('.modal-body p').text(_message);
			
			// 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);
		});
		
		$('##{confirmdelete_id}').find('.modal-footer #confirm').on('click', function() {
			$etype = $(this).data('delete-type');
			console.log($etype);
			
			if($etype === 'Anhang')
			{
				ws.send("fileupload_remove", {uid: $(this).data('tr').prop('id')});
				return;
			}
			
			var tr = $(this).data('tr');
			// ATTENTION: andere Behandlung als Attachments!!!
			if(tr.is(":last-child") && tr.is(":first-child")) {
				var table = tr.closest("table");
				var table_id = table.prop('id');
				var t_parent = table.parent();
				table.remove();
				t_parent.append("<p><i>Keine Empfänger in dieser Kategorie angegeben.</i></p>");
				if(table_id === "destination_to") {
					#{function_update_sendbutton}(false);
					//-$("#button_next").prop('disabled', true);
				}
			}
			else
				tr.remove();
				
			$('##{confirmdelete_id}').modal('hide');
		});
		
		ws.bind('fileupload_remove_result', function(data) {
			console.log(data);
		
			var tr = $("#"+data.uid);
			
			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><i>Keine Anhänge vorhanden.</i></p>");
			}
			else
				tr.remove();
				
			$('#confirmDelete').modal('hide');
		});
		
		function init_form_emailaddresschooser_direct() {
			$('#form-emailaddresseditor-direct').validator().on('submit', function(e) {
				if( ! e.isDefaultPrevented() )
				{
					console.log(e);
					var dest;
					switch($("#emailinput_type").prop("selectedIndex")) {
						case 1: dest="cc"; break;
						case 2: dest="bcc"; break;
						default: dest="to";
					}
					add_email_address({'dest': dest, 'name': $("#emailinput").val(), 'kontext': '-', 'description' : 'direkt', 'address': $("#emailinput").val()});
					e.preventDefault();
				}
			});
		}
		init_form_emailaddresschooser_direct();

		function get_emailaddresses_from_table(tableid) {
			var table = $(tableid);
			if(table.length === 0)
				return [];
			
			var trs = table.find('tr');
			console.log(trs);
			
			var addresses = [];
			
			trs.each(function(index) {
				addresses.push({ 'addresses' : $(this).data('addresses'), 'recipient_name' : $(this).data('recipient-name'), 'recipient' : $(this).find('.the_email_recipient').html() });
			});
			
			return addresses;
		}
