$(document).ready(function () {
	$('#hi_there').bind("click", startPortfolio);
	$('#hi_there').hover(

	function () {
		$('#ok_go').addClass("bright");
	}, function () {
		$('#ok_go').removeClass("bright");
	});

	g_gallery = $('div#gallery');
	$('#category_choice').hover(showCategories, hideCategories);
	$('ul#category_list li').click(clickCategory);

	$('div#gallery_right_box').bind("click", onNextPortfolioClick);
	$('div#gallery_left_box').bind("click", onPrevPortfolioClick);

	$("img.gallery_image").live("mousedown", onGalleryMouseDown);
	$("img.gallery_image").live("touchstart", onGalleryMouseDown);

	$(window).resize(function () {
		onWindowResize();
	});

	$(window).keydown(function (evt) {
		if (evt.which == 39) onNextPortfolioClick();
		if (evt.which == 37) onPrevPortfolioClick();
	});

	onWindowResize();
});

var g_is_categories_tweening = false;
var g_portfolio_focus = {};
var g_is_portfolio_started = false;
var g_resize_timeout = 0;
var g_is_dragging_gallery = false;
var g_dragging_origin = {};
var g_gallery_origin = 0;
var g_gallery_drag_interval = 0;
var g_gallery_last_position = 0;
var g_gallery_curr_position = 0;
var g_last_time = 0;
var g_gallery_friction = 0.85;
var g_gallery = {};

function onGalleryMouseDown(event) {
	event.preventDefault();
	event = abstractTouchEvent(event);

	g_is_dragging_gallery = true;

	stopIntegration();
	stopAllPortfolioAnimations();

	if (g_is_categories_tweening || !g_is_portfolio_started) return;

	g_gallery_origin = parseInt(g_gallery.css('margin-left'));
	g_gallery_last_position = g_gallery_origin;
	g_gallery_curr_position = g_gallery_origin;
	g_dragging_origin = {
		x: event.pageX,
		y: event.pageY
	};

	$(window).bind("mousemove", onGalleryDragging);
	$(window).bind("mouseup", onGalleryMouseUp);

	$(window).bind("touchmove", onGalleryDragging);
	$(window).bind("touchend", onGalleryMouseUp);
}

function abstractTouchEvent(event) {
	if (event.originalEvent.touches && event.originalEvent.touches.length) {
		event = event.originalEvent.touches[0];
	} else if (event.originalEvent.changedTouches && event.originalEvent.changedTouches.length) {
		event = event.originalEvent.changedTouches[0];
	}

	return event;
}

function onGalleryDragging(event) {
	event = abstractTouchEvent(event);

	var new_pos = g_gallery_origin - (g_dragging_origin.x - event.pageX);
	var cur_pos = parseInt(g_gallery.css('margin-left'));

	g_gallery_curr_position = new_pos;
	g_gallery.css('margin-left', new_pos);

	var t = new Date().getTime();
	if (t - g_last_time > 50 || typeof (g_last_time) == 'undefined') {
		g_gallery_last_position = cur_pos;
		g_last_time = new Date().getTime();
	}
}

function onGalleryIntegrate() {
	return;

	if (g_is_dragging_gallery) return;

	var t = new Date().getTime();
	var now_pos = g_gallery_curr_position;

	if (!isNaN(g_gallery_last_position)) {
		var calc_pos = now_pos + ((now_pos - g_gallery_last_position) * g_gallery_friction);

		g_gallery.css('margin-left', Math.floor(calc_pos));

		var diff = Math.abs(now_pos - calc_pos);

		if (diff < 0.5) {
			stopIntegration();
			return;
		}

		g_gallery_curr_position = calc_pos;
		g_gallery_last_position = now_pos;
	} else {
		g_gallery_last_position = now_pos;
	}
}

function stopIntegration() {
	if (isNaN(g_gallery_drag_interval)) return;

	window.clearInterval(g_gallery_drag_interval);
	g_gallery_drag_interval = null;
}

function startIntegration() {
	stopIntegration();
	g_gallery_drag_interval = window.setInterval("onGalleryIntegrate()", 50);
}

function onGalleryMouseUp(event) {
	$(window).unbind("mousemove", onGalleryDragging);
	$(window).unbind("touchmove", onGalleryDragging);
	g_is_dragging_gallery = false;
	findCenteredImage();
	startIntegration();
}

function findCenteredImage() {
	var images = $('div#gallery img');
	var docWidth = getDocWidth();
	var cur_pos = parseInt(g_gallery.css('margin-left'));
	var center_pos = -cur_pos + (docWidth * 0.5);
	var totalWidth = 0;

	for (var i = 0; i < images.size(); i++) {
		var img = images[i];
		totalWidth += parseInt($(img).width());

		if (totalWidth >= center_pos || i == (images.size() - 1)) {
			g_portfolio_focus = $(img);
			onTransitionToFocus();
			return;
		}
	}
}

function showCategories() {
	if (g_is_categories_tweening) return;

	g_is_categories_tweening = true;

	var time = 150;
	var item_count = $('ul#category_list li').size();

	$('ul#category_list li').removeClass("hidden").addClass("selectable");
	$('img#cat_arrow').animate({
		rotate: 180
	}, time);
	$('ul#category_list').animate({
		height: item_count * 15 + 8
	}, time, 'swing', onShowCategoriesComplete);
}

function onNextPortfolioClick() {
	if (!g_is_portfolio_started) {
		startPortfolio();
	}

	var next = $(g_portfolio_focus).next('img');
	log("next: " + next);
	if (next.size() != 0) {
		g_portfolio_focus = next;
		onTransitionToFocus();
	}
}

function onPrevPortfolioClick() {
	var prev = g_portfolio_focus.prev('img');
	if (prev.size() != 0) {
		g_portfolio_focus = prev;
		onTransitionToFocus();
	}
}

function log(msg) {
	try	{
		if(console.log)
			console.log(msg);
	} catch(e) {}		
}

function stopAllPortfolioAnimations() {
	$('div#gallery,div#gallery_right_box,div#gallery_left_box').stop();
}

function onTransitionToFocus(forced_speed) {
	if(g_portfolio_focus == null) {
		g_portfolio_focus = $('img.gallery_image').first();
	}
	
	stopAllPortfolioAnimations();
	stopIntegration();

	var caption = $(g_portfolio_focus).attr('data-caption');
	var count = $(g_portfolio_focus).attr('data-count');

	var docWidth = getDocWidth();
	var imgWidth = $(g_portfolio_focus).width();
	var imgLeft = Math.round((docWidth - imgWidth) * 0.5);
	var galleryDest = -($(g_portfolio_focus).position().left - imgLeft) + $('div#gallery').offset().left;
		galleryDest -= 0.05;
	var rightWidth = getDocWidth() - (imgLeft + imgWidth);
	var dist = Math.abs(galleryDest - parseInt(g_gallery.css('margin-left')));
		dist = Math.max(dist, Math.abs(parseInt($('div#gallery_right_box').css('width')) - (rightWidth)));
	var speed = Math.max(100, Math.min(Math.floor(dist), 500));

	if (forced_speed !== undefined) {
		speed = forced_speed;
	}
	
	$('span#caption').html(caption);
	$('span#num').html(count);
	$('div#gallery').animate({
		marginLeft: galleryDest
	}, { speed:speed });
	$('div#gallery_right_box').animate({
		left: imgLeft + imgWidth,
		width: rightWidth
	}, speed);
	$('div#gallery_left_box').animate({
		left: "0",
		width: imgLeft
	}, speed, "swing", onStartPortfolioComplete);
}

function hideCategories(event, speed) {
	if (g_is_categories_tweening) return;

	speed = typeof (speed) != 'undefined' ? speed : 42;
	g_is_categories_tweening = true;

	$('img#cat_arrow').animate({
		rotate: 0
	}, speed);
	$('ul#category_list').animate({
		height: 9
	}, speed, 'swing', onHideCategoriesComplete);
}

function onHideCategoriesComplete() {
	g_is_categories_tweening = false;
	$('ul#category_list li').addClass("hidden").removeClass("selectable");
	$('ul#category_list li.selected').removeClass("hidden");
}

function onShowCategoriesComplete() {
	g_is_categories_tweening = false;
}

function clickCategory(evt) {
	if (!g_is_portfolio_started) {
		startPortfolio();
	}

	$('ul#category_list li').removeClass("selected");
	$(evt.target).addClass("selected");
	hideCategories(null, 1);

	var category_id = $(evt.target).attr('data-id');
	$('span#artwork').load('/portfolio.php?id=' + category_id, onCategoryLoaded);
}

function onCategoryLoaded() {
	$('span#total').html($('img.gallery_image').size());
	g_portfolio_focus = $($('img.gallery_image')[0]);
	
	$(g_portfolio_focus).bind('load', webkitDelay);	
}

function webkitDelay() {
	setTimeout('onTransitionToFocus()', 100);
}

function startPortfolio() {
	if (g_is_portfolio_started) return;

	g_is_portfolio_started = true;
	var speed = 300;

	var item_count = $('img.gallery_image').size();
	g_portfolio_focus = $('img.gallery_image:nth-child(2n)');

	$('div#hi_there,div#gallery_edge').animate({
		marginLeft: -468
	}, speed);
	$('div#hutch').animate({
		opacity: 1.0
	}, speed).removeClass('hidden');

	onTransitionToFocus(500);
}

function onStartPortfolioComplete() {
	return;
}

function centerPortfolioOn() {
	var position = g_portfolio_focus.position();
}

function getDocWidth() {
	return Math.min($(document).width(), $(window).width());
}

function onPortfolioResize() {

}

function onWindowResize() {
	if (!g_is_portfolio_started) {
		$('div#gallery_right_box').css("left", "468px").width(getDocWidth() - 468);
	} else {
		var docWidth = getDocWidth();
		var imgWidth = g_portfolio_focus.width();
		var imgLeft = (docWidth - imgWidth) / 2;
		var rightWidth = getDocWidth() - (imgLeft + imgWidth);

		$('div#gallery_right_box').css("width", rightWidth).css("left", imgLeft + imgWidth);
		$('div#gallery_left_box').css("width", imgLeft);
		clearInterval(g_resize_timeout);
		g_resize_timeout = setTimeout(resizePortfolio, 250);
	}
}

function resizePortfolio() {
	clearInterval(g_resize_timeout);
	onTransitionToFocus();
}
