;(function($){

	var defaults = {
		duration : 500,
		delay	 : 4000
	};

	$.fn.sliderButtons = function(options) {


		return this.each(function(){
			var	$this 		 	= $(this),
				$buttons 	 	= $(this).find('ul#buttons li a'),
				$panels		 	= $('#images').find('div.panel'),
				$mask 		 	= $('#images-mask'),
				panelCount   	= $panels.length,
				currentPanel 	= 1,
				containerHeight = panelCount * 220,
				//containerHeight = $('#images').height(),
				timer;

			var settings = $.extend({}, defaults, options);



			// Add the click event to the buttons
			$buttons.click(function(){
				return buttonClick(this, parseInt($(this).attr('href').replace('#horizontalSlider_Buttons_panel-', ''))+1);
			});

			// Initialize the slider
			initSlider();


			function initSlider()
			{
				// 1. Activate the current button
				$this.find('ul#buttons li a:first').addClass('active');

				// 2. Move the slider to the inital position and hide overflow
				$mask
					.css('overflow', 'hidden')
					.scrollTop(0);

				// 3. Start the slider
				timer = setInterval(slide, settings.delay);
			}


			function slide()
			{
				// When we've reached the end of the panels, move back to the starting point

				// console.log(currentPanel);

				if ( currentPanel >= panelCount ) {
					currentPanel = 0;
				}

				// Slide to the next panel
				$mask.animate({ scrollTop : currentPanel * ( containerHeight / panelCount) }, settings.duration);

				// Activate the current button
				activateButton(currentPanel);

				// Increase the counter
				currentPanel++;



			}

			function buttonClick(button, index)
			{
				$button = $(button);

				// Scroll to the correct panel
				$mask.scrollTo($button.attr('href'), 500);

				// Activate the correct button
				activateButton($button.attr('href'));

				//console.log('current panel: ' + currentPanel);

				// Set the active panel
				currentPanel = index;

				// console.log('current panel: ' + currentPanel);

				// Reset the timer
				clearInterval(timer);
				timer = setInterval(slide, settings.delay);

				return false;
			};


			function activateButton(href)
			{

				if ( typeof href == "number" ) {
					href = $('ul#buttons li a[href="#horizontalSlider_Buttons_panel-' + href + '"]').attr('href');
				}

				// Remove the active state from all the buttons
				// console.log($buttons);
				$buttons.removeClass('active');

				// Add the class "active" to the current active button
				$this.find('ul#buttons li a[href="' + href + '"]').addClass('active');

			}
		});

	}

})(jQuery);