function initIZoom() { new iBox().initZoom(); }
function iBox()
{
	// internal and css id's
	this.OverlayID 						= 'jsIBoxOverlay';
	this.OverlayBackgroundID 			= 'jsIBoxOverlayBackground';
	this.OverlayFolderPanelID 			= 'jsIBoxOverlayFolderPanel';
	this.OverlayImageContainerID		= 'jsIBoxOverlayImageContainer';
	this.OverlayLoadFolderImageClass 	= 'jsIBoxFolderImageLoad';
	this.OverlayLoadImageClass 			= 'jsIBoxImageLoad';
	this.OverlayFolderImageClass 		= 'jsIBoxFolderImage';
	this.OverlayImageClass 				= 'jsIBoxImage';
	this.OverlayImageSelectionPrefix	= 'jsIBoxImageSelID_';
	this.LoaderForImage					= '/js/ibox/iboxload.gif';
	this.LoaderForFolderImage			= '/js/ibox/iboxloadersmall.gif';
	this.OverlayOpacity = 75;
	this.OverlayFadeStep = 20;
	this.OverlayFadeSpeed = 50;
	this.Overlay = null;
	this.OverlayBlendTimer = null;
	this.Panel = null;
	this.Imagecontainer = null;
	this.ZoomImage = null;
	this.MediaPath = null;
	this.MediaFolders = [];
	this.Media = [];
	this.SelectedMedia = null;
    this.SelectedImagePath = null;
	this.LastImageContainerTarget = '';
	this._isFoldersGenerated = false;
	this.body = null;
	this.GalleryTarget = null;
	
	this.init = function(mediaPath)
	{
		this.createOverlay();
		this.MediaPath = mediaPath;
		//this._findLinks();
		return this;
	};
	
	this.initZoom = function()
	{
		this.createOverlay();
		this._findZoomLinks();
		return this;
	};
	
	this.initGallery = function(galleryContainerID, galleryTargetImageID)
	{
		this.GalleryTarget = document.getElementById(galleryTargetImageID);
		this._findGalleryLinks(galleryContainerID);
		return this;
	};
	
	this.createOverlay = function()
	{
		var self = this;
		this.body = document.getElementsByTagName("body").item(0);
		
		var overlay = document.createElement("div");
		overlay.className = this.OverlayID;
		overlay.style.visibility = 'hidden';
		// overlay.style.opacity = 0; // fade bug
		overlay.onclick = function () { self.Hide(); };
		if (window.addEventListener) { overlay.addEventListener("click", function() { self.Hide(); }, false); }
		else { overlay.attachEvent("onclick", function() { self.Hide(); } ); }
			
		var background = document.createElement("div");
		background.className = this.OverlayBackgroundID;
		background.style.position = 'fixed';
		background.style.left = '0px';
		background.style.top = '0px';		
		background.style.width = '100%';
		background.style.height = '100%';
		background.style.margin = '0px';
		background.style.padding = '0px';
		background.onclick = function () { self.Hide(); };
		if (window.addEventListener) { background.addEventListener("click", function() { self.Hide(); }, false); }
		else { background.attachEvent("onclick", function() { self.Hide(); } ); }

		overlay.appendChild(background);

		// fetch my css
		var css = document.createElement("link") 
		css.href = "/js/ibox/ibox.css"; 
		css.rel = "stylesheet"; 
		css.type = "text/css"; 
		document.body.appendChild(css);
		
		this.body.insertBefore(overlay, this.body.firstChild);
		this.Overlay = overlay;
	};

	this._overlayFade = function(step)
	{
		var self = this;
		if(this.OverlayBlendTimer != null) { clearInterval(this.OverlayBlendTimer); }
		this.OverlayBlendTimer = setInterval( function() { self._overlayBlendSetOpacity(step); } , this.OverlayFadeSpeed);
	};

	this._overlayBlendSetOpacity = function(step)
	{
		if(this.Overlay.style.visibility == 'hidden') { this.Overlay.style.visibility = 'visible'; }
		newOpac = parseFloat(this.Overlay.style.opacity) + (step/100);
		newFilterOpac = (newOpac * 100);
		if( (newOpac <= 1) && (newOpac >= 0))
		{
			this.Overlay.style.opacity = newOpac;
			this.Overlay.style.filter = "alpha(opacity=" + newFilterOpac + ")"; 
		}
		if( (newOpac >= 1) || (newOpac <= 0))
		{
			clearInterval(this.OverlayBlendTimer);
			this.OverlayBlendTimer = null; 
			if(newOpac <= 0) {this.Overlay.style.visibility = 'hidden'; }
		}
	};
	
	this._makeFolder = function (folder)
	{
		var self = this;
		var div = document.createElement("div");
		div.style.margin = '0px';
		div.style.padding = '20px';
		var folderName = document.createElement("p");
		folderName.innerHTML = folder.caption;
		div.appendChild(folderName);
		
		for(var i in folder.images)
		{
			// create the image, set placeholder image
			var img = document.createElement("img");
			img.setAttribute('id', folder.images[i].id );
			img.setAttribute('title', folder.images[i].caption );
			img.setAttribute('src', this.LoaderForFolderImage);
			img.className = this.OverlayLoadFolderImageClass;
			if (window.addEventListener) { img.addEventListener("click", function(evt) { self._ImageSelected(evt); }, false); }
			else { img.attachEvent("onclick", function(evt) { self._ImageSelected(evt); } ); }
			div.appendChild(img);
			// now lets load the real image, will be replacing the loader image when loaded
			var imgLoader = new Image();
			imgLoader.onload = this._createImageLoadedHandler(img, imgLoader, this.OverlayFolderImageClass);
			imgLoader.setAttribute('src', this.MediaPath + folder.images[i].file);
		}
		this.Panel.appendChild(div);
	};
	
	this._createImageLoadedHandler = function(_target, _loader, _targetCSS)
	{
		var self = this;
		return function(evt) { self._handleImageLoaded(evt, {target:_target, loader:_loader, css:_targetCSS} ); }
	};
	
	this._handleImageLoaded = function(evt, source)
	{
		source.target.src = source.loader.src;
		source.target.className = source.css;
	};
	
	this._makeFolders = function()
	{
		if ( this.Panel.hasChildNodes() )
		{
			while ( this.Panel.childNodes.length >= 1 )
			{
				this.Panel.removeChild( this.Panel.firstChild );       
			} 
		}
		for(var folder in this.Media.folders)
		{
			this._makeFolder(this.Media.folders[folder]); 
		}
		this._isFoldersGenerated = true;
	};
	
	this.createFolderPanel = function()
	{
		this.Panel = document.createElement("div");
		this.Panel.className = this.OverlayFolderPanelID;
		this.Overlay.appendChild(this.Panel);
	};
	
	this._prepareImageContainer = function()
	{
		if(this.Imagecontainer != null)
		{
			return;
		}
		var self = this;
		this.Imagecontainer = document.createElement("div");
		this.Imagecontainer.className = this.OverlayImageContainerID;
		this.Overlay.appendChild(this.Imagecontainer);
	};
	
	this._prepareZoomImage = function(target)
	{
		var self = this;
		if(this.ZoomImage == null)
		{
			this.ZoomImage = document.createElement("img");
			this.ZoomImage.className = this.OverlayLoadImageClass;
			if (window.addEventListener) { this.ZoomImage.addEventListener("click", function() { self.Hide(); }, false); }
			else { this.ZoomImage.attachEvent("onclick", function() { self.Hide(); } ); }			
			this.Imagecontainer.appendChild(this.ZoomImage);
		}
		this.ZoomImage.setAttribute('src', this.LoaderForImage);
		this.LastImageContainerTarget = target;
		// now lets load the real image, will be replacing the loader image when loaded
		var imgLoader = new Image();
		imgLoader.onload = this._createImageLoadedHandler(this.ZoomImage, imgLoader, this.OverlayImageClass); 
		imgLoader.setAttribute('src', target);	
	};
	
	this.SetMedia = function(media)
	{
		this.Media = media;
		this.createFolderPanel();
		//this._makeFolders();
	};
	
	this.GetSelectedMediaID = function()
	{
		return ( this.SelectedMedia ) ? this.SelectedMedia : null;
	};
	
	this.GetMediaPath = function() { return this.MediaPath; };

	this.GetImageAtrributes = function(mediaid)
	{
		for(var folder in this.Media.folders)
		{
			for(var img in this.Media.folders[folder].images)
			{
				if( this.Media.folders[folder].images[img].id == mediaid )
				{
					var attr =
					{
						file:(this.Media.folders[folder].images[img].file),
						caption:(this.Media.folders[folder].images[img].caption)
					};
					return attr;
				}
			}
		}
		return mediaid;
	};

    this.GetSelectedImagePath = function()
    {
        if(this.SelectedMedia == null)
        {
            return null;
        }
        var attr = this.GetImageAtrributes(this.SelectedMedia);
        return this.MediaPath + attr.file;
    };

    this.SetImageSelection = function(hiddenVarForID, containerForImage)
    {
        document.getElementById(hiddenVarForID).value = this.SelectedMedia;
        var imgContainer = document.getElementById(containerForImage);
        if(imgContainer.firstChild != null)
        {
            imgContainer.removeChild(imgContainer.firstChild);
        }
        var img = document.createElement('img');
        img.src = this.SelectedImagePath;
        imgContainer.appendChild(img);
    };

    this.SetInitialImageSelection = function(hiddenVarForID, containerForImage)
    {
        if(document.getElementById(hiddenVarForID).value)
        {
            this.SelectedMedia = document.getElementById(hiddenVarForID).value;
            this.SelectedImagePath = this.GetSelectedImagePath();
            this.SetImageSelection(hiddenVarForID, containerForImage);
        }
    };
	
	this._ImageSelected = function(event)
	{
		var self = this;
		var _id = (event.srcElement) ? event.srcElement.id : event.target.id;
		this.Hide();
		this.SelectedMedia = _id;
        this.SelectedImagePath = self.GetSelectedImagePath();
		this._sendImageSelected(self, { id:_id });
	};
	
	// custom events
	var eventAction = null;
	this.ImageSelected = function(fn) { eventAction = fn; };
	this._sendImageSelected = function(sender, media)
	{
		if(eventAction != null) { eventAction(sender, media); }
	};		
	
	this.Hide = function()
	{
        // fade bug fix
        this.Overlay.style.visibility = 'hidden';
        return;

        // this has the bug
		this._overlayFade(-this.OverlayFadeStep);
		return;
	};
	
	this.SelectImage = function()
	{
		this.SelectedMedia = null;
		this._ShowFolders();
	};
	
	this._ShowFolders = function()
	{
		if(this._isFoldersGenerated == false)
		{
			this._makeFolders();
		}

        // bug overlay fix
        this.Overlay.style.visibility = 'visible';
        return;

        // this has the bug
		this._overlayFade(this.OverlayFadeStep);
		return;
		
		psize = this.getPageSize();
		pwidth = psize[0]; 
		pheight = psize[1];
		o = document.getElementById(this.OverlayID).style;
		//o.width = pwidth + 'px';
		//o.height = pheight + 'px';
		o.width = '100%';
		o.height = '100%';		
		//b = document.getElementById(ImageBoxBackground).style;
		o.filter = "alpha(opacity=" + this.OverlayOpacity + ")"; 
		o.opacity = (this.OverlayOpacity/100);
		o.visibility = 'visible';
	};
	
    this.PreviewImage = function(srcSelector, srcPath)
    {
        var L = document.getElementById(srcSelector);
        //var N = L.selectedIndex;
        var F = document.getElementById(srcSelector).options[L.selectedIndex];
       // var C = document.getElementById(srcSelector).options[N].text;
        if(F.id)
        {
            var sender = {target:F.id};
            this._ShowImage(null, {target:F.id});
        }
        return false;
    }
	
	this._ShowImage = function(event, sender)
	{
		
		this._prepareImageContainer();
		if(this.LastImageContainerTarget != sender.target)
		{
			this._prepareZoomImage(sender.target); 
		}
		
		this._overlayFade(this.OverlayFadeStep);
		
		
		// center this
	//psize = getPageSize();
	//pwidth = psize[0]; 
	//pheight = psize[1];
	//o = document.getElementById(ImageBoxOverlay).style;
	//o.width = pwidth + 'px';
	//o.height = pheight + 'px';
	//b = document.getElementById(ImageBoxBackground).style;
	//b.filter = "alpha(opacity=" + OverlayOpacity + ")"; 
	//b.opacity = (OverlayOpacity/100);
	//b.width = o.width;
	//b.height = o.height;

	//wsize = getWindowSize();
	//scrollpos = wsize[2];
	//wwidth = wsize[0]; 
	//wheight = wsize[1];
	
	//p = document.getElementById(PreloadBox).style
	//p.left = ((wwidth - 128) / 2) + 'px';
	//p.top = (((wheight - 15) / 2) + scrollpos) + 'px';
	//o.visibility = 'visible';		

		return false;
	};
	
	this._findZoomLinks = function() 
	{
		if (! document.getElementsByTagName) { return; }
		var links = document.getElementsByTagName("a");
		var self = this;
		for (i = 0; i < links.length; i++) 
		{
			if (links[i].getAttribute("href")) 
			{
				if (links[i].getAttribute("href").search(/(.*)\.(jpg|jpeg|gif|png|bmp|tif|tiff)/gi) != -1) 
				{
					if ((links[i].getAttribute("rel") == "") || (links[i].getAttribute("rel") == undefined))
					{
						links[i].onclick = function (event) { return self._ShowImage( event, {source:this, target:this.getAttribute("href"), caption:this.getAttribute("title")} ); }; // the this is the key for always the right reference!!!
					}
				}
			}
		}
	};

	this._findGalleryLinks = function(galleryContainerID) 
	{
		if (! document.getElementById) { return; }
		var g = document.getElementById(galleryContainerID);
		var self = this;
		var links = g.getElementsByTagName('a');
		for (i = 0; i < links.length; i++) 
		{
			if ((links[i].getAttribute("href")) && (links[i].getAttribute("rel") == "iGallery"))
			{
				if (links[i].getAttribute("href").search(/(.*)\.(jpg|jpeg|gif|png|bmp|tif|tiff)/gi) != -1) 
				{
					links[i].onclick = function (event) { return self._ChangeGalleryImage( event, {source:this, target:this.getAttribute("href")} ); };
					links[i].onmouseover = function (event) { return self._ChangeGalleryImage( event, {source:this, target:this.getAttribute("href")} ); }; // the this is the key for always the right reference!!!
				}
			}
		}
	};
	
	this._ChangeGalleryImage = function(event, sender)
	{
		if(this.GalleryTarget.getAttribute('src') != sender.target)
		{
			this.GalleryTarget.setAttribute('src', sender.target);
		}
		return false;
	};
	
	this.getWindowSize = function()
	{
		// scroll pos
		var myScroll;
		if (self.innerHeight)
		{ // Everyone but IE
		
			myScroll = window.pageYOffset;
		} else if (document.documentElement && document.documentElement.clientHeight)
		{ // IE6 Strict
		
			myScroll = document.documentElement.scrollTop;
		} else if (document.body) { // Other IE, such as IE7
		
			myScroll = document.body.scrollTop;
		}
		
		var windowWidth, windowHeight;
			
		if (self.innerHeight) 
		{	// all except Explorer
			if(document.documentElement.clientWidth)
			{
				windowWidth = document.documentElement.clientWidth; 
			} 
			else 
			{
				windowWidth = self.innerWidth;
			}
			windowHeight = self.innerHeight;
		} 
		else if (document.documentElement && document.documentElement.clientHeight) 
		{ // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		}
		else if (document.body) 
		{ // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}	
		
		return [windowWidth, windowHeight, myScroll];
	};
	
	this.getPageSize = function()
	{
		var xScroll, yScroll;
			
		if (window.innerHeight && window.scrollMaxY) 
		{	
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} 
		else if (document.body.scrollHeight > document.body.offsetHeight)
		{ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} 
		else 
		{ // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
			
		var windowWidth, windowHeight;
			
		if (self.innerHeight) 
		{	// all except Explorer
			if(document.documentElement.clientWidth)
			{
				windowWidth = document.documentElement.clientWidth; 
			} 
			else 
			{
				windowWidth = self.innerWidth;
			}
			windowHeight = self.innerHeight;
		} 
		else if (document.documentElement && document.documentElement.clientHeight) 
		{ // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		}
		else if (document.body) 
		{ // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}	
			
		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight)
		{
			pageHeight = windowHeight;
		} 
		else 
		{ 
			pageHeight = yScroll;
		}
		
		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth)
		{	
			pageWidth = xScroll;		
		} 
		else 
		{
			pageWidth = windowWidth;
		}
	
		return [pageWidth,pageHeight];
	};	
	
}
