$(function () {

	$('#menu a').add('a.scroll').click(function () {
		var target = $(this.hash);
		var hash = this.hash;
		if (target.length) {
			var targetOffset = target.offset().top;
			$('html,body').animate({scrollTop: targetOffset}, 600);
			return false;
		}
	});

	/*
 	 * This is using lots of vars because it gets called all the time
 	 * on scroll, so it needs to be fast.
	 */
	var nav = $('#menu');
	nav.css({'position': 'absolute'});
	var left_point = $('#header').offset().left;
	var topmost_point = nav.offset().top;
	var padding_top = 110; // MAGIC NUMBER
	var real_top = topmost_point - padding_top;
	var the_window = $(window);
	var nav_is_fixed = (nav.css('position') == 'fixed');

	the_window.scroll(function () {
		if (the_window.scrollTop() > real_top) {
			if ($.browser.msie && $.browser.version == "6.0") {
				nav.css('top', the_window.scrollTop() + padding_top);
			} else if (!nav_is_fixed) {
				nav.css({
					left: left_point,
					top: padding_top,
					position: 'fixed'
				});
				nav_is_fixed = true;
			}
		} else {
			if (nav_is_fixed) {
				nav.css({
					position: 'absolute',
					top: topmost_point,
					left: ''
				});
				nav_is_fixed = false;
			}
		}

		if (getScrollY() > 100) {
			$('#back_to_top').fadeIn();
		} else {
			$('#back_to_top').fadeOut();
		}

	});

	the_window.resize(function () {
		left_point = $('#header').offset().left;
		if (nav_is_fixed) {
			nav.css('left', left_point);
		}
	});

	$('#back_to_top').bind('click', function() {
		$('html,body').animate({scrollTop: 0}, 600);
		return false;
	});

	// portfolio
	var initalImgIndex = random($('#case-pagination a').length);
	var initalImg = $('#case-pagination a:eq('+ initalImgIndex +')');
	initalImg.addClass('select');
	$('#case-image').css('background-image', 'url(' + initalImg.attr('href') + ')');

	$('#case-pagination a').click(function() {
		$('#case-pagination a').removeClass('select');
		var href = $(this).attr('href');
		$('#case-image').fadeOut(500, function() {
			$('#case-image').css('background-image', 'url(' + href + ')').fadeIn(500);
		});
		$(this).addClass('select');
		return false;
	});

	function random(max) {
		var x = Math.floor(Math.random() * max);
		if (x > 0) x = x - 1;
		return x;
	}

});

function getScrollY() {
	var scrOfX = 0, scrOfY = 0;
	if( typeof( window.pageYOffset ) == 'number' ) {
		scrOfY = window.pageYOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		scrOfY = document.body.scrollTop;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		scrOfY = document.documentElement.scrollTop;
	}
	return scrOfY;
}



