// portfolio.js
$(function(){ // Function initiates when DOM is ready
    
    // Apply styles to #portfolio and wrap it in #portfolio-wrapper
    $('#portfolio')
        .css({
            height: '163px', // 163 is the height of each portfolio piece 
            width: ($(this).width() * $('#portfolio li').size()) + 'px', // i.e. 900x10 = 9000
            position: 'relative'
        })
        .wrap('<div id="portfolio-wrapper" style="width:586px;overflow:hidden;position:relative;"></div>'); // Wrap in new DIV element (required for scroll to work properly)
    
    $('#portfolio li')
        // Looping through each list-item:
        .each(function(){
            
            var newNavItem = addPortfolioNavItem( $(this).attr('id') , $('img:eq(0)',this).attr('src') , $('h3',this).text() );
            
            newNavItem.children('a:eq(0)').click(function(){
                // When portfolio nav-item is clicked:
                $('img',this).css({opacity:0.8}); // Dim to .8 opacity (to show the user they've been there)
                var id = $(this).attr('href').split('#')[1]; // FIX: IE returns actual HREF instead of href attribute
                var difference = $('#portfolio').offset().left-$('#portfolio li#' + id).offset().left; // leftOffset of ul#portfolio minus leftOffset of selected portfolio piece
                $('#portfolio').animate({left: difference}, 700); // Animate to the value of different over 700 milliseconds
                return false; // prevent default action of links
            });
            
        })
        .css({
            width: '586px', // Specify width as 880 (900 minus 10px padding on each side)
            margin: 0, 
            float: 'left'
        });

});

function addPortfolioNavItem(id,imgSrc,title) {

    // If the new navigation menu has NOT been created yet:
    if(!$('#portfolio-nav').get(0)) { // Test whether nav-menu already exists
        $('<ul id="portfolio-nav"/>')
            .insertAfter('#portfolio-wrapper'); // If it does not exist then create it and insert before #portfolio-wrapper (an element which will be created later)
    }
    // creates a new list item and appends it to #portfolio-nav
    return $('<li><a href="#' + id + '" title="' + title + '"><img width="84" src="' + imgSrc + '" alt="' + title + '" /></a></li>').css({display:'inline'}).appendTo('#portfolio-nav');

}