;(function($){
	var ep = window.ep = new function() {
		this.controllers = ['highscores', 'about', 'news'],		
		this.flashed = false;
		this.init = function() {
			//this.geolocation();
			//this.getAddress();
			this.stars();
			this.headerAnimation();
			this.highscoreForm();
		},
		this.flashReady = function(val) {
			this.flashed = true;
			this.playlist();
			this.pauseResume();	
		},
		this.getStart = function(start) {
			if (start == true) {
				$('#startRules').fadeOut(300);
			}
		},
		this.getSong = function(song) {
			//console.log(song);
			$('#playing #title').html(song.title);
			$('#playing #totalTime').html('(' + song.time + ')');
			
			$('#moreSongs a').removeClass().addClass('notSelected');
			$('a#song_' + song.folder).removeClass().addClass('selected');
		},
		this.getScore = function(score) {
			var self = this;
			//$('#navigation #score').html('(' + score + ')');
			
			$.ajax({
				type: "post",
				url: baseUrl + '/../game/getscore/',
				data: {'score':score},
				success: function(data){
					if (data == 'highscore') {
						self.animateHighscores();
					}
				}
			});			
		},		
		this.getPrize = function(prize) {
			var self = this;
			
			//console.log(prize);
			$('#prizeLoader').show();
			
			$.ajax({
				type: "post",
				url: baseUrl + '/../game/getprize/',
				data: {'prizeText':prize.text, 'prizeId':prize.prize_id},
				success: function(){
					$('#prizeLoader').hide();					
					self.getMovie('flash').pauseGamePrizeJs();
					
					$('#prize span#prizeContainer').html('<a class="prize" id="'+prize.prize_id+'" href="#">the '+prize.text+' package!</a>');
					$('#done').hide();
					$('#downloadForm').show();
					$('#downloadContainer').hide();
					$('#prizeOptions').show();					
					$('#prize').fadeIn(50);
					$('#getit').live('click', function(e) {
						e.preventDefault();
						$('#downloadContainer').show();
						if (locationStored == false) {
							self.getAddress();
						}							
					});
					$('#resume').live('click', function(e) {
						e.preventDefault()
						$('#prize').hide();
						self.getMovie('flash').resumeGamePrizeJs();
					});
					$('a#'+prize.prize_id).live('click', function(e) {
						$('#downloadContainer').show();
						$('#prizeOptions').show();						
						e.preventDefault()
					});
					self.downloadForm();					
				}
			});				
			//self.animatePrize($('a#'+prize.prize_id));
		},			
		this.playlist = function() {
			var self = this;
			
			$('#moreSongs li a').click(function(e) {
				e.preventDefault();
				var songIndex = $(this).parent().index();
				self.getMovie('flash').startGameFromJs(songIndex);
			});
		},
		this.pauseResume = function() {
			var self = this;
			
			$(window).keydown(function(e) {
				if (e.which == 80) { // p = pause
					self.getMovie('flash').pauseGameJs();
				}
				if (e.which == 27) { // esc - resume
					self.getMovie('flash').resumeGameJs();
				}
			});
		},
		this.showDownloadContainer = function() {
			$('#downloadContainer').fadeIn(50, function() {
				$('#prize').animate({
					width:'300px',
				}, 200, function() {
				});
			});
		},
		this.animatePrize = function($prize) {
			var self = this;
			
			var colors = ['#FFCC00', '##E2E2D3', '#FF0000'];
			var index = self.random(colors.length,0);

			$prize.animate({
				borderTopColor:colors[index], 
				borderLeftColor:colors[index], 
				borderBottomColor:colors[index], 
				borderRightColor:colors[index]
				},500, function() { 
					self.animatePrize($prize); 
			});
		},
		this.animateHighscores = function() {
			var self = this;
			
			$('#highscoresNav').animate({color: 'red'}, 1000, function() { self.animateBack(); });
		},
		this.animateBack = function() 
		{
			var self = this;
			
			$('#highscoresNav').animate({color: '#C4C4C4'}, 1000, function() { self.animateHighscores(); } );
		},
		this.headerAnimation = function() {
			$('h1').hover(function() {
				$('h1 span').stop();
				$('h1 span').animate({marginLeft:'18px', marginRight:'18px'}, 300);
			}, function() {
				$('h1 span').stop();
				$('h1 span').animate({marginLeft:'0px', marginRight:'0px'}, 400); 
			});
		},
		this.stars = function() {
			var self = this;
			var controller = self.getController();
			var colors;
			
			switch (controller) {
				case 'highscores':
					if ($('#gameover p').size() == 0) {
						colors = ['#E2E2D3', 'brown'];
						self.drawStars(colors);
					}
					break;
				case 'about':
					colors = ['#E2E2D3', 'yellow'];
					self.drawStars(colors);
					break;
				case 'news':
					colors = ['#E2E2D3', 'blue'];
					self.drawStars(colors);
				default:
					break;
			}
			
			
		},
		this.drawStars = function(colors) {
			var self = this;
			$('#gameover').append('<p id="stars"></p>');
			
			// stars * 5016
			// squares 1000
			
			var interval = setInterval(function() {
				if ($('#gameover span').size() < 1806) {
					var colorIndex = self.random(colors.length,0);
					var opacity = self.random(10, 1);
					$('#gameover p#stars').append('<span class="square" style="background-color:'+colors[colorIndex]+'; opacity:0.'+opacity+'"></span> ');
				} else {
					clearInterval(interval);
					$('#gameover p#stars').append('<span id="congratulations">CONGRATULATIONS!</span>');					
				}		
			}, 50);				
		},
		this.random = function(max, add) {
			return Math.floor(Math.random()*max+add)
		},
		this.isEmail = function isEmail(email){
			return /^[\w-+\.]+@([\w-]+\.)+[\w-]{2,}$/i.test(email);
		},
		this.getMovie = function(movieName) {
			  if (window.document[movieName]) 
			  {
			      return window.document[movieName];
			  }
			  if (navigator.appName.indexOf("Microsoft Internet")==-1)
			  {
			    if (document.embeds && document.embeds[movieName])
			      return document.embeds[movieName]; 
			  }
			  else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
			  {
			    return document.getElementById(movieName);
			  }
		},		
		this.getController = function() {
			var self = this;
			var pathname = window.location.pathname;
			var controller;
			for (var i=0; i<self.controllers.length; i++) {
				var query = new RegExp(self.controllers[i], 'i');
				if (pathname.search(query) > 0) { controller = self.controllers[i]; }
			}
			return controller;
		},	
		this.downloadForm = function() {
			var self = this;
			$('input').not('#submit').focus(function() {
				$(this).removeClass().val('');
			});
			
			$('#downloadContainer a.closeButton').live('click', function(e) {
				e.preventDefault();
				$('#downloadContainer').fadeOut(100);
			});
			$('form').submit(function(e){
				e.preventDefault();
				var form = this;
				var errors = [];	
				
				if(form.name.value.length > 100) {
					var error = {'field':'name', 'message':'can you try a shorter name please?'};
					errors.push(error);	
				}	
				if(form.email.value == '') {
					var error = {'field':'email', 'message':'what\'s your email please?'};
					errors.push(error);	
				}
				if(form.email.value.length > 0 && !self.isEmail(form.email.value)) {
					var error = {'field':'email', 'message':'i\'m not sure it\'s an email.'};
					errors.push(error);	
				}
				
				if (errors.length > 0) {
					self.displayErrors(errors, form);
					return false;
				}				
				
				var params = $(this).serialize();
				$('#downloadLoader').show();					
				
				$.ajax({
					type: "post",
					dataType: 'json',
					url: baseUrl + '/../game/downloadrequest/',
					data: params,
					success: function(data){
						if (data.result == true) {
							$('#downloadLoader').hide();												
							//window.open(baseUrl + '/../game/file/','downloading');
							$('#downloadForm').hide();
							$('#prizeOptions').hide();
							$('#done').html(data.html).show();							
						} 
						//self.getMovie('flash').resumeGameJs();						
						//$('form').hide();
						//$('div#done').fadeIn(500);
					}
				});
			});
		},
		this.highscoreForm = function() {
			var self = this;
			var getPrize = false;
			
			$('input').not('#submit').not('.mailingList').focus(function() {
				$(this).removeClass().val('');
			});
			$('#highscoreResult a').click(function(e) {
				e.preventDefault();
				
				getPrize = true;
				if (locationStored == false) {
					self.getAddress();
				}	
				
				$('#highscoreResult > p').hide();
				$('#highscoreResult ul li.additional').show();
				$('#highscoreResult input#submit').val('get it!');
				
			});
			
			$('form#highscoreForm').submit(function(e){
				e.preventDefault();
				var form = this;
				
				var errors = [];	
				
				if(form.name.value == '') {
					var msg = 'hi! my name is Or. what\'s yours?';
					var error = {'field':'name', 'message':'hi! my name is Or. what\'s yours?'};
					errors.push(error);					
				}
				if(form.name.value.length > 100) {
					var error = {'field':'name', 'message':'can you try a shorter name please?'};
					errors.push(error);	
				}			
				if(form.message.value.length > 140) {
					var error = {'field':'message', 'message':'try keeping your message under 140 characters.'};
					errors.push(error);	
				}					
				if (getPrize == true) {
					if(form.email.value == '') {
						var error = {'field':'email', 'message':'what\'s your email please?'};
						errors.push(error);	
					}
					if(form.email.value.length > 0 && !self.isEmail(form.email.value)) {
						var error = {'field':'email', 'message':'i\'m not sure it\'s an email.'};
						errors.push(error);	
					}
					
					if (errors.length > 0) {
						self.displayErrors(errors, form);
						return false;
					}
					
					var params = $(this).serialize();

					$.ajax({
						type: "post",
						url: baseUrl + '/../game/downloadrequest/',
						dataType: 'json',
						data: params,
						success: function(data){
							if (data.result == true) {
								//window.open(baseUrl + '/../game/file/','downloading');
								$('#highscoreResult').html(data.thankyou);								
							} 
							$('table#highscores').html(data.html);
							//$('#highscoreResult').fadeOut(1000, function() {
								//$('#highscoreResult').remove();
								//self.stars();
							//});	
						}
					});					
				} else {
					if (errors.length > 0) {
						self.displayErrors(errors, form);
						return false;
					}
					
					var params = $(this).serialize();

					$.ajax({
						type: "post",
						url: baseUrl + '/../game/addhighscore/',
						data: params,
						success: function(data){
							$('table#highscores').html(data);
							$('#highscoreResult').fadeOut(1000, function() {
								$('#highscoreResult').remove();								
								self.stars();
							});
						}						
					});					
				}
			});
		},
		this.getAddress = function() {
			retrieve_zip("ep.parseAddress");
			function retrieve_zip(callback)
			{
				try { if(!google) { google = 0; } } catch(err) { google = 0; } // Stupid Exceptions
				if(navigator.geolocation) // FireFox/HTML5 GeoLocation
				{
					navigator.geolocation.getCurrentPosition(function(position) {
						zip_from_latlng(position.coords.latitude,position.coords.longitude,callback);
					}, errorCallback, {maximumAge: 75000});
				}
				else if(google && google.gears) // Google Gears GeoLocation
				{
					var geloc = google.gears.factory.create('beta.geolocation');
					geloc.getPermission();
					geloc.getCurrentPosition(function(position)
					{
						zip_from_latlng(position.latitude,position.longitude,callback);
					},function(err){});
				}
			}
			function zip_from_latlng(latitude,longitude,callback)
			{
				// Setup the Script using Geonames.org's WebService
					var script = document.createElement("script");
					script.src = "http://ws.geonames.org/findNearbyPostalCodesJSON?lat=" + latitude + "&lng=" + longitude + "&callback=" + callback;
				// Run the Script
					document.getElementsByTagName("head")[0].appendChild(script);
			}
			function errorCallback(error) {
				var error = error.code;
			}
		},
		this.parseAddress = function(json) {
			// Now we have the data!  If you want to just assume it's the 'closest' zipcode, we have that below:
			zip = json.postalCodes[0].postalCode;
			country = json.postalCodes[0].countryCode;
			state = json.postalCodes[0].adminName1;
			place = json.postalCodes[0].placeName;
			
			$.ajax({
				type: "post",
				url: baseUrl + '/../game/storelocation/',
				data: {'zip':zip, 'country':country, 'state':state, 'place':place},
				success: function(){
							
				}
			});				
			
			
		},
		this.displayErrors = function(errors, form) {
			for (var i=0; i<errors.length; i++) {
				var field = errors[i]['field'];
				var message = errors[i]['message'];
				$('input#' + field).addClass('error').val(message);
			}
		};
	};
})(jQuery);

$(document).ready(function(){
	ep.init();
});
