/** 全局变量 */
var trueArr = [1,'1',true,'true','on'];
var falseArr = [0,'0',false,'false','off'];

String.prototype.lTrim = function(s) {
    s = (s ? s : "\\s");                            //没有传入参数的，默认去空格
    s = ("(" + s + ")");
    var reg_lTrim = new RegExp("^" + s + "*", "g");     //拼正则
    return this.replace(reg_lTrim, "");
};

String.prototype.rTrim = function(s) {
    s = (s ? s : "\\s");
    s = ("(" + s + ")");
    var reg_rTrim = new RegExp(s + "*$", "g");
    return this.replace(reg_rTrim, "");
};

String.prototype.trim = function(s) {
    s = (s ? s : "\\s");
    s = ("(" + s + ")");
    var reg_trim = new RegExp("(^" + s + "*)|(" + s + "*$)", "g");
    return this.replace(reg_trim, "");
};

String.prototype.replaceAll = function(s1,s2){   
	return this.replace(new RegExp(s1,"gm"),s2);   
};

function selectSpecOption($select, text)
{
	$.each($select.children('option'), function()
	{
		if (this.text == text)
		{
			this.selected = true;
			return false;
		}
	});
}

var ObjUtils = new Object();
/**比较两个对象内容是否相等，不包含原型上的属性比较*/
ObjUtils.equals = function(obj1, obj2)
{
	if (obj1 && obj2 && obj1.constructor && obj2.constructor)
	{
		if((typeof obj1 === "object") && (typeof obj2 === "object"))
		{
			if(obj1.constructor == Array && obj2.constructor == Array)		//数组比较
				return compArr(obj1, obj2);
			
			if(getJsonObjSize(obj1) != getJsonObjSize(obj2))				//对象比较
				return false;
			
			for(var propName in obj1)
			{
				if(! (obj1.hasOwnProperty(propName) && obj2.hasOwnProperty(propName)))
					return false;
				
				if(! ObjUtils.equals(obj1[propName], obj2[propName]))
					return false;
			}
		}
		else																//纯属性比较
			return obj1 == obj2;
	}
	return obj1 == obj2;
	
	function compArr(array1, array2)
	{
		if (array1.length == array2.length)
		{
			for (var i = 0; i < array1.length; i++)
			{
				if(typeof array1[i] != typeof array2[i])
					return false;
				else if(array1[i].constructor == Array && array2[i].constructor == Array)		//数组比较
				{
					if(! compArr(array1[i], array2[i]))
						return false;
				}
				else if(typeof array1[i] === 'object' && typeof array2[i] === 'object')
				{
					var ggg = ObjUtils.equals(array1[i], array2[i]);
					if (!ggg)
						return false;
				}
				else
				{
					if(array1[i] != array2[i])
						return false;
				}
			}
			return true;
		}
		else
			return false;
	}
};

/**
 * 根据元素的ID，对元素文本尾部居中
 * 
 * @param elementName
 * @param value
 */
function focusLastById(elementId,value){
	var packNumberElement = document.getElementById(elementId); 
	packNumberElement.style.visibility = 'visible'; 
	packNumberElement.value = value; 
	var txt =packNumberElement.createTextRange(); 
	txt.moveStart('character',packNumberElement.value.length); 
	txt.collapse(true); 
	txt.select(); 
}

/**
 * 根据元素的名称，对元素文本尾部居中
 * @param elementName
 * @param value
 */
function focusLastByName(elementName,value){
	var packNumberElement = document.getElementsByName(elementName)[0]; 
	packNumberElement.style.visibility = 'visible'; 
	packNumberElement.value = value; 
	var txt =packNumberElement.createTextRange(); 
	txt.moveStart('character',packNumberElement.value.length); 
	txt.collapse(true); 
	txt.select(); 
}

/**
 * 四舍五入到指定小数点位数
 * @param number
 * @param dotScale
 * @returns
 */
Math.roundByDotScale = function(number, dotScale)
{
	number = Math.round(number * Math.pow(10, dotScale)) / Math.pow(10, dotScale); 
	return number; 
};

/**
 * 获取汉字“是/否”
 * @param flag 标识：支持1|0、true|false、on|off
 */
function getYesOrNo(flag)
{
	if($.inArray(flag, trueArr) > 0)		//true
		return '是';
	else if($.inArray(flag, falseArr) > 0)	//false
		return '否';
	else
		return '-';
}

/**
 * 获取指定jsonObj的元素长度
 * @param {} jsonObj
 */
function getJsonObjSize(jsonObj)
{
	var count = 0;
	for(var obj in jsonObj)
	{
		if(jsonObj.hasOwnProperty(obj))
			count ++;
	}
	return count;
}

/**
 * 拼接url和请求参数
 * @param {} url
 * @param {请求参数-json格式} paramJson
 */
function SplicingUrlAndParams(url, paramJson)
{
	if(paramJson != null && getJsonObjSize(paramJson) > 0)
	{
		var flag = false;
		$.each(paramJson, function(key, value)
		{
			var paramStr = key + '=' + encodeURIComponent(value);
			if(flag == true)
				url += '&' + paramStr;
			else
			{
				url += '?' + paramStr;
				flag = true;
			}
		});
	}
	return url;
}

function UIutil(){}
/**
 * 生成easyui窗口对象
 * 已经在pageUtils中重新实现
 * @param id
 * @param title
 */
UIutil.buildEasyuiWindowElement = function(id, title, width)
{
	if(id == null || id == '')
		id = 'detailInfoWindow';
	
	var escId = id.replaceAll('\\.', '\\.');
	var win = $('div#' + escId);
	
	if(win.length == 0)
	{
		var htmlStr = '<div id="' + id + '" class="easyui-window" ';
		htmlStr += 'modal="true" closed="true" closable="true" ' +
				'collapsible="false" minimizable="false" maximizable="false" resizable="false" cache="false"';
		var wid = 750;
		if(width != null && width != '')
			wid = width;
		htmlStr += 'style="width: ' + wid + 'px;" ';
		
		if(title != null && title != '')
			htmlStr += ' title="' + title + '"';
			
		htmlStr += '></div>';
		
		//window.top.$('body').append(htmlStr);
		$('body').append(htmlStr);
		win = $('div#' + escId);
		win.window
		({
			onLoad : function()		//窗口居中
			{
				$(this).window('center');
			},
			onOpen : function()
			{
				$(this).window('center');
			}/*,
			onClose : function()
			{
				$(this).empty();
			}*/
		});
	}
	return win;
}

/**
 * 显示response返回的json对象中的信息对话框
 * @param response
 */
UIutil.alertRespJsonMsg = function(respJson, sucfn, failFn)
{
	if(respJson.sessionTimeout)		//会话过期已在ajax的complate事件中处理过，此处需要过滤掉。
		return;
	
	var msg = respJson.message, icon = 'info', title = '提示', tempFn = $.noop;
	if(respJson.flag != null && ! respJson.flag)		//出现错误
	{
		if(! msg)
			msg = '系统内部错误，请联系系统管理员。';
		icon = 'error';
		title = '错误';
		tempFn = function()
		{
			if(failFn instanceof Function)
				failFn();
		};
	}
	else
	{
		tempFn = function()
		{
			if(sucfn instanceof Function)
				sucfn(respJson);
		};
	}
	
	if(! msg)
		tempFn();
	else
	{
		if(! respJson.popupType || respJson.popupType == 'alert')
			$.messager.alert(title, msg, icon, tempFn);
		else if(respJson.popupType == 'confirm')		//确认框
		{
			$.messager.confirm(title, msg, function(r)
			{
				if(r)
					tempFn();
			});
		}
	}
}

/**
 * 显示进度条
 */
UIutil.showProgressBar = function(title, msg)
{
	if(/*window.top.*/$('div.messager-progress').length == 0)
	/*window.top.*/$.messager.progress({title: title ? title : '请稍后', msg: msg ? msg : '加载数据中...'});
};

/**
 * 关闭进度条
 */
UIutil.closeProgressBar = function()
{
	if(/*window.top.*/$('div.messager-progress').length > 0)
	/*window.top.*/$.messager.progress('close');
};

/**
 * 在光标处插入指定内容
 */
function insertStrToCursor(inputEl, str)
{
	var length = inputEl.value.length;
	inputEl.focus();
	if(typeof document.selection != undefined)
		document.selection.createRange().text = str;
	else
		inputEl.value = inputEl.value.substr(0, inputEl.selectionStart) + str + inputEl.value.substring(inputEl.selectionStart, length);
}

function setEditBtnStatus($grid, $btn)
{
	$btn.linkbutton();
	if($grid.datagrid('getSelections').length != 1)
		$btn.linkbutton('disable');
	else
		$btn.linkbutton('enable');
}

function HtmlUtil(){}
/**
 * 生成复选框HtmlStr
 * @param {checkbox的属性对象} propJson
 * @param {是否只读} readonly
 */
HtmlUtil.buildCheckboxHtmlByPropJson = function(propJson, readonly)
{
	var str = '<input type="checkbox" ';
	for(var obj in propJson)
		str += obj + '="' + propJson[obj] + '"';
	if(readonly == true)
		str += ' onclick="return  false;"';
	str += '>';
	return str;
};


$.cookie = function(name, value, options) {
	if (typeof value != 'undefined') {
		options = options || {};
		if (value === null) {
			value = '';
			options = $.extend({}, options);
			options.expires = -1;
		}
		var expires = '';
		if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
			var date;
			if (typeof options.expires == 'number') {
				date = new Date();
				date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
			} else {
				date = options.expires;
			}
			expires = '; expires=' + date.toUTCString();
		}
		var path = options.path ? '; path=' + (options.path) : '';
		var domain = options.domain ? '; domain=' + (options.domain) : '';
		var secure = options.secure ? '; secure' : '';
		document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
		} else {
			var cookieValue = null;
			if (document.cookie && document.cookie != '') {
			var cookies = document.cookie.split(';');
			for (var i = 0; i < cookies.length; i++) {
				var cookie = jQuery.trim(cookies[i]);
				if (cookie.substring(0, name.length + 1) == (name + '=')) {
					cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
					break;
				}
			}
		}
		return cookieValue;
	}
};

function EasyuiUtil(){}
EasyuiUtil.DatagridUtil = function(){};
/** 获取datagrid的指定单元格的编辑控件焦点 */
EasyuiUtil.DatagridUtil.focusOnEditCell = function($datagrid, index, fieldName)
{
	$datagrid.datagrid('beginEdit', index);
	var $ed = $datagrid.datagrid('getEditor' , {index : index , field : fieldName});
	try
	{
		if($($ed.target).is(':input'))
		{
			$ed.target.focus();
			$ed.target.select();
		}
		else
		{
			var inputs = $($ed.target).find(':input');
			inputs[0].focus();
			inputs[0].select();
		}
	}
	catch(e){}
};

/**
 * 上移选择行
 * @param {} $grid
 * @param {} messageOfEmptyRow
 */
EasyuiUtil.DatagridUtil.upSelectedRow = function($grid, messageOfEmptyRow)
{
	var idField = $grid.datagrid('options').idField;
	var selRows = $grid.datagrid('getSelections');
	if(selRows.length == 0)
	{
		$.messager.alert('提示', messageOfEmptyRow ? messageOfEmptyRow : '请选择要上移的行。', 'info');
		return;
	}
	selRows.sort(function(r1, r2){return $grid.datagrid('getRowIndex', r1[idField]) - $grid.datagrid('getRowIndex', r2[idField])});
	var rows = $grid.datagrid('getRows');
	
	/* 计算可以上移的起始下标 */
	var tmpIdx = $grid.datagrid('getRowIndex', rows[0]);
	var startIdx = 0;
	for(; startIdx < selRows.length; startIdx++)
	{
		var idx = $grid.datagrid('getRowIndex', selRows[startIdx]);
		if(idx != tmpIdx++)
			break;
	}
	
	/* 依次上移 */
	var selIds = [];
	var topIdx;
	while(selRows.length > startIdx)
	{
		var tmpRow = selRows[startIdx];
		selIds.push(tmpRow[idField]);
		var rowIdx = $grid.datagrid('getRowIndex', tmpRow[idField]);
		if(rowIdx - 1 == topIdx)
		{
			selRows.splice(startIdx, 1);		//移除当前行
			topIdx++;
			continue;
		}
		$grid.datagrid('deleteRow', rowIdx);
		$grid.datagrid('insertRow', {index: rowIdx - 1, row: tmpRow});
		if($grid.datagrid('getRowIndex', tmpRow[idField]) == rowIdx)	//分组view中的第一行上移不会改变其索引号
			topIdx = rowIdx;
	}
	
	if(selIds.length > 0)
	{
		for(var i in selIds)
			$grid.datagrid('selectRow', $grid.datagrid('getRowIndex', selIds[i]));
	}
};

/**
 * 下移选择行
 * @param {} $grid
 * @param {} messageOfEmptyRow
 */
EasyuiUtil.DatagridUtil.downSelectedRow = function($grid, messageOfEmptyRow)
{
	var idField = $grid.datagrid('options').idField;
	var selRows = $grid.datagrid('getSelections');
	if(selRows.length == 0)
	{
		$.messager.alert('提示', messageOfEmptyRow ? messageOfEmptyRow : '请选择要下移的行。', 'info');
		return;
	}
	selRows.sort(function(r1, r2){return $grid.datagrid('getRowIndex', r1[idField]) - $grid.datagrid('getRowIndex', r2[idField])});
	var rows = $grid.datagrid('getRows');
	
	/* 计算可以下移的末尾下标 */
	var tmpIdx = $grid.datagrid('getRowIndex', rows[rows.length - 1]);
	var startIdx = selRows.length -1;
	for(; startIdx >= 0; startIdx--)
	{
		var idx = $grid.datagrid('getRowIndex', selRows[startIdx]);
		if(idx != tmpIdx--)
			break;
	}
	
	/* 依次下移 */
	var selIds = [];
	var bottomIdx;
	for(;startIdx >= 0; startIdx--)
	{
		var tmpRow = selRows[startIdx];
		selIds.push(tmpRow[idField]);
		var rowIdx = $grid.datagrid('getRowIndex', tmpRow[idField]);
		if(rowIdx + 1 == bottomIdx)
		{
			selRows.splice(startIdx, 1);		//移除当前行
			bottomIdx--;
			continue;
		}
		$grid.datagrid('deleteRow', rowIdx);
		$grid.datagrid('insertRow', {index: rowIdx + 1, row: tmpRow});
		if($grid.datagrid('getRowIndex', tmpRow[idField]) == rowIdx)	//分组view中的最后一行下移不会改变其索引号
			bottomIdx = rowIdx;
		
	}
	
	if(selIds.length > 0)
	{
		for(var i in selIds)
			$grid.datagrid('selectRow', $grid.datagrid('getRowIndex', selIds[i]));
	}
};

function DateUtil(){}
DateUtil.toString = function(val)
{
	if(typeof val == 'number')
	{
		var date = new Date();
		date.setTime(val);
		var m = (date.getMonth() + 1);
		var d = date.getDate();
		return date.getFullYear() + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d);
	}
};

DateUtil.formatDate = function(dateStr)
{
	var tempDateRegexp = null;
	var dateStrArr = [];
	var year,month,day;
	if(dateStr.length == 10)		//格式为YYYY-mm-dd或YYYY.mm.dd或YYYY/mm/dd
	{
		tempDateRegexp = new RegExp("^\\d{4}([-|\\.|/]\\d{2}){2}$");		//YYYY-mm-dd或YYYY.mm.dd或YYYY/mm/dd正则
		if(!tempDateRegexp.test(dateStr))
			return null;
		
		if(dateStr.indexOf("-") > 0)		//YYYY-mm-dd
			dateStrArr = dateStr.split("-");
		else if(dateStr.indexOf(".") > 0)	//YYYY.mm.dd
			dateStrArr = dateStr.split(".");
		else if(dateStr.indexOf("/") >0 )	//YYYY/mm/dd
			dateStrArr = dateStr.split("/");
	}
	else if(dateStr.length == 8)	//格式为YYYYmmdd或YY-mm-dd或YY.mm.dd或YY/mm/dd
	{
		tempDateRegexp = new RegExp("^\\d{8}$");		//YYYYmmdd正则
		if(tempDateRegexp.test(dateStr))		//YYYYmmdd
		{
			dateStrArr.push(dateStr.substring(0,4));
			dateStrArr.push(dateStr.substring(4,6));
			dateStrArr.push(dateStr.substring(6,8));
		}
		else
		{
			tempDateRegexp = new RegExp("^\\d{2}([-|\\.|/]\\d{2}){2}$");		//YY-mm-dd或YY.mm.dd或YY/mm/dd正则
			if(tempDateRegexp.test(dateStr))		//YYYYmmdd
			{
				if(dateStr.indexOf("-") > 0)		//YYYY-mm-dd
					dateStrArr = dateStr.split("-");
				else if(dateStr.indexOf(".") > 0)	//YYYY.mm.dd
					dateStrArr = dateStr.split(".");
				else if(dateStr.indexOf("/") >0 )	//YYYY/mm/dd
					dateStrArr = dateStr.split("/");
			}
			else
				return null;
		}
	}
	else if(dateStr.length == 6)		//格式YYmmdd
	{
		tempDateRegexp = new RegExp("^\\d{6}$");		//YYYYmmdd正则
		if(!tempDateRegexp.test(dateStr))
			return null;
		
		dateStrArr.push("20" + dateStr.substring(0,2));
		dateStrArr.push(dateStr.substring(2,4));
		dateStrArr.push(dateStr.substring(4,6));
	}
	else
		return null;
	
	if(dateStrArr.length != 3)
		return null;
	
	year = parseFloat(dateStrArr[0]);
	month = parseFloat(dateStrArr[1]) - 1;
	day = parseFloat(dateStrArr[2]);
	if(!checkValidDateValue(month, day))
		return null;
	return dateStrArr[0] + "-" + dateStrArr[1] + "-" + dateStrArr[2];
};

DateUtil.formatDateTime = function(datetimeStr)
{
	var dateStr,timeStr;
	if(datetimeStr.indexOf(" ") == -1)			//只有日期
	{
		var formatDateValue = formatDate(datetimeStr);	
		if(formatDateValue != null)
			return formatDateValue+" 00:00:00";
		else
			return null;
	}
		
	var strArr = datetimeStr.split(" ");
	if(strArr.length != 2)
		return null;
	
	dateStr = strArr[0];
	timeStr = strArr[1];
	
	var formatDateValue = formatDate(dateStr);
	if(formatDateValue == null)
		return null;
	
	var formatTimeValue = formatTime(timeStr);
	if(formatTimeValue == null)
		return null;
	
	return formatDateValue+" "+formatTimeValue;
};

DateUtil.formatTime = function(timeStr)
{
	var tempTimeRegexp = null;
	var timeStrArr = [];
	var hour,minute,second;
	
	if(timeStr.length > 8)
		timeStr = timeStr.substring(0, 8);
	
	if(timeStr.length == 8)			//格式为hh:mm:ss或hh.mm.ss
	{
		tempTimeRegexp = new RegExp("^\\d{2}([:|\\.]\\d{2}){2}$");		//hh:mm:ss或hh.mm.ss正则
		if(!tempTimeRegexp.test(timeStr))
			return null;
		
		if(timeStr.indexOf(":") > 0)		//hh:mm:ss
			timeStrArr = timeStr.split(":");
		else if(timeStr.indexOf(".") > 0)	//hh.mm.ss
			timeStrArr = timeStr.split(".");
	}
	else if(timeStr.length == 6)		//格式为hhmmss
	{
		tempTimeRegexp = new RegExp("^\\d{6}$");		//hhmmss正则
		if(!tempTimeRegexp.test(timeStr))
			return null;
		
		timeStrArr.push(timeStr.substring(0,2));
		timeStrArr.push(timeStr.substring(2,4));
		timeStrArr.push(timeStr.substring(4,6));
	}
	else if(timeStr.length == 5)		//格式为hh:mm或hh.mm
	{
		tempTimeRegexp = new RegExp("^\\d{2}[:|\\.]\\d{2}$");		//hh:mm或hh.mm正则
		if(!tempTimeRegexp.test(timeStr))
		return null;
		
		if(timeStr.indexOf(":") > 0)		//hh:mm:ss
			timeStrArr = timeStr.split(":");
		else if(timeStr.indexOf(".") > 0)	//hh.mm.ss
			timeStrArr = timeStr.split(".");
		
		timeStrArr.push("00");
	}
	else if(timeStr.length == 4)		//格式为hhmm
	{
		tempTimeRegexp = new RegExp("^\\d{4}$");		//hhmm正则
		if(!tempTimeRegexp.test(timeStr))
			return null;
		
		timeStrArr.push(timeStr.substring(0,2));
		timeStrArr.push(timeStr.substring(2,4));
		timeStrArr.push("00");
	}
	
	if(timeStrArr.length != 3)
		return null;
	
	hour = parseFloat(timeStrArr[0]);
	minute = parseFloat(timeStrArr[1]);
	second = parseFloat(timeStrArr[2]);
	if(!checkValidTimeValue(hour, minute, second))
		return null;
	return timeStrArr[0] + ":" + timeStrArr[1] + ":" + timeStrArr[2];
};