/*
 * jQuery Rotator Plugin
 * Modified version (per original MIT license) of Orbit Plugin
 * Original Copyright 2010, ZURB - Free to use under the MIT license - http://www.opensource.org/licenses/mit-license.php
*/

(function($) {

    $.fn.rotator = function(opts) {

        //Defaults to extend opts
        var defaults = {  
            animation: 'horizontal-push', 	// fade, horizontal-push
            animationSpeed: 1000, 			// how fast animtions are
            timer: true, 					// true or false to have the timer
            advanceSpeed: 10000, 			// if timer is enabled, time between transitions 
            pauseOnHover: true, 			// if you hover pauses the slider
            startClockOnMouseOut: true, 	// if clock should start on MouseOut
            startClockOnMouseOutAfter: 500, // how long after MouseOut should the timer start again
            directionalNav: false, 			// manual advancing directional navs
            bulletNav: false,				// true or false to activate the bullet navigation
            textNav: false,					// true or false to activate the text navigation
            textNavArray: [],				// define nav text
            beforeChange: function(){},		// empty function 
            afterChange: function(){} 		// empty function 
     	};  
        
        //Extend those opts
        var opts = $.extend(defaults, opts); 
	
        return this.each(function() {

		//= SETUP ============================
            //Global Variables
            var activeSlide = 0,
            	numberSlides = 0,
            	rotatorWidth,
            	rotatorHeight,
            	locked;
            
            //Initialize
            var rotator = $(this);
            rotator.add(rotatorWidth).width('1px').height('1px');
	    	            
            //Collect all slides and set slider size of largest image
            var slides = rotator.children('div.slide').css('position','absolute');
            slides.each(function() {
                var _slide = $(this),
                	_slideWidth = _slide.width(),
                	_slideHeight = _slide.height();
                if(_slideWidth > rotator.width()) {
	                rotator.add().width(_slideWidth);
	                rotatorWidth = rotator.width();	       			
	            }
	            if(_slideHeight > rotator.height()) {
	                rotator.add().height(_slideHeight);
	                rotatorHeight = rotator.height();
				}
                numberSlides++;
            });
            
            //Animation locking functions
            function unlock() {
                locked = false;
            }
            function lock() { 
                locked = true;
            }
            
            //If there is only a single slide remove nav, timer, bulletNav and textNav
            if(slides.length == 1) {
            	opts.directionalNav = false;
            	opts.timer = false;
            	opts.bulletNav = false;
            	opts.textNav = false;
            }
            
            //Set initial front photo z-index and fade it in
            slides.eq(activeSlide)
            	.css({'z-index' : 3})
            	.fadeIn(function() {
            		//brings in all other slides IF css declares a display: none
            		slides.css({'display':'block'})
            	});
            
		//= TIMER ============================
            //Timer Execution
            function startClock() {
            	if(!opts.timer  || opts.timer == 'false') { 
            		return false;
            	} else  {
		            clock = setInterval(function(e){
						shift('next');  
		            }, opts.advanceSpeed);            		
            	}
	        }
	        function stopClock() {
	        	if(!opts.timer || opts.timer == 'false') { return false; } else {
		            timerRunning = false;
		            clearInterval(clock);
				}
	        }  
            
            //Timer Setup
            if(opts.timer) {
				var timerRunning;
				var clock; 
				startClock();
				if(opts.startClockOnMouseOut){
				    var outTimer;
				    rotator.mouseleave(function() {
				        outTimer = setTimeout(function() {
				            if(!timerRunning){
				                startClock();
				            }
				        }, opts.startClockOnMouseOutAfter)
				    })
				    rotator.mouseenter(function() {
				        clearTimeout(outTimer);
				    })
				}                
            }  
	        
	        //Pause Timer on hover
	        if(opts.pauseOnHover) {
		        rotator.mouseenter(function() {
		        	stopClock(); 
		        });
		   	}
            
		//= DIRECTIONAL NAV ============================
            //DirectionalNav { rightButton --> shift("next"), leftButton --> shift("prev");
            if(opts.directionalNav) {
            	if(opts.directionalNav == 'false') { return false; }
                var directionalNavHTML = '<span class="rotatorArrow next">next</span><span class="rotatorArrow prev">prev</span>';
                rotator.append(directionalNavHTML);
                var leftBtn = rotator.children('.rotatorArrow.prev'),
                	rightBtn = rotator.children('.rotatorArrow.next');
                leftBtn.click(function() { 
                    stopClock();
                    shift('prev');
                    opts.timer = false;                
                });
                rightBtn.click(function() {
                    stopClock();
                    shift('next');
                    opts.timer = false;
                });
                rotator.hover(function(){
	                	if ($.browser.msie && $.browser.version < 9) {
							leftBtn.show();
							rightBtn.show();
						} else {	
							leftBtn.fadeIn(250);
							rightBtn.fadeIn(250);
						}					
					},function(){
						if ($.browser.msie && $.browser.version < 9) {
							leftBtn.hide();
							rightBtn.hide();
						} else {	
							leftBtn.fadeOut(100);
							rightBtn.fadeOut(100);
						}
				});
            }
            
		//= BULLET NAV ============================
            //Bullet Nav Setup
            if(opts.bulletNav) { 
            	var bulletHTML = '<div class="rotatorBullets"></div>';            	
            	rotator.append(bulletHTML);
            	$('.rotatorBullets').css('margin-top',rotatorHeight+15);
            	var bulletNav = rotator.children('div.rotatorBullets');
            	for(i=0; i<numberSlides; i++) {
            		var iMarkup = $('<span>'+(i+1)+'</span>');
            		rotator.children('div.rotatorBullets').append(iMarkup);
            		iMarkup.data('index',i);
            		iMarkup.click(function() {
            			stopClock();
            			shift($(this).data('index'));
            			opts.timer = false;
            		});
            	}
            	// Center Bullets in IE7
            	if ($.browser.msie && $.browser.version == 7) {
            		var bulletHTMLW = (984 - $('.rotatorBullets').width())/2;
            		$('.rotatorBullets').css('margin-left',bulletHTMLW);
            	}
            	setActiveBullet();
            }
            
            //Bullet Nav Execution
        	function setActiveBullet() { 
        		if(!opts.bulletNav) { return false; } else {
	        		bulletNav.children('span').removeClass('active').eq(activeSlide).addClass('active');
	        	}
        	}
        	
		//= TEXT NAV ============================
            //Text Nav Setup
            if(opts.textNav) { 
            	var textHTML = '<div class="rotatorText"></div>';            	
            	rotator.append(textHTML);
            	$('.rotatorText').css('margin-top',rotatorHeight);
            	var textNav = rotator.children('div.rotatorText');
            	var textNavArray = opts.textNavArray.split(',');
            	var iTxt = 0;
            	for(i=0; i<numberSlides; i++) {
            		var iMarkup = $('<span>'+textNavArray[iTxt++]+'</span>');
            		rotator.children('div.rotatorText').append(iMarkup);
            		iMarkup.data('index',i);
            		iMarkup.click(function() {
            			stopClock();
            			shift($(this).data('index'));
            			opts.timer = false;
            		});
            	}
            	// Center Bullets in IE7
            	if ($.browser.msie && $.browser.version == 7) {
            		var textHTMLW = (984 - $('.rotatorText').width())/2;
            		$('.rotatorText').css('margin-left',textHTMLW);
            	}
            	setActiveText();
            }
            
            //Text Nav Execution
        	function setActiveText() { 
        		if(!opts.textNav) { return false; } else {
	        		textNav.children('span').removeClass('active').eq(activeSlide).addClass('active');
	        	}
        	}
        	
        	
        //= ANIMATION ============================
            //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; }
                
                opts.beforeChange.call(this);
                
                //reset Z & Unlock
                function resetAndUnlock() {
                    slides
                    	.eq(prevActiveSlide)
                    	.css({'z-index' : 1});
                    unlock();
                    opts.afterChange.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 to correct text
                     setActiveText();
                     
                    //set previous slide z-index to one below what new activeSlide will be
                    slides
                    	.eq(prevActiveSlide)
                    	.css({'z-index' : 2}).removeClass('active');    
                    
                    //fade
                    if(opts.animation == 'fade') {
                        slides
                        	.eq(activeSlide)
                        	.css({'opacity' : 0, 'z-index' : 3})
                        	.animate({'opacity' : 1}, opts.animationSpeed, resetAndUnlock);
                    }
                    //push-over
                    if(opts.animation == 'horizontal-push') {
                        if(slideDirection == "next") {
                            slides
                            	.eq(activeSlide)
                            	.css({'left': rotatorWidth, 'z-index' : 3}).addClass('active')
                            	.animate({'left' : 0}, opts.animationSpeed, resetAndUnlock);
                            slides
                            	.eq(prevActiveSlide)
                            	.animate({'left' : -rotatorWidth}, opts.animationSpeed);
                        }
                        if(slideDirection == 'prev') {
                            slides
                            	.eq(activeSlide)
                            	.css({'left': -rotatorWidth, 'z-index' : 3}).addClass('active')
                            	.animate({'left' : 0}, opts.animationSpeed, resetAndUnlock);
							slides
                            	.eq(prevActiveSlide)
                            	.animate({'left' : rotatorWidth}, opts.animationSpeed);
                        }
                    }
                } //lock
            }//rotator function
        });//each call
    }//rotator plugin call
})(jQuery);
