/*
 * Adapted from the original here:
 * http://kiyo.wordpress.com/2007/04/29/google-spreadsheet-json-to-timeline/
 *
 * Enhancements:
 * - public functions/objects are scoped by naming them tl_*
 * - date parsing does MM/DD/YYYY instead of YYYY-MM-DD
 * - get more values from the spreadsheet (fewer defaults)
 * - added rudimentary theme support for events
 *
 * License:
 * http://creativecommons.org/licenses/by-nc-sa/3.0/
 */

var tl_eventSource;

function tl_loadWorksheetJSON(json) {
  var themes = {
                 "default"   : { "color" : "black",   "textColor" : "black" },
                 "life"      : { "color" : "red",     "textColor" : "red" },
                 "education" : { "color" : "blue",    "textColor" : "blue" },
                 "work"      : { "color" : "purple",  "textColor" : "purple" },
                 "outdoors"  : { "color" : "green",   "textColor" : "green" },
                 "athletics" : { "color" : "orange",  "textColor" : "orange" },
                 "friends"   : { "color" : "orange",  "textColor" : "orange" },
                 "events"    : { "color" : "orange",  "textColor" : "orange" },
               };

  var entries = json.feed.entry;
  var timelinerEntries = [];
  for (var i = 0; i < entries.length; ++i) {
    var entry = entries[i];
    var start = tl_convertFromGDataDate(entry["gsx$start"].$t);
    var end = tl_convertFromGDataDate(entry["gsx$end"].$t);
    //var duration = (entry["gsx$duration"].$t.toLowerCase() == "true" ? true : false); 
    var duration = true; // fuzzy events look prettier
    var title = entry["gsx$title"].$t;
    var description = entry["gsx$description"].$t;
    var image = entry["gsx$image"].$t;
    if (image != "") {
      description = '<p style="float: right;"><img src="' + image + '"></p>' + description;
    }
    var link = entry["gsx$link"].$t;
    var icon = entry["gsx$icon"].$t;
    var category = entry["gsx$category"].$t.toLowerCase();
    if (category == "" || themes[category] == undefined) {
      category = "default";
    }
    timelinerEntries.push(new Timeline.DefaultEventSource.Event(
      start,
      end,
      null, // latestStart
      null, // latestEnd
      duration, 
      title,
      description,
      null, // image - stored in description currently
      link,
      icon,
      themes[category]["color"],
      themes[category]["textColor"]
    ));
  }
  eventSource.addMany(timelinerEntries);
};

function tl_convertFromGDataDate(/*string<MM/DD/YYYY>*/ date) {
  var match = date.match(/(\d+)\/(\d+)\/(\d{4})/);
  if(null != match) {
    return new Date(parseInt(match[3], 10),      // year
                    parseInt(match[1], 10) - 1,  // month
                    parseInt(match[2], 10) + 1); // day
  } else {
    return null;
  }
}

var tl_object;
function tl_init() {
  // event source
  eventSource = new Timeline.DefaultEventSource();

  var bandInfos = [
    // create month band - use hot zones to zoom on busy dates
    Timeline.createBandInfo({
        eventSource:    eventSource,
        //date:           "Mar 26 1978 00:00:00 GMT", // init timeline to interesting date
        date:           new Date(), // init timeline to now
        width:          "70%", 
        intervalUnit:   Timeline.DateTime.MONTH, 
        intervalPixels: 100,
        timeZone:       -8,
    }),
    // create year band - use hot zones to zoom on busy dates
    Timeline.createBandInfo({
        eventSource:    eventSource,
        //date:           "Mar 26 1978 00:00:00 GMT", // init timeline to interesting date
        date:           new Date(), // init timeline to now
        width:          "30%", 
        intervalUnit:   Timeline.DateTime.YEAR, 
        intervalPixels: 100,
        timeZone:       -8,

        // make events less detailed for year band
        showEventText:  false,
        trackHeight:    0.5,
        trackGap:       0.2,
    })
  ];

  // scroll bands together, syncing band 1 with band 0
  bandInfos[1].syncWith = 0;

  // highlight band 1 to reflect time in band 0 (which is synced)
  bandInfos[1].highlight = true;

  // make event layouts between band 0 and 1 match
  bandInfos[1].eventPainter.setLayout(bandInfos[0].eventPainter.getLayout());

  // create & draw the timeline
  tl_object = Timeline.create(document.getElementById("timeline"), bandInfos);

  // JSON feed for google spreadsheet, will load events internally
  var feedUrl = "http://spreadsheets.google.com/feeds/list/pu1JqzPKsipKl2H7e9EmmRA/od6/public/values";
  feedUrl += "?alt=json-in-script&callback=tl_loadWorksheetJSON";

  var scriptTag = document.createElement('script');
  scriptTag.src = feedUrl;
  document.body.appendChild(scriptTag);
}

var tl_resizeTimerID = null;
function tl_resize() {
    if (tl_resizeTimerID == null) {
        tl_resizeTimerID = window.setTimeout(function() {
            tl_resizeTimerID = null;
            tl_object.layout();
        }, 500);
    }
}

