/**
 * countDown (Version 1.2)
 * @author lv ming (akm107@163.com)
 *
 * Create a countDown
 * @example var countDown=new CountDown('endTime'[,showTime,startTime]);
 * 			countDown.init('#day','#hour','#minute','#second'[,function(){endFucCode},function(){beforeFucCode}]);
 * @desc select DOM on Jquery , Time(day/month/year[ hour:minute:second]):'17/7/2010[ 00:00:00]'
 */

function CountDown(endTime,showTime,startTime){
	var eTime=new Date(endTime).getTime();
	var sTime=new Date(startTime).getTime()||new Date().getTime();
	this.sTime=sTime;
	this.leftTime=parseInt((eTime-sTime)/1000,10);
	this.showTime=new Date(showTime).getTime();
	}
CountDown.prototype={
	_pad:function(num,n){
		var len = num.toString().length;
		while (len < n) {
			num = "0" + num;
			len++;
		}
		return num;
	},
	_format:function(leftTime){
		return {
			d:parseInt(leftTime/3600/24,10),
			h:this._pad(parseInt(leftTime/3600%24,10),2),
			m:this._pad(parseInt(leftTime/60%60,10),2),
			s:this._pad(parseInt(leftTime%60,10),2)
		};
	},
	init:function(day,hour,minute,second,endFuc,beforeFuc){
		var _this=this;
		var leftTime=this.leftTime;
		if(_this.showTime > _this.sTime) {
			if(beforeFuc){
				beforeFuc();
			}
			return;
		}
		var calculagraph = function(){
			if (leftTime >= 0) {
				var format = _this._format(leftTime);
				var d = $(day)[0];//document.getElementById(day);
				var h = $(hour)[0];//document.getElementById(hour);
				var m = $(minute)[0];//document.getElementById(minute);
				var s = $(second)[0];//document.getElementById(second);
				if(format.h==23&&format.m==59&&format.s==59||h.innerHTML==00&&m.innerHTML==00&&s.innerHTML==00||d.innerHTML==''){
					d.innerHTML = format.d;
				}
				if(format.m==59&&format.s==59||h.innerHTML==00&&m.innerHTML==00&&s.innerHTML==00||h.innerHTML==''){
					h.innerHTML = format.h;
				}
				if(format.s==59||m.innerHTML==00&&s.innerHTML==00||m.innerHTML==''){
					m.innerHTML = format.m;
				}
				s.innerHTML = format.s;
				leftTime--;
				setTimeout(function(){calculagraph();}, 1000);
			}else{
				if(endFuc){
					endFuc();
				}
			}
		};
		calculagraph();
	}
};