//gallery vars
var SELECTED_THUMB=-1;
var GALLERY_PHOTOS;

//gallery functions
function initGallery(photos) {
	GALLERY_PHOTOS = photos;
	jQuery(document).ready(function() {
	    jQuery("#carousel").jcarousel({
				scroll: 3,
  	    vertical:true,
	     	scrollAnimation: "slow",
				size: GALLERY_PHOTOS.length,	    
        itemLoadCallback: {onBeforeAnimation: my_itemLoadCallback},
        itemVisibleInCallback: {onAfterAnimation: my_itemVisibleInCallback}
	    });
	});
}

function clearThumb() {Element.hide('selected_thumb');}

function moveIndicator(x,y) {
	var selected = $('selected_thumb');
	selected.style.top =  x + 'px';
	selected.style.left =  y + 'px';
	selected.style.display = 'block';
}

//thumbnails start at 1 because the carousel starts at 1
function selectPhoto(id) {//highlights thumbnail
	SELECTED_THUMB = parseInt(id.substring(5,id.length));
	var off = Position.cumulativeOffset($(id));
	moveIndicator(parseInt((off.last())),parseInt((off.first())));
}

function showPhoto(path) {
	Element.hide('large_gallery_photo');
	document.getElementById('large_gallery_photo').src=path;
	new Effect.Appear('large_gallery_photo', { duration: 0.9 });
}

function getItemHTML(item, counter) {
	var img = new Image();
	img.src = item.url;//preload
  return '<a id="photolink' + counter + '" href="javascript:showPhoto(\'' + item.largeurl +'\');selectPhoto(\'photo'+ counter +'\');"><img id="photo' + counter + '" src="' + item.url + '" alt="' + item.url + '" /></a>';
}

function my_itemVisibleInCallback(carousel, obj, index, state) {
	if (SELECTED_THUMB != -1) {
		var found = false;
		var last = carousel.last;
		if (state == 'next') {if (carousel.last == (SELECTED_THUMB)) {	found = true;}}
		if (!found) {if (state == 'prev') {if (carousel.first == (SELECTED_THUMB)) {found = true;}}}	
		if (!found) {if (index == SELECTED_THUMB) {	found = true;}}
    if (found) { selectPhoto('photo'+(SELECTED_THUMB)); }}
}

function my_itemLoadCallback(carousel, state) {//load 4 at a time
	clearThumb();
	var start = carousel.first;
	if (start == null) start = 1;
	if (state == 'next') start++;
    for (var i = 1; i < 5; i++) {
		if (state != 'prev') {
			if (!carousel.has(start)) {
      	if (start > GALLERY_PHOTOS.length) {break;}
					carousel.add(start, getItemHTML(GALLERY_PHOTOS[start-1],(start)));
		    }
	    }
   		start++;
    }
}