////////////////////////////////////////////////
//
// Purpose : sets three HTML elements dynamically with information for the next event on a shared google calendar               
//
// Instructions :
//	 1. create 3 HTML elements with the following attributes
//			1.1 anchor tag (href dynamically set to Google event's WHERE attribute) : <a id="eventRegLink" target="_blank" href="eventRegLink">
//  		1.2 span/div tag for event name (value dynamically set to Google event's TITLE): <span id="eventName">eventName</span>
//  		1.3 span/div tag for event date/time (value dynamically set to timezone adjusted value of Google's event): <span id="eventDateTime">eventDateTime</span>
//	 2. insert the following line at the bottom of your HTML (just above the </body> tag and without the //)
//   <script type="text/javascript" src="http://www.google.com/calendar/feeds/loopfuse.com_vu63qdq67edsk863bhimlcjol0%40group.calendar.google.com/public/full?alt=json-in-script&callback=displaySingleEvent&orderby=starttime&max-results=1&singleevents=true&sortorder=ascending&futureevents=true"></script>
//
////////////////////////////////////////////////

function getDayOfWeek(myDate)
{
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";

return (weekday[myDate.getDay()]);
}


/**
 * Converts an xs:date or xs:dateTime formatted string into the local timezone
 * and outputs a human-readable form of this date or date/time.
 *
 * @param {string} gCalTime is the xs:date or xs:dateTime formatted string
 * @return {string} is the human-readable date or date/time string
 */
function formatGCalTime(gCalTime) { 
	//if (console!=null) console.log("formatGCalTime",gCalTime);
  // text for regex matches
  var remtxt = gCalTime;

  function consume(retxt) {
	//if (console!=null) console.log("consume",retxt);

    var match = remtxt.match(new RegExp('^' + retxt));
    if (match) {
      remtxt = remtxt.substring(match[0].length);
      return match[0];
    }
    return '';
  }

  // minutes of correction between gCalTime and GMT
  var totalCorrMins = 0;

  var year = consume('\\d{4}');
  consume('-?');
  var month = consume('\\d{2}');
  consume('-?');
  var dateMonth = consume('\\d{2}');
  var timeOrNot = consume('T');

  // if a DATE-TIME was matched in the regex 
  if (timeOrNot == 'T') {
    var hours = consume('\\d{2}');
    consume(':?');
    var mins = consume('\\d{2}');
    consume('(:\\d{2})?(\\.\\d{3})?');
    var zuluOrNot = consume('Z');

    // if time from server is not already in GMT, calculate offset
    if (zuluOrNot != 'Z') {
      var corrPlusMinus = consume('[\\+\\-]');
      if (corrPlusMinus != '') {
        var corrHours = consume('\\d{2}');
        consume(':?');
        var corrMins = consume('\\d{2}');
        totalCorrMins = (corrPlusMinus=='-' ? 1 : -1) * 
            (Number(corrHours) * 60 + 
	    (corrMins=='' ? 0 : Number(corrMins)));
      }
    } 

    // get time since epoch and apply correction, if necessary
    // relies upon Date object to convert the GMT time to the local
    // timezone
    var originalDateEpoch = Date.UTC(year, month - 1, dateMonth, hours, mins);
    var gmtDateEpoch = originalDateEpoch + totalCorrMins * 1000 * 60;
    var ld = new Date(gmtDateEpoch);

		// determine day of week
		var dayOfWeek = getDayOfWeek(ld);

    // date is originally in YYYY-MM-DD format
    // time is originally in a 24-hour format
    // this converts it to MM/DD hh:mm (AM|PM) 
    dateString = (ld.getMonth() + 1) + '/' + ld.getDate() + ' @ ' + 
        ((ld.getHours()>12)?(ld.getHours()-12):(ld.getHours()===0?12:
	ld.getHours())) + ':' + ((ld.getMinutes()<10)?('0' + 
	ld.getMinutes()):(ld.getMinutes())) + ' ' + 
	((ld.getHours()>=12)?'PM':'AM');
  } else {
    // if only a DATE was matched
    dateString =  parseInt(month, 10) + '/' + parseInt(dateMonth, 10);
  }
  return dayOfWeek +" "+ dateString;
}


/**
 * Sets pre-defined DOM IDs values with those from the next event in the google calendar feed
 * @param {json} root is the root JSON-formatted content from GData
  */ 
function displaySingleEvent(root) {
	//if (console!=null) console.log("displaySingleEvent",root);

  var entry = root.feed.entry[0];
  var when = entry['gd$when'][0].startTime;
  var readableWhen = formatGCalTime(entry['gd$when'][0].startTime);
  //if (console!=null) console.log("readableWhen",readableWhen); 
   
  document.getElementById("eventName").innerHTML=entry.title.$t;
  document.getElementById("eventDateTime").innerHTML=readableWhen;
  document.getElementById("eventRegLink").href=entry['gd$where'][0].valueString; 
}

