/* Not exactly a standalone class yet. Written specifically for the wind direction applet */
var drawing = new Class({
	Implements: [Options,Events],
	
	initialize: function(el, options){
		this.el = $(el);
		this.history = [];
		this.show_wind_window = options.show_wind_window ? true : false;
		this.radius = this.el.width/2;
		this.ctx = this.el.getContext('2d');
		this.ctx.save();

		/* Move the cursor to the center */
		this.ctx.translate(this.el.width/2, this.el.height/2);
	},
	
	drawBase: function(){
		/* Draw the base border */
		this.arc(this.radius-2, 0, 360, 1, '#DDDDDD');
	},
	
	drawCurrent: function(){
		/* Draw the current wind */
		this.arc(this.radius-5, this.current-7, this.current+7, 6, '#111111');
	},
	
	drawHistory: function(){
		this.history.each(function(x){
			this.arc(this.radius-5, x[0], x[1], 10, '#FF4444');
		},this);
	},
	
	drawWindWindow: function(){
		/* The window (blue) */
		this.arc(this.radius * .9, (this.current + 95), (this.current - 95), 1, 'black', 'rgba(0,0,255,0.3)');
	},
	
	drawPortTack: function(){
		/* Port Tack Area (red) */
		this.arc(this.radius * .9, (this.current + 65), (this.current + 125), 1, 'black', 'rgba(255,0,0,0.3)');
	},
	
	drawStarboardTack: function(){
		/* Starboard Tack Area (green) */
		this.arc(this.radius * .9, (this.current - 125), (this.current - 65), 1, 'black', 'rgba(0,255,0,0.3)');
	},
	
	update: function(degrees, strength){
		this.history.push([degrees-7,degrees+7]);
		var temp = [];
		while(this.history.length > 0){
			temp = this.mergeArcs(this.history.shift(),temp);
		}
		this.history = temp;
		this.current = degrees;
		// this.strength = (strength == null ? .9 : strength);
		
		this.clear();
		this.drawBase();
		this.drawHistory();
		this.drawCurrent();
		if(this.show_wind_window)
			this.drawWindWindow();
	},
	
	clear: function(){
		this.ctx.clearRect(-this.radius,-this.radius,this.el.width,this.el.height);
	},
	
	arc: function(radius,start,stop,lineWidth,strokeStyle,fillStyle){
		this.ctx.lineWidth = lineWidth;
		this.ctx.strokeStyle = strokeStyle;
		this.ctx.beginPath();
		this.ctx.arc(0,0,radius,this.deg2Rad(start),this.deg2Rad(stop), false);
		
		if(fillStyle){
			this.ctx.lineTo(0,0);
			this.ctx.closePath();
			this.ctx.fillStyle = fillStyle;
			this.ctx.fill();
		}

		this.ctx.stroke();
	},
	
	deg2Rad: function(deg){
		return deg * (Math.PI/180);
	},
	
	mergeArcs: function(x, b){
		if(b.length == 0) return [x];
		var collision = false;

		b.each(function(y){
			if(x[0] >= y[0] && x[0] <= y[1]){
				// console.log('left collision',x,y);
				y[1] = (x[1] > y[1] ? x[1] : y[1]);
				collision = true;
				return;
			}else if(y[0] >= x[0] && y[0] <= x[1]){
				// console.log('right collision',x,y);
				y[0] = (x[0] > y[0] ? y[0] : x[0]);
				collision = true;
				return;
			}else{
				// console.log('no collisions',x,y);
			}
		});

		/* No collsions detected, stick x onto the end of b */
		if(!collision){
			b[b.length] = x;
		}

		return b;
	}
});
