/*
	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").children('.panel').hide().end().prepend('<p class="loading">Loading...<br /><img src="images/ajax-loader.gif" alt="loading..." /></p>');
});

var sliderCount = 1;
var sliderClick = false;

$.fn.codaSlider = function(settings) {

	settings = $.extend({
		autoHeight: true,
		autoHeightEaseDuration: 100,
		autoHeightEaseFunction: "easeInOutExpo",
		autoSlide: false,
		autoSlideInterval: 7000,
		autoSlideStopWhenClicked: true,
		crossLinking: true,
		dynamicArrows: false,
		dynamicArrowLeftText: "&larr;",
		dynamicArrowRightText: "&rarr;",
		dynamicTabs: false,
		dynamicTabsAlign: "center",
		dynamicTabsPosition: "center",
		externalTriggerSelector: "a.xtrig",
		firstPanelToLoad: 1,
		panelTitleSelector: "h2.title",
		slideEaseDuration: 700,
		slideEaseFunction: "easeInOutExpo"
	}, settings);

	return this.each(function(){
		
		// Uncomment the line below to test your preloaderer
		// alert("Testing preloader");
		
		var slider = $(this);

		// Hotkeys
		$(document).bind('keydown', 'left', function(e) { keyboardDir('left'); });
		$(document).bind('keydown', 'right', function(e) { keyboardDir('right'); });
		$(document).bind('keydown', 'a', handleKeyboard); //About
		$(document).bind('keydown', 'v', handleKeyboard); //DeviantArt
		$(document).bind('keydown', 'f', handleKeyboard); //Flickr
		$(document).bind('keydown', 'e', handleKeyboard); //EyesOnWalls
		$(document).bind('keydown', 'l', handleKeyboard); //Legend/Credits
		$(document).bind('keydown', 'x', handleKeyboard); //Exit

		$(document).bind('keydown', 'd', handleKeyboard); //Download
		$(document).bind('keydown', 'p', handleKeyboard); //Purchase
		$(document).bind('keydown', '0', handleKeyboard); //2010
		$(document).bind('keydown', '1', handleKeyboard); //2011
		$(document).bind('keydown', '5', handleKeyboard); //2005
		$(document).bind('keydown', '6', handleKeyboard); //2006
		$(document).bind('keydown', '7', handleKeyboard); //2007
		$(document).bind('keydown', '8', handleKeyboard); //2008
		$(document).bind('keydown', '9', handleKeyboard); //2009

		// scrollTop locations for the years
		var years = [];
		var isAnimating = false;
		var bodyEle = ($.browser.safari) ? $('body') : $('html,body');
		var aboutPanel = $('.panel').index($('#about')) + 1;
		var panelWidth = slider.find(".panel").width() + parseInt(slider.find(".panel").css('marginRight'));
		var panelCount = slider.find(".panel").size();
		var panelContainerWidth = panelWidth*panelCount;
		var navClicks = 0; // Used if autoSlideStopWhenClicked = true
		var halfHeight = Math.floor($(window).height() / 2);
		var yLoc = halfHeight + 1;
		
		// 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 && ($(location.hash).length && !$(location.hash).hasClass('year'))) {
			if (location.hash == '#about' && typeof $().ytchromeless == 'function') $('a#youtube-video').ytchromeless();
			var currentPanel = $('.panel').index($(location.hash)) + 1;
			if (currentPanel < 1) currentPanel = 1;
			var offset = - (panelWidth*(currentPanel - 1));
			$('.panel-container', slider).css({ marginLeft: offset });
			bodyEle.scrollTop(0);
			$('#back-button:hidden').fadeIn();
			$(window).trigger('scroll.lazyload'); //Hax for LazyLoad
		// 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 });
			$(window).trigger('scroll.lazyload'); //Hax for LazyLoad
		// Otherwise, we'll just set the current panel to 1...
		} else {
			var currentPanel = 1;
		};
		topButton();
		backButton();
		setupLegend();

		$('#top-button').animate({opacity: 0}, 100, 'linear', function() {
			$('#top-button').css({ opacity: 1 }).hide();
			$(window).on('scroll.imageslider', topButton);
		});

		$(window).bind( 'hashchange', function(){
			if (!sliderClick) {
				var hash = location.hash;
				if (hash == '') {
					animateSlide('#', false);
				} else if ($(hash).hasClass('year')) {
					animateSlide('#', hash.replace(/#/, ''));
				} else {
					animateSlide(hash, false);
				}
			}
			sliderClick = false;
		})

		// External triggers (anywhere on the page)
		$(settings.externalTriggerSelector).each(function() {
			var href = $(this).attr('href');
			if (href == '#prev' || href == '#next') {
				$(this).click(function() {
					var direction = (href == '#prev') ? 'left' : 'right';
					keyboardDir(direction);
					return false;
				});
			} else if (href == '#' || $(href).length) {
				$(this).click(function() {
					sliderClick = true;
					hash = $(this).attr('href');
					animateSlide(hash, $(this).attr('rel'));
					return false; // Actual hash setting fucks it up?
				});
			}
		});
		$('#prev-button').bind('click', function() { keyboardDir('left'); });
		$('#next-button').bind('click', function() { keyboardDir('right'); });
		$('.panel-wrapper').each(function() {
			var aWidth = $(this).children('a:first').width();
			if (aWidth) $(this).width(aWidth);
		});

		function topButton() {
			if (currentPanel == 1 && !isAnimating) {
				yLoc = bodyEle.scrollTop();
				if (yLoc < halfHeight) {
					$('#top-button:visible').fadeOut();
				} else {
					$('#top-button:hidden').fadeIn();
				}
			}
		}

		function backButton() {
			
			if (currentPanel != 1 && !isAnimating) {
				$('#back-button:hidden').fadeIn();
				var currentYear = $('.panel:eq(' + (currentPanel - 1) + ') a[rel]').attr('rel');
				if (!currentYear) currentYear = '';
				$('#back-button').attr('href', '#' + currentYear);
				if (currentYear != '') {
					$('#back-button').attr('rel', currentYear);
				} else {
					$('#back-button').removeAttr('rel');
				}
			} else {
				$('#back-button:visible').fadeOut();
			}
		}

		function calcYearPos() {
			$('.year').each(function() {
				years[parseInt(this.id)] = $(this).position().top;
			});
		}

		function handleKeyboard(e) {
			var l, pan, link, year;
			l = e.data;
			pan = '.panel:eq(' + (currentPanel - 1) + ') ';
			if (l == 'd') { //Download
				link = $(pan + 'h3 a');
				if (!link.length) return;
				location.href = link.attr('href');
			} else if (l == 'p') { //Purchase
				link = $(pan + 'h2 a');
				if (!link.length) return;
				location.href = link.attr('href');
			} else if (l == 'a') { //About\
				animateSlide('#about', false);
			} else if (l == 'v') { //DeviantArt
				location.href = $('#deviantart').attr('href');
			} else if (l == 'f') { //Flickr
				location.href = $('#flickr').attr('href');
			} else if (l == 'e') { //EyesOnWalls
				location.href = $('#eow').attr('href');
			} else if (l == 'l') { //Legend
				showLegend();
			} else if (l == 'x') { //Exit
				var top = $('#top-button');
				var back = $('#back-button');
				if (back.is(':visible')) {
					animateSlide(back.attr('href'), back.attr('rel'));
				} else if (top.is(':visible')) {
					animateSlide('#', '');
				}
			} else if (l.match(/\d/)) { //Year
				year = (parseInt(l) < 5) ? '201' + l : '200' + l;
				animateSlide('#', year);
			}
		}

		function keyboardDir(dir) {
			var targetPanel, panelMove, yPos, currentYear;
			if (years.length == 0) calcYearPos();
			//if (isAnimating) return;

			if (currentPanel == 1 && dir == 'left' || currentPanel == $('.panel').length && dir =='right') return;

			if (currentPanel == 1 && dir == 'right') {
				yPos = bodyEle.scrollTop() + halfHeight;
				for (year in years) {
					if (years[year] <= yPos) currentYear = year;
				}
				//targetPanel = '#' + $('a[rel=' + currentYear + ']:first').parents('.panel:first').attr('id');
				targetPanel = '#' + currentYear + 'intro';
			} else {
				if (dir == 'left') {
					targetPanel = currentPanel - 1;
				} else if (dir == 'right') {
					targetPanel = currentPanel + 1;
				}
			}
			animateSlide(targetPanel, false);
		}

		function animateSlide(hash, rel) {
			var targetPanel;
			$('.panel-container', slider).stop();
			$('#legend:visible').fadeOut();

			if (!isNaN(hash)) {
				targetPanel = hash;
				hash = (hash == 1) ? $('.panel .year:first').attr('id') : $('.panel:eq(' + (hash - 1) + ')').attr('id');
			} else {
				targetPanel = (hash == '#' || hash == '') ? 1 : $('.panel').index($(hash)) + 1;
			}
			if (targetPanel < 1) targetPanel = 1;
			alterPanelHeight(targetPanel);
			currentPanel = targetPanel;
			offset = (hash == '#' || hash == '') ? 0 : - (panelWidth*(currentPanel - 1));

			//Load YTChromeless if About slide
			if (hash == '#about' && typeof $().ytchromeless == 'function') {
				$('a#youtube-video').ytchromeless();
			}

			// Slide
			isAnimating = true;
			yLoc = (rel) ? $('#' + rel).position().top : 0;
			if (currentPanel > 1 || yLoc < halfHeight) $('#top-button:visible').fadeOut();
			bodyEle.animate({ scrollTop: yLoc }, settings.slideEaseDuration, settings.slideEaseFunction);
			$('.panel-container', slider).animate({ marginLeft: offset }, settings.slideEaseDuration, settings.slideEaseFunction, function() {
				location.hash = (hash == '#') ? rel : hash;
				$(window).trigger('scroll.lazyload'); //Hax for LazyLoad
				isAnimating = false;
				topButton();
				backButton();
				//yLoc = 1;
			});
		}

		function setupLegend() {
			$('#legend .hotkey').each(function() {
				$(this).mouseover(function() {
					var key = $(this).text().toLowerCase();
					if (key.match(/^(e|f|v)$/)) return;

					$('#legend .active').each(function() { $(this).removeClass('active'); });
					$(this).addClass('active');
					if ($(this).parent('.arrow').length) {
						$('#hotkey-list .hotkey-arrows').addClass('active');
					} else if ($(this).parent('.number').length) {
						$('#hotkey-list .hotkey-num').addClass('active');
					} else {
						$('#hotkey-list .hotkey-' + key).addClass('active');
					}
				});
				$(this).click(function() {
					var key = $(this).text().replace(/.(\d)/, '$1').toLowerCase();
					var e = {};
					e.data = key;
					handleKeyboard(e);
				});
			});
			$('#legend, #close-legend').click(function() {
				$('#legend').fadeOut();
				if ($(this).attr('id') == 'close-legend') return false;
			});
			$('#keyboard').bind('click', function() {
				return false;
			}, false);

			$('#show-legend').click(function() {
				showLegend();
				return false;
			});
		}

		function showLegend() {
			var isHidden = $('#legend').is(':hidden');
			$('#legend')[ isHidden ? 'fadeIn' : 'fadeOut' ]();
		}
		// Set the height of the first panel
		if (settings.autoHeight) {
			panelHeight = $('.panel:eq(' + (currentPanel - 1) + ')', slider).height() + 15;
			slider.css({ height: panelHeight });
		};
		
		function alterPanelHeight(x) {
			if (settings.autoHeight && x != '') {
				panelHeight = $('.panel:eq(' + (x - 1) + ')', slider).height() + 15;
				slider.animate({ height: panelHeight }, settings.autoHeightEaseDuration, settings.autoHeightEaseFunction);
			};
		};
		
		// Kill the preloader
		$('.panel', slider).show().end().find("p.loading").remove();
		slider.removeClass("preload");
		
		sliderCount++;
		
	});
};
