﻿(function ($) {
    jQuery.fn.rockwellCalendar = function (settings) {
        var config =
		{
		    month: null,
		    year: null,
		    calendarSelector: "div#calendar",
		    eventListingSelector: "div#eventListing",
		    calendarObj: new Date(),
		    monthArr: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
		    shortMonthArr: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"],
		    weekdayArr: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
		};

        if (settings) {
            jQuery.extend(config, settings);
        }

        this.each(function () {
            // Set a reference of the object
            obj = jQuery(this);

            // Unbind prior click events
            jQuery("img.lastMonth").unbind();
            jQuery("img.nextMonth").unbind();
            jQuery("td.event").unbind();

            // Set the date object's current month and year, and set the date to the first of the month
            config.calendarObj.setMonth(config.month);
            config.calendarObj.setFullYear(config.year);
            config.calendarObj.setDate(1);

            // Determine next year and next month.
            if (config.month == 0) {
                lastMonth = 11;
                lastYear = Number(config.year) - 1;
                nextMonth = Number(config.month) + 1;
                nextYear = Number(config.year);
            }
            else if (config.month == 11) {
                lastMonth = Number(config.month) - 1;
                lastYear = Number(config.year);
                nextMonth = 0;
                nextYear = Number(config.year) + 1;
            }
            else {
                lastMonth = Number(config.month) - 1;
                lastYear = Number(config.year);
                nextMonth = Number(config.month) + 1;
                nextYear = Number(config.year);
            }

            // Get the last day of the current month
            lastDay = new Date((new Date(nextYear, nextMonth, 1)) - 1).getDate();

            var domain = document.domain;
            var url = "http://" + domain + "/Rockwell/Layouts/NewsEventsCalendarJSON.aspx";

            // Make the AJAX request to get the events from this month
            jQuery.ajax(
			{
			    type: "GET",
			    url: url,
			    data:
				{
				    m: (config.month + 1),
				    y: config.year
				},
			    dataType: "json",
			    beforeSend: function (xhr) {
			        // Construct the loading text
			        loadingText = "<img src=\"/~/media/Images/Loading/modal_loading.ashx\" alt=\"Loading...\" title=\"Loading...\" />\n";
			        loadingText += "<span>Loading...</span>";

			        // Populate the loading div
			        obj.html(loadingText);
			    },
			    error: function (xhr, textStatus, errorThrown) {
			        // Spit out the error
			        console.log(textStatus + ": " + errorThrown);
			    },
			    success: function (data, textStatus, xhr) {
			        // Set up the initial calendar string
			        calendarString = "<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" class=\"calendar\" width=\"100%\">";
			        calendarString += "<tr class=\"header\">";
			        calendarString += "<td valign=\"top\" align=\"center\" class=\"arrow\"><img src=\"/~/media/Images/Buttons/arrow_left.ashx\" alt=\"Arrow Left\" title=\"Arrow Left\" class=\"lastMonth\" /></td>";
			        calendarString += "<td valign=\"middle\" align=\"center\" colspan=\"5\" class=\"month\">" + config.monthArr[config.month] + " " + config.year + "</td>";
			        calendarString += "<td valign=\"top\" align=\"center\" class=\"arrow\"><img src=\"/~/media/Images/Buttons/arrow_right.ashx\" alt=\"Arrow Right\" title=\"Arrow Right\" class=\"nextMonth\" /></td>";
			        calendarString += "</tr>";
			        calendarString += "<tr class=\"header\">";
			        calendarString += "<td valign=\"middle\" align=\"center\" class=\"day\">Su</td>";
			        calendarString += "<td valign=\"middle\" align=\"center\" class=\"day\">M</td>";
			        calendarString += "<td valign=\"middle\" align=\"center\" class=\"day\">Tu</td>";
			        calendarString += "<td valign=\"middle\" align=\"center\" class=\"day\">W</td>";
			        calendarString += "<td valign=\"middle\" align=\"center\" class=\"day\">Th</td>";
			        calendarString += "<td valign=\"middle\" align=\"center\" class=\"day\">F</td>";
			        calendarString += "<td valign=\"middle\" align=\"center\" class=\"day\">Sa</td>";
			        calendarString += "</tr>";
			        calendarString += "<tr class=\"week\">";

			        // Initialize the counter variable
			        i = 0;

			        // Start the day count
			        d = 1;

			        // Print out the blank squares first
			        while (i < config.calendarObj.getDay()) {
			            // Add a blank square
			            calendarString += "<td valign=\"top\" align=\"right\" class=\"day\">&nbsp;</td>";

			            // Increment the counter
			            i++;
			        }

			        // Loop through all of the days
			        while (d <= lastDay) {
			            // Loop through one week at a time
			            while (i <= 6) {
			                // If we're starting a new row, open a new row tag
			                if (i == 0 && d > 1) {
			                    calendarString += "<tr class=\"week\">";
			                }

			                // Begin the day string
			                calendarString += "<td valign=\"top\" align=\"right\" class=\"day";

			                // If there's an event on this day, highlight the day
			                if (typeof (data[(Number(config.month) + 1) + "_" + d + "_" + config.year]) == "object") {
			                    calendarString += " event";
			                }

			                // Assign a unique ID to the day
			                calendarString += "\" id=\"" + (Number(config.month) + 1) + "_" + d + "_" + config.year + "\">" + d + "</td>";

			                // Increment counters for the counter and the day variable.
			                i++;
			                d++;

			                // If we've hit the last day of the month and we've got spaces left in the row, print out the first days of the next month
			                if (d > lastDay && i <= 6) {
			                    // Initialize a counter for the days in the next month
			                    j = 1;

			                    while (i <= 6) {
			                        // Add a blank box for the end of the month
			                        calendarString += "<td valign=\"top\" align=\"right\" class=\"day\">&nbsp;</td>";

			                        // Increment all counters
			                        j++;
			                        i++;
			                    }
			                }

			                // If we're at the end of a row, close the row tag
			                if (i == 7) {
			                    // Close the table row
			                    calendarString += "</tr>";
			                }
			            }

			            // Reset the counter
			            i = 0;
			        }

			        // Populate the targeted element
			        obj.html(calendarString);

			        // Bind last month event
			        jQuery("img.lastMonth").bind("click", function () {
			            // Run this plugin on the default selector
			            jQuery(config.calendarSelector).rockwellCalendar({ month: lastMonth, year: lastYear });
			        });

			        // Bind next month event
			        jQuery("img.nextMonth").bind("click", function () {
			            // Run this plugin on the default selector
			            jQuery(config.calendarSelector).rockwellCalendar({ month: nextMonth, year: nextYear });
			        });

			        // Cycle through the events and bind click events
			        jQuery("td.event").each(function () {
			            // Bind the click event
			            jQuery(this).bind("click", function () {
			                // Save the event ID
			                eventId = jQuery(this).attr("id");

			                // Make the AJAX request for the events on this day
			                jQuery.ajax(
							{
							    type: "GET",
							    dataType: "json",
							    url: url,
							    data:
								{
								    m: data[eventId][0].m,
								    d: data[eventId][0].d,
								    y: data[eventId][0].y
								},
							    beforeSend: function (xhr) {

							    },
							    success: function (eventData, textStatus, xhr) {
							        // Begin the event string
							        var eventString = "<p class=\"dateHeading\">Event(s) on " + config.monthArr[(eventData[eventId][0].m - 1)] + " " + eventData[eventId][0].d + "</p>";

							        // Cycle through each of the elements in the array
							        for (var i in eventData[eventId]) {
							            if (eventData[eventId][i].d != undefined) {
							                eventString += "<div class=\"eventInfo\">";
							                eventString += "<p class=\"eventCopy\">";
							                eventString += "<span class=\"date\">" + config.shortMonthArr[(eventData[eventId][i].m - 1)] + " " + eventData[eventId][i].d

							                // Get the ending and beginning timestamps
							                var startTs = Math.round(new Date(eventData[eventId][i].y, eventData[eventId][i].m - 1, eventData[eventId][i].d).getTime() / 1000);
							                var endTs = Math.round(new Date(eventData[eventId][i].endy, eventData[eventId][i].endm - 1, eventData[eventId][i].endd).getTime() / 1000);

							                if (startTs != endTs) {
							                    eventString += "&mdash;" + config.shortMonthArr[(eventData[eventId][i].endm - 1)] + " " + eventData[eventId][i].endd;
							                }

							                eventString += "</span><br />";
							                eventString += "<a href=\"" + eventData[eventId][i].ei + "\">" + eventData[eventId][i].en + "</a><br />";
							                eventString += eventData[eventId][i].ci + ", " + eventData[eventId][i].s + ", " + eventData[eventId][i].co + "<br />";
							                eventString += eventData[eventId][i].t;
							                eventString += "</p>";
							                eventString += "</div>";
							            }
							        }

							        // Populate the event details section
							        jQuery(config.eventListingSelector).html(eventString);
							    }
							});
			            });
			        });

			        // Build an empty array for the event types:
			        eventTypeArr = [];

			        // Build the event string
			        var eventString = "<p class=\"dateHeading\">Event(s) in " + config.monthArr[config.month] + "</p>";

			        // Set the event count iterator
			        var x = 1;

			        // Cycle through the event data object
			        for (var day in data) {
			            if (day.split("_")[0] == (config.month + 1)) {
			                // Cycle through the arrays on this date
			                for (var event in data[day]) {
			                    if (data[day][event].d != undefined) {
			                        // Check our event count
			                        if (x < 4) {
			                            // Check the array result
			                            if (!in_array(data[day][event].t, eventTypeArr)) {
			                                // Append to the event string
			                                eventString += "<div class=\"eventInfo\">";
			                                eventString += "<p class=\"eventCopy\">";
			                                eventString += "<span class=\"date\">" + config.shortMonthArr[(data[day][event].m - 1)] + " " + data[day][event].d;

			                                // Get the ending and beginning timestamps
			                                var startTs = Math.round(new Date(data[day][event].y, data[day][event].m - 1, data[day][event].d).getTime() / 1000);
			                                var endTs = Math.round(new Date(data[day][event].endy, data[day][event].endm - 1, data[day][event].endd).getTime() / 1000);

			                                if (startTs != endTs) {
			                                    eventString += "&mdash;" + config.shortMonthArr[(data[day][event].endm - 1)] + " " + data[day][event].endd;
			                                }

			                                eventString += "</span><br />";
			                                eventString += "<a href=\"" + data[day][event].ei + "\">" + data[day][event].en + "</a><br />";

			                                // Change to account for missing state, country, etc.
			                                var locationInfo = "";
			                                locationInfo += data[day][event].ci;
			                                if (data[day][event].s != null && data[day][event].s != "") {
			                                    if (locationInfo != null && locationInfo != "") {
			                                        locationInfo += ", " + data[day][event].s;
			                                    }
			                                    else {
			                                        locationInfo += data[day][event].s;
			                                    }
			                                }
			                                if (data[day][event].co != null && data[day][event].co != "") {
			                                    if (locationInfo != null && locationInfo != "") {
			                                        locationInfo += ", " + data[day][event].co;
			                                    }
			                                    else {
			                                        locationInfo += data[day][event].co;
			                                    }
			                                }

			                                eventString += locationInfo;
			                                //			                                eventString += data[day][event].ci + ", " + data[day][event].s + ", " + data[day][event].co + "<br />";
			                                eventString += "<br />" + data[day][event].t;
			                                eventString += "</p>";
			                                eventString += "</div>";

			                                // Add this event type to the array
			                                eventTypeArr.push(data[day][event].t);

			                                // Increment the event count
			                                x++;
			                            }
			                        }
			                    }
			                    else {
			                        // Break the loop
			                        break;
			                    }
			                }
			            }
			        }

			        // Show the event string
			        jQuery(config.eventListingSelector).html(eventString);
			    }
			});
        });

        return this;
    };
})(jQuery);
