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

var msgcount = 0;
var scoTableContent = "";

function sendDebug(txtMsg) {
	//var debugmsg = document.getElementById('debugmsg'); 
	//msgcount = msgcount + 1;
	//debugmsg.innerHTML += msgcount + ":" + txtMsg + "<BR>";
}

/** 
* Initialises the Google JavaScript Client Library and then Loads the ScoMIS Calendar. */
function init() {  
	sendDebug("01:Function Init");
	// init the Google data JS client library with an error handler  
	google.gdata.client.init(handleGDError);  
	loadCalendarByAddress('04sfet29fu8ub2thlk4mvpi03g@group.calendar.google.com');
}


/** 
* 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) {  
	sendDebug("03:Function loadCalendarByAddress");
    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) {
	sendDebug("04:Function Load Calendar");
	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(100);
	query.setFullTextQuery(searchfor);
	sendDebug("05:Search For: " + searchfor);
	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) {
	sendDebug("05: Function handleGDError");
    //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());  
	}
}
  
/** * 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) {
	sendDebug("06:Function listEvents");
	var entries = feedRoot.feed.getEntries();  
	var scoDate, scoCourse, scoLocation, scoTimes, scoPrice, scoURL, scoTrainer, scoPricePerPerson, scoPricePerSchool;
	var scoStart, scoFinish;
	var mydesc;
	
	/* loop through each event in the feed */
	var len = entries.length;
	for (var i = 0; i < len; i++) {
		/* Reset the Event Details to blanks to prevent incorrect data from displaying */
		scoDate = "";
		scoCourse = "&nbsp;";
		scoLocation = "&nbsp;";
		scoTimes = "&nbsp;";
		scoPrice = "&nbsp;";
		scoURL = "";
		scoTrainer = "&nbsp;";
		scoPricePerPerson = "";
		scoPricePerSchool = "";
		scoStart = "0.00";
		scoFinish = "0.00";
		scoDay = "1";
	
		var entry = entries[i];
		// Get the Title of the Event
		var title = entry.getTitle().getText();
		
		// Get the Content, otherwise define it as empty
		if (entry.getContent() != null) { 
			mydesc = entry.getContent().getText();
		}  else {
			mydesc = "empty";
		}
		
		// Get the Google Calendar URL
		var entryLinkHref = null;
		if (entry.getHtmlLink() != null) {
			entryLinkHref = entry.getHtmlLink().getHref();
		}

		//Get the Event Start Date and Time
		var startDateTime = null;
		var startJSDate = null;    
		var times = entry.getTimes();
		if (times.length > 0) {
			startDateTime = times[0].getStartTime();
			startJSDate = times[0].getStartTime().getDate();
		}
		
		if (!startDateTime.isDateOnly()) {
			//dateString += " " + startJSDate.getHours() + ":" + padNumber(startJSDate.getMinutes());
			scoStart = startJSDate.getHours() + ":" + padNumber(startJSDate.getMinutes());
		}
		//var dateString =  padNumber(startJSDate.getDate()) + "/" + (startJSDate.getMonth() +1) + "/" + startJSDate.getYear();
		
		var finishDateTime = null;
		var finishJSDate = null;
		finishDateTime = times[0].getEndTime();
		finishJSDate = finishDateTime.getDate();
		
		if (!finishDateTime.isDateOnly()) {
			//dateString += " " + finishJSDate.getHours() + ":" + padNumber(finishJSDate.getMinutes());
			scoFinish = finishJSDate.getHours() + ":" + padNumber(finishJSDate.getMinutes());
		}				
		
		scoDate = padNumber(startJSDate.getDate()) + "/" + padNumber(startJSDate.getMonth() +1) + "/" + startJSDate.getFullYear();
			
		scoTimes = scoStart + " - " + scoFinish;
		
		/* Decode the Content Section and break into Variables */
		/* Variables
		URL=http://training.scomis.org/attendance-7-for-new-users/;
		Trainer=Frank Prowse;
		PricePerPerson=£150;
		PricePerSchool=£220;
		Location=Exeter;
		*/

		var myarray = new Array();
		var j;
		myarray = mydesc.split(";");
		for (j=0;j<myarray.length;j++) 
		{
			var scoprop, scovalue;
			var tarray = new Array();
			tarray = myarray[j].split("=");
			scoprop = alltrim(tarray[0]);
			scovalue = tarray[1];

			switch (scoprop) 
			{
				case "Trainer":
					scoTrainer = scovalue;
					break;
				case "URL":
					scoURL = scovalue;
					break;
				case "Location":
					scoLocation = scovalue;
					break;
				case "PricePerPerson":
					scoPricePerPerson = scovalue;
					break;
				case "PricePerSchool":
					scoPricePerSchool = scovalue;
					break;
				case "Day":
					scoDay = scovalue;
				default:
					scovalue = "";
			}
		}

		// If a URL was found in the content then turn the title into a URL Link
		if (scoURL != "") {
			title = "<a href='" + scoURL + "'>" + title + "</a>";
		} 
		
		// Convert the Location into a URL, for Exeter, Plymouth and Barnstaple areas
		scoLocation = LocationURL(scoLocation);
		
		// Create ScoMIS Price
		scoPrice = ScoMISPrices(scoPricePerPerson,scoPricePerSchool);

		// Update the Table
		if (scoDay == "1") {
			AddToTable(i,scoDate, title, scoLocation, scoTimes, scoPrice, entryLinkHref)
		}

				
	} 
	if (len != 0) {
		//document.getElementById('waitmsg').innerHTML = "<p><strong>Calendar " + feedRoot.feed.title.$t + "</strong></p>";
		WriteTable();
	} else {
		WriteNoCoursesInfo();
	}
}

function WriteNoCoursesInfo() {
	sendDebug("Writing Table");
	var scoTableDiv = document.getElementById('scoTableDiv');
	var scoTable = "<p><strong>Course Booking enquiries</strong><br>01392 385300 or email <a href='mailto://scomis@devon.gov.uk'>scomis@devon.gov.uk</a></p>";
	scoTable += "<p><strong>Course dates to be allocated according to demand.</strong>  If you are interested in this course, please complete the form below;</p>";
	scoTable += "<div align=center><a href='http://www.scomis.org/forms/bookingenquiry.php?";
	scoTable += "coursecode=";
	scoTable += searchfor;
	scoTable += "&coursetitle=";
	scoTable += coursetitle;
	scoTable += "'>";
	scoTable += "Enquire about this course</a></div>";
	scoTableDiv.innerHTML = scoTable;
}

function WriteTable() {
	sendDebug("Writing Table");
	var scoTableDiv = document.getElementById('scoTableDiv');
	var scoTable = "<p><strong>Course Booking enquiries</strong><BR>01392 385300 or email <a href='mailto://scomis@devon.gov.uk'>scomis@devon.gov.uk</a></p>";
	scoTable += "<table id='scoTable' cellpadding='4' border='0' width='100%' style='border-collapse:collapse; border:1px solid #a8bece'>";
	scoTable += "<thead><tr><td>&nbsp;</td><td>Date</td><td>Course</td><td>Location</td><td width='80px'>Times</td>";
	scoTable += "<td width='150px'>Price</td></tr></thead>"
	scoTable += "<tbody id='scoBody' style='border-collapse:collapse; border:1px solid #000000'>";
	scoTable += scoTableContent;
	scoTable += "</tbody></table>";
	
	scoTableDiv.innerHTML = scoTable;
}


function AddToTable(id, scoDate, title, scoLocation, scoTimes, scoPrice, entryLinkHref) {
	//sendDebug(title);
	scoTableContent += "<tr style='border: 1px solid #a8bece'>";
	scoTableContent += "<td>";
	scoTableContent += "<a href='" + entryLinkHref + "' target='_blank'><img src='http://training.scomis.org/wp-content/themes/ScoMISNew/Google-Calendar-32.png' alt='Add to your Google Calendar' border=0></a>";
	scoTableContent += "</td><td>";
	scoTableContent += scoDate;
	scoTableContent += "</td><td>";
	scoTableContent += title;
	scoTableContent += "</td><td>";
	scoTableContent += scoLocation;
	scoTableContent += "</td><td>";
	scoTableContent += scoTimes;
	scoTableContent += "</td><td>";
	scoTableContent += scoPrice;
	scoTableContent += "</td></tr>";
}

function LocationURL(scoLocation) {
	var myLocation;
	switch (scoLocation) {
		case "Exeter":
			myLocation = "<a href='http://training.scomis.org/venues/exeter/'>" + scoLocation + "</a>";
			break;
		case "Plympton":
			myLocation = "<a href='http://training.scomis.org/venues/plymouth/'>" + scoLocation + "</a>";
			break;
		case "Barnstaple":
			myLocation = "<a href='http://training.scomis.org/venues/barnstaple/'>" + scoLocation + "</a>";
			break;
		default:
			myLocation = scoLocation;
	}
	return myLocation;
}

function ScoMISPrices(scoPricePerPerson,scoPricePerSchool) {
	var scoPrice;
	if (scoPricePerPerson !="") {
		scoPrice = "Per Person <b>" + scoPricePerPerson + "</b>";
	} else {
		scoPrice = "Per School <b>" + scoPricePerSchool + "</b>";
	}
	if (scoPricePerSchool !="" && scoPricePerPerson !="") {
		scoPrice = "Per Person <b>" + scoPricePerPerson + "</b><BR>Per School <b>" + scoPricePerSchool + "</b>";
	}	
	return scoPrice;
}

function alltrim(str) {
	return str.replace(/^\s+|\s+$/g, '');
}

  
google.setOnLoadCallback(init);
