$('document').ready(function() {

	/* -----------------------------------------------------
	   Keep an eye on the window for resizing, so we can 
	   resize our portfolio images accordingly
	   ----------------------------------------------------- */
 	windowHeight = $(window).height();
	$(window).bind("resize", function() { windowHeight = $(window).height(); });	
	
	/* -----------------------------------------------------
	   The Homepage Image Rotator 
	   ----------------------------------------------------- */
	if ($('#index #content').length > 0) {
		
		// Hide the home portfolio div until we're ready for it
        $('#home-portfolio, #home-portfolio li').hide();
        
		interval     = '6s';   // Interval between image swaps in miliseconds, or for seconds add an s (ex: '30s')
	    fadeDuration =1200;    // How long it takes for our pics to fade in and out, in miliseconds

	    // Scrape our list of our images into an array
	    imageList   = new Array();
	    ratioList   = new Array(); 
	    captionList = new Array();

	    $('#home-portfolio a').each(function() {
	        imageList.push($(this).attr('href'));
	        ratioList.push($(this).attr('rel'));
	        captionList.push($(this).html());
	    });
	    
	    // A simple counter so we can loop through our items. Pick a random item to start with.
        counter = Math.floor(Math.random() * (imageList.length));
        
        // Create a dummy, off-screen img to use for preloading
		dummyImg   = $('<img />');
		
        // Start preloading the next image while the first one's displaying
        dummyImg.attr('src',imageList[counter + 1]);
        
        // Add the first image to the dom
        $('#home-portfolio').append('<img id="slideshow-photo" src="'+imageList[counter]+'" alt="" /> <p id="slideshow-caption" class="caption">'+captionList[counter]+'</p>');
    	currentImg = $('#slideshow-photo');
		currentCaption = $('#slideshow-caption');
				
		// Set the height of the image explicitly, and link it to the Works page when a user clicks
		currentImg.height(windowHeight - 100).click(function() { window.location.href = '/works.php'; }).ready(function() {
		    newWidth = Math.round((windowHeight - 100) * ratioList[counter]);
		});
	    
	    // Fade the image in
        $('#home-portfolio').fadeIn(fadeDuration);

        // Set the width of the container divs based on the size of the image
		$('#container').width(newWidth + 50);
		$('#content').width(newWidth);
        	                            				    		    		
	    // Start the looping! This uses the jQuery Timers plugin to make
	    // life much, much easier. Here we are fading out the currently-shown
	    // image every x seconds, getting the next item in the array (resetting
	    // the loop if needed), then fading in that next item via fadeOut's 
	    // callback so we're ready for the next go-round without overlapping

	    currentImg.everyTime(interval,function() {
	        $('#home-portfolio').fadeOut(fadeDuration,function() {
                // We're now in the callback for fadeOut, so start working on the next image
                (counter >= (imageList.length - 1)) ? counter = 0 : counter++;
                
                // Swap out the current image for the new one
                currentImg.attr('src',imageList[counter]).height(windowHeight - 100);
                currentCaption.html(captionList[counter]);
                
				// Fade in the new image
				$('#home-portfolio').fadeIn(fadeDuration);

                // Preload the next image in line to try to speed things up
                dummyImg.attr('src',imageList[counter + 1]);
                
                // Set the width of the content div to match the image
				$('#content').width(currentImg.width());
				$('#container').width(currentImg.width() + 50);

	        });
	        
	    });
	    	        
	}
	
	/* -----------------------------------------------------
	   The Works page thumbnail browser
	   ----------------------------------------------------- */
   	// Insert the Works page thumbnail pagination
   	var paginationHTML  = '';

    if ($('#works #content').length > 0) {   

	// Insert the previous/next navigation
	$('#works #content').prepend('<div id="works-portfolio-nav"><a href="#" id="works-portfolio-nav-prev" onclick="$.galleria.prev(); return false;">&lt; <strong>previous</strong></a> <a href="#"  id="works-portfolio-nav-next" onclick="$.galleria.next(); return false;"><strong>next</strong> &gt;</a></div>');
	
	// Run the Galleria plugin to make the thumbnail browser do its work

	$('#portfolio').galleria({
		history: true,
		clickNext: true,
		insert: 'portfolio',
		onImage: function(image,caption,thumb) { 
			// Display the navigation
			$('#works-portfolio-nav').css('display','block');
			// Hide the thumbnails and pagination navigation
			$('#works-pagination-nav').css('display','none');
			$('#portfolio li').css('display','none');

			// Hide the image, reset the height and width based on the browser window height
			ratio = image.width() / image.height();
			image.css('display','none').height(windowHeight - 100).width(image.height() * ratio);

			// Set the width of the content div to match the image
			$('#content').width(image.width());
			$('#container').width(image.width() + 50);
			
			// fade in the image & caption
			image.fadeIn(1000);
			caption.css('display','none').fadeIn(1000);
		}
	});
    }	
	// Set up the pagination navigation
	$('#portfolio h2').each(function() {
		label = $(this).html();
		rel   = $(this).attr('title');
		paginationHTML += '<span rel="'+rel+'">'+label+'</span>';
	}).hide();
		
	// Insert the thumbnail pagination navigation
	$('#works #content').prepend('<div id="works-pagination-nav">'+paginationHTML+'</div>');
	$('#works-pagination-nav span').click(function() {
	    switchPage($(this).attr('rel'));
    
        // Update the .current class on the menu so that the new 
        // current page will be the only one highlighted
    	$('#works-pagination-nav span').removeClass('current');
    	$(this).addClass('current');
	});

	// Show the first set of images by default
	firstPage = $('#works-pagination-nav span').eq(0);
	firstPage.addClass('current');
	switchPage(firstPage.attr('rel'));

	function switchPage(page) { 
		thisPage    = "#portfolio li."+page;
		notThisPage = "#portfolio li:not('."+page+"')";
		$(notThisPage).hide();	// Hide all other pages
		$(thisPage).show();		// But do show the page we've requested
	}
});