/*
* Author:      Marco Kuiper (http://www.marcofolio.net/)
*              Sylvain Papet (http://www.com-ocean.com/)
*/

(function($) {
  $.bgimgSlideshow = {version: '1.0.0'};

  $.fn.bgimgSlideshow = function(options) {
    options = jQuery.extend({
      slideshowSpeed: 6000,
      photos : [],
      markup: '<div id="background">\
  <div id="bis_images">\
    <div id="bis_image1" class="bis_image"></div>\
    <div id="bis_image2" class="bis_image"></div>\
  </div>\
  <div id="bis_container">\
    <div id="bis_caption">\
      <p class="bis_title">\
         <a href="#" id="bis_titlelink"></a>\
      </p>\
    </div>\
  </div>\
</div>',
    createThumbs : true
      },options);

    var interval;
    var activeContainer = 1;
    var currentImg = 0;
    var started = false;
    var animating = false;
    var currentZindex = -1;

    var image_cache = [];

    $.bgimgSlideshow.preLoadImage = function() {
      var args_len = arguments.length;
      for (var i = args_len; i--;) {
        var cacheImage = document.createElement('img');
        cacheImage.src = arguments[i];
        image_cache.push(cacheImage);
      }
    }

    $.bgimgSlideshow.createThumbs = function(){
        $('#bis_nav').append($('<div />').addClass('nav-items'));

        $.each(options.photos, function(i, v){
            $('.nav-items').append($('<a />')
            .addClass('nav-item')
            .html($('<span />').text(i))
            .attr('href', v.image));
                
        })

        $('.nav-item', $('#bis_nav')).live('click', function(e){
            e.preventDefault();
            var currElem = $(this);
            $.each(options.photos, function(k, v){
                if(currElem.attr('href') == v.image){
                    currentImg = k;
                    $.bgimgSlideshow.navigate('jump');
                }
            })
        })
    }

    $.bgimgSlideshow.preLoadPhotoObjects = function(photoObjects) {
      for(i in photoObjects)
      {
        $.bgimgSlideshow.preLoadImage(photoObjects[i].image, photoObjects[i].image);
      }
      
      if(options.createThumbs){
          $.bgimgSlideshow.createThumbs();
      }
      
    }

    $.bgimgSlideshow.initialize = function() {
      $('#slide-container').prepend(options.markup);
      $.bgimgSlideshow.preLoadPhotoObjects(options.photos);

      // Backwards navigation
      $("#bis_back").click(function() {
      	$.bgimgSlideshow.stopSlideshow();
      	$.bgimgSlideshow.navigate("back");
      });

      // Forward navigation
      $("#bis_next").click(function() {
        $.bgimgSlideshow.stopSlideshow();
      	$.bgimgSlideshow.navigate("next");
      });

      $("#bis_control").click(function(){
        if(started)
        {
          $.bgimgSlideshow.stopSlideshow();
        }
        else
        {
          $.bgimgSlideshow.startSlideshow();
        }
      });
      $.bgimgSlideshow.startSlideshow();
    };

    $.bgimgSlideshow.navigate = function(direction) {
    	// Check if no animation is running. If it is, prevent the action
    	if(animating) {
    		return;
    	}

        var jumpTo;

    	// Check which current image we need to show
    	if(direction == "next") {
    		currentImg++;
    		if(currentImg == options.photos.length + 1) {
    			currentImg = 1;
    		}

                jumpTo = currentImg - 1;
    	} 
        
        if(direction == 'back') {
            currentImg--;
            if(currentImg == 0) {
                currentImg = options.photos.length;
            }

            jumpTo = currentImg - 1;
    	}

        if(direction == 'jump'){
            jumpTo = currentImg;
        }

    	// Check which container we need to use
    	var currentContainer = activeContainer;
    	if(activeContainer == 1) {
    		activeContainer = 2;
    	} else {
    		activeContainer = 1;
    	}

    	$.bgimgSlideshow.showImage(jumpTo, currentContainer, activeContainer);
    };

    $.bgimgSlideshow.showImage = function(numImg, currentContainer, activeContainer) {
      var photoObject = options.photos[numImg];
    	animating = true;

    	// Make sure the new container is always on the background
    	currentZindex--;

    	// Set the background image of the new active container
    	$("#bis_image" + activeContainer).css({
    		"background-image" : "url(" + photoObject.image + ")",
    		"display" : "block",
    		"z-index" : currentZindex,
                'position' : 'absolute',
                'top' : 0,
                'left' : 0,
                'height' : 415,
                'width' : 2560
    	});

      if(options.createThumbs){
          $('.nav-item').removeClass('item-active');
          $('.nav-item').each(function(i){
              if($(this).attr('href') == photoObject.image){
                  $(this).addClass('item-active');
              }
          })
      }

      if(photoObject.url)
      {
        $("#bis_caption p").html('<a class="image_link" href="'+photoObject.url+'"><span>'+photoObject.title+'</span></a>');
      }
      else
      {
        $("#bis_caption p").html(photoObject.title);
      }

    	// Fade out the current container
    	// and display the header text when animation is complete
    	$("#bis_image" + currentContainer).fadeOut(function() {
    		setTimeout(function() {
    			animating = false;
    		}, 500);
    	});
    };

    $.bgimgSlideshow.stopSlideshow = function() {
    	// Change the background image to "play"
      $("#bis_control").css({ "background-image" : "url(img/btn_play.png)" });
    	// Clear the interval
    	clearInterval(interval);
      started = false;
    };

    $.bgimgSlideshow.startSlideshow = function() {
      $("#bis_control").css({ "background-image" : "url(img/btn_pause.png)" });
    	$.bgimgSlideshow.navigate("next");
    	interval = setInterval(function() { $.bgimgSlideshow.navigate("next"); }, options.slideshowSpeed);
      started = true;
    };

    $.bgimgSlideshow.initialize();
    return this;
  }

})(jQuery);

