﻿/*****************************************************
 * My97日期控件 My97 DatePicker Ver 2.1 正式版
 * 2.1版更新说明
 * 新增日期范围限制,可以在选择框指定MINDATE和MAXDATE属性来限制日期范围
 * 增强的自动纠错功能,纠错处理可设置为3种模式 1.提示(默认) 2.自动纠错 3.标记
 * 2.0版更新说明
 * 支持两种调用方式
 * 支持自定义皮肤和动态切换皮肤(感谢why提供whyGreen皮肤)
 * 跨越框架显示选择框
 * 自动提示日期错误
 * 年份,月份设置为选择模式
 * 支持日期和时间的编辑,编辑时自动跳转到对应月份和时间
 * 根据网页大小自动选择显示位置
 * 支持时间选择
 * 自定义日期时间格式
 * 支持多国语言设置
 * 支持周末加亮设置
 * 支持编码设置(如utf-8,gb2312,big5)
 * 完美支持FireFox,在FF中的效果跟IE一模一样
 * ---------------------------------------------------
 * 联系My97:
 * 如果您在使用过程中遇到问题,或者有更好的建议
 * 欢迎您访问
 * BLOG: http://blog.csdn.net/my97/
 * MAIL: smallcarrot@163.com
 ****************************************************/

/* 设置 */
var dpcfg = {};
/* 默认风格 如果你喜欢whyGreen这个样式,你可以改成whyGreen 另外你还可以自定义自己的样式 */
dpcfg.skin = "default";		
/* 日期格式 %Y %M %D %h %m %s 表示年月日时分秒(注意大小写) */
dpcfg.dateFmt = "%Y-%M-%D";
/* 是否显示时间 */
dpcfg.showTime = false;	
/* 是否高亮显示 周六 周日 */
dpcfg.highLineWeekDay = true;
/* 日期范围 */
dpcfg.minDate = "1900-1-1";
dpcfg.maxDate = "2099-12-30";
/* 纠错模式设置 可设置3中模式 0 - 提示 1 - 自动纠错 2 - 标记 */
dpcfg.errDealMode = 0;
/* 纠错提示信息,仅当提示提示模式为0时有效 */
dpcfg.errAlertMsg = "不合法的日期格式或者日期超出限定范围,需要撤销吗?";
/* 语言设置 */
dpcfg.aWeekStr = ["日","一","二","三","四","五","六"];
dpcfg.aMonStr = ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一","十二"];
dpcfg.todayStr = "今天";
dpcfg.okStr = "确定";
dpcfg.timeStr = "时间";
dpcfg.monthStr = "月份";
dpcfg.yearStr = "年份";

//公共变量 
var $d = null;

function __sb()
{
	this.s = new Array();
	this.i = 0;
	this.a = function(t){this.s[this.i++]=t;};
	this.j = function(){return this.s.join('');};
}
/**
 * 主函数
 */
function WdatePicker(el,dateFmt,showTime,skin){
	/* 为窗口对象建立指针 */	
	this.win = window;/* 触发事件所在的窗体 */
	this.top = window;/* 找到除FrameSet外的 最顶层的窗体 */	
	while(this.top.parent.document != this.top.document && this.top.parent.document.getElementsByTagName("frameset").length == 0){this.top = this.top.parent;}
	
	this._todayDate = new Date();
	this.t_year = this._todayDate.getFullYear();
	this.t_month = this._todayDate.getMonth()+1;
	this.t_date = this._todayDate.getDate();
	this.t_hour = this._todayDate.getHours();
	this.t_minute  = this._todayDate.getMinutes();
	this.t_sec  = this._todayDate.getSeconds();
	
	this.eCont = (typeof el=='string')?document.getElementById(el):el;
	this.dateFmt = (dateFmt==null)?dpcfg.dateFmt:dateFmt;
	this.showTime = (showTime!=dpcfg.showTime)?showTime:dpcfg.showTime;
	this.skin = (skin==null)?dpcfg.skin:skin;
	var _tempMinMaxDate = this.eCont.getAttribute("MINDATE");
	if(_tempMinMaxDate==null){_tempMinMaxDate=dpcfg.minDate;}
	if(_tempMinMaxDate.substring(0,1)=='$'){
		_tempMinMaxDate = document.getElementById(_tempMinMaxDate.substring(1));
		if(_tempMinMaxDate){
			if(_tempMinMaxDate.getAttribute("REALVALUE")==null||_tempMinMaxDate.getAttribute("REALVALUE")==""){
				_tempMinMaxDate = _tempMinMaxDate.value;
			}
			else{
				_tempMinMaxDate = _tempMinMaxDate.getAttribute("REALVALUE");
			}
		}else{_tempMinMaxDate=null;}
		if(_tempMinMaxDate==null || _tempMinMaxDate==''){
			_tempMinMaxDate = dpcfg.minDate;
		}
	}

	_tempMinMaxDate = _tempMinMaxDate.replace(/#Today/,this.t_year+'/'+this.t_month+'/'+this.t_date);
	this.minDate = this._splitDate(_tempMinMaxDate);
	_tempMinMaxDate = this.eCont.getAttribute("MAXDATE");
	if(_tempMinMaxDate==undefined){_tempMinMaxDate=dpcfg.maxDate;}
	if(_tempMinMaxDate.substring(0,1)=='$'){
		_tempMinMaxDate = document.getElementById(_tempMinMaxDate.substring(1));
		if(_tempMinMaxDate){
			if(_tempMinMaxDate.getAttribute("REALVALUE")==null||_tempMinMaxDate.getAttribute("REALVALUE")==""){
				_tempMinMaxDate = _tempMinMaxDate.value;
			}
			else{
				_tempMinMaxDate = _tempMinMaxDate.getAttribute("REALVALUE");
			}
		}
		else{_tempMinMaxDate=null;}
		if(_tempMinMaxDate==null || _tempMinMaxDate==''){
			_tempMinMaxDate = dpcfg.maxDate;
		}
	}

	_tempMinMaxDate = _tempMinMaxDate.replace(/#Today/,this.t_year+'/'+this.t_month+'/'+this.t_date);
	this.maxDate = this._splitDate(_tempMinMaxDate);
	//alert("this.minDate:"+this.minDate.year+'-'+this.minDate.month+'-'+this.minDate.date+'\nthis.maxDate:'+this.maxDate.year+'-'+this.maxDate.month+'-'+this.maxDate.date);
	
	/* 判断对象是否已经存在 */
	if(this.top.document.dateDiv && this.top.document.dateDiv.obj.eCont==this.eCont){
		$d = this.top.document.dateDiv;	
	}
	else{
		this.top.document.dateDiv = null;
	}
	/* 初始化默认设置变量 */
	this.cssPath = webheader + '/App_Themes/Default/datepicker.css';
	this.highLineWeekDay = dpcfg.highLineWeekDay;
	this.aWeekStr = dpcfg.aWeekStr;
	this.aMonStr = dpcfg.aMonStr;
	this.todayStr = dpcfg.todayStr;
	this.okStr = dpcfg.okStr;
	this.timeStr = dpcfg.timeStr;
	
	/* 根据传入的皮肤 动态改变css 要用的$d,所以必须放在$d指向top.div之后 */
	this._loadSkin();
	
	this._initDate(this.eCont.value,this.dateFmt);
	if(this.eCont.value != '' && this.eCont.getAttribute("REALVALUE")==null && this._judgeCorrectDateTime(this.eCont.value)){
		this._setRealValue();
	}
	
	this.s_year = this.year;
	this.s_month = this.month;
	this.s_date = this.date;
	
	/* 创建弹出层 如果已经建立了层则直接使用之 */	
	if(this.top.document.dateDiv == null){
	/* 说明层没有创建 */		
		this.dd = this.top.document.createElement("DIV");
		this.dd.style.cssText = 'position:absolute;z-index:197;width:180px;';
		this.dd.obj = this;
		this.dd.className = "WdateDiv";
		this.dd.innerHTML = this._createPickerHTML();	
		var tmpIF = this.top.document.createElement('iframe');
		this.dd.ifr = tmpIF;
		var tmpInputs = this.dd.getElementsByTagName('input');
		this.dd.mInput = tmpInputs[0];
		this.dd.yInput = tmpInputs[1];	
		var tmpDivs = this.dd.getElementsByTagName('div');
		this.dd.mDiv = tmpDivs[2];
		this.dd.yDiv = tmpDivs[4];
		this.dd.dDiv = tmpDivs[5];
		this.dd.tDiv = tmpDivs[6].firstChild;
		this.dd.dDiv.innerHTML = this._createDateTable();
		this._inputKeydown = function(){
			var evt = $d.obj.top.event;
			var k =(evt.which==undefined)?evt.keyCode:evt.which;
			if( !((k>=48 && k<=57) || (k>=96 && k<=105) || k==8 || k==46 || k==37 || k==39) ){evt.returnValue=false;}
		};
		this.dd.mInput.attachEvent('onkeydown',this._inputKeydown);
		this.dd.yInput.attachEvent('onkeydown',this._inputKeydown);
		this.dd.yInput.onblur = function(){
			if(parseInt(this.value)!=$d.obj.year){
				$d.obj.redraw();
			}
			this.className='yminput';
		};
		this.dd.mInput.onblur = function(){
			if(this.value>12){
				this.value='12';
			}
			else if(this.value<1){
				this.value='1';
			}
			else if(parseInt(this.value)!=$d.obj.month){
				$d.obj.redraw();
			}
			this.className='yminput';
		};
		this.dd.mInput.onfocus = function() {this.className='yminputfocus';this.select();$d.obj._fillmonth();$d.mDiv.style.display='block';};
		this.dd.yInput.onfocus = function() {this.className='yminputfocus';this.select();$d.obj._fillyear();$d.yDiv.style.display='block';};
		
		/* 添加time相关时间和指针 */
		this.dd.hhInput = tmpInputs[2];
		this.dd.mmInput = tmpInputs[4];
		this.dd.ssInput = tmpInputs[6];
		this.dd.okInput = tmpInputs[7];
		this.dd.hhInput.onfocus = this.dd.mmInput.onfocus = this.dd.ssInput.onfocus = function(){this.select();$d.obj.currFocus = this;};
		this.dd.hhInput.onblur = function(){
			if(parseInt(this.value)>23){this.value='23';}
			else if(parseInt(this.value)<0){this.value='0';}
		};
		this.dd.mmInput.onblur = this.dd.ssInput.onblur = function(){
			if(parseInt(this.value)>59){	this.value='59';}
			else if(parseInt(this.value)<0){	this.value='0';}
		};
		this.dd.hhInput.attachEvent('onkeydown',this._inputKeydown);
		this.dd.mmInput.attachEvent('onkeydown',this._inputKeydown);
		this.dd.ssInput.attachEvent('onkeydown',this._inputKeydown);
		var tmpBtn = this.dd.getElementsByTagName('button');
		this.dd.upButton = tmpBtn[0];
		this.dd.downButton = tmpBtn[1];
		this.dd.upButton.onclick = function(){
			if($d.obj.currFocus == undefined){
				$d.obj.currFocus = $d.mmInput;
			}				
			if(($d.obj.currFocus==$d.hhInput && parseInt($d.obj.currFocus.value)<23) || ($d.obj.currFocus!=$d.hhInput && parseInt($d.obj.currFocus.value)<59) ){	
				$d.obj.currFocus.value = parseInt($d.obj.currFocus.value)+1;
			}
			$d.obj.currFocus.focus();	
		};
		this.dd.downButton.onclick = function(){
			if($d.obj.currFocus == undefined){
				$d.obj.currFocus = $d.mmInput;
			}				
			if(parseInt($d.obj.currFocus.value)>0){
				$d.obj.currFocus.value = parseInt($d.obj.currFocus.value)-1;
			}					
			$d.obj.currFocus.focus();
		};
		
		this.top.document.body.insertAdjacentElement('afterBegin', this.dd);
		this.top.document.body.insertAdjacentElement('beforeEnd', this.dd.ifr);
		this.top.document.dateDiv = this.dd;
		
		/* 为日期框添加getValue函数 */
		this.eCont.getValue = function() {
			if(this.value==''){
				return '';
			}
			else{
				return this.getAttribute("REALVALUE");
			}
		};
		
		/* 限制tab键 */
		this.eCont.attachEvent('onkeydown',function(){
			if($d.style.display!='none'){
				var evt = $d.obj.top.event;
				var k =(evt.which==undefined)?evt.keyCode:evt.which;
				if(k==9){
					evt.returnValue=false;
				}
			}			
		});
	}
	else{
	/* 说明层已经创建 直接使用即可*/
		this.dd = this.top.document.dateDiv;
		this.dd.obj.win = this.win;/* 触发事件所在的窗体 */
		this.dd.obj.top = this.top;/* 最顶层的窗体 */
		this.dd.obj.eCont = this.eCont;
		this.dd.obj.showTime = this.showTime;
		this.dd.obj.dateFmt = this.dateFmt;
		this.dd.style.display = '';
		this.dd.mInput.value = this.month;
		this.dd.yInput.value = this.year;
		this.dd.dDiv.innerHTML = this._createDateTable();
		if(this.showTime){
			this.dd.tDiv.style.display = 'block';
			this.dd.hhInput.value = this.hour;
			this.dd.mmInput.value = this.minute;
			this.dd.ssInput.value = this.sec;
		}
		else{
			this.dd.tDiv.style.display = 'none';
		}
	}
	/* 添加到公共变量 */
	this._setPubVar();
	this._setOkInput();
	
	var objxy = this.eCont.getBoundingClientRect();

	var mm = $getAbsM(this.top);	
	var currWinSize = $getClientWidthHeight(this.top);
	var ddTop = mm.topM + objxy.bottom;
	var ddLeft = mm.leftM + objxy.left;	
	/* 高度显示位置 */	
	if((ddTop+parseInt(this.dd.offsetHeight) < (currWinSize.height) ) ||(ddTop-this.eCont.offsetHeight < this.dd.offsetWidth*0.8) )
	{/* 下面高度适合 或者 上面高度小于80%的控件高度 */
		this.dd.style.top = (this.top.document.body.scrollTop + ddTop + 1)+'px';
	}
	else{
		this.dd.style.top = (this.top.document.body.scrollTop + ddTop - parseInt(this.dd.offsetHeight) - this.eCont.offsetHeight - 3)+'px';
	}
	this.dd.style.left = -1 + this.top.document.body.scrollLeft + Math.min(ddLeft, currWinSize.width-parseInt(this.dd.offsetWidth)-5) +'px';
	//使用一个IFrame用于盖住<SELECT>
	this.dd.ifr.style.cssText='top:'+this.dd.style.top+';left:'+(this.dd.style.left)+';width:'+Math.min(180,(this.dd.offsetWidth-1))+'px;height:'+(this.dd.offsetHeight-1)+'px;position:absolute;z-index:196;overflow:hidden;border:0px;filter:alpha(opacity=0);';
	
}

WdatePicker.prototype._createCssPath = function(){
	var path = '';
	var i;
	/* 得到库文件的路径 */
	var scripts = document.getElementsByTagName("script");
	for(i=0; i<scripts.length; i++){
		if(scripts[i].src.substring(scripts[i].src.length-14).toLowerCase() == 'wdatepicker.js'){
			path = scripts[i].src.substring(0,scripts[i].src.length-14);
			break;
		}
	}
	
	if(path.indexOf('://') == -1){
		var a = this.top.location.href.toLowerCase();
		var b = location.href.toLowerCase();
		var al='',bl='',bls='';
		var j,s='';
		for(i=0; i<Math.max(a.length,b.length); i++){
			if(a.charAt(i) != b.charAt(i)){
				j = i;
				while(a.charAt(j) != '/'){if(j==0){break;}j-=1;}
				al = a.substring(j+1,a.length);
				al = al.substring(0,al.indexOf('/'));
				bl = b.substring(j+1,b.length);
				bl = bl.substring(0,bl.indexOf('/'));
				break;
			}
		}
		if(al!=''){	for(i=0; i<al.split('/').length; i++){s += "../";}}
		if(bl!=''){
			bls = bl.split('/');
			for(i=0; i<bls.length; i++){s += bls[i] + '/';}
		}
		path = s + path;
	}
	
	this.cssPath = calendar + this.skin.toLowerCase() + '/datepicker.css'; 
};

/* 自动载入其他JS文件 */
WdatePicker.prototype._loadSkin = function() {
    if (!$d || ($d && $d.obj.skin != this.skin)) {
        if ($d) { $d.obj.skin = this.skin; }
        /* 有改变 */
        /* 自动转换路径 */
        this._createCssPath();
        /* 查找CSS如果不相同就并禁用 */
        var needAddNew = true;
        for (var i = this.top.document.styleSheets.length - 1; i >= 0; i--) {
            tempStyle = this.top.document.styleSheets[i];
            if (tempStyle.href != null && tempStyle.href != '') {
                if (tempStyle.href.substring(tempStyle.href.lastIndexOf('/') + 1).toLowerCase() == 'datepicker.css') {
                    if (tempStyle.href.toLowerCase() == this.cssPath.toLowerCase()) {/* 皮肤相同则启用皮肤 */
                        needAddNew = false;
                        tempStyle.disabled = false;
                        continue;
                    }
                    else {/* 禁用 */
                        tempStyle.disabled = true;
                    }
                }
            }
        }
        /* 如果没有找到就添加新的 */
        if (needAddNew) {
            this.top.document.createStyleSheet(this.cssPath);
        }
    }
};

/* 根据fmt转换字符串为日期 */
WdatePicker.prototype._initDate = function(str, fmt)
{
	this.year = this.month = this.date = this.hour = this.minute = this.sec = -1;
	var v = str.split(/\W+/);
	var f = fmt.match(/%./g);
	//for(var i=0; i<f.length; i++){alert(f[i]);}
	for (var i=0; i<f.length; i++) {
		if(v[i]){
			if(f[i].toLowerCase() == '%y'){
				this.year = parseInt(v[i], 10); 
				if(isNaN(this.year)){this.year = this.t_year;}
			}			
			else if(f[i] == '%M'){
				this.month = parseInt(v[i], 10); 
				if(isNaN(this.month)){this.month = this.t_month;}
			}
			else if(f[i].toLowerCase() == '%d'){
				this.date = parseInt(v[i], 10);
				if(isNaN(this.date)){this.date = this.t_date;}
			}
			else if(f[i].toLowerCase() == '%h'){
				this.hour = parseInt(v[i], 10); 
				if(isNaN(this.hour)){this.hour = this.t_hour;}
			}
			else if(f[i] == '%m'){
				this.minute = parseInt(v[i], 10);
				if(isNaN(this.minute)){this.minute = this.t_minute;}
			}
			else if(f[i].toLowerCase() == '%s'){
				this.sec = parseInt(v[i], 10); 
				if(isNaN(this.sec)){this.sec = this.t_sec;}
			}
		}
	}
	/* 判断日期的合法性 */
	if( !this._isDate(this.year+'-'+this.month+'-'+this.date) ){
		this.year = this.t_year;this.month = this.t_month;this.date = this.t_date;
	}
	/* 判断时间的合法性 */
	if((this.hour<0) || (this.hour>23)){this.hour = this.t_hour;}
	if((this.minute<0) || (this.minute>59)){this.minute = this.t_minute;}
	if((this.sec<0) || (this.sec>59)){this.sec = this.t_sec;}
};
/* 填充月份 */
WdatePicker.prototype._fillmonth = function()
{
	var s = new __sb();
	s.a("<table cellspacing=0 cellpadding=2 border=0>");
	var i,n=0,v=parseInt(this.dd.mInput.value);
	var aMonStrT = new Array(12);
	var aMonStrV = new Array(12);
	for(i=0; i<11; i++){
		if(i+1==v){n=1;}
		aMonStrT[i] = this.aMonStr[n+i];
		aMonStrV[i] = n+i+1;
	}
	this.year = parseInt(this.dd.yInput.value);
	var needCompareMinMonth = this.year==this.minDate.year;
	var needCompareMaxMonth = this.year==this.maxDate.year;
	var needCompareBoth = needCompareMinMonth&&needCompareMaxMonth;
	var validMonth = (this.year>this.minDate.year &&　this.year<this.maxDate.year);
	var isValidMonth;
	for(i=0; i<6; i++){
		s.a("<tr><td ");
		isValidMonth = (validMonth)||(!needCompareBoth&&((needCompareMinMonth&&aMonStrV[i]>=this.minDate.month)||(needCompareMaxMonth&&aMonStrV[i]<=this.maxDate.month)))||(needCompareBoth&&(aMonStrV[i]>=this.minDate.month&&aMonStrV[i]<=this.maxDate.month));
		s.a((isValidMonth)?"class='Wym' onmouseover=\"this.className='WdayOn'\" onmouseout=\"this.className='Wym'\" onmousedown=\"$d.mInput.value='" + aMonStrV[i] + "';$d.mDiv.style.display='none';$d.mInput.blur();\"":"class='Winvalidym'");
		s.a(">" + aMonStrT[i] + "</td>");				
		if(i==5){break;}
		s.a("<td ");
		isValidMonth = (validMonth)||(!needCompareBoth&&((needCompareMinMonth&&aMonStrV[i+6]>=this.minDate.month)||(needCompareMaxMonth&&aMonStrV[i+6]<=this.maxDate.month)))||(needCompareBoth&&(aMonStrV[i+6]>=this.minDate.month&&aMonStrV[i+6]<=this.maxDate.month));
		s.a((isValidMonth)?"class='Wym' onmouseover=\"this.className='WymOn'\" onmouseout=\"this.className='Wym'\" onmousedown=\"$d.mInput.value='" + aMonStrV[i+6] + "';$d.mDiv.style.display='none';$d.mInput.blur();\"":"class='Winvalidym'");
		s.a(">" + aMonStrT[i+6] + "</td></tr>");
	}
	s.a("<td align=center onmouseover=\"this.className='WymOn'\" onmouseout=\"this.className='Wym'\" onmousedown=\"$d.mDiv.style.display='none';\">×</td</tr>");
	s.a("</table>");
	this.dd.mDiv.innerHTML = s.j();
};

/* 填充年份 */
/**
 * minV 下限
 * maxV 上限
*/
WdatePicker.prototype._fillyear = function(minV,maxV)
{
	if(minV == null || maxV == null){
	/* 没有参数 */
		var v=parseInt(this.dd.yInput.value);
		minV = v-5;maxV = v+4;
	}
	var i;
	var a = new Array(maxV-minV);	
	for(i=minV; i<=maxV; i++){
		a[i-minV] = i;
	}
	var n = (a.length/2);
	var s = new __sb();
	var isValidYear;
	s.a("<table cellspacing=0 cellpadding=2 border=0>");
	for(i=0; i<n; i++){
		isValidYear = (a[i]>=this.minDate.year &&　a[i]<=this.maxDate.year);
		s.a("<tr><td ");
		s.a((isValidYear)?"class='Wym' onmouseover=\"this.className='WymOn'\" onmouseout=\"this.className='Wym'\" onmousedown=\"$d.yInput.value='" + a[i] + "';$d.yDiv.style.display='none';$d.yInput.blur();\"":"class='Winvalidym'");
		s.a(">" + a[i] + "</td><td ");
		isValidYear = (a[i+n]>=this.minDate.year &&　a[i+n]<=this.maxDate.year);
		s.a((isValidYear)?"class='Wym' onmouseover=\"this.className='WymOn'\" onmouseout=\"this.className='Wym'\" onmousedown=\"$d.yInput.value='" + a[i+n] + "';$d.yDiv.style.display='none';$d.yInput.blur();\"":"class='Winvalidym'");
		s.a(">" + a[i+n] + "</td></tr>");
	}
	s.a("</table>");
	s.a("<table cellspacing=0 cellpadding=3 border=0><tr><td ");
	s.a((this.minDate.year<minV)?"class='Wym' onmouseover=\"this.className='WymOn'\" onmouseout=\"this.className='Wym'\" onmousedown='$d.obj._fillyear("+(minV-10)+","+(maxV-10) + ")'":"class='Winvalidym'");
	s.a(">←</td><td class='Wym' onmouseover=\"this.className='WymOn'\" onmouseout=\"this.className='Wym'\" onmousedown=\"$d.yDiv.style.display='none';$d.yInput.blur();\">×</td><td ");
	s.a((this.maxDate.year>maxV)?"class='Wym' onmouseover=\"this.className='WymOn'\" onmouseout=\"this.className='Wym'\" onmousedown='$d.obj._fillyear("+(minV+10)+","+(maxV+10) + ")'":"class='Winvalidym'");
	s.a(">→</td></tr></table>");
	this.dd.yDiv.innerHTML = s.j();
};

/* 根据格式返回字符串 */
WdatePicker.prototype._returnDateStr = function(Y,M,D,h,m,s,fmt)
{
	if(Y==null){Y = this.year;}
	if(M==null){M = this.month;}
	if(D==null){D = this.date;}
	if(h==null){h = this.hour;}
	if(m==null){m = this.minute;}
	if(s==null){s = this.sec;}
	if(fmt==null){fmt = this.dateFmt;}
	var sDate = fmt.replace(/%[Yy]/,this._doStr(Y,4)).replace(/%[M]/,this._doStr(M,2)).replace(/%[Dd]/,this._doStr(D,2));
	if(this.showTime){
		sDate = sDate.replace(/%[Hh]/,this._doStr(h,2)).replace(/%[m]/,this._doStr(m,2)).replace(/%[Ss]/,this._doStr(s,2));
	}
	return sDate;
};
WdatePicker.prototype._doStr = function(s,len){
	s = s + '';
	for(var i=s.length; i<len; i++){
		s ='0' + s;
	}
	return s;
};
WdatePicker.prototype._splitDate = function (sDate) {
	/* 将datetime -> date */
	if(sDate.indexOf(' ')!=-1){sDate = sDate.substring(0,sDate.indexOf(' '));}
	var s = sDate.split(/\W+/);
	if(s.length>=3 && this._isDate(s[0]+'/'+s[1]+'/'+s[2])){
		return {'year':parseInt(s[0],10),'month':parseInt(s[1],10),'date':parseInt(s[2],10)};
	}
	else{
		alert('日期范围格式错误\nInvalid MINDATE or MAXDATE\nFormat:YYYY-MM-DD or YYYY/MM/DD');
		return ;
	}
};
/* 设置realvalue属性 */
WdatePicker.prototype._setRealValue = function (Y,M,D,h,m,s) {
	if(this.showTime){
		this.eCont.setAttribute("REALVALUE",this._returnDateStr(Y,M,D,h,m,s,'%Y-%M-%D %h:%m:%s'));
	}
	else{
		this.eCont.setAttribute("REALVALUE",this._returnDateStr(Y,M,D,null,null,null,'%Y-%M-%D'));
	}
};
/* 验证日期 */
WdatePicker.prototype._isDate = function (sDate) {	
	return sDate.match(/^((\d{2}(([02468][048])|([13579][26]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|([1-2][0-9])))))|(\d{2}(([02468][1235679])|([13579][01345789]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\s(((0?[0-9])|([1-2][0-3]))\:([0-5]?[0-9])((\s)|(\:([0-5]?[0-9])))))?$/); 
};

WdatePicker.prototype._judgeCorrectDateTime = function (sDateTime) {	
	var Y,M,D,h,m,s;
	var v = sDateTime.split(/\W+/);
	var f = this.dateFmt.match(/%./g);
	for (var i=0; i<f.length; i++) {		
		if(f[i].toLowerCase() == '%y'){
			Y = Number(v[i]);
			if(isNaN(Y)){return false;}
		}			
		else if(f[i] == '%M'){
			M = Number(v[i]); 
			if(isNaN(M)){return false;}
		}
		else if(f[i].toLowerCase() == '%d'){
			D = Number(v[i]);
			if(isNaN(D)){return false;}
		}
		else if(f[i].toLowerCase() == '%h'){
			h = Number(v[i]);
			if(isNaN(h)){return false;}
		}
		else if(f[i] == '%m'){
			m = Number(v[i]);
			if(isNaN(m)){return false;}
		}
		else if(f[i].toLowerCase() == '%s'){
			s = Number(v[i]);
			if(isNaN(s)){return false;}
		}		
	}
	Y = (Y==undefined)?'2000':Y;
	M = (M==undefined)?'1':M;
	D = (D==undefined)?'1':D;
	/* 验证 年月日 时分秒 是否合法 */
	if( this._isDate(Y+'-'+M+'-'+D) && (h==undefined || (h>=0) && (h<=23)) && (s==undefined || (m>=0) && (h<=59)) &&(s==undefined || (s>=0) && (s<=59)) ){
		/* 如果数据是合法的则转换成符合设定格式的字符串 */
		this.eCont.value = this._returnDateStr(Y,M,D,h,m,s);		
		/* 验证范围是否正确 */
		if(((Y*10000+M*100+D*1)>=(this.minDate.year*10000+this.minDate.month*100+this.minDate.date*1))&&((Y*10000+M*100+D*1)<=(this.maxDate.year*10000+this.maxDate.month*100+this.maxDate.date*1))){
			return true;
		}
	}
	return false;
};

/* 创建容器的HTML */
WdatePicker.prototype._createPickerHTML = function () 
{
	var s = new __sb();
	/* 头部容器 */
	s.a("<div id=dpTitle>");
	/* 月份 */
	s.a("<div style='float:left;margin:2px'><div class='ymsel'></div>"+dpcfg.monthStr+"<input class='yminput' style='width:40px;' maxlength=2 value="+this.month+"></div>");
	/* 年份 */
	s.a("<div style='float:right;margin:2px'><div class='ymsel'></div>"+dpcfg.yearStr+"<input class='yminput' style='width:50px;' maxlength=4 value="+this.year+"></div></div>");
	/* 星期 天数 */
	s.a("<div></div>");		//dDiv
	/* 时间 */
	s.a("<div>");
	s.a(this._createTimeTable());
	s.a("</div>");
	return s.j();
};

WdatePicker.prototype._createTimeTable = function () {
	var s = new __sb();
	s.a("<div id=dpTime style='" + ((this.showTime)?'':'display:none;') + "float:left;margin-top:3px'><table cellspacing=0 cellpadding=0 border=0><tr><td rowspan=2><span id=dpTimeStr>"+this.timeStr+"</span>");
	s.a(" <input class=tB maxlength=2 value="+this.hour+"><input value=':' class=tm readonly>");
	s.a("<input class=tE maxlength=2 value="+this.minute+"><input value=':' class=tm readonly>");
	s.a("<input class=tE maxlength=2 value="+this.sec+"></td><td>");
	s.a("<button id=dpTimeUp></button></td></tr><tr><td><button id=dpTimeDown></button></td></tr></table></div>");	
	s.a("<div style='float:right;margin-top:3px;text-align:right'>");
	s.a("<input id=dpOkInput type=button style='height:20px;width:90%'></input>");
	s.a("</div>");
	return s.j();
};

WdatePicker.prototype._setOkInput = function(){
	var d=$d.obj;
	if(d.eCont.value == ""){
		if(((this.t_year*10000+this.t_month*100+this.t_date*1)>=(this.minDate.year*10000+this.minDate.month*100+this.minDate.date*1))&&((this.t_year*10000+this.t_month*100+this.t_date*1)<=(this.maxDate.year*10000+this.maxDate.month*100+this.maxDate.date*1))){
			$d.okInput.onclick = function(){var d=$d.obj;d.pickDate(d.t_year,d.t_month,d.t_date,d.t_hour,d.t_minute,d.t_sec);};
		}
		else{
			$d.okInput.disabled = "disabled";
		}
		$d.okInput.value = d.todayStr + ((d.showTime)?"":(" "+d._doStr(d.t_year,4)+'-'+d._doStr(d.t_month,2)+'-'+d._doStr(d.t_date,2)));
	}
	else{
		$d.okInput.onclick = function(){$d.obj.pickDate();};
		$d.okInput.value = d.okStr;
	}
};

WdatePicker.prototype._createDateTable = function () {
	var tempYear,tempMonth;
	if((this.year*100+this.month*1)<(this.minDate.year*100+this.minDate.month*1)){
		/* 比最小日期小 */
		this.dd.yInput.value = tempYear = this.minDate.year;
		this.dd.mInput.value = tempMonth = this.minDate.month;
	}
	else if((this.year*100+this.month*1)>(this.maxDate.year*100+this.maxDate.month*1)){
		/* 比最大日期大 */
		this.dd.yInput.value = tempYear = this.maxDate.year;
		this.dd.mInput.value = tempMonth = this.maxDate.month;
	}
	else{
		tempYear = this.year;
		tempMonth = this.month;
	}
	var firstDay,firstDate,lastDay,lastDate;
	var s = new __sb();
	var i,j,k;
	firstDay = new Date(tempYear,tempMonth-1,1).getDay();
	firstDate = 1 - firstDay;
	lastDay = new Date(tempYear,tempMonth,0).getDay();
	lastDate = new Date(tempYear,tempMonth,0).getDate();
	s.a("<table id=dpDayTable width=100% border=0 cellspacing=0 cellpadding=0>");
	/* 星期 */
	s.a("<tr id=dpWeekTitle align=center>");
	var ss = new Array();
	for(i=0; i<7; i++){s.a("<td>" + this.aWeekStr[i] + "</td>");}
	/* 天数 */
	var classStr = '';
	var chassOnStr = '';
	var isThisMonth = ((tempYear==this.t_year)&&(tempMonth==this.t_month));
	var isSelMonth = ((tempYear==this.s_year)&&(tempMonth==this.s_month));
	var needCompareMinDate = ((tempYear*100+tempMonth*1)==(this.minDate.year*100+this.minDate.month));
	var needCompareMaxDate = ((tempYear*100+tempMonth*1)==(this.maxDate.year*100+this.maxDate.month));
	var needCompareBoth = needCompareMinDate&&needCompareMaxDate;
	var isValidDate = !needCompareMinDate && !needCompareMaxDate;
	for (i=1,j=firstDate; i<7; i++)	{
		s.a("<tr>");
		for (k=0; k<7; k++){
			if(j>=1 && j<=lastDate){
				if(isSelMonth && (j==this.s_date)){
					/* 选中的那天 */
					classStr = 'Wselday';
				}
				else if(isThisMonth && (j==this.t_date)){
					/* 今天 */
					classStr = 'Wtoday';
				}
				else{
					classStr = ((this.highLineWeekDay&&(k==0 || k==6))?'Wwday':'Wday');
				}				
				classOnStr = ((this.highLineWeekDay&&(k==0 || k==6))?'WwdayOn':'WdayOn');
				s.a("<td align=center ");
				if(isValidDate || (!needCompareMaxDate&&((needCompareMinDate && j>=this.minDate.date) || (needCompareMaxDate && j<=this.maxDate.date))) || (needCompareMaxDate&&(j>=this.minDate.date)&&(j<=this.maxDate.date))){
					s.a("onclick=\"$d.obj.pickDate(null,null," + j + ");\" ");
					s.a("onmouseover=\"this.className='" + classOnStr + "'\" ");
					s.a("onmouseout=\"this.className='" + classStr + "'\" ");	
				}
				else{
					classStr = 'WinvalidDay';
				}
				s.a("class=" + classStr);
				s.a("><span>" + j + "</span>");
			}
			else{
				s.a("<td><span></span>");
			}
			j++;
			s.a("</td>");
		}
		s.a("</tr>");
	}
	s.a("</table>");
	return s.j();
};

WdatePicker.prototype._setPubVar = function () {	
	this.top.$d = this.top.document.dateDiv;
	$d = this.top.$d;
};

WdatePicker.prototype.redraw = function () {	
	this.year = this.dd.yInput.value;
	this.month = this.dd.mInput.value;
	this.dd.dDiv.innerHTML = this._createDateTable();
};

WdatePicker.prototype.pickDate = function(Y,M,D,h,m,s){
	if(Y == null){Y = this.dd.yInput.value;}
	if(M == null){M = this.dd.mInput.value;}
	if(D == null){D = this.date;}
	this.year = Y;this.month = M;this.date=D;
	if(this.showTime){
		if(h == null){h = this.dd.hhInput.value;}
		if(m == null){m = this.dd.mmInput.value;}
		if(s == null){s = this.dd.ssInput.value;}	
		this.hour=h;this.minute=m;this.sec=s;
		this.eCont.value = this._returnDateStr(Y,M,D,h,m,s);
	}
	else{
		this.eCont.value = this._returnDateStr(Y,M,D);
	}
	/* 为日期框添加REALVALUE属性 */
	this._setRealValue(Y,M,D,h,m,s);

	$d.obj._markValue(true);	
	this.dd.style.display = 'none';
	this.dd.ifr.style.display = 'none';
};

WdatePicker.prototype._markValue = function(bValue){
	if(bValue){
		this.eCont.className = this.eCont.className.replace(/ WdateFmtErr/,'');
	}
	else{
		//根据错误处理模式决定如何处理
		var tempMode = dpcfg.errDealMode;
		while(true)	{
			switch(tempMode){
				case 0://提示
					if(!confirm(dpcfg.errAlertMsg)){
						tempMode = 2;
						continue;
					}
				case 1://自动纠正
					if(this.eCont.getAttribute("REALVALUE")){
						this._judgeCorrectDateTime(this.eCont.getAttribute("REALVALUE"));
					}else{
						this.eCont.value = "";
					}
					this.eCont.className = this.eCont.className.replace(/ WdateFmtErr/,'');
					break;
				case 2://标记
					this.eCont.className = this.eCont.className.replace(/ WdateFmtErr/,'');
					this.eCont.className = this.eCont.className.replace(/Wdate/,'Wdate WdateFmtErr');
					break;
			}
			break;
		}
	}
};

/* FireFox 扩展 */
if(navigator.product == 'Gecko')
{
	Window.prototype.__defineGetter__("screenLeft",function(){		
       return this.screenX+(this.outerWidth-this.innerWidth);
       });
	
	Window.prototype.__defineGetter__("screenTop",function(){		
       return screenY+(window.outerHeight-window.innerHeight);
       });
	Document.prototype.attachEvent = function(sType,fHandler){
		var shortTypeName=sType.replace(/on/,"");
		fHandler._ieEmuEventHandler=function(e){
			window.event=e;	return fHandler();
		};
		this.addEventListener(shortTypeName,fHandler._ieEmuEventHandler,false);
	};
	Document.prototype.createStyleSheet = function(cssPath){
		var head = document.getElementsByTagName('HEAD').item(0); 
		var style = document.createElement('link'); 
		style.href = cssPath; 
		style.rel = 'stylesheet';
		style.type = 'text/css';
		head.appendChild(style);
	};
	Event.prototype.__defineSetter__("returnValue",function(value){
		if(!value){this.preventDefault();}	return value;});
		Event.prototype.__defineGetter__("srcElement", function() {
		    var node = this.target;
		    // altered by Tony Pan at 2009-6-5
		    while (node != null && node.nodeType != 1) { node = node.parentNode; } 
		    return node;
		});
	Node.prototype.replaceNode=function(Node){	this.parentNode.replaceChild(Node,this);};
	Node.prototype.removeNode=function(removeChildren){		
			if(removeChildren){
				return this.parentNode.removeChild(this);}
			else{
				var range=document.createRange();
				range.selectNodeContents(this);
				return this.parentNode.replaceChild(range.extractContents(),this);
			}		
	};
   HTMLElement.prototype.__defineSetter__("outerHTML",function(sHTML){
       var r=this.ownerDocument.createRange();
       r.setStartBefore(this);
       var df=r.createContextualFragment(sHTML);
       this.parentNode.replaceChild(df,this);
       return sHTML;
       });
   
	HTMLElement.prototype.__defineGetter__("outerHTML",function(){
		var attr;
		var attrs=this.attributes;
		var str="<"+this.tagName;
		for(var i=0;i<attrs.length;i++){
    		attr=attrs[i];
			if(attr.specified){
				str+=" "+attr.name+'="'+attr.value+'"';
			} 
		}
		if(!this.canHaveChildren){
			return str+">";
		}
		return str+">"+this.innerHTML+"</"+this.tagName+">";
	});
   
	HTMLElement.prototype.__defineGetter__("parentElement",function(){
		if(this.parentNode==this.ownerDocument){return null;}
		return this.parentNode;
	});

	HTMLElement.prototype.attachEvent = function(sType,fHandler)
	{
       var shortTypeName = sType.replace(/on/,"");
       fHandler._ieEmuEventHandler = function(e){
		   window.event=e;return fHandler();
       };
       this.addEventListener(shortTypeName,fHandler._ieEmuEventHandler,false);
    };
	
	HTMLElement.prototype.insertAdjacentElement=function(where,parsedNode){
       switch(where){
           case "beforeBegin":
               this.parentNode.insertBefore(parsedNode,this);
               break;
           case "afterBegin":
               this.insertBefore(parsedNode,this.firstChild);
               break;
           case "beforeEnd":
               this.appendChild(parsedNode);
               break;
           case "afterEnd":
               if(this.nextSibling){
                   this.parentNode.insertBefore(parsedNode,this.nextSibling);
			   }
               else{
                   this.parentNode.appendChild(parsedNode);
			   }
               break;
           }
       };
	HTMLElement.prototype.getBoundingClientRect = function(){
		var obj = this;
		var top = obj.offsetTop;     
		var left = obj.offsetLeft; 
		var right = obj.offsetWidth; 
		var bottom = obj.offsetHeight; 
		while( obj = obj.offsetParent ) {  			
			if ( obj.style.position=='absolute' || obj.style.position=='relative' || ( obj.style.overflow!='visible' && obj.style.overflow!= '') ) { 
				break; 
			}  
			top += obj.offsetTop; 
			left += obj.offsetLeft; 
		}		
		left -= document.body.scrollLeft;
		top  -= document.body.scrollTop;
		right += left;
		bottom += top;
		return {'left':left,'top':top,'right':right,'bottom':bottom};
	}	
	HTMLIFrameElement.prototype.__defineGetter__("Document",function(){return this.contentDocument});
}

/* 获得浏览器可用尺寸 */
function $getClientWidthHeight(win)
{
	var cw = win.document.body.clientWidth;
	var ch = win.document.body.clientHeight;
	//alert(cw+'  '+ch);
	return {'width':cw, 'height':ch};
}

function $getAbsM(topWin)
{
	if(topWin==null){topWin=top;}
	var leftM = 0;	var topM  = 0;
	var tempWin = window;	
	while(tempWin!=topWin){
		var ifs = tempWin.parent.document.getElementsByTagName('iframe');
		for(var i=0; i<ifs.length; i++){
			/* 在IE中子框架不能操作同级子框架的document,所以加上try */
			try{
				if(ifs[i].Document == tempWin.document){
					var rc = ifs[i].getBoundingClientRect();
					leftM += rc.left;
					topM  += rc.top;
					break;
				}
			}
			catch(e){continue;}				
		}
		tempWin = tempWin.parent;		
	}
	return {'leftM':leftM,'topM':topM};
}

function disposeDatePicker(){
	if($d!=undefined && $d.obj!=undefined && $d.obj.eCont != window.event.srcElement && $d.style.display != 'none')
	{
		var x = event.clientX;
		var y = event.clientY;							
		var rc = $d.getBoundingClientRect();
		if(x < rc.left || x > rc.right || y < rc.top || y > rc.bottom){
			/* 判断日期是否有误 */
			if( $d.obj.eCont.value == '' || $d.obj._judgeCorrectDateTime($d.obj.eCont.value) ){
				/* 标记正确 */
				$d.obj._markValue(true);
				if( $d.obj.eCont.value != ''){
					$d.obj._initDate($d.obj.eCont.value,$d.obj.dateFmt);
					/* 为日期框添加REALVALUE属性 */
					$d.obj._setRealValue();
				}
				else{
					/* 空值时清空REALVALUE属性 */
					$d.obj.eCont.setAttribute("REALVALUE","");
				}
			}
			else{
				/* 标记错误 */
				$d.obj._markValue(false);
			}
			$d.yDiv.style.display = $d.mDiv.style.display = 'none';
			$d.ifr.style.display = 'none';
			$d.style.display = 'none';
		}
		else{
			$d.yDiv.style.display = $d.mDiv.style.display = 'none';
		}	
	}
}

/* 添加销毁选择日期事件 */
document.attachEvent('onmousedown',disposeDatePicker);