/*
* boatRacer  v0.1.1
* http://www.seanmccambridge.com/boat-racer/
*
* Copyright (c) 2009 Sean McCambridge
*
* Date: 2009-10-22 04:02:00 -0500 (Thu, 22 October 2009)
*/

var gameover = 0;
var stopped = 1;
var capt = 0;
var vess = 0;
var diff = 0;
var buoyShapes = [];
var cd = 4;
var min = 0;
var sec = 0;
var second = 0;
var seconds = 0; // total in seconds, e.g. 129
var mil = 0;
var message = '';
var poly = [];
var currentBuoy = 1;

function even(num) {
	return (num % 2 == 0) ? true : false;
}

function Boat() {
 	this.h = 0; //heading
 	this.i = 0; //old heading
 	this.s = 0; //speed
 	this.r = 0; //rudder
 	this.t = 0; //throttle
 	this.x = 0; //locx
 	this.y = 0; //locy
 }
 
 function Buoy() {
 	this.x = 0;
 	this.y = 0;
 	this.n = 0;
 }
 
 var boats = new Array();
 var buoys = new Array();
 	
 function placeBoat(id,x,y,h) {
 	boats[id] = new Boat();
 	boats[id].x = x + 10;
 	boats[id].y = y + 10;
 	boats[id].h = h;
 	$('#'+id).addClass('heading-'+h).css({left:x,top:y});
 }
 
 function placeBuoy(id,x,y,n) {
 	buoys[id] = new Buoy();
 	buoys[id].x = x;
 	buoys[id].y = y;
 	buoys[id].n = n;
 	$('#'+id).css({left:x-10,top:y-15,display:'block',background:'url(media/layout/buoy'+n+'.png) no-repeat'});
 }
 
 function status(boat) {
 	return boats[boat];
 }
 
 function rotate(boat,dir) {
 	if (gameover == 0) {
	 	var current = boats[boat].h;
	 	boats[boat].i = current;
	 	boats[boat].h = (dir == 'l') ? current - 1 : current + 1;
	 	if (boats[boat].h > 15) boats[boat].h = 0;
	 	if (boats[boat].h < 0) boats[boat].h = 15;
	 	$('#'+boat).removeClass('heading-'+current).addClass('heading-'+boats[boat].h);
 	}
 }
 
function throttle(boat,dir) {
 	var current = boats[boat].t;
 	boats[boat].t = (dir == 'd') ? current - 1 : current + 1;
 	if (boats[boat].t == 2 && dir == 'u') boats[boat].t = 3;
 	if (boats[boat].t == 2 && dir == 'd') boats[boat].t = 1;
 	if (boats[boat].t > 4) boats[boat].t = 4;
 	if (boats[boat].t > 0 && stopped == 1) go();
 	if (boats[boat].t <= 0) {
 		boats[boat].t = 0;
 		stop();
 	}
}

function countdown(){
	if (cd == 4) {
		cd = 3;
		to = setTimeout(countdown,1000);
	} else if (cd == 3) {
		$('#countdown').css('background-position','0 0').show().fadeOut(1100);
		cd = 2;
		to = setTimeout(countdown,1200);
	} else if (cd == 2) {
		$('#countdown').css('background-position','0 -237px').show().fadeOut(1100);
		cd = 1;
		to = setTimeout(countdown,1200);
	} else if (cd == 1) {
		$('#countdown').css('background-position','0 -474px').show().fadeOut(1100);
		cd = 0;
		to = setTimeout(countdown,1200);
	} else if (cd == 0) {
		$('#countdown').css('background-position','0 -711px').show().fadeOut(2000);
		cd = -1;
 		timer();
		start();
	}
}

function timer() {
	mil++;
	mil == 10 ? mil = 0 : mil;
	mil == 0 ? sec++ : sec;
	mil == 0 ? seconds++ : sec;
	sec == 60 ? sec = 0 : sec;
	sec < 10 ? second = '0'+sec : second = sec;
	(mil == 0 && sec == 0) ? min++ : min;
	timeString = min+':'+second+'.'+mil;
	$('#timer').html(timeString);
	tto = setTimeout(timer,100);
}

// keyboard stuff
	shortcut.add("Left", function() {
		rotate(abbr,'l');
	});
	
	shortcut.add("Right", function() {
		rotate(abbr,'r');
	});
	
	shortcut.add("Up", function() {
		throttle(abbr,'u');
	});
	
	shortcut.add("Down", function() {
		throttle(abbr,'d');
	});
 
function start() {
 	gameover = 0;
 	currentBuoy = 1;
 	
 	if (difficulty == 'easy') {
		buoyXs = [
 			0,452,643,837,875,837,643,452,417
 		];
 		buoyYs = [
 			0,262,262,262,331,402,402,402,331
 		];
 		for (i=1;i<=8;i++) {
 			$('#map').append('<div id="buoy'+i+'" class="buoy"></div>');
 			placeBuoy('buoy'+i,buoyXs[i],buoyYs[i],i);
 			buoyShapes[i] = [
 				{x: buoyXs[i]-30,y: buoyYs[i]+20},
 				{x: buoyXs[i],y: buoyYs[i]+20},
 				{x: buoyXs[i]-30,y: buoyYs[i]-15},
 				{x: buoyXs[i],y: buoyYs[i]-15},
 			]
 		}
 	} else if (difficulty == 'medium') {
 		buoyXs = [
 			0,426,527,742,895,823,234,241,318
 		];
 		buoyYs = [
 			0,261,261,176,79,404,405,309,90
 		];
 		for (i=1;i<=8;i++) {
 			$('#map').append('<div id="buoy'+i+'" class="buoy"></div>');
 			placeBuoy('buoy'+i,buoyXs[i],buoyYs[i],i);
 			buoyShapes[i] = [
 				{x: buoyXs[i]-20,y: buoyYs[i]-10},
 				{x: buoyXs[i],y: buoyYs[i]-10},
 				{x: buoyXs[i]-20,y: buoyYs[i]+10},
 				{x: buoyXs[i],y: buoyYs[i]+10},
 			]
 		}
 	} else if (difficulty == 'hard') {
		buoyXs = [
 			0,431,567,672,834,203,80,46,341
 		];
 		buoyYs = [
 			0,125,105,34,437,195,230,37,124
 		];
 		for (i=1;i<=8;i++) {
 			$('#map').append('<div id="buoy'+i+'" class="buoy"></div>');
 			placeBuoy('buoy'+i,buoyXs[i],buoyYs[i],i);
 			buoyShapes[i] = [
 				{x: buoyXs[i]-20,y: buoyYs[i]-10},
 				{x: buoyXs[i],y: buoyYs[i]-10},
 				{x: buoyXs[i]-20,y: buoyYs[i]+10},
 				{x: buoyXs[i],y: buoyYs[i]+10},
 			]
 		}
 	}
}
 
 // collision testing

// from this guy's fine work
//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/math/is-point-in-poly [v1.0]

function collision(poly, pt){
	poly = typeof(poly) != 'undefined' ? poly : [ {x:0, y:0},{x:0, y:500},{x:950, y:500},{x:950, y:0} ];
	for(var c = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i)
		((poly[i].y <= pt.y && pt.y < poly[j].y) || (poly[j].y <= pt.y && pt.y < poly[i].y))
		&& (pt.x < (poly[j].x - poly[i].x) * (pt.y - poly[i].y) / (poly[j].y - poly[i].y) + poly[i].x)
		&& (c = !c);
	return c;
}

// collisions -- coastlines.js contains coords
 
function navigable(bX,bY) {

	if (mil == 0) {
		return false;
	} else if (collision(ironbound, {x: bX, y: bY})) {
		return false;
	} else if (collision(cranberries, {x: bX, y: bY})) {
		return false;
	} else if (collision(mdi, {x: bX, y: bY})) {
		return false;
	} else if (collision(jordan, {x: bX, y: bY})) {
		return false;
	} else if (collision(mainland1, {x: bX, y: bY})) {
		return false;
	} else if (collision(mainland2, {x: bX, y: bY})) {
		return false;
	} else if (collision(mainland3, {x: bX, y: bY})) {
		return false;
	} else if (collision(ducks, {x: bX, y: bY})) {
		return false;
	} else if (collision(sutton, {x: bX, y: bY})) {
		return false;
	} else if (collision(petit, {x: bX, y: bY})) {
		return false;
	} else if (collision(eggrock, {x: bX, y: bY})) {
		return false;
	} else if (collision(buoyShapes[1], {x: bX, y: bY})) {
		if (currentBuoy == 1) {
			$('#buoy1').css('background-position','0 -30px');
			currentBuoy = 2;
		}
		return true;
	} else if (collision(buoyShapes[2], {x: bX, y: bY})) {
		if (currentBuoy == 2) {
			$('#buoy2').css('background-position','0 -30px');
			currentBuoy = 3;
		}
		return true;
	} else if (collision(buoyShapes[3], {x: bX, y: bY})) {
		if (currentBuoy == 3) {
			$('#buoy3').css('background-position','0 -30px');
			currentBuoy = 4;
		}
		return true;
	} else if (collision(buoyShapes[4], {x: bX, y: bY})) {
		if (currentBuoy == 4) {
			$('#buoy4').css('background-position','0 -30px');
			currentBuoy = 5;
		}
		return true;
	} else if (collision(buoyShapes[5], {x: bX, y: bY})) {
		if (currentBuoy == 5) {
			$('#buoy5').css('background-position','0 -30px');
			currentBuoy = 6;
		}
		return true;
	} else if (collision(buoyShapes[6], {x: bX, y: bY})) {
		if (currentBuoy == 6) {
			$('#buoy6').css('background-position','0 -30px');
			currentBuoy = 7;
		}
		return true;
	} else if (collision(buoyShapes[7], {x: bX, y: bY})) {
		if (currentBuoy == 7) {
			$('#buoy7').css('background-position','0 -30px');
			currentBuoy = 8;
		}
		return true;
	} else if (collision(buoyShapes[8], {x: bX, y: bY})) {
		if (currentBuoy == 8) {
			$('#buoy8').css('background-position','0 -30px');
			currentBuoy = 9;
			gameover = 1;
		}
		return true;
	} else {
		return true;
	}
 }

// move player boat
var to;

function go() {

if (gameover == 0) {
	stopped = 0;
	var t = boats[abbr].t;
	var h = boats[abbr].h;
	if (t == 1) {
		to = setTimeout(go,60);
	} else if (t == 3) {
		to = setTimeout(go,20);
	} else if (t == 4) {
		to = setTimeout(go,10);
	}
	
	if (t != 0) {
		t = 1; // now t is constant and timeout changes instead
		var boat = $('#' + abbr);
		var pos = boat.position();
		var x = pos.left;
		var y = pos.top;
		
		// the easy ones
		if (h == 0 && y > 0 && navigable(x-t,y)) $('#' + abbr).css({top: y - t}); // N
		if (h == 4 && x < 934 && navigable(x+t,y)) $('#' + abbr).css({left: x + t}); // E
		if (h == 8 && y < 480 && navigable(x,y+t)) $('#' + abbr).css({top: y + t}); // S
		if (h == 12 && x > 0 && navigable(x-t,y)) $('#' + abbr).css({left: x - t}); // W
		if (h == 2 && y > 0 && x < 934 && navigable(x+t,y-t)) $('#' + abbr).css({left: x + t, top: y - t}); // NE
		if (h == 6 && y < 480 && x < 934 && navigable(x+t,y+t)) $('#' + abbr).css({left: x + t, top: y + t}); // SE
		if (h == 10 && y < 480 && x > 0 && navigable(x-t,y+t)) $('#' + abbr).css({left: x - t, top: y + t}); // SW
		if (h == 14 && y > 0 && x > 0 && navigable(x-t,y-t)) $('#' + abbr).css({left: x - t, top: y - t}); // NW
		
		//the hard ones
		if (h == 1 && y > 0 && x < 934 && navigable(x,y)) $('#' + abbr).css({left: ((even(y)) ? x : x + t), top: y - t}); // NNE
		if (h == 3 && y > 0 && x < 934 && navigable(x,y)) $('#' + abbr).css({left: x + t, top: ((even(x)) ? y : y - t)}); // ENE
		if (h == 5 && y < 480 && x < 934 && navigable(x,y)) $('#' + abbr).css({left: x + t, top: ((even(x)) ? y : y + t)}); // ESE
		if (h == 7 && y < 480 && x < 934 && navigable(x,y)) $('#' + abbr).css({left: ((even(y)) ? x : x + t), top: y + t}); // SSE
		if (h == 9 && y < 480 && x > 0 && navigable(x,y)) $('#' + abbr).css({left: ((even(y)) ? x : x - t), top: y + t}); // SSW
		if (h == 11 && y < 480 && x > 0 && navigable(x,y)) $('#' + abbr).css({left: x - t, top: ((even(x)) ? y : y + t)}); // WSW
		if (h == 13 && y > 0 && x > 0 && navigable(x,y)) $('#' + abbr).css({left: x - t, top: ((even(x)) ? y : y - t)}); // WNW
		if (h == 15 && y > 0 && x > 0 && navigable(x,y)) $('#' + abbr).css({left: ((even(y)) ? x : x - t), top: y - t}); // NNW
		
		//store position
		pos = boat.position();
		boats['' + abbr].x = pos.left + 10;
		boats['' + abbr].y = pos.top + 10;
	}
} else if (gameover == 1 && currentBuoy == 9) { // race finished!
	$('.boat').css('z-index',9);
	clearTimeout(tto);
	score();
}
	
}

function stop() {
	stopped = 1;
	clearTimeout(to);
	boats[abbr].t = 0;
}

function score() {
	$('#timer').hide();
	thumb = '<img src="media/layout/capt-' + captain + '.png" />';
	messageBoat = '<img src="media/layout/boat-' + vessel + '.png" />';
	
	if (difficulty == 'easy') {
		if (seconds > 25) {
			place = 'third';
			messageMessage = 'You might want to spend some time in the pond before you head out to sea!';
		} else if (seconds > 14) {
			place = 'second';
			messageMessage = 'Not bad. You could still use just a bit more sea time, though.';
		} else {
			place = 'first';
			messageMessage = 'Hey, Captain! I bet you\'re proud of yourself the way you can handle a boat!';
		}
	} else if (difficulty == 'medium') {
		if (seconds > 60) {
			place = 'third';
			messageMessage = 'You might want to spend some time in the pond before you head out to sea!';
		} else if (seconds > 25) {
			place = 'second';
			messageMessage = 'Not bad. You could still use just a bit more sea time, though.';
		} else {
			place = 'first';
			messageMessage = 'Hey, Captain! I bet you\'re proud of yourself the way you can handle a boat!';			
		}
	} else if (difficulty == 'hard') {
		if (seconds > 85) {
			place = 'third';
			messageMessage = 'You might want to spend some time in the pond before you head out to sea!';
		} else if (seconds > 70) {
			place = 'second';
			messageMessage = 'Not bad. You could still use just a bit more sea time, though.';
		} else {
			place = 'first';
			messageMessage = 'Hey, Captain! I bet you\'re proud of yourself the way you can handle a boat!';			
		}
	}
	messageScore = '<img src="media/layout/score-' + place + '.jpg" />';
	
	$('#overlay').fadeIn(400);
	message = '<div id="thumb">' + thumb + '</div><div id="message-score">' + messageScore + '</div><div id="message-boat">' + messageBoat + '</div><div id="final-time">' + timeString + '</div><div id="message-message">' + messageMessage + '</div><div id="again"></div>';
	$('#message').html(message).fadeIn(900);
	
	$('#again').click(function() {
	 	$('#map').children().fadeOut(300);
 		$('#overlay').fadeIn(400);
	 	$('#screen-welcome, #captains, #timer').fadeIn(800);
	 	reset();
 	}).hover(function() {
 		$(this).css('background-position','0 -47px');
 	},function() {
 		$(this).css('background-position','0 0');
 	});
}

function reset() {
	gameover = 0;
	stopped = 1;
	capt = 0;
	vess = 0;
	diff = 0;
	buoyShapes = [];
	cd = 4;
	min = 0;
	sec = 0;
	second = 0;
	seconds = 0; // total in seconds, e.g. 129
	mil = 0;
	message = '';
	poly = [];
	currentBuoy = 1;
	abbr = 0;
	vessel = 0;
 	
 	typeof(to) != 'undefined' ? clearTimeout(to) : hello = 1;
 	typeof(tto) != 'undefined' ? clearTimeout(tto) : hello = 1;
 	
 	$('.boat, .buoy').remove();
}
