/*
 * 	Slide Pages - jQuery plugin
 *	written by MagicWeb.org
 *	http://magicweb.org
 *	Copyright (c) 2011 MagicWeb.org LLC (http://magicweb.org)
 */

/*
 *	markup example for $("div.slide-pages").slidePages();
 *	
 * 	<div class="slide-pages">
 *		<child>...</child>
 *		<child>...</child>
 *		...
 * 	</div>
 *
 */

(function($) {

	$.fn.slidePages = function(options) {

		/**
		 * Default configuration properties
		 */
		var defaults = {
		    autorun          : 'true',
		    childrenClass    : 'page',
		    buttonBarClass   : 'button-bar',
		    statusBarClass   : 'status-bar',
			prevClass        : 'prev-btn',
			prevLabel        : 'Previous',
			nextClass        : 'next-btn',
			nextLabel        : 'Next',
			orientation      : 'horizontal',
			interval         : 2000,
			speed            : 500
		};
        
		/**
		 * Override defaults with opt
		 */
		var opt = $.extend(defaults, options);

		/**
		 * Return set of matched elements to maintain chainablilty
		 */
		return this.each(function() {
            
			// Define key elements
			var $pageContainer = $(this);
			var $children = $pageContainer.find('.container-child').children('.' + opt.childrenClass);
			$children.wrapAll('<div class="wrapper"><div class="frame"><div class="slider"></div></div></div>');
			var $slider = $children.parent();
			var $frame  = $slider.parent();
			
			// Define measurement constants
			var l = $children.length;
			var w = $slider.width();
			var h = maxHeight($children);
			
			// Set CSS appropriately
			$frame.css({
				'position': 'relative',// fixes the overflow:hidden bug in IE
				'overflow': 'hidden',
				'padding': 0
			});
			$slider.css({
				'position': 'relative',
				'width': l*w,
				'height': h,
				'margin-left': 0
			});
			$children.css({
				'display': 'block',
				'position': 'absolute',
				'top': 0,
				'left': 0,
				'width': w,
				'height': h
			});
			
			// Add buttons
			var $prevBtn = $('<a href="javascript:void(0)" class="' + opt.prevClass + '">' + opt.prevLabel + '</a>');
			var $nextBtn = $('<a href="javascript:void(0)" class="' + opt.nextClass + '">' + opt.nextLabel + '</a>');
			var $buttonBar = $('<div class="' + opt.buttonBarClass + '"></div>');
			var $statusBar = $('<div class="' + opt.statusBarClass + '"></div>');
			$buttonBar.append($prevBtn, $nextBtn).insertAfter($frame);
			$statusBar.insertAfter($buttonBar);
			
			// Iterate children
			$children.each(function(i) {
				// Position children
				if ('horizontal' === opt.orientation) {
					$(this).css({ 'left': i*w });					
				} else {
					$(this).css({ 'top': i*h });
				}
				// Add links to childrenBar
				var $childBtn = $('<a href="javascript:void(0)">' + (i+1) + '</a>');
				$childBtn.appendTo($statusBar).click(function(e) {
					slideTo(i);
				});
			});
			
			// Add event handlers
			$prevBtn.click(function(e) { slidePrev() });
			$nextBtn.click(function(e) { slideNext() });
			$(document).keydown(function(evt) {
				if ('horizontal' == opt.orientation) {
		            if (evt.keyCode == 37) slidePrev();
		            if (evt.keyCode == 39) slideNext();
				} else {
		            //if (evt.keyCode == 38) slideUp();
		            //if (evt.keyCode == 40) slideDown();
				}
	        });			
			// Init plugin
			if (opt.autorun) autorun();
			updateStatusBar(0);
			
			/**
			 * Transition to the right
			 */
			function slidePrev()
			{
				var offset = parseInt($slider.css('margin-left'));
				var margin = parseInt((offset + 1) / w) * w;
				$slider.animate({'margin-left': margin}, opt.speed, function() {
					// Set autorun if on
					if (opt.autorun) autorun();
				});
				updateStatusBar(margin);
			}
			
			/**
			 * Transition to the left
			 */
			function slideNext()
			{
				var offset = parseInt($slider.css('margin-left'));
				var max = w * l;
				var margin = (parseInt(offset/w) * w - w) % max;
				$slider.animate({'margin-left': margin}, opt.speed, function() {
					// Set autorun if on
					if (opt.autorun) autorun();
				});
				updateStatusBar(margin);
			}
			
			function slideTo(index)
			{
				var margin = -(index * w);
				$slider.animate({'margin-left': margin}, opt.speed, function() {
					// Set autorun if on
					if (opt.autorun) autorun();
				});
				updateStatusBar(margin);
			}
			
			function updateStatusBar(offset)
			{
				var index = Math.abs(parseInt(offset / w));
				$statusBar.children().removeClass('on');
				var active = $statusBar.children().get(index);
				$(active).addClass('on');
			}
			
			/**
			 * Run the transition periodically, but cancel if one is running
			 */
			function autorun()
			{
				if (typeof intervalId == 'number') clearInterval(intervalId);
				intervalId = setInterval(function() {
					slideNext();
				}, opt.interval);
			}
			
			/**
			 * Get the tallest child
			 */
			function maxHeight($elements)
			{
				var maxHeight = 0;
				$elements.each(function(i) {
					maxHeight = Math.max(maxHeight, $(this).height());
				});
				return maxHeight;
			}
			
		});

	};

})(jQuery);
