var images = $( '#MainImage .slides_container img' ),
    next = $('#MainImage .next').eq(0)
    previous = $('#MainImage .prev').eq(0),
    current_offset = 0,
    fade_speed = 400,
    interval = 4000,
    timeout = undefined,
    from_z = 2,
    to_z = 1,
    do_fade = function(next_offset){
        if ( next_offset === undefined ) next_offset = current_offset + 1;
        var from = $(images[current_offset]),
            to = images[next_offset];

        if ( to === undefined ) {
            next_offset = 0;
            to = images[next_offset];
        }

        to = $(to);

        from.css('z-index' , from_z);
        to.css('z-index' , to_z)
            .css('opacity' , 1);
        from.animate({
            opacity: 0
        }, fade_speed);

        current_offset = next_offset;
        timeout = setTimeout(do_fade , interval);
    };

images.each(function(i){
    $(images[i]).css('opacity' , 0);
});

$(images[0]).css('opacity' , 1);

timeout = setTimeout(do_fade , interval);

next.click(function(){
    clearTimeout( timeout );
    do_fade( current_offset + 1 );
    return false;
});

previous.click(function(){
    clearTimeout( timeout );
    do_fade( current_offset - 1 < 0 ? images.length - 1 : current_offset - 1 );
    return false;
});

