/*
 Preview Box

 (c) 2007-2009, RAWR-Designs, Some Rights Reserved -
	Christopher "That Stevens Guy" Stevens
	Richard "Giant Eagle" Tuininga
 (CC) http://creativecommons.org/licenses/by-nc-sa/3.0/

 Any queries? -
	Email: contact[at]rawr-designs.com
	Forum: http://www.rejetto.com/forum/index.php?board=34.0
 	Homepage: http://www.rawr-designs.com/	
*/

function rawrBoxClass()
{
	//-- Configurable settings --//
	//- General settings -//
	this.fade_fps					= 1000 / 60;// The approximate fps we should aim for
	this.heightOffset				= 50;		// The offset from the top of the page in pixels
	this.enablePreload				= 1;		// Preload images in a group
	
	//- Overlay fade settings -//
	this.overlay_fadeIn				= 0; 		// 1 = enabled, 0 = disabled
	this.overlay_fadeIn_speed		= 150; 		// in ms (1000ms = 1s)
	this.overlay_fadeIn_opacity		= 80; 		// Visbibility in percents (100% = pure black, 0% = invisible)
	this.overlay_fadeOut			= 1; 		// 1 = enabled, 0 = disabled
	this.overlay_fadeOut_speed		= 200; 		// in ms (1000ms = 1s)
	
	//- Stage fade settings -//
	this.stage_fadeIn				= 1; 		// 1 = enabled, 0 = disabled
	this.stage_fadeIn_speed			= 300; 		// in ms (1000ms = 1s)
	this.stage_fadeOut				= 0;		// 1 = enabled, 0 = disabled
	this.stage_fadeOut_speed		= 75;		// in ms (1000ms = 1s)
	
	//- Image fade settings -//
	this.image_fadeIn				= 1;
	this.image_fadeIn_speed			= 300;
	
	this.initialize();
	
	/*
	To-Do List:
		[fix] IE6 cannot use fixed positioning, must use absolute and possible javascript to hold the overlay center.
		
		[to-do] Integrate the close button (<a href=""><img title="Close Preview" src="close.gif" alt="X" height="30" width="30" align="top" id="rbCloseButton"></a>)
		[to-do] Image scaling, scale the image so the box stays within the bounds of the browser
		[to-do] Title value? title="This image blah blah..." it replaces filename.
		[to-do] If no image available, end slideshow, show an error (loading icon with next/prev button... maybe), something?
		[to-do] Prevent objects from coming back to the stage whilst fading.
		
		ONLY THESE THINGS TO GO then we can release the code :D
	*/
	
}

rawrBoxClass.prototype.initialize = function()
{
	//- Overlay settings -//
	this.obj_body = document.getElementsByTagName("body")[0];
	this.obj_overlay = document.createElement("div");
		//- With this.obj_overlay -//
		this.obj_overlay.setAttribute('id', 'rbOverlay');
		this.obj_overlay.setAttribute('name', 'rbOverlay');
		if (!this.overlay_fadeIn && !this.overlay_fadeOut) {
			this.obj_overlay.style.opacity = this.overlay_fadeIn_opacity / 100;
			this.obj_overlay.style.filter = "alpha(opacity=" + this.overlay_fadeIn_opacity + ")";
		}
		this.obj_overlay.style.display = "none";
	this.obj_body.appendChild( this.obj_overlay );
	this.overlay_state = 0;
	//- Main stage -//
	this.obj_stage = document.createElement("div");
		//- With this.obj_stage -//
		this.obj_stage.setAttribute('id', 'rbStage');
		this.obj_stage.setAttribute('name', 'rbStage');
		this.obj_stage.style.display = "none";
		//- Main stage - container -//
		this.obj_stage_container = document.createElement("div");
			//- With this.obj_stage_container -//
			this.obj_stage_container.setAttribute('id', 'rbStageContainer');
			this.obj_stage_container.setAttribute('name', 'rbStageContainer');
		this.obj_stage.appendChild( this.obj_stage_container );
		//- Title bar -//
		this.obj_stage_caption = document.createElement("div");
			//- With this.obj_caption -//
			this.obj_stage_caption.setAttribute('id', 'rbStageCaption');
			this.obj_stage_caption.setAttribute('name', 'rbStageCaption');
		this.obj_stage.appendChild( this.obj_stage_caption );
	this.obj_body.appendChild( this.obj_stage );
	this.stage_state = 0;
	//- Array items -//
	this.current_imageArray = new Array();
	this.current_imageArray_loaded = new Array();
	this.current_image = new Image();
	if (this.enablePreload) {
		this.next_image = new Image();
		this.prev_image = new Image();
	}
	//- Catch all elements with a relative set to rawrBox -//
	var objs_temp = document.getElementsByTagName("a");
	for (i in objs_temp)
		if (String(objs_temp[i].rel).toLowerCase().match("^rawrbox") == "rawrbox")
			objs_temp[i].onclick = function() { rawrBox.showBox(this); return false; }
}

rawrBoxClass.prototype.showBox = function(element)
{
	if (!element)
		return false;
	
	var href = element.getAttribute('href');
	var rel = element.getAttribute('rel').toLowerCase();
	
	if (href.match(".(jpg|jpeg|png|bmp)$").length > 0) {
		this.current_imageArray = new Array();
		this.current_imageArray_loaded = new Array();
		
		if (rel.indexOf("[") == 7 && rel.indexOf("]") == rel.length - 1) {
			var groupname = rel.substr(8, rel.length - 9);
			var objs_temp = document.getElementsByTagName("a");
			for (i in objs_temp) {
				try {
					if (String(objs_temp[i].rel).toLowerCase() == rel) {
						if (this.current_imageArray.inArray(objs_temp[i].getAttribute('href')) == -1) {
							this.current_imageArray[this.current_imageArray.length] = objs_temp[i].getAttribute('href');
							this.current_imageArray_loaded[this.current_imageArray_loaded.length] = false;
						}
					}
				} catch(ex) {}
			}
		}
		
		/* Hide all embedded objects */
		var objects = document.getElementsByTagName('OBJECT');
		for (i=0; i<objects.length; i++) objects[i].style.display = 'none';
		
		if (this.current_imageArray.length == 0) {
			this.current_imageArray[0] = href;
		}
		
		if (this.overlay_state)	{
			this.onClickHandler(2);
			setTimeout("rawrBox.changeContent('image', " + (this.current_imageArray.inArray(href)) + ");", 50);
		} else {
			this.resetLoadingState();
			this.resetCaptionState();
			this.current_image = new Image();
			this.current_image.src = href;
			this.toggleOverlay(true, "rawrBox.toggleStage(true, \"rawrBox.changeContent('image', " + (this.current_imageArray.inArray(href)) + ", 1);\");");
		}
	} else {
		// HTML BOX
	}
}

rawrBoxClass.prototype.closeBox = function()
{
	if (!this.overlay_state)
		this.toggleOverlay(!this.overlay_state, "rawrBox.toggleStage(!rawrBox.stage_state);");
	else
		this.toggleStage(!this.stage_state, "rawrBox.toggleOverlay(!rawrBox.overlay_state);");
		
	/* Show all embedded objects */
	var objects = document.getElementsByTagName('OBJECT');
	for (i=0; i<objects.length; i++) objects[i].style.display = '';
}

rawrBoxClass.prototype.changeContent = function(type, itemid, parm2, parm3)
{
	switch (type)
	{
		case "image":
			// New image, initial call
			if (!parm2)
			{
				this.current_image = new Image()
				this.current_image.src = this.current_imageArray[itemid];
				if (!parm3)
					// This means there is no overlay yet
					setTimeout("rawrBox.changeContent('" + type + "', " + (itemid) + ", 1, 1);", 100);
				else
					// This means there is already an overlay
					setTimeout("rawrBox.changeContent('" + type + "', " + (itemid) + ", 2, 1);", 100);
			}
			else if (this.current_image.complete)
			{
				this.current_imageArray_loaded[itemid] = true;
				if (parm2 == 1)
				{
					this.obj_stage_container.innerHTML = "";
					this.obj_stage_container.style.width = this.current_image.width + "px";
					this.obj_stage_container.style.height = this.current_image.height + "px";
					var node = document.createElement("img");
					node.src = this.current_image.src;
					node.id = "rbContentImage";
					if (this.image_fadeIn)
					{
						node.style.opacity = 0;
						node.style.filter = "alpha(opacity=0)";
					}
					this.obj_stage_container.appendChild(node);
					if (this.image_fadeIn)
					{
						setTimeout("rawrBox.fadeIn(\"rbContentImage\", -1, " + (this.image_fadeIn_speed) + ", 100);", 1);
					}
					this.changeContent('image', itemid, 2, 0);
				}
				else if (parm2 == 2)
				{
					if (parm3)
					{
						this.obj_stage_container.innerHTML = this.obj_stage_caption.innerHTML = "";
						this.obj_stage_container.style.width = this.current_image.width + "px";
						var node = document.createElement("img");
						node.src = this.current_image.src;
						node.id = "rbContentImage";
						if (this.image_fadeIn)
						{
							node.style.opacity = 0;
							node.style.filter = "alpha(opacity=0)";
						}
						this.obj_stage_container.appendChild(node);
					}
					this.obj_stage_caption.style.width = this.current_image.width + "px";
					if (this.current_imageArray.length > 1)
					{
						var previous = next = caption = "";
						
						// Generate a previous button
						if (itemid - 1 >= 0)
						{
							var span = document.createElement("span");
							span.style.styleFloat = span.style.cssFloat = "left";
							
							var anc = document.createElement("a");
							anc.href = "javascript:rawrBox.changeContent(\"image\"," + (itemid - 1) + ",0,1);";
							var img = document.createElement("img");
							img.src = "/stevens/code/rawr_box/back.gif";	img.width = "30";	img.height = "30";	img.align = "top";
							
							anc.appendChild(img);
							span.appendChild(anc);
							
							if (this.enablePreload && !this.current_imageArray_loaded[itemid - 1]) {
								var load = document.createElement("img");
								load.src = "/stevens/code/rawr_box/loading.gif";	load.width = "30";	load.height = "30";	load.align = "top";
								load.id = "rbLoadPrev";
								span.appendChild(load);
								setTimeout("rawrBox.preloadImage("+(itemid-1)+", 1);", this.image_fadeIn_speed + 200);
							}
							
							this.obj_stage_caption.appendChild(span);
						}
						
						// Generate a next button
						if (this.current_imageArray.length > itemid + 1)
						{
							var span = document.createElement("span");
							span.style.styleFloat = span.style.cssFloat = "right";
							
							if (this.enablePreload && !this.current_imageArray_loaded[itemid + 1]) {
								var load = document.createElement("img");
								load.src = "/stevens/code/rawr_box/loading.gif";	load.width = "30";	load.height = "30";	load.align = "top";
								load.id = "rbLoadNext";
								span.appendChild(load);
								setTimeout("rawrBox.preloadImage("+(itemid+1)+", 2);", this.image_fadeIn_speed + 200);
							}
							
							var anc = document.createElement("a");
							anc.href = "javascript:rawrBox.changeContent(\"image\"," + (itemid + 1) + ",0,1);";
							var img = document.createElement("img");
							img.src = "/stevens/code/rawr_box/next.gif";	img.width = "30";	img.height = "30";	img.align = "top";
							
							anc.appendChild(img);
							span.appendChild(anc);
							this.obj_stage_caption.appendChild(span);
						}
						
						var div = document.createElement("div");
						div.style.clear = "both";
						this.obj_stage_caption.appendChild(div);
						
						var span = document.createElement("span");
						span.style.position = "relative";
						span.style.top = "-30px";
						span.innerHTML = /*(this.current_imageArray[itemid].substring(this.current_imageArray[itemid].lastIndexOf("/") + 1)) +*/ "Captions, IE6 Compatibility and a visible Close button are Coming Soon! &nbsp; (" + (itemid + 1) + " of " + ( this.current_imageArray.length ) + ")";
						this.obj_stage_caption.appendChild(span);
					}
					else
					{
						this.obj_stage_caption.innerHTML = (this.current_imageArray[itemid].substring(this.current_imageArray[itemid].lastIndexOf("/") + 1));
					}
					this.obj_stage_container.style.height = this.current_image.height + "px";
					if (this.image_fadeIn && parm3)
					{
						this.fadeIn("rbContentImage", -1, this.image_fadeIn_speed, 100);
					}
				}
			}
			else
			{
				if (this.stage_state) {
					this.resetLoadingState();
					//this.resetCaptionState();
					if (!parm3)
						parm3 = 0;
					setTimeout("rawrBox.changeContent('" + type + "', " + (itemid) + ", " + (parm2) + ", " + (parm3) + ");", 100);
				}
			}
		break;
	}
}

rawrBoxClass.prototype.preloadImage = function(itemid, type, stage)
{
	if (type == 1) { // Previous image
		if (!stage) {
			this.prev_image = new Image();
			this.prev_image.src = this.current_imageArray[itemid];
				setTimeout("rawrBox.preloadImage("+itemid+", 1, 1);", 100);
		} else if (stage == 1) {
			if (this.prev_image.complete) {
				try {
					var node = document.getElementById("rbLoadPrev").parentNode;
					node.removeChild(node.childNodes[1]);
				} catch(ex) {}
			} else {
				setTimeout("rawrBox.preloadImage("+itemid+", 1, 1);", 500);
			}
		}
	} else if (type == 2) { // Next image
		if (!stage) {
			this.next_image = new Image();
			this.next_image.src = this.current_imageArray[itemid];
				setTimeout("rawrBox.preloadImage("+itemid+", 2, 1);", 100);
		} else if (stage == 1) {
			if (this.next_image.complete) {
				try {
					var node = document.getElementById("rbLoadNext").parentNode;
					node.removeChild(node.childNodes[0]);
				} catch(ex) {}
			} else {
				setTimeout("rawrBox.preloadImage("+itemid+", 2, 1);", 500);
			}
		}
	}
}

rawrBoxClass.prototype.onClickHandler = function(state)
{
	if (!state || state == 2)
		document.onclick = function() {}
	if (state)
		setTimeout("document.onclick = function(e){rawrBox.test(e);}", 500);
}

rawrBoxClass.prototype.test = function(e) {
	var e = e || window.event;
	var target = e.target || window.event.srcElement;
	if (target.getAttribute('id') != "rbStageContainer" && target.getAttribute('id') != "rbStageCaption")
	{
		try
		{
			while (target.parentNode)
			{
				target = target.parentNode
				if (target.getAttribute('id') == "rbStageContainer" || target.getAttribute('id') == "rbStageCaption")
				{
					break;
				}
			}
		}
		catch(err)
		{
			rawrBox.closeBox();
		}
	}
}

//-- Disable or enable the overlay shadow --//
rawrBoxClass.prototype.toggleOverlay = function(state, func) 
{
	state = (state) || false;
	if (state != this.overlay_state) {
		this.onClickHandler(state);
		if (this.overlay_fadeIn || this.overlay_fadeOut)
		{
			if ((state && this.overlay_fadeIn) || (!state && this.overlay_fadeOut))
			{
				this.overlay_state = state;
				if (state)
				{
					//- Fade in -//
					this.fadeIn( this.obj_overlay.getAttribute('id'), func, this.overlay_fadeIn_speed, this.overlay_fadeIn_opacity );
				}
				else
				{
					//- Fade out -//
					this.fadeOut( this.obj_overlay.getAttribute('id'), func, this.overlay_fadeOut_speed );
				}
			}
			else
			{
				this.overlay_state = state;
				if (state)
				{
					this.obj_overlay.style.opacity = this.overlay_fadeIn_opacity / 100;
					this.obj_overlay.style.filter = "alpha(opacity=" + this.overlay_fadeIn_opacity + ")";
					this.obj_overlay.style.display = "";
				}
				else
				{
					this.obj_overlay.style.opacity = 0;
					this.obj_overlay.style.filter = "alpha(opacity=0)";
					this.obj_overlay.style.display = "none";
				}
				if (func)
					setTimeout(func, 1);
			}
		}
		else
		{
			this.overlay_state = state;
			if (state)
			{
				this.obj_overlay.style.display = "";
			}
			else
			{
				this.obj_overlay.style.display = "none";
			}
			if (func)
				setTimeout(func, 1);
		}
	}
}

//-- Disable or enable the overlay shadow --//
rawrBoxClass.prototype.toggleStage = function(state, func) 
{
	state = (state) || false;
	if (state != this.stage_state)
	{
		if (state)
			this.obj_stage.style.top = (this.getScrollHeight() + this.heightOffset) + "px";
		if (this.stage_fadeIn || this.stage_fadeOut)
		{
			if ((state && this.stage_fadeIn) || (!state && this.stage_fadeOut)) {
				this.stage_state = state;
				if (state)
				{
					//- Fade in -//
					this.fadeIn( this.obj_stage.getAttribute('id'), func, this.stage_fadeIn_speed, 100 );
				}
				else
				{
					//- Fade out -//
					this.fadeOut( this.obj_stage.getAttribute('id'), func, this.stage_fadeOut_speed );
				}
			}
			else
			{
				this.stage_state = state;
				if (state)
				{
					this.obj_stage.style.opacity = 1;
					this.obj_stage.style.filter = "alpha(opacity=100)";
					this.obj_stage.style.display = "";
				}
				else
				{
					this.obj_stage.style.opacity = 0;
					this.obj_stage.style.filter = "alpha(opacity=0)";
					this.obj_stage.style.display = "none";
				}
				if (func)
					setTimeout(func, 1);
			}
		} else {
			this.stage_state = state;
			if (state)
			{
				this.obj_stage.style.display = "";
			}
			else
			{
				this.obj_stage.style.display = "none";
			}
			if (func)
				setTimeout(func, 1);
		}
	}
}

rawrBoxClass.prototype.fadeIn = function(id, func, speed, opacity, fadeInTimer)
{
	//- Prechecks -//
	var obj = document.getElementById(id).style;
	if (!fadeInTimer)
	{
		fadeInTimer = new Date().getTime();
		obj.opacity = 0;
		obj.filter = "alpha(opacity=0)";
		obj.display = "";
	}
	var newOpacity = ((new Date().getTime() - fadeInTimer) / speed) * opacity;
	if (newOpacity >= opacity)
	{
		obj.opacity = opacity / 100;
		obj.filter = "alpha(opacity=" + opacity + ")";
		if (func)
			setTimeout(func, 1);
	}
	else
	{
		obj.opacity = newOpacity / 100;
		obj.filter = "alpha(opacity=" + newOpacity + ")";
		setTimeout("rawrBox.fadeIn(\""+id+"\", \""+func+"\", \""+speed+"\", \""+opacity+"\", \""+fadeInTimer+"\");", this.fade_fps);
	}
}

rawrBoxClass.prototype.fadeOut = function(id, func, speed, opacity, fadeOutTimer)
{
	//- Prechecks -//
	var obj = document.getElementById(id).style;
	if (!fadeOutTimer)
	{
		opacity = (obj.opacity * 100) || 100;
		fadeOutTimer = new Date().getTime();
	}
	var newOpacity = (1 - (new Date().getTime() - fadeOutTimer) / speed) * opacity;
	if (newOpacity <= 0)
	{
		obj.opacity = 0;
		obj.filter = "alpha(opacity=0)";
		obj.display = "none";
		if (func)
			setTimeout(func, 1);
	}
	else
	{
		obj.opacity = newOpacity / 100;
		obj.filter = "alpha(opacity=" + newOpacity + ")";
		setTimeout("rawrBox.fadeOut(\""+id+"\", \""+func+"\", \""+speed+"\", \""+opacity+"\", \""+fadeOutTimer+"\");", this.fade_fps);
	}
}

//= Snatched from: http://www.west-wind.com/WebLog/posts/4607.aspx =//
rawrBoxClass.prototype.getScrollHeight = function()
{
	var ScrollTop = document.body.scrollTop;
	if (!ScrollTop)
	{
		if (window.pageYOffset)
		{
			ScrollTop = window.pageYOffset;
		}
		else
		{
			ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
		}
	}
	return ScrollTop;
}

//= Snatched from: http://www.sean.co.uk/a/webdesign/javascriptdelay.shtm =//
rawrBoxClass.prototype.pause = function(ms)
{
	var date = new Date();
	var curDate = null;

	do { curDate = new Date(); }
	while(curDate-date < ms);
} 

rawrBoxClass.prototype.resetLoadingState = function()
{
	if (this.obj_stage_container.style.width != "65px") {
		this.resetCaptionState();
		this.obj_stage_container.style.width = "65px";
		this.obj_stage_container.style.height = "65px";
		this.obj_stage_container.innerHTML = "<img src='/stevens/code/rawr_box/loading.gif' alt=''/>";
	}
}

rawrBoxClass.prototype.resetCaptionState = function()
{
//	this.obj_stage_caption.style.width = "0";
//	this.obj_stage_caption.style.height = "0";
//	this.obj_stage_caption.style.padding = "0";
	this.obj_stage_caption.innerHTML = "";
}

//-- Initializes the whole thing --//
function initializeRawrBox()
{
	rawrBox = new rawrBoxClass();
}

//-- Initialize the whole thing onLoad --//
if (window.addEventListener)
{
	window.addEventListener("load", initializeRawrBox, false);
}
else if (window.attachEvent)
{
	window.attachEvent("onload", initializeRawrBox);
}
else
{
	window.onload = function() { initializeRawrBox(); }
}

//-- Other functions --//
Array.prototype.inArray = function(value)
{
	for (var i in this)
		if (this[i] === value)
			return i;
	return -1
}