(function($) {

    /**
     * Parses news feed document and populates the news div
     *
     * @param xml The RSS document containing the news feed data
     */
    function parseNewsFeed(xml) {
        var feed = $(xml);
        feed.find("item").each(function() {
            var $this = $(this),
                item = {
                    title: $this.find("title").text(),
                    link: $this.find("link").text(),
                    description: snippet($this.find("description").text(), 120),
                    pubDate: new Date($this.find("pubDate").text()).toLocaleDateString()
                };

            $("#news").append(
                $("<div/>").addClass("feedItem").append(
                    $("<h3/>").addClass("headline").append($("<a/>").attr("href", item.link).text(item.title)),
                    $("<div/>").addClass("lastUpdated").text(item.pubDate),
                    $("<p/>").text(item.description).append($("<a/>").attr("href", item.link).attr("title", "Read more about : " + item.title).text("Read More"))
                )
            );
        })
    }

    function snippet(text, max) {
        text = text.replace(/<script/gi, "<!-- ").replace(/<\/script.*?>/gi, "-->");  //Prevent script injection
        text = $("<div/>").html(text).text();                                         //Prevent HTML injection
        return (text.length > max ? text.substr(0, max) : text) + " ... ";
    }

    $(document).ready(function() {
        $("#news").data('ajaxQueue', [
            {
                type: "GET",
                url: "/newsroom/releases/home_feed.xml",
                dataType: "xml",
                cache: false,
                success: parseNewsFeed
            }
        ]).ajaxQueue();
    });

})(jQuery);

