$(document).ready(function () {

	// State if JS enabled (add a class to the body tag)
	$("body").addClass("js");

	// Do things on the homepage
	if ($("body#home").length > 0) {
	
		//create home image
		var homeImageNo = 1;
		var homeImageTotal = $("#caption li").size();
		var homeImageSrc = $("#caption li:nth-child("+homeImageNo+") a").attr("rel");
	 	$("#bkg").append("<img src=\""+homeImageSrc+"\" width=\"1200\" height=\"1000\" alt=\"Case study\" />");

		//add next arrow
		$('#caption li').append('<a href="#" class="nextArrow" title="View another piece of work"><img src="http://kindersleystudio.co.uk/site/wp-content/themes/richardkindersley/images/arrow-next.gif" alt="Next" /></a>');

		//hide caption list
		$('#caption li').hide();
		$('#caption li:nth-child(1)').show();
		
		//rescale bkg image func call
		rescale();
		$(window).resize(function(){
			rescale();
		});
	};	


	// Adding support for :nth-child for IE6
	$(".work li:nth-child(3n)").addClass("end-row");
	$(".work li:nth-child(3n+1)").addClass("first-row");
	
	$(".relatedWork li:nth-child(4n)").addClass("end-row");
	$(".relatedWork li:nth-child(4n+1)").addClass("first-row");



	// nextArrow moves slideshow onwards
	$("#caption a.nextArrow").click(function () { 

		homeImageNo++;
		if (homeImageNo > homeImageTotal) {
			homeImageNo = 1;
		}
		homeImageSrc = $("#caption li:nth-child("+homeImageNo+") a").attr("rel");
		$("#bkg img").attr("src",homeImageSrc);

		$('#caption li').hide();
		$('#caption li:nth-child('+homeImageNo+')').show();

		return false;
	});


	// Gallery thing
	$(".gallery a").click(function () { 
		$image = $(this).attr("href");
		$image2 = $(this).attr("rel");
		$(".gallery a").removeClass("active");
		$(this).addClass("active");
		$("#mainimage img").attr("src", $image);
		$("#mainimage a").attr("href", $image2);
		return false;
    });




});

function rescale() {
	var max_height = $(window).height();
	var max_width = $(window).width();
	var min_width = 960;

	var height = $("#bkg img").height();
	var width = $("#bkg img").width();
	var ratio = height/width;

	// If height or width are too large, they need to be scaled down
	// Multiply height and width by the same value to keep ratio constant
	ratio = max_height / height;
	height = height * ratio;
	width = width * ratio;

	if (width < max_width) {
		// alert ("image width smaller than window width")
		ratio = max_width / width;
		height = height * ratio;
		width = width * ratio;
	}

	$("#bkg img").height(height);
	$("#bkg img").width(width);
	$("#bkg").height(max_height);

	// set top/left
	var top = $("#bkg img").offset().top;
	var left = $("#bkg img").offset().left;
	top = Math.round((max_height - height)/2);
	left = Math.round((max_width - width)/2);
	$("#bkg img").css("margin-top",top);
	$("#bkg img").css("margin-left",left);

}