/*
 * SIMPLEPIE LIVE: Base functionality for requesting feeds via JavaScript.
 * http://live.simplepie.org
 * (c) 2004-2009, Ryan Parman, Geoffrey Sneddon
 */

var _callback = [];
var SimplePie = function(feedUrl, opt) {
	this.guid = this.getGuid();
	this.opt = opt;
	if (typeof feedUrl != 'string') this.opt.feedUrl = feedUrl.join('__feedUrl__');
	else this.opt.feedUrl = feedUrl;
	_callback[this.guid] = this.opt.onSuccess;
	_callback['error_'+this.guid] = this.opt.onFailure;
	this.opt.onSuccess = '';
	this.opt.onFailure = '';
	this.init(this.opt.handler);
	return this;
};
SimplePie.prototype = {
	init: function(handler) {
		switch(handler) {
			case 'json':
				var tag = new SimplePie_Remote('http://live.simplepie.org/app/0.5/json.js?' + this.toQueryString(this.opt), this.guid);
				break;
			default:
				var tag = new SimplePie_Remote('http://live.simplepie.org/app/0.5/api.js?' + this.toQueryString(this.opt), this.guid);
				break;
		}
	},
	getGuid: function() {
		var arr = '';
		for (var x = 0; x < 5; x++) {
			arr += ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'][Math.floor(Math.random() * 26)];
		}
		return arr + (new Date()).getTime();
	},
	toQueryString: function(source) {
		var queryString = [];
		for (var property in source) {
			queryString.push(encodeURIComponent(property)+'='+encodeURIComponent(source[property]));
		}
		return queryString.join('&').replace(/__feedUrl__/gi, "&feedUrl=");
	},
	cleanup: function() {
		document.getElementsByTagName("head")[0].removeChild(document.getElementById('simplepielive'+this.guid));
	}
};
var SimplePie_Remote = function(remote_url, guid) {
	this.url = remote_url;
	this.noCacheIE = '&guid=' + guid;
	this.guid = guid;
	this.obj = document.createElement("script");
	this.obj.setAttribute("type", "text/javascript");
	this.obj.setAttribute("src", this.url + this.noCacheIE);
	this.obj.setAttribute("id", 'simplepielive'+this.guid);
	document.getElementsByTagName("head")[0].appendChild(this.obj);
	return this;
};
