// 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();
  
  calendarsRequested.push('http://www.google.com/calendar/feeds/editor@chryslerclub.org.au/public/full');
  /**************add more calendars here***********************/
  /* calendarsRequested.push('http://www.google.com/calendar/feeds/.....');
  calendarsRequested.push('http://www.google.com/calendar/feeds/.....');
  */
  
  calendarCompletionObject = new GlobalCalendarJobCompletionObject( calendarsRequested, 1 /*for the next 1 month*/);
  
  //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 ));
  
  //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();
	var calendartitle = feedRoot.feed.title.$t;
  /* loop through each event in the feed */
          
    /* 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(calendartitle, startDateTime,endDateTime,entries[i]));	  
    }
	
	//notify the completion object that one more job has completed	
	calendarCompletionObject.jobCompletedCallBack();
}


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 firstly by date and secondly by name
	
	
	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 = ul = document.createElement('ul'); 
       
    /* loop through each event in the feed */
    var len = eventCollection.getCount();
	
	//////////////////////////////////////
	var eventListDiv = null;
    var calendartitle = null;
  	//////////////////////////////////////
    	
    for (var i = 0; i < len; i++) 
    {
		var startDateTime = eventCollection.getEvent(i).startDateTime;
		var endDateTime   = eventCollection.getEvent(i).EndDateTime;
		var currcalendartitle = eventCollection.getEvent(i).calendarname;
		  //
		startJSDate = startDateTime.getDate();
		
		var date = startDateTime.getDate();
		var year = startJSDate.getFullYear();
		
		if(calendartitle == null || calendartitle!= currcalendartitle)
		{
			  calendartitle = currcalendartitle;
			  
			  eventListDiv = document.createElement('div');
			  
			  ul = document.createElement('ul');			  
			  
			  //create the title			  
			 
			  			 	
			  eventListDiv.appendChild(ul);
			  eventsDiv.appendChild(eventListDiv);			  	  			  
		}		  
		addEventFor(startDateTime,endDateTime, eventCollection.getEvent(i).EventData, ul);		
	}
   /* append the list items onto the div */
   //eventsDiv.appendChild(ul); 
   
   //now call the enabled tooltips from the bubble.js file as it should be already loaded
   enableInfo();
}

function addEventFor(startDateTime, endDateTime ,entry, ul)
{
	var entryLinkHref = null;
    
    var date = startDateTime.getDate();
	var year = startJSDate.getFullYear();		
	
    if (entry.getHtmlLink() != null) 
	{
      entryLinkHref = entry.getHtmlLink().getHref();	  
    }
		
	//format here is dd[st, nd, rd, th] month, yyyy
	var dateString = date.getDate() + getDateEndString(date.getDate()) + " " + getMonthString(date.getMonth()) + ", " + year;
	
	var title = entry.getTitle().getText();
		  
	//create the title			  
	var eventTitle = dateString + " - " + title;
	
    var li = document.createElement('li');

    /* if we have a link to the event, create an 'a' element */
    if (entryLinkHref != null) 
	{
      li.appendChild(document.createTextNode(dateString + " - "));
	  
	  var entryLink1 = document.createElement('a');
	  entryLink1.setAttribute('href', entryLinkHref);
	  entryLink1.setAttribute('target', "_blank");
	  entryLink1.setAttribute('id', "title");
	  
	  entryLink1.setAttribute('info', entry.getContent().getText());
	  entryLink1.setAttribute('eventTitle', title);
		  
	  entryLink1.appendChild(document.createTextNode(title));
	  
	  li.appendChild(entryLink1);
	  
	  //create the hyphen separator between the event link and the map link
	  //otherwise the hyphen will respond to mouse over events too.	  
  	  li.appendChild(document.createTextNode(" - "));
	  
	  //lets do the map as a link element otherwise the info pane will try ad pick up event info from the map link
	  var mapLink = document.createElement('a');
	  var mapString = "http://maps.google.com.au/maps?q="; //we use Australian google as it will be faster than uk link
	  var mapLang = "&hl=en-GB"; 
	  var mapLocation = entry.getLocations()[0].getValueString();
	  
	  var mapURL = mapString + escape(mapLocation) + mapLang;
	  	  
	  mapLink.setAttribute('href', mapURL);
	  mapLink.setAttribute('target', "_blank");
	  
	  var maptext = document.createTextNode("Map");
	  
	  mapLink.appendChild(maptext);
	  
	  li.appendChild(mapLink);
	  
     /* append the list item onto the unordered list */
      ul.appendChild(li);
	}
}

/**
 * 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 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 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 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);   
}
