$(function(){

	var offset = 110;
	var width = 680;

	$('div.featured-videos').scrolly({
		selectors: {
			items: '.video-item'
		},

		after: function(){
			this.bindNext($('.right-bar a', this.el));
			this.bindPrev($('.left-bar a', this.el));
		},

		before: function() {
			var container = this.container(),
			items     = this.items();

			// Ensure we have 2 elements
			if (this.total() < 2) {
				items.eq(0).appendTo(container);
			}

			// Clone the last two elements and shove them first
			container.prepend(items.slice(-2).clone().addClass('clone'));

			// Clone first two elements and put them at the end
			container.append(items.slice(0,2).clone().addClass('clone'));

			// set active element
			this.at(3).addClass(this.classes.active).css({
				opacity: 1
			});

			this.container().css({
				left: (2 * -width) + offset
			});
		},

		autoscroll: 4000,

		autohide:false,

		valueNextIncrement: function(){
			if (this.current() > this.total() - 1){
				return 3;
			}

			return this.current() + 1;
		},

		valuePrevIncrement: function(){
			if (this.current() < 3){
				return this.total() - 3;
			}

			return this.current() - 1;
		},

		/**
					 * Show an element of a container
					 */
		show: function(item){
			var $item = $(item),
			self  = this,
			itemIndex = this.indexOf($item);

			// Activate current item
			this.activate($item);

			// Move the container to the correct position
			this.shiftContainer(itemIndex * -width + offset, 400, function(){

				// If we have moved to a cloned element, move to our real element
				if ($item.hasClass('clone')){

					var realIndex = itemIndex < 2 ? self.total() - 2 : 3,
					realElement = self.at(realIndex);

					// Highlight new element
					self.highlight(realElement, 0);

					// Activate it
					self.activate(realElement);

					// Hide old element
					self.hide($item);

					// Shift the container
					self.shiftContainer((realIndex - 1) * -width + offset, 0);
				}
			});

			this.highlight($item);
		},

		activate: function(item){
			item.addClass(this.classes.active);
		},

		shiftContainer: function(left, speed, callback){
			callback = callback || function(){};

			this.container().stop(true).animate({
				left: left
			}, speed, 'swing', callback);
		},

		indexOf: function(item){
			return item.prevAll().length;
		},

		highlight: function(item, time){
			if (typeof time === 'undefined'){
				time = 800;
			}

			item.stop(true,true).animate({
				opacity:1
			}, time);
			item.siblings().stop(true,true).animate({
				opacity: .3
			}, 400);
		},

		hide: function(item){
			$(item).removeClass(this.classes.active);
		}
	});
});