/* 正则验证表达式 */
var DECIMAL_EL_REGEXP = new RegExp("^decimal\\(\\d+\\)(?:\\{(?:(?:(?:-?\\d+)?,-?\\d+)|(?:-?\\d+,(?:-?\\d+)?))\\})?$");
var DECIMAL_EL_LONG_REGEXP = new RegExp("^decimal\\(\\d+\\)\\{(?:(?:(?:-?\\d+)?,-?\\d+)|(?:-?\\d+,(?:-?\\d+)?))\\}$");
var DECIMAL_EL_MAX_REGEXP = new RegExp("^decimal\\(\\d+\\)\\{,-?\\d+\\}$");
var DECIMAL_EL_MIN_REGEXP = new RegExp("^decimal\\(\\d+\\)\\{-?\\d+,\\}$");
var DECIMAL_EL_SHORT_REGEXP = new RegExp("^decimal\\(\\d+\\)$");
var URL_REGEXP = new RegExp("^(https?|ftp):\\/\\/(((([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&'\\(\\)\\*\\+,;=]|:)*@)?(((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]))|((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|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7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$");
var DATE_ISO_REGEXP = new RegExp("^\\d{4}(-\\d{2}){2}$");
var DATETIME_ISO_REGEXP = new RegExp("^\\d{4}(-\\d{2}){2} (\\d{2}:){1,2}\\d{2}$");
var TIME_ISO_REGEXP = new RegExp("^(\\d{2}:){1,2}\\d{2}$");

/** 31天的月份（0=1月） */
var bigMonthMap={0:0,2:2,4:4,6:6,7:7,9:9,11:11};

/**
 * 验证form中所有元素
 * @param $form jquery对象：表单
 */
function validateForm($form)
{
	var flag=true;
	$form.find(":input:not(:disabled)").each(function(i,item)
	{
		flag = validateFormItem($form, item);
			
		if(!flag)
			return false;
	});

	return flag;
}

/**
 * 初始化form的验证事件
 * @param $form {jquery form对象}
 * @param passedFn {验证通过后的回调函数，参数为jquery表单对象}
 */
function initFormValidateEvent($form, passedFn)
{
	$form.submit(function(e)
	{
		if(!validateForm($(this)))
			return false;
		
		if(passedFn == null);
			return true;
		
		passedFn($(this));
	});
	
	initFormItemValidateEvent($form);
}

/**
 * 初始化form表单元素的验证事件
 * @param $form jquery对象：表单
 */
function initFormItemValidateEvent($form)
{
	$form.find(":input:not(:disabled)").change(function()
	{
		validateFormItem($form, this);
	});
}
		
/**
 * 验证指定表单元素
 * @param item
 */
function validateFormItem($form, item)
{
	var flag = true;
	var tagName = $(item).get(0).tagName;
	var inputType = $(item).attr("type");
	var notNull = $(item).attr("notNull");
	
	if(notNull == "true" || notNull == true)		//非空
	{
		if(inputType == "radio" || inputType == "RADIO")
			flag = valiRadioNotNull($form, $(item));
		else
			flag = valiNotNull($(item));
	}
	if(!flag)
		return false;
	
	if(/*tagName != "TEXTAREA" && */inputType != "radio" && inputType != "select" && inputType != "checkbox")	//input标签
	{
		var dataType = $(item).attr("dataType");
		if(dataType != null)
		{
			if(dataType == "email")						//email
				flag = valiEmail($(item));
			
			if(!flag)
				return false;
			
			if(dataType == "url")						//url
				flag = valiUrl($(item));
			
			if(!flag)
				return false;
			
			if(dataType.indexOf("decimal") >= 0)		//数字
				flag = valiDecimal($(item));
			
			if(!flag)
				return false;
			
			if(dataType == "dateISO")					//标准日期
				flag = valiDateIso($(item));
				
			if(!flag)
				return false;
			
			if(dataType == "datetimeISO")				//标准日期-时间
				flag = valiDateTimeIso($(item));
				
			if(!flag)
				return false;
			
			if(dataType == "timeISO")					//标准时间
				flag = valiTimeIso($(item));
				
			if(!flag)
				return false;
		}
	}
	
	if($(item).attr("minLength") != null)		//最小长度验证
		flag = valiMinLength($(item));
	
	if(!flag)
		return false;
	
	if($(item).attr("maxLength") != null)		//最大长度验证
		flag = valiMaxLength($(item));
	
	if(!flag)
		return false;
	
	if($(item).attr('charScope') != null)		//字符范围验证
		flag = valiCharScope($(item));
	
	if(!flag)
		return false;
	
	if($(item).attr("customValidate") != null)	//正则验证
		flag = customValidate($(item));
	
	return flag;
}

/** 字符范围验证 */
function valiCharScope(item)
{
	var value = getRealValue(item);
	if(value == null || value == '')
		return true;
	
	var charScopeStr = item.attr("charScope");
	var tips = item.attr("tips");
	var title = item.attr("title");
	
	var charScopeArr = charScopeStr.split('');		//['a','A','z','0','@',' ']
	var regExp = '', msg = '';
	for(var i in charScopeArr)
	{
		var scopeChar = charScopeArr[i];
		if(scopeChar == 'a')		//小写英文
		{
			regExp += 'a-z';
			msg += msg == '' ? '小写英文' : '、小写英文';
		}
		else if(scopeChar == 'A')	//大写英文
		{
			regExp += 'A-Z';
			msg += msg == '' ? '大写英文' : '、大写英文';
		}
		else if(scopeChar == 'z')	//中文
		{
			regExp += '\\u4e00-\\u9fa5';
			msg += msg == '' ? '中文' : '、中文';
		}
		else if(scopeChar == '0')	//数字
		{
			regExp += '\\d';
			msg += msg == '' ? '数字' : '、数字';
		}
		else if(scopeChar == '@')	//特殊字符
		{
			regExp += '[^a-zA-Z\\d\\s\\u4e00-\\u9fa5]';
			msg += msg == '' ? '特殊字符' : '、特殊字符';
		}
		else if(scopeChar == ' ')	//空白字符
		{
			regExp += '\\s';
			msg += msg == '' ? '任意空白字符' : '、任意空白字符';
		}
	}
	
	if(regExp == '')			//无效的正则
	{
		$.messager.alert('提示', title + '的验证格式不正确，请联系系统管理员。', 'info', function()
		{
			item.focus();
			try
			{
				item.select();
			}
			catch (e){}
		});
		return false;
	}

	var charScopeRegExp = new RegExp('^[' + regExp + ']+$');
	
	if(!charScopeRegExp.test(value))
	{
		if(tips == null)
			tips = title + "的格式不正确，只允许" + msg + "。";
		$.messager.alert('提示',tips,'info', function()
		{
			item.focus();
			try
			{
				item.select();
			}
			catch (e){}
		});
		return false;
	}
	item.attr('value', value);
	return true;
}

/** 正则验证 */
function customValidate(item)
{
	var value = getRealValue(item);
	var title = item.attr("title");
	
	if(value == null || value == '')
		return true;
	var regExp = item.attr("customValidate");
	if(! regExp)
	{
		$.messager.alert('提示', title + '验证格式不正确，请联系系统管理员。', 'info', function()
		{
			return false;
		});
	}
	var tips = item.attr("tips");
	
	regExp.replace('\\', '\\\\');
	regExp = new RegExp(regExp);
	
	if(value != "" && !regExp.test(value))
	{
		if(tips == null)
			tips = title + "的格式不正确。";
		$.messager.alert('提示',tips,'info', function()
		{
			item.focus();
			try
			{
				item.select();
			}
			catch (e){}
		});
		return false;
	}
	item.attr('value', value);
	return true;
}

function valiRadioNotNull($form, item)					//radio非空
{
	var name=item.attr("name");
	var tips = item.attr("tips");
	var title=item.attr("title");
	if($form.find("input:radio[name='"+name+"']:checked").length<=0)
	{
		if(tips == null)
			tips = (title || name || item.attr('id')) + '不可为空。';
		$.messager.alert('提示', tips, 'info', function()
		{
			item.focus();
			try
			{
				item.select();
			}
			catch (e){}
		});
		return false;
	}
	return true;
}

/**非空验证*/
function valiNotNull(item)						//text非空
{
	var value = getRealValue(item);
	if(value == null)
		value = '';
	
	var title=item.attr("title");
	if(value == "")
	{
		$.messager.alert('提示', (title || item.attr('name') || item.attr('id')) + '不可为空。','info', function()
		{
			item.focus();
			try
			{
				item.select();
			}
			catch (e){}
		});
		return false;
	}
	item.attr('value', value);
	return true;
}

/** email验证 */
function valiEmail(item)
{
	var value = getRealValue(item);
	if(value == null || value == '')
		return true;
	
	var title=item.attr("title");
	var tips = item.attr("tips");
	if(value!=""&&!EMAIL_REGEXP.test(value))
	{
		if(tips == null)
			tips = title + 
		$.messager.alert('提示', tips, 'info', function()
		{
			item.focus();
			try
			{
				item.select();
			}
			catch (e){}
		});
		return false;
	}
	item.attr('value', value);
	return true;
}

/** url验证 */
function valiUrl(item)
{
	var value = getRealValue(item);
	if(value == null || value == '')
		return true;
	
	var title=item.attr("title");
	var tips = item.attr("tips");
	if(value!=""&&!URL_REGEXP.test(value))
	{
		if(tips == null)
			tips = title + '不是有效的URL。';
		$.messager.alert('提示', tips, 'info', function()
		{
			item.focus();
			try
			{
				item.select();
			}
			catch (e){}
		});
		return false;
	}
	item.attr('value', value);
	return true;
}

/** 数字验证（包括小数点） */
function valiDecimal(item)
{
	var value = getRealValue(item);
	if(value == null || value == '')
		return true;
	
	if(value == '')
		return true;
	
	var title=item.attr("title");
	var tips = item.attr("tips");
	var decimalElStr=item.attr("dataType");
	
	//解析dataType 如：“decimal(2){0,9999}”;
	if(!valiDecimalEl(decimalElStr,title))		//数字表达式格式不对
		return false;
	
	if(isNaN(value))		//不是数字
	{
		if(tips == null)
			tips = title + '不是有效的数字。';
		$.messager.alert('提示', tips, 'info',function()
		{
			item.focus();
			try{item.select();}
			catch (e){}
		});
		return false;
	}
	
	var valiMsg = null;
	var numValue = parseFloat(value);
	
	/* 取出最小和最大值，与value比较 */
	if(DECIMAL_EL_LONG_REGEXP.test(decimalElStr))		//如decimal(2){0,3000}
	{
		var minValue , maxValue;
		if(DECIMAL_EL_MAX_REGEXP.test(decimalElStr))	//如decimal(2){,3000}
			maxValue = parseFloat(decimalElStr.substring(decimalElStr.indexOf(",")+1, decimalElStr.indexOf("}")));		//最大值
		else if(DECIMAL_EL_MIN_REGEXP.test(decimalElStr))	//如decimal(2){3000,}
			minValue = parseFloat(decimalElStr.substring(decimalElStr.indexOf("{")+1, decimalElStr.indexOf(",")));		//最小值
		else											//如decimal(2){0,3000}
		{
			minValue = parseFloat(decimalElStr.substring(decimalElStr.indexOf("{")+1, decimalElStr.indexOf(",")));		//最小值
			maxValue = parseFloat(decimalElStr.substring(decimalElStr.indexOf(",")+1, decimalElStr.indexOf("}")));		//最大值
		}
		
		if(minValue != null && numValue < minValue)
			valiMsg = (tips == null) ? title+"不得小于"+minValue+"。" : tips;
		else if(maxValue != null && numValue > maxValue)
			valiMsg = (tips == null) ? title+"不得大于"+maxValue+"。" : tips;
	}
	
	if(valiMsg != null)
	{
		$.messager.alert('提示',valiMsg,'info',function()
		{
			item.focus();
			try{item.select();}
			catch (e){}
		});
		return false;
	}
	
	var dotScale = parseFloat(decimalElStr.substring(decimalElStr.indexOf("(")+1,decimalElStr.indexOf(")")));		//小数位数
	var formatValue = Math.roundByDotScale(numValue, dotScale).toString();
	if(formatValue.indexOf(".") == -1 && dotScale > 0)		//整数，需要精确到小数位
	{
		var decimalValue = "";
		while(decimalValue.length < dotScale)
			decimalValue += "0";
		
		formatValue += "."+decimalValue;
	}
	
	item.attr("value",formatValue);		//自动格式化
	return true;
}

/* decimalEl格式验证 */
function valiDecimalEl(decimalElStr,title)
{
	if(!DECIMAL_EL_REGEXP.test(decimalElStr))
	{
		$.messager.alert('提示',title+"的数字表达式格式错误，请联系系统管理员。",'info');
		return false;
	}
	return true;
}

/** 日期验证 */
function valiDateIso(item)
{
	var value = getRealValue(item);
	if(value == null || value == '')
		return true;
	
	var title=item.attr("title");
	var tips = item.attr("tips");
	var formatValue = DateUtil.formatDate(value);
	
	if(formatValue != null)
		item.attr("value",formatValue);
	
	if(formatValue == null || !DATE_ISO_REGEXP.test(formatValue))
	{
		if(tips == null)
			tips = title + '不是有效的日期，有效日期格式如下：<OL><LI>YYYY-MM-DD</LI><LI>YYYY.MM.DD</LI><LI>YYYY/MM/DD</LI><LI>YY-MM-DD</LI><LI>YY.MM.DD</LI><LI>YY/MM/DD</LI><LI>YYMMDD</LI><LI>YYYYMMDD</LI><OL>';
		$.messager.alert('提示', tips, 'info');
		return false;
	}
	return true;
}

/** 日期-时间验证 */
function valiDateTimeIso(item)
{
	var value = getRealValue(item);
	if(value == null || value == '')
		return true;

	var title=item.attr("title");
	var tips = item.attr("tips");
	var formatValue = DateUtil.formatDateTime(value);
	
	if(formatValue != null)
		item.attr("value",formatValue);
	
	if(formatValue == null || !DATETIME_ISO_REGEXP.test(formatValue))
	{
		if(tips == null)
			tips = title + "不是有效的日期-时间，有效的日期-时间格式如下："+
				"<OL><LI>日期和时间之间必须以\" \"(空格)分隔</LI>"+
				"<LI>日期："+
					"<LI>YYYY-MM-DD</LI><LI>YYYY.MM.DD</LI><LI>YYYY/MM/DD</LI><LI>YY-MM-DD</LI><LI>YY.MM.DD</LI><LI>YY/MM/DD</LI><LI>YYMMDD</LI><LI>YYYYMMDD</LI>"+
				"</LI>"+
				"<LI>时间："+
					"<LI>hh:mm:ss</LI><LI>hh.mm.ss</LI><LI>hhmmss</LI><LI>hh:mm</LI><LI>hh.mm</LI><LI>hhmm</LI>"+
				"</LI>"+
			"<OL>";
		$.messager.alert('提示', tips, 'info');
		return false;
	}
	return true;
}

/** 时间验证 */
function valiTimeIso(item)
{
	var value = getRealValue(item);
	if(value == null || value == '')
		return true;
	
	var title=item.attr("title");
	var tips = item.attr("tips");
	var formatValue = DateUtil.formatTime(value);

	if(formatValue != null)
		item.attr("value",formatValue);
	
	if(formatValue == null || !TIME_ISO_REGEXP.test(formatValue))
	{
		if(tips == null)
			tips = title + '不是有效的时间，有效的时间格式如下：<OL><LI>hh:mm:ss</LI><LI>hh.mm.ss</LI><LI>hhmmss</LI><LI>hh:mm</LI><LI>hh.mm</LI><LI>hhmm</LI><OL>';
		$.messager.alert('提示', tips, 'info');
		return false;
	}
	return true;
}

/** 最小长度验证 */
function valiMinLength(item)
{
	var value = getRealValue(item);
	if(value == null || value == '')
		return true;
	
	var title=item.attr("title");
	var tips = item.attr("tips");
	if(value.length < item.attr("minLength"))
	{
		if(tips == null)
			tips = title + "至少需要"+item.attr("minLength")+"位。";
		$.messager.alert('提示', tips, 'info', function()
		{
			item.focus();
			try{item.select();}
			catch (e){}
		});
		return false;
	}
	item.attr('value', value);
	return true;
}

/** 最大长度验证 */
function valiMaxLength(item)
{
	var value = getRealValue(item);
	if(value == null || value == '')
		return true;
		
	var title=item.attr("title");
	var tips = item.attr("tips");
	if(value.length > item.attr("maxLength"))
	{
		if(tips == null)
			tips = title + "不可超过"+item.attr("maxLength")+"位。"
		$.messager.alert('提示', tips, 'info', function()
		{
			item.focus();
			try{item.select();}
			catch (e){}
		});
		return false;
	}
	item.attr('value', value);
	return true;
}

function checkValidTimeValue(hour, minute, second)		//时分秒
{
	if(hour > 23)
		return false;
	if(minute > 59)
		return false;
	if(second > 59)
		return false;
	
	return true;
}

function checkValidDateValue(month, day)				//日期
{
	if(month > 11)
		return false;
	else if(month == 1)		//2月
	{
		if(month > 29)
			return false;
	}
	else
	{
		if(bigMonthMap[month] != null)		//31天
		{
			if(day >31)
				return false;
		}
		else							//30天
		{
			if(day >30)
				return false;
		}
	}
	return true;
}

function getRealValue($item)
{
	var value = $item.val();
	try
	{
		var val = $item.combobox('getValue');		//包括EASY UI 的 COMBOBOX
		if(val != '')
			value = val;
	}
	catch(e){}
	
	if(value == null)
		return value;
	return value.trim();
}