
// shows a fullscreen image at the current position,
// with scroll protection 
// takes a src as argument, if omitted, uses the img element
// which is inside the clicked element

function fullscreen(src) {

	if (!Prototype) {
		alert("fullscreen needs prototype to work!");
		return;
	}

	var d = new Element('DIV',{id:"fullscreenImage",
							   style:"background-color: #000000; opacity: 0.5;",
							   "class":"fullscreen"});

	d.img = new Element('IMG',{style:"border: 3px solid #222222"});
	if (typeof src === "string") {
		d.img.src = src;
	} else if (src && src.tagName==="A" && src.firstChild && src.firstChild.src) {
		// take first child
		d.img.src = src.firstChild.src;
	} else {
		alert("fullscreen, no img found!");
		return;
	}
	
	d.repos = function() {
		var vp = document.viewport;

		if (!this.origDim) {
			this.origDim = { width: d.img.width,
							 height: d.img.height };
			this.gap = 50; // the "border" around the image
		}

		var win = vp.getDimensions();
		var dst = {};
		
		if (this.origDim.width > win.width - this.gap * 2 ||
			this.origDim.height > win.height - this.gap * 2) {
			var winAspect = win.width / win.height;
			var imgAspect = this.origDim.width / this.origDim.height;

			if (imgAspect > winAspect) {
				dst.width = win.width - this.gap * 2;
				dst.height = dst.width / imgAspect;
			} else {
				dst.height = win.height - this.gap * 2;
				dst.width = dst.height * imgAspect;
			}
		} else {
			// leave dimensions as they are, if the original 
			// dimensions are smaller than the viewport
			dst.height = this.origDim.height;
			dst.width = this.origDim.width;
		}

		// position overlay
		this.style.position = 'fixed';
		this.style.top = 0; 
		this.style.left = 0; 
		this.style.width = win.width+'px';
		this.style.height = win.height+'px';
		this.style.zIndex = 99;

		// position & resize image
		d.img.style.position = 'fixed';
		d.img.style.width = dst.width + 'px';
		d.img.style.height =  dst.height + 'px';
		d.img.style.top = parseInt(( win.height - dst.height ) / 2) + 'px';
		d.img.style.left = parseInt(( win.width - dst.width ) / 2) + 'px'; 
		d.img.style.zIndex = 100;	
	}

	d.tryToRepos = function() {
		if (d.img.width > 0) {
			d.repos();
		} else {
			// try again later
			d.tryToRepos.delay(0.5);
		}
	}

	d.tryToRepos();

	d.clear = function() {
		d.img.remove();
		d.remove();
	}

	Event.observe(d,"click",function() {
		d.clear();
	});

	Event.observe(d.img,"click",function() {
		d.clear();
	});

	Event.observe(window,"resize", function() { d.repos(); });

	document.body.appendChild(d);
	document.body.appendChild(d.img);
}
