/********************************************************************
	Library:	Majik
	Version:	1.0
	Date:		Apr 14 2009
	Author:		Daniel Wright
	Contact:	http://danwright.info/contact

	Requires prototype.js.
*********************************************************************/

/***
	Design notes:
		our info should be associated with the link ('a'). Contents does not HAVE to be a thumbnail, it
		could also be text, for example.
	<a href="image.jpg" class="majik-loupe"><img src="thumbnail.jpg" alt="" title="click to enlarge" /></a>
 ***
 All of the generated document elements are in div#majik-container.
 A MajikLoupe object is created to track/display one picture, it handles all animations etc for that one
 picture.
****/
var majik = {

Version: '0.91',

// global configuration/user settings go here

allowMultipleLoupes     : false, /* allow multiple image loupes to be visible at the same time */
obscurePageWhileViewing : true, /* "hide" page in background while a loupe is visible */
saveLoupePositions	    : false, /* true: [N/I] loupes "remember" their old position when re-opened */
zoomToWindowCenter      : true,  /* true: zoom image to center of window, false: zoom near thumbnail */

blankImageSrc: "/images/blank.gif",

loadingImageSrc: "/images/progressBarLong.gif", /* indicator_black.gif, indicator_white.gif, progressBarLong.gif */
loadingText: "Loading...",

darkBoxColor: 'rgb(64,64,64)',	/* color (tint/tone) of the obscuring "dark box" */
darkBoxOpacity: 0.7,			/* 1.0 completely hides the rest of the page; default is 0.7 */

// localization
textClickToReturn: "Click to return",

// end of configuration/user settings

debugging: true, /* true when debugging this script, false otherwise */

// Internal properties

ie: (document.all && !window.opera),
safari : navigator.userAgent.indexOf("Safari") != -1,

hasAlphaImageLoader : false,
hasPngSupport : false,

loupes : new Array(),
loupeCount: 0,
activeLoupes: 0,

kContainerZ : 100,
kDarkBoxZ   : 199,
kProgressZ  : 299,
kBlankImageZ: 999,

darkbox: null,

imagesToPreload: new Array(),
imagesPreloadCount: 0,
imagesPreloadCountMax: 2,

dragLoupeIdx: -1,


log: function(msg) {
	if (majik.debugging) {
	var debuglog = $('debuglog');
	if (debuglog != null || typeof Debug == "Object")
		{
		var msgbits = (null == msg || msg instanceof Array) ? msg : new Array(msg);
		for (i = 0; i < msgbits.length; i++)
			{
			if (Debug != null)
				Debug.log(msgbits[i]);
			else
				{
				debuglog.appendChild(document.createTextNode(msgbits[i]));
				debuglog.appendChild(document.createElement('br'));
				}
			}
		}
	else if ((!majik.ie || majik.ieVersion() >= 8.0) && typeof console != "undefined")
		{
		var msgbits = (null == msg || msg instanceof Array) ? msg : new Array(msg);
		for (i = 0; i < msgbits.length; i++)
			console.log(msgbits[i]);
		}
	}
},

createElement: function(tag, attributes, style, children)
{
	var element = Element.extend(document.createElement(tag));
	if (attributes) majik.setAttributes(element, attributes);
	if (style) majik.setStyle(element, style);
	if (children) $A(children).each( function(child){element.appendChild(child);} );
	return element;
},

setAttributes: function(element, attributes)
{
	for (var attribute in attributes)
		element[attribute] = attributes[attribute];
},

setStyle: function(element, style)
{
	for (var styleItem in style)
		try { element.style[styleItem] = style[styleItem]; } catch (error) { }
},

ieVersion: function() {
	arr = navigator.appVersion.split("MSIE");
	return parseFloat(arr[1]);
},

initProperties : function()
{
	var v = majik.ieVersion();
	hasPngSupport = !majik.ie || (majik.ie && v >= 8);
	hasAlphaImageLoader = majik.ie && v >= 5.5 && v < 8;
},

windowSize : function()
{
	return document.viewport.getDimensions();
},

getTextForEntity: function(entity)
{
	if (!majik.dummy)
		majik.dummy = majik.createElement('div', null, {display: 'none'});
	document.body.appendChild(majik.dummy);
	majik.dummy.innerHTML = entity;
	var text = majik.dummy.innerText;
	document.body.removeChild(majik.dummy);
	return text;
},

activeLightBoxZIndex : function()
{
	return 200 + majik.loupeCount;
},

getLightTable : function(element)
{
	while (element.parentNode && element.className != 'majik-lighttable')
		element = element.parentNode;
	
	return (element != null && element.className == 'majik-lighttable') ? element : null;
},

getLightTableID : function(element)
{
	var lightTable = majik.getLightTable(element);
	if (lightTable != null && lightTable.id.match(/^majik-loupe-\d+/))
		return lightTable.id.replace(/^majik-loupe-(\d+)/, "$1");
	return;
},

handleMouseClick : function(event)
{
	event = Event.extend(event || window.event);
	if (event.button > 1) 
		return true;
	
	var obj = event.element();
	while (obj.parentNode && (null == obj.className || !obj.className.match(/majik/)))
		obj = obj.parentNode;
	if (null == obj.parentNode)
		return true;
	
	if (event.type === 'mousedown')
		{
		if (obj.hasClassName('majik-plexiglass'))
			{
			var lightTable = majik.getLightTable(obj);
			var dragLoupeIdx = majik.getLightTableID(lightTable);
			if (dragLoupeIdx >= 0 && majik.dragLoupeIdx < 0)
				{
				majik.dragLoupeIdx = dragLoupeIdx;
				var loupe = majik.loupes[dragLoupeIdx];
				if (loupe != null)
					{
					if (loupe.isSelected())
						{
						majik.dragElement = lightTable; //loupe.content;
						majik.dragStartLightTableLeft = parseInt(majik.dragElement.style.left);
						majik.dragStartLightTableTop  = parseInt(majik.dragElement.style.top);
						majik.dragStartMouseX = event.clientX;
						majik.dragStartMouseY = event.clientY;
						majik.dragStartTime = new Date().getTime();
						obj.style.cursor = 'move';
						document.observe('mousemove', majik.handleMouseMove);
						}
					else
						loupe.bringToFront();
					event.stop();
					}
				}
			return false;
			}
		}
	else if (event.type === 'mouseup')
		{
		if (majik.dragLoupeIdx >= 0)
			{
			var now = new Date().getTime();
			var elapsed = now - majik.dragStartTime;
			if (elapsed < 250 || (elapsed < 500 && event.clientX == majik.dragStartMouseX && event.clientY == majik.dragStartMouseY))
				{
				var loupe = majik.loupes[majik.dragLoupeIdx];
				if (loupe != null)
					{
					loupe.close();
					}
				}
			document.stopObserving('mousemove', majik.handleMouseMove);
			majik.dragLoupeIdx = -1;
			majik.dragElement = null;
			obj.style.cursor = 'pointer';
			}
		}
	else if (event.type === 'dragstart')
		{
		event.stop();
		}
	return true;
},

handleMouseMove : function(event)
{
	event = Event.extend(event || window.event);
	if (majik.dragLoupeIdx >= 0)
		{
		var newLeft = majik.dragStartLightTableLeft + event.clientX - majik.dragStartMouseX;
		var newTop  = majik.dragStartLightTableTop  + event.clientY - majik.dragStartMouseY;
		majik.dragElement.style.left = newLeft + "px";
		majik.dragElement.style.top  = newTop  + "px";
		}
	return false;
},

next: function()
{
	var loupe = majik.getActiveLoupe();
	if (loupe != null)
		{
		if (loupe.a.majikNext)
			majik.magnify(loupe.a.majikNext, {});
		}
},

previous: function()
{
	var loupe = majik.getActiveLoupe();
	if (loupe != null)
		{
		if (loupe.a.majikPrevious)
			majik.magnify(loupe.a.majikPrevious, {});
		}
},

handleKeyPress: function(event)
{
	if (majik.activeLoupes == 0)
		return true;
	
	var keyCode = event.keyCode;
	var keyChar = String.fromCharCode(keyCode).toLowerCase();
	if (39 == keyCode || 'n' == keyChar)
		majik.next();
	else if (37 == keyCode || 'p' == keyChar)
		majik.previous();
	else if (27 == keyCode || '.' == keyChar)
		{
		var activeLoupe = majik.getActiveLoupe();
		if (activeLoupe) activeLoupe.close();
		}
	else if (13 == keyCode)
		{
		var activeLoupe = majik.getActiveLoupe();
		if (activeLoupe)
			{
			var altref = activeLoupe.altref();
			if (activeLoupe.hasFolioView() && altref)
				{
				majik.setProxyLink(altref, true);
				return false;
				}
			else
				majik.hideProxyLink();
			}
		}
	return true;
},


findLoupeForLink: function(link)
{
	for (var i = 0; i < majik.loupes.length; i++)
		if (majik.loupes[i] != null && majik.loupes[i].a == link)
			return majik.loupes[i];
	return null;
},

getActiveLoupe: function()
{
	for (var i = 0; i < majik.loupes.length; i++)
		if (majik.loupes[i] != null && majik.loupes[i].isSelected())
			return majik.loupes[i];
	return null;
},

magnify: function(link, params)
{
	try	{
		var loupeTarget = majik.findLoupeForLink(link);
		var loupeActive = majik.allowMultipleLoupes ? null : majik.getActiveLoupe();
		if (loupeActive != null && loupeActive != loupeTarget)
			{
			loupeActive.closeKeepingDarkBox();
			}
		if (loupeTarget == null)
			{
			new MajikLoupe(link, params);
			}
		else
			{
			loupeTarget.select();
			}
		return false;
		}
	catch (exc)
		{
		log("magnify exception: " + exc);
		throw exc;
		return false;
		}
},

handleLinkClick: function(event)
{
	var target = event.element();
	while (target.parentNode != null && target.tagName != 'A')
		target = target.parentNode;
	event.stop();
	return majik.magnify(target, {});
},

scanForImagesToPreload: function()
{
	var links = $$('a.majik-loupe');
	for (var i=0, link=null; i < links.length && majik.imagesPreloadCount < majik.imagesPreloadCountMax; i++)
		{
		link = links[i];
		if (link.href.match(/\w+\.jpg$/))
			{
			if (!majik.imagesToPreload[link.href])
				{
				var img = new Image();
				img.onload = function () { if (majik.imagesPreloadCount-- < 3) majik.scanForImagesToPreload(); };
				img.src = link.href;
				majik.imagesToPreload[link.href] = img;
				majik.imagesPreloadCount++;
				}
			}
		}
},

scanForMajikLoupes : function()
{
	var links = $$('a.majik-loupe');
	for (var i=0, link=null; i < links.length; i++)
		{
		var prev = link;
		link = links[i];
		$(link).observe('click', majik.handleLinkClick);
		if (prev)
			{ prev.majikNext = link; link.majikPrevious = prev; }
		}
	majik.scanForImagesToPreload();
	if (majik.ie && majik.ieVersion() < 7.0)
		majik.obscurePageWhileViewing = false; /* not supported for IE 6 */
},

handleDocumentLoad : function()
{
	majik.initProperties();
	majik.scanForMajikLoupes();
	document.observe('mousedown', majik.handleMouseClick);
	document.observe('mouseup', majik.handleMouseClick);
	document.observe('keydown', majik.handleKeyPress);
	if (Prototype.Browser.IE)
		document.observe('dragstart', majik.handleMouseClick);
	
	Event.observe(window, 'resize', majik.resizeDarkBox);
},

ensureContainer : function()
{
	if (!majik.container)
		{
		majik.container = majik.createElement('div', {id: 'majik-container'},
							{ position: 'absolute', left: '0px', top: '0px',
							  width: '100px', height: '100px', zIndex: majik.kContainerZ });
		document.body.appendChild(majik.container);

		majik.darkbox = majik.createElement('div', {id: 'majik-darkbox'},
							{ position: 'absolute', left: '0px', top: '0px', 
								visibility: 'hidden',
								width: '100px', height: '100px', zIndex: majik.kDarkBoxZ,
								background: majik.darkBoxColor
								});
		majik.container.appendChild(majik.darkbox);
		
		majik.proxyLink = majik.createElement('a', {href:'#',target:'_blank'}, {display:'none', outline:'none'}, [document.createTextNode('*')]);
		majik.container.appendChild(majik.proxyLink);
		}
},

setProxyLink : function(uri, takeFocus)
{
	if (uri)
		majik.proxyLink.href = uri;
	if (takeFocus)
		{
		if (majik.proxyLink.style.display == 'none')
			{
			majik.proxyLink.setOpacity(0.25);
			majik.proxyLink.style.display = 'inline';
			}
		majik.proxyLink.focus();
		}
},

hideProxyLink : function()
{
	majik.proxyLink.style.display = 'none';
},

resizeDarkBox : function()
{
	if (majik.obscurePageWhileViewing && majik.darkbox)
		{
		var size = majik.windowSize();
		size.width -= 1;
		majik.darkbox.style.width = size.width + 'px';
		majik.darkbox.style.height = size.height + 'px';
		}
},

showDarkBox : function()
{
	if (majik.obscurePageWhileViewing)
		{
		majik.resizeDarkBox();
		majik.darkbox.style.visibility = 'visible';
		}
},

hideDarkBox : function()
{
	majik.darkbox.style.visibility = 'hidden';
}

}; // var majik

MajikLoupe = function(a, params) 
{
	// Is the loupe already open?
	for (i = 0; i < majik.loupes.length; i++)
		if (majik.loupes[i] != null && majik.loupes[i].a == a)
			{
			log("MajikLoupe: already have it open");
			return false;
			}
	
	majik.ensureContainer();
	
	this.status = 'initializing';
	this.a = a;
	this.idx = majik.loupeCount++;
	majik.loupes[this.idx] = this;
	
	this.overlays = [];
	this.thumb = a.getElementsByTagName('img')[0];
	this.plexiglass = majik.createElement('img', 
						{src: majik.blankImageSrc, className: 'majik-plexiglass'},
						{visibility: 'hidden', display: 'block', position:'absolute', zIndex: majik.kBlankImageZ
						});
										
	this.home = $(this.thumb).cumulativeOffset();
	log("pos of thumb: " + this.home.left + ", " + this.home.top);
	
	this.lighttable = majik.createElement('div', {id: 'majik-loupe-'+this.idx, className: 'majik-lighttable'},
					{visibility: 'hidden', position: 'absolute', 
					 top: this.home.top + 'px', left: this.home.left + 'px', width: '100%',
					 padding: '10px 10px 20px 10px',
					 background: '#fff'
					 });
	this.lighttable.style.zIndex = majik.activeLightBoxZIndex();
	
	this.textDiv = majik.createElement('div', {className: 'majik-text'},
					{textAlign: 'center'});

	majik.container.appendChild(this.lighttable);
	
	this.thumbWidth = this.thumb.width ? this.thumb.width : this.thumb.offsetWidth;
	this.thumbHeight = this.thumb.height ? this.thumb.height : this.thumb.offsetHeight;
	this.thumbPosition = $(this.thumb).cumulativeOffset();
	this.thumbBorderWidth = this.thumb.getStyle('borderWidth') || this.thumb.getStyle('borderTopWidth');
	this.animation = null;
	
	this.progressBlock = majik.createElement('div', { className: 'majik-progress' },
							{ display: 'none', margin: 'auto', zIndex: majik.kProgressZ }
							);
	this.progressBlock.appendChild(					
						 majik.createElement('img',
							{ src: majik.loadingImageSrc, title: majik.loadingText, alt: majik.loadingText },
							{ display: 'block'
							}));

	// for now, that's it; in the future we might add majik.loadingText as a caption in the block
	
	// ====
	this.createImage();
	/*this.lighttable.style.left = this.home.left + 'px';
	this.lighttable.style.top  = this.home.top  + 'px';
	this.lighttable.style.width = '0px';
	this.lighttable.style.height = '0px';*/
	
	this.lighttable.appendChild(this.plexiglass);
	this.plexiglass.style.visibility = '';
	//this.plexiglass.show();
	this.lighttable.appendChild(this.content);
	this.lighttable.appendChild(this.textDiv);
	//majik.container.style.visibility = '';
	//this.lighttable.style.visibility = '';
	majik.container.show();
	this.lighttable.show();
	
	
	this.createStandardOverlays();
	
	this.plexiglass.observe('mouseover', this.onMouseOver.bind(this));
	this.plexiglass.observe('mouseout', this.onMouseOut.bind(this));
	
	++majik.activeLoupes;
};

MajikLoupe.prototype.hasFolioView = function()
{
	return this.a.hasAttribute('altref');
};

MajikLoupe.prototype.createImage = function()
{
	log("MajikLoupe.createImage");
	this.status = 'loading';
	var img = majik.createElement('img',
					{ className: 'majik-loupe', src: null, title: majik.textClickToReturn },
					{ visibility: 'hidden', display: 'block'
					//, 
					/*position: 'absolute', top: '0px', left: '0px', */
					//zIndex: 30 
					});
	this.content = Element.extend(img);
	// REVIEW: Why was this line written for safari only??
	// Doesn't seem necessary for firefox, but it's needed for IE 7
	/*if (majik.safari) */majik.container.appendChild(img);

	img.onload = (function(i) { if (majik.loupes[i]) {
						this.finalHeight = this.content.height;
						this.finalWidth = this.content.width;
						this.finalBorderWidth = this.content.getStyle('borderTopWidth');
						if (isNaN(parseInt(this.finalBorderWidth)))
							this.finalBorderWidth = '10px';
						this.plexiglass.title = this.content.title;
						this.zoomIn();
						}}).bind(this,this.idx);
	img.src = this.a.href;
	
	this.showLoading();
	
};

MajikLoupe.prototype.respondToImageLoaded = function() 
{
	log("MajikLoup.respondToImageLoaded");
	this.hideLoading();
	this.finalHeight = this.content.height;
	this.finalWidth  = this.content.width;
	this.finalBorderWidth = this.content.getStyle('borderTopWidth');
	if (isNaN(parseInt(this.finalBorderWidth)))
		this.finalBorderWidth = '10px';
	this.plexiglass.title = this.content.title;
	this.zoomIn();
};

MajikLoupe.prototype.showLoading = function()
{
	log("MajikLoupe.showLoading");
	this.progressBlock.style.display = 'block';
	
};

MajikLoupe.prototype.hideLoading = function()
{
	log("MajikLoupe.hideLoading");
	this.progressBlock.style.display = 'none';
};

MajikLoupe.prototype.createStandardOverlays = function()
{			
	var closeBox = majik.createElement('a', {className:'majikCloseBox'},
											{position: 'absolute', display: 'block',
											 left: '-10px', top: '-10px', zIndex: 1000});
	//majik.container.appendChild(closeBox);
	this.lighttable.appendChild(closeBox);
	
	var nextButton = majik.createElement('a', {className:'majikNextButton'},
											{position: 'absolute', display: 'block',
											 right: '0px', top:'50px', zIndex: 1000});
	var prevButton = majik.createElement('a', {className:'majikPrevButton'},
											{position: 'absolute', display: 'block',
											 left: '0px', top:'50px', zIndex: 1000});
//	var playButton = majik.createElement('a', {className:'majikPlayButton'},
//											{position: 'absolute', display: 'block',
//											 left: '50%', top:'50px', zIndex: 1000});

	this.lighttable.appendChild(nextButton);
	this.lighttable.appendChild(prevButton);
//	this.lighttable.appendChild(playButton);
	
//	var zoomButton = majik.createElement('a', {className:'majikZoomButton', target:'_blank'},
//											{position: 'absolute', display: 'block',
//											 left: '100px', top:'0px',
//											 zIndex: 1000});
//	this.lighttable.appendChild(zoomButton);

	if (this.hasFolioView())
		{
		var folioButton = majik.createElement('a', {className: 'majikFolioButton', target:'_blank',
												href: this.altref() },
												{display: 'block', textAlign: 'right',
												position: 'absolute', right: '10px', bottom: '20px', zIndex: 1000},
												[document.createTextNode(majik.getTextForEntity('&raquo;'))]);
		this.lighttable.appendChild(folioButton);
		}
		
	nextButton.observe('click', majik.next);
	prevButton.observe('click', majik.previous);
	closeBox.observe('click', majik.bind(this, this.close));

	this.addOverlay([closeBox, nextButton, prevButton]);
	this.hideOverlays();
};

MajikLoupe.prototype.respondToNavClick = function(event)
{
	var button = event.element();
	
};

MajikLoupe.prototype.addOverlay = function(overlays)
{
	$A(overlays).each( (function(overlay) {
		if (this.overlays.indexOf(overlay) < 0)
			this.overlays.push(overlay);
		}).bind(this));
};

MajikLoupe.prototype.removeOverlay = function(overlays)
{
	$A(overlays).each( (function(overlay) {
		this.overlays = this.overlays.without(overlay);
		}).bind(this) );
};

MajikLoupe.prototype.altref = function()
{
	return this.a.getAttribute('altref');
};

MajikLoupe.prototype.hide = function(keepDarkBox)
{
	var idx = this.idx;
	if (this.lighttable.parentNode != null)
		majik.activeLoupes--;
		
	this.content.style.cursor = 'default';
	this.lighttable.style.width = 'auto';
	this.lighttable.parentNode.removeChild(this.lighttable);
	if (!majik.saveLoupePositions)
		{
		this.lighttable.style.top = this.home.top + 'px';
		this.lighttable.style.left = this.home.left + 'px';
		}
	
	if (!keepDarkBox)
		majik.hideDarkBox();
};

MajikLoupe.prototype.close = function()
{
	this.zoomOut(false);
};

MajikLoupe.prototype.closeKeepingDarkBox = function()
{
	this.zoomOut(true);
};

MajikLoupe.prototype.bringToFront = function()
{
	var myZIndex = this.lighttable.style.zIndex;
	for (var i = 0; i < majik.loupeCount; i++)
		{
		if (i != this.idx && majik.loupes[i].isVisible())
			{
			var zIndex = majik.loupes[i].lighttable.style.zIndex;
			if (zIndex > myZIndex)
				{
				majik.loupes[i].lighttable.style.zIndex = --zIndex;
				}
			}
		}
	this.lighttable.style.zIndex = majik.activeLightBoxZIndex();
	
};

MajikLoupe.prototype.select = function()
{
	this.plexiglass.width = this.content.width;
	this.plexiglass.height = this.content.height;
	this.plexiglass.title = this.content.title;
	var hidden = !this.isVisible();
	if (hidden)
		{
		majik.container.appendChild(this.lighttable);
		majik.activeLoupes++;
		}
	this.bringToFront();
	if (hidden || this.isClosing())
		this.zoomIn();
};

MajikLoupe.prototype.isVisible = function()
{
	return (this.lighttable.parentNode != null 
			&& this.lighttable.parentNode.nodeType != Node.DOCUMENT_FRAGMENT_NODE);
};

MajikLoupe.prototype.isSelected = function()
{
	if (!this.isVisible())
		return false;
		
	for (var i = 0; i < majik.loupeCount; i++)
		{
		if (i != this.idx && majik.loupes[i].isVisible())
			{
			if (majik.loupes[i].lighttable.style.zIndex > this.lighttable.style.zIndex)
				return false;
			}
		}
	return true;
};

MajikLoupe.prototype.showOverlays = function()
{
	this.overlays.each( function(overlay) { overlay.style.visibility = ''; } );
};

MajikLoupe.prototype.hideOverlays = function()
{
	this.overlays.each( function(overlay) {
			overlay.style.visibility = 'hidden';
		} );
};

MajikLoupe.prototype.onMouseOver = function() 
{
	//this.showOverlays();
};

MajikLoupe.prototype.onMouseOut = function(/*rel*/) 
{
	//this.hideOverlays();
/*	this.overlays.each( function(overlay) {
		var node = rel;
		while (node && node.parentNode)
			{
			if (node == overlay)
				return;
			node = node.parentNode;
			}
		if (overlay.getAttribute['hideOnMouseOut'])
			overlay.style.visibility = 'hidden';
		}); */
};

MajikLoupe.prototype.zoomedTargetPosition = function()
{
	if (majik.zoomToWindowCenter)
		var wsize = majik.windowSize();

	var c = majik.zoomToWindowCenter 
				? {x: wsize.width/2, y: wsize.height/2}
				: {x: this.home.left + 32, y: this.home.top + 32};
	
	return {left: Math.max(0, c.x - this.finalWidth/2),
			top:  Math.max(0, c.y - this.finalHeight/2)};
};

MajikLoupe.prototype.zoomIn = function()
{
	var finalWidth = this.finalWidth || this.content.width;
	var finalHeight = this.finalHeight || this.content.height;
	
	this.content.style.width = this.thumbWidth + 'px';
	this.content.style.height = this.thumbHeight + 'px';
	this.content.style.visibility = 'visible';

	this.plexiglass.width = 0;
	this.plexiglass.height = 0;
	
	if (this.animation != null)
		this.animation.cancel();
		
	var param=[	{ element: this.content, 
				  options: { sizeEnd:{width:finalWidth, height:finalHeight},
				  			 borderWidth: this.finalBorderWidth,
				  			 borderWidthStart: this.thumbBorderWidth} },
				//{ element: $(this.content.parentNode),
				{ element: this.lighttable,
				  options: { posStart:{top:this.home.top, left:this.home.left},
							 posEnd: this.zoomedTargetPosition(),
							 sizeEnd:{width:finalWidth+22, height:finalHeight+22},
							 paddingStart: [0,0,0,0],
							 paddingLeftStart: 0,
							 paddingRightStart: 0,
							 paddingTopStart: 0,
							 paddingBottomStart: 0,
							 paddingLeft: this.lighttable.getStyle('paddingLeft'),
							 paddingTop:  this.lighttable.getStyle('paddingTop'),
							 paddingRight: this.lighttable.getStyle('paddingRight'),
							 paddingBottom: this.lighttable.getStyle('paddingBottom')
							 , opacity: 1.0
							 } },
				{ element: majik.darkbox,
				  options: { opacity: majik.darkBoxOpacity } }];
				  
	if (majik.darkbox != null && majik.obscurePageWhileViewing)
		majik.resizeDarkBox();
	else
		param.pop();
		
	this.animation = new MajikAnim(param, {finishFunction: (function() {
										this.animation = null;
										this.plexiglass.width = this.content.width;
										this.plexiglass.height = this.content.height;
										if (this.hasFolioView())
											majik.setProxyLink(this.altref(), true);
										else
											majik.hideProxyLink();
										this.status = 'active';
										this.textDiv.innerText = this.thumb.title;
										this.showOverlays();
										}).bind(this)});
	this.status = 'opening';
};

/*MajikLoupe.prototype.finishZoomOut = function(keepDarkBox)
{
	this.animation = null;
	this.hide(keepDarkBox);
	this.status = 'closed';
};*/

MajikLoupe.prototype.zoomOut = function(keepDarkBox)
{
	this.plexiglass.width = 0;
	this.plexiglass.height = 0;
	if (this.animation != null)
		this.animation.cancel();

	var param = [
				{element: this.content,
				 options: {sizeEnd:{width:this.thumbWidth, height: this.thumbHeight},
				 		   borderWidth: this.thumbBorderWidth}},
				 
				{element: this.lighttable,
				 options: {posStart:{top: parseInt(this.lighttable.style.top),
										 left: parseInt(this.lighttable.style.left)},
						   posEnd:{top:this.home.top, left:this.home.left},
						   sizeEnd:{width:0, height:0}
						   }},
				
				{element: majik.darkbox,
				 options: {opacity: 0.0}}
				 ];

	if (null == majik.darkbox || !majik.obscurePageWhileViewing || keepDarkBox)
		param.pop();

	this.hideOverlays();
	this.textDiv.innerText = '';
	this.animation = new MajikAnim(param, 
								{fast: true,
								// finishFunction: this.finishZoomOut.bind(this, keepDarkBox)});
								finishFunction: (function (keepDarkBox) {
									this.animation = null;
									this.hide(keepDarkBox);
									this.status = 'closed';
									}).bind(this,keepDarkBox)});

	this.status = 'closing';							
};

MajikLoupe.prototype.isClosing = function()
{
	return this.animation && this.status == 'closing';
};

MajikLoupe.prototype.isOpening = function()
{
	return this.animation && this.status == 'opening';
};

function log(foo)
{
	majik.log(foo);
}

function assert(val)
{
	if (!val)
		{
		var args = $A(arguments);
		args.shift();
		log("assertion failed" + (!args.length ? "" :(": "+args.concat())));
		}
}

document.observe('dom:loaded',majik.handleDocumentLoad);
