/*
Example of usage:
object.addAnimation({
	"field" : "style.left",
	"valueFrom" : 0,
	"valueTo" : 100,
	"frames" : 10,
	"dim" : "px",
	"onStart" : function() {alert('start');},
	"onEnd" : function() {alert('end');}
});

*/

function initAnimation() {
	addAnimation = function(obj,name,params) {
		animation.addChannel(name+getId(obj), obj, params);
	}

	stopAnimation = function(obj,name) {
		animation.removeChannel(name+getId(obj));
	}

	stopLoop = function(obj,name) {
		animation.stopLoop(name+getId(obj));
	}


	drawNextFrame = function() {
		animation.drawNextFrame();
	}


	animation = {
		"channels" : {},
		"nextKey" : 0,
		"isStarted" : false,

		"addChannel" : function(key, obj, params) {
			params.currentFrame = 1;
			if (params.values) params.frames = params.values.length;
			if (!params.valueFrom) {
				if (params.styleField)
					params.valueFrom = obj.style[params.styleField] ? parseInt(obj.style[params.styleField]) : 0;
				if (params.attributeField)
					params.valueFrom = obj[params.attributeField] ? parseInt(obj[params.attributeField]) : 0;
			}

			params.obj = obj;
			this.channels[key] = params;

			if (params.onStart) params.onStart();
			this.start();
		},


		"removeChannel" : function(key) {
			delete this.channels[key];
		},

		"start" : function() {
			if (!this.isStarted) {
				this.isStarted = true;
				this.drawNextFrame();
			}
		},

		"stop" : function() {
			this.isStarted = false;
		},

		"stopLoop" : function(key) {
			if (this.channels[key]) this.channels[key].loop = false;
		},

		"drawNextFrame" : function() {
			if (this.isStarted) {
				var doStop = true;
				for(i in this.channels) {
					this.doAnimate(i);
					doStop = false;
				}
				if (doStop) this.stop();
				else setTimeout('drawNextFrame()', 10);
			}
		},

		"doAnimate" : function(key) {
			obj = this.channels[key].obj;
			anim = this.channels[key];

			if (anim.skip) {
				anim.skip--;
			}
			else {
				if (anim.styleField && anim.styleField == 'opacity')
					setOpacity(obj, this.getValue(anim));
				else if (anim.styleField)
					obj.style[anim.styleField] = this.getValue(anim);
				else if (anim.attributeField)
					obj[anim.attributeField] = this.getValue(anim);

				if (anim.currentFrame == anim.frames && anim.loop)
					anim[key].currentFrame = 1;

				else if (anim.currentFrame == anim.frames) {
					this.removeChannel(key);
					if (anim.onEnd) anim.onEnd();
				}
				else
					anim.currentFrame++;
			}
		},

		"getValue" : function(anim) {
			if (anim.currentFrame == anim.frames)
				if (anim.values)
					return anim.values[anim.frames-1] + this.dimention(anim);
				else
					return anim.valueTo + this.dimention(anim);
			else 
				if (anim.values)
					return anim.values[anim.currentFrame-1] + this.dimention(anim);
				else
					return (anim.valueFrom + ((anim.valueTo-anim.valueFrom)/anim.frames * anim.currentFrame)) + this.dimention(anim)
		},

		"dimention" : function(anim) {
			return (anim.dimention ? anim.dimention : "")
		}
	}
}

