// Utility Functions

PadNum = function(number, size) {
    var result = "";
    var string = number.toString();
    var start = string.length;
    for (var i=0;i<(size-start);i++) {
	result += "0";
    }

    result += string;

    return(result);
};

// Calculate days in the month (Janunary = 0)
DaysInMonth = function (month, year) {
    var days = 31;

    if ((month == 3) | (month == 5) | (month == 8) | (month == 10)) 
	days = 30;
    else if ((month == 1) && ((year % 4) == 0))
	days = 29;
    else if (month == 1)
	days = 28;
    else 
	days = 31;

    return (days);
}

// Global Variables
var Categories;
var Events;
var Display = "Month";
var CurrentDate;
var StartDate;
var EndDate;
var Location = "1";
var Category = "All";
var EventAjaxCounter = 0;
var CategoryAjaxCounter = 0;
var hoverId;
var DisplayInstructions;

var m_names = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
var d_names_week = new Array("Sunday", "Thursday", "Monday", "Friday", "Tuesday", "Saturday", "Wednesday");


// Page Setup
jQuery(document).ready(function() {
	// Initialize the display date range
	CurrentDate = new Date();
	SetDateRange();

	// Setup Calendar Tabs
	$("#CalendarDisplayOptions").selectable({selected: SelectedOption});
	$("#CalendarDisplayLocations").selectable({selected: SelectedLocation});

	$("#CalendarDisplayOptions li").hover(function () {
		$(this).addClass("ui-myhover");
	    }, function () {
		$(this).removeClass("ui-myhover");
	    });

	$("#CalendarDisplayLocations li").hover(function () {
		$(this).addClass("ui-myhover");
	    }, function () {
		$(this).removeClass("ui-myhover");
	    });

	$("#CalendarMisc li").hover(function () {
		$(this).addClass("ui-myhover");
	    }, function () {
		$(this).removeClass("ui-myhover");
	    });


	$('#Instructions').dialog({position: "center", autoOpen: false, width: 450, resizable: false, modal: true, buttons: {Ok: function() {$(this).dialog('close');}}});

	
	$("#CalendarHelp").bind("click", function () {
		$('#Instructions').dialog("open");
	    });
	$("#CalendarPDF").bind("click", function () {
		document.location.href = ($(this).find("a")[0].href);
	    });
	
	// Build the calendar based on the defaults for the page
	BuildCalendar();

	// Fetch the categories for the current date range
	BuildCategories();
	
	// Setup the checout area to receive
	$('#checkout_container').droppable({hoverClass: 'drophover', drop: DropEvent, tolerance: 'pointer'});
	
	// display the instructions
	if (DisplayInstructions) {
	    $('#Instructions').dialog("open");
	    DisplayInstructions = false;
	}
    });
// Move the Calendar to the next date based on display type
NextDate = function () {
    var Year = StartDate.getFullYear();
    var Month = StartDate.getMonth();
    var Day = StartDate.getDate();

    Category = "All";

    if (Display == "Month") {
	Month++;
	if (Month > 11) {Year++; Month = 0}

    } else if (Display == "Week") {
	Day += 7;
	if (Day > DaysInMonth(Month, Year)) {Day -= DaysInMonth(Month, Year); Month++;}
	if (Month > 11) {Year++; Month = 0}

    } else {
	Day++;
	if (Day > DaysInMonth(Month, Year)) {Day -= DaysInMonth(Month, Year); Month++;}
	if (Month > 11) {Year++; Month = 0}
    }

    CurrentDate = new Date(Year, Month, Day);
    SetDateRange();
    
    BuildCalendar();
    BuildCategories();
}


// Move the Calendar to the next date based on display type
PreviousDate = function () {
    var Year = StartDate.getFullYear();
    var Month = StartDate.getMonth();
    var Day = StartDate.getDate();
    
    Category = "All";

    if (Display == "Month") {
	Month--;
	if (Month < 0) {Year--; Month = 11}

    } else if (Display == "Week") {
	Day -= 7;
	if (Day < 1) {Month--; Day = DaysInMonth(Month, Year)+Day;}
	if (Month < 0) {Year--; Month = 11}
    } else {
	Day--;
	if (Day < 1) {Month--; Day = DaysInMonth(Month, Year)+Day;}
	if (Month < 0) {Year--; Month = 11}
    }

    CurrentDate = new Date(Year, Month, Day);
    SetDateRange();
    
    BuildCalendar();
    BuildCategories();
}



// Process and display the category data 
BuildCategories = function (data) {
    CategoryAjaxCounter++;
    $.getJSON("/categories/getactivities/Start:" + StartDate.getFullYear() + "-" + (StartDate.getMonth()+1) + "-" + StartDate.getDate() + "/End:" + EndDate.getFullYear() + "-" + (EndDate.getMonth()+1) + "-" + EndDate.getDate() + "/Location:" + Location + "/Counter:" + CategoryAjaxCounter, BuildCategoriesCallback);
}

// Process and display the category data 
BuildCategoriesCallback = function (data) {
    // Ignore old responses
    if (data.counter != CategoryAjaxCounter)
	return 0;
    
    // Extract out the actual data
    data = data.value;

    Categories = data;

    var html = '<div>';
    var PrevCat = '';

    for (var i=0; i < Categories.length; i++) {

	if (Categories[i].categories.name != PrevCat) {
	    if (PrevCat != '')
		html += "</ul>";
	    
	    PrevCat = Categories[i].categories.name;
	    html += '<h3 id="Category' + Categories[i].categories.id + '"><a href="#" >' + Categories[i].categories.name + "</a></h3>";
	    html += "<ul class='activities'>";
	}
	 
	html += "<li class='activity" + i + "'><span class='name'>" + Categories[i].activities.name + "</span></li>";
    }

    html += "</ul></div>";
    
    if ($("#categories").children().length > 0) {
	$("#categories").accordion( 'destroy' );
	$("#categories").html("&nbsp");
    }


    $("#categories").html(html);
    $("#categories div").accordion({change: ChangedCategory, fillSpace: false, active: '#Category' + Category});
    
    //    $("#categories .activities").jScrollPane();

    // Setup the click handler for the categories area
    $("#categories li").hover(
			   function () {
			       var id = this.className.substr(8);
			       var pos = $(this).offset();
			       $(this).addClass("ui-myhover");
			       ShowActivityDescription(id, pos.top, pos.left);
			       hoverId = Categories[id].activities.id;
			       $(".activity"+hoverId).addClass("ui-myhover");
			   },
			   function () {
			       var id = this.className.substr(8);
			       $("#ActivityDescription").hide();
			       $(this).removeClass("ui-myhover");
			       $(".activity"+hoverId).removeClass("ui-myhover");
			   }
);
    



}

// Build the calendar for the current date range    
BuildCalendar = function () {
    var Year = StartDate.getFullYear();
    var Month = StartDate.getMonth();
    var StartDay = StartDate.getDate();
    var EndDay = EndDate.getDate();
    
    var CalendarDays;
    var CalendarRows;
    var CalendarCols;
    
    if (Display == "Month") {
	CalendarRows = 6;
	CalendarCols = 7;

	$("#CurrentDate").html(m_names[Month] + " " + Year);
    } else if (Display == "Week") {
	CalendarRows = 4;
	CalendarCols = 2;	

	$("#CurrentDate").html("Week of " + (Month+1) + "/" + StartDay + "/" + Year);
    } else {
	CalendarRows = 1;
	CalendarCols = 1;

	$("#CurrentDate").html((Month+1) + "/" + StartDay + "/" + Year);
    }

    $("#PDFDownload").attr("href", "/documents/DownloadCalendar/" + Year + "/" + (Month+1));

    CalendarDays = CalendarRows * CalendarCols;	
    CalendarData = new Array(CalendarDays);
    
    if (Display == "Month") {
	var StartDayOfWeek = StartDate.getDay() - 1;

	for (var i=0; i < CalendarDays; i++) {
	    CalendarData[i] = {Year: 0, Month: 0, Day: 0};
	    
	    if (i < (StartDayOfWeek)) {
		CalendarData[i].Year = 0;
		CalendarData[i].Month = 0;
		CalendarData[i].Day = 0;
	    } else if ((i-StartDayOfWeek) > EndDay) {
		CalendarData[i].Year = 0;
		CalendarData[i].Month = 0;
		CalendarData[i].Day = 0;
	    } else {
		CalendarData[i].Year = Year;
		CalendarData[i].Month = PadNum(Month+1,2);
		CalendarData[i].Day = PadNum(i-StartDayOfWeek, 2);
	    }
	}
	
    } else if (Display == "Week") {
	for (var i=0; i < CalendarDays; i++) {
	    CalendarData[i] = {Year: 0, Month: 0, Day: 0};

	    if (i<7) {
		CalendarData[i].Year = Year;
		CalendarData[i].Month = PadNum(Month+1,2);
		CalendarData[i].Day = PadNum(StartDay, 2);
	    }
	    StartDay++;
	    if (StartDay > DaysInMonth(Month, Year)) {StartDay -= DaysInMonth(Month, Year); Month++;}
	    if (Month > 11) {Year++; Month = 0}
	}

	// Rearrange the days to match a better layout
	var swap;

	swap = CalendarData[6];
	CalendarData[6] = CalendarData[3];
	CalendarData[3] = CalendarData[5];
	CalendarData[5] = swap;
	swap = CalendarData[1];
	CalendarData[1] = CalendarData[4];
	CalendarData[4] = CalendarData[2];
	CalendarData[2] = swap;
	
    } else {
	CalendarData[0] = {Year: 0, Month: 0, Date: 0};
	CalendarData[0].Year = Year;
	CalendarData[0].Month = PadNum(Month+1,2);
	CalendarData[0].Day = PadNum(StartDay, 2);
    }
    
    
    // Draw the calendar framework
    var html = '<table id="calendar_table">';

    // Add the days of the week to the month dislay
    if (Display == "Month") {
	html += "<tr>\n";
	html += "<td class='DoW'>Sunday</td><td class='DoW'>Monday</td><td class='DoW'>Tuesday</td><td class='DoW'>Wednesday</td><td class='DoW'>Thursday</td><td class='DoW'>Friday</td><td class='DoW'>Saturday</td>";
	html += "</tr>\n";
    }
    
    for (var row=0; row<CalendarRows; row++) {
	
	if (row >= 5 && CalendarData[35].Day == 0) {
	    // Do nothing
	} else {
	    
	    html += "<tr>\n";
	    for (var col=0; col<CalendarCols; col++) {
		Position = (row * CalendarCols + col);
		html += "<td class='Day'>";
		html += "<div class='" + Display + "Format'>";
		if (CalendarData[Position].Day == 0) {
		    html += "<div class='Empty'>&nbsp;</div>";
		} else {
		    if (Display == "Month") {
			html += "<div class='DoM'>" + CalendarData[Position].Day + "</div>";
		    } else if (Display == "Week") {
			html += "<div class='DoM DoMLeft'>Activities for " + d_names_week[Position] + " " + CalendarData[Position].Month + "/" + CalendarData[Position].Day + "</div>";
		    } else if (Display == "Day") {
			html += "<div class='DoM DoMLeft'>Activities for " + d_names_week[Position] + " " + CalendarData[Position].Month + "/" + CalendarData[Position].Day + "</div>";
		    }
		    html += "<div id='" + CalendarData[Position].Year + "-" + CalendarData[Position].Month + "-" + CalendarData[Position].Day + "' class='DayCell'>";
		    
		    html += "<p></p>";
		    html += "</div>";
		}
		html += "</div>";
		html += "</td>\n";
	    }
	    html += "</tr>\n";
	}
    }
    
    html += "</table>";
    $("#calendar_layout").html(html);
    
    GetEvents();
}
    
    
// Get the events for the calendar
GetEvents = function (data) {
    EventAjaxCounter++;
    $.getJSON("/events/getforcalendar/Start:" + StartDate.getFullYear() + "-" + (StartDate.getMonth()+1) + "-" + StartDate.getDate() + "/End:" + EndDate.getFullYear() + "-" + (EndDate.getMonth()+1) + "-" + EndDate.getDate() + "/Location:" + Location + "/Category:" + Category + "/Counter:" + EventAjaxCounter, GetEventsCallback);
}

// Process and display the activities data
GetEventsCallback = function (data) {
    // Ignore old responses
    if (data.counter != EventAjaxCounter)
	return 0;
    
    // Extract out the actual data
    data = data.value;

    // Remove Events
    $(".event").remove();

    // Keep the data
    Events = data;

    // Display each event
    for (var i=0; i < Events.length; i++) {

	// Build the html for an activity display
	var html = "";

	if (Display == "Month") {
	    html += "<h4 class='event activity" +  Events[i].activities.id + "'>";
	    html += "<div id='event" + i + "'>";
	    html += "<span class='time'>" + Events[i].events.start_time + "</span> ";
	    html += "<span class='name'>" + Events[i].activities.name + "</span>";
	    html += "</div>";
	    html += "</h4>";
	} else if (Display == "Week") {
	    html += "<h4 class='event activity" +  Events[i].activities.id + "'>";
	    html += "<div id='event" + i + "'>";
	    html += "<span class='time'>" + Events[i].events.start_time + "-" +  Events[i].events.end_time + "</span> ";
	    html += "<span class='name'>" + Events[i].activities.name + "</span>";
	    html += "<span class='description'>" + Events[i].activities.description + "</span>";
	    html += "</div>";
	    html += "</h4>";
	
	} else if (Display == "Day") {
	    html += "<h4 class='event activity" +  Events[i].activities.id + "'>";
	    html += "<div id='event" + i + "'>";
	    html += "<span class='time'>" + Events[i].events.start_time + " - " +  Events[i].events.end_time + "</span> ";
	    html += "<span class='name'>" + Events[i].activities.name + "</span>";
	    html += "<span class='location'>" + Events[i].locations.name + "</span>";
	    html += "<span class='description'>" + Events[i].activities.description + "</span>";
	    html += "</div>";
	    html += "</h4>";
	
	}

	$("#" + Events[i].events.date).append(html);

    }

    $(".event").draggable({ addClasses: false, helper: mydrag, revert: "invalid" });
    $(".event").hoverIntent({ sensitivity: 3, interval: 200, over: CalendarEventHoverIn, timeout: 0, out: CalendarEventHoverOut});
}
    
CalendarEventHoverIn = function () {
    var id = this.firstChild.id.substr(5);

    var pos = $(this).offset();
    $(this).addClass("ui-myhover");

    if (Display == "Month")
	ShowEventDescription(id, pos.top, pos.left + this.offsetWidth);

}
    
CalendarEventHoverOut = function () {
    $("#ActivityDescription").hide();
    $(this).removeClass("ui-myhover");
}


mydrag = function () {
    return $(this).clone().css('width', this.offsetWidth - 4)[0];
    }

// Provide more information for a single event    
ShowEventDescription = function (id, top, left) {
    var i = parseInt(id);
    
    var offset = $('#body').offset();
    
    $("#ActivityDescription .name").html(Events[i].activities.name);
    $("#ActivityDescription .description").html(Events[i].activities.description);
    $("#ActivityDescription").css({'top' : top - offset.top, 'left' : left - offset.left - 5});
    $("#ActivityDescription").show();
}

// Provide more information for a single activity
ShowActivityDescription = function (id, top, left) {
    
    var i = parseInt(id);

    var offset = $('#body').offset();
	    
    $("#ActivityDescription .name").html(Categories[i].activities.name);
    $("#ActivityDescription .description").html(Categories[i].activities.description);
    $("#ActivityDescription").css({'top' : top - offset.top, 'left' : 85 + left - offset.left});
    $("#ActivityDescription").show();
}

DropEvent = function(event, ui) {
    var html = "";
    var eventId = ui.draggable[0].firstChild.id.substr(5);

    $("#EventRegister .instructions").remove();

    // Check if it is already on the list 
    if ($("#EventRegister").find("[value="+Events[eventId].events.id+"]").length > 0) {
	alert("This Activity is already on your list");
    } else {
	html += "<div class='RegisteredEvent ui-corner-top'>";
	html += "<input type='hidden' name='data[Event][]' value='" + Events[eventId].events.id + "' />";
	html += "<div class='date ui-corner-top'>";
	
	html += Events[eventId].events.start_time  + "<br />";
	html += m_names[Events[eventId].events.date.substr(5,2)-1] + " ";
	html += Events[eventId].events.date.substr(8,2) + " ";
	html += Events[eventId].events.date.substr(0,4);
	
	html += "</div> ";
	html += "<div class='name'>" + Events[eventId].activities.name + "</div>";
	html += "</div>";
	
	$("#EventRegister").append(html).children(":last").hover(EventHoverIn, EventHoverOut);
    }
    
}

EventHoverIn = function ()
{
    $(this).append("<img class='closebox' src='/img/close.gif' />");
    $(this).find(".closebox").click(function () {$(this).parent().remove();});
}

EventHoverOut = function ()
{
    $(this).find(".closebox").remove();
}


SelectedOption = function(event, ui) {
    var myDisplay = ui.selected.id.substr(7);

    if (myDisplay == "Next") {
	$("#CalendarDisplayOptions li").removeClass("ui-selected");
	$("#Display"+Display).addClass("ui-selected");
	NextDate();
    } else if (myDisplay == "Previous") {
	$("#CalendarDisplayOptions li").removeClass("ui-selected");
	$("#Display"+Display).addClass("ui-selected");
	PreviousDate();
    } else {
	Display = myDisplay;
	SetDateRange();
	BuildCalendar();
    }
}

ChangedCategory = function(event, ui) {
    Category = ui.newHeader[0].id.substr(8);
    GetEvents();
}

SelectedLocation = function(event, ui) {
    Location = ui.selected.id.substr(8);

    GetEvents();
    BuildCategories();
}

// Set Date Range sets the start and end dates based on the current date
SetDateRange = function() {
    var Year = CurrentDate.getFullYear();
    var Month = CurrentDate.getMonth();
    var Day = CurrentDate.getDate();

    if (Display == "Month") {
	StartDate = new Date(Year, Month, 1);
	EndDate = new Date(Year, Month, DaysInMonth(Month, Year));
	
    } else if (Display == "Week") {
	var FirstDay = Day - CurrentDate.getDay();
	StartDate = new Date(Year, Month, FirstDay);
	
	var LastDay = FirstDay + 6;
	if (LastDay > DaysInMonth(Month, Year)) {LastDay -= DaysInMonth(Month, Year); Month++;}
	if (Month > 11) {Year++; Month = 0}

	EndDate = new Date(Year, Month, LastDay);
    } else {
	StartDate = new Date(Year, Month, Day);
	EndDate = new Date(Year, Month, Day);
    }
}


