/* -------------------------------------
   W O R K S   M E N U   D R O P D O W N
   ------------------------------------- */

// Immediately hide the #works-menu so we can do the dropdown trick below
var isWorksPage       = (document.location.href.indexOf('/works/') > -1);
var cameFromWorksPage = (document.referrer.indexOf('/works/') > -1);

if (!isWorksPage || !cameFromWorksPage) {
	document.write('<style type="text/css">#works #works-menu { display: none; }</style>');
}

/* ----------------------------------
   G A L L E R Y    F U N C T I O N S 
   ---------------------------------- */

var currentImageIndex = 0;
function gallerySwapImage(el) {
    
    // Prevent this function from running twice if the user has picked the
    // image that is already highlighted
    if (currentImageIndex == $('.gallery a').index($(el))) { return false; }
    
    // Specify where we want our images to be inserted        
    currentImg = $('#gallery-photo').children('img').eq(0);
    
    // Hide the video player if it's already playing
    if ($('#video').html() != '') {
        $('#video').empty();
    } else {
        currentImg.show();
    }
		    	        
    if ($(el).attr('id') == 'gallery-nav-back') { 
        // The user has selected the "Back" navigation button
        if (currentImageIndex > 1) {
            --currentImageIndex;
        } else {
            return false;
        }
    } else if (($(el).attr('id') == 'gallery-nav-forward') || ($(el).is('img'))) { 
        // The user has selected the "Next" navigation button
        if (currentImageIndex < ($('.gallery a').size() - 2)) {
            ++currentImageIndex;
        } else {
            // If the user is clicking the image and we're at the end, loop back to the beginning
			if ($(el).is('img')) {
				currentImageIndex = 1;
			} else {
				return false;
			}
        }
    } else {
        // The user has selected one of the numbered items from the list
        currentImageIndex = $('.gallery a').index($(el));
    }
    
    // Swap in the next image requested
    currentImg.attr('src',$('.gallery a').eq(currentImageIndex).attr('href'));
    
    // Highlight the image number that we're currently showing
    $('.gallery a').removeClass('current').eq(currentImageIndex).addClass('current');
    
    // Swap out the descriptive text with the relevant HTML
    $('#gallery-description').html($('.gallery a').eq(currentImageIndex).attr('title'));
    
    // Make sure that the image is showing
    $('#video').hide();
    $('#gallery-photo img').show();
    
}

function setupGallery() {
    // Insert the placeholder for our gallery images
    $('#content').prepend('<div id="gallery-photo"><img /></div>');

    // Un-hide the gallery links 
    $('.gallery a').each(function() {
        $(this).attr('title',$(this).html().replace(/  /g,'')).text($(this).index() + 1);
    });

	// If there are more than 9 images, the next arrow should float to the top-right
	forwardArrowClass = ($('.gallery a').length > 9) ? 'class="gallery-nav-forward-far-right"' : '';
	
    // Add the slideshow navigation controls (Previous / Next arrows)
    $('.gallery').prepend('<a href="#" id="gallery-nav-back">&laquo;</a>').append('&nbsp;<a href="#" id="gallery-nav-forward" '+forwardArrowClass+'>&raquo;</a> <p id="gallery-description"></p>');

    // Un-hide the gallery links
    $('.gallery a').show();
                
    // Set up the first image
    gallerySwapImage($('.gallery a').eq(1));

    // Swap out images on click
    $('.gallery a, #gallery-photo img').click(function() {
        gallerySwapImage($(this));
        return false;
    });

    /* ---------------------------------------
       V I D E O   P L A Y E R   F E A T U R E 
       --------------------------------------- */
    $('#gallery-photo').append('<div id="video" />');
    $(".gallery-video").click(function() {

        // Grab and split the parameters we need to show the video clip
        query         = $(this).attr('href').split('?');
        videoURL 	 = query[0];
		widthSearch  = query[1].match(/width=([0-9]+)/gi);
		width    	 = parseInt(RegExp.$1);
		heightSearch = query[1].match(/height=([0-9]+)/gi);
		height       = parseInt(RegExp.$1) + 15;
		
		
		if ((width == undefined) || (width == '')) {
			width = 400;
		}
		
		if ((height == undefined) || (height == '')) {
			height: 240;
		}
	

        videoObjectHTML = ' \
            <object width="'+width+'" height="'+height+'" codebase="http://www.apple.com/qtactivex/qtplugin.cab" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"> \
                <param value="'+videoURL+'" name="src"> \
                <param value="true" name="autoplay"> \
                <param value="video/quicktime" name="type"> \
                <embed width="'+width+'" height="'+height+'" pluginspage="http://www.apple.com/quicktime/download/" type="video/quicktime" autoplay="true" src="'+videoURL+'" /> \
            </object>';
            
        $('#gallery-photo img').hide();
        $('.gallery a').removeClass('current');
        $('html, body').animate({scrollTop: 0 }, (600));
        $('#video').css('width',width).html(videoObjectHTML).show();
        return false;

    });
}


$(document).ready(function() { 

	// Slide down the Works menu, if we're coming in from a non-Works page
	if (isWorksPage && !cameFromWorksPage) {
		$('#works-menu').show();
		$('#nav-works-video').css('opacity',0).delay(800).animate({ opacity: '1.0' },1200);
		$('#nav-works-photography').css('opacity',0).delay(1400).animate({ opacity: '1.0' },1200);
		$('#nav-works-sculpture').css('opacity',0).delay(1800).animate({ opacity: '1.0' },1200);
		$('#nav-works-archive').css('opacity',0).delay(2200).animate({ opacity: '1.0' },1200);
	}
	
    /* W I L L   B E   D E F U N C T ,   R E M O V E   S O O N */
	if (($('#works').length > 0) && ($('.slideshow').length > 0)) {
        // prettyPhoto popup styling for the Works slideshows
        $("a[rel^='prettyPhoto']").prettyPhoto();
   
        // Style the slideshow links 
        $('.slideshow a').eq(0).html('more images').show();
    }

	/* Enable the gallery feature on the Works pages */
	if (($('#works').length > 0) && ($('.gallery').length > 0)) {
		setupGallery();
	}
    
    /* Sidebar Highlighting */ 
    currentURLParts  = document.location.href.split('/');
    currentDirectory = currentURLParts[currentURLParts.length - 2];
    currentPage      = currentURLParts[currentURLParts.length -1];
    if (currentPage == '') { currentPage = 'index.php'; }

    // Run through the list and check to see if any of the links match our current URL
    $('#works #sidebar a').each(function() {
        if ($(this).attr('href').indexOf(currentDirectory) > 0) {
            $(this).addClass('current');
        }
    });
    
    $('#texts #sidebar a').each(function() {
        if ($(this).attr('href').indexOf(currentPage) >= 0) {
            $(this).addClass('current');
        }
    });
});

/* Homepage updater */
$('#home').ready(function() { 

    interval     = '10s';   // Interval between image swaps in miliseconds, or for seconds add an s (ex: '30s')
    fadeDuration = 1600;    // How long it takes for our pics to fade in and out, in miliseconds

    // Create a JS array from our images list
    images = new Array();
    $('#homepage-photos a').each(function() {
        images.push($(this).attr('href'));
    });

    // Figure out how many homepage photos we have listed
    numOfImages = images.length;

    // A simple counter so we can loop through our items. Pick a random item to start with.
    counter = Math.floor(Math.random() * (numOfImages));

    // Add the first image to the dom
    $('#homepage-photos').append('<img id="homepage-photo" src="'+images[counter]+'" alt="" />');
    $('#homepage-photos').fadeIn(fadeDuration);
    counter++;

    // Create a dummy off-screen image element for preloading the other images
    var dummy = document.createElement('img');
    dummy.setAttribute('src',images[counter]);

    $('#homepage-photos').everyTime(interval,function() {

        $('#homepage-photo').fadeOut(fadeDuration, function() {
            // When we're done fading out, swap out for the next image
            $('#homepage-photo').attr('src',images[counter]);
        });

        // Fade the new photo in
        $('#homepage-photo').fadeIn(fadeDuration);

        // Figure out if we need to reset our counter
        (counter >= (numOfImages - 1)) ? counter = 0 : counter++;

        // Start pulling in the next photo (hopefully will be downloaded fast enough...)
        dummy.setAttribute('src',images[counter]);

    });
});