addLoadEvent(init);

var showDate;
var iTunes;
iTunes = false;
showDate = false;
var request;

// Define some namespaces commonly used in feeds
var NS_DC = "http://purl.org/dc/elements/1.1/";
var NS_CONTENT = "http://purl.org/rss/1.0/modules/content/";
var NS_XHTML = "http://www.w3.org/1999/xhtml";


function init(){
rssForm();

getRSS('appl');

}

function createRequest(url) {
   
	request = false;
    // branch for native XMLHttpRequest object
    if(window.XMLHttpRequest) {
    	try {
			request = new XMLHttpRequest();
        } catch(e) {
			request = false;
        }
    // branch for IE/Windows ActiveX version
    } else if(window.ActiveXObject) {
       	try {
        	request = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		request = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		request = false;
        	}
		}
    }
	if(request) {
	    request.onreadystatechange = updatePage;
		request.open("GET", url, true);
		request.send("");
		return url;
	}
}

function getRSS(str) {
var url="http://www.commandertrombone.com/getrss3.php";
if(str == "Choose RSS Feed...") {
return false;
} else {

url=url+"?q="+str
url = url + "&dummy=" + new Date().getTime();
var itms = str.indexOf("appl");
if(itms != -1){
iTunes = true;
}
createRequest(url);
}
 }
     

function updatePage() {
var theSpin = document.getElementById('spinner');
theSpin.style.display = "block";
if(request.readyState == 4){  
if (request.status == 200) {
theSpin.style.display = "none";
var theText = request.responseText;
var xmlDoc = request.responseXML;
var doc = xmlDoc.documentElement;
clearAll(document.getElementById('feed'));
clearAll(document.getElementById('feedtitle'));
var results;
if (doc.tagName.toLowerCase() == "feed") {
             
             results = parseAtomFeed(doc);
             addEntriesToContents(results);
             } else {
            writeRSSFeed(xmlDoc, theText);
        }

      }
 } 
 
}





function writeRSSFeed(xmlDoc, theText)  { 

var title = xmlDoc.getElementsByTagName('title')[0];

var link = xmlDoc.getElementsByTagName('link')[0];


if(title.childNodes.length >0)
{
var thisFeedtxt = xmlDoc.getElementsByTagName('title')[0].firstChild.nodeValue;
} else {
 var thisFeedtxt = "No RSS Title!";
}

if(link.childNodes.length >0){
var thisFeedlink = xmlDoc.getElementsByTagName('link')[0].firstChild.nodeValue;
} else {
var thisFeedlink = null;
}


var newFeed = document.getElementById('feed');
var feedDivTitle = document.getElementById('feedtitle');
var feedH = document.createElement('h1');
var feedA = document.createElement('a'); 
feedA.setAttribute('href', thisFeedlink);
var feedHed = document.createTextNode(thisFeedtxt);
feedA.appendChild(feedHed);
feedH.appendChild(feedA);
feedDivTitle.appendChild(feedH);
var allItems = xmlDoc.getElementsByTagName('item');

for (var i=0; i<allItems.length; i++){

var Leadtxt = getTextNode(allItems[i], 'title');
var Linktxt = getTextNode(allItems[i], 'link');
var Desctxt = getTextNode(allItems[i], 'description');


//Clip out ads for NYT
if(Desctxt.indexOf('<br') != -1){
var Clipstring = Desctxt.indexOf('<br');
Desctxt = Desctxt.substring(0, Clipstring);
}


var Pubtxt = getTextNode(allItems[i], 'pubDate');
var Authtxt = getTextNode(allItems[i], 'creator');

//create elements
var oneHed = document.createElement('h3');
var oneDesc = document.createElement('p');
var oneLink = document.createElement('a');
var onePub = document.createElement('span');

var oneAuth = document.createElement('span');
var theAuth = document.createTextNode(Authtxt);
oneAuth.className = "by";

//add link URL attribute
oneLink.setAttribute('href', Linktxt); 
//create document text nodes
var thisHed = document.createTextNode(Leadtxt);
var theCopy = document.createTextNode(Desctxt); 
var thePub = document.createTextNode(Pubtxt); 
onePub.className = "date";
//append elements to text nodes
oneLink.appendChild(thisHed);
oneHed.appendChild(oneLink);


oneDesc.innerHTML = Desctxt;


onePub.appendChild(thePub);

oneAuth.appendChild(theAuth);

//actually add to feed div here
newFeed.appendChild(oneHed);

newFeed.appendChild(oneAuth);

newFeed.appendChild(onePub);
newFeed.appendChild(oneDesc);
}
 }
 

function rssForm() {
var rssForm = document.getElementById('rssform');
if(rssForm != null)
{
return;
} else {
//for nyt
var nyt = Array(); 

var nytEnv = Array();
nytEnv['name'] = 'NYT > Environment';
nytEnv['url'] = 'nytenviro';
nyt[0] = nytEnv;
var nytTech = Array();
nytTech['name'] = 'NYT > Technology';
nytTech['url'] = 'nyttech';
nyt[1] = nytTech;
var nytTv = Array();
nytTv['name'] = 'NYT > Television';
nytTv['url'] = 'nyttv';
nyt[2] = nytTv;
var nytThr = Array();
nytThr['name'] = 'NYT > Theater';
nytThr['url'] = 'nyttheater';
nyt[3] = nytThr;
var nytMv = Array();
nytMv['name'] = 'NYT > Movies';
nytMv['url'] = 'nytmv';
nyt[4] = nytMv;
var nytMu = Array();
nyt[5] = nytMu;
nytMu['name'] = 'NYT > Music';
nytMu['url'] = 'nytmus';

var npr = Array(); 

var nprArt = Array();
nprArt['name'] = 'NPR: Arts & Culture';
nprArt['url'] = 'nprarts';
npr[0] = nprArt;
var nprJazz = Array();
nprJazz['name'] = 'NPR: Jazz & Blues';
nprJazz['url'] = 'nprjazz';
npr[1] = nprJazz;
var nprPea = Array();
nprPea['name'] =  'NPR: People & Places';
nprPea['url'] = 'nprpeople';
npr[2] = nprPea;
var nprWesat = Array();
nprWesat['name'] = 'NPR: W E Saturday';
nprWesat['url'] = 'nprwesat';
npr[3] = nprWesat;       
var nprWesun = Array();
nprWesun['name'] = 'NPR: W E Sunday';
nprWesun['url'] = 'nprwesun';
npr[4] = nprWesun; 

var mr = Array();

var mrMov = Array();
mrMov['name'] = 'Rotten Tomatoes: Movies';
mrMov['url'] = 'rttomato';
mr[0] = mrMov;

var appl = Array();

var apple = Array();
apple['name'] = 'Top Jazz Albums';
apple['url'] = 'appl';
appl[0] = apple;
var applejz = Array();
applejz['name'] = 'Top Jazz Songs';
applejz['url'] = 'appljz';
appl[1] = applejz;


var theForm = document.createElement('form'); 
theForm.setAttribute('id','rssform');
theForm.setAttribute('action', 'ajrss.js'); // path to script should be correct here!
var theSelection = document.createElement('select'); 
theSelection.setAttribute('name','selectrss');
theForm.appendChild(theSelection);
var topOpt = document.createElement('option'); 
var topTxt = document.createTextNode('Choose RSS Feed...');
topOpt.appendChild(topTxt);
theSelection.appendChild(topOpt);
var nytGrp = document.createElement('optgroup'); 
nytGrp.setAttribute('label','New York Times');
var nprGrp = document.createElement('optgroup');
nprGrp.setAttribute('label','National Public Radio');

var appleGrp = document.createElement('optgroup');
appleGrp.setAttribute('label','iTunes');


var mrGrp = document.createElement('optgroup'); 
mrGrp.setAttribute('label','More...');


addOptions(nyt, nytGrp);
addOptions(npr, nprGrp);
addOptions(mr, mrGrp);
addOptions(appl, appleGrp);



theSelection.appendChild(nytGrp);
theSelection.appendChild(nprGrp);
theSelection.appendChild(appleGrp);
theSelection.appendChild(mrGrp);


var brk = document.createElement('br');
theForm.appendChild(brk);
var ctrlBut = document.createElement('input');
ctrlBut.setAttribute('type', 'button');
ctrlBut.setAttribute('value', 'Go!');
ctrlBut.className = 'go';
ctrlBut.onclick = function(){
getRSS(theSelection.value);
}
theForm.appendChild(ctrlBut);
}

var newSpin = document.createElement('img');
newSpin.setAttribute('id','spinner');
newSpin.setAttribute('src','/images/ajax-loader.gif');

var newRss = document.getElementById('rss');
var curTitleDiv = document.getElementById('feedtitle');
newRss.insertBefore(theForm, curTitleDiv);

newRss.insertBefore(newSpin, curTitleDiv);

}


function clearAll(el) {
	while(el.firstChild) el.removeChild(el.firstChild);
}



//
// Function: parseAtomFeed(atom)
// Parse an Atom feed.
//
// atom: Atom feed as an XML document.
//
// Returns the parsed results array.
//
function parseAtomFeed(atom)
{
    // Check for a global base URL
    var base = atom.getAttribute("xml:base");
    if (base) {
        feed.baseURL = splitURL(base);
    }

    
    var titleTxt = getTextNode(atom, 'title');
    var lnkObj = atom.getElementsByTagName('link')[0];
    //var lnkTxt = lnkObj.getAttribute('href');
    
    var lnkTxt= 'http://click.linksynergy.com/fs-bin/stat?id=3XO2i140ohg&offerid=146261&type=3&subid=0&tmpid=1826&RD_PARM1=http%253A%252F%252Fitunes.apple.com%252FWebObjects%252FMZStore.woa%252Fwa%252FviewTop%253Fid%253D12%2526popId%253D11%2526partnerId%253D30'

    
    var thisHed = document.createTextNode(titleTxt);
    var titleLink = document.createElement('a');
    titleLink.setAttribute('href', lnkTxt); 
    
    
    
    var atomHed = document.createElement('h1');
    atomHed.appendChild(thisHed);
    

    
    titleLink.appendChild(atomHed);
    
    var newTitle = document.getElementById('feedtitle');
    
    newTitle.appendChild(titleLink);
    
    //Fix Link for Title
    
     var results = new Array;

    // For each element, get title, link and publication date.
    // Note that all elements of an item are optional.
    for (var item = atom.firstChild; item != null; item = item.nextSibling) {
        if (item.nodeName == "entry") {
            var title = atomTextToHTML(findChild(item, "title"));

            // we have to have the title to include the item in the list
            if (title) {
                // Just get the first link for now - Atom is complicated
                var link;
                var linkElement = findChild(item, "link");
                if (linkElement) {
                    link = linkElement.getAttribute("href");
                }

                // Try a few different ways to find a date
                var dateEl = findChild(item, "updated")
                    || findChild(item, "issued") 
                    || findChild(item, "modified")
                    || findChild(item, "created");
                var itemDate = parseDate(allData(dateEl));

                var description;
                var descElt = findChild(item, "content") || findChild(item, "summary");
                if (descElt) {
                    description = atomTextToHTML(descElt);
                }

                results[results.length] = {
                    title: title,
                    link: link,
                    date: itemDate,
                    description: description
                }
            }
        }
    }

    return results;
}


//
// Function: atomTextToHTML(element)
// Extracts the content of an atom text construct as HTML for display
//
// element: an Atom element containing an atomTextConstruct per RFC4287
//
// Returns an HTML div Element node containing the HTML
//
function atomTextToHTML(element)
{
    if (!element) {
        return;
    }

    var html;

    var type = element.getAttribute("type");
    if (type && (type.indexOf("xhtml") > -1)) {
        // The spec says there should be a DIV in the XHTML namespace
        var div = findChild(element, "div", NS_XHTML);
        if (div) {
            html = div.cloneNode(true);
        }
    }
    else if (type && (type.indexOf("html") > -1)) {
        // Encoded HTML
        html = document.createElement("div");
        html.innerHTML = allData(element);
    }
    else {
        // Plain text
        html = document.createElement("div");
        var elementText = allData(element);
        elementText = elementText.replace(/^\s+/, "");
        elementText = elementText.replace(/\s+$/, "");
        html.innerText = elementText;
    }

    return html;
}

//
// Function: findChild(element, nodeName, namespace)
// Scans the children of a given DOM element for a node matching nodeName, optionally in a given namespace.
//
// element: The DOM element to search.
// nodeName: The node name to search for.
// namespace: Optional namespace the node name must be in.
//
// Returns the child node if found, otherwise null.
//
function findChild(element, nodeName, namespace)
{
    var child;

    for (child = element.firstChild; child != null; child = child.nextSibling) {
        if (child.localName == nodeName) {
            if (namespace == null || child.namespaceURI == namespace)
                return child;
        }
    }

    return null;
}

//
// Function: createDateStr(date)
// Generate a date label from a JavaScript date.
//
// date: JavaScript date object
//
// Returns a string containing the short date.
//
function createDateStr(date)
{
    var month;
    switch (date.getMonth()) {
        case 0: month = "Jan"; break;
        case 1: month = "Feb"; break;
        case 2: month = "Mar"; break;
        case 3: month = "Apr"; break;
        case 4: month = "May"; break;
        case 5: month = "Jun"; break;
        case 6: month = "Jul"; break;
        case 7: month = "Aug"; break;
        case 8: month = "Sep"; break;
        case 9: month = "Oct"; break;
        case 10: month = "Nov"; break;
        case 11: month = "Dec"; break;
    }
    return month + " " + date.getDate();
}



//
// Function: addEntriesToContents(entries)
// Take the parsed results and display them in the content area.
//
// entries: Array of items to display.
//
function addEntriesToContents(entries)
{
    // copy title and date into rows for display. Store link so it can be used when user
    // clicks on title
    nItems = entries.length;

    var contentElement = document.getElementById("feed");
    for (var i = 0; i < nItems; ++i) {
        var item = entries[i];
        var row = createRow(item.title, item.link, item.date, item.description, i);

        contentElement.appendChild(row);
    }
}


//
// Function: splitURL(url)
// Split components of the URL (protocol, domain, resource)
//
// url: URL to split
//
function splitURL(url)
{
    var baseURL = { protocol: "", domain: "", resource: "" };
    if (!url || url.length < 1) {
        return baseURL;
    }

    var components = url.split("://");
    baseURL.protocol = components[0];
    var slashIndex = components[1].indexOf("/");
    if (slashIndex >= 0) {
        baseURL.domain = components[1].substring(0, slashIndex);
        baseURL.resource = components[1].substring(slashIndex + 1, components[1].length);
    }
    else {
        baseURL.domain = components[1];
    }

    return baseURL;
}


//
// Function: parseDate(dateToParse)
// Parse a date string in several formats into a Date object
//
// dateToParse: String containing a date.
//
// Returns a Date object containing the parsed date.
//
function parseDate(dateToParse)
{
    var returnDate = null;
    if (!dateToParse || dateToParse.length < 1) {
        return null;
    }
    
    // try to parse as date string
    returnDate = new Date(dateToParse);

    // if no success, try other formats
    if ((!returnDate || isNaN(returnDate.valueOf()))) {
        var dateTimeSeparator = null;
        var monthIndex = null;
        var dayIndex = null;
        var yearIndex = null;
        // try ISO 8601 format (YYYY-MM-DDTHH:MM:SS+OO:OO)
        if (dateToParse.match(/^\d\d\d\d-\d\d-\d\d/)) {
            dateTimeSeparator = "T";
            monthIndex = 1;
            dayIndex = 2;
            yearIndex = 0;
        }
        // try other format (MM-DD-YYYY HH:MM:SS)
        else if (dateToParse.match(/^\d\d-\d\d-\d\d\d\d/)) {
            dateTimeSeparator = " ";
            monthIndex = 0;
            dayIndex = 1;
            yearIndex = 2;
        }
        
        // if the date format was recognized, parse it
        if (dateTimeSeparator) {
            returnDate = new Date();
            // separate date and time
            var dateTime=dateToParse.split(dateTimeSeparator);

            // set the date
            var dateArray = dateTime[0].split("-");
            if (dateArray[monthIndex]) returnDate.setMonth(dateArray[monthIndex]-1);
            if (dateArray[dayIndex]) returnDate.setDate(dateArray[dayIndex]);
            if (dateArray[yearIndex]) returnDate.setYear(dateArray[yearIndex]);

            // split time and offset
            var timeArray = null;
            if (dateTime[1]) timeArray = dateTime[1].match(/(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:([+-])(\d\d):(\d\d))?/);
            if (timeArray) {
                // set the time
                if (timeArray[1]) returnDate.setHours(timeArray[1]);
                if (timeArray[2]) returnDate.setMinutes(timeArray[2]);
                if (timeArray[3]) returnDate.setSeconds(timeArray[3]);

                // add the offset
                if (timeArray[4] && timeArray[5]) {
                    var time = returnDate.getTime() - returnDate.getTimezoneOffset() * 60000;
                    if (timeArray[4] == "+")
                        time -= timeArray[5] * 3600000;
                    else
                        time += timeArray[5] * 3600000;
                    returnDate.setTime(time);
                }
            }
        }
    }

    // if no success, return null
    if (returnDate && isNaN(returnDate.valueOf())) {
        returnDate = null;
    }

    return returnDate;
}


//
// Function: createRow(title, link, date, description, index)
// Generate a new row for the content area.
//
// title: Article's title.
// link: Article's link.
// date: Article's date.
// description: Article's description.
// index: Row number for even/odd hilighting.
//
// Returns the created DIV element
//
function createRow(title, link, date, description, index)
{
    // create a DIV for the article
    var article = document.createElement("div");
    article.setAttribute("class", "article " + (index % 2 ? "even" : "odd"));
    // if it is not the first article, include a separation line
    if (index > 0) {
        var articleseparator = document.createElement("div");
        articleseparator.setAttribute("class", "articleseparator");
        article.appendChild(articleseparator);
    }

    // optionally, make the title a link
    var articlehead;
    if (link && link.length) {
        // if it is a relative link, make it absolute
        if (link.indexOf(":") < 0) link = absoluteURL(link);
        // set the link
        articlehead = document.createElement("a");
        articlehead.setAttribute("href", link);
    }
    else {
        articlehead = document.createElement("span");
    }
    articlehead.setAttribute("class", "articlehead");

    // title of the article
    var subjectElt = makeEntryDiv(title);
    subjectElt.setAttribute("class", "subject");
    articlehead.appendChild(subjectElt);

    // date of the article
    if (date != null && !isNaN(date.valueOf())) {
        var dateDiv = document.createElement("div");
        dateDiv.setAttribute ("class", "date");
        if (showDate) {
            dateDiv.innerText = createDateStr(date);
        }

        articlehead.appendChild(dateDiv);
    }

    article.appendChild(articlehead);

    // main body of the article
    if (description != null) {
        var descElt = makeEntryDiv(description);
        descElt.setAttribute("class", "articlebody");

        article.appendChild(descElt);
    }
    
if(iTunes == true){
 fixLinks(article);
 }

   return article;
}

//
// Function: makeEntryDiv(content)
// Formats an entry's content as a div for display
//
// content: string or element containing an entry
//
function makeEntryDiv(content)
{
    var div;

    if (typeof content == "string") {
        // If it's a plain string, wrap it in a div
        div = document.createElement("div");
        div.innerHTML = content;
    }
    else {
        div = content;
    }

    return div;
}


//
// Function: allData(node)
// Concatenate all the text data of a node's children.
//
// node: DOM element to search for text.
//
// Returns the concatenated text.
//
function allData(node)
{
    var data = "";
    if (node && node.firstChild) {
        node = node.firstChild;
        if (node.data) data += node.data;
        while (node = node.nextSibling) {
            if (node.data) data += node.data;
        }
    }

    return data;
}


function fixLinks(htmlFragment)
{
    var trklnk = 'http://click.linksynergy.com/fs-bin/stat?id=3XO2i140ohg&offerid=146261&type=3&subid=0&tmpid=1826&RD_PARM1=';
    
    var links = htmlFragment.getElementsByTagName("a");
    for (var i = 0; i < links.length; i++) {
    thisLnk = links[i].href;
    var tmpLnk = thisLnk.split('?');
    
    var tmpLnk = tmpLnk[0] + '?partnerId=30&siteID=1494688';
    
    var tmpLnk = encodeURIComponent(tmpLnk);
    
    var tmpLnk = encodeURIComponent(tmpLnk);
    
    
    links[i].href = trklnk + tmpLnk;
        
    }
}

//Used for RSS parse

function getTextNode(eL, eChild){
var eArray = eL.getElementsByTagName(eChild);
if (eArray.length > 0 && eArray[0].childNodes.length >0) {
var cTxt  = eArray[0].firstChild.nodeValue;
} else {
var cTxt = "";
}
return cTxt;
}

// The array, the group

function addOptions(arr, grp){

for (var index=0; index< arr.length; index++) {
var tmpOpt = document.createElement('option');
tmpOpt.setAttribute('value', arr[index].url);
var tmpTxt = document.createTextNode(arr[index].name);
tmpOpt.appendChild(tmpTxt);
grp.appendChild(tmpOpt);
}

  }

























