(function($) {
	
	// SETTINGS //////////////////////////////////////////////////////////////////
	
	if(!window.backgroundUrl) {
		window.backgroundUrl = 'img/backgrounds/';
	}
	var bkgTimer = 30; // frequency in seconds the background will change
	var bkgWidth = 1800;
	var bkgHeight = 1000;
	
	var backgrounds = [
		{ imgUrl: 'alicia_keys.jpg', title: 'Alicia Keys', url: 'http://itunes.apple.com/us/app/alicia-keys-open-mic/id367825113?mt=8' },
		{ imgUrl: 'delane.jpg', title: 'Delane', url: '' },
		{ imgUrl: 'fugitive.jpg', title: 'Fugitive', url: '' },
		{ imgUrl: 'hess_jet.jpg', title: 'Hess Jet', url: 'http://itunes.apple.com/us/app/hess-jet/id409216271?mt=8' },
		{ imgUrl: 'make_it_rain.jpg', title: 'Make It Rain', url: '' },
		{ imgUrl: 'overpass.jpg', title: 'Overpass', url: '' },
		{ imgUrl: 'proving_ground.jpg', title: 'Proving Ground', url: '' },
		{ imgUrl: 'ride.jpg', title: 'Ride', url: '' },
		{ imgUrl: 'skullcandy.jpg', title: 'Peril Lift', url: '' },
		{ imgUrl: 'skullcandy_blow.jpg', title: 'Skull Candy Blow', url: 'http://www.skullcandy.com/ar' },
		{ imgUrl: 'there_really_is_a_way.jpg', title: 'There Really Is a Way', url: '' },
		{ imgUrl: 'unicorns.jpg', title: 'Unicorns', url: '' },
		{ imgUrl: 'rkr_1.jpg', title: 'The Adventures of Timmy&trade;: Run Kitty Run', url: 'http://www.theadventuresoftimmy.com'},
		{ imgUrl: 'rkr_2.jpg', title: 'The Adventures of Timmy&trade;: Run Kitty Run', url: 'http://www.theadventuresoftimmy.com'},
		{ imgUrl: 'rkr_3.jpg', title: 'The Adventures of Timmy&trade;: Run Kitty Run', url: 'http://www.theadventuresoftimmy.com'}
	];
	
	var pages = ['work', 'blog', 'contact', 'jobs'];
	
	
	//////////////////////////////////////////////////////////////////////////////
	
	/*--- Rotating Backgrounds ---*/
	
	var of = backgrounds.length;
	var at = Math.round(Math.random()*(of - 1));
	var changeInterval;
	
	loadBackground(at);
	backgrounds[at].img.appendTo("#background .sizer");
	if(backgrounds[at].url != ''){
		var projectLink = '<a href="'+backgrounds[at].url+'" id="view-project-link" class="view-project-link" target="_blank">&rarr;&nbsp;'+
			backgrounds[at].title
			+'</a>';
		$("#background-title").html(projectLink);
	}
	else
	{
		$("#background-title").html(backgrounds[at].title);
	}
	
	$("#background-title").html();
	
	$('#background img').one('load', function() {
		$('#loader').fadeOut();
		for (var i = 0; i < backgrounds.length; i++) {
			if(backgrounds[i].loaded) continue;
			loadBackground(i);
		}
	});
	
	function loadBackground(index) {
		var data = backgrounds[index];
		return data.img = $('<img>').attr('src', window.backgroundUrl + data.imgUrl).load(function() {
			data.loaded = true;
		});
	}
	
	// update the background with the new number from "at"
	function updateBackground(direction) {
		if (!$('#nav').hasClass('top')) {
			var data = backgrounds[at],
				img = $('#background img'),
				next = data.img,
				transition;

			img.css('position', 'absolute');
			next.css('position', 'absolute');
			next.hide().appendTo('#background .sizer');

			var speed = 800;
			next.show('slide', { direction: direction }, speed, function() {
				img.detach();
			});
			img.hide('slide', { direction: direction == 'left' ? 'right' : 'left' }, speed);
			
			if(data.url != ''){
				var projectLink = '<a href="'+data.url+'" id="view-project-link" class="view-project-link" target="_blank">&rarr;&nbsp;'+
					data.title
					+'</a>';
				$("#background-title").html(projectLink);
			}
			else
			{
				$("#background-title").html(data.title);
			}
			
			$('#nav .showcase').attr('src', 'img/logos/' + data.imgUrl);
		}
	}

	$('#nav .prev-link, #nav .next-link').click(function(evt) {
		evt.preventDefault();
		
		var direction = $(this).hasClass('prev-link') ? 'left' : 'right';
		var nextPos = direction == 'left' ? at - 1 : at + 1;
		nextPos = ((nextPos + of) % of);
		
		// Prevent background switching if animation is not complete or next image not loaded
		var img = backgrounds[at].img;
		var data = backgrounds[nextPos];
		
		var fxQueue = img.queue("fx");
		if(fxQueue.length || !data.loaded)
		{
			return;
		}
		
		at = nextPos;
		updateBackground(direction);
		clearInterval(changeInterval);
		changeInterval = setInterval(nextBkg, bkgTimer*1000);		
	});
	
	function nextBkg() {
		$('#nav .next-link').click();
	}
	
	changeInterval = setInterval(nextBkg, bkgTimer*1000);

	
	/*--- "Backside" ---*/
	/* Disable backside for now, see #207
	$("#backside-link").click(function(evt) {
		evt.preventDefault();
	});
	$('.cssrotatey  #backside-link').click(function() {
		var left = $('<div class="curtain left"></div>').appendTo('body').hide().show('slide', { direction: 'left' }, 1000);
		var right = $('<div class="curtain right"></div>').appendTo('body').hide().show('slide', { direction: 'right' }, 1000, function() {
			
			$('body').toggleClass('flipped');
			$('.mask').toggleClass('flipped');
			if ($('body').hasClass('flipped')) {
				$('#backside-link').appendTo('body').addClass('flipped');
//				$('.chat').fadeIn().find('.name').focus();
			} else {
//				$('.chat').hide();
				$('#backside-link').appendTo('#links').removeClass('flipped');
			}
			
			left.hide('slide', { direction: 'left' }, 1000);
			right.hide('slide', { direction: 'right' }, 1000, function() {
				left.remove();
				right.remove();
			});
		});
	});*/
	
	
	/*--- Section/Page Navigation ---*/
	
	var anchor = location.hash.substr(1);
	var page = "work";
	
	// Scroll to a position
	$.fn.scrollTo = function(value) {
		var scrollTop = this.scrollTop();
		var height = this.height();
		var speed = Math.abs(scrollTop - value) > height ? 1000 : 600;
		this.animate({ scrollTop: value }, speed);
	};
	
	// On any iframe refreshes, scroll back to the top, see #206
	$("iframe").bind('load',function(){
		
		var iframePath = '';
		if($(this)[0].contentWindow.location.pathname){
			iframePath = $(this)[0].contentWindow.location.pathname;
		}
		
		// But not on individual work posts or the initial page load (when the page is scrolled at the top)
		if($(this).attr("rel") == "loadedOnce" && iframePath.match(/^\/post\//i) == null){
			scrollToPages();
		}
		$(this).attr("rel","loadedOnce");
	});
	
	function scrollToPages()
	{
		var bottom = $(".pages").offset().top;
		$('html, body').scrollTo(bottom);
	}
	
	function scrollToPage(anchor) {
		$("#" + page).css("height", 0);
		$("#" + page).css("overflow", "hidden");
		$("#" + anchor).css("height", "auto");
		$("#" + anchor).css("overflow", "visible");
		
		// Scroll to pages
		scrollToPages();
	}
	
	function scrollToSection(anchor) {
	
		var $section = $("#" + anchor);
		var top = $section.offset().top;
		$('html,body').scrollTo(top);
		
		$(".circle").removeClass("current");
		$(".circle." + anchor).addClass("current");
	}
	
	function slideInPage(anchor) {
	
		var nextPagePos = $.inArray(anchor, pages);
		var currentPagePos = $.inArray(page, pages);
	
		// Page is the same -- do nothing
		if(nextPagePos == currentPagePos) {
			// Scroll to pages
			scrollToPages();
			return;
		}
	
		// Use pixel width for starting position instead of percentage due to bug in Chrome
		var pageWidth = $("body").width();
		var startPosition = "-" + pageWidth + "px";
		if(nextPagePos > currentPagePos) {
			startPosition = pageWidth + "px";
		}
		
		var $currentPage = $('#' + page);
		var $nextPage = $('#' + anchor);
		
		// Set starting attributes for animation
		$nextPage.css("height", "100%");
		$nextPage.css("position", "absolute");
		$nextPage.css("left", startPosition);
		
		$currentPage.css("height", "100%");
		$currentPage.css("position", "absolute");
		$currentPage.css("left", 0);
		
		// animate is used instead of slide since iframes need to be 'displayed' in order to 
		// preload content
		$currentPage.animate(
			{
				left: startPosition == "-" + pageWidth + "px" ? pageWidth + "px" : "-" + pageWidth + "px"
			},
			1000,
			function() {
				$currentPage.css("position", "relative");
				$currentPage.css("height", 0);
				$currentPage.css("overflow", "hidden");
			}
		);
		
		$nextPage.animate(
			{
				left: "0"
			},
			1000,
			function() {
				$nextPage.css("position", "relative");
				$nextPage.css("height", "auto");
				$nextPage.css("overflow", "visible");
			}
		);
		
		// Scroll to pages
		scrollToPages();
	}
	
	// Scroll to page on page load
	if (anchor.length) {
		var pagePos = $.inArray(anchor, pages);
		if(pagePos > -1) {
			scrollToPage(anchor);
			page = anchor;
		}
	}
	else {
		$(document).scrollTop(0);
	}
	
	// Scroll to page on hash change
	$(window).hashchange(function() {
		anchor = location.hash.substr(1);
		
		var pagePos = $.inArray(anchor, pages);
		if(pagePos > -1) {
			scrollToPage(anchor);
			page = anchor;
		}
	});
	
	if(navigator.userAgent.match(/iPad/i)){
		// Don't use iFrames with iPad--clicking hashtag links will redirect iPad users to a different page
		$('a.replace-ipad').click(function(){
			window.location = $(this).attr("href").substr(1)+".php";
		});
	}
	
	// Scroll to section or page on link click
	$('a[href*=#]').click(function(evt) {
		if($(this).attr('href').indexOf("http://")) {
		evt.preventDefault();
		
		anchor = $(this).attr('href').substr(1);
		if (!anchor) return;
		
		// Prevent anchor scrolling in iPad
		if(navigator.userAgent.match(/iPad/i)){
			evt.preventDefault();
			return;
		}
		
		var nextPagePos = $.inArray(anchor, pages);
		var currentPagePos = $.inArray(page, pages);
		
		// Slide in page
		if (
			nextPagePos > -1
			&& currentPagePos > -1
		) {
			slideInPage(anchor);
		}
		// Scroll to page
		else if(nextPagePos > -1) {
			scrollToPage(anchor);
		}
		// Scroll to section
		else
		{
			scrollToSection(anchor);
		}
		
		if(nextPagePos > -1) {
			page = anchor;
		}
			
		if (anchor == "work") {
			// Checks to see if the user is still in the work.mediarain.com domain
			if ($("#work-iframe")[0].contentWindow.location.href.indexOf($("#work-iframe").attr('src')) < 0) {
				$("#work-iframe")[0].contentWindow.location = $("#work-iframe").attr("src");
			}
		}
		else if (anchor == "blog") {
			if ($("#blog-iframe")[0].contentWindow.location.href.indexOf($("#blog-iframe").attr('src')) < 0) {
				$("#blog-iframe")[0].contentWindow.location = $("#blog-iframe").attr("src");
			}
		}
		
		if (history.pushState) history.pushState({}, '', '#' + anchor);
	}
	});
	
	function onResize() {
		if (anchor != "") {
			var $section = $("#" + anchor);
			var top = $section.offset().top;
			$(document).scrollTop(top);
		}
		
		var background = $('#background'),
				sizer = background.find('.sizer'),
				bwidth = background.width(),
				bheight = background.height(),
				scale;
		if (bwidth/bkgWidth > bheight/bkgHeight) {
			scale = bwidth/bkgWidth;
			sizer.css('margin-left', '').css('margin-top', -(bkgHeight*scale - bheight)/2);
		} else {
			scale = bheight/bkgHeight;
			sizer.css('margin-top', '').css('margin-left', -(bkgWidth*scale - bwidth)/2);
		}
		
		sizer.width(bkgWidth*scale).height(bkgHeight*scale);
	}
	$(window).resize(onResize).resize();
	
	// keep the circles at the top of the page if scrolled past their position, and nav
	function updateScroll() {
		var nav = $('#nav');
		var scrollTop = $(document).scrollTop();
		
		if(scrollTop > 4000){
			nav.css("top", scrollTop);
		} else {
			nav.css("top", "");
		}
		
		
		var navHeight = nav.outerHeight();
		var sectionHeight = $(".section").outerHeight();
		var navTop = sectionHeight * 3 + navHeight; // 3 sections
		
		if (scrollTop > navTop) {
			if (!nav.hasClass('top')) nav.addClass('top');
			if (nav.hasClass('bottom')) nav.removeClass('bottom');
		} else if (scrollTop > navTop - navHeight) {
			if (!nav.hasClass('bottom')) nav.addClass('bottom');
			if (nav.hasClass('top')) nav.removeClass('top');
		} else {
			if (nav.hasClass('top')) nav.removeClass('top');
			if (nav.hasClass('bottom')) nav.removeClass('bottom');
		}
		
		var subnav = $('#subnav');
		var subnavTop = sectionHeight/2 - navHeight;
		var subnavBottom = sectionHeight * 3; // 3 sections
		if (scrollTop > subnavBottom) {
			if (!subnav.hasClass('bottom')) subnav.addClass('bottom');
			if (subnav.hasClass('top')) subnav.removeClass('top');
		} else if (scrollTop > subnavTop) {
			if (!subnav.hasClass('top')) subnav.addClass('top');
			if (subnav.hasClass('bottom')) subnav.removeClass('bottom');
		} else {
			if (subnav.hasClass('top')) subnav.removeClass('top');
			if (subnav.hasClass('bottom')) subnav.removeClass('bottom');
		}
	}
	
	$(window).scroll(updateScroll);
	
	
	/*--- Contact Page ---*/
	
	$("#contact-form").submit(function(evt)
	{
		evt.preventDefault();
		
		var $form = $(this);
		var formData = $form.serialize();
		var formAction = $form.attr("action");
		$.post(
			formAction, 
			formData, 
			function(data) {
				$message = $("#contact-message");
				
				if(data == '1') {
					$message.html("You did it. You are now harnessing the awesome power of the \"net\".");		
					// Clear inputs
					$form.find(":input").each(function(key, value) {
						$(this).val("");
					});
				}
				else {
					$message.html("Oops. Enter all required fields.");
				}
				
				Cufon.replace("#contact-message", {fontWeight: 300});
				$message.fadeIn();
			}
		);
	});
	
	
	/*--- Jobs Page ---*/
	
	// Toggle content visibility when expandable list item clicked
	$(".expandable h3 a").click(function(evt) {
		evt.preventDefault();
		
		$(this).parent().next(".expandable-content").slideToggle();
	});
	
	
	/*--- Chat ---*/
	/*
	$('.chat .input').attr('disable', true);
	$('.chat .name').keydown(function(event) {
		if (event.keyCode == 13) {
			chat.connect($(this).val());
		}
	});
	$('.chat .input').keydown(function(event) {
		if (event.keyCode == 13) sendChat();
	});
	$('.chat button').click(sendChat);
	
	chat.on('connect', function() {
		$('<p><strong>CONNECTED</strong></p>').sendTo('.chat .output');
		$('.chat .input').attr('disable', false).focus();
	}).on('disconnect', function() {
		$('.chat .input').attr('disable', true);
		$('.chat .name').focus();
		$('<p><strong>DISCONNECTED</strong></p>').sendTo('.chat .output');
	}).on('join', function(data) {
		console.log('join', data);
		$('<p><strong></strong> <em></em> <em class="date"></em></p>')
				.find('strong').text(data.name).end()
				.find('em:first').text('joined the conversation').end()
				.find('em:last').text(data.date).end()
				.sendTo('.chat .output');
	}).on('leave', function(data) {
		console.log('leave', data);
		$('<p><strong></strong> <em></em> <em class="date"></em></p>')
				.find('strong').text(data.name).end()
				.find('em:first').text('left the conversation').end()
				.find('em:last').text(data.date).end()
				.sendTo('.chat .output');
	}).on('rename', function(data) {
		console.log('rename', data);
		$('<p><strong></strong> <em></em> <em class="date"></em></p>')
				.find('strong').text(data.previous).end()
				.find('em:first').text('is now known as ' + data.name).end()
				.find('em:last').text(data.date).end()
				.sendTo('.chat .output');
	}).on('message', function(data) {
		console.log('message', data);
		$('<p><strong></strong> <em class="date"></em> <span></span></p>')
				.find('strong').text(data.name).end()
				.find('em').text(data.date).end()
				.find('span').text(data.message).end()
				.sendTo('.chat .output');
	}).on('error', function(error) {
		alert('An error has occurred: ' + error.error);
	});
	
	
	$.fn.sendTo = function(selector) {
		var elem = $(selector);
		var sHeight = elem[0].scrollHeight, sTop = elem.scrollTop(), height = elem.innerHeight();
		var scrollDown = (sHeight - height == sTop);
		elem.append(this);
		if (scrollDown) elem.scrollTop(elem[0].scrollHeight - height);
	};
	
	
	function sendChat() {
		var input = $('.chat .input'), msg = input.val().replace(/^\s+|\s+$/g, '');
		if (!chat.name) {
			$('.chat .name').focus();
			alert('Please enter a name and press ENTER before chatting.');
		}
		if (!msg) return;
		chat.send(msg);
		input.val('').focus();
	}
	*/
	
})(jQuery);
