jQuery(document).ready(function($){
	var nevercalled = true;
	var keys = [];
	var toasty = $('.toasty');
	var audio = $('.toasty audio');
	var pic = $('.toasty img');
	var songs = [
					{"name":"Still Alive", "width": "26590px", "file":"stillalive", "lyrics": "This was a triumph. I'm making a note here: HUGE SUCCESS. It's hard to overstate my satisfaction. Aperture Science We do what we must because we can. For the good of all of us. Except the ones who are dead. But there's no sense crying over every mistake. You just keep on trying till you run out of cake. And the Science gets done. And you make a neat gun. For the people who are still alive. I'm not even angry. I'm being so sincere right now. Even though you broke my heart. And killed me. And tore me to pieces. And threw every piece into a fire. As they burned it hurt because I was so happy for you! Now these points of data make a beautiful line. And we're out of beta. We're releasing on time. So I'm GLaD. I got burned. Think of all the things we learned for the people who are still alive. Go ahead and leave me. I think I prefer to stay inside. Maybe you'll find someone else to help you. Maybe Black Mesa THAT WAS A JOKE. HAHA. FAT CHANCE. Anyway, this cake is great. It's so delicious and moist. Look at me still talking when there's Science to do. When I look out there, it makes me GLaD I'm not you. I've experiments to run. There is research to be done. On the people who are still alive. And believe me I am still alive. I'm doing Science and I'm still alive. I feel FANTASTIC and I'm still alive. While you're dying I'll be still alive. And when you're dead I will be still alive."},
					{"name":"Legend of Zelda", "width": "9165px", "file":"zelda8bit", "lyrics": "Link, had come to town. Come to save the princess Zelda, Ganon took her away, now the children don't play, but they will when Link saves the day. HALLELUJAH! Now Link, fill up your hearts, so you can shoot your sword with power. And when you're feeling all down, the faerie will come around so you'll be brave, and not a sissy coward. Now Link, has saved the day, put Ganon in his grave. So now-a Zelda is free, and now our hero shall be. Link, I think your name shall go down into history!"},
					{"name":"Eye of the Tiger", "width": "23900px", "file":"eyeofthetiger", "lyrics": "Risin' up, back on the street, did my time, took my chances. Went the distance, now I'm back on my feet, just a man and his will to survive. So many times, it happens too fast, you change your passion for glory. Don't lose your grip on the dreams of the past, you must fight just to keep them alive. It's the eye of the tiger, it's the cream of the fight, risen' up to the challenge of our rival. And the last known survivor stalks his prey in the night, and he's watchin' us all in the eye of the tiger. Face to face, out in the heat, handgun' tough, stayin' hungry. They stack the odds 'til we take to the street, for we kill with the skill to survive. It's the eye of the tiger, it's the cream of the fight, risen' up to the challenge of our rival. And the last known survivor stalks his prey in the night, and he's watchin' us all in the eye of the tiger. Risin' up, straight to the top. Have the guts, got the glory. Went the distance, now I'm not gonna stop, just a man and his will to survive. It's the eye of the tiger, it's the cream of the fight, risen' up to the challenge of our rival. And the last known survivor stalks his prey in the night, and he's watchin' us all in the eye of the tiger. The eye of the tiger. The eye of the tiger. The eye of the tiger. The eye of the tiger."},
					{"name":"Crazy Train", "width": "19785px", "file":"crazytrain", "lyrics": "All aboard! Ha ha ha ha ha ha haaaa! Ay, Ay, Ay, Ay, Ay, Ay, Ay. Crazy, but that's how it goes. Millions of people living as foes. Maybe it's not too late. To learn how to love and forget how to hate. Mental wounds not healing. Life's a bitter shame. I'm going off the rails on a crazy train. I'm going off the rails on a crazy train. Let's Go! I've listened to preachers, I've listened to fools. I've watched all the dropouts who make their own rules. One person conditioned to rule and control. The media sells it and you live the role. Mental wounds still screaming, driving me insane. I'm going off the rails on a crazy train. I'm going off the rails on a crazy train. I know that things are going wrong for me. You gotta listen to my words. Yeah. Heirs of a cold war, that's what we've become. Inheriting troubles, I'm mentally numb. Crazy, I just cannot bear. I'm living with something' that just isn't fair. Mental wounds not healing, who and what's to blame? I'm going off the rails on a crazy train. I'm going off the rails on a crazy train."},
					{"name":"Stairway to Heaven", "width": "31680px", "file":"stairwaytoheaven", "lyrics": "There's a lady who's sure all that glitters is gold, and she's buying the stairway to heaven. When she gets there she knows, if the stores are all closed with a word she can get what she came for. Ooh, ooh, and she's buying the stairway to heaven. There's a sign on the wall but she wants to be sure, 'cause you know sometimes words have two meanings. In a tree by the brook, there's a songbird who sings, sometimes all of our thoughts are misgiven. Ooh, it makes me wonder. Ooh, it makes me wonder. There's a feeling I get when I look to the west, and my spirit is crying for leaving. In my thoughts I have seen rings of smoke through the trees, and the voices of those who stand looking. Ooh, it makes me wonder. Ooh, it really makes me wonder. And it's whispered that soon if we all call the tune then the piper will lead us to reason. And a new day will dawn for those who stand long and the forests will echo with laughter. If there's a bustle in your hedgerow, don't be alarmed now, it's just a spring clean for the May queen. Yes, there are two paths you can go by, but in the long run there's still time to change the road you're on. And it makes me wonder. Your head is humming and it won't go, in case you don't know, the piper's calling you to join him. Dear lady, can you hear the wind blow, and did you know your stairway lies on the whispering wind. And as we wind on down the road. Our shadows taller than our soul. There walks a lady we all know who shines white light and wants to show how everything still turns to gold. And if you listen very hard the tune will come to you at last. When all are one and one is all. To be a rock and not to roll. And she's buying the stairway to heaven. "},
					{"name":"Master of Puppets", "width": "36050px", "file":"masterofpuppets", "lyrics": "End of passion play. Crumbling away. I'm your source of self-destruction. Veins that pump with fear. Sucking darkest clear. Leading on your death's construction. Taste me you will see. More is all you need. Dedicated to how I'm killing you. Come crawling faster. Obey your master. Your life burns faster. Obey your master. Master. Master of puppets I'm pulling your strings. Twisting your mind and smashing your dreams. Blinded by me you can't see a thing. Just call my name 'cause I'll hear you scream. Master. Master. Just call my name 'cause I'll hear you scream. Master. Master. Needlework the way. Never you betray. Life of death becoming clearer. Pain monopoly. Ritual misery. Chop your breakfast on a mirror. Taste me you will see. More is all you need. Dedicated to how I'm killing you. Come crawling faster. Obey your master. Your life burns faster. Obey your master. Master. Master of puppets I'm pulling your strings, twisting your mind and smashing your dreams. Blinded by me you can't see a thing. Just call my name 'cause I'll hear you scream. Master. Master. Just call my name 'cause I'll hear you scream. Master. Master, master, master, master... Master, master, where's the dreams that I've been after? Master, master, promised only lies. Laughter, laughter, all I hear or see is laughter. Laughter, laughter, laughing at my cries FIX ME! Hell is worth all that. Natural habitat. Just a rhyme without a reason. Never-ending maze. Drift on numbered days. Now your life is out of season. I will occupy. I will help you die. I will run through you. Now I rule you too. Come crawling faster. Obey your master. Your life burns faster. Obey your master. Master. Master of puppets I'm pulling your strings, twisting your mind and smashing your dreams. Blinded by me you can't see a thing. Just call my name 'cause I'll hear you scream. Master. Master. Just call my name 'cause I'll hear you scream. Master. Master."},
					{"name":"Blackened", "width": "29000px", "file":"blackened", "lyrics": "Blackened is the end. Winter it will send. Throwing all you see. Into obscurity. Death of mother Earth. Never a rebirth. Evolution's end. Never will it mend. Never. Fire. To begin whipping dance of the dead. Blackened is the end. To begin whipping dance of the dead, color our world blackened. Blistering of Earth. Terminate it's worth. Deadly nicotine, kills what might have been. Callous frigid chill. Nothing left to kill. Never seen before. Breathing nevermore. Never. Fire. To begin whipping dance of the dead. Blackened is the end. To begin whipping dance of the dead, color our world blackened. Blackened. Opposition (Opposition). Contradiction (Contradiction). Premonition (Premonition). Compromise. Agitation (Agitation). Violation (Violation). Mutilation (Mutilation). Planet dies. Darkest color. Blistered Earth. True death of life. (Termination) Termination (Termination). (Expiration) Expiration (Expiration). Cancellation. Human race. (Expectation) Expectation. (Liberation) Liberation. (Population) Population laid to waste. See our mother put to death (death, death). See our mother die. Smoldering decay. Take her breath away. Millions of our years. In minutes disappears. Darkening in vain. Decadence remains. All is said and done. Never is the sun. Never. Fire. To begin whipping dance of the dead. Blackened is the end. To begin whipping dance of the dead. Fire. Is the outcome of hypocrisy. Darkest potency. In the exit of humanity. Color our world blackened. Blackened."},
					{"name":"Rock Lobster", "width": "19750px", "file":"rocklobster", "lyrics": "We were at a party. His ear lobe fell in the deep. Someone reached in and grabbed it. It was a rock lobster. We were at the beach. Everybody had matching towels. Somebody went under a dock, and there they saw a rock. It wasn't a rock, it was a rock lobster. Motion in the ocean. His air hose broke. Lots of trouble. Lots of bubble. He was in a jam. S'in a giant clam. Down, down. Underneath the waves, mermaids waving'. Wavin' to mermen. Wavin' sea fans. Sea horses saline'. Dolphins wailing'. Red snappers snapping'. Clam shells clapping'. Muscles flexion'. Flippers flipping'. Down, down. Let's rock! Boy's in bikinis. Girls in surfboards. Everybody's rocking'. Everybody's fruggin'. Twistin' 'round the fire. Havin' fun. Bakin' potatoes. Bakin' in the sun. Put on your noseguard. Put on the lifeguard. Pass the tanning butter. Here comes a stingray. There goes a manta-ray. In walked a jelly fish. There goes a dogfish, chased by a catfish. In flew a sea robin. Watch out for that piranha. There goes a narwhale. HERE COMES A BIKINI WHALE!"},
					{"name":"Imperial March", "width": "3340px", "file":"imperialmarch", "lyrics": "I am lord of the Sith step aside. I read minds so there's no place to hide. I can kill you with my lightsaber. I'm friends with the emperor, and I'm coming through step aside."}					
	];
	var randomSong = $('.style audio');
	var randomSongSource = randomSong.attr('data-root');
	
	var images = [
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image1.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image2.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image3.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image4.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image5.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image6.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image7.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image8.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image9.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image10.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image11.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image12.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image13.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image14.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image15.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image16.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image17.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image18.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image19.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image20.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image21.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image22.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image23.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image24.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image25.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image26.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image27.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image28.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image29.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image30.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image31.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image32.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image33.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image34.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image35.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image36.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image37.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image38.jpg"},
		{"file":"http://josephrogermoore.com/wp-content/uploads/2011/08/image39.jpg"}
	];
	
	function secretFunction(){
		var oldCaption = $('.caption').remove();
		var winX = $(window).width();
		var winY = $(window).height();
		var startX = winX + 'px';
		var endX = winX - 300 + 'px';
		var onlyY = winY - 284 + 'px';
		var randomSongOgg = $('.style audio .ogg');
		var randomSongMp3 = $('.style audio .mp3');
		
		var random = Math.floor(Math.random()*(songs.length));

		
		var secretImages = '';
		for(i=0; i<images.length; i++){
			secretImages = secretImages + '<img class="secret-images" src="' + images[i].file + '" alt="" />'; 
		}
		
		var jukebox = '<form action="" class="jukebox">';
		for(i=0;i<songs.length;i++){
			jukebox += '<input type="radio" name="secret-song" value="' + i + '" /><label for="secret-song">' + songs[i].name + '</label>';
		}
		jukebox += '</form>';
		
		toasty.css({'display':'block', 'top':onlyY, 'left':startX});
		audio[0].play();
	    toasty.animate({'left':endX}, 300, function(){
			setTimeout(function(){toasty.animate({'left':startX}, 300, function(){
				toasty.css({'display':'none'});
				$('html').addClass('secret');
				if(nevercalled === true){
					$('footer').after(secretImages);
					$('footer').after(jukebox);
					$('footer').after('<button class="translate alien">Translate</button>');
					nevercalled = false;
				}
				startSong(random);
				
				$('.jukebox input:radio').change(function(){
					$('.caption').remove();
					startSong(this.value);
				});
				startConuntingClicks(5, clickImages);
				$('.translate').click(function(){
					if($(this).hasClass('alien')){
						$(this).removeClass('alien');
						$(this).addClass('english');
						$('.caption').css({'font-family': 'VT323 !important'});
					} else {
						$(this).removeClass('english');
						$(this).addClass('alien');
						$('.caption').css({'font-family': 'Futurama !important'});
					}
				});			
			});}, 400);
		});
		keys = [];
	}

	function checkPattern(arr){
	    for(i=0;i<arr.length;i++){
	        if(arr[i+9]){
	            if(arr[i] == 38 && arr[i+1] == 38 && arr[i+2]== 40 && arr[i+3] ==40 && arr[i+4] == 37 && arr[i+5] == 39 &&arr[i+6] == 37 && arr[i+7] == 39 &&arr[i+8] == 66 && arr[i+9]== 65 ){
	                secretFunction();
	            } else {
	                arr.splice(i,1);
	            }
	        }
	    }
	}

	function checkKey(e){
	    keys.push(e.keyCode);
	    checkPattern(keys); 
	    console.log(keys);    
	}
	
	function startConuntingClicks(num, fx){
		var totalClicks = 0;
		$(document).click(function(e){
			totalClicks += 1;
			if(totalClicks === num){
				fx(e);
				totalClicks = 0;
			}
			return true;
		});
	}
	
	function clickImages(e){
		var rand = Math.floor(Math.random()*images.length);
		var image = $('.secret-images')[rand];
		var imageurl = 'url(' + $(image).attr('src') + ')';
		var newrand = Math.floor(Math.random()*100);
		if(newrand%2){
			$('body').css({'background-image': imageurl, 'background-size':'80%', 'background-position':'180px 120px', 'background-repeat':'no-repeat'});
		} else {
			$('body').css({'background-image': 'none'});
			var left = (e.pageX-($(image).width()/2)) + 'px';
			var top = (e.pageY-($(image).height()/2)) + 'px';
			$('.secret-images').css({'display':'none'});
			$(image).css({'display':'block', 'top': top, 'left': left, 'opacity':1});
			$(image).animate({'opacity':0}, 500, function(){$(image).css({'display':'none'});});
		}
	}
	
	function startSong(num){
		var songname = songs[num].name;
		var lyrics = songs[num].lyrics;
		var songfile = songs[num].file;
		var lyricswidth = songs[num].width;
		var negLyricswidth = '-' + lyricswidth;
		var caption = '<p class="caption">' + lyrics + '</p>';
		var mp3 = randomSongSource + songfile + '.mp3';
		var ogg = randomSongSource + songfile + '.ogg';
		randomSong.after(caption);
		randomSong.html('<source class="mp3" src="' + mp3 + '" /><source class="ogg" src="' + ogg + '" />');
		randomSong[0].load();
		$($('.jukebox input:radio')[num]).attr('checked', 'checked');
		var audioReady = function(){
		        if (randomSong[0].buffered.length > 0) {
		            randomSong[0].play();
					var duration = Math.ceil(randomSong[0].duration *1000);
					$('.caption').css({'width':lyricswidth})
					$('.caption').css({'display':'block'});
					$('.caption').animate({'left':negLyricswidth}, duration, 'linear');
		        } else {
					// console.log(randomSong[0].buffered.length);
		            setTimeout(audioReady, 250);
		        }
		    }
		audioReady();
	}
	
	$(document).keydown(checkKey);
	
});
