/*
 * Copyright 2009 Palm, Inc. All rights reserved.
 */
/*global Mojo, Class */

var PageSearchAnimation = Class.create({

	initialize: function(details) {

		Mojo.require(details.controller, "PageSearchAnimation requires a controller");
		Mojo.require(details.model, "PageSearchAnimation requires a model");
		this._controller = details.controller;
		this._model = details.model;
		this._iconClass = details.model.icon;
		this._iconSelector = '.' + details.model.icon;

		this._frameHeight = details.frameHeight || 48;
		this._frameCount = details.frameCount || 12;
		this._fps = details.fps || 12;

		this._drawInterval = Math.max(1, Mojo.Animation.targetFPS/this._fps);
		this._currentFrameIndex = 0;
		this._hasStarted = false;
	},

	_getElement: function() {

		var icon = this._controller.select(this._iconSelector);
		if (icon) {
			icon = icon[0];
		}
		return icon;
	},

	start: function() {

		// Add to the animation queue if the element exists.
		var element = this._getElement();
		if (element) {
			// Get a handle onto the main animation queue.
			this._animationQueue = Mojo.Animation.queueForElement(element);
		}

		// If the play period isn't defined the play forever.
		this._currentFrameIndex = 0;
		this._drawCount = 0;
		if (!this._hasStarted && this._animationQueue) {
			this._animationQueue.add(this);
			this._hasStarted = true;
		}
	},

	stop: function(){

		if (this._hasStarted && this._animationQueue) {
			this._animationQueue.remove(this);
		}
		this._hasStarted = false;
	},

	animate: function() {

		if (this._drawCount < this._drawInterval) {
			this._drawCount++;
		} else {
			this._drawCount -= this._drawInterval;
			this._currentFrameIndex++;
			this._currentFrameIndex = this._currentFrameIndex % this._frameCount;
			this._setFrame(this._currentFrameIndex);
		}
	},

	_setFrame: function(index){

		var element = this._getElement();
		if (element) {
			if (this._model._progress) {
				element.removeClassName(this._model._progress);
			}
			var progress = 'progress-' + index;
			element.addClassName(progress);
			this._model.icon = this._iconClass + ' ' + progress;
			this._model._progress = progress;
		}
	}
});
