(function(dojo) {
    dojo.require('dojo.window');
    dojo.declare("NextendWindow", null, {
        constructor: function(args) {
            dojo.mixin(this, args);
            if(typeof window.nextendwindows == 'undefined'){
                window.nextendwindows = [];
            }
            this.container = dojo.query('.nextend-window-container', this.node)[0];
            this.containerinner = dojo.query('.nextend-window-container-inner', this.node)[0];
            this.showed = false;
            this.onResize();
            dojo.connect(window, 'resize', this, 'onResize');

            dojo.connect(document, 'click', function(e) {
                window.nextendwindow = false;
            });

            dojo.connect(this.save, 'click', this, 'hideOverlay');
            if (this.button) dojo.connect(this.button, 'click', this, 'showOverlay');
        },

        onResize: function() {
            this.vs = dojo.window.getBox();
            if (this.showed) this.showOverlay();
        },

        showOverlay: function() {
            dojo.style(this.node, 'display', 'block');
            dojo.style(this.node, 'visibility', 'visible');
            dojo.addClass(this.node, 'active');
            var vs = this.vs;
            dojo.contentBox(this.node, {
                w: vs.w,
                h: vs.h
            });
            dojo.marginBox(this.container, {
                w: vs.w,
                h: vs.h
            });
            
            var h = dojo.position(this.container).h;
            dojo.marginBox(this.containerinner, {
                h: h-70
            });

            if (this.showed == false) this.onResize();
            this.showed = true;
            window.nextendwindows.push(this);
            setTimeout(dojo.hitch(this, 'fireEvent', window, 'resize'), 500);
        },

        hideOverlay: function(e) {
            if(typeof window.nextendajax != 'undefined' && window.nextendajax > 0){
                dojo.stopEvent(e);
                alert('Please wait while processing AJAX call!');
                return;
            }
            if (e) {
                if (window.nextendwindow) return;
                window.nextendwindow = true;
            }
            this.showed = false;
            window.nextendwindows.pop();
            dojo.removeClass(this.node, 'active');
            var _this = this;
            setTimeout(function(){
                dojo.style(_this.node, 'visibility', 'hidden');
                dojo.style(_this.node, 'height', '1px');
            }, 450);
            this.onHide();
        },

        onHide: function() {

        }
    });
    
    /*
     * Close top window on ESC
     */
    dojo.connect(document, 'keyup', function(e){
        if(e.which == 27 && typeof window.nextendwindows != 'undefined' && window.nextendwindows.length > 0){
            window.nextendwindows[window.nextendwindows.length-1].hideOverlay(e);
        }
    });
})(ndojo);