(function ($) {
    $.extend($.fn, {
        ariScrollable: function (options) {
            var opt = { displayCount: 1, currIndex: 0, shuffle: false, speed: 400, itemClass: 'inv-product', prevClass: 'left-arrow', nextClass: 'right-arrow' };
            $.extend(opt, options);

            return this.each(function () {
                var totalWidth = 0;
                var itemCount = 0;
                var $items = $('.' + opt.itemClass, this);
                $items.each(function () {
                    $(this).css({ 'float': 'left' });
                    totalWidth += $(this).outerWidth(true);
                    ++itemCount;
                });

                var $scrollable = $items.wrapAll('<div role="scrollable" />').parent();
                $scrollable.width(totalWidth);

                if (opt.shuffle)
                    shuffle();

                var avgItemWidth = totalWidth / itemCount;
                var containerWidth = opt.displayCount * avgItemWidth;

                var $container = $scrollable.wrapAll('<div role="container" />').parent();
                $container.width(containerWidth).css({ 'overflow-x': 'hidden', 'position': 'relative', 'float': 'left' });

                var $leftNav = $('.' + opt.prevClass, this);
                var $rightNav = $('.' + opt.nextClass, this);

                $leftNav.click(function (e) {
                    e.preventDefault();
                    scroll(-1);
                });

                $rightNav.click(function (e) {
                    e.preventDefault();
                    scroll(1);
                });

                $container.before($leftNav).after($rightNav);

                center($(this).width());

                scroll(0);

                function scroll(offset) {
                    var curr = opt.currIndex;
                    opt.currIndex += offset;
                    if (opt.currIndex < 0)
                        opt.currIndex = 0;
                    if (opt.currIndex + opt.displayCount > itemCount - 1)
                        opt.currIndex = itemCount - opt.displayCount;

                    if (curr !== opt.currIndex) {
                        $scrollable.animate({
                            'margin-left': -(opt.currIndex * avgItemWidth) + 'px'
                        }, opt.speed);
                    }
                    $leftNav.toggleClass('ui-state-disabled', opt.currIndex <= 0);
                    $rightNav.toggleClass('ui-state-disabled', opt.currIndex + opt.displayCount >= itemCount);
                }

                function shuffle() {
                    for (var i = 0; i < itemCount; ++i) {
                        var randomIdex = Math.floor(Math.random() * itemCount);
                        $scrollable.prepend($scrollable.find('.' + opt.itemClass).eq(randomIdex));
                    }
                }

                function center(w) {
                    var w2 = $container.outerWidth(true) + $leftNav.outerWidth(true) + $rightNav.outerWidth(true);
                    if (w > w2) {
                        w2 = Math.ceil(((w - w2) / 2) - parseInt($leftNav.css('margin-left')));
                        $leftNav.css('margin-left', w2 + 'px');
                    }
                }
            });
        },

        formatNews: function (options) {
            var opt = { preferredWidth: 120, preferredHeight: 120, shortenTextLength: 200 };
            $.extend(opt, options);

            return this.each(function () {
                var $container = $(this).find('.img-container');
                var $content = $(this).find('.news-content');

                var $img = $content.find('img');
                var src = $img.attr('src');
                $img.remove();

                var $newImg = $('<img />').load(function () {
                    if (sizeImage($(this), opt.preferredWidth, opt.preferredHeight)) {
                        $container.append(this);
                        $content.text(shortenText($content.text(), opt.shortenTextLength));
                    }
                    else {
                        $container.remove();
                        $(this).remove();
                    }
                }).attr('src', src);
            });
        }
    });

    function sizeImage($img, preferredWith, preferredHeight) {
        var imgWidth = parseFloat($img.attr('width'));
        var imgHeight = parseFloat($img.attr('height'));
        if (imgWidth / preferredWith < .75 || imgHeight / preferredHeight < .75) {
            return false;
        }
        var w, h;
        if (imgWidth < imgHeight) {
            w = preferredWith;
            h = Math.ceil(w / imgWidth * imgHeight);
        }
        else {
            h = preferredHeight;
            w = Math.ceil(h / imgHeight * imgWidth);
        }
        $img.width(w).height(h);
        return true;
    }

    function shortenText(fullText, shortLen) {
        if (fullText.length > shortLen) {
            fullText = fullText.substr(0, shortLen);
            var lBound = shortLen - 20;
            var i = shortLen - 2;

            while (i > lBound) {
                if (/[0-9A-Za-z][^0-9A-Za-z]/.test(fullText.substr(i, 2)))
                    return fullText.substr(0, i + 1) + '…'
                --i;
            }
            return fullText.substr(0, index - 1) + '…';
        }
        return fullText;
    }

})(jQuery);
