var is_shown = '';
var the_image;
var loading_shown = false;
var loading_image = new Image();
loading_image.src = '/images/loading.jpg';

function load_media(which_img) {
	if (is_shown != which_img) {
		the_image = new Image();
		the_image.src = media[which_img];
		
		if (the_image.complete) {
			setup_media();
			is_shown = which_img;
			loading_shown = false;
		} else {
			is_shown = 'loading';
			show_loading();
			var t = setTimeout("load_media('" + which_img + "')", 1000);
		}
	}
	
}

function setup_media() {
	var max_width = 700;
	
	var pic_w = the_image.width;
	var pic_h = the_image.height;
	
	if (pic_w > max_width) {
		scale_factor = max_width / pic_w;
		pic_w = max_width;
		pic_h = pic_h * scale_factor;
	}

	if (is_shown != '') {
		fade_out.start();
		is_shown = '';
		var t = setTimeout("show_media('" + the_image.src + "', '" + pic_w + "', '" + pic_h + "')", 1010);
		//show_media(the_image.src, pic_w, pic_h);
	} else {
		show_media(the_image.src, pic_w, pic_h);
	}
}

function show_media(src, width, height) {
	//GET DOCUMENT ELEMENTS
	var media_viewer = document.getElementById('media_viewer');
	var media_space = document.getElementById('media_space');
	
	//SET THE VIEWER WIDTH AND HEIGHT
	var viewer_width = Number(width) + 10;
	var viewer_height = Number(height) + 10;
	
	//FIGURE OUT THE WINDOW WIDTH, HEIGHT AND SCROLL POSITION
	var win_h;
	var win_w;
	var scroll_y;
	if (parseInt(navigator.appVersion)>3) {
		if (navigator.appName.indexOf("Microsoft") != -1) {
			scroll_y = document.body.scrollTop;
			win_w = document.body.offsetWidth;
			win_h = document.body.offsetHeight;
		} else {
			scroll_y = window.pageYOffset;
			win_w = window.innerWidth;
			win_h = window.innerHeight;
		}
	}
	
	//CENTER IN THE WINDOW, ACCOUNTING FOR SCROLLING
	x = (win_w - width) / 2;
	y = scroll_y + (win_h - height) / 2;

	//SIZE AND POSITION THE DIV
	media_viewer.style.left = x + 'px';
	media_viewer.style.top = y + 'px';
	media_viewer.style.width = (viewer_width) + 'px';
	media_viewer.style.height = (viewer_height) + 'px';
	
	//SIZE THE IMAGE
	media_space.width = width;
	media_space.height = height;
	media_space.src = src;
	
	fade_in.start();
}

function hide() {
	if (is_shown != '') {
		is_shown = '';
		fade_out.start();
		var t = setTimeout("move_away()", 1010);
	}
}

function move_away() {
	var media_viewer = document.getElementById('media_viewer');
	media_viewer.style.width = "1px";	
	media_viewer.style.height = "1px";	
}

function show_loading() {
	if (!loading_shown) {
		show_media(loading_image.src, loading_image.width, loading_image.height);
		loading_shown = true;
	}
}

