var jKill = {
	defaults: {},
	bullets: 22,
	index: 0,
	interval: 900,
	kills: 0,
	killerID: 0,
	totalKills: 0,
	level: 1,
	maxLevel: 10,	
	maxWidth: 320,
	minWidth: 0,
	maxHeight: 240,
	minHeight: 0,
	totalPoints: 0,
	setup: [
		{img: 'img/victims/borisov.jpg', points: -1, name: 'Boiko Borisov', desc: 'Prime Minister of Bulgaria (from 27 July 2009'},
		{img: 'img/victims/bush.jpg', points: 5, name: 'George W. Bush', desc: 'The President of USA (January 20, 2001 – January 20, 2009)'},
		{img: 'img/victims/castro.jpg', points: 5, name: 'Fidel Castro', desc: 'President of Cuba (December 2, 1976 – February 24, 2008)'},
		{img: 'img/victims/chavez.jpg', points: 4, name: 'Hugo Chavez', desc: 'President of Venezuela (2 February 1999)'},
		{img: 'img/victims/kostov.jpg', points: 3, name: 'Ivan Kostov', desc: 'Prime Minister of Bulgaria (21 May 1997 – 24 July 2001)'},
		{img: 'img/victims/obama.jpg', points: -1, name: 'Barack Obama', desc: 'The President of USA (from January 20, 2009)'},
		{img: 'img/victims/parvanov.jpg', points: 1, name: 'Georgi Parvanov', desc: 'President of Bulgaria (from 22 January 2002)'},
		{img: 'img/victims/stanishev.jpg', points: 2, name: 'Sergei Stanishev', desc: 'Prime Minister of Bulgaria (17 August 2005 – 27 July 2009)'},
		{img: 'img/victims/tomov.jpg', points: 3, name: 'Aleksandar Tomov', desc: 'Bulgarian politician, Vice Premier of Bulgaria'},
		{img: 'img/victims/zhivkov.jpg', points: 5, name: 'Todor Zhivkov', desc: 'First Secretary of the Central Committee of the Bulgarian Communist Party (March 4, 1954 – November 10, 1989)'}
	],
	step: 30,	
	targets: 0,
	targetSetup: [
		{},
		{kills: 13, sim: 2, interval: 900, bullets: 22}, 
		{kills: 17, sim: 3, interval: 800, bullets: 25}, 
		{kills: 20, sim: 4, interval: 700, bullets: 27}, 
		{kills: 22, sim: 5, interval: 600, bullets: 28}, 
		{kills: 25, sim: 6, interval: 500, bullets: 30}, 
		{kills: 27, sim: 7, interval: 400, bullets: 31}, 
		{kills: 30, sim: 8, interval: 300, bullets: 33}, 
		{kills: 32, sim: 9, interval: 200, bullets: 34}, 
		{kills: 34, sim: 10, interval: 100, bullets: 35},
		{kills: 36, sim: 11, interval: 80, bullets: 36}
	],
	timerID: 0,
	
	aim: function (x, y) {
		$("#sight").css({left: x + 'px', top: y + 'px'});
	},
	bind: function () {
		$("#box").unbind().mousemove(function (e) {
			
			var offset = $(this).offset();
			jKill.mouseX = e.pageX - offset.left;
			jKill.mouseY = e.pageY - offset.top;	
			jKill.aim(jKill.mouseX - (jKill.sight.width / 2), jKill.mouseY - (jKill.sight.height / 2));
			
		}).click(function (e) {
			
			var offset = $(this).offset();
			jKill.mouseX = e.pageX - offset.left;
			jKill.mouseY = e.pageY - offset.top;			
			jKill.shoot(jKill.mouseX, jKill.mouseY);
		});
	},
	getHighScore: function () {
		var name = "jkill=";
		var carray = document.cookie.split(";");
		var c;
		for (var i = 0; i < carray.length; i++) {
			c = carray[i];
			while (c.charAt(0) === ' ') {
				c = c.substring(1, c.length);
			}
			if (c.indexOf(name) === 0) {
				return c.substring(name.length, c.length);
			}
		}
		return null;
	},
	init: function (options) {
		this.opts = $.extend(this.defaults, options);
		this.started = false;
		this.paused  = false;
		this.sight = {width: $("#sight").width(), height: $("#sight").height()};
		clearInterval(this.killerID);
		this.killerID = 0;		
		
		$("#s_bullets").text(this.bullets);
		$("#s_level").text(this.level);
		$("#s_totalKills").text(this.totalKills);
		$("#s_kills").text(this.kills);
		$("#s_targetKills").text(this.targetSetup[this.level].kills);
		$("#s_time").text(this.minutes.toString() + ':' + this.seconds.toString());
		$("#s_totalPoints").text(this.totalPoints);
		$("#s_points").text("0");
		$("#s_murder").text("");
		$("#s_totalTargets").text("0");
	},
	kill: function (target) {
		var rel = target.attr('rel');
		
		// Reduce targets
		this.targets = this.targets - 1;
		
		// Increase kills
		this.kills = this.kills + 1;
		this.totalKills = this.totalKills + 1;
		$("#s_totalKills").text(this.totalKills);
		$("#s_kills").text(this.kills);
		$("#s_targetKills").text(this.targetSetup[this.level].kills);
		
		// points
		this.totalPoints = this.totalPoints + this.setup[rel].points;
		$("#s_totalPoints").text(this.totalPoints);
		if (this.setup[rel].points > 0) {
			$("#s_points").text(this.setup[rel].points).css({color: 'green'});
		} else {
			$("#s_points").text(this.setup[rel].points).css({color: 'red'});
		}
		$("#s_murder").text(this.setup[rel].name + ', ' + this.setup[rel].desc);
		
		// Remove target
		target.animate({
			left: 0,
			top: 0,
			width: 0,
			height: 0,
			opacity: 0.3
		}, 500, 'easeOutExpo', function () {
			$(this).remove();
		});
		
		// Check level
		if (this.targetSetup[this.level].kills === this.kills) {
			this.kills = 0;
			this.bullets = this.targetSetup[this.level].bullets;
			this.interval = this.targetSetup[this.level].interval;
			$("#s_bullets").text(this.bullets);
			
			if (this.level === this.maxLevel) {
				this.overlay('show', 'Congrats! You win the game');
				this.setHighScore(this.totalKills);
				this.newGame();
				return;
			}
			
			this.level = this.level + 1;
			$("#s_level").text(this.level);
			
			$("#s_kills").text(this.kills);
			$("#s_targetKills").text(this.targetSetup[this.level].kills);
			this.sound("sound_reload");
		}
	},
	newGame: function () {
		this.level = 1;
		this.minutes = 0;
		this.seconds = 0;
		this.totalKills = 0;
		this.kills = 0;
		this.bullets = this.targetSetup[this.level].bullets;
		this.interval = this.targetSetup[this.level].interval;
		this.totalPoints = 0;
		this.targets = 0;
		this.index = 0;
		
		this.init();
		if ($("#overlay").css("display") === 'none') {
			this.bind();
		}
		$(".target").remove();
	},
	overlay: function (a, note) {
		switch (a) {
		case 'show':
			$(document).unbind().bind("keydown", function (e) {
				var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
				// Escape
				if (key === 27) {
					jKill.overlay('hide');					
				}
			});
			$("a.nav").unbind();
			
			var w = $(document.body).innerWidth();
			var h = $(document.body).innerHeight();			
			var offset = $("#box").offset();
			
			$("#overlay").css({width: w.toString() + 'px', height: h.toString() + 'px'});
			$("#overlayBox").css({left: offset.left.toString() + 'px', top: offset.top.toString() + 'px'});
			
			$("#overlayNote").text(note);
			$("#overlayBox").fadeIn("normal", function () {
				$(this).show();
			});
			$("#overlay").fadeIn("normal", function () {
				$(this).show();
			});			
			break;
		case 'hide':
			$("#overlayBox").fadeOut("normal", function () {
				$(this).hide();
				$("#overlayNote").text('');
			});
			$("#overlay").fadeOut("normal", function () {
				$(this).hide();
			});
			this.bind();
			break;
		}
	},
	pause: function () {
		if (this.started) {
			this.paused = true;
		}
	},
	resume: function () {
		this.paused = false;
	},
	setHighScore: function (score) {
		var high = this.getHighScore();
		if (score > high) {
			document.cookie = "jkill=" + score + "; expires=" + 60 * 60 * 24 * 30 + "; path=/";
		}
	},
	shoot: function (x, y) {
		if (this.bullets === 0 || !this.started || this.paused) {
			return;	
		}
		// Reduce bullets
		this.bullets = this.bullets - 1;
		$("#s_bullets").text(this.bullets);
		
		// Play a gun shot sound
		this.sound("sound_shot");
			
		// Fire out
		$("#sight").addClass("fire").animate({
			opacity: 0.1
		}, 200, "linear", function () {
			$(this).removeClass("fire").css({opacity: 1});
		});

		// Check target
		$(".target").each(function () {
			var t_left = parseInt($(this).css("left").split("p")[0], 10);
			var t_top = parseInt($(this).css("top").split("p")[0], 10);
			if ((x >= t_left && x <= t_left + jKill.step) && (y >= t_top && y <= t_top + jKill.step)) {
				// Kill				
				jKill.kill($(this));
				return true;
			}
		});
	},
	sound: function (id) {
		/*var audio = document.getElementById(id);
		var canPlayOgg = ("no" !== audio.canPlayType("audio/ogg")) && ("" !== audio.canPlayType("audio/ogg"));
		var canPlayWav = ("no" !== audio.canPlayType("audio/x-wav")) && ("" !== audio.canPlayType("audio/x-wav"));
		var canPlayMp3 = ("no" !== audio.canPlayType("audio/mpeg")) && ("" !== audio.canPlayType("audio/mpeg"));
		if (canPlayOgg || canPlayWav || canPlayMp3) {
			audio.pause();
			audio.play();
		}*/
		$("#" + id).jPlayer("stop").jPlayer("play");
	},
	start: function () {
		this.started = true;
		this.paused = false;
		
		if (!this.killerID) {
			this.target();
			this.targetScheduler();
			this.timer();
		}
	},
	stop: function () {
		if (this.started) {
			this.overlay('show', 'Game Over');
		}
		this.setHighScore(this.score);
		this.newGame();
	},
	target: function () {
		var x, y;
		do {
			x = Math.round(Math.random() * (this.maxWidth - this.step));
		} while (!!(x % this.step));

		do {
			y = Math.round(Math.random() * (this.maxHeight - this.step));
		} while (!!(y % this.step));
		
		if (this.targets === this.targetSetup[this.level].sim) {
			this.targets = this.targets - 1;
			$(".target").eq(0).remove();
		}
		this.index = this.index + 1;
		var i = Math.floor(Math.random() * this.setup.length);
		//var t = '<div id="t_' + this.index + '" rel="' + i + '" class="target" style="background: url(img/' + this.setup[i].img + ') 0 0 no-repeat; left: ' + x + 'px; top: ' + y + 'px"></div>';
		//$("#box").append(t);
		//jQuery 1.4
		$("<div>", {
			id: "t_" + this.index,
			rel: i,	
			"class": "target",
			css: {
				background: "url(" + this.setup[i].img + ") 0 0 no-repeat",
				left: x + "px",
				top: y + "px"
			}
		}).appendTo("#box");
		this.targets = this.targets + 1;
		$("#s_totalTargets").text(this.index);		
	},
	targetScheduler: function () {
		clearInterval(this.killerID);
		this.killerID = setInterval(function () {
			if (jKill.started && !jKill.paused) {	
				jKill.target();
			}
		}, this.interval);
	},
	timer: function () {
		clearInterval(this.timerID);
		this.timerID = setInterval(function () {
			if (jKill.started && !jKill.paused) {
				jKill.seconds = jKill.seconds + 1;
				if (jKill.seconds === 60) {
					jKill.seconds = 0;
					jKill.minutes = jKill.minutes + 1;
				}
				var time = [jKill.minutes.toString(), jKill.seconds.toString()];
				$("#s_time").text(time.join(':'));
			}
		}, 1000);
	}
};
