// Google Calendars Mootools-based API

var Calendar = new Class({
	orderby: "starttime",
	singleEvents: true,
	futureEvents: true,
	sortOrder: "ascending",
	entries: new Array(),
	initialize:function(u){
		if(u){this.uri = u;}
		return this;
	},
	buildURL:function(){
		var str = "http://www.google.com/calendar/feeds/";
		str += this.uri;
		str += "/public/full-noattendees?orderby=" + this.orderby;
		str += "&alt=json-in-script&callback=window.activeCalendar.parseFeed&";
		str += "singleevents=" + this.singleEvents;
		str += "&sortorder=" + this.sortOrder;
		str += "&futureevents=" + this.futureEvents;
		return str;
	},
	loadFeed:function(){
		window.activeCalendar = this;
		var headTag = document.getElementsByTagName('head')[0]; 
		var script = document.createElement("script");
		script.src = this.buildURL();
		script.type = "text/javascript";
		headTag.appendChild(script);
		return this;
	},
	parseFeed:function(json){
		var c = this;
		e = (json.feed.entry) ? json.feed.entry : [];
		for(var i=0;i < e.length;i++){
			this.entries[i] = new Calendar.EventEntry(e[i])
		}
		try {
			this.onSuccess.call(c,c.entries);
      	} catch (e) {
			this.onError.call(c,e);
		}
	},
	onSuccess:function(c){void(0);},
	onError:function(c){void(0);}
});

Calendar.EventEntry = new Class({
	title:null,
	content:null,
	startDate:null,
	endDate:null,
	location:null,
	initialize:function(entry){
		this.title = entry.title.$t;
		this.content = entry.content.$t;
		this.startDate = dateConverter.rfc3339toDate(entry.gd$when[0].startTime);
		this.endDate = dateConverter.rfc3339toDate(entry.gd$when[0].endTime);
		this.location = entry.gd$where[0].valueString;
		this.$startTime = entry.gd$when[0].startTime;
		this.$endTime = entry.gd$when[0].endTime;
	}
});

var dateConverter = {
	rfc3339toDate: function(t){
		t = t.substr(0,19).replace(/-/g,"/").replace("T"," ");
		var dt = new Date();
		dt.setTime(Date.parse(t));
		return dt;
	}
};
