include mixins
include mixins_day

doctype html
html(lang="de", xml:lang="de", xmlns="http://www.w3.org/1999/xhtml")
	include header
	script(src='/javascripts/pfiswebsocket.js')
	script(src='/templates/daycontent.js')
	script(src='/templates/timelinecontent.js')
	script(src='/templates/timeline_eventdetails.js')
	script(src='/templates/pastoralteamcontent.js')
	script(src='/templates/pfarreientimelinecontent.js')
	script(src='/templates/errorview_inlay.js')
	script(src='/templates/pcal/pentry_clone_move.js')
	script(src='/templates/pcal/pentry_clone_move_parishday.js')
	script(src='/javascripts/pcal_pentry_clone_move_manager.js')
	script(src='/templates/pcal/pentry_edit.js')
	script(src='/templates/pcal/edit_event.js')
	script(src='/templates/pcal/edit_away.js')
	script(src='/templates/pcal/edit_todo.js')
	script(src='/templates/pcal/edit_keep_in_mind.js')
	script(src='/templates/pcal/edit_vehicle_use.js')
	script(src='/templates/actorselector_inlay.js')
	script(src='/templates/pastoralunitselector_inlay.js')
	script(src='/templates/locationselector_inlay.js')
	script(src='/templates/locationeditor_inlay.js')
	script(src='/templates/roleeditor_inlay.js')
	script(src='/templates/involvededitor_inlay.js')
	script(src='/templates/messageview_inlay.js')
	script(src='/templates/parishdbpersongroupselector_inlay.js')
	script(src='/javascripts/pcal_pentry_edit_manager.js')
	script(src="/javascripts/typeahead.jquery.min.js")
	link(href="/stylesheets/mytypeahead.css", rel="stylesheet")
	script(src="/javascripts/validator.min.js")
	script(src='/javascripts/runtime.js')
	link(href="/stylesheets/bootstrap-datepicker.min.css", rel="stylesheet")
	script(src='/javascripts/bootstrap-datepicker.min.js' )
	script(src='/javascripts/bootstrap-datepicker.de.min.js' )
	link(href="/stylesheets/style_day.css", rel="stylesheet")
	link(href="/stylesheets/style_week.css", rel="stylesheet")
	style.
		.block-relative { position: relative; width: 100%; }
		.block-absolute { position: absolute; padding-left: 2px; padding-right: 2px; padding-bottom: 2px;}
		.timepoint { font-size: 80%; position: absolute; border-top-style: dotted; border-top-width: 1px; border-top-color: grey; right: -15px; left: -15px; z-index: -5; }
		
		/* for pentry_clone_move */
		.cell_element { display: table-cell; }
		.td_new_celebration { padding-top: 10px; }
		.give_margin_left { padding-left: 10px; }
		@media only screen and (max-width: 768px) {
			.cell_element {
				display: block;
				margin-bottom: 15px;
			}
			.td_new_celebration { padding-top: 0px; }
			.give_margin_left { padding-left: 0px; }
		}

		/* for pentry_edit */
		.panel { margin-bottom: 5px; }
		.panel-title { cursor: pointer; }
		//- .panel_group_and_unit { border-width: 3px; }
		
		/* The sticky class is added to the header with JS when it reaches its scroll position */
		.sticky {
			position: fixed;
			top: 0;
			z-index: 5;
		}
		
	body
		script.
			console.log(history.state);
			
			if(history.state === null || typeof history.state.direction === 'undefined')
			{
				history.replaceState({direction: 'back'}, document.title, "/#{viewformat}/#{date.date}?back=false");
				history.pushState({direction: 'mainpage', date: "#{date.date}", scrollto: ''}, document.title, "/#{viewformat}/#{date.date}");
			}
			else
				console.log(history.state.direction);
		
				
		.modal.fade(id="daypickerDialog", role="dialog", aria-labelledby="daypickerDialogLabel", aria-hidden="true")
			.modal-dialog(role="document")
				.modal-content
					.modal-header
						button(type="button", class="close", data-dismiss="modal", aria-hidden="true") &times;
						h4(class="modal-title" id="daypickerDialogLabel") Datum anspringen
					.modal-body
						#datepicker()
					.modal-footer
						button(type="button", class="btn btn-default", data-dismiss="modal") Abbrechen
						button(type="button", class="btn btn-success", id="confirm") Anspringen
						
		+standard_delete_dialog("confirmDelete")
		
		#pentry_clone_move_parent.sidewideoverlay(style="z-index: 5;")
			
		#pentry_edit_parent.sidewideoverlay(style="z-index: 5;")

		#daymainview.root
		
			.new_flex_zero
				+nav_main_primary(viewformat, date.date)
					
			#dataparent.subroot.full_height(style="margin-top: 5px;")
				if viewformat == "timeline"
					+timeline(date, litinfo, last_week, yesterday, tomorrow, next_week, parishcal, messages)
				else if viewformat == "pastoralteam"
					+pastoralteam(date, litinfo, last_week, yesterday, tomorrow, next_week, parishcal, messages)
				else if viewformat == "pfarreientimeline"
					+pfarreientimeline(date, litinfo, last_week, yesterday, tomorrow, next_week, parishcal, messages)
				else
					+daycontent(date, litinfo, last_week, yesterday, tomorrow, next_week, parishcal, messages)
	
	- var d = JSON.stringify(date);
	
	script.
		var ws;
		var viewformat = "#{viewformat}";

		var pcal_pentry_clone_move_manager;
		var pcal_pentry_edit_manager;
		
		var saved_messages = [];
		
		$(document).ready(function() {
			ws = new PfISWebSocket("#{sessionuuid}");
			ws.bind_standard_close_handler();
			

			pcal_pentry_clone_move_manager = new pcalPentryCloneMoveManager(ws, "#{viewformat}");
			pcal_pentry_clone_move_manager.set_date(!{d});
			
			pcal_pentry_edit_manager = new pcalPentryEditManager(ws);
			pcal_pentry_edit_manager.set_date(!{d});
			
			/*if("#{event}" !== "") {
				ws.bind('open', function() {day_show_event("#{date.date}", "#{event}");});
			}*/
			
			
			ws.bind('get_parishday_result', function(data){
				var scrollto = '';
				if(history.state && history.state.scrollto)
					scrollto = history.state.scrollto;
				// console.log('scrollto:', scrollto);
			
				// history.replaceState({direction: 'back'}, document.title, '/'+ viewformat + '/' + data.date.date + '?back=false');
				if(history.state && history.state.date && history.state.date === data.date.date && history.state.direction === "mainpage")
				{
					console.log('NO new entry in history created')
				}
				else {
					history.pushState({direction: 'mainpage', date: data.date.date }, document.title, '/'+ viewformat + '/' + data.date.date) ;
					console.log('new entry in history created')
				}
				
				update_navlinks(data.date.date); // navlinks include the current date, so they must always be updated!
			
				var html;
				switch(viewformat) {
					case "timeline"          : html = timelinecontent_template(data); break;
					case "pastoralteam"      : html = pastoralteamcontent_template(data); break;
					case "pfarreientimeline" : html = pfarreientimelinecontent_template(data); break;
					default                  : html = daycontent_template(data); break;
				} 
				$('#dataparent').html(html);
				
				for(midx in saved_messages)
					$('#daycontrol_parent').append(saved_messages[midx]);
				saved_messages = [];
				
				if((viewformat === "timeline" || viewformat === "pastoralteam" || viewformat === "pfarreientimeline") && scrollto !== '') {
					var the_elem = $("[data-event-uuid='" + scrollto + "']");
					// this event (the_elem) might have been deleted!!!
					if(the_elem.length > 0) {
						$('#timelinebody').parent().parent().animate({
							scrollTop: the_elem.offset().top - $("#timelinebody").offset().top
						}, 1000);
					}
				}
				
				pcal_pentry_clone_move_manager.set_date(data.date);
				pcal_pentry_edit_manager.set_date(data.date);
				
				//console.log("FINISHED REDRAW", new Date());
			});
				
			ws.bind('event_details_result', function(data) {
				console.log('event_details_result');
				
				if(data.result === "OK") {
					if(history.state.direction !== 'day_show_event')
						if(history.state.direction === 'day_show_event_after_edit')
							history.replaceState({direction: 'day_show_event', event_uuid: data.event.uuid, date: data.date.date}, document.title, location.pathname /* + '/' + data.event.uuid*/);
						else
							history.pushState({direction: 'day_show_event', event_uuid: data.event.uuid, date: data.date.date}, document.title, location.pathname /* + '/' + data.event.uuid*/);
					var html = timeline_eventdetails_template({date : data.date, litinfo: data.litinfo, event: data.event, pcalview: viewformat} );
					$('#dataparent').html(html);
				}
				else {
					if(history.state.direction !== 'day_show_event')
						history.pushState({direction: 'day_show_event', event_uuid: 'invalid', date: data.date.date}, document.title, location.pathname);
					else
						history.replaceState({direction: 'day_show_event', event_uuid: 'invalid', date: data.date.date}, document.title, location.pathname);
					var html = errorview_inlay_template({ messages: data.messages, is_error: true, session_ended: false});
					$('#dataparent').html(html);
				}
			});
			
			ws.bind('pentry_delete_result', function(data) {
				console.log("pentry_delete_result");
				console.log(data);
				
				var message = errorview_inlay_template({ messages: data.messages, is_error: (data.result === 'OK' ? false : true), session_ended: false});
				
				if(data.pentrytype !== 'event') {
					if(data.result === 'OK') {
						var button = $('[data-pentry-uuid="'+ data.uuid + '"]');
						var type = data.pentrytype;
						var box = button.closest('.' + type);
						box.remove();
					}
					
					$('#daycontrol_parent').append(message);
				}
				else {
					saved_messages.push(message);
					history.back();
				}
					
				$('#confirmDelete').modal('hide');
			});
			
			ws.bind('tevent_delete_result', function(data) {
				console.log(data);
				
				if(data.result === "OK") {
				
					var delete_button = $('[data-event-uuid="'+ data.event + '"][data-tevent-uuid="'+ data.tevent + '"]');
					
					console.log(delete_button);
					
					var eventbox = delete_button.closest('.eventbox');
					var number_of_children = eventbox.parent().children().length;
				
					console.log('number_of_children: ', number_of_children);
				
					if(number_of_children > 1) {
						if(eventbox.is(':first-child')) { // disable up-button
							$(eventbox.next().find("div > button:nth-child(2)")[0]).prop('disabled', true);
						}
						if(eventbox.is(':last-child')) { // disable down-ubtton
							$(eventbox.prev().find("div > button:nth-child(3)")[0]).prop('disabled', true);
						}
					}
					
					eventbox.remove();
				}
				else
					console.log('tevent_delete_result: ', data);
					
				$('#confirmDelete').modal('hide');
			});
			
			function adjust_updown_buttons(teventbox) {
				if(teventbox.is(':first-child'))
				{
					$(teventbox.find("div > button:nth-child(2)")[0]).prop('disabled', true);
					$(teventbox.find("div > button:nth-child(3)")[0]).prop('disabled', false);
				}
				else
				{
					if(teventbox.is(':last-child'))
					{
						$(teventbox.find("div > button:nth-child(2)")[0]).prop('disabled', false);
						$(teventbox.find("div > button:nth-child(3)")[0]).prop('disabled', true);
					}
					else
					{
						$(teventbox.find("div > button:nth-child(2)")[0]).prop('disabled', false);
						$(teventbox.find("div > button:nth-child(3)")[0]).prop('disabled', false);
					}
				}
			}
			
			ws.bind('tevent_move_updown_result',function(data){
				console.log(data);
				
				// via the delete_button we can get the eventbox!
				var delete_button = $('[data-event-uuid="'+ data.event + '"][data-tevent-uuid="'+ data.tevent + '"]');
				var eventbox = delete_button.closest('.eventbox');
				var other = {};
				/* http://stackoverflow.com/questions/3050830/reorder-list-elements-jquery */
				if(data.updown === "down")
				{
					next = eventbox.next();
					next.after(eventbox);
					other = next;
				}
				else /* up */
				{
					prev = eventbox.prev();
					prev.before(eventbox);
					other = prev;
				}
				adjust_updown_buttons(eventbox);
				adjust_updown_buttons(other);
				
				/* $('body').loading('stop'); */
			});
			
			if(history.state.direction === 'day_show_event' && history.state.event_uuid != 'invalid')
			{
				ws.bind('open', function() {day_show_event("#{date.date}", history.state.event_uuid)});
			}
			else if(history.state.direction === 'clone_move')
			{
				ws.bind('open', function() {pcal_pentry_clone_move_manager.start(history.state.pentrytype, history.state.uuid, history.state.clone_or_move);});
			}
			else if(history.state.direction.substr(0,12) === 'pentry_edit_')
			{
				ws.bind('open', function() {pcal_pentry_edit_manager.start(history.state.pentrytype, history.state.uuid);});
			}
			
			if("#{scrollto}" !== "") {
				$('#timelinebody').animate({
					scrollTop: $("[data-event-uuid='#{scrollto}']").offset().top - $("#timelinebody").offset().top
				}, 1000);
			}

		});
		
		function set_viewformat(format, new_date) {
			viewformat = format;
			day_goto(new_date);
		}
		
		function update_navlinks(new_date) {
			var day_elem    = $('.navbar-collapse > ul > li:nth(0) > a');
			var tml_elem    = $('.navbar-collapse > ul > li:nth(1) > a');
			var pt_elem     = $('.navbar-collapse > ul > li:nth(2) > a');
			var pfrtl_elem  = $('.navbar-collapse > ul > li:nth(3) > a');
			
			var week_elem = $('.navbar-collapse > ul > li:nth(4) > a');
			week_elem.prop('href', '/week/' + new_date);
			var select_for_view_elem = $('#select_punits_for_view').closest('a');
			select_for_view_elem.prop("href", "/"+ viewformat +"/"+new_date+"/select_punits_for_view");
			var parishcalA4week_elem = $('#parishcalA4week').closest('a');
			parishcalA4week_elem.prop("href", "/parishcalA4week/" + new_date);
			
			switch(viewformat) {
				case "timeline":
					day_elem.prop("href", "javascript: set_viewformat('day', '" + new_date + "');");
					day_elem.parent().removeClass("active");
					pt_elem.prop("href", "javascript: set_viewformat('pastoralteam', '" + new_date + "');");
					pt_elem.parent().removeClass("active");
					pfrtl_elem.prop("href", "javascript: set_viewformat('pfarreientimeline', '" + new_date + "');");
					pfrtl_elem.parent().removeClass("active");
					tml_elem.prop("href", "#");
					tml_elem.parent().addClass("active");
					break;
				case "pastoralteam":
					day_elem.prop("href", "javascript: set_viewformat('day', '" + new_date + "');");
					day_elem.parent().removeClass("active");
					tml_elem.prop("href", "javascript: set_viewformat('timeline', '" + new_date + "');");
					tml_elem.parent().removeClass("active");
					pfrtl_elem.prop("href", "javascript: set_viewformat('pfarreientimeline', '" + new_date + "');");
					pfrtl_elem.parent().removeClass("active");
					pt_elem.prop("href", "#");
					pt_elem.parent().addClass("active");
					break;
				case "pfarreientimeline":
					day_elem.prop("href", "javascript: set_viewformat('day', '" + new_date + "');");
					day_elem.parent().removeClass("active");
					tml_elem.prop("href", "javascript: set_viewformat('timeline', '" + new_date + "');");
					tml_elem.parent().removeClass("active");
					pfrtl_elem.prop("href", "#");
					pfrtl_elem.parent().addClass("active");
					pt_elem.prop("href", "javascript: set_viewformat('pastoralteam', '" + new_date + "');");
					pt_elem.parent().removeClass("active");
					break;
				default:
					day_elem.prop("href", "#");
					day_elem.parent().addClass("active");
					tml_elem.prop("href", "javascript: set_viewformat('timeline', '" + new_date + "');");
					tml_elem.parent().removeClass("active");
					pt_elem.prop("href", "javascript: set_viewformat('pastoralteam', '" + new_date + "');");
					pt_elem.parent().removeClass("active");
					pfrtl_elem.prop("href", "javascript: set_viewformat('pfarreientimeline', '" + new_date + "');");
					pfrtl_elem.parent().removeClass("active");
			}
			
			//console.log("UPDATED NAVLINKS", new Date());
		}
		
		function day_goto(new_date) {
			ws.send('get_parishday', {format : viewformat, date : new_date});
		}
		
		function day_show_event(date, event) {
			//console.log('day_show_event', date, event);
			history.replaceState({direction: 'mainpage', date: date, scrollto: event }, document.title, "/" + viewformat + "/" + date) ;
			//console.log(ws);
			ws.send('event_details', { date: date, event: event});
		}
		
		$('#datepicker').datepicker({format: "yyyy-mm-dd", language: "de", calendarWeeks: true, todayHighlight: true});
			
		$('#daypickerDialog').on('show.bs.modal', function (e) {
			date = $(e.relatedTarget).attr('data-date');
			$('#datepicker').datepicker("update", date);
		});
		
		$('#daypickerDialog').find('.modal-footer #confirm').on('click', function() {
				$('#daypickerDialog').modal('hide');
				//console.log('CLICKED');
				day_goto($("#datepicker").datepicker('getFormattedDate'));
		});
		
		function toggle_pentrydetails_visibility(pentry) {
			$(pentry).find(".pentry_details").toggle();
		}
		
		$('#confirmDelete').on('show.bs.modal', function (e) {
			if(pcal_pentry_edit_manager.is_active()) {
				pcal_pentry_edit_manager.deletedialog_handle_show($(this), e);
				return;
			}
		
			$etitle = $(e.relatedTarget).attr('data-pentry-title');
			$(this).find('.modal-body p').text("Sind Sie sicher, dass Sie " + $etitle + " löschen wollen?");
		
			$(this).find('.modal-footer #confirm').data('button', $(e.relatedTarget));
		});
		
		$('#confirmDelete').find('.modal-footer #confirm').on('click', function() {
				if(pcal_pentry_edit_manager.is_active()) {
					pcal_pentry_edit_manager.deletedialog_handle_confirm($(this));
					return;
				}

				var delete_button = $(this).data('button');
				
				var date = delete_button.data('date');
				var type = delete_button.data('pentry-type');
				
				if(type === "tevent") {
					console.log('delete tevent');
					var event = delete_button.data('event-uuid');
					var tevent = delete_button.data('tevent-uuid');
					
					console.log(date, event, tevent);
					
					ws.send('tevent_delete', { date: date, event: event, thereafter: tevent });
					
					return;
				}
				
				var uuid = delete_button.data('pentry-uuid');

				console.log(date, type, uuid);
				
				ws.send('pentry_delete', { date: date, pentrytype: type, uuid: uuid });
		});
		
		do_tevent_move_updown = function(button, date, event, tevent, updown) {
			ws.send('tevent_move_updown', { date: date, event: event, thereafter: tevent, updown: updown });
		}

		window.addEventListener("popstate", function(e) {
			console.log(e.state);
			if(e.state !== null) {
				if(e.state.direction === "back") {
					history.go(1);
					return;
				}
				if(e.state.direction === "mainpage"){
					// clone_move/edit _manager is active if user clicked on back-button in browser; handle this here:
					if(pcal_pentry_clone_move_manager.is_active())
						pcal_pentry_clone_move_manager.finish();
					if(pcal_pentry_edit_manager.is_active())
						pcal_pentry_edit_manager.finish();
					
					day_goto(e.state.date);
					return;
				}
				if(e.state.direction === "pentry_edit_main" && pcal_pentry_edit_manager.is_active())
				{
					pcal_pentry_edit_manager.show_edit_main();
					return;
				}
				if(e.state.direction.substr(0, 12) === "pentry_edit_")
				{
					history.go(-1);
				}
				if(e.state.direction === "day_show_event_after_edit")
				{
					pcal_pentry_edit_manager.finish();
				}
				
				history.replaceState({direction: "mainpage", date: e.state.date}, document.title)
				day_goto(e.state.date);
			}
		}, false);
