/**
 * Copyright (C) 2006 by FGCZ.
 * http://www.snyke.net
 *
 * @author	Christian Decker <decker.christian@gmail.com>
 *
 * GCalendar is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Foobar; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
// ==========================================================================
/**
 * Class that represents the calendar.
 */
var GCalendar = Class.create();
GCalendar.prototype = {
	uri: "msamokhvalov%40gmail.com",
	orderby: "starttime",
	singleEvents: true,
	futureEvents: true,
	sortOrder: "ascending",
	entries: {},
	initialize: function(u){
		if(u){this.uri = u;}
	},
	
	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;
document.write(str);
		return str;
	},
	
	loadFeed: function(){
		window.activeCalendar = this;
		var headTag = document.getElementsByTagName('head')[0]; 
		var script = document.createElement("script");
		script.src = this.buildURL();
		script.language = "JavaScript";
		headTag.appendChild(script);
	},

	parseFeed: function(json)
	{
		e = json.feed.entry;
		for(var i=0;i < e.length;i++)
		{
			this.entries[i] = new EventEntry(e[i])
		}
		try 
		{
			this.onsuccess(this);
      	} catch (e) {}
	},
	
	onsuccess: function(c){}
};

// ==========================================================================
/**
 * Singleton object used to convert Dates from one format to another.
 */
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;
	}
};

// ==========================================================================
var EventEntry = Class.create();
EventEntry.prototype = {
	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;
	}
};