var loadingImageURL = 'http://www.milano-tokyo.com/_new/common_image/loadingAnimation.gif';

function changeImage(url) {
	var target = $('#bigImage');
	var maxWidth = 490;
	var maxHeight = 326;
	var image = new Image();
	$(image).css({ display: 'none' });
	
	$(loadingImage).css({ position: 'relative', top: Math.floor((maxHeight - loadingImage.height) / 2) });
	target.empty();
	target.append(loadingImage);
	
	image.onload = function() {
		imageInit(this, maxWidth, maxHeight);
		$(target).empty();
		$(target).append(this);
		$(this).fadeIn();
	}
	
	image.src = url;
}

function imageInit(image, maxWidth, maxHeight) {
	calcImageSize(image, maxWidth, maxHeight, false);

	if (maxHeight > image.height) {
		$(image).css({
			'position': 'relative',
			'top': Math.floor((maxHeight - image.height) / 2)
		});
	}
}

function calcImageSize(image, maxWidth, maxHeight, zoom)
{
	var width = image.width;
	var height = image.height;

	if (zoom == undefined) {
		zoom = false;
	}
	
    if (maxHeight > 0 && (zoom || height > maxHeight)) {
        width = calcWidth(width, height, maxHeight);
        height = maxHeight;

        if (maxWidth > 0 && width > maxWidth) {
            height = calcHeight(width, height, maxWidth);
            width = maxWidth;
        }
    }

    if (maxWidth > 0 && (zoom || width > maxWidth)) {
        height = calcHeight(width, height, maxWidth);
        width = maxWidth;

        if (maxHeight > 0 && height > maxHeight) {
            width = calcWidth(width, height, maxHeight);
            height = maxHeight;
        }
    }

    image.width = width;
    image.height = height;
}

function calcHeight(baseWidth, baseHeight, newWidth)
{
    var ratio = (100 * newWidth) / baseWidth;
    return (baseHeight * ratio) / 100;
}

function calcWidth(baseWitdh, baseHeight, newHeight)
{
    var ratio = (100 * newHeight) / baseHeight;
    return (baseWitdh * ratio) / 100;
}

$(function() {
	loadingImage = new Image();
	loadingImage.src = loadingImageURL;
	AjaxZip2.JSONDATA = 'http://www2.milano-tokyo.com/cgi-bin/js/ajaxzip2data';
	
	var image = [];
	var anchor = [];

	$('ul.parent li a').each(function(i) {
		image[i] = new Image();
		anchor[i] = this;
		$(image[i]).css({ display: 'none' });
		$(this).append(loadingImage);
		
		image[i].onload = function() {
			imageInit(this, 135, 90);
			$(anchor[i]).empty();
			$(anchor[i]).append(this);
			$(this).fadeIn();
		}
		
		image[i].src = $('img', $(this)).attr('src');
	});
	
	$('ul.vertical li a').each(function(i) {
		image[i] = new Image();
		anchor[i] = this;
		$(image[i]).css({ display: 'none' });
		$(this).append(loadingImage);
		
		image[i].onload = function() {
			imageInit(this, 100, 66);
			$(anchor[i]).empty();
			$(anchor[i]).append(this);
			$(this).fadeIn();
		}
		
		image[i].src = $('img', $(this)).attr('src');
	});

});