// vtype extend
// Ext.form.VTypes["number"] = /^[0-9_]+$/;
Ext.form.VTypes["number"] = function(v) {
	return Ext.form.VTypes["numberMask"].test(v);
}
Ext.form.VTypes["numberText"] = "只允许输入数字"
Ext.form.VTypes["numberMask"] = /^[0-9_]+$/;

Ext.form.VTypes["onlyChiness"] = function(v) {
	return Ext.form.VTypes["onlyChinessMask"].test(v);
}
Ext.form.VTypes["onlyChinessText"] = "只允许输入中文"
Ext.form.VTypes["onlyChinessMask"] = /^[x00-xff]/;

Ext.form.VTypes["notChiness"] = function(v) {
	return Ext.form.VTypes["notChinessMask"].test(v);
}
Ext.form.VTypes["notChinessText"] = "不允许输入中文"
Ext.form.VTypes["notChinessMask"] = /(\w|\.)+$/;
// ------未测试通过---------------

Ext.form.VTypes["float"] = function(v) {
	return Ext.form.VTypes["floatMask"].test(v);
}
Ext.form.VTypes["floatText"] = "只允许输入浮点数"
Ext.form.VTypes["floatMask"] = /^\d+(\.\d{0,2})?$/g;
// -------未测试通过---------------

// ---------ajax------
Ext.form.Action.Submit.prototype.failure =function(){
	if(action.response.status == 401){
          Ext.Msg.show({
              title:'<div align="center">error</div>'
              ,msg:"超时请重新登陆!"
              ,height:200
              ,width:200
              ,closable:false
              ,buttons:Ext.Msg.OK
              ,fn: function(btn){
              window.location = 'index.html';             	    			
              }
          });
     }else{
         Ext.Msg.alert('错误',action.result.msg);
     }
}

Ext.Ajax.on('requestexception', function(conn, response, options) {
 //console.log("Attempting to trap exception....", Ext.Msg);
 //console.log(conn, response, options, this);
  switch (response.status) {
case 401:
   //console.log("Response 401");
Ext.Msg.show({
     title:'<div align="center">error</div>'
     ,msg:"超时请重新登陆!"
     ,height:200
     ,width:200
     ,closable:false
     ,buttons:Ext.Msg.OK
     ,fn: function(btn){
      window.location = 'index.html';
     }
   });	
  }//end switch
});
var ajaxRequest = function(url, args, callback) {
	args = args ? args : {};
	//new showProcess();
	Ext.Ajax.request({
				url : url,
				params : args,
				method : 'POST',
				waitTitle:'Connecting...',
				waitMsg:'Uploading data...',
				callback : function(request, success, response) {
					if (!success) {
						Ext.Msg.alert('警告','出现错误，请联系管理员！');
					} else {
						callback(Ext.decode(response.responseText));
					}
				}
			});	
};
// -----end-----------ajax-------------
// ----------start---------动态添加列------------
var addColumn = function() {
	this.fields = '';
	this.columns = '';
	this.addColumns = function(name, caption) {
		if (this.fields.length > 0) {
			this.fields += ',';
		}
		if (this.columns.length > 0) {
			this.columns += ',';
		}
		this.fields += '{name:"' + name + '"}';
		this.columns += '{header:"' + caption + '",dataIndex:"' + name
				+ '",width:100,sortable:true}';
	};
};
// ------------end---------动态添加列------------

// --------DictionaryColumn-------------
Ext.grid.DictionaryColumn = function(config) {
	Ext.apply(this, config);
	if (!this.id) {
		this.id = Ext.id();
	}
	this.renderer = this.renderer.createDelegate(this);
	this.valueField = this.valueField || 'key';
	this.displayField = this.displayField || 'value';
	this.mode = this.mode || 'local';
	this.width = this.width || 100;
	this.editable = this.editable || false;
	if (this.editable) {
		this.editor = new Ext.form.ComboBox({
					displayField : this.displayField,
					valueField : this.valueField,
					store : this.store,
					mode : this.mode,
					width : this.width,
					typeAhead : true,
					triggerAction : 'all',
					lazyRender : true,
					editable : false,
					listClass : 'x-combo-list-small'
				});
	}
};

Ext.grid.DictionaryColumn.prototype = {
	renderer : function(v, p, record) {
		// Ext.Msg.alert(index,this.displayField);
		var index = this.store.find(this.valueField, v);
		// Ext.Msg.alert(index,v);
		if (typeof(this.store.getAt(index)) == 'object')
			return this.store.getAt(index).get(this.displayField);
	}
};

// ----end----DictionaryColumn-------------
// ---------------------del column-----------
var deleteColumn = function(config) {

	this.columnID = '';
	this.ajaxUrl = '';
	this.hasPageToolBar = true;
	this.makesureMsg = '确定要删除';

	if (typeof(config) == "object") {
		this.columnID = config.id;
		this.ajaxUrl = config.url;
//		this.hasPageToolBar = config.ptb || this.hasPageToolBar;
		if(!config.ptb)
		this.hasPageToolBar = config.ptb ;
		this.makesureMsg = config.makesureMsg || this.makesureMsg;
	}
	if (!this.getSelectionModel().hasSelection()) {
		Ext.Msg.alert('提示', '请选择一条记录');
		return;
	}
	Ext.Msg.confirm('提醒', this.makesureMsg, function() {
				if (arguments[0] == 'yes') {
					var records = this.getSelectionModel().getSelections();
					var ids = records[0].get(this.columnID);
					for (var i = 1; i < records.length; i++) {
						ids = ids + ',' + records[i].get(this.columnID);
					};
					ajaxRequest(this.ajaxUrl, {
								ids : ids
							},
							// 调用common的showPage
							function(result) {
								if(result.success){
									if (this.hasPageToolBar) {
									var activePage = this.getBottomToolbar()
											.getPageData().activePage;
									// 回退页数
									var backword = 1;
									// 如果该页所有所有记录删除
									if (records.length == this.getStore()
											.getCount()) {
										backword = 2;
										if(activePage == 1){//第一页，即所有元素都被删除
											this.getStore().removeAll();
										}
									}
									this.getBottomToolbar()
											.doLoad((activePage - backword)
													* this.pageSize);
								   } else {
									this.getStore().removeAll();
								 	this.getStore().reload();
								   }
								}
								Ext.Msg.alert('提示',result.msg);
								if(config.adFunc){//执行额外操作
									config.adFunc();
								}
							}.createDelegate(this));
				} else {
					// Ext.Msg.alert(this.columnID);
				}
			}.createDelegate(this))
};
// ------------end delColumn
// -------------grid----renderer-------------
// linker: example(JSON格式):{text:'Ext',url:'http://extjs.com'}
function linker(val) {
	var data = Ext.decode(val);
	if (typeof data == 'object') {
		return '<a style="display:table;width:100%;" title="' + data.url
				+ '" target="_blank" href="' + data.url + '">' + data.text
				+ '</a>'
	}
	return val;

}
// num---color
function num(val) {
	if (val > 0) {
		return '<span style="color:green;">' + val + '</span>';
	} else if (val < 0) {
		return '<span style="color:red;">' + val + '</span>';
	}
	return val;
}
// icon,example:../images/ test.jgp
function icon(val) {
	return '<img src=' + val + '">'
}
// qtips ,example:../images/test.jgp
function qtips(val) {
	return '<span style="display:table;width:100%;" qtip=\'<img src="' + val
			+ '">\'>' + val.substring(val.lastIndexOf("/") + 1, val.length)
			+ '</span>'
}
// tips，example(JSON格式):{text:'Ext',tips:'http://extjs.com'}
function tips(val) {
	var data = Ext.decode(val);
	if (typeof(data) == 'object') {
		return '<span style="display:table;width:100%;" title="' + data.tips
				+ '">' + data.text + '</span>'

	} else {

		Ext.Msg.alert(val + " is not JSONObject-string");
	}
	return val
}
// tips--same
function tips_same(val) {

	return '<span style="display:table;width:100%;" title="' + val + '">' + val
			+ '</span>'

}
// ----end---------grid----renderer-------------
// --------show process------------
var showProcess = function() {
	Ext.MessageBox.show({
				title : '请稍等',
				msg : '正在提交数据...',
				progressText : '',
				width : 300,
				progress : true,
				closable : false,
				animEl : 'loding'
			});
	var f = function(v) {
		return function() {
			var i = v / 100;
			Ext.MessageBox.updateProgress(i, '');
		};
	};

	for (var i = 1; i < 13; i++) {
		setTimeout(f(i), i * 150);
	}
}
// ----------end show process--------------
// ----edit gird column------------
Ext.override(Ext.data.Store, {
			addField : function(field) {
				if (typeof field == 'string') {
					field = {
						name : field
					};
				}
				this.recordType.prototype.fields.replace(field);
				if (typeof field.defaultValue != 'undefined') {
					this.each(function(r) {
								if (typeof r.data[field.name] == 'undefined') {
									r.data[field.name] = field.defaultValue;
								}
							});
				}
			},
			removeField : function(name) {
				this.recordType.prototype.fields.removeKey(name);
				this.each(function(r) {
							delete r.data[name];
						});
			}
		});
Ext.override(Ext.grid.ColumnModel, {
			addColumn : function(column, colIndex) {
				if (typeof column == 'string') {
					column = {
						header : column,
						dataIndex : column
					};
				}
				var config = this.config;
				this.config = [];
				if (typeof colIndex == 'number') {
					config.splice(colIndex, 0, column);
				} else {
					colIndex = config.push(column);
				}
				this.setConfig(config);
				return colIndex;
			},
			removeColumn : function(colIndex) {
				var config = this.config;
				this.config = [config[colIndex]];
				config.remove(colIndex);
				this.setConfig(config);
			}
		});
Ext.override(Ext.grid.GridPanel, {
			addColumn : function(field, column, colIndex) {
				if (!column) {
					if (field.dataIndex) {
						column = field;
						field = field.dataIndex;
					} else {
						column = field.name || field;
					}
				}
				this.store.addField(field);
				this.colModel.addColumn(column, colIndex);
			},
			removeColumn : function(name, colIndex) {
				this.store.removeField(name);
				if (typeof colIndex != 'number') {
					colIndex = this.colModel.findColumnIndex(name);
				}
				if (colIndex >= 0) {
					this.colModel.removeColumn(colIndex);
				}
			}
		});
// -----------end----edit gird column---------
//------字符长度判断及截取，汉字返回2，其他返回1-------
function substrTrueLength(data,length){
	if(length>getTrueLength(data))return data;
	var tmp="";
	for(i=0,j=0;i<data.length&&j<length-1;i++){
		tmp += data.substr(i,1);
		if(ischinese(data.substr(i,1))){
			j +=2; 
		}else{
			j +=1;
		}
	}
	return tmp;
}
function getTrueLength(data){
	var count = 0;
	for(i=0;i<data.length;i++){
		if(ischinese(data.substr(i,1))){
			count +=2; 
		}else{
			count +=1;
		}
	}
	return count;
}
function ischinese(str){
	var   pattern   =   /^([\u4E00-\u9FA5]|[\uFE30-\uFFA0])*$/gi;   
  if   (pattern.test(str)){
  	return true;
  }else{
  	return false;
  }
}
//------字符长度判断，汉字返回2，其他返回1-------
// ------------统计图表---折线图----------

//参数含义(传递的数组，横坐标，纵坐标，图表的宽度，图表的高度,折线条数)
//传递的数组描述：new array(横坐标数组,数据数组1，数据数组2，数据数组3......)
//	 数据数组描述：new array(整体参数,数据1，数据2，数据3，数据4......)
//	    整体参数：字符串"参数1线条的颜色，参数2线条的宽度，参数3线条的类型，参数4转折点的类型,参数5线条" 
//	         例："#FF0000,1.5,1,2,公司1"
function table_fold(total,all_width,all_height,line_no)
{
var table_x = 1;
var table_y = 2;
var returnStr = "";
var line_color = "#69f";
var left_width = 35;
var total_no = total[1].length//每条折线的记录点数量
var temp1,temp2,temp3,temp4//temp1：传入数据最大纵坐标值；temp2：传入数据最大纵坐标值的第2位数字；temp3：显示最大纵坐标；
temp1 = 0;
temp2 = 0;
temp3 = 0;
temp4 = 0;
//调整传入参数
if(line_no == 0)line_no = total.length-1;
if(all_width<total_no*80)all_width=total_no*80;//每列最小宽度
//计算传入的最大值
for(var i=1;i<total_no;i++)
{
 for(var j=1;j<=line_no;j++)
 {
  if(parseInt(temp1)<parseInt(total[j][i])){
   temp1 = total[j][i];
  }
 } 
}
temp1 = parseInt(temp1);
//---end---计算传入的最大值
//计算纵坐标显示的最大值
if(temp1>9)
{
 temp2 = temp1.toString().substr(1,1);
 if(temp2>4)
 {
  temp3 = (parseInt(temp1/(Math.pow(10,(temp1.toString().length-1))))+1)*Math.pow(10,(temp1.toString().length-1));
 }
 else
 {
  temp3 = (Math.round(temp1/(Math.pow(10,(temp1.toString().length-1))))+0.5)*Math.pow(10,(temp1.toString().length-1))
 }
 
}
else
{
 if(temp1>4)
 {
  temp3 = 10; 
 }
 else
 {
  temp3 = 5;
 }
}
temp4 = temp3;
//-------计算纵坐标显示的最大值
returnStr += "<v:rect id='_x0000_s1027' alt='' style='position:absolute;left:" + (table_x + left_width) + "px;top:" + table_y + "px;width:" + all_width + "px;height:" + all_height + "px;z-index:-1' fillcolor='#9cf' stroked='f'><v:fill rotate='t' angle='-45' focus='100%' type='gradient'/></v:rect>";
//绘制5层纵坐标
for(var i=0;i<all_height;i += all_height/5)
{
 returnStr += "<v:line id='_x0000_s1027' alt='' style='position:absolute;left:0;text-align:left;top:0;flip:y;z-index:-1' from='" + (table_x + left_width + length) + "px," + (table_y + all_height - length - i) + "px' to='" + (table_x + all_width + left_width) + "px," + (table_y + all_height - length - i) + "px' strokecolor='" + line_color + "'/>";
 returnStr += "<v:line id='_x0000_s1027' alt='' style='position:absolute;left:0;text-align:left;top:0;flip:y;z-index:-1' from='" + (table_x + (left_width - 15)) + "px," + (table_y + i) + "px' to='" + (table_x + left_width) + "px," + (table_y + i) + "px'/>";
 returnStr += "<v:shape id='_x0000_s1025' type='#_x0000_t202' alt='' style='position:absolute;left:" + table_x + "px;top:" + (table_y + i) + "px;width:" + left_width + "px;height:18px;z-index:1'>";
 returnStr += "<v:textbox inset='0px,0px,0px,0px'><table cellspacing='3' cellpadding='0' width='100%' height='100%'><tr><td align='right'>" + temp4 + "</td></tr></table></v:textbox></v:shape>";
 temp4 = temp4 - temp3/5;
}
returnStr += "<v:line id='_x0000_s1027' alt='' style='position:absolute;left:0;text-align:left;top:0;flip:y;z-index:-1' from='" + (table_x + left_width) + "px," + (table_y + all_height) + "px' to='" + (table_x + all_width + left_width) + "px," + (table_y + all_height) + "px'/>";
returnStr += "<v:line id='_x0000_s1027' alt='' style='position:absolute;left:0;text-align:left;top:0;flip:y;z-index:-1' from='" + (table_x + left_width) + "px," + table_y + "px' to='" + (table_x + left_width) + "px," + (table_y + all_height) + "px'/>";
var tmpStr = ""
for(i=1;i<=line_no;i++)
{
 var re  = /,/g;
 tmpStr += ",[\"" + total[i][0].replace(re,"\",\"") + "\"]"
}
tmpStr = tmpStr.substr(1,tmpStr.length-1)
//参数1线条的颜色，参数2线条的宽度，参数3线条的类型，参数4转折点的类型,参数5线条名称
var line_code = eval("new Array(" + tmpStr + ")")
for(var j=1;j<=line_no;j++)
{
 var x1,y1,x2,y2;
 if(total_no==1){//没有横坐标
 	x2 = table_x + left_width ;
    y2 = table_y + all_height;
 }
 if(total_no==2){//一个横坐标
    x2 = table_x + left_width ;
    y2 = table_y + (temp3 - total[j][1]) * (all_height/temp3)
 }
 for(var i=1;i<total_no-1;i++)
 {
   x1 = table_x + left_width + all_width * (i - 1)/(total_no-1)
   y1 = table_y + (temp3 - total[j][i]) * (all_height/temp3)
   x2 = table_x + left_width + all_width * i/(total_no-1)
   y2 = table_y + (temp3 - total[j][i+1]) * (all_height/temp3)
  
  returnStr += "<v:line id='_x0000_s1025' alt='' style='position:absolute;left:0;text-align:left;top:0;z-index:1' from='" + x1 + "px," + y1 + "px' to='" + x2 + "px," + y2 + "px' coordsize='21600,21600' strokecolor='" + line_code[j-1][0] + "' strokeweight='" + line_code[j-1][1] + "'>";
  //线条类型
  switch (parseInt(line_code[j-1][2]))
  {
   case 1:
    break;
   case 2:
    returnStr += "<v:stroke dashstyle='1 1'/>";
    break;
   case 3:
    returnStr += "<v:stroke dashstyle='dash'/>";
    break;
   case 4:
    returnStr += "<v:stroke dashstyle='dashDot'/>";
    break;
   case 5:
    returnStr += "<v:stroke dashstyle='longDash'/>";
    break;
   case 6:
    returnStr += "<v:stroke dashstyle='longDashDot'/>";
    break;
   case 7:
    returnStr += "<v:stroke dashstyle='longDashDotDot'/>";
    break;
  }
  
  returnStr += "</v:line>";
  //转折点
  switch (parseInt(line_code[j-1][3]))
  {
   case 1:
    break;
   case 2:
    returnStr += "<v:rect id='_x0000_s1027' style='position:absolute;left:" + (x1 - 2) + "px;top:" + (y1 - 2) + "px;width:4px;height:4px; z-index:2' fillcolor='" + line_code[j-1][0] + "' strokecolor='" + line_code[j-1][0] + "'/>";
    break;
   case 3:
    returnStr += "<v:oval id='_x0000_s1026' style='position:absolute;left:" + (x1 - 2) + "px;top:" + (y1 - 2) + "px;width:4px;height:4px;z-index:1' fillcolor='" + line_code[j-1][0] + "' strokecolor='" + line_code[j-1][0] + "'/>";
    break;
  } 
  
 }
  //最后一个转折点
  switch (parseInt(line_code[j-1][3]))
  {
   case 1:
    break;
   case 2:
    returnStr += "<v:rect id='_x0000_s1027' style='position:absolute;left:" + (x2 - 2) + "px;top:" + (y2 - 2) + "px;width:4px;height:4px; z-index:2' fillcolor='" + line_code[j-1][0] + "' strokecolor='" + line_code[j-1][0] + "'/>";
    break;
   case 3:
    returnStr += "<v:oval id='_x0000_s1026' style='position:absolute;left:" + (x2 - 2) + "px;top:" + (y2 - 2) + "px;width:4px;height:4px;z-index:1' fillcolor='" + line_code[j-1][0] + "' strokecolor='" + line_code[j-1][0] + "'/>";
    break;
  }
}
//右上角文字说明
for(var i=0;i<total_no-1;i++)
{
 returnStr += "<v:line id='_x0000_s1027' alt='' style='position:absolute;left:0;text-align:left;top:0;flip:y;z-index:-1' from='" + (table_x + left_width + all_width * (i)/(total_no-1)) + "px," + (table_y + all_height) + "px' to='" + (table_x + left_width + all_width * (i)/(total_no-1)) + "px," + (table_y + all_height + 15) + "px'/>";
 returnStr += "<v:shape id='_x0000_s1025' type='#_x0000_t202' alt='' style='position:absolute;left:" + (table_x + left_width + all_width * (i)/(total_no-1)) + "px;top:" + (table_y + all_height) + "px;width:" + (all_width/(total_no-1)) + "px;height:18px;z-index:1'>";
 returnStr += "<v:textbox inset='0px,0px,0px,0px'><table cellspacing='3' cellpadding='0' width='100%' height='100%'><tr><td align='left'>" + total[0][i] + "</td></tr></table></v:textbox></v:shape>";
}
//右上角与说明对应的颜色块
var tb_height = 20
returnStr += "<v:rect id='_x0000_s1025' style='position:absolute;left:" + (table_x + all_width + 20) + "px;top:" + table_y + "px;width:100px;height:" + (line_no * tb_height + 10) + "px;z-index:1'/>";
for(var i=0;i<line_no;i++)
{
 returnStr += "<v:shape id='_x0000_s1025' type='#_x0000_t202' alt='' style='position:absolute;left:" + (table_x + all_width + 20) + "px;top:" + (table_y + 10+(i) * tb_height) + "px;width:70px;height:" + tb_height + "px;z-index:1'>";
 returnStr += "<v:textbox inset='0px,0px,0px,0px'><table cellspacing='3' cellpadding='0' width='100%' height='100%'><tr><td align='left'>" + line_code[i][4] + "</td></tr></table></v:textbox></v:shape>";
 returnStr += "<v:rect id='_x0000_s1040' alt='' style='position:absolute;left:" + (table_x + all_width + 80) + "px;top:" + (table_y + 10+(i) * tb_height + 4) + "px;width:30px;height:10px;z-index:1' fillcolor='" + line_code[i][0] + "'><v:fill color2='" + line_code[i][0] + "' rotate='t' focus='100%' type='gradient'/></v:rect>";
}
return returnStr;
}
//----end--------折线图
//---------无权限-panel-----
NotEnoughRightPanel = function(){	
	NotEnoughRightPanel.superclass.constructor.call(this,{
		border:true,
		html:'您没有足够的权限'
	})
};
Ext.extend(NotEnoughRightPanel, Ext.Panel, {});
//---------无权限---------
Ext.namespace('Ext.ux');
//Utility classif(!Ext.ux.Utility)    
Ext.ux.Utility = {
	isNullOrUndefined: function(obj){           
		return (typeof obj == 'undefined' || obj == null ); 
	},        
	isFunction: function(f){
		return typeof f == 'function';
	}
};
Ext.ux.FieldReadOnlyPlugin = function(){
    
    this.init = function(f){
         f.setReadOnly = function(value){
            if(f.readOnly)//if setted readonly in the Ext way, like in cfg object, do not take any action.
                return;
            f._readOnly = value;
            if(f.rendered){
                if(Ext.ux.Utility.isNullOrUndefined(f.editable) || f.editable === true){
                    var el = f.getEl();
                    el.dom.setAttribute('readOnly', value);
                    el.dom.readOnly = value;
                }
            }
            else {
                f.readOnly = value;
            }
         };
        
        if(Ext.ux.Utility.isFunction(f.expand))
            f.expand = f.expand.createInterceptor(function(){
                return !f._readOnly;      
            }); 
        if(Ext.ux.Utility.isFunction(f.onTriggerClick))
            f.onTriggerClick = f.onTriggerClick.createInterceptor(function(){
                return !f._readOnly;      
            });
        if(Ext.ux.Utility.isFunction(f.onClick))
            f.onClick = f.onClick.createInterceptor(function(){
                if(f._readOnly){
                    this.el.dom.checked = f.checked;
                }
                return !f._readOnly;      
            });
        if(Ext.ux.Utility.isFunction(f.setValue) && f instanceof Ext.form.Checkbox)
            f.setValue = f.setValue.createInterceptor(function(){ 
                return !f._readOnly;      
            }); 
    }
}
