$(document).ready(function(){

/* TRACK LOADING TIME */
var st = new Date();

/* PSEUDO URLS */
var max = $('#bg img').length;
var blankload = false;
var index;

function parseHash(){ //validate and adjust hash
	index = window.location.hash.replace('#','');
	if (index == ''){blankload = true;} //load like http://www.frederikring.com
	if (index.match(/\D/)){window.location.hash = '#1';index = '1';} //non-numeric element in hash
	if (index > max || index == 0){window.location.hash = '#1';} //hash is zero or larger than number of images
	if (index == '' || index > max || index == 0){index = '1';} //set index to 1
}

parseHash();

/* RANDOM SLOGANS */
var stupid = ['oh howdy Raquel','O RLY?','smarter than your average bear','if a problem comes along you must whip it','someone stole a bag of peat moss from my living room','full on double rainbow','and at the end Harry just blasts him away'];

for (var n = 0; n < stupid.length - 1; n++) { //shuffle slogans
    var k = n + Math.floor(Math.random() * (stupid.length - n));
    var temp = stupid[k];
    stupid[k] = stupid[n];
    stupid[n] = temp;
}

var slIndex = 0;

function randomSlogan(){
	var slogan = stupid[slIndex];
	$('#slogans').html(slogan);
	slIndex = (slIndex == stupid.length - 1) ? 0 : slIndex + 1;
}

randomSlogan(); //first slogan

$('#slogans').css('cursor','pointer').click(function(){ //update slogans
	_gaq.push(['_trackEvent', 'UI', 'ChangedSlogan']);
	randomSlogan();
});

/* PRELOAD IMAGES */
var numPics = $('#bg img').length;
var picsLoaded = 0;

if ($(window).width() < 575){ //small screen changes UI a little
	_gaq.push(['_trackEvent', 'Pageload', 'LoadWithSmallScreen']);
	$('#loader p').last().html('Tap/Click on the sides of the screen to navigate<br/>forward and backward');
}

$(window).unload(function(){ //track window being closed before loading finished
	_gaq.push(['_trackEvent', 'Pageload', 'ClosedBeforeLoad']);
});

$('#bg img').each(function(){
	var img = $(this);
	img.load(function(){
	picsLoaded++;
	var percent = Math.round(100-(picsLoaded / numPics)*100);
	var text = 'Only '+percent+'% to go!'; 
	$('#percentage').html(text); //text for preloader
	if (picsLoaded == numPics){
			$('#percentage').html('Done!');
			RING();
		}
	});
	img.attr('src', img.attr('src')); //weird IE-Fix
});

function RING(){

$(window).unbind('unload'); //unbind listener for window close
$('#loaderwrap').remove(); //remove preloader

var lt = new Date() - st; //calculate waiting time
_gaq.push(['_trackEvent', 'Pageload', 'Waited for', lt]);

/* CENTERED BACKGROUND */

$('#bg img').each(function(){ //store original image ratio in $.cache
	$(this).data('ratio', $(this).width() / $(this).height());
});

function scaleScene(){ //resize & center

	$('#bg').css({'width':'100%','height':'100%'});

	var screenWidth = $(window).width();
	var screenHeight = $(window).height();

        $('#bg img').each(function(){

			var picRatio = $(this).data('ratio');

            if (screenWidth / screenHeight < picRatio) { //either crop sides
                $(this).css({'height':'100%','width':'','margin-left': -(screenHeight*picRatio-screenWidth)/2, 'margin-top': '0'});//center horizontally
            } else { //or crop top
				$(this).css({'width':'100%', 'height':'','margin-top': -(screenWidth/picRatio-screenHeight)/2.564, 'margin-left': '0'});//center vertically according to golden ratio
            }

        });

}

scaleScene(); //Adjust images to initial browser dimensions
$(window).resize(function(){scaleScene();}); //resize again on window resize

/* SLIDESHOW FUNCTIONS */

	var playing = false; //toggle for playing-state
	var slides; //interval

    function nextPic(){
		index = $('#bg img:visible').nextAll().length ? parseInt(index)+1 : 1;
		window.location.hash = '#'+index;
    }
	function prevPic(){
		index = $('#bg img:visible').prevAll().length ? parseInt(index)-1 : max;
		window.location.hash = '#'+index;
	}
	function playSlideshow(){
		slides = setInterval(nextPic, 3500);
		playing = true;
		$('#playpause').html('Pause');
	}
	function stopSlideshow(){
		clearInterval(slides);
		playing = false;
		$('#playpause').html('Play');
	}

	$('#playpause').css('cursor','pointer').click(function(){
		if (playing){
			_gaq.push(['_trackEvent', 'UI', 'ClickPause']);
			stopSlideshow();
		} else {
			_gaq.push(['_trackEvent', 'UI', 'ClickPlay']);
			setTimeout(function(){ //lag in playback feels VCR-like
				nextPic();
				playSlideshow();
			},100);

		}
	});
	$('#forward').css('cursor','pointer').click(function(){
		_gaq.push(['_trackEvent', 'UI', 'ClickForward']);
		stopSlideshow();
		nextPic();
	});
	$('#back').css('cursor','pointer').click(function(){
		_gaq.push(['_trackEvent', 'UI', 'ClickBack']);
		stopSlideshow();
		prevPic();
	});
	
	$(window).hashchange(function(){ //Handle Hash-Changes
		parseHash();
		_gaq.push(['_trackPageview','/#'+index]); //track pageview
		$('#bg img').hide().eq(index-1).show();
		$('#description p').hide().eq(index-1).show();
	});
		
	/* START SLIDESHOW*/
	$('#bg img').eq(index-1).fadeIn(350,function(){ //sequential fadeIn
		$('#about').fadeIn(350,function(){
			$('#description p').eq(index-1).fadeIn(350,function(){
				$('#navwrapper').fadeIn(350);
			});
		});
	});
	//play slides
	if (blankload){ //no-hash load
		_gaq.push(['_trackEvent', 'Pageload', 'NoHashLoad']);
		playSlideshow(); 
	} else { //load with anchor
		_gaq.push(['_trackEvent', 'Pageload', 'HashLoad']);
		$('#playpause').html('Play');
	}
	
	/* MOUSE WHEEL */
	$('body').mousewheel(function(objEvent,delta){
		_gaq.push(['_trackEvent', 'UI', 'Mousewheel']);
		stopSlideshow();
		if(delta > 0){
			prevPic();
		} else if (delta < 0){
			nextPic();
		}
	});
	
	/* MOBILE DEVICES */
	$('#bigForward').css('cursor','pointer').click(function(){
		_gaq.push(['_trackEvent', 'UI', 'TapForward']);
		stopSlideshow();
		nextPic();
	});
	$('#bigBack').css('cursor','pointer').click(function(){
		_gaq.push(['_trackEvent', 'UI', 'TapBack']);
		stopSlideshow();
		prevPic();
	});
	
	window.onorientationchange = function(){
		location.reload();
	}
	
	/* TRACK HYPERLINKS */
	$('a').click(function(){ //track clicks on <a>s
		_gaq.push(['_trackEvent', 'LinkClicked', $(this).attr('href')]);
	});
}
});
