
(function ($) {
    $.fn.rssfeed = function (url, options, fn) {
        var defaults = { limit: 10, header: true, titletag: 'h4', date: true, content: true, snippet: true, showerror: true, errormsg: '', key: null, ssl: false, linktarget: '_self' }; var options = $.extend(defaults, options); return this.each(function (i, e) {
            var $e = $(e); var s = ''; if (options.ssl) s = 's'; if (!$e.hasClass('rssFeed')) $e.addClass('rssFeed'); if (url == null) return false; var api = "http" + s + "://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q=" + encodeURIComponent(url); if (options.limit != null) api += "&num=" + options.limit; if (options.key != null) api += "&key=" + options.key; api += "&output=json_xml"
            $.getJSON(api, function (data) {
                window.console && console.log(data); if (data.responseStatus == 200) { _process(e, data.responseData, options); if ($.isFunction(fn)) fn.call(this, $e); } else {
                    if (options.showerror)
                        if (options.errormsg != '') { var msg = options.errormsg; } else { var msg = data.responseDetails; }; $(e).html('<div class="rssError"><p>' + msg + '</p></div>');
                };
            });
        });
    }; var _process = function (e, data, options) {
        var feeds = data.feed; if (!feeds) { return false; }
        var html = ''; var row = 'odd'; var xml = getXMLDocument(data.xmlString); var xmlEntries = xml.getElementsByTagName('item'); if (options.header)
            html += '<div class="rssHeader">' + '<a href="' + feeds.link + '" title="' + feeds.description + '">' + feeds.title + '</a>' + '</div>'; html += '<div class="rssBody">' + '<ul class="latest-jobs">'; for (var i = 0; i < feeds.entries.length; i++) {
            var entry = feeds.entries[i]; var pubDate; if (entry.publishedDate) { var entryDate = new Date(entry.publishedDate); var pubDate = entryDate.toLocaleDateString()/* + ' ' + entryDate.toLocaleTimeString()*/; }
            html += '<li class="rssRow ' + row + '">' + '<' + options.titletag + '><a href="' + entry.link + '" title="View this feed at ' + feeds.title + '" target="' + options.linktarget + '">' + entry.title + '</a></' + options.titletag + '>'
            if (options.date && pubDate) html += '<span>Closing Date ' + getClosingDate(entry.content) + '</span>'
            if (options.content) {
                if (options.snippet && entry.contentSnippet != '') { var content = entry.contentSnippet; } else { var content = entry.content; }
                html += '<p>' + content + '</p>'
            }
            if (xmlEntries.length > 0) {
                var xmlMedia = xmlEntries[i].getElementsByTagName('enclosure'); if (xmlMedia.length > 0) {
                    html += '<div class="rssMedia"><div>Media files</div><ul class="latest-jobs">'
                    for (var m = 0; m < xmlMedia.length; m++) { var xmlUrl = xmlMedia[m].getAttribute("url"); var xmlType = xmlMedia[m].getAttribute("type"); var xmlSize = xmlMedia[m].getAttribute("length"); html += '<li><a href="' + xmlUrl + '" title="Download this media">' + xmlUrl.split('/').pop() + '</a> (' + xmlType + ', ' + formatFilesize(xmlSize) + ')</li>'; }
                    html += '</ul></div>'
                }
                html += '</li>';
            }
            if (row == 'odd') { row = 'even'; } else { row = 'odd'; }
        }
        html += '</ul>' + '</div>'
        $(e).html(html);
    };

    function formatFilesize(bytes) {
        var s = ['bytes', 'kb', 'MB', 'GB', 'TB', 'PB']; var e = Math.floor(Math.log(bytes) / Math.log(1024)); return (bytes / Math.pow(1024, Math.floor(e))).toFixed(2) + " " + s[e];
    }

    function getXMLDocument(string) {
        var browser = navigator.appName; var xml; if (browser == 'Microsoft Internet Explorer') {
            xml = new ActiveXObject('Microsoft.XMLDOM'); xml.async = 'false'
            xml.loadXML(string);
        } else { xml = (new DOMParser()).parseFromString(string, 'text/xml'); }
        return xml;
    }

    function getClosingDate(descriptionText) {
        var startPos = descriptionText.indexOf("Close date:") + 12;
        var closingDate = descriptionText.substring(startPos, descriptionText.length);
        var daysLong = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
        var daysShort = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
        var monthsShort = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
        var monthsLong = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
        var weekDay = "";
        var numberDay = "";
        var month = "";

        //week day - long
        for (var i = 0; i <= 6; i++) {
            if (closingDate.substring(0, 3) == daysShort[i]) {
                weekDay = daysLong[i];
            }
        }

        //day number + 2 character suffix        
        if (closingDate.substring(5, 7) == "01" || closingDate.substring(5, 7) == "21" || closingDate.substring(5, 7) == "31") {
            numberDay = closingDate.substring(5, 7) + "st";
        }
        else if (closingDate.substring(5, 7) == "02" || closingDate.substring(5, 7) == "22") {
            numberDay = closingDate.substring(5, 7) + "nd";
        }
        else if (closingDate.substring(5, 7) == "03" || closingDate.substring(5, 7) == "23") {
            numberDay = closingDate.substring(5, 7) + "rd";
        }
        else {
            numberDay = closingDate.substring(5, 7) + "th";
        }

        //month - long 
        for (var i = 0; i <= 11; i++) {
            if (closingDate.substring(8, 11) == monthsShort[i]) {
                month = monthsLong[i];
            }
        }        

        return weekDay + ", " + numberDay + " " + month + " " + closingDate.substring(12, 16);
    }
})(jQuery);
