
var oldIndex = 0;

$(function(){
    // Save the selector so we can reuse it
    feature = $('#landingFeature');

    // Main function
    $('#topNav ul:first').children('li').mouseover(function(){
        index = $(this).parent().find('> ' + this.tagName).index(this);
        swapState(index);
    });

    $('#landingNav div').mouseover(function(){
        //console.log($('#landingNav').find(this.tagName).index(this));
        index = $('#landingNav').find(this.tagName).index(this);
        swapState(index);
    });
    
    // Show the first image
    $('img', feature).each(function(index){
        $(this).attr('data-index', index);
    });

    $('#landingNav div').each(function(){
        $(this).data('background-image', $(this).css('background-image'));
    });

    swapState(oldIndex, true);
    
});

function swapState(index, force) {
    if ((oldIndex != index || force)) { 
        feature = $('#landingFeature');
        nav = $('#landingNav');

        // Hide all
        $('ul', nav).hide();

        // Show the correct index
        // Lower the last image
        $('img[data-index='+(oldIndex)+']', feature).css('z-index', 2);
        // Hide, raise then fade in the new image
        $('img[data-index='+index+']', feature).hide().css('z-index', 3).fadeIn(400, function() {
            // Move all the other images to the floor
            $('img[data-index!='+index+']', feature).css('z-index', 1);
        });

        $('#landingNav div').each(function(){
            $(this).css('background-image', $(this).data('background-image'));
        });

        $('div:nth-child('+(index+1)+')', nav).css('background-image','none');
        $('#logo h3').text($('div:nth-child('+(index+1)+') h3', nav).text());

        $('div:nth-child('+(index+1)+') ul', nav).show();
        // Save the index as old index so we know which one to move down later
        oldIndex = index;
    }
}

