/**
 * Changes the subsite filter on the financial inbox and updates the entry list.
 *
 * @param event         \c object Required DOM Event object.
 * @param sourceElement \c object Required reference to the source HTML element (this).
 * @param siteID        \c int    Requied site ID to filter by.
 * @return void
 */
function financialInboxFilterBySite(event, sourceElement, siteID) {
    $(sourceElement).parent().children('span').each(
        function () {
            $(this).removeClass('active');
        }
    );

    $(sourceElement).addClass('active');

    populateFinancialInbox(siteID);

    return;
}


function populateFinancialInbox(siteID) {
    // Globals.
    ENTRIES = [];
	SITE_ID = siteID;
	
    // Locals.
    var requestData = {};
    var sites = [1, 2, 3, 4];
    var target = $('#financial-inbox > .body');

    jQuery.get(
        '/inboxfeed.php',
        requestData,
        function(data, status) {
        /*
                for (var index in sites) {
                    var id = sites[index];
                }
                */

                var counts = [];

                $(data).find('entry').each(
                    function () {
                        var currentSiteID = $(this).find('site_id').text();

                        if (typeof(counts[currentSiteID]) == 'undefined') {
                            counts[currentSiteID] = 0;
                        }

                        // Site ID does not match the current outer loop (loop through sites, and
                        // then through *all* articles).
                        /*
                        if (currentSiteID != id) {
                            return;
                        }
                        */

                        if (siteID == 0) {
                            if (currentSiteID == 2 && counts[currentSiteID] == 2) { // MMA, 2 articles.
                                return;
                            } else if (currentSiteID != 2 && counts[currentSiteID] == 1) {
                                return;
                            }
                        } else if (currentSiteID != siteID) { // A filter is in effect.
                            return;
                        }

                        var articleID   = $(this).find('id').text();
                        var title       = $(this).find('title').text();
                        var publishDate = $(this).find('publish_date').text();
                        var teaser      = $(this).find('teaser').text();
                        var slug        = $(this).find('slug').text();
                        var ent         = newEntry(currentSiteID, articleID, title, publishDate, teaser, slug);

                        // Save for later.
                        ENTRIES.push(ent);
                        counts[currentSiteID]++;
                    }
                );
			
			// If unfiltered, sort results by date.
			var shouldSort = true;
			for (var i = 0; i < ENTRIES.length; i++) {
				var item = $('.date', $(ENTRIES[i]));
				if (!item.html()) {
					shouldSort = false;
					break;
				}
			}
			String.prototype.trim = function() {return this.replace(/^\s+|\s+$/g,"");}
			if (shouldSort && SITE_ID == 0) ENTRIES = ENTRIES.sort(function(a, b) {
				var arrA = $('.date', $(a)).html().trim().split("/");
				var arrB = $('.date', $(b)).html().trim().split("/");
				
				var dateA = parseInt(arrA[2].trim() + arrA[0].trim() + arrA[1].trim());
				var dateB = parseInt(arrB[2].trim() + arrB[0].trim() + arrB[1].trim());
				
				return dateB - dateA;
			});
			
            // Replace the inbox entries all at once.
            var tempElement = jQuery('<div></div>');
            for (var i = 0; i < ENTRIES.length; i++) {
                tempElement.append(ENTRIES[i]);
            }
            target.html(tempElement.html());
        }
    );

    return;
}


/**
 * Creates a new financial inbox entry.  Returns a jQuery HTML element on success.
 *
 * @param  int siteID    SOA site ID (required).
 * @param  int articleID Article ID (required).
 * @param  string title  Article title (required).
 * @return object
 */
function newEntry(siteID, articleID, title, publishDate, teaser, slug) {
    // Locals.
    var siteName = null;
    var baseURL = null;
    var entry = null;

    // Setup subsite name and base URL.
    if (siteID == 1) {
        siteName = 'High Monthly Income';
        baseURL = '/highmonthlyincome';
    } else if (siteID == 2) {
        siteName = 'Making Money Alert';
        baseURL = '/makingmoneyalert';
    } else if (siteID == 3) {
        siteName = 'ETF Trader';
        baseURL = '/etftrader';
    } else if (siteID == 4) {
        siteName = 'Successful Investing';
        baseURL = '/successfulinvesting';
    }


    if (articleID == 0) {
        entry = jQuery(
            '<div class="entry subscribe">'
            + '    <div class="title">'
            + '        <a href="' + baseURL + '/">' + title + '</a>'
            + '    </div>'
            + '    <div class="subscribe">'
            + '        <a href="' + baseURL + '/">Subscribe</a>'
            + '    </div>'
            + '    <div class="subtitle">'
            + '        ' + siteName
            + '    </div>'
			+ '	   <div class="date" style="display:none">'
			+ '	       ' + publishDate
			+ '	   </div>'
            + '    <div class="body">'
            //+ '        Subscribe to see our latest recommendation'
            + '    </div>'
			
            //+ '    <div class="body">'
            //+ '        ' + teaser
            //+ '        <span>'
            //+ '            &#8230;'
            //+ '        </span>'
            //+ '    </div>'

            //+ '    <div class="body">'
            //+ '        ' + teaser
            //+ '        <span>'
            //+ '            &#8230;'
            //+ '        </span>'
            //+ '    </div>'
            //+ '    <div class="readmore">'
            //+ '        <div class="contents">'
            //+ '            Read More'
            //+ '        </div>'
            //+ '    </div>'
            + '</div>'
            + ''
        );

    } else {
        entry = jQuery(
            '<div class="entry">'
            + '    <div class="title">'
            + '        <a href="' + baseURL + slug + '">'
            + '            ' + title + ''
            + '        </a>'
            + '    </div>'
            + '    <div class="date">'
            + '        ' + publishDate
            + '    </div>'
            + '    <div class="subtitle">'
            + '        ' + siteName
            + '    </div>'
            + '    <div class="body">'
            + '        ' + teaser
            + '        <span>'
            + '            &#8230;'
            + '        </span>'
            + '    </div>'
            + '    <div class="ellipsis">'
            + '            &#8230;'
            + '    </div>'
            + '    <div class="readmore">'
            + '        <div class="contents">'
            + '            <a href="' + baseURL + slug + '">'
            + '                Read More'
            + '            </a>'
            + '        </div>'
            + '    </div>'
            + '</div>'
            + ''
        );
    }

    return entry;
}


