var slideFlag = -1;
var slider;
var allImages;
$(document).ready(function(){
	
	
	$('img#mainimage').load(function(){
		
		$('img#mainimage').fadeIn('fast');
	})
	
	$('.thumbs a').click(function(){
		return false;
	})
	$('.thumbs a img').click(function(){
		
		if( $('#currentimage').html() ==  $(this).get(0).id ) return false;
		$('img#mainimage').fadeOut('fast');
		$('img#mainimage').get(0).src = $(this).get(0).src.replace('w=79;h=63', 'w=338;h=240');
		$('#imagetitle').html($(this).get(0).alt);
		$('#currentimage').html($(this).get(0).id);
	
//		$('.gallery').children('img:first').fadeIn('slow'); // !!
		return false; 
	})
	$('div.pages a.pages').click(function(){
		var page = parseInt( $(this).html() );
//		console.log( page );
		$('div.pages').children('a').each(function(i){
			$(this).removeClass('current');
			$(this).addClass('pages');
		})
		$(this).addClass('current');
		$(this).removeClass('pages');
		$('div.pages').children('a:last').removeClass('current');
		$('div.pages').children('a:last').removeClass('pages');
		$('div.thumbs a').each(function(i){
			$(this).hide();
		})
		$('div.thumbs a.page_'+page).show();
		
		return false;
	})
	$('div.pages a.current').click(function(){
		var page = parseInt( $(this).html() );
//		console.log( page );
		$('div.pages').children('a').each(function(i){
			
			$(this).removeClass('current');
			$(this).addClass('pages');
		})
		$(this).addClass('current');
		$(this).removeClass('pages');
		$('div.pages').children('a:last').removeClass('current');
		$('div.pages').children('a:last').removeClass('pages');
		$('div.thumbs a').each(function(i){
			$(this).hide();
		})
		$('div.thumbs a.page_'+page).show();
		
		return false;
	})
	$('a.slide').click(function(){

		slideFlag = slideFlag * -1;
			
		allImages = $('div.thumbs a');	
//		console.log(  );
		if( slideFlag > 0 ){
			slider = setTimeout(slideShow, 5000);
		} else {
			clearTimeout(slider);
		}		
		
		
		
		return false;
	})
})



function slideShow(){
	var currentImage = parseInt( $('#currentimage').html() );
	
	var image = $('div.thumbs a img').get(currentImage);
	
//	console.log(image);
	if( !image ) {
		slideFlag = slideFlag * -1;
//		console.log('stop timer'); 
		clearTimeout(slider);
		return;
	}
//	console.log('in timer');
	
	$('img#mainimage').fadeOut('fast');
	$('img#mainimage').get(0).src = image.src.replace('w=79;h=63', 'w=338;h=240');
	
	$('#imagetitle').html(image.alt);
	$('#currentimage').html(image.id);
//	if( isImageOk( $('.gallery').children('img:first') ) ) $('.gallery').children('img:first').fadeIn('slow');
//	$('.gallery').children('img:first').fadeIn('slow'); // !!

	slider = setTimeout(slideShow, 5000);
}


