$(document).ready(function(){
	
	jQuery.extend( jQuery.easing,
	{
		easeInQuad: function (x, t, b, c, d) {
			return c*(t/=d)*t + b;
		},
		easeOutQuad: function (x, t, b, c, d) {
			return -c *(t/=d)*(t-2) + b;
		},
		easeInCubic: function (x, t, b, c, d) {
			return c*(t/=d)*t*t + b;
		},
		easeOutCubic: function (x, t, b, c, d) {
			return c*((t=t/d-1)*t*t + 1) + b;
		},
		easeInCirc: function (x, t, b, c, d) {
			return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
		},
		easeOutCirc: function (x, t, b, c, d) {
			return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
		}
	});
	
	var selected = null,
		called = false
	
	$("#grid .work")
	.hover(
		function(){
			var that = this;
			if (that.animating) return;
			that.animating = true;
			$(that).find("div.off").animate(
				{
					marginTop: "150px"
				}, 350, "easeInCirc", function(){ that.animating = false; }
			);
		},
		function(){
			if(this==selected) return;
			$(this).find("div.off").animate(
				{
					marginTop: "0px"
				}, 350, "easeOutCirc"
			);
		}
	)
	.click(function(){
		window.location = $(this).find("a").get(0).href;
	});
	
	$("#grid .image")
	.hover(
		function(){ $(this).addClass("hover"); },
		function(){ $(this).removeClass("hover"); }
	)
	.click(function(){
		var that = this;
		$("body>.on").hide("slow");
		$(that)
		.find(".on")
		.clone()
		.appendTo("body")
		.click(function(){ $(this).hide("fast"); })
		.css(
			{
				height: "150px",
				width: "150px",
				position: "absolute",
				top: that.offsetTop,
				left: that.offsetLeft,
				zIndex: "200000"
			}
		)
		.show()
		.animate(
			{
				width: $(that).find("img")[0].width+"px",
				height: $(that).find("img")[0].height+"px",
				left: function(){
					var pos = $(that).prevAll().size()+1;
					var perline = 5;
					var horizontal = perline-(((Math.ceil(pos/perline))-pos/perline)*perline);
					var reach = ($(that).find("img").attr("width")/150)+horizontal-1;
					if(reach>perline){ //we'd expand outside the ul boundaries so let's shift however many 150's we need to the left
						return "-="+150*(reach-perline)+"px"; 
					}
					return "-=0px";
				}(),
				top: function(){
					var imgheight = $(that).find("img").attr("height")/150;
					var pos = $(that).prevAll().size()+1;
					var total = $(that).siblings().size()+1;
					var perline = 5;
					var lines = Math.ceil(total/perline);
					var vertical = ((Math.ceil(pos/perline)-lines)-1)*(-1);
					var reach = imgheight-vertical;
					//console.log("imgheight: "+imgheight+"\npos: "+pos+"\ntotal: "+total+"\nperline: "+perline+"\nlines: "+lines+"\nvertical: "+vertical+"\nreach: "+reach);
					if(reach){
						return "-="+150*(reach-(imgheight-lines))+"px";
					}
					return "-=0px";
				}()
			}, 400, "easeOutCirc"
		);
	});
	
});
