﻿/////////////////////////////////////////////////////////////////////
// 类型扩充
Date.prototype.format = function(format)
{
    var o = 
    {
        "M+" : this.getMonth()+1, //month
        "d+" : this.getDate(),    //day
        "h+" : this.getHours(),   //hour
        "m+" : this.getMinutes(), //minute
        "s+" : this.getSeconds(), //second
        "q+" : Math.floor((this.getMonth()+3)/3),  //quarter
        "S" : this.getMilliseconds() //millisecond
    }
    if(/(y+)/.test(format))
        format=format.replace(RegExp.$1,(this.getFullYear()+"").substr(4 - RegExp.$1.length));
    for(var k in o)
        if(new RegExp("("+ k +")").test(format))
            format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
    return format;
}
Date.prototype.getWeekDayCN = function()
{
	var d = this.getDay();
	var tmp = ['日','一','二','三','四','五','六'];
	return '星期' + tmp[d];
}
String.prototype.trim = function()
{
    return this.replace(/^\s+|\s+$/, '');
}
// StringBuilder
function StringBuilder(){ this.ary = new Array(); }
StringBuilder.prototype.append = function(value) { if (value) this.ary.push(value); }
StringBuilder.prototype.clear = function() { this.ary.length = 0; }
StringBuilder.prototype.toString = function() { return this.ary.join(""); }
/////////////////////////////////////////////////////////////////////
// 系统相关
function addLoadListener(fn)
{ 
    if(typeof window.addEventListener !='undefined')    window.addEventListener('load',fn,false); 
    else if(typeof document.addEventListener !='undefined')    document.addEventListener('load',fn,false); 
    else if(typeof window.attachEvent !='undefined')    window.attachEvent('onload',fn); 
    else{ 
        var oldfn=window.onload 
        if(typeof window.onload !='function')    window.onload=fn; 
        else    window.onload=function(){oldfn();fn();} 
    } 
}
function addClickListener(fn)
{
    if(typeof window.addEventListener !='undefined')    { window.addEventListener('click',fn,false); }
    else if(typeof document.addEventListener !='undefined')    { document.addEventListener('click',fn,false); }
    else if(typeof document.attachEvent !='undefined')    { document.attachEvent('onclick',fn); }
    else{
        var oldfn=window.onclick 
        if(typeof window.onclick !='function')    window.onclick=fn; 
        else    window.onclick=function(){oldfn();fn();} 
    } 
}
function SilenceClose()
{
    window.opener = null;
    window.close();
}
function IsIE()
{
	return navigator.appVersion.indexOf("MSIE")>0;
}
/////////////////////////////////////////////////////////////////////
// WebService调用，url直接调用
function WSCall(url,act,paraml,fncb,cbparam)
{
    var vdt = '<?xml version="1.0" encoding="utf-8"?>';
    vdt += '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">';
    vdt += '<soap:Body>';
    vdt += '<' + act + ' xmlns="http://tempuri.org/">';
    vdt += paraml;
    vdt += '</' + act + '>';
    vdt += '</soap:Body>';
    vdt += '</soap:Envelope>';

    var xmlHttp = CreateHttpRequest();
    xmlHttp.onreadystatechange = function()
    {
        if (fncb != null && xmlHttp.readyState == 4)
        {
            if (xmlHttp.status == 200)
            {
                var xmlNodes = GetElementsOfXML(xmlHttp.responseXML, "ns1:out");
                if (xmlNodes.length == 0)
                    xmlNodes = GetElementsOfXML(xmlHttp.responseXML, act + "Result");
                fncb(true, xmlNodes[0].childNodes[0].nodeValue, cbparam);
            }
            else
                fncb(false, xmlHttp.responseXML, cbparam);
        }
    }
    xmlHttp.open("POST", url, true);
    xmlHttp.SetRequestHeader ("Content-Type","text/xml; charset=utf-8"); 
    xmlHttp.SetRequestHeader ("SOAPAction","http://tempuri.org/" + act);
    xmlHttp.send(vdt);
}
function GetElementsOfXML(xmlNode, tagName)
{
    if (IsIE())
        return xmlNode.getElementsByTagName(tagName);
    else
    {
        if (tagName.contains(":")) tagName = tagName.split(":")[1];
        return xmlNode.getElementsByTagName(tagName);
    }
}
function DynaCall(url,fncb,cbparam)
{
	var xmlHttp = CreateHttpRequest();
	xmlHttp.onreadystatechange = function()
	{
		if (fncb != null && xmlHttp.readyState == 4)
			fncb(xmlHttp,cbparam);
	}
	xmlHttp.open("GET", url);
	xmlHttp.send(null);	
}
function CreateHttpRequest()
{
	var xmlHttp = null;
    if (window.XMLHttpRequest)
        xmlHttp = new XMLHttpRequest();
    else if (window.ActiveXObject)
    {
		try
		{	xmlHttp = new ActiveXObject("Msxml2.XMLHTTP.5.0")	}
		catch(e)
		{
			try
			{	xmlHttp = new ActiveXObject("Msxml2.XMLHTTP.4.0")	}
			catch(e)
			{
				try
				{	xmlHttp = new ActiveXObject("Msxml2.XMLHTTP")	}
				catch(e)
				{
					try{	xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");	}catch(e){}
				}
			}
		}
    }
    return xmlHttp;
}
/////////////////////////////////////////////////////////////////////
// 页面元素
function GetElement(id)
{ return document.getElementById(id); }
function SetElementText(id, str)
{
	var v = document.getElementById(id);
	if (v != null) v.innerText = str;
}
function SetElementHtml(id, str)
{
	var v = document.getElementById(id);
	if (v != null) v.innerHTML = str;
}
function SetElementValue(id, vlu)
{
	var v = document.getElementById(id);
	if (v != null) v.value = vlu;
}
function GetElementValue(id)
{
	var v = document.getElementById(id);
	return GetElementValueInside(v);
	//if (v == null) return null;
	//return v.value;
}
function GetElementValueInside(e)
{
	if (e == null) return '';
	var tmp;
	switch (e.tagName.toUpperCase())
	{
		case 'INPUT':
			switch (e.type.toUpperCase())
			{
				case 'CHECKBOX':	return	e.checked ? 'Y' : 'N';
				case 'RADIO':
					tmp = document.getElementsByName(e.name);
					if (tmp == null)	return	'';
					for (var i = 0; i < tmp.length; i++)
					{	if (tmp[i].checked) return tmp[i].value;	}
					return '';
				default:	break;
			}
			break;
		case 'SPAN':
			if (typeof(e.value) == 'string')
				return e.value;
			return e.innerText.trim();
		case 'DIV':	return e.innerText.trim();
		case 'SELECT':
			if (e.selectedIndex < 0)	return '';
			return e.options[e.selectedIndex].value;
		default:
			break;
	}
	return e.value != null ? e.value : '';
}
function GetElementText(id)
{
	var v = document.getElementById(id);
	if (v == null) return null;
	return v.innerText;
}
function CalcElementPos(e)
{
    if (e == null) null;
    var t=e.offsetTop, l=e.offsetLeft; 
    while(e=e.offsetParent)
    { 
        t+=e.offsetTop; l+=e.offsetLeft; 
    }
    return [l, t];
}
function CalcElementPosID(id)
{ return CalcElementPos(document.getElementById(id)); }
function TrimElement(e)
{
	e.value = e.value.trim();
}
function TrimElementID(id)
{
	TrimElement(document.getElementById(id));
}
function EnableElement(id,bEnable)
{
	var v = document.getElementById(id);
	if (v == null) return;
	v.disabled = bEnable ? '' : 'disabled';
}
function DoNothing()
{
}

/////////////////////////////////////////////////////////////////////
// 页面区域隐藏/显示
function ShowHideArea(id,disp)
{
    var v = GetElement(id);
    if (v == null) { alert('ERROR: Failed to getElementById ' + id); return;}
    if (disp == null) disp = 'block';
    if (v.style.display == 'none')
        v.style.display = disp;
    else
        v.style.display = 'none';
}

function ShowArea(id,disp)
{
    var v = GetElement(id);
    if (disp == null) disp = 'block';
    if (v != null) v.style.display = disp;
}

function HideArea(id)
{
    var v = GetElement(id);
    if (v != null) v.style.display = "none";
}
/////////////////////////////////////////////////////////////////////
// 数据格式
function CheckLength(id,btrm,minl,maxl,errt)
{
    var v = GetElement(id);
    if (v == null || minl > maxl)
    {
        alert("ERROR: CheckLenth the element is null or range invalid. msg=" + errt);
        return false;
    }
    var t = v.value;
    if (btrm) t = t.trim();
    if (t.length < minl || t.length > maxl)
    {
        if (minl == maxl)
            alert(errt + " 的长度应该是 " + minl + "，请重新输入。");
        else
        {
			if (t.length > maxl)
				alert(errt + ' 的长度不能超过 ' + maxl + ' ，请重新输入。');
            else if (minl == 1)
                alert(errt + " 不能为空，请重新输入。");
            else
                alert(errt + " 的长度应该在 " + minl + " - " + maxl + " 之间，请重新输入。");
        }
        v.focus();
        v.select();
        return false;
    }
    if (t != v.value)
        v.value = t;
    return true;
}
function CheckNotNull(id, msg)
{
	var v = GetElement(id);
    if (v == null)
    {
        alert("ERROR: CheckNotNull the element is null. msg=" + msg);
        return false;
    }
    if (v.value.trim() == "")
    {
        alert(msg);
        v.focus();
        return false;
    }
    return true;
}
function CheckPassword(pwd1,pwd2)
{
    var v1 = document.getElementById(pwd1);
    var v2 = document.getElementById(pwd2);
    if (v1 == null || v2 == null)
    {
        alert("ERROR: CheckPassword the element is null.");
        return false;
    }
    if (v1.value != v2.value)
    {
        alert("密码错误，请重新输入。");
        v1.value = "";
        v2.value = "";
        v1.focus();
        return false;
    }
    if (v1.value.length < 1)
    {
        alert("密码不能为空。");
        return false;
    }
    return true;
}
function CheckReg(id, nullable, errt, reg, tpn)
{
	var v = GetElement(id);
	if (v == null)
	{
		alert("ERROR: CheckIsInt the element is null. id=" + id);
        return false;
	}	
	var s = v.value.toString().trim();
	if (s == '')
	{
		if (nullable)	return true;
		alert(errt + ' 不能为空。');
		v.focus(); v.select();
		return false;
	}
	if (!reg.test(s))
	{
		alert(errt + ' 必须是' + tpn + '，请重新输入。');
		v.focus(); v.select();
		return false;
	}
	return true;
}
function CheckIsInt(id, nullable, errt)
{
	var reg = /^-?\d+$/;
	return CheckReg(id, nullable, errt, reg, '整数');
}
function CheckIsFloat(id, nullable, errt)
{
	var reg = /^(-?\d+)(\.\d+)?$/;
	return CheckReg(id, nullable, errt, reg, '浮点数');
}
function CheckIsEMail(id, nullable, errt)
{
	var reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
	return CheckReg(id, nullable, errt, reg, 'E-Mail地址');
}
function FormatStandDate(dstr)
{
	if (dstr == null || dstr == "")
		return "";
    var today = new Date(), nd, yy, mm, dd;
    today.setHours(0); today.setMinutes(0); today.setSeconds(0); today.setMilliseconds(0);
    if (dstr == ".")
    {
        yy = today.getFullYear();
        mm = today.getMonth() + 1;
        dd = today.getDate();
    }
    else if (dstr == "+")
    {
        yy = today.getFullYear();
        mm = today.getMonth() + 1;
        dd = today.getDate() + 1;
    }
    else if (dstr.length == 3)
    {
        yy = today.getFullYear();
        mm = parseInt(dstr.substr(0,1), 10);
        dd = parseInt(dstr.substr(1,2), 10);
        if (isNaN(mm) || isNaN(dd))
            return "";
        if (mm < today.getMonth())
            yy++;
    }
    else if (dstr.length == 4)
    {
        yy = today.getFullYear();
        mm = parseInt(dstr.substr(0,2), 10);
        dd = parseInt(dstr.substr(2,2), 10);
        if (isNaN(mm) || isNaN(dd))
            return "";
        if (mm < today.getMonth())
            yy++;
    }
    else if (dstr.length == 5)
    {
        yy = today.getFullYear();
        mm = parseInt(dstr.substr(0,2), 10);
        dd = parseInt(dstr.substr(3,2), 10);
        if (isNaN(mm) || isNaN(dd))
            return "";
        if (mm < today.getMonth())
            yy++;
    }
    else if (dstr.length == 8)
    {
        yy = parseInt(dstr.substr(0,4), 10);
        mm = parseInt(dstr.substr(4,2), 10);
        dd = parseInt(dstr.substr(6,2), 10);
        if (isNaN(yy) || isNaN(mm) || isNaN(dd))
            return "";
    }
    else if (dstr.length == 10)
    {
        yy = parseInt(dstr.substr(0,4), 10);
        mm = parseInt(dstr.substr(5,2), 10);
        dd = parseInt(dstr.substr(8,2), 10);
        if (isNaN(yy) || isNaN(mm) || isNaN(dd))
            return "";
    }
    else
        return "";
    nd = today;
    nd.setYear(yy);nd.setMonth(mm-1); nd.setDate(dd);
    return nd.format("yyyy-MM-dd");
}
function ConvertDate(e,bNotNull)
{
    if (e == null)	return false;
    var dstr = FormatStandDate(e.value);
    if (dstr == "" && bNotNull)
    {
        alert("请输入日期，格式可以是：mdd,mmdd,mm-dd,mm.dd,yyyymmdd,yyyy-mm-dd。");
        e.focus();
        return false;
    }
    e.value = dstr;
    return true;
}
function ConvertDateID(id,bNotNull)
{ConvertDate(document.getElementById(id), bNotNull);}
function ParseDate(str)
{
	if(typeof str == 'string')
	{   
		var results = str.match(/^ *(\d{4})-(\d{1,2})-(\d{1,2}) *$/);  
		if(results && results.length>3)   
			return new Date(parseInt(results[1],10),parseInt(results[2],10) -1,parseInt(results[3],10));    
		results = str.match(/^ *(\d{4})-(\d{1,2})-(\d{1,2}) +(\d{1,2}):(\d{1,2}):(\d{1,2}) *$/);   
		if(results && results.length>6)   
			return new Date(parseInt(results[1],10),parseInt(results[2],10) -1,parseInt(results[3],10),parseInt(results[4],10),parseInt(results[5],10),parseInt(results[6],10));    
		results = str.match(/^ *(\d{4})-(\d{1,2})-(\d{1,2}) +(\d{1,2}):(\d{1,2}):(\d{1,2})\.(\d{1,9}) *$/);   
		if(results && results.length>7)   
			return new Date(parseInt(results[1],10),parseInt(results[2],10) -1,parseInt(results[3],10),parseInt(results[4],10),parseInt(results[5],10),parseInt(results[6],10),parseInt(results[7],10));    
	}   
	return null;
}
function CheckCardID(id)
{
	var v = GetElement(id);
	if (v == null)
	{
		alert("程序错误：身份证号ID无效。");
		return false;
	}
	var cid = v.value.replace(/^\s+|\s+$/, '');
	v.value = cid;
	if (cid.length != 15 && cid.length != 18)
	{
		alert("身份证号码长度错误，应该是15或18个字符。请重新输入。");
		v.focus();
		return false;
	}
	var y,m,d
	if (cid.length == 15)
	{
		y = parseInt(cid.substr(6,2), 10) + 1900;
		m = parseInt(cid.substr(8,2), 10);
		d = parseInt(cid.substr(10,2), 10);
	}
	else if (cid.length == 18)
	{
		y = parseInt(cid.substr(6,4), 10);
		m = parseInt(cid.substr(10,2), 10);
		d = parseInt(cid.substr(12,2), 10);
	}
	var bd = new Date(y,m-1,d);
	if (bd.getFullYear() != y || bd.getMonth()+1 != m || bd.getDate() != d)
	{
		alert("身份证号码内的生日错误，请重新输入。");
		v.focus();
		return false;
	}
//	if (cid.length == 18)
//	{
//		var idcard_array = cid.split("");
//		var s = (parseInt(idcard_array[0]) + parseInt(idcard_array[10])) * 7
//				+ (parseInt(idcard_array[1]) + parseInt(idcard_array[11])) * 9
//				+ (parseInt(idcard_array[2]) + parseInt(idcard_array[12])) * 10
//				+ (parseInt(idcard_array[3]) + parseInt(idcard_array[13])) * 5
//				+ (parseInt(idcard_array[4]) + parseInt(idcard_array[14])) * 8
//				+ (parseInt(idcard_array[5]) + parseInt(idcard_array[15])) * 4
//				+ (parseInt(idcard_array[6]) + parseInt(idcard_array[16])) * 2
//				+ parseInt(idcard_array[7]) * 1 
//				+ parseInt(idcard_array[8]) * 6
//				+ parseInt(idcard_array[9]) * 3 ;
//		var y = s % 11;
//		var JYM = "10X98765432";
//		var m = JYM.substr(y,1);
//		if(m != idcard_array[17])
//		{
//			alert("身份证号码校验错误，请重新输入。");
//			v.focus();
//			return false;
//		}
//	}
	return true;
}
function ToUpper(e)
{
	if (e != null) e.value = e.value.toUpperCase().trim();
}
function ToUpperID(id)
{
	ToUpper(GetElement(id));
}
function MakeTransVars(id_list)
{
	if (id_list == null) return '';	
	var aryIDs = id_list.split(',');
	var sb = new StringBuilder();
	for (var i = 0; i < aryIDs.length; i++)
	{
		var ctrl = GetElement(aryIDs[i]);
		if (ctrl == null)
		{	alert('ERROR: Failed to find trans_var for ID ' + aryIDs[i]);	continue;	}
		var value = ctrl.value.toString().trim();
		sb.append(aryIDs[i] + ':' + value.length + ',' + value + ';');
	}
	return sb.toString();
}
function UpdateTransVars(str)
{
	if (str == null) return '';
	var nPos = 0;
	while (nPos < str.length)
	{
	    var nFindName = str.indexOf(':', nPos);
	    if (nFindName < 0)  break;
	    var nFindValue = str.indexOf(',', nFindName + 1);
	    if (nFindValue < 0 || nFindValue + 1 >= str.length)
	        break;
		var nValueLen = parseInt(str.substr(nFindName + 1, nFindValue - (nFindName + 1)), 10);
		if (nValueLen < 0)
		{
			var nFindRtn = str.indexOf(';', nFindValue + 1);
			if (nFindRtn < 0)
				nValueLen = str.length;
			else
				nValueLen = nFindRtn - (nFindValue + 1);
		}
		
		var id = str.substr(nPos, nFindName - nPos);
		var val;
		if (nFindValue + 1 + nValueLen < str.length)
			val = str.substr(nFindValue + 1, nValueLen);
		else
			val = str.substr(nFindValue + 1);
		var e = GetElement(id);
		if (e != null)
			e.value = val
		else
			alert('ERROR: Failed to update element value, id = ' + id + ' value = ' + val);
		nPos = nFindValue + 1 + nValueLen + 1;
	}
}
/////////////////////////////////////////////////////////////////////
// 弹出窗口
function OpenNewCenter(url)
{
	var nWidth = 600, nHeight = 600;
	var nLeft = (window.screen.width - nWidth) / 2;
	var nTop = (window.screen.height - nHeight) / 3;
	window.open(url, 'wndPopup',
		'Scrollbars=yes,Toolbar=no,Location=no,Direction=no,resizable=yes,'+
		',width=' + nWidth + ',height=' + nHeight +
		',left=' + nLeft + ',top=' + nTop);
}
function ShowDialog(url,args,nWidth,nHeight)
{
	if (nWidth == null) nWidth = 580;
	if (nHeight == null) nHeight = 620;
	var nLeft = (window.screen.width - nWidth) / 2;
	var nTop = (window.screen.height - nHeight) / 3;
	window.showModalDialog(url,args, 'dialogWidth=' + nWidth + 'px;dialogHeight=' + nHeight + 'px;dialogTop=' + nTop + 'px;resizable=no;help=no');
}

/////////////////////////////////////////////////////////////////////
// 表格
function SetupTableHover(tblId, startLine, hoverClr)
{
	var tbl = GetElement(tblId);
	for (var i = startLine; i < tbl.rows.length; i++)
	{
		var row = tbl.rows[i];
		row.onmouseover = function() { this.style.backgroundColor=hoverClr; }
		row.onmouseout = function() { this.style.backgroundColor=''; }
	}
}
/////////////////////////////////////////////////////////////////////
// cookie
function GetCookie(ckName)
{
	var search = ckName + "=" 
	var returnvalue = ""; 
	if (document.cookie.length > 0)
	{ 
		offset = document.cookie.indexOf(search) 
		if (offset != -1)
		{ 
			offset += search.length 
			end = document.cookie.indexOf(";", offset); 
			if (end == -1) 
				end = document.cookie.length; 
			returnvalue=unescape(document.cookie.substring(offset, end)) 
		}
	}
	return returnvalue; 
}
function GetQuery(name)
{
	if(location.href.indexOf("?")==-1 || location.href.indexOf(name+'=')==-1)
		return ''
	var queryString = location.href.substring(location.href.indexOf("?")+1);
	var parameters = queryString.split("&");
	var pos, paraName, paraValue;
	for(var i=0; i<parameters.length; i++)
	{
		pos = parameters[i].indexOf('=');
		if(pos == -1) { continue; }
		paraName = parameters[i].substring(0, pos);
		paraValue = parameters[i].substring(pos + 1);
		if(paraName == name)
		{
			return unescape(paraValue.replace(/\+/g, " "));
		}
	}
	return '';
}

/////////////////////////////////////////////////////////////////////
// 检查码

function RefreshCheckCode(id)
{
	var img = GetElement(id);
	if (img == null)	return;
	var tm = new Date();
	img.src = '../Start/CheckCode.aspx?tm=' + tm.toString();
}

/////////////////////////////////////////////////////////////////////
// 全局
document.execCommand("BackgroundImageCache", false, true);