/* Load the Google data JavaScript client library */
google.load("gdata", "2.x");

function init() {
  // init the Google data JS client library with an error handler
  google.gdata.client.init(handleGDError);
}

/**
 * Adds a leading zero to a single-digit number.  Used for displaying dates.
 */
function padNumber(num) {
  if (num <= 9) {
    return "0" + num;
  }
  return num;
}

function pageInit() {
  // Asynchronously invoke google interface
  window.setTimeout("registerEventCallback();", 1);
}

function registerEventCallback() {
  var service = new 
      google.gdata.calendar.CalendarService('cwtchcakes-flipcalendar-1.0');
  var query = 
   new google.gdata.calendar.CalendarEventQuery('http://www.google.com/calendar/feeds/lizbeth@vancura.co.uk/public/full');
  query.setOrderBy('starttime');
  query.setSortOrder('ascending');
  query.setFutureEvents(true);
  query.setSingleEvents(true);
  query.setMaxResults(1);

  // Indicate that we're looking for data
  var addfindingtext = document.getElementById("addfindingtext");
  if (addfindingtext) {
    addfindingtext.appendChild(document.createTextNode(" ... checking our calendar for details"));
  }

  service.getEventsFeed(query, listEvents, handleGDError);
}

/**
 * Callback for errors does nothing (no need for the user to see an error).
 */
function handleGDError(e) {
}

var weekday = new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";

function getDayString(day) {
  switch (day) {
  case 0: return "Sunday";
  case 1: return "Monday";
  case 2: return "Tuesday";
  case 3: return "Wednesday";
  case 4: return "Thursday";
  case 5: return "Friday";
  case 6: return "Saturday";
  default: return "";
  }
}

function getMonthString(month) {
  switch (month) {
  case 0: return "January";
  case 1: return "February";
  case 2: return "March";
  case 3: return "April";
  case 4: return "May";
  case 5: return "June";
  case 6: return "July";
  case 7: return "August";
  case 8: return "September";
  case 9: return "October";
  case 10: return "November";
  case 11: return "December";
  default: return "";
  }
}

function getDateWithSuffix(date) {
  var rem = date % 10;
  switch(rem) {
  case 1:
    if (date == 11) return date + 'th';
    return date + 'st';
  case 2:
    if (date == 12) return date + 'th';
    else return date + 'nd';
  case 3:
    if (date == 13) return date + 'th';
    return date + 'rd';
  }
  return date + 'th';
}

/**
 * When we've found the event, we create our specially named div,
 * for which the flip calendar background etc. is set in the css.
 */ 
function listEvents(feedRoot) {
  // Get the first entry
  var entries = feedRoot.feed.getEntries();
  if (entries.length > 0) {
    var entry = entries[0];

    // Get the container to add our section too, and double check
    // we haven't already added it.
    var container = document.getElementById("calendarcontainer");
    if (container) {

      // Clear out the existing contents
      while (container.firstChild) {
        container.removeChild(container.firstChild);
      }

      // Create our div
      flipcalendar = document.createElement("div");
      flipcalendar.id = "flipcalendar";

      // Fill in the date
      var times = entry.getTimes();
      if (times.length > 0) {
        startDateTime = times[0].getStartTime();
        startJSDate = startDateTime.getDate();

        // Month
        var month = document.createElement("div");
        month.id = "month";
        month.appendChild(document.createTextNode(getMonthString(startJSDate.getMonth())));
        flipcalendar.appendChild(month);

        // Day
        var day = document.createElement("div");
        day.id = "day";
        day.appendChild(document.createTextNode(getDayString(startJSDate.getDay())));
        flipcalendar.appendChild(day);

        // Date
        var date = document.createElement("div");
        date.id = "date";
        date.appendChild(document.createTextNode(getDateWithSuffix(startJSDate.getDate())));
        flipcalendar.appendChild(date);
      }

      // Create the description section
      var description = document.createElement("div");
      description.id = "caldescription";

      // Add the header
      var headerSpan = document.createElement("span");
      headerSpan.className = "calheader";
      headerSpan.appendChild(document.createTextNode("Next place to see us:"));
      headerSpan.appendChild(document.createElement("br"));
      description.appendChild(headerSpan);

      // Add the title
      var titleSpan = document.createElement("span");
      titleSpan.className = "caltitle";
      titleSpan.appendChild(document.createTextNode(entry.getTitle().getText()));
      titleSpan.appendChild(document.createElement("br"));
      description.appendChild(titleSpan);

      // Add the description
      var descriptionSpan = document.createElement("span");
      descriptionSpan.innerHTML = entry.getContent().getText();
      description.appendChild(descriptionSpan);

      // Location
      var locations = entry.getLocations();
      if (locations && locations.length > 0) {
        var location = locations[0];
        if (location) {
          var mapLink = document.createElement("a");
          var mapSearch = location.getValueString().replace('\s+','\+');
          mapLink.href = "http://maps.google.co.uk/maps?q=" + mapSearch;
          mapLink.appendChild(document.createTextNode("Click for a map"));
          descriptionSpan.appendChild(document.createElement("br"));
          descriptionSpan.appendChild(mapLink);
        }
      }

      flipcalendar.appendChild(description);

      // Add the div to the container
      container.appendChild(flipcalendar);
    }
  }
}

google.setOnLoadCallback(init);

