﻿/// <summary>
/// This file contains javascript for pulling feeds from locations that have a CSMF widgetServer deployed
/// </summary>
(function () {
    INTEL("widget", function () {

        /// <summary>Initialize the widget infrastructure and setup feeds specific functionality.</summary>

        var widgetFunctions;
        // Setup the widgetFunctions, these will be used by csmf-handler code to initialize and process messages
        // when the communications channel is setup and ready to use.
        widgetFunctions = {
            // setup a container to hold callbacks if the calling code wants to register a method to 
            // be executed when the data is returned.
            callBacks: [],
            readyInitialize: function (widget) {
                /// <summary>
                /// This method will be called by the csmf-handler.js code when the communications between
                /// the client and the server have been established.
                ///</summary>
                /// <param name="widget" type="Object">Widget that has estabilished communication.</param>
                var callBacks = this.callBacks,
                getFeedFunction = function (request, callBack) {
                    /// <summary>
                    /// This function will send a request to the server and register a callback for the
                    /// the specified request.  This will take the form of a url request for a specific feed
                    /// from the server.
                    /// </summary>
                    if (callBacks[request.key]) {
                        delete callBacks[request.key];
                    }
                    callBacks[request.key] = callBack;     // Store the callback.
                    INTEL.widget.message(widget, request); // Issue the request
                };

                getISO8601 = function (dateStr) {
                    /// <summary>Method to convert the string form of an IS08601 date into a javascript date object.</summary>
                    /// <param name="dateStr" type="String">ISO8601 formatted date string.</param>
                    var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
                            "(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" +
                            "(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?",
                             d = dateStr.match(new RegExp(regexp)),
                            offset = 0,
                            date = new Date(1, 0, 1);

                    if (d) {
                        date = new Date(d[1], 0, 1);
                        if (d[3]) { date.setMonth(d[3] - 1); }
                        if (d[5]) { date.setDate(d[5]); }
                        if (d[7]) { date.setHours(d[7]); }
                        if (d[8]) { date.setMinutes(d[8]); }
                        if (d[10]) { date.setSeconds(d[10]); }
                        if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); }
                        if (d[14]) {
                            offset = (Number(d[16]) * 60) + Number(d[17]);
                            offset *= ((d[15] == '-') ? 1 : -1);
                        }

                        offset -= date.getTimezoneOffset();
                        time = (Number(date) + (offset * 60 * 1000));
                        date = new Date(Number(time));
                    }
                    return date;
                };
                monthAbbreviations = {
                    /// <summary>Member that contains translations for short month names.</summary>
                    "$COPY$_en_us": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
                    "$COPY$_de_de": ["Jan", "Feb", "Mrz", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"],
                    "$COPY$_fr_fr": ["janv.", "févr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.", "déc."],
                    "$COPY$_ru_ru": ["янв", "фев", "мар", "апр", "май", "июн", "июл", "авг", "сен", "окт", "ноя", "дек"]
                };

                /// <summary>
                /// The folowing code will pull the configuration information from the HTML page and will establish communication with
                /// the defined feed servers. It assumes that this configuration information is registered as a module using the
                /// intel JS loader and that the module is loaded using the name Feeds (INTEL.Feeds).
                /// This module should be defined as follows:
                ///
                ///  [
                ///    {
                ///        widgetName: 'forumWidget',       // name of widget
                ///        proxy: '/itcenter/proxy.htm',    // path to the CSFM proxy file.
                ///        dataFrame: 'http://url-to-widget-server/FeedDataFrame.htm',  // Url to the FeedDataFrame.htm file.
                ///        feeds:   // array definition containing the list of feeds to be retreived.
                ///        [
                ///         {
                ///            url: 'http://inside.intel.com/presto/edge/api/rest/WrapperMashupIntel/Invoke?SN=ITmashup&ON=runMashup', //url of the feed to be pulled.
                ///            target: '#blogs-implement', // Target element on the page where the feed markup will be inserted.
                ///            maxToShow: 4                // maximum number of feed items to display
                ///            viewAllLabel: 'View All'    // label to be displayed that links to the feed source.
                ///            viewAllLink: 'http://url-to-view-all-for-feed' // url that points to the location where view all link will point.
                ///         }
                ///         // Additional feeds can be defined here.
                ///        ]
                ///     }
                ///     // Additional feed sources can be defined here.
                ///  ]
                ///
                ///
                /// </summary>
                jQuery(INTEL.Feeds).filter(function () { return (jQuery(this).attr("widgetName") === widget.name); }).each(function () {
                    jQuery(this.feeds).each(function (i, val) {
                        /// <summary>Request each individual feed.</summary>
                        /// <param name="i" type="int">index of feed.</param>
                        /// <param name="val" type="object">value of array item.</param>

                        var url = this.url,
                        target = this.target,
                        key = widget.name + '-frq-' + i,
                        maxToShow = (this.maxToShow && (!isNaN(parseInt(this.maxToShow, 10)))) ? this.maxToShow : 4,
                        viewAllLabel = (this.viewAllLabel) ? this.viewAllLabel : "View all",
                        viewAllLink = (this.viewAllLink) ? this.viewAllLink : null;

                        // Call the get feed function to request the feed data.
                        getFeedFunction({ key: key, url: url, max: maxToShow },
                            function (response) {
                                /// <summary>
                                ///     Handles the data that is returned from the feed.
                                /// </summary>
                                /// <param name="response" type="object">Response information received from feed request.</param>
                                var feedMarkup = '',
                                numToShow = maxToShow,
                                numToShow = (response.length < numToShow) ? response.length : numToShow,
                                pageLocale = (jQuery('html').attr('lang')) ? jQuery('html').attr('lang').toLowerCase() : 'en_us',
                                months = (monthAbbreviations['$COPY$_' + pageLocale]) ? monthAbbreviations['$COPY$_' + pageLocale] : monthAbbreviations['$COPY$_en_us'];

                                // Process the feed data, but only up to the numToShow
                                jQuery(response).slice(0, numToShow).each(function () {
                                    var date = getISO8601(this.updated),
                                    link = this.link,
                                    title = this.title,
                                    dateStr = months[date.getMonth()] + ' ' + date.getDate();

                                    // If we're in IE6 we had to code some values had to be coded in order for them to
                                    // be passed through CSMF communications (this has to do with a limitation of IE6's Javascript functions
                                    // encodeURIComponent and decodeURIComponent.  In the FeedDataFrame.htm code, these values are specially
                                    // encoded if the browser is IE6, and so here we need to decoded them specificially.
                                    if (jQuery.browser.msie && jQuery.browser.version === '6.0') {
                                        link = (link) ? link.replace(/\&amp;/g, '&').replace(/\&quot;/g, '"').replace(/\&\#25;/g, '%') : link;
                                        title = (title) ? title.replace(/\&amp;/g, '&').replace(/\&quot;/g, '"').replace(/\&\#25;/g, '%') : title;
                                    }

                                    // Create the markup for each feed item that will be inserted into the DOM
                                    feedMarkup += '<div class="content-item without-thumb">';
                                    feedMarkup += '<div class="content-description">';
                                    feedMarkup += '<p class="forwebpub">' + dateStr + '</p>';
                                    feedMarkup += '<a href="' + link + '" title="' + title + '">' + title + '</a>';
                                    feedMarkup += '</div>';
                                    feedMarkup += '<span class="cleaner"></span></div>';
                                })

                                // This is special case code that was added to process the view all link for community feeds if
                                // the viewAllLink was not specified. It will strip out the /commuity/feeds portion of the
                                // feed url and use that as the view all link.
                                if (!viewAllLink && url.toLowerCase().indexOf('/community/feeds') !== -1) {
                                    viewAllLink = url.replace(/\/community\/feeds/i, '');
                                }
                                // Render the view all link.
                                if (viewAllLink) {
                                    feedMarkup += '<a title="' + viewAllLabel + '" class="right-aligned" target="_blank" href="' + viewAllLink + '">' + viewAllLabel + ' &gt;</a>';
                                }
                                // Insert the markup into the DOM.
                                jQuery(target).html(feedMarkup);
                            });
                    });
                });
            },
            onmessage: function (data, widget) {
                /// <summary>This method will handle processing messages received back from the server.</summary>
                /// <param name="data" type="object">data that was received.</param>
                /// <param name="widget" type="object">Widget targeted to receive the message.</param>

                    if (widget && this.callBacks && this.callBacks[data.key]) {// When the data is received this handles dispatching the response to the appropriate callback.
                        this.callBacks[data.key](data.response);  // execute the callback.
                        // clear the callback for this request.
                        delete this.callBacks[data.key];
                    }
            }
        };

        // Make sure the Feeds were defined for the page and intialize each unique feed source as a widget.
        if (INTEL.Feeds) {
            jQuery(INTEL.Feeds).each(function () {
                // Verify that the widget dom element exists, if not, create it.
                if (jQuery('#' + this.widgetName).length === 0) {
                    jQuery('body').append('<div style="display:none" id="' + this.widgetName + '"></div>');
                }
                // Store the feed's widgetFunction in jQuery.
                jQuery[this.widgetName] = widgetFunctions;
                // Initialize the widget.
                INTEL.widget({ container: "#" + this.widgetName,
                    src: this.dataFrame,
                    proxy: this.proxy,
                    name: this.widgetName,
                    height: 0,
                    width: 0
                });
            })
        }
    });
})();



