﻿/// Home items slider
jQuery(function ($) {
	$.fn.slide = function () {
		var slider = new $.fn.slide.slider(this);
		//return this.each(function() {
		//});
	}

	$.fn.slide.options = {
		changeTimeout: 3000,
		duration: 1500
	}

	// Slider
	$.fn.slide.slider = function (slider) {
		this.init(slider);
	}

	$.fn.slide.slider.prototype = {
		init: function (slider) {
			this._timer = null;
			this._index = null;
			this._width = 0;

			this._slider = slider;
			this._itemsBox = this._slider.children('.items');
			this._items = this._itemsBox.children('.item');
			this._image2 = $('<div class="image"/>').prependTo(this._slider);
			this._image1 = $('<div class="image"/>').prependTo(this._slider);

			this._title2 = $('<div class="title"/>').prependTo(this._slider);
			this._title1 = $('<div class="title"/>').prependTo(this._slider);

			// Preload images
			this._items.each(function () {
				var imgUrl = $(this).attr('background');
				var img = new Image();
				img.src = imgUrl;
			});

			// Fix items width
			var sliderWidth = this._slider.outerWidth(true);
			var itemsWidthSum = 0;
			this._items.each(function () { itemsWidthSum += $(this).outerWidth(true); });

			var itemAvgSize = sliderWidth / this._items.length;
			var overSizedItems = this._items.filter(function () { return $(this).outerWidth(true) > itemAvgSize; });
			var clipWidth = (itemsWidthSum - sliderWidth) / overSizedItems.length;
			overSizedItems.each(function () {
				var self = $(this);
				var w = self.width() - clipWidth;
				self.width(w);
			});

			var lastItem = this._items.last();
			lastItem
				.width(lastItem.width() + parseInt(lastItem.css('margin-right')))
				.css('margin-right', 0);

			this.slide();
		},

		slide: function () {
			clearTimeout(this._timer);

			var index = this._index || 0;
			if (this._index != null) index++;

			this.move(index);
			this.startTimer();
		},

		move: function (index) {
			if (index >= this._items.length) {
				index = 0;
			}
			if (index == this._index) return;
			this._index = index;

			// Move button
			this._items.stop(true, false).removeClass('selected');
			var selItem = $(this._items[index]);
			selItem.addClass('selected');

			// Move image & title
			var url = 'url(' + selItem.attr('background') + ')';
			var title = selItem.html();
			this._title1.html(title);
			this._title2.hide();

			this._image2.css({ 'background-image': url, opacity: 0 })
				.stop(true, false)
				.animate(
					{ 'opacity': 1 },
					$.fn.slide.options.duration,
					Function.createDelegate(this, function () {
						this._image1.css({ 'background-image': url });
						this._image2.css({ opacity: 0 });
					})
				);
		},

		startTimer: function () {
			var me = this;
			this._timer = setTimeout(function () { me.slide(); }, $.fn.slide.options.changeTimeout);
		}
	}
});
