/*
	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.
	Massively overhauled & extended by Rob Ford for use on thebackcountry.co.uk
*/

$(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...<br /><img src="/images/ajax-loader.gif" alt="loading..." /></p>');
});

var sliderCount = 1;

$.fn.codaSlider = function(settings) {
	settings = $.extend({
		autoHeight: true,
		autoHeightEaseDuration: 1000,
		autoHeightEaseFunction: "easeInOutExpo",
		crossLinking: true,
		externalTriggerSelector: "a.xtrig",
		firstPanelToLoad: 'home-panel',
		panelTitleSelector: "h2.title",
		slideEaseDuration: 1000,
		slideEaseFunction: "easeInOutExpo"
	}, settings);

	return this.each(function() {
		var slider = $(this);
		var panelWidth = slider.find(".panel").width();
		var panelCount = slider.find(".panel").size();
		var panelContainerWidth = panelWidth * panelCount;
		var navClicks = 0;
		// 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) {
			var currentPanel = $('.panel-container').find('.panel').index($(location.hash + '-panel', slider));
			var offset = - (panelWidth * currentPanel);
			$('.panel-container', slider).css({marginLeft: offset});
			// fix the nav indicators
			$('#nav li').removeClass('active').eq(currentPanel).addClass('active');
			$('#smallnav a').each(function() {
                $(this).find('img').attr('src', '/images/bullet-off.jpg');
                if ($(this).attr('href') == location.hash) {
                    $(this).find('img').attr('src', '/images/bullet-on.jpg');
                }
            });
		// 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 != 'home-panel') {
			var currentPanel = $('.panel-container').find('.panel').index($('#' + settings.firstPanelToLoad));
			var offset = - (panelWidth * currentPanel);
			$('.panel-container', slider).css({marginLeft: offset});
		// Otherwise, we'll just set the current panel to 1...
		} else {
			var currentPanel = 1;
		};

		// Main nav clicks
		$('#coda-nav-' + sliderCount + ' a').each(function(z) {
			// What happens when a nav link is clicked
			$(this).bind("click", function() {
				navClicks++;
				$(this).addClass('current').parents('ul').find('a').not($(this)).removeClass('current');
				var href = $(this).attr('href'); // already contains a #
				currentPanel = $('.panel-container').find('.panel').index($(href + '-panel'));
				alterPanelHeight(currentPanel);
				offset = - (panelWidth * currentPanel);
				$('.panel-container', slider).animate({ marginLeft: offset }, settings.slideEaseDuration, settings.slideEaseFunction);
                // toggle the active indicator on the li
                $(this).parent().addClass('active').parents('ul').find('li').not($(this).parent()).removeClass('active');
                // toggle the active link image in the smallnav too
                $('#smallnav a').each(function() {
                    $(this).find('img').attr('src', '/images/bullet-off.jpg');
                    if ($(this).attr('href') == href) {
                        $(this).find('img').attr('src', '/images/bullet-on.jpg');
                    }
                });
				if (!settings.crossLinking) { // Don't change the URL hash unless cross-linking is specified
					return false;
				};
			});
		});

		// 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() {
					navClicks++;
					var href = $(this).attr('href'); // already contains a #
					targetPanel = parseInt($('.panel-container').find('.panel').index($(href + '-panel')));
					offset = - (panelWidth * (targetPanel));
					alterPanelHeight(targetPanel);
					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);
                    // toggle the active indicator on the li
                    $('#nav li').removeClass('active').find('a[href=' + href + ']').parent().addClass('active');
                    // toggle the active link image in the smallnav too
                    $('#smallnav a').each(function() {
                        $(this).find('img').attr('src', '/images/bullet-off.jpg');
                        if ($(this).attr('href') == href) {
                            $(this).find('img').attr('src', '/images/bullet-on.jpg');
                        }
                    });
					if (!settings.crossLinking) { // Don't change the URL hash unless cross-linking is specified
						return false;
					};
				});
			};
		});

		// 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) {
			$("#coda-nav-" + sliderCount + " a" + location.hash + "-panel").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 != 'home-panel') {
			$("#coda-nav-" + sliderCount + " a#" + settings.firstPanelToLoad).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 = $('div.panel:eq(' + currentPanel + ')' , slider).height();
			slider.css({ height: panelHeight });
		};

		function alterPanelHeight(currentPanel) {
			if (settings.autoHeight) {
				panelHeight = $('div.panel:eq(' + currentPanel + ')', slider).height();
				slider.animate({height: panelHeight}, settings.autoHeightEaseDuration, settings.autoHeightEaseFunction);
			};
		};
		// Kill the preloader
		$('.panel', slider).show().end().find("p.loading").remove();
		slider.removeClass("preload");
		sliderCount++;
	});
};
