var boxID = '#galleryBig';
var imagesQ = 0;
var loadedQ = 0;
var imagesPosUpdatedQ = 0;
var fadeTime = 200;

function initNav() {
	var nav = document.getElementById("nav");
	if(nav) {
		var lis = nav.getElementsByTagName("li");
		for (var i=0; i<lis.length; i++) {
			lis[i].onmouseover = function() {
				this.className += " hover";
			}
			lis[i].onmouseout = function() {
				this.className = this.className.replace(" hover", "");
			}
		}
	}
}
if (document.all && !window.opera) attachEvent("onload", initNav);




$(document).ready(function(){

$('#mycarousel').jcarousel({
    	wrap: 'last',
		scroll:3
});


	$('#galleryBig img').hide();
	preloadImages();
	
	$('#galleryThumbs li.galleryThumb').eq(0).addClass('active');
	$('#galleryThumbs li.galleryThumb').click( function(){
		
		if(!$(this).hasClass('active')){
		
		el = $(this).get(0);
		
		n = $('#galleryThumbs li.galleryThumb').index(el);
		
		dList = $('#galleryDescription div');
		iList = $('#galleryBig img');
		tList = $('#galleryThumbs .galleryThumb');
		
		dList.removeClass('active');
		dList.eq(n).addClass('active');
		
		
		
		iList.fadeOut(fadeTime);
		iList.eq(n).fadeIn(fadeTime);		
			
		tList.removeClass('active');
		tList.eq(n).addClass('active');
		
		}    
		return false;
	});
	
});

preloadImages =  function (){
    imagesQ = $(boxID+' img').length;
    $(boxID).append('<div id="preload"></div>');
    $(boxID+' img').each(function(el){
		var oldImg = $(this);
		var newImg = new Image();
		var imgSrc = oldImg.attr('src');
		if(oldImg.get(0).complete||oldImg.get(0).readyState == 'complete'||oldImg.get(0).readyState == 'loaded'){
			loadedQ++;
			updateImagePosition(oldImg);
		} else {			
			jQuery(newImg).load(function(){				
				updateImagePosition(oldImg);
			});
			newImg.src = imgSrc;
		}
    });
	
	if(imagesQ<=7){
		$('.jcarousel-next, .jcarousel-prev').width(0);
	}
}
 

updateImagePosition = function(img){	
	curImg = img;	
			ind = $(boxID+' img').index(curImg);			
			w = -curImg.width()/2;
			h = -curImg.height()/2;			
			curImg.css("margin-left", w);	
			curImg.css("margin-top", h);				
			imagesPosUpdatedQ++;
			if(imagesPosUpdatedQ>=imagesQ) removePreload();  
}

removePreload = function(){
	$('#preload').fadeOut(function(){
				$(this).remove(); 
	});
	$(boxID+' img:first').fadeIn(fadeTime);
}


