/*
 * jQuery plugin for slideshow
 */
(function($){
  var self, interval, loadCounter = 0, imgCount = 0;
  
  $.fn.slideShow = function(options) {
    return this.each(function() {
      $.fn.slideShow.init(this, options)
    });
  };
  
  $.fn.slideShow.prefs = {
          "speed": 1500,
          "duration" : 6000,
          "total" : 4,
          "texts" : ["[ not used ]",
              ""                              // text first slide
            ],
          "title" : "",
          "progresIndicator" : false,
          "imagePath" : "/assets/img/",
          "fileName" : "header",
          "fileExtension" : "jpg",
          "randomStart" : false,
          "element" : $("#slideshow"),
          "backgroundImages" : false,
          "test" : false
        };
  
  $.fn.slideShow.randomNumber = function(num_start, num_end) {
    return Math.floor(Math.random() * (num_end - num_start + 1) + num_start);
  };
  
  $.fn.slideShow.init = function(element, options) {
    
    //slideShow.init(options);
    
    var el, start_slide = 0;

    self = this;

    /*
     * Use sent in preferences instead of pre-defined ones
     */
    for (var key in options) {
      if (self.prefs.hasOwnProperty(key)) {
        self.prefs[key] = options[key];
      }
    }
    self.prefs.element = $(element);
    
    el = self.prefs.element;

    imgCount = el.find("img").length;

    if (imgCount < 1) {
      // add fixed number of images from /img/ folder
      var content_slide = '<ul class="slides">';
      for (i = 1; i <= self.prefs.total; i++) {
        // check if texts exist for image
        if (typeof self.prefs.texts[i] == "undefined") {
          self.prefs.texts[i] = '';
        }

        content_slide += '<li><img src="' + self.prefs.imagePath + self.prefs.fileName + i + '.' + self.prefs.fileExtension + '" alt="' + self.prefs.title + '"><h2>' + self.prefs.texts[i] + '</h2></li>';
      }
      content_slide += '</ul>';
      
      el.append(content_slide);
      imgCount = el.find("img").length;
    }
		
		// start slideshow if there is more than 1 image
		if (imgCount > 1) {
			// bind to the images' load event
			$(el).find('.slides img')
				.load(function() {
					// increment the load counter
					loadCounter++;

					// once the load counter equals the total number of images
					if(loadCounter === imgCount) {

						// move images to background of .slides li
						if (self.prefs.backgroundImages) {
							$(el).find('.slides img').each(function(){
								$(this)
										.parents('li')
										.css('background-image', 'url(' + $(this).attr('src') + ')')
										.find('img')
										.remove();
							});
						}

						// random start
						if (self.prefs.randomStart) {
							start_slide = self.randomNumber(1, imgCount) - 1;
						}

						$(el).find('.slides li:eq(' + start_slide + ')')
								.css({opacity: 0.0})
								.addClass('active')
								.animate({opacity: 1.0}, self.prefs.speed);

						// add progress indicator
						if (self.prefs.progresIndicator) {
							// add progress buttons
							var content_progress = '<ul class="progress">';
							for (i = 1; i <= imgCount; i++) {
								// progress bar
								content_progress += '<li>' + i + '</li>';
							}
							content_progress += '</ul>';

							$(el).append(content_progress);

							// add event handler for clicks on progress indicators
							$(el).find('.progress li').click(function() {
								self.slideClick($(this));
							});

							$(el).find('.progress li:eq(' + start_slide + ')').addClass('active');
						}

						interval = setInterval(function() {self.slideSwitch();}, self.prefs.duration);
					}
				})
				.each(function() {
					// trigger the load event in case the image has been cached by the browser
					if(this.complete)
					{
							$(this).trigger('load');
					}
				});
		}

  };
  
  $.fn.slideShow.slideSwitch = function() {
    var el = self.prefs.element;
    
    var $active = $(el).find('.slides li.active');
    var $active_progress = $(el).find('.progress li.active');

    // if ( $active.length == 0 ) $active = $(self.prefs.element + ' img:last');

    // use this to pull the images in the order they appear in the markup
    var $next =  $active.next().length ? $active.next() : $(el).find('.slides li:first');
    var $next_progress =  $active_progress.next().length ? $active_progress.next() : $(el).find('.progress li:first');

    $active.addClass('last-active');
    $active_progress.removeClass('active');

    // use this to fade the current slide to 0 first
    // $active.animate({opacity: 0}, slide_show_speed, function() {
      $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, self.prefs.speed, function()
        {
          $active.removeClass('active last-active');
        });
      $next_progress.addClass('active');
    // });
  };
  
  $.fn.slideShow.slideClick = function($el) {
    var el = self.prefs.element;
    
    clearInterval(interval);

    var clicked_index = $el.index();

    var $active = $(el).find('.slides li.active');
    var $active_progress = $(el).find('.progress li.active');

    // if ( $active.length == 0 ) $active = $(el).find('li img:last');

    // use this to pull the images in the order they appear in the markup
    var $next = $(el).find('.slides li:nth-child(' + (clicked_index + 1) + ')');
    var $next_progress =  $(el).find('.progress li:nth-child(' + (clicked_index + 1) + ')');

    $active.addClass('last-active');
    $active_progress.removeClass('active');

    // use this to fade the current slide to 0 first
    // $active.animate({opacity: 0}, slide_show_speed, function() {
      $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, self.prefs.speed, function()
        {
          $active.removeClass('active last-active');
        });
      $next_progress.addClass('active');
    // });

    interval = setInterval(function() {self.slideSwitch();}, self.prefs.duration);
  };
  
  /* stop slideshow */
  $.fn.slideShow.stop = function() {
    clearInterval(interval);
    $(self.prefs.element).clearQueue();
  };
  
  /* start slideshow */
  $.fn.slideShow.start = function() {
    interval = setInterval(function() {self.slideSwitch();}, self.prefs.duration);
  };
  
  /* previous slide */
  $.fn.slideShow.previous = function() {
    var el = self.prefs.element;
    
    var $active = $(el).find('.slides li.active');
    var $active_progress = $(el).find('.progress li.active');

    // if ( $active.length == 0 ) $active = $(self.prefs.element + ' img:last');

    // use this to pull the images in the order they appear in the markup
    var $previous =  $active.prev().length ? $active.prev() : $(el).find('.slides li:last');
    var $previous_progress =  $active_progress.prev().length ? $active_progress.prev() : $(el).find('.progress li:last');

    $active.addClass('last-active');
    $active_progress.removeClass('active');

    // use this to fade the current slide to 0 first
    // $active.animate({opacity: 0}, slide_show_speed, function() {
      $previous.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, self.prefs.speed, function()
        {
          $active.removeClass('active last-active');
        });
      $previous_progress.addClass('active');
    // });
  };
})(jQuery);

