
// 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 isIE6 = Prototype.Browser.IE && easydb.utils.getIEVersion() == 6;

	var d = new Element('DIV',{"id": "fullscreenImage",
							   "class": "fullscreen-image-overlay"});
    
	d.img = new Element('IMG',{"class":"fullscreen-image"});
	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;
		}

        var position = 'fixed';
        var offsY = 0;
        if (isIE6) {
            position = 'absolute';
            offsY = document.documentElement.scrollTop;
        }

		// position overlay
		this.style.position = position;
		this.style.top = offsY;
		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 = position;
		d.img.style.width = dst.width + 'px';
		d.img.style.height =  dst.height + 'px';
		d.img.style.top = (offsY + 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(); });

    if (isIE6) {
        Event.observe(window,"scroll", function() { d.repos(); });
    }

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

