
// Left Pad Function
var padLeft = function (str, len, chr){
	if(!chr){
		chr = "0";
	}
	if(str.length >= len){
		return str;
	}

	do{
		str = chr + str;
	}while(str.length < len);

	return str;
};

/**
 * JavaScript CountDown
 * usage example:
 * 			var count1 = new jsCounter();
 *			count1.init( string_of_element_ID, start_number, ratePerSecond );
 *
 */
var jsCounter = (
	function(){
		function _class(){

			var _self = this;
			var currentCount, lastUpdate, targDiv, ratePerSecond, digits,
				ratePerSecond, currentCount, lastUpdate;

			var redrawFrequency = 220; // ms
			var digitLength = 14;


			/* Object METHODS */
			this.calcChange = function(){
				var currentMs = new Date().getTime();

				var newCount = _self.currentCount - (( currentMs - _self.lastUpdate ) * _self.ratePerSecond / 1000) ;

				var strNum = padLeft("" + newCount + "", _self.digitLength, '0');
				var max = _self.digits.length;

				// Update Digits
				for(var x=0;x < max; x+=1){
					_self.digits[x].innerHTML = strNum[x];
				}

				_self.redrawCounter();
				_self.lastUpdate = currentMs;
				_self.currentCount = newCount;

				if(newCount > 0){
					setTimeout( _self.calcChange, _self.redrawFrequency);
				}

			}; // end calcChange()

			this.redrawCounter = function(){
				this.digits.each(function(e){
					var i = parseInt(e.innerHTML,10);
					i = Math.max(0,(i * 10) + (i - 0.5));
					e.style.backgroundPosition = "center "+i+"%";
				});
			}; // end redraw()

			/* --- Initialization & Start Method --- */
			this.init = function(targDiv0,initNumber,countPerSecond){
				this.targDiv = targDiv0;

				this.currentCount = parseInt(initNumber);
				this.lastUpdate = new Date().getTime();
				this.ratePerSecond = countPerSecond;

				if(typeof targDiv0 == "string"){
					this.targDiv = $(targDiv0);
				}

				var strNum = padLeft("" + this.currentCount + "", this.digitLength, '0');

				// Insert Digits
				for(var x=0;x<strNum.length; x+=1){
					this.targDiv.insert("<div class='digit'>"+strNum[x]+"</div>");
				}

				this.digits = this.targDiv.childElements();

				this.redrawCounter();



				setTimeout( this.calcChange, this.redrawFrequency);
			}; // end init()

		}; // end _class

		return _class;
	}
)();

