(function(){
    
    var glow,
        DEBUG = false;

    gloader.load(
		["glow", "1", "glow.dom", "glow.embed", "glow.events", "glow.widgets.Mask", "glow.widgets.Overlay", "glow.widgets.Panel", "glow.net"],
		{
			async: false,
			onLoad: function(fetchedGlow) {
				glow = fetchedGlow;
				glow.ready(init);
			}
		}
	);
    
    function init() {
    }

/**
 * ContextPanel
 *
 * ContextPanel extends glow.widgets.Panel
 * allowing the caller to specify an optional
 * 'context' option. The Panel will be centred
 * over this context.
 * 
 */
function ContextPanel( content, opts ) {
    
    //arguments.callee.base.apply(this, arguments);
    
    //var context, modal, mask, panel;
    
    this.eventsRemoved = false;
    
    var self = this;
    var opts = opts || {};
    
    this.context = opts["context"] ? opts["context"] : null;
    this.modal = opts["modal"] ? opts["modal"] : false;
    
    // Clear the modal flag as we'll be using our own
    // ContextMask instead of the Panel's
    if(this.modal) {
        opts["modal"] = false;
    }
    
    if(this.context) {
        delete opts["context"];
    }
    
    var that = this;
    
    if(DEBUG && console) console.log("About to create glow panel:", content, opts);
    
    // Create the mask if we have the modal flag
    // set
    if(this.modal && this.context) {
        this.mask = new ContextMask({   context:this.context,
                                        onClick: function() {
                                            if(DEBUG && console) console.log("mask on click from panel");
                                            that.hide();
                                        }
                                    });
    }
    
    opts["autoPosition"] = false;
    this.panel = new glow.widgets.Panel(content , opts);
    
    // override the close button
    var closeButton = this.panel.container.get(".panel-close");
    var newCloseEvt = glow.events.addListener( closeButton, "click", function() { that.hide(); } );
    
    
    // Override resize event for panel
    //this._removeParentalEventListeners();
    

    glow.events.addListener(window, "resize", function() { that.doAutoPosition(); } );
    
    // Override scroll event for panel
    glow.events.addListener(window, "scroll", function() { that.doAutoPosition(); } );
    
    // Add event listeners to underlying panel and pass through to
    //  users listening to this panel
    var supportedEvents = [ "show", "afterShow", "hide", "afterHide" ];
    // params: the source of the original events, the events to listener for, the new source for the events
    this._proxyEventListeners( this.panel, supportedEvents, this );
    
    // Set-up pass-through properties for panel
    this.container  = this.panel.container;
    this.content    = this.panel.content; 
}

ContextPanel.prototype = {
    show: function() {
        if(this.mask) this.mask.add();
        
        this.panel.show();
        
        /*
        if(!this.eventsRemoved) {
            this._removeParentalEventListeners();
            eventsRemoved = true;
        }
        */
        
        this.doAutoPosition();
        if(DEBUG && console) console.log("Show context panel: ", this.panel);
    },
    hide: function() {
        if(this.mask) this.mask.remove();
        this.panel.hide();
    },
    doAutoPosition: function() {
        this._locatePanelInContext(this.context, this.panel);
    },
    _locatePanelInContext: function(ctx, panel) {
        if(DEBUG && console) console.log("Locate panel in context: ", ctx, panel);
        
        var ctxX, ctxY, ctxW, ctxH;
        var midCtxX, midCtxY;
        var pW, pH, pX, pY;
        
        var container;
        container = panel.container;
        
        // Find all the dimensions
        //  of the context
        ctx = glow.dom.get(ctx);
        ctxW = ctx.width();
        ctxH = ctx.height();
        
        var offset = this._findPos(ctx[0]);
        ctxX = offset.left;
        ctxY = offset.top;
        
        // Mid point of context
        midCtxX = ctxX + (ctxW / 2);
        midCtxY = ctxY + (ctxH / 2);
        
        // Find dimensions of panel
        pW = container.width();
        pH = container.height();
        
        // Calc. x and y pos. of panel
        pX = midCtxX - (pW / 2);
        pY = midCtxY - (pH / 2);
        
        //container.width( ctxW );
        //container.height( ctxH );
        container.css('top', pY + "px");
        container.css('left', pX + "px");
        
        if(DEBUG && console) console.log("Position panel at: ", pX, pY, container);
    },
    _findPos: function(obj) {
        var curleft = curtop = 0;
        if (obj.offsetParent) {
                curleft = obj.offsetLeft
                curtop = obj.offsetTop
                while (obj = obj.offsetParent) {
                        curleft += obj.offsetLeft
                        curtop += obj.offsetTop
                }
        }
        return { left:curleft, top:curtop }; //[curleft,curtop];
    },
    _removeParentalEventListeners: function() {
        if(DEBUG && console) console.log("Removing panel events listeners: ", this.panel._scrollEvt, this.panel._resizeEvt );
        glow.events.removeListener(this.panel._scrollEvt);
        glow.events.removeListener(this.panel._resizeEvt);
    },
    _proxyEventListeners: function(source, eventNames, destination) {
        var destination = destination || this,
            i = 0,
            len = eventNames.length;
        for ( ; i < len; i++ ) {
            glow.events.addListener( source, eventNames[i], this._createFireEvent( destination, eventNames[i] ) );
        }
    },
    _createFireEvent: function( eventSource, eventName ) {
        return function( event ) {
            glow.events.fire( eventSource, eventName, event );
        };
    }
}

if ( !bbc || !bbc.fmtj || !bbc.fmtj.apps || !bbc.fmtj.apps ) {
    window.bbc = window.bbc || {};
    window.bbc.fmtj = window.bbc.fmtj || {};
    window.bbc.fmtj.apps = window.bbc.fmtj.apps || {};
}

window.bbc.fmtj.apps.ContextPanel = ContextPanel;

})(); // end sandbox