﻿function getRSS(options){
    $.ajax({
        url:options.url,
        data: options.requestData,
	    dataType:"xml",
        success: function(xmlobject){parseRSS(xmlobject,options)}
	})
}

function parseRSS(xmlobject,options){
    span = document.getElementById(options.targetElement);
    while (span.firstChild) {
       span.removeChild(span.firstChild);
    }
    //Proccess the required channel information	
    var channels = xmlobject.getElementsByTagName('channel');
    var title = xmlobject.getElementsByTagName('title');
    var link = xmlobject.getElementsByTagName('link');
    var description = xmlobject.getElementsByTagName('description');
    if(options.title){
        h = document.createElement('h2');
        a = document.createElement('a');
        a.setAttribute('href',link[0].firstChild.nodeValue);
        a.innerHTML = title[0].firstChild.nodeValue;
        h.appendChild(a);
        span.appendChild(h);
    }
    if(options.description){
        p = document.createElement('p');
        p.innerHTML = description[0].firstChild.nodeValue;
        span.appendChild(p);
    }
    //Process the optional channel information
    if(options.image){
        var imageSrc = xmlobject.getElementsByTagName('url');
        im = document.createElement('img');
        im.setAttribute('src',imageSrc[0].firstChild.nodeValue);
        span.appendChild(im);
    }
    //Create a list to hold list items
    if(options.listTag == "ol"  || options.listTag == "ul"){ 
        list = document.createElement(options.listTag);
    }else{
        list = document.createElement('ul');
    }
    
    //Loop through items of the feed and create the main list
    var items = channels[0].getElementsByTagName('item');
    if(!options.items){
        iterations = items.length;
    }else{
        iterations = Math.min(items.length,options.items);
    }
    for(i = 0 ; i < iterations ; i++){
        //retreive required information from xml
        var linklocation = items[i].getElementsByTagName('link');
        var title = items[i].getElementsByTagName('title');
        var description = items[i].getElementsByTagName('description');
	    //Create list item[i]
        if(linklocation[0].firstChild && title[0].firstChild){
            a = document.createElement('a');
            a.setAttribute('href',linklocation[0].firstChild.nodeValue);
            a.innerHTML = title[0].firstChild.nodeValue;
            li = document.createElement('li');
            li.appendChild(a);
            list.appendChild(li);
        }else{
        li = document.createElement('li');
            if (title[0].firstChild) {
                li.appendChild(document.createTextNode(title[0].firstChild.nodeValue));
                list.appendChild(li);
            }
        }	  
    }
    span.appendChild(list);
}
