
var myTimer;

$(function(){
    $('#btnNext').click(function(){
        var oCurPhoto = $('#picture div.current');
        var oNxtPhoto = oCurPhoto.next();
        if (oNxtPhoto.length == 0)
            oNxtPhoto = $('#picture div:first');
            
        oCurPhoto.removeClass('current').css("z-index", "0");
        oNxtPhoto.addClass('current').css("z-index", "2");
        $('.titulo_destacado p').html(oNxtPhoto.find('img').attr("alt"));
    });
    
    $('#btnPrev').click(function(){
        var oCurPhoto = $('#picture div.current');
        var oPrvPhoto = oCurPhoto.prev();
        if (oPrvPhoto.length == 0)
            oPrvPhoto = $('#picture div:last');
        
        oCurPhoto.removeClass('current').css("z-index", "0");
        oPrvPhoto.addClass('current').css("z-index", "2");
        $('.titulo_destacado p').html(oPrvPhoto.find('img').attr("alt"));
    });
});

jQuery.fn.rotator = function($options){

    var defaults = {
        duration : 5000,
        images : []
    };
    
    $current = jQuery(this);
    
    jQuery.extend(defaults, $options);
    for(i = 0; i < defaults['images'].length; i++){
        $div = jQuery('<div></div>');
        
        
        $style = 'width:' + $current.width() + 'px; '; 
        $img = jQuery('<img/>').attr('src', defaults['images'][i][0]).attr("style", $style)
            .attr("alt", defaults['images'][i][1]);
        
        $link = $('<a><a/>').attr("href", defaults['images'][i][2]).append($img);
        $div.append($link);
        
        $style += 'position: absolute; overflow: hidden; height: ' + $current.height() + 'px; ';
        
        
        if (i == 0){
            $style += 'z-index: 2; ';
            $div.addClass('current');
            $('.titulo_destacado p').html(defaults['images'][i][1]);
        } else {
            $style += 'z-index: 0; ';
        }

        $div.attr('style', $style);
        $current.append($div);
    }

    startRotate(myTimer, $current.attr('id'), defaults['duration']);
}

function startRotate(myTimer, which, time){
    myTimer = setInterval("rotateImages('" + which +  "')", time);
}

function rotateImages(which){
    var oCurPhoto = $('#' + which + ' div.current');
    var oNxtPhoto = oCurPhoto.next();
    if (oNxtPhoto.length == 0)
        oNxtPhoto = $('#' + which + ' div:first');

    oCurPhoto.removeClass('current').css("z-index", "0").addClass('previous').css("z-index", "1");
  
    oNxtPhoto.css({opacity:0.0}).addClass('current').css("z-index", "2").animate({opacity:1.0}, 1000,
        function(){
            oCurPhoto.removeClass('previous').css("z-index", "0");
            $('.titulo_destacado p').html(oNxtPhoto.find('img').attr("alt"));
        });
}


