/*
 * Mini-RSS aggregator.
 * See the PHP script (hardcoded below) for documentation.
 */

String.random = function() {
	var chars = 'abcdefghiklmnopqrstuvwxyz';
	var s = '';
	for (var i = 0; i < 16; i++) {
		var n = Math.floor(Math.random() * chars.length);
		s += chars.substring(n, n+1);
	}
	return s;
};

var OPML = Class.create({
	initialize: function(args) {
		this.element = args.element;
		this.jsonp = String.random();
		window[this.jsonp] = this.display.bind(this);
		this.script = 'http://www.lib.uchicago.edu/public/opml/index.php?jsonp=' + escape(this.jsonp) + '&opml=' + escape(args.opml);
		document.observe('dom:loaded', this.setup.bind(this));
	},
	setup: function () {
		$(this.element).hide();
		this.script = new Element('script', {
			'src': this.script,
			'type': 'text/javascript'
		});
		$$('body').first().insert(this.script);
	},	
	display: function(rsses) {
		rsses.each(function(rss) {
			$(this.element).insert(
				new Element('h3').insert(
					new Element('a', {
						'href': rss.link
					}).insert(rss.title)));

			var ul = new Element('ul');
			$(this.element).insert(ul);

			var a = 0;
			for (var articlelink in rss.items) {
				if (a < 3) {
					ul.insert(	
						new Element('li').insert(
							new Element('a', {
								'href': articlelink
							}
						).insert(rss.items[articlelink])
					));
				} else {
					ul.insert(	
						new Element('li').insert(($H(rss.items).keys().length - 3) + ' more articles.')
					);
					break;
				}
				a++;
			}
		}.bind(this));
		$(this.element).show();
	}
});

