$(function() {

    var ProductsCarousel = function($el, products) {
      this._$el = $el;
      this._products = [];
      this._scrollInterval;
      this._currentIndex = 0;

      this._init(products);
    };
    
    ProductsCarousel.PER_PAGE = 3;
    ProductsCarousel.ITEM_WIDTH = 138;
    ProductsCarousel.AUTOSCROLL_DELAY = 10 * 1000;
    ProductsCarousel.BASE_URL = "http://shop.respectproduction.com";
    
    ProductsCarousel.prototype._init = function(products) {
        var self = this;
        var $container = this._createItems(products);

        // stop right here if all products fits one page
        if (products.length <= ProductsCarousel.PER_PAGE) {
            return;
        }
        
        // create controls otherwise
        this._createControls($container);

        // and start autoscroll
        this._scrollInterval = setInterval(function() {
            if (!self._$el.is(':visible')) {
                return;
            }
            self._scrollPage(1);
        }, ProductsCarousel.AUTOSCROLL_DELAY);
    };
    
    ProductsCarousel.prototype._createItems = function(products) {
        var self = this;
        var $container = $('<div class="products_list_wrapper" />').appendTo(this._$el);
        this._$ul = $('<ul class="product_list"/>').width(32e3).appendTo($container); // 32Kpx will be enough for everyone :)

        $.each(products, function(_, productJSON) {
            self._createItem(productJSON)
        });

        for(var i=0; i < ProductsCarousel.PER_PAGE - this._products.length; i++) {
            self._createItem(products[i]);
        }
        
        return $container;
    };

    ProductsCarousel.prototype._createItem = function(productJSON) {
        var product = typeof productJSON === 'string' ? eval('(' + productJSON + ')') : productJSON;
        var url;
        if (product.images && product.images[1]) {
            url = product.images[1].thumb_url.replace('thumb', 'medium');
            if ($.trim(url).toLowerCase().indexOf('http://') !== 0) {
                url = ProductsCarousel.BASE_URL + url;
            }
            var $productEl = $('<li class="shop_item">' +
                      '<a target="_blank" href="' + 'http://shop.respectproduction.com' + product.url + '" class="shop_item_link">' +
                          '<img src="' + url + '" alt="" class="shop_item_img" />' +
                          '<span class="shop_item_price">' + product.variants[0].price + ' руб.</span>' +
                      '</a>' +
                 '</li>').appendTo(this._$ul);

            this._products.push($productEl);
        }
    };

    ProductsCarousel.prototype._createControls = function($container) {
        var self = this;
        var $scrollLeft = $('<a href="#" class="scroll_left"><img src="/images/icons/str3.gif" alt="" /></a>');
        var $scrollRight = $('<a href="#" class="scroll_right"><img src="/images/icons/str4.gif" alt="" /></a>');

        $scrollLeft.add($scrollRight)
            .click(function() {
                clearInterval(self._scrollInterval);
                return self._scrollPage(this === $scrollLeft[0] ? -1 : 1);
            })
            .insertBefore($container);
    };
    
    ProductsCarousel.prototype._scrollPage = function(n) {
        n = n * ProductsCarousel.PER_PAGE;
        var newIndex = this._currentIndex + n;
        var toRemove = [];
        var self = this;
        var fixMargin = 0
        
        this._$ul.stop(false, true);
        
        // todo: simplify this shit
        if (newIndex < 0) {
            var toMove = this._products.splice(newIndex, Math.abs(newIndex));
            var clone;
            
            for(i = toMove.length; i--;) {
                clone = toMove[i].clone();
                clone.prependTo(this._$ul);
                this._$ul.animate({ 'marginLeft': '-=' + ProductsCarousel.ITEM_WIDTH }, 0);
                this._products.unshift(clone);
                toRemove.push(toMove[i]);
            }
            
            this._currentIndex = 0;
        } else if (newIndex + ProductsCarousel.PER_PAGE >= this._products.length) {
            // debugger;
            var m = newIndex + ProductsCarousel.PER_PAGE - this._products.length;
            toMove = this._products.splice(0, m);
            
            for(i = 0 ; i < toMove.length; ++i) {
                clone = toMove[i].clone();
                clone.appendTo(this._$ul);
                this._products.push(clone);
                toRemove.push(toMove[i]);
            }
            this._currentIndex = newIndex - m;
            fixMargin = m * ProductsCarousel.ITEM_WIDTH;
        } else {
          this._currentIndex = newIndex;
        }
        
        this._$ul.animate({
            'marginLeft': '-=' + n * ProductsCarousel.ITEM_WIDTH
        }, 600, function() {
            for(var i = toRemove.length; i--;) {
                toRemove[i].remove();
            }
            self._$ul.animate({
                'marginLeft': '+=' + fixMargin
            }, 0);
        });
        
        return false;
    };

    $('#shop_tabs').tabs();

    var shopCategories = [
          'http://shop.respectproduction.com/collection/hats.json',
          'http://shop.respectproduction.com/collection/disks.json'
    ];

    $.each(shopCategories, function(i, url) {
        i++;
        window['_respectshop' + i] = function (json) {
            if (!json.products || !json.products.length) {
              return;
            }

            new ProductsCarousel($('#shop-tab-' + i), json.products);
        };
        var $script = $('<script/>');
        $script.attr('src', url + '?callback=_respectshop' + i);
        $script.appendTo('head');
    });

});
 
