// Create a global variable that stores the current position of div.image_frame_inner
var innerPosition = 0;

$(document).ready(function(){
	
	// End if we're not on the Projects page
	if (!$('body#projects').length) return false;
	
	// Show div#container
	$('div#container').show();

	// Hide All Project Sets when page loads	
	$('#project_sets .project_set').hide();

	// Collapse the project list
	$('a#list_toggle, ul#project_list_container li:first').addClass("collapsed");
	$('ul#projects_list').hide();

	// Add the Javascript CSS File
	$('head').append('<link rel="stylesheet" href="css/javascript.css" type="text/css">');

	// Create an invisible div to preload css images
	$('body').append('<div id="preloader"></div>');
	$('div#preloader').hide().append('<img src="images/all_pages/spinner.gif"><img src="images/projects/prev_button.png"><img src="images/projects/next_button.png">');


	/*=========================================
	SHAREBAR SETUP
	=========================================*/

	// Hide the sharebar
	$("div#shareContainer").hide();

	/*=========================================
	SETUP MOUSE EVENTS ON THE SHARE BAR
	=========================================*/

	addShareEvents();

	function addShareEvents() {
		$("a#shareExpand").click( function(){ 

			if ($("a#shareExpand.expanded").length == 0) {
				$("div#shareContainer").css("width", 600);
				$(this).addClass("expanded");
			} else {
				$(this).removeClass("expanded");
				$("div#shareContainer").css("width", 65);
			}

			return false;
		});
	}


	/*=========================================
	SPLASH SCREEN
	=========================================*/

	// Hide the thumbnail grid and show reveal the splash screen
	$('ul#project_thumbs').hide();
	// Create the img for the splash screen
	$('div#container').append('<img id="splash" src="" alt="" >');

	// Hide the Splash Screen
	$('img#splash').hide();
	
	// If we've already shown the splash screen recently, don't show it again
	if (checkIfPageHasBeenRecentlyVisited())
	{
		loadThumbGrid();
	} else {
		var splashArray = new Array();

		// Load the Splash XML file and assign each image within to an array
		$.get('xml/splash.xml', function(xml) {
			$('image', xml).each(function (i) {
				splashArray.push($(this).attr("src"));
			});

		displaySplash();
		});
	}
	
	function checkIfPageHasBeenRecentlyVisited()
	{
		if ($.cookie('xten_recently_visited') == 'yes') {
			return true;
		} else {
			$.cookie('xten_recently_visited', 'yes', { expires: 1 });
			return false;
		}
	}

	function displaySplash()
	{
		// Generate a random number
		var random = Math.floor( Math.random() * splashArray.length ); // This int is equal to number of splash images

		$('img#splash').load(function () {
			revealSplash();
		})

		// if there was an error loading the image, react accordingly
		.error(function () {
			loadThumbGrid();
		})

		.attr('src', "xml/splash/" + splashArray[random]).attr('alt', "XTEN Architecture");
	};	


	function revealSplash() {
		$('img#splash').fadeIn("slow").fadeTo(1500, 1).fadeTo("slow", 0, loadThumbGrid);
	};

	function loadThumbGrid() {
		if ($('img#splash').length) {
			$('img#splash').remove();
		}
		$('ul#project_thumbs').fadeIn("slow");
	};


	/*=========================================
	THUMBNAIL GRID AND PROJECT LIST ROLLOVER
	=========================================*/

	// Expand or Collapse the project list when clicked
	$('ul#project_list_container li:first').click( function(){

		// Actual Expanding and collapsing, depending on current state
		if ($('a#list_toggle').attr("class") == "collapsed") {
			$('ul#projects_list').show("fast");
		} else {
			$('ul#projects_list').hide("fast");
		};

		// Toggle the Collapsed class
		$(this).toggleClass("collapsed");
		$('a#list_toggle').toggleClass("collapsed");

		return false;
	});

	// Add an invisible div to prevent the scrollbar appearance issue on smaller screen sizes
	$('div#container').append('<div id="tempBlock"></div>');

	// Add a click and hover events to every project list item and every thumb	
	addMouseEvents($('ul#projects_list a'));
	addMouseEvents($('ul#project_thumbs a'));

});


function addMouseEvents(target) {
	$(target).each(function(myInt){

		$(this).hover(
			function () {
				// If any projects are already visible then stop
				if ( $('.currentProject').length > 0 ) {
					return false;
				};
				// Reposition the project description based on height of the thumbs
				var thumbHeight = $('ul#project_thumbs').height();
				$('div.project_description').eq(myInt).css({top: thumbHeight + 170 + "px"});

				// Add highlighted classes to list item and thumb
				$('ul#projects_list a').eq(myInt).addClass("highlighted");
				$('ul#project_thumbs a').eq(myInt).addClass("highlighted");
				$('ul#image_buttons').remove();
				$('h6#imageNumber').remove();
				$('div.loader').remove();
				$('div#project_sets div.project_set').eq(myInt).find('div.image_frame_outer').hide();
				$('div#project_sets div.project_set').eq(myInt).find('p').hide();
				$('div#project_sets div.project_set').eq(myInt).find('p:first').show();
				$('div#project_sets div.project_set').eq(myInt).show();
			}, 
			function () {
				// Remove the highlighted classes
				$('ul#projects_list a').eq(myInt).removeClass("highlighted");
				$('ul#project_thumbs a').eq(myInt).removeClass("highlighted");
				// If there isn't a project active, hide all project set
				if ( $('.currentProject').length == 0 ) {
					$('div#project_sets div.project_set').hide();
				};
				// Reset the project description height
				$('div.project_description').eq(myInt).css({top: '640px'});
			}
		);

		$(this).click( function(){ 
			// Is the clicked on project already active? If so, return false;
			if ($(this).eq(myInt).attr("class") == "current") {
				return false;
			};

			// Set the location hash to the current project (revisit this later)
			// window.location.hash = myInt;

			// Reset the project description height
			$('div.project_description').eq(myInt).css({top: '640px'});

			// Remove the image toggle buttons
			$('ul#image_buttons').remove();

			// Remove the current class from the existing list item and thumb
			$('ul#projects_list a.current').removeClass("current");
			$('ul#project_thumbs a.current').removeClass("current");

			// Add the current class to the project list item
			$('ul#projects_list a').eq(myInt).addClass("current");
			// Add the current class to the project thumbnail
			$('ul#project_thumbs a').eq(myInt).addClass("current");

			// Hide any currently active project
			$('.currentProject').removeClass("currentProject").hide();
			// Mark the clicked project as .currentProject
			$('div#project_sets div.project_set').eq(myInt).addClass("currentProject").hide();
			// Display .image_frame_outer
			$('.currentProject div.image_frame_outer').show();

			// Hide all paragraphs, then show the first
			$('.currentProject p').hide();
			$('.currentProject p:first').show();

			// Initialize the Share Bar
			shareBarSetup();
			// Show the ShareBar
			$("div#shareContainer").show();

			slideThumbs();

			return false;

		});

	});
};

function slideThumbs() {
	// Check to see if the thumbs are already slid
	if ($('ul#project_thumbs.slid').length > 0) {
		showProject();
		return false;
	};

	// Lock the width of ul#projects_list so it doesn't shift around while minimized
	var thumbsWidth = $('ul#project_thumbs').width();
	$('ul#project_thumbs').css({width: thumbsWidth});

	// Fade out ul#project_thumbs
	$('ul#project_thumbs').fadeOut("medium", moveThumbnails);

	function moveThumbnails() {
		showProject();
		$('ul#project_thumbs a.current').removeClass("current");
		$('ul#project_thumbs').addClass("slid");
		$('ul#project_thumbs').css({left: '105%'});
		$('ul#project_thumbs').show();
		$('ul#project_thumbs').animate({left: '97%'}, 700, revealLowerThumbs);
	};

	function revealLowerThumbs() {
		// Open the projects list if it isn't already open
		if ($('a#list_toggle.collapsed').length > 0 ) {
			// Toggle the Collapsed class
			$('a#list_toggle').toggleClass("collapsed");
			$('ul#projects_list').show("medium");
		};

		// Now we add the link to lower the thumbs
		$('div#container').append('<a id="lowerThumbs" href="">Lower Thumbnails</a>');
		$('a#lowerThumbs').hide();
		$('a#lowerThumbs').show("medium");

		// Set up the click event for the new link
		$('a#lowerThumbs').click( function(){ 
			lowerThumbs();
			return false;
		});	
	};
};

function lowerThumbs() {
	// Hide the sharebar
	$("div#shareContainer").hide();

	// Remove the background image on a#lowerThumbs
	$('a#lowerThumbs').css({'background-image':'none'});

	// Remove the existing previous and next buttons
	$('ul#image_buttons').remove();

	// Hide the current project and remove .currentProject class
	$('.currentProject').hide("fast").removeClass("currentProject");

	// Remove .current class from all links
	$('ul#projects_list a.current, ul#project_thumbs a.current').removeClass("current");

	// Shift down the position of the ul#project_thumbs
	$('ul#project_thumbs').animate({left: '105%'}, 500, removeThumbLink);

	function removeThumbLink() {
		// Hide the thumb grid
		$('ul#project_thumbs').hide();

		// Change the width back to 100%
		$('ul#project_thumbs').css({width: '100%'});

		// Put ul#project_thumbs back in it's previous position
		$('ul#project_thumbs').css({left: '0'});

		// Remove .slid from ul#project_thumbs
		$('ul#project_thumbs').removeClass("slid");

		// Fade the thumb grid back in
		$('ul#project_thumbs').fadeIn("medium");

		// Remove thumb lowerer
		$('a#lowerThumbs').remove();
	};
};

function showProject() {
	// If images already exist for this project then just quit
	if ( $('.currentProject img').length == 0 ) {
		createProjectImages();
	};

	$('.currentProject').show("slow");

	// Set the first image as the current image
	$('.currentImage').removeClass("currentImage");
	$('.currentProject img:first').addClass("currentImage");
	// Shift the position of div.image_frame_inner back to 0
	$('.currentProject div.image_frame_inner').css({left: '0px'});

	addProjectButtons();	
	
	removeProjectIndicatorAndScrollEvents();
	removeProjectPositionIndicators();

	addProjectPositionIndicators();
	addProjectIndicatorAndScrollEvents();
};

function addProjectIndicatorAndScrollEvents () {
	$('.currentProject .image_frame_inner img, .indicator')
		.bind('mousemove', projectImageMouseMove)
		.bind('mouseout', projectImageMouseOut)
		.bind('mousewheel', projectImageScroll);
	
	$('.image_frame_outer').bind('mouseover', projectImageEnter);
	$('.image_frame_outer').bind('mouseout', projectImageExit);
		
	$('#prev-indicator').bind('click', prevClick);
	$('#next-indicator').bind('click', nextClick);
}

function removeProjectIndicatorAndScrollEvents () {
	$('.image_frame_inner img, .indicator')
		.unbind('mousemove', projectImageMouseMove)
		.unbind('mouseout', projectImageMouseOut)
		.unbind('mousewheel', projectImageScroll);
		
	$('.image_frame_outer').unbind('mouseover', projectImageEnter);
	$('.image_frame_outer').unbind('mouseOut', projectImageExit);
	
	$('#prev-indicator').unbind('click', prevClick);
	$('#next-indicator').unbind('click', nextClick);
}

function projectImageEnter (e) {
	$('.indicator').removeClass('hidden-indicator');
}

function projectImageExit (e) {
	$('.indicator').addClass('hidden-indicator');
}

function projectImageMouseMove (e) {
	var h = $('.currentProject .image_frame_outer');
	var hOff = h.offset();
	var x = e.pageX - hOff.left;
	var y = e.pageY - hOff.top;

	// Define the image halfway point
	var imageHalf = h.width() / 2;

	if (x < imageHalf)
	{
		hoverProjectLeftIndicator();
	} else {
		hoverProjectRightIndicator();
	}
}

function projectImageMouseOut (e) {
	$('#prev-indicator').removeClass('highlighted');
	$('#next-indicator').removeClass('highlighted');
}

function projectImageScroll (e, delta, deltaX, deltaY) {	
	if (delta > 0) prevClick();
	if (delta < 0) nextClick();

	return false;
}
	
function addProjectPositionIndicators () {
	$('.currentProject .image_frame_outer').append('<div class="indicator" id="prev-indicator"></div>')
		.append('<div class="indicator" id="next-indicator"></div>');
	$('.indicator').addClass('hidden-indicator');
		
	updateProjectIndicators(null);
}

function removeProjectPositionIndicators () {
	$('.image_frame_outer .indicator').remove();		
}

function updateProjectIndicators (e) {

	if (innerPosition == "0") {
		$('#prev-indicator').hide();
	} else {
		$('#prev-indicator').show();
	}

	if ($('.currentProject img.currentImage + img').length == 0) {
		$('#next-indicator').hide();
	} else {
		$('#next-indicator').show();
	}
}

function hoverProjectLeftIndicator () {
	$('#prev-indicator').addClass('highlighted');
	$('#next-indicator').removeClass('highlighted');
}

function hoverProjectRightIndicator () {
	$('#next-indicator').addClass('highlighted');
	$('#prev-indicator').removeClass('highlighted');
}

function createProjectImages() {

	// Add a loader to display when images are still loading
	$('div.image_frame_outer').append('<div class="loader" ></div>');

	// Set a variable to 4, because we're loading the first 4 images
	var imagesToLoad = 4;

	// For each link in the project set, create a new image
	$('.currentProject div.image_frame_outer a').each(function(myInt){
		// Hide the source link
		$(this).hide();
		// Get the photographer
		var photographer;
		if ($(this).attr('photographer') != '')
		{
			photographer = $(this).attr('photographer');
		}
		// Create an empty img
		$('.currentProject .image_frame_inner').append('<img src="" alt="" photographer="' + photographer + '" >');
	});

	// Load each image in order
	$('.currentProject img:first, .currentProject img:first + img, .currentProject img:first + img + img, .currentProject img:first + img + img + img').each(function(myInt){
		// Vars to store the src and alt
		var imageLocation = $('.currentProject div.image_frame_outer a').eq(myInt).attr("href");
		var imageTitle = $('.currentProject div.image_frame_outer a').eq(myInt).attr("title");

		// Load each image
		$('.currentProject img').eq(myInt).load(function () {
			// $('body').append('<h6>' + myInt + '</h6>');
			imagesToLoad -= 1;
			if (imagesToLoad == 0) {
				$('div.loader').fadeOut("slow", removeLoader);
				// Start loading the rest of the links
				loadRemainingImages();
			};
			}).attr('src', imageLocation).attr('alt', imageTitle);
		});

		function removeLoader() {
			$('div.loader').remove();
		};

		function loadRemainingImages() {
			// Load each image in order
			$('.currentProject img').each(function(myInt){
				// Vars to store the src and alt
				var imageLocation = $('.currentProject div.image_frame_outer a').eq(myInt).attr("href");
				var imageTitle = $('.currentProject div.image_frame_outer a').eq(myInt).attr("title");

				$(this).attr('src', imageLocation).attr('alt', imageTitle);
			});
		};

	};

	function addProjectButtons() {

		// Reset innerPosition to 0;
		innerPosition = 0;

		// If the prev next buttons already exist for this project, remove them
		if ($('.currentProject ul#image_buttons').length > 0) {
			$('.currentProject ul#image_buttons').remove();
		};

		$('.currentProject').append('<ul id="image_buttons"> <li id="prev_button"><a href="">Previous Image</a></li><li id="next_button"><a href="">Next Image</a></li> </ul>');

		// Setup the click actions for the prev buttons
		$('.currentProject li#prev_button a').click( prevClick);

		// Setup the click actions for the next buttons
		$('.currentProject li#next_button a').click( nextClick);

		// Disable the prev button because we're just getting started
		$('.currentProject li#prev_button a').addClass("inactive");

		// Add the click event to the images
		$("div.image_frame_outer img").unbind('click'); // Removes all existing click events from images
		$(".currentProject img").click(imageClick);

		// Remove the current image numbering
		if ($('.currentProject h6#imageNumber').length > 0) { $('.currentProject h6#imageNumber').remove(); };
		// Get the number of images
		var numberImages = $('.currentProject img').length;
		// Get the index of img.currentImage
		var imageIndex = $('.currentProject img').index( $('img.currentImage')[0]);
		$('.currentProject').append('<h6 id="imageNumber"><span id="imageNumber">' + (imageIndex + 1) + '</span> / <span class="totalImages">' + (numberImages) + '</span></h6>');
		
		togglePhotoCredit();
	};

	function imageClick(e)
	{	
		// Determine where we clicked in relation to div.image_frame_outer
		var h = $(".currentProject div.image_frame_outer");
		var hOff = h.offset()
		var x = e.pageX - hOff.left;
		var y = e.pageY - hOff.top;

		// Define the image halfway point
		var imageHalf = 345;

		if (x < imageHalf)
		{
			// We're going backwards
			prevClick();
		} else {
			// We're going forward
			nextClick();
		}
	}

	function prevClick() {
		// Is innerPosition set to 0?
		if (innerPosition == "0") {
			return false;
		};

		// How wide is the image before.currentImage?
		var prevWidth = $('img.currentImage').prev('img').width();
		// How width is the image before the previous image?
		var prevPrevWidth = $('img.currentImage').prev('img').prev('img').width();

		// If the previous two images are both vertical, we want to skip through them both
		if ( (prevWidth + prevPrevWidth) <= 680 ) {
			prevWidth += 350;
			// Remove .currentImage from current and give it to the next one
			$('.currentProject img.currentImage').prev('img').addClass("currentImage");
			$('.currentProject img.currentImage').eq(1).removeClass("currentImage");
		};

		// What is the gutter width?
		var gutterWidth = 10;
		// Our target position equals the previous position - the current image's width + the gutter
		innerPosition += (prevWidth + gutterWidth);
		// Stop any currently running animations on div.image_frame_inner
		$('.currentProject div.image_frame_inner').stop();
		// Run the animation
		$('.currentProject div.image_frame_inner').animate({left: (innerPosition) + 'px'}, 500, toggleItems);

		// Remove .currentImage from current and give it to the previous one
		$('.currentProject img.currentImage').prev('img').addClass("currentImage");
		$('.currentProject img.currentImage').eq(1).removeClass("currentImage");

		return false;	
	};

	function nextClick() {
		// How wide is .currentImage?
		var currentWidth = $('img.currentImage').width();
		// How wide is the next image?
		var nextWidth = $('img.currentImage').next('img').width();

		// Are we at the last image?
		if ($('.currentProject img.currentImage + img').length == 0) {
			rewindToBeginning();
			return false;
		};

		// Are there two vertical images together on the screen?
		if ( (currentWidth + nextWidth) <= 680 ) {
			// Is this set the last 2 images?
			if ($('.currentProject img.currentImage + img').next('img').length == 0) {
				$('.currentProject img.currentImage + img').addClass("currentImage");
				$('.currentProject img.currentImage:first').removeClass("currentImage");
				rewindToBeginning();
				return false;
			};
			// Scroll through them both at once
			currentWidth += 350;
			// Remove .currentImage from current and give it to the next one
			$('.currentProject img.currentImage + img').addClass("currentImage");
			$('.currentProject img.currentImage:first').removeClass("currentImage");
		};

		// What is the gutter width?
		var gutterWidth = 10;
		// Our target position equals the previous position - the current image's width + the gutter
		innerPosition -= (currentWidth + gutterWidth);
		// Stop any currently running animations on div.image_frame_inner
		$('.currentProject div.image_frame_inner').stop();
		// Run the animation
		$('.currentProject div.image_frame_inner').animate({left: (innerPosition) + 'px'}, 500, toggleItems);

		// Remove .currentImage from current and give it to the next one
		$('.currentProject img.currentImage + img').addClass("currentImage");
		$('.currentProject img.currentImage:first').removeClass("currentImage");

		toggleImageNumber();
		toggleParagraph();

		return false;
	};

	function rewindToBeginning() {
		// Reset the position of div.image_frame_inner
		innerPosition = 0;
		// Rewind to the first image
		$('.currentProject div.image_frame_inner').animate({left: '0'}, 500, toggleItems);
		$('.currentProject img.currentImage').removeClass("currentImage");
		$('.currentProject img:first').addClass("currentImage");
		// Disable the prev button because we're just getting started (again)
		$('.currentProject li#prev_button a').addClass("inactive");
		return false;
	};

	function toggleItems() {
		togglePrevNext();
		toggleImageNumber();
		toggleParagraph();
		togglePhotoCredit();
		updateProjectIndicators(null);
	};

	function togglePrevNext() {
		/* This is disabled because even the last next button rewinds to the beginning
		// If we're on the last image, then next_button is inactive
		if ($('.currentProject img.currentImage + img').length == 0) {
		$('.currentProject li#next_button a').addClass("inactive");
		} else {
		$('.currentProject li#next_button a').removeClass("inactive");
		};
		*/

		// If we're on the first image, then prev_button is inactive
		if (innerPosition == "0") {
			$('.currentProject li#prev_button a').addClass("inactive");
		} else {
			$('.currentProject li#prev_button a').removeClass("inactive");
		};
	};

	function toggleImageNumber() {
		// Get the index of img.currentImage
		var imageIndex = $(".currentProject img").index( $('img.currentImage')[0]);
		// Replace the contents with the current Image Number
		$('.currentProject span#imageNumber').text(imageIndex + 1);
	};

	function toggleParagraph() {
		// Divde the current position of image_frame_inner by the width of the frame
		var currentPosition = $('.currentProject div.image_frame_inner').css('left').slice(0, -2);
		var currentNumber = (currentPosition / -700);
		if (currentPosition == 0) {
			currentNumber = 0;
		};

		// Check to see if there is a paragraph for the indexed image
		if ($('.currentProject p').eq(currentNumber).length > 0) {
			// Hide the current paragraph
			$('.currentProject p:visible').hide();

			// Show the paragraph for the Indexed Image
			$('.currentProject p').eq(currentNumber).show();
		};
	};
	
	function togglePhotoCredit ()
	{
		var photographer = $('img.currentImage').attr('photographer');
		var photoCredit = $('div.currentProject h4.photoCredit');
		
		if (photographer != 'undefined')
		{
			photoCredit.html('Photography by ' + photographer);
			photoCredit.fadeIn('fast');
		} else {
			photoCredit.fadeOut('fast');
		}
	}
	
	function shareBarSetup() {

		// Vars to store default Facebook and Twitter Link Source
		var facebookDefault = $("iframe").attr("src");
		var twitterDefault = $("a#twitterBtn").attr("href");

		var shareBar = $("div#shareContainer");

		// Reset the width of the sharebar
		shareBar.css("width", 65);

		$("a#shareExpand").removeClass("expanded");

		// If we're in a project, place the shareBar in that project
		if ( $('.currentProject').length > 0 ) {

			// Select the current project to append to
			var targetDesc = $('.currentProject div.project_description');

			// And append the sharebar to it
			shareBar.appendTo(targetDesc);
		} else {
			// Select the current project to append to
			var targetDesc = $('div.project_description').eq(1);
			shareBar.appendTo(targetDesc);
		}

		// Refresh then update the Twitter Link Target
		$("a#twitterBtn").attr("href", twitterDefault);

		// Update Twitter Link
		oldSrc = $("a#twitterBtn").attr("href");
		newSrc = oldSrc.replace("XX", "0");
		$("a#twitterBtn").attr("href", newSrc);
	}
