<% events_groups = events.group_by do |event|
	event.start_time.in_time_zone.strftime("%Y/%m/%d")
end 

HALF_HOUR_HEIGHT = 28 # pixel height of half-hour sections in calendar. DO NOT CHANGE RESPONSIVELY
SIX_AM_MINUTES = 360 # start time of calendar 
EIGHT_PM_MINUTES = 1200 # end time of calendar
%>

<div id="pagetitle">
	<h3>
		<%= @space.name %> Calendar
		<span class="dcf-subhead">See all our upcoming events!</span>
	</h3>
</div>

<div class="calendar">
	<div class="calendar-header">
		<a href="/<%= @space.url_name %>/calendar/?date=<%= (date-7.days).strftime('%Y-%m-%d') %><%= defined?(kiosk_mode) && kiosk_mode == 'true' ? '&kiosk_mode=true' : ''%>" id="prev-week" class="schedulericon-angle-circled-left dcf-txt-decor-none"><span class="dcf-sr-only">Previous Week</span></a>
		<a href="/<%= @space.url_name %>/calendar/?date=<%= (date+7.days).strftime('%Y-%m-%d') %><%= defined?(kiosk_mode) && kiosk_mode == 'true' ? '&kiosk_mode=true' : ''%>" id="next-week" class="schedulericon-angle-circled-right dcf-txt-decor-none"><span class="dcf-sr-only">next week</span></a>
		<h4 class="unl-font-sans">
		<%= month = sunday.strftime('%B %Y') %><%= (month2 = (sunday+6.days).strftime('%B %Y')) == month ? '' : " - #{month2}" %>
		</h4>
	</div>
	<div class="day-label-container">
		<% (1..5).each do |i| %>
			<% day = (sunday + i.days + 1.hour).midnight %>
			<label class="day-header"><%= day.strftime("%^a %-m/%d") %></label>
		<% end %>
	</div>
	<div class="calendar-container">
		<div class="time-labels">
			<div class="time-chart">
				<% (12..39).each do |j| %>
					<div class="calendar-half-hour">
						<label><%= "#{(j / 2) % 12 + (j==24 ? 12 : 0)} #{j>=24 ? 'PM': 'AM'}" if j % 2 == 0 %></label>
					</div>
				<% end %>
			</div>
		</div>
		<% (1..5).each do |i| %>
		<% day = (sunday + i.days + 1.hour).midnight %>
		<% slots = [0] * 36 %>
		<div class="calendar-day" data-day="<%= day.strftime("%Y/%m/%d") %>">
			<!-- <label class="day-header"><%= day.strftime("%^a %-m/%d") %></label> -->
			<div class="day-chart" title="Open">
				<% if week_hours.has_key?(i) %>
					<% # figure out where the closed divs need to be
						# we can assume that all records in this space_hour are non-intertwined
						closed_start = 0
						closed_end = 0
						starts = week_hours[i].hours.map{|record| record[:start]}
						ends = week_hours[i].hours.map{|record| record[:end]}
						%> <%
						closeds = []
						(360..1199).each do |j|
							if starts.include?(j)
								closed_end = j
								closeds << [closed_start, closed_end]
								closed_start = 0
								closed_end = 0
							end
							if ends.include?(j)
								closed_start = j
							end
						end 
						closed_end = 1200
						closeds << [closed_start, closed_end]

						closeds.each do |closed|
							start_time = closed[0] %>
		            		<% end_time = closed[1] %>
		            		<%
		            		# if the end time is before 6 am, skip.
		            		if ((end_time - SIX_AM_MINUTES) / 30).floor < 0
								next
							end
							# calculate top based off of 6 am start
							top = ((start_time - SIX_AM_MINUTES) / 30) * HALF_HOUR_HEIGHT
							height = (end_time - start_time) * HALF_HOUR_HEIGHT / 30
							# normalize top to 0, reduce height to accomodate
							if top < 0
								height += top
								top = 0
							end
							# normalize the bottom to the bottom of the calendar at 8pm. 
							if top + height > (EIGHT_PM_MINUTES / 30) * HALF_HOUR_HEIGHT
								height = (EIGHT_PM_MINUTES / 30) * HALF_HOUR_HEIGHT - top
							end
							%>
							<div class="status closed" title="Closed" style="top: <%= top %>px; height: <%= height %>px;">
								&nbsp;
							</div>
							<%
						end
					%>
					<% week_hours[i].hours.each do |record| %>
						<% if record[:status] != 'open' && record[:status] != 'closed' %>
							<% start_time = record[:start] %>
		            		<% end_time = record[:end] %>
		            		<% if ((end_time - SIX_AM_MINUTES) / 30).floor < 0
								next
							end
							top = ((start_time - SIX_AM_MINUTES) / 30) * HALF_HOUR_HEIGHT
							height = (end_time - start_time) * HALF_HOUR_HEIGHT / 30
							if top < 0
								height += top
								top = 0
							end 
							if top + height > (EIGHT_PM_MINUTES / 30) * HALF_HOUR_HEIGHT
								height = (EIGHT_PM_MINUTES / 30) * HALF_HOUR_HEIGHT - top
							end
							%>
							<div title="<%= record[:status].split('_').join(' ').capitalize_all %>" class="status <%= record[:status].downcase.split('_').join('-') %>" style="top: <%= top %>px; height: <%= height %>px;">
								&nbsp;
							</div>
						<% end %>
					<% end %>
				<% end %>

				<% day_events = events_groups[day.strftime("%Y/%m/%d")] %>
				<% unless day_events.nil? %>
				<% day_events.sort{|a, b| a.start_time <=> b.start_time}.each do |res| %>
					<% start_slot = [(((res.start_time.in_time_zone - day.midnight) / 60 - SIX_AM_MINUTES) / 30).floor, 0].max 
					end_slot = [(((res.end_time.in_time_zone - day.midnight) / 60 - SIX_AM_MINUTES) / 30).floor, 35].min 
					if end_slot < 0
						next
					end
					over = 0 
					(start_slot..end_slot).each do |k|
						over = slots[k] if slots[k] > over
					end
					over = [over,3].min
					top = (((res.start_time.in_time_zone - day.midnight) / 60 - SIX_AM_MINUTES) / 30) * HALF_HOUR_HEIGHT
					height = res.length * HALF_HOUR_HEIGHT / 30
					top_overflow = false
					bottom_overflow = false
					if top < 0
						height += top
						top = 0
						top_overflow = true
					end 
					if top + height > (EIGHT_PM_MINUTES / 30) * HALF_HOUR_HEIGHT
						height = (EIGHT_PM_MINUTES / 30) * HALF_HOUR_HEIGHT - top
						bottom_overflow = true
						events_groups[(day + 1.day).strftime("%Y/%m/%d")] ||= []
						events_groups[(day + 1.day).strftime("%Y/%m/%d")] << res
					end
					%>
					<div class="event-container" style="top: <%= top %>px;">
						<div id="event<%=res.id %>" data-start="<%= res.start_time.in_time_zone %>" data-end="<%= res.start_time.in_time_zone + (res.length * 60) %>" class="event <%= 'top-overflow' if top_overflow %> <%= 'bottom-overflow' if bottom_overflow %>" style="height: <%= height %>px;">
							<p><strong><%= res.title ? (res.title.empty? ? 'Reserved' : res.title) : 'Reserved' %></strong></p>		
							<% if height >= 42 %>
								<p class="eventicon-clock"><%= res.start_time.in_time_zone.strftime('%I:%M  %p') %> - <%= res.end_time.in_time_zone.strftime('%I:%M  %p') %></p>
							<% end %>
						</div>
						<div class="tooltip <%= top >= 50 ? "hang-above" : "hang-below" %> <%= day.strftime("%^a") == "FRI" ? "hang-left" : "hang-right" %>">
			                <div>
			                    <h6 style="margin-top: 0px; margin-bottom: .25em;"><%= res.title ? (res.title.empty? ? 'Reserved' : res.title) : 'Reserved' %></h6>
			                    <p style="margin-bottom: 10px;" class="eventicon-clock"><%= res.start_time.in_time_zone.strftime('%I:%M  %p') %> - <%= res.end_time.in_time_zone.strftime('%I:%M  %p') %></p>
			                   	<p style="margin-bottom: 10px;"><a href="<%= res.info_link %>"" class="dcf-btn dcf-btn-primary dcf-txt-sm">View</a> <a href="<%= res.download_link %>" class="download-ics dcf-btn wdn-button-triad dcf-txt-sm">Download</a></p>
			                   	<div class="close"><a href="#">&times;</a></div>
			                </div>
			            </div>
					</div>
 					
					<% (start_slot..end_slot).each do |k| %>
						<% slots[k] = slots[k] + 1 %>
					<% end %>
				<% end %>
				<% end %>
				
				<div>
				<% (12..39).each do |j| %>
					<div class="calendar-half-hour">
						&nbsp;
					</div>
				<% end %>
				</div>
			</div>
		</div>
		<% end %>
	</div>
</div>

<% append_script_declaration(%q[require(['jquery', '/js/functions.js', '/js/jquery.mousewheel.min.js', '/js/jquery.mCustomScrollbar.js'], function ($, functions) {
	var openZ = 5;
	var closedZ = 3;
	$(document).ready(function () {
		$('.event').click(function (e) {
			e.stopPropagation();
			var $eventContainer = $(this).parent();
			$eventContainer.css('z-index', openZ);

			var $tooltip = $(this).next(".tooltip");
			$tooltip.show();
			if($tooltip.hasClass("hang-below")){
				$tooltip.css("margin-bottom", ($tooltip.find("div").height()+35)*-1);
			}
		});

		$('.tooltip div.close a').click(function (click) {
			click.preventDefault();
			$(this).closest('.tooltip').hide();
		});

		$(window).on("load",function(){
            $(".calendar-container").mCustomScrollbar(
            	{
            		mouseWheel:{ enable: true },
            		theme:"rounded-dots-dark",
            		callbacks:{
					},
					setTop: "95px"
            	}
            );
        });

		function tick(){
			var dateTime = functions.getDateTime();
			$(".calendar-day").each(function(){
				if(dateTime.date == $(this).data("day")){

					var top = (dateTime.hour-6) * 2 * 28;
					top += dateTime.minute / 60 * 2 * 28;

					if($(this).children(".day-chart").children("#nowArrow").length){
						$(this).children(".day-chart").children("#nowArrow").css({top:top})
						$(this).children(".day-chart").children("#nowLine").css({top:top})
					}else{
						$("#nowArrow").remove();
						$("#nowLine").remove();
						$(this).children(".day-chart").append($("<div id='nowArrow'>"));
						$(this).children(".day-chart").children("#nowArrow").css({top:top})
						$(this).children(".day-chart").append($("<div id='nowLine'>"));
						$(this).children(".day-chart").children("#nowLine").css({top:top})
					}

				}
			});
			$(".event").each(function(){
				var eventEnd = new Date($(this).data("end").replace(" -0500", "")).getTime();
				var now = new Date();
				now = now.getTime();
				if (eventEnd < now) {
					$(this).addClass("past");
				}
			});
		};

		tick();
    	setInterval(tick, 60000);
	});
});]) %>