/* Copyright (c) 2011 Felix Laukel (http://laukel.com)
 * Version 1.0
 ************************************************************* */

function Roach(element) {
	
	this.obj = element;
	
	this.maxSpeed = 4;
	this.speed = this.maxSpeed;
	
	this.xMin = 600;
	this.xMax = 7000;
	this.yMin = 50;
	this.yMax = 500;
	this.rangeMin = 300;
	this.rangeMax = 500;
	
	this.x = this.xMin + Math.random()*this.xMax |0;
	this.y = -150;
	this.rotation = 0;
	this.tx = this.x + this.rangeMin;
	this.ty = 180;
	this.interval;
	
	this.totalframes = 6;
	this.currentframe = 1;
	this.frameheight = 80;
	
	var fmax = 2;
	var fi = 0;
	
	var that = this;
	
	this.getAngleDelta = function(a, b)	{
		var diff = b-a;
		if (diff > 180) {
		  return ((diff + 180) % 360 ) - 180;
		} else if (diff < -180) {
		  return ((diff - 180) % 360 ) + 180;
		} else {
		  return diff % 360;
		}
	}
	
	this.getDistance = function(x, y) {
		var dx = this.x - x; 
        var dy = this.y - y; 
        return Math.sqrt((dx*dx)+(dy*dy));
	}
	
	this.update = function() {
		this.obj.style.left = this.x+'px';
		this.obj.style.top = this.y+'px';
		
		$(this.obj).css('transform', 'rotate('+this.rotation+'deg)');
		$(this.obj).css('-ms-transform', 'rotate('+this.rotation+'deg)');
		$(this.obj).css('-moz-transform', 'rotate('+this.rotation+'deg)');
		$(this.obj).css('-webkit-transform', 'rotate('+this.rotation+'deg)');
		$(this.obj).css('-o-transform', 'rotate('+this.rotation+'deg)');
		
		if (++fi == fmax) {
			if (++this.currentframe > this.totalframes) this.currentframe = 1;
			$(this.obj).css('background-position', '0 '+((this.currentframe-1)*-this.frameheight)+'px');
			fi = 0;
		}
	}
	
	this.setNewPath = function() {
		
		var dx = (that.rangeMin + Math.random()*(that.rangeMax-that.rangeMin)) * (Math.random() < 0.5 ? 1 : -1);
		
		that.tx += dx;
		that.tx = Math.min(that.xMax, Math.max(that.xMin, that.tx)); 
		that.ty += Math.random()*that.rangeMax*2-that.rangeMax;
		that.ty = Math.min(that.yMax, Math.max(that.yMin, that.ty)); 
		
		clearInterval(that.interval);
		that.interval = setInterval(that.setNewPath, 3000);
	}
	
	this.move = function() {
		
		if (!stopAnimations) {
			var angle = Math.atan2(that.ty - that.y, that.tx - that.x) * 180 / Math.PI;
			angle = that.getAngleDelta(angle, that.rotation);
			var diff = ((that.rotation - angle) - that.rotation) / 8;
	
			that.rotation += diff;
			
			angle = that.rotation * Math.PI / 360;
			var px = Math.cos(angle * 2);
			var py = Math.sin(angle * 2);
			that.x += px*that.speed;
			that.y += py*that.speed;
			
			if (that.getDistance(that.tx, that.ty) < that.speed * 2) {
				that.setNewPath();
			}
			
			that.update();
			
			//console.log('Roach tx/ty: '+that.tx+' / '+that.ty);
		}
		
		requestAnimationFrame( that.move );
		
	}
}
