
(function($){
    $.modalbox = {
        show : function(s)
        {
            if(!$.modalbox._cache) $.modalbox._cache = [];
            
            s = $.extend({}, $.modalbox.defaults, s);
            var showButton = s.showOk || s.showCancel;

            if($.isFunction(s.onopen))
            {
                if(!s.onopen()) return 0;
            };
            $.modalbox._viewport = null;
            $.modalbox._dragging = false;
            s.boxid = (s.boxid == null ? $.event.guid++ : s.boxid.toString());

            var h_id = s.boxid;
            if($.modalbox._cache[h_id]) $.modalbox.close(h_id);
            $.modalbox._cache[h_id] = s;

            if(!$.modalbox._zIndex) $.modalbox._zIndex = s.zIndex;
            $.modalbox._zIndex += 5;

            var bgif = ($.isFunction($.fn.bgiframe));

            var h_index = $.modalbox._zIndex;

            var h_body = '<div class="modalbox-body" _boxId="' + h_id + '"></div>'
            var h_title = s.showTitle ?
                '   <div class="modalbox-title">' +
                '       <div class="modalbox-title-content">' +
                '           <h3><span>' + s.title + '</span></h3>' +
                '           <a><span>X</span></a>' +
                '       </div>' +
                '   </div>' : "";

            var h_content ='<div class="modalbox-content"></div>';
            var h_b_ok = s.showOk ? '<input type="button" class="modalbox-button-ok" value="' + s.okBtnName + '" />' : "";
            var h_b_cancel = s.showCancel ? '<input type="button" class="modalbox-button-cancel" value="' + s.cancelBtnName + '" />' : "";
            var h_foot = showButton ? '<div class="modalbox-foot">' + h_b_ok + h_b_cancel + '</div>' : '';

            $("body").append($(h_body));

            var h_c_h = $(window).height();
            var h_c_w = $(window).width();
            $(".modalbox-body[_boxId=" + h_id + "]")
                .append($(h_title + h_content + h_foot))
                .css("z-index", h_index)
                .css("top", (Math.max(0, parseInt((h_c_h - s.height) / 2))) + "px")
                .css("left", (Math.max(0, parseInt((h_c_w - s.width) / 2))) + "px")
                .width(s.width)
                .height(s.height)
            ;
            var h_t_height = $(".modalbox-body[_boxId=" + h_id + "] .modalbox-title").height();
            var h_f_height = showButton ? $(".modalbox-body[_boxId=" + h_id + "] .modalbox-foot").height() : 0;
            var h_c_h = (s.height - h_t_height - h_f_height - 4);
            var h_c_w = (s.width - 4);

            var h_iframe = "";
            switch(s.contentType.toLowerCase())
            {
                case "url":
                    h_iframe = '<div class="modalbox-content-iframe"><iframe width="' + h_c_w + '" height="' + h_c_h + '" id="modalbox-iframe" frameborder="0" scrolling="auto" src="' + s.content + '" /></div>';
                    break;
                case "selector":
                    var _c_detail = $(s.content).html();
                    $.modalbox._cache[h_id]._html = _c_detail;
                    $(s.content + ":eq(0)").html("");
                case "html":
                default:
                    var a_scro = {"no": "overflow: hidden;", "x": "overflow-x: auto;", "y": "overflow-y: auto;", "auto": "overflow: auto;"};
                    var s_sc = a_scro[s.scroll] || "overflow: hidden;";
                    h_iframe = '<div class="modalbox-content-detail" style="width: ' + h_c_w + 'px;height: ' + h_c_h + 'px;' + s_sc + '">' + ($.modalbox._cache[h_id]._html || s.content) + '</div>';
                    break;
            };

            $(".modalbox-body[_boxId=" + h_id + "] .modalbox-content").append(h_iframe);

            if(s.showTitle)
            {
                $(".modalbox-body[_boxId=" + h_id + "] .modalbox-title")
                    .find("a").click(function(){
                        $.modalbox.close(h_id);
                        return false;
                    }).mousedown(function(){
                        $.modalbox.close(h_id);
                        return false;
                    })
                ;
            };

            if(s.showOk)
            {
                $(".modalbox-body[_boxId=" + h_id + "]")
                    .find("input.modalbox-button-ok")
                    .click(function(){
                        var onok = $.modalbox._cache[h_id].onok;
                        if($.isFunction(onok)) 
                        	onok();
                        $.modalbox.close(h_id);                        
                        return false;
                    });
            };

            if(s.showCancel)
            {
                $(".modalbox-body[_boxId=" + h_id + "]")
                    .find("input.modalbox-button-cancel")
                    .click(function(){
                        var oncancel = $.modalbox._cache[h_id].oncancel;
                        if($.isFunction(oncancel)) oncancel();
                        $.modalbox.close(h_id);
                        return false;
                    });
            };

            if(s.draggable && s.showTitle)
            {
                var h_drag_it = '<div id="modalbox-drag-it"><input id="modalbox-drag-it-input" readonly="readonly" type="text" /></div>';
                if($("#modalbox-drag-it").length == 0)
                {
                    $(h_drag_it).appendTo("body");
                }
                $("#modalbox-drag-it-input").width(s.width - 10);
                $(".modalbox-body[_boxId=" + h_id + "] .modalbox-title").mousedown(function(e){
                    $.modalbox.startdrag(e, h_id);
                })
            };

            if(s.modal)
            {
                h_c_h = $("body",parent.document).attr("clientHeight");
                h_c_w = $("body",parent.document).attr("clientWidth");
                var h_cover = '<div class="modalbox-cover"></div>';
                $("body").append(h_cover);
                $(".modalbox-cover")
                    .css("z-index", s.zIndex)
                    .width(h_c_w)
                    .height(h_c_h)
                ;
                if(bgif){
                	$(".modalbox-cover").bgiframe();
                }
            }
            else if(bgif) $(".modalbox-body[_boxId=" + h_id + "]").bgiframe();

            return h_id;
        },
        close: function(id)
        {
            if(typeof(id) == "undefined")
            {
                last = $(".modalbox-body[_boxId]:last");
                if(last.length == 0) return false;
                var id = last.attr("_boxId");
            }
            
            $(".modalbox-body[_boxId=" + id + "] .modalbox-title").unbind("mousedown");
            $(".modalbox-body[_boxId=" + id + "] .modalbox-title a").unbind("click");
            $(".modalbox-body[_boxId=" + id + "]").html("").remove();
            if($.modalbox._cache[id].modal)
            {
                $(".modalbox-cover",parent.document).html("").remove();
            }

            var onclose = $.modalbox._cache[id].onclose;
            if($.modalbox._cache[id].contentType.toLowerCase() == "selector")
            {
                $($.modalbox._cache[id].content + ":eq(0)").html($.modalbox._cache[id]._html);
            }

            $.modalbox._cache[id] = undefined;
            delete $.modalbox._cache[id];

            if($.isFunction(onclose)) onclose();
        },
        resize: function(o, id)
        {
            var ojq = id ? $(".modalbox-body[_boxId=" + id + "]") : $(".modalbox-body[_boxId]:last");
            if(ojq.length == 1){
                id = ojq.attr("_boxId");
                var s = $.modalbox._cache[id];
                if(!s) return !!alert("error cache");
                var showButton = s.showCancel || s.showOk;
                var h_t_height = $(".modalbox-body[_boxId=" + id + "] .modalbox-title").height();
                var h_f_height = showButton ? $(".modalbox-body[_boxId=" + id + "] .modalbox-foot").height() : 0;
                var h_c_h = (o.h - h_t_height - h_f_height - 4);
                var h_c_w = (o.w - 4);

                $.modalbox._cache[id].width = o.w;
                $.modalbox._cache[id].height = o.h;
                ojq.width(o.w).height(o.h);
                
                if(s.contentType == "url")
                {
                    ojq.find(".modalbox-content-iframe iframe:eq(0)").width(h_c_w).height(h_c_h);
                }
                else
                {
                    ojq.find(".modalbox-content-detail:eq(0)").width(h_c_w).height(h_c_h);
                }
                return true;
            }
            return false;
        },
        moveto: function(o, id)
        {
            var ojq = id ? $(".modalbox-body[_boxId=" + id + "]") : $(".modalbox-body[_boxId]:last");
            var x = 0, y = 0;
            if(typeof(o) == "string"){
                if(o == "center"){
                    id = ojq.attr("_boxId");
                    var s = $.modalbox._cache[id];
                    if(!s) return !!alert("error cache");
                    var h_c_h = $(window).height();
                    var h_c_w = $(window).width();
                    x = Math.max(0, parseInt((h_c_w - s.width) / 2));
                    y = Math.max(0, parseInt((h_c_h - s.height) / 2));
                }
            }
            else
            {
                x = o.x;
                y = o.y;
            }
            ojq.css("top", y + "px").css("left", x + "px");
            alert(1122);
            return true;
        },
        startdrag: function(e, id)
        {
            if(e.which != 1) return false;
            if($.modalbox._dragging) return false;
            $.modalbox.mathviewport(id);
            $.modalbox._dragging = true;

            var jq = $(".modalbox-body[_boxId=" + id + "]");
            var offset = jq.offset();

            var posX;
            var posY;
            if ($.browser.msie) {
                posY = window.event.clientY + document.body.scrollTop;
                posX = window.event.clientX + document.body.scrollLeft;
            } else {
                posY = e.clientY + window.scrollY;
                posX = e.clientX + window.scrollX;
            }

            var xOffs = posX - parseInt(offset.left);
            var yOffs = posY - parseInt(offset.top);
            var hwidth = $.modalbox._cache[id].width;
            var hheight = $.modalbox._cache[id].height;

            $("#modalbox-drag-it")
                .width(jq.width())
                .height(jq.height())
                .css("left", jq.css("left"))
                .css("top", jq.css("top"))
                .show();
            $(document)
                .mousemove(function(e){
                    var posX;
                    var posY;
                    if ($.browser.msie) {
                        posY = window.event.clientY + document.body.scrollTop;
                        posX = window.event.clientX + document.body.scrollLeft;
                    } else {
                        posX = e.pageX;
                        posY = e.pageY;
                    }

                    var left = (posX - xOffs);
                    var top = (posY - yOffs);
                    
                    // prevent horizontal move verflow width
                    if(hwidth < $.modalbox._viewport.width - 6)
                    {
                        if(left <= 1) left = 1; if(left >= $.modalbox._viewport.maxLeft) left = $.modalbox._viewport.maxLeft;
                        $("#modalbox-drag-it").css("left",left + "px");
                    }
                    
                    // prevent vertical move overflow height
                    if(hheight < $.modalbox._viewport.height)
                    {
                        if(top <= 1) top = 1; if(top >= $.modalbox._viewport.maxTop) top = $.modalbox._viewport.maxTop;
                        $("#modalbox-drag-it").css("top",top + "px");
                    }
                })
                .mouseup(function(e){
                    $(".modalbox-body[_boxId=" + id + "]")
                        .css("left", $("#modalbox-drag-it").css("left"))
                        .css("top", $("#modalbox-drag-it").css("top"))
                    ;

                    $("#modalbox-drag-it").hide();
                    $.modalbox._dragging = false;
                    $(document).unbind("mousemove").unbind("mouseover").unbind("mouseup");
                })
                .mouseover(function(e){
                    if ($.browser.msie) {
                        window.event.cancelBubble = true;
                        window.event.returnValue = false;
                    } else {
                        e.preventDefault();
                        e.stopPropagation();
                    }
                    return false;
                });
        },
        mathviewport: function(id)
        {
            $.modalbox._viewport = [];
            if(!$.browser.msie)
            {
                // in standards compliant mode (i.e. with a valid doctype as the first line in the document)
                if (typeof document.documentElement != 'undefined'
                && typeof document.documentElement.scrollWidth !=
                'undefined' && document.documentElement.scrollWidth != 0)
                {
                    $.modalbox._viewport.width = document.documentElement.scrollWidth;
                    $.modalbox._viewport.height = document.documentElement.scrollHeight;
                }        

                $.modalbox._viewport.width = Math.max($.modalbox._viewport.width, (Math.max(document.body.scrollWidth, document.body.clientWidth)));
                $.modalbox._viewport.height = Math.max($.modalbox._viewport.height, (Math.max(document.body.scrollHeight, document.body.clientHeight)));
            }
            else
            {
                // in standards compliant mode (i.e. with a valid doctype as the first line in the document)
                if (typeof document.documentElement != 'undefined'
                && typeof document.documentElement.clientWidth !=
                'undefined' && document.documentElement.clientWidth != 0)
                {
                    $.modalbox._viewport.width = document.documentElement.clientWidth;
                    $.modalbox._viewport.height = document.documentElement.clientHeight;
                }
                // older versions of IE
                else
                {
                    $.modalbox._viewport.width = document.getElementsByTagName('body')[0].clientWidth;
                    $.modalbox._viewport.height = document.getElementsByTagName('body')[0].clientHeight;
                }

                $.modalbox._viewport.width = Math.max(document.body.scrollWidth, $.modalbox._viewport.width);
                $.modalbox._viewport.height = Math.max(document.body.scrollHeight, $.modalbox._viewport.height);
            }

            $.modalbox._viewport.maxLeft = $.modalbox._viewport.width - $.modalbox._cache[id].width - 6;
            $.modalbox._viewport.maxTop = $.modalbox._viewport.height - $.modalbox._cache[id].height - 6;
        }
    };
    
    $.modalbox.defaults = {
        boxid: null,
        title: '',
        contentType: 'html', // html selector url
        content: "",
        width: 400,
        height: 200,

        draggable: true,
        modal: true,
        scroll: "y",

        showTitle: true,
        showCancel: true, 
        showOk: true,

        okBtnName: 'Ok',
        cancelBtnName: 'Cancel',
        zIndex: 900,
        onclose: null,
        onopen: null,
        onok: null,
        oncancel: null
    }
})(jQuery);


