﻿﻿﻿Ext.QuickTips.init();
Ext.BLANK_IMAGE_URL = App.ctx + '/images/default/s.gif';
Ext.debug = {};
Ext.override(Ext.form.BasicForm,{
    //add keep dirty param
    updateRecord:function(record,bKeepDirty){
        if(bKeepDirty) record.editing=true;
        else record.beginEdit();
        
        var fs = record.fields;
        fs.each(function(f){
            var field = this.findField(f.name);
            if(field){
                record.set(f.name, field.getValue());
            }
        }, this);
        record.endEdit();
        return this;
    }
});

var _treenodeRender = Ext.tree.TreeNode.prototype.render;
Ext.override(Ext.tree.TreeNode,{
    render:function(bulkRender){
        if (this.attributes['gfaModule'] && !Gfa.purview.check(this.attributes['gfaModule'])) {
			//don't render
        } else {
        	_treenodeRender.apply(this,[bulkRender]);
        }
    }
});

var _cmpRender = Ext.Component.prototype.render;
Ext.override(Ext.Component,{
    render:function(container, position){
        var cmp=_cmpRender.apply(this,[container, position]);
		if (cmp.gfaModule && !Gfa.purview.check(cmp.gfaModule))
			cmp.hide();
        return cmp;
    }
});

var _comboFindRec = Ext.form.ComboBox.prototype.findRecord;
Ext.override(Ext.form.ComboBox,{
    findRecord:function(prop, value){//optimize perfomance
        if(this.store.reader && prop == this.store.reader.meta.id)
            return this.store.getById(value);
        return _comboFindRec.apply(this,[prop, value]);
    }
});

var _pagingLoad = Ext.PagingToolbar.prototype.onLoad;
Ext.override(Ext.PagingToolbar,{
    onLoad:function(store, r, o,response){
        if(typeof o.params.start != 'undefined')//query? update pager
            _pagingLoad.apply(this,[store, r, o]);
        else//custom request
            this.loading.enable();//stop loading img
    }
});

var _recReject = Ext.data.Record.prototype.reject;
var _recSet = Ext.data.Record.prototype.set;
Ext.override(Ext.data.Record,{
    reject:function(silent){
        if(this.data.rowStatus === Gfa.data.ROWSTATUS_ADDED)//New reject?
            this.store.remove(this);
        else
            _recReject.apply(this, arguments);
    },
    set : function(name, value) {
		//空值单元格, 则不做处理
    	if (this.data[name] === null && value === '') {
    		return;
    	}
    	_recSet.apply(this, arguments);
    }
});

var _gridOnEditComplete = Ext.grid.EditorGridPanel.prototype.onEditComplete;
Ext.override(Ext.grid.EditorGridPanel, {
    onEditComplete :  function(ed, value, startValue){
    	//空值单元格
    	if (startValue === null && value === '') {
			value = startValue;
		}
		
		//将 ComboBox 实体值赋给 value
    	if(ed.field.isEntity && ed.field instanceof Ext.form.ComboBox){
    		if(ed.field.selectedIndex == -1 || startValue == value){
				return;
			} else {
				value = ed.field.store.getAt(ed.field.selectedIndex).data;
				ed.field.selectedIndex = -1;
			} 
    	}    	
    	_gridOnEditComplete.apply(this, arguments);
    }
});

// 重载 Ext.data.Store.prototype.applySort 函数以修复 DataStore 对汉字排序异常的问题
// var _applySort = Ext.data.Store.prototype.applySort;	//如有需要，保存原 applySort 函数的引用
Ext.data.Store.prototype.applySort = function() { // 重载 applySort
	if (this.sortInfo && !this.remoteSort) {
		var s = this.sortInfo, f = s.field;
		var st = this.fields.get(f).sortType;
		var fn = function(r1, r2) {
			var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
			// 添加:修复汉字排序异常的Bug
			if (typeof(v1) == "string") { // 若为字符串，
				// 则用 localeCompare 比较汉字字符串, Firefox 与 IE 均支持
				return v1.localeCompare(v2);
			}
			// 添加结束
			return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
		};

		this.data.sort(s.direction, fn);
		if (this.snapshot && this.snapshot != this.data) {
			this.snapshot.sort(s.direction, fn);
		}
	}
}; 

// 重写toggleCheck方法
Ext.override(Ext.tree.TreeNodeUI, {
	toggleCheck : function(value){
        var cb = this.checkbox;
        if(cb){
            cb.checked = (value === undefined ? !cb.checked : value);
            this.node.attributes.checked = cb.checked;	//+
        }
    }
});

Ext.override(Ext.util.Event, {
	fire : function(){
		var ls = this.listeners, scope, len = ls.length;
        if(len > 0){
            this.firing = true;
            var args = Array.prototype.slice.call(arguments, 0);
            for(var i = 0; i < len; i++){
                var l = ls[i];
                try {
	                if(l.fireFn.apply(l.scope||this.obj||window, arguments) === false){
	                    this.firing = false;
	                    return false;
	                }
                } catch(e) {
                	//Ext.Msg.alert(null, e.message);
                	if(window.console) {
                		console.error(e);
                	}
                	this.firing = false;
                	return false;
                }
            }
            this.firing = false;
        }
        return true;
    }
});


DWREngine.setErrorHandler(function(msg, ex){
   if(msg.indexOf("The specified call count is not a number") > -1){ 
         window.location = 'Main.jsp';// 刷新页面的代码
   }
   else {
         Gfa.net.onRequestError(null, null, null, ex);
   }
});

/*

//DWR错误处理
DWREngine.setErrorHandler(function(msg, ex){
	Gfa.net.onRequestError(null, null, null, ex);
});
*/
Ext.namespace("Gfa");
Gfa.net={
    onRequestError:function(proxy, response, loadCallback, ex){
    	var msg = ex.cause ? ex.cause.message : ex.message;
	    Ext.MessageBox.show({
	    	width: 300,
	    	plain:true,
			msg: msg,
			buttons: Ext.Msg.OK,
			icon: Ext.MessageBox.ERROR
	    });
    },
    redirect:function(targetUrl){
        window.location.href=targetUrl;
    }
};
Gfa.util={
    intercept:function(oriFun,itcpBefore,itcpAfter,scope){
        return function(){
            if(!scope) scope=this;
            if(itcpBefore) itcpBefore.apply(scope,arguments);
            var o = oriFun.apply(this,arguments);
            if(itcpAfter) itcpAfter.apply(scope,arguments);
            return o;
        };
    },
    
    eval : function(str){
    	try {
    		return eval(str);
    	} catch (e) {
    		return str;
    	}
    },
    
    /**
     * @param {Ext.TabPanel} container
     * @param {Ext.Window} popup
     */
    regPopup : function(container, popup) {
    	if (popup.rendered) return;
    	popup.render(Ext.getBody());
    	container.on('beforedestroy', function(){
    		Ext.destroy(popup);
    	});
    }
};

Gfa.purview={
    PV_STORE:null,
    check:function(cmp){
		if(eval('Gfa.purview.PV_STORE.menus.' + cmp) !== undefined)
			return true;
    	return false;
    },
	init:function(pvStore){
        Gfa.purview.PV_STORE=pvStore;
    }
};

Ext.namespace("Gfa.form");
Gfa.form.VTypes = function(){
    var gfaNum = /^[-\+]?\d+(\.\d+)?$/;
    var gfaChs = /^[\u0391-\uFFE5]+$/;
    var gfaInt = /^[-\+]?\d+$/;
    return {
        'gfaNum' : function(v){
            return gfaNum.test(v);
        },
        'gfaNumText' : 'This field should be a numeric',
        'gfaNumMask' : /[0-9\.\+\-]/i,
        
        'gfaChs':function(v){
            return gfaChs.test(v);
        },

        'gfaChsText' : 'This field should be a Chinese',
        'gfaChsMask' : / /i,
        
        'gfaInt':function(v){
            return gfaInt.test(v);
        },
        'gfaIntText' : 'This field should be a Integer',
        'gfaIntMask' : /[0-9\+\-]/i
    };
}();
Ext.apply(Ext.form.VTypes,Gfa.form.VTypes);

Ext.namespace("Gfa.page");

//------------Gfa.page.TreeChecker------------
Ext.namespace("Gfa.tree");
Gfa.tree.TreeLoader = function(config){
    this.url = Gfa.net.getServiceUrl();
    this.store = config.store;
    Gfa.tree.TreeLoader.superclass.constructor.call(this);
    
    this.store.on('load',function(ds,recs,options,response){
        if(!recs)return;//exption
        var q=options.params;
        if(typeof q.start != 'undefined'){//Query
            var node=options.params.node;
            this.processResponse(response,node,options.callback);
            node.expand();
        }
        else
            Gfa.data.isSuccess();
        
        return false;
    },this);
};
Ext.extend(Gfa.tree.TreeLoader,Ext.tree.TreeLoader,{
    requestData : function(node, callback){
        this.store.load({params:{start:0,node:node},callback:callback});
    }
});

Gfa.page.TreeChecker = function(config){
    var $init = function(){
        if(!this.store)
            this.store=new Gfa.data.Store();

        this.tree.loader = new Gfa.tree.TreeLoader({store:this.store});
        
        this.tree.on('checkchange',checkChild,this);
        this.tree.on("load",function(){nData = {};oData = {};},this);
    };
    
    var checkChild = function(node,checked){
        setCheckNode.apply(this,[node]);
        toggleCheckParent(node);
        if(!node.isLeaf() || node.childNodes.length>0){ // preloaded?
            if(!node.isExpanded())
                this.tree.loader.load(node);
            for(var i=0;i<node.childNodes.length;i++){
                var nodeChild = node.childNodes[i];
                
                nodeChild.getUI().toggleCheck(checked);
                nodeChild.attributes.checked = checked;
                
                if(!node.isLeaf || node.childNodes.length>0)
                    checkChild.apply(this,[nodeChild,checked]);
                else
                    setCheckNode(this,[nodeChild]);
            }
        }    
    };
    
    var toggleCheckParent = function(node){
        var attr = node.attributes;
        var parentNode = node.parentNode;
        if(!parentNode) return;
        if(attr.checked){
            var suc = true;
            for(var i=0;i<parentNode.childNodes.length;i++){
                var nodeChild = parentNode.childNodes[i];
                if(!nodeChild.attributes.checked){
                    suc = false;
                    break;
                }
            }
            if(suc){
                parentNode.getUI().toggleCheck(attr.checked);
                parentNode.attributes.checked = attr.checked;
                toggleCheckParent(parentNode);
            }
        }else{
            parentNode.getUI().toggleCheck(attr.checked);
            parentNode.attributes.checked = attr.checked;
            toggleCheckParent(parentNode);
        }
    };
    
    var setCheckNode = function(node){
        var attr = node.attributes;
        if(!attr.leaf && attr.leaf!=this.isLeafOnly) return;
        if(typeof(oData[attr.id])=="undefined"){
            oData[attr.id] = !attr.checked;
        }
        if(attr.checked ^ oData[attr.id]){
            nData[attr.id] = attr.checked;
        }else if(typeof(nData[attr.id])!="undefined"){
            delete nData[attr.id];
        }
    };
    
    this.getCheckedList=function(){
        var li = [];
        for(var id in nData)
        {
            var o = {};
            o['Id'] = id;
            o['Checked'] = nData[id];
            li.push(o);
        }
        return li;
    };
    this.submit=function(pId){//parent
        var li = this.getCheckedList();
        if(Gfa.data.isChanged(pId && li.length>0)){
            var obj={Id:pId,Children:li};
            this.store.load({params:{
                Args:Ext.encode({obj:obj})
            }});//update
        }
    }

    var oData = {};//old
    var nData = {};//new
    this.tree = null;//required
    this.isLeafOnly=true;//save leaf only or parents?
    this.store=null;
    Ext.apply(this, config);
    $init.apply(this);
}

Ext.namespace('Gfa.grid');
Gfa.grid.CheckColumn = function(config){
    Ext.apply(this, config);
    if(!this.id){
        this.id = Ext.id();
    }
    this.renderer = this.renderer.createDelegate(this);
};

Gfa.grid.CheckColumn.prototype ={
    checkedState:{},
    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);
            
            var idField = "";
            for(var i = 0, len = this.grid.getColumnModel().length; i < len; i++){
                var c = this.grid.getColumnModel()[i];
                if(c["id"] != undefined){
                    idField = c["id"];
                    return ;
                }      
            }
            
            var idValue = record.get(idValue);
            if(this.checkedState[idValue]==undefined){
                this.checkedState[idValue] = record.data[this.dataIndex];
            }else if(this.checkedState[idValue] == !record.data[this.dataIndex]){
                record.reject();
                return;
            }
            record.set(this.dataIndex, !record.data[this.dataIndex]);
        }
    },

    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>';
    },
    
    initState : function(){
       this.checkedState = {}; 
    }
};
//create by guosg 
Gfa.grid.ComboBoxRenderer = function(config){
    Ext.apply(this,config);
};

Gfa.grid.ComboBoxRenderer.prototype = {
    
    //如果此类设为grid的plugin，假设store还没有load，此时grid的将会在store load刷新行
    init:function(grid){
        this.grid = grid;
        this.grid.on('render',function(){
            this.isRender = true;
        },this);
    },
    //获得一个renderer
    getRenderer:function(){
        var renderer = null;
        if(this.store){
            this.store.on('load',function(){
                this.isLoaded = true;
                if(this.isRender){
                    this.reRender();
                }
            },this);
            renderer = function(value, p, r){
                if(!this.isLoaded) return;
                var r = this.findRecord(this.valueField,value);
                if(r)
                    return r.get(this.displayField);
                else if(this.forceDisplay)
                    return;
                else
                    return value;
            };
        }else{
            renderer = function(value, p, r){
                if(!value) return;   
                return value[this.displayField];
            };
        }
        
        return renderer.createDelegate(this);
    },
    //重新刷新这个页面
    reRender:function(){
        this.grid.store.each(function(r){
            this.getView().refreshRow(r);
        },this.grid);
    },
    
    findRecord:function(prop, value){
        if(this.store.reader && prop == this.store.reader.meta.id)
            return this.store.getById(value);
        
        var record;
        if(this.store.getCount() > 0){
            this.store.each(function(r){
                if(r.data[prop] == value){
                    record = r;
                    return false;
                }
            });
        }
        return record;
    },
    //要显示的字段名
    displayField:null, 
    //dataIndex
    valueField:null,
    
    //需要显示转换的数据源
    store:null,
    //需要做显示转换的grid
    grid:null,
    //store是否已经load完成
    isLoaded:false,
    //是否已经Render完成
    isRender:false,
    //强至显示数据源中的数据
    forceDisplay:false
    
};
var dsAction = new Ext.data.SimpleStore({
    fields: ['Value', 'Name'],
    data : [
        ['1','Yes'],
        ['0','No']
    ]
});

