//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, atom) {
  //required
  this.title;
  this.link;
  this.description;
  this.content;

  //optional vars
  this.author;
  this.image;
  this.comments;
  this.pubDate;

  //optional objects
  this.category;
  this.enclosure;
  this.guid;
  this.source;

  var properties = new Array("title", "link", "content", "description", "author", "comments", "published", "pubDate", "content:encoded" , "encoded");
  var tmpElement = null;
  for (var i in properties) {
    var property = properties[i];
    tmpElements = itemxml.getElementsByTagName(property);
    tmpElement = tmpElements[0];   
    if (tmpElement != null) {
      if (property == 'content:encoded') property = 'encoded';
      if (property == 'content' && tmpElement.getAttribute("type") == 'html' ) property = 'encoded';
      if (property == 'content') property = 'description';
      if (property == 'published') property = 'pubDate';
      if (atom && property == "link") {
        for (var el = 0; el < tmpElements.length; ++el) {
          tmpElement = tmpElements[el];
          if (tmpElement.getAttribute('rel') == 'image') {
            this.image = new RSS2Image(tmpElement);
          } else if (tmpElement.getAttribute('rel') == 'alternate') {
            this.link = tmpElement.getAttribute('href');
          }
        }
      } else if (atom && property == "author") {
        tmpElement = tmpElement.getElementsByTagName("name")[0];
        if (tmpElement != null) {
          this.author = tmpElement.childNodes[0].nodeValue;
        }
      } else if (tmpElement.childNodes[0]) {
        eval("this."+property+"=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","href","title","link","width","height","description");
    for (i in imgAttribs) {
      var attr = imgAttribs[i];
      tmpElement = imgElement.getAttribute(attr);
      if (tmpElement != null ) {
        if (attr == 'href') attr = 'url';
        eval("this."+attr+"=tmpElement");
      }
    }
  }
}

//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;

  if (window.ActiveXObject)
   null;
      else if (window.XMLHttpRequest) {
   }

  this.atom = false;
  var chanElement = rssxml.getElementsByTagName("channel")[0];
  var itemElements = rssxml.getElementsByTagName("item");
  if (chanElement == null) {
    chanElement = rssxml.getElementsByTagName("feed")[0];
    itemElements = rssxml.getElementsByTagName("entry");
    this.atom = true;
  }

  for (var i=0; i<itemElements.length; i++)
  {
    Item = new RSS2Item(itemElements[i],this.atom);
    this.items.push(Item);
    //chanElement.removeChild(itemElements[i]);
  }

  var properties = new Array("title", "link", "description", "language", "copyright", "managingEditor", "webMaster", "pubDate", "lastBuildDate", "generator", "docs", "ttl", "rating", "image");
  var tmpElement = null;
  for (var i in properties) {
    var property = properties[i];
    tmpElements = chanElement.getElementsByTagName(property);
    tmpElement = tmpElements[0];
    if (tmpElement!= null) {
      if (this.atom && property == "link") { 
        for (var el = 0; el < tmpElements.length; ++el) {
          tmpElement = tmpElements[el];
          if (tmpElement.getAttribute('rel') == 'alternate') {
            this.link = tmpElement.getAttribute('href');
            break;
          }
        }
      } else if (property == "image") {
         this.image = new RSS2Image(tmpElement);
      } else {
        eval("this."+property+"=tmpElement.childNodes[0].nodeValue");
      }
    }
  }
  this.category = new RSS2Category(chanElement.getElementsByTagName("category")[0]);
}

//PROCESSES

//uses xmlhttpreq to get the raw rss xml
function GetXmlData(url, objId, nitems, text_processor, title, description, titlelength, descriptionlength, template) {	
  if (nitems == undefined) nitems = 3;
  if (titlelength == undefined) titlelength = 50;
  if (descriptionlength == undefined) descriptionlength = 50;
  var xhr;
  //call the right constructor for the browser being used
  if (window.ActiveXObject) {
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
  } else if (window.XMLHttpRequest) {
   xhr = new XMLHttpRequest();
   if (xhr.overrideMimeType) {
       xhr.overrideMimeType('text/xml');
   }
  } else {
    alert("not supported");
  }
  //prepare the xmlhttprequest object
  xhr.open("GET",url,true);
  xhr.setRequestHeader("Cache-Control", "no-cache");
  xhr.setRequestHeader("Pragma", "no-cache");
  if (xhr.overrideMimeType) {
      xhr.overrideMimeType('text/xml');
  }
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      if (xhr.status == 200) {
        if (xhr.responseText != null) {
          processNItemsRSS(objId, nitems, xhr.responseXML, text_processor, title, description, titlelength, descriptionlength, template);
        } else {
          alert("Failed to receive RSS file from the server - file not found.");
          return false;
        }
      } else {
        alert("Error code " + xhr.status + " received: " + xhr.statusText);
        return false;
      }
    }
  }
  //send the request
  xhr.send(null);
}

//processes the received rss xml
function processNItemsRSS(objId, nitems, rssxml, text_processor, title, description, titlelength, descriptionlength, template) {

  RSS = new RSS2Channel(rssxml);

  //populate the items
  document.getElementById(objId).innerHTML = "";

  cntItems = (RSS.items.length < nitems)?RSS.items.length:nitems;
  item_html = '<h3><a href="' + RSS.link + '">' + title + '</a></h3>'
  if (description != null) {
    item_html += description;
  }
  for (var i=0; i<cntItems; i++) {
    if (template == 'twitter') {
      processItemTwitter(RSS.items[i],i,text_processor,titlelength,descriptionlength);
    } else {
      processItemSimple(RSS.items[i],i,text_processor,titlelength,descriptionlength);
    }
  }
  if (cntItems>0) {
    document.getElementById(objId).innerHTML = item_html;
  }
	setTimeout("if (typeof sifr_replace == 'function') sifr_replace();",200);
  return true;
}

function processItemSimple(item,index,text_processor,titlelength,descriptionlength) {
    item_html += '<div class="rssitem ' + (index%2 == 0 ? 'even' : 'odd') + '">';
    item_html += '<h4>' + '<a href="' + ((item.link == null) ? "" : item.link) + '">';
    itemtitle = item.title;
    // strip twitter name in title 
    if (text_processor == twitter_format) {
      var pos = itemtitle.indexOf(": ");
      if (pos >= 0) itemtitle = itemtitle.substring(pos+2);
    }
    if (itemtitle.length > titlelength) itemtitle = itemtitle.substring(0,titlelength) + '...'; 
    item_html += itemtitle + '</a></h4>';
    item_html += ((item.pubDate == null) ? "" : '<span>' + formatDate(item.pubDate) + '</span>') ;
    var text = item.encoded;
    if (text != null) {
      text = text.replace(/'/g,"\\'");
    }
    if (text_processor && typeof text_processor == 'function') eval("text="+text_processor+"('"+text+"', " + descriptionlength + ");");					
    item_html += ((text == null) ? "" : "<br />" + text);
    item_html += '</div>';
}

function processItemTwitter(item,index,text_processor,titlelength,descriptionlength) {
    item_html += '<div class="rssitem ' + (index%2 == 0 ? 'even' : 'odd') + '">';
    if (item.image != null) {
      item_html += '<img class="rssimage" src="' + item.image.url + '" />'; 
    }
    item_html += '<h4>' + '<a href="' + ((item.link == null) ? "" : item.link) + '">';
    item_html += ((item.pubDate == null) ? "" : '<span>' + formatTime(item.pubDate) + '</span>') ;
    // strip real name in author 
    itemauthor = item.author;
    var pos = itemauthor.indexOf(" ");
    if (pos >= 0) itemauthor = itemauthor.substring(0,pos);
    item_html += ' @' + itemauthor + '</a></h4>' 
    itemtitle = item.title;
    pos = itemtitle.indexOf(": ");
    if (pos >= 0) itemtitle = itemtitle.substring(pos+2);
    if (itemtitle.length > titlelength) itemtitle = itemtitle.substring(0,titlelength) + '...'; 
    item_html += '<p>' +itemtitle + '</p>';
    item_html += '</div>';
}

var d_names = new Array("zondag", "maandag", "dinsdag",
"woensdag", "donderdag", "vrijdag", "zaterdag");

var m_names = new Array("januari", "februari", "maart", 
"april", "mei", "juni", "juli", "augustus", "september", 
"oktober", "november", "december");

function formatDate( str ) {
	var d = new Date(Date.parse(str));
	var formatted = d_names[d.getDay()] + " " + d.getDate() + " ";
	formatted += m_names[d.getMonth()] + " ";
	formatted += d.getFullYear();
	return formatted;
}

function formatTime( str ) {
	var d = new Date(Date.parse(str));
	var formatted = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
	return formatted;
}

function rss_format(text, descriptionlength) {
  if (text != null && text !='undefined') {
    var pos = text.indexOf("<hr>");
    if (pos >= 0)  text = text.substring(pos+4);
    var pos = text.indexOf("<");
    if (pos >= 0)  text = text.substring(0,pos);
    text = text.substring(0,descriptionlength) + "...";
    text = '<p>'+text+'</p>';    
    return text;
  }
}

function twitter_format(text, descriptionlength) {
  return rss_format(text, descriptionlength);
}

var xhr;

