﻿/*
 * Global function, responsible for the client-server asynchronous interactions
 *
 * Parameters:
 *  . iframeObjId: ID of the IFRAME element where content pages are rendered;
 *  . iframeInitUrl: The iframe's initial url;
 *  . ifrmContentSrcCookieName: Name of the cookie holding the current iframe url;
 *  . menuUrlBindings: Array of objects specifying a menu object id - iframe url binding. Each objects has
 *      to have the attributes 'menuId' and 'regex'. The 'regex' attribute is a regex matched against the 
 *      iframe's current loaded url. 
 *      The array items must be ordered so that the scope of each regex is expanded as we traverse it:
 *          [   {menuId: 'menu1', regex: /(.*)pag.aspx?(.*)x=y(.*)/}, 
 *              {menuId: 'menu2', regex: /(.*)pag.aspx(.*)/} ]
 *
 *      The first item of the sample array matches a page with a specific GET parameter, while the second 
 *      item matches the same page with or without parameters - the scope of the second regex is larger than 
 *      the first;
 *  . bgObjId: ID of the element to where the background image is rendered;
 *  . bgListContainerObjId: ID of the element to where the list of available backgrounds is rendered;
 *  . user: [ Optional ] Object that contains logged user info. 
 *      Attributes:
 *          . id: The user's ID;
 *          . bgImage: [ Optional ]The user's preferred backgroud image;
 *
 * Dependencies:
 *  . YUI: yahoo-dom-event.js | animation-min.js
 *  . AjaxMethods object (created by the ScriptManager object)
*/
function zeeGlobal(iframeObjId, iframeInitUrl, ifrmContentSrcCookieName, menuUrlBindings, bgObjId, bgListContainerObjId, user) {
    this._BG_LOADING_OBJS = [ document.getElementById("bgLoading1"), document.getElementById("bgLoading2") ];
    var _BG_ICON_CSS_CLASSES = [ "Violet", "Yellow", "Red", "Green", "Blue" ];
    
    this._bg = document.getElementById(bgObjId);
    var _iframe = document.getElementById(iframeObjId);
    var _bgList = document.getElementById(bgListContainerObjId);
    var _menuUrlBindings = menuUrlBindings;
    var _user = user;

    // Holds the current microsite reference, null when not in a microsite
    var _ms = null;
    var _msChanged = false;
    
    // Method that render's the backgrounds list and the current background image, based on the current
    // microsite reference
    this.renderBackgrounds = function() {
        var onSuccess = function(result, context) {
            if (result.length == 0)
                return;
        
            // Render the background list
            _bgList.innerHTML = "";
            
            var iconIndex = 0;
            var bgInfo = null;
            var userBgInfoFound = false;
            
            for (var i = 0; i < result.length; i++) 
            {
                iconIndex = _BG_ICON_CSS_CLASSES[iconIndex] ? iconIndex : 0;

                var cur = document.createElement("a");
                
                cur.setAttribute("href", "javascript: void(0);");
                cur.className = "bgItem " + _BG_ICON_CSS_CLASSES[iconIndex];                
                _bgList.appendChild(cur);
                
                YAHOO.util.Event.addListener(cur, "click", function(e, imageUrl) {
                    context.selectBackground(e.target || e.srcElement, imageUrl);
                }, result[i].imageUrl);
                
                if (_user && _user.bgImage && !_ms && result[i].imageUrl == _user.bgImage) {
                    // An item corresponding to the user's preferred background was found, keep a reference to it
                    bgInfo = { bgItem: cur, bgImage: result[i].imageUrl };
                    userBgInfoFound = true;
                }
                
                if (i == 0)
                    // Keep the first item as the default one while the proper one is not found
                    bgInfo = { bgItem: cur, bgImage: result[i].imageUrl };
                
                if (result[i].isDefault && !userBgInfoFound)
                    // An item corresponding to the default background was found, keep a reference to it
                    bgInfo = { bgItem: cur, bgImage: result[i].imageUrl };
                
                iconIndex++;
            }
            
            var clearFloat = document.createElement("div");
            clearFloat.setAttribute("style", "clear: both");
            _bgList.appendChild(clearFloat);
            
            // Select the initial background
            context.selectBackground(bgInfo.bgItem, bgInfo.bgImage);
        }
        
        // Dummy function to prevent errors from showing up on the page
        var onError = function() { }
        
        AjaxMethods.GetLimitedSeriesBackgroundImages(_ms || "", onSuccess, onError, this);
    }
    
    this.selectBackground = function(bgItem, bgImage) {
        // Resolve the background image url
        bgImage = bgImage ? bgImage : "";
        var resolvedBgImage = bgImage.replace("~", window.location.protocol + "//" + window.location.host + window.location.pathname.substring(0, window.location.pathname.lastIndexOf("/")));

        if (resolvedBgImage != "" && this._bg.style.backgroundImage.match(new RegExp(resolvedBgImage, "i")))
            return;
        
        // Clear all selected background items, select the corresponding one
        YAHOO.util.Dom.getElementsByClassName("bgItem", "a", _bgList, function(obj) { obj.className = obj.className.replace("selected", ""); });
        bgItem.className = bgItem.className + " selected";
        bgItem.blur();
        
        // Load the background
        if (bgImage == "")
            YAHOO.util.Dom.setStyle(this._bg, "background", "transparent no-repeat center top");
        else {
            for (var i = 0; i < this._BG_LOADING_OBJS.length; i++)
                this._BG_LOADING_OBJS[i].style.visibility = "visible";
            
            this.preloadImages([ resolvedBgImage ], 
                function(context) {
                    for (var i = 0; i < context._BG_LOADING_OBJS.length; i++)
                        context._BG_LOADING_OBJS[i].style.visibility = "hidden";

                    YAHOO.util.Dom.setStyle(context._bg, "opacity", 0);
                    YAHOO.util.Dom.setStyle(context._bg, "background", "transparent url(" + resolvedBgImage + ") no-repeat center top");
                    
                    (new YAHOO.util.Anim(context._bg, { opacity: { to: 1 } }, 2, YAHOO.util.Easing.easeOut)).animate();
                },
                function(context) {
                    for (var i = 0; i < context._BG_LOADING_OBJS.length; i++)
                        context._BG_LOADING_OBJS[i].style.visibility = "hidden";
                }, this);
        }

        // Set the user's preferred background image
        if (bgImage != "" && !_ms && _user && _user.bgImage) {
            var onSuccess = function(result) {
                _user.bgImage = bgImage;
            }
            
            var onError = function() { };

            AjaxMethods.SetUserBackgroundImage(_user.id, bgImage, onSuccess, onError);
        }
    }

    // Preloads the array of images supplied. 
    // If a function 'fn' is supplied, it will be invoked when each image loads. A custom object 'obj'
    // may be supplied and will be passed to the function
    this.preloadImages = function(images, successFn, errorFn, obj) {
        if (images && images.length) {
            for (var i = 0; i < images.length; i++) {
                var bgImg = document.createElement("img");

                bgImg.onload =  function()  { if (successFn) successFn(obj); };
                bgImg.onerror = function()  { if (errorFn) errorFn(obj); };
                bgImg.src = images[i];
            }
        }
    };
    
    if (!YAHOO || !AjaxMethods || !_iframe || !this._bg || !_bgList || !_menuUrlBindings || !_menuUrlBindings.length)
        return;
    
    // Set the iframe's onload event
    YAHOO.util.Event.addListener(_iframe, "load", function(e, context) {
        if (!this.contentWindow)
            return;
            
        // Set the document's title
        document.title = this.contentWindow.document.title;
        
        // Check if a menu is bound to the current iframe url, if so css-select it
        var src = this.contentWindow.location.href.toLowerCase();
        var menuFound = false;
        
        // Store the current iframe src
        document.cookie = ifrmContentSrcCookieName + "=" + escape(src);

        for (var i = 0; i < _menuUrlBindings.length; i++) {
            // Keep a reference to the Dom element of the menu in the 'obj' attribute of the current 
            // menuUrlBinding object
            if (!_menuUrlBindings[i].obj)
                _menuUrlBindings[i].obj = document.getElementById(_menuUrlBindings[i].menuId);
        
            if (_menuUrlBindings[i].obj)
                _menuUrlBindings[i].obj.className = "menu";
                
            if (!menuFound && _menuUrlBindings[i].regex) {
                if (src.match(_menuUrlBindings[i].regex)) {
                    menuFound = true;
                    
                    if (_menuUrlBindings[i].obj) {
                        _menuUrlBindings[i].obj.className = "menu selected";
                        _menuUrlBindings[i].obj.blur();
                    }
                }
            }
        }
        
        // Render the background list items if the current microsite reference (provided by the iframe's 
        // current page) differs from the last one, or if it is the first rendering
        if (!_msChanged || (_ms != this.contentWindow.ZEE_MS)) {
            _ms = this.contentWindow.ZEE_MS;
            _msChanged = true;
            
            context.renderBackgrounds();
        }
        
    }, this);
    
    // Set the iframe's initial url
    _iframe.src = iframeInitUrl;
}
