var idx = 0;
var timer = null;

$(function(){
	var url = $('#image img:first').attr('src').replace(/\.jpg/, '_thumb.jpg');
	idx = 0;
	$('#list img').each(function(){
		if($(this).attr('src') == url)
			return false;
		idx++;
		return true;
	});
	
	$('#list').mousemove(function(e){
		var x = (e.clientX - $(this).offset().left) * 100 / $(this).width();
		if(x < 30) {
			list_scroll((x - 30) / 2);
		} else if(x > 70) {
			list_scroll((x - 70) / 2);
		}
	}).mouseout(function(){
		list_scroll(0);
	});
	
	$('#list a').click(function(){
		idx = $('#list a').index(this);
		var url = $('img', this).attr('src').replace(/_thumb/, '');
		
		var load = $('<div style="position:absolute; top:150px; left:309px; z-index:200;"><img src="images/design/loading.gif" alt="" border="0"></div>').appendTo('#image');
		
		var img = $('#image img:first');
		img.css({
			position: 'absolute',
			zIndex: '3'
		});
		
		var i = new Image();
		$(i).load(function(){
			var w = i.width;
			var h = i.height;
			var ratio = Math.min(384 / h, 550 / w);
			
			load.remove();
			var img2 = img.parent().prepend('<img src="' + url + '" style="position:relative; z-index:2; top:'+Math.round((384 - (h * ratio)) / 2)+'px; left:'+Math.round((550 - (w * ratio)) / 2)+'px; width:'+Math.round(w * ratio)+'px; height:'+Math.round(h * ratio)+'px;">');
			img.fadeOut(false, function(){
				img.remove();
			});
			
			list_prev_next();
			delete i;
		});
		i.src = url;
		return false;
	});
	
	$('#img_prev').click(function(){
		idx--;
		$('#list a:eq(' + idx + ')').click();
		return false;
	});
	$('#img_next').click(function(){
		idx++;
		$('#list a:eq(' + idx + ')').click();
		return false;
	});
	
	list_prev_next();
})

function list_prev_next() {
	if(idx > 0)
		$('#img_prev').fadeIn();
	else
		$('#img_prev').fadeOut();
	
	if(idx < $('#list img').length - 1)
		$('#img_next').fadeIn();
	else
		$('#img_next').fadeOut();
}

function list_scroll(off) {
	off = Math.round(off);
	if(timer) {
		timer = window.clearTimeout(timer);
		timer = null;
	}
	if(off) {
		$('#list').scrollLeft($('#list').scrollLeft() + off);
		timer = window.setTimeout(function(){ list_scroll(off); }, 100);
	}
}