/**
 * Depends on jQuery
 * @author Henrik Hedelund <henrik@improove.se>
 */
var impEyes =  {
	eye: null,
	init: function(eye, container) {
		this.eye = eye;
		$(container).mousemove(this.mouseMoved);
		$(container).mouseleave(this.mouseOut);
		$(container).mouseenter(this.mouseIn);
		this.center();
	},
	center: function() {

		$(impEyes.eye).each(function() {
			var e = $(this); // e = eye
			var eo = e.offset(); // eo = eye offset

			var c = { // c = center
				x: e.width()/2 + eo.left,

				y: e.height()/2 + eo.top
			}
		
			$(this).children().each(function() {

				var p = $(this); // p = pupil
				p.css('position', 'absolute');
				p.css('top', (c.y - (p.height()/2)) + 'px');
				p.css('left', (c.x - (p.width()/2)) + 'px');
			});
		});

	},
	mouseIn: function(evt) {

		$(impEyes.eye)
			.children()
				.css('-webkit-transition-duration', '')
				.css('-webkit-transition-property', '');
		$(impEyes.eye)
			.children()
				.css('-moz-transition-duration', '')
				.css('-moz-transition-property', '');
		$(impEyes.eye)
			.children()
				.css('-o-transition-duration', '')
				.css('-o-transition-property', '');

	},
	mouseOut: function(evt) {

		$(impEyes.eye)
			.children()
				.css('-webkit-transition-duration', '0.3s')
				.css('-webkit-transition-property', 'top left');
		$(impEyes.eye)
			.children()
				.css('-moz-transition-duration', '0.3s')
				.css('-moz-transition-property', 'top left');
		$(impEyes.eye)
			.children()
				.css('-o-transition-duration', '0.3s')
				.css('-o-transition-property', 'top left');	
		impEyes.center();	
	},
	mouseMoved: function(evt) {

		$(impEyes.eye).each(function() {
			var e = $(this); // e = eye
			var eo = e.offset(); // eo = eye offset

			var c = { // c = center
				x: e.width()/2 + eo.left,

				y: e.height()/2 + eo.top
			}

			var d = { // d = delta
				x: evt.pageX - c.x,
				y: evt.pageY - c.y
			}

			var r = Math.atan2(d.y, d.x);			

			$(this).children().each(function() {

				var p = $(this); // p = pupil
				p.css('position', 'absolute');
				var po = p.offset(); // po = pupil offset
				var pp = {x: 0, y: 0}

				var a = {

					left: eo.left + p.width()/2,
					top: eo.top + p.height()/2, 
					right: eo.left + e.width() - p.width()/2, 
					bottom: eo.top + e.height() - p.height()/2,
					width: function() {return this.right - this.left;},

					height: function() {return this.bottom - this.top;}
				};
			
				pp.x = c.x + (Math.cos(r) * (a.width()/2));
				pp.y = c.y + (Math.sin(r) * (a.height()/2));

				var mDX = Math.abs(pp.x - c.x);

				var mDY = Math.abs(pp.y - c.y);
						
				if(Math.abs(d.x) <= mDX && Math.abs(d.y) <= mDY) {
					pp.x = evt.pageX;
					pp.y = evt.pageY;
				}

				p.css('top', (pp.y - (p.height()/2)) + 'px');

				p.css('left', (pp.x - (p.width()/2)) + 'px');
			});			
		});
	}
}

