// variable functions, see defaults for parameters:
var applyFontEffect = true;
var handleError;
var handleNewFeed;
var nowPlaying; // must return true if an event is now playing, false otherwise
var nowPlayingOutlineColor = '#0e0e0e';

var clockDivParentTop = "73px";
var clockDivParentRight = "260px";
var altClockDivParentTop = "60px";
var altClockDivParentRight = "410px";

var showMoreText = "+ more";
var showLessText = "- less";
var showingMore = false;

var startingMomentarilyMessage = "[starting momentarily]";
var nothingScheduledMessage = "no programming scheduled at this time";
var nextScheduledIncludesCurrentEvent = true;

var doThreeDaySchedule = false;
var numDaysInSchedule = 3;
var eventSeparator = "<br><br>";

// other variables:
var checkCalendarWaitTime = 10000;
var calendarMaxResults = 100;

var calendar_account = "07gc0eti6unme0e4qumnanpths@group.calendar.google.com";  // get the calendar address from the calendar settings, after making it public:
var feedUrl_prefix = "http://www.google.com/calendar/feeds/"; 
var feedUrl_postfix = "/public/full";

var myService;
var query;

var maxTime = 9999999999999;
var recheckCalendarTimeout = maxTime;
var oldTs = "";
var lastCalendarUpdateDate = "";
var firstCalendarFeedHandled = false;

var calendarError;

var title_content = "";
var description_content = "";
var time_content = "";
var where_content = "";
var description_content = "";

var firstNowPlaying = true;
var futureIndex = 0;

var highlightsArray = new Array();
var highlight;
var defaultHighlightImage = "/images/site/schedule/imagePlaceholder240x168.png";
var highlight_date_offset = -10800000;

function getTimeRange(event)
{
  return getClockTime(getEventUTCTime(event)) + " - " + getClockTime(getEventUTCEndTime(event));
}

function getClockTime(timeinms)
{
   var now    = new Date( timeinms + hebron_offset ); // UTC time plus Hebron offset (2 hours)
   var hour   = now.getUTCHours();
   var minute = now.getUTCMinutes();
   var ap = "AM";
   if (hour   > 11) { ap = "PM";             }
   if (hour   > 12) { hour = hour - 12;      }
   if (hour   == 0) { hour = 12;             }
   if (minute < 10) { minute = "0" + minute; }
   var timeString = hour +  ':' + minute + " " + ap;
   return timeString;
}


function googlecalendar_setup() {
  google.load("gdata", "1.s");
  google.setOnLoadCallback(getFirstFeed);

  if(doThreeDaySchedule) {
    for (var i=1; i<=numDaysInSchedule; i++) document.getElementById("day" + i + "Wrapper").style.display = "none";

    
      highlight = new Object();
      highlight.date = new Date( 1288653222000 + highlight_date_offset );

      if("" == "") highlight.image = defaultHighlightImage;
      else highlight.image = "/images/site/schedule/_240.jpg"

      highlight.title = "Moe&#8217;s ribs (#2+3) hurt? / Mich&#8217;ael&#8217;s [liver] &amp; &#123;head&#125; does!&nbsp; PHP &amp; html, are enemies - for sure.".replace("&#8217\;", "'");
      highlight.header = "apostrophe ' slash / pipe | comma, period. exclamation! question? number # (parentheses) plus + [brackets] {more brackets} ".replace("&#8217\;", "'"); 
  
      highlightsArray.push(highlight);

    
  }
}

function getFirstFeed() {
  setupMyService();
  query = new google.gdata.calendar.CalendarEventQuery(feedUrl_prefix + calendar_account + feedUrl_postfix);
  //query.setFutureEvents(true);
  query.setMaxResults(calendarMaxResults);
  query.setOrderBy('starttime');
  query.setSortOrder('ascending');

  getMyFeed();
}

function getMyFeed() {
  var requestStartTimeDate = new Date(new Date().getTime() + time_offset - (24 * 60 * 60 * 1000));
  var requestStartTime = new google.gdata.DateTime(requestStartTimeDate, false);
  query.setMinimumStartTime(requestStartTime);

  myService.getEventsFeed(query, handleMyFeed, sleepThenHandleError);
}

function setupMyService() {
  myService = new google.gdata.calendar.CalendarService('HEB2-calendar');
}


function default_nowPlaying(event) {
  title_content = "";
  description_content = "";
  time_content = "";
  where_content = "";
  description_content = "";

  if (event != undefined)
  {
    if (getEventUTCTime(event) <= getUTCTime()) {  // if the event started before now
      title_content = event.getTitle().getText();
      description_content = event.getContent().getText();
      time_content =  getTimeRange(event);
      where_content = event.getLocations()[0].getValueString();
      
      recheckCalendarTimeout = getEventUTCEndTime(event);
    }
  }

  var nowPlayingIntroE = document.getElementById('nowPlayingIntro');
  var nowPlayingTitleE = document.getElementById('nowPlayingTitle');
  var nowPlayingDescriptionE = document.getElementById('nowPlayingDescription');
  var nowPlayingTimesE = document.getElementById('nowPlayingTimes');
  var nowPlayingWhereE = document.getElementById('nowPlayingWhere');
  var showDescriptionE = document.getElementById('showDescription');
  var clockDivParentE = document.getElementById('clockDivParent');

  if (applyFontEffect) {
    if (nowPlayingIntroE) $("#nowPlayingIntro").removeFE(true);  
    if (nowPlayingTitleE) $("#nowPlayingTitle").removeFE(true);
    if (nowPlayingTimesE) $("#nowPlayingTimes").removeFE(true);
    if (nowPlayingWhereE) $("#nowPlayingWhere").removeFE(true);
    if (showDescriptionE) $("#showDescription").removeFE(true);
    if (nowPlayingDescriptionE) $("#nowPlayingDescription").removeFE(true);
  }

  if (title_content != "") {
    if (nowPlayingIntroE) nowPlayingIntroE.innerHTML = "// NOW PLAYING:";
    if (nowPlayingTitleE) nowPlayingTitleE.innerHTML = title_content;
    if (nowPlayingWhereE) nowPlayingWhereE.innerHTML = where_content;
    if (nowPlayingTimesE) nowPlayingTimesE.innerHTML = time_content;
    if (nowPlayingDescriptionE) nowPlayingDescriptionE.innerHTML = "";
    if (description_content != "" && showDescriptionE) {
      showDescriptionE.innerHTML = showMoreText;
      showDescriptionE.onclick = toggleShowDescription;
    } else if (description_content == "" && showDescriptionE) {
      document.getElementById('showDescription').innerHTML = "";
      document.getElementById('showDescription').onclick = function(){};}
    showingMore = false;
    
    if (applyFontEffect) {
      if (nowPlayingIntroE) $("#nowPlayingIntro").FontEffect({ outline:true, outlineColor1:nowPlayingOutlineColor, outlineWeight:1 });
      if (nowPlayingTitleE) $("#nowPlayingTitle").FontEffect({ outline:true, outlineColor1:nowPlayingOutlineColor, outlineWeight:1 });
      if (nowPlayingWhereE) $("#nowPlayingWhere").FontEffect({ outline:true, outlineColor1:nowPlayingOutlineColor, outlineWeight:1 });
      if (nowPlayingTimesE) $("#nowPlayingTimes").FontEffect({ outline:true, outlineColor1:nowPlayingOutlineColor, outlineWeight:1 });
      if (showDescriptionE) $("#showDescription").FontEffect({ outline:true, outlineColor1:nowPlayingOutlineColor, outlineWeight:1 });
    }

    if (clockDivParentE) {
      clockDivParentE.style.top = altClockDivParentTop;
      clockDivParentE.style.right = altClockDivParentRight;
    }

    if (nextScheduledIncludesCurrentEvent) {
      nextScheduledFunc(event);
      var startingMomentarilyE = document.getElementById('startingMomentarily');
      if (startingMomentarilyE) startingMomentarilyE.innerHTML = startingMomentarilyMessage; 
    }

  } else {
    if (nowPlayingIntroE) nowPlayingIntroE.innerHTML = "";
    if (nowPlayingTitleE) nowPlayingTitleE.innerHTML = "";
    if (nowPlayingDescriptionE) nowPlayingDescriptionE.innerHTML = "";
    if (nowPlayingTimesE) nowPlayingTimesE.innerHTML = "";
    if (nowPlayingWhereE) nowPlayingWhereE.innerHTML = "";
    if (showDescriptionE) {
      showDescriptionE.innerHTML = "";
      showDescriptionE.onclick = function(){};}
    showingMore = false;

    if (clockDivParentE) {
      clockDivParentE.style.top = clockDivParentTop;
      clockDivParentE.style.right = clockDivParentRight;
    }
 }

  return (title_content != ""); 
}
nowPlaying = default_nowPlaying;

function toggleShowDescription() {
  if (!showingMore) {
    showingMore = true;

    if (applyFontEffect) {
      $("#showDescription").removeFE(true);
      $("#nowPlayingDescription").removeFE(true);
    }

    $("#showDescription").text(showLessText);
    document.getElementById('showDescription').onclick = toggleShowDescription;
    document.getElementById('nowPlayingDescription').innerHTML = description_content;

    if (applyFontEffect) {
      $("#nowPlayingDescription").FontEffect({ outline:true, outlineColor1:nowPlayingOutlineColor, outlineWeight:1 });
      $("#showDescription").FontEffect({ outline:true, outlineColor1:nowPlayingOutlineColor, outlineWeight:1 });
    }

    $("#nowPlayingDescription").stop(true,true);
  } else {
    showingMore = false;

    if (applyFontEffect) {
      $("#showDescription").removeFE(true);
      $("#nowPlayingDescription").removeFE(true);
    }

    $("#showDescription").text(showMoreText);
    document.getElementById('showDescription').onclick = toggleShowDescription;
    document.getElementById('nowPlayingDescription').innerHTML = "";
    if (applyFontEffect) $("#showDescription").FontEffect({ outline:true, outlineColor1:nowPlayingOutlineColor, outlineWeight:1 });
  }
}

function handleMyFeed(result) {
  var now = new Date(new Date().getTime() + time_offset + hebron_offset);
  if (result.feed.getUpdated().$t != oldTs || !sameDay(now, lastCalendarUpdateDate) || getUTCTime() > recheckCalendarTimeout) {
    oldTs = result.feed.getUpdated().$t;
    lastCalendarUpdateDate = now;
    recheckCalendarTimeout = maxTime;
    handleNewFeed(result);
  }

  // schedule next update
  setTimeout("getMyFeed()", checkCalendarWaitTime);
  
}

function getFutureIndex(entries) {
  var now = new Date(new Date().getTime() + time_offset + hebron_offset);
  futureIndex = 0;
  while((futureIndex < entries.length) && (getEventEndDate(entries[futureIndex]).getTime() < now.getTime())) futureIndex++;
}

function default_handleNewFeed(result) {
  // Obtain the array of CalendarEventEntry
  var entries = result.feed.entry;
  getFutureIndex(entries);

  var nowPlayingExists = nowPlaying(entries[futureIndex]);

  if (!(nowPlayingExists && nextScheduledIncludesCurrentEvent)) {
    var nextIndex = nowPlayingExists ? (futureIndex + 1) : futureIndex;
    if (nextIndex >= entries.length) nothingScheduled();
    else nextScheduledFunc(entries[nextIndex]);
  }

  if (doThreeDaySchedule) threeDaySchedule(entries);

  firstCalendarFeedHandled = true;
  
}
handleNewFeed = default_handleNewFeed;


function nothingScheduled() {
  var scheduledTitleE = document.getElementById('scheduledTitle');
  var scheduledWhereE = document.getElementById('scheduledWhere');
  var scheduledTimesE = document.getElementById('scheduledTimes');
  var scheduledDateE =  document.getElementById('scheduledDate');
  var startingMomentarilyE = document.getElementById('startingMomentarily');

  if (scheduledTitleE) scheduledTitleE.innerHTML = nothingScheduledMessage;
  if (scheduledWhereE) scheduledWhereE.innerHTML = "";
  if (scheduledTimesE) scheduledTimesE.innerHTML = "";
  if (scheduledDateE) scheduledDateE.innerHTML = "";
  if (startingMomentarilyE) startingMomentarilyE.innerHTML = "";
}

function dateString(d) {
  return numToDay(d.getUTCDay()) + ", " + numToMonth(d.getUTCMonth()) + " " + d.getUTCDate() + ", " + d.getUTCFullYear();
}

function nextScheduledFunc(event) {
  if (recheckCalendarTimeout == maxTime) recheckCalendarTimeout = getEventUTCTime(event);

  var title = event.getTitle().getText();
  var times =  getTimeRange(event);
  var where = event.getLocations()[0].getValueString();

  var d = new Date(hebron_offset + event.getTimes()[0].getStartTime().getDate().getTime());
  var datestring = dateString(d);

  $("#scheduledTitle").text(title);
  $("#scheduledTimes").text(times);
  $("#scheduledWhere").text(where);
  $("#scheduledDate").text(datestring);
  $("#startingMomentarily").text("");
}

function numToDay(i) {
  switch (i) {
    case 0:
      return "Sun";
    case 1:
      return "Mon";
    case 2:
      return "Tue";
    case 3:
      return "Wed";
    case 4:
      return "Thu";
    case 5:
      return "Fri";
    default:
      return "Sat";
  }
}

function numToMonth(i) {
  switch (i) {
    case 0:
      return "Jan.";
    case 1:
      return "Feb.";
    case 2:
      return "Mar.";
    case 3:
      return "Apr.";
    case 4:
      return "May";
    case 5:
      return "Jun.";
    case 6:
      return "Jul.";
    case 7:
      return "Aug.";
    case 8:
      return "Sep.";
    case 9:
      return "Oct.";
    case 10:
      return "Nov.";
    default:
      return "Dec.";
  }
}

function sleepThenHandleError(e)
{
  calendarError = e;
  setTimeout("handleError()", 10000);
}

function default_handleError() {
  var errordiv = document.getElementById('errorDiv');
  if (errordiv)
  {
    //var em = "There was an error! ";
    //em += calendarError.cause ? calendarError.cause.statusText : calendarError.message;
    errordiv.innerHTML =  "Error: Could not connect to schedule."
  }
}
handleError = default_handleError;

function sameDay(date1, date2) {
  return (date1.getUTCDate() == date2.getUTCDate()) && (date1.getUTCMonth() == date2.getUTCMonth());
}

function getEventDate(e) {
  return new Date(getEventUTCTime(e) + hebron_offset);
}

function getEventEndDate(e) {
  return new Date(getEventUTCEndTime(e) + hebron_offset);
}

function getUTCTime() {
  return new Date().getTime() + time_offset;
}

function getEventUTCTime(e) {
  return e.getTimes()[0].getStartTime().getDate().getTime();
}

function getEventUTCEndTime(e) {
  return e.getTimes()[0].getEndTime().getDate().getTime();
}

function getEventTitle(e) {
  return e.getTitle().getText();
}

function getEventDescription(e) {
  return e.getContent().getText();
}

function getEventWhere(e) {
  return e.getLocations()[0].getValueString();
}

function inProgress(now, e) {
  return (now.getTime() >= getEventDate(e).getTime()) && (now.getTime() <= getEventEndDate(e).getTime());
}

function threeDaySchedule(events) {
  var now = new Date(new Date().getTime() + time_offset + hebron_offset);
  var tomorrow = new Date(now.getTime() + (24 * 60 * 60 * 1000)); 
  var eventIndex = 0;
  var highlightIndex = 0;
  while((eventIndex < events.length) && (getEventDate(events[eventIndex]).getTime() < now.getTime()) && !sameDay(now, getEventDate(events[eventIndex]))) eventIndex++;
  var initEventIndex = eventIndex;  

  for (var i=1; i<=numDaysInSchedule; i++) {
    var dayIntroE = document.getElementById("day" + i + "Intro");
    var dayE = document.getElementById("day" + i);
    var dayWrapperE = document.getElementById("day" + i + "Wrapper");
    dayE.innerHTML = "";
    var dayHighlightImageE = document.getElementById("day" + i + "HighlightImage");
    var dayHighlightTitleE = document.getElementById("day" + i + "HighlightTitle");
    var dayHighlightHeaderE = document.getElementById("day" + i + "HighlightHeader");

    if (eventIndex >= events.length) {
      dayIntroE.innerHTML = "";
      dayWrapperE.style.display="none";
      continue;
    } else {dayWrapperE.style.display="block";}

    var currentDay = getEventDate(events[eventIndex]);

    if (sameDay(currentDay, now)) {
      dayIntroE.innerHTML = "Today, " + numToMonth(currentDay.getUTCMonth()) + " " + currentDay.getUTCDate() + ", " + currentDay.getUTCFullYear();
    } else if (sameDay(currentDay, tomorrow)) {
      dayIntroE.innerHTML = "Tomorrow, " + numToMonth(currentDay.getUTCMonth()) + " " + currentDay.getUTCDate() + ", " + currentDay.getUTCFullYear();
    } else {
      dayIntroE.innerHTML = dateString(currentDay);
    }

    while ((eventIndex < events.length) && sameDay(currentDay, getEventDate(events[eventIndex]))) {
      var e = events[eventIndex];
      if (dayE.innerHTML != "") dayE.innerHTML += eventSeparator;
      var fontPrefix = "";
      var fontSuffix = "";
      if (inProgress(now, e)) {
        fontPrefix = "<span class='highlighted'>";
        fontSuffix = "</span>";
      }
      dayE.innerHTML += fontPrefix + "<span class='scheduleTitle'>" + getEventTitle(e) + " </span><span class='scheduleData'>" + getEventWhere(e) + " " + getTimeRange(e) + "</span>" + fontSuffix;
      eventIndex++;  
    }

    // highlights:
    
    while ((highlightIndex < highlightsArray.length) && !sameDay(currentDay, highlightsArray[highlightIndex].date) && highlightsArray[highlightIndex].date < currentDay) {highlightIndex++;}
 
    if ((highlightIndex < highlightsArray.length) && sameDay(currentDay, highlightsArray[highlightIndex].date)) {
      dayHighlightImageE.src = highlightsArray[highlightIndex].image;
      dayHighlightTitleE.innerHTML = highlightsArray[highlightIndex].title;
      dayHighlightHeaderE.innerHTML = highlightsArray[highlightIndex].header;
      highlightIndex++;
    } else { // no highlights found for this day
      dayHighlightImageE.src = defaultHighlightImage;
      dayHighlightTitleE.innerHTML = "";
      dayHighlightHeaderE.innerHTML = "";
    }

  }

  if (eventIndex == initEventIndex) {
    var nothingScheduledDivE = document.getElementById("nothingScheduledDiv");
    if (nothingScheduledDivE) nothingScheduledDivE.innerHTML = nothingScheduledMessage;
  } else {
    var nothingScheduledDivE = document.getElementById("nothingScheduledDiv");
    if (nothingScheduledDivE) nothingScheduledDivE.innerHTML = "";
  }
}    
