(function( $ ){
  $.fn.emAutoSlideshow = function(options){			
			  var opts = $.extend({}, $.fn.emAutoSlideshow.defaults, options);
			//    debug(this);

    // iterate and reformat each matched element
    return this.each(function() {
      $this = $(this);
      // build element specific options
     o = $.meta ? $.extend({}, opts, $this.data()) : opts;
	$this.css({'width':o.width+'px', 'height':o.height+'px', 'overflow': 'hidden'})
	$this.append('<img id="emAutoSlideshowImage" />');
	totalSlides = o.data.length;
	slideflip=undefined;
	currentSlide = Math.floor(Math.random()*totalSlides);
	if(o.autostart) $.fn.emAutoSlideshow.startSlideShow()
    });
  };
		
		function loadImage(i){
		$('#emAutoSlideshowImage').hide();
		$('#emAutoSlideshowImage').load(function () {
            $(this).fadeIn();
        }).error(function () {
            // notify the user that the image could not be loaded
        }).attr('src', i);
	}
	
	function showSlide(s){
		if(s == undefined) return
		loadImage('/admin/uploads/intro/' + s.path);
		showTitle(s.name);
	}
	
		function showTitle(n){
		$this.trigger('new-title',[n]); 
		//$(o.title).html('<h1>' + n + '</h1>')
	}
	
		function nextSlide(){
					var nextSlide = currentSlide + 1; 
					if(nextSlide >= totalSlides)nextSlide=0;
					currentSlide++;
					if(currentSlide >= totalSlides)currentSlide=0;
					showSlide(o.data[currentSlide])
	
	 }
		
		
	  $.fn.emAutoSlideshow.defaults = {
			 	path:'images/',
			 	data:{},
			 	width:100,
			 	height:100,
			 	autostart:true,
			 	title:'#meta',
			 };  
			 
	$.fn.emAutoSlideshow.showTitle = function(n){
		//$(o.title).html('<h1>' + n + '</h1>')
		$this.trigger('new-title', n); 
	};
	
	$.fn.emAutoSlideshow.startSlideShow = function() {		
		showSlide(o.data[currentSlide])
		if(!slideflip)slideflip = setInterval(nextSlide, 3000);
	};
	
	$.fn.emAutoSlideshow.showSlideIndex = function(i){
		showSlide(o.data[i])
	};
	
			 
$.fn.emAutoSlideshow.pauseSlideShow = function() {
    	try{
			clearInterval(slideflip);
			slideflip = undefined;
		}catch(e){}
};
$.fn.emAutoSlideshow.resumeSlideShow = function() {
	try{
		nextSlide();
    	if(!slideflip)slideflip = setInterval(nextSlide, 5000);
	}catch(e){}
};

	})(jQuery);
