- var publicationformats_string = JSON.stringify(publicationformats);

include mixins
include mixins_pcalpub
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')
	script(src='/templates/emailaddresschooser_inlay.js')
	script(src='/templates/pcalpub_summary.js')
	script(src="/javascripts/runtime.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 folgenden Schritte ausgeführt werden:
						table(class="table table-condensed")
							tr
								td
									span#status_collect(class="glyphicon glyphicon-unchecked", aria-hidden="true")
								td <b>Sammle Informationen</b>
							tr
								td
									span#status_convert(class="glyphicon glyphicon-unchecked", aria-hidden="true")
								td <b>Konvertiere Daten in das DOC-Format</b>
							tr
								td
									span#status_send(class="glyphicon glyphicon-unchecked", aria-hidden="true")
								td <b>Versende eMail</b>
						#sendEmail_message
						#sendEmail_explanation
					.modal-footer
						button#sendEmail_closebutton(type="button", class="btn btn-default", data-dismiss="modal", style="display: none;") Schließen
						
		.modal.fade(id="initSendingDialog", role="dialog", aria-labelledby="initSendingLabel", aria-hidden="true")
			.modal-dialog(role="document")
				.modal-content
					.modal-header
						h4(class="modal-title", id="initSendingLabel") TV per eMail senden
					.modal-body
						p(style="font-weight: bold; font-style: italic;") Bitte warten Sie, während die eMail vorbereitet wird ...
						
		#emaileditor.sidewideoverlay(style="z-index: 5;")
			.root
				.new_flex_zero
					+nav("PfarrInfoSystem", "emaileditor_menu")
					.container-fluid
						h1 Eine Terminveröffentlichung erstellen
							.small eMail vor dem Versenden bearbeiten
						h4
							span#emaileditor_parish_name
							span : 
							span#emaileditor_factory_name
							.small#emaileditor_timespan(style="font-size: 80%; white-space: nowrap;")
						nav
							ul.pager
								li.previous
									span(onclick="$('#mainpanel').show(); $('#emaileditor').hide();  $('html, body').scrollTop(0);") Zurück
								li.next
									span(onclick="save_html();") Weiter
				.new_flex_one#editorparent
					div(style="margin-bottom: 15px; margin-left: 15px; margin-right: 15px;")
						textarea#html_for_email
							
		#addresschooser.sidewideoverlay(style="z-index: 10;")
			.root
				.new_flex_zero
					+nav_with_form("PfarrInfoSystem", "PfIS", "entryeditnav")
					.container-fluid
						h1 Eine Terminveröffentlichung erstellen
							.small Adressaten auswählen
						h4
							span#addresschooser_parish_name
							span : 
							span#addresschooser_factory_name
							.small#addresschooser_timespan(style="font-size: 80%; white-space: nowrap;")
						nav
							ul.pager
								li.previous
									span(onclick="show_emaileditor('#addresschooser');") Zurück
								li.next.disabled
									span#addresschooser_next_button(	onclick="if($(this).parent().hasClass('disabled')){return;} save_emailaddresses();",
																		title="Sie müssen mindestens einen Empfänger angeben!"
																		) Weiter
						+emaildestinationview([], [], [], false, "")
				.new_flex_one
					.container-fluid#addresschooserpane
						
		#summary.sidewideoverlay(style="z-index: 15;")
			.root
				.new_flex_zero
					+nav("PfarrInfoSystem", "summary_nav")
					.container-fluid
						h1 Eine Terminveröffentlichung erstellen
							.small Zusammenfassung
						h4
							span#summary_parish_name
							span : 
							span#summary_factory_name
							.small#summary_timespan
						p Bitte überprüfen Sie nochmal alle Angaben!
						nav
							ul.pager
								li.previous
									a(href="#", onclick="show_addresschooser('#summary');") Zurück
								li.next
									a(href="#", data-toggle="modal", data-target="#sendEmail", data-backdrop="static", data-keyboard="false") eMail senden
				.new_flex_one
					.container-fluid#summarypane

		#mainpanel
			.root
				.new_flex_zero
					+nav("PfarrInfoSystem", "mainmenu")
					.container-fluid
						h1 Eine Terminveröffentlichung erstellen
				.new_flex_one(style="margin-bottom: 10px;")
					.container-fluid
						+pcalpubsettings(0,0,2, date, publicationformats)
			
		script.
			$("#entryeditnav-form").on('submit', function(e){
				console.log('FILTER SUBMIT');
				e.preventDefault();
			});
			
			function show_searchbar(functiontocall) {
				console.log($("#entryeditnav-form"));
				$("#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);");
			
			var publicationformats = !{publicationformats_string};
			
			var full = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');
			console.log(full);

			function activate_datepicker() {
				$('#datepicker').datepicker({format: "yyyy-mm-dd", language: "de", calendarWeeks: true, todayHighlight: true});
			}
			
			activate_datepicker();
			
			function update_factories() {
				var optionSelected = $("#combo_parish").prop('selectedIndex');
				
				$("#combo_factory").empty();
				
				for(idx = 0; idx < publicationformats[optionSelected].publicationformats.length; ++idx) {
					var factory = publicationformats[optionSelected].publicationformats[idx];
					$("#combo_factory").append($("<option></option>").text(factory.name));
				}
				
				update_buttons();
			}
		
			function update_buttons() {
				var selectedParish = $("#combo_parish").prop('selectedIndex');
				var selectedFactory = $("#combo_factory").prop('selectedIndex');
				
				var factory = publicationformats[selectedParish].publicationformats[selectedFactory];
				
				console.log(factory);
				
				if(factory.can_html) {
					$("#btn_html").prop('disabled', false);
					$("#btn_email").prop('disabled', false);
				}
				else {
					$("#btn_html").prop('disabled', true);
					$("#btn_email").prop('disabled', true);
				}
				
				if(factory.can_custom_background)
					$("#fileinput").prop('disabled', false);
				else
					$("#fileinput").prop('disabled', true);
			}
			update_buttons();
			
			// WebSocket setup
			
			var ws = new PfISWebSocket("#{sessionuuid}", "#{taskuuid}");
			ws.bind_standard_close_handler();
			
			// ONE SHOT FUNCTIONS BEGIN
			
			var the_new_win;
			
			function pcalpub_generate_html() {
				console.log('btn_html');
				
				the_new_win = window.open('', '_blank');
				
				var selectedParish = $("#combo_parish").prop('selectedIndex');
				var selectedFactory = $("#combo_factory").prop('selectedIndex');
				var durance = parseInt($("#combo_durance").val());
				var date = $("#datepicker").datepicker('getFormattedDate');
				
				ws.send('pcalpub_generate_html', { parishid : selectedParish, factoryid : selectedFactory, date: date, durance : durance});
				
				return false;
			}
			
			ws.bind('pcalpub_generate_html_result', function(data) {
				the_new_win.location=data.file;
				the_new_win.document.title=data.title;
			});
			
			function pcalpub_generate_and_view_document() {
				the_new_win = window.open('', '_blank');
				
				var selectedParish = $("#combo_parish").prop('selectedIndex');
				var selectedFactory = $("#combo_factory").prop('selectedIndex');
				var durance = parseInt($("#combo_durance").val());
				var date = $("#datepicker").datepicker('getFormattedDate');
				
				if($("#fileinput").val() == '')
					ws.send('pcalpub_generate_pdf', { parishid : selectedParish, factoryid : selectedFactory, date: date, durance : durance, use_background: false});
				else {
					var files = $('#fileinput').prop('files');
					console.log(files);
					console.log(files.length);
					
					$("#upload_pending_indicator").show();
					
					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
								};
								
								ws.send('fileupload', data);
							}})(file);
						reader.readAsDataURL(file);
					}
				}
			}
			
			ws.bind('fileupload_result', function(data) { 
				if(data.result === "ERROR") {
					alert(data.message);
					return;
				}
				console.log('fileupload_result', data); 
				$("#upload_pending_indicator").hide(); 
				
				var selectedParish = $("#combo_parish").prop('selectedIndex');
				var selectedFactory = $("#combo_factory").prop('selectedIndex');
				var durance = parseInt($("#combo_durance").val());
				var date = $("#datepicker").datepicker('getFormattedDate');
				
				ws.send('pcalpub_generate_pdf', { parishid : selectedParish, factoryid : selectedFactory, date: date, durance : durance, use_background: true });
			});
			
			ws.bind('pcalpub_generate_pdf_result', function(data) {
				the_new_win.location=data.file;
				the_new_win.document.title=data.title;
			});
			
			// ONE SHOT FUNCTIONS END
			
			function pcalpub_send_html_per_email() {
				$('#initSendingDialog').modal({
					backdrop: 'static',
					keyboard: false
				});
		
				var mydata = {
					publicationformats : publicationformats,
					parishid: $("#combo_parish").prop('selectedIndex'),
					factoryid: $("#combo_factory").prop('selectedIndex'),
					durance: parseInt($("#combo_durance").val()),
					date: $("#datepicker").datepicker('getFormattedDate')
				};
				ws.send('init_send_per_email', mydata);
			}
			
			tinymce.editors=[];
			tinymce.init({
				selector: '#html_for_email',
				height: '100%',
				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
				});
			
			ws.bind('init_send_per_email_result', function(data) {
				console.log('generate_html_for_email_result');
				
				if(data.result === "ERROR") {
					alert(data.message);
					$("#initSendingDialog").modal('hide');
					return;
				}

				// setup emaileditor
				$("#emaileditor_parish_name").text(data.parish_name);
				$("#emaileditor_factory_name").text(data.factory_name);
				$("#emaileditor_timespan").text(data.timespan);
				tinymce.get('html_for_email').setContent(decodeURIComponent(escape(window.atob(data.html))));
				
				// setup addresschooser
				$("#addresschooser_parish_name").text(data.parish_name);
				$("#addresschooser_factory_name").text(data.factory_name);
				$("#addresschooser_timespan").text(data.timespan);
				var myhtml = emailaddresschooser_inlay_template({parishdb: data.parishdb});
				$("#addresschooserpane").html(myhtml);
				init_form_emailaddresschooser_direct();
				
				// setup summary
				$("#summary_parish_name").text(data.parish_name);
				$("#summary_factory_name").text(data.factory_name);
				$("#summary_timespan").text(data.timespan);
				
				show_emaileditor("#mainpanel");
				
				$("#initSendingDialog").modal('hide');
			});
			
			function show_emaileditor(calling_from_id) {
				$("#emaileditor").show();
				$(calling_from_id).hide();
				setTimeout(function(){ 
						tinymce.get('html_for_email').execCommand('mceAutoResize'); 
						$("#editorparent").scrollTop(0); 
					}, 100);
				$("html, body").scrollTop(0);
			}
			
			function update_sendbutton(to_is_filled) {
				console.log('update_sendbutton: ', to_is_filled);
				if(to_is_filled) {
					$('#addresschooser_next_button').parent().removeClass('disabled');
					$('#addresschooser_next_button').prop('title','');
				}
				else {
					$('#addresschooser_next_button').parent().addClass('disabled');
					$('#addresschooser_next_button').prop('title','Sie müssen mindestens einen Empfänger angeben!');
				}
			}
	
			function save_html() {
				var mydata = {	html : tinymce.get('html_for_email').getContent() };
				ws.send('save_html', mydata);
			}
			
			ws.bind('save_html_result', function(data) {
				if(data.result === "ERROR") {
					alert(data.message);
					return;
				}
				show_addresschooser("#emaileditor");
			});
			
			function show_addresschooser(calling_from_id) {
				$("#addresschooser").show();
				$(calling_from_id).hide();
				$("#addresschooserpane").parent().scrollTop(0);
				$("html, body").scrollTop(0);
			}
		
			function save_emailaddresses() {
				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")
					};
					
				if(data.dest_to.length === 0) {
					// this has not to happen, but might happen, if we click 'forward' with removed email-adresses!!!
					// -> go back
					console.log('ERROR_IN_SUBMIT_EMAILADDRESSES!');
					return;
				}
				ws.send('save_emailaddresses', data);
			}
			
			ws.bind('save_emailaddresses_result', function(data) {
				if(data.result === "ERROR") {
					alert(data.message);
					return;
				}
				var myhtml = pcalpub_summary_template(data);
				$("#summarypane").html(myhtml);
				show_summary('#addresschooser')
			});
			
			function show_summary(calling_from_id) {
				$("#summary").show();
				$(calling_from_id).hide();
				$("#summarypane").parent().scrollTop(0);
				$("html, body").scrollTop(0);
			}
			
			$('#sendEmail').on('show.bs.modal', function (e) {
				is_sending = true;

				$("#status_collect").prop("class", "glyphicon glyphicon-unchecked");
				$("#status_convert").prop("class", "glyphicon glyphicon-unchecked");
				$("#status_send").prop("class", "glyphicon glyphicon-unchecked");
				$("#sendEmail_message").html("");
				$("#sendEmail_explanation").html("");
				$("#sendEmail_closebutton").hide();
				
				$("#button_summary_back").hide();
				$("#button_summary_send").hide();
				
				ws.send('send_html', {});
			});
			
			$("#sendEmail").on('hidden.bs.modal',  function(e) {
				is_sending = false;
				$("#button_summary_back").show();
				$("#button_summary_send").show();
			});
			
			ws.bind('send_html_step', function(step) {
				console.log('STEP', step);
				$("#" + step.id).removeClass($("#" + step.id).prop('class'));
				$("#" + step.id).addClass("glyphicon " + step.glyphicon);
			});
			
			ws.bind('send_html_result', function(result) {
				/*if(result.result === "ERROR") {
					alert(result.message);
					return;
				}*/

				console.log('RESULT', result);
				$("#sendEmail_message").html(result.message);
				$("#sendEmail_explanation").html(result.explanation);
				$("#sendEmail_closebutton").show();
			});
			
	+email_scripts("", "update_sendbutton", "confirmDelete")
