/**
* Basic reader to pull information from webservice and display it. URLS are limited to trusted sources.
* Options:
		rssFeedUrl: where to make the ajax request to,
        urls: the urls of the rss feeds that you would like to gather,
        title: Use "" for system Generated Title,
        description: Use "" for system Generated Description,
        maxNb: Max number of records returned,
        maxDescLng:Max length of each entries description,
        allFeedsNmb: Max number of records from each url/feed,
        pullFirstFullFeedOnly: if True it only pulls the first feed with any Entries, False Pulls feeds until maxNb is reached.,
        maxDescTruncate: if true, truncates Entries Description Length,
        limitTotalResults: if true it will Limit the Max Number of Entry records returned,
        pullLimitedFromAllFeeds: if true, will limit the Max Number of Entry records retuned from each urls/feeds,
        showErrors: Shows Errors on the screen for users to see,
        newWindow: If set to true Links the widgets produces from the RSS feed will open in a new window,
        showLoading: If set to true a loading icon will appear while waiting for the ajax request.
        hideOnNoEntries: Hides the entire element if there are no entries. Default: true
*
*@author bollama -NGC
*@version 1.0
*/

(function($) {
    //Coding Standards: http://www.jameswiseman.com/blog/2010/04/20/jquery-standards-and-best-practice/
    //and from http://www.learningjquery.com/2007/10/a-plugin-development-pattern

    $.fn.rssfeedreader = function(opts){
        if (opts && typeof (opts) === "string") {
            var args = [];
            for (var i = 1; i < arguments.length; i++) {
                args.push(arguments[i]);
            }
            var htmlarea = jHtmlArea(this[0]);
            var f = htmlarea[opts];
            if (f) {
                return f.apply(htmlarea, args);
            }
        }
        return this.each(function() {
            jRSSFeedReader(this, opts);
        });
    };
    var jRSSFeedReader = window.jRSSFeedReader = function(elem, options){
        if (elem.jquery) {
            return jRSSFeedReader(elem[0]);
        }
        if (elem.jrssfeedreaderObject) {
            return elem.jrssfeedreaderObject;
        } else {
            return new jRSSFeedReader.fn.init(elem, options);
        }

    };
    jRSSFeedReader.fn = jRSSFeedReader.prototype = {
        //Current Version
        jrssfeedreader: "1.0.3",

        init: function(elem, options){
            if(elem.nodeName.toLowerCase() === "div"){
                var opts = $.extend({}, jRSSFeedReader.defaultOptions, options);
                var divArea = this.divArea = $(elem);
                var jFeedArea = this.jFeedArea = $("<div>").addClass("jRSSFeedReader");
                $(divArea).append(jFeedArea);

                priv.initPullRSSFeed.call(this, opts);
            }
        }
    };

    jRSSFeedReader.fn.init.prototype = jRSSFeedReader.fn;

    jRSSFeedReader.defaultOptions = {
        rssFeedUrl: "/CareersRSS/WebService/RSSAgrigator",
        urls: "",
        title: "",
        description: "",
        maxNb: 25,
        maxDescLng:25,
        allFeedsNmb: 9,
        pullFirstFullFeedOnly:false,
        maxDescTruncate: false,
        limitTotalResults:false,
        pullLimitedFromAllFeeds: false,
        showErrors: true,
        newWindow: false,
        showLoading: true,
        hideOnNoEntries: true
    };

    var priv = {
        initPullRSSFeed: function(options){
            var that = this;

            var SUCCESS = "successful";
            var FAILURE = "failure";
            var WARNING = "warning";
            var STATUS = "status";
            var STATUS_MSG = "statusMsg";


            function getTransferObject(options){
                var rtv = new Object();
                rtv.urls = options.urls;
                rtv.title = options.title;
                rtv.description = options.description;
                rtv.maxNb = options.maxNb;
                rtv.maxDescLng = options.maxDescLng;
                rtv.allFeedsNmb = options.allFeedsNmb;
                rtv.pullFirstFullFeedOnly = options.pullFirstFullFeedOnly;
                rtv.maxDescTruncate = options.maxDescTruncate;
                rtv.limitTotalResults = options.limitTotalResults;
                rtv.pullLimitedFromAllFeeds = options.pullLimitedFromAllFeeds;
                return rtv;
            }

            function addErrortoScreen(errorName, description){
                if(options.showErrors){
                    var error = that.error = $("<div>").addClass("error").addClass("roundedCorners").hide();
                    error.append(errorName + ": " + description);
                    that.jFeedArea.append(error);
                    error.fadeIn();
                } else {
                    that.divArea.hide();
                }
            }

            function addFeedtoScreen(options, data){
                if(data.feed.entries.length > 0){
                    $(that.jFeedArea).hide();
                    var title = that.title = $("<h3>").addClass("title");
                    $(title).append(data.feed.title.toString());
                    that.jFeedArea.append(title);
                    var elementList= that.elementList = $("<ul>").addClass("elementList");
                    that.jFeedArea.append(elementList);
                    var evenNumber = false;
                    $.each(data.feed.entries, function(){
                        var entry = this;
                        var listItem = null
                        //Creating LI
                        if(evenNumber){
                            listItem = $("<li>").addClass("even");
                            evenNumber = false;
                        }else{
                            listItem = $("<li>").addClass("odd");
                            evenNumber = true;
                        }
                        //Making the Link to the title of the entry and adding it to the LI
                        var link = $("<a>").attr("href", entry.link.toString());

                        //Checks to see if should have links open in a new window
                        if(options.newWindow){
                            link.attr("target", "_blank")
                        }

                        $(link).append(entry.title.toString());
                        //                        $(link).append("Test");
                        listItem.append(link);

                        //Creating Sub List of the description below title. If Length 0 doesn't insert ul.
                        if(entry.description.length > 0){
                            var descriptionList = $("<ul>").addClass("listDescription");
                            var descriptionListItem = $("<li>").append(entry.description.toString());
                            descriptionList.append(descriptionListItem);
                            listItem.append(descriptionList);
                        }

                        //Adding completed LI to the total ul
                        elementList.append(listItem);
                    });
                    $(that.jFeedArea).slideDown();
                } else {
                    $(that.jFeedArea).hide();
                }

            }

            function addLoadingDiv(){
                if(options.showLoading){
                    var loading = that.loading = $("<div>").addClass("loading");
                    that.jFeedArea.append(loading);
                }
            }

            function removeLoadingDiv(){
                if(options.showLoading){
                    $(that.loading).remove();
                }
            }



            var toOptions = getTransferObject(options)
            $.ajax({
                data: toOptions,
                //contentType: "application/json; charset=utf-8",
                //page returns JSON object
                dataType: 'json',
                url: options.rssFeedUrl,
                type: "POST",
                //30 Second Timeout
                timeout: 30000,
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    //TODO: Fix error status to represent something
                    removeLoadingDiv();
                    addErrortoScreen(errorThrown, textStatus);
                },
                success: function(data) {
                    //                    var jsonRSSFeed = this.jsonRSSFeed = data;

                    removeLoadingDiv();
                    if(data.status == SUCCESS){
                        addFeedtoScreen(options, data);
                    } else {
                        removeLoadingDiv();
                        addErrortoScreen(data.status, data.statusMsg);
                    }
                },
                //displays loading screen
                beforeSend: function(XMLHttpRequest){
                    addLoadingDiv();
                },
                //refresh results every execute (no storing in a cookie, sends unique number in request)
                cache: false
            });
        }
    };

}(jQuery));
