include mixins
include mixins_email

doctype html
html
	include header
	link(href="/stylesheets/bootstrap-datepicker.min.css", rel="stylesheet")
	script(src='/javascripts/bootstrap-datepicker.min.js' )
	script(src='/javascripts/bootstrap-datepicker.de.min.js' )
	script(src='/javascripts/tinymce/tinymce.min.js' )
	script(src="/javascripts/validator.min.js")
	script(src='/javascripts/pfiswebsocket.js')
	body
		
		+standard_delete_dialog("confirmDelete")
						
		.modal.fade(id="sendEmail", role="dialog", aria-labelledby="sendEmailLabel", aria-hidden="true")
			.modal-dialog(role="document")
				.modal-content
					.modal-header
						h4(class="modal-title", id="sendEmailLabel") eMail versenden
					.modal-body
						p(style="font-weight: bold; font-style: italic;") Bitte warten Sie, während die eMail versendet wird ...
						#sendEmail_message
						#sendEmail_explanation
					.modal-footer
						button#sendEmail_closebutton(type="button", class="btn btn-default", data-dismiss="modal", style="display: none;") Schließen
						
		#emailaddresschooser.sidewideoverlay(style="z-index: 5;")
			.root
				.new_flex_zero
					+nav_with_form("PfarrInfoSystem", "PfIS", "entryeditnav")
					p.pentryedit_headline eMail-Empfänger auswählen
					
				.new_flex_one(style="margin-bottom: 15px; padding-left: 15px; padding-right: 15px; overflow: auto;")
					+email_directinput
					.parishdbelemspane(style="margin-top: 5px;")
						for elem in parishdb
							if elem.type === "person"
								+email_do_person(elem)
							if elem.type === "group"
								+email_do_group(elem)
		
		.root

			.new_flex_zero
				+nav("PfarrInfoSystem", "dropdown_menu")
				p.pentryedit_headline eMail versenden 
					button.btn.btn-success.btn-xs#sendbutton(style="margin-left: 15px; margin-right: 5px;", data-toggle="modal" data-target="#sendEmail") Senden
					span.glyphicon.glyphicon-info-sign#sendbutton_info(aria-hidden="true", style="color: red;", data-toggle="tooltip" data-placement="bottom" title="Sie müssen mindestens einen Empfänger sowie den Betreff angeben!")
				
			.new_flex_one(style="margin-bottom: 15px; padding-left: 15px; padding-right: 15px; overflow: auto;")
				+emaildestinationview([], [], [], true, "history.pushState({direction: 'emailchooser'}, document.title, location.pathname); $('#emailinput').val('peter@halieus.de'); $('#emailaddresschooser').show();")
				fieldset(id="fieldset_subject")
					legend(style="font-size: 120%; margin-bottom: 0px;") Betreff
					//- form#form-subject
					//-	.form-group
					input(type="text", id="subject", class="control-label col-xs-12", oninput="update_sendbutton();")
				fieldset(id="fieldset_body", style="margin-top: 5px;")
					legend(style="font-size: 120%; margin-bottom: 0px;") Nachricht
					textarea#bodyeditor
				fieldset(style="margin-top: 5px;")
					legend(style="font-size: 120%; margin-bottom: 0px;") Anhänge
						span(style="font-size: 65%; margin-left: 2px;") Zum Hinzufügen auf den Button unten klicken!
					#attachments_parent
						p <i>Keine Anhänge vorhanden.</i>
								//-	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}")
				
				
				input(type="file", id="fileupload", style="margin-top: 0px;")
				p#upload_pending_indicator(style='display: none; text-style: italic;') Datei wird hochgeladen...
				//- button#fileuploadbutton(type="button", class="btn btn-default btn-xs", onclick="do_fileupload();", disabled) Datei hochladen
			
			
		script.
			$("#sendbutton").prop('disabled', 'true');
			
			$(function () {
				$('[data-toggle="tooltip"]').tooltip();
			})
			
			tinymce.editors=[];
			tinymce.init({
				selector: '#bodyeditor',
				resize: false,
				language: 'de',
				plugins: 'advlist,autolink,autoresize,lists,link,image,charmap,print,preview,anchor,searchreplace,visualblocks,code,insertdatetime,media,table,contextmenu,paste',
				toolbar: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image',
				autoresize_bottom_margin: 5,
				autoresize_min_height: 150
				});
			
			
			$("#entryeditnav-form").on('submit', function(e){
				console.log('FILTER SUBMIT');
				e.preventDefault();
			});
			
			function show_searchbar(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>");
			}
			show_searchbar("adjust_visible_elems(this);"); // can always be on!!!
			
			var __cache_to_is_filled = false;
			function update_sendbutton(to_is_filled) {
				if(typeof to_is_filled !== 'undefined')
					__cache_to_is_filled = to_is_filled;
				console.log('update_sendbutton: ', to_is_filled, __cache_to_is_filled);
				if(__cache_to_is_filled && $('#subject').val() != '') {
					$('#sendbutton').prop('disabled', false);
					$('#sendbutton_info').hide();
				}
				else {
					$('#sendbutton').prop('disabled', true);
					$('#sendbutton_info').show();
				}
			}
			
			var ws = new PfISWebSocket("#{sessionuuid}", "#{taskuuid}");
			ws.bind_standard_close_handler();
			
			$("#fileupload").on('change', function(e){
				var files=$("#fileupload").prop('files');
				/*if(files.length === 0)
					$("#fileuploadbutton").prop('disabled', true);
				else
					$("#fileuploadbutton").prop('disabled', false);*/
				do_fileupload();
			});
			
			function do_fileupload() {
				var files=$("#fileupload").prop('files');
				if(files.length === 0)
					return;
				console.log(files);
				console.log(files.length);
				
				$("#upload_pending_indicator").show();
				
				// $("#fileuploadbutton").prop('disabled', true);
	
				for (var i = 0, numFiles = files.length; i < numFiles; i++) {
					var file = files[i];
					console.log(file.name);
					console.log(file.size);
					console.log(file.type);
					
					var reader = new FileReader();
					reader.onload = (function(aFile) { return function(e) { 
							var data = {
								name : aFile.name,
								size : aFile.size,
								type : aFile.type,
								content : e.target.result,
								uid : generateUID()
							};
							
							ws.send('fileupload', data);
						}})(file);
					reader.readAsDataURL(file);
				}
				$("#fileupload").val('');
			}
			
			ws.bind('fileupload_result', function(data) { console.log(data); add_attachment(data)});
			
			function add_attachment(file) {
				var the_table = $("#attachments");
		
				if(the_table.length === 0) {
					$("#attachments_parent").empty();
					// <thead><tr><td width='75%'><span style='color: grey; font-size: 80%;'>Name</span></td><td width='20%'><span style='color: grey; font-size: 80%;'>Typ</span></td><td width='5%'></td></tr></thead>
					$("#attachments_parent").append("<table width='100%' class='table table-condensed' style='margin-bottom: 0px;' id='attachments'></table>");
					the_table = $("#attachments");
				}
				
				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="Anhang", data-delete-name="' + file.name + '"></span>';
				//  width='90%'
				the_table.append("<tr id='" + file.uid + "'><td><p style='margin-bottom: 0px;'>" + file.name + "</p><p class='parishdbelemspane_elem_kontext', style='font-size: 80%;'>(" + file.type + ")</p></td><td width='5%'>" + the_delete + "</td></tr>");
				
				$("#upload_pending_indicator").hide();
			}
	
			var is_sending = false;
	
			$('#sendEmail').on('show.bs.modal', function (e) {
				is_sending = true;
			
				$("#sendEmail_message").html("");
				$("#sendEmail_explanation").html("");
				$("#sendEmail_closebutton").hide();
				
				var data = {
						dest_to : get_emailaddresses_from_table("#destination_to"),
						dest_cc : get_emailaddresses_from_table("#destination_cc"),
						dest_bcc : get_emailaddresses_from_table("#destination_bcc"),
						subject : $("#subject").val(),
						body : tinymce.get('bodyeditor').getContent(),
						body_raw: tinymce.get('bodyeditor').getContent({format : 'text'})
					};
					
				ws.send('email_send', data);
			});
			
			$("#sendEmail").on('hidden.bs.modal',  function(e) {
				is_sending = false;
				$("#button_summary_back").show();
				$("#button_summary_send").show();
			});
			
			ws.bind('email_send_result', function(result) {
				console.log('RESULT', result);
				$("#sendEmail_message").html(result.message);
				$("#sendEmail_explanation").html(result.explanation);
				$("#sendEmail_closebutton").show();
			});
			
			history.pushState   ({direction: 'main'}, document.title, location.pathname);
			
			window.addEventListener("popstate", function(e) {
				if(e.state !== null) {
					console.log(e.state);
					if(e.state.direction === 'main')
						$('#emailaddresschooser').hide();
					else if(e.state.direction === 'emailchooser')
						$('#emailaddresschooser').show();
				}
			}, false);
			
		+email_scripts("$('#emailaddresschooser').hide();", "update_sendbutton", "confirmDelete")
