include mixins

mixin involved_list_label(name, style_label, style_headline, section_uid)
	- var link_add = ( section_uid === '' ? '' : '?role='+ section_uid +'' );
	- var glyphicon_class = ( section_uid === '' ? 'glyphicon-thumbs-up' : 'glyphicon-hand-right' );
	legend(style=style_label) 
		table(width="100%")
			tr
				td
					span(class=["glyphicon", glyphicon_class], aria-hidden="true")
					span 
					span(style=style_headline) #{name}
				td(align="right")
					if section_uid !== ""
						button(type="button", class="btn btn-default btn-xs", onclick="save_and_goto('#{event_href}/edit_role/#{section_uid}');")
							span(class="glyphicon glyphicon-edit", 	aria-hidden="true", style='color: blue; display: inline;')
						button(	type="button", class="btn btn-default btn-xs", 
							data-toggle="modal", data-target="#confirmDelete", data-delete-type="Dienst", data-delete-name="#{section_name}")
							span(class="glyphicon glyphicon-trash", aria-hidden="true", style='color: red; display: inline;')
					+dropdown_button("Hinzufügen", "new_involved", "right")
						+dropdown_button_element_href("Von Liste", 'javascript: save_and_goto("' +event_href + '/add_actor' + link_add +'");')
						+dropdown_button_element_href("Aus Datenbank", "#")
						+dropdown_button_element_href("Manuell", "#")

mixin involved_list(the_involved, section_name, section_uid)
	.col-sm-12(style="padding-right: 0px;")
		if the_involved.length === 0
			p Keine Beteiligten ausgewählt.
		else
			table(class="table table-condensed", style="margin-bottom: 5px;")
				thead
					tr
						th 
							span(style="color: grey;") Name
						th
				tbody
					each inv in the_involved
						tr(id="#{inv.uid}", data-uid="#{inv.uid}", data-role="#{section_uid}")
							td(width="80%") #{inv.name}
							td(align="right")
								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="Beteiligten aus dem Bereich '#{section_name}'", data-delete-name="#{inv.name}"
										)

mixin location_list(the_locations)
	.col-sm-12(style="padding-right: 0px;")
		if the_locations.length === 0
			p Keine Orte ausgewählt.
		else
			table(class="table table-condensed", style="margin-bottom: 5px;")
				thead
					tr
						th 
							span(style="color: grey;") Name
						th
							span(style="color: grey;") Signum
						th
				tbody
					each loc in the_locations
						tr(id="#{loc.uid}", data-uid="#{loc.uid}")
							td(width="80%") #{loc.name}
							td(widht="10%") #{loc.sign}
							td(align="right")
								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="Ort", data-delete-name="#{loc.name}"
										)

- var parent_event_uuid = (is_thereafter ? parent_event.uuid : "");

doctype html
html
	include header
	script(src='/javascripts/socket.io.js' )
	script(src="/javascripts/jquery.loading.min.js")
	link(href="/stylesheets/jquery.loading.min.css", rel="stylesheet")
	script(src="/javascripts/validator.min.js")
	body(style="overflow: hidden;")
	
		.modal.fade(id="confirmDelete", role="dialog", aria-labelledby="confirmDeleteLabel", aria-hidden="true")
			.modal-dialog
				.modal-content
					.modal-header
						button(type="button", class="close", data-dismiss="modal", aria-hidden="true") &times;
						h4(class="modal-title") Löschen bestätigen
					.modal-body
						p Sind Sie sicher, dass Sie das Ereignis löschen wollen?
					.modal-footer
						button(type="button", class="btn btn-default", data-dismiss="modal") Abbrechen
						button(type="button", class="btn btn-danger", id="confirm") Löschen
						
		
		.container-horizontal(style="overflow: hidden;")
    
			.flex-one(style="overflow: hidden; height: 100%;")
      
				.container-vertical
      
					.flex-zero
						+nav("PfarrInfoSystem: Ereignis bearbeiten", "dropdown_menu")
	
					.flex-one(style="overflow: auto; padding-left: 15px; padding-right: 15px;")
						
						p Ereignis am #{date.weekday_short}, #{date.day}. #{date.month} #{date.year} #{edit_type}.
						
						form(class="form-horizontal", role="form", id="form", method="POST", action="#{event_href}/commit")
							button(class="btn btn-success btn-xs", type="submit") 
								span(class="glyphicon glyphicon-ok", aria-hidden="true")
								span 
								span Übernehmen
								
							.form-group
								
								if ! is_thereafter
									label(for='edit_kontext', class="col-sm-2 control-label") Kontext
									.col-sm-10
										.input-group
											input(id="edit_kontext_dn", type="hidden", name="punit_dn", value="#{event.punit.dn}")
											input(id="edit_kontext", type="text", name="punit_name", class="form-control", value="#{event.punit.name}", readonly)
											span(class="input-group-btn")
												button(class="btn btn-default", type="button", onclick="save_and_goto('#{event_href}/select_pastoralunit')") Ändern
											
							.form-group
								label(for='edit_name', class="col-sm-2 control-label") Name
								.col-sm-10
									input(id='edit_name', type="text", class="form-control noEnterSubmit", name="edit_name", value="#{event.name}", required)
									.help-block.with-errors
										
							.form-group
								label(for='edit_name_secondary', class="col-sm-2 control-label") Zusatz zum Namen
								.col-sm-10
									input(id='edit_name_secondary', type="text", class="form-control noEnterSubmit", name="edit_name_secondary", value="#{event.name_secondary}")
									.help-block.with-errors
										
							.form-group
								label(for='combo_type', class="col-sm-2 control-label") Typ
								.col-sm-10
									select(id='combo_type', name="combo_type", class="form-control")
										option(value="gdx") Gottesdienst (außergewöhnlich)
										option(value="gd") Gottesdienst
										option(value="publx") Öffentlich (außergewöhnlich)
										option(value="publ") Öffentlich
										option(value="intern") Intern
										option(value="hidden") Verborgen
										
							script.
								/*switch("{event.pretty.visibility_short}")
								{
									case "[G+]":
										$("#combo_type").val("gdx");
										break;
									case "[G]":
										$("#combo_type").val("gd");
										break;
									case "[Ö+]":
										$("#combo_type").val("publx");
										break;
									case "[Ö]":
										$("#combo_type").val("publ");
										break;
									case "[I]":
										$("#combo_type").val("intern");
										break;
									case "[V]":
										$("#combo_type").val("hidden");
										break;
								}*/
								$("#combo_type").val("#{event.visibility}")

							if ! is_thereafter
								.form-group
									label(for='edit_begin', class="col-sm-2 control-label") Beginn
									.col-sm-5
										input(id='edit_begin', type="text", class="form-control noEnterSubmit", name="edit_begin",
														pattern="([01][0-9]|2[0-3]):[0-5][0-9]", 
														data-error="Bitte geben Sie eine gültige Uhrzeit ein!", 
														data-when_end_then_start="bar", 
														data-when_end_then_start-error="Wenn Sie ein Ende angeben, müssen Sie auch einen Beginn angeben!", 
														value="#{event.start}")
										.help-block.with-errors
								
							- var disable_end = is_thereafter && parent_event.start == "";
							.form-group(style="margin-bottom: 5px;")
								label(for='edit_end', class="col-sm-2 control-label") Ende
								.col-sm-5
									input(id='edit_end', type="text", class="form-control noEnterSubmit", name="edit_end",
													pattern="(([01][0-9]|2[0-3]):[0-5][0-9])|(24:00)", 
													data-error="Bitte geben Sie eine gültige Uhrzeit ein!", 
													data-end_after_start="bar", 
													data-end_after_start-error="Das Ende muss nach dem Beginn liegen!", 
													value="#{event.end}",
													disabled=disable_end)
									.help-block.with-errors
										if disable_end
											p Da das übergeordnete Ereignis keinen Beginn hat, können Sie hier kein Ende angeben!
							
										
							.form-group
								label(for='check_end_is_vague', class="col-sm-2 control-label", id="check_end_is_vague_label") Ende ist ungenau
								.col-sm-5.checkbox
									label
										input(id='check_end_is_vague', type="checkbox", name="check_end_is_vague", disabled=disable_end)
						
							script.
								if($('#edit_end').val().trim().length===0)
								{
									$('#check_end_is_vague').prop('disabled', true);
									$('#check_end_is_vague_label').css('color','grey');
								}
								
								$("#edit_end").on('keyup blur', function(){
									var disable_end_is_vague = (this.value.trim().length===0);
									$('#check_end_is_vague').prop('disabled', disable_end_is_vague);
									$('#check_end_is_vague_label').css('color', (disable_end_is_vague ? "grey" : "black"));
								});
													
							fieldset(class="col-xs-12 col-sm-6", style="margin-bottom: 20px;", id="locations")
								legend(style="font-size: 150%; margin-bottom: 10px;") 
									table(width="100%")
										tr
												td Orte
												td(align="right")
													+dropdown_button("Hinzufügen", "new_location", "right")
														+dropdown_button_element_href("Von Liste", "javascript: save_and_goto('" + event_href +"/add_predefined_location');")
														+dropdown_button_element_href("Manuell", "#")
								
								+location_list(event.locations)
															
							fieldset(class="col-xs-12 col-sm-6")
								legend(style="font-size: 150%;") Beteiligte
								
								fieldset(class="col-sm-12", style="padding-right: 0px;")
									+involved_list_label("Allgemein", "font-size: 130%; margin-bottom: 5px;", "font-style: italic;", "")
									+involved_list(event.involved, "Allgemein", "")
																
								fieldset(class="col-sm-12", style="margin-top: 15px; padding-right: 0px;")
									legend(style="font-size: 130%; margin-bottom: 10px;")
										table(width="100%")
											tr
												td
													span(class=["glyphicon", "glyphicon-thumbs-up"], aria-hidden="true")
													span 
													span(style=style_headline) <i>Dienste</i>
												td(align="right")
													button(type="button", class="btn btn-default btn-xs", onclick="save_and_goto('#{event_href}/add_role');")
														span(	class="glyphicon glyphicon-plus", aria-hidden="true")
														span 
														span Dienst hinzufügen
									
									if event.involved_roles.length === 0
										.col-sm-12
											p Keine Dienste angegeben
									else
										div
											each role in event.involved_roles
												fieldset(class="col-sm-12", style="padding-right: 0px; margin-top: 5px;", data-uid="#{role.uid}")
													+involved_list_label(role.name, "font-size: 120%; margin-bottom: 5px;", "font-weight: normal; font-style: italic;", role.uid)
													+involved_list(role.involved, role.name, role.uid)
										
							fieldset(class="col-sm-12", style="margin-top: 20px;")
								legend(style="font-size: 150%") Beschreibung
								textarea(class="form-control", rows="5", id="area_description", name="area_description").
									#{event.description}
									
							fieldset(class="col-sm-12", style="margin-top: 20px;")
								legend(style="font-size: 150%") Anmerkungen
								textarea(class="form-control", rows="5", id="area_annotations", name="area_annotations").
									#{event.annotations}
									
						br
						span &nbsp;
						br 
						span  &nbsp;
						br 
						span &nbsp;
						br 
						span &nbsp;
						br 
						span &nbsp;
						
		script.
			
			$('.noEnterSubmit').keypress(function(e){
				if ( e.which == 13 ) e.preventDefault();
			});
			
			var is_thereafter = #{is_thereafter};
			
			$(document).ready(function(){
			
			$('#form').validator({ 
				custom: {
							end_after_start: function(el) 
							{ 
								var start = "";
								if(is_thereafter)
									start = parent_event.start;
								else
									start =  $('#edit_begin').val();
								var end   = $('#edit_end').val();
								
								if(end.length === 0)
									return true;
								
								return Date.parse("2015-08-31T"+end) > Date.parse("2015-08-31T"+start);
							},
							when_end_then_start: function(el)
							{
								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 false;
									
								return true;
							}
						}, 
				errors: {
							end_after_start: "Das Ende des Ereignisses muss nach dessen Beginn liegen!",
							when_end_then_start: "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);
			})});
			
			var sockets = io.connect();
			
			$('#confirmDelete').on('show.bs.modal', function (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);
			});

			$('#confirmDelete').find('.modal-footer #confirm').on('click', function() {
				$etype = $(this).data('delete-type');
				console.log($etype);
				if($etype === "Dienst")
				{
					var fieldset = $(this).data('fieldset');
					var uid = fieldset.data('uid');
					var request = {day: "#{date.date}", event: "#{event.uuid}", uid: uid, is_thereafter: is_thereafter};
					if(is_thereafter)
						request.parent_event = "#{parent_event_uuid}"
					sockets.emit('event_remove_role', request);
				}
				else
				{
					var tr = $(this).data('tr');
					var uid = tr.data('uid');
					
					var request = {day: "#{date.date}", event: "#{event.uuid}", uid: uid, is_thereafter: is_thereafter};
					if(is_thereafter)
						request.parent_event = "#{parent_event_uuid}"
					
					if($etype === "Ort")
					{
						sockets.emit('event_remove_location', request);
					}
					else
					{
						var role = tr.data('role');
						request.role = role;
						sockets.emit('event_remove_involved', request);
					}
				}
			});
			
			sockets.on('event_remove_involved_result', function(data) {
				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();
				$('#confirmDelete').modal('hide');
			});
			
			sockets.on('event_remove_location_result', function(data) {
				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();
				$('#confirmDelete').modal('hide');
			});
			
			sockets.on('event_remove_role_result',function(data){
				var fieldset = $('#confirmDelete').find('.modal-footer #confirm').data('fieldset');
				
				var is_last_role = (fieldset.is(":last-child") && fieldset.is(":first-child"));
				var f_parent = fieldset.parent();
				
				fieldset.remove();
				if(is_last_role)
					f_parent.append("<div class='col-sm-12'><p>Keine Dienste angegeben.</p></div>")

				$('#confirmDelete').modal('hide');
			});
			
			function save_and_goto(href) {
			
				var event = {
					uuid : "#{event.uuid}",
					punit : { name : $("#edit_kontext").val(), dn : $("#edit_kontext_dn").val() },
					name : $("#edit_name").val(),
					name_secondary: $("#edit_name_secondary").val(),
					visibility: $("#combo_type").val(),
					end : $("#edit_end").val(),
					end_is_vague : $("#check_end_is_vague").prop("checked"),
					description : $("#area_description").val(),
					annotations : $("#area_annotations").val()
				};
				
				if( ! is_thereafter)
					event.start = $("#edit_begin").val();
				else
					event.parent_uuid = "#{parent_event_uuid}"

				console.log(event);
			
				sockets.emit('event_save', { day: "#{date.date}", event : event, is_thereafter : is_thereafter });
				location.assign(href);
			}
			
			// HANDLE SIMPLE BACK
			history.replaceState({direction: 'back'}, document.title, location.pathname);
			history.pushState({direction: 'actual'}, document.title, location.pathname);
			window.addEventListener("popstate", function(e) {
				console.log(e.state);
				if((e.state !== null) && (e.state.direction === "back")) {
					history.replaceState(null, document.title, location.pathname);
					setTimeout(function(){
						location.replace("#{event_href}/cancel");
					},0);
				}
			}, false);
			
