/*
A Note Regarding Variables in This Script

selected_date (string format "MM DD YYYY") is the first date whose events should appear in the event list.
date_to_show (string format "MM DD YYYY") is used to determine what month should appead in the month calendar. This is separate from selected_date so that visitors using JavaScript can browse the month calendar without the distraction of a constantly-refreshing event list.
*/

getCalendarURLVars();

$(document).ready(function() {
	if(typeof selected_date=='undefined') {
		var now = new Date();
		var months = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
		selected_date = months[now.getMonth()] + ' ' + now.getDate() + ' ' + now.getFullYear();
	}
	
	$('.event').each(function() {
		if($(this).hasClass('noscript')) {
			$(this).hide();
		}
	});
	
	$('.day').each(function() {
		if($(this).hasClass('noscript')) {
			$(this).hide();
		}
	});
	
	// Check if there's anything written in the "events" <div>. If not, we're looking at a particular event. No need to show the list.
	if($('#events').length>0) {
		if($('#events').html().search(/[a-z]/i)>-1) {
			updateEvents(selected_date,selected_event_type);
			calendarClickable();
		
			// Behavior for clicking event types.
			$('#event_types ul a').click(function(event) {
				event.preventDefault();
				selectEventType($(this));
			});
		}
	}
	
});

function selectEventType(obj) {
	// Get the title of the event type link and add "event_type_" to it. This correlates to the classNames of individual events.
	// If the title is "Show All Events", then set the classname identifier to "event", so that all events will be shown.
	if(obj.attr('title')=='Show All Events') {
		event_type_classname = 'event';
	} else {
		event_type_classname = 'event_type_' + friendlyText(obj.attr('title'));
	}
	
	if(event_type_classname=='event') {
		obj.parent().parent().find('a').removeClass('minor');
	} else {
		obj.parent().parent().find('a').each(function() {
			// Set all event type links to "minor" class to acknowledge that they are not seleted.
			$(this).addClass('minor');
		});		
		// The clicked event type is selected, so we remove the "minor" class to reflect that.
		obj.removeClass('minor');
	}
	
	showHideEventTypes();
	
}

function showHideEventTypes(speed) {
	// Show or hide events based on relevance.
	if(typeof(speed)=='undefined') {
		$('.event').each(function() {
			if(!$(this).hasClass(event_type_classname)) {
				$(this).fadeTo('200',0,function() {
					$(this).slideUp('500');
				});
			} else {
				$(this).fadeTo('200',1);
				$(this).slideDown('500');
			}
		});
	} else if(speed=='fast') {
		$('.event').each(function() {
			if(!$(this).hasClass(event_type_classname)) {
				$(this).hide();
			} else {
				$(this).show();
			}
		});
	}
}


// calendarClickable adds click events to a calendar.

// USING calendarClickable
// 1. Make a <div> with class "calendar" and populate with contents of month_calendar.php
// 2. Make a <div> with id "events"

function calendarClickable() {
	// A click in the calendar will request a redraw with the correct date. The title attribute of the links contain the date we will request.
	$('.calendar a').click(function(event) {
		event.preventDefault();
		if(!$(this).hasClass('month_arrow')) {
			selected_date = $(this).attr('title');
		}
		$.get('month_calendar.php',
			{
				date_to_show: $(this).attr('title'),
				selected_date: selected_date
			},
			function(data) {
				$('#month_calendar').html(data);
				// After we redraw the calendar, we have to call this function again to add click events to it.
				calendarClickable();
			},
			'html'
		);
		// This is the part that pulls the event data.
		if(!$(this).hasClass('month_arrow')) {
			updateEvents($(this).attr('title'));
/*
			$.get('events.php',
				// Again, we use the title attribute of the links to set the date we're requesting.
				{ date_to_show: $(this).attr('title') },
				function(xml) {
					$(xml).find('day').each(function() {
						var this_date = $(this).attr('date');
						// Each day that is shown gets its own div with id "events_day_YYYYMMDD". Here, we see if that day's info has already been pulled before. If so, we don't bother updating its contents.
						var day_div = $('#events #events_day_' + this_date);
						
						// If the <div> for that date already exists, show it if it isnt' already visible.
						if(day_div.length>0) {
							day_div.slideDown(500);
						} else {
							// If that div doesn't exist, we'll make one.
							var html_injection = '<div class="day" id="events_day_' + this_date + '">' + "\n";
							html_injection += '<h2>' + $(this).attr('title') + '</h2>' + "\n";
							
							$(this).find('event').each(function() {
								html_injection += '<div class="event" id="event_' + $(this).attr('id') + '">' + "\n";
								html_injection += '<h3>' + $(this).find('event_name').text() + '</h3>' + "\n";
								
								html_injection += '<p>' + $(this).find('abstract').text() + '</h3>' + "\n";
								html_injection += '</div>' + "\n";
							});
							
							
							html_injection += '</div>' + "\n";
							
							// Since we want to keep the <div>'s in the appropriate order by date, we need to look at what dates are already accounted for. The variable "injected" keeps track of whether or not we have placed the event in the DOM.
							var injected = false;
							
							// If there are no days represented, just stick this one in there and be done with it.
							if($('#events .day').length==0) {
								$('#events').append(html_injection);
								injected = true;
							} else {
								// Otherwise, we look at each represented date in order until we find a date that is later than the one we're trying to put in. Then we add the new date right before that.
								$('#events .day').each(function() {
									if(!injected) {
										var date_compare = $(this).attr('id').replace('events_day_','');
										if(this_date<date_compare) {
											$(this).before(html_injection);
											injected = true;
										}
									}
								});
								
								// If we've looked at all the current dates and still haven't found a place to stick it, it goes at the end.
								if(!injected) {
									$('#events').append(html_injection);
								}
							}
							// Then we reveal the new date.
							$('#events_day_' + this_date).hide();
							$('#events_day_' + this_date).slideDown(500);
						}
					});
					
					// Now we look through the most recent XML list of dates. If any dates currently visible are not listed in the latest XML, we hide them.
					$('#events .day').each(function() {
						var this_date = $(this).attr('id').replace('events_day_','');
						var find_relevant_date = $(xml).find('day[date="' + this_date + '"]');
						if(find_relevant_date.length==0) {
							$(this).slideUp(500);
						}
					});
					
				},
				'xml'
			);
*/
		}
	});
}

// getCalendarURLVars() reads the current url for calendar parameters separated by slashes in the URL.
function getCalendarURLVars() {
	selected_event_type = '';
	// Grab the part of the URL after 'calendar/'.
	URL_varstring = location.href.replace(/^.*calendar\//,'');
	var URL_vars = new Array();
	// Split string at the slashes.
	URL_vars = URL_varstring.split('/');
	for(var i in URL_vars) {
		// If this piece starts with the name of a month, it's the selected date. Split it into chunks by non-alphanumeric delimiters.
		if(URL_vars[i].match(/^(january|february|march|april|may|june|july|august|september|october|november|december)/i)) {
			URL_date_pieces = URL_vars[i].split(/[^A-Za-z0-9]/);
		} else if(URL_vars[i].length > 0) {
			if(URL_vars[i]=='confirm') {
			} else {
				// Otherwise, it's the selected event type.
//				selected_event_type = URL_vars[i];
			}

			if(selected_event_type!='Show All Events') {
//				event_type_classname = 'event_type_' + selected_event_type;
			}
			
		}
		if(typeof(event_type_classname)=='undefined') {
			event_type_classname = 'event';
		}
	}
	// If we have a selected date, assemble the three parts (month, day, year) with a space between them.
	if(typeof(URL_date_pieces)!='undefined') {
		var URL_date_piece_count = 0;
		var temp_selected_date = '';
		for(var i in URL_date_pieces) {
			if(URL_date_pieces[i].match('[A-Za-z0-9]')) {
				temp_selected_date += URL_date_pieces[i];
				URL_date_piece_count++;
				if(URL_date_piece_count<3) {
					temp_selected_date += ' ';
				} else {
					break;
				}
			}
		}
	}
	selected_date = temp_selected_date;
}


// getGet is a solution for extracting HTTP GET variables by parsing the url string.
// The argument is a comma-separated list of variable names. The result is the JavaScript equivalent of the following PHP statement:
//    $foo = $_GET['foo'];

// Alternatively, an argument of '*' can be used, which executes a similar functionality in JavaScript to PHP's register_globals directive. Please be sure you understand the potential risk involved in this functionality before invoking it.

function getGet(variable_names) {
	alert('Looking for ' + variable_names + ' in ' + location.href);
	window['test'] = 'okay';
	var variables = variable_names.split(',');
	// We're interested in the part of the URL that comes after the question mark.
	var query_string = location.href.indexOf('?');
	// If we can't find it, there's nothing to get (pun intended).
	if(query_string==-1) {
		return false;
	} else {
		query_string = location.href.substr(query_string+1);
		// Break the individual variable assignments by looking for the ampersand.
		query_variables = query_string.split('&');
		for(var i in query_variables) {
			// Split the key from the value at the equals sign.
			var query_variable_parts = query_variables[i].split('=');
			var query_variable_key = query_variable_parts[0];
			var query_variable_value = unescape(query_variable_parts[1]);
			query_variable_value = query_variable_parts[1];
			
			// If a variable is mentioned but not assigned a value, it's probably important enough to leave in. We'll give it a value of [true].
			if(query_variable_value===undefined) {
				query_variable_value = true;
			}
			// Compare each $_GET variable to the list of variables we're looking for.
			for(var j in variables) {
				variable_name = variables[j];
				alert(variable_name + ' vs. ' + query_variable_value);
				// If there's a match, or if we've invoked register_globals, assign the variable.
				if(query_variable_key==variable_name || variable_name=='*') {
					window[query_variable_key] = query_variable_value;
				}
			}
			
		}
	}
}

function updateEvents(date_to_show,event_type) {
	$.get('events.php',
		// Again, we use the title attribute of the links to set the date we're requesting.
		{ date_to_show: date_to_show },
		function(xml) {
			$(xml).find('day').each(function() {
				var this_date = $(this).attr('date');
				// Each day that is shown gets its own div with id "events_day_YYYYMMDD". Here, we see if that day's info has already been pulled before. If so, we don't bother updating its contents.
				var day_div = $('#events #events_day_' + this_date);
				
				// If the <div> for that date already exists, show it if it isnt' already visible.
				if(day_div.length>0) {
					day_div.slideDown(500);
				} else {
					// If that div doesn't exist, we'll make one.
					var html_injection = '<div class="day" id="events_day_' + this_date + '">' + "\n";
					html_injection += '<h2>' + $(this).attr('title') + '</h2>' + "\n";
					
					$(this).find('event').each(function() {
						var this_event_className = 'event';
						if($(this).attr('event_types').length>0) {
							var these_event_types = $(this).attr('event_types').split(',');
							for(var i_event_types in these_event_types) {
								this_event_className += ' event_type_' + these_event_types[i_event_types];
							}
						}
						html_injection += '<div class="' + this_event_className + '" id="event_' + $(this).attr('id') + '">' + "\n";
						html_injection += '<h3><a href="http://www.menlo.edu/calendar/event/' + $(this).attr('id') + '/">' + $(this).find('event_name').text() + '</a></h3>' + "\n";
						
						var this_event_location = $(this).find('event_location').text();
						var this_event_time_start = $(this).attr('time_start');
						var this_event_time_and_location = '';
						
						
						if(this_event_time_start.length>0) {
							html_injection += '<h3 class="event_time_location">' + this_event_time_start;
							if(this_event_location.length>0) {
								html_injection += ' | ' + this_event_location;
							}
							html_injection += '</h3>' + "\n";
						} else if(this_event_location.length>0) {
							html_injection += '<h3 class="event_time_location">' + this_event_location + '</h3>' + "\n";
						}
						
						html_injection += '<p>' + $(this).find('abstract').text() + '</h3>' + "\n";
						html_injection += '</div>' + "\n";
					});
					
					
					html_injection += '</div>' + "\n";
					
					// Since we want to keep the <div>'s in the appropriate order by date, we need to look at what dates are already accounted for. The variable "injected" keeps track of whether or not we have placed the event in the DOM.
					var injected = false;
					
					// If there are no days represented, just stick this one in there and be done with it.
					if($('#events .day').length==0) {
						$('#events').append(html_injection);
						injected = true;
					} else {
						// Otherwise, we look at each represented date in order until we find a date that is later than the one we're trying to put in. Then we add the new date right before that.
						$('#events .day').each(function() {
							if(!injected) {
								var date_compare = $(this).attr('id').replace('events_day_','');
								if(this_date<date_compare) {
									$(this).before(html_injection);
									injected = true;
								}
							}
						});
						
						// If we've looked at all the current dates and still haven't found a place to stick it, it goes at the end.
						if(!injected) {
							$('#events').append(html_injection);
						}
					}
					// Before we reveal the new dates, we keep it hidden and show or hide event types.
					$('#events_day_' + this_date).hide();
					
					showHideEventTypes('fast');
					$('#events_day_' + this_date).slideDown(500);
				}
			});
			
			// Now we look through the most recent XML list of dates. If any dates currently visible are not listed in the latest XML, we hide them.
			$('#events .day').each(function() {
				var this_date = $(this).attr('id').replace('events_day_','');
				var find_relevant_date = $(xml).find('day[date="' + this_date + '"]');
				if(find_relevant_date.length==0) {
					$(this).slideUp(500);
				}
			});
			
		},
		'xml'
	);
}