/*
UvumiTools Odometer v1.0 http://tools.uvumi.com/odometer.html

Copyright (c) 2008 Uvumi LLC

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/

var UvumiOdometer = new Class({

	Implements:[Options,Events],
	
	options:{
		counterClass:'odometer',
		digits:6,
		image:'odometer/odometer.gif',
		imageIE:'',
		overlay:'odometer/overlay.png',
		startDuration:500,
		cruiseDuration:100,
		setAnimValDuration:500,
		setDevider:false,
		hasDecimal:false,
		language:'',
		currencyId:'',
		transition:'linear',
		onComplete:$empty,
		onSetAnimValueComplete:$empty,
		url:false,
		refreshRate:10/*,
		indicatorClass:'loading'*/
	},
	/* inits the name for the Element and the options, bind domreadyEvent */ 
	initialize:function(container,options){
		this.counter = container;
		this.setOptions(options);
		window.addEvent('domready',this.domReady.bind(this));
	},
	/* onDomReady: finds Element, and sets the Images */
	domReady:function(){
		this.counter = $(this.counter);
		this.image = new Asset.image(this.options.image,{
			onload:this.build.bind(this)
		});
	},
	
	/* 	gets the values for the counter (and the wheels)
		gets the number that is shown
		sets style for the counter
		gets the wheel-styles from the ADDNUMBER method
		sets the overlay
	 */
	build:function(){
		this.fullHeight = this.image.height;
		this.height = (this.fullHeight/10).toInt();
		this.width = this.image.width;
		var value = this.counter.get('html').clean().toInt();
		if(isNaN(value)){
			value=0;
		}
		/* styles for the counter (=container for the wheels) */
		/* 
			sets the Margin for a Devider-Sign (depending on the digits and 	
			if the Number shows digits after the decimal sign) 
		*/
		if(this.options.setDevider){
			var deviderMargin;
			if(this.options.hasDecimal && this.options.digits > 2){
				deviderMargin = (this.options.digits > 2)?1:0;
				deviderMargin += Math.floor((this.options.digits-2)/3);
			} 
			else if(this.options.digits > 3){
				deviderMargin = Math.floor((this.options.digits)/3);
			} 
		}
		
		this.counter.empty().setStyles({
			width:this.options.digits*this.width + 11*deviderMargin,
			height:this.height,
			overflow:'hidden',
			display:'block',
			position:(this.counter.getStyle('position')=='absolute'?'absolute':'relative')
		}).addClass(this.options.counterClass);
		//this.counter.set('title','Double-click on counter to directly jump to final value');
		this.numbers = [];
		for(var i=0;i<this.options.digits;i++){
			var number = this.addNumber();
			if(this.options.setDevider){
				if(this.options.hasDecimal){
					if(i==1)number.setStyle('margin-left','11px');
					if((i+2)%3 == 0)number.setStyle('margin-left','11px');
				}else{
					//alert(i);
					if((i+1)%3 == 0)number.setStyle('margin-left','11px');
				}	
			}
			number.inject(this.counter);
			this.numbers.push(number);
		}
		if(this.options.overlay){
			this.overlay = Element('div',{
				styles:{
					'position':'absolute',
					'top':0,
					'left':0,
					'width':'100%',
					'height':this.height,
					'font-size':0,
					'line-height':0,
					'background-image':'url('+this.options.overlay+')',
					'background-position':'left center'
				}
			}).inject(this.counter);
		}
		

		
		
		/* is used in the CONVERTNUMBER method */
		this.clear = new Element('br',{styles:{'clear':'right'}}).inject(this.counter);
		
		/* ANIMATION */
		this.animation = new Fx.Elements(this.numbers,{
			link:'chain',
			duration:this.options.startDuration,
			transition:this.options.transition,
			onStart:function(){
				
				//console.log(this.numbers);
				
				this.animating=true;		
				this.currentCount = this.currentCount + (this.direction?1:-1);
				if(this.step<=this.mid){
					//this.animation.options.duration = (this.options.startDuration-(1-Math.exp(-this.step))*this.durationVariation).toInt();
					this.step++;
				}else{
					this.step++;
					//this.animation.options.duration = (this.options.startDuration-(1-Math.exp(this.step-2*this.mid))*this.durationVariation).toInt();
				}
				
			}.bind(this),
			onChainComplete:function(){
				this.animating=false;
				this.fireEvent('onComplete',this.value);
				(function(){this.refreshed=false;}).delay(this.options.refreshRate*1000,this);
			}.bind(this)
		});
			

		this.durationVariation=this.options.startDuration - this.options.cruiseDuration;
		this.spins = [];
		
		this.setValue(value);
		/*--------- anim ------------*/ 
		

		if(this.options.url){
			if(this.options.indicatorClass){
				this.indicator=new Element('div',{
					'class':this.options.indicatorClass
				})
			}
			this.request = new Request({
				url:this.options.url,
				autoCancel:true,
				onComplete:function(response){
					var value = response.toInt();
					this.countTo(value);
					if(this.indicator){
						(function(){this.indicator.dispose()}).delay(1000,this);
					}
				}.bind(this)
			});
			this.refreshed=true;
			$(document.body).addEvent('mousemove',this.refresh.bind(this));
			(function(){this.refreshed=false;}).delay(this.options.refreshRate*1000,this);
		}
		
		/*this.counter.addEvent('dblclick',this.override.bind(this));*/
	},
	
	/* sets the style for one single number and returns it to the BUILD-method */
	addNumber:function(){
		if(!Browser.Engine.trident4){
			return number = new Element('div',{
				styles:{
					width:this.width,
					height:this.height,
					'font-size':0,
					'line-height':0,
					'float':'right',
					'background-image':'url('+this.options.image+')',
					'background-position':'bottom center'
				}
			});
		}else{
			return number = new Element('div',{
				styles:{
					width:this.width,
					height:this.height,
					'font-size':0,
					'line-height':0,
					'float':'right',
					'background':'transparent',
					'background-image':'url('+this.options.imageIE+')',
					'background-position':'bottom center'
				}
			});
		}
	},
	
	/* sets the value for the first display odometer */
	/*after this the COUNTTO can be called*/
	setValue:function(value){
		if(isNaN(value)){
			return false;
		}
		value = value.toInt();
		if(value<0){
			value=0;
		}
		this.value = value;
		this.currentCount = value;
		this.convertNumber();
		for(var i=0;i<this.options.digits;i++){
			this.numbers[i].setStyle('background-position',this.getCoord(this.spins[i]));
		}
	},
	
	setAnimValue:function(value){
		this.setValue(this.value);
		
		if(isNaN(value)){
			return false;
		}
		value = value.toInt();
		if(value<0){
			value=0;
		}
		if(value == this.value){
			return;
		}
		if(this.animating){
			this.animation.cancel();
			this.value = this.currentCount;
			this.convertNumber();
		}
		
		var anim = {};
		var previousSpin = $A(this.spins);

		this.value = value;
		this.convertNumber();
		
		this.setValueAnimateDuration = 200;
		
		this.myFx = new Fx.Elements(this.numbers,{
			link:'chain', 
			duration:this.setValueAnimateDuration,
			onChainComplete:function(){
				this.animating = false;
				this.setValue(this.value);
				this.fireEvent('onSetAnimValueComplete',this.value);
				(function(){this.refreshed=false;}).delay(this.options.refreshRate*1000,this);
			}.bind(this)
		});
		
		this.spins.each(function(val,j){
				if(previousSpin[j]>=val)val = val.toInt() + 10;
				var theobj ={};
				theobj[j]={'background-position':this.getCoord(val)};
				this.myFx.start(theobj);	
		},this);
	},
	
	countTo:function(value){
		if(isNaN(value)){
			return false;
		}
		value = value.toInt();
		if(value<0){
			value=0;
		}
		if(value == this.value){
			return;
		}
		
		if(this.animating){
			this.animation.cancel();
			this.value = this.currentCount;
			this.convertNumber();
		}
		
		var steps = Math.abs(value-this.value);
		this.mid = steps/2;
		this.step=0;
		
		if(value>this.value){
			this.direction=true; //ascending
			for(var i=this.value+1;i<=value;i++){
				this.enqueueAnim(i);
			}
		}else{
			this.direction=false;//decending
			for(var i=this.value-1;i>=value;i--){
				this.enqueueAnim(i);
			}
		}
		
		
	},
	/*
	
	*/
	convertNumber:function(){
		var val = this.value+"";
		if(val.length>this.options.digits){
			var number = this.addNumber();
			number.inject((this.overlay?this.overlay:this.clear),'before');
			this.numbers.push(number);
			this.options.digits++;
			this.counter.setStyle('width',this.options.digits*this.width );
			this.animation.elements = this.animation.subject = $$(this.numbers);
			number.setStyle('background-position',this.getCoord(0));
			this.convertNumber();
			return;
		}else{
			while(val.length<this.options.digits){
				val = "0"+val;
			}
			for(var i=0;i<val.length;i++){
				this.spins[i]=val.charAt(val.length-1-i);
			}
		}
	},
	
	getCoord:function(value){
		return '0px '+(this.height+value*this.height)+'px';
	},
	
	enqueueAnim:function(i){
		var anim = {};
		var previousSpin = $A(this.spins);

		this.value = i;
		this.convertNumber();
		this.spins.each(function(val,j){
			if(previousSpin[j]!=val){
				
				if(val==0 && this.direction){
					anim[j]={'background-position':[this.getCoord(-1),this.getCoord(0)]};
				}else if(val==9 && !this.direction){
					anim[j]={'background-position':[this.getCoord(10),this.getCoord(9)]};
				}else{
					anim[j]={'background-position':this.getCoord(val)};
				}
			}
		},this);
		this.animation.start(anim);
	},
	
	refresh:function(){
		if(!this.refreshed){
			this.refreshed=true;
			if(!this.animating){	
				this.request.send();
				if(this.indicator){
					var coords=this.counter.getCoordinates();
					this.indicator.setStyles({
						position:'absolute',
						top:coords.top,
						left:coords.right
					});
					this.indicator.inject(document.body);
				}
			}
		}
	},
	
	getValue:function(){
		return this.value;
	}/*,
	override:function(){
		if(this.animating){
			this.animation.cancel().fireEvent('onChainComplete');
			this.setValue(this.value);
		}
	}*/
});