var FCFeedParser = Class.create();

FCFeedParser.prototype = {
	items: new Array(),
	callback: null,
	
	initialize: function() {
		
	},
	Parse: function(_key, _callback) {
		var self = this;
		
		self.callback = _callback;
		
		var _url = "http://gateway.freecaster.tv/rss_channel/"+_key+"_date.rss";
		
		if (_key.match(/http:\/\/.*/)) {
			_url = "/feedcopy.php?url="+_key;
		} else {
			_url = "/feedcopy.php?category="+_key;
		}
		
		
		new Ajax.Request(_url, {
			method: "get",
			onSuccess: function(req) {
					self.ParseXML(req);
				},
			onFailure: function(req) {
				}
			
			});
			
			
			
	},
	ParseXML: function(req) {
		var self = this;
		var error = "";
		
		while (self.items.length) self.items.pop();
		
		if (req.responseXML == undefined){
		
			error = req.responseText;
		} else {
			var elements = req.responseXML.documentElement.getElementsByTagName('item');
			//alert(elements.length);
			for (var i = 0; i < elements.length; i++) {
				var idx = elements.length-1-i;
				var el = elements[idx];
				var item = new Object();
			
				item.title = this.GetNodeValue(el, 'title'); //el.getElementsByTagName('title')[0].firstChild.nodeValue;
				//if (i==1) alert(item.title);
				item.link = this.GetNodeValue(el, 'link'); //el.getElementsByTagName('guid')[0].firstChild.nodeValue;
				if (item.link == "") item.link = this.GetNodeValue(el, 'guid');
				item.description = this.GetNodeValue(el, 'description'); //el.getElementsByTagName('description')[0].firstChild.nodeValue;
				item.img = self.GetImage(item.description);
				item.type = "";
				item.date = this.GetNodeValue(el, 'pubDate'); //el.getElementsByTagName('pubDate')[0].firstChild.nodeValue;
				//alert (item.link);
				var temp = item.link.match(/http:\/\/([a-z]).*([a-z]{7}).*([0-9]{7})/);
				//alert (temp);
				item.channel_id = temp[1];
				item.clip_id = temp[2];
				//alert ("test3");
				var temp = el.getElementsByTagName('category');
				
				/*if (i==0)
				{
					for (var t = 0; t < temp.length; t++)
						alert (temp[t]);
					//alert (temp);
					//item.img.setAttribute("width","50");
				}*/
				for (var t = 0; t < temp.length; t++) {
					if (temp[t].getAttribute("domain") == "contentType") {
						item.type = temp[t].firstChild.nodeValue;
					}
				}
			
				self.items[idx] = item;
			
				delete item;
			}
		}
		
		self.callback(self.items, error);
		
	},
	GetNodeValue: function(_node, _name) {
		var value = "";
		
		try {
			value = _node.getElementsByTagName(_name)[0].firstChild.nodeValue;
		} catch(e) {}
		
		return value;
	},
	GetImage: function(_s) {
		var tag = _s.match(/<img[^>]*>/);
		var s = new String(tag);
		var link = s.match(/http:\/\/[^']*/);
		delete s;
		
		return link;
	}
};