﻿function ConfigObj(el) {
    this.getBool = function(attr, def) {
        if (el.getAttribute(attr) == null) return def;
        return el.getAttribute(attr) == "true";
    };
    this.getInt = function(attr, def) {
        if (el.getAttribute(attr) == null) return def;
        return parseInt(el.getAttribute(attr));
    };
    this.getFloat = function(attr, def) {
        if (el.getAttribute(attr) == null) return def;
        return parseFloat(el.getAttribute(attr));
    };
    this.getRegex = function(attr) {
        if (el.getAttribute(attr) == null) return null;
        return new RegExp(el.getAttribute(attr));
    };
    this.getStr = function(attr) {
        if (el.getAttribute(attr) == null) return "";
        return el.getAttribute(attr);
    };
    this.getWidth = function(def) {
        if (el.getAttribute("ext_width") != null)
            return el.getAttribute("ext_width");
        return (def == null) ? "auto" : def;
    };
    this.getHeight = function(def) {
        if (el.getAttribute("ext_height") != null)
            return el.getAttribute("ext_height");
        return (def == null) ? "auto" : def;
    };

    this.id = el.id;
    this.name = el.name;
    if (el.getAttribute('ext_value') == null)
        this.value = this.getStr('value');
    else
        this.value = this.getStr('ext_value');
    this.standardSubmit = this.getBool('ext_standardSubmit', true);

    this.allowBlank = this.getBool("ext_allowBlank", true);
    if (el.getAttribute("ext_blankText") != null)
        this.blankText = el.getAttribute("ext_blankText");
    this.cls = this.getStr("ext_cls");
    this.disabled = this.getBool("ext_disabled", false);
    this.readonly = this.getBool("ext_readonly", false);
    this.validateOnBlur = this.getBool("ext_validateOnBlur", true);
    this.width = this.getWidth();
    this.height = this.getHeight();
    this.xtype = this.getStr("xtype");

    this.inputType = this.getStr("ext_inputType");
    this.disableKeyFilter = this.getBool("ext_disableKeyFilter", false);
    this.emptyText = this.getStr("ext_emptyText");
    this.maskRe = this.getRegex("ext_maskRe");
    this.maxLength = this.getInt("ext_maxLength", Number.MAX_VALUE);
    this.minLength = this.getInt("ext_minLength", 0);
    this.regex = this.getRegex("ext_regex");
    this.regexText = this.getStr("ext_regexText");
    this.selectOnFocus = this.getBool("ext_selectOnFocus", false);
    this.vtype = this.getStr("ext_vtype");

    if (this.xtype == "numberfield") {
        this.allowDecimals = this.getBool("ext_allowDecimals", true);
        this.allowNegative = this.getBool("ext_allowNegative", true);
        this.decimalPrecision = this.getInt("ext_decimalPrecision", 2);
        this.maxValue = this.getFloat("ext_maxValue", Number.MAX_VALUE);
        this.minValue = this.getFloat("ext_minValue", Number.NEGATIVE_INFINITY);
    }

    if (this.xtype == "datefield") {
        this.format = this.getStr("ext_format");
        this.showToday = this.getBool("ext_showToday", true);
    }

    if (this.xtype == "timefield") {
        this.format = this.getStr("ext_format");
        this.increment = this.getInt("ext_increment", 5);
        this.minValue = this.getStr("ext_minValue");
        this.maxValue = this.getStr("ext_maxValue");
    }

    if (this.xtype == "combo") {
        this.mode = this.getStr("ext_mode");
        this.editable = this.getBool("ext_editable", true);
        this.forceSelection = this.getBool("ext_forceSelection", false);
        this.resizable = this.getBool("ext_resizable", false);
        this.displayField = this.getStr("ext_displayField");
        this.valueField = this.getStr("ext_valueField");
        this.maxHeight = this.getInt("ext_maxHeight", 300);
        this.listWidth = this.getInt("ext_listWidth", 200);
        this.hideTrigger = this.getBool("ext_hideTrigger", false);
    }

    this.columns = this.getInt("ext_columns", 1);
    this.initialPassField = this.getStr("ext_initialPassField");
};

Ext.apply(Ext.form.VTypes, {
    password: function(val, field) {
        if (field.initialPassField != null && field.initialPassField.length > 0) {
            var pwd = Ext.getCmp(field.initialPassField);
            return (val == pwd.getValue());
        }
        return true;
    },

    passwordText: 'Passwords do not match'
});

// fix the bug
Ext.form.TriggerField.override({
    afterRender: function() {
        Ext.form.TriggerField.superclass.afterRender.call(this);
        var y;
        if (Ext.isIE && !this.hideTrigger && this.el.getY() != (y = this.trigger.getY())) {
            this.el.position();
            this.el.setY(y);
        }
    }
});

Ext.override(Ext.form.TextField, {
    validator: function(text) {
        if (this.allowBlank == false && Ext.util.Format.trim(text).length == 0)
            return false;
        else
            return true;
    }
}); 


// extend CheckboxList
Ext.form.CheckboxList = function() {
    Ext.form.CheckboxList.superclass.constructor.apply(this, arguments);
};
Ext.extend(Ext.form.CheckboxList, Ext.form.Field, {
    onRender: function(ct, position) {
    },
    validateValue: function(value) {
        if (this.allowBlank == false && this.getValues() == '') {
            this.markInvalid(this.blankText);
            return false;
        }
        return true;
    },
    getValues: function() {
        var ids = '';
        for (i = 0; i < this.children.length; i++) {
            var box = this.children[i];
            if (box.getValue()) {
                if (ids.length > 0) ids += ',';
                ids += box.name.split('$')[1];
            }
        }
        return ids;
    },
    setValues: function(values) {
        alert("Not impleted");
    }
});


// extend RadioButtonList
Ext.form.RadioButtonList = function() {
    Ext.form.RadioButtonList.superclass.constructor.apply(this, arguments);
};
Ext.extend(Ext.form.RadioButtonList, Ext.form.Field, {
    onRender: function(ct, position) {
    },
    validateValue: function(value) {
        if (this.allowBlank == false && this.getValue() == null) {
            this.markInvalid(this.blankText);
            return false;
        }
        return true;
    },
    getValue: function() {
        for (i = 0; i < this.children.length; i++) {
            var box = this.children[i];
            if (box.checked)
                return box.inputValue;
        }
        return null;
    },
    setValue: function(value) {
    }
});

Ext.data.AspNetProxy = function(ctrlId, pageSize, fnPostAsync) {
    Ext.data.AspNetProxy.superclass.constructor.call(this);
    this.fnPostAsync = fnPostAsync;
    this.options = null;
    this.ctrlId = ctrlId;
    this.pageSize = pageSize;
};

Ext.extend(Ext.data.AspNetProxy, Ext.data.DataProxy, {
    load: function(params, reader, callback, scope, arg) {
        if (this.fireEvent("beforeload", this, params) !== false) {
            if (params.start != null)
                Ext.getDom(this.ctrlId + "_pageindex").value = ((params.start / this.pageSize) + 1).toString();
            if (params.sort != null) {
                Ext.getDom(this.ctrlId + "_sortfield").value = params.sort;
                Ext.getDom(this.ctrlId + "_sortdirection").value = params.dir;
            }
            if (ExtPage.grids[this.ctrlId].getSelectionModel().singleSelect)
                Ext.getDom(this.ctrlId + "_selected").value = ',';
            this.options = {
                params: params || {},
                request: {
                    callback: callback,
                    scope: scope,
                    arg: arg
                },
                reader: reader,
                callback: this.loadResponse,
                scope: this
            };
            var prm = Sys.WebForms.PageRequestManager.getInstance();
            if (!prm.get_isInAsyncPostBack())
                this.fnPostAsync();
            else
                ExtPage.requests.push(this);
        } else {
            callback.call(scope || this, null, arg, false);
        }
    },

    loadResponse: function(success, response) {
        if (!success) {
            this.fireEvent("loadexception", this, this.options, response);
            this.options.request.callback.call(this.options.request.scope, null, this.options.request.arg, false);
            return;
        }

        var result;
        try {
            this.options.params.start = (response.pageIndex - 1) * response.pageSize;
            this.options.params.limit = response.resultset.length;
            if (response.sortField != null) {
                ExtPage.grids[this.ctrlId].store.sortInfo = {};
                ExtPage.grids[this.ctrlId].store.sortInfo.field = response.sortField;
                ExtPage.grids[this.ctrlId].store.sortInfo.direction = response.sortDirection;
            }
            Ext.getDom(this.ctrlId + "_selected").value = response.selectedIds;
            result = this.options.reader.readRecords(response);
        } catch (e) {
            this.fireEvent("loadexception", this, this.options, response, e);
            this.options.request.callback.call(this.options.request.scope, null, this.options.request.arg, false);
            return;
        }
        this.fireEvent("load", this, this.options, this.options.request.arg);
        this.options.request.callback.call(this.options.request.scope, result, this.options.request.arg, true);
    },

    // private
    update: function(dataSet) {

    },

    // private
    updateResponse: function(dataSet) {

    }
});


ExtPage =
{
    forms: new Array(),
    requests: new Array(),
    ctrls: {},
    grids: {},
    onFormSubmit: function(evt, el, o) {
        if (o.isValid())
            return true;
        window.status = "the form is invalid";
        if (evt.preventDefault) { evt.preventDefault(); }
        evt.returnValue = false;
        return false;
    },
    init: function() {
        ExtPage.converCtrls();
        if (typeof (Sys) != 'undefined') {
            Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function() {
                ExtPage.onAtlasEndRequest();
                var o = ExtPage.requests.shift();
                if (o != null) { o.fnPostAsync(); }
            });
        }
        document.body.style.visibility = "visible";
    },

    onAtlasEndRequest: function() {
        var hiddens = Ext.query('input[isJsonResponseForGridCtrl="1"]');
        for (var k = 0; k < hiddens.length; k++) {
            hiddens[k].setAttribute("isJsonResponseForGridCtrl", "0");
            var id = hiddens[k].getAttribute("for");
            var objData = eval(hiddens[k].value);
            ExtPage.grids[id].store.proxy.loadResponse(true, objData);
            var selectedRows = [];
            var selectedIds = Ext.getDom(id + "_selected").value;
            for (l = 0; l < ExtPage.grids[id].store.getCount(); l++) {
                var r = ExtPage.grids[id].store.getAt(l);
                if (selectedIds.indexOf(',' + r.id + ',') >= 0)
                    selectedRows.push(r);
            }
            ExtPage.grids[id].getSelectionModel().selectRecords(selectedRows);
        }

        ExtPage.converCtrls();
    },

    // covert the form into EXT
    converCtrls: function() {
        var forms = document.getElementsByTagName("form");
        for (var i = 0; i < forms.length; i++) {
            var config = new ConfigObj(forms[i]);
            var form = new Ext.form.BasicForm(forms[i], config);
            Ext.EventManager.addListener(forms[i], "submit", ExtPage.onFormSubmit, ExtPage, form);
            ExtPage.forms.push(form);
            var ctrls = Ext.query('*[xtype]', forms[i]);
            for (var j = 0; j < ctrls.length; j++) {
                var ctrlId = ctrls[j].id;
                var input = ExtPage.populateCtrl(ctrls[j]);
                ExtPage.ctrls[ctrlId] = input;

                if (input) {
                    input.on("invalid", ExtPage.onFieldInvalid);
                    input.on("valid", ExtPage.onFieldValid);
                    form.add(input);
                }
            } // for
        } // for

        var ctrls = Ext.query("*[xtype]");
        for (var j = 0; j < ctrls.length; j++) {
            ExtPage.populateCtrl(ctrls[j]);
        } // for
    },

    populateCtrl: function(ctrl) {
        if (ctrl.getAttribute("init") != null)
            return;
        ctrl.setAttribute("init", true);

        var input = null;
        switch (ctrl.getAttribute("xtype")) {
            case "textfield":
                var config = new ConfigObj(ctrl);
                config.applyTo = ctrl.id;
                config.anchor = '100%';
                config.allowDomMove = false;
                input = new Ext.form.TextField(config);
                break;

            case "textarea":
                var config = new ConfigObj(ctrl);
                config.applyTo = ctrl.id;
                config.allowDomMove = false;
                input = new Ext.form.TextArea(config);
                break;

            case "numberfield":
                var config = new ConfigObj(ctrl);
                config.applyTo = ctrl.id;
                config.allowDomMove = false;
                input = new Ext.form.NumberField(config);
                break;

            case "datefield":
                var config = new ConfigObj(ctrl);
                config.applyTo = ctrl.id;
                config.allowDomMove = false;
                input = new Ext.form.DateField(config);
                break;

            case "timefield":
                var config = new ConfigObj(ctrl);
                config.applyTo = ctrl.id;
                config.allowDomMove = false;
                input = new Ext.form.TimeField(config);
                break;

            case "combo":
                var config = new ConfigObj(ctrl);
                config.allowDomMove = false;
                config.triggerAction = 'all';
                if (config.width != null)
                    config.width = parseInt(config.width);
                var onchange = ctrl.getAttribute("onchange");
                if (onchange != null && Ext.isIE) {
                    onchange = onchange.toString();
                    s = onchange.indexOf('{') + 1;
                    e = onchange.lastIndexOf('}');
                    onchange = onchange.substring(s, e);
                }
                if (config.forceSelection) {
                    config.transform = ctrl.id;
                    config.lazyRender = false;
                }
                else {
                    var data = [];
                    for (var z = 0; z < ctrl.options.length; z++)
                        data.push([ctrl.options[z].value, ctrl.options[z].text]);
                    var store = new Ext.data.SimpleStore(
					{
					    fields: [config.valueField, config.displayField],
					    data: data
					});
                    Ext.DomHelper.insertAfter(ctrl, { id: ctrl.id + '_wrap', tag: 'span' });
                    Ext.removeNode(ctrl);
                    config.renderTo = ctrl.id + '_wrap';
                    config.id = ctrl.id;
                    config.name = ctrl.id;
                    config.tpl = '<tpl for="."><div class="x-combo-list-item">{Text}</div></tpl>',
					config.store = store;
                }
                input = new Ext.form.ComboBox(config);
                if (onchange != null)
                    input.on("select", (function(code) {
                        return function() {
                            eval(code);
                        };
                    })(onchange)
						);

                break;

            case "checkbox":
                var config = new ConfigObj(ctrl);
                var label = Ext.query("label[for='" + ctrl.id + "']")[0];
                var strLabel = (label == null) ? "" : (label.innerText || label.textContent);
                Ext.removeNode(label);
                input = new Ext.form.Checkbox({ applyTo: ctrl.id,
                    boxLabel: strLabel,
                    id: ctrl.id,
                    name: ctrl.id,
                    checked: ctrl.checked,
                    disabled: ctrl.disabled
                });
                break;

            case "radiobutton":
                var config = new ConfigObj(ctrl);
                var label = Ext.query("label[for='" + ctrl.id + "']")[0];
                var strLabel = (label == null) ? "" : (label.innerText || label.textContent);
                Ext.removeNode(label);
                input = new Ext.form.Radio({ applyTo: ctrl.id,
                    boxLabel: strLabel,
                    id: ctrl.id,
                    name: ctrl.id,
                    checked: ctrl.checked,
                    disabled: ctrl.disabled,
                    inputValue: ctrl.value
                });
                break;

            case "checkboxlist":
                var config = new ConfigObj(ctrl);
                var boxes = Ext.query("input[type='checkbox']", ctrl);
                var children = [];
                for (i = 0; i < boxes.length; i++) {
                    var label = Ext.query("label[for='" + boxes[i].id + "']")[0];
                    var strLabel = (label == null) ? "" : (label.innerText || label.textContent);
                    Ext.removeNode(label);
                    children.push(new Ext.form.Checkbox({ applyTo: boxes[i].id,
                        boxLabel: strLabel,
                        id: boxes[i].id,
                        name: boxes[i].name,
                        checked: boxes[i].checked,
                        disabled: boxes[i].disabled
                    })
					);
                }
                config.children = children;
                config.applyTo = ctrl.id;
                config.allowDomMove = false;
                input = new Ext.form.CheckboxList(config);
                break;

            case "radiobuttonlist":
                var config = new ConfigObj(ctrl);
                var boxes = Ext.query("input[type='radio']", ctrl);
                var children = [];
                for (i = 0; i < boxes.length; i++) {
                    var label = Ext.query("label[for='" + boxes[i].id + "']")[0];
                    var strLabel = (label == null) ? "" : (label.innerText || label.textContent);
                    Ext.removeNode(label);
                    children.push(new Ext.form.Radio({ applyTo: boxes[i].id,
                        boxLabel: strLabel,
                        id: boxes[i].id,
                        name: boxes[i].name,
                        inputValue: boxes[i].value,
                        checked: boxes[i].checked,
                        disabled: boxes[i].disabled
                    })
					);
                }
                config.children = children;
                config.applyTo = ctrl.id;
                config.allowDomMove = false;
                input = new Ext.form.RadioButtonList(config);
                break;

            default: return null;
        } //switch

        return input;
    },


    onFieldInvalid: function(obj, errorMsg) {
        var divTip = obj.tipDiv;
        if (divTip != null)
            divTip.remove();

        Ext.DomHelper.useDom = true;
        divTip = Ext.getBody().createChild({
            tag: 'div',
            id: obj.getEl().id + "_tip",
            name: '_error_tip',
            html: Ext.util.Format.htmlEncode(errorMsg),
            style: 'position:absolute;border:solid 1px orange;background-color:#FFFFCC;' +
		'color:#444444;font-family:Tahoma;padding-left:5px;padding-right:5px;padding-top:1px;' +
		'left:' + (obj.getEl().getX() + obj.getEl().getWidth() + 20) + 'px;' +
		'top:' + (obj.getEl().getY()).toString() + 'px;'
        });
        obj.tipDiv = divTip;
    },

    onFieldValid: function(obj) {
        var divTip = obj.tipDiv;
        if (divTip != null)
            divTip.remove();
    },

    onWndResized: function() {
        var divs = Ext.query("div[name='_error_tip']");
        Ext.each(divs, function(v, i, a) {
            var sId = v.id.substr(0, v.id.length - 4);
            v.style.top = (Ext.getCmp(sId).getEl().getY()).toString() + 'px';
            v.style.left = (Ext.getCmp(sId).getEl().getX() + Ext.getCmp(sId).getEl().getWidth() + 20) + 'px';
        }, null);
    },

    none: null
};



Ext.EventManager.onDocumentReady(ExtPage.init);
Ext.EventManager.onWindowResize(ExtPage.onWndResized);

