window.addEvent('domready', function() {
	var FeedReader = new Class({
		initialize: function( url ){
			this.url = url;
		},

		getURL: function() {
			return this.url;
		}
	});

	var TwitterReader = new Class({
		Implements: FeedReader,

		getItems: function( callback ) {
			new Request.JSONP({
				url: this.url,
				callbackKey: "callback",
				onComplete: function( data ) {
					if (!data) {
						return;
					}

					var items = [];

					var max = 0;

					data.each(function( item ) {
						items.push({
							href: "http://twitter.com/".concat(item.user.screen_name, "/status/", item.id),
							text: item.text,
							date: item.created_at
						});
					});

					callback.apply(this, [ items ]);
				}
			}).send();
		}
	});

	var YahooReader = new Class({
		Implements: FeedReader,

		getItems: function( callback ) {
			new Request.JSONP({
				url: this.url,
				callbackKey: "_callback",
				onComplete: function( data ) {
					if (!data || data.count == 0) {
						return;
					}

					var items = [];

					var max = 0;
					data.value.items.each(function( item ) {
						if (max++ < 5) {
							items.push({
								href: item.link,
								text: item.title,
								date: item.pubDate
							});
						}
					});

					callback.apply(this, [ items ]);
				}
			}).send();
		}
	});

	$$("link.reader").each(function( link ) {
		var relName = link.get("rel");
		var href = link.get("href");

		if (!relName || !href) {
			return;
		}

		var selectedItem = $(relName);

		var reader;
		switch(true) {
			case link.hasClass("yahoo"):
				reader = new YahooReader(href);
				break;

			case link.hasClass("twitter"):
				reader = new TwitterReader(href, "http://twitter.com/ikaraszi/");
				break;

			default:
				throw "Unknown reader";
		}

		reader.getItems(function( items ) {
			var div = new Element("div").addClass('reader').setStyles({
				opacity: 0,
				display: "none",
				overflow: "hidden"
			}).inject(selectedItem);

			var ul = new Element("ul");
			items.each(function( item ) {
				var li = new Element("li");

				if (item.href == null) {
					li.set("text", item.text);
				} else {
					new Element("a").set({
						href: item.href,
						text: item.text
					}).inject(li);
				}

				li.inject(ul);
			});

			ul.inject(div);

			var fx = new Fx.Morph(div, {
				duration: 'normal',
				transition: Fx.Transitions.Sine.easeOut
			});

			var height = 0;

			selectedItem.addEvents({
				mouseout: function() {
					if (height == 0) {
						return;
					}

					fx.cancel().start({
						height: 0,
						opacity: 0
					});
				},
				mouseover: function() {
					if (height == 0) {
						div.setStyle("display", "block");
						height = div.getSize().y;
						div.setStyle("height", 0);
					}

					fx.cancel().start({
						height: height,
						opacity: 1
					});
				}
			});
		});
	});
});
