// On page load
$(function() {

	// Avoid having the plugin colliding with existing
	(function($) {
		
		var activeSlideIndex = 0;
		var nrOfSlides = 0;
		var topSlideZIndex = 0;
		var paused = false;
		var slideHideTexts = !($.browser.msie && $.browser.version < 7);
		var changing = false;
		var slides, activeSlide, slideToGoTo, slideIndexToGoTo, originalTextMarginLeft, hideTextTargetMarginLeft, changeTimeout, textTimeout;
		
		var settings = {
			'displayTime': 5000,
			'fadeDuration' : 1000,
			'textHideDuration': 800, // Initial duration for hiding the first text
			'textHideDurationChange': 200
		};
		
		var methods = {
			
			init: function(options) {
				
				// If options exist, lets merge them
				// with our default settings
				if (options) { 
					$.extend(settings, options);
				}
				
				methods.bindNavigation();
				
				// Store all slides
				slides = $('.slide', this);
				
				// Extract the first slide
				var firstSlide = slides.eq(0); 
				
				originalTextMarginLeft = 0; //firstSlide.find('.textWrapper').eq(0).css('left');
				hideTextTargetMarginLeft = '-' + (firstSlide.width() + 10);
				
				nrOfSlides = slides.length;
				
				// Hide all slides except the first one
				slides.slice(1).hide();
				
				if (slideHideTexts) {
					
					slides.slice(1)
						.find('.textWrapper')
							.css('left', hideTextTargetMarginLeft + 'px');
					
				};

				// Move the first slide up a bit in the z-order to prevent collisions later on
				// and store the max z-index
				topSlideZIndex = slides.eq(0).css('z-index', slides.eq(0).css('z-index')+100).css('z-index');
				
				$('a', slides).bind('mouseover', function() {
					
					paused = true;
					
				});
				
				$('a', slides).bind('mouseout', function() {
					
					paused = false;
					
				});
				
				methods.setChangeTimeout();

			}, // Init
			
			bindNavigation: function() {
				
				// Prev
				$('.navPrev').bind('click', function(event) {
					
					event.preventDefault();
					
					if (!changing) {
					
						methods.clearTimeouts();
					
						methods.change(false);
					
					}
					
				});
				
				// Next
				$('.navNext').bind('click', function(event) {
					
					event.preventDefault();
					
					if(!changing) { 
					
						methods.clearTimeouts();

						methods.change();
					
					}
					
				});
				
			}, // bindNavigation
			
			setChangeTimeout: function(timeoutTime) {
				
				changing = false;
				
				timeoutTime = typeof(timeoutTime) != 'undefined' ? timeoutTime : settings.displayTime;
				
				changeTimeout = window.setTimeout(function(){  methods.change(); }, timeoutTime);
				
			}, // setChangeTimeout
			
			clearTimeouts: function() {
			
				clearTimeout(changeTimeout);
				clearTimeout(textTimeout);
				
			}, // clearTimeouts
						
			change: function(goForward) {
				
				// Make sure we are not paused
				if(!paused) {
					
					changing = true;
				
					// Lets go to the next slide
					goForward = typeof(goForward) != 'undefined' ? goForward : true;
					
					if (goForward) {
						
						slideIndexToGoTo = activeSlideIndex + 1;
						
					} else {
						
						slideIndexToGoTo = activeSlideIndex - 1;
						
					}

					activeSlide = slides.eq(activeSlideIndex);
					
					// If we have gone past the last slide
					if(slideIndexToGoTo >= nrOfSlides) {
						
						// Oh, let's go back to the start / Chris Martin of Coldplay
						slideIndexToGoTo = 0;
						
					} else if(slideIndexToGoTo < 0) {
						
						slideIndexToGoTo = (nrOfSlides-1);
						
					}
					
					slideToGoTo = slides.eq(slideIndexToGoTo);
					
					// Move the slide that we want to go to to just below the current one and show it 
					slides.eq(slideIndexToGoTo).css('z-index', topSlideZIndex-1).show();
					
					methods.hideTexts(slideIndexToGoTo);
				
				} else { // Slider is paused
					
					// Try again in a showrt while
					methods.setChangeTimeout((settings.displayTime/3));
					
				}
				
			}, // change
			
			hideTexts: function(slideIndexToGoTo) {
				
				var textHideDuration = settings.textHideDuration; 
				
				var activeTextWrappers = $('.textWrapper', activeSlide);
				
				// Slide the text away
				activeTextWrappers.each(function() {
					
					methods.hideText($(this), textHideDuration);
					
					textHideDuration += settings.textHideDurationChange;
					
				});
				
				// Wait until all texts has been changed
				textTimeout = window.setTimeout(function() { methods.hideImage(); }, settings.textHideDuration);
				
			}, // hideTexts
			
			hideText: function(elm, textHideDuration) {
				
				if(slideHideTexts) {
				
					elm.stop(false, false).animate({'left': hideTextTargetMarginLeft}, textHideDuration);
				
				}
				
			}, // hideText
			
			hideImage: function() {
				
				var imgElm = $('img', activeSlide);
				
				// Fade out the active slide
				imgElm.stop(false, false).fadeOut(settings.fadeDuration, function() {
					
					// Move the faded slide to the bottom
					activeSlide.css('z-index', 0);
					
					// Move now visible slide to top
					slideToGoTo.css('z-index', topSlideZIndex);
					
					// Make sure that it is hidden ok in case the animation has not completed
					imgElm.fadeTo(0, 1);
					
					// The now visible slide is now the active
					activeSlideIndex = slideIndexToGoTo;
				
					methods.showTexts(slides.eq(activeSlideIndex), function() { methods.setChangeTimeout(); });
					
				});
				
			}, // hideImage
			
			showTexts: function(elm, callbackFunction) {
										
				var textShowDuration = settings.textHideDuration; 
				
				var activeTextWrappers = $('.textWrapper', elm);
				
				activeTextWrappers.each(function() {
					
					methods.showText($(this), textShowDuration);
					
					textShowDuration += settings.textHideDurationChange;
					
				});
				
				if(typeof callbackFunction === 'function') {
					
					textTimeout = window.setTimeout(function() { callbackFunction.call(); }, settings.textHideDuration);
					
				}
				
			}, // showTexts
			
			showText: function(elm, textShowDuration) {
				
				if(slideHideTexts) {
				
					elm.stop(false, false).animate({'left': originalTextMarginLeft}, textShowDuration);
				
				}
				
			} // showText
				
		};
		
		 $.fn.loSlider = function( method ) {
		    
			// Method calling logic
			if ( methods[method] ) {
				return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
			} else if ( typeof method === 'object' || ! method ) {
				return methods.init.apply( this, arguments );
			} else {
				$.error( 'Method ' +  method + ' does not exist on jQuery.liSlider' );
			}    
		  
		};
		
	})(jQuery);
	
	$('.loSlideshow').loSlider({
			'displayTime': 4000,
			'fadeDuration': 500
			
	});

});
