/* scriptaculous gallery 0.5
020708 - Vince Lee */
function handle_page_change() {

	var existing_options_array = $('gallery-thumbs').childElements();
	for(i = 0; i < existing_options_array.length; i++) {
		$(existing_options_array[i]).remove();
	}

	var imageIndex = 0;
	imageArrayIndex = (pageIndex * totalImagesToDisplay) - totalImagesToDisplay;
	do  {
		var new_li = Builder.node('li');
		var new_image = Builder.node('img', {
			id: 'thumbnail' + imageArrayIndex,
			src: folderToCheck + 'thumb/' + imagesArray[imageArrayIndex],
			alt: '',
			onclick: 'handle_image_change(' + imageArrayIndex + '); return false;'
		});
		new_li.appendChild(new_image);
		$('gallery-thumbs').appendChild(new_li);
	
		imageIndex++;
		imageArrayIndex++;	
	}while((imageIndex < totalImagesToDisplay)&&(imageArrayIndex < imagesArray.length));
	
	handle_image_change((pageIndex * totalImagesToDisplay) - totalImagesToDisplay);
	manage_gallery_nav();
}	

function manage_gallery_nav() {
	if(pageIndex == 1) {
		$('prev-images').hide();
	}else if(pageIndex * totalImagesToDisplay >= imagesArray.length) {
		$('next-images').hide();
	}else {
		$('prev-images').show();
		$('next-images').show();
	}
}

function handle_prev() {
	if(pageIndex > 1) {
		pageIndex--;
		handle_page_change();
	}
}
function handle_next() {
	if(pageIndex * totalImagesToDisplay < imagesArray.length) {
		pageIndex++;
		handle_page_change();
	}
}


function handle_image_change(image_index_to_display) {
	Effect.Fade($('image-container'), {afterFinish: function () { load_image(image_index_to_display) } });
}

function load_image(image_index_to_display) {

	var existing_options_array = $('image-container').childElements();
	for(i = 0; i < existing_options_array.length; i++) {
		$(existing_options_array[i]).remove();
	}
	
	var new_image = Builder.node('img', {
		id: 'main-image',
		src: folderToCheck + 'large/' + imagesArray[image_index_to_display],
		alt: ''
	});
	$('image-container').appendChild(new_image);
	
	Event.observe($('main-image'), 'load', image_loaded);
}

function image_loaded() {
	Effect.Appear($('image-container') );
}

