$(document).ready(function () {

  var slideshow = new Slideshow();
  slideshow.init();
  
});

function Slideshow() {
  var slideshow = this; // Copy the object to use in Jquery callbacks etc.
  
  this.current = 0; // Default current image
  this.delay = 6; // In seconds
  this.interval = false; // Store the fade interval
  
  this.images = null; // List of images
  this.links = null; // List of "switch image" links
  
  // Initalise slideshow
  this.init = function() {
  
    // Get list of images
    this.images = $(".main-promo > .homimg");
    
    // Get list of links 
    this.links = $(".controls a");
  
    // Set default image + active link
    $(this.images).each(function(i) {
        if (i != slideshow.current) {
        $(this).addClass("hidden");
      } else {
        $(this).removeClass("hidden");
      }
    });
  
    this.setactive();
    this.hideimages();

    // Add click event to links
    $(this.links).each(function(i){
      $(this).click( function() {
        clearInterval(slideshow.interval); // Stop animation on click
        slideshow.interval = false;
        
        slideshow.current = i;
        slideshow.hideimages();
        slideshow.setactive();
        
		// DO NOT Continue automatic slideshow
        // this.nextslide();
      });
    });
  
  
    // Start the automatic slideshow
    this.interval = setInterval(nextslide, this.delay * 1000);

	// Wrapper function so it can be used in the setInterval function
	function nextslide() {
		slideshow.nextslide();	
	}
  };

  // Call the next image using 'hideimages' method
  this.nextslide = function() {
  	if (slideshow.current == (slideshow.images.length - 1)) {
    	slideshow.current = 0; // Go back to the beginning if the current image is the last one
    } else {
        slideshow.current += 1; // Or else just go to the next image
    }
    slideshow.hideimages(); // Update the images' hidden classes
  };

  // Updates the hidden/displayed classes on the images
  this.hideimages = function() {
    $(this.images).each(function(i) {
        if (i != slideshow.current) {
			$(this).fadeOut("slow"); 
		  } else {
			$(this).fadeIn("slow", function() {
					slideshow.setactive(); // Update the active link once the fade in has finished
				});
		  }
    });
  };

  // Updates the active link
  this.setactive = function() {
    $(this.links).each(function(i) {
      if (i != slideshow.current) {
        $(this).removeClass("active");
      } else {
        $(this).addClass("active");
      }
    });
  }
  
}

