﻿/// <summary>This file contains common code that assists in hooking up CSMF communications in a way that
///          allows an initialization method to be called when the communications have been established
///          and it is ready to start receiving requests
///</summary>
///<remarks>
///     This code hooks up to the CSMF's widget onmessage method to handle communications coming back
/// from the widgetServer (remote server).  Based on the widget that's communicating it will a. call
///  a readyInitialize function that's been defined for that specific widget once communications have
///  been established.  b. all subsequent messages for that specific widget will be forwarded to the
///  specific widget's onmessage handler.
///  In order to use this infrastructure, each widget will need to create an object that contains the
///  methods readyInitialize, and onmessage, and store a reference to them in the jQuery data storage
///  keyed by the name of the widget.
/// </remarks>
(function() {
    var delegate = function() {
        var isInitialized, existingHandler;
        // If this has already been done, don't do it again.
        if (typeof(INTEL.widget.onmessage) === "function") {
            existingHandler = INTEL.widget.onmessage;
        }
        else {
            // Shorten the domain.  We'll wrap in
            // try/catch for situations (i.e. intel.jp.co )
            // where we can't shorten the domain.
            try {
                document.domain = "intel.com";
            } catch (e) { }
        }
        INTEL.widget.onmessage = function(data, widget) {
            if (widget.name === 'promoWidget') {
                var widgetMethods = jQuery[widget.name];
                if (data && data.ready && widgetMethods && widgetMethods.readyInitialize) {
                    widgetMethods.readyInitialize(widget);
                    isInitialized = true;
                }
                else if (isInitialized && widgetMethods && widgetMethods.onmessage) {
                    data = widgetMethods.onmessage(data, widget);
                }
            }
            // This is requied to cascade and use the default handler
            if (existingHandler) {
                data = existingHandler(data, widget);
            }
            return data;
        };
    }
    INTEL("widget", delegate);
})()


