var interval=0;
var limage=6;
var oimage=7;
var final=7;
var currentimg=1;

function slideShow() {
	clearInterval ( interval );
	//Set the opacity of all images to 0
	$('#hslideshow span').stop(true, true);
	$('#hslideshow span').css({opacity: 0.0});
	
	currentimg=1;
	//Get the first image and display it (set it to full opacity)
	$('#hslideshow span').removeClass('show');
	$('#hslideshow span:first').css({opacity: 1.0});
	$('#hslideshow span:first').addClass('show')
	
	$('.replay').hide();

	//Call the gallery function to run the slideshow, 6000 = change to next image after 6 seconds
	interval=setInterval('gallery()',5000);

}

function gotoImage(img,oimg){
	

	var current =  $('#hslideshow #p'+oimg);;

	var next = $('#hslideshow #p'+img);
	
	next.css({opacity: 0.0})
	.animate({opacity: 1.0}, 700);

	//Hide the current image
	current.animate({opacity: 0.0}, 700);

}

function loopLast(){
	clearInterval(interval);
	if (limage==7){ 
		limage=6;
		oimage=7;
	}else{
		limage=7;
		oimage=6;
	}
	gotoImage(limage,oimage);
	interval=setInterval('loopLast()',2000);
	
}

function gallery() {

	//if no IMGs have the show class, grab the first image
	 var current =  $('#hslideshow #p'+currentimg);
	 currentimg++;
	 var next= $('#hslideshow #p'+currentimg);
	// var current = ($('#hslideshow span.show')?  $('#hslideshow span.show') : $('#hslideshow span:first'));

	//Get next image, if it reached the end of the slideshow, rotate it back to the first image
	//var next = ((current.next().length) ? ((current.next().hasClass('caption'))? $('#hslideshow span:first') :current.next()) : 0);
	
	if (currentimg==(final-1)){
		clearInterval(interval);
		interval=setInterval('gallery()',2000);	
		
	}
        if (currentimg==final){
            clearInterval(interval);
			$('.replay').show();
			loopLast();
        }else{
            //Get next image caption
            var caption = next.find('img').attr('rel');

            //Set the fade in effect for the next image, show class has higher z-index
            next.css({opacity: 0.0})
            .addClass('show')
            .animate({opacity: 1.0}, 1000);

            //Hide the current image
            current.animate({opacity: 0.0}, 1000)
            .removeClass('show');
        }
}

$(document).ready(function() {

	//Execute the slideShow
	slideShow();

});

