<h1>Listing events</h1>

Events (by week):

<% 

#now, we want to go through events, putting them into place in the day
#structure
def period (time)
	(time.to_i / (60 * 15)).floor
end

def overlap(e1, e2)
	(period(e1["end"]) >= period(e2["start"]) &&
	period(e1["end"]) <= period(e2["end"])) ||
	(period(e1["start"]) >= period(e2["start"]) &&
	period(e1["start"]) <= period(e2["end"]))
end
#ok, fuck, what do I do about the following: [ [ [ ] ] ]?
def append_event (e1, e2)
	if e1["title"].class == Array
		e1["title"].push (e2["title"])
	else
		e1["title"] = [e1["title"], e2["title"]]
	end
end

def clone_event (e)
	e2 = e.clone
	e2.id = e.id
	e2
end

def split_events (e1, e2)
	#from two events, generates three at most three events which
	#encompass both

	out = []
	#bottom: 
	if period (e1["start"]) < period (e2["start"])
		newevent = clone_event e1 #this part is just e1
		newevent ["end"] = e2["start"]
		newevent ["continue"] = 1
		out.push (newevent)
	end
	#middle (both)

	newevent = clone_event e1
	append_event (newevent, e2)
	out.push (newevent)

	#both end at same time
	if period (e1["end"]) == period (e2["end"])
		return out
	end

	newevent["continue"] = 1
	if period (e1["end"]) > period (e2["end"])
		newevent ["end"] = e2 ["end"]

		newevent = clone_event e1
		newevent ["start"] = e2["end"]
		out.push (newevent)
	else
		newevent ["end"] = e1 ["end"]

		newevent = clone_event e2
		newevent ["start"] = e1["end"]
		out.push (newevent)
	end
	out
end

elist = []
for event in @events
	#look at the previous event, if any
	if elist.empty?
		elist.push event
	else
		lastevent = elist [-1]
		if overlap (lastevent, event)
			elist.pop
			split_events(lastevent, event).each {|e| elist.push e}
		else
			elist.push event
		end
	end
end
@events = elist


#starting this week:
today = Date.today
sunday = today.jd - today.wday

%>

<table>
  <tr>
<% for column in Event.content_columns %>
    <th><%= column.human_name %></th>
<% end %>
  </tr>
  
<% for event in @events %>
  <tr>
  <% for column in Event.content_columns %>
    <td><%=h event[column.name] %></td>
  <% end %>
    <td><%= link_to 'Show', :action => 'show', :id => event.id %></td>
    <td><%= link_to 'Edit', :action => 'edit', :id => event.id %></td>
    <td><%= link_to 'Destroy', :action => 'destroy', :id => event.id %></td>
  </tr>
<% end %>
</table>

<br />

<%= link_to 'New event', :action => 'new' %>
