/**
 * Ajax RSS Reader
 *
 * this javascript allow you to parse a rss and load it from the client side
 * The server is free from load :)
 *
 * @author	Paul Sobocinski
 *
 * Edited to accept external xml
*/


var request_timeout = 5000;

//objects inside the RSS2Item object
function RSS2Enclosure(encElement)
{
	if (encElement == null)
	{
		this.url = null;
		this.length = null;
		this.type = null;
	}
	else
	{
		this.url = encElement.getAttribute("url");
		this.length = encElement.getAttribute("length");
		this.type = encElement.getAttribute("type");
	}
}

function RSS2Guid(guidElement)
{
	if (guidElement == null)
	{
		this.isPermaLink = null;
		this.value = null;
	}
	else
	{
		this.isPermaLink = guidElement.getAttribute("isPermaLink");
		this.value = guidElement.childNodes[0].nodeValue;
	}
}

function RSS2Source(souElement)
{
	if (souElement == null)
	{
		this.url = null;
		this.value = null;
	}
	else
	{
		this.url = souElement.getAttribute("url");
		this.value = souElement.childNodes[0].nodeValue;
	}
}

//object containing the RSS 2.0 item
function RSS2Item(itemxml)
{
	//required
	this.title;
	this.link;
	this.description;

	//optional vars
	this.author;
	this.comments;
	this.pubDate;

	//optional objects
	this.category;
	this.enclosure;
	this.guid;
	this.source;

	var properties = new Array("title", "link", "description", "author", "comments", "pubDate");
	var tmpElement = null;

	var length = properties.length;
	for (var i=0; i<length; i++)
	{
		tmpElement = itemxml.getElementsByTagName(properties[i])[0];
		if (tmpElement != null)
			eval("this."+properties[i]+"=tmpElement.childNodes[0].nodeValue");
	}

	this.category = new RSS2Category(itemxml.getElementsByTagName("category")[0]);
	this.enclosure = new RSS2Enclosure(itemxml.getElementsByTagName("enclosure")[0]);
	this.guid = new RSS2Guid(itemxml.getElementsByTagName("guid")[0]);
	this.source = new RSS2Source(itemxml.getElementsByTagName("source")[0]);
}

//objects inside the RSS2Channel object
function RSS2Category(catElement)
{
	if (catElement == null)
	{
		this.domain = null;
		this.value = null;
	}
	else
	{
		this.domain = catElement.getAttribute("domain");
		this.value = catElement.childNodes[0].nodeValue;
	}
}

//object containing RSS image tag info
function RSS2Image(imgElement)
{
	if (imgElement == null)
	{
	this.url = null;
	this.link = null;
	this.width = null;
	this.height = null;
	this.description = null;
	}
	else
	{
		imgAttribs = new Array("url","title","link","width","height","description");
		for (var i=0; i<imgAttribs.length; i++)
			if (imgElement.getAttribute(imgAttribs[i]) != null)
				eval("this."+imgAttribs[i]+"=imgElement.getAttribute("+imgAttribs[i]+")");
	}
}
 
var Utf8 = {
 
	// public method for url encoding
	encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// public method for url decoding
	decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
};

function strip_tags(text){
 return text.replace(/<\/?[^>]+>/gi, '');
}

//object containing the parsed RSS 2.0 channel
function RSS2Channel(rssxml)
{
	//required
	//this.title;
	//this.link;
	//this.description;

	//array of RSS2Item objects
	this.items = new Array();

	//optional vars
	//this.language;
	/*
	this.copyright;
  this.managingEditor;
	this.webMaster;
	this.pubDate;
	this.lastBuildDate;
	this.generator;
	this.docs;
	this.ttl;
	this.rating;
	*/

	//optional objects
	//this.category;
	//this.image;


	var chanElement = rssxml.getElementsByTagName("channel")[0];
	var itemElements = rssxml.getElementsByTagName("item");

	for (var i=0; i<itemElements.length; i++)
	{
		Item = new RSS2Item(itemElements[i]);
		this.items.push(Item);
		//chanElement.removeChild(itemElements[i]);
	}
/*
	var properties = new Array("title", "link", "description", "language");
	var tmpElement = null;
	for (var i=0; i<properties.length; i++)
	{
		tmpElement = chanElement.getElementsByTagName(properties[i])[0];
		if (tmpElement!= null)
			eval("this."+properties[i]+"=tmpElement.childNodes[0].nodeValue");
	}
*/
	//this.category = new RSS2Category(chanElement.getElementsByTagName("category")[0]);
	//this.image = new RSS2Image(chanElement.getElementsByTagName("image")[0]);
}
//PROCESSES
//uses xmlhttpreq to get the raw rss xml
function getRSS(url,details,nb_items,errormsg) {

  jQ.ajaxSetup({
    timeout: 10000
  });

	jQ.ajax({
    type: 'GET',
    processData: false,
    url: url,
    timeout: request_timeout,
    complete: function(data,t){
      if(t != 'timeout') {
        processRSS(data.responseXML,details,nb_items,data.responseText);
      }
    },
    error: function(data) {
		  document.getElementById("feed_items").innerHTML = '<li>'+errormsg+'</li>';
    }
  });	
	
	return;
}
//processes the received rss xml
function processRSS(rssxml,details,nb_items,rsstext) {
	RSS = new RSS2Channel(rssxml);
	showRSS(RSS,details,nb_items,rsstext);
}

/*
function fchange(str) {

  return str.replace(/et#(\d+);/g, function (m, n) { return String.fromCharCode(n); });   

}
*/

//shows the RSS content in the browser
function showRSS(RSS,details,nb_items,rsstext) {
	//populate the items
	document.getElementById("feed_items").innerHTML = "";
  var encodage = '';
	var length = RSS.items.length;
  
  b = rsstext.match(/encoding='?"?([\w-]+)'?"?/);
  if (b) { var encodage = b[1].toLowerCase(); }

	/* Number of wished items */
	if ( nb_items < length ) { length = nb_items; }

	for (var i=0; i<length; i++)
	{
		item_html = '<li>';

    if(i+1 == length) {
      item_html = '<li class="last">';
    }

		if ( RSS.items[i].title != null ) {
  		if(!jQ.browser.msie) {
  		  if(encodage == 'utf-8') {
          RSS.items[i].title = Utf8.decode(RSS.items[i].title);
        }
      }
			item_html += '<a href="'+RSS.items[i].link+'" target="_blank" class="title"><strong>'+ RSS.items[i].title;
		}
		if ( details == 1 && RSS.items[i].description != null ) {
  		if(!jQ.browser.msie) { 
        if(encodage == 'utf-8') {
          RSS.items[i].description = Utf8.decode(RSS.items[i].description);
        } 
      }
      
      //RSS.items[i].description = fchange(RSS.items[i].description);
      
			item_html += '</strong><span>'+strip_tags(RSS.items[i].description)+'</span>';
		}
		item_html += '</a></li>';
		document.getElementById("feed_items").innerHTML += item_html;	  
	}
	//$('rssloader').hide();
	return true;
}

var xhr;

