/*
Load calendar feeds into a DIV

Take a DIV hook, feed URL, #days in the future to display, flag for "pop-up" content, section heading

Place into DIV:
<h1>Heading</h1>
<h2>Date</h2>
<h3>Title</h3>
<p>Content</p>

Give <div> class if "pop-up"

Dependencies: date.js, lib.js

Added: find the date-range in a calendar (used for producing archived newsletters)

*/

google.load("gdata", "1");
google.setOnLoadCallback(init);

var issueDate = [];

function loadDates(feed) {
	var endd = new Date();
	var startd = new Date();
	startd.setFullYear(2009,6,24); //first online newsletter 2009-07-24
	//startd.setFullYear(startd.getFullYear(),0,1); //only show the current year's newsletters
	var service = new google.gdata.calendar.CalendarService('gdata-js-client-samples-simple');
	var query = new google.gdata.calendar.CalendarEventQuery(feed);
	query.setOrderBy('starttime');
	query.setSortOrder('descending');
	query.setSingleEvents(true);
	var startTime = google.gdata.DateTime.fromIso8601(formatDate(startd, 'y-MM-dd') + 'T00:00:00.000');
	var endTime = google.gdata.DateTime.fromIso8601(formatDate(endd, 'y-MM-dd') + 'T23:59:59.000');
	query.setMinimumStartTime(startTime);
	query.setMaximumStartTime(endTime);
	doCal = function(feedRoot) {
		var entries = feedRoot.feed.getEntries();
		var thisEntry, startDateTime, startJSDate;
		if (entries.length) {
			for (var i = 0; i < entries.length; i++) {
				thisEntry = entries[i];
				times = thisEntry.getTimes();
				startDateTime = times[0].getStartTime();
				startJSDate = startDateTime.getDate();
				//alert('Found ' + thisEntry.getTitle().getText() + ' on ' + startJSDate);
				issueDate.push(formatDate(startJSDate, 'y-MM-dd'));
			}
			loadIssue();
		}
	}
	service.getEventsFeed(query, doCal, handleGDError);
}

function init() {
	// init the Google data JS client library with an error handler
	google.gdata.client.init(myErrorHandler);
}

function myErrorHandler(){
	//There's been an error.
	//Oh no.
	alert('Error initiliasing GData module');
}

function loadCalendar(targetDiv, currDate, numDays, sectionHeading, hasDate, isCal, hasPopup, calendarURL) {
	//fail if no DOM methods or missing arguments
	if (!document.getElementById) {
		return false;
	}
	if (typeof(targetDiv) == 'undefined') {
		return false;
	}
	if (typeof(currDate) == 'undefined') {
		return false;
	}
	if (typeof(calendarURL) == 'undefined') {
		return false;
	}
	var hook = document.getElementById(targetDiv);
	if (!hook) {
		return false;
	}
	
	//make a local copy of currDate, as currDate is a ptr and changing it is global
	//(a looooong period of debugging found this out ...)

	var d = new Date(currDate);
	
	//now construct the feed request
	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 startTime = google.gdata.DateTime.fromIso8601(formatDate(d, 'y-MM-dd') + 'T00:00:00.000'), endTime; //do I need timezone +12:00?
	if (numDays) {
		d.setDate(d.getDate() + numDays); 
	}
	endTime = google.gdata.DateTime.fromIso8601(formatDate(d, 'y-MM-dd') + 'T23:59:59.000');
	query.setMinimumStartTime(startTime);
	query.setMaximumStartTime(endTime);
	doCal = createCal(hook, sectionHeading, currDate, isCal, hasDate, hasPopup);
	service.getEventsFeed(query, doCal, handleGDError);
}

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());
	}
}

function createCal(eventDiv, sHead, theDate, isCal, hasDate, hasPopup) {
	return function(feedRoot){
		var entries = feedRoot.feed.getEntries();
		if (entries.length) {
			//var eventDiv = document.getElementById(hook);
			while (eventDiv.hasChildNodes()) eventDiv.removeChild(eventDiv.firstChild);
			var calHead = document.createElement('div');
			var calHeadline = document.createElement('h1');
			calHeadline.appendChild(document.createTextNode(sHead));
			calHead.appendChild(calHeadline);
			if (hasDate) {
				var theIssue = formatDate(theDate,'EE, d MMM y');
				var issueDate = document.createElement('p');
				issueDate.className = 'issueDate';
				issueDate.appendChild(document.createTextNode(theIssue));
				calHead.appendChild(issueDate);
			}
			if (hasPopup) {
				//add a link to the full calendar
				var calLink = document.createElement('a');
				calLink.setAttribute('href', 'http://www.google.com/calendar/hosted/verdoncollege.school.nz/embed?src=webmaster@verdoncollege.school.nz&ctz=Pacific/Auckland&color=%230D7813');
				calLink.setAttribute('target', '_blank');
				calLink.appendChild(document.createTextNode('full calendar'));
				var calP = document.createElement('p');
				calP.appendChild(document.createTextNode('See all events on our '));
				calP.appendChild(calLink);
				calP.appendChild(document.createTextNode(' (this opens in a new window)'));
				calHead.appendChild(calP);
			}
			var thisEntry, times, startDateTime, startJSDate, endDateTime, endJSDate
			var title, content, bHead, bBody, thisDate, lastDate = '', doThisEntry, calLink, calContent, descID = 0;
			var entryLinkHref, startTime, endTime, endDate, dateRange, calDateRange, doneHead = false;
			for (var i = 0; i < entries.length; i++) {
				thisEntry = entries[i];
				times = thisEntry.getTimes();
				startDateTime = times[0].getStartTime();
				startJSDate = startDateTime.getDate();
				endDateTime = times[0].getEndTime();
				endJSDate = (endDateTime) ? endDateTime.getDate() : null;
				doThisEntry = (!endJSDate) || (!startDateTime.isDateOnly()) || (endJSDate.toDateString() != theDate.toDateString())
				if (doThisEntry) {
					if (!doneHead) {
						//has to go HERE rather than above since a feed with entries could still
						//NOT have any events due to the way Google Calendar stores all-day events
						eventDiv.appendChild(calHead);
						doneHead = true;
					}
					title = thisEntry.getTitle().getText();
					content = (thisEntry.getContent().getText() == undefined) ? '' : thisEntry.getContent().getText();
					//replace \r\n's with \n
					while ((p = content.indexOf('\r\n')) > -1) content = content.substring(0,p) + '\n' + content.substring(p+2);
					//remove double-blank lines
					while ((p = content.indexOf('\n\n')) > -1) content = content.substring(0, p) + content.substring(p+1);
					if (!isCal) {
						//is an article rather than a list of events
						bHead = document.createElement('h2');
						bHead.appendChild(document.createTextNode(title));
						eventDiv.appendChild(bHead);
					}
					else {
						//do the calendar thing
						if (times.length > 0) {
							thisDate = formatDate(startJSDate, 'd MMM');
							if (thisDate != lastDate){
								bHead = document.createElement('h2');
								bHead.appendChild(document.createTextNode(thisDate));
								eventDiv.appendChild(bHead);
								lastDate = thisDate;
							}
							bHead = document.createElement('h3');
							if (hasPopup && content) {
								entryLinkHref = (thisEntry.getHtmlLink()) ? thisEntry.getHtmlLink().getHref() : null;
								calLink = document.createElement('a');
								calLink.setAttribute('href', entryLinkHref);
								calLink.setAttribute('title', 'Display more information');
								calLink.onclick = toggleCal;
								calLink.onmouseout = timeTheClose;
								calLink.onmouseover = haltTheClose;
								calLink.appendChild(document.createTextNode(title));
								bHead.appendChild(calLink);
								eventDiv.appendChild(bHead);
							}
							else {
								bHead.appendChild(document.createTextNode(title));
								eventDiv.appendChild(bHead);
							}
							//right -- check start and end dates/times.
							dateRange = '';
							if (startDateTime.isDateOnly() && endJSDate) {
								endJSDate.setDate(endJSDate.getDate() - 1);
							}
							if (endJSDate) {
								endDate = formatDate(endJSDate, 'd MMM');
								endTime = (endDateTime.isDateOnly()) ? null : formatDate(endJSDate, 'h:mm a');
							}
							//alert(startJSDate + ' -> ' + endJSDate);
							if (!startDateTime.isDateOnly()) {
								//display times
								startTime = formatDate(startJSDate, 'h:mm a');
								dateRange = startTime + ' to ' + endTime;
								if (endDate != thisDate) {
									dateRange += ' (' + endTime + ')';
								}
							}
							else {
								//display dates
								if (endDate != thisDate) {
									dateRange = thisDate + ' to ' + endDate;
								}
							}
							if (dateRange != '') {
								calDateRange = document.createElement('p');
								calDateRange.className = 'dateRange';
								calDateRange.appendChild(document.createTextNode(dateRange));
								eventDiv.appendChild(calDateRange);
							}
						}
					}
					if (content) {
						calContent = document.createElement('div');
						if (hasPopup) {
							calContent.className = 'displaycontent';
							calContent.id = 'displayContent' + descID++;
							calContent.style.display = 'none';
							//calLink.onclick = toggleCal(calContent.id);
							calLink.setAttribute('displayID', calContent.id);
						}
						eventDiv.appendChild(calContent);
						p = content.indexOf('\n');
						while (p != -1){
							bBody = document.createElement('p');
							bBody.appendChild(document.createTextNode(content.substring(0,p)));
							calContent.appendChild(bBody);
							content = content.substring(p+1);
							p = content.indexOf('\n')
						}
						if (content) {
							//tidy up if there is a block left with no newlines
							bBody = document.createElement('p');
							bBody.appendChild(document.createTextNode(content));
							calContent.appendChild(bBody);
						}
					}
				}
			}
			if (smartenIt) {
				smartenIt(eventDiv);
			}
		}
	}
}

//functions to make the popup show
function timedClose(wID) {
	var what = document.getElementById(wID);
	if (what)
	{
		what.style.display =  'none';
		what.setAttribute('title', 'Display more information');
	}
}

function timeTheClose() {
	var theDesc = document.getElementById(this.getAttribute('displayID'));
	if (theDesc.style.display =='block')
		theDesc.theTimer = setTimeout('timedClose(\'' + theDesc.id + '\')', 20000);
}

function haltTheClose() {
	var theDesc = document.getElementById(this.getAttribute('displayID'));
	if (theDesc.theTimer)
		clearTimeout(theDesc.theTimer);
}

function toggleCal(cID) {
	//var theDesc = this.parentNode.nextSibling;
	var theDesc = document.getElementById(this.getAttribute('displayID'));
	theDesc.style.display =  (theDesc.style.display == 'none') ? 'block' : 'none';
	if (theDesc.style.display == 'none')
		this.setAttribute('title', 'Display more information')
	else
		this.setAttribute('title', 'Hide');
	return false; //stop the link from working
}

