/* 
 This file was generated by Dashcode.  
 You may edit this file to customize your widget or web page 
 according to the license.txt file included in the project.
 */

// The podcast feed, as obtained from attributes.js
var feed = attributes.podcastURL.replace(/^(itpc|pcast|feed):/i, "http:");

var xmlRequest = null;             // The current XMLHttpRequest
var results = new Array;           // The saved, parsed results of the request, used to store the episodes

//
// Function: podcastLoad()
// Called when the widget loads.  Clears out placeholder text on the widget.
// Adds an invisible <select> used to populate the episode name menu.
//
function podcastLoad()
{
    if (attributes.podcastURL == "") {
            showError("No Podcast specified\nProvide a Podcast URL in Application Attributes");
    }
    else {
        var now = (new Date).getTime();

        if(xmlRequest) {
            xmlRequest.abort();
            xmlRequest = null;
        }
        xmlRequest = new XMLHttpRequest();

        xmlRequest.onload = function(e) {
            if (xmlRequest.status == 200) {
                processFeed(e, xmlRequest);
            }
            else {
                showError("No Podcast Available");
            }
        };
        try{
            xmlRequest.overrideMimeType("text/xml");
            xmlRequest.open("GET", feed);
            xmlRequest.setRequestHeader("Cache-Control", "no-cache");
            xmlRequest.send(null);        
        } catch (e) {
            if( e == "Error: Permission denied" ){
                showError("Podcast not available.  The Podcast URL must be from the same source as your web application.");
            }else{
                showError("Podcast not available.");
            }
            return false;
        }
    }
}

//
// Function: findChild(element, nodeName)
// Scans the children of a given DOM element for a node matching nodeName.
//
// element: The DOM element to search.
// nodeName: The node name to search for.
//
function findChild(element, nodeName)
{
    var child;

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

    return null;
}

//
// Function: processFeed(e, request)
// Extract the content of the podcast RSS feed and store the data in a results array.
//
// e: onLoad event from XMLHttpRequest
// request: xmlHttpRequest containing the feed
//
function processFeed(e, request)
{
    xmlRequest = null;
    if (request.responseXML) {
        // Clear the results array
        while(results.length > 0) {
            results.pop();
        }

        // Get the top level <rss> element
        var rss = findChild(request.responseXML, 'rss');
        if (!rss) return;

        // Get single subordinate channel element
        var channel = findChild(rss, 'channel');
        if (!channel) return;

        // Get all item elements subordinate to the channel element.
        // For each element, get title, pubDate, subtitle, description, and episode URL.
        for (var item = channel.firstChild; item != null; item = item.nextSibling) {
            if (item.nodeName == 'item') {
                var title = findChild (item, 'title');

                // we have to have the title to include the item in the list
                if (title) {
                    var title = findChild(item, 'title');
                    if (!title || !title.firstChild) {
                        title = "No episode title provided";
                    }
                    else {
                        title = title.firstChild.data;
                    }

                    var date = findChild(item, 'pubDate');
                    var dateString = null;
                    if (!date || !date.firstChild) {
                        dateString = null;
                        date = null;
                    }
                    else {
                        dateString = date.firstChild.data;
                        date = new Date(Date.parse(date.firstChild.data));
                    }

                    var description = findChild(item, 'description');
                    if (!description || !description.firstChild) {
                        description = "No episode description provided";
                    }
                    else {
                        description = description.firstChild.data;
                    }

                    var subtitle = findChild(item, 'itunes:subtitle');
                    if (!subtitle || !subtitle.firstChild) {
                        subtitle = description;
                    }
                    else {
                        subtitle = subtitle.firstChild.data;
                    }

                    var link = findChild (item, 'link');
                    if (!link) {
                        link = null;
                    }
                    else {
                        link = link.firstChild.data;
                    }

                    var enclosure = findChild(item, 'enclosure');
                    if (!enclosure) {
                        // if there's no enclosure, there's no episode to play; ignore the entry and move on.
                        continue;
                    }
                    else {
                        enclosure = enclosure.getAttribute('url');
                    }

                    results[results.length] = {
                        title: title,
                        date: date,
                        dateString: dateString,
                        subtitle: subtitle,
                        description: description,
                        link: link,
                        track: enclosure
                    };
                }
            }
        }

        // Sort by date
        results.sort(function (a, b) { return b.date - a.date; });
    }
    
    displayTitles();
}

//
// Function: createDateStr(date)
// Creates a readable date string from the provided Date object.
//
// date: JavaScript Date object to format
//
function createDateStr(date)
{
    if (!date) {
        return "??/??";
    }

    var day = date.getDate();
    var month = (date.getMonth()) + 1; // add one since Date returns 0-11 month values

    if (day == "" && month == "") {
        return "??/??";
    }
    else {
        return month + "/" + day;
    }
}

//
// Function: stripTags(aString)
// Removes any extra HTML tags that may be strewn about the response XML.
//
// aString: string to strip the tags from
//
function stripTags(aString)
{
    return aString.replace(/<[^>]*>/g, "");
}

//
// Function: extractText(content)
// Pulls text out of div elements
//
// content: string or element containing an entry
//
function extractText(content)
{
    var extractedString;

    if (typeof content == "string") {
        extractedString = content;
    }
    else {
        extractedString = content.innerText;
    }
    extractedString = extractedString.replace(/\n/g," ");
    
    return extractedString;
}


//
// Function: showError(errorString)
// Show an error in a red box
//
// errorString: string to be displayed
//
function showError(errorString)
{
    document.getElementById("stackLayout").object.setCurrentView("episodeList", false);

    var errorDiv;
    errorDiv = document.createElement("div");
    errorDiv.innerText = errorString;
    errorDiv.setAttribute("style", "position: absolute; border-style: solid; border-width: 1px; right: 10px; left: 10px; top: 120px; background-color: rgb(32, 32, 32); border-color: rgb(0, 0, 0); -webkit-border-radius: 10px 10px; text-align: center; padding: 15px; font-family: Helvetica; font-weight: bold; color: rgb(255, 255, 255); font-size: 15px; text-shadow: rgb(0, 0, 0) 0px -1px 0px;");
    document.getElementById("episodeList").appendChild(errorDiv);
}


