downloaded_images = Array();

window.addEvent('load', function () {
	if ($('controls')) {
		
		img = $('gallery_image');
		
		downloaded_images[img.src] = img;
		
		$('panes').getElements('a.a_block').each(function(el) {
			el.addEvent('click', function(event) {
				
				image_id = el.rel;
				image = image_data['images'][image_id];
				
				if (image != false) {
					event.stop();
					
					gallery_href = image_data['basedir']+image['p'];
												
					if ($('gallery_image').src != gallery_href) {
						loadImage(gallery_href);
						if ($('gallery_image_anchor')) {
							$('gallery_image_anchor').set('href', el.href);
							rel_string = 'lightbox[gallery';
							if (image['w'] && image['h']) {
								rel_string += ' '+image['w']+' '+image['h'];
							}
							rel_string += ']';
							$('gallery_image_anchor').set('rel', rel_string);							
							$('current_text').set('html', image['d']);
							$('current_title').set('html', image['t']);
						}
					}
				}								
			});			
		});
		
		myTabs = new SlidingTabs('buttons', 'panes');
	
		$('previous').addEvent('click', myTabs.previous.bind(myTabs));
		$('next').addEvent('click', myTabs.next.bind(myTabs));
		window.addEvent('resize', myTabs.recalcWidths.bind(myTabs));
	}
	
	if ($('colors')) {
		$('_color_map').getElements('area').each(function(el) {
			el.addEvent('click', function(event) {
				event.stop();
				
				src = $('gallery_image').src;
				
				array = src.split('_');
				href = src.replace(array[1], el.alt+'.jpg');
				loadImage(href);
			});			
		});

//		alert(.getElements(''););
	}
});

function loadImage(href) {
	if (img = downloaded_images[href]) {
		replaceImage(img);
	} else {
//		console.log('loading');
		img = new Asset.image(href, {id: 'gallery_image', onload: replaceImage, onError: replaceImageError });
	}	
}

function replaceImage(img) {
//	console.log('done');
	downloaded_images[img.src] = img;
	img.replaces($('gallery_image'));
}

function replaceImageError(error)
{
	alert(error);	
}