
function Calendar_Request(method) {
	google.load("gdata", "2.x");
	google.setOnLoadCallback(method);
}

function Kalender_Parse() {
  // init the Google data JS client library with an error handler
  google.gdata.client.init(handleGDError);
  //loadCalendarParser('tbq74hiiutmfr2f3oovjovm07s@group.calendar.google.com'); //Bungalow
  loadCalendarParser('f3bdaop279mlnjdqsf7844l26c@group.calendar.google.com'); //Activiteiten
  loadCalendarParser('f403lujiv94s293mk998r92p14@group.calendar.google.com'); //Leiding Kalender
  loadCalendarParser('mcub4glbvlc470rjbqbh03j5ac@group.calendar.google.com'); //Schoonmaakrooster
}

function loadCalendarParser(calendarAddress) {
  var calendarUrl = 'http://www.google.com/calendar/feeds/' +
                    calendarAddress + 
                    '/public/full';
					
  var now = new Date();
  var minDate = getDateFormat(now);
  var endDate = new Date(now.getFullYear(), now.getMonth()+2, now.getDate());
  var maxDate = getDateFormat(endDate);					
					
  loadCalendar(calendarUrl, minDate, maxDate);
}

/**
 * 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, starttime, endtime) {
  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);

  if(starttime && endtime) {
	query.setMinimumStartTime(starttime);
	query.setMaximumStartTime(endtime);
  } else {
	query.setFutureEvents(true);
	query.setMaxResults(10);
  }
  var x = service.getEventsFeed(query, listEvents, 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 listEvents(feedRoot) {
  var entries = feedRoot.feed.getEntries();
  
  //Get calender id & title
  var calid_begin = feedRoot.feed.id.$t.indexOf('feeds/')+6;
  var calid_end = feedRoot.feed.id.$t.indexOf('%');
  var calId = feedRoot.feed.id.$t.slice(calid_begin, calid_end);
  var calTitle = feedRoot.feed.title.$t;
  
  /* loop through each event in the feed */
  var len = entries.length;
  for (var i = 0; i < len; i++) {
    var entry = entries[i];

	//Get event id & title
	var id_begin = entry.id.$t.indexOf('events/')+7;
	var eventId = entry.id.$t.slice(id_begin);
	var eventTitle = entry.getTitle().getText();

	//Get dates & times
	var startDateTime = null;
    var startJSDate = null;
    var times = entry.getTimes();
    if (times.length > 0) {
      startDateTime = times[0].getStartTime();
      startJSDate = startDateTime.getDate();
    }
	var eventStartTime = entry.gd$when[0].startTime.substr(0, 16);
	var eventEndTime = entry.gd$when[0].endTime.substr(0, 16);
	var eventContent = entry.getContent().getText();
	var eventLocations = entry.getLocations();
	var eventLocation = "";
	if(eventLocations.length > 0) {
		eventLocation = eventLocations[0].getValueString();
	}
		
	// Update database table
	httpObjectKalSave = getHTTPObject();
	if (httpObjectKalSave != null) {
		httpObjectKalSave.open("GET", "ajax.php?type=kalender&method=SAVE&eventId="+eventId+"&eventTitle="+eventTitle+"&calTitle="+calTitle+"&calId="+calId+"&eventStartTime="+eventStartTime+"&eventEndTime="+eventEndTime+"&eventContent="+nl2br(eventContent)+"&eventLocation="+eventLocation, true);
		httpObjectKalSave.send(null);
		httpObjectKalSave.onreadystatechange = function() {
			if(httpObjectKalSave.readyState == 4){
				var resp = httpObjectKalSave.responseText;
				var feedbackDiv = document.getElementById('feedback');
				feedbackDiv.innerHTML += '<br/>:'+resp;
			}
		}
	}
  }

  //Remove all other entries from database
  httpObjectKalClean = getHTTPObject();
  if (httpObjectKalClean != null) {
	httpObjectKalClean.open("GET", "ajax.php?type=kalender&method=CLEAN&calId="+calId, true);
	httpObjectKalClean.send(null);
  }
}


/**
 * 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('jsSourceFinal').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());
  }
}

