google.load("gdata", "1");

siteWide = {};
siteWide.calCount = '8';

function init() {

}

function loadcal(){
	
}
/**
 * Adds a leading zero to a single-digit number.  Used for displaying dates.
 */
function padNumber(num) {
  if (num <= 9) {
    return "0" + num;
  }
  return num;
}

/**
 * Determines the full calendarUrl based upon the calendarAddress
 * argument and calls loadCalendar with the calendarUrl value.
 *
 * @param {string} calendarAddress is the email-style address for the calendar
 */ 
function loadCalendarByAddress(calendarAddress) {
  	var calendarUrl = 'http://www.google.com/calendar/feeds/' + calendarAddress + '/public/full';
	loadCalendar(calendarUrl);
	
}

/**
 * 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) {
  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.setFutureEvents(true);
  query.setSingleEvents(true);
  query.setMaxResults(5);
  service.getEventsFeed(query, listEvents, handleGDError);
}

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

/**
 * Callback function for the Google data JS client library to call with a feed 
 * of events retrieved.
 *
 *
 * @param {json} feedRoot is the root of the feed, containing all entries 
 */ 




function listEvents(feedRoot) {
	var myhtml = '';	

	var entries = feedRoot.feed.getEntries();

  	/* loop through each event in the feed */
  	var len = entries.length;
  	for(var i=0;i<len;i++){

		var entry = entries[i];
	    var title = entry.getTitle().getText();
		var locations = entry.getLocations();
		var loc = locations[0].getValueString();
		var description = entry.getContent().getText();
		

		
	 
		
	    var startDateTime = null;
	    var startJSDate = null;
	    var times = entry.getTimes();
	    if (times.length > 0) {
	      	startDateTime = times[0].getStartTime();
	      	startJSDate = startDateTime.getDate();
			endDateTime = times[0].getEndTime(); 
			endJSDate = endDateTime.getDate(); 
	    }


	    var entryLinkHref = null;
	    if (entry.getHtmlLink() != null) {
	      entryLinkHref = entry.getHtmlLink().getHref();
	    }
		/* if we have a link to the event, create an 'a' element */
	    if (entryLinkHref != null) {      
			 var mylink = entryLinkHref + '^' + title + '^' + loc + '^' + description;
	    }
	
		var dateString  = '';
		var startMonth  = (startJSDate.getMonth() + 1);
		var startDay	= startJSDate.getDate();
		
		startMonth = startMonth.toString();
		startDay   = startDay.toString();

		if(startMonth.length == 1){
			startMonth = '0' + startMonth;
		}

		if(startDay.length == 1){
			startDay = '0' + startDay;
		}
		
	    var dateString = startMonth + "/" + startDay;
	
	
		if (!startDateTime.isDateOnly()) {
			if(startJSDate.getHours()<12){
				start_am_pm = ' a.m.';
				start_hours = startJSDate.getHours();
			} else {
				start_am_pm = ' p.m.';
				if(startJSDate.getHours() == '12'){
					start_hours = startJSDate.getHours();
				} else {
					start_hours = startJSDate.getHours()-12;
				}
										
			}
			

	      	dateString += " " + start_hours + ":" + padNumber(startJSDate.getMinutes()) + start_am_pm;
	      	
	    }
		stringHyphen = ' - ';
	
		var dateString2 = (startJSDate.getMonth() + 1) + "/" + startJSDate.getDate();
		
		if(dateString2 != (endJSDate.getMonth() + 1) + "/" + endJSDate.getDate()){
			if((endJSDate.getDate()-1) != startJSDate.getDate()){
				myMonth = endJSDate.getMonth();
				if(myMonth == 0){
					myMonth = '12';
				}
				if(myMonth == '1'){
					prevmonthDays = '31';
				} else if(myMonth == '2'){
					prevmonthDays = '28';
				} else if(myMonth == '3'){
					prevmonthDays = '31';			
				} else if(myMonth == '4'){
					prevmonthDays = '30';			
				} else if(myMonth == '5'){
					prevmonthDays = '31';			
				} else if(myMonth == '6'){
					prevmonthDays = '30';			
				} else if(myMonth == '7'){
					prevmonthDays = '31';			
				} else if(myMonth == '8'){
					prevmonthDays = '31';			
				} else if(myMonth == '9'){
					prevmonthDays = '30';			
				} else if(myMonth == '10'){
					prevmonthDays = '31';			
				} else if(myMonth == '11'){
					prevmonthDays = '30';			
				} else if(myMonth == '12'){
					prevmonthDays = '31';		
				}

				if((endJSDate.getDate()-1) == '0'){
					lastday = prevmonthDays;
					lastMonth = endJSDate.getMonth();
					if(lastMonth == 0){
						lastMonth = '12';
					}
				} else {
					lastday = (endJSDate.getDate()-1);
					lastMonth = (endJSDate.getMonth() + 1);
				}
				dateString += ' - ' + lastMonth + "/" + lastday;	
			} else if((endJSDate.getDate()-1) == startJSDate.getDate() && endJSDate.getHours() != 0){
				lastday = endJSDate.getDate();
				lastMonth = (endJSDate.getMonth() + 1);
			
				dateString += ' - ' + lastMonth + "/" + lastday;
			}
			
			stringHyphen = ' ';

		}
		
		if (!endDateTime.isDateOnly()) {
	
			if(endJSDate.getHours()<12){
				end_am_pm = ' a.m.';
				end_hours = endJSDate.getHours();
			} else {
				end_am_pm = ' p.m.';
				if(endJSDate.getHours() == '12'){
					end_hours = endJSDate.getHours();
				} else {
					end_hours = endJSDate.getHours()-12;
				}			
			}
			

			dateString += stringHyphen + end_hours + ":" + padNumber(endJSDate.getMinutes()) + end_am_pm;	
			
	    }	    
  
		myhtml = myhtml + "**" + dateString + "^" + mylink;

	}


	if(document.getElementById('html_builder').innerHTML == ''){
		document.getElementById('html_builder').innerHTML = myhtml
	} else {
		document.getElementById('html_builder').innerHTML = document.getElementById('html_builder').innerHTML + myhtml;		
	}
	
	
	//alert(document.getElementById('calcounter').value);
		switch(siteWide.calCount){
			// Youth Calendar
			case '8':
				siteWide.calCount = '7';
				loadCalendar('http://www.google.com/calendar/feeds/7tq0d3jblsi6ibou1ub97ro8b0@group.calendar.google.com/public/full');
			break;
			// Trinity of Coopestown
			//case '9':
			//	loadCalendar('http://www.google.com/calendar/feeds/bo84ml9u4vqmth0cmnkdo61kp4@group.calendar.google.com/public/full');
			//	document.getElementById('calcounter').value = '8';		
			//break;
			// Trinity of Binford
			case '7':
				siteWide.calCount = '6';
				loadCalendar('http://www.google.com/calendar/feeds/6de4abuinjk9hdjcfcqua5fp7g@group.calendar.google.com/public/full');
			break;
			// Our Savior's of McHenry
			case '6':
				siteWide.calCount = '5';	
				loadCalendar('http://www.google.com/calendar/feeds/uekm97jsdnmoqp6lgf1sgbtvtg@group.calendar.google.com/public/full');
			break;
			// Our Savior's of Kloten
			case '5':
				siteWide.calCount = '4';		
				loadCalendar('http://www.google.com/calendar/feeds/f0mh99t035s9emfvej1vmr7kk0@group.calendar.google.com/public/full');
			break;
			// Mabel Lutheran of Sutton
			//case '5':
				//loadCalendar('http://www.google.com/calendar/feeds/9qlp4teboan1u4rs0feptiqkts@group.calendar.google.com/public/full');
				//document.getElementById('calcounter').value = '4';		
			//break;
			// Lutheran Curch of McVille
			case '4':
				siteWide.calCount = '3';		
				loadCalendar('http://www.google.com/calendar/feeds/i285o5ureneun3f9068q9h1bhs@group.calendar.google.com/public/full');
			break;
			// Grace of Grace City
			case '3':
				siteWide.calCount = '2';		
				loadCalendar('http://www.google.com/calendar/feeds/puofesq6mci9qc46hqt1tqij7k@group.calendar.google.com/public/full');
			break;
			// First Presbyterian
			case '2':
				siteWide.calCount = '1';		
				loadCalendar('http://www.google.com/calendar/feeds/ejkaqhms89ov345uegljs8465g@group.calendar.google.com/public/full');
			break;
			// Faith of Hannaford
			case '1':
				siteWide.calCount = '0';		
				loadCalendar('http://www.google.com/calendar/feeds/q1fr9n7psh8jtok8atr68jcqqc@group.calendar.google.com/public/full');
			break;
			// Tricounty
			case '0':

				var	myMixedEvents = document.getElementById('html_builder').innerHTML;

				eventsArray = myMixedEvents.split('**');

				eventsArray.sort();
				myhtml = '';
				
				var header_titles = '';
				var header_location = '';
				var header_descriptions = '';
				var header_times = '';
				var header_urls = '';

				for(i=1;i<eventsArray.length;i++){
				

					singleEvent = eventsArray[i].split('^');
					
					var splitMyTime = singleEvent[0].split('/');
					
					switch(splitMyTime[0]){
						case '01': myMonth = 'Jan.'; break;
						case '02': myMonth = 'Feb.'; break;
						case '03': myMonth = 'March'; break;
						case '04': myMonth = 'April'; break;
						case '05': myMonth = 'May'; break;
						case '06': myMonth = 'June'; break;
						case '07': myMonth = 'July'; break;
						case '08': myMonth = 'Aug.'; break;
						case '09': myMonth = 'Sept.'; break;
						case '10': myMonth = 'Oct.'; break;
						case '11': myMonth = 'Nov.'; break;
						case '12': myMonth = 'Dec.'; break;						
					}
					
					header_times += '|'+myMonth + ' ' + splitMyTime[1];	
					header_urls += '|'+singleEvent[1];									
					header_titles += '|'+singleEvent[2];
					if(singleEvent[3]){
						header_location += '|Upcoming Event @ '+singleEvent[3];						
					} else {
						header_location += '|Upcoming Event';						
					}
					header_descriptions += '|'+singleEvent[4];
					
					
					fullTime = singleEvent[0].split(' - ');						
					startDates = fullTime[0].split('/');

					if(startDates[0].substring(0,1) == 0){
						startMonth = startDates[0].substring(1);
					} else {
						startMonth = startDates[0];
					}
					
					if(startDates[1].substring(0,1) == 0){
						startDay = startDates[1].substring(1);
					} else {
						startDay = startDates[1];
					}
					
					if(fullTime[1]){
						endDates = fullTime[1].split('/');
					}
					
					if(fullTime[1]){
						if(fullTime[1].substring(0,1) == 0){
							startTime = ' - ' + fullTime[1].substring(1);
						} else {
							startTime = ' - ' + fullTime[1];
						}
					} else {
						startTime = '';
					}
					
					 myhtml += startMonth + '/' + startDay + startTime + '</div></li>';
				}

				document.getElementById('header_times').innerHTML = header_times;
				document.getElementById('header_urls').innerHTML = header_urls;
				document.getElementById('header_titles').innerHTML = header_titles;
				document.getElementById('header_location').innerHTML = header_location;
				document.getElementById('header_descriptions').innerHTML = header_descriptions;
				
					
				header_times += '|'+singleEvent[0];	
				header_urls += '|'+singleEvent[1];									
				header_titles += '|'+singleEvent[2];
				header_location += '|'+singleEvent[3];
				header_descriptions += '|'+singleEvent[4];
				
				message_rotation();
			break;		
		}	
		
}

google.setOnLoadCallback(init);
