var isInitialLoad = true, inDetailMode=false, startExample = 0;
var $examples = null, $detail = null, $exampleControls = null, $detailControls = null, $mainContent = null, $detailContent = null;

$(document).ready(function() {
	$examples = $('#work_examples div.examples');
	$detail = $('#detail_view');
	$exampleControls = $('#work_examples div.controls');
	$detailControls = $('#detail_view div.controls');
	$mainContent = $('#content');
	$detailContent = $('#detail_view div.content');

	// Hide elements
	$('.covert').hide().removeClass('covert');
	
	// Setup page split
	$('body').addClass('page_closed');
	$('#header').hide().css({ top: 250 });
	$('#info_container').hide().css({ top: 250 });
	$('#main_container').hide();
	$('#footer').hide();
	$('#work_examples div.controls_wrapper').hide();
	if(inDetailMode)
		$detail.hide();
	
	// Disable all nav links & add navigation events
	$('a').not("a[href^='http']").each(function() {
		$(this)[0].onclick = function() { return false; };
	});
	$('#nav a').not("a[href^='http']").click(navHandler);
	
	// Work Example Slide Toggle
	$exampleControls.find('p.display_toggle a').click(function() { toggleWorkExamples(); });
	
	activateWorkExampleMouseWheel();
	
	// Bind click to each work example item
	$('#work_examples div.examples ul li a').click(showDetail);
	
	// Activate close detail view button
	$detailControls.find('p.close_display a').click(function(e) {
		$examples.trigger('stop');
		$detail.slideUp('slow');
		$mainContent.fadeTo('slow', 1.0, function() {
			if ($.browser.msie)
				this.style.removeAttribute('filter'); 
		});
		$examples.find('div.screen').fadeTo('slow', 0, function() { $(this).hide(); });
		inDetailMode = false;
		isInitialLoad = true;
		activateWorkExampleMouseWheel();
	});
	
	// Bind events to detail view controls
	$detailControls.find('p.next a').click(function() { 
		isInitialLoad = false;
		$exampleControls.find('p.next a').trigger('click');
		pauseSlideshow();
	});
	$detailControls.find('p.previous a').click(function() { 
		isInitialLoad = false;
		$exampleControls.find('p.previous a').trigger('click'); 
		pauseSlideshow();
	});
	$detailControls.find('p.play a').click(function() { playSlideshow(); });
	$detailControls.find('p.pause a').click(function() { pauseSlideshow(); });
	
	// Media handler
	$detailContent.find('div.media').live('click', function() {
		$examples.trigger('stop');
		var content = $(this).find('p.flash').html();
		if(content != null && content.length > 0)
			$(this).html(content);
	});
	
	// Find current page
	var relativeUrl = window.location.href.replace('http://www.sassafrascreative.com','');
	initPage(relativeUrl);
});


$(window).load(function() {
	// Activate thumbnails
	$examples.serialScroll({
		items: 'li',
		prev: '#work_examples div.controls p.previous a',
		next: '#work_examples div.controls p.next a',
		axis: 'x',
		duration: 400,
		force: true,
		constant: false,
		jump: true,
		cycle: true,
		lazy: true,
		stop: true,
		lock: true,
		start: startExample, 
		interval: 5000,
		onBefore: function(e, ele, $pane, $items, pos) {
			/**
			 * 'this' is the triggered element 
			 * e is the event object
			 * elem is the element we'll be scrolling to
			 * $pane is the element being scrolled
			 * $items is the items collection at this moment
			 * pos is the position of elem in the collection
			 * if it returns false, the event will be ignored
			 */
			 if(inDetailMode && !isInitialLoad) {
			 	showDetailLoading();
				loadWorkExample($(ele).children('a').attr('href'));
				isInitialLoad = false;
			 }
		}
	});
	$examples.trigger('stop');
	
	var speed = 600;
	$('#header').fadeIn(800).animate({ opacity: 1.0 }, 600, function() {			
		$('#header').animate({ top: 0 }, speed);
		$('body').removeClass('page_closed');
		$('#info_container').animate({ top: 0 }, { queue: false, duration: speed }).slideDown(speed, function() {
			$('#work_examples div.controls_wrapper').slideDown();
		
			var showContent = function() {
				$('#main_container').fadeIn('slow', function() {
					if ($.browser.msie)
						this.style.removeAttribute('filter'); 
				});
				$('#footer').fadeIn('slow', function() {
					if ($.browser.msie)
						this.style.removeAttribute('filter'); 
				});
			};
			if(inDetailMode) {
				$detail.slideDown();
				showContent();
			}
			else
				toggleWorkExamples(showContent);
		});
	});
});

/////
// Functions
////

function playSlideshow()
{
	$examples.trigger('start');
	$detailControls.find('p.pause').show();
	$detailControls.find('p.play').hide();
}

function pauseSlideshow()
{
	$examples.trigger('stop');
	$detailControls.find('p.pause').hide();
	$detailControls.find('p.play').show();
}

function toggleWorkExamples(callback) {
	$examples.slideToggle('slow', function() {
		$('#work_examples div:first').toggleClass('closed').toggleClass('open');
		if(callback)
			callback();
	});
}

function showDetailLoading() {
	$detailContent.fadeOut('fast');
}

function showDetail() {
	deactivateWorkExampleMouseWheel();
	inDetailMode = true;
	isInitialLoad = true;
	$detail.slideDown('slow');
	$mainContent.fadeTo('slow', 0);
	$examples.find('div.screen').show().fadeTo('slow', 0.8);
	showDetailLoading();
	loadWorkExample($(this).attr('href'));
}

function initPage(url) {	
	if(inDetailMode) {
		deactivateWorkExampleMouseWheel();
		$detailContent.find('div.text').columnize({ lastNeverTallest: true });
		$examples.find('div.screen').fadeTo('fast', 0.8);
		$("#nav a[href='/']").trigger('click');
	}
	else {
		$examples.find('div.screen').fadeTo('slow', 0).hide();
		var curLink = $("#nav a[href='" + url + "']:last");
		curLink.parents('#nav li').addClass('active');
		curLink.parents('#nav ul').show();
		columnizeContent(curLink);
	}
}

function navHandler(e) {
	var curTarget = $(this).parent();
	var isActive = curTarget.hasClass('active');
	var subLinks = curTarget.children('ul');
	var targetHref = curTarget.children('a').attr('href');
	
	if(!isInitialLoad)
		$detailControls.find('p.close_display a').trigger('click');
	else
		isInitialLoad = false;
	
	if(isActive && subLinks.size() == 0)
		return;
		
	if(!isActive || curTarget.find("li a[href='" + targetHref + "']").size() == 0) {
		$mainContent.fadeOut('fast', function() {
			$.post(targetHref, { is_async: "true" }, function(data) {
				$mainContent.html('<div></div>');
				$mainContent.find('div').html(data);
				$mainContent.fadeIn('fast', function() {
					if ($.browser.msie)
						this.style.removeAttribute('filter'); 
				});
				columnizeContent(curTarget.children('a:first'));
			}, 'html');
		});
	}
		
	if(!isActive) {
		curTarget.parent().find('li').removeClass('active');
		curTarget.parent().children('li').find('ul').slideUp('fast');
		
		curTarget.addClass('active');
	}
	
	subLinks.find('li').removeClass('active');
	if(subLinks.size() > 0) {
		subLinks.find('li').children("a[href='" + targetHref + "']").parent().addClass('active');
		subLinks.slideDown('fast');
	}
}

function columnizeContent(curLink) {
	if(!curLink.hasClass('one_col') && !curLink.hasClass('two_cols') && !curLink.hasClass('two_cols') && !curLink.hasClass('four_cols'))
		return;
		
	if(curLink.hasClass('one_col')) {
		$mainContent.find('div:first').addClass('one_col');
		return;
	}
	
	var num_cols = 2;
	if(curLink.hasClass('two_cols'))
		num_cols = 2;
	else if(curLink.hasClass('three_cols'))
		num_cols = 3;
	else if(curLink.hasClass('four_cols'))
		num_cols = 4;
	
	$mainContent.columnize({
		columns: num_cols,
		lastNeverTallest: true    
	});
}

function activateWorkExampleMouseWheel() {
	$examples.mousewheel(function(event, delta) {
		if(delta > 0)
			$exampleControls.find('p.previous a').trigger('click');
		else
			$exampleControls.find('p.next a').trigger('click');
		return false;
	});
}

function deactivateWorkExampleMouseWheel() {
	$examples.unbind('mousewheel');
}

function loadWorkExample(url) {
	$detail.find('div.loading').fadeIn('fast');
	$.post(url, { is_async: "true" }, function(data) {
		$('img', data).load(function() {
			$detail.find('div.loading').fadeOut('fast');
			$detailContent.fadeIn('fast', function() {
				if ($.browser.msie)
					this.style.removeAttribute('filter'); 
			});
			$detailContent.html(data);
			//$detailContent.find('div.text').columnize({ lastNeverTallest: true });
			isInitialLoad = false;
		});
	}, 'html');
}