//<using>
//  nui/nui.js
//  nui/prototype.js
//</using>

/**
 * Layout
 * Copyright 2010, NetRanking.cn
 * @namespace NUI.Layout
 */
 
/* Tips:
   1. You may use the method Layout.bindLoadEvent to bind a function to 
      the onload events sequence. When the page loaded compoletely, the 
      events would be invoked.
*/
 
NUI.Layout = (function() {
    var m_PageLoadEvents = [];
    var m_OnLoad = function() {
        NUI.Layout.ComponentMenu.initialize();
        for (var i = 0; i < m_PageLoadEvents.length; i++)
            m_PageLoadEvents[i]();
    }; 
    var m_BindLoadEvent = function(e) {
        if (typeof(e) == "function")
            m_PageLoadEvents.push(e);
    };
    return {
        onLoad : m_OnLoad,
        bindLoadEvent : m_BindLoadEvent,
        ComponentMenu : { }
    };
})();

NUI.Layout.ComponentMenu = (function () {
    var RES_PREFIX = "component-button-";
    var m_SelectedId = 0;
    var m_HoveredId = 0;
    var m_Update = function(selected_id, hovered_id) {
        for (var i = 1; i <= 4; i++)
            NUI.Util.DomService.getNode(RES_PREFIX + i).style.backgroundPositionY = 
                (((selected_id == i) ? 0 : -90) + ((hovered_id == i) ? -45 : 0)) + "px";
        for (var i = 1; i < 4; i++)
            NUI.Util.DomService.getNode(RES_PREFIX + "separator-" + i).style.backgroundPositionY =
                (((i == selected_id) ? 0 : ((i + 1 == selected_id) ? -135 : -270)) + 
                 ((i == hovered_id) ? -45 : 0) + ((i + 1 == hovered_id) ? -90 : 0)) + "px";
    };
    var m_UpdateCurrent = function() {
        m_Update(m_SelectedId, m_HoveredId);
    };
    var m_GetId = function(res) {
        return parseInt(res.id.substring(RES_PREFIX.length));
    };
    var m_OnButtonMouseOver = function(res) {
        m_HoveredId = m_GetId(res);
        m_UpdateCurrent();
    };
    var m_OnButtonMouseOut = function(res) {
        m_HoveredId = 0;
        m_UpdateCurrent();
    };
    var m_BindEvents = function() {
        for (var i = 1; i <= 4; i++) {
            var obj = NUI.Util.DomService.getNode(RES_PREFIX + i);
            obj.onmouseover = function() { 
                NUI.Layout.ComponentMenu.onButtonMouseOver(this);
            };
            obj.onmouseout = function() {
                NUI.Layout.ComponentMenu.onButtonMouseOut(this);
            };
        }
    };
    var m_Initialize = function() {
        if (NUI.Util.DomService.getNode("component-menu") == null)
            return;
        m_BindEvents();
        if (typeof(Environment.CurrentComponent) != "undefined")
            m_SelectedId = Environment.CurrentComponent;
        m_UpdateCurrent();    
    };
    return {
        initialize : m_Initialize,
        onButtonMouseOver : m_OnButtonMouseOver,
        onButtonMouseOut : m_OnButtonMouseOut
    };
})();

