(function ($) {
    function Gallery(el, options) {
        this._hold = $(el);
        this.initOptions(options);
        this._timer = options.autoRotation;
        this._t;
        this.initialize();
    }

    $.fn.gallery = function (options) {
        return new Gallery(this.get(0), options);
    };

    Gallery.prototype = {
        initOptions: function (_obj) {
            this.options = {
                duration: 700,
                slideElement: 1,
                autoRotation: false,
                effect: false,
                listOfSlides: 'ul > li',
                switcher: false,
                disableBtn: false,
                stop: false,
                nextBtn: 'a.link-next, a.btn-next, a.next',
                prevBtn: 'a.link-prev, a.btn-prev, a.prev',
                circle: true,
                direction: false,
                IE: false
            };
            for (key in _obj) this.options[key] = _obj[key];
        },
        initialize: function () {
            var _this = this;
            var _hold = _this._hold;
            var _speed = _this.options.duration;
            var _timer = _this.options.autoRotation;
            var _el = _hold.find(_this.options.listOfSlides);
            if (_this.options.effect) var _list = _el;
            else var _list = _el.parent();
            var _switcher = _hold.find(_this.options.switcher);
            var _next = _hold.find(_this.options.nextBtn);
            var _prev = _hold.find(_this.options.prevBtn);
            var _count = _el.index(_el.filter(':last'));
            var _w = _el.outerWidth(true);
            var _h = _el.outerHeight(true);
            if (_this.options.switcher) var _active = _switcher.index(_switcher.filter('.active:eq(0)'));
            else var _active = _el.index(_el.filter('.active:eq(0)'));
            if (_active < 0) _active = 0;
            var _last = _active;

            // Installation directions
            if (!_this.options.direction) {
                var _wrapHolderW = Math.ceil(_list.parent().width() / _w);
                if (((_wrapHolderW - 1) * _w + _w / 2) > _list.parent().width()) _wrapHolderW--;
            }
            else {
                var _wrapHolderW = Math.ceil(_list.parent().height() / _h);
                if (((_wrapHolderW - 1) * _h + _h / 2) > _list.parent().height()) _wrapHolderW--;
            }

            // Setting "fade" or "slide" effect
            if (!_this.options.effect) var rew = _count - _wrapHolderW + 1;
            else var rew = _count;
            if (!_this.options.effect) {
                if (!_this.options.direction) _list.css({ marginLeft: -(_w * _active) })
                else _list.css({ marginTop: -(_h * _active) })
            }
            else {
                _list.css({
                    opacity: 0
                }).removeClass('active').eq(_active).addClass('active').css({
                    opacity: 1
                }).css('opacity', 'auto');
                _switcher.removeClass('active').eq(_active).addClass('active');
            }

            // Disable or enable buttons "prev next"
            if (_this.options.disableBtn) {
                if (_count < _wrapHolderW) _next.addClass(_this.options.disableBtn);
                if (_active == 0) _prev.addClass(_this.options.disableBtn);
            }

            // Function to "fade"
            function fadeElement() {
                if ($.browser.msie && _this.options.IE) {
                    _list.eq(_last).css({ opacity: 0 });
                    _list.removeClass('active').eq(_active).addClass('active').css({ opacity: 'auto' });
                }
                else {
                    _list.eq(_last).animate({ opacity: 0 }, { queue: false, duration: _speed });
                    _list.removeClass('active').eq(_active).addClass('active').animate({
                        opacity: 1
                    }, { queue: false, duration: _speed, complete: function () {
                        $(this).css('opacity', 'auto');
                    } 
                    });
                }
                if (_this.options.switcher) _switcher.removeClass('active').eq(_active).addClass('active');
                _last = _active;
            }

            // Function for "slide"
            function scrollEl() {
                if (!_this.options.direction) _list.animate({ marginLeft: -(_w * _active) }, { queue: false, duration: _speed })
                else _list.animate({ marginTop: -(_h * _active) }, { queue: false, duration: _speed })
                if (_this.options.switcher) _switcher.removeClass('active').eq(_active).addClass('active');
            }

            function toPrepare() {
                if ((_active == rew) && _this.options.circle) _active = -_this.options.slideElement;
                for (var i = 0; i < _this.options.slideElement; i++) {
                    _active++;
                    if (_active > rew) {
                        _active--;
                        if (_this.options.disableBtn && (_count > _wrapHolderW)) _next.addClass(_this.options.disableBtn);
                    }
                };
                if (_active == rew) if (_this.options.disableBtn && (_count > _wrapHolderW)) _next.addClass(_this.options.disableBtn);
                if (!_this.options.effect) scrollEl();
                else fadeElement();
            }
            _this._hold.bind('runTimer', function () {
                if (_this._t) clearTimeout(_this._t);
                _this._t = setInterval(function () {
                    toPrepare();
                }, _this._timer);
            });
            _next.click(function () {
                if (_this._t2) clearTimeout(_this._t2);
                if (_this._t) clearTimeout(_this._t);
                if (_this.options.disableBtn && (_count > _wrapHolderW)) _prev.removeClass(_this.options.disableBtn);
                toPrepare();
                if (!_this.options.stop) {
                    if (_this._timer) _this._hold.trigger('runTimer');
                } else {
                    _this._t2 = setTimeout(function () {
                        if (_this._timer) _this._hold.trigger('runTimer');
                    }, _this.options.stop - _speed);
                }
                return false;
            });
            _prev.click(function () {
                if (_this._t) clearTimeout(_this._t);
                if (_this.options.disableBtn && (_count > _wrapHolderW)) _next.removeClass(_this.options.disableBtn);
                if ((_active == 0) && _this.options.circle) _active = rew + _this.options.slideElement;
                for (var i = 0; i < _this.options.slideElement; i++) {
                    _active--;
                    if (_active < 0) {
                        _active++;
                        if (_this.options.disableBtn && (_count > _wrapHolderW)) _prev.addClass(_this.options.disableBtn);
                    }
                };
                if (_active == 0) if (_this.options.disableBtn && (_count > _wrapHolderW)) _prev.addClass(_this.options.disableBtn);
                if (!_this.options.effect) scrollEl();
                else fadeElement();
                if (!_this.options.stop) {
                    if (_this._timer) _this._hold.trigger('runTimer');
                } else {
                    _this._t2 = setTimeout(function () {
                        if (_this._timer) _this._hold.trigger('runTimer');
                    }, _this.options.stop - _speed);
                }
                return false;
            });
            if (_this.options.switcher) _switcher.click(function () {
                _active = _switcher.index($(this));
                if (_this._t) clearTimeout(_this._t);
                if (!_this.options.effect) scrollEl();
                else fadeElement();
                if (_this._timer) _this._hold.trigger('runTimer');
                return false;
            });
            if (_this._timer) _this._hold.trigger('runTimer');
        },
        stop: function () {
            var _this = this;
            if (_this._t) clearTimeout(_this._t);
        },
        play: function () {
            var _this = this;
            if (_this._t) clearTimeout(_this._t);
            if (_this._timer) _this._hold.trigger('runTimer');
        }
    }
} (jQuery));

jQuery.fn.gallSlide = function (_options) {
    // defaults options	
    var _options = jQuery.extend({
        duration: 700,
        listOfSlides: 'ul > li',
        nextBtn: 'a.btn-next',
        autoRotation: false,
        stop: false,
        setTo: false,
        prevBtn: 'a.btn-prev'
    }, _options);

    return this.each(function () {
        var _hold = $(this);
        var _speed = _options.duration;
        var _wrap = _hold.find(_options.listOfSlides).parent();
        var _el = _hold.find(_options.listOfSlides);
        var _next = _hold.find(_options.nextBtn);
        var _prev = _hold.find(_options.prevBtn);
        var _count = 0, der = 0, rety = 0, _t = null, _t2 = null;
        var _count2 = _el.index(_el.filter(':last'));
        var _wrapHolderW = _wrap.parent().width();
        var sum = 0;
        _el.each(function () {
            sum += $(this).outerWidth(true);
        });
        _wrap.eq(0).append(_el.clone());
        _wrap.eq(0).prepend(_el.clone());

        _el.each(function (_i) {
            _count = _count + $(this).outerWidth(true);
            if (rety + _el.eq(_count2 - _i).outerWidth(true) <= _wrapHolderW) {
                der++;
                rety = rety + _el.eq(_count2 - _i).outerWidth(true);
            }
        });
        var _active = 0, _w = sum;
        $(window).load(function () {
            _wrap.animate({ marginLeft: -(_w) }, { queue: false, duration: _speed });
        });



        this.setInitPos = function (pos) {
            var indexval = 0;
            if (!pos) {
                pos = -294; //294 position of aside on page;
                var cur = _el.find('a').filter('.active');
                if (!cur.length) cur = _el.find('a').filter('[href*=' + window.location.href + ']');
                if (cur.length) {
                    var ind = _el.find('a').index(cur);
                    indexval = ind;
                    if (ind == -1) i = 0;
                    for (var i = 0; i < ind; i++) {
                        pos += _el.eq(i).outerWidth(true);
                    };
                }
            };
            _w = pos + sum;
            $(window).load(function () {
                _wrap.animate({ marginLeft: -(_w) }, { queue: false, duration: _speed });
            });
            _active = indexval - 3;
        };
        if (_options.setTo) this.setInitPos();

        function scrollEl(_stop) {
            if (_t) clearTimeout(_t);
            if (!_stop) autorotate();
            else {
                _t2 = setTimeout(function () {
                    autorotate();
                }, _stop - _options.autoRotation);
            }
            _wrap.eq(0).animate({
                marginLeft: -(_w) + "px"
            }, { queue: false, duration: _speed });
        }
        function rotate(_stop) {
           if (_w == _count - _wrapHolderW + sum) _active = -1;
            _w = 0;
            _active++;
            _active++;
            for (var i = 0; i < _active; i++) {
                _w += _el.eq(i).outerWidth(true);
            };
            _w += sum;
           
            if (_w > (_count - _wrapHolderW + sum)) {
                _w = _count - _wrapHolderW + sum;
                scrollEl(_stop);
            } else {
                scrollEl(_stop);
            }
        }

        function autorotate() {
            if (_t) clearTimeout(_t);
            if (_options.autoRotation) {
                _t = setTimeout(function () {
                    rotate();
                }, _options.autoRotation);
            }
        }
        autorotate();

        _next.click(function () {
            rotate(_options.stop);
            if (_t2) clearTimeout(_t2);
            if (_t) clearTimeout(_t);
            return false;
        });
        _prev.click(function () {
            if (_t2) clearTimeout(_t2);
            _w = 0;
            _active--;
            _active--;
            if (_active < 0) { _active = _count2 + _active; }
            for (var i = 0; i < _active; i++) {
                _w += _el.eq(i).outerWidth(true);
            };
            _w += sum;
            if (_w > (_count - _wrapHolderW + sum)) _w = _count - _wrapHolderW + sum;
            if (_active == -1) {
                _w = _count - _wrapHolderW + sum;
                _active = _count2 - der + 1
                scrollEl(_options.stop);
            }
            else {
                scrollEl(_options.stop);
            }
            return false;
        });
    });
}

function initCufon() {
    Cufon.replace('.intro .gallery .heading h2', { fontFamily: 'futura-mb' });
    Cufon.replace('.product-list li a', { fontFamily: 'futura-m', hover: true });
    Cufon.replace('#sidebar .heading a', { fontFamily: 'futura-mb', hover: true });
    Cufon.replace('.socials-hold strong', { fontFamily: 'futura-m' });
    Cufon.replace('.add-nav strong', { fontFamily: 'futura-m' });
    Cufon.replace('.co-sponsor strong', { fontFamily: 'futura-m' });
}

function initTabs() {
    $('ul.tabset').each(function () {
        var btn_h = $(this);
        var _btn = $(this).find('a.tab');
        var _a = _btn.index(_btn.filter('.active:eq(1)'));
        if (_a == -1) _a = 0;
        _btn.removeClass('active').eq(_a).addClass('active');
        _btn.each(function (_i) {
            this._box = this.href.substr(this.href.indexOf("#") + 1);
            if (this._box) {
                this._box = $('#' + this._box);
                if (_i == _a) this._box.show();
                else this._box.hide();
            }
            this.onclick = function () {
                changeTab(_i);
                return false;
            }
        });
        function changeTab(_ind) {
            if (_ind != _a) {
                if (_btn.get(_a)._box) _btn.get(_a)._box.hide();
                if (_btn.get(_ind)._box) _btn.get(_ind)._box.show();
                _btn.eq(_a).removeClass('active');
                _btn.eq(_ind).addClass('active');
                _a = _ind;
            }
        }
    });
}

jQuery.fn.mouseGallerySlide = function (_options) {
    // defaults options	
    var _options = jQuery.extend({
        scrollElParent: 'ul',
        scrollEl: 'li'
    }, _options);

    return this.each(function () {
        var _this = $(this);
        var prev = _this.find('a.btn-prev');
        var next = _this.find('a.btn-next');
        var _gWidth = _this.outerWidth();
        var _scrollElParent = jQuery(_options.scrollElParent, _this);
        var _scrollEl = jQuery(_options.scrollEl, _this);
        var _liSum = 0;
        _scrollEl.each(function () {
            _liSum += $(this).outerWidth(true);
        });

        var _sec = (_liSum - _gWidth) * 30;

        var _maxMargin = _liSum;
        var _posHolder = _this.offset();
        var _width = _this.outerWidth();
        var _height = _this.outerHeight();

        var _chapter = _gWidth / 12;
        var _speed = 0
        var _direction = 2;
        var _timerOut = false;

        var _cloneList = _scrollEl.clone();
        _scrollElParent.append(_cloneList);

        jQuery(document).resize(function () {
            _posHolder = _this.offset();
        });
        mouseOverMove();
        function mouseOverMove() {
            _speed = 0.5;
            _direction = 3;
            animateEl();
        }

        prev.mousedown(function () {
            _scrollElParent.stop();
            _speed = 2.5;
            _direction = 1;
            animateEl();
        });
        prev.mouseup(function () {
            _scrollElParent.stop();
        });
        prev.click(function () {
            return false;
        });
        next.mousedown(function () {
            _scrollElParent.stop();
            _speed = 2.5;
            _direction = 3;
            animateEl();
        });
        next.mouseup(function () {
            _scrollElParent.stop();
        });
        next.click(function () {
            return false;
        });
        function animateEl() {
            if (_timerOut) clearTimeout(_timerOut);
            _scrollElParent.stop();
            var _curMargin = parseInt(_scrollElParent.css('marginLeft'));

            if (_direction == 1) {
                var k = -_curMargin / _maxMargin;
                _scrollElParent.stop()
					.animate(
						{ marginLeft: 0 },
						{ easing: 'linear', duration: (_sec / _speed) * k, complete: function () {
						    _scrollElParent.css({ 'marginLeft': -(_maxMargin) });
						    _timerOut = setTimeout(function () { animateEl() }, 15)
						} 
						}
					);
            }
            if (_direction == 3) {
                var k = (_maxMargin + _curMargin) / _maxMargin;
                _scrollElParent.stop()
					.animate(
						{ marginLeft: -_maxMargin },
						{ easing: 'linear', duration: (_sec / _speed) * k, complete: function () {
						    _scrollElParent.css({ 'marginLeft': 0 });
						    _timerOut = setTimeout(function () { animateEl() }, 15)
						} 
						}
					);
            }
        }
    });
}

$(window).bind('load', function () {
    $('div.scrollGallery').mouseGallerySlide({
        scrollElParent: 'ul',
        scrollEl: 'li'
    });
});

$(document).ready(function () {
    initCufon();
    $('div.gal-slide').gallSlide({
        listOfSlides: 'div.holder > ul > li',
        autoRotation: 6000,
        stop: 15000,
        duration: 500
    });
    $('div.gal-slide2').gallSlide({
        listOfSlides: 'div.hold > ul > li',
        setTo: true,
        nextBtn: 'a.btn-sp-next',
        prevBtn: 'a.btn-sp-prev'
    });

    $('div.gal-fade').gallery({
        effect: true,
        duration: 500,
        stop: 15000,
        autoRotation: 5000,
        listOfSlides: '> ul > li'
    });
    initTabs();
});
