﻿function readNewsFeed(limit) {
    requestCrossDomain('http://www.ir-site.com/QNSData/?ticker=FMD', function (result) {
        var num = 1;

        var browserName = navigator.appName;
        var doc;
        if (browserName == 'Microsoft Internet Explorer') {
            doc = new ActiveXObject('Microsoft.XMLDOM');
            doc.async = 'false'
            doc.loadXML(result.results);
        } else {
            doc = (new DOMParser()).parseFromString(result.results, 'text/xml');
        }
        var xml = doc;


        $(xml).find('news').each(function () {

            if (num <= limit) {
                var date = $(this).attr('date');
                var headlines = $(this).find('headlines').text();
                var link = $(this).find('link').text();

                if (headlines.length > 100) { headlines = headlines.substring(0, 103) + "..."; }

                var content = "<p>" + headlines + "</p><a class='more' href='" + link + "'>continue reading</a>";
                $("#news" + num).html(content);
                num++;
            }
        });
    });  
}

// Accepts a url and a callback function to run.
function requestCrossDomain(site, callback) {

    // If no url was passed, exit.
    if (!site) {
        alert('No site was passed.');
        return false;
    }

    // Take the provided url, and add it to a YQL query. Make sure you encode it!
    var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from xml where url="' + site + '"') + '&format=xml&callback=?';

    // Request that YSQL string, and run a callback function.
    // Pass a defined function to prevent cache-busting.
    $.getJSON(yql, cbFunc);

    function cbFunc(data) {
        // If we have something to work with...
        if (data.results[0]) {
            if (typeof callback === 'function') {
                callback(data);
            }
        }
        // Else, Maybe we requested a site that doesn't exist, and nothing returned.
        else throw new Error('Nothing returned from getJSON.');
    }
}
