/*

	Supersized - Fullscreen Slideshow jQuery Plugin
	Version : Core 3.2.1
	Site	: www.buildinternet.com/project/supersized
	
	Author	: Sam Dunn
	Company : One Mighty Roar (www.onemightyroar.com)
	License : MIT License / GPL License
	
*/

(function($){

	/* Place Supersized Elements
	----------------------------*/
//Add in Supersized elements
    $(document).ready(function() {
    
      //hide all more-info-entries and ts more info
      $('#defaultContent .ssCnt, #defaultContent .ssMoreInfoWrap').css({'display':'none'});
      // get total count
      var totalItemsCount = $('#defaultContent .ssCnt').size();
      $('.ssTotal').html(totalItemsCount);
      
      var left = $('.tx_k77supersize .cnt_el_default').offset().left;
      var top = $('.tx_k77supersize .cnt_el_default').offset().top+9;
      var divState = 0;
      
      $('body').prepend('<div id="supersized-loader"></div><div id="supersized"></div>');
      
      // set handler for closer in ts more info layer      
      $('.ssCloseLayer').click(function(){
        $(this).parent().parent().parent().hide();
        $('.ssAllItemsWrap').show();     
      });
      
      // set handler to open ts more info
      $('.ssTsWording').click(function(){  
        // kill slideshow interval
        clearInterval(slideshow_interval)
        // hide all items
        $('.ssAllItemsWrap').hide();
        // show ts more info
        $('.ssTsInfoHide .cnt_el_default').show();
      });
        
      // set handler
      $('.ssCnt').bind('mouseenter',function(){     
        $('.ssCnt').removeClass('nobgimg');      
      });
      
      $('.ssCnt').bind('mouseleave',function(){ 
        if(divState == 0){
          $('.ssCnt').addClass('nobgimg'); 
        }
      });
      
      // set closer      
      $('.ssCloseLayerItem').click(function(){
        clearInterval(slideshow_interval);
        if(divState == 0) {
          return false;
        } else {
          divState = 0;
        }
        $('.ssCloseLayerItem').toggleClass('nobgimg');
        $('.ssMoreInfoWrap').hide();
        $('.ssInfo a').removeClass('ssInfoOpen');
      });
        
      $('.ssInfo').click(function(){
        clearInterval(slideshow_interval);
        if(divState == 0) {
          divState = 1; 
          $('.ssCloseLayerItem').toggleClass('nobgimg');
          $('.ssInfo a').addClass('ssInfoOpen');      
            animateInfo ();
        } else {
          return false;
        }
      });
        
      function animateInfo () {
        $('.ssMoreInfoWrap').animate({
          height: 'toggle', 
          opacity: 'toggle'
          }, 500);
        }
        $("#ssCnt0").show();
      });
    
    
    $.supersized = function(options){
    	
    	/* Variables
		----------------------------*/
    	var el = '#supersized',
        	base = this;
        // Access to jQuery and DOM versions of element
        base.$el = $(el);
        base.el = el;
        vars = $.supersized.vars;
        // Add a reverse reference to the DOM object
        base.$el.data("supersized", base);
        api = base.$el.data('supersized');
		
		base.init = function(){
        	// Combine options 
        	$.supersized.vars.options = $.extend({},$.supersized.defaultOptions, options);
            base.options = $.supersized.vars.options;
            
            base._build();
        };
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        /* Build Elements
		----------------------------*/
        base._build = function(){
				
            base._start(); // Get things started
        };
        
        
        /* Initialize
		----------------------------*/
    	base._start = function(){
			
			// Determine if starting slide random
			if (base.options.start_slide){
				vars.current_slide = base.options.start_slide - 1;
			}else{
				vars.current_slide = Math.floor(Math.random()*base.options.slides.length);	// Generate random slide number
			}
			
			// If links should open in new window
			var linkTarget = base.options.new_window ? ' target="_blank"' : '';
			
			// Set current image
			imageLink = (api.getField('url')) ? "href='" + api.getField('url') + "'" : "";
			var img = $('<img src="'+api.getField('image')+'"/>');      
			img.appendTo(base.el); //.wrap('<a class="image-loading activeslide" ' + imageLink + linkTarget + '></a>').css('visibility','hidden');
			
			img.load(function(){
				//base._origDim($(this));
				//base.resizeNow();	// Resize background image
				base.launch();
			});
			
			//  Hide elements to be faded in
			base.$el.css('visibility','hidden');
      
      // --------------------------------------
      var element = base.$el;		//Supersized container
      var currentSlide = 1;
      // s.gen setting
      
      // extend
      /*
      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 isPaused = false;						//Tracks paused on/off
      var image_path = options.image_path;		//Default image path for navigation control buttons

      //Set slideshow quality (Supported only in FF and IE, no Webkit)
      if (options.performance == 3){
          element.addClass('speed'); 		//Faster transitions
      } else if ((options.performance == 1) || (options.performance == 2)){
          element.addClass('quality');	//Higher image quality
      }
      
      // e.gen setting

      /* start slide.nav */
      for (j = 1; j <= options.slides.length; j++) {
        if(j==1) {
          liopts = '<li class="navcircles active" id="navslide_' + j + '">&nbsp;</li>';
        } else {
          liopts += '<li class="navcircles" id="navslide_' + j + '">&nbsp;</li>';
        }
        $('<img/>').attr("src", options.slides[j-1].image).appendTo(el).wrap('<div  id="imgHolder' + j +'" class="imgHolder" style="background-color:' + options.slides[j-1].becolor +'"></div><div class="clearboth"></div>');
      }

      $('.ssNaviItemsWrap ul').html(liopts);
        $('.ssNaviItemsWrap ul li').each(function(index) {
            $(this).bind('click', function() {
                if(inAnimation) return false;		//Abort if currently animating
                clearInterval(slideshow_interval);
                specslide($(this).attr('id').substr(9),0);		//Go to next slide
                return false;
            });
        });
        /* end slide.nav */
        
        $(window).load(function(){
          $('#supersized-loader').hide();		//Hide loading animation
          $('#imgHolder1 img').fadeIn('fast');				//Fade in background
          $('#imgHolder1 img').addClass('active');
          $('#imgHolder1').css('z-index','-7');
          resizenow();	//Resize background image
          slideshow_interval = setInterval(autoslide, options.slide_interval);
        });		//End window load
      
        //Adjust image when browser is resized
        $(window).resize(function(){
            resizenow();
        });

        function autoslide() {
            specslide(currentSlide,1);
        }
        
        var myStop = false;
        // Pause on content hover
				$('.ssCnt').hover(
				  function () {
				    clearInterval(slideshow_interval);
				    return false;
				  }, 
				  function () {
				    if (!myStop) {
							slideshow_interval = setInterval(autoslide, 5000);
					    return false;
				    }
				  }
				);
				$('.ssInfo').click(
				  function () {
				    myStop = true;
						clearInterval(slideshow_interval);
				    return false;
				});

				$('.ssCloseLayerItem').click(
				  function () {
				    myStop = false;
					  return false;
				});   
        
        //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

                    //Gather browser size
                    
                    
                    var browserwidth = $(window).width();
                    var browserheight = $(window).height();
                    var offset;
                    /*
                    
                    	var browserwidth = base.$el.width(),
                      browserheight = base.$el.height(),
                      offset;
                    */

                   

                    //Horizontally Center
                    if (options.horizontal_center){
                        $(this).css('left', ((browserwidth) - $(this).width())/2);
                    }
                   
                   /*
                    if($(this).height() > browserheight) {               
                        var beheight = $(this).height();
                    } else {
                        var beheight = browserheight;
                    }
                    if($(this).width() > browserwidth) {               
                        var bewidth = $(this).width();
                    } else {
                        var bewidth = browserwidth;
                    }*/
                    
                   $(this).css('width','2560px' );
                   // $(this).parent().css('height',$(this).height() );
                   
                   //alert('-> width: ' + $(this).width());
                    

                });

                //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;
            });
        };
        
        //specific slide
        function specslide(sindex, auto) {

						if(inAnimation) return false;		//Abort if currently animating
            else inAnimation = true;		//Otherwise set animation marker

            if(auto == 1) {
                if(currentSlide+1 > $('.ssTotal').html()) {
										sindex = 1;
                } else {
                    sindex = Number(currentSlide)+1;
                }
            }
            
            
            liTarget = $('.ssNaviItemsWrap ul li').find('active').next();
            $('.ssNaviItemsWrap ul li').removeClass('active');
            $("#navslide_" + sindex).addClass('active');
            var nextslide = $('#imgHolder' + sindex + ' img');
            
            $('#imgHolder' + currentSlide).css('z-index','-8');
            $('#imgHolder' + sindex).css('z-index','-7');
            //$('.imgHolder img.active').hide();
            nextslide.hide().fadeTo(options.transition_speed, 1, function(){    
                afterAnimation();
            });
            $('#imgHolder' + currentSlide).css('z-index','-9');
            
            nextslide.addClass('active');
            $('.ssCurr').html(sindex);
            $(".ssCnt").hide();
            $("#ssCnt"+(sindex-1)).show();
            currentSlide = sindex;
        }

        //After slide animation
        function afterAnimation() {
            inAnimation = false;
            //If hybrid mode is on swap back to higher image quality
            if (options.performance == 1){
                element.removeClass('speed').addClass('quality');
            }
            resizenow();
        }
        
        	resizenow();
        
			
    	};
		
		
		/* Launch Supersized
		----------------------------*/
		base.launch = function(){
		
			base.$el.css('visibility','visible');
			$('#supersized-loader').hide();		//Hide loading animation
			resizenow();	//Resize background image
			// Adjust image when browser is resized
			$(window).resize(function(){
	    		//base.resizeNow();
          resizenow();	//Resize background image
			});
      
      
      
      
      
      
    		
    	};
        
        
        /* Resize Images
		----------------------------*/
		base.resizeNow = function(){
			
			return base.$el.each(function() {
		  		//  Resize each image seperately
		  		$('img', base.el).each(function(){
		  			
					thisSlide = $(this);
					var ratio = (thisSlide.data('origHeight')/thisSlide.data('origWidth')).toFixed(2);	// Define image ratio
					
					// Gather browser size
					var browserwidth = base.$el.width(),
						browserheight = base.$el.height(),
						offset;
					
					/*-----Resize Image-----*/
					if (base.options.fit_always){	// Fit always is enabled
						if ((browserheight/browserwidth) > ratio){
							resizeWidth();
						} else {
							resizeHeight();
						}
					}else{	// Normal Resize
						if ((browserheight <= base.options.min_height) && (browserwidth <= base.options.min_width)){	// If window smaller than minimum width and height
						
							if ((browserheight/browserwidth) > ratio){
								base.options.fit_landscape && ratio < 1 ? resizeWidth(true) : resizeHeight(true);	// If landscapes are set to fit
							} else {
								base.options.fit_portrait && ratio >= 1 ? resizeHeight(true) : resizeWidth(true);		// If portraits are set to fit
							}
						
						} else if (browserwidth <= base.options.min_width){		// If window only smaller than minimum width
						
							if ((browserheight/browserwidth) > ratio){
								base.options.fit_landscape && ratio < 1 ? resizeWidth(true) : resizeHeight();	// If landscapes are set to fit
							} else {
								base.options.fit_portrait && ratio >= 1 ? resizeHeight() : resizeWidth(true);		// If portraits are set to fit
							}
							
						} else if (browserheight <= base.options.min_height){	// If window only smaller than minimum height
						
							if ((browserheight/browserwidth) > ratio){
								base.options.fit_landscape && ratio < 1 ? resizeWidth() : resizeHeight(true);	// If landscapes are set to fit
							} else {
								base.options.fit_portrait && ratio >= 1 ? resizeHeight(true) : resizeWidth();		// If portraits are set to fit
							}
						
						} else {	// If larger than minimums
							
							if ((browserheight/browserwidth) > ratio){
								base.options.fit_landscape && ratio < 1 ? resizeWidth() : resizeHeight();	// If landscapes are set to fit
							} else {
								base.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() < base.options.min_width ){
								if (thisSlide.width() * ratio >= base.options.min_height){
									thisSlide.width(base.options.min_width);
						    		thisSlide.height(thisSlide.width() * ratio);
						    	}else{
						    		resizeHeight();
						    	}
						    }
						}else{
							if (base.options.min_height >= browserheight && !base.options.fit_landscape){	// If minimum height needs to be considered
								if (browserwidth * ratio >= base.options.min_height || (browserwidth * ratio >= base.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(base.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 >= base.options.min_width){
									thisSlide.height(base.options.min_height);
									thisSlide.width(thisSlide.height() / ratio);
								}else{
									resizeWidth(true);
								}
							}
						}else{	// Otherwise, resized as normal
							if (base.options.min_width >= browserwidth){	// If minimum width needs to be considered
								if (browserheight / ratio >= base.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(base.options.min_width);
						    		thisSlide.height(thisSlide.width() * ratio);
								}
							}else{	// Otherwise, resize as normal
								thisSlide.height(browserheight);
								thisSlide.width(browserheight / ratio);
							}
						}
					};
					
					/*-----End Resize Functions-----*/
					
					if (thisSlide.parent().hasClass('image-loading')){
						$('.image-loading').removeClass('image-loading');
					}
					
					// Horizontally Center
					if (base.options.horizontal_center){
						$(this).css('left', (browserwidth - $(this).width())/2);
					}
					
					// Vertically Center
					if (base.options.vertical_center){
						$(this).css('top', (browserheight - $(this).height())/2);
					}
					
				});
				
				// Basic image drag and right click protection
				if (base.options.image_protect){
					
					$('img', base.el).bind("contextmenu mousedown",function(){
						return false;
					});
				
				}
				
				return false;
				
			});
			
		};
        
		
		/* Get Original Dimensions
		----------------------------*/
		base._origDim = function(targetSlide){
			targetSlide.data('origWidth', targetSlide.width()).data('origHeight', targetSlide.height()).css('visibility','visible');
		};
		
		base.getField = function(field){
			return base.options.slides[vars.current_slide][field];
		};
		
        // Make it go!
        base.init();
	};
	
	
	/* Global Variables
	----------------------------*/
	$.supersized.vars = {
		
		// Internal variables
		current_slide			:	0,			// Current slide number
		options					:	{}			// Stores assembled options list
		
	};
	
	
	/* Default Options
	----------------------------*/
	$.supersized.defaultOptions = {
    
    // Functionality
    slideshow             : 1,		  // Slideshow on/off
    autoplay				      :	1,		  // Slideshow starts playing automatically
		start_slide           : 1,		  // Start slide (0 is random)
		new_window				    :	0,			// Image links open in new window/tab
		image_protect			    :	0,			// Disables image dragging and right click with Javascript
		

    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 transiti
    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)

		// 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_always				    :	0,			// Image will never exceed browser width or height (Ignores min. dimensions)
		fit_portrait         	: 0,			// Portrait images will not exceed browser height
		fit_landscape			    : 0			  // Landscape images will not exceed browser width
    	
    };
    
    $.fn.supersized = function(options){
        return this.each(function(){
            (new $.supersized(options));
        });
    };
    
    		
})(jQuery);


