/***************************************************
/
/  This script is a modified version of the original
/  MSN Widgit script located at: 
/  http://stj.msn.com/br/gbl/js/snd2m10.js
/
/  We have modified the script to allow for its re-use
/  with the iconmobile based widget
/
/  (SJ/iconmobile: updated to support branded widgets)
/
***************************************************/
    var g_widgetManagerIndex=0;
    // Iframe Settings
    var g_iFrameWidth  = 336; // pixel
    var g_iFrameHeight = 203; // pixel
    var g_iFrameZindex = 500;
    var g_currentOpenIframeWidget = null;
    var g_widgetEntryScreen = "/w/MSNMobileEntryScreen.aspx";
    var g_widgetEntryBaseUrl = null;
    var g_imagesBaseURL = null;
    var g_preOpenCb = null;
    var g_mobileWidgetHost = "msn";
    var g_imagesLocalBaseUrl = "http://assets.xbox.com/en-us/newsletters/email-widget/img";

    Mobile_SetWidgetGlobals = function(name, value){ 
        switch (name.toLowerCase())
        {
            case "mobilebaseurl":
                g_widgetEntryBaseUrl = value.toLowerCase() ;
                break;
            // note: in most cases, you will not need to set the imagesbaseurl
            // let us set the default setting for you.
            case "imagebaseurl":
                g_imagesBaseURL = value.toLowerCase() ;
                break;
            case "preopencb":
                g_preOpenCb = value;
            // Added to support use with iconmobile widget, defaults to MSN to best ensure compatiblility with existing pages
            case "mobilewidgethost":
                g_mobileWidgetHost = value.toLowerCase() ;
                break;
            // Added to support use with iconmobile widget, defaults to MSN to best ensure compatiblility with existing pages
            case "widgetentryscreen":
                g_widgetEntryScreen = value.toLowerCase() ;
                break;
            default:
                break;
        }
    }
   
    Mobile_GetOpenWindow = function() {return g_currentOpenIframeWidget;}
    
    Mobile_WidgetManager = function(appName, scenarioId, locale)
    {
        var m_appName = appName;
        var m_scenarioId = scenarioId;
        var m_locale = locale;
        var m_widgetManagerIndex = g_widgetManagerIndex ++;
        var m_numWidgets = 0;
        var m_cssPath = null;
        var self = this;
        
        if (g_widgetEntryBaseUrl == null)
        {
            alert ("Please set mobilebaseurl first!");
        }
        
        if (locale != 'en-us')
            g_iFrameHeight = 340;

        if (g_imagesBaseURL == null)
        {
            if (g_widgetEntryBaseUrl.indexOf ("xbox.com") != -1)
            {
                // live site
                g_imagesBaseURL = "http://www.xbox.com/xweb/xbox/xboxV2/images";
            }
            else
            {
                // test cluster
                g_imagesBaseURL = g_widgetEntryBaseUrl + "img";
            }
        }

        this.GetAppName = function() { return m_appName; }                
        this.GetScenarioId = function(){ return m_scenarioId; }
        this.GetLocale = function(){ return m_locale; }   
        this.GetCssPath = function(){ return m_cssPath; }     

        this.SetCssPath = function(cssPath){ m_cssPath = cssPath; }
        
        this.AddWidget = function(widget){
            if (!IsIE() || IsIE5_5Up())
                widget.DisplayWidget (self, m_widgetManagerIndex, m_numWidgets ++);
        }
    };
    
    IsIE = function()
    {
        // convert all characters to lowercase to simplify testing
        var agt    = navigator.userAgent.toLowerCase();
        return ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
    }
 
    IsIE5_5Up = function()
    {
        // convert all characters to lowercase to simplify testing
        var agt    = navigator.userAgent.toLowerCase();
        var is_ie  = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
        var is_major = parseInt(navigator.appVersion);
        var is_ie3 = (is_ie && (is_major < 4));
        var is_ie4 = (is_ie && (is_major == 4) && (agt.indexOf("msie 4")!=-1) );
        var is_ie5 = (is_ie && (is_major == 4) && (agt.indexOf("msie 5.0")!=-1) );
        return (is_ie && !is_ie3 && !is_ie4 && !is_ie5);
    }

    Mobile_Widget = function(nameValueCollection, displayMask, displayString)
    {
        var m_nameValueCollection = nameValueCollection;
        var m_displayMask = displayMask;
        var m_displayString = displayString;
        var m_widgetManager = null;
        var m_iframeOpen = false;
        var m_baseId = null;
        var self = this;
        var m_parent = null;
        var m_forceX = null;
        var m_forceY = "bottom";
        var m_leadingElement = null;
        var m_trailingElement = null;
      
        function IsTextVisible(){
            if (m_displayString == null || m_displayString == "") return 0;
            return m_displayMask & 2;
        }
        function IsPhoneImageVisible(){ return m_displayMask & 4; }
        
        this.SetLeadingElement = function(value){ m_leadingElement = value; }
        
        this.SetTrailingElement = function(value){ m_trailingElement = value; }
        
        function GetTargetUrl()
        {
            var widgetFullUrl;
            
            // Added to support use with iconmobile widget, defaults to MSN to best ensure compatiblility with existing pages
            if (g_mobileWidgetHost == "iconmobile")
            {
                widgetFullUrl = g_widgetEntryBaseUrl + g_widgetEntryScreen;
            }
            else
            {
                /* Append the URL with the query string parameters that partner passes */
                widgetFullUrl = g_widgetEntryBaseUrl + g_widgetEntryScreen + "?appname=" + m_widgetManager.GetAppName() + "&scenarioid=" + m_widgetManager.GetScenarioId() + "&lc=" + m_widgetManager.GetLocale() + "&cid=" + m_widgetManager.GetAppName() + "_" + m_widgetManager.GetScenarioId();
                
                /* append css path if provided */
                if (m_widgetManager.GetCssPath() != null)
                    widgetFullUrl = widgetFullUrl + "&css=" + m_widgetManager.GetCssPath();
                
                if ( m_nameValueCollection != null && m_nameValueCollection != "" )
                    widgetFullUrl = widgetFullUrl + "&" + m_nameValueCollection;
            }                
                            
            return widgetFullUrl;
                
        }
        
        this.ForcePosition  = function (x, y)
        {
            if (x != null)
                m_forceX = x;
            if (y != null)
                m_forceY = y;
        }
        this.SetParent = function(parent){ m_parent = parent; }
        
        function FindRealPos (el) 
        {
            var c = {x : 0, y : 0};
            while (el) {
                c.x += el.offsetLeft;
                c.y += el.offsetTop;
                el = el.offsetParent;
            }
            return c;
        }
        function PositionIframe(spanEl, iframe)
        {
            /* for now, simply insert at the end of the span */
            var truePos = FindRealPos (spanEl.firstChild);
            var winLeft = truePos.x - document.body.scrollLeft;
            var winTop  = truePos.y - document.body.scrollTop;
            var spLeft  = winLeft;
            var spRight = document.body.clientWidth - spLeft - spanEl.offsetWidth;
            var spTop   = winTop;
            var spBottom= document.body.clientHeight - spTop - spanEl.firstChild.offsetHeight;
            if (m_forceX == "left" || (m_forceX == null && spRight < g_iFrameWidth && spLeft > g_iFrameWidth - spanEl.offsetWidth))
                iframe.style.left = (spanEl.offsetWidth + truePos.x - g_iFrameWidth) + "px";
            else  iframe.style.left = truePos.x + "px";
            
            if (m_forceY == "top" || (m_forceY == null && spBottom < g_iFrameHeight && spTop > g_iFrameHeight))
                iframe.style.top = (truePos.y - g_iFrameHeight) + "px";
            else iframe.style.top = (spanEl.firstChild.offsetHeight + truePos.y) + "px";
        }

        /* Displays the Widget Iframe */
        this.ShowIframe = function()
        {   
            // invoke preopen callback.
            if (g_preOpenCb != null)
                g_preOpenCb("snd2m");
                
            var spanEl = document.getElementById ("span_" + m_baseId);
            if (spanEl == null)
                return;
            
            var iframe = document.createElement("iframe");
            iframe.id = "iframe_" + m_baseId;
            iframe.src= GetTargetUrl();
            iframe.frameBorder = "0";
            iframe.noresize = "true";
            iframe.vspace = "0" ;
            iframe.hspace = "0" ;
            iframe.scrolling = "no";
            iframe.style.height = g_iFrameHeight + "px";
            iframe.style.width  = g_iFrameWidth + "px";
            iframe.style.zIndex   = g_iFrameZindex;
            iframe.style.borderWidth = '0px';
            iframe.style.position = 'relative';
            iframe.allowTransparency="true";
           
            if (g_currentOpenIframeWidget != null)
                g_currentOpenIframeWidget.HideIframe();
            g_currentOpenIframeWidget = self;
            m_iframeOpen = true;

            var elDiv = document.createElement("div");
            elDiv.id = "div_" + m_baseId;
            elDiv.style.borderWidth = "0px";
            elDiv.style.position = "absolute";
            elDiv.style.width = g_iFrameWidth + "px";
            elDiv.style.zIndex = g_iFrameZindex;
            elDiv.style.display = "inline";

            elDiv.style.background = "transparent url('" + g_imagesLocalBaseUrl + "/xbox_widget_box.gif') no-repeat";

            var head = "";
            head += "<table cellpadding='0' cellspacing='0' width='100%' style='font-size: 0px; border:0px; height: 25px;'>";
            head += "<tr>";
            head += "<td align='left' width='80%'></td>";
            // Changed reference form g_imagesBaseUrl to g_imagesLocalBaseUrl to support re-use with iconmobile Widget
            head += "<td align='right' style='padding-left:0px;padding-top:5px;padding-right:10px;padding-bottom:0px;height:25px;'><img width='20' height='20' id='close_" + m_baseId + "' src='" + g_imagesLocalBaseUrl + "/xbox_widget_close.gif'></td>";
            head += "</tr>";
            head += "</table>";
            
            elDiv.innerHTML = head;
            
            var closeButton = elDiv.getElementsByTagName("table")[0].getElementsByTagName("tr")[0].getElementsByTagName("td")[1].getElementsByTagName("img")[0];

            if (closeButton) {
                closeButton.style.cursor = document.all ? "hand" : "pointer";
                closeButton.onclick = self.DoClick;
//                elDiv.onmouseover = HandleMouseOver;
                closeButton.onmouseover = HandleMouseOver;
//                elDiv.onmouseout = HandleMouseOut;
                closeButton.onmouseout = HandleMouseOut;
            } 
            elDiv.appendChild (iframe);
            PositionIframe (spanEl, elDiv);
            
            // append the div to the document body to avoid firefox issues. This will not affect the positioning
            // of the div since it is absolute.
            document.body.appendChild(elDiv);
       }

        /* Hides the Widget Iframe */
        this.HideIframe = function()
        {
            var div = document.getElementById ("div_" + m_baseId);

            if (div)
                document.body.removeChild(div);
            div = null;
            m_iframeOpen = false;
            g_currentOpenIframeWidget = null;
        }                
            
        /* On Click Widget Icon either to Show or Hide the Widget Iframe */
        this.DoClick = function()
        {
            if (m_iframeOpen) self.HideIframe();
            else self.ShowIframe();
            
            return false;
        }
        
        this.DisplayWidget = function(widgetManager, mgri, i)
        {
            var parentElement;
            if (m_parent != null)
                parentElement = document.getElementById (m_parent);
            else
                parentElement = document.body;
            if (parentElement == null) return;

            m_widgetManager = widgetManager;
            m_baseId = "mgr" + mgri + "wgt" + i;
            var spanEl = document.createElement('span'); 
            spanEl.id = "span_" + m_baseId;

            if (IsPhoneImageVisible() != 0){
                //display small phone
                var elSmallPhone= new Image(); 
                elSmallPhone.src = g_imagesBaseURL + "/smallphone.png"
                elSmallPhone.style.cursor = document.all ? "hand" : "pointer";
                elSmallPhone.onclick = self.DoClick;
                elSmallPhone.style.verticalAlign = "middle";
                spanEl.appendChild(elSmallPhone);
            }
            if (IsTextVisible() != 0){
                //display text
                var elLabelSendToMobile = document.createElement("a");
                elLabelSendToMobile.innerHTML = m_displayString;
                elLabelSendToMobile.href = "javascript:void(0)";
                elLabelSendToMobile.style.cursor = document.all ? "hand" : "pointer";
                elLabelSendToMobile.style.verticalAlign = "middle";
                elLabelSendToMobile.onclick = self.DoClick;
                spanEl.appendChild(elLabelSendToMobile);
            }
            
            if (m_leadingElement != null) parentElement.appendChild (m_leadingElement);
            parentElement.appendChild (spanEl);
            if (m_trailingElement != null) parentElement.appendChild (m_trailingElement);
        }

        function HandleMouseOver()
        {
            var close = document.getElementById ("close_" + m_baseId);

            // Changed reference form g_imagesBaseUrl to g_imagesLocalBaseUrl to support re-use with iconmobile Widget
            if (close) 
                close.src = g_imagesLocalBaseUrl  + "/xbox_widget_over.gif";

            return true;
        }

        function HandleMouseOut()
        {
            var close = document.getElementById ("close_" + m_baseId);

            // Changed reference form g_imagesBaseUrl to g_imagesLocalBaseUrl to support re-use with iconmobile Widget
            if (close)
                close.src = g_imagesLocalBaseUrl  + "/xbox_widget_close.gif";

            return true;
        }
    }