include mixins
include mixins_day

doctype html
html
	include header
	script(src='/javascripts/socket.io.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' )
	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; }
		.event_name { font-size: 85%; font-weight: bold; font-style: italic; margin-bottom: 0px;}
		.event_name_secondary { font-size: 75%; font-weight: bold; }
		.event_locations { font-size: 70%; color: darkblue; font-weight: bold; margin-bottom: 0px; }
		.event_involved { font-size: 70%; color: green; font-style: italic; margin-bottom: 0px; }
		
	body(style="overflow: hidden;")
		script.
			history.replaceState({direction: 'back'}, document.title, "/timeline/#{date.date}?back=false");
			history.pushState({direction: 'mainpage', date: "#{date.date}", scrollto: ''}, document.title, "/timeline/#{date.date}");
				
		.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
						
		.modal.fade(id="confirmDelete", role="dialog", aria-labelledby="confirmDeleteLabel", 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="confirmDeleteLabel") 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

		
		.root(style="overflow: hidden;")
		
			.new_flex_zero
				+nav("PfarrInfoSystem", "dropdown_menu")
					+nav_item( "/day/" + date.date ) Tag
					+nav_item( "#", "active" ) TagZeitleiste
					+nav_item( "/week/" + date.date) Woche
					+nav_item( "/timeline/"+date.date+"/select_punits_for_view" ) Angezeigte Orte konfigurieren
					+nav_item( "/info" ) Info
					
			#dataparent.subroot(style="overflow: hidden; height: 100%;")
				+timeline(date, litinfo, last_week, yesterday, tomorrow, next_week, messages, parishcal)
	
	script.
		var sockets;
		
		var saved_messages = [];
		
		var updown_button = {};
		var updown_direction = "";
		
		$(document).ready(function() {
			console.log('NOW CONNECTING');
		 	sockets = io.connect();
			
			sockets.on('day_goto_result',function(data){
					console.log('day_goto_result');

					if(data.result === "OK") {
						var html = $(data.html);
						
						history.replaceState({direction: 'back'}, document.title, "/timeline/" + data.date + "?back=false");
						history.pushState({direction: 'mainpage', date: data.date }, document.title, "/timeline/" + data.date) ;
					
						$('#dataparent').html(data.html);
						
						var day_elem = $('.navbar-collapse > ul > li:nth(0) > a');
						day_elem.prop('href', '/day/' + data.date);
						var week_elem = $('.navbar-collapse > ul > li:nth(2) > a');
						week_elem.prop('href', '/week/' + data.date);
						
						for(midx in saved_messages)
							$('#daycontrol_parent').append(saved_messages[midx]);
						saved_messages = [];

						console.log(data.scrollto);
						
						if((typeof data.scrollto !== 'undefined') && (data.scrollto !== '')) {
							var the_elem = $("[data-event-uuid='" + data.scrollto + "']");
							// this event (the_elem) might have been deleted!!!
							if(the_elem.length > 0) {
								$('#timelinebody').animate({
									scrollTop: the_elem.offset().top - $("#timelinebody").offset().top
								}, 1000);
							}
						}
					}
					else {
						$('#dataparent').html("<div class='new_flex_one' style='padding-left: 15px; padding-right: 15px;'>"+data.html+"</div>");
					}
				});
				
			sockets.on('day_show_event_result', function(data) {
				console.log('day_show_event_result');
				
				if(data.result === "OK") {
					history.pushState({direction: 'day_show_event'}, document.title, location.pathname + '/' + data.event);
					$('#dataparent').html(data.html);
				}
				else {
					$('#dataparent').html("<div class='new_flex_one' style='padding-left: 15px; padding-right: 15px;'>"+data.html+"</div>");
				}
			});
			
			sockets.on('pentry_delete_result', function(data) {
				console.log("pentry_delete_result");
				console.log(data);
				
				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(data.message);
				}
				else {
					saved_messages.push(data.message);
					history.back();
				}
					
				$('#confirmDelete').modal('hide');
			});
			
			sockets.on('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');
			});
			
			sockets.on('tevent_move_updown_result',function(data){
				console.log(data);
				/*window.location.reload();*/
					
				/* http://stackoverflow.com/questions/3050830/reorder-list-elements-jquery */
				var eventbox = updown_button.closest('.eventbox');
				var other = {};
				if(updown_direction === "down")
				{
					next = eventbox.next();
					next.after(eventbox);
					other = next;
				}
				else /* up */
				{
					prev = eventbox.prev();
					prev.before(eventbox);
					other = prev;
				}
				
				if(eventbox.is(':first-child'))
				{
					$(eventbox.find("div > button:nth-child(2)")[0]).prop('disabled', true);
					$(eventbox.find("div > button:nth-child(3)")[0]).prop('disabled', false);
				}
				else
				{
					if(eventbox.is(':last-child'))
					{
						$(eventbox.find("div > button:nth-child(2)")[0]).prop('disabled', false);
						$(eventbox.find("div > button:nth-child(3)")[0]).prop('disabled', true);
					}
					else
					{
						$(eventbox.find("div > button:nth-child(2)")[0]).prop('disabled', false);
						$(eventbox.find("div > button:nth-child(3)")[0]).prop('disabled', false);
					}
				}
				
				if(other.is(':first-child'))
				{
					$(other.find("div > button:nth-child(2)")[0]).prop('disabled', true);
					$(other.find("div > button:nth-child(3)")[0]).prop('disabled', false);
				}
				else
				{
					if(other.is(':last-child'))
					{
						$(other.find("div > button:nth-child(2)")[0]).prop('disabled', false);
						$(other.find("div > button:nth-child(3)")[0]).prop('disabled', true);
					}
					else
					{
						$(other.find("div > button:nth-child(2)")[0]).prop('disabled', false);
						$(other.find("div > button:nth-child(3)")[0]).prop('disabled', false);
					}
				}
				
				/* $('body').loading('stop'); */
			});
			
			if("#{event}" !== "")
				day_show_event("#{date.date}", "#{event}");
				
			if("#{scrollto}" !== "") {
				$('#timelinebody').animate({
					scrollTop: $("[data-event-uuid='#{scrollto}']").offset().top - $("#timelinebody").offset().top
				}, 1000);
			}

		});
		
		function day_goto(new_date, scrollto) {
			console.log(new_date);
			console.log('scrollto ', scrollto);
			console.log((typeof scrollto !== 'undefined' ? scrollto : ''));
			sockets.emit('day_goto_timeline', {date : new_date, scrollto: (typeof scrollto !== 'undefined' ? scrollto : '')});
		}
		
		function day_show_event(date, event) {
			console.log('day_show_event', date, event);
			history.replaceState({direction: 'mainpage', date: date, scrollto: event }, document.title, "/timeline/" + date) ;
			sockets.emit('day_show_event', { 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) {
			$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() {
				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);
					
					sockets.emit('tevent_delete', { date: date, event: event, tevent: tevent });
					
					return;
				}
				
				var uuid = delete_button.data('pentry-uuid');
				
				/*if(type === "event") {
					// special handling, because we can it not remove from the view, but have to go back to the view
					// because this delete-button is only presented in the detail-view!!!
					console.log('delete event');
					
					sockets.emit('event_delete', { date: date, event: uuid });
					
					return;
				}*/
				
				console.log(date, type, uuid);
				
				sockets.emit('pentry_delete', { date: date, pentrytype: type, uuid: uuid });
		});
		
		do_tevent_move_updown = function(button, date, event, tevent, updown) {
			updown_button = button;
			updown_direction = updown;
			sockets.emit('tevent_move_updown', { date: date, event: event, tevent: tevent, updown: updown });
		}

		window.addEventListener("popstate", function(e) {
			console.log(e.state);
			if(e.state !== null) {
				if(e.state.direction === "back") {
					history.go(1);
				}
				if(e.state.direction === "mainpage")
					day_goto(e.state.date, e.state.scrollto);
			}
		}, false);
