jQuery(function($){

    $.fn.extend({
        rvkJCarousel: function(o) {
            return this.each(function() {
                // copy all items
                var hidden_div = $('<div style="display: none;"></div>').appendTo($(this).parent());
                $(this).clone().appendTo(hidden_div);
                // title correct
                $('ul > li > a', hidden_div).each(function(){
                    if ($('span.title', $(this).parent()).size() > 0) {
                        $(this).attr('title', $('> span.title', $(this).parent()).html());
                    }
                });
                var itemList = [];
                $('li', this).each(function(){
                    itemList[itemList.length] = $(this).html();
                    $(this).remove();
                });
                
                var defaults = {
                    wrap: 'circular',
                    itemVisibleInCallback: {
                        onBeforeAnimation: function(carousel, item, i, state, evt) {
                            var idx = carousel.index(i, itemList.length);
                            carousel.add(i, itemList[idx - 1]);
                            var w, h;
                            // rel correct
                            var rel = $('> a', item).attr('rel');
                            if (rel != null && rel.length > 0) {
                                rel += '_click';
                                $('> a', item).attr('rel', rel);
                            }
                            $('img', item).each(function(){
                                w = $(this).width();
                                h = $(this).height();
                                if (w > 0 && h > 0) {
                                    $(this).css({left: ($(this).parent().width() - w) / 2, top: ($(this).parent().height() - h) / 2});
                                }
                            });
                        }
                    },
                    itemVisibleOutCallback: {
                        onAfterAnimation: function(carousel, item, i, state, evt) {
                            $('> a', item).unbind('click');
                            carousel.remove(i);
                        }
                    },
                    initCallback: function(carousel, state) {
                        if (state == 'init') {
                            $('.jcarousel-next,.jcarousel-prev', carousel.container).bind('click', function(){
                                carousel.options.auto = 0;
                            });
                        }
                    }
                }
                var options = $.extend(defaults, o || {});
                
                $(this).jcarousel(options);
                
            });
        }
    });

});
