﻿/**
 * jQuery EasyUI 1.3.6
 * 
 * Copyright (c) 2009-2014 www.jeasyui.com. All rights reserved.
 *
 * Licensed under the GPL license: http://www.gnu.org/licenses/gpl.txt
 * To use it on other terms please contact us at info@jeasyui.com
 *
 */
require('./parser');
//require('./css/panel.css');

(function($) {
    $.fn._remove = function() {
        return this.each(function() {
            $(this).remove();
            try {
                this.outerHTML = "";
            } catch (err) {}
        });
    };

    function removeEach(target) {
        target._remove();
    };

    function resize(target, options) {
        var opts = $.data(target, "panel").options;
        var panel = $.data(target, "panel").panel;
        var panelHeader = panel.children("div.panel-header");
        var panelContent = panel.children("div.panel-content");
        if (options) {
            $.extend(opts, {
                width: options.width,
                height: options.height,
                left: options.left,
                top: options.top
            });
        }
        opts.fit ? $.extend(opts, panel._fit()) : panel._fit(false);
        panel.css({
            left: opts.left,
            top: opts.top
        });
        if (!isNaN(opts.width)) {
            panel._outerWidth(opts.width);
        } else {
            panel.width("auto");
        }
        if (!isNaN(opts.height)) {
            panel._outerHeight(opts.height);
            panelContent._outerHeight(panel.height() - panelHeader._outerHeight());
        } else {
            panelContent.height("auto");
        }
        panel.css("height", "");
        opts.onResize.apply(target, [opts.width, opts.height]);
        $(target).find(">div:visible,>form>div:visible").triggerHandler("_resize");
    };

    function move(target, options) {
        var opts = $.data(target, "panel").options;
        var panel = $.data(target, "panel").panel;
        if (options) {
            if (options.left != null) {
                opts.left = options.left;
            }
            if (options.top != null) {
                opts.top = options.top;
            }
        }
        panel.css({
            left: opts.left,
            top: opts.top
        });
        opts.onMove.apply(target, [opts.left, opts.top]);
    };

    function create(target) {
        $(target).addClass("panel-content");
        var panel = $("<div class=\"panel\"></div>").insertBefore(target);
        panel[0].appendChild(target);
        panel.bind("_resize", function() {
            var opts = $.data(target, "panel").options;
            if (opts.fit == true) {
                resize(target);
            }
            return false;
        });
        return panel;
    };

    function init(target) {
        var opts = $.data(target, "panel").options;
        var panel = $.data(target, "panel").panel;
        if (opts.tools && typeof opts.tools == "string") {
            panel.find(">div.panel-header>div.panel-tool .panel-tool-a").appendTo(opts.tools);
        }
        removeEach(panel.children("div.panel-header"));
        if (opts.title && !opts.noheader) {
            var panelHeader = $("<div class=\"panel-header\"><div class=\"panel-title\">" + opts.title + "</div></div>").prependTo(panel);
            if (opts.iconCls) {
                panelHeader.find(".panel-title").addClass("panel-with-icon");
                $("<div class=\"panel-icon\"></div>").addClass(opts.iconCls).appendTo(panelHeader);
            }
            var panelTool = $("<div class=\"panel-tool\"></div>").appendTo(panelHeader);
            panelTool.bind("click", function(e) {
                e.stopPropagation();
            });
            if (opts.tools) {
                if ($.isArray(opts.tools)) {
                    for (var i = 0; i < opts.tools.length; i++) {
                        var t = $("<a href=\"javascript:void(0)\"></a>").addClass(opts.tools[i].iconCls).appendTo(panelTool);
                        if (opts.tools[i].handler) {
                            t.bind("click", eval(opts.tools[i].handler));
                        }
                    }
                } else {
                    $(opts.tools).children().each(function() {
                        $(this).addClass($(this).attr("iconCls")).addClass("panel-tool-a").appendTo(panelTool);
                    });
                }
            }
            if (opts.collapsible) {
                $("<a class=\"panel-tool-collapse\" href=\"javascript:void(0)\"></a>").appendTo(panelTool).bind("click", function() {
                    if (opts.collapsed == true) {
                        showPanelContent(target, true);
                    } else {
                        hidePanelContent(target, true);
                    }
                    return false;
                });
            }
            if (opts.minimizable) {
                $("<a class=\"panel-tool-min\" href=\"javascript:void(0)\"></a>").appendTo(panelTool).bind("click", function() {
                    minimize(target);
                    return false;
                });
            }
            if (opts.maximizable) {
                $("<a class=\"panel-tool-max\" href=\"javascript:void(0)\"></a>").appendTo(panelTool).bind("click", function() {
                    if (opts.maximized == true) {
                        restore(target);
                    } else {
                        maximize(target);
                    }
                    return false;
                });
            }
            if (opts.closable) {
                $("<a class=\"panel-tool-close\" href=\"javascript:void(0)\"></a>").appendTo(panelTool).bind("click", function() {
                    hidePanel(target);
                    return false;
                });
            }
            panel.children("div.panel-content").removeClass("panel-content-noheader");
        } else {
            panel.children("div.panel-content").addClass("panel-content-noheader");
        }
    };

    function refreshPanelContent(target, params) {
        var state = $.data(target, "panel");
        var opts = state.options;
        if (params) {
            opts.queryParams = params;
        }
        if (opts.href) {
            if (!state.isLoaded || !opts.cache) {
                var queryParams = $.extend({}, opts.queryParams);
                if (opts.onBeforeLoad.call(target, queryParams) == false) {
                    return;
                }
                state.isLoaded = false;
                destroyPanelContent(target);
                if (opts.loadingMessage) {
                    $(target).html($("<div class=\"panel-loading\"></div>").html(opts.loadingMessage));
                }
                opts.loader.call(target, queryParams, function(data) {  //success callback
                    reloadContent(opts.extractor.call(target, data)); //format remote data
                    opts.onLoad.apply(target, arguments);
                    state.isLoaded = true;
                }, function() { //error callback
                    opts.onLoadError.apply(target, arguments);
                });
            }
        } else {
            if (opts.content) {
                if (!state.isLoaded) {
                    destroyPanelContent(target);
                    reloadContent(opts.content);
                    state.isLoaded = true;
                }
            }
        }

        function reloadContent(content) {
            $(target).html(content);
            $.parser.parse($(target));
        };
    };

    function destroyPanelContent(target) {
        var t = $(target);
        t.find(".combo-f").each(function() {
            $(this).combo("destroy");
        });
        t.children("div").each(function() {
            $(this)._fit(false);
        });
    };

    function resizePanel(target) {
        $(target).find("div.panel:visible").each(function() {
            $(this).triggerHandler("_resize", [true]);
        });
    };

    function showPanel(target, force) {
        var opts = $.data(target, "panel").options;
        var panel = $.data(target, "panel").panel;
        if (force != true) {
            if (opts.onBeforeOpen.call(target) == false) {
                return;
            }
        }
        panel.show();
        opts.closed = false;
        opts.minimized = false;
        var restoreBtn = panel.children("div.panel-header").find("a.panel-tool-restore");
        if (restoreBtn.length) {
            opts.maximized = true;
        }
        opts.onOpen.call(target);
        if (opts.maximized == true) {
            opts.maximized = false;
            maximize(target);
        }
        if (opts.collapsed == true) {
            opts.collapsed = false;
            hidePanelContent(target);
        }
        if (!opts.collapsed) {
            refreshPanelContent(target);
            resizePanel(target);
        }
    };

    function hidePanel(target, force) {
        var opts = $.data(target, "panel").options;
        var panel = $.data(target, "panel").panel;
        if (force != true) {
            if (opts.onBeforeClose.call(target) == false) {
                return;
            }
        }
        panel._fit(false);
        panel.hide();
        opts.closed = true;
        opts.onClose.call(target);
    };

    function destroy(target, force) {
        var opts = $.data(target, "panel").options;
        var panel = $.data(target, "panel").panel;
        if (force != true) {
            if (opts.onBeforeDestroy.call(target) == false) {
                return;
            }
        }
        destroyPanelContent(target);
        removeEach(panel);
        opts.onDestroy.call(target);
    };

    function hidePanelContent(target, animate) {
        var opts = $.data(target, "panel").options;
        var panel = $.data(target, "panel").panel;
        var panelContent = panel.children("div.panel-content");
        var collapseBtn = panel.children("div.panel-header").find("a.panel-tool-collapse");
        if (opts.collapsed == true) {
            return;
        }
        panelContent.stop(true, true);
        if (opts.onBeforeCollapse.call(target) == false) {
            return;
        }
        collapseBtn.addClass("panel-tool-expand");
        if (animate == true) {
            panelContent.slideUp("normal", function() {
                opts.collapsed = true;
                opts.onCollapse.call(target);
            });
        } else {
            panelContent.hide();
            opts.collapsed = true;
            opts.onCollapse.call(target);
        }
    };

    function showPanelContent(target, animate) {
        var opts = $.data(target, "panel").options;
        var panel = $.data(target, "panel").panel;
        var panelContent = panel.children("div.panel-content");
        var collapseBtn = panel.children("div.panel-header").find("a.panel-tool-collapse");
        if (opts.collapsed == false) {
            return;
        }
        panelContent.stop(true, true);
        if (opts.onBeforeExpand.call(target) == false) {
            return;
        }
        collapseBtn.removeClass("panel-tool-expand");
        if (animate == true) {
            panelContent.slideDown("normal", function() {
                opts.collapsed = false;
                opts.onExpand.call(target);
                refreshPanelContent(target);
                resizePanel(target);
            });
        } else {
            panelContent.show();
            opts.collapsed = false;
            opts.onExpand.call(target);
            refreshPanelContent(target);
            resizePanel(target);
        }
    };

    function maximize(target) {
        var opts = $.data(target, "panel").options;
        var panel = $.data(target, "panel").panel;
        var maxBtn = panel.children("div.panel-header").find("a.panel-tool-max");
        if (opts.maximized == true) {
            return;
        }
        maxBtn.addClass("panel-tool-restore");
        if (!$.data(target, "panel").original) {
            $.data(target, "panel").original = {
                width: opts.width,
                height: opts.height,
                left: opts.left,
                top: opts.top,
                fit: opts.fit
            };
        }
        opts.left = 0;
        opts.top = 0;
        opts.fit = true;
        resize(target);
        opts.minimized = false;
        opts.maximized = true;
        opts.onMaximize.call(target);
    };

    function minimize(target) {
        var opts = $.data(target, "panel").options;
        var panel = $.data(target, "panel").panel;
        panel._fit(false);
        panel.hide();
        opts.minimized = true;
        opts.maximized = false;
        opts.onMinimize.call(target);
    };

    function restore(target) {
        var opts = $.data(target, "panel").options;
        var panel = $.data(target, "panel").panel;
        var maxBtn = panel.children("div.panel-header").find("a.panel-tool-max");
        if (opts.maximized == false) {
            return;
        }
        panel.show();
        maxBtn.removeClass("panel-tool-restore");
        $.extend(opts, $.data(target, "panel").original);
        resize(target);
        opts.minimized = false;
        opts.maximized = false;
        $.data(target, "panel").original = null;
        opts.onRestore.call(target);
    };

    function initStyle(target) {
        var opts = $.data(target, "panel").options;
        var panel = $.data(target, "panel").panel;
        var panelHeader = $(target).panel("header");
        var panelContent = $(target).panel("body");
        panel.css(opts.style);
        panel.addClass(opts.cls);
        if (opts.border) {
            panel.removeClass("panel-noborder");
        } else {
            panel.addClass("panel-noborder");
        }
        panelHeader.addClass(opts.headerCls);
        panelContent.addClass(opts.bodyCls);
        if (opts.id) {
            $(target).attr("id", opts.id);
        } else {
            $(target).attr("id", "");
        }
    };

    function setTitle(target, title) {
        $.data(target, "panel").options.title = title;
        $(target).panel("header").find("div.panel-title").html(title);
    };
    var TO = false;  //timeout obj
    var _5b = true;
    // @todo unkown func
    $(window).unbind(".panel").bind("resize.panel", function() {
        if (!_5b) {
            return;
        }
        if (TO !== false) {
            clearTimeout(TO);
        }
        TO = setTimeout(function() {
            _5b = false;
            $("body").children("div.panel:visible").triggerHandler("_resize");
            _5b = true;
            TO = false;
        }, 200);
    });
    $.fn.panel = function(options, param) {
        if (typeof options == "string") {
            return $.fn.panel.methods[options](this, param);
        }
        options = options || {};
        return this.each(function() {
            var state = $.data(this, "panel");
            var opts;
            if (state) {
                opts = $.extend(state.options, options);
                state.isLoaded = false;
            } else {
                opts = $.extend({}, $.fn.panel.defaults, $.fn.panel.parseOptions(this), options);
                $(this).attr("title", "");
                state = $.data(this, "panel", {
                    options: opts,
                    panel: create(this),
                    isLoaded: false
                });
            }
            init(this);
            initStyle(this);
            if (opts.doSize == true) {
                state.panel.css("display", "block");
                resize(this);
            }
            if (opts.closed == true || opts.minimized == true) {
                state.panel.hide();
            } else {
                showPanel(this);
            }
        });
    };
    $.fn.panel.methods = {
        options: function(jq) {
            return $.data(jq[0], "panel").options;
        },
        panel: function(jq) {
            return $.data(jq[0], "panel").panel;
        },
        header: function(jq) {
            return $.data(jq[0], "panel").panel.find(">div.panel-header");
        },
        body: function(jq) {
            return $.data(jq[0], "panel").panel.find(">div.panel-content");
        },
        setTitle: function(jq, title) {
            return jq.each(function() {
                setTitle(this, title);
            });
        },
        open: function(jq, forceOpen) {
            return jq.each(function() {
                showPanel(this, forceOpen);
            });
        },
        close: function(jq, forceClose) {
            return jq.each(function() {
                hidePanel(this, forceClose);
            });
        },
        destroy: function(jq, forceDestroy) {
            return jq.each(function() {
                destroy(this, forceDestroy);
            });
        },
        refresh: function(jq, params) {
            return jq.each(function() {
                var panel = $.data(this, "panel");
                panel.isLoaded = false;
                if (params) {
                    if (typeof params == "string") {
                        panel.options.href = params;
                    } else {
                        panel.options.queryParams = params;
                    }
                }
                refreshPanelContent(this);
            });
        },
        resize: function(jq, options) {
            return jq.each(function() {
                resize(this, options);
            });
        },
        move: function(jq, options) {
            return jq.each(function() {
                move(this, options);
            });
        },
        maximize: function(jq) {
            return jq.each(function() {
                maximize(this);
            });
        },
        minimize: function(jq) {
            return jq.each(function() {
                minimize(this);
            });
        },
        restore: function(jq) {
            return jq.each(function() {
                restore(this);
            });
        },
        collapse: function(jq, animate) {
            return jq.each(function() {
                hidePanelContent(this, animate);
            });
        },
        expand: function(jq, animate) {
            return jq.each(function() {
                showPanelContent(this, animate);
            });
        }
    };
    $.fn.panel.parseOptions = function(target) {
        var t = $(target);
        return $.extend({}, $.parser.parseOptions(target, ["id", "width", "height", "left", "top", "title", "iconCls", "cls", "headerCls", "bodyCls", "tools", "href", "method", {
            cache: "boolean",
            fit: "boolean",
            border: "boolean",
            noheader: "boolean"
        }, {
            collapsible: "boolean",
            minimizable: "boolean",
            maximizable: "boolean"
        }, {
            closable: "boolean",
            collapsed: "boolean",
            minimized: "boolean",
            maximized: "boolean",
            closed: "boolean"
        }]), {
            loadingMessage: (t.attr("loadingMessage") != undefined ? t.attr("loadingMessage") : undefined)
        });
    };
    $.fn.panel.defaults = {
        id: null,
        title: null,
        iconCls: null,
        width: "auto",
        height: "auto",
        left: null,
        top: null,
        cls: null,
        headerCls: null,
        bodyCls: null,
        style: {},
        href: null,
        cache: true,
        fit: false,
        border: true,
        doSize: true,
        noheader: false,
        content: null,
        collapsible: false,
        minimizable: false,
        maximizable: false,
        closable: false,
        collapsed: false,
        minimized: false,
        maximized: false,
        closed: false,
        tools: null,
        queryParams: {},
        method: "get",
        href: null,
        loadingMessage: "Loading...",
        loader: function(param, successCallback, errorCallback) {
            var opts = $(this).panel("options");
            if (!opts.href) {
                return false;
            }
            $.ajax({
                type: opts.method,
                url: opts.href,
                cache: false,
                data: param,
                dataType: "html",
                success: function(data) {
                    successCallback(data);
                },
                error: function() {
                    errorCallback.apply(this, arguments);
                }
            });
        },
        extractor: function(data) {
            var pattern = /<body[^>]*>((.|[\n\r])*)<\/body>/im;
            var matches = pattern.exec(data);
            if (matches) {
                return matches[1];
            } else {
                return data;
            }
        },
        onBeforeLoad: function(param) {},
        onLoad: function() {},
        onLoadError: function() {},
        onBeforeOpen: function() {},
        onOpen: function() {},
        onBeforeClose: function() {},
        onClose: function() {},
        onBeforeDestroy: function() {},
        onDestroy: function() {},
        onResize: function(width, height) {},
        onMove: function(left, top) {},
        onMaximize: function() {},
        onRestore: function() {},
        onMinimize: function() {},
        onBeforeCollapse: function() {},
        onBeforeExpand: function() {},
        onCollapse: function() {},
        onExpand: function() {}
    };
})(jQuery);
