﻿Ext.QuickTips.init();
Ext.plugins = [];
Ext.override(Ext.form.Field, {
    msgTarget: 'side',
    isLabel: false,
    setIsLabel: function(isLabel) {
        if (this.isLabel == isLabel)
            return;

        this.isLabel = isLabel;
        this.oldAllowBlank = this.allowBlank;
        this.allowBlank = true;
        if (this.wrap)
            this.wrap.setDisplayed(!isLabel);
        else
            Ext.form.Field.superclass[isLabel ? 'onHide' : 'onShow'].call(this);
        this.clearInvalid();
        if (isLabel) {
            this.lbl = this.container.createChild({});
            this.lbl.applyStyles('paddingTop:4px;');
            this.updateLabel();
            this.on('changed', this.updateLabel, this);
        }
        else {
            if (this.lbl) {
                this.lbl.remove();
                delete this.lbl;
            }
            if (typeof this.oldAllowBlank == 'undefined')
                this.oldAllowBlank = true;
            this.allowBlank = this.oldAllowBlank;
            this.un('changed', this.updateLabel, this);
        }
    },
    getIsLabel: function() { return this.isLabel },
    updateLabel: function() {
        var value = this.lastSelectionText ? this.lastSelectionText : this.getValue();
        if (this.inputType == 'password')
            value = value.replace(/\w/g, '*');
        this.lbl.dom.innerHTML = value.split ? value.split("\n").join("<br />") : value;
    },
    hide: function() {
        Ext.form.Field.superclass.hide.call(this);
        var c = this.container.up('div.x-form-item');
        if (!c)
            c = this.container;
        c.setDisplayed(false);
        return this;
    },
    show: function() {
        Ext.form.Field.superclass.show.call(this);
        var c = this.container.up('div.x-form-item');
        if (!c)
            c = this.container;
        c.setDisplayed(true);
        return this;
    },
    render: function(c, p) {
        Ext.form.Field.superclass.render.call(this, c, p);
        if (this.isLabel) {
            this.isLabel = false;
            this.setIsLabel(true);
        }
        return this;
    },
    onHide: Ext.emptyFn,
    onShow: Ext.emptyFn
});
Ext.override(Ext.form.TriggerField, {
    onHide: Ext.emptyFn,
    onShow: Ext.emptyFn,
    alignErrorIcon: function() {
        this.errorIcon.alignTo(this.trigger, 'tl-tr', [2, 0]); 
    },
    getErrorCt: function() {
        return this.wrap; 
    }
});
Ext.grid.GridPanel.prototype.callback = Ext.tree.TreePanel.prototype.callback = Ext.form.ComboBox.prototype.callback = Ext.form.TreeField.prototype.callback = function(config) {
    if (!config)
        config = {};
    Ext.applyIf(config, { loadMask: true, msgMask: 'Carregando...' });
    if (config.loadMask && this.bwrap)
        this.bwrap.mask(config.msgMask, 'x-mask-loading');
    if (!this.Ajax)
        this.Ajax = new FLAjax(this.id, this);
    config.xfn = this.afterCallback;
    this.Ajax.callback(config);
};
Ext.override(Ext.grid.GridPanel, {
    addKey: function() {
        this.addKeys.call(this, arguments[0]);
    },
    addKeys: function() {
        var store = this.store;
        var items = arguments[0].length > 0 ? arguments[0] : arguments;
        for (var i = 0; i < items.length; i++)
            store.proxy.data[store.proxy.data.length] = items[i];
        store.add(store.reader.readRecords(items).records);
    },
    updateKey: function(row, key) {
        var store = this.store;
        var index = store.proxy.data.indexOf(row.json);
        store.proxy.data[index] = key;
        index = store.findBy(function(r) { return r.json == row.json; })
        store.remove(store.getAt(index));
        store.insert(index, store.reader.readRecords([key]).records[0]);
    },
    removeKey: function() {
        this.removeKeys.call(this, arguments[0]);
    },
    removeKeys: function() {
        var store = this.store;
        var items = arguments[0].length > 0 ? arguments[0] : arguments;
        for (var i = 0; i < items.length; i++) {
            var key = items[i];
            var index = store.findBy(function(r) { return r.json == key; })
            store.remove(store.getAt(index));
            store.proxy.data.remove(key);
        }
    },
    getArrayKeys: function(items, args) {
        var result = [];
        var filter = function(obj) { };
        var clone = function(obj) { return obj; };
        var only = false;
        for (var x = 0; x < args.length; x++) {
            if (typeof (args[x]) == 'function') {
                filter = args[x];
                clone = function(obj) { return Ext.util.JSON.decode(Ext.util.JSON.encode(obj)); }
            } else {
                only = args[x];
            }
        }
        for (index = 0; index < items.length; index++) {
            if (!only || items[index].modified) {
                var obj = clone(items[index].json);
                filter(obj);
                result[result.length] = obj;
            }
        }
        return result;
    },
    getKeys: function() {
        return this.getArrayKeys(this.store.data.items, arguments);
    },
    getSelectedKeys: function() {
        return this.getArrayKeys(this.selModel.selections.items, arguments);
    },
    getSelectedKey: function() {
        return this.getArrayKeys(this.selModel.selections.items, arguments)[0];
    },
    getData: function(only) {
        var data = [];
        var items = this.store.data.items;
        for (index = 0; index < items.length; index++)
            if (!only || items[index].modified)
            data[index] = items[index].data;
        return data;
    },
    getSelectedData: function() {
        if (this.selModel.selections.items.length == 0)
            return null;
        if (arguments.length == 1)
            return this.selModel.selections.items[0].data[arguments[0]];
        var data = {};
        for (k in this.selModel.selections.items[0].data)
            data[k] = this.selModel.selections.items[0].data[k];
        return data;
    },
    getRecord: function(key, fn) {
        if (!fn)
            fn = function(r) { return r.json == key; };
        return this.store.getAt(this.store.findBy(fn));
    },
    clear: function() {
        this.store.proxy.data = [];
        this.store.removeAll();
    },
    afterCallback: function(rs) {
        var bbar = this.getBottomToolbar();
        var pData;
        if (bbar && bbar.getPageData)
            pData = bbar.getPageData();
        var store = this.store;
        store.proxy.data = eval(rs["__" + this.id + "_ds"]);
        store.reload();
        if (pData && pData.activePage > bbar.getPageData().pages)
            bbar.onClick('last');
        if (this.Ajax.config.loadMask && this.bwrap)
            this.bwrap.unmask(true);
    }
});
Ext.override(Ext.form.ComboBox, {
    afterCallback: function(rs) {
        var store = this.store;
        store.removeAll();
        store.loadData(eval(rs["__" + this.id + "_ds"]));
    }
});
Ext.override(Ext.tree.TreePanel, {
    afterCallback: function(rs) {
        this.root.attributes.children = eval(rs["__nodes"]);
        this.loader.load(this.root);
        if (this.Ajax.config.loadMask)
            this.bwrap.unmask(true);
    },
    getAllNodes: function() {
        var ar = [];
        return this.getChildrenNodes(this.getRootNode(), 0, ar, this.getRootNode());
    },
    findNode: function(value, nodes) {
        if (!nodes)
            nodes = this.root.childNodes;
        if (nodes.length == 0)
            return false;

        for (var x = 0; x < nodes.length; x++)
            if (nodes[x].attributes.value == value)
            return nodes[x];
        else {
            if (nodes[x].childNodes.length > 0) {
                var node = this.findNode(value, nodes[x].childNodes);
                if (node)
                    return node;
            }
        }
        return false;
    },
    getChildrenNodes: function(node, index, ar, fields) {

        if (node != null) {
            ar[index] = {};
            for (var i in fields) {
                if (typeof (fields[i]) == 'function')
                    continue;
                ar[index][i] = node[i];
            }
            index++;
            if (node.childNodes != null && node.childNodes.length > 0) {
                for (var j = 0; j < node.childNodes.length; j++) {
                    child = node.childNodes[j];
                    ar = this.getChildrenNodes(child, index, ar, child);
                    index = ar.length;
                }
            }
        }
        return ar;
    }
});
Ext.override(Ext.Panel, {
    validate: function() {
        var items = [];
        if (arguments.length == 0) {
            if (!this.items)
                return true;
            items = this.items.items;
        }
        else if (typeof (arguments[0]) == 'string')
            for (var x = 0; x < arguments.length; x++)
            items[items.length] = Ext.getCmp(arguments[0]);

        var result = true;
        for (var x = 0; x < items.length; x++)
            if (items[x].validate && !items[x].validate())
            result = false;
        return result;
    }
});
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); };
Ext.getWin = function(id) { return Ext.WindowMgr.get(id) };
Ext.getMenu = function(id) { return Ext.menu.MenuMgr.get(id) };
Ext.createObj = function(value) { return Ext.ComponentMgr.create(eval("(" + value + ")")); };
Ext.menu.Menu.prototype.cancelEvent = function(e) { if (e.stopEvent) e.stopEvent(); };
Ext.addJs = function(src) {
    var scripts = document.getElementsByTagName("script");
    for (x = 0; x < scripts.length; ++x)
        if (scripts[x].src == src)
        return;

    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = src;
    document.getElementsByTagName('head')[0].appendChild(script);
};
Ext.addCss = function(url) {
    try {
        var links = document.getElementsByTagName('link');
        for (var i = 0; i < links.length; i++)
            if (links[i].href == url)
            return;

        newScript = document.createElement("link");
        newScript.setAttribute("type", "text/css");
        newScript.setAttribute("rel", "stylesheet");
        newScript.setAttribute("href", url);
        document.getElementsByTagName('head')[0].appendChild(newScript);
    } catch (e) {
        document.write('<link tupe="text/css" rel="stylesheet" href="' + url + '" />');
    }
};
Ext.grid.GridPanel.completeEdit = function(editor, value, startValue) {
    eval("editor.record.json." + editor.record.fields.keys[editor.col] + " = " + Ext.util.JSON.encode(value));
};
Ext.ns('Ext.ux.layout');
Ext.ux.layout.ColumnFitLayout = Ext.extend(Ext.layout.ColumnLayout, {
    onLayout: function(ct, target) {
        Ext.ux.layout.ColumnFitLayout.superclass.onLayout.apply(this, arguments);

        var cs = ct.items.items, len = cs.length, c, i;
        var size = Ext.isIE && target.dom != Ext.getBody().dom ? target.getStyleSize() : target.getViewSize();
        var h = size.height - target.getPadding('tb');

        for (i = 0; i < len; i++) {
            c = cs[i];
            c.setHeight(h + (c.footer ? c.footer.getHeight() : 0));
        }
    }
});
Ext.Container.LAYOUTS['columnfit'] = Ext.ux.layout.ColumnFitLayout;
Ext.grid.CheckColumn = function(config) {
    Ext.apply(this, config);
        
    if (!this.id) {
        this.id = Ext.id();
    }
    Ext.plugins[this.id] = this;
    this.renderer = this.renderer.createDelegate(this);
};

Ext.grid.CheckColumn.prototype = {
    init: function(grid) {
        this.grid = grid;
        this.grid.on('render', function() {
            var view = this.grid.getView();
            view.mainBody.on('mousedown', this.onMouseDown, this);
        }, this);
    },

    onMouseDown: function(e, t) {
        if (t.className && t.className.indexOf('x-grid3-cc-' + this.id) != -1) {
            e.stopEvent();
            var index = this.grid.getView().findRowIndex(t);
            var record = this.grid.store.getAt(index);
            record.set(this.dataIndex, !record.data[this.dataIndex]);
            if (record.modified && record.data[this.dataIndex] == record.modified[this.dataIndex]) {
                delete record.modified[this.dataIndex];
                this.grid.store.afterReject(record)
            }
            if (this.handler)
                this.handler(this, record.data[this.dataIndex], this.grid.colModel.config.indexOf(this), record);
        }
    },

    renderer: function(v, p, record) {
        p.css += ' x-grid3-check-col-td';
        return '<div class="x-grid3-check-col' + (v ? '-on' : '') + ' x-grid3-cc-' + this.id + '">&#160;</div>';
    }
};
Ext.form.SearchField = Ext.extend(Ext.form.TwinTriggerField, {
    initComponent: function() {
        Ext.form.SearchField.superclass.initComponent.call(this);
        if (this.keyFilter == 'enter')
            this.on('specialkey', function(f, e) { if (e.getKey() == e.ENTER) { this.onTrigger2Click(); } }, this);
        this.addEvents('search', 'clear');
    },
    initEvents: function() {
        Ext.form.SearchField.superclass.initEvents.call(this);
        if (this.keyFilter == 'all')
            this.el.on('keyup', this.onTrigger2Click, this);
    },
    validationEvent: false,
    validateOnBlur: false,
    trigger1Class: 'x-form-clear-trigger',
    trigger2Class: 'x-form-search-trigger',
    hideTrigger1: true,
    width: 180,
    hasSearch: false,
    keyFilter: 'enter',
    xtype: 'search',
    onTrigger1Click: function() {
        if (this.hasSearch) {
            this.triggers[0].hide();
            this.hasSearch = false;
            this.setValue('');
            this.fireEvent("clear", this);
            this.focus();
        }
    },
    onTrigger2Click: function() {
        var v = this.getRawValue().trim();
        if (v.length < 1) {
            this.onTrigger1Click();
            return;
        }
        this.fireEvent("search", this, v);
        this.hasSearch = true;
        this.triggers[0].show();
        this.focus();
    }
});
Ext.reg("search", Ext.form.SearchField);
Ext.override(Ext.Button, {
    setIcon: function(icon) {
        if (this.rendered)
            this.container.child(this.buttonSelector).setStyle('background-image', 'url(' + icon + ')');
    }
});
Ext.override(Ext.tree.TreeLoader, {
    updateParams: function(data, extraParams) {
        data = Ext.apply(data, { __treeloader: 1 });
        this.baseParams = { __CALLBACKID: this.treeId, __CALLBACKPARAM: Ext.util.JSON.encode(data), __VIEWSTATE: "" };
        Ext.apply(this.baseParams, extraParams);
    },
    processResponse: function(response, node, callback) {
        var json = response.responseText.substr(2);
        try {
            var o = eval("(" + json + ")");
            node.beginUpdate();
            for (var i = 0, len = o.length; i < len; i++) {
                var n = this.createNode(o[i]);
                if (n) { node.appendChild(n) }
            }
            node.endUpdate();
            if (typeof callback == "function") {
                callback(this, node)
            }
        } catch (e) {
            this.handleFailure(response)
        }
    }
});
Ext.override(Ext.form.HtmlEditor, {
    allowBlank: true,
    markInvalid: function(css) {
        Ext.form.HtmlEditor.superclass.markInvalid.call(this, css);
        Ext.get(this.iframe).addClass(this.invalidClass);
    },
    clearInvalid: function() {
        Ext.form.HtmlEditor.superclass.clearInvalid.call(this);
        Ext.get(this.iframe).removeClass(this.invalidClass);
    },
    getErrorCt: function() { return this.el.findParent('.x-html-editor-wrap', 5, true); },
    validateValue: function(value) {
        if (this.allowBlank)
            return true;

        value = value.replace(/<[a-zA-Z\/][^>]*>/g, '').replace(/&nbsp;/g, '').trim();
        if (value.length > 0)
            return true;
            
        this.markInvalid(this.blankText);
        return false;
    },
    alignErrorIcon: function() {
        this.errorIcon.alignTo(this.tb.el, 'tl-tr', [-16, 4]);
    }
});
Ext.apply(Ext.form.VTypes, {
    daterange: function(val, field) {
        var date = field.parseDate(val);
        if (!date) {
            return;
        }
        if (field.beginField && (!this.dateRangeMax || (date.getTime() != this.dateRangeMax.getTime()))) {
            var start = Ext.getCmp(field.beginField);
            if (!start)
                return true;
            start.setMaxValue(date);
            this.dateRangeMax = date;
        }
        else if (field.endField && (!this.dateRangeMin || (date.getTime() != this.dateRangeMin.getTime()))) {
            var end = Ext.getCmp(field.endField);
            if (!end)
                return true;
            end.setMinValue(date);
            this.dateRangeMin = date;
        }
        return true;
    },
    password: function(val, field) {
        if (field.firstField) {
            var pwd = Ext.getCmp(field.firstField);
            return (val == pwd.getValue());
        }
        return true;
    },
    passwordText: 'As senhas não correspondem'
});