$(function(){
	
	var ball = $('<span class="ball" />').appendTo('body'),
			gameTrigger = $('header span'),
      gameOn = false,
			initd = false,
			paused = false,
			bounceSnd,deathSnd,paddles
			
			canPlaySnd = !!document.createElement('audio').canPlayType,
			
			ph = 100; // paddles height
			
			
	if (canPlaySnd) {
		bounceSnd = $("<audio autobuffer><source src='sound/bounce.ogg' /><source src='sound/bounce.mp3' /></audio>").appendTo('body').get(0);
		deathSnd = $("<audio autobuffer><source src='sound/death.ogg' /><source src='sound/death.mp3' /></audio>").appendTo('body').get(0);
	}	
	

	
	
	function startGame(){
		var ox,oy,x,y,angle,coords,py,interval,
				speed = 6,
				bs = 16,
				deg2rad = Math.PI/180;
		
		if (gameOn) {return;}
		
		if (!paddles) {
			paddles = $('<span />').addClass('paddles').css({height: ph}).appendTo('body');
		}
		paddles.css({top:0}).fadeTo(500,1);
		
		gameOn = true;
		paused = false;
		
		_gaq.push(['_trackEvent', 'click', 'game']);
		
		function movePaddles(e){
			var maxy = $(window).height()-ph;
			
			py = e.clientY - (ph/2);
			if (py<0) {py = 0;}
			if (py>maxy) {py = maxy;}
			
			paddles.css({top: py});
		}
		
		function moveBall(){
			var my,newx,mx,bounce = false;
			if (paused) {return;}
			x += speed*Math.sin(angle*deg2rad);
			y += speed*Math.cos(angle*deg2rad);
			ball.css({left:x,top:y});
			
			mx = $(window).width() - bs - 1;
			
			if (x <= 28 || x>= mx-28) {
				if (py <= y+(bs/2) && py >= y-ph+6) {
					if (x <= 28) {angle = 360 - angle; x = 28; bounce = true;} // bounce off left
					if (x >= mx-28) {angle = 360 - angle; x = mx-28; bounce = true;} // bounce off right
				} else {
					// missed
					setTimeout(ballDeath, 100);
				}
			}
			my = $(window).height() - bs - 1;
			if (y <= 0) { angle = 180 - angle; y = 0; bounce = true;} // bounce off top
			if (y >= my) {angle = 180 - angle; y = my; bounce = true;} // bounce off bottom
			
			if (canPlaySnd && bounce) { bounceSnd.play(); }
		}
		
		function ballDeath(){
			if (gameOn == false) {return;}
			gameOn = false;
			$(document).unbind('mouseleave mouseenter mousemove');
			clearInterval(interval);
			ball.animate({opacity: 0, width: 48, height: 48, left: x-16, top: y-16});
			paddles.fadeTo(500,0,function() {
				$(this).css({top: -100});
			});
			if (canPlaySnd) {deathSnd.play();}
		}
		
		angle = 100+Math.floor(Math.random()*70);
		if (angle % 2 === 0) angle = angle - 180;
		
		coords = gameTrigger.offset();
		ox = x = coords.left;
		oy = y = coords.top + gameTrigger.height() - 15;
		
		ball.css({left: x, top: y, opacity: 1, width: 16, height: 16});
		
		$(document).bind('mousemove', movePaddles)
							 .bind('mouseleave', function(){ paused = true;})
							 .bind('mouseenter', function() { paused = false;});
		
		interval = setInterval(moveBall, 16);
		
		
	}
	
	gameTrigger.click(startGame);

});
