﻿
$.fn.smooth = function (settings) {

	settings = $.extend({
		autoSlide: true,
		autoSlideInterval: 12000,
		autoSlideStopWhenClicked: true,
		firstPanelToLoad: 0
	}, settings);

	return this.each(function () {
		var smooth = $(this);

		var panelWidth = smooth.find(".smoothPanel").width();
		var panelCount = smooth.find(".smoothPanel").size();

		var navPanel = smooth.find(".smoothNav");

		var navClicks = 0; // Used if autoSlideStopWhenClicked = true

		var currentPanelIndex = settings.firstPanelToLoad;

		// Create navigation elements (bulls)
		$(".smoothPanel", smooth).each(function (n) {
			navPanel.append('<div class="smoothDot">'+(n+1)+'</div>');
		});

		// Click navigation element
		$(".smoothDot", navPanel).click(function () {
			navClicks++;

			currentPanelIndex = $(this).index();

			setPanel();
		});


		// Show start panel when smooth is ready
		smooth.ready(function () {

			navPanel.find(".smoothDot:eq(" + currentPanelIndex + ")").addClass("smoothSelectedDot");
			//smooth.find(".smoothPanel:eq(" + currentPanelIndex + ")").css("opacity", "1");
			//smooth.find(".smoothPanel:eq(" + currentPanelIndex + ")").show();

			setTimeout(autoSlide, settings.autoSlideInterval);
		});


		// Slide using current index
		function setPanel() {
			if (currentPanelIndex >= panelCount) currentPanelIndex = 0;

			var currentPanel = smooth.find(".smoothPanel:eq(" + currentPanelIndex + ")");
			var currentNavElement = navPanel.find(".smoothDot:eq(" + currentPanelIndex + ")");

			// Check if this panel already active
			if (currentNavElement.hasClass("smoothSelectedDot"))
				return;

			// Reset all navigation elements
			navPanel.find(".smoothDot").each(function (n) {
				$(this).removeClass("smoothSelectedDot");
			});

			// Hide all panels
			smooth.find(".smoothPanel").each(function (n) {
				//$(this).fadeOut(150);
				//$(this).animate({ opacity: "0", filter: "", zoom: "" }, 150);
				$(this).hide()
			});

			//currentPanel.fadeIn(300);
			//currentPanel.animate({ opacity: "1", filter: "", zoom: "" }, 300);
			currentPanel.show();

			currentNavElement.addClass("smoothSelectedDot");
		}

		function autoSlide() {
			if (navClicks == 0 || !settings.autoSlideStopWhenClicked) {

				currentPanelIndex++;

				setPanel();

				setTimeout(autoSlide, settings.autoSlideInterval);
			};
		};
	});
};
