// ICEbox by Aaron Gough 2007. http://aarongough.com
// Development sponsored in part by Walden http://waldendesign.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 indenting to tabs instead of spaces & added basic commenting
// Stopped the page from returning to 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:
// Now working in Safari 2!!! ( the windowWidth, windowHeight, xoffset and yoffset were not being detected properly )
// Added loading swizzy
//
// 2nd November 2007:
// The script now detects the jQuery object and if it is found then it uses the jQuery animations to fade elements in and out.. cool!
// All event handlers now support at least one other event having been attached to an object before hand. The old handler is saved and fired after the new one
// All the variable names are now camelCase as opposed to underscored_names


// TO-DO:
// Add multiple redundancy to the script in general
// Convert script to be more standards compliant
// Bugfix for IE 5.2 on Mac ( never gonna happen... what a crappy browser )
// 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  = "http://mastcanada.org/images/overlaybg.png";						// The path to the GIF binary transparent overlay
alphabg = "http://mastcanada.org/images/overlayalphabg.png";					// The path to the Alpha transparent PNG overlay
closebutton = "http://mastcanada.org/images/closebutton.png";				// The path to the small close button in the top right hand corner of the popup
loadingImage = "http://mastcanada.org/images/loading.gif";					// The path to an animated GIF loading image...

thumbnail_width = 390;									// 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 = 0;											// This is the default max height for the popup ( this will be updated automatically by the script )
maxwidth = 780;											// This is the default max width for the popup ( this will be updated automatically by the script )

show_stupid_alert = false;								// This variable sets whether or not we should should show an instructional alert for stupid people or not

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() 
	{
	if( typeof(jQuery) == "object"  )
		{
		jQuery("#icebox").fadeOut("fast", function () { jQuery("#overlay").fadeOut("fast"); });
		
		}
	else
		{
		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 or class attribute containing the word '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.id = "busyImage";
	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 ( careful! assumption is the mother of all fuckups! )
	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 ) || ( browser == "Opera")) 
		{
		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");
		anchorClass = anchor.getAttribute("class");
		if( anchorClass == null ) 
			{
			anchorClass = anchor.className;
			}
		if( target && (anchor.getAttribute("rel")== "icebox")) anchor.onclick = createPopup;
		if( anchorClass.indexOf("icebox") != -1) anchor.onclick = createPopup;
		} 
		
	// here we will find any images that have an 'alt' or 'class' attribute containing '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 (  this is a fallback method for WYSIWYG editors that don't allow you to change the rel attribute )
	images = document.getElementsByTagName( "img" );
	for ( x = 0; x < images.length; x++)
		{
		image = images[x];
		src = image.src;
		alt = image.getAttribute("alt");
		imgClass = image.getAttribute("class");
		if( imgClass == null ) 
			{
			imgClass = image.className;	
			}
		if( typeof(alt) == "string" && (alt.indexOf( 'icebox') != -1))
			  {
			  image.onclick = createPopup;
			  resizeImage( image, thumbnail_width, thumbnail_height );
			  image.style.visibility = "visible";
			  }
		if( typeof(imgClass) == "string" && (imgClass.indexOf( 'icebox') != -1))
			  {
			  image.onclick = createPopup;
			  resizeImage( image, thumbnail_width, thumbnail_height );  
			  image.style.visibility = "visible";
			  }	  
		} 

	center();
	}
	
	
// This function displays the overlay and popup and then centers and re-sizes both of them
function showIceBox( elementid, popwidth, popheight )
	{ 
	notLoading();
	if( typeof(jQuery) == "object"  )
		{
		jQuery( "#overlay" ).fadeIn("slow");
		}
	else 
		{
		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();

		if( typeof(jQuery) == "object"  )
			{
			el.style.visibility = "visible";
			jQuery("#icebox").fadeIn("fast");	
			}
		else
			{
			el.style.display="block";
			el.style.visibility = "visible";
			}
		if( show_stupid_alert )
			{
			alert( "Click the X at top right to close window when finished" );
			show_stupid_alert = false;
			}
		}
	}

// 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";
		}
	
	if( !maxwidth ) maxwidth = pageWidth - 100;
	if(!maxheight ) 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 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
		
		parentClass = targ.parentNode.getAttribute("class");
		if( parentClass == null ) 
			{
			parentClass = targ.parentNode.className;	
			}
		if( parentClass.indexOf( "icebox") != -1 )
			{
			var showImage = true;	
			}
		
		if( targ.parentNode.tagName == "A" && (targ.parentNode.getAttribute("rel") == "icebox" || showImage))
			{
			targ = targ.parentNode;	
			}
		
		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" || "tif"))
		{
		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 passed to it so that is is within the maximum height and width allowable
function resizeImage ( image, maxwidth , maxheight )
	{
	if( typeof( image ) == "string" )
		{
		image = document.getElementById( image );	
		}
	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 ()
	{
	if( typeof(jQuery) == "object" ) 
		{
		jQuery("#busyImage").fadeIn("fast");	
		}
	else
		{
		busyImage.style.display = "block";
		}
	}
	
// This function hides the loading swizzy
function notLoading ()
	{
	if( typeof(jQuery) == "object" ) 
		{
		jQuery("#busyImage").fadeOut("fast");	
		}
	else
		{
		busyImage.style.display = "none";
		}
	}



// 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;

