/*
	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.
*/

$(function(){
	// Remove the coda-slider-no-js class from the body
	$("body").removeClass("coda-slider-no-js");
	// Preloader
	//$("#coda-slider-1").children('.panel').hide().end().prepend('<p class="loading">Loading...</p>');
	$("#coda-slider-1").children('.panel').hide().end().prepend('<p class="loading">Loading...</p>');
/*	$("#coda-slider-2").children('.panel').hide().end().prepend('<p class="loading">Loading...</p>');
	$("#coda-slider-3").children('.panel').hide().end().prepend('<p class="loading">Loading...</p>');
	$("#coda-slider-4").children('.panel').hide().end().prepend('<p class="loading">Loading...</p>');
*/});

var sliderCount = 1;

$.fn.codaSlider = function(settings) {
	settings = $.extend({
		autoHeight: false,
		autoHeightEaseDuration: 1000,
		autoHeightEaseFunction: "easeInOutExpo",
		autoSlide: true,
		autoSlideInterval: 6000,
		timer:4000,
		autoSlideStopWhenClicked: false,
		autoSlidePause: false,
		crossLinking: true,
		dynamicArrows: true,
		dynamicArrowLeftText: "&nbsp;",
		dynamicArrowRightText: "&nbsp;",
		dynamicTabs: true,
		dynamicTabsAlign: "center",
		dynamicTabsPosition: "middle",
		externalTriggerSelector: "a.xtrig",
		firstPanelToLoad: 1,
		panelTitleSelector: "h2.title",
		productPanelTitleSelector: "h2.tabtitle",
		slideEaseDuration: 1000,
        slideEaseFunction: "easeInOutExpo",
        selectionWillChangeCallback:null,
        selectionDidChangeCallback:null

	}, settings);
	
	return this.each(function(){
		
		// Uncomment the line below to test your preloader
		
		var slider = $(this);
		
		// If we need arrows
		if (settings.dynamicArrows) {
			slider.parent().addClass("arrows");
			slider.after('<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>');
		};
		
		var panelWidth = slider.find(".panel").width();
		var panelCount = slider.find(".panel").size();
		var panelContainerWidth = 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 });
				
		// Specify the current panel.
		// If the loaded URL has a hash (cross-linking), we're going to use that hash to give the slider a specific starting position...
		if (settings.crossLinking && location.hash && parseInt(location.hash.slice(1)) <= panelCount) {
			var currentPanel = parseInt(location.hash.slice(1));
			var offset = - (panelWidth*(currentPanel - 1));
			$('.panel-container', slider).css({ marginLeft: offset });

		// If that's not the case, check to see if we're supposed to load a panel other than Panel 1 initially...
		} else if (settings.firstPanelToLoad != 1 && settings.firstPanelToLoad <= panelCount) { 
			var currentPanel = settings.firstPanelToLoad;
			var offset = - (panelWidth*(currentPanel - 1));
			$('.panel-container', slider).css({ marginLeft: offset });
		// Otherwise, we'll just set the current panel to 1...
		} else { 
			var currentPanel = 1;
		};
		
		// Left arrow click
		$("#coda-nav-left-" + sliderCount + " a").click(function(){		
		    // Stop sliding.
		    pause();
		    // Change the pause button into play.		    
		    slider.siblings('.coda-nav').find('#coda-nav-pause-1').removeClass('stop').addClass('start');
		    
			navClicks++;
            //console.log('LEFT: current id: ' + currentId + " = currentPanel: " + currentPanel);               
        	if (currentPanel <= 1) {
        		var offset = 0;
        		currentPanel = 1;
        	} else {
                currentPanelId = currentId + currentPanel;
                //console.log('LEFT: currentPanel: ' + currentPanel + ' currentPanelId: ' + currentPanelId);
                currentPanel -= 1;
                $.each( $(".panel-container").children(), function(i){
                    var substr = currentPanelId.split('');
                    currentTab = substr[0];
                });
        	    alterPanelHeight(currentPanel - 1);
                var offset = - (panelWidth*(currentPanel-1));
        		
        	};
        	
        	// Switch the current tab:
            $.each( $(".panel-container").children(), function(i){
               if (i == (currentPanel - 1)){
                currentPanelId = $(this).attr('id');
                var substr = currentPanelId.split('');
                currentTab = substr[0];
              }
            });
            
            //console.log(slider.siblings('.coda-nav').find('a').removeClass('current').parents('ul').find('#' + currentTab));
            slider.siblings('.coda-nav').find('a').removeClass('current').parents('ul').find('#' + currentTab).addClass('current');
        	// Slide:
        	$('.panel-container', slider).animate({ marginLeft: offset }, settings.slideEaseDuration, settings.slideEaseFunction);			
			
/*            var previousPanel = currentPanel;
			if (currentPanel == 1) {
				offset = - (panelWidth*(panelCount - 1));
				alterPanelHeight(panelCount - 1);
				currentPanel = panelCount;
				slider.siblings('.coda-nav').find('a.current').removeClass('current').parents('ul').find('li:last a').addClass('current');
			} else {
				currentPanel -= 1;
				alterPanelHeight(currentPanel - 1);
				offset = - (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 = currentPanel }; // Change the URL hash (cross-linking)*/
			return false;
		});
			
		// Right arrow click
		$('#coda-nav-right-' + sliderCount + ' a').click(function(){
		    // Stop sliding.
		    pause();
		    // Change the pause button into play.
		    slider.siblings('.coda-nav').find('#coda-nav-pause-1').removeClass('stop').addClass('start');
		    navClicks++;
            currentId = slider.siblings('.coda-nav').find('a.current').attr('id');
            //console.log('RIGHT: current id: ' + currentId + " = currentPanel: " + currentPanel);                
        	if (currentPanel == panelCount) {
        		var offset = 0;
        		currentPanel = 1;
        		alterPanelHeight(0);
        	} else {
        	
        		currentPanelId = currentId + currentPanel;
                //console.log('RIGHT: currentPanel: ' + currentPanel + ' currentPanelId: ' + currentPanelId);
                $.each( $(".panel-container").children(), function(i){
                    var substr = currentPanelId.split('');
                    currentTab = substr[0];
                });
                var offset = - (panelWidth*currentPanel);
        	    currentPanel += 1;
        	};
        	alterPanelHeight(currentPanel - 1);
        	
        	 
        	// Switch the current tab:
            $.each( $(".panel-container").children(), function(i){
               if (i == (currentPanel - 1)){
                currentPanelId = $(this).attr('id');
                var substr = currentPanelId.split('');
                currentTab = substr[0];
              }
            });
        	

            slider.siblings('.coda-nav').find('a').removeClass('current').parents('ul').find('#' + currentTab).addClass('current');
        	// Slide:
        	$('.panel-container', slider).animate({ marginLeft: offset }, settings.slideEaseDuration, settings.slideEaseFunction);
        	
		
		/*	navClicks++;
			if (currentPanel == panelCount) {
				offset = 0;
				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);
				alterPanelHeight(currentPanel);
				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 = currentPanel }; // 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 + '"><span id="coda-nav-pause-1" class="stop"></span><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
			$.each( $("#coda-slider").children(), function(i,l){
			        var targetUrl;
			        var tabAction;
                    currentId = $(this).find(settings.productPanelTitleSelector).attr('id');
                    targetUrl = $(this).find(settings.productPanelTitleSelector).attr('target');
                    //ul.append('<li class="tab' + (i+1) + '" ><a href="#_' + currentId + '" id=' + currentId +'><span>&nbsp;</span><h3>' + $(this).find(settings.productPanelTitleSelector).text() + '</h3></span></a></li>');                    // old script
                    
                    if (targetUrl){tabAction = targetUrl + ".html";} else {tabAction = "#_" + currentId;}
                    ul.append('<li class="tab' + (i+1) + '" ><a href="' + tabAction + '" id=' + currentId +'>' + $(this).find(settings.productPanelTitleSelector).text() + '</span></a></li>');                    // old script
             });
			
			navContainerWidth = slider.width() + slider.siblings('.coda-nav-left').width() + slider.siblings('.coda-nav-right').width();
			//navContainerWidth = "260px";
			ul.parent().css({ width: navContainerWidth });
			switch (settings.dynamicTabsAlign) {
				case "center":
					//ul.css({ width: ($("li", ul).width() + 2) * panelCount });
					ul.css({ width: '920px'});
					break;
				case "right":
					ul.css({ float: 'right' });
					break;
			};
		};
			
        // Pause button click
		$("#coda-nav-pause-" + sliderCount).click(function(){
		  //console.log('click on pause');
		  pauseOrRestart();
		});
		
		// 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() {
		    // Stop sliding.
		    pause();
		    // Change the pause button into play.		    
		    slider.siblings('.coda-nav').find('#coda-nav-pause-1').removeClass('stop').addClass('start');
			
				navClicks++;
				$(this).addClass('current').parents('ul').find('a').not($(this)).removeClass('current');
                  currentProduct = this.id;
                  currentProductPanel = this.id + '1';
                  productPanels = 0;
                 $.each( $(".panel-container").children(), function(i){
                    currentPanelId = this.id;
                    if (currentProductPanel == currentPanelId){
                        currentPanel = i+1;
                    }
                    var substr = currentPanelId.split('');
                    if (currentProduct == substr[0] ){
                      productPanels += 1;
                    } 
                 });
				///offset = - (panelWidth*(z*productPanels));
				//console.log('CLICK: current id: ' + currentId + " = currentPanel: " + currentPanel);               

				offset = - (panelWidth*(currentPanel-1));
				//console.log ("Click");
				alterPanelHeight(z);
				$('.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
			});
		});
		
		// External triggers (anywhere on the page)
		$(settings.externalTriggerSelector).each(function() {
			// Make sure this only affects the targeted slider
			//console.log('clickk');
			if (sliderCount == parseInt($(this).attr("rel").slice(12))) {
				$(this).bind("click", function() {
					navClicks++;
					targetPanel = parseInt($(this).attr("href").slice(1));
					 
					offset = - (panelWidth*(targetPanel - 1));
					alterPanelHeight(targetPanel - 1);
					currentPanel = targetPanel;
					// Switch the current tab:
					slider.siblings('.coda-nav').find('a').removeClass('current').parents('ul').find('li:eq(' + (targetPanel - 1) + ') 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
				});
			};
		});
			
		// Specify which tab is initially set to "current". Depends on if the loaded URL had a hash or not (cross-linking).
		if (settings.crossLinking && location.hash && parseInt(location.hash.slice(1)) <= panelCount) {
			$("#coda-nav-" + sliderCount + " a:eq(" + (location.hash.slice(1) - 1) + ")").addClass("current");
		// If there's no cross-linking, check to see if we're supposed to load a panel other than Panel 1 initially...
		} else if (settings.firstPanelToLoad != 1 && settings.firstPanelToLoad <= panelCount) {
			$("#coda-nav-" + sliderCount + " a:eq(" + (settings.firstPanelToLoad - 1) + ")").addClass("current");
		// Otherwise we must be loading Panel 1, so make the first tab the current one.
		} else {
			$("#coda-nav-" + sliderCount + " a:eq(0)").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() {
				settings.timer = setTimeout(autoSlide,settings.autoSlideInterval);
			});
		};
		
		function alterPanelHeight(x) {
			if (settings.autoHeight) {
				panelHeight = $('.panel:eq(' + x + ')', slider).height()
				slider.animate({ height: panelHeight }, settings.autoHeightEaseDuration, settings.autoHeightEaseFunction);
			};
		};
		
		
		// Pauses the slides
		function pause(){
		 settings.autoSlidePause = true;
		 if (settings.timer){
		      clearTimeout(settings.timer);
		  }
		}
		
		// Pauses or restarts the slider.
		function pauseOrRestart(){
		  settings.autoSlidePause = !settings.autoSlidePause;
		  
		  if(settings.autoSlidePause){
		      slider.siblings('.coda-nav').find('#coda-nav-pause-1').removeClass('stop').addClass('start');
		  
		  } else slider.siblings('.coda-nav').find('#coda-nav-pause-1').removeClass('start').addClass('stop');
		  
		  
		  if (settings.timer){
		      clearTimeout(settings.timer);
		  }
		  settings.timer = setTimeout(autoSlide, 100);	  
		}
		
		function autoSlide() {
		    if (settings.autoSlidePause) {
		      // Wait for autoSlidePause to be set on false.
		      // Schedule another autoSlide.
	         settings.timer = setTimeout(autoSlide, settings.autoSlideInterval);
		    } else if (navClicks == 0 || !settings.autoSlideStopWhenClicked) {
                    currentId = slider.siblings('.coda-nav').find('a.current').attr('id');
                    //console.log('current id: ' + currentId + " = currentPanel: " + currentPanel);                
    				if (currentPanel == panelCount) {
    					var offset = 0;
    					currentPanel = 1;
    				} else {
    					currentId = slider.siblings('.coda-nav').find('a.current').attr('id');
                        currentPanelId = currentId + currentPanel;
                        //console.log('SLIDE TO currentPanel: ' + currentPanel + ' currentPanelId: ' + currentPanelId);
                        $.each( $(".panel-container").children(), function(i){
                            var substr = currentPanelId.split('');
                            currentTab = substr[0];
                        });
                        var offset = - (panelWidth*currentPanel);
    					currentPanel += 1;
    				};
    				
    				alterPanelHeight(currentPanel - 1);
    				
    				// Switch the current tab:
                    $.each( $(".panel-container").children(), function(i){
                       if (i == (currentPanel - 1)){
                        currentPanelId = $(this).attr('id');
                        var substr = currentPanelId.split('');
                        currentTab = substr[0];
                      }
                    });
        
        //			slider.siblings('.coda-nav').find('a').removeClass('current').parents('ul').find('li:eq(' + (currentPanel - 1) + ') a').addClass('current');
                    slider.siblings('.coda-nav').find('a').removeClass('current').parents('ul').find('#' + currentTab).addClass('current');
    				// Slide:
    				$('.panel-container', slider).animate({ marginLeft: offset }, settings.slideEaseDuration, settings.slideEaseFunction);
    				settings.timer = setTimeout(autoSlide,settings.autoSlideInterval);
  			};
		};
		
		// Kill the preloader
		$('.panel', slider).show().end().find("p.loading").remove();
		slider.removeClass("preload");
		sliderCount++;
	});
};


