$(function(){
    
    var $media = $("#media");
    var numberOfImages = $media.find('li').length;
    
    if( numberOfImages > 1 ) {
        
        $media
            .addClass('gallery')
            .prepend('<ul id="img-counter"/>')
            .find('li')
                .hide()
                .each(function(i){
                    this.id = 'image-'+i;
                    $('#img-counter').append('<li id="anchor-'+i+'"><a href="#image-'+i+'" title="Ver imagem '+ i+1 +'">•</a></li>');
                })
                .click(function(){
                    $this = $(this);
                    if ($this.next().length > 0) {
                        $this.hide().next().show();
                        $('#img-counter li.sel').removeClass('sel').next().addClass('sel');
                    }
                    else {
                        $this.hide().siblings().first().show();
                        $('#img-counter li.sel').removeClass('sel').siblings().first().addClass('sel');
                    }     
                })           
                .first()
                    .show()
                    .end()
                .end()
            .find('#img-counter li a')
                .click(function(){
                    $('#img-counter li.sel').removeClass('sel');
                    $(this).parent().addClass('sel');                                        
                    $media.find('#images li').hide().end().find( this.hash ).show();
                    return false;
                })
                .first()
                    .parent()
                    .addClass('sel');
    }
    
})
