/*
* jQuery Orbit Plugin 1.2.3
* www.ZURB.com/playground
* Copyright 2010, ZURB
* Free to use under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*/


(function ($) {

	$.fn.orbit = function (options) {

		//Defaults to extend options
		var defaults = {
			animationSpeed: 600, 			// how fast animtions are
			width: 1000,
			height: 400,
			timer: true, 						// true or false to have the timer
			advanceSpeed: 4000, 				// if timer is enabled, time between transitions 
			pauseOnHover: true, 				// if you hover pauses the slider
			directionalNav: true, 				// manual advancing directional navs
			captions: true, 					// do you want captions?
			captionAnimationSpeed: 600, 		// if so how quickly should they animate in
			bullets: false, 					// true or false to activate the bullet navigation
			bulletThumbs: false, 				// thumbnails for the bullets
			bulletThumbLocation: '', 			// location from this file where thumbs will be
			afterSlideChange: function () { } 	// empty function
		};

		//Extend those options
		var options = $.extend(defaults, options);

		return this.each(function () {

			// ==============
			// ! SETUP   
			// ==============

			//Global Variables
			var activeSlide = 0,
				numberSlides = 0,
				orbitWidth,
				orbitHeight,
				locked;

			//Initialize

			//Load images from ul list
			var orbit = $(this).addClass('orbit'),
			orbitWrapper = orbit.wrap('<div class="orbit-wrapper"/>').parent();
			var images = $("#imageLibrary").children('li');
			var slides = orbit.children('img, a, div');

      images.each(function (index) {
        slides.eq(index+1).append('<img src="' + $(this).html() + '" class="orbit-image-holder" />');
       });

			orbit.add(orbitWidth).width('1px').height('1px');
			_slideWidth = options.width;
			_slideHeight = options.height;
			orbit.width('100%');
			orbit.add(orbitWrapper).css({ "text-align": "center" });
			orbitWidth = orbit.width();
			orbit.add(orbitWrapper).height(options.height);
			orbitHeight = orbit.height();
			numberSlides = slides.length;

			//Animation locking functions
			function unlock() {
				locked = false;
			}
			function lock() {
				locked = true;
			}

			//If there is only a single slide remove nav, timer and bullets
			if (slides.length == 1) {
				options.directionalNav = false;
				options.timer = false;
				options.bullets = false;
			}

			// The slides should start out transparent
			slides.each(function () {
				$(this).css({ "opacity": 0 })
			});

			//Set initial front photo z-index and fades it in
			slides.eq(activeSlide)
				.css({ "z-index": 3, "opacity": 1 })
				.fadeIn(function () {
					//brings in all other slides IF css declares a display: none
					slides.css({ "display": "inline" })
				});

			// ==============
			// ! TIMER   
			// ==============

			//Timer Execution
			function startClock() {
				if (!options.timer || options.timer == 'false') {
					return false;
				}
				if (timerRunning) {
					return false;
				}
				timerRunning = true;
				clock = setInterval(function (e) {
					shift("next");
				}, options.advanceSpeed);
			}
			function stopClock() {
				if (!options.timer || options.timer == 'false') {
					return false;
				}
				else {
					timerRunning = false;
					clearInterval(clock);
					pause.addClass('active');
				}
			}

			//Timer Setup
			if (options.timer) {
				var timerHTML = '<div class="timer"><span class="mask"><span class="rotator"></span></span><span class="pause"></span></div>'
				orbitWrapper.append(timerHTML);
				var timer = orbitWrapper.children('div.timer'),
					timerRunning;
				if (timer.length != 0) {
					var rotator = $('div.timer span.rotator'),
						mask = $('div.timer span.mask'),
						pause = $('div.timer span.pause'),
						degrees = 0,
						clock;
					startClock();
				}
			}

			//Pause Timer on hover
       if (options.pauseOnHover) {
               $('.orbit-image-holder').mouseenter(function () {
                       stopClock();
               });
               $('.orbit-image-holder').mouseleave(function () {
                       startClock();
               });              
              $('.orbit-caption-display').live('mouseenter', function() {
                       stopClock();
               });
               $('.orbit-caption-display').live('mouseleave', function() {
                       startClock();
               });  
       
       }

			// ==============
			// ! CAPTIONS   
			// ==============

			//Caption Setup
       if (options.captions) {
               var captionHTML = '<div class="orbit-caption-display"><div class="orbit-caption-holder"><div class="orbit-caption-text"></div></div></div>';
               orbitWrapper.append(captionHTML);
               var caption = orbitWrapper.children('.orbit-caption-display').children('.orbit-caption-holder').children('.orbit-caption-text');
               setCaption();
       }

			//Caption Execution
			function setCaption() {
				if (!options.captions || options.captions == "false") {
					return false;
				} else {
					var _captionLocation = slides.eq(activeSlide).data('caption'); //get ID from rel tag on image
					_captionHTML = $(_captionLocation).html(); //get HTML from the matching HTML entity					

					caption.fadeOut(options.captionAnimationSpeed, function () {
						caption.attr('id', _captionLocation) // Add ID caption
							.html(_captionHTML); // Change HTML in Caption 
					});
					caption.fadeIn(options.captionAnimationSpeed);
				}
			}

			// ==================
			// ! DIRECTIONAL NAV   
			// ==================

			if (options.directionalNav) {
				if (options.directionalNav == "false") { return false; }
        var navButtons = $('<div class="orbit-bns"><a class="prevButton">Prev</a><a class="nextButton">Next</a></div>');
        orbitWrapper.append(navButtons);
				var leftBtn = $(".prevButton"),
						rightBtn = $(".nextButton");
				leftBtn.click(function () {
					stopClock();
					shift("prev");
				});
				rightBtn.click(function () {
					stopClock();
					shift("next");
				});
			}

			// ==================
			// ! BULLET NAV   
			// ==================

			//Bullet Nav Setup
			if (options.bullets) {
				var bulletHTML = '<ul class="orbit-bullets"></ul>';
				orbitWrapper.append(bulletHTML);
				var bullets = orbitWrapper.children('ul.orbit-bullets');

				for (i = 0; i < numberSlides; i++) {
					var liMarkup = $('<li class="bullet">' + (i + 1) + '</li>');
					if (options.bulletThumbs) {
						var thumbName = slides.eq(i).data('thumb');
						if (thumbName) {
							var liMarkup = $('<li class="has-thumb">' + i + '</li>')
							liMarkup.css({ "background": "url(" + options.bulletThumbLocation + thumbName + ") no-repeat" });
						}
					}
					bullets.append(liMarkup);
					liMarkup.data('index', i);
					liMarkup.click(function () {
						stopClock();
						shift($(this).data('index'));
					});
				}
				setActiveBullet();
			}

			//Bullet Nav Execution
			function setActiveBullet() {
				if (!options.bullets) { return false; } else {
					bullets.children('li').removeClass('active').eq(activeSlide).addClass('active');
				}
			}

			// ====================
			// ! SHIFT ANIMATIONS   
			// ====================

			//Animating the shift!
			function shift(direction) {
				//remember previous activeSlide
				var prevActiveSlide = activeSlide,
					slideDirection = direction;
				//exit function if bullet clicked is same as the current image
				if (prevActiveSlide == slideDirection) { return false; }
				//reset Z & Unlock
				function resetAndUnlock() {
					slides
						.eq(prevActiveSlide)
						.css({ "z-index": 1 });
					unlock();
					options.afterSlideChange.call(this);
				}
				if (slides.length == "1") { return false; }
				if (!locked) {
					lock();
					//deduce the proper activeImage
					if (direction == "next") {
						activeSlide++
						if (activeSlide == numberSlides) {
							activeSlide = 0;
						}
					} else if (direction == "prev") {
						activeSlide--
						if (activeSlide < 0) {
							activeSlide = numberSlides - 1;
						}
					} else {
						activeSlide = direction;
						if (prevActiveSlide < activeSlide) {
							slideDirection = "next";
						} else if (prevActiveSlide > activeSlide) {
							slideDirection = "prev"
						}
					}
					//set to correct bullet
					setActiveBullet();

					//set previous slide z-index to one below what new activeSlide will be
					slides
						.eq(prevActiveSlide)
						.css({ "z-index": 2 });

					if (slideDirection == "next") {
						slides
							.eq(prevActiveSlide)
							.stop()
							//.css({ "z-index": 3 })
							//.animate({ "left": -orbitWidth }, { duration: options.animationSpeed, queue: false, easing: 'easeInCubic' })
							.animate({ "opacity": 0 }, { duration: options.animationSpeed, queue: false, easing: 'easeOutQuad' })
							.delay(options.animationSpeed / 2)
							.queue(function () {
								slides
									.eq(activeSlide)
									//.css({ "left": orbitWidth, "opacity": 0, "z-index": 3 })
									.stop()
									//.animate({ "left": 0 }, { duration: options.animationSpeed, queue: false, easing: 'easeOutCubic' })
									.animate({ "opacity": 1 }, { duration: options.animationSpeed, queue: false, easing: 'easeInQuad', complete: resetAndUnlock });
							});
					}
					if (slideDirection == "prev") {
						slides
							.eq(prevActiveSlide)
							.stop()
							//.css({ "z-index": 3 })
							//.animate({ "left": orbitWidth }, { duration: options.animationSpeed, queue: false, easing: 'easeInCubic' })
							.animate({ "opacity": 0 }, { duration: options.animationSpeed, queue: false, easing: 'easeOutQuad' })
							.delay(options.animationSpeed / 2)
							.queue(function () {
								slides
									.eq(activeSlide)
									//.css({ "left": -orbitWidth, "opacity": 0, "z-index": 3 })
									.stop()
									//.animate({ "left": 0 }, { duration: options.animationSpeed, queue: false, easing: 'easeOutCubic' })
									.animate({ "opacity": 1 }, { duration: options.animationSpeed, queue: false, easing: 'easeInQuad', complete: resetAndUnlock });
							});
					}

					setCaption();
				} //lock
			} //orbit function
		}); //each call
	} //orbit plugin call
})(jQuery);
