(function($){

    $.fn.carousel = function(settings, callback)
    {
        var config      = {},
                carousel    = $(this);
    if (settings) $.extend(config, settings);

        // center images
        $(window).bind('resize', function()
            {
                carousel.find('img.background').each(function() {
                    $(this).css(
                        {
                            left: '50%',
                            marginLeft: -1 * $(this).width() / 2
                        }
                    );
                });
            }
        );
        $(window).resize();

        function carouselTimer() {
            $('.itemHolder').everyTime(6000, 'timer', function() {
                var next = $('.carouselItem.current').next();
                if (next.length == 0) {
                    next = $('.carouselItem:first');
                }
                location.hash = next.attr('rel');
            });
        }
        $(window).bind('hashchange', function()
        {
            var newPane = $('.carouselItem[rel="'+location.hash.substr(1)+'"]');
            if(newPane.length > 0)
            {
                var holder = newPane.parent(),
                        panes = holder.find('.carouselItem'),
                        arrowLeft = holder.siblings('.arrowLeft'),
                        arrowRight = holder.siblings('.arrowRight'),
                        currentPane = holder.find('.current'),
                        prevPane = newPane.prev(),
                        nextPane = newPane.next();

                currentPane.removeClass('current');
                newPane.addClass('current');

                $('.itemHolder').stopTime('timer');
                //carouselTimer();

                if (prevPane.length > 0) {
                    arrowLeft.show().attr('href', '#' + prevPane.attr('rel'));
                } else {
                    arrowLeft.hide();
                }
                if (nextPane.length > 0) {
                    arrowRight.show().attr('href', '#' + nextPane.attr('rel'));
                } else {
                    arrowRight.hide();
                }

                panes.each(function() {
                    $(this).animate(
                        { marginLeft: '-' + (newPane.index() * 100) + '%' },
                        700,
                        'easeInOutSine'
                    )
                });
                var carouselControls = holder.siblings('.carouselControls');
                carouselControls.find('.current').removeClass('current');
                carouselControls.children(':nth-child('+(newPane.index()+1)+')').addClass('current');
            }
        });
        if (location.hash) {
            $(window).hashchange();
        } else if ($('.carouselItem:first').length > 0) {
            location.hash = $('.carouselItem:first').addClass('current').attr('rel');
        }
        return this;
    }

})(jQuery);
