var slideswitch = 0;

//Function for images on startpage
function slideSwitch() {
	if(jQuery('#slideshow img').length > 0) {
		var active = jQuery('#slideshow img.active');
	
	    if ( active.length == 0 ) active = jQuery('#slideshow img:last');
	
	    // use this to pull the images in the order they appear in the markup
	    var next = jQuery(active).next().length ? jQuery(active).next() : endSlideSwitch();
	
	    jQuery(active).addClass('last-active').removeClass('active').hide(0);
		
		
	    	jQuery(next).show(0).addClass('active').removeClass('last-active');
		
	}
}

//Function to end slideshow
function endSlideSwitch () {

	clearInterval( slideswitch );
	
	jQuery('#uiw').stop().fadeOut(500, function(){
		jQuery('#uiw, #putext, #slideshow_wrapper').remove();
	});

}

//Function that toggles visibility of submenus
function showsubs ( subid ) {

	jQuery('#submenu_' + subid).slideToggle(300);

}

//Function to get id of active image
function getActiveID() {
	
	var active = jQuery('#gallery-image-wrapper div.active').attr('id');

	var id = active.substring(6);
	
	return parseFloat(id);

}

//Function to show an image
function showimage( imgid ) {
	
	jQuery('#gallery-image-wrapper').stop().fadeTo(300,0,function(){
		jQuery('.image').hide(0).removeClass('active');
		jQuery('#image_'+imgid).show(0).addClass('active');
		var page = Math.ceil(parseFloat(imgid)/6);
		jQuery('#thumbs').trigger('goto', [ page ] );
		jQuery('#gallery-image-wrapper').fadeTo(300,1);
	});
	
}

//Function to show next image
function nextimage() {
	var curItem = getActiveID();
	var total = jQuery("#gallery-image-wrapper .image").length;
	
	if( curItem == total ) {
		showimage(1);
	} else {
		showimage(curItem+1);
	}
}

//Function to show preivous image
function previmage() {
	var curItem = getActiveID();
	var total = jQuery("#gallery-image-wrapper .image").length;
	
	if( (curItem-1) < 1 ) {
		showimage(total);
	} else {
		showimage(curItem-1);
	}
}

//When document is ready, execute gallery function
jQuery(document).ready(function($) {
	
	//Center elements with class "center"
	$('#loading').center();
		
	//When all images loaded
	$(window).load( function() {
		
		if($('#gallerywrapper').length > 0) {
			
			$('#thumbs').infiniteCarousel();
			
			$('#next').click(function(){
				nextimage();
			});
			
			$('#previous').click(function(){
				previmage();
			});
			
			//Add key events
			$(document).keyup(function (e) {
				if(e.which == 37) {
					previmage();
				}
				if(e.which == 39) {
					nextimage();
				}
			});
		}
		
		if($('#putext').length > 0) {
			$('#slideshow_wrapper').center('absolute');
			$('#putext').stop().animate({opacity: 1.0}, 500).fadeOut(600, function(){
				slideswitch = setInterval( "slideSwitch()", 300 );
			});
		} else if($('#uiw').length > 0) {
			$('#uiw').stop().fadeOut(500, function(){
				$('#uiw').remove();
			});
		}
	});

});