/*
	jQuery Coda-Slider v2.0 - http://www.ndoherty.biz/coda-slider
	Copyright (c) 2009 Niall Doherty
	This plugin available for use in all personal or commercial projects under both MIT and GPL licenses.
*/

jQuery(document).ready(function($)
{
	// Remove the coda-slider-no-js class from the body
	$("body").removeClass("coda-slider-no-js");
	// Preloader
	$(".coda-slider").children('.panel').hide().end().prepend('<p class="loading">Loading...</p>');
});

var sliderCount = 1;

(function( $ ){
	
	$.fn.codaSlider = function(settings) {

		settings = $.extend({
			autoHeight: true,
			autoHeightEaseDuration: 1000,
			autoHeightEaseFunction: "easeInOutExpo",
			autoSlide: false,
			autoSlideInterval: 7000,
			autoSlideStopWhenClicked: true,
			crossLinking: true,
			dynamicArrows: true,
			dynamicArrowLeftText: "&#171;",
			dynamicArrowRightText: "&#187;",
			dynamicTabs: true,
			dynamicTabsAlign: "center",
			dynamicTabsPosition: "top",
			externalTriggerSelector: "a.xtrig",
			firstPanelToLoad: 1,
			panelTitleSelector: "h2.title",
			slideEaseDuration: 1000,
			slideEaseFunction: "easeInOutExpo"
		}, settings);
		
		
		$.fn.codaSlider.panelWidth;
		$.fn.codaSlider.panelCount;
		$.fn.codaSlider.panelContainerWidth;
		$.fn.codaSlider.currentPanel;
		$.fn.codaSlider.panelArray = Array();
		
		return this.each(function()
		{	
			// Uncomment the line below to test your preloader
			// alert("Testing preloader");
			
			var slider = $(this);
			
			// If we need arrows
			if (settings.dynamicArrows) {
				slider.parent().addClass("arrows");
				slider.before('<div class="coda-nav-left" id="coda-nav-left-' + sliderCount + '"><a href="#">' + settings.dynamicArrowLeftText + '</a></div>');
				slider.after('<div class="coda-nav-right" id="coda-nav-right-' + sliderCount + '"><a href="#">' + settings.dynamicArrowRightText + '</a></div>');
			};
			
			
			$("#coda-nav-1 li a").each( function()
			{
				$.fn.codaSlider.panelArray.push( $(this).attr("href").replace("#", "") );
			});
			
			//log ( $.fn.codaSlider.panelArray[2] );
			
			
			
			//var panelWidth = slider.find(".panel").width();
			$.fn.codaSlider.panelWidth = slider.find(".panel").width();
			
			var panelCount = slider.find(".panel").size();
			$.fn.codaSlider.panelCount = panelCount;
			 
			//var panelContainerWidth = panelWidth*panelCount;
			$.fn.codaSlider.panelContainerWidth = $.fn.codaSlider.panelWidth * panelCount;
			
			var navClicks = 0; // Used if autoSlideStopWhenClicked = true
			

			
			// Surround the collection of panel divs with a container div (wide enough for all panels to be lined up end-to-end)
			$('.panel', slider).wrapAll('<div class="panel-container"></div>');
			
			// Specify the width of the container div (wide enough for all panels to be lined up end-to-end)
			//$(".panel-container", slider).css({ width: panelContainerWidth });
			$(".panel-container", slider).css({ width: $.fn.codaSlider.panelContainerWidth });
			
			
			// Specify the current panel
			
			// Current panel index
			var currentPanel = parseInt(location.hash.slice(1))-1;
			$.fn.codaSlider.currentPanel = currentPanel;
			
			// Check to see if there is something with the ID of the hash in the slider, it conveniently already has the # on it
			var panel = $( location.hash.replace("#", "#panel-") );
			
			// Check that either the index isn't greater than the panelCount (now 0 based) or that we could find a panel with the ID
			if (settings.crossLinking && location.hash && (currentPanel < panelCount || panel.length == 1))
			{
			   // Check if there was a numeric hash, or if it was named...
			   if (isNaN(currentPanel)) {
				  currentPanel = $('.panel-container').find('.panel').index(panel);
				  
				  //currentPanel++;
				  $.fn.codaSlider.currentPanel = currentPanel + 1;
				 // log(currentPanel);
				 // $.fn.codaSlider.currentPanel = currentPanel = currentPanel + 1;
				 // log(currentPanel);
			   }
			  // var offset = - (panelWidth*(currentPanel));
			  var offset = - ($.fn.codaSlider.panelWidth*(currentPanel));
			   $('.panel-container', slider).css({ marginLeft: offset });
			  
			  $.fn.codaSlider.currentPanel = currentPanel = currentPanel + 1;
			}
			else if (settings.firstPanelToLoad != 1 && settings.firstPanelToLoad <= panelCount) { 
				var currentPanel = settings.firstPanelToLoad;
				$.fn.codaSlider.currentPanel = settings.firstPanelToLoad;
				//var offset = - (panelWidth*(currentPanel - 1));
				var offset = - ($.fn.codaSlider.panelWidth*(currentPanel - 1));
				$('.panel-container', slider).css({ marginLeft: offset });
			// Otherwise, we'll just set the current panel to 1...
			} else { 
				var currentPanel = 1;
				$.fn.codaSlider.currentPanel = 1;
			};
						

						
						

			
			/* Left and Right Arrows -------------------------------------------------------------- */
			
			// Left arrow click
			$("#coda-nav-left-" + sliderCount + " a").click(function()
			{
				navClicks++;
				if (currentPanel == 1)
				{
					//offset = - (panelWidth*(panelCount - 1));
					offset = - ($.fn.codaSlider.panelWidth*(panelCount - 1));
					alterPanelHeight(panelCount - 1);
					currentPanel = panelCount;
					$.fn.codaSlider.currentPanel = panelCount;
					slider.siblings('.coda-nav').find('a.current').removeClass('current').parents('ul').find('li:last a').addClass('current');
				}
				else
				{

					currentPanel -= 1;
					$.fn.codaSlider.currentPanel -= 1;
					alterPanelHeight(currentPanel - 1);
					//offset = - (panelWidth*(currentPanel - 1));
					offset = - ($.fn.codaSlider.panelWidth*(currentPanel - 1));
					slider.siblings('.coda-nav').find('a.current').removeClass('current').parent().prev().find('a').addClass('current');
				}
				
				$('.panel-container', slider).animate({ marginLeft: offset }, settings.slideEaseDuration, settings.slideEaseFunction);
				
				if (settings.crossLinking) { location.hash = $.fn.codaSlider.panelArray[currentPanel-1] }; // Change the URL hash (cross-linking)
				
				return false;
			});
				
			// Right arrow click
			$('#coda-nav-right-' + sliderCount + ' a').click(function()
			{
				navClicks++;
				if (currentPanel == panelCount)
				{
					offset = 0;
					currentPanel = 1;
					$.fn.codaSlider.currentPanel = 1;
					alterPanelHeight(0);
					slider.siblings('.coda-nav').find('a.current').removeClass('current').parents('ul').find('a:eq(0)').addClass('current');
				} 
				else
				{
					//offset = - (panelWidth*currentPanel);

					
					offset = - ($.fn.codaSlider.panelWidth*currentPanel);
					alterPanelHeight(currentPanel);
					currentPanel += 1;
					$.fn.codaSlider.currentPanel += 1;
					slider.siblings('.coda-nav').find('a.current').removeClass('current').parent().next().find('a').addClass('current');
				};
				
				$('.panel-container', slider).animate({ marginLeft: offset }, settings.slideEaseDuration, settings.slideEaseFunction);
				
				if (settings.crossLinking) { location.hash = $.fn.codaSlider.panelArray[currentPanel-1] }; // Change the URL hash (cross-linking)
				
				return false;
			});
			
			/* ------------------------------------------------------------------------------------ */
			
			
			
			
			// If we need a dynamic menu
			if (settings.dynamicTabs) {
				var dynamicTabs = '<div class="coda-nav" id="coda-nav-' + sliderCount + '"><ul></ul></div>';
				switch (settings.dynamicTabsPosition) {
					case "bottom":
						slider.parent().append(dynamicTabs);
						break;
					default:
						slider.parent().prepend(dynamicTabs);
						break;
				};
				ul = $('#coda-nav-' + sliderCount + ' ul');
				// Create the nav items
				$('.panel', slider).each(function(n) {
					ul.append('<li class="tab' + (n+1) + '"><a href="#' + (n+1) + '">' + $(this).find(settings.panelTitleSelector).text() + '</a></li>');												
				});
				navContainerWidth = slider.width() + slider.siblings('.coda-nav-left').width() + slider.siblings('.coda-nav-right').width();
				ul.parent().css({ width: navContainerWidth });
				switch (settings.dynamicTabsAlign) {
					case "center":
						ul.css({ width: ($("li", ul).width() + 2) * panelCount });
						break;
					case "right":
						ul.css({ 'float': 'right' });
						break;
				};
			};
				
				
				
				
				
			// If we need a tabbed nav
			$('#coda-nav-' + sliderCount + ' a').each(function(z) {
				// What happens when a nav link is clicked
				$(this).bind("click", function(e) {
				
					e.preventDefault();

					window.location.hash = $(this).attr('href');
					
					navClicks++;
					$(this).addClass('current').parents('ul').find('a').not($(this)).removeClass('current');
					//offset = - (panelWidth*z);
					offset = - ($.fn.codaSlider.panelWidth*z);
					
					//log($.fn.codaSlider.panelWidth);
					
					alterPanelHeight(z);
					currentPanel = z + 1;
					$.fn.codaSlider.currentPanel = z + 1;
					$('.panel-container', slider).animate({ marginLeft: offset }, settings.slideEaseDuration, settings.slideEaseFunction);
					if (!settings.crossLinking) { return false }; // Don't change the URL hash unless cross-linking is specified
				});
			});
			
			
			
			/* For #product-name ---------------- */
			
			// External triggers (anywhere on the page)
			$(settings.externalTriggerSelector).each(function()
			{
			   // Make sure this only affects the targeted slider
			   if (sliderCount == parseInt($(this).attr("rel").slice(12))) {
				  $(this).bind("click", function(e) {
				  				
					//e.preventDefault();

					 navClicks++;
					 // Subtract 1 to make it zero based
					 targetPanel = parseInt($(this).attr("href").slice(1))-1;
					 
					 // If the hash isn't numeric, see if we can get an index from the ID
					if (isNaN(targetPanel))
					{
						var hashStr = $(this).attr('href').split('#')[1];
						var panel = $( "#panel-" + hashStr, slider);
						targetPanel = $('.panel-container').find('.panel').index(panel);
					}
					 
					 // Don't have to subtract 1 anymore, any where targetPanel is used
					 //offset = - (panelWidth*(targetPanel));
					 offset = - ($.fn.codaSlider.panelWidth*(targetPanel));
					 alterPanelHeight(targetPanel);
					 currentPanel = targetPanel + 1;
					 $.fn.codaSlider.currentPanel = targetPanel + 1;
					 
					// log( targetPanel );
					 
					// Switch the current tab:
					//slider.siblings('.coda-nav').find('a').removeClass('current').parents('ul').find('li:eq(' + (targetPanel) + ') a').addClass('current');					
					$(".coda-nav a").removeClass("current");
					$(".coda-nav li:eq("+targetPanel+") a").addClass("current");
					 
					 // Slide
					 $('.panel-container', slider).animate({ marginLeft: offset }, settings.slideEaseDuration, settings.slideEaseFunction);
					 if (!settings.crossLinking) { return false }; // Don't change the URL hash unless cross-linking is specified
				  });
			   };
			});
			
			/* ---------------------------------- */


			/* set current tab on load to current */
		
			//log(location.hash.slice(1) - 1);
		
		 	if (settings.crossLinking && location.hash && parseInt(location.hash.slice(1)) <= panelCount)
			{
				// Specify which tab is initially set to "current". Depends on if the loaded URL had a hash or not (cross-linking).				
				$("#coda-nav-" + sliderCount + " a:eq(" + (location.hash.slice(1) - 1) + ")").addClass("current");
			} 
			else if (settings.firstPanelToLoad != 1 && settings.firstPanelToLoad <= panelCount)
			{
				// If there's no cross-linking, check to see if we're supposed to load a panel other than Panel 1 initially...
				$("#coda-nav-" + sliderCount + " a:eq(" + (settings.firstPanelToLoad - 1) + ")").addClass("current");
			}
			else
			{
				// Otherwise we must be loading Panel 1, so make the first tab the current one.
				$("#coda-nav-" + sliderCount + " a:eq(0)").addClass("current");
			};
			
			
			
			if ( location.hash )
			{
				$("#coda-nav-1 a").removeClass("current");
				$("#carousel-" + location.hash.replace("#", "") ).addClass("current");
			}

			
			
			// Set the height of the first panel
			if (settings.autoHeight) {
				panelHeight = $('.panel:eq(' + (currentPanel - 1) + ')', slider).height();
				slider.css({ height: panelHeight });
			};
			
			// Trigger autoSlide
			if (settings.autoSlide) {
				slider.ready(function() {
					setTimeout(autoSlide,settings.autoSlideInterval);
				});
			};
			
			function alterPanelHeight(x) {
				if (settings.autoHeight) {
					panelHeight = $('.panel:eq(' + x + ')', slider).height()
					slider.animate({ height: panelHeight }, settings.autoHeightEaseDuration, settings.autoHeightEaseFunction);
				};
			};
			
			function autoSlide() {
				if (navClicks == 0 || !settings.autoSlideStopWhenClicked) {
					if (currentPanel == panelCount) {
						var offset = 0;
						currentPanel = 1;
						$.fn.codaSlider.currentPanel = 1;
					} else {
						//var offset = - (panelWidth*currentPanel);
						var offset = - ($.fn.codaSlider.panelWidth*currentPanel);
						currentPanel += 1;
						$.fn.codaSlider.currentPanel += 1;
					};
					alterPanelHeight(currentPanel - 1);
					// Switch the current tab:
					slider.siblings('.coda-nav').find('a').removeClass('current').parents('ul').find('li:eq(' + (currentPanel - 1) + ') a').addClass('current');
					// Slide:
					$('.panel-container', slider).animate({ marginLeft: offset }, settings.slideEaseDuration, settings.slideEaseFunction);
					setTimeout(autoSlide,settings.autoSlideInterval);
				};
			};
			
			// Kill the preloader
			$('.panel', slider).show().end().find("p.loading").remove();
			slider.removeClass("preload");
			
			sliderCount++;
			
		});
	};
	
	
	
	
	$.fn.codaSlider.updateWidth = function( newWidth )
	{
		$.fn.codaSlider.panelWidth				= newWidth;
		$.fn.codaSlider.panelContainerWidth		= newWidth * ($.fn.codaSlider.panelCount + 1);

		//log( $.fn.codaSlider.currentPanel );
		
		offset = - ($.fn.codaSlider.panelWidth * ($.fn.codaSlider.currentPanel-1) );
		$('.panel-container', "#coda-slider-1").width($.fn.codaSlider.panelContainerWidth).animate({ marginLeft: offset }, 100);
		
		//log( $.fn.codaSlider.panelContainerWidth );
		
		return true;
	}
	
	

})( jQuery );
