// JavaScript Document
var eventCollection;
var calendarCompletionObject;

function init() 
{
  // init the Google data JS client library with an error handler
  google.gdata.client.init(handleGDError);  
  
  //holds the ALL the events when they come back from google (from all calendars requested)
  eventCollection = new EventCollection();
  
  var calendarsRequested = new Array();
  
  //shin bu kan brighton events Calendar
  calendarsRequested.push('http://www.google.com/calendar/feeds/cerljm1kacosi7vfcbc4q3etnc@group.calendar.google.com/public/full');
  
 //shin bu kan BKA iaido Events Calendar
  calendarsRequested.push('http://www.google.com/calendar/feeds/jhaf8v57nt01l5ebd9khv12va0@group.calendar.google.com/public/full');

      
  /**************add more calendars here***********************/
  //  calendarsRequested.push('http://www.google.com/calendar/feeds/< Enter Feed Name here.....>/public/full'); 
  
  calendarCompletionObject = new GlobalCalendarJobCompletionObject( calendarsRequested, 3 /*for the next 3 months*/);
  
  //now start it all off 
  calendarCompletionObject.start();
}

/**
 * Uses Google data JS client library to retrieve a calendar feed from the specified
 * URL.  The feed is controlled by several query parameters and a callback 
 * function is called to process the feed results.
 *
 * @param {string} calendarUrl is the URL for a public calendar feed
 */  
function loadCalendar(calendarUrl, numofmonths)
{
  var service = new google.gdata.calendar.CalendarService('gdata-js-client-samples-simple');
  var query = new google.gdata.calendar.CalendarEventQuery(calendarUrl);
  query.setOrderBy('starttime');
  query.setSortOrder('ascending');
 
  query.setSingleEvents(true);
 
  var startdate = new Date(); //from today
  
  var start = new google.gdata.DateTime(startdate);
 
  query.setMinimumStartTime(start);  
  
  query.setMaximumStartTime(getEndDate(numofmonths -1));
  
  //asynchronous callback from this service which will call addEvents fucntion  
  service.getEventsFeed(query, addEvents, handleGDError);
}

/**
 * Callback function for the Google data JS client library to call with a feed 
 * of events retrieved.
 *
 * Creates an unordered list of events in a human-readable form.  This list of
 * events is added into a div called 'events'.  The title for the calendar is
 * placed in a div called 'calendarTitle'
 *
 * @param {json} feedRoot is the root of the feed, containing all entries 
 */ 
function addEvents(feedRoot)
{ 
	var entries  = feedRoot.feed.getEntries();
          
    /* loop through each event in the feed */
  	var len = entries.length;
    	
	for (var i = 0; i < len; i++) 
  	{
	  var times = entries[i].getTimes();  
	  
	  if (times.length > 0) 
	  {
		  var startDateTime = times[0].getStartTime();
		  var endDateTime   = times[0].getEndTime();
		  
	  }	  
	  
	  //add the evnt to the collection for sorting later	  
	  eventCollection.add(new EventObject(startDateTime,endDateTime,entries[i]));	  
    }
	
	//notify the completion object that one more job has completed	
	calendarCompletionObject.jobCompletedCallBack();
}

/**
 * Callback function for the Google data JS client library to call with a feed 
 * of events retrieved.
 *
 * Creates an unordered list of events in a human-readable form.  This list of
 * events is added into a div called 'events'.  The title for the calendar is
 * placed in a div called 'calendarTitle'
 *
 * @param {json} feedRoot is the root of the feed, containing all entries 
 */ 
function listEvents() 
{	
	//if we got here we got all the event data from our calendars
	//first sort our events in chronological ascending order.
	
	eventCollection.sortEvents();
	
	//everything is sorted now
	
	var eventsDiv = document.getElementById('AllEvents');
    var wait = document.getElementById('wait');
  
  	//clear down the wait message node from the DOM
    if(wait != null )
    {
	  if(wait.childNodes.length > 0)
	  {
		var len = wait.childNodes.length;
		var i;
		for(i=0; i < len ; i++)
			wait.removeChild(wait.childNodes[0]);
	  }
    }
	
	//clear out previous entries
    if (eventsDiv != null && eventsDiv.childNodes.length > 0) 
    {
	  eventsDiv.removeChild(eventsDiv.childNodes[0]);
    }
      
    /* create a new unordered list */
    var ul = null;  
    var eventListDiv = null;
   
    /* loop through each event in the feed */
    var len = eventCollection.getCount();
    var month = null;
	
    for (var i = 0; i < len; i++) 
    {
		var startDateTime = eventCollection.getEvent(i).startDateTime;
		var endDateTime   = eventCollection.getEvent(i).EndDateTime;
		  
		//
		startJSDate = startDateTime.getDate();
		
		var currMonth = startJSDate.getMonth();
		var year  = startJSDate.getFullYear();
		  
		if(month == null || month != currMonth)
		{
		   month = currMonth;
			  
		   eventListDiv = document.createElement('div');
			  
		   ul = document.createElement('ul');			  
			  
		   //create the title			  
		   var eventTitle = "Events for " + getMonthString(currMonth) + " " + year ;
		   eventListDiv.innerHTML = "<h1>"+ eventTitle + "</h1>";
			  			 	
		   eventListDiv.appendChild(ul);
		   eventsDiv.appendChild(eventListDiv);			  	  			  
		 }
		 
	  	 addEventFor(startDateTime,endDateTime, eventCollection.getEvent(i).EventData, ul);
	}
   /* append the list item onto the unordered list */ 
   
   //now call the enabled tooltips from the bubble.js file as it should be already loaded
   enableInfo("cal_entry");
}

function areDatesEqual(date1, date2)
{
	if(date1.getDate() == date2.getDate() && 
	   date1.getMonth() == date2.getMonth() &&
	   date1.getFullYear() == date2.getFullYear())
	{
		return true;
	}
	return false;
}

function listDailyEvents() 
{	
	//if we got here we got all the event data from our calendars
	//first sort our events in chronological ascending order.
	
	eventCollection.sortEvents();
	
	//everything is sorted now
	
	var eventsDiv = document.getElementById('AllEvents');
    var wait = document.getElementById('wait');
  
  	//clear down the wait message node from the DOM
    if(wait != null )
    {
	  if(wait.childNodes.length > 0)
	  {
		var len = wait.childNodes.length;
		var i;
		for(i=0; i < len ; i++)
			wait.removeChild(wait.childNodes[0]);
	  }
    }
	
	//clear out previous entries
    if (eventsDiv != null && eventsDiv.childNodes.length > 0) 
    {
	  eventsDiv.removeChild(eventsDiv.childNodes[0]);
    }
      
    /* create a new unordered list */
    var ul = null;  
    var eventListDiv = null;
   
    /* loop through each event in the feed */
    var len = eventCollection.getCount();
    var date = null;
	
    for (var i = 0; i < len; i++) 
    {
		var startDateTime = eventCollection.getEvent(i).startDateTime;
		var endDateTime   = eventCollection.getEvent(i).EndDateTime;
		  //
		startJSDate = startDateTime.getDate();
		
		var currdate = startDateTime.getDate();
		var year  = startJSDate.getFullYear();
		  
		if(date == null || areDatesEqual(date, currdate) == false)
		{
		   date = currdate;
			  
		   eventListDiv = document.createElement('div');
			  
		   ul = document.createElement('ul');
		   
		   var dateString = padNumber(date.getDate()) + "." + (date.getMonth() + 1) + "." + date.getFullYear();
			  
		   //create the title			  
		   var eventTitle = getDayString(date.getDay()) + ", " + dateString;
		   eventListDiv.innerHTML = "<h1>"+ eventTitle + "</h1>";
			  			 	
		   eventListDiv.appendChild(ul);
		   eventsDiv.appendChild(eventListDiv);			  	  			  
		 }
		 
	  	 addEventFor(startDateTime,endDateTime, eventCollection.getEvent(i).EventData, ul);
	}
   /* append the list item onto the unordered list */ 
   
   //now call the enabled tooltips from the bubble.js file as it should be already loaded
   enableInfo();
}

function addEventFor(startDateTime, endDateTime ,entry, ul)
{
	var title = entry.getTitle().getText();
	var startJSDate = null;
	var endJSDate = null;
    var entryLinkHref = null;
    
    startJSDate = startDateTime.getDate();
	endJSDate = endDateTime.getDate();
	
    if (entry.getHtmlLink() != null) 
	{
      entryLinkHref = entry.getHtmlLink().getHref();
    }
   // var dateString = padNumber(startJSDate.getDate()) + "/" + (startJSDate.getMonth() + 1) + "/" + startJSDate.getFullYear();
	
	var dateString = startJSDate.getDate() + getDateEndString(startJSDate.getDate());
	dateString += " ";
    
	if (!startDateTime.isDateOnly()) 
	{
		dateString += "(";
      	dateString += " " + startJSDate.getHours() + ":" + padNumber(startJSDate.getMinutes()) ;
	  	dateString += " - " + endJSDate.getHours() + ":" + padNumber(endJSDate.getMinutes()) ;
		dateString += ")"
    }
	
    var li = document.createElement('li');

    /* if we have a link to the event, create an 'a' element */
    if (entryLinkHref != null) 
	{
      entryLink = document.createElement('a');
	  entryLink.setAttribute('href', entryLinkHref);
	  entryLink.setAttribute('target', "_blank");
	  entryLink.setAttribute('id', "cal_entry");
	  
	  entryLink.setAttribute('info', FilterForCRLF(entry.getContent().getText()));
	  entryLink.setAttribute('eventTitle', title);
		  
	  entryLink.appendChild(document.createTextNode(title + ' - ' + dateString));	 
	  
	  li.appendChild(entryLink);	  
    }
	else
	{
      li.appendChild(document.createTextNode(title + ' - ' + dateString));
    }	    

    /* append the list item onto the unordered list */
    ul.appendChild(li);  	
}

function FilterForCRLF(text)
{
	var Text = new String(text);
	//replace all instances of \r\n in the string with html <br/> , we use a regex /g
	Text = Text.replace(/\r/g, "<br/>");
	return Text.replace(/\n/g, "");	
}

/**
 * Callback function for the Google data JS client library to call when an error
 * occurs during the retrieval of the feed.  Details available depend partly
 * on the web browser, but this shows a few basic examples. In the case of
 * a privileged environment using ClientLogin authentication, there may also
 * be an e.type attribute in some cases.
 *
 * @param {Error} e is an instance of an Error 
 */
function handleGDError(e) 
{
 /* document.getElementById('AllEvents').setAttribute('style','display:none');
  if (e instanceof Error) 
  {
	  */
    /* alert with the error line number, file and message */
 /*   alert('Error at line ' + e.lineNumber +
          ' in ' + e.fileName + '\n' +
          'Message: ' + e.message);
 */
    /* if available, output HTTP error code and status text */
 /*   if (e.cause) 
	{
      var status = e.cause.status;
      var statusText = e.cause.statusText;
      alert('Root cause: HTTP error ' + status + ' with status text of: ' + 
            statusText);
    }
  } 
  else
  {
    alert(e.toString());
  }
  */
}

/***************************************************************************************
 Code below is ancillary and used for format and presentation of the data
 **********************************************************************************/
function getDateEndString(date)
{
	var ending = new Array(" ", "st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "st");
	
	return ending[date];
}

function getMonthString(monthIndex)
{
	var month=new Array(12)
	month[0]="January"
	month[1]="February"
	month[2]="March"
	month[3]="April"
	month[4]="May"
	month[5]="June"
	month[6]="July"
	month[7]="August"
	month[8]="September"
	month[9]="October"
	month[10]="November"
	month[11]="December"
	
	return month[monthIndex];
}

function getDayString(dayIndex)
{
	var day=new Array(7)
	day[0]="Sun"
	day[1]="Mon"
	day[2]="Tue"
	day[3]="Wed"
	day[4]="Thu"
	day[5]="Fri"
	day[6]="Sat"
			
	return day[dayIndex];
}

/*works out the number of days in a month*/
function getLastDay( date )
{
  var month = date.getMonth() + 1;
  
  if(month == 9 || month == 4 || month == 6 || month == 11)
  {
	  return 30;
  }
  else if( month == 2)
  {
	  var Y = date.getFullYear();
	  
	  //is it a leap year
	  if( ((Y)>0) && !((Y)%4) && ( ((Y)%100) || !((Y)%400) ) )
	  	return 29;
		
	  //no just a normal year
	  return 28;
  }
 
  return 31;   
}
/**
 * Adds a leading zero to a single-digit number.  Used for displaying dates.
 * 
 * @param {int} num is the number to add a leading zero, if less than 10
 */
function padNumber(num) {
  if (num <= 9) {
    return "0" + num;
  }
  return num;
}

function getEndDate(monthsToShow) 
{	
  var enddate = new Date();
  var year    = enddate.getFullYear();
  var month   = enddate.getMonth();
  
  if(month + monthsToShow > 11)
  {
	  var months = monthsToShow % 12;
	  var years  = monthsToShow / 12;
	  
	  if(years > 0)
	  {
		  enddate.setFullYear(year + years);
	  }
	  
	  if(months > 0)
	  {
		  if(month + monthsToShow > 11)
		  {
			  enddate.setFullYear(year + 1);
			  enddate.setMonth((month + months) -12 );		  
		  }
		  else
		  {
			  enddate.setMonth(month + months );
		  }
	  }
  }
  else
  {
	  enddate.setMonth(month + (monthsToShow <= 0 ? 0 : monthsToShow));
  }  
  
  enddate.setDate(getLastDay( enddate ));
  enddate.setHours(23,59,59,999);
  //alert(enddate);
  return new google.gdata.DateTime(enddate);   
}
