// ICEbox by Aaron Gough 2007. http://aarongough.com
// This work is licensed under the Creative Commons Attribution-Share Alike 3.0 License. 
// To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/ 

// CHANGELOG:
// Changes before the 7th August 2007 were not noted and are therefore undocumented... oops
// 7th August 2007:
// Converted all formatting to tabs instead of spaces & added basic commenting
// Stopped the page from returning too the top when a popup is created
// fixed bug where uppercase image file extensions would stop the image from being displayed correctly
//
// 8th August 2007:
// MADE IT WORK IN SAFARI 2!!! ( the windowWidth, windowHeight, xoffset and yoffset were not being detected properly )
// Added loading swizzy


// TO-DO:
// Add multiple redundancy to the script in general
// Convert script to be more standards compliant
// change all event handler assignments to the newer type that will check for old event handlers before overwriting
// Convert variable names to standard Javascript camelcase naming conventions
// Bugfix for IE 5.2 on Mac
// Add functionality to add onclick behaviours to links that point to an image and have 'target="_blank"'



// These are the preferences variables for the script
safebg  = "images/overlaybg.png";						// The path to the GIF binary transparent overlay
alphabg = "images/overlayalphabg.png";					// The path to the Alpha transparent PNG overlay
closebutton = "images/closebutton.png";					// The path to the small close button in the top left hand corner of the popup
loadingImage = "images/loading.gif";					// The path to an animated GIF loading image...

thumbnail_width = 200;									// This variable set the maximum width for the dynamically created thumnbnails
thumbnail_height = 0;									// This variable sets the meximum height for the dynamically created thumbnails
maxheight = 900;										// This is the default max height for the popup ( this will be updated automatically by the script )
maxwidth = 400;											// This is the default max width for the popup ( this will be updated automatically by the script )

copyprotect = true;										// This variable controls whether or not copy protection is activated ( stops people from right clicking on the page and stops them from dragging images out of their browser )

icebox  = new Array();									// Here we set-up some of the global variables we will need for later on
newbrowser = false; 
overlay = 0;
busyImage = 0;

// This function simply hides the popup div and the overlay div
function hidePopup() 
	{
	document.getElementById( icebox[0] ).style.display="none";
	overlay.style.display="none";
	}


// This function sets-up the necessary variables in order for the script to run and also finds, resizes and adds behaviours to any images marked with an alt tag ending in 'icebox'
// it also adds the onclick behaviour to any links found with a 'rel' attribute of 'icebox'
function initIceBox () 
	{
	// Here we will create and test the overlay and icebox divs ready for later use
	pagebody = document.getElementsByTagName("body").item(0);
		
	overlay = document.createElement( "div" );
	overlay.id = "overlay";
	overlay.style.display = "none";
	overlay.style.position = "absolute";
	overlay.style.top = "0px";
	overlay.style.left = "0px";
	overlay.style.zIndex = "9998";
	overlay.onclick = hidePopup;
	document.body.appendChild( overlay );
	overlay.innerHTML += " ";						// A bit of a kick in the bum for safari to help it realize that it should update the DOM tree
	
	overlay = document.getElementById( "overlay" );	// now ( as a backup ) if the overlay div cannot be found we will try to create it using the innerHTML method
	if( !overlay ) pagebody.innerHTML += '<div id="overlay" style="display:none;position:absolute;top:0px;left:0px;z-index:9998;"> </div>';
	overlay = document.getElementById( "overlay" ); // now we will test for the presence of the overlay again.. if we can't find it then we exit
	if( !overlay ) alert( "unable to create overlay" );
	
	// now we will create the container div for the dynamic content
	var iceboxDiv = document.createElement( "div" );
	iceboxDiv.id = "icebox";
	iceboxDiv.style.display = "none";
	iceboxDiv.style.zIndex = 9999;
	iceboxDiv.className = "popup";
	document.body.appendChild( iceboxDiv );
	iceboxDiv.innerHTML += " ";						// another kick in the a@@ for Safari
	
	iceboxDiv = document.getElementById( "icebox" );	// now ( as a backup ) if the icebox div cannot be found we will try to create it using the innerHTML method 
	if( !iceboxDiv ) pagebody.innerHTML += '<div id="icebox" style="display:none;z-index:9999;" class="popup"> </div>';
	iceboxDiv = document.getElementById( "icebox" ); // now we will test for the presence of the icebox div again.. if we can't find it then we exit
	if( !iceboxDiv ) alert( "unable to create icebox" );
	
	// and now we will add a loading indicator
	busyImage = document.createElement( "img" );
	busyImage.src = loadingImage;
	busyImage.style.position = "fixed";
	busyImage.style.left = "50%";
	busyImage.style.top = "50%";
	busyImage.style.visibilty = "hidden";
	busyImage.style.zIndex = 9999;
	document.body.appendChild( busyImage );
	busyImage.onload = function ()
		{
		busyImage.style.marginLeft = "-" + ( busyImage.width / 2 ) + "px";
		busyImage.style.marginTop = "-" + ( busyImage.height / 2 ) + "px";
		busyImage.style.display = "none";
		busyImage.style.visibilty = "visible";
		}
	
	// Now some checks to see if the browser supports PNG alpha transparency... if not then we will use a binary transparent overlay image
	// if we decide the browser is a 'new' browser we also assume that it supports position:fixed and the cursor:pointer CSS rules
	var browser=navigator.appName;
	var b_version=navigator.appVersion;
	var version=parseFloat(b_version);
	if( (browser == "Netscape" && version >= 5) || (browser == "Konqueror") || ( browser == "Microsoft Internet Explorer" && version >= 7 )) 
		{
		newbrowser = true;
		overlay.style.background="transparent url('" + alphabg + "') repeat";
		}
	else overlay.style.background="transparent url('" + safebg + "') repeat";

	// Now we will find any links that have the 'rel' tag set to 'icebox' and attach our onclick event handler to them
	var anchors = document.getElementsByTagName( "a" );
	for ( x = 0; x < anchors.length; x++)
		{
		anchor = anchors[x];
		target = anchor.getAttribute("href");
		if( target && (anchor.getAttribute("rel")== "icebox")) anchor.onclick = function () { createPopup; return false; }
		} 
		
	// here we will find any images that have an 'alt' tag ending in 'icebox' and re-size it to the the dimensions specified in the preference variables
	// then we attach an onclick event that allow the full-size image to be shown in a icebox popup
	images = document.getElementsByTagName( "img" );
	for ( x = 0; x < images.length; x++)
		{
		image = images[x];
		src = image.src;
		alt = image.getAttribute("alt");
		if( typeof(alt) == "string" && alt.substring( alt.length - 6) == 'icebox')
			  {
			  image.onclick = function () { createPopup; return false; }
			  resizeImage( image, thumbnail_width, thumbnail_height );  
			  }
		} 

	center();
	}
	
	
// This function displays the overlay and popup and then centers and re-sizes both of them
function showIceBox( elementid, popwidth, popheight )
	{ 
	notLoading();
	overlay.style.display="block";

	el = document.getElementById( elementid );
	if( el )
		{
		icebox[0] = elementid;
		icebox[1] = popwidth;
		icebox[2] = popheight;

		el.style.position = (newbrowser) ? "fixed":"absolute";

		el.style.height= popheight + "px";
		el.style.width= popwidth + "px";

		center();

		el.style.display="block";
		el.style.visibility = "visible";
		init();								//ATTENTION: this is a change to accomodate the nosave javascript
		}
	}

// This function automatically re-centers and re-sizes both the overlay and the image popup
function center ()
	{
	var xOffset, yOffset;
	if (self.pageYOffset) 
		{
		yOffset = self.pageYOffset;
		xOffset = self.pageXOffset;
		} 
	else if (document.documentElement && document.documentElement.scrollTop)
		{	 // Explorer 6 Strict
		yOffset = document.documentElement.scrollTop;
		xOffset = document.documentElement.scrollLeft;
		} 
	else if (document.body) 
		{// all other Explorers
		yOffset = document.body.scrollTop;
		xOffset = document.body.scrollLeft;	
		}
	
	
	var ScrollHeight, ScrollWidth;
	if (window.innerHeight && window.scrollMaxY) 
		{	
		ScrollHeight = window.innerWidth + window.scrollMaxX;
		ScrollWidth = window.innerHeight + window.scrollMaxY;
		} 
	else if (document.body.scrollHeight > document.body.offsetHeight)
		{ // all but Explorer Mac
		ScrollHeight = document.body.scrollWidth;
		ScrollWidth = document.body.scrollHeight;
		} 
	else 
		{ // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		ScrollHeight = document.body.offsetWidth;
		ScrollWidth = document.body.offsetHeight;
		}


	var windowWidth, windowHeight;
	if (self.innerHeight) 
		{	// all except Explorer
		windowWidth = (document.documentElement.clientWidth) ? document.documentElement.clientWidth : 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;
		}	
	
	// if the document width orheight is less than the viewport width or height then we adjust accordingly
	pageHeight = (ScrollWidth < windowHeight) ? windowHeight : ScrollWidth;
	pageWidth = (ScrollHeight < windowWidth) ? ScrollHeight : windowWidth;
	
	if( overlay )
		{
		overlay.style.height = pageHeight + "px";
		overlay.style.width= pageWidth + "px";
		}
	
	maxwidth = pageWidth - 100;
	maxheight = pageHeight - 100;

	var el = document.getElementById( icebox[0] );

	if ( el)
		{
		var left= (( windowWidth / 2) - ( icebox[1] / 2) + xOffset );
		if ( newbrowser ) var top= ((windowHeight / 2) - ( icebox[2] / 2));
		else var top= ((windowHeight / 2) - ( icebox[2] / 2) + yOffset );

		el.style.top = ( top < 0 ) ? "0px": top + "px";
		el.style.left = ( left < 0 ) ? "0px" : left + "px";
		}
	//alert( "ScreenWidth =" + windowWidth + " ScreenHeight =" + windowHeight + " widthOffset =" + ScrollHeight + " heightOffset =" + ScrollWidth ); 
	}

// This function creates and displays an image or url in a popup window
function createPopup ( src )
	{
	if( (!src) || (typeof src == 'object') )
		{
		var targ;
		if (!src) var src = window.event;
		if (src.target) targ = src.target;
		else if (src.srcElement) targ = src.srcElement;
		if (targ.nodeType == 3) targ = targ.parentNode; // defeat Safari bug
		src = targ.src;
		if( !src ) src = targ.getAttribute("href");
		}
		
	var extension = src.substring( src.length -3 );
	extension = extension.toLowerCase();
	document.getElementById( 'icebox' ).style.visibility = "hidden";
	if( extension == ("jpg" || "gif" || "png" || "peg" || "bmp"))
		{
		overlay.style.display="block";
		loading();
		document.getElementById( 'icebox' ).style.display= "block";
		divstring = '<img src="' + closebutton + '" onclick="hidePopup()" align="right"/>';
		divstring += '<img src="' + src + '" id="iceboximage" style="margin-top: 16px; margin-left: 16px;" onclick="hidePopup()" />';
		document.getElementById('icebox').innerHTML = divstring;
		document.getElementById( 'iceboximage' ).onload = function ()
			{
			var iceboximage = document.getElementById( 'iceboximage' );
			resizeImage( iceboximage, maxwidth, maxheight );
			showIceBox( 'icebox', width + 32, height + 32 ) ;
			}
		}
		
	else
		{
		divstring = '<img src="' + closebutton + '" onclick="hidePopup()" align="right"/>';
		divstring += '<iframe src="' + src + '" width="' + maxwidth + 'px"' + ' height="' + maxheight + 'px" style="margin-top: 16px; margin-left:16px; border: 0;"></iframe></div>';
		document.getElementById('icebox').innerHTML = divstring;
		showIceBox( 'icebox', maxwidth + 32, maxheight + 32 ) ;
		}
	return false;
	}

// This function will resize the image passes to it so that is is within the maximum height and width allowable
function resizeImage ( image, maxwidth , maxheight )
	{
	width = image.width;
	height = image.height;
	if( height > maxheight && maxheight > 0)
		{
		scale = height / maxheight;
		height = height / scale;
		width = width / scale;
		}
	if ( width > maxwidth && maxwidth > 0 )
		{
		scale = width / maxwidth;
		width = width / scale;
		height = height / scale;
		}
	image.height = height ;
	image.style.height = height + "px";
	image.width = width ;
	image.style.width = width + "px";
	image.style.cursor = (newbrowser) ? "pointer" : "hand";
	}
	
// This function displays a nice loading swizzy to keep the user enthralled while they wait for their slow connection to load the content
function loading ()
	{
	busyImage.style.display = "block";
	}
	
// This function hides the loading swizzy
function notLoading ()
	{
	busyImage.style.display = "none";
	}
	
// This function contains various trickery to stop the average user from being able to copy images
// it will stop anyone from right clicking on ANY part of the page and will stop users from dragging images outside of the browser
function copyProtect ()
	{
	document.body.oncontextmenu = function () { alert( "don't right click!" ); }
	}

// Here we check if there is already an existing onload event. if there is then we execute it before we perform our own onload event
var oldOnLoad = window.onload;
if( typeof( oldOnLoad ) == 'function' ) window.onload = function() {oldOnLoad(); initIceBox(); }
else window.onload = initIceBox;

// Here we will attach the event handlers to the onscroll and onresize events
var oldOnScroll = window.onscroll;
if( typeof( oldOnScroll ) == 'function' ) window.onscroll = function() { oldOnScroll(); center(); }
else window.onscroll = center;

var oldOnResize = window.onresizel;
if( typeof( oldOnResize ) == 'function' ) window.onresize = function() { oldOnResize(); center(); }
else window.onresize = center;
