/*
 * Copyright (c) 2006 AWS Convergence Technologies, Inc. 
 * All rights reserved.
 * Visit http://www.aws.com
 *
 * WBVaneAnimator.js
 *
 * This scripts contains the WBVaneAnimator resuable class. A WBVaneAnimator
 * animats our beloved WeatherBug wind vane, so that the interface looks a little nicer.
 */
 
 // Object definition
function WBVaneAnimator(vanecanvas,duration)
{	
	this.canvas = vanecanvas;
	this.currentAngle = 0;
	this.finishAngle;
	this.duration = duration;
	var self = this;
	this.vaneAnimator = null;
			
	// AppleAnimation callback; this is where we actually change the rotation
	this.nextFrame = function (animation, now, first, done) {
		self.currentAngle = now;
		var context = self.canvas.getContext("2d");
		var theta = now*3.1415/180;
		context.clearRect(0,0,70,70);
		context.save();
		context.translate(70/2,70/2);
		context.fillStyle = "rgba(255,0,0,.7)";
		context.rotate(theta);
		context.beginPath();
		context.moveTo(-3,-70/2);
		context.lineTo(0,-10);
		context.lineTo(3,-70/2);
		context.fill();
		context.restore();
	}
	
	// Callback for AppleAnimator; also called to interrupt a vane-animation-in-progress
	this.doneAnimating = function () {
		if(this.finishAngle > 360)
		{
			this.finishAngle = this.finishAngle - 360;
		}
		else if(this.finishAngle < 0)
		{
			this.finishAngle = this.finishAngle + 360;
		}
		
		this.currentAngle = this.finishAngle;
		delete self.vaneAnimator;
	}
}

// Do not call this function directly, only from an initialized WBVaneAnimator object.
// This starts the whole animation process from the currentAngle to the finishAngle.
WBVaneAnimator.prototype.changePosition = function (num)
{
	this.finishAngle = num;

	if(this.currentAngle != this.finishAngle)
	{
		if (this.vaneAnimator) {
			this.vaneAnimator.stop();
			this.doneAnimating();
		}
		
		if((this.currentAngle - this.finishAngle) > 180)
		{
			this.finishAngle = this.finishAngle + 360;
		}
		else if((this.finishAngle - this.currentAngle) > 180)
		{
			this.finishAngle = this.finishAngle - 360;
		}
		
		this.vaneAnimator = new AppleAnimator(this.duration, 50, this.currentAngle, this.finishAngle, this.nextFrame);
		this.vaneAnimator.oncomplete = this.doneAnimating;
		this.vaneAnimator.start();
	}
}