
var easyUI = {
	fpbind:function()
	{
		if(!Function.prototype.bind)
		{
			Function.prototype.bind = function(obj)
			{
				//alert("点击了日历面板！");
				var owner = this,args = Array.prototype.slice.call(arguments),callobj = Array.prototype.shift.call(args);
				return function(e){e=e||top.window.event||window.event;owner.apply(callobj,args.concat([e]));};
			};
		}
	}(),
	getElementsBy:function(att,svalue,stag,dmodule)
	{
		var rd = [];
		if(!att||!svalue||!stag||!dmodule){return rd;}
		var tmpd = dmodule.getElementsByTagName(stag),tmpdl = tmpd.length;
		if(!tmpdl){return rd;}
		if(att=='class'&&(/msie[67]/i).test(navigator.appVersion.replace(/\s/g,''))){att='classname'}
		var satt = null,rxp = new RegExp("("+svalue+")","i");
		for(var i=0;i<tmpdl;i++){
			satt = tmpd[i].getAttribute(att);
			if(satt&&rxp.test(satt)){
				rd.push(tmpd[i]);
				rxp.lastIndex = -1;
			}
		}
		return rd;
	},
	getPosition:function(){
		return document.documentElement.getBoundingClientRect && function(o){
			var pos = o.getBoundingClientRect(), root = o.ownerDocument || o.document;
			return {x:pos.left+root.documentElement.scrollLeft,y:pos.top+root.documentElement.scrollTop};
		} || function(o){
			var x = 0, y = 0;
			do{x += o.offsetLeft;y += o.offsetTop;}while((o=o.offsetParent));
			return {'x':x,'y':y};
		};
	}(),
	setPosition:function(obj,x,y){
		obj.style.left = x + "px";
		obj.style.top = y + "px";
	},
	getStyle:function(dom,stylename){
		if(dom.currentStyle){
			return dom.currentStyle[stylename];
		}else{
			return window.getComputedStyle(dom,null).getPropertyValue(stylename);
		}
	},
	contains:function(f,c){
		if(f==null){return false;}
		var bCB2F = false;
		if(f.contains){bCB2F = f.contains(c);}else{bCB2F = (f.compareDocumentPosition(c)==20)?true:false;}
		return bCB2F;
	},
	getTarget:function(e){
		e = e||window.event;
		return e.srcElement||e.target;
	},
	stopEvent:function(e){
		e = e||window.event;
		if(e.stopPropagation){e.stopPropagation();}else{e.cancelBubble = true;}
		if(e.preventDefault){e.preventDefault();}else{e.returnValue = false;}
	},
	doWhileExist:function(sModuleId,oFunction){
        if(document.getElementById(sModuleId)){oFunction(document.getElementById(sModuleId));}
    }
};

var EasyCalendar = function(){
	//直接通过控件apply，所有属性都写在控件上
	this.perWidth = 180;//单列宽度
	this.perHeight = 180;//单列高度
	this.year = new Date().getFullYear();//当前年
	this.month = (new Date().getMonth()+1);//当前月
	this.day = new Date().getDate();//当前日
	this.cyear = this.year;//选中年
	this.cmonth = this.month;//选中月
	this.cday = null;//选中日
	this.pformat = null;//输入格式
	this.pTotalShow = 1;//总计要显示几个月的数据
	this.pExtendir = 6;//扩展显示的方向，6右侧，2下方
	this.scrollMonthAble = true;//是否可以滚动月份
	this.scrollYearAble = true;//是否可以滚动年
	this.pickStart = null;//可以选择的起始日期，此日期之前的所有时间都不可选
	this.pickEnd = null;//可以选择的结束日期，此日期之后的所有时间都不可选
	this.timer = null;
	this.showPanel = function()
	{//开启面板
		var pos = easyUI.getPosition(this);
		if(this.panel&&this.panel.isOpen){return false;}//如果面板已开启则返回
		var sv = new Date(this.value.replace(/\D/g,'/'));
		if(!isNaN(sv)){
			this.year = this.cyear = sv.getFullYear();
			this.month = this.cmonth = sv.getMonth()+1;
			this.day = this.cday = sv.getDate();
		}else{
			var rv = (this.pickStart.constructor==Function)?this.pickStart():this.pickStart;
			this.year = (rv&&rv.getFullYear)?rv.getFullYear():this.year;
			this.month = (rv&&rv.getMonth)?rv.getMonth()+1:this.month;
		}
		this.showCalendar(this.year,this.month);
		this.panel.style.left = pos.x+'px';
		var py = pos.y,ih = (this.pTotalShow>1&&this.pExtendir==2)?this.pTotalShow*this.perHeight:this.perHeight,ch = document.documentElement.clientHeight,st = document.documentElement.scrollTop,oh = this.offsetHeight;
		var y = (py-st+ih>ch&&py-st>ih)?pos.y-oh-ih:py+oh;
		this.panel.style.top = y+'px';
		this.panel.open();
		this.focus();
	};
	this.closePanel = function(){//关闭面板
		if(!this.panel.isOpen){return false;}
		this.timer = window.setTimeout(this.panel.close.bind(this.panel),200);
	};
	this.onclick = this.showPanel;
	this.onfocus = this.showPanel;
	this.onblur = this.closePanel;
	this.getToday = function(){
		var d = new Date();
		return new Date(d.getFullYear()+'/'+(d.getMonth()+1)+'/'+d.getDate());
	};
	this.getDays = function(y,m){//取某年某月有多少天 
		return new Date(y,m,0).getDate();//y,m,0 修复Chrome
	};
	this.getDaysList = function(y,m){//取某年某月所有天数的排列
		y = y?y:this.year;
		m = m?m:this.month;
		var days = this.getDays(y,m)+1,sd = this.pickStart,ed = this.pickEnd,sf = this.pformat;
		sd = (sd.constructor==Function)?sd():sd;
		ed = (ed.constructor==Function)?ed():ed;
		var ad = [],tnd = null,tmpDate =0,tmpD = 0,tmpS = '',fd = new Date(y+'/'+m+'/1').getDay();
		for(var i=0;i<7;i++){ad[i] = [];}
		for(var n=1;n<days;n++){
			tnd = new Date(y+'/'+m+'/'+n);
			tmpDate = tnd.getDate();
			tmpD = tnd.getDay();
			tmpT = sf.replace(/y/i,y).replace(/m/i,m).replace(/d/i,tmpDate);
			tmpS = (sd>tnd||ed<tnd)?'style="line-height:20px;color:#A9AA98;"':'style="line-height:20px;" title="'+tmpT+'" year="'+y+'" month="'+m+'"';
			ad[tmpD].push('<li class="'+y+'-'+m+'-'+tmpDate+'-" '+tmpS+'>'+n+'</li>');
		}
		if(fd>0){for(var m=0;m<fd;m++){ad[m].unshift('<li style="line-height:20px;">&nbsp;</li>');}}
		return ad.slice(0);
	};
	this.getCalendar = function(y,m){//取日历数据
		y = y?y:this.year;
		m = m?m:this.month;
		var list = this.getDaysList(y,m);
		var slist = [];
		var dlist = ['日','一','二','三','四','五','六'];
		for(var i=0;i<7;i++){
			slist.push('<ul style="float:left;margin:0;padding:0;list-style:none;width:25px;text-align:center;"><li style="line-height:20px;border-bottom:1px solid #ABA899;color:#0054E5;margin-bottom:5px;">'+dlist[i]+'</li>'+list[i].join('')+'</ul>');
		}
		var sf = (this.pTotalShow>1&&this.pExtendir==6)?'float:left;':'';
		var rs = '<div style="width:'+this.perWidth+'px;'+sf+'"><div style="line-height:25px;font-weight:bold;color:#D8E4F8;background:#7A96DF;margin:1px;text-align:center;"><span>'+y+'年'+m+'月</span></div><div style="margin:0 auto;width:175px;overflow:hidden;zoom:1;">'+slist.slice(0).join('')+'</div></div>';
		list = slist = dlist = null;
		return rs;
	};
	this.showCalendar = function(y,m){//展示日历 
		y = y?y:this.year;
		m = m?m:this.month;
		this.year = y;
		this.month = m;
		var nd = new Date(),cday = this.cyear+'-'+this.cmonth+'-'+this.cday+'-',today = nd.getFullYear()+'-'+(nd.getMonth()+1)+'-'+nd.getDate()+'-';
		var its = this.pTotalShow,sym = [];
		for(var i=0;i<its;i++){
			sym[i] = this.getCalendar(y,m);
			if(m<12){m++;}else{y++;m=1;}
		}

		this.panel.contentArea.innerHTML = sym.join('');

		var dcday = easyUI.getElementsBy('class',cday,'li',this.panel.contentArea),dtoday = easyUI.getElementsBy('class',today,'li',this.panel.contentArea);
		if(dcday.length){dcday[0].style.background = '#5487D8';dcday[0].style.color = '#fff';}
		if(dtoday.length){dtoday[0].style.color = '#f00';}
	};
	this.pickContent = function(e){//点击日历面板事件
		window.clearTimeout(this.timer);
		var dtarg = easyUI.getTarget(e);
		var stag = dtarg.tagName;
		var sv = dtarg.innerHTML; 
		var st = dtarg.getAttribute('title'); 
		switch(stag){
			case 'EM'://换月
				var m = (sv=='&lt;')?--this.month:++this.month;
				if(m==0){this.year--;this.month=12;}
				if(m>12){this.year++;this.month=1;}
				this.showCalendar();
				this.focus();
				break;
			case 'STRONG'://换年
				(sv=='&lt;&lt;')?--this.year:++this.year;
				this.showCalendar();
				this.focus();
				break;
			case 'LI'://选定日期
				if(isNaN(parseInt(sv,10))||!st){return false;}
				this.cyear = dtarg.getAttribute('year');
				this.cmonth = dtarg.getAttribute('month');
				this.cday = sv; 
				/*
				if(this.pformat.indexOf('-')!=-1)
				{  
					var stem_=st.split('-');
					var str=st;
					if(stem_[1].length==1||stem_[2].length==1)	
					{
						str=stem_[0];
						if(stem_[1].length==1)
							str=str+'-0'+stem_[1];
						else
							str=str+'-'+stem_[1];
						if(stem_[2].length==1)
							str=str+'-0'+stem_[2];
						else
							str=str+'-'+stem_[2];
					} 
					st=str; 
				}
				if(this.pformat.indexOf('/')!=-1&&this.pformat=='y/m/d')
				{ 
					var stem_=st.split('/');
					var str=st;
					if(stem_[1].length==1||stem_[2].length==1)	
					{
						str=stem_[0];
						if(stem_[1].length==1)
							str=str+'/0'+stem_[1];
						else
							str=str+'/'+stem_[1];
						if(stem_[2].length==1)
							str=str+'/0'+stem_[2];
						else
							str=str+'/'+stem_[2];
					}
					st=str; 
				}
				if(this.pformat.indexOf('/')!=-1&&this.pformat=='m/d/y')
				{ 
					var stem_=st.split('/');
					var str=st;
					alert("str="+str);
					if(stem_[0].length==1||stem_[1].length==1)	
					{
						alert('----');
						str="";
						if(stem_[0].length==1)
							str='0'+stem_[0];
						else
							str=stem_[0];
						if(stem_[1].length==1)
							str=str+'/0'+stem_[1];
						else
							str=str+'/'+stem_[1];
						str=str+'/'+stem_[2];
					}
					st=str; 
				} */ 
				this.value = st;    
				//--选着一个日历后弹出后面的一个日历(cjf添加)**************
				var nexthand=this.getAttribute('nexthand');
				//是否需要弹出第二个日历框
				var neednext=this.getAttribute('isneed');
				//alert(neednext);
				//当前日历框点击后他还有结束日期
				if(nexthand!=null&&neednext!=null&&neednext=='Y')
				{
					//alert("初始化第二个。");
					document.getElementById(nexthand).showPanel();
				}
				//--************************************************
				this.panel.close();
				break;
			case 'DIV'://关闭区域
				if(/close/i.test(sv)){this.panel.close();}
				break;
			case 'SPAN'://清除区域
				this.value="";
				this.panel.close();
				break;
			default:
				this.focus();
				break;
		}
	};
	this.checkDate = function(){//检查日期格式
		var cs = this.value;
		if(!cs.replace(/\s/g,'')){return true;}
		//y-m-d  y/m/d m/d/y 分别匹配出ymd所在位置，判断实际值各个位置值是否匹配
		var sf = this.pformat,fsp = sf.substr(1,1);
		var sy = sf.indexOf('y'),sm = sf.indexOf('m'),sd = sf.indexOf('d');
		if(sy==-1||sm==-1||sd==-1){sy=1;sm=3;sd=5;}
		sy = parseInt(sy/2);
		sm = parseInt(sm/2);
		sd = parseInt(sd/2);
		var mp = cs.match(/(\d+)(?=\D?)/g);
		var msp = cs.replace(/\d/g,'').substr(0,1);
		if(!mp||mp.length!=3){this.value=sf;return false;};
		var mpsy = mp[sy],mpsm = mp[sm],mpsd = mp[sd];
		if(mpsy.length>4||parseInt(mpsy)<1000){this.value=sf;return false;}
		if(mpsm.length>2||parseInt(mpsm)<1||parseInt(mpsm)>12){this.value=sf;return false;}
		if(mpsd.length>2||parseInt(mpsd)<1||parseInt(mpsd)>31){this.value=sf;return false;}
		if(msp!=fsp){this.value=sf;return false;}
		this.value = mp.join(fsp);
		return true;
	};
	this.extfoo = {//自定义属性方法
		beforeDom:function(id){if(!id){return 'InvalieDate';}else{var d = document.getElementById(id);if(!d){return 'InvalieDate';}else{return function(){var dv = new Date(d.value.replace(/\D/g,'/'));if(!isNaN(dv)){return dv;}else{var nd = new Date();return 'InvalieDate';}}}}},
		afterDom:function(id){if(!id){return 'InvalieDate';}else{var d = document.getElementById(id);if(!d){return 'InvalieDate';}else{return function(){var dv = new Date(d.value.replace(/\D/g,'/'));if(!isNaN(dv)){return dv;}else{var nd = new Date();return new Date(nd.getFullYear()+'/'+(nd.getMonth()+1)+'/'+nd.getDate());}}}}},
		today:function(){var d = new Date();return new Date(d.getFullYear()+'/'+(d.getMonth()+1)+'/'+d.getDate());},
		daysLater:function(n){n=(isNaN(n))?1:parseInt(n,10);var sd = new Date(this.pickStart);if(!isNaN(sd)){sd.setDate(sd.getDate()+n);return sd;}else{var rv = new Date();rv.setDate(rv.getDate()+n);return rv;}},
		monthLater:function(n){n=(isNaN(n))?1:parseInt(n,10);var sd = new Date(this.pickStart);if(!isNaN(sd)){sd.setMonth(sd.getMonth()+n);return sd;}else{var rv = new Date();rv.setMonth(rv.getMonth()+n);return rv;}},
		yearsLater:function(n){n=(isNaN(n))?1:parseInt(n,10);var sd = new Date(this.pickStart);if(!isNaN(sd)){sd.setFullYear(sd.getFullYear()+n);return sd;}else{var rv = new Date();rv.setFullYear(rv.getFullYear()+n);return rv;}}
	};
	this.initpty = function()
	{//初始化属性
		var sf = this.getAttribute('format')||'y/m/d';
		this.pformat = sf;
		var sy = sf.indexOf('y'),sm = sf.indexOf('m'),sd = sf.indexOf('d'),sv = new Date(this.value.replace(/\D/g,'/'));
		if(sy==-1||sm==-1||sd==-1){alert('日期格式设置错误!\n仅支持：\ny-m-d\ny/m/d\nm/d/y');}
		var s = this.getAttribute('start'),ed = this.getAttribute('end'),ef = this.extfoo;
		if(s){s = s.replace(/fileopen/i,'');}
		var parseExtFoo = function(str)
		{
			if(!str){return 'InvalieDate';}
			var avr = str.match(/^(\w+)\(([^\)]*)\)$/i),avrName = avr?avr[1]:str,avrArgs = avr?avr[2]:null;
			var rv = (ef[avrName])?ef[avrName](avrArgs):new Date(avrName.replace(/\D/g,'/'));
			return rv;
		};
		this.pickStart = parseExtFoo(s);
		this.pickEnd = parseExtFoo(ed);
		this.pTotalShow = this.getAttribute('totalshow')||1;
		this.pExtendir = this.getAttribute('extendir')||6;
		if(!isNaN(sv))
		{
			this.year = this.cyear = sv.getFullYear();
			this.month = this.cmonth = sv.getMonth()+1;
			this.day = this.cday = sv.getDate(); 
		}
	};
	this.initPanel = function()
	{//初始化面板
		var ipw = this.perWidth,iph = this.perHeight,iw = (this.pTotalShow>1&&this.pExtendir==6)?ipw*2:ipw,ih = (this.pTotalShow>1&&this.pExtendir==2)?iph*2:iph;
		if(!this.panel)
		{
			this.panel = document.createElement('div');
			document.body.appendChild(this.panel);
			var fiw = parseInt(iw,10)+20,fih = parseInt(ih,10)+20;
			this.panel.style.cssText = 'position:absolute;left:0;top:0;padding:1px;visibility:hidden;overflow:hidden;background:#5487D8;';
			var lbtn = '<div style="position:absolute;left:5px;top:7px;z-index:2;cursor:pointer;"><strong style="border:1px outset;padding:0 3px;margin-right:2px;">&lt;&lt;</strong><em style="border:1px outset;padding:0 3px;margin-right:5px;">&lt;</em></div>';
			var rbtn = '<div style="position:absolute;right:5px;top:7px;z-index:2;cursor:pointer;"><em style="border:1px outset;padding:0 3px;margin-left:5px;">&gt;</em><strong style="border:1px outset;padding:0 3px;margin-left:2px;">&gt;&gt;</strong></div>';
			this.panel.innerHTML = '<div style="position:relative;font-family:arial;font-size:12px;width:100%;height:100%;overflow:visible;"><div></div><div>关闭(Close)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span>清除</span></div>'+lbtn+rbtn+'<iframe src="about:blank" style="position:absolute;z-index:-1;left:-10px;top:-10px;width:'+fiw+'px;height:'+fih+'px;overflow:hidden;-moz-opacity:0;opacity:0;filter:alpha(opacity=0);background:#5487D8;border:none;"></iframe></div>'; 
		} 
		this.panel.style.width = iw+'px';
		this.panel.contentArea = this.panel.childNodes[0].childNodes[0];
		this.panel.closeArea = this.panel.childNodes[0].childNodes[1];
		this.panel.contentArea.style.cssText = 'width:'+iw+'px;height:'+ih+'px;background:#fff;cursor:pointer;overflow:hidden;zoom:1;';
		this.panel.closeArea.style.cssText = 'width:100%;background:#D8E4F8;text-align:center;cursor:pointer;clear:both;';
		this.panel.isOpen = false;
		this.panel.open = function(callback){this.panel.style.visibility = 'visible';this.panel.isOpen = true;if(callback&&callback.constructor==Function){callback();}}.bind(this);
		this.panel.close = function(callback){if(this.checkDate()){this.panel.style.visibility = 'hidden';this.panel.isOpen = false;}if(callback&&callback.constructor==Function){callback();}}.bind(this);
		this.panel.onclick = this.pickContent.bind(this);
	};
	this.bind2handles = function()
	{//绑定调用对象
		var dHandles = this.getAttribute('handles')||null;
		if(!dHandles){return false;}
		var i = 0,dhs = dHandles.split(','),dhsl = dhs.length;
		for(;i<dhsl;i++)
		{ 
			document.getElementById(dhs[i]).onclick = this.showPanel.bind(this);
		}
	};
	this.init = function()
	{
		this.initpty();
		this.initPanel();
		//this.bind2handles();
	};
	this.init();
};