var dialog = new function() {
    
    this.width = 920;
    this.maxWidth = $(window).width()-100;
    this.height = "auto";
    this.maxHeight = $(window).height()-100;
    this.position = ['top', 50];

    this.open = function(content, title, width, height, index) {
        
        if(typeof(index) == "undefined") index = 0;
        if(typeof(index) == "boolean") {
            index = 0;
            while($("#dialog"+index).length != 0 && index < 5) {
                index++;
            }
        };
        
        if($("#dialog"+index).length == 0) {
            this.generate(index);
        }
        
        if(typeof(title) == "string") $("#dialog"+index).dialog("option", "title", title);
        if(isNaN(parseInt(width))) width = this.width;
        if(isNaN(parseInt(height))) height = this.height;   
        
        document.getElementById("dialog"+index).innerHTML = "<div style='max-height: " + (this.maxHeight - 50) + "px;'>" + content + "</div>";        
        if(!this.isOpen(index) || index == 0) {
            $("#dialog"+index).dialog("option", "width", width);
            $("#dialog"+index).dialog("option", "height", height);
            $("#dialog"+index).dialog("option", "position", this.position);
            $("#dialog"+index).dialog("open");
        } else {
            $("#dialog"+index).dialog("moveToTop");
        }
        
        return index;
        
    };
    
    this.close = function(timeout, index) {
        
        if(typeof(timeout) == "number") {
            setTimeout(function() {
                dialog.close(null, index)
            }, timeout);
            
            return;
        }
        
        if(typeof(index) != "undefined") {
            if(index.substring(0, 6) == "dialog") index = index.substring(6);
            $("#dialog"+index).dialog("close");
            $("#dialog"+index).html(" ");
            $("#dialog"+index).dialog("option", "title", " ");
        } else {
            $("div[id^=dialog]").each(function() {
                $(this).dialog("close");
                $(this).html(" ");
                $(this).dialog("option", "title", " ");
            });
        }
    };
    
    this.isOpen = function(index) {
        if(typeof(index) == "undefined") index = 0;
        if($("#dialog"+index).length == 0) return false;
        else return $("#dialog"+index).dialog("isOpen");
    }
    
    this.generate = function(index) {
        $("body").append('<div id="dialog' + index + '" style="display: none; "></div>');
        $("#dialog"+index).dialog({
                autoOpen: false,
                position: this.position,
                minHeight: 150,
                minWidth: 300,
                maxHeight: this.maxHeight,
                maxWidth: this.maxWidth,
                close: function(event, ui) {
                    document.getElementById(event.target.id).innerHTML = '';
                    }
            });
    };
    
}


