/*
	Supersized - Fullscreen Slideshow jQuery Plugin
	Version 3.1.3
	www.buildinternet.com/project/supersized
	
	By Sam Dunn / One Mighty Roar (www.onemightyroar.com)
	Released under MIT License / GPL License
*/

(function($){

	//Add in Supersized elements
	$(document).ready(function() {
		$('body').prepend('<div id="supersized-loader"></div>').prepend('<div id="supersized"></div>');
	});
	
	//Resize image on ready or resize
	$.supersized = function( options ) {
		
		//Default settings
		var settings = {
			
			//Functionality
			slideshow               :   1,		//Slideshow on/off
			autoplay				:	1,		//Slideshow starts playing automatically
			start_slide             :   1,		//Start slide (0 is random)
			random					: 	0,		//Randomize slide order (Ignores start slide)
			slide_interval          :   5000,	//Length between transitions
			transition              :   1, 		//0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
			transition_speed		:	750,	//Speed of transition
			new_window				:	1,		//Image links open in new window/tab
			pause_hover             :   0,		//Pause slideshow on hover
			keyboard_nav            :   1,		//Keyboard navigation on/off
			performance				:	1,		//0-Normal, 1-Hybrid speed/quality, 2-Optimizes image quality, 3-Optimizes transition speed // (Only works for Firefox/IE, not Webkit)
			image_protect			:	1,		//Disables image dragging and right click with Javascript
			image_path				:	'img/', //Default image path
			
			//Size & Position
			min_width		        :   0,		//Min width allowed (in pixels)
			min_height		        :   0,		//Min height allowed (in pixels)
			vertical_center         :   1,		//Vertically center background
			horizontal_center       :   1,		//Horizontally center background
			fit_portrait         	:   0,		//Portrait images will not exceed browser height
			fit_landscape			:   0,		//Landscape images will not exceed browser width  
			
			//Components
			navigation              :   1,		//Slideshow controls on/off
			thumbnail_navigation    :   0,		//Thumbnail navigation
			slide_counter           :   1,		//Display slide numbers
			slide_captions          :   1		//Slide caption (Pull from "title" in slides array)
			
    	};
		//Default elements
		var element = $('#supersized');		//Supersized container
		//Combine options with default settings
		if (options) {
			var options = $.extend(settings, options);	//Pull from both defaults and supplied options
		}else{
			var options = $.extend(settings);			//Only pull from default settings		
		}
		//General slideshow variables
		var inAnimation = false;					//Prevents animations from stacking
		var isLoaded = false;
		var quedIsLoaded = false;
		var isPaused = true;						//Tracks paused on/off
		var image_path = options.image_path;		//Default image path for navigation control buttons
		
		//Determine starting slide (random or defined)
		var currentSlide = 0;
		var currentSet = 'home';

		//If links should open in new window
		var linkTarget = options.new_window ? ' target="_blank"' : '';
		/***Load initial set of images***/

		//Set current image
		$('<img class="activeslide" />').attr("src", 'img/bg/IMG_2027-copy.jpg').appendTo(element).wrap('<a></a>');

		/***End load initial images***/
		$('#supersized-loader').hide();
		$('#nextslide').hide();
		$('#prevslide').hide();
		$('.lc').css('opacity', 0);
		$('.rc').css('opacity', 0);
		$('#controls-wrapper').hide();	//Hide controls to be displayed
		//Account for loading in IE
		$(document).ready(function() {
			resizenow();
		});

		
		$(window).load(function(){
			element.fadeIn('fast');				//Fade in background
			$('#controls-wrapper').show();		//Display controls
			//Display thumbnails
			resizenow();	//Resize background image
			
			if (!(options.navigation)) $('#navigation').hide();	//Display navigation
			

		    var bg_animation_id = setInterval(function() { nextslide(); }, 7500);	// Initiate slide interval
			
            //Navigation controls
            if (options.navigation){
            	
            	//Next button clicked
                $('#nextslide').click(function() {
                	//$('#supersized-loader').fadeIn('fast');
                	if(inAnimation) return false;		//Abort if currently animating

            	    nextslide();		//Go to next slide					    
            	    return false;
                });
            
            	$('.sl').not('#characters').click(function() {
                	if(inAnimation) return false;		//Abort if currently animating
		    clearInterval(bg_animation_id);
		    if(this.id == 'home')
			bg_animation_id = setInterval(function() { nextslide(); }, 7500);
            	    gotoslide(this.getAttribute('id'));		//Go to next slide					   
            	    return false;
                });
            
                //Previous button clicked
                $('#prevslide').click(function() {
                	if(inAnimation) return false;		//Abort if currently animating
            	    prevslide();		//Go to previous slide
            	    return false;
                });

                
            }	//End navigation controls
							
		});		//End window load
				
		//Keyboard Navigation
		/*
		if (options.keyboard_nav){
		
			$(document.documentElement).keydown(function (event) {
				
				if ((event.keyCode == 37) || (event.keyCode == 40)) { //Left Arrow or Down Arrow
					if ($('#prevslide').attr('src')) $('#prevslide').attr("src", image_path + "back.png");		//If image, change back button to active
				} else if ((event.keyCode == 39) || (event.keyCode == 38)) { //Right Arrow or Up Arrow
					if ($('#nextslide').attr('src')) $('#nextslide').attr("src", image_path + "forward.png");	//If image, change next button to active
				}
				
			});
			
			$(document.documentElement).keyup(function (event) {
			
				
				if ((event.keyCode == 37) || (event.keyCode == 40)) { //Left Arrow or Down Arrow
					
					if ($('#prevslide').attr('src')) $('#prevslide').attr("src", image_path + "back_dull.png");	//If image, change back button to normal
					
					if(inAnimation) return false;		//Abort if currently animating
					    	
					prevslide();		//Go to previous slide
										
					return false;
				
				} else if ((event.keyCode == 39) || (event.keyCode == 38)) { //Right Arrow or Up Arrow
					
					if ($('#nextslide').attr('src')) $('#nextslide').attr("src", image_path + "forward_dull.png");	//If image, change next button to normal
					
					if(inAnimation) return false;		//Abort if currently animating
					    	
				    nextslide();		//Go to next slide
				    				   
				    return false;
				
				}
			
			});
		}
		*/
				
		//Adjust image when browser is resized
		$(window).resize(function(){
    		resizenow();
		});
		
		
		//Adjust image size
		function resizenow() {
			return element.each(function() {
		  	
		  		var t = $('img', element);
		  		
		  		//Resize each image seperately
		  		$(t).each(function(){
		  		
					var ratio = ($(this).height()/$(this).width()).toFixed(2);	//Define image ratio
					thisSlide = $(this);
					
					//Gather browser size
					var browserwidth = $(window).width();
					var browserheight = $(window).height();
					var offset;
					
					/**Resize image to proper ratio**/
					
					if ((browserheight <= options.min_height) && (browserwidth <= options.min_width)){	//If window smaller than minimum width and height
					
						if ((browserheight/browserwidth) > ratio){
							options.fit_landscape && ratio <= 1 ? resizeWidth(true) : resizeHeight(true);	//If landscapes are set to fit
						} else {
							options.fit_portrait && ratio > 1 ? resizeHeight(true) : resizeWidth(true);		//If portraits are set to fit
						}
					
					} else if (browserwidth <= options.min_width){		//If window only smaller than minimum width
					
						if ((browserheight/browserwidth) > ratio){
							options.fit_landscape && ratio <= 1 ? resizeWidth(true) : resizeHeight();	//If landscapes are set to fit
						} else {
							options.fit_portrait && ratio > 1 ? resizeHeight() : resizeWidth(true);		//If portraits are set to fit
						}
						
					} else if (browserheight <= options.min_height){	//If window only smaller than minimum height
					
						if ((browserheight/browserwidth) > ratio){
							options.fit_landscape && ratio <= 1 ? resizeWidth() : resizeHeight(true);	//If landscapes are set to fit
						} else {
							options.fit_portrait && ratio > 1 ? resizeHeight(true) : resizeWidth();		//If portraits are set to fit
						}
					
					} else {	//If larger than minimums
						
						if ((browserheight/browserwidth) > ratio){
							options.fit_landscape && ratio <= 1 ? resizeWidth() : resizeHeight();	//If landscapes are set to fit
						} else {
							options.fit_portrait && ratio > 1 ? resizeHeight() : resizeWidth();		//If portraits are set to fit
						}
						
					}
					
					/**End Image Resize**/
					
					
					/**Resize Functions**/
					
					function resizeWidth(minimum){
						if (minimum){	//If minimum height needs to be considered
							if(thisSlide.width() < browserwidth || thisSlide.width() < options.min_width ){
								if (thisSlide.width() * ratio >= options.min_height){
									thisSlide.width(options.min_width);
						    		thisSlide.height(thisSlide.width() * ratio);
						    	}else{
						    		resizeHeight();
						    	}
						    }
						}else{
							if (options.min_height >= browserheight && !options.fit_landscape){	//If minimum height needs to be considered
								if (browserwidth * ratio >= options.min_height || (browserwidth * ratio >= options.min_height && ratio <= 1)){	//If resizing would push below minimum height or image is a landscape
									thisSlide.width(browserwidth);
									thisSlide.height(browserwidth * ratio);
								} else if (ratio > 1){		//Else the image is portrait
									thisSlide.height(options.min_height);
									thisSlide.width(thisSlide.height() / ratio);
								} else if (thisSlide.width() < browserwidth) {
									thisSlide.width(browserwidth);
						    		thisSlide.height(thisSlide.width() * ratio);
								}
							}else{	//Otherwise, resize as normal
								thisSlide.width(browserwidth);
								thisSlide.height(browserwidth * ratio);
							}
						}
					};
					
					function resizeHeight(minimum){
						if (minimum){	//If minimum height needs to be considered
							if(thisSlide.height() < browserheight){
								if (thisSlide.height() / ratio >= options.min_width){
									thisSlide.height(options.min_height);
									thisSlide.width(thisSlide.height() / ratio);
								}else{
									resizeWidth(true);
								}
							}
						}else{	//Otherwise, resized as normal
							if (options.min_width >= browserwidth){	//If minimum width needs to be considered
								if (browserheight / ratio >= options.min_width || ratio > 1){	//If resizing would push below minimum width or image is a portrait
									thisSlide.height(browserheight);
									thisSlide.width(browserheight / ratio);
								} else if (ratio <= 1){		//Else the image is landscape
									thisSlide.width(options.min_width);
						    		thisSlide.height(thisSlide.width() * ratio);
								}
							}else{	//Otherwise, resize as normal
								thisSlide.height(browserheight);
								thisSlide.width(browserheight / ratio);
							}
						}
					};
					
					/**End Resize Functions**/
					
					
					//Horizontally Center
					if (options.horizontal_center){
						$(this).css('left', (browserwidth - $(this).width())/2);
					}
					
					//Vertically Center
					if (options.vertical_center){
						$(this).css('top', (browserheight - $(this).height())/2);
					}
					
				});
				
				//Basic image drag and right click protection
				if (options.image_protect){
					
					$('img', element).bind("contextmenu",function(){
						return false;
					});
					$('img', element).bind("mousedown",function(){
						return false;
					});
				
				}
				
				return false;
				
			});
		};
	
		
		//Next slide
		function nextslide() {
		    
		    if(typeof currentSet == 'string') currentSet = settings['slides'][currentSet]; // DUH!!!!!!!!! why would this be missing?

			if(inAnimation) return false;		//Abort if currently animating
				else inAnimation = true;		//Otherwise set animation marker
				
			if (quedIsLoaded){
				var isLoaded = true;
			}
			
			var prevslide = element.find('.activeslide');		//Find active slide
			prevslide.removeClass('activeslide');				//Remove active class
			var quedslide = element.find('.quedslide');		//Find qued slide
			quedslide.removeClass('quedslide');
			
			//Get the slide number of new slide
			currentSlide++;
                        if(currentSlide > (currentSet.length - 1)) currentSlide = 0; // ....obviously needed
			
			//set next / prev buttons
			if (currentSlide+1 == currentSet.length) {
				$('.rc:visible').fadeTo(300, 0, function(){$("#nextslide").hide();/*console.log($('.rc').css('opacity'));*/});
				$("#prevslide").show();
				$('.lc').fadeTo(300, 0.2);
			} else {
				$("#prevslide").show();
				$('.lc').fadeTo(300, 0.2);
			}
			
			/**** Image Loading ****/
			
			//Load next image
			loadSlide = false;
			
		    var nextslide = $('<img style="display: none;" />');
			nextslide.addClass('activeslide');
			var isLoaded = false;
			nextslide.bind("load",function(){
				isLoaded = true;
				resizenow();
				nextslide.fadeIn(options.transition_speed, function(){ afterAnimation(); prevslide.parent().remove(); quedslide.parent().remove(); });
				//nextslide.show();
				//prevslide.fadeOut(options.transition_speed, function(){ afterAnimation(); prevslide.remove(); });
				$('#supersized-loader').fadeOut('fast');
			});

		    
/*
		        console.log(nextslide);
    		        console.log(currentSet);
		        console.log(currentSlide);
		        console.log(currentSet[currentSlide]);
		        console.log(currentSet[currentSlide].image); 
                        console.log(settings);
		        console.log(settings['slides']);
*/


			nextslide.appendTo(element);
			nextslide.attr("src", currentSet[currentSlide].image).wrap('<a></a>');

			
			nextslide.bind("load",function(){
				resizenow();
				nextslide.fadeIn(options.transition_speed, function(){ afterAnimation(); prevslide.parent().remove(); });
				$('#supersized-loader').fadeOut('fast');
			});
			
			if (currentSlide+1 < currentSet.length) {
				quedIsLoaded = false;
				var quedslide = $("<img/>");
				quedslide.hide().addClass('quedslide').bind("load",function(){
					quedIsLoaded = true;
				});
				quedslide.appendTo(element);
				quedslide.attr("src", currentSet[currentSlide+1].image).wrap('<a></a>');
			}
			
			/**** End Image Loading ****/
			
			//Check to see when previous image should be faded out
			setTimeout(function(){
				if (isLoaded == false) {
					$('#supersized-loader').fadeIn('fast');
					prevslide.fadeOut(options.transition_speed, function(){prevslide.parent().remove();});
				} else {
					return false;
				}
			}, 150);
			nextslide.addClass('activeslide');	//Update active slide
  
		}
		
		//Go to Slide
		function gotoslide(slide) {
			
			if(inAnimation) return false;		//Abort if currently animating
				else inAnimation = true;		//Otherwise set animation marker

			currentSet = options.slides[slide]; 
			
			var prevslide = element.find('.activeslide');		//Find active slide
			prevslide.removeClass('activeslide');
			if (prevslide.next().length) {
				prevslide.next().remove();
			}
			var quedslide = element.find('.quedslide');		//Find active slide
			if (quedslide.length) {
				quedslide.remove();
			}
						
			//Get the slide number of new slide
			currentSlide = 0;

			/**** Image Loading ****/
			
			//Load next image
			loadSlide = false;
			
			//Load image and fade in when loaded
			var nextslide = $("<img/>");
			nextslide.addClass('activeslide');
			var isLoaded = false;
			nextslide.bind("load",function(){
				isLoaded = true;
				resizenow();
				nextslide.fadeIn(options.transition_speed, function(){ afterAnimation(); prevslide.parent().remove(); });
				//nextslide.show();
				//prevslide.fadeOut(options.transition_speed, function(){ afterAnimation(); prevslide.remove(); });
				$('#supersized-loader').fadeOut('fast');
			});
			nextslide.appendTo(element);

		        /* console.log(nextslide);
    		        console.log(currentSet);
		        console.log(currentSlide);
		        console.log(currentSet[currentSlide]);
		        console.log(currentSet[currentSlide].image); */

			nextslide.attr("src", currentSet[currentSlide].image).wrap('<a></a>');

			
			if (currentSet.length > 1) {
				quedIsLoaded = false;
				var quedslide = $("<img/>");
				quedslide.hide().addClass('quedslide').bind("load",function(){
					quedIsLoaded = true;
				});
				quedslide.appendTo(element);
				quedslide.attr("src", currentSet[currentSlide+1].image).wrap('<a></a>');
			}
			
			/**** End Image Loading ****/

			//Check to see when previous image should be faded out
		    setTimeout(function(){
				if (isLoaded == false) {
					$('#supersized-loader').fadeIn('fast');
					prevslide.fadeOut(options.transition_speed, function(){prevslide.remove();});
				} else {
					return false;
				}
			}, 150);
			
		    nextslide.hide().addClass('activeslide');	//Update active slide
  
		}
		
		//Previous Slide
		function prevslide() {
		
			if(inAnimation) return false;		//Abort if currently animating
				else inAnimation = true;		//Otherwise set animation marker
			
			var quedslide = element.find('.quedslide');		//Find qued slide
			quedslide.parent().remove();
			var prevslide = element.find('.activeslide');		//Find active slide
			prevslide.removeClass('activeslide');				//Remove active class
						
			//Get the slide number of new slide
			currentSlide--;
			
			//set next / prev buttons
			if (currentSlide == 0) {
				$('.lc:visible').fadeTo(300, 0, function(){$("#prevslide").hide();});
				$("#nextslide").show();
				$('.rc').css('opacity', 0);
				$('.rc').fadeTo(300, 0.2);
			} else {
				$("#nextslide").show();
				$('.rc').css('opacity', 0);
				$('.rc').fadeTo(300, 0.2);
			}
			
			/**** Image Loading ****/
			
			//Load next image
			loadSlide = false;
			
			//Load image and fade in when loaded
			var nextslide = $("<img/>");
			nextslide.addClass('activeslide');
			var isLoaded = false;
			nextslide.bind("load",function(){
				isLoaded = true;
				resizenow();
				nextslide.fadeTo(options.transition_speed, 1, function(){ afterAnimation(); prevslide.parent().remove(); });
				$('#supersized-loader').fadeOut('fast');
			});
			nextslide.appendTo(element).wrap("<a></a>");
			nextslide.attr("src", currentSet[currentSlide].image);
			
			if (currentSlide+1 < currentSet.length) {
				quedIsLoaded = false;
				var quedslide = $("<img/>");
				quedslide.hide().addClass('quedslide').bind("load",function(){
					quedIsLoaded = true;
				});
				quedslide.appendTo(element);
				quedslide.attr("src", currentSet[currentSlide+1].image).wrap('<a></a>');
			}
			
			
			/**** End Image Loading ****/
			
			//Check to see when previous image should be faded out
			setTimeout(function(){
				if (isLoaded == false) {
					prevslide.fadeOut(options.transition_speed, function(){prevslide.parent().remove();});
					$('#supersized-loader').fadeIn('fast');
				} else {
					return false;
				}
			}, 150);
			
			nextslide.hide().addClass('activeslide');	//Update active slide
			
		}
		
		//After slide animation
		function afterAnimation() {
		
			inAnimation = false;
			
			resizenow();
			
		}
	};
		
})(jQuery);


