﻿// ----------- actions button helper class ----------- //
Ext.ux.ActionsButtonHelper = Ext.extend(Ext.util.Observable, {

    // internal fields
    m_visibilty: 0,
    m_marginTop: 0,
    m_cancelClick: false,


    // delegates
    m_beforeShowDelegate: null,

    // delegate setters
    setBeforeShowDelegate: function(theDelegate) {
        this.m_beforeShowDelegate = theDelegate;
    },


    // standard constructor
    constructor: function() {
        Ext.ux.ActionsButtonHelper.superclass.constructor.call(this);
    },

    // standard initializer
    initComponent: function() {
        Ext.ux.ActionsButtonHelper.superclass.initComponent.apply(this, arguments);

        // extra args have to go here as base class initComponent doesn't get called for some reason
        var config = {};

        Ext.apply(this, config);
        Ext.apply(this.initialConfig, config);
    },


    initialize: function(
        button,
        buttonImageId,
        buttonImageHover,
        buttonImageInactive,
        menuContainer,
        headerWrapper) {

        $.preloadImages(buttonImageHover, buttonImageInactive);

        // bind hover images
        $.bindHoverImages(
            buttonImageId,
            buttonImageHover,
            buttonImageInactive,
            0,
            null, null, null, null, null, null);

        // hook up menu display animation
        $("." + button + "").click(delegate(this, function(event) {
            if (this.m_visibilty == 1) {
                $("#" + menuContainer + "").animate({ marginTop: this.m_marginTop }, 500);
                this.m_visibilty = 0;
            }
            else {
                if (this.m_cancelClick === false) {

                    // call external delegate
                    if (this.m_beforeShowDelegate) {
                        this.m_beforeShowDelegate();
                    }

                    $("#" + menuContainer + "").animate({ marginTop: $("#" + headerWrapper + "").height() - 2 }, 500);
                    this.m_visibilty = 1;
                }

                this.m_cancelClick = false;
            }
        }));

        // hook up close-on-lose-focus handler
        $("body").mouseup(delegate(this, function(event) {
            if (this.m_visibilty == 1) {
                $("#" + menuContainer + "").animate({ marginTop: this.m_marginTop }, 500);

                if (((event.originalTarget) && (event.originalTarget.id == "action_button")) || // firefox
                   ((event.srcElement) && (event.srcElement.id == "action_button")))            // IE
                    this.m_cancelClick = true;

                this.m_visibilty = 0;
            }
        }));
    },

    // set the margin top
    // this is the place at which the top of the menu scrolls to when closed up
    setMarginTop: function(marginTop) {
        this.m_marginTop = marginTop;
    }
});