- var publicationformats_string = JSON.stringify(publicationformats);

include mixins
include mixins_pcalpub
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='/socket.io/socket.io.js')
	script(src='/siofu/client.js')
	script(src='/javascripts/pfiswebsocket.js')
	body(style="overflow: hidden;")
		
		+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
		
		.root
			.new_flex_zero
				+nav_with_form("PfarrInfoSystem", "PfIS", "entryeditnav")
				.container-fluid
					h1 Eine Terminveröffentlichung erstellen
			.new_flex_one
				.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) {
				$("#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>");
			}
			
			var publicationformats = !{publicationformats_string};
			
			var full = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');
			console.log(full);

			var sockets = io.connect(full+'/pcalpub');
			var siofu = new SocketIOFileUpload(sockets);
				
			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();
			
			// 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');
				
				sockets.emit('pcalpub_generate_html', { parishid : selectedParish, factoryid : selectedFactory, date: date, durance : durance, publicationformats : publicationformats});
				
				return false;
			}
			
			sockets.on('pcalpub_generate_html_result', function(data) {
				the_new_win.location=data.file;
				the_new_win.document.title=data.title;
			});
			
			// Do something on upload progress:
			siofu.addEventListener("progress", function(event){
				var percent = event.bytesLoaded / event.file.size * 100;
				//console.log("File is", percent.toFixed(2), "percent loaded");
				$("#fileinput_message").text("Date zu " + percent.toFixed(2) +"% hochgeladen.")
			});
		
			function pcalpub_generate_and_view_document() {
				//var mystate = save_settings();
				//sockets.emit('pcalpub_generate_and_view_document', mystate);
				
				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() == '')
					sockets.emit('pcalpub_generate_pdf', { parishid : selectedParish, factoryid : selectedFactory, date: date, durance : durance, use_background: false});
				else {
						siofu.submitFiles($('#fileinput').prop('files'));
					}
			}
			
			siofu.addEventListener("complete", function(event){
				$("#fileinput_message").text("Erfolgreich hochgeladen");
				
				var selectedParish = $("#combo_parish").prop('selectedIndex');
				var selectedFactory = $("#combo_factory").prop('selectedIndex');
				var durance = parseInt($("#combo_durance").val());
				var date = $("#datepicker").datepicker('getFormattedDate');
				
				sockets.emit('pcalpub_generate_pdf', { parishid : selectedParish, factoryid : selectedFactory, date: date, durance : durance, use_background: true, background_pdf: event.file.name});
			});
			
			sockets.on('pcalpub_generate_pdf_result', function(data) {
				the_new_win.location=data.file;
				the_new_win.document.title=data.title;
			});
			
			// ONE SHOT FUNCTIONS END
			
			var ws = new PfISWebSocket("#{sessionuuid}", "#{taskuuid}");
			
			var pcalpub_steps = { BACK : 0, SETTINGS : 1, EDITOR : 2, ADDRESSCHOOSER : 3, SUMMARY : 4 };
			var current_step  = pcalpub_steps.SETTINGS;
			var highest_reached_step = current_step;
			
			
			sockets.on('pcalpub_show_settings_result', function(data) {
				console.log('pcalpub_show_settings_result');
				
				$(".root").children(".subroot").remove();
				$(".root").append(data.html);
				
				activate_datepicker();
				update_buttons();
				
				current_step = pcalpub_steps.SETTINGS;
				
				//$('body').loading('stop');
			});
			
			function pcalpub_send_html_per_email() {
				var mydata = {
					publicationformats : publicationformats,
					parishid: $("#combo_parish").prop('selectedIndex'),
					factoryid: $("#combo_factory").prop('selectedIndex'),
					durance: parseInt($("#combo_durance").val()),
					date: $("#datepicker").datepicker('getFormattedDate')
				};
				console.log(mydata);
				sockets.emit('pcalpub_generate_html_for_email', mydata);
			}
			
			sockets.on('pcalpub_generate_html_for_email_result', function(data) {
				console.log('pcalpub_generate_html_for_email_result');
				console.log(data);
				
				$(".root").children(".subroot").remove();
				$(".root").append(data.html);
				
				//$(".subroot > .new_flex_one").scrollTop(0);
				
				if(highest_reached_step < pcalpub_steps.EDITOR) {
					highest_reached_step = pcalpub_steps.EDITOR;
					console.log('push EDITOR');
					history.pushState({	step: pcalpub_steps.EDITOR }, 'PfIS: Terminveröffentlichung (HTML)', document.pathname);
				}
				
				current_step = pcalpub_steps.EDITOR;
			});
			
			/*function save_html() {
				var mystate = {	direction: 'html_for_email_edit_from_saved',
								html : tinymce.get('html_for_email').getContent()
				};
				console.log(mystate);
				
				history.replaceState(mystate, 'PfIS: Terminveröffentlichung (HTML [saved])', location.pathname);
				return mystate;
			}*/
			
			function pcalpub_choose_addresses() {
				var mydata = {	html : tinymce.get('html_for_email').getContent() };
				
				sockets.emit('pcalpub_show_addresschooser', mydata);
			}
			
			sockets.on('pcalpub_show_addresschooser_result', function(data) {
				console.log('pcalpub_show_addresschooser_result', data.push_state);
				
				$(".root").children(".subroot").remove();
				$(".root").append(data.html);
				
				$(".subroot > .new_flex_one").scrollTop(0);
				
				if(highest_reached_step < pcalpub_steps.ADDRESSCHOOSER) {
					highest_reached_step = pcalpub_steps.ADDRESSCHOOSER;
					console.log('push ADDRESSCHOOSER');
					history.pushState({ step : pcalpub_steps.ADDRESSCHOOSER }, 'PfIS: Terminveröffentlichung (Adressen wählen)', document.pathname);
				}
				
				current_step = pcalpub_steps.ADDRESSCHOOSER;
			});
			
			function submit_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;
			}
			
			function submit_emailaddresses() {
				$("#entryeditnav-form").empty();
			
				var data = {
						dest_to : submit_emailaddresses_from_table("#destination_to"),
						dest_cc : submit_emailaddresses_from_table("#destination_cc"),
						dest_bcc : submit_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
					history.back();
					return;
				}
			
				//history.replaceState({direction: 'pcalpub_addresschooser_from_saved'}, 'PfIS: Terminveröffentlichung (Adressen wählen [saved])', document.pathname);
				console.log('SUBMIT EMAIL');
				sockets.emit('pcalpub_show_summary', data);
			}
			
			sockets.on('pcalpub_show_summary_result', function(data) {
				console.log('pcalpub_show_summary_result');
				
				$(".root").children(".subroot").remove();
				$(".root").append(data.html);
				
				if(highest_reached_step < pcalpub_steps.SUMMARY) {
					highest_reached_step = pcalpub_steps.SUMMARY;
					console.log('push SUMMARY');
					history.pushState({	step : pcalpub_steps.SUMMARY }, 'PfIS: Terminveröffentlichung (Zusammenfassung)', document.pathname);
				}
				
				current_step = pcalpub_steps.SUMMARY;
			});
			
			function pcalpub_generate_publication_send_html() {
				sockets.emit('pcalpub_generate_publication_send_html', {});
			}
			
			/*function pcalpub_generate_publication_send_html2() {
				history.replaceState({direction: 'pcalpub_summary_saved'}, 'PfIS: Terminveröffentlichung (Zusammenfassung [saved])');
				sockets.emit('pcalpub_generate_publication_send_html2', {});
			}
			
			sockets.on('pcalpub_generate_publication_send_html2_result', function(data) {
					$(".root").children(".subroot").remove();
					$(".root").append(data.html);
					
					history.pushState({	direction: 'pcalpub_sending2'}, 'PfIS: Terminveröffentlichung (Senden)', document.pathname);
					
					pcalpub_generate_publication_send_html();
			});*/
			
			function go_forward_to(step , func) {
				if(highest_reached_step >= step)
					history.forward();
				else
					func();
			}
			
			var is_sending = false;
			
			$('#sendEmail').on('show.bs.modal', function (e) {
				is_sending = true;
			
				/*history.replaceState({direction: 'pcalpub_summary_saved'}, 'PfIS: Terminveröffentlichung (Zusammenfassung [saved])');
				history.pushState({direction: 'disable_back'}, document.title, location.pathname);
				history.pushState({direction: 'sending'}, document.title, location.pathname);*/
				$("#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();
				
				pcalpub_generate_publication_send_html();
			});
			
			$("#sendEmail").on('hidden.bs.modal',  function(e) {
				is_sending = false;
				$("#button_summary_back").show();
				$("#button_summary_send").show();
			});
			
			sockets.on('pcalpub_generate_publication_send_html_step', function(step) {
				console.log('STEP', step);
				$("#" + step.id).removeClass($("#" + step.id).prop('class'));
				$("#" + step.id).addClass("glyphicon " + step.glyphicon);
			});
			
			sockets.on('pcalpub_generate_publication_send_html_result', function(result) {
				console.log('RESULT', result);
				$("#sendEmail_message").html(result.message);
				$("#sendEmail_explanation").html(result.explanation);
				$("#sendEmail_closebutton").show();
				
				/*if(result.result === "ERROR") {
					$("#button_summary_back").show();
					$("#button_summary_send").show();
				}*/
				
				/*if(result.result === "ERROR") {
					$("#summary_title").css('color', 'red');
					$("#summary_title").html("Die eMail konnte nicht erfolgreich übertragen werden. Bitte korrigieren Sie die Fehler bzw. versuchen es später noch einmal.");
				}
				else {
						$("#summary_title").css('color', 'green');
						$("#summary_title").html("Die eMail wurde erfolgreich übertragen. Sie können das Fenster nun schließen.");
					}*/
					
				//history.go(-2);
			});
			
			
			
			history.replaceState({step : pcalpub_steps.BACK}, document.title, location.pathname);
			history.pushState({step : pcalpub_steps.SETTINGS}, 'PfIS: Terminveröffentlichung (Einstellungen)', location.pathname);
			
			window.addEventListener("popstate", function(e) {
			
				$("#entryeditnav-form").empty();
			
				if(e.state !== null) {
					console.log(e.state);
					if(e.state.step === pcalpub_steps.BACK) {
						console.log(location.pathname);
						window.location.href = location.pathname;
					}
					if(e.state.step === pcalpub_steps.SETTINGS)
						sockets.emit('pcalpub_show_settings', {});
					else if(e.state.step === pcalpub_steps.EDITOR) {
						if(current_step < pcalpub_steps.EDITOR)
							pcalpub_send_html_per_email();
						else
							sockets.emit('pcalpub_show_html_for_email', {});
					}
					else if(e.state.step === pcalpub_steps.ADDRESSCHOOSER) {
						if(current_step < pcalpub_steps.ADDRESSCHOOSER)
							pcalpub_choose_addresses();
						else if(is_sending === true)
							history.forward(); // we are about to go back from SUMMARY - do not allow that if sending!!!
						else
							sockets.emit('pcalpub_show_addresschooser_from_saved', {});
					}
					else if(e.state.step === pcalpub_steps.SUMMARY && ! is_sending) {
						if(current_step < pcalpub_steps.SUMMARY) {
							console.log("AABB");
							submit_emailaddresses();
						}
						else {
							console.log("WRONG");
							sockets.emit('pcalpub_show_summary_from_saved', {});
							}
					}
				}
			}, false);
