/**
 * Class to create a new pop-up window
 */
TPopup = function(name, width, height, top, left) {

    this.id        = name;
    this.top       = !top ? -1 : top;
    this.left      = !left ? -1 : left;
    this.width     = !width ? 200 : width;
    this.height    = !height ? 200 : height;
    this.scrolls   = false;
    this.toolbar   = false;
    this.statusbar = false;
    this.resizable = false;

    this.handler   = null;

    /**
     * Open a new window
     */
    this.open = function(url) {
        this.top  = this.top < 0 ? (screen.height - this.height - 40) / 2 : this.top;
        this.left = this.left < 0 ? (screen.width - this.width - 25) / 2 : this.left;
        var settings  ='width='+this.width+',';
            settings +='height='+this.height+',';
            settings +='top='+this.top+',';
            settings +='left='+this.left+',';
            settings +='status='+(this.statusbar ? 1 : 0)+',';
            settings +='toolbar='+(this.toolbar ? 1 : 0)+',';
            settings +='resizable='+(this.resizable ? 1 : 0)+',';
            settings +='scrollbars='+(this.scrolls ? 1 : 0);
        this.handler = window.open(url,this.id,settings);
        if (this.handler) {
            this.handler.focus();
        }
    }

    /**
     * Open a new window as a modal win
     * Note: since FF2 does not support bring to front
     *       child windows when focusing we now close
     *      the child window when loose the focus
     */
    this.showModal = function(url) {
        this.open(url);
        TEvents.listen(this.handler.opener,'focus',this._keepModal,this);
    }

    this._keepModal = function(win,e) {
        // this.handler.focus();
        TEvents.unlisten(this.handler.opener,'focus',this._keepModal);
        this.handler.close();
    }

    /**
     * Minimize the opened window
     */
    this.minimize = function minimize(){
        this.win.blur();
    }
}

/**
 * Static method to instantly create a new TPopup
 * and open it.
 */
TPopup.New = function(name,width,height,src,scrolls,resizable,modal) {
    var popup = new TPopup(name);
    popup.scrolls = scrolls;
    popup.resizable = resizable;
    if (screen.height - 150 < height) {
        height = screen.height - 150;
        popup.scrolls = true;
    }
    if (screen.width - 150 < width) {
        width = screen.width - 150;
        popup.scrolls = true;
    }
    popup.width = width;
    popup.height = height;
    if (modal) {
        popup.showModal(src);
    } else {
        popup.open(src);
    }
    return popup;
}
