// External Box
// 
// Every <a rel="externalbox-something">content</a> will have its 
// content copied to <div id="something"> when clicked

(function($)
{
	var sourceElements = {}; // sourceElements['id'] = domelement

	var relRegexp = /\sexternalbox-(\S+)\s/;
	var openbydefaultRegexp = /\sexternalboxopenbydefault\s/;
	$.ExternalBox = {
		disabled: false,
		
		setDisabled: function(disabled)
		{
			$.ExternalBox.disabled = disabled;
		}
	};
	
	$(function()
	{
		var a, links, rel, regexp, result;
		
		links = $('a[rel]').get();
		for (a = 0; a < links.length; a++)
		{
			rel = links[a].getAttribute("rel");
			if (!rel) continue;
			
			result = relRegexp.exec(" "+rel+" ");
			if (result)
			{
				// result[1] is the target id
				$(links[a]).bind("click", {targetId: result[1]}, externalbox_click);
				if (openbydefaultRegexp.test(" "+rel+" "))
					$(links[a]).click();
			}
		}
	});
	
	$.fn.externalbox = function()
	{
		var links, a, len, rel;
		links = $(this).get();
		
		for (a = 0, len = links.length; a < len; a++)
		{
			rel = links[a].getAttribute("rel");
			if (!rel) continue;
			
			result = relRegexp.exec(" "+rel+" ");
			if (result)
			{
				// result[1] is the target id
				$(links[a]).bind("click", {targetId: result[1]}, externalbox_click);
				if (openbydefaultRegexp.test(" "+rel+" "))
					$(links[a]).click();
			}
		}
	};
	
	function img_load(e)
	{
		var img = this;
		img.style.marginBottom = '1px';
		setTimeout(function() 
		{
			img.style.marginBottom = '';
		}, 0);
	}
	
	function externalbox_click(e)
	{
		var oldSource, source, target, a, len, imgs;
		if ($.ExternalBox.disabled) return;
		e.preventDefault();
		
		oldSource = sourceElements[e.data.targetid];
		sourceElements[e.data.targetid]	= source = this; // <a rel="externalbox-something">...</a>
		target = document.getElementById(e.data.targetId);
		if (!target) return;
		
		//remove any old elements in the div
		while (target.childNodes.length)
		{
			target.removeChild(target.firstChild);
		}
		
		//copy the content of this link
		for (a = 0, len = source.childNodes.length; a < len; a++)
		{
			target.appendChild(source.childNodes[a].cloneNode(true));
		}
		
		//Set the src of the image to the href of the <a>
		imgs = target.getElementsByTagName('img');
		for (a = 0, len = imgs.length; a < len; a++)
		{
			imgs[a].removeAttribute('width');
			imgs[a].removeAttribute('height');
			imgs[a].setAttribute('src', source.getAttribute('href'));
			
			imgs[a].onload = img_load;
		}
		
		$(source).addClass("externalbox-open");
		$(source.parentNode).addClass("externalbox-open");
		if (oldSource && oldSource !== source)
		{
			$(oldSource).removeClass("externalbox-open");
			$(oldSource.parentNode).removeClass("externalbox-open");
		}
		
		if (window.supersleight) //png fix
			supersleight.run(target);
	}
})(jQuery);