var current = 1;
var last = 0;

jQuery.fn.slideshow = function(options) {
	var pauseState = 0;

    var timer = '';
	
    var settings = {
        timeout: '3000',
        pauselink: null,
        playcallback: null,
        pausecallback: null
    }
    if (options){
		jQuery.extend(settings, options);
	}

    var change = function() {
        if (pauseState == 0) {
			//Hide all to start with
            HideAll();
			
			//Set the current indicator
			var square = parseInt(current);
			
			//Show the next
			ShowHide(last,current);

			//Work out the next move
			TransitionNext();

			//Start the change
			timer = setTimeout(change, settings.timeout);

			//Update the indicator
            UpdateTheIndicator(square);
        }
    }
	
	//Add an onclick listener
    $('#fader_info_panel img').click(function(e) {
		var clicked = e.target.id.split('_')[1];
		if(clicked!=current){
			clearTimeout(timer);
			HideAll();	
			current = clicked;		
			ShowHide(last,current);
			UpdateTheIndicator(parseInt(current));
			last=current;
		}		
    });
	
	function HideAll(){
		for (var i = 0; i < slides.length; i++) {
			jQuery(slides[i]).css('display', 'none');
		}	
	}
	
	function TransitionNext(){
		if ((current + 1) < slides.length) {
			current = current + 1;
			last = current - 1;
		}
		else {
			current = 0;
			last = slides.length - 1;
		}	
	}
	
	function UpdateTheIndicator(square){
		var counter = document.getElementById('fader_bg_number');
		if (counter != undefined) {
			counter.innerHTML = parseInt(square +1);
		}

		for (var i = 0; i < slides.length; i++) {
			if (i == square) {
				if (document.getElementById('square_' + square) != undefined) {
					document.getElementById('square_' + square).style.background = '#DF99A6';
				}
			} else {
				if (document.getElementById('square_' + i) != undefined) {
					document.getElementById('square_' + i).style.background = 'white';
				}
			}
		}	
	}
	
	function ShowHide(last,current){
		//Re-show the last one then fade the new one in over the top
		jQuery(slides[last]).css('display', 'block').css('zIndex', '0');
		jQuery(slides[current]).css('zIndex', '1').fadeIn(1200);
	}
	
    this.css('position', 'relative');
    var slides = this.find('.img_div').get();
    jQuery.each(slides, function(i) {
        jQuery(slides[i]).css('zIndex', slides.length - i).css('position', 'absolute').css('top', '0').css('left', '0');
    });

     timer = setTimeout(change, settings.timeout);

    return this;
};
