function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}
var gallery = {
	config : {
		theLinks : "gallery",
		lastClicked : ""
	},
	startUp : function() {
		var galleryLinks = document.getElementsByTagName("a");
		for (i=0; i<galleryLinks.length; i++){
			if (galleryLinks[i].className == gallery.config.theLinks) {
				var theSpan = galleryLinks[i].getElementsByTagName("span");
				theSpan[0].style.display = "none";
			}
		}
	},
	getBrowserWidth : function(){
		if (window.innerWidth){
			return window.innerWidth;
		}	
		else if (document.documentElement && document.documentElement.clientWidth != 0){
			return document.documentElement.clientWidth;
		}
		else if (document.body){
			return document.body.clientWidth;
		}		
			return 0;
	},
	findPos : function(obj){
		var curleft = curtop = 0;
		if (obj.offsetParent) {
			do	{
				curleft += obj.offsetLeft;
				curtop += obj.offsetTop;
			}	while (obj = obj.offsetParent);
		}
		return [curleft,curtop];
	},
	init : function(){
		gallery.startUp();
		var galleryLinks = document.getElementsByTagName("a");
		for (i=0; i<galleryLinks.length; i++){
			if (galleryLinks[i].className == gallery.config.theLinks) {
				galleryLinks[i].onclick = function() {
					if (this != gallery.lastClicked) {
						gallery.startUp();
					}
					
					var theSpan = this.getElementsByTagName("span");
					var position = gallery.findPos(this);
					theSpan[0].style.display = (theSpan[0].style.display === "none") ? "block" : "none";
					theSpan[0].style.position = "absolute";
					
					//Make sure we don't go past the bounds of the browser width
					var theWidth = theSpan[0].offsetWidth;
					var browserWidth = gallery.getBrowserWidth();
					if (browserWidth < 800) {
						var posLeft = (browserWidth - theWidth) / 2;	
					} else{
						var posLeft = (browserWidth - theWidth - 200 > position[0]) ? position[0] - 200 : position[0]- 350 ;
					}
					var posTop = position[1] - 200 > 0 ? position[1] - 200 : 0;
					theSpan[0].style.top  = posTop + "px";
					theSpan[0].style.left = posLeft + "px";
					
					//Set our lastclicked element
					gallery.lastClicked = this;
					return false;
				}
			}
		}
	}
}
addLoadEvent(gallery.init);