window.console = window.console || {log : $.noop, dir : $.noop};

$(function()
{
	var userAgent = window.navigator.userAgent.toLowerCase();
	$.browser.msie10 = $.browser.msie && /msie 10\.0/i.test(userAgent);
	$.browser.msie9 = $.browser.msie && /msie 9\.0/i.test(userAgent);
	$.browser.msie8 = $.browser.msie && /msie 8\.0/i.test(userAgent);
	$.browser.msie7 = $.browser.msie && /msie 7\.0/i.test(userAgent);
	$.browser.msie6 = !$.browser.msie8 && !$.browser.msie7 && $.browser.msie && /msie 6\.0/i.test(userAgent);
});


/**
 * 如果浏览器是ie6,在遮罩层上增加iframe解决ie6的zindex穿透问题
 */
(function($)
{
	if ($.browser.msie6)		//如果浏览器是ie6
	{
		$.fn.easyui_window = $.fn.window;
		$.fn.window = function(options, param)
		{
			var rt = $(this).easyui_window(options, param);
			if (typeof options != "string")
			{
				//在遮罩层上增加iframe解决ie6的zindex穿透问题
				$(".window-mask:not(:has(.mask-iframe))").append("<iframe class='mask-iframe' style='position: absolute;width: 100%;height: 100%;z-index:-1;filter:alpha(opacity=0);'></iframe>");
			}
			return rt;
		};
		$.fn.window.methods = $.fn.easyui_window.methods;
		$.fn.window.parseOptions = $.fn.easyui_window.parseOptions;
		$.fn.window.defaults = $.fn.easyui_window.defaults;
	} 
})(jQuery);

$(document).ready(function()
{
	$('body').unbind('keydown');
	$('body').bind('keydown', function(e)
	{
		switch(e.keyCode)		//屏蔽【退格键】
		{
			case 8:
				if((e.target.nodeName != 'INPUT' && e.target.nodeName != 'TEXTAREA') || $(e.target).attr('readonly') == 'readonly')
					e.preventDefault();
				break;
		}
	});
});

/* 全局ajax设置 */
$.ajaxSetup
({
	type: "POST",
	traditional : true,
	cache : false,
	//async: false,		//同步请求
	context: document.body,
	beforeSend : function(jqXHR)
	{
		//showProgressBar();
	},
	complete : function(jqXHR, textStatus)
	{
		//closeProgressBar();
		if(textStatus == 'success')
		{
			try
			{
				var contentType = jqXHR.getResponseHeader('Content-Type');
				if(contentType != null && contentType.toLowerCase().indexOf('text/html') == -1)
				{
					var respJson = $.parseJSON(jqXHR.responseText);
					//转换成功，表示是一个JSON
					if(respJson.sessionTimeout)		//会话过期
					{
						$('.easyui-window:visible').window('close');
						window.top.$.fn.window.defaults.closable = false;
						window.top.$.messager.alert('错误', '会话已过期，请重新登录。', 'error', function()
						{
							window.top.location.href = '';
						});
					}
					if(respJson.errorMsg)
						window.top.$.messager.alert('错误', respJson.errorMsg, 'error');
				}
			}
			catch(e){/*do nothing*/}		//转换失败，表示是一个页面
		}
		else if(textStatus == 'error')
		{
			var msg = '<P style="color: red;">服务器内部错误，请联系系统管理员。</P>详细信息：<BR><PRE>' +jqXHR.responseText+ '</PRE>';
			$('.easyui-window:visible').window('close');
			$.messager.alert('错误', msg, 'error');
			UIutil.closeProgressBar();
		}
	}
});

/** 扩展easyui-treegrid方法 */
/*$.extend($.fn.treegrid.methods, 
{
	check : function(jq, id)
	{
		return jq.each(function()
		{
			checkById(this, id);
		});
		
		function checkById($grid, id)
		{
			var gridCfg=$.data($grid,"treegrid");
			var opts=gridCfg.options;
			if(opts.checkOnSelect)		//选中的行必会勾选
				$grid.treegrid('select', id);
			else
			{
				var ck=opts.finder.getTr($grid, id).find("div.datagrid-cell-check input[type=checkbox]");
				ck._propAttr("checked",true);
			}
			var row=opts.finder.getRow($grid, id);
			opts.onCheck.call($grid, row);
		}
	},
	uncheck : function(jq, id)
	{
		return jq.each(function()
		{
			uncheckById(this, id);
		});
		
		function uncheckById($grid, id)
		{
			var gridCfg=$.data($grid,"treegrid");
			var opts=gridCfg.options;
			if(opts.checkOnSelect)		//选中的行必会勾选
				$grid.treegrid('unselect', id);
			else
			{
				var ck=opts.finder.getTr($grid, id).find("div.datagrid-cell-check input[type=checkbox]");
				ck._propAttr("checked", false);
				
				var row=opts.finder.getRow($grid, id);
				opts.onUncheck.call($grid, row);
			}
		}
	},
	getChecked : function(jq)
	{
		var gridCfg=$.data(jq[0], "treegrid");
		var opts=gridCfg.options;
		if(opts.selectOnCheck)			//勾选的行必是选中状态
			return jq[0].treegrid('getSelections');
		
		var nodes = [];
		opts.finder.getTr(jq[0], "", "checked").each(function()
		{
			nodes.push(opts.finder.getRow(jq[0], $(this)));
		});
		return nodes;
	}
});*/

/* panel默认加载提示信息 */
$.fn.panel.defaults.loadingMessage = '加载中...';

/* 定义easyui alert关闭按钮事件(对应版本：easyui-1.3) */
//$.extend($.messager, 
//{
//	alert : function(_217, msg, icon, fn)
//	{
//		var contentHtml = "<div>" + msg + "</div>";
//		switch (icon)
//		{
//			case "error" :
//				contentHtml = "<div class=\"messager-icon messager-error\"></div>" + contentHtml;
//				break;
//			case "info" :
//				contentHtml = "<div class=\"messager-icon messager-info\"></div>" + contentHtml;
//				break;
//			case "question" :
//				contentHtml = "<div class=\"messager-icon messager-question\"></div>" + contentHtml;
//				break;
//			case "warning" :
//				contentHtml = "<div class=\"messager-icon messager-warning\"></div>" + contentHtml;
//				break;
//		}
//		contentHtml += "<div style=\"clear:both;\"/>";
//		var _219 = {};
//		_219[$.messager.defaults.ok] = function()
//		{
//			win.dialog({closed : true});
//			/*if(fn)
//			{
//				fn();
//				return false;
//			}*/
//		};
//		_219[$.messager.defaults.ok] = function()
//		{
//			win.window("close");
//			/*if (fn)
//			{
//				fn();
//				return false;
//			}*/
//		};
//		var win = _211(_217, contentHtml, _219);
//		/* 自定義 $.message.alert 關閉事件 start */
//		win.window
//		({
//			onBeforeClose : function()
//			{
//				if (fn)
//					fn();
//			}
//		});
//		win.children("div.messager-button").children("a:first").focus();
//		/*自定義 end*/
//		
//		function _211(_212,_213,_214){
//		var win=$("<div class=\"messager-body\"></div>").appendTo("body");
//		win.append(_213);
//		if(_214){
//		var tb=$("<div class=\"messager-button\"></div>").appendTo(win);
//		for(var _215 in _214){
//		$("<a></a>").attr("href","javascript:void(0)").text(_215).css("margin-left",10).bind("click",eval(_214[_215])).appendTo(tb).linkbutton();
//		}
//		}
//		win.window({title:_212,noheader:(_212?false:true),width:300,height:"auto",modal:true,collapsible:false,minimizable:false,maximizable:false,resizable:false,onClose:function(){
//		setTimeout(function(){
//		win.window("destroy");
//		},100);
//		}});
//		win.window("window").addClass("messager-window");
//		//win.children("div.messager-button").children("a:first").focus();
//		return win;
//		};
//	}
//});

$.fn.datagrid.defaults.fitColumns = true;
$.fn.datagrid.defaults.striped = true;
/* 分页栏默认总记录数 */
$.fn.pagination.defaults.total = 0;
$.fn.pagination.defaults.pageNumber = 0;
$.fn.datagrid.defaults.pageSize = 20;
$.fn.datagrid.defaults.pageList = [20, 50, 100, 200];
/* datagrid默认加载机制 */
$.fn.datagrid.defaults.loader = function(param, success, error)
{
	var $this = $(this);
	var opts = $this.datagrid('options');
	if(! opts.url)
		return false;
	
	$.ajax
	({
		type : opts.method || 'post',
		url : opts.url,
		data : param,
		//contentType : 'application/json;charset=UTF-8',
		success : function(data, textStatus, jqXHR)
		{
			if(typeof data == 'string'){
				data = $.parseJSON(data);
			}
			UIutil.alertRespJsonMsg(data);
			if(data.flag)
				success(data);
			else
				error();
		},
		error : function(XMLHttpRequest, textStatus, e)
		{
			error();
		}
	});
};

/**
 * 扩展datagrid方法增加以下方法
 * 1、silentSelectRow(index) ：静默选中指定行（不触发onSelect事件）；
 * 2、silentUnselectRow(index) ：静默取消选中指定行（不触发onUnselect事件）。
 * 3、getRowsByField({filed:'', value:''})：根据指定字段的值过滤行
 */
$.extend($.fn.datagrid.methods,
{
	/** 根据指定字段的值过滤行 */
	getRowsByField : function(jq, param)
	{
		var rs = [];
		if(param)
		{
			var rows = $(jq[0]).datagrid('getRows');
			for(var i in rows)
			{
				if(rows[i][param.field] == param.value)
					rs.push(rows[i])
			}
		}
		return rs;
	},
	/** 静默选中指定行（不触发onSelect事件） */
	silentSelectRow : function(jq, index)
	{
		jq.each(function()
		{
			var $grid = $(this);
			var data = $grid.data('datagrid');
			
			data.selectedRows.push(data.data.rows[index]);		//添加到selectedRows中
			
			var $panel = $grid.datagrid('getPanel');
			/* 添加选中样式 */
			var $tr1s = $panel.find('div.datagrid-view1 tr.datagrid-row');
			var $tr2s = $panel.find('div.datagrid-view2 tr.datagrid-row');
			var $tr1 = $tr1s.filter('[datagrid-row-index="' + index + '"]');
			var $tr2 = $tr2s.filter('[datagrid-row-index="' + index + '"]');
			if(! $tr1.hasClass('datagrid-row-selected'))
			{
				$tr1.addClass('datagrid-row-selected');
				$tr2.addClass('datagrid-row-selected');
			}
			
			if(data.options.checkOnSelect)					//选择即勾选
			{
				data.checkedRows.push(data.data.rows[index]);		//添加到checkedRows中
				if(! $tr1.hasClass('datagrid-row-checked'))
				{
					$tr1.addClass('datagrid-row-checked');		//添加勾选样式
					$tr2.addClass('datagrid-row-checked');		//添加勾选样式
				}
				$tr1.find(':checkbox').attr('checked', true);
			}
		});
	},
	/** 静默取消选中指定行（不触发onUnselect事件） */
	silentUnselectRow : function(jq, index)
	{
		jq.each(function()
		{
			var $grid = $(this);
			var data = $grid.data('datagrid');
			
			data.selectedRows = $.grep(data.selectedRows, function(row, i)		//过滤掉待移除的行
			{
				return $grid.datagrid('getRowIndex', row) != index;
			});
			
			var $panel = $grid.datagrid('getPanel');
			/* 移除选中样式 */
			var $tr1s = $panel.find('div.datagrid-view1 tr.datagrid-row');
			var $tr2s = $panel.find('div.datagrid-view2 tr.datagrid-row');
			var $tr1 = $tr1s.filter('[datagrid-row-index="' + index + '"]');
			var $tr2 = $tr2s.filter('[datagrid-row-index="' + index + '"]');
			if($tr1.hasClass('datagrid-row-selected'))
			{
				$tr1.removeClass('datagrid-row-selected');
				$tr2.removeClass('datagrid-row-selected');
			}
			
			if(data.options.checkOnSelect)					//选择即勾选
			{
				data.checkedRows = $.grep(data.checkedRows, function(row, i)
				{
					return $grid.datagrid('getRowIndex', row) != index;
				});
				if($tr1.hasClass('datagrid-row-checked'))
				{
					$tr1.removeClass('datagrid-row-checked');	//移除勾选样式
					$tr2.removeClass('datagrid-row-checked');	//移除勾选样式
				}
				$tr1.find(':checkbox').removeAttr('checked');
			}
		});
	}
});

$.extend($.messager,
{
	/** 展现多行文本框的对话框 */
	promptForTextArea : function(_28b,msg,fn)
	{
		var _28c="<div class=\"messager-icon messager-question\"></div>"+"<div>"+msg+"</div>"+"<br/>"+"<div style=\"clear:both;\"><textarea class=\"messager-input\" style=\"height: 80px;\"></textarea></div>";
		var _28d={};
		_28d[$.messager.defaults.ok]=function(){
		win.window("close");
		if(fn){
		fn(true, $(".messager-input",win).val());
		return false;
		}
		};
		_28d[$.messager.defaults.cancel]=function(){
		win.window("close");
		if(fn){
		fn(false, $(".messager-input",win).val());
		return false;
		}
		};
		var win=_27f(_28b,_28c,_28d);
		win.children("input.messager-input").focus();
		return win;
		
		function _27f(_280,_281,_282){
		var win=$("<div class=\"messager-body\"></div>").appendTo("body");
		win.append(_281);
		if(_282){
		var tb=$("<div class=\"messager-button\"></div>").appendTo(win);
		for(var _283 in _282){
		$("<a></a>").attr("href","javascript:void(0)").text(_283).css("margin-left",10).bind("click",eval(_282[_283])).appendTo(tb).linkbutton();
		}
		}
		win.window({title:_280,noheader:(_280?false:true),width:300,height:"auto",modal:true,collapsible:false,minimizable:false,maximizable:false,resizable:false,onClose:function(){
		setTimeout(function(){
		win.window("destroy");
		},100);
		}});
		win.window("window").addClass("messager-window");
		win.children("div.messager-button").children("a:first").focus();
		return win;
		};
	}
});

/**
 * Datagrid扩展方法tooltip 基于Easyui 1.3.3，可用于Easyui1.3.3+ 简单实现，如需高级功能，可以自由修改 使用说明:
 * 在easyui.min.js之后导入本js
 * 代码案例: $("#dg").datagrid({....}).datagrid('tooltip', 'fieldName');		//需要展现列内容的tooltip列名 
 */
$.extend($.fn.datagrid.methods,
{
	tooltip : function(jq, field)
	{
		return jq.each(function()
		{
			var panel = $(this).datagrid('getPanel');
			if (field)
				bindEvent(panel.find('div.datagrid-view2 div.datagrid-body table.datagrid-btable tr.datagrid-row td[field='+ field +']'), field);
		});

		function bindEvent(tds, field)
		{
			tds.mouseover(function(e)
			{
				var content = $(this).text();
				if(content == null || content == '')
					return;
				$(this).tooltip(
				{
					content : content,
					trackMouse : true,
					position : 'right',
					showDelay : 0,
					hideDelay : 0,
					trackMouseX : e.pageX,
					trackMouseY : e.pageY,
					onHide : function()
					{
						$(this).tooltip('destroy');
					}
				}).tooltip('show');
			});
		}
	}
});

/**
 * 修复easyui-window：vcenter、hcenter、center方法，变更window大小，遮罩没有正确跟随window的问题。
 */
$.extend($.fn.window.methods, 
{
	vcenter : function(jq)
	{
		jq.each(function()
		{
			var data = $(this).data('window');
			var winHeight = data.window.height;
			if(isNaN(winHeight))
				winHeight = data.window.outerHeight();
			
			var top = 0;
			if(data.options.inline)
			{
				var parent = data.window.parent();
				top = (parent.height() - winHeight) / 2 + parent.scrollTop();
			}
			else
				top = ($(window).height() - winHeight) / 2 + $(document).scrollTop();
			
			$(this).panel('resize', {top: top});
		});
	},
	hcenter : function(jq)
	{
		jq.each(function()
		{
			var data = $(this).data('window');
			var winWidth = data.window.width;
			if(isNaN(winWidth))
				winWidth = data.window.outerWidth();
			
			var left = 0;
			if(data.options.inline)
			{
				var parent = data.window.parent();
				left = (parent.width() - winWidth) / 2 + parent.scrollLeft();
			}
			else
				left = ($(window).width() - winWidth) / 2 + parent.scrollLeft();
			
			$(this).panel('resize', {left: left});
		});
	},
	center : function(jq)
	{
		jq.each(function()
		{
			var data = $(this).data('window');
			var parent = data.window.parent();
			
			var winHeight = data.window.height;
			if(isNaN(winHeight))
				winHeight = data.window.outerHeight();
			
			var top = 0;
			if(data.options.inline)
				top = (parent.height() - winHeight) / 2 + parent.scrollTop();
			else
				top = ($(window).height() - winHeight) / 2 + $(document).scrollTop();
			
			var winWidth = data.window.width;
			if(isNaN(winWidth))
				winWidth = data.window.outerWidth();
			
			var left = 0;
			if(data.options.inline)
				left = (parent.width() - winWidth) / 2 + parent.scrollLeft();
			else
				left = ($(window).width() - winWidth) / 2 + parent.scrollLeft();
			
			$(this).panel('resize', {top: top, left: left});
		});
	}
});

/** 扩展easyui-datagrid editor */
$.extend($.fn.datagrid.defaults.editors,
{
	/*
	options:
	{
		valueFormat: '[json|separatorJoin]',
		separator : '[.|,|:|...]',
		controlArr:
		[
			{type : 'textinput', options: {label: 'lable1', name: 'name1'}},
			{type : 'select', options: {label: 'label2', name: 'name2', optionArr: [...]}},
			...
		]
	}
	*/
	controlGroup :
	{
		init: function(container, options)
		{
			var $html = $('<span></span>');
			var ctrlArr = options.controlArr;
			if(ctrlArr)
			{
				for(var i in ctrlArr)
				{
					var editorType =  ctrlArr[i].type;
					if(editorType == null)
						continue;
					var label = ctrlArr[i].options ? ctrlArr[i].options.label || null : null;
					var name = ctrlArr[i].options ? ctrlArr[i].options.name || i : i;
					var labelHtml = '';
					if(label != null)
						labelHtml += '<label for="datagrid_ctrl_' + i + '" style="word-break: keep-all;">' + label + '</label>';
					$html.append(labelHtml);
					
					if(editorType == 'textinput')
					{
						var input = '<input id="datagrid_ctrl_' + i + '" name="' + name + '">';
						$html.append(input);
					}
					else if(editorType == 'select')
					{
						var input = '<select id="datagrid_ctrl_' + i + '"';
						if(name != null)
							input += ' name="' + name + '"';
						input += '>';
						var textField = ctrlArr[i].options.textField || 'text';
						var valueField = ctrlArr[i].options.valueField || 'value';
						
						var optionArr = ctrlArr[i].options.optionArr;
						for(var i = 0 ;i < optionArr.length ;i++)
							input += '<option value="' + optionArr[i][valueField] + '">' + optionArr[i][textField] + '</option>';
						input += '</select>';
						$html.append(input);
					}
					else
					{
						alert('暂不支持[textinput]和[select]之外的组合控件。');
						return '';
					}
				}
			}
			$html.appendTo(container);
			$html.data('valueFormat', options.valueFormat || 'json');
			$html.data('separator', options.separator || ',');
			return $html;
		},
		getValue : function(target)
		{
			format = target.data('valueFormat');
			if(format == 'json')
			{
				var valObj = {};
				$.each(target.find(':input'), function(i, input)
				{
					var val = $(input).val();
					if(val != '')
						valObj[$(input).attr('name')] = val;
				});
				return valObj;
			}
			else		//format == separatorJoin
			{
				var separator = target.data('separator');
				var valArr = [];
				$.each(target.find(':input'), function(i, input)
				{
					valArr.push($(input).val() || '');
				});
				return valArr.join(separator);
			}
		},
		setValue : function(target, value)
		{
			if(value == null || $.isEmptyObject(value))
				return;
			format = target.data('valueFormat');
			if(format == 'json')
			{
				$.each(target.find(':input'), function(i, input)
				{
					var $input = $(input);
					$input.val(value[$input.attr('name')]);
				});
			}
			else		//format == separatorJoin
			{
				var separator = target.data('separator');
				var valArr = value.split(separator);
				$.each(target.find(':input'), function(i, input)
				{
					$(input).val(valArr[i]);
				});
			}
		},
		resize : function(target, width)
		{
			var ctrlArr = [];
			$.each(target.children(), function(i, node)
			{
				$node = $(node);
				if($node.is('label'))
				{
					ctrlArr.push({label: $node});
				}
				else if($node.is(':input'))
				{
					if(ctrlArr[ctrlArr.length - 1] != null && ctrlArr[ctrlArr.length - 1].label != null)
						ctrlArr[ctrlArr.length-1].input = $node;
					else
						ctrlArr.push({input: $node});
				}
			});
			
			var wid = width / ctrlArr.length;
			for(var i in ctrlArr)
				ctrlArr[i].input.width(ctrlArr[i].label ? wid - ctrlArr[i].label.width() : wid);
		}
	},
	selectGroup :
	{
		/*
		options:
		{
			selectArr:
			[
				{optionArr: [{text: '...', value: '...'}, ...], relatedSelectIndex : 1, relatedFn : function($this, $targetSelect){...}},
				{optionArr: [{text: '...', value: '...'}, ...], relatedSelectIndex : 2, relatedFn : function($this, $targetSelect){...}},
				...
			]
		}
		 */
		init: function(container, options)
		{
			var html = '<span></span>';
			var $html = $(html).appendTo(container);
			
			var selectCount = 0;
			if(options.selectArr)
			{
				var selectArr = options.selectArr;
				for(var i in selectArr)
				{
					selectCount++;
					
					var select = '<select>';
					if(selectArr[i].optionArr)
					{
						var optionArr = selectArr[i].optionArr;
						var optArr = (optionArr instanceof Function ? eval(selectArr[i].optionArr)() : optionArr);
						for(var j in optArr)
							select += '<option value="' + (optArr[j].value || '') + '">' + (optArr[j].text || '') + '</option>';
					}
					select += '</select>';
					var $select = $(select).appendTo($html);
					
					if(selectArr[i].relatedFn instanceof Function && selectArr[i].relatedSelectIndex != null)
					{
						$select.data('relatedSelectIndex', selectArr[i].relatedSelectIndex);
						$select.data('relatedFn', selectArr[i].relatedFn);
					}
				}
			}
			
			/* 注册srcSelect、relatedFn */
			var $selectArr = $html.find('select');
			$.each($selectArr, function(i, select)
			{
				var $select = $(select);
				var relatedIdx = $select.data('relatedSelectIndex');
				if(relatedIdx != null)
				{
					var $targetSelect = $($selectArr[relatedIdx]);
					if($targetSelect.length > 0 && ! $targetSelect.is($select))
					{
						$targetSelect.data('$srcSelect', $select);
				
						var relatedFn = $select.data('relatedFn');
						if(relatedFn instanceof Function)
						{
							$select.bind('change', function()
							{
								relatedFn($select, $targetSelect);
							});
						}
					}
				}
			});
			
			$html.data('selectCount', selectCount)
			return $html;
			
		},
		getValue : function(target)
		{
			var $span = $(target);
			var val = '';
			$.each($span.find('select'), function(i, select)
			{
				if(val.length > 0)
					val += '.';
				val += $(select).val() || '';
			});
			return val;
		},
		setValue : function(target, value)
		{
			if(value == undefined || value == "")
				return;
			
			var $span = $(target);
			var valArr = value.split('.');
			$.each($span.find('select'), function(i, select)
			{
				if(valArr[i] == null)
					return true;
				$(select).val(valArr[i]);
				$(select).triggerHandler('change');
			});
		},
		resize : function(target, width)
		{
			var $span = $(target);
			if ($.boxModel == true)
				width = width - ($span.outerWidth() - $span.width());
			
			var selectCount = $span.data('selectCount');
			if(selectCount > 0)
			{
				var wid = width / selectCount;
				$span.find('select').width(wid);
			}
			
		    $span.width(width);
		}
	},
	/*
	options:{label: "label1", attrbute1:"...", attrbute2:"...", ...}
	*/
	textinput :
	{
		init : function(container, options)
		{
			var text = '';
			if(options && options.label != null)
				text = '<label>' + options.label + '</label>';
			
			text += '<input type="text" ';
			if (options)
			{
				for(var key in options)
				{
					if(key == 'label')
						continue;
					text += '' + key + '="' + options[key] + '" ';
				}
			}
			text += ">";
			var input = $(text).appendTo(container);
			input.data('options', options);
			return input;
		},
		getValue : function(target)
		{
			return $(target).val();
		},
		setValue : function(target, value)
		{
			if (value)
				$(target).val(value);
			else if ($(target).data('options'))
				$(target).val($(target).data('options').value);
		},
		resize : function(target, width)
		{
			var input = $(target);
			if ($.boxModel == true)
				input.width(width - (input.outerWidth() - input.width()) - 5);
			else
				input.width(width - 5);
		}
	},
	select :
	{
		/*
		options:
		{
			label : 'label1',
			className : '...', valueField : 'value',textField : 'text', 
			optionArr:
			[
				{text:'...', value: '...'},
				{},
				...
			],
			onchange : function(e){...},
			callback : function(){}
		}
		*/
		init: function(container, options)
		{
			var className = options.className;
			var optionArr = options.optionArr;
			var textField = options.textField || 'text';
			var valueField = options.valueField || 'value';
			var defaultValue = options.defaultValue;
			var html = '';
			if(options.label != null)
				html += '<label for="datagrid_select"><span>' + options.label + '</span></label>';
			
			html += '<select id="datagrid_select"';
			if(className)
				html += ' class="' + className + '"';
			
			html += ">";
			for(var i = 0 ;i < optionArr.length ;i++)
				html += '<option value="' + (optionArr[i][valueField] || '') + '">' + (optionArr[i][textField] || '') + '</option>';
			
			html += '</select>';
			
			var select = $(html).appendTo(container);
			
			if(options.defaultValue != null)
				$(select).val(options.defaultValue);
			
			var onchange = options.onchange;
			if(onchange)
				$(select).bind("change" , {$select : $(select)}, onchange);
			
			var callback = options.callback;
			if(callback)
				callback.call(select);
			
			return select;
        },  
		getValue: function(target)
		{
			if(target.is('label'))
				return $(target).nextAll('select').val();
		    return $(target).val();
		},
		setValue: function(target, value)
		{
			if(target.is('label'))
				$(target).nextAll('select').val(value || '');
			else
		    	$(target).val(value || '');
		},
		resize: function(target, width)
		{
			var ctrlArr = [];
			$.each(target, function(i, node)
			{
				$node = $(node);
				if($node.is('label'))
					ctrlArr.push({label: $node});
				if($node.is(':input'))
				{
					if(ctrlArr[i-1] != null && ctrlArr[i-1].label != null)
						ctrlArr[i-1].input = $node;
					else
						ctrlArr.push({input: $node});
				}
			});
			
			var wid = width / ctrlArr.length;
			for(var i in ctrlArr)
				ctrlArr[i].input.width(ctrlArr[i].label ? wid - ctrlArr[i].label.width() : wid);
		}
	},
	radioboxGroup :
	{
		/** options:{itemArr:[text:"...", value:"...", checked:true]} */
		init: function(container, options)
		{
			var itemArr = options.itemArr;
			var html = '<SPAN>';
			for(var i = 0 ;i < itemArr.length ;i++)
			{
				html += '<LABEL><INPUT type="radio" name="dataGridCellRadio" value="' + itemArr[i].value + '" ';
				if(itemArr[i].checked == true)
					html += 'checked="checked"';
				html += '>' + itemArr[i].text + '</LABEL>';
			}
			html += "</SPAN>";
			var radioBox = $(html).appendTo(container);  
			return radioBox;
        },
        getValue: function(target)
        {
	        return $(target).find(':radio:checked').val();
        },
        setValue: function(target, value)
        {
            $(target).find(':radio[value="' + value + '"]').click();
        },
        resize: function(target, width)
        {
            var $select = $(target);
            if ($.boxModel == true)
                $select.width(width - ($select.outerWidth() - $select.width()));
            else
                $select.width(width);  
        }
	},
	checkbox:
	{
		/** options:{on: true, off: false, align:'left|center|right', onchange: function(){...}} */
		init: function(container, options)
		{
			var html = '<INPUT type="checkbox"';
			if(options.align)
				html += ' style="text-align: ' + options.align + ';"';
			html += '>';
			var chkBox = $(html).appendTo(container);
			if(options.onchange instanceof Function)
				chkBox.bind('change', options.onchange);
			chkBox.data('displayCfg', {on: options.on, off: options.off});
			return chkBox;
        },
        getValue: function(target)
        {
	        if($(target).attr('checked'))
	        	return $(target).data('displayCfg').on;
	        return $(target).data('displayCfg').off;
        },
        setValue: function(target, value)
        {
        	if(value == 'true' || value == true)
            	$(target).attr('checked', 'checked');
            else
        		$(target).removeAttr('checked');
        },
        resize: function(target, width)
        {
            var $target = $(target);
            if ($.boxModel == true)
                $target.width(width - ($target.outerWidth() - $target.width()));
            else
                $target.width(width);  
        }
	}/*,
	textarea:
	{
		*//** options:{width : 200, height : 60} *//*
		init: function(container, options)
		{
			var html = '<textarea';
			if(options.width || options.height)
			{
				html += ' style="';
				if(options.width)
					html + 'width:'+options.width+'px;';
				if(options.height)
					html + ' height:'+options.height+'px;';
				html += '"'
			}
			html += '></textarea>';
			var textarea = $(html).appendTo(container);
			textarea.data('options', options);
			return textarea;
        },
        getValue: function(target)
        {
	        return $(target).val();
        },
        setValue: function(target, value)
        {
    		$(target).val(value);
        },
        resize: function(target, width)
        {
            var $target = $(target);
            var opts = $target.data('options');
            
            if(opts && opts.height)
	        	$target.height($target.data('options').height);
            if(opts && opts.width)
            {
	        	$target.width($target.data('options').width);
	        	return;
            }
            
            if ($.boxModel == true)
                $target.width(width - ($target.outerWidth() - $target.width()));
            else
                $target.width(width);  
        }
	}*/
});