Cufon.replace("h1", { hover: true });
Cufon.replace("p.tagline, body>.header h2, body>.header .two-columns h3, body>.content-parent .three-columns h4, .projects h3");
Cufon.replace("body>.header ul.menu li, body>.content-parent h3", { hover: true });

$("a.contrast").click(function() { $("body").toggleClass("hc"); createCookie("style", $("body").hasClass("hc") ? "hc" : "", 365); return false; });
if (readCookie("style") == "hc" && !$("body").hasClass("hc"))
	$("a.contrast").click();


String.prototype.startsWith = function(start) {
	var str = this.substr(0, Math.min(this.length, start.length));
	return str == start;
};


var
	intro = null
,	introTimer = null
,	introAuto = true
,	introPos = 0
,	introItems = 8
,	introSlideInTime = 2000
,	introSlideOutTime = 1000
,	introItemTime = 13000
,	introRulerStep = Math.round(930 / introItems)
,	introNavH = 0
,	introContentH = 0
,	introW = 0
,	pl = $("body").hasClass("pl")
;


function introStop() { if (introTimer) { clearTimeout(introTimer); introTimer = null; } }


function introPause(dir)
{
	introStop();
	introAuto = !introAuto;
	if (introAuto)
		introPlay();
}


function introPlay() { introStop(); introTimer = setTimeout("introChange()", introItemTime); }


function introChange(dir, manual)
{
	if (!dir)
		dir = 1;

	if (manual)
		introStop();

	var next = intro.find("> .content.current").stop(true).animate({ left: (-dir * introW) + "px" }, introSlideOutTime).removeClass("current");
	next = (dir < 0) ? next.prev(".content") : next.next(".content");
	if (!next.length)
	{
		next = (dir < 0) ? intro.find("> .content:last") : intro.find("> .content:first");
		introPos = (dir < 0) ? introItems - 1 : 0;
	}
	else
		introPos += dir;

	var ruler = intro.find(".ruler > a");
	ruler.stop(true).animate({ left: (introPos * introRulerStep) + "px"}, introSlideInTime);
	if (!next.is(":animated"))
		next.css("left", (dir * introW) + "px");
	next.addClass("current").show().stop(true).animate({ left: "0px" }, introSlideInTime);
	ruler.find("span").text(next.find(".info > span:first").data("info"));
	if (introAuto)
		introPlay();
}


function introChangeTo(item)
{
	var current = intro.find("> .content.current");
	dir = (item > introPos) ? 1 : -1;
	if (introPos != item)
		current.stop(true).animate({ left: (-dir * introW) + "px" }, introSlideOutTime).removeClass("current");
	next = intro.find("> .content:eq(" + item + ")");
	var ruler = intro.find("> .ruler > a");
	ruler.stop(true).animate({ left: (item * introRulerStep) + "px"}, introSlideInTime);
	if (introPos != item)
		next.addClass("current").css("left", (dir * introW) + "px").show().stop(true).animate({ left: "0px" }, introSlideInTime);
	ruler.find("span").text(next.find(".info > span:first").data("info"));
	introPos = item;
}


var tooltip = null;


function tooltipShow(element, text)
{
	tooltip.find("span").text(text);

	var IEOffset = { left: 0 };
	if ($.browser.msie)
		IEOffset = $("body").offset();
	var offset = element.offset();

	tooltip.css({ left: (offset.left + element.width() - IEOffset.left - 10) + "px", top: (offset.top + (element.outerHeight() - tooltip.outerHeight()) / 2) + "px" }).show();
}


var tooltipAlt = null;


function tooltipAltShow(element, text)
{
	var i = text.indexOf(":");
	tooltipAlt.find("span").empty().append("<strong>" + text.substring(0, i + 1) + "</strong> " + text.substring(i + 1));

	var IEOffset = { left: 0 };
	if ($.browser.msie)
		IEOffset = $("body").offset();
	var offset = element.offset();

	tooltipAlt.css({ left: (offset.left + element.width() - IEOffset.left) + "px", top: (offset.top + (element.outerHeight() - tooltipAlt.outerHeight()) / 2) + "px" }).show();
}


/*
** site map magix
*/

$("#site-map:first").clone().prependTo("body");
$(".site-map:last").remove();
var sitemap = $("#site-map");
var sitemapH = -sitemap.outerHeight();
sitemap.css("margin-top", sitemapH + "px").hide();

$("a[href=#site-map]").click(function()
{
	if (sitemap.is(":animated"))
		return false;
	if (sitemap.is(":visible"))
		sitemap.stop(true).animate({ marginTop: sitemapH + "px" }, 750, "swing", function() { $(this).hide(); });
	else
		sitemap.show().stop(true).animate({ marginTop: "0px" }, 750, "swing");
	return false;
});


/*
** tooltip
*/
if ($(".tooltip-alt").length)
{
	$("body").append("<p id=\"tooltip-alt\"><span></span></p>");
	tooltipAlt = $("#tooltip-alt").hide();
	$(".work .work img").hover(function() { tooltipAltShow($(this), $(this).attr("alt")); }, function() { tooltipAlt.hide(); });
}


/*
** intro stuff
*/
intro = $(".intro");
if (intro.length)
{
	$.getJSON(pl ? "data/intro_pl.js" : "data/intro.js", function(json)
	{
		intro.addClass("intro-scripted");
		var introNav = intro.find("> .navigation > ul");

		// data loaded from JSON, now inject it to the HTML
		for (var i = 0; i < introItems; i++)
		{
			var item = intro.find("> .content:first").clone().insertBefore(intro.find("> .ruler"));
			item.find("> .photo img").attr("src", "data/intro/" + json.items[i].file + ".jpg").attr("alt", json.items[i].info);
			item.find("> h2").html(json.items[i].title);
			var info = item.find("> .info");
			info.find("> span").text(json.items[i].info_ex ? json.items[i].info_ex : json.items[i].info).data("info", json.items[i].info);
			if (json.items[i].visit)
				info.find("> a").attr("href", json.items[i].visit).text(pl ? "Odwiedź" : "Visit");
			else
				info.find("> a").attr("href", json.items[i].work).text(pl ? "Zobacz" : "See project");
			info.find("~ p").remove();
			for (t in json.items[i].text)
				item.append("<p>" + json.items[i].text[t] + "</p>");
		}

		Cufon.replace(".intro h2");

		intro.find("> .content:first").remove();

		// make navigation work
		introNav.find("> li:first").after("<li><a class=\"pause\" href=\"#\">|| / [&gt;</a></li>");
		introNavH = -introNav.outerHeight() - intro.find("> .navigation > p").outerHeight();
		introNav.css("margin-top", introNavH + "px").hide();
		intro.find("> .navigation")
			.bind("mouseenter", function() { introNav.show().stop(true).animate({ marginTop: "0px" }, 350, "swing"); })
			.bind("mouseleave", function() { introNav.stop(true).animate({ marginTop: introNavH + "px" }, 150, "swing", function() { $(this).hide(); }); });

		// content sliding
		introContentH = 0;
		introW = intro.find("> .content:first").addClass("current").outerWidth();
		intro.find("> .content").each(function() { introContentH = Math.max($(this).outerHeight(), introContentH); }).not(":first").hide();
		intro.height(introContentH + 30);

		intro.append("<div class=\"fade-left\"></div><div class=\"fade-right\"></div>");
		intro.find("> .fade-left, > .fade-right").height(intro.find("> .content").outerHeight());

		// handle clicking on previous and next buttons
		intro.find("> .navigation a.previous").click(function() { introChange(-1, true); return false; });
		intro.find("> .navigation a.next").click(function() { introChange(1, true); return false; });
		intro.find("> .navigation a.pause").click(function() { $(this).toggleClass("play"); introPause(); return false; });

		intro.find("> .ruler").css("padding-top", (introContentH + 10) + "px").find("a").css("left", (introPos * introRulerStep) + "px")
			.bind("dragstart dragend", function()
			{
				$(this).stop(true).toggleClass("drag");
				introStop();
			})
			.bind("drag", function(event)
			{
				var offset = $(this).parent().offset();
				var max_x = (introItems - 1) * introRulerStep;
				var x = Math.min(max_x, Math.max(0, event.offsetX - offset.left - 34));
				$(this).css("left", x + "px");
				x = Math.round(x / introRulerStep);
				$(this).find("span").text(intro.find("> .content:eq(" + x + ") .info > span:first").data("info"));
			})
			.bind("dragend", function(event)
			{
				var offset = $(this).parent().offset();
				var max_x = (introItems - 1) * introRulerStep;
				var x = Math.round(Math.min(max_x, Math.max(0, event.offsetX - offset.left - 34)) / introRulerStep);
				introChangeTo(x);
				if (introAuto)
					setTimeout("introPlay()", introSlideInTime + 1000);
			});

		intro.find('a[href]').attachGallery();

		introPlay();

		if ($.browser.msie && $.browser.version < 7)
			intro.find("> .ruler > a").attr("href", "#").click(function() { return false; });
	});
}


var testimonials = $(".testimonials");
if (testimonials.length)
{
	testimonials.append("<ul class=\"numbers\"></ul>");
	var h = 0;
	testimonials.find("> ul:not(.numbers) > li").each(function(i)
	{
		h = Math.max(h, $(this).outerHeight());
		$(this).attr("id", "testimonial-" + i);
		testimonials.find(".numbers").append("<li><a href=\"#testimonial-" + i + "\">" + (i + 1) + "</a></li>");
	});
	testimonials.find("> ul:not(.numbers)").height(h);

	testimonials.find(".numbers a").click(function(event, fast)
	{
		if ($(this).hasClass("selected"))
			return false;

		$(this).parents(".numbers").find("a.selected").removeClass("selected");
		$(this).addClass("selected");

		if (fast)
		{
			$(this).parents(".testimonials").find("> ul:not(.numbers) > li:visible").hide();
			$($(this).hrefId()).show();
		}
		else
		{
			$(this).parents(".testimonials").find("> ul:not(.numbers) > li:visible").fadeOut(500);
			$($(this).hrefId()).animate({ opacity: "show" }, 500, "linear", function() { if ($.browser.msie && $.browser.version == 7) this.style.removeAttribute("filter"); });
		}

		return false;
	});

	testimonials.find(".numbers a:first").trigger("click", true);
}


$(".welcome p:first-child").append("<a class=\"close\">X</a>");
$(".welcome a.close").click(function() { $(this).parent().height($(this).parent().height()).animate({ opacity: "hide" }, 1000, "linear", function() { $(this).css({ display: "block", visibility: "hidden" }); $(this).parent().animate({ height: 0, paddingTop: 0, paddingBottom: 0 }, 1000, "swing", function() { $(this).remove(); }); }); return false; });


/*
** Google map
*/
var googleMap = $(".google-map");
var map;
if (googleMap.length)
{
	map = new GMap2(googleMap.empty()[0]);
	var center = new GLatLng(52.396567, 16.923923);
	map.setCenter(center, 15);
	map.addOverlay(new GMarker(center));
	map.addControl(new GSmallMapControl());
	map.addControl(new GMapTypeControl());
    map.addControl(new GOverviewMapControl());
	$(window).unload(GUnload);
}


var $twitter = $("ul.three-columns p.twitter");
if ($twitter.length)
{
	$.getJSON("http://www.twitter.com/statuses/user_timeline/merix_studio.json?count=1&callback=?", function(data)
	{
		if (data[0] && data[0].text && data[0].text.length)
		{
			data[0].text = data[0].text.replace(/(ftp|http|https|file):\/\/[\S]+(\b|$)/gim, '<a href="$&">$&</a>');
			$twitter.html(data[0].text);
		}
		else
			$twitter.text("Error loading content.");
	});
}


if ($.isFunction($("input.date").DatePicker))
	$("input.date").DatePicker
	({
		eventName: "focus"
	,	date: ""
	,	onBeforeShow: function() { $("input.date").DatePickerSetDate($("input.date").val(), true); }
	,	onChange: function(formated, dates) { $("input.date").val(formated); }
	});


$("div.more").each(function() { $(this).prev().append(" <a class=\"show-more\">rozwiń</a>").find("a.show-more").click(function() { $(this).parent().next(".more").show(); $(this).fadeOut(2000, function() { $(this).remove(); }); return false; }); });


if ($.browser.msie)
	$("a:not([href])").attr("href", "#");


/*
 * Merix projects gallery
 */
var gallery = null;
var $overlay = $('<div class="overlay overlay-loading overlay-hidden"></div>').appendTo("body");


function openGallery(prj) {
	if (gallery) {
		$overlay.removeClass('overlay-loading');
		_openGallery(prj);
	} else {
		if ($.browser.msie && $.browser.version <= 6)
			$overlay.height($(window).height());
		$overlay.css("opacity", "0").show().animate({opacity: 1}, 2000);

		$.getJSON("data/work" + (pl ? "_pl" : "") + ".js", function(data)
		{
			for (var g in data)
				for (var p = 0; p < data[g]['projects'].length; p++)
					if (data[g]['projects'][p]['visible'] == 1) {
						data[g]['projects'].splice(p, 1);
						p--;
					}

			$overlay.removeClass('overlay-loading');
			gallery = data;
			_openGallery(prj, true);
		});
	}
}


$('a[href$="' + (pl ? 'portfolio' : 'work') + '"]').each(function() {
	$(this).attr('href', $(this).attr('href') + (pl ? '#portfolio' : '#work'));
});


function _openGallery(project, overlayVisible)
{
	introPause();
	window.scroll(0, 0);

	var $gallery = $('<div id="gallery">\
		<div class="navigation">\
			<div class="tabs"><ul></ul><p class="right"><a href="#">Close showcase</a></p></div>\
			<div class="slider"><div class="slider-child"><p class="left"><a href="#">&lt;</a></p><p class="right"><a href="#">&gt;</a></p><div class="clip"><div class="fade-left"></div><div class="fade-right"></div></div></div></div></div>\
		<div class="thumbnails"><h1>Merix Studio <em>Showcase</em></h1></div>\
		<div class="preview"><div style="overflow: hidden; zoom: 1;"><ul class="tabs"></ul><p class="visit"><a href="#">Visit site</a></p><p class="back"><a href="#">Back to index</a></p></div><div class="description"></div>\
		<p class="loading"><img src="images/gallery/loading_alt.gif" alt="" /></p><img src="" alt=""></div>\
		<div class="project"><p class="prev"><a title="Previous project" href="#">&lt;</a></p><p class="next"><a title="Next project" href="#">&gt;</a></p></div></div>').hide().appendTo("body");

	if ($.browser.msie && $.browser.version <= 6)
	{
		$overlay.height($(window).height());
		$gallery.height($(window).height());
	}

	var tooltip2AltShow = function(element, text)
	{
		var i = text.indexOf(":");
		tooltip2Alt.find("span").empty().append("<strong>" + text.substring(0, i + 1) + "</strong> " + text.substring(i + 1));

		var IEOffset = { left: 0 };
		if ($.browser.msie)
			IEOffset = $("body").offset();
		var offset = element.offset();

		tooltip2Alt.css({ left: (offset.left + element.width() - IEOffset.left) + "px", top: (offset.top + (element.outerHeight() - tooltip2Alt.outerHeight()) / 2) + "px" }).show();
	};
	$("body").append("<p id=\"tooltip2-alt\"><span></span></p>");
	var tooltip2Alt = $("#tooltip2-alt").hide();

	var $tabs = $gallery.find(".navigation .tabs ul");
	var $clip = $gallery.find(".navigation .slider .clip");
	var $thumbs = $gallery.children('.thumbnails');
	var $preview = $gallery.children('.preview');
	var $project = $gallery.children('.project');
	var modes = {thumbs: 1, preview: 2};
	var mode = modes.thumbs;
	var gPos = 0, pPos = 0;

	if (pl)
	{
		$thumbs.children("h1").html('<em>Portfolio</em> Merix Studio');
		$gallery.find(">.navigation .tabs p.right a").text("Zamknij portfolio");
		$preview.find(" p.visit>a").text("Odwiedź stronę");
		$preview.find(" p.back>a").text("Wróć do listy projektów");
		$project.find(">p.prev>a").attr("title", "Poprzedni projekt");
		$project.find(">p.next>a").attr("title", "Następny projekt");
	}

	$tabs.append('<li><a gindex="-1" class="active" href="#gallery-slider-all">' + (pl ? 'Wszystkie' : 'Index') + '</a></li>');
	var showProjectGallery = -1, showProjectIndex = -1;
	for (var g in gallery)
	{
		$thumbs.append('<h2 gindex="' + g + '">' + gallery[g]['name'] + '</h2>');
		var $list = $('<ul gindex="' + g + '"></ul>').appendTo($thumbs);

		$tabs.append('<li><a gindex="' + g + '" href="#gallery-slider-' + g + '">' + gallery[g]['name'] + '</a></li>');
		var $list2 = $('<ul id="gallery-slider-' + g + '"></ul>').prependTo($clip);
		for (var p in gallery[g]['projects']) {
			$list.add($list2).append('<li><a gindex="' + g + '" iindex="' + p + '" href="#gallery-slider-' + g + '"><img src="data/gallery/thumbnails/' + gallery[g]['projects'][p]['file'] + '.jpg" alt=""><span></span></a></li>');
			if (project && project == gallery[g]['projects'][p]['file'])
			{
				showProjectGallery = g;
				showProjectIndex = p;
			}
		}
	}

	Cufon.replace('#gallery .thumbnails h1, #gallery .thumbnails h2');
	Cufon.replace('#gallery .navigation .tabs a', { hover: true });

	var $curThumbs = $gallery.find(".slider ul").eq(0), thumbsPos = 0, thumbsMax = Math.max($curThumbs.children().length - 5, 0);

	// Close preview and display thumbnails.
	$preview.find(".back a").click(function()
	{
		$tabs.find('a[gindex="-1"]').click();
		return false;
	});

	var showProject = function(gindex, iindex, tabClick)
	{

		var oldmode = mode;
		mode = modes.preview;
		$preview.find('p.loading').show();
		$tabs.find('a[gindex="' + gindex + '"]').trigger("click", true);

		gPos = gindex;
		pPos = iindex;

		var $desc = $preview.children(".description").empty().hide();
		var project = gallery[gPos]["projects"][iindex];
		if (project["description"])
		{
			var desc = project["description"];
			$desc.append('<h3>' + desc.title + '</h3><p class="date">' + desc.date + '</p>');
			for (var t in desc.text)
				$desc.append('<p>' + desc.text[t] + '</p>');
			if (desc.design || desc.templates || desc.programming)
			{
				var p = '<p class="tooltip-alt">', label = pl ? 'Zakres prac: ' : 'The scope of work: ';
				if (desc.design)
					p += '<img src="images/gallery/icon_04.png" alt="' + label + (pl ? 'projekt graficzny' : 'Graphic Design') + '">'
				if (desc.templates)
					p += '<img src="images/gallery/icon_11.png" alt="' + label + (pl ? 'szablony (X)HTML/CSS/JS' : '(X)HTML/CSS/JS templates') + '">'
				if (desc.programming)
				{
					var prog_text = pl ? ["serwis internetowy", "zarządzanie treścią", "sklep internetowy"] : ["Website (PHP)", "Content Management System (CMS)", "Online Store"];
					p += '<img src="images/gallery/icon_14.png" alt="' + label + prog_text[desc.programming - 1] + '">'
				}
				$desc.append(p + '</p>');
				$desc.find("p.tooltip-alt img").hover(function() { tooltip2AltShow($(this), $(this).attr("alt")); }, function() { tooltip2Alt.hide(); });
			}

			Cufon.replace("#gallery>.preview>.description h3");
		}

		var $ptabs = $preview.find('ul.tabs').empty().hide();
		for (var i = 0; i < project.count; i++)
			$ptabs.append('<li><a pos="' + (i + 1) + '" href="#">' + (i + 1) + '</a></li>');
		$ptabs.children(":first").children().addClass("active");
		if (project["description"])
			$ptabs.prepend('<li class="description"><a href="#">' + (pl ? 'Szczegóły' : 'About') + '</a></li>');

		if (project.visit)
			$preview.find("p.visit").css("visibility", "visible").children("a").attr("href", project.visit);
		else
			$preview.find("p.visit").css("visibility", "hidden");

		if ($ptabs.children().length > 1)
		{
			$ptabs.show().find("a").click(function()
			{
				if ($(this).parent().hasClass("description"))
				{
					$(this).toggleClass("active");
					$preview.children("div.description").animate({height: "toggle"}, 500);
				}
				else
				{
					if ($(this).hasClass("active"))
						return false;


					$(this).addClass("active").parent().siblings().not(".description").children().removeClass("active");
					$preview.find('p.loading').show();
					var pos = parseInt($(this).attr("pos"), 10);

					$preview.children("img").each(function() {
						$(this).unbind('load').removeClass('new').css('margin-bottom', (-$(this).outerHeight()) + 'px');
					});
					$('<img alt="" class="new">').css('opacity', '0').appendTo($preview).load(function() {
						if (!$(this).hasClass('new')) {
							$(this).css('margin-bottom', (-$(this).outerHeight()) + 'px');
							return;
						}
						$preview.find('p.loading').hide();
						$preview.children("img").not(this).fadeOut(500, function() { $(this).remove(); });
						$(this).animate({opacity: "1"}, 500, function() { $(this).removeClass('new'); });
					}).attr("src", "data/gallery/" + project.file + "_" + (pos < 10 ? "0" : "") + pos + ".jpg");
				}

				return false;
			});
		}

		if (oldmode == modes.preview && mode == modes.preview)
		{
			$preview.children("img").each(function() {
				$(this).unbind('load').removeClass('new').css('margin-bottom', (-$(this).outerHeight()) + 'px');
			});
			$('<img alt="" class="new">').css('opacity', '0').appendTo($preview).load(function() {
				if (!$(this).hasClass('new')) {
					$(this).css('margin-bottom', (-$(this).outerHeight()) + 'px');
					return;
				}
				$preview.find('p.loading').hide();
				$preview.children("img").not(this).fadeOut(500, function() { $(this).remove(); });
				$(this).animate({opacity: "1"}, 500, function() { $(this).removeClass('new'); });
			}).attr("src", "data/gallery/" + project.file + "_01.jpg");
		}
		else {
			$preview.children("img").css({opacity: "0"}).removeAttr("src").load(function()
			{
				$preview.find('p.loading').hide();
				$(this).animate({opacity: "1"}, 250).unbind("load");
			}).attr("src", "data/gallery/" + project.file + "_01.jpg");
		}

		if (oldmode == modes.thumbs && mode == modes.preview)
			$thumbs.fadeOut(500, function()
			{
				window.scroll(0, 0);
				$preview.fadeIn(750, function() { if ($.browser.msie && $.browser.version <= 8 && $.browser.version > 6) this.style.removeAttribute("filter"); });
				$project.fadeIn(500);
			});

		thumbsMax = Math.max($curThumbs.children().length - 5, 0);

		thumbsPos = pPos - 2;
		thumbsPos = Math.min(Math.max(thumbsPos, 0), thumbsMax);

		$curThumbs.stop(true).animate({left: (thumbsPos * -160) + "px"}, 500);

		window.location.hash = (pl ? '#portfolio' : '#work') + (':' + project.file);
	};


	$thumbs.find("ul a").click(function()
	{
		showProject(parseInt($(this).attr("gindex"), 10), parseInt($(this).attr("iindex"), 10));
		return false;
	});


	$tabs.find("a").click(function(e, dontResetPos)
	{
		var g = parseInt($(this).attr("gindex"), 10);
		if (g == -1)
		{
			$(this).addClass("active").parent().siblings().find("a").removeClass("active");
			$thumbs.children('h2,ul').show();
			$gallery.find(".navigation").trigger("mouseleave");
			mode = modes.thumbs;
			$project.stop(true).fadeOut(500);
			$preview.stop(true).fadeOut(500, function() { $thumbs.stop(true).fadeIn(500); });
			window.location.hash = (pl ? '#portfolio' : '#work');
			return false;
		}

		if (mode == modes.thumbs)
		{
			$(this).addClass("active").parent().siblings().find("a").removeClass("active");
			$thumbs.children('h2,ul').hide().filter('[gindex="' + g + '"]').show();
		}
		else
		{
			$(this).addClass("active").parent().siblings().find("a").removeClass("active");

			if (!dontResetPos/* && !($.browser.msie && $.version != 6)*/)
			{
				var $a = $(this);
				$gallery.find(">.navigation .slider-child").stop(true).animate({marginTop: "-162px"}, 250, function()
				{
					$gallery.find(">.navigation .slider-child").animate({marginTop: "0px"}, 250);

					$curThumbs = $clip.find("ul" + $a.hrefId()).addClass("active");
					if (!dontResetPos)
					{
						$curThumbs.css("left", "0");
						thumbsMax = Math.max($curThumbs.children().length - 5, 0);
						thumbsPos = 0;
					}
					$curThumbs.siblings("ul").removeClass("active");
					$curThumbs.find('a').eq(0).click();
				});
			}
			else
			{
				$curThumbs = $clip.find("ul" + $(this).hrefId()).addClass("active");
				if (!dontResetPos)
				{
					$curThumbs.css("left", "0");
					thumbsMax = Math.max($curThumbs.children().length - 5, 0);
					thumbsPos = 0;
				}
				$curThumbs.siblings("ul").removeClass("active");
				//$curThumbs.find('a').eq(0).trigger('click');
			}

			gPos = Math.max(g, 0);
			pPos = 0;
		}
		return false;
	});

	$gallery.find(".navigation")
		.bind("mouseenter", function()
		{
			if (mode != modes.preview)
				return;

			$(this).find(".slider-child").stop(true).animate({marginTop: "0px"}, 500);
			$gallery.children(".preview").stop(true).animate({opacity: "1", paddingTop: "244px"}, 500, function() { if ($.browser.msie && $.browser.version <= 8 && $.browser.version > 6) this.style.removeAttribute("filter"); });

			// Firefox fix - force parent redraw
			if ($.browser.mozilla)
				$gallery.find(".slider").css("outline", "0px solid rgba(0, 0, 0, 0)").animate({outlineWidth: "10px"}, 500);
		}).bind("mouseleave", function()
		{
			if (mode != modes.preview) {
				$gallery.children(".preview").animate({paddingTop: "82px"}, 500);
				return;
			}
			$(this).find(".slider-child").stop(true).animate({marginTop: "-162px"}, 500);
			$gallery.children(".preview").stop(true).animate({opacity: "1", paddingTop: "82px"}, 500, function() { if ($.browser.msie && $.browser.version <= 8 && $.browser.version > 6) this.style.removeAttribute("filter"); });
		});

	$gallery.find(".slider p.right a").click(function()
	{
		if (thumbsPos < thumbsMax)
			$curThumbs.stop(true).animate({left: (++thumbsPos * -160) + "px"}, 500);
		return false;
	});
	$gallery.find(".slider p.left a").click(function()
	{
		if (thumbsPos > 0)
			$curThumbs.stop(true).animate({left: (--thumbsPos * -160) + "px"}, 500);
		return false;
	});

	$clip.find("ul a").click(function()
	{
		showProject(parseInt($(this).attr("gindex"), 10), parseInt($(this).attr("iindex"), 10));
		return false;
	});

	// Close whole gallery.
	$gallery.find(".navigation .tabs p.right a").click(function()
	{
		$overlay.fadeOut(500, function() { $(this).addClass('overlay-loading'); });
		$gallery.fadeOut(500, function() { $(this).remove(); });
		tooltip2Alt.remove();
		introPause();
		window.location.hash = '';
		return false;
	});

	$project.find("p.prev a").click(function()
	{
		if ($tabs.find('a[gindex="-1"]').hasClass("active"))
		{
			if (pPos <= 0)
			{
				if (gPos > 0)
					gPos--;
				else
					gPos = gallery.length - 1;
				pPos = gallery[gPos]["projects"].length;
			}
		}
		else
			pPos = (pPos <= 0) ? gallery[gPos]["projects"].length : pPos;
		if ($preview.children("div.description").is(':visible'))
			$preview.children("div.description").animate({height: "hide"}, 500, function() {
				showProject(gPos, pPos - 1, true);
			});
		else
			showProject(gPos, pPos - 1, true);
		return false;
	});

	$project.find("p.next a").click(function()
	{
		if ($tabs.find('a[gindex="-1"]').hasClass("active"))
		{
			if (pPos >= gallery[gPos]["projects"].length - 1)
			{
				if (gPos < gallery.length - 1)
					gPos++;
				else
					gPos = 0;
				pPos = 0;
			}
			else
				pPos++;
		}
		else
			pPos = (pPos >= gallery[gPos]["projects"].length - 1) ? 0 : pPos + 1;
		if ($preview.children("div.description").is(':visible'))
			$preview.children("div.description").animate({height: "hide"}, 500, function() {
				showProject(gPos, pPos, true);
			});
		else
			showProject(gPos, pPos, true);
		return false;
	});


	window.location.hash = (pl ? '#portfolio' : '#work');

	if (!overlayVisible)
		$overlay.css("opacity", "0").show().animate({opacity: 1}, 2000);
	$gallery.fadeIn(1000);
	if (project)
		showProject(showProjectGallery, showProjectIndex);
}


if (window.location.hash.startsWith(pl ? '#portfolio' : '#work')) {
	var i = window.location.hash.indexOf(':'), project = null;
	if (i >= 0)
		project = window.location.hash.substr(i + 1);
	openGallery(project);
}

$.fn.extend({attachGallery: function() {
	return this.each(function() {
		var id = $(this).hrefId();
		if (id.startsWith(pl ? '#portfolio' : '#work'))
			$(this).click(function() {
				var i = id.indexOf(':'), project = null;
				if (i >= 0)
					project = id.substr(i + 1);
				openGallery(project);
				return false;
			});
	});
}});

$('a[href]').attachGallery();
