﻿//hyperlink
//拓展Label，实现超链接
Ext.ns("SharpExt");
SharpExt.Hyperlink=Ext.extend(Ext.form.Label,{
    initComponent:function(){
        if(this.hyperlink){
            var link=['<a href="',this.hyperlink];
            if(this.target){
                link.push('" target="');            
                link.push(this.target);
            }
            link.push('">');
            link.push(this.text);
            link.push('</a>');
            this.html=link.join('');
            delete this.text;
        }        
        SharpExt.Hyperlink.superclass.initComponent.call(this);
    }
});
Ext.reg("hyperlink",SharpExt.Hyperlink);

//sbutton
//拓展Button，通过后台字串查找并获取SharpExt.Event的方法
SharpExt.Button=Ext.extend(Ext.Button,{
    initComponent:function(){
        this.handler=SharpExt.Event[this.handler].createDelegate(this);
        SharpExt.Button.superclass.initComponent.call(this);
    }
});
Ext.reg("sbutton",SharpExt.Button);

//shtmleditor
//拓展htmleditor，支持图片上传
SharpExt.HTMLEditor = Ext.extend(Ext.form.HtmlEditor, {
	addImage : function() {
		var editor = this;
		var imgform = new Ext.FormPanel({
			region : 'center',
			labelWidth : 55,
			frame : true,
			bodyStyle : 'padding:5px 5px 0',
			autoScroll : true,
			border : false,
			fileUpload : true,
			items : [{
						xtype : 'textfield',
						fieldLabel : '选择文件',
						name : 'userfile',
						inputType : 'file',
						allowBlank : false,
						blankText : '文件不能为空',
						height : 25,
						anchor : '90%'
					}],
			buttons : [{
				text : '上传',
				type : 'submit',
				handler : function() {
					if (!imgform.form.isValid()) {return;}
					imgform.form.submit({
						waitMsg : '正在上传......',
						url : 'htmleditorUpload.ashx',
						success : function(form, action) {
							var element = document.createElement("img");
							element.src = action.result.fileURL;
							if (Ext.isIE) {
								editor.insertAtCursor(element.outerHTML);
							} else {
								var selection = editor.win.getSelection();
								if (!selection.isCollapsed) {
									selection.deleteFromDocument();
								}
								selection.getRangeAt(0).insertNode(element);
							}
							win.hide();
						},
						failure : function(form, action) {
							form.reset();
							if (action.failureType == Ext.form.Action.SERVER_INVALID)
								Ext.MessageBox.alert('警告',
										action.result.errors.msg);
						}
					});
				}
			}, {
				text : '关闭',
				type : 'submit',
				handler : function() {
					win.close(this);
				}
			}]
		})

		var win = new Ext.Window({
					title : "上传图片",
					width : 300,
					height : 200,
					modal : true,
					border : false,
					iconCls : "picture.png",
					layout : "fit",
					items : imgform

				});
		win.show();
	},
	createToolbar : function(editor) {
		SharpExt.HTMLEditor.superclass.createToolbar.call(this, editor);
		this.tb.insertButton(16, {
					cls : "x-btn-icon",
					icon : "images/SHtmlEditor/picture.png",
					handler : this.addImage,
					scope : this
				});
	}
});
Ext.reg('shtmleditor2', SharpExt.HTMLEditor);

//sgrid
//拓展GridPanel，自动创建列模型
SharpExt.GridPanel = Ext.extend(Ext.grid.GridPanel, {
    buttonAlign: "left",
    viewConfig: { forceFit: true },
    initComponent: function() {
        this.autoHeight = false;
        if (!this.sm)
            this.sm = new Ext.grid.CheckboxSelectionModel({ width: 20 });
        if (this.initRowEditor)
            this.plugins = new Ext.ux.grid.RowEditor({ saveText: '确定', cancelText: '取消', errorSummary: false });
        var cols = [];

        if (!this.hideRowNumberer)
            cols.push(new Ext.grid.RowNumberer({ width: 30 }));
        if (!this.hideCheckBoxSm)
            cols.push(new Ext.grid.CheckboxSelectionModel({ width: 20, moveEditorOnEnter: true }));
        if (this.expanderTpl) {
            var expander = new Ext.ux.grid.RowExpander({ tpl: new Ext.Template(this.expanderTpl) });
            this.plugins = this.plugins ? this.plugins.concat(expander) : expander;
            cols.push(expander);
        }

        this.columns = cols.concat(this.columns);
        this.store.idIndex = 0;
        this.store.proxy = new Ext.ux.data.PagingMemoryProxy(this.store.data);
        this.store = new Ext.data.ArrayStore(this.store);
        this.bbar = new Ext.PagingToolbar({
            pageSize: 30,
            store: this.store,
            displayInfo: true
        });
        this.store.load({ params: { start: 0, limit: 30} });
        if (!this.nofilter) {
            if (!this.fbar)
                this.fbar = [];
            this.fbar.push({ xtype: "button", iconCls: "i-filter", text: "搜索", handler: function(btn) {
                var g = btn.findParentByType("sgrid");
                Service.GetFilter(g.bcode, function(res) {
                    res.srcCode = g.bcode;
                    res.fbar = [{ xtype: "button", iconCls: "i-filter", text: "确定", handler: function(b) {
                        var w = this.findParentByType("window");
                        var f = w.findByType("form")[0];

                        var v = f.getForm().getFieldValues();
                        Service.DoFilter(w.srcCode, ToNameValue(v), function(rsp) {
                            if (rsp) {
                                var g = Ext.getCmp(w.srcCode);
                                g.getStore().proxy = new Ext.ux.data.PagingMemoryProxy(rsp);
                                g.getStore().load({ params: { start: 0, limit: 30} });
                            } else {
                                Warning("没有找到您指定的记录");
                            }
                            w.close();
                        }, function(rsp) {

                        });
                    } }];
                        var w = Ext.ComponentMgr.create(res);
                        w.show();
                        btn.enable();
                    });
                }
            });

        }
        SharpExt.GridPanel.superclass.initComponent.call(this);
    }
});
Ext.reg('sgrid', SharpExt.GridPanel);

//seditorgrid
SharpExt.EditorGridPanel = Ext.extend(Ext.grid.EditorGridPanel,{
    clicksToEdit:1,
    initComponent:function(){
        this.store=new Ext.data.ArrayStore(this.store);
        SharpExt.EditorGridPanel.superclass.initComponent.call(this);
    }
});
Ext.reg('seditorgrid', SharpExt.EditorGridPanel);

Ext.grid.ComboColumn = Ext.extend(Ext.grid.Column, {
    constructor: function(cfg){
        Ext.grid.ComboColumn.superclass.constructor.call(this, cfg);
        this.renderer=function(v){
            this.editor.setValue(v);
            return this.editor.lastSelectionText;
        }.createDelegate(this);
    }
});
Ext.grid.Column.types.combocolumn=Ext.grid.ComboColumn;

Ext.grid.PasswordColumn = Ext.extend(Ext.grid.Column, {
    constructor: function(cfg){
        Ext.grid.PasswordColumn.superclass.constructor.call(this, cfg);
        this.renderer=function(v){
            return "******";
        }.createDelegate(this);
    }
});
Ext.grid.Column.types.pswcolumn=Ext.grid.PasswordColumn;

SharpExt.DynaFormGrid = Ext.extend(Ext.form.FormPanel, {
    closable: true,
    buttonAlign: "left",
    bodyStyle: "padding:10px;",
    autoHeight: true,
    autoScroll: true,
    defaults: { border: false, xtype: 'fieldset' },
    layout: { type: 'hbox', align: 'stretch', pack: 'start', extraCls: 'x-column' },
    fbar: [{
        //xtype:"button",
        iconCls: "i-table-save",
        text: "保存",
        handler: function() {
            var _this = this.findParentByType("formgrid");
            if (_this.getForm().isValid()) {
                var v = _this.getForm().getFieldValues();
                Service.Update(_this.tabname, ToNameValue(v), function(res) {
                    Warning(res);
                    var rec = _this.findByType("sgrid")[0].getSelectionModel().getSelected();
                    Ext.apply(rec.data, v);
                    rec.commit();
                });
            }
        }
}],
        listeners: {
            render: function(f) {
                var g = f.findByType("sgrid")[0];
                g.getSelectionModel().selectRow(0);
            },
            delay: 10 // Allow rows to be rendered.
        },
        initComponent: function() {
            var _this = this;
            Ext.apply(this.grid, {
                id: undefined,
                autoHeight: false,
                border: true,
                header: false,
                hideHeaders: true,
                viewConfig: { forceFit: true },
                sm: new Ext.grid.RowSelectionModel({
                    singleSelect: true,
                    listeners: {
                        rowselect: function(sm, row, rec) {
                            _this.getForm().loadRecord(rec);
                        }
                    }
                })
            });
            this.grid.nofilter = true;
            this.items = [{
                width: this.hideGrid ? 0 : 200,
                layout: "fit",
                items: this.grid
            }, {
                flex: 1,
                bodyStyle: "padding:0 20px",
                defaults: { anchor: "100%" },
                items: this.fields
}];
                delete this.grid;
                delete this.fields;
                SharpExt.DynaFormGrid.superclass.initComponent.call(this);
            }
        });
Ext.reg("formgrid",SharpExt.DynaFormGrid);

SharpExt.BillForm=Ext.extend(Ext.form.FormPanel,{
    bodyStyle:"padding:10px",
    defaults:{plain:true},
    fieldColumn:2,
    buttonAlign:'left',
    buttons:[{text:"保存",iconCls:'i-table-save',handler:function(btn){
        var f=btn.findParentByType('billform');
        var w=btn.findParentByType('window');
        if(f.getForm().isValid())
        {
            var fv=GetBillFormFieldValues.call(f);
            Service.BillFormInsert(f.bcode,fv,GetBillFormGridValues.call(f),function(res){
                var g=Ext.getCmp(w.srcCode);
                if(g){
                    var rec={};
                    Ext.each(fv,function(v){
                        rec[v.key]=v.val;
                    });
                    rec[res.key]=res.val;
                    var record=new Ext.data.Record(rec);
                    record.id=res.val;
                    g.getStore().add(record);
                }
                f.getForm().reset();
                btn.enable();
            });
            btn.disable();
        }
    }}],
    layout: {type:'vbox',align:'stretch'},
    initComponent:function(){
        var len=this.items.length;
        var fs=[];
        var fs2={columnWidth:1,items:[]};
        for(var i=0;i<this.fieldColumn;i++){
            fs.push({items:[]});
        }
        for(var i=0;i<len;i++){
            if(this.items[i].xtype=='hidden'||this.items[i].xtype=='htmleditor'||this.items[i].xtype=='shtmleditor'||this.items[i].xtype=='textarea')
                fs2.items.push(this.items[i]);
            else
                fs[(i-fs2.items.length)%this.fieldColumn].items.push(this.items[i]);
        }
        this.items=[{defaults:{xtype:'fieldset',defaults:{anchor:'95%'},border:false,columnWidth:1/this.fieldColumn},bodyStyle:"padding:10px 10px 0px 10px;margin-bottom:10px;",height:160,autoScroll:true,layout:'column',items:fs.concat(fs2)}];
        if(this.grids){
            var bar=new Ext.Toolbar({
                items:[{
                    iconCls:'i-rec-add',
                    tooltip:"添加行",
                    text:'添加行',
                    handler:function(){
                        var g=this.findParentByType("tabpanel").getActiveTab();
                        g.getStore().insert(0, new Ext.data.Record({}));
                        g.getView().refresh();
                        g.plugins.startEditing(0);
                    }
                },{
                iconCls:"i-rec-delete",
                text:'删除行',
                tooltip:"删除行",
                handler:function(){
                    var g=this.findParentByType("tabpanel").getActiveTab();
                    var r=g.getSelectionModel().getSelections();
                    if(!r||r.length==0){
                        Warning("请选择记录");
                        return;
                    }
                    Ext.Msg.confirm("确认","您确认要删除所选的记录吗？",function(e){
                        if(e=='yes'){
                            for(var i=0;i<r.length;i++){
                                g.getStore().remove(r[i]);
                            }
                        }
                    })
                }
            }]});
            this.items.push({columnWidth:1,flex:1,border:true,xtype:"tabpanel",anchor:'100% 0',tbar:bar,defaults:{iconCls:'i-detail',closable:false},activeTab:0,items:this.grids});
            delete this.grids;
        }
        SharpExt.BillForm.superclass.initComponent.call(this);
    }
});
Ext.reg("billform",SharpExt.BillForm);

SharpExt.ColumnForm=Ext.extend(Ext.form.FormPanel,{
    fieldColumn:2,
    initComponent:function(){
        var len=this.items.length;
        var fs=[];
        var fs2={columnWidth:1,items:[]};
        for(var i=0;i<this.fieldColumn;i++){
            fs.push({items:[]});
        }
        for(var i=0;i<len;i++){
            if(this.items[i].xtype=='hidden'||this.items[i].xtype=='htmleditor'||this.items[i].xtype=='shtmleditor'||this.items[i].xtype=='textarea')
                fs2.items.push(this.items[i]);
            else
                fs[(i-fs2.items.length)%this.fieldColumn].items.push(this.items[i]);
        }
        this.items=[{defaults:{xtype:'fieldset',defaults:{anchor:'95%'},border:false,columnWidth:1/this.fieldColumn},layout:'column',items:fs.concat(fs2)}];
        
        SharpExt.ColumnForm.superclass.initComponent.call(this);
    }
});

Ext.reg("columnform",SharpExt.ColumnForm);


SharpExt.DataView=Ext.extend(Ext.DataView,{
    itemSelector:'',
    initComponent:function(){
    this.tpl=new Ext.XTemplate(this.tpl);
        this.store=new Ext.data.ArrayStore(this.store);
        SharpExt.DataView.superclass.initComponent.call(this);
    }
});
Ext.reg('sdataview',SharpExt.DataView);


Ext.namespace('Ext.ux.form');  
  
/** 
 * FCKeditor 初始配置信息 
 *  
 * @type {Object} 
 */  
var oFCKeditorOptions = {  
    BasePath : 'js/fckeditor/',  
    Config : {  
        BaseHref : window.location,  
        SkinPath : '../editor/skins/office2003/',  
        ProcessHTMLEntities : true,  
        ProcessNumericEntities : false,  
        ToolbarStartExpanded : true,  
        LinkBrowser : true,  
        ImageBrowser : true,  
        FlashBrowser : true,  
        LinkUpload : true,  
        ImageUpload : true,  
        FlashUpload : true  
    }//,  
    //ToolbarSet : 'Symbol'  
};  
  
/** 
 * Ext FCKeditor 
 *  
 * @param {Object} 
 *            config 配置信息 
 */  
Ext.ux.form.FCKeditor = function(config) {  
    this.config = config;  
    Ext.ux.form.FCKeditor.superclass.constructor.call(this, config);  
    /** 
     * 通知FCKeditor是否实例化  
     * notice the component's FCKeditor instance inited 
     * @type Boolean 
     */  
    this.instanceLoaded = false;  
    /** 
     * 实例值 
     * the component's FCKeditor instance value 
     * @type String 
     */  
    this.instanceValue = '';  
    /** 
     * 组件的FCKeditor实例 
     * @type {FCKeditor} 
     */  
    this.editorInstance = undefined;  
};  
/** 
 * Ext FCKeditor 
 *  
 * @class Ext.ux.form.FCKeditor 
 * @extends Ext.form.TextArea 
 */  
Ext.extend(Ext.ux.form.FCKeditor, Ext.form.TextArea, {  
            /** 
             * 初始化事件 
             */  
            initEvents : function() {  
                this.on('destroy', function() {  
                            if (typeof this.editorInstance != 'undefined') {  
                                delete this.editorInstance;  
                            }  
                        });  
            },  
            onRender : function(ct, position) {  
                if (!this.el) {  
                    this.defaultAutoCreate = {  
                        tag : "textarea",  
                        style : "width:100px;height:60px;",  
                        autocomplete : "off"  
                    };  
                }  
                Ext.form.TextArea.superclass.onRender.call(this, ct, position);  
                this.hideMode = "visibility";  
                this.hidden = true;  
                if (this.grow) {  
                    this.textSizeEl = Ext.DomHelper.append(document.body, {  
                                tag : "pre",  
                                cls : "x-form-grow-sizer"  
                            });  
                    if (this.preventScrollbars) {  
                        this.el.setStyle("overflow", "hidden");  
                    }  
                    this.el.setHeight(this.growMin);  
                }  
                setTimeout("loadFCKeditor('" + this.id + "'," + this.config.height + ");", 100); // Change  
            },  
            /** 
             * 设置是否已经加载过此控件 
             * set FCKeditor instance is inited 
             * @param {Boolean} v 
             */  
            setIsLoaded : function(v) {  
                this.instanceLoaded = v;  
            },  
            /** 
             * 获取是否已实例化过此控件 
             * get FCKeditor instance is inited 
             * @return {Boolean} 
             */  
            getIsLoaded : function() {  
                return this.instanceLoaded;  
            },  
            /** 
             *  
             * @param {String} value 
             */  
            setValue : function(value) {  
                this.instanceValue = value;  
                if (this.instanceLoaded) {  
                    this.FCKeditorSetValue(value); // Change this.name  
                }  
                Ext.form.TextArea.superclass.setValue.apply(this, [value]);  
            },  
            /** 
             *  
             * @return {String} 
             */  
            getValue : function() {  
                if (this.instanceLoaded) {  
                    value = this.FCKeditorGetValue(); // Change this.name to this.id  
                    Ext.form.TextArea.superclass.setValue.apply(this, [value]);  
                    return Ext.form.TextArea.superclass.getValue.call(this); // Change getValue(this) to  
                } else {  
                    return this.instanceValue;  
                }  
            },  
            /** 
             *  
             * @return {String} 
             */  
            getRawValue : function() {  
                if (this.instanceLoaded) {  
                    value = this.FCKeditorGetValue(); // Change this.name to this.id  
                    Ext.form.TextArea.superclass.setRawValue.apply(this, [value]);  
                    return Ext.form.TextArea.superclass.getRawValue.call(this); // Change getValue(this) to  
                } else {  
                    return this.instanceValue;  
                }  
            },  
            /** 
             * 设置FCKeditor实例的值 
             * @param {String} value 
             */  
            FCKeditorSetValue : function(value) {  
                if(this.instanceLoaded == false){  
                    return;  
                }  
                // fix IE No Permission Denied errors  
                var runner = new Ext.util.TaskRunner();  
                var task = {  
                    run : function() {  
                        try {  
                            var editor = this.editorInstance; // update var editor  
                            if (editor.EditorDocument.body) {  
                                editor.SetData(value);  
                                runner.stop(task);  
                            }  
                        } catch (ex) {  
                            //Ext.logf('调试信息(info)：{0}', ex);  
                        }  
                    },  
                    interval : 100,  
                    scope : this  
                };  
                runner.start(task); // end fix  
            },  
            /** 
             * 获取FCKeditor实例的值 
             * @return {String} 
             */  
            FCKeditorGetValue : function() {  
                var data = '';  
                if(this.instanceLoaded == false){  
                    return data;  
                }  
                data = this.editorInstance.GetData();                 
                return data;  
            }  
        });
        Ext.reg('shtmleditor', Ext.ux.form.FCKeditor);  
  
/** 
 * 实例化FCKeditor 
 *  
 * @param {String} 
 *            element el id 
 * @param {Number} 
 *            height 
 */  
function loadFCKeditor(element, height) {  
    var oFCKeditor = new FCKeditor(element);  
    oFCKeditor.BasePath = oFCKeditorOptions.BasePath;  
    oFCKeditor.ToolbarSet = oFCKeditorOptions.ToolbarSet;  
    oFCKeditor.Config = oFCKeditorOptions.Config;  
    oFCKeditor.Height = height;  
    oFCKeditor.ReplaceTextarea();  
}  
/** 
 * FCKeditor API: 当FCKeditor实例化完成时执行 
 *  
 * @param {FCKeditor} editorInstance 
 */  
function FCKeditor_OnComplete(editorInstance) {  
    /** 
     * @type {Ext.ux.form.FCKeditor} 
     */  
    var activeEditor = Ext.getCmp(editorInstance.Name);  
    activeEditor.editorInstance = editorInstance;  
    activeEditor.instanceLoaded = true;  
    activeEditor.FCKeditorSetValue(activeEditor.instanceValue);  
    editorInstance.Events.AttachEvent('OnBlur', FCKeditor_OnBlur);  
    editorInstance.Events.AttachEvent('OnFocus', FCKeditor_OnFocus);  
}  
  
function FCKeditor_OnBlur(editorInstance) {  
    editorInstance.ToolbarSet.Collapse();  
}  
  
function FCKeditor_OnFocus(editorInstance) {  
    editorInstance.ToolbarSet.Expand();  
}  