$(function(){ // Function initiates when DOM is ready
 
    // Apply styles to #portfolio and wrap it in #portfolio-wrapper
    $('#portfolio')
        .css({
            width: ($(this).width() * $('#portfolio li').size()) + 'px', // i.e. 900x10 = 9000
            position: 'relative'
        })
        .wrap('<div id="portfolio-wrapper" style="width:937px;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') , $('h2',this).text() , $(this).attr('title') );
 
            newNavItem.children('a:eq(0)').click(function(){
                // When portfolio nav-item is clicked:
                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: '937px', // Specify width as 880 (900 minus 10px padding on each side)
            margin: 0, 
            float: 'left'
        });
});
 
function addPortfolioNavItem(id,thing,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 class="' + id +'"><a href="#' + id + '" title="' + thing + '">' + title + '</a></li>').css({}).appendTo('#portfolio-nav');
}
