var webrootPath = '';
var noLoginObj = null;
var headsStr = 'id,name';
var orderByStr = 'operateTime desc';
var whereStr = '';
var entityName = '';
var entityAction = null;
var zIndex = 1;
var backDiv = null;
function getRandom(n) {
	return Math.floor(Math.random() * n + 1)
}
function greStrInt(input, numLen) {
	var s = input + '';
	var len = s.length;
	if (len > numLen) {
		s = s.substring(0, numLen);
	} else {
		for ( var i = 0; i < numLen - len; i++) {
			s = "0" + s;
		}
	}
	return s;
}

// 时间显示
function showYTime(longtime) {
	var date = new Date(longtime);
	return date.getFullYear() + '-' + greStrInt(date.getMonth() + 1, 2) + '-' + greStrInt(date.getDate(), 2) + ' ' + greStrInt(date.getHours(), 2) + ':' + greStrInt(date.getMinutes(), 2);
}
// 时间date
function showDate(longtime) {
	var date = new Date(longtime);
	return date.getFullYear() + '-' + greStrInt(date.getMonth() + 1, 2) + '-' + greStrInt(date.getDate(), 2);
}
function showCoolTime(longtime) {
	var longNow = new Date().getTime();
	// var date = new Date(longtime);
	var cha = longNow - longtime;
	if (cha <= 1000 * 60) {
		return parseInt(cha / (1000)) + '秒前';
	} else if (cha <= 1000 * 60 * 60) {
		return parseInt(cha / (1000 * 60)) + '分前';
	} else if (cha <= 1000 * 60 * 60 * 24) {
		return parseInt(cha / (1000 * 60 * 60)) + '小时前';
	} else if (cha <= 1000 * 60 * 60 * 24 * 7) {
		return parseInt(cha / (1000 * 60 * 60 * 24)) + '天前';
	} else {
		return showYTime(longtime);
	}
}
function addArrayNew(list, obj) {
	var isNew = true;
	$.each(list, function(k, v) {
		if (v == obj) {
			isNew = false;
			return;
		}
	});
	if (isNew) {
		list.push(obj);
	}
}

function loginForm() {
}
$(document).ready( function() {
	$('body').append('<div id="loading" style="top:0;left:0;display:none;position: absolute;border:4px solid #df4918;background:#fdbeaa;padding:6px;width:140px;font-weight:bold;color:#df4918">处理中...</div>');
});
function sendAJAX(o) {
	var s = o.success;
	o.success = function(msg) {
		if (msg.status == -11) {
			noLoginObj = {
				func :s,
				thisObj :this,
				param :msg
			};
			alert("没有登录，请先登录再操作！");
			loginForm();
		} else {
			s.call(this, msg);
		}
	}
	o.error = function(msg) {
		alert('网络繁忙，' + msg);
	}
	o.complete = function(msg) {
		$('#loading').fadeOut('slow');
	}
	$('#loading').css( {
		'zIndex' :++zIndex,
		'left' :$(window).width() / 2,
		'top' :20 + $(window).scrollTop()
	}).show();
	$.ajax(o);
}
function showListContent(msg) {
	var str = headStr();
	if (msg.pageData != null) {
		$.each(msg.pageData.pageList, function(k, v) {
			str += '<tr bgcolor="#' + (k % 2 == 0 ? 'dddddd' : 'efefef') + '">';
			var id = v[0], status = v[1];
			$.each(v, function(kk, vv) {
				str += showInfo(kk, vv, v);
			});
			str += '<td align="center" nowrap><a href="./' + entityName + 'Edit.jsp?id=' + id + '">浏览 / 修改</a></td>';
			str += '<td align="center"><img src="' + webrootPath + '/jsp/admin/images/' + (status == 1 ? 'yes' : 'no') + '.gif" width="12" height="12" border="0" title="' + status + '" onclick="changeStatus(this,' + id
					+ ')" style="cursor: pointer;"></td>';
			str += '<td align="center"><a href="javascript:delData(' + id + ')">删除</a></td>';
			str += '</tr>';

		});
	}
	$('#listTable').html(str);
}

function showPageDiv(msg, pageDiv, pageAction) {
	if (msg.pageData == null)
		return;
	pageDiv.html('');
	var pageNo = msg.pageData.pageNo;
	var totalPage = msg.pageData.totalPage;
	var totalNum = msg.pageData.totalNum;
	if (totalPage >= 1) {
		var pageStr = '';
		pageStr += '共<span class="num">' + msg.pageData.totalNum + '</span>条';
		if (totalNum > 0) {
			if (pageNo > 1) {
				pageStr += '<a href="javascript:' + pageAction + '(' + (pageNo - 1) + ')"><img src="/images/arrow_left.gif" width="9" height="9" border="0"></a>';
			}
			var start = 0, end = 0;
			start = pageNo - 6;
			end = pageNo + 6;
			start = start < 1 ? 1 : start;
			end = end > totalPage ? totalPage : end;

			for ( var i = start; i <= end; i++) {
				if (i == pageNo) {
					pageStr += '&nbsp;' + i + '&nbsp;';
				} else {
					pageStr += '&nbsp;<a href="javascript:' + pageAction + '(' + (i) + ')">' + i + '</a>&nbsp;';
				}
			}

			if (pageNo < totalPage) {
				pageStr += '<a href="javascript:' + pageAction + '(' + (pageNo + 1) + ')"><img src="/images/arrow_right.gif" width="9" height="9" border="0"></a>';
			}
		}
		pageDiv.html(pageStr).show();
	}
}
function indexData(id, obj) {
	var v = $(obj).attr('value');
	if (v != '') {
		if (v.match(new RegExp(/^\d+$/)) == null)
			v = '';
	}
	if (v == '') {
		alert('格式不正确，必须是数字！');
		$(obj).css('background', '#FF7777').focus();
		return;
	}
	sendAJAX( {
		url :webrootPath + '/a/json_' + entityName + '_edit.html',
		data :'indexNo=' + v + '&submit=true&id=' + id,
		dataType :'json',
		type :'post',
		async :false,
		success : function(msg) {
			if (msg.status == 1) {
				getData();
			} else {
				alert('操作失败:' + msg.msg);
			}
		}
	});
}
function getData(pageNo) {
	pageNo = pageNo == null ? 1 : pageNo;
	entityAction = entityAction == null ? "query" : entityAction;
	var paramStr = whereStr + 'pageSize=50&orderByStr=' + encodeURIComponent(orderByStr) + '&orderByStr=' + encodeURIComponent('operateTime desc') + '&headsStr=' + headsStr + '&pageNo=' + pageNo;
	sendAJAX( {
		url :webrootPath + '/a/json_' + entityName + '_' + entityAction + '.html',
		data :paramStr,
		dataType :'json',
		success : function(msg) {
			showListContent(msg);
			showPageDiv(msg, $('#pageDiv'), 'goPage');
		}
	});
}

function delData(id) {
	if (confirm('确认删除该条数据')) {
		sendAJAX( {
			url :webrootPath + '/a/json_' + entityName + '_del.html',
			data :'id=' + id,
			dataType :'json',
			success : function(msg) {
				if (msg.status == 1) {
					getData();
				} else {
					alert('操作失败:' + msg.msg);
				}
			}
		});
	}
}
function changeStatus(obj, id, fieldName) {
	fieldName = fieldName == null ? 'status' : fieldName;
	var status = $(obj).attr('title');
	var v = status == 1 ? '0' : '1';
	sendAJAX( {
		url :webrootPath + '/a/json_' + entityName + '_edit.html',
		data :'submit=true&id=' + id + '&' + fieldName + '=' + v,
		dataType :'json',
		success : function(msg) {
			if (msg.status == 1) {
				$(obj).attr('title', v).attr('src', webrootPath + '/jsp/admin/images/' + (v == 1 ? 'yes' : 'no') + '.gif');
				$(obj).attr('title', status == 1 ? '0' : '1');
			} else {
				alert(msg.msg);
			}
		}
	});
}
function goPage(pageNo) {
	getData(pageNo);
}
function exportExcel() {
	$('#exportLink').hide();
	$('#exportPath').html('导出处理中...');
	sendAJAX( {
		url :webrootPath + '/a/json_' + entityName + '_exportExcel.html',
		data :'submit=true',
		dataType :'json',
		success : function(msg) {
			$('#exportPath').html('<a href="' + webrootPath + '/' + msg['excelPath'] + '">点击下载</a>');
		}
	});
}
Object.extend = function(destination, source) {
	for ( var property in source)
		destination[property] = source[property];
	return destination;
};
Object.extend(String.prototype, {
	inc : function(str, sSplit) {
		sSplit = sSplit || ","
		return (sSplit + this + sSplit).indexOf(sSplit + str + sSplit) > -1 ? true : false;
	},
	// 用于计算显示所占的像素
	lenB : function() {
		return this.replace(/[^\x00-\xff]/g, '**').length;
	},
	// 用于计算存储所占的位数
	savelenB : function() {
		return this.replace(/[^\x00-\xff]/g, hanzi).length;
	},
	toEntityforStr : function() {
		return this.substring(0, 1).toUpperCase() + this.substring(1);
	},
	toInstanceforStr : function() {
		return this.substring(0, 1).toLowerCase() + this.substring(1);
	},
	textToHtml : function() {
		return this.replace(/\&/g, "&amp;").replace(/\</g, "&lt;").replace(/\>/g, "&gt;").replace(/(|\r)\n/g, "<br>").replace(/  /g, "&nbsp;&nbsp;")
	},
	startsWith : function(pattern) {
		return this.indexOf(pattern) === 0;
	},
	endsWith : function(pattern) {
		var d = this.length - pattern.length;
		return d >= 0 && this.lastIndexOf(pattern) === d;
	},
	replaceAll : function(AFindText, ARepText) {
		raRegExp = new RegExp(AFindText, "g");
		return this.replace(raRegExp, ARepText)
	}

});
// 四舍五入函数
function forDight(Dight, How) {
	var Dight = Math.round(Dight * Math.pow(10, How)) / Math.pow(10, How);
	return Dight;
}
function strLen(str, len) {
	if (str.lenB() > len && len > 3) {
		var s = '';
		for ( var i = 0; i < str.length; i++) {
			// alert(str.charAt(i));
			// alert(str.charCodeAt(i));
			len -= str.charCodeAt(i) > 256 ? 2 : 1;
			if (len < 3)
				break;
			s += str.charAt(i);
		}
		str = s + '...'
	}
	return str;
}
function getParamStr(str) {
	return str + '=' + encodeURIComponent($('#' + str).attr('value'));
}
function changeCode(img) {
	$('#' + img + 'Img').attr('src', webrootPath + '/jsp/code.jsp?checkCodeName=' + img + '&id=' + getRandom(1000));
}
function resetPassword(id) {
	if (confirm('是否确认重置该用户的密码！')) {
		sendAJAX( {
			url :webrootPath + '/a/json_user_resetPassword.html',
			data :'id=' + id,
			type :'post',
			dataType :'json',
			success : function(msg) {
				if (msg.status == 1) {
					alert('重置密码成功，新密码为:' + msg.pass + '，请牢记！');

				} else {
					alert('操作失败!');
				}
			}
		});
	}
}
/* ----------------------- page fun */
function setInputMsg(obj, inputMsg) {
	obj.css('color', '#aaa').attr('value', inputMsg).bind('blur', function(e) {
		if ($(e.target).attr('value') == '') {
			$(e.target).attr('value', inputMsg).css('color', '#aaa');
		}
	}).bind('focus', function(e) {
		if ($(e.target).attr('value') == inputMsg) {
			$(e.target).attr('value', '').css('color', '#000');
		}
	});
}
/*------------------------- login */
function doLoginOut() {
	if (confirm('是否确认注销登录？')) {
		window.location.href = webrootPath + "/a/j_user_loginOut.html";
	}
}
function loginSeccuss() {
}
var loginUserObj = null;
function showUserInfo() {
	if (loginUserObj == null) {
		sendAJAX( {
			url :webrootPath + '/a/json_user_getLoginUserInfo.html',
			dataType :'json',
			async :false,
			success : function(msg) {
				loginUserObj = msg['user_login'];
			}
		});
	}
	if (loginUserObj != null) {
		$('#loginUserName').html(loginUserObj.userName);
		$('#weclomeSpan').show();
		$('#loginLinkHead').hide();
	}
	loginSeccuss();
}

// -------cookies-----------------------
function setCookie(name, value) { // 设置名称为name,值为value的Cookie
	var Days = 60;
	var exp = new Date();
	exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
	document.cookie = name + "=" + value + ";expires=" + exp.toGMTString() + ";path=/";
}
function deleteCookie(name) { // 删除名称为name的Cookie
	var exp = new Date();
	exp.setTime(exp.getTime() - 1);
	var cval = getCookie(name);
	if (cval != null)
		document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString() + ";path=/";
}
function getCookieVal(offset) { // 取得项名称为offset的cookie值
	var endstr = document.cookie.indexOf(";", offset);
	if (endstr == -1)
		endstr = document.cookie.length;
	return decodeURIComponent(document.cookie.substring(offset, endstr));
}
function getCookie(name) { // 取得名称为name的cookie值
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	while (i < clen) {
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg)
			return getCookieVal(j).replace(/"/g, '');
		i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0)
			break;
	}
	return null;
}

/**
 * 图片预加载
 * 
 * @param url
 * @param callback
 * @return
 */
function loadImg(url, callback) {
	var img = new Image();
	img.src = url;
	if (img.complete) {
		if (callback)
			callback.call(img);
		return;
	}
	img.onload = function() {
		if (callback)
			callback.call(img);
	};
}
/*------------------page */
/**
 * 用于处理页面的跳转。
 * 
 * @param paramNames
 *            需要对当前url中要替换的参数名数组。
 * @param paramValues
 *            需要对当前url中要替换的参数值数组。
 * @param cUrl,当前url，如果当前url与cUrl相等，则执行参数替换，如果不等，则将待替换的参数直接跟上url跳转。
 * @return
 */
function goUrl(paramNames, paramValues, cUrl) {
	var oparams = 0;
	var str = 'http://' + window.location.hostname + (window.location.port != '' ? (':' + window.location.port) : '');
	var pathname = window.location.pathname;
	var searchStr = '';
	if (pathname == cUrl || cUrl == null) {
		str += pathname;
		var l_search = window.location.search;
		if (l_search != '') {
			var params = l_search.substring(1).split('&');
			for ( var ji = 0; ji < params.length; ji++) {
				var pv = params[ji].split('=');
				var isExist = false;
				for ( var ji_1 = 0; ji_1 < paramNames.length; ji_1++) {
					if (pv[0] == paramNames[ji_1]) {
						isExist = true;
						break;
					}
				}
				if (!isExist) {
					searchStr += (ji == 0 ? '?' : '&') + params[ji];
					oparams++;
				}
			}
		}
	} else {
		str += cUrl;
	}

	if (paramNames.length > 0) {
		if (oparams == 0) {
			str += '?'
		} else {
			str += searchStr;
		}
		for ( var ji_1 = 0; ji_1 < paramNames.length; ji_1++) {
			str += (oparams == 0 ? '' : '&') + paramNames[ji_1] + '=' + paramValues[ji_1];
			oparams++;
		}
	}
	return str;
}

function goToPage(paramNames, paramValues, cUrl) {
	window.location.href = goUrl(paramNames, paramValues, cUrl);
}

var windowDivCon = null, backDivCon = null;
function showBackDivCon() {
	if (backDivCon == null) {
		backDivCon = $('<div class="backDivCon"></div>');
		$('body').append(backDivCon);
	}
	$('body').css('overflow', 'hidden');
	backDivCon.css( {
		width :$(window).width(),
		height :$(window).height(),
		top :$(window).scrollTop(),
		left :$(window).scrollLeft(),
		opacity :0.85,
		zIndex :++zIndex
	}).show();
}
function showWindow(width, height, title, content) {
	if (windowDivCon == null) {
		windowDivCon = $('<div class="windowDivCon"></div>');
		$('body').append(windowDivCon);
	}

	windowDivCon.html('');
	showBackDivCon();
	windowDivCon.css( {
		width :width,
		height :height,
		zIndex :++zIndex
	});

	var str = '<div class="windowTitle"><div style="float:left;font-weight:bold;font-size:14px">' + title + '</div><div style="float:right;"><a href="javascript:closeWindow()"><img src="' + webrootPath
			+ '/images/closewin.gif" style="border: 1px solid #ccc" /></a></div><div class="clearDiv"></div></div>';
	str += '<div class="windowContent">';
	str += content;
	str += '</div>';
	var left = $(window).scrollLeft() + ($(window).width() - windowDivCon.width()) / 2
	var top = $(window).scrollTop() + ($(window).height() - windowDivCon.height()) / 2
	windowDivCon.css( {
		left :left,
		top :top
	}).html(str).show();
}

function closeWindow() {
	if (windowDivCon != null)
		windowDivCon.hide();
	backDivCon.hide();
	$('body').css('overflow', 'auto');
}

