$(document).ready(function(){
	// CREATE REQUIRED ARRAYS AND VALUES					   
	
	// add slide show button
	var slideNavHtml = '<li><a id="slide_show" class="active_nav" href="#">Slideshow</a></li>';
	$("#lc_site_functions").prepend(slideNavHtml);
	var slideShowOn = true;
	
	// check is slide show is active by checking the url
	var windowLocation = window.location.hash;
	
	// set slide show varibles
	var slideTransitionLength = 4500;
	var slideTime;
	
	// define heights for various image sizes
	var featureHeight = 750; // the height of featured images 
	
	// Populate and create all arrays - these array stores values that are used by all functions to display images, calculate widths and retrieve images
	var numberOfPosts = $('.lc_recent_work_listing').length; // numberOfImages
	var featureUrls = []; // stores the image url
	var featureTitle =[]; // Stores the title of each post
	var featureContent=[];//Stores the content of each post
	var postUrls =[]; // Stores the link to each project
	var featureWidths =[]//Stores the width of each image
	$('.lc_recent_work_listing').each(function(){
		var index = $('.lc_recent_work_listing').index(this);
		featureTitle[index] = $(this).children('h3').text();
		featureUrls[index] = $(this).find('.lc_image_url').attr('href');
		postUrls[index] = $(this).find('.lc_post_url').attr('href');
		featureContent[index]=$(this).find('p').html();
	});
	
	var currentSlide = 0;
	
	// track cookies
	var lightboxImageUrls = "";
	var lightboxImageUrlsArray=new Array();
	var currentLightboxImages = 0;
	var lightboxMenuHTML = '<li class="lc_page_link"><a id="lightboxStatus" class="inactive" href="'+$("#lc_site_logo a").attr("href")+'/?page_id=2">Lightbox 0</a></li>';
	$("#lc_site_functions").append(lightboxMenuHTML);
	$.cookie('lightbox_active', 'true', { path: '/' }); // set test cookie
	if ($.cookie('lightbox_active') == 'true') { // check if cookie is enabled
			if ($.cookie('lightboxImageUrls') == null || $.cookie('lightboxImageUrls') == "") { // if cookies don't exist add them
				$.cookie('lightboxImageUrls', '', {expires: 28, path: '/'});
			} else {
				// pass the cookie data to varibles
				lightboxImageUrls = $.cookie('lightboxImageUrls');
			}
			if (lightboxImageUrls.indexOf('&') != -1) {
				lightboxImageUrlsArray=lightboxImageUrls.split("&");
				currentLightboxImages = lightboxImageUrlsArray.length;
				$("#lightboxStatus").removeClass("inactive");
			} else {
				$("#lightboxStatus").addClass("inactive");
			};
			$("#lightboxStatus").text("Lightbox "+currentLightboxImages);
	};
	
	// get the url of the loader
	var loaderUrl = $("#loaderUrl").text();
	
	// this function calculates the width of the image - the height and width of the original image are in the actual file name
	function calculateImgWidth(filename, newHeight) {
		//gfgfdgfd
		var oldHeight = filename.slice((filename.lastIndexOf('y')+1),(filename.lastIndexOf('.'))); // get the old height from the filename
		var oldWidth = filename.slice((filename.lastIndexOf('x')+1),(filename.lastIndexOf('y'))); // get the old height from the filename
		var ratio=(oldHeight/oldWidth); // get the old ratio
		var newWidth = (Math.floor(newHeight/ratio)); // calculate the new width by using the newHeight and the old ratio
		return(newWidth); // return the new Width
	};
	
	// setup the initial screen
	createPreviews();
	function createPreviews(){
		// setup gallery
		var galleryHTML ='<div id="lc_gallery"><div id="lc_gallery_mask"></div><div id="lc_featured_outer"><div id="lc_featured_inner"></div><img id="gallery_loader" src="'+loaderUrl+'" /></div></div>';
		$("#lc_site_content").html(galleryHTML);
		$("#gallery_loader").show();
		resizeContent();
		var largeNavHTML = '<a id="lc_large_left_nav" class="lc_large_nav" href="#"></a><a id="lc_large_right_nav" class="lc_large_nav" href="#"></a>'
		$("#lc_featured_outer").append(largeNavHTML);
		$(".lc_large_nav").hide();
		$("#lc_featured_inner").hide();
		// load the first image
		loadFeatured();
	};
	
	function loadFeatured() {
		$("#gallery_loader").show();
		var featureImg = new Image();
		$(featureImg).load(function () {
			$(".lc_large_nav").fadeOut(500);
			$("#lc_featured_inner").fadeOut(500, function(){
				var captionHTML ='<div id="lc_gallery_caption"><h3>Recent<br />Work //</h3><p>'+featureContent[currentSlide]+'</p></div>';
				$("#lc_featured_inner").empty().append(featureImg).append(captionHTML).css('cursor','pointer');
				resizeContent();
				$("#lc_gallery_caption").hide();
				$("#lc_featured_inner").fadeIn(500, function(){
					$("#gallery_loader").hide();
					$("#lc_gallery_mask").hide();
					if (slideShowOn == false) {
						$(".lc_large_nav").fadeIn(500);
					} else {
						slideTime = setTimeout(gotoNextSlide, slideTransitionLength);
					};
				});
			});
		})
		.attr('src', featureUrls[currentSlide]);
	};
	
	// RESIZE FUNCTION
	function resizeContent(){
		var availableWidth = parseInt($('#lc_site_container').width()) - parseInt($('#lc_side_bar').outerWidth()) - 30;
		if (($('#lc_site_container').width() * 0.75) < $('#lc_site_container').height()) {
			var availableHeight = parseInt($('#lc_site_container').width()*0.75) - parseInt($('#lc_site_header').outerHeight());
		} else {
			var availableHeight = parseInt($('#lc_site_container').height()) - parseInt($('#lc_site_header').outerHeight());
		};
		$("#lc_site_content").width(Math.floor(availableWidth)).height(Math.floor(availableHeight));
		if ($("#lc_gallery").length != 0) {
			var outerFeatureHeight = parseInt(availableHeight - 76); // 76 is the height of the preview thumbnails if they existed
			var innerFeatureHeight = parseInt(outerFeatureHeight - 0); // 20 is the height of the image title if it existed
			$(".lc_large_nav").height(innerFeatureHeight);
			$("#lc_featured_inner").height(innerFeatureHeight);
			var currentImageWidth = (calculateImgWidth(featureUrls[currentSlide], innerFeatureHeight))-1;
			if (currentImageWidth < 450) {
				currentImageWidth = 450;
			};
			$("#lc_featured_inner").width(currentImageWidth);
			$("#lc_featured_outer").width(currentImageWidth);
			$("#lc_featured_outer, #lc_side_bar").height(outerFeatureHeight);
			$("#gallery_loader").attr("height", innerFeatureHeight).attr("width", 2);
			if ($("#lc_gallery_caption").size() == 1) {
				$("#lc_gallery_caption").width(currentImageWidth-48).height((innerFeatureHeight/2)-36);
			};
		};
	};
	
	// attach a window resize listener to call the resizeContent function
	$(window).resize(function() {
  		resizeContent();
	});
	
	// hover event to show caption
	$("#lc_featured_inner").live('hover', function(event) {
  		if (event.type == 'mouseover') {
    		$("#lc_gallery_caption").dequeue().fadeIn(500);
  		} else if (event.type == 'mouseout') {
    		$("#lc_gallery_caption").dequeue().fadeOut(500);
  		};
	
	});
	
	// click event to open post
	$("#lc_featured_inner").live('click', function(event) {
  		$("#lc_gallery_mask").show();
		$("#lc_site_content").fadeOut(1000, function() {
			var hashLocation = window.location.hash;
			var switchStyle = parseInt(hashLocation.indexOf("black"));
			// swap hash url and colour schem to opposite colour
			var scheme;
			if (switchStyle == -1) {
				scheme = "color-scheme=white";
			} else {
				scheme = "color-scheme=black";
			};
			hashLocation = "#"+scheme+"&slideshow=false";
			var postUrl = postUrls[currentSlide];
			var gotoLocation = postUrl.concat(hashLocation);
			window.location = gotoLocation;
		});
	});
	
	// function for moving to next slide
	// checks if the this is the last slide and returns to the start
	function gotoNextSlide(){
		$("#lc_gallery_mask").show(); // to prevent further user interaction
		currentSlide = currentSlide + 1;
		if (currentSlide >= numberOfPosts) {
			currentSlide = 0;
		}
		loadFeatured();
	};
	
	$("#lc_large_right_nav").live('click', function(event) {
		gotoNextSlide();
		return false;
	});
	
	// function for moving to pre iousslide
	// checks if the this is the first slide and moves to the last slide
	function gotoPreviousSlide(){
		$("#lc_gallery_mask").show(); // to prevent further user interaction
		currentSlide = currentSlide - 1;
		if (currentSlide < 0 ) {
			currentSlide = numberOfPosts - 1;
		}
		loadFeatured();
	};
	$("#lc_large_left_nav").live('click', function(event) {
		gotoPreviousSlide();
		return false;
	});
	// checks if the hash url has changed and sets slideShowOn to true or false
	// The function to change the hash or to slideshow true is in the standard interface script
	checkSlideShowStatus();
	function checkSlideShowStatus(){
		var winLocation = window.location.hash;
		var switchSlidesOn = parseInt(winLocation.indexOf("true"));
		if (switchSlidesOn != -1) {
			$("#slide_show").addClass("active_nav");
			if (slideShowOn == false){
				slideShowOn = true;
				$(".lc_small_nav").stop().fadeOut(750);
				$(".lc_large_nav").stop().fadeOut(750);
				$("#lc_gallery_mask").show();
				slideTime = setTimeout(gotoNextSlide, slideTransitionLength);
			};
		} else {
			$("#slide_show").removeClass("active_nav");
			if (slideShowOn == true){
				slideShowOn = false;
				$(".lc_large_nav").stop().fadeIn(750);
				$("#lc_gallery_mask").hide();
				clearTimeout(slideTime);
			};
		};
		setTimeout(checkSlideShowStatus, 250);
	};
});
