$(function(){
    var cxCarousel = function(id,step,width,carousel,leftb,rightb) {
        var $id = $(id);
        if ($id.length == 0) return false;

        var getItemWidth = function() {
            var a = $id.find('a').first();
            return a.width();
        };

        var countItems = function() {
            return $id.find('a').length-1;
        };

        var opt = {
            step: step || 2,
            width: width || getItemWidth(),
            carousel: carousel || '.inner',
            leftb: leftb || '.toLeft',
            rightb: rightb || '.toRight'
        };

        var getItems = function() {
            var arr = [];
            $id.find(opt.carousel).find('a').each(function(){
               arr.push($(this));
            });
            return arr;
        };

        opt.items = getItems();

        $id.find(opt.carousel).css({
            'width':opt.width*countItems(),
            'left': '-'+opt.width*step+'px'
        });

        var animatedFlag = false;

        var leftbClick = function(left) {
            if (animatedFlag) return false;
            animatedFlag = true;
            var csswidth = opt.items[0].css('width');
            var cssmr = opt.items[0].css('marginRight');
            var elem, elem2, s, s2;
            for (var i=0; i<opt.step; i++) {
                if (left) { elem = opt.items[opt.items.length-1-i]; s = 0; s2 = 400; }
                else { elem = opt.items[i]; s = 400; s2 = 0; }
                    elem.animate({
                        width: 0,
                        marginRight: 0
                    },s,function(){
                            if (left) elem2 = $(this).prependTo(id+' '+opt.carousel);
                            else elem2 = $(this).appendTo(id+' '+opt.carousel);
                            elem2.animate({
                                width: csswidth,
                                marginRight: cssmr
                            },s2,function(){ opt.items = getItems(); animatedFlag = false; });
                        }
                    );
            }
        };

        $id.find(opt.leftb).bind('click',function(){
            leftbClick(true);
            return false;
        });

        $id.find(opt.rightb).click(function(){
            leftbClick();
            return false;
        });

   };
   cxCarousel('#brandsline',2,122);
});
