$(function(){
	$.ajaxSetup
	({  
		cache: false  
	});

	var u = navigator.userAgent.toLowerCase();
	var col_w = 240;
	var det_cols = 3;
	var spacing = 20;
	var margin_t = 70;
	var margin_b = 32;
	var min_w = det_cols*(col_w+margin_b);
	var slide_w = 700;
	var num_slides = 0;
	var hdr_expand = "";
	var done_load = false;
	var txt_h = 18;

	// Header functions
	$("a#btn_home").click(function()
	{
		reset_hdr();
		$.address.value("");
	});

	$("a#btn_contact").click(function(e)
	{
		e.preventDefault();
		$.address.value("");

		if (hdr_expand == "contact")
		{
			reset_hdr();
		}
		else
		{
			hdr_expand = "contact";
			adjust_hdr();
		}
	});

	$("a#btn_clients").click(function(e)
	{
		e.preventDefault();
		$.address.value("");

		if (hdr_expand == "clients")
		{
			reset_hdr();
		}
		else
		{
			hdr_expand = "clients";
			adjust_hdr();
		}
	});

	$("html").click(function()
	{
		if (u.indexOf("msie 6") == -1) reset_hdr();
	});

	$("#hdr").click(function(e)
	{
		if (u.indexOf("msie 6") == -1) e.stopPropagation();
	});

	function adjust_hdr()
	{
		if (hdr_expand == "contact")
		{
			$("#hdr").animate({"top":0},"fast");
			$("#hdr_top").animate({"height":$("#contact").outerHeight()},"fast");
			$("#wrap").animate({"top":0},"fast");
		}
		else if (hdr_expand == "clients")
		{
			$("#hdr").animate({"top":0},"fast");
			$("#hdr_top").animate({"height":$("#clients").outerHeight()},"fast");
			$("#wrap").animate({"top":-$("#contact").outerHeight()},"fast");
		}
	}

	function reset_hdr()
	{
		hdr_expand = "";
		$("#hdr").animate({"top":-$("#hdr").height()+$("#gnav").height()},"fast");
	}

	// Randomize position of images on load
	$(".box").each(function()
	{
		var win_center_x = Math.floor($(window).width()/2);
		var win_center_y = Math.floor($(window).height()/2);
		var temp_href = $(this).find("a").attr("href").replace(/^[^\/]*(?:\/[^\/]*){2}/,"");
		$(this).attr("id",temp_href);
		$(this).css({"position":"absolute","left":Math.floor(Math.random()*(3*col_w+1)+win_center_x-2*col_w),"top":Math.floor(Math.random()*(401)+win_center_y-300)});
		$(this).wrapInner("<div class=\"tmb\" />");
		$(this).prepend("<div class=\"detail\" />");
		$(this).prepend("<div class=\"ldr\"><img src=\"/wp-content/themes/mk/images/ldr.gif\" /></div>");
	});

	$(".box .tmb a").live("click",function(e)
	{
		e.preventDefault();

		if (done_load)
		{
			reset_hdr();
//			var temp_href = $(this).attr("href").replace(/^[^\/]*(?:\/[^\/]*){2}/,"");
//			$.address.value(temp_href);
			$.address.value($(this).parent().parent().attr("id"));
		}
	});

	$(".box .tmb a").live("mouseenter",function()
	{
		$(this).find(".txt").stop().animate({"top":$(this).find("img").height()-$(this).find(".tags").height()-txt_h},"fast");
		// $(this).find("img").removeClass("gray gray_ie","fast");
	}).live("mouseleave",function()
	{
		$(this).find(".txt").stop().animate({"top":$(this).find("img").height()},"fast");
		// $(this).find("img").addClass("gray gray_ie","fast");
	});

	$(".box .pic img").load(function()
	{
		set_box($(this).parents(".box"));
		// $(this).addClass("gray gray_ie");
	});

	$(window).load(function(e)
	{
		done_load = true;
		reset_hdr();

		// Force IE
		$(".box .pic img").each(function()
		{
			set_box($(this).parents(".box"));
			// Add css grayscale effect --- choppy transitions
			// $(this).addClass("gray gray_ie");

			// Add canvas grayscale effect --- slows down animation
			/*
			$(this).css({"position":"absolute"}).wrap("<div class=\"img_wrapper gray gray_ie\" style=\"display:inline-block;\">").clone().css({"position":"absolute","z-index":2,"opacity":0}).insertBefore($(this)).queue(function()
			{
				$(this).parent().css({"width":this.width,"height":this.height});
				$(this).animate({opacity:1},"fast")
				$(this).dequeue();
			});
			*/
		});

		if ((cur_page == "/") || (cur_page == "")) adjust_boxes();
	});

	function set_box(trgt)
	{
		var img_h = trgt.find(".tmb .pic img").height();
		trgt.css("height",img_h+margin_b);
		trgt.find(".pic").css("height",img_h+spacing);
		trgt.find(".info").css("height",img_h+spacing);
		trgt.find(".txt").css("top",img_h);
		trgt.css("visibility","visible");
	}

	// Slider functions
	var cur_slide = 0;

	$("a.prev").live("click",function()
	{
		cur_slide = (cur_slide > 0) ? cur_slide-1 : num_slides-1;
		$("ul.slides").animate({"left":(-cur_slide*slide_w)});
		$(".box .detail .nums").html((cur_slide+1)+"/"+num_slides);
		($("ul.slides li:eq(" + cur_slide + ") img").attr("title") == "") ? $(".box .detail .desc b").html($("ul.slides li:eq(" + cur_slide + ") img").attr("alt")) : $(".box .detail .desc b").html($("ul.slides li:eq(" + cur_slide + ") img").attr("title"));
	})

	$("a.next").live("click",function()
	{
		cur_slide = (cur_slide < num_slides-1) ? cur_slide+1 : 0;
		$("ul.slides").animate({"left":(-cur_slide*slide_w)});
		$(".box .detail .nums").html((cur_slide+1)+"/"+num_slides);
		($("ul.slides li:eq(" + cur_slide + ") img").attr("title") == "") ? $(".box .detail .desc b").html($("ul.slides li:eq(" + cur_slide + ") img").attr("alt")) : $(".box .detail .desc b").html($("ul.slides li:eq(" + cur_slide + ") img").attr("title"));
	});

	$(".detail a").live("mouseenter",function()
	{
		if (u.indexOf("msie 6") == -1) $(this).stop().fadeTo("fast",1);
	}).live("mouseleave",function()
	{
		if (u.indexOf("msie 6") == -1) $(this).stop().fadeTo("fast",0.5);
	});

	function adjust_boxes()
	{
		var win_w = $("body").innerWidth();
		if (win_w < min_w) win_w = min_w;
		var num_cols = parseInt(win_w/col_w);
		var margin_l = parseInt(win_w-spacing-(num_cols*col_w))/2;
		var cur_col = 0;
		var prev_bots = [];
		var temp_top = 0;
		var max_h = 0;

		// Populate first row of prev_bots with zero
		for (i=0; i<num_cols; i++) prev_bots[i] = 0;

		$(".box").each(function()
		{
			if ($(this).hasClass("sel"))
			{
				if (prev_bots[cur_col])
				{
					cur_col = get_optimal_id(prev_bots,det_cols,num_cols);
					temp_top = get_max(prev_bots,cur_col);
					if (cur_col > num_cols-det_cols) cur_col = 0;
				}
				else
				{
					if (cur_col == 0)
					{
						temp_top = 0;
					}
					else if (cur_col > num_cols-det_cols)
					{
						cur_col = get_optimal_id(prev_bots,det_cols,num_cols);
						temp_top = prev_bots[cur_col];
						if (cur_col > num_cols-det_cols) cur_col = 0;
					}
				}

				prev_bots[cur_col] = temp_top + $(this).outerHeight() + margin_b;
				prev_bots[cur_col+1] = temp_top + $(this).outerHeight() + margin_b;
				prev_bots[cur_col+2] = temp_top + $(this).outerHeight() + margin_b;
				$(this).animate({"left":(cur_col*col_w)+margin_l, "top":temp_top + margin_t});
				cur_col = cur_col + det_cols;

				$("html").animate({scrollTop:temp_top-($(this).height()-margin_t)/2});
				if (u.indexOf("ipad") == -1) $("body").animate({scrollTop:temp_top-($(this).height()-margin_t)/2});		// Need for Chrome & Safari, but ignore iPad
			}
			else
			{
				if (prev_bots[cur_col])
				{
					cur_col = get_min_id(prev_bots);
					temp_top = prev_bots[cur_col];
				}

				prev_bots[cur_col] = temp_top + $(this).outerHeight();
				$(this).animate({"left":(cur_col*col_w)+margin_l, "top":temp_top + margin_t});
				cur_col++;
			}

			if (cur_col == num_cols) cur_col = 0;
		});
	}


	// Deep link functions
	var cur_page = "";
	var prev_page = "";
	var cur_box = "";
	var prev_box = "";
	var prev_content = "";

	$.address.change(function(e)
	{
		cur_slide = 0;
		prev_page = cur_page;
		cur_page = e.value;
		$(".box .ldr").hide();

		if (cur_page != "\/")
		{
			cur_box = $("[id=\"" + cur_page + "\"]");
			prev_box = $("[id=\"" + prev_page + "\"]");
			$.address.title(cur_box.find(".pic img").attr("alt") + " - McAndrew|Kaps - Phoenix, AZ - Web Site, Web/Mobile/iPhone App, Brand Design and Development Agency");
			var temp_href = cur_box.attr("id").replace("\/","");
			if (prev_page != "") reset_box(prev_box);
			var img_h = cur_box.find(".detail").css("height");
			var img_w = cur_box.find(".detail").css("width");
			cur_box.find(".ldr").css("left",Math.floor(parseInt(img_w)/2));
			cur_box.find(".ldr").css("top",Math.floor(parseInt(img_h)/2));
			cur_box.addClass("sel").css("height",img_h);
			cur_box.find(".nums").html("0/0");
			if (prev_page != "") adjust_boxes();

			cur_box.find(".tmb").fadeOut("fast",function()
			{
				cur_box.find(".ldr").fadeIn("fast");
				cur_box.find(".detail").load("/wp-content/themes/mk/detail.php?id="+temp_href,function()
				{
					num_slides = cur_box.find("ul.slides li").length;
					cur_box.addClass("sel");
					cur_box.find(".nums").html("1/"+num_slides);

					cur_box.find("ul.slides li:first img").load(function()
					{
						cur_box.find(".detail").fadeIn("fast",function()
						{
							cur_box.find(".ldr").fadeOut("fast");
							img_h = cur_box.find(".pic img").height();
							cur_box.css("height",img_h);
							cur_box.find("ul.slides").css({"height":img_h},"fast");
							cur_box.find(".detail").css("height",img_h);
							cur_box.find(".detail .wrap").css("height",img_h);
							cur_box.find(".pic").css("height",img_h);
							cur_box.find(".ctrls a").animate({"height":img_h},"fast");
							adjust_boxes();
						});
					});
				});
			});
		}
		else
		{
			$.address.title("McAndrew|Kaps - Phoenix, AZ - Web Site, Web/Mobile/iPhone App, Brand Design and Development Agency");

			if (prev_page != "")
			{
				prev_box = $("[id=\"" + prev_page + "\"]");
				reset_box(prev_box);
			}

			$(".box").each(function()
			{
				var img_h = $(this).find(".tmb .pic img").height();
				$(this).css("height",img_h+margin_b);
				$(this).find(".pic").animate({"height":img_h+spacing},"fast");
				$(this).find(".info").animate({"height":img_h+spacing},"fast");
				$(this).find(".txt").css("top",img_h);
			});

			prev_box = "";
			cur_box = "";
		}
	});

	function reset_box(trgt)
	{
		trgt.removeClass("sel");
		trgt.find(".detail").fadeOut("fast").html("");
		trgt.find(".tmb").fadeIn("fast",function()
		{
			var img_h = trgt.find(".tmb .pic img").height();
			trgt.css("height",img_h+margin_b);
			trgt.find(".pic").css("height",img_h+spacing);
			trgt.find(".info").css("height",img_h+spacing);
			trgt.find(".txt").css("top",img_h);
			adjust_boxes();
		});
	}

	// Window resize
	var adjust_timeout = false;

	$(window).resize(function()
	{
		if (adjust_timeout) clearTimeout(adjust_timeout);
		adjust_timeout = setTimeout(adjust_elements,200);
	});

	function adjust_elements()
	{
		adjust_boxes();
		adjust_hdr();
	}

	// IE6 Fixed Header
	if (u.indexOf("msie 6") != -1) $("#hdr").css("position","absolute");

/*
	$(window).scroll(function()
	{
		if (u.indexOf("msie 6") != -1) $("#hdr").css("top",$(this).scrollTop());
	})
*/

	// Disable href=#
	$("a").live("click",function(e)
	{
		var temp_href = $(this).attr("href");
		if(temp_href.charAt(temp_href.length-1) == "#") e.preventDefault();
	});
});

function get_min_id (arr)
{
	var min = arr[0];
	var len = arr.length;
	var id = 0;

	for (var i=1; i<len; i++)
	{
		if (arr[i] < min)
		{
			min = arr[i];
			id = i;
		}
	}

	return id;
}

function get_max_id (arr)
{
	var max = arr[0];
	var len = arr.length;
	var id = 0;

	for (var i=1; i<len; i++)
	{
		if (arr[i] > max)
		{
			max = arr[i];
			id = i;
		}
	}

	return id;
}

function get_optimal_id (arr,det_cols,num_cols)
{
	var min = 100000;
	var max = -100000;
	var len = arr.length;
	var id = 0;
	var max_id = 0;
	var found = false;
	var min_found = 100000;

	// Get max
	for (var i=0; i<len; i++)
	{
		if (arr[i] > max)
		{
			max = arr[i];
			max_id = i;
		}
	}

	for (var i=0; i<len; i++)
	{
		if ((arr[i] < min) || ((arr[i] == min) && !found))
		{
			min = arr[i];

			if (i <= num_cols-det_cols)
			{
				if (((arr[i+1] <= arr[i]) && (arr[i+2] <= arr[i])) || ((arr[i+1] < max) && (arr[i+2] < max)))
				{
					if (get_max(arr,i) < min_found)
					{
						id = i;
						found = true;
						min_found = arr[i];
					}
				}
			}
		}
	}

	return (found) ? id : max_id;
}

function get_max (arr,start_id)
{
	var max = arr[start_id];
	var len = arr.length;
	var id = 0;

	for (var i=start_id+1; i<start_id+3; i++)
	{
		if (arr[i] > max)	max = arr[i];
	}

	return max;
}
