/// <reference path="jQuery.intellisense.js"/>
/// <reference path="xeko.js"/>
/// <reference path="messaging.js"/>

$(document).ready(function() 
{
	// Get today's date server-side (defaults to client-side date if an error occurs)
	$.ajax({
		type: "GET",
		url : "/widgets/widget.Events.handler.php?type=getDate",
		beforeSend: function() {  },
		complete: function() {
			xeko.widgets.events.constructDateMenu(xeko.widgets.events.today.getMonth(), instance);
			$("#eventsLoading").hide();
		},
		success : function(xml)
		{
			xeko.widgets.events.today = new Date(Date.parse($("date", xml).text()));
			
			// Get events XML for the current month
			xeko.widgets.events.getEventsByMonth(xeko.widgets.events.today.getMonth() + 1, xeko.widgets.events.today.getFullYear(), instance);
		}
	});
	
});



xeko.widgets.events = {
  "today": new Date(),
  "monthsToShow": 6,
  "months": new Array(),
  "monthXml": {},
  "itemsPerPage": { "Page": 4, "Drawer": 2 },
  "constructDateMenu": function(selectedMonth, instance) {
    // if an instance is specified, apply to only that instance; otherwise apply to all instances
    var identifierPrefix = instance ? "#events" + instance : ".events";

    // clear existing links
    $(identifierPrefix + "UpcomingMonths>li").remove();

    // display dates from this month through monthsToShow
    var throughDate = new Date(this.today);
    throughDate = throughDate.setMonth(throughDate.getMonth() + this.monthsToShow);

    // Display all months in order w/ selected month plucked out
    for (var dte = new Date(this.today); dte < throughDate; dte.setMonth(dte.getMonth() + 1)) {
      if (dte.getMonth() == selectedMonth) {
        $(identifierPrefix + "CurrentMonth").text(xeko.utilities.formatMonthYear(dte));
      }
      else {
        // Store month/year information in a static variable
        xeko.widgets.events.months[dte.getMonth()] = { "month": dte.getMonth() + 1, "year": dte.getFullYear() };
        $(identifierPrefix + "UpcomingMonths")	// the list element
					.append("<li></li>")	// add a new list item
					.children(":last")	// select the just-added list item
					.append("<a href=\"#" + dte.getMonth() + "\">" + xeko.utilities.formatMonthYear(dte) + "</a>&nbsp; | &nbsp;")	// add the link
					.children()	// select the just-added link
					.click(function(e) {
					  e.preventDefault();

					  var thisCurrentMonth = $(this).attr("href").substr(1);

					  // current instance is embedded in the ID of the parent <ol>
					  var parentId = $(this).parent().parent().attr("id");
					  var thisCurrentInstance = parentId.substring("events".length, parentId.indexOf("UpcomingMonths"));

					  // recreate the date menu with the current month selected
					  xeko.widgets.events.constructDateMenu(thisCurrentMonth, thisCurrentInstance);

					  // fetch and render Events HTML
					  xeko.widgets.events.getEventsByMonth(xeko.widgets.events.months[thisCurrentMonth].month, xeko.widgets.events.months[thisCurrentMonth].year, thisCurrentInstance);
					})
				;
      }
    }
  },
  "getEventsByMonth": function(month, year, instance) {
    // Load the XML for this month, unless it has already been loaded
    if (!this.monthXml[month + "_" + year]) {
      $.ajax({
        type: "GET",
        url: "/widgets/widget.Events.handler.php?type=getMonth&month=" + month + "&year=" + year,
        beforeSend: function() { xeko.lightbox.show(xeko.strings.LOADING, true, "eventsMonthLoad"); },
        complete: function() { xeko.lightbox.hide("eventsMonthLoad"); },
        success: function(xml) {
          if ($("errors", xml).text().length > 0) {
            xeko.widgets.events.throwError(xeko.messaging.error.EVENTS_LOAD_ERROR, instance);
          }
          else {
            xeko.widgets.events.hideError(instance);

            // Cache XML
            xeko.widgets.events.monthXml[month + "_" + year] = xml;

            //##TODO determine if it's feasible to use w/ multiple months?
            //						// Initialize pagination
            //						xeko.paging.init(
            //							"events" + instance, 
            //							$("event", xml).length, 
            //							xeko.widgets.events.itemsPerPage[instance], 
            //							"#eventsNavBarRange", 
            //							".eventsNavBarPagination", 
            //							"xeko.widgets.events.renderEvents(" + month + ", " + year + ", \"" + instance +"\")"
            //						);

            // Render loaded Events XML
            xeko.widgets.events.renderEvents(month, year, instance);
          }
        },
        error: function(xmlHttpRequest, status, err) {
			if (xmlHttpRequest.status > 0) xeko.widgets.events.throwError(xeko.messaging.error.EVENTS_LOAD_ERROR, instance);
        }
      });
    }
    else {
      // Render cached Events XML
      this.renderEvents(month, year, instance);
    }
  },
  "renderEvents": function(month, year, instance) {
    //##TODO determine if it's feasible to use w/ multiple months?
    //xeko.paging.construct("events" + instance);

    // if an instance is specified, apply to only that instance; otherwise apply to all instances
    var identifierPrefix = instance ? "#events" + instance : ".events";

    var xml = this.monthXml[month + "_" + year];

    // Total # of records
    //##TODO add pagination
    $(identifierPrefix + "ItemsPerPage").text($("events>item", xml).length);
    $(identifierPrefix + "TotalItems").text($("events>item", xml).length);

    // Clear existing list items
    $(identifierPrefix + "List>li").remove();

    var currentItem = 1;
    $("events>item", xml).each(function() {
      //if (xeko.paging.isInRange(currentItem, "events" + instance)) {
      if ($(this).find("display").text() == 1) {
        var startdate = xeko.utilities.formatDateFromOldServices($(this).find("startdate").text());
        var dteStr = xeko.utilities.formatShortDate(startdate.toString());

        var times = $(this).find("times").text();
        var description = $(this).find("description").text().replace(/\n/g, "<br />");
        var location = $(this).find("location").text().replace(/\n/g, "<br />");
        var url = $(this).find("url").text();
        if (url.length > 0) {
          url = "<div class='eventLink'><a target='_blank' href='" + url + "'>Location link &#0187;</a></div>";
        }
        
        $(identifierPrefix + "List")
						.append("<li></li>")
						.find("li:last")
        //.append("<h2>" +  + "</h2>")	// Event Title NOT SUPPORTED
						.append("<h2>" + description + "</h2>")	// description
						.append("<div class='eventLocation'>" + location + "</div>")	// Location
						.append("<div class='eventDate'>" + dteStr + "<br />" + times + "</div>")	// Date & time
						.append("<div class='clear'></div>")
						.append(url)
						.append("<div class='eventUnderline'></div>");
        ;
      }
      //}
      currentItem++;
    });
  },
  "throwError": function(msg, instance) {
    // if an instance is specified, apply to only that instancel; otherwise apply to all instances
    var identifierPrefix = instance ? "#events" + instance + " " : "";

    $(identifierPrefix + "p.error").text(msg).show();
  },
  "hideError": function(instance) {
    // if an instance is specified, apply to only that instancel; otherwise apply to all instances
    var identifierPrefix = instance ? "#events" + instance + " " : "";

    $(identifierPrefix + "p.error").hide();
  }
};
