



function smoothScrollTo(hash) {
	$("html:not(:animated).,body:not(:animated)").animate(
		{
			scrollTop: $(hash).offset().top
		},
		500,
		function() {
			location.hash = hash;
		}
	);
}

$(function() {
	if ($("#thumbnails.sortable .pdf").length>1) {
		$("#thumbnails.sortable.pdf").sortable({
			distance: 20,
			stop: function(e, ui) {
				var index = $("#thumbnails.sortable.pdf li").index(ui.item);
				if (index!=-1) {
					var url = "/pdf/move/"+ui.item.attr("id").substr(2)+"/"+index;
					$.get(url);
				}
			}
		});
	}
	$("div.text").click(function() {
		smoothScrollTo("#"+$("div.image:first").attr("id"));
	});
	$(".image a[href*=#]").click(function() {
		this.blur();
		smoothScrollTo(this.hash);
		return false;
	});
	$("div.text p:last").addClass("last");
	$("a[href^='http://']").click(function() {
		if (this.href.substr(0, 29)=="http://www.andstudio.co.uk/") {
			return true;
		}
		window.open(this.href);
		return false;
	});
	$("#contEmailAddress, #personaliseTitle").inputLabel();
	$(".submit").click(function() {
		$(this).parents("form").submit();
	});
	$(".pdfbutton span").click(function() {
		var parent = $(this).parents("li");
		var url = "/"+location.pathname.split("/")[1]+"/pdf/"+($(this).hasClass("add") ? "add" : "remove")+(parent.hasClass("text") ? "text" : "image")+"/"+parent.attr("id").substr(2);
		if (parent.hasClass("pdf")) {
			url += "?returnTo=pdf";
		}
		location.href = url;
	});
	$("#personaliseButton").click(function() {
		$("#personalise").toggle();
		$(this).toggleClass("selected");
	});
	$(".preview li").mousemove(function(e) {
		var images = $("img", this);
		var $this = $(this);
		var offset = Math.floor((e.pageX-$this.offset().left)/($this.width()/images.length));
		images.addClass("hidden").eq(offset).removeClass("hidden");
	});
	$(".preview li").mouseleave(function(e) {
		$("img", this).addClass("hidden").eq(0).removeClass("hidden");
	});
});

$(window).load(function() {
	$("#related .image").each(function() {
		$(this).siblings(".description").find("a")
			.height($(this).height()-3)
			.width($(this).width()-5);
	});
	var lastImage = $("#content.details .image:last");
	lastImage.css("padding-bottom", $(window).height()-lastImage.height());

	$(".article").each(function() {
		var article = $(this);
		var height = article.height();
		article.height(0);
		article.prev().addClass("clickable").click(function() {
			var id = this.id;
			$(".expanded").animate({height: 0}, 500).removeClass("expanded");
			article.width("100%").animate({height: article.height() ? 0 : height}, height, function() {
				if (article.height()) {
					article.addClass("expanded");
					location.hash = id.substr(8);
				} else {
					article.removeClass("expanded");
					location.hash = "";
				}
			});
		});
	});

	if (location.hash) {
		$("#article_"+location.hash.substr(1)).next().width("100%").height("auto").addClass("expanded");
	}
});