;(function($){
	ep.game = new function() {
		this.height,
		this.width,
		this.score = 0,
		this.totalscore = 0,
		this.levelTarget = 15,
		this.clickWorth = 1;
		this.currentLevel = 1;
		this.maxSquares = 6,
		this.lightningPressed = false,
		this.lightningFiller,
		this.lightningTimeout = 320,
		this.speed = 7800,
		this.levels = [{'goal':0, 'speed':7800, 'clickWorth':0, 'lightningTimeout':320, 'text':'', 'prizeId':''},
		               {'goal':20, 'speed':6200, 'clickWorth':1, 'lightningTimeout':320, 'text':'download the EP', 'prizeId':'download_regular'},
		               {'goal':60, 'speed':5600, 'clickWorth':2, 'lightningTimeout':220, 'text':'download the EP in high quality!', 'prizeId':'download_hq'},
		               {'goal':120, 'speed':4200, 'clickWorth':3, 'lightningTimeout':160, 'text':'download a super secret treat!', 'prizeId':'treat_hq'},        
		               {'goal':380, 'speed':3800, 'clickWorth':4, 'lightningTimeout':100, 'text':'obtain world domination!', 'prizeId':'treat_hq'}			                    
		               ],
		this.init = function() {
			this.dimensions();
			this.score = 0;
			this.totalscore = 0;
			this.updateScoreBoard();
			this.enableLightning();
			this.clickSquare();
			this.setupLevel(this.currentLevel);
			this.pause();
			this.resume();
			this.prizes();
			this.generateSquares();
			this.moveSquares();
		},
		this.dimensions = function() {
			this.height = $('#game').outerHeight();
			this.width = $('#game').outerWidth();
			//alert($('#container').width(););
		},
		this.generateSquares = function() {
			var self = this;

			for (var i=0;i<self.maxSquares;i++) {
				var width = $('.square:eq('+i+')').width();
				$('.square:eq('+i+')').css({'height':width+'px'});
			}
		},
		this.moveSquares = function() {
			var self = this;
			var i=0;
			for (var i=0;i<self.maxSquares;i++) {
				var active = $('.square:eq('+i+')');
				self.moveSquare(active);
			}
		},
		this.moveSquare = function(element) {
			var self = this;
			var directions = ['down', 'right', 'up', 'left'];
			var direction = directions[ep.random(4,0)];

			var topStart; var leftStart; var topEnd; var leftEnd;
			var speed =  self.speed+(ep.random(1000,0));

			var width = $(element).outerWidth();
			var height = $(element).outerHeight();

			switch (direction) {
				case 'down':
					topStart = -height;
					leftStart = ep.random((self.width-width),0);
					topEnd = self.height;
					leftEnd = ep.random((self.width-width));
					break;
				case 'right':
					topStart =  ep.random(self.height,0);
					leftStart = -width;
					topEnd = ep.random(self.height,0);
					leftEnd = self.width;
					break;
				case 'up':
					topStart =  self.height+height;
					leftStart = ep.random((self.width-width),0);
					topEnd = -height;
					leftEnd = ep.random((self.width-width),0);					
					break;
				case 'left':
					topStart =  ep.random(self.height,0);
					leftStart = self.width;
					topEnd = ep.random(self.height,0);
					leftEnd = -width;					
					break;
				}
			
			//alert(direction+'&&&'+speed+'^^^'+topStart+':'+topEnd + '///' + topStart+':'+leftEnd);

			$(element)
			.css({'top':topStart+'px','left':leftStart+'px'})
			.show()
			.animate({
				top: topEnd,
				left: leftEnd
			},speed, 'linear', function() {
				$(this).removeClass().addClass('square');
				self.moveSquare(element);
			});					
			
		},
		this.enableLightning = function() {
			var self = this;

			$(document).keydown(function(e) {
				if (e.keyCode == 65) {
 					//if (self.lightningPressed == false) {
						self.changeBg();
 						self.lightning();
						//self.lightningBar();
					//}
					//self.lightningPressed = true;
				}
			});	
		},
		this.lightning = function()
		{
			var self = this;
			
			$('.square').removeClass('ghost').addClass('visibleGhost');
			setTimeout(function() { 
				$('.square').removeClass('visibleGhost').addClass('ghost');
			}, 200); 
			
//			var lightningTimeout = setTimeout(function() {
//				self.lightningPressed = false;
//			}, self.lightningTimeout);
		},
		this.changeBg = function() {
			var images = $('#game > img').size();
			var current = $('#game > img.selected').index();
			$('#game > img').removeClass();
			var index = (current == images-1) ? 0 : current+1;
			$('#game img:eq('+index+')').addClass('selected');
		},
		this.lightningOld = function()
		{
			var self = this;
			
			$('#lightning')
			.fadeIn(100, function() { 
				$('.square').removeClass('ghost').addClass('visibleGhost');
				$(this).fadeOut(200, function() { 
					$('.square').removeClass('visibleGhost').addClass('ghost');
				}); 
				
				var lightningTimeout = setTimeout(function() {
					self.lightningPressed = false;
				}, self.lightningTimeout);
			});	
		},		
		this.lightningBar = function() {
			var self = this;
			clearInterval(self.lightningFiller);
			var width = 0;
			var addition = 100 / (self.lightningTimeout / 40);
			self.lightningFiller = setInterval(function() {
				width = width + addition;
				if (width > 100) {
					$('#lightningFiller').css({'width':'100%'});
				}
				else if (width <= 100) {
					$('#lightningFiller').css({'width':width+'%'});
				}
			}, 40);
			
		},
		this.clickSquare = function() {
			var self = this;
			$('.square').live('click', function() {
				$(this).removeClass().addClass('clicked');
				$(this).append('<span class="points">+'+self.clickWorth+'</span>');
				$('span', this).fadeOut(1200);
				self.score = self.score + self.clickWorth;
				self.totalscore = self.totalscore + self.clickWorth;
				self.bonus();
				if (self.score >= self.levelTarget) {
					self.score = 0;
					self.levelup();
					self.scoreBoardFiller(self.score);
					self.addPrize(self.currentLevel);
					self.currentLevel = self.currentLevel+1;
					self.setupLevel(self.currentLevel);
				}
				self.updateScoreBoard();
			});
		},
		this.bonus = function() {
			var self = this;
			var clicked = $('.clicked').size();
			if (clicked > 1) {
				var bonus = (clicked * self.clickWorth);
				html = '<span class="bonus">+'+bonus+' bonus!</span>';
				$('#game').append(html);
				setTimeout(function() {
					$('#game span').fadeOut(500);
				},500);
				self.score = self.score + bonus;
				self.totalscore = self.totalscore + bonus;
			}
		},
		this.setupLevel = function(level) {
			var self = this;
			var selectedLevel = self.levels[level];
			self.speed = selectedLevel.speed;
			self.levelTarget = selectedLevel.goal;
			self.clickWorth = selectedLevel.clickWorth;
			$('#nextGoal #goalText').text(selectedLevel.text);
			$('#left').text(self.levelTarget);
		},
		this.pause = function() {
			var self = this;

			$('#jplayer_pause').click(function(e) {
				e.preventDefault();
				$('#game div').remove();
				ep.theway.stop();
			});
		},
		this.resume = function() {
			var self = this;

			$('#jplayer_play.resume').click(function(e) {
				e.preventDefault();
				self.generateSquares();
				self.moveSquares();
			});
		},
		this.updateScoreBoard = function() {
			var self = this;
			$('#score').text(self.totalscore);
			var value = (self.score/self.levelTarget)*100;
			self.scoreBoardFiller(value);
			var pointLeft = self.levelTarget-self.score;
			$('#nextGoal #left').text(pointLeft);
			$('#levelup #goalPoints').text(pointLeft);
		},
		this.scoreBoardFiller = function(percentage) {
			$('div#scoreFiller').css({'background-color':'#b0e0dd','width':percentage+'%'});
		},
		this.addPrize = function(levelWon) {
			var self = this;
			var prizeText = self.levels[levelWon].text;
			var prizeId = self.levels[levelWon].prizeId;
			$('#prizes li').last().remove();
			$('#prizes').append('<li><a href="#" class="prize" id="'+prizeId+'">'+prizeText+'</a></li>');
			$('#levelup .prize').attr('id', prizeId).text(prizeText);
		},
		this.prizes = function() {
			$('.prize').live('click', function(e) {
				e.preventDefault();
				var type = $(this).attr('id').substring(9);
				ep.download(type);
			});
		},
		this.reset = function() {
			this.score = 0;
			this.totalscore = 0;
		},
		this.levelup = function() {
			$('#levelupPopup').show(); 
			setTimeout(function() { 
				$('#levelupPopup').fadeOut(1000); 
			}, 2000);
		},
		this.gameover = function() {
			var self = this;

			$(document).keydown(function(e) {
				if (e.keyCode == 27) {
					$('#gameoverPopup').fadeOut(100);
				}
			});	
			$('#gameoverClose').live('click', function(e) {
				e.preventDefault();
				$('#gameoverPopup').fadeOut(100);
			});
			
			$('#totalscore').text(self.totalscore);
			
			if ((self.currentLevel)-1 > 0) {
				var prizeText = self.levels[(self.currentLevel)-1].text;
				var prizeId = self.levels[(self.currentLevel)-1].prizeId;
				$('.prize').attr('id', prizeId).text(prizeText);
			} else {
				$('#gameResult').html("you didn't win anything")
			}
			
			if (self.totalscore > minTopScore && self.totalscore > 0) {
				$('#highscoreResult').show();
				self.highscore(self.totalscore);
			} else {
				$('#noHighscore').show();
				$('a#viewHighscore').live('click', function(e) {
					e.preventDefault();
					$('#gameoverPopup').hide();
					$('#highscoresPopup').fadeIn(500);
				});
			}
			
			$('#gameoverPopup').fadeIn(200);
			
			$('#gameoverPopup #playAgain').live('click', function() {
	    	    location.reload();
			});
		},
		this.highscore = function(score) {
			$(document).keydown(function(e) {
				if (e.keyCode == 27) {
					$('#highscoresPopup').fadeOut(100);
				}
			});	
			$('#highscoresClose').live('click', function(e) {
				e.preventDefault();
				$('#highscoresPopup').fadeOut(100);
			});
			
			var self = this;
			$('input').not('#submit').focus(function() {
				$(this).removeClass().val('');
			});
			$('textarea').focus(function() {
				$(this).removeClass().val('');
			});
			$('#highscoreForm').submit(function(e){
				e.preventDefault();
				var form = this;
				
				if(form.name.value == '') {
					var msg = "you forgot to tell us who you are";
					$('input#name').addClass('error').val(msg);
					return false;
				}
				if(form.name.value.length > 30) {
					var msg = "maximum 30 characters, sorry";
					$('input#name').addClass('error').val(msg);
					return false;
				}
				if(form.message.value.length > 140) {
					var msg = "this can be maximum 140 characters, sorry."
					$('textarea#message').addClass('error').val(msg);
					return false;
				}
				
				var params = $(this).serializeArray();
				$.ajax({
					type: "post",
					url: baseUrl + '/../interactive/addhighscore/',
					data: {'name':params[0].value, 'score':score, 'message':params[1].value},
					success: function(data){
					    $("#highscoresPopup").html(data);
						$('#gameoverPopup').hide();
						$('#highscoresPopup').fadeIn(500);
					}
				});
			});
		},
		this.showHighscores = function() {
			$('#highscoresPopup').show();
			$(document).keydown(function(e) {
				if (e.keyCode == 27) {
					$('#highscoresPopup').fadeOut(100);
				}
			});	
			$('#highscoresClose').live('click', function(e) {
				e.preventDefault();
				$('#highscoresPopup').fadeOut(100);
			});
			
		};
	};
})(jQuery);
