// minmax.js: make IE5+/Win support CSS min/max-width/height
// version 1.0, 08-Aug-2003
// written by Andrew Clover <and@doxdesk.com>, use freely

/*@cc_on
@if (@_win32 && @_jscript_version>4 && @_jscript_version<5.8)

var minmax_elements;

minmax_props= new Array(
  new Array('min-width', 'minWidth'),
  new Array('max-width', 'maxWidth'),
  new Array('min-height','minHeight'),
  new Array('max-height','maxHeight')
);

// Binding. Called on all new elements. If <body>, initialise; check all
// elements for minmax properties

function minmax_bind(el) {
  var i, em, ms;
  var st= el.style, cs= el.currentStyle;

  if (minmax_elements==window.undefined) {
    // initialise when body element has turned up, but only on IE
    if (!document.body || !document.body.currentStyle) return;
    minmax_elements= new Array();
    window.attachEvent('onresize', minmax_delayout);
    // make font size listener
    em= document.createElement('div');
    em.setAttribute('id', 'minmax_em');
    em.style.position= 'absolute'; em.style.visibility= 'hidden';
    em.style.fontSize= 'xx-large'; em.style.height= '5em';
    em.style.top='-5em'; em.style.left= '0';
    if (em.style.setExpression) {
      em.style.setExpression('width', 'minmax_checkFont()');
      document.body.insertBefore(em, document.body.firstChild);
    }
  }

  // transform hyphenated properties the browser has not caught to camelCase
  for (i= minmax_props.length; i-->0;)
    if (cs[minmax_props[i][0]])
      st[minmax_props[i][1]]= cs[minmax_props[i][0]];
  // add element with properties to list, store optimal size values
  for (i= minmax_props.length; i-->0;) {
    ms= cs[minmax_props[i][1]];
    if (ms && ms!='auto' && ms!='none' && ms!='0' && ms!='') {
      st.minmaxWidth= cs.width; st.minmaxHeight= cs.height;
      minmax_elements[minmax_elements.length]= el;
      // will need a layout later
      minmax_delayout();
      break;
  } }
}

// check for font size changes

var minmax_fontsize= 0;
function minmax_checkFont() {
  var fs= document.getElementById('minmax_em').offsetHeight;
  if (minmax_fontsize!=fs && minmax_fontsize!=0)
    minmax_delayout();
  minmax_fontsize= fs;
  return '5em';
}

// Layout. Called after window and font size-change. Go through elements we
// picked out earlier and set their size to the minimum, maximum and optimum,
// choosing whichever is appropriate

// Request re-layout at next available moment
var minmax_delaying= false;
function minmax_delayout() {
  if (minmax_delaying) return;
  minmax_delaying= true;
  window.setTimeout(minmax_layout, 0);
}

function minmax_stopdelaying() {
  minmax_delaying= false;
}

function minmax_layout() {
  window.setTimeout(minmax_stopdelaying, 100);
  var i, el, st, cs, optimal, inrange;
  for (i= minmax_elements.length; i-->0;) {
    el= minmax_elements[i]; st= el.style; cs= el.currentStyle;

    // horizontal size bounding
    st.width= st.minmaxWidth; optimal= el.offsetWidth;
    inrange= true;
    if (inrange && cs.minWidth && cs.minWidth!='0' && cs.minWidth!='auto' && cs.minWidth!='') {
      st.width= cs.minWidth;
      inrange= (el.offsetWidth<optimal);
    }
    if (inrange && cs.maxWidth && cs.maxWidth!='none' && cs.maxWidth!='auto' && cs.maxWidth!='') {
      st.width= cs.maxWidth;
      inrange= (el.offsetWidth>optimal);
    }
    if (inrange) st.width= st.minmaxWidth;

    // vertical size bounding
    st.height= st.minmaxHeight; optimal= el.offsetHeight;
    inrange= true;
    if (inrange && cs.minHeight && cs.minHeight!='0' && cs.minHeight!='auto' && cs.minHeight!='') {
      st.height= cs.minHeight;
      inrange= (el.offsetHeight<optimal);
    }
    if (inrange && cs.maxHeight && cs.maxHeight!='none' && cs.maxHeight!='auto' && cs.maxHeight!='') {
      st.height= cs.maxHeight;
      inrange= (el.offsetHeight>optimal);
    }
    if (inrange) st.height= st.minmaxHeight;
  }
}

// Scanning. Check document every so often until it has finished loading. Do
// nothing until <body> arrives, then call main init. Pass any new elements
// found on each scan to be bound   

var minmax_SCANDELAY= 500;

function minmax_scan() {
  var el;
  for (var i= 0; i<document.all.length; i++) {
    el= document.all[i];
    if (!el.minmax_bound) {
      el.minmax_bound= true;
      minmax_bind(el);
  } }
}

var minmax_scanner;
function minmax_stop() {
  window.clearInterval(minmax_scanner);
  minmax_scan();
}

minmax_scan();
minmax_scanner= window.setInterval(minmax_scan, minmax_SCANDELAY);
window.attachEvent('onload', minmax_stop);

@end @*/

/********************************************************************************************************************
* PopBox.js, v2.5 released December 18, 2007. Copyright (c) 2007, C6 Software, Inc. (http://www.c6software.com/)
* PopBox is released under the Creative Commons Attribution 3.0 license (http://creativecommons.org/licenses/by/3.0/)
* and is free to use in both commercial and non-commercial work, provided this header remains at the top.
* The latest version and documentation can be found at http://www.c6software.com/products/popbox/default.aspx.
* Questions and suggestions can be sent to john.reid@c6software.com. Please put "PopBox" somewhere in the
* email subject so I can easily filter. Send me your URL and I may post it!
* PopBox relies on many methods from Danny Goodman's (www.dannyg.com) javascript library DHTMLAPI.js
* and his books, without which scores of web developers would be totally lost. Thanks Danny.
********************************************************************************************************************/

// Seek nested NN4 layer from string name
function SeekLayer(doc, name) {
    var theObj;
    for (var i = 0; i < doc.layers.length; i++) {
        if (doc.layers[i].name == name) {
            theObj = doc.layers[i];
            break;
        }
        // dive into nested layers if necessary
        if (doc.layers[i].document.layers.length > 0) {
            theObj = SeekLayer(document.layers[i].document, name);
        }
    }
    return theObj;
}

// Convert object name string or object reference into a valid element object reference
function GetRawObject(obj) {
    var theObj;
    if (typeof obj == "string") {
		var isCSS = (document.body && document.body.style) ? true : false;
        if (isCSS && document.getElementById) {
            theObj = document.getElementById(obj);
        } else if (isCSS && document.all) {
            theObj = document.all(obj);
        } else if (document.layers) {
            theObj = SeekLayer(document, obj);
        }
    } else {
        // pass through object reference
        theObj = obj;
    }
    return theObj;
}

// Return the available content width and height space in browser window
function GetInsideWindowSize() {
    if (window.innerWidth) {
        return {x:window.innerWidth, y:window.innerHeight};
    } else if (document.compatMode && document.compatMode.indexOf("CSS1") >= 0) {
        return {x:document.body.parentNode.clientWidth, y:document.body.parentNode.clientHeight};
    } else if (document.body && document.body.clientWidth) {
        return {x:document.body.clientWidth, y:document.body.clientHeight};
    }
    return {x:0, y:0};
}

// Retrieve the padding around an object
function GetObjectPadding(obj) {
	var elem = GetRawObject(obj);

	var l = 0;
	var r = 0;
	var t = 0;
	var b = 0;
	if (elem.currentStyle)
	{
		if (elem.currentStyle.paddingLeft)
			l = parseInt(elem.currentStyle.paddingLeft, 10);
		if (elem.currentStyle.paddingRight)
			r = parseInt(elem.currentStyle.paddingRight, 10);
		if (elem.currentStyle.paddingTop)
			t = parseInt(elem.currentStyle.paddingTop, 10);
		if (elem.currentStyle.paddingBottom)
			b = parseInt(elem.currentStyle.paddingBottom, 10);
	}
	else if (window.getComputedStyle)
	{
		l = parseInt(window.getComputedStyle(elem,null).paddingLeft, 10);
		r = parseInt(window.getComputedStyle(elem,null).paddingRight, 10);
		t = parseInt(window.getComputedStyle(elem,null).paddingTop, 10);
		b = parseInt(window.getComputedStyle(elem,null).paddingBottom, 10);
	}
	if (isNaN(l) == true) l = 0;
	if (isNaN(r) == true) r = 0;
	if (isNaN(t) == true) t = 0;
	if (isNaN(b) == true) b = 0;

	return {l:(l),r:(r),t:(t),b:(b)};
}

// Retrieve the rendered size of an element
function GetObjectSize(obj)  {
    var elem = GetRawObject(obj);
    var w = 0;
    var h = 0;
    if (elem.offsetWidth) {
			w = elem.offsetWidth; h = elem.offsetHeight;
    } else if (elem.clip && elem.clip.width) {
			w = elem.clip.width; h = elem.clip.height;
    } else if (elem.style && elem.style.pixelWidth) {
			w = elem.style.pixelWidth; h = elem.style.pixelHeight;
    }
    
    w = parseInt(w, 10);
    h = parseInt(h, 10);
    
   // remove any original element padding
   var padding = GetObjectPadding(elem);
   w -= (padding.l + padding.r);
   h -= (padding.t + padding.b);

   return {w:(w), h:(h)};
}

// Return the element position in the page, not it's parent container
function GetElementPosition(obj)
{
	var elem = GetRawObject(obj);
	var left = 0;
	var top = 0;

	// add any original element padding
	var elemPadding = GetObjectPadding(elem);
	left = elemPadding.l;
	top = elemPadding.t;

	if (elem.offsetParent)
	{
		left += elem.offsetLeft;
		top += elem.offsetTop;
		var parent = elem.offsetParent;
		while (parent)
		{
			left += parent.offsetLeft;
			top += parent.offsetTop;
			var parentTagName = parent.tagName.toLowerCase();
			if (parentTagName != "table" &&
				parentTagName != "body" && 
				parentTagName != "html" && 
				parentTagName != "div" && 
				parent.clientTop && 
				parent.clientLeft)
			{
				left += parent.clientLeft;
				top += parent.clientTop;
			}

			parent = parent.offsetParent;
		}
	}
	else if (elem.left && elem.top)
	{
		left = elem.left;
		top = elem.top;
	}
	else
	{
		if (elem.x)
			left = elem.x;
		if (elem.y)
			top = elem.y;
	}
	return {x:left, y:top};
}

// return the number of pixels the scrollbar has moved the visible window
function GetScrollOffset()
{
    if (window.pageYOffset) {
        return {x:window.pageXOffset, y:window.pageYOffset};
    } else if (document.compatMode && document.compatMode.indexOf("CSS1") >= 0) {
        return {x:document.documentElement.scrollLeft, y:document.documentElement.scrollTop};
    } else if (document.body && document.body.clientWidth) {
        return {x:document.body.scrollLeft, y:document.body.scrollTop};
    }
    return {x:0, y:0};
}

function CreateRandomId()
{
	var randomNum = 0.0;
	while (randomNum == 0.0)
		randomNum = Math.random();
	var random = randomNum + "";
	return "id" + random.substr(2);
}

function MouseMoveRevert(e)
{
	if (pbMouseMoveRevert != null && pbMouseMoveRevert.length != 0)
	{
		var evt = (e) ? e : window.event;
		var mouse = {x:0, y:0};
		if (evt.pageX || evt.pageY)
		{
			mouse.x = evt.pageX;
			mouse.y = evt.pageY;
		}
		else if (evt.clientX || evt.clientY)
		{
			var scroll = GetScrollOffset();
			mouse.x = evt.clientX + scroll.x;
			mouse.y = evt.clientY + scroll.y;
		}
		
		for (var x = 0; x < pbMouseMoveRevert.length;)
		{
			if (pbMouseMoveRevert[x] != null)
			{
				var id = pbMouseMoveRevert[x].id;
				if (typeof popBox[id] != "undefined" && popBox[id] != null && popBox[id].hTarg != 0)
				{
					// if the mouse is outside the box then call revert
					if (mouse.x < popBox[id].xTarg || mouse.x > (popBox[id].xTarg + popBox[id].wTarg) || mouse.y < popBox[id].yTarg || mouse.y > (popBox[id].yTarg + popBox[id].hTarg))
					{
						var className = pbMouseMoveRevert[x].className;
						pbMouseMoveRevert.splice(x, 1);
						Revert(id, null, className);
						continue;
					}
				}				
			}
			
			x++;
		}
	}
}

// holds numerous properties related to position, size and motion
var popBox = new Array();
// holds positioning value for the z axis
var popBoxZ = 100;
// holds the popped image for each <img> tag with a pbsrc attribute
var pbSrc = new Array();
// holds the popbar function for each <img> tag with a pbShowPopBar attribute
var pbPopBarFunc = new Array();
// holds the array of image ids for onmousemove Revert calls
var pbMouseMoveRevert = null;

// add initialization to window.onload
if (typeof window.onload == 'function')
{
	var func = window.onload;
	window.onload = function(){func();InitPbSrc();InitPbPopBar();};
}
else
{
	window.onload = function(){InitPbSrc();InitPbPopBar();};
}

// loads all the popped src images
function InitPbSrc()
{
	var images = null;
	if (document.body)
	{
		if (document.body.getElementsByTagName)
			images = document.body.getElementsByTagName("img");
		else if (document.body.all)
			images = document.body.all.tags("img");
	}

	if (images != null)
	{
		for (var x = 0; x < images.length; x++)
		{
			var poppedSrc = images[x].getAttribute('pbSrc');
			if (poppedSrc != null)
			{
				if (images[x].id == "")
					images[x].id = CreateRandomId();
					
				if (pbSrc[images[x].id] == null)
				{
					pbSrc[images[x].id] = new Image();
					pbSrc[images[x].id].src = poppedSrc;
				}
			}
		}
	}
}

// adds PopBar to images
function InitPbPopBar()
{
	var images = null;
	if (document.body)
	{
		if (document.body.getElementsByTagName)
			images = document.body.getElementsByTagName("img");
		else if (document.body.all)
			images = document.body.all.tags("img");
	}

	if (images != null)
	{
		var imgArray = new Array();
		for (var x = 0; x < images.length; x++)
		{
			if (images[x].id == "")
				images[x].id = CreateRandomId();
			
			imgArray[x] = images[x];
		}

		for (var x = 0; x < imgArray.length; x++)
			CreatePopBar(imgArray[x]);
	}
}

// initialize default popbox object
function InitPopBox(obj)
{
	obj = GetRawObject(obj);
	if (typeof popBox[obj.id] != "undefined" && popBox[obj.id] != null)
		return obj;
		
	var parent = document.body;
	if (obj.id == "")
		obj.id = CreateRandomId();

	var elem = obj;
	var startPos = GetElementPosition(elem);
	var initSize = GetObjectSize(elem);

	if (elem.style.position == "absolute" || elem.style.position == "relative")
	{
		parent = elem.parentNode;
		startPos.x = parseInt(elem.style.left, 10);
		startPos.y = parseInt(elem.style.top, 10);
	}
	
	// if there is a pbsrc then create that, else if it's not absolute or relative then create a copy
	if (pbSrc[elem.id] != null || (elem.style.position != "absolute" && elem.style.position != "relative"))
	{
		var img = document.createElement("img");
		// copy image properties
		img.border = elem.border;
		img.className = elem.className;
		img.height = elem.height;
		img.id = "popcopy" + elem.id;
		img.src = (pbSrc[elem.id] != null) ? pbSrc[elem.id].src : elem.src;
		img.alt = elem.alt;
		img.title = elem.title;
		img.width = elem.width;
		img.onclick = elem.onclick;
		img.ondblclick = elem.ondblclick;
		img.onmouseout = elem.onmouseout;

		// remove event so the object doesn't jump
		elem.onmouseout = null;

		img.style.width = initSize.w;
		img.style.height = initSize.h;
		img.style.position = "absolute";
		img.style.left = startPos.x + "px";
		img.style.top = startPos.y + "px";
		img.style.cursor = elem.style.cursor;
		
		parent.appendChild(img);
		elem.style.visibility = "hidden";
		elem = img;
	}
	
	popBox[elem.id] = {	elemId:elem.id,
							xCurr:0.0,
							yCurr:0.0,
							xTarg:0.0,
							yTarg:0.0,
							wCurr:0.0,
							hCurr:0.0,
							wTarg:0.0,
							hTarg:0.0,
							xStep:0.0,
							yStep:0.0,
							wStep:0.0,
							hStep:0.0,
							xDelta:0.0,
							yDelta:0.0,
							wDelta:0.0,
							hDelta:0.0,
							xTravel:0.0,
							yTravel:0.0,
							wTravel:0.0,
							hTravel:0.0,
							velM:1.0,
							velS:1.0,
							interval:null,
							isAnimating:false,
							xOriginal:startPos.x,
							yOriginal:startPos.y,
							wOriginal:parseFloat(initSize.w),
							hOriginal:parseFloat(initSize.h),
							isPopped:false,
							fnClick:null,
							fnDone:null,
							fnPre:null,
							originalId:null,
							cursor:""
							};
							
	if (typeof obj.onclick == "function")
	{
		popBox[elem.id].fnClick = elem.onclick;
		
		if (popBoxAutoClose == true && (typeof obj.ondblclick != "function" || obj.ondblclick == null) && typeof obj.onmouseover != "function")
			elem.ondblclick = function(){Revert(elem.id, null, elem.className);};
	}

	if (popBoxAutoClose == true && typeof obj.onmouseover == "function" && (typeof obj.onmouseout != "function" || obj.onmouseout == null))
	{
		if (popBoxMouseMoveRevert == true)
		{
			if (pbMouseMoveRevert == null)
			{
				pbMouseMoveRevert = new Array();
				if (typeof document.onmousemove == 'function')
				{
					var func = document.onmousemove;
					document.onmousemove = function(e){func(e);MouseMoveRevert(e);};
				}
				else
				{
					document.onmousemove = MouseMoveRevert;
				}
			}
			
			pbMouseMoveRevert.push({id:elem.id, className:elem.className});
		}
		else
		{
			elem.onmouseout = function(){Revert(elem.id, null, elem.className);};
		}
	}

	if (obj.id != elem.id)
		popBox[elem.id].originalId = obj.id;
		
	return elem;
}

// calculate next steps and assign to style properties
function DoPopBox(elem)
{
	if (typeof elem == "string") elem = GetRawObject(elem);
	try
	{
		var bMDone = false;
		var bSDone = false;
		if ((popBox[elem.id].xTravel + Math.abs(popBox[elem.id].xStep)) < popBox[elem.id].xDelta)
		{
			var x = popBox[elem.id].xCurr + popBox[elem.id].xStep;
			elem.style.left = parseInt(x, 10) + "px";
			popBox[elem.id].xTravel += Math.abs(popBox[elem.id].xStep);
			popBox[elem.id].xCurr = x;
		} else {
			popBox[elem.id].xTravel += Math.abs(popBox[elem.id].xStep);
			elem.style.left = parseInt(popBox[elem.id].xTarg, 10) + "px";
			bMDone = true;
		}
		if ((popBox[elem.id].yTravel + Math.abs(popBox[elem.id].yStep)) < popBox[elem.id].yDelta)
		{
			var y = popBox[elem.id].yCurr + popBox[elem.id].yStep;
			elem.style.top = parseInt(y, 10) + "px";
			popBox[elem.id].yTravel += Math.abs(popBox[elem.id].yStep);
			popBox[elem.id].yCurr = y;
			bMDone = false;
		} else {
			popBox[elem.id].yTravel += Math.abs(popBox[elem.id].yStep);
			elem.style.top = parseInt(popBox[elem.id].yTarg, 10) + "px";
		}
		if ((popBox[elem.id].wTravel + Math.abs(popBox[elem.id].wStep)) < popBox[elem.id].wDelta)
		{
			var w = popBox[elem.id].wCurr + popBox[elem.id].wStep;
			elem.style.width = parseInt(w, 10) + "px";
			popBox[elem.id].wTravel += Math.abs(popBox[elem.id].wStep);
			popBox[elem.id].wCurr = w;
		} else {
			popBox[elem.id].wTravel += Math.abs(popBox[elem.id].wStep);
			elem.style.width = parseInt(popBox[elem.id].wTarg, 10) + "px";
			bSDone = true;
		}
		if ((popBox[elem.id].hTravel + Math.abs(popBox[elem.id].hStep)) < popBox[elem.id].hDelta)
		{
			var h = popBox[elem.id].hCurr + popBox[elem.id].hStep;
			elem.style.height = parseInt(h, 10) + "px";
			popBox[elem.id].hTravel += Math.abs(popBox[elem.id].hStep);
			popBox[elem.id].hCurr = h;
			bSDone = false;
		} else {
			popBox[elem.id].hTravel += Math.abs(popBox[elem.id].hStep);
			elem.style.height = parseInt(popBox[elem.id].hTarg, 10) + "px";
		}

		var obj = elem;
		
		if (bMDone == true && bSDone == true)
		{
			clearInterval(popBox[elem.id].interval);
			
			elem.style.cursor = popBox[elem.id].cursor;

			var func = null;
			if (popBox[elem.id].fnDone != null && typeof popBox[elem.id].fnDone == "function")
				func = popBox[elem.id].fnDone;
			
			if (popBox[elem.id].isPopped == true)
			{
				elem.style.zIndex = null;
	
				if (popBox[elem.id].originalId != null)
				{
					obj = GetRawObject(popBox[elem.id].originalId);
					obj.onmouseout = elem.onmouseout; // copy method back to original
					obj.style.visibility = "visible";
					
					// remove the copied object from the body and the array
					elem.parentNode.removeChild(elem);
				}
				else
				{
					elem.style.width = parseInt(popBox[elem.id].wOriginal, 10) + "px";
					elem.style.height = parseInt(popBox[elem.id].hOriginal, 10) + "px";
				
					if (typeof popBox[elem.id].fnClick == "function")
						elem.onclick = popBox[elem.id].fnClick;
				}

				delete popBox[elem.id];
				popBox[elem.id] = null;
				CreatePopBar(obj);
			}
			else
			{
				popBox[elem.id].isPopped = true;
				popBox[elem.id].isAnimating = false;
				CreateRevertBar(elem);
			}
				
			if (func != null && typeof func == "function")
				func(obj);
		}
	}
	catch(ex){}
}

function HasRevertBar(obj)
{
	if (typeof obj == "string") obj = GetRawObject(obj);
	
	var elem = obj;
	if (popBox[elem.id] != null && popBox[elem.id].originalId != null)
		elem = GetRawObject(popBox[elem.id].originalId);

	var pbShowBar = elem.getAttribute('pbShowRevertBar');
	var pbShowText = elem.getAttribute('pbShowRevertText');
	var pbShowImage = elem.getAttribute('pbShowRevertImage');
	pbShowBar = (pbShowBar != null) ? (pbShowBar == "true" || pbShowBar == true) : popBoxShowRevertBar;
	pbShowText = (pbShowText != null) ? (pbShowText == "true" || pbShowText == true) : popBoxShowRevertText;
	pbShowImage = (pbShowImage != null) ? (pbShowImage == "true" || pbShowImage == true) : popBoxShowRevertImage;
	
	return (pbShowBar || pbShowText || pbShowImage);
}

function HasCaption(obj)
{
	if (typeof obj == "string") obj = GetRawObject(obj);
	var elem = obj;
	if (popBox[elem.id] != null && popBox[elem.id].originalId != null)
		elem = GetRawObject(popBox[elem.id].originalId);

	var pbShowCaption = elem.getAttribute('pbShowCaption');
	pbShowCaption = (pbShowCaption != null) ? (pbShowCaption == "true" || pbShowCaption == true) : popBoxShowCaption;
	var pbCaption = null;
	if (pbShowCaption == true)
	{
		pbCaption = elem.getAttribute('pbCaption');
		if (pbCaption == null && elem.title != "") pbCaption = elem.title;
	}

	return (pbCaption != null && pbCaption != "");
}

function CreateRevertBar(obj)
{
	if (typeof obj == "string") obj = GetRawObject(obj);
	
	var elem = obj;
	if (popBox[elem.id] != null && popBox[elem.id].originalId != null)
		elem = GetRawObject(popBox[elem.id].originalId);

	var pbShowBar = elem.getAttribute('pbShowRevertBar');
	var pbShowText = elem.getAttribute('pbShowRevertText');
	var pbShowImage = elem.getAttribute('pbShowRevertImage');
	var pbText = elem.getAttribute('pbRevertText');
	var pbImage = elem.getAttribute('pbRevertImage');
	pbShowBar = (pbShowBar != null) ? (pbShowBar == "true" || pbShowBar == true) : popBoxShowRevertBar;
	pbShowText = (pbShowText != null) ? (pbShowText == "true" || pbShowText == true) : popBoxShowRevertText;
	pbShowImage = (pbShowImage != null) ? (pbShowImage == "true" || pbShowImage == true) : popBoxShowRevertImage;
	if (pbText == null) pbText = popBoxRevertText;
	if (pbImage == null) pbImage = popBoxRevertImage;

	var pbShowCaption = elem.getAttribute('pbShowCaption');
	pbShowCaption = (pbShowCaption != null) ? (pbShowCaption == "true" || pbShowCaption == true) : popBoxShowCaption;
	var pbCaption = null;
	if (pbShowCaption == true)
	{
		pbCaption = elem.getAttribute('pbCaption');
		if (pbCaption == null && elem.title != "") pbCaption = elem.title;
	}

	CreatePbBar(obj, pbShowBar, pbShowText, pbShowImage, pbText, pbImage, popBoxRevertBarAbove, true, pbCaption)
}

function CreatePopBar(obj)
{
	if (typeof obj == "string") obj = GetRawObject(obj);
	if (typeof pbPopBarFunc[obj.id] != 'undefined' && pbPopBarFunc[obj.id] != null) return;
	var pbShowBar = obj.getAttribute('pbShowPopBar');
	if (pbShowBar != null)
	{
		var pbShowText = obj.getAttribute('pbShowPopText');
		var pbShowImage = obj.getAttribute('pbShowPopImage');
		var pbText = obj.getAttribute('pbPopText');
		var pbImage = obj.getAttribute('pbPopImage');
		pbShowBar = (pbShowBar == "true" || pbShowBar == true);
		pbShowText = (pbShowText != null) ? (pbShowText == "true" || pbShowText == true) : popBoxShowPopText;
		pbShowImage = (pbShowImage != null) ? (pbShowImage == "true" || pbShowImage == true) : popBoxShowPopImage;
		if (pbText == null) pbText = popBoxPopText;
		if (pbImage == null) pbImage = popBoxPopImage;

		CreatePbBar(obj, pbShowBar, pbShowText, pbShowImage, pbText, pbImage, popBoxPopBarAbove, false, null)
	}
}

function CreatePbBar(obj, pbShowBar, pbShowText, pbShowImage, pbText, pbImage, pbBarAbove, isRevert, pbCaption)
{
	if (pbShowBar == false && pbShowText == false && pbShowImage == false && pbCaption == null) return;
	if (typeof obj == "string") obj = GetRawObject(obj);

	var objCursor = "hand";
	if (obj.currentStyle)
		objCursor = obj.currentStyle.cursor;
	else if (window.getComputedStyle)
		objCursor = window.getComputedStyle(obj,null).cursor;

	var fnClick = function(){if (typeof obj.onclick == 'function') obj.onclick();};
	var fnMouseOut = function(){if (typeof obj.onmouseout == 'function') obj.onmouseout();};
	var fnMouseOver = function(){if (typeof obj.onmouseover == 'function') obj.onmouseover();};
	var fnRemove = new Array();

	var isPositioned = (obj.style.position == "absolute" || obj.style.position == "relative");
	var left = 0;
	var top = 0;
	var parentNode = obj.parentNode;
	var objSpan = null;
	if (isPositioned == true)
	{
		left = parseInt(obj.style.left, 10);
		top = parseInt(obj.style.top, 10);
		var padding = GetObjectPadding(obj);
		left += padding.l;
		top += padding.t;	
	}
	else
	{
		objSpan = document.createElement("span");
		objSpan = (obj.nextSibling != null) ? parentNode.insertBefore(objSpan, obj.nextSibling) : parentNode.appendChild(objSpan);
		objSpan.style.position = "relative";
		objSpan.style.left = "0px";
		objSpan.style.top = "0px";
		var floatValue = "";
		if (obj.align == "left") floatValue = "left";
		else if (obj.align == "right") floatValue = "right";
		floatValue = (obj.style.styleFloat && obj.style.styleFloat != "") ? obj.style.styleFloat : (obj.style.cssFloat && obj.style.cssFloat != "") ? obj.style.cssFloat : floatValue;
		if (typeof obj.style.styleFloat != "undefined") objSpan.style.styleFloat = floatValue;
		else if (typeof obj.style.cssFloat != "undefined") objSpan.style.cssFloat = floatValue;
		
		var imgPos = GetElementPosition(obj);
		var spanPos = GetElementPosition(objSpan);
		objSpan.style.left = (spanPos.x > imgPos.x) ? (imgPos.x - spanPos.x) + "px" : imgPos.x - spanPos.x + "px";
		objSpan.style.top = (spanPos.y > imgPos.y) ? (imgPos.y - spanPos.y) + "px" : imgPos.y - spanPos.y + "px";
		
		objSpan.onclick = fnClick;
		if (isRevert == true)
			objSpan.onmouseout = fnMouseOut;
		else
			objSpan.onmouseover = fnMouseOver;
		parentNode = objSpan;
	}

	var width = parseInt(obj.style.width, 10);
	var height = parseInt(obj.style.height, 10);
	var size = GetObjectSize(obj);
	if (isNaN(width) == true)
		width = size.w;
	else if (size.w > width)
		left += ((size.w - width) / 2);
	if (isNaN(height) == true)
		height = size.h;
	else if (size.h > height)
		top += ((size.h - height) / 2);

	if (pbBarAbove == true) top -= 20;
	var z = obj.style.zIndex + 1;

	if (pbShowBar == true)
	{
		var divTrans = document.createElement("div");
		divTrans.id = "popBoxDivTrans" + z;
		divTrans.style.width = width + "px";
		divTrans.style.height = "20px";
		divTrans.style.borderStyle = "none";
		divTrans.style.padding = "0px";
		divTrans.style.margin = "0px";
		divTrans.style.position = "absolute";
		divTrans.style.left = left + "px";
		divTrans.style.top = top + "px";
		divTrans.style.backgroundColor = "#000000";
		divTrans.style.cursor = objCursor;
		divTrans.style.zIndex = z;
		if (pbBarAbove == false)
		{
			if (typeof divTrans.style.filter != 'undefined')
				divTrans.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=20)";
			if (typeof divTrans.style.opacity != 'undefined')
				divTrans.style.opacity = "0.2";
		}
		divTrans.onclick = fnClick;
		if (isRevert == true)
			divTrans.onmouseout = fnMouseOut;
		else
			divTrans.onmouseover = fnMouseOver;
		parentNode.appendChild(divTrans);
		
		fnRemove.push(function(){divTrans.parentNode.removeChild(divTrans);});
	}

	if (pbShowText == true)
	{
		var divText = document.createElement("div");
		divText.id = "popBoxDivText" + z;
		divText.style.width = width + "px";
		divText.style.height = "20px";
		divText.style.borderStyle = "none";
		divText.style.padding = "0px";
		divText.style.margin = "0px";
		divText.style.position = "absolute";
		divText.style.left = left + "px";
		divText.style.top = top + "px";
		divText.style.cursor = objCursor;
		divText.style.textAlign = "center";
		divText.style.fontFamily = "Arial, Verdana, Sans-Serif";
		divText.style.fontSize = "10pt";
		divText.style.backgroundColor = "Transparent";
		divText.style.color = "#ffffff";
		divText.style.zIndex = z;
		divText.innerHTML = pbText;
		divText.onclick = fnClick;
		if (isRevert == true)
			divText.onmouseout = fnMouseOut;
		else
			divText.onmouseover = fnMouseOver;
		parentNode.appendChild(divText);

		fnRemove.push(function(){divText.parentNode.removeChild(divText);});
	}
	
	if (pbShowImage == true)
	{
		var imgPopped = document.createElement("img");
		imgPopped.id = "popBoxImgPopped" + z;
		imgPopped.src = pbImage;
		imgPopped.style.width = "20px";
		imgPopped.style.height = "20px";
		imgPopped.style.borderStyle = "none";
		imgPopped.style.padding = "0px";
		imgPopped.style.margin = "0px";
		imgPopped.style.position = "absolute";
		imgPopped.style.left = (left + width - 20) + "px";
		imgPopped.style.top = top + "px";
		imgPopped.style.cursor = objCursor;
		imgPopped.style.zIndex = z;
		imgPopped.onclick = fnClick;
		if (isRevert == true)
			imgPopped.onmouseout = fnMouseOut;
		else
			imgPopped.onmouseover = fnMouseOver;
		parentNode.appendChild(imgPopped);

		fnRemove.push(function(){imgPopped.parentNode.removeChild(imgPopped);});
	}
	
	if (pbCaption != null && pbCaption != "")
	{
		top += (height - 20);
		if (pbBarAbove == true) top += 20;
		if (popBoxCaptionBelow == true)  top += 20;

		var divCapTrans = document.createElement("div");
		divCapTrans.id = "popBoxDivCapTrans" + z;
		divCapTrans.style.width = width - 2 + "px";
		divCapTrans.style.height = "20px";
		divCapTrans.style.borderStyle = "solid";
		divCapTrans.style.borderWidth = "1px";
		divCapTrans.style.borderColor = "#999999";
		divCapTrans.style.padding = "0px";
		divCapTrans.style.margin = "0px";
		divCapTrans.style.position = "absolute";
		divCapTrans.style.left = left + "px";
		divCapTrans.style.top = top - 1 + "px";
		divCapTrans.style.backgroundColor = "#ffffdd";
		divCapTrans.style.zIndex = z;
		if (popBoxCaptionBelow == false)
		{
			if (typeof divCapTrans.style.filter != 'undefined')
				divCapTrans.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=70)";
			if (typeof divCapTrans.style.opacity != 'undefined')
				divCapTrans.style.opacity = "0.7";
		}
		parentNode.appendChild(divCapTrans);
		fnRemove.push(function(){divCapTrans.parentNode.removeChild(divCapTrans);});

		var divCapText = document.createElement("div");
		divCapText.id = "popBoxDivCapText" + z;
		divCapText.style.width = width - 20 + "px";
		divCapText.style.height = "20px";
		divCapText.style.borderStyle = "none";
		divCapText.style.padding = "0px";
		divCapText.style.margin = "0px";
		divCapText.style.position = "absolute";
		divCapText.style.left = left + 10 + "px";
		divCapText.style.top = top + "px";
		divCapText.style.textAlign = "center";
		divCapText.style.fontFamily = "Arial, Verdana, Sans-Serif";
		divCapText.style.fontSize = "10pt";
		divCapText.style.overflowY = "hidden";
		divCapText.style.backgroundColor = "Transparent";
		divCapText.style.color = "#000000";
		divCapText.style.zIndex = z;
		parentNode.appendChild(divCapText);
		fnRemove.push(function(){divCapText.parentNode.removeChild(divCapText);});

		AddCaptionText(divCapTrans, divCapText, pbCaption);
	}

	if (fnRemove.length != 0)
	{
		if (objSpan != null)
			fnRemove.push(function(){objSpan.parentNode.removeChild(objSpan);});
		
		if (isRevert == true)
		{
			if(popBox[obj.id].fnPre != null && typeof(popBox[obj.id].fnPre) == 'function')
				fnRemove.push(popBox[obj.id].fnPre);
		
			popBox[obj.id].fnPre = function(){for(var x = 0; x < fnRemove.length; x++){fnRemove[x]();}};
		}
		else
		{
			pbPopBarFunc[obj.id] = function(){for(var x = 0; x < fnRemove.length; x++){fnRemove[x]();}};
		}
	}
}

function AddCaptionText(divCapTrans, divCapText, caption)
{
	var width = parseInt(divCapText.style.width, 10);
	var divSizer = document.createElement("div");
	divSizer.style.position = "absolute";
	divSizer.style.width = width + "px";
	divSizer.style.margin = "0px";
	divSizer.style.fontFamily = divCapText.style.fontFamily;
	divSizer.style.fontSize = divCapText.style.fontSize;
	divSizer.style.visibility = "hidden";
	divSizer.innerHTML = caption;
	document.body.appendChild(divSizer);
	var newSize = GetObjectSize(divSizer);
	if (newSize.h > 20)
	{
		divSizer.innerHTML = caption + "..." + popBoxCaptionLessText;

		newSize = GetObjectSize(divSizer);

		var fullCaption = caption;
		var charCount = parseInt(width * 0.14, 10) - 5; // safe estimate
		divCapText.innerHTML = caption.substr(0, charCount) + "...";
		
		var spanMore = document.createElement("span");
		spanMore.style.color = "#0000ff";
		spanMore.style.textDecoration = "underline";
		spanMore.style.cursor = "pointer";
		spanMore.onclick = function(){spanMore.parentNode.removeChild(spanMore);ResizeCaption(divCapTrans.id,divCapText.id,newSize.h,fullCaption);};
		spanMore.innerHTML = popBoxCaptionMoreText;
		divCapText.appendChild(spanMore);
	}
	else
		divCapText.innerHTML = caption;

	document.body.removeChild(divSizer);
}

function ResizeCaption(divCapTrans, divCapText, height, caption)
{
	if (typeof divCapTrans == "string") divCapTrans = GetRawObject(divCapTrans);
	if (typeof divCapText == "string") divCapText = GetRawObject(divCapText);

	var h = parseInt(divCapText.style.height, 10);
	var top = parseInt(divCapText.style.top, 10);
	
	if (h < height)
	{
		if (h == 20)
		{
			height += 10;
			divCapText.style.paddingTop = "5px";
			divCapText.innerHTML = caption + "...";
			
			var spanLess = document.createElement("span");
			spanLess.style.color = "#0000ff";
			spanLess.style.textDecoration = "underline";
			spanLess.style.cursor = "pointer";
			spanLess.onclick = function(){spanLess.parentNode.removeChild(spanLess);divCapText.innerHTML = caption;ResizeCaption(divCapTrans.id,divCapText.id,20,caption);};
			spanLess.innerHTML = popBoxCaptionLessText;
			divCapText.appendChild(spanLess);
			
			if (popBoxCaptionBelow == false)
			{
				if (typeof divCapTrans.style.filter != 'undefined')
					divCapTrans.style.filter = "";
				if (typeof divCapTrans.style.opacity != 'undefined')
					divCapTrans.style.opacity = "1.0";
			}
		}
		
		if ((h + 10) >= height)
		{
			top -= (height - h);
			h = height;
		}
		else
		{
			top -= 10;
			h += 10;
		}
		
		divCapTrans.style.height = h + "px";
		divCapText.style.height = h + "px";
		divCapTrans.style.top = (top - 1) + "px";
		divCapText.style.top = top + "px";

		if (h != height)
			setTimeout("ResizeCaption(\"" + divCapTrans.id + "\",\"" + divCapText.id + "\"," + height + ",\"" + caption + "\")", 10);
	}
	else
	{
		if ((h - 10) <= height)
		{
			top += (h - height);
			h = height;
		}
		else
		{
			top += 10;
			h -= 10;
		}
		
		divCapTrans.style.height = h + "px";
		divCapText.style.height = h + "px";
		divCapTrans.style.top = (top - 1) + "px";
		divCapText.style.top = top + "px";
		divCapText.style.paddingTop = "0px";

		if (h == height)
		{
			if (popBoxCaptionBelow == false)
			{
				if (typeof divCapTrans.style.filter != 'undefined')
					divCapTrans.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=70)";
				if (typeof divCapTrans.style.opacity != 'undefined')
					divCapTrans.style.opacity = "0.7";
			}

			AddCaptionText(divCapTrans, divCapText, caption);
		}
		else
		{
			setTimeout("ResizeCaption(\"" + divCapTrans.id + "\",\"" + divCapText.id + "\"," + height + ",\"" + caption + "\")", 10);
		}
	}
}

function CreateWaitImage(obj)
{
	if (typeof obj == "string") obj = GetRawObject(obj);

	var newId = "popBoxImgWait" + obj.id;
	var imgWait = GetRawObject(newId);
	if (imgWait != null)
		return imgWait;

	var left = 0;
	var top = 0;
	if (obj.style.position == "absolute" || obj.style.position == "relative")
	{
		left = parseInt(obj.style.left, 10);
		top = parseInt(obj.style.top, 10);
	}
	else
	{
		var xy = GetElementPosition(obj);
		left = xy.x;
		top = xy.y;
		var padding = GetObjectPadding(obj);
		left -= padding.l;
		top -= padding.t;
	}

	var width = parseInt(obj.style.width, 10);
	var height = parseInt(obj.style.height, 10);
	var size = GetObjectSize(obj);
	if (isNaN(width) == true)
		width = size.w;
	else if (size.w > width)
		left += ((size.w - width) / 2);
	if (isNaN(height) == true)
		height = size.h;
	else if (size.h > height)
		top += ((size.h - height) / 2);

	var parentNode = obj.parentNode;

	imgWait = document.createElement("img");
	imgWait.id = newId;
	imgWait.src = popBoxWaitImage.src;
	imgWait.style.position = "absolute";
	imgWait.style.left = (left + (width / 2) - (popBoxWaitImage.width / 2)) + "px";
	imgWait.style.top = (top + (height / 2) - (popBoxWaitImage.height / 2)) + "px";
	imgWait.style.cursor = obj.style.cursor;
	imgWait.style.zIndex = obj.style.zIndex + 1;
	parentNode.appendChild(imgWait);

	return imgWait;
}

// encapsulates the Popped image sizing logic
function CalculateImageDimensions(newWidth, newHeight, fullWidth, fullHeight, windowSize)
{
	if (newWidth == null)
	{
		if (newHeight == null)
		{
			newWidth = fullWidth;
			newHeight = fullHeight;
		}
		else if (newHeight == 0)
		{
			newHeight = Math.min(windowSize.y, fullHeight);
			var scale = parseFloat(newHeight) / parseFloat(fullHeight);
			newWidth = parseInt(fullWidth * scale);
		}
		else
		{
			var scale = parseFloat(newHeight) / parseFloat(fullHeight);
			newWidth = parseInt(fullWidth * scale);
		}
	}
	else if (newWidth == 0)
	{
		if (newHeight == null)
		{
			newWidth = Math.min(windowSize.x, fullWidth);
			var scale = parseFloat(newWidth) / parseFloat(fullWidth);
			newHeight = parseInt(fullHeight * scale);
		}
		else if (newHeight == 0)
		{
			if (windowSize.x < fullWidth || windowSize.y < fullHeight)
			{
				var scale = Math.min(parseFloat(windowSize.x) / parseFloat(fullWidth), parseFloat(windowSize.y) / parseFloat(fullHeight));
				newWidth = parseInt(fullWidth * scale);
				newHeight = parseInt(fullHeight * scale);
			}
			else
			{
				newWidth = fullWidth;
				newHeight = fullHeight;
			}
		}
		else
		{
			var scale = parseFloat(newHeight) / parseFloat(fullHeight);
			newWidth = Math.min(windowSize.x, parseInt(fullWidth * scale));
		}
	}
	else
	{
		if (newHeight == null)
		{
			var scale = parseFloat(newWidth) / parseFloat(fullWidth);
			newHeight = parseInt(fullHeight * scale);
		}
		else if (newHeight == 0)
		{
			var scale = parseFloat(newWidth) / parseFloat(fullWidth);
			newHeight = Math.min(windowSize.y, parseInt(fullHeight * scale));
		}
	}
	
	return {x:newWidth, y:newHeight};
}

/***************************************************************************************************
* This is where the user-callable section starts.
* Function signatures above this line are subject to change.
***************************************************************************************************/

// Globals you can assign
var popBoxAutoClose = true;
var popBoxMouseMoveRevert = true;
var popBoxWaitImage = new Image();
popBoxWaitImage.src = "/content/images/popbox/spinner40.gif";

var popBoxShowRevertBar = true;
var popBoxShowRevertText = true;
var popBoxShowRevertImage = true;
var popBoxRevertText = "Click the image to shrink it.";
var popBoxRevertImage = "/content/images/popbox/magminus.gif";
var popBoxRevertBarAbove = false;

// there is no popBoxShowPopBar global, but instead the pbShowPopBar attribute must be
// set on the img for the PopBar funtionality to work (can be true or false)
var popBoxShowPopText = true;
var popBoxShowPopImage = true;
var popBoxPopText = "Click to expand.";
var popBoxPopImage = "/content/images/popbpx/magplus.gif";
var popBoxPopBarAbove = false;

var popBoxShowCaption = true;
var popBoxCaptionBelow = false;
var popBoxCaptionMoreText = "more";
var popBoxCaptionLessText = "less";

// these custom attributes on the <img> element will override the globals above
// pbShowRevertBar, pbShowRevertText, pbShowRevertImage, pbRevertText, pbRevertImage
// pbShowPopBar, pbShowPopText, pbShowPopImage, pbPopText, pbPopImage, pbShowCaption

// Advanced method to begin moves and resizes. (Use Pop/PopEx and Revert where possible instead.)
// X and Y postfixes refer to the top left pixel. W and H postfixes refer to the width and height
// speedM and speedS are the speeds of the move and size respectively
// className denotes the CSS class to apply to the object that is being moved and/or sized
// fnDone denotes the script method to run when the move/resize is complete. It must have a single
// parameter that holds the object itself.
function PopBox(obj, startX, startY, endX, endY, startW, startH, endW, endH, speedM, speedS, className, fnDone)
{
	if (typeof obj == "string") obj = GetRawObject(obj);
	if (obj == null || typeof obj != "object" || isNaN(startX) || isNaN(startY) || isNaN(endX) || isNaN(endY) || isNaN(startW) || isNaN(startH) || isNaN(endW) || isNaN(endH) || isNaN(speedM) || isNaN(speedS))
		return;
	var elem = InitPopBox(obj);

	if (popBox[elem.id].isAnimating == true)
	{
		var str = "PopBox('" + elem.id + "'," + startX + "," + startY + "," + endX + "," + endY + "," + startW + "," + startH + "," + endW + "," + endH + "," + speedM + "," + speedS + ",'" + className + "');";
		setTimeout(str, 10);
	}
	else
	{
		popBox[elem.id].isAnimating = true;
		popBox[elem.id].xCurr = parseFloat(startX);
		popBox[elem.id].yCurr = parseFloat(startY);
		popBox[elem.id].wCurr = parseFloat(startW);
		popBox[elem.id].hCurr = parseFloat(startH);
		popBox[elem.id].xTarg = parseFloat(endX);
		popBox[elem.id].yTarg = parseFloat(endY);
		popBox[elem.id].wTarg = parseFloat(endW);
		popBox[elem.id].hTarg = parseFloat(endH);
		popBox[elem.id].xDelta = Math.abs(parseFloat(endX) - parseFloat(startX));
		popBox[elem.id].yDelta = Math.abs(parseFloat(endY) - parseFloat(startY));
		popBox[elem.id].wDelta = Math.abs(parseFloat(endW) - parseFloat(startW));
		popBox[elem.id].hDelta = Math.abs(parseFloat(endH) - parseFloat(startH));
		popBox[elem.id].velM = (speedM) ? Math.abs(parseFloat(speedM)) : 1.0;
		popBox[elem.id].velS = (speedS) ? Math.abs(parseFloat(speedS)) : 1.0;
		popBox[elem.id].xTravel = 0.0;
		popBox[elem.id].yTravel = 0.0;
		popBox[elem.id].wTravel = 0.0;
		popBox[elem.id].hTravel = 0.0;
		// set element's start position
		elem.style.position = "absolute";
		elem.style.left = startX + "px";
		elem.style.top = startY + "px";
		// set element's start size
		elem.style.width = startW + "px";
		elem.style.height = startH + "px";
		elem.style.display = "inline";

		// the length of the line between start and end points
		var lenMove = Math.sqrt((Math.pow((startX - endX), 2)) + (Math.pow((startY - endY), 2)));
		var lenSize = Math.sqrt((Math.pow((startW - endW), 2)) + (Math.pow((startH - endH), 2)));
		// if the speeds are the same then they should be in sync
		if (popBox[elem.id].velM == popBox[elem.id].velS)
			lenMove = lenSize = Math.sqrt(Math.pow(lenMove, 2) + Math.pow(lenSize, 2));

		// how big the pixel steps are along each axis
		popBox[elem.id].xStep = ((popBox[elem.id].xTarg - popBox[elem.id].xCurr) / lenMove) * popBox[elem.id].velM;
		popBox[elem.id].yStep = ((popBox[elem.id].yTarg - popBox[elem.id].yCurr) / lenMove) * popBox[elem.id].velM;

		// how big the pixel steps are for each resize
		popBox[elem.id].wStep = ((popBox[elem.id].wTarg - popBox[elem.id].wCurr) / lenSize) * popBox[elem.id].velS;
		popBox[elem.id].hStep = ((popBox[elem.id].hTarg - popBox[elem.id].hCurr) / lenSize) * popBox[elem.id].velS;
		
		popBox[elem.id].fnDone = fnDone;
		if (className != null)
			elem.className = className;

		popBox[elem.id].cursor = elem.style.cursor;
		elem.style.cursor = "default";

		if (popBox[elem.id].isPopped == false)
			elem.style.zIndex = ++popBoxZ;

		var id = elem.id;
		if (popBox[elem.id].originalId != null) id = popBox[elem.id].originalId;
		if (pbPopBarFunc[id] != null)
		{
			pbPopBarFunc[id]();
			pbPopBarFunc[id] = null;
		}
			
		if (popBox[elem.id].fnPre != null && typeof popBox[elem.id].fnPre == 'function')
			popBox[elem.id].fnPre();

		// start the repeated invocation of the animation
		popBox[elem.id].interval = setInterval("DoPopBox('" + elem.id + "')", 10);
	}
}

/***************************************************************************************************
* Helper functions. Use these! They are much easier. Call Pop/PopEx and then Revert, or set the
* popBoxAutoClose global to true and Revert will be called for you.
***************************************************************************************************/

// this basic method centers the image in the browser and displays it at its full resolution, subject to window size.
function Pop(obj, speed, className)
{
	PopEx(obj, null, null, 0, 0, speed, className);
}

// If newLeft is null then the image is centered horizontally in the browser. Ditto for newTop (vertically).
// End newLeft and/or newTop with "A" for an absolute position, otherwise it is treated as a relative position.
// Ex: a newLeft of 20 would move right 20 pixels, "20A" would position 20 pixels from the left of it's containing element.
// If newWidth is 0 then the full image width is used, subject to scaling and window size. Ditto for newHeight.
// If newWidth is null the full width is used, regardless of window size, but still subject to scaling. Ditto for newHeight.
function PopEx(obj, newLeft, newTop, newWidth, newHeight, speed, className)
{
	if (typeof obj == "string") obj = GetRawObject(obj);
	if (obj.id == "")
		obj.id = CreateRandomId();

	var poppedSrc = obj.getAttribute('pbSrcNL');
	if (poppedSrc == null && pbSrc[obj.id] == null)
		poppedSrc = obj.getAttribute('pbSrc');

	if (poppedSrc != null)
	{
		var poppedImg = new Image();
		poppedImg.src = poppedSrc;
		
		if (pbSrc[obj.id] != null)
			delete pbSrc[obj.id];
			
		pbSrc[obj.id] = poppedImg;
	}
	
	var objToPop = (pbSrc[obj.id] != null) ? pbSrc[obj.id] : obj;
	var isReady = (typeof objToPop.readyState != 'undefined') ? (objToPop.readyState == "complete") : ((typeof objToPop.complete != 'undefined') ? (objToPop.complete == true) : true);
	if (isReady == false)
	{
		var imgWait = CreateWaitImage(obj);
		var str = "var imgWait = GetRawObject('" + imgWait.id + "'); if (imgWait != null) { imgWait.parentNode.removeChild(imgWait); PopEx('" + obj.id + "'," + newLeft + "," + newTop + "," + newWidth + "," + newHeight + "," + speed + ",'" + className + "'); }";
		objToPop.onload = new Function("", str);
		return;
	}

	var elem = InitPopBox(obj);

	if (popBox[elem.id].isPopped == true) return;

	if (typeof elem.ondblclick == "function")
		elem.onclick = elem.ondblclick;

	var startX = parseInt(elem.style.left);
	var startY = parseInt(elem.style.top);

	// figure out the popped image size and position
	var windowSize = GetInsideWindowSize();
	var hasRevertBar = HasRevertBar(obj);
	var hasCaption = HasCaption(obj);
	if (hasRevertBar == true && popBoxRevertBarAbove == true) windowSize.y -= 20;
	if (hasCaption == true && popBoxCaptionBelow == true) windowSize.y -= 20;

	var fullWidth = newWidth;
	var fullHeight = newHeight;

	if (newWidth == 0 || newHeight == 0 || newWidth == null || newHeight == null)
	{
		// get size from original object
		if (pbSrc[obj.id] != null)
		{
			fullWidth = pbSrc[obj.id].width;
			fullHeight = pbSrc[obj.id].height;
		}
		else if (obj.naturalWidth && obj.naturalHeight)
		{
			fullWidth = obj.naturalWidth;
			fullHeight = obj.naturalHeight;
		}
		else
		{
			var img = new Image();
			img.src = elem.src;
			fullWidth = img.width;
			fullHeight = img.height;
			delete img;
		}
		
		// some browsers have a race condition where it still doesn't get set so just fill the window
		if (fullWidth == 0 || fullHeight == 0)
		{
			var scale = Math.min(parseFloat(windowSize.x) / parseFloat(elem.width), parseFloat(windowSize.y) / parseFloat(elem.height));
			fullWidth = parseInt(elem.width * scale);
			fullHeight = parseInt(elem.height * scale);
		}
	}

	// adjust window size variables for new image boundaries
	if (newLeft != null)
	{
		if (typeof newLeft == "string" && newLeft.indexOf("A") == (newLeft.length - 1))
			newLeft = parseInt(newLeft, 10);
		else
			newLeft = popBox[elem.id].xOriginal + parseInt(newLeft, 10);
			
		windowSize.x -= newLeft;
	}

	if (newTop != null)
	{
		if (typeof newTop == "string" && newTop.indexOf("A") == (newTop.length - 1))
			newTop = parseInt(newTop, 10);
		else
			newTop = popBox[elem.id].yOriginal + parseInt(newTop, 10);
			
		windowSize.y -= newTop;
	}

	// adjust for scrollbars that might appear (quick compromise for browser incompatibilities)
	if (newWidth == null && newHeight == 0 && fullWidth > (windowSize.x - 20))
		windowSize.y -= 20;
	else if (newWidth == 0 && newHeight == null && fullHeight > (windowSize.y - 4))
		windowSize.x -= 4;

	var newSize = CalculateImageDimensions(newWidth, newHeight, fullWidth, fullHeight, windowSize);

	// width and height are now set, so position it
	if (newLeft == null || newTop == null)
	{
		var scroll = GetScrollOffset();

		if (newLeft == null)
		{
			newLeft = ((windowSize.x / 2) + scroll.x) - (newSize.x / 2);
			if (newLeft < 0) newLeft = 0;
		}
		
		if (newTop == null)
		{
			newTop = ((windowSize.y / 2) + scroll.y) - (newSize.y / 2);
			if (hasRevertBar == true && popBoxRevertBarAbove == true) newTop += 10;
			if (hasCaption == true && popBoxCaptionBelow == true) newTop -= 10;
			if (newTop < 0) newTop = 0;
		}
	}

	var func = null;
	if (typeof PostPopProcessing == "function")
		func = PostPopProcessing;

	if (typeof PrePopProcessing == "function")
		PrePopProcessing(obj);

	PopBox(elem, startX, startY, newLeft, newTop, popBox[elem.id].wOriginal, popBox[elem.id].hOriginal, newSize.x, newSize.y, speed, speed, className, func);
}

// Helper function for PopBox to move/resize the image back to its original position/size. Use this! It's much easier.
function Revert(obj, speed, className)
{
	if (typeof obj == "string") obj = GetRawObject(obj); 
	if (typeof popBox[obj.id] == "undefined" || popBox[obj.id] == null) return;

	if (typeof speed == 'undefined' || speed == null || speed == 0)
		speed = Math.max(popBox[obj.id].velM, popBox[obj.id].velS);
		
	if (typeof className == 'undefined')
		className = popBox[obj.id].originalClassName;
	
	var func = null;
	if (typeof PostRevertProcessing == "function")
		func = PostRevertProcessing;

	if (typeof PreRevertProcessing == "function")
		PreRevertProcessing(obj);

	PopBox(obj, popBox[obj.id].xTarg, popBox[obj.id].yTarg, popBox[obj.id].xOriginal, popBox[obj.id].yOriginal, popBox[obj.id].wTarg, popBox[obj.id].hTarg, popBox[obj.id].wOriginal, popBox[obj.id].hOriginal, speed, speed, className, func);
}


/***************************************************************************************************
* These methods are the pre and post processing events for Pop/PopEx and Revert.
* Feel free to copy them to your own page script and add your own code to the method bodies.
***************************************************************************************************/

// called before the Pop begins
// The parameter is the original object
//function PrePopProcessing(obj)
//{
//}

// called after the pop is complete
// The parameter is the copy of the object that is resized
//function PostPopProcessing(obj)
//{
//}

// called before the Revert begins
// The parameter is the copy of the object that is resized
//function PreRevertProcessing(obj)
//{
//}

// called after the Revert is complete
// The parameter is the original object
//function PostRevertProcessing(obj)
//{
//}

/*

FREESTYLE MENUS v1.0 RC (c) 2001-2006 Angus Turnbull, http://www.twinhelix.com
Altering this notice or redistributing this file is prohibited.

*/



// This is the full, commented script file, to use for reference purposes or if you feel
// like tweaking anything. I used the "CodeTrimmer" utility availble from my site
// (under 'Miscellaneous' scripts) to trim the comments out of this JS file.



// *** COMMON CROSS-BROWSER COMPATIBILITY CODE ***


// This is taken from the "Modular Layer API" available on my site.
// See that for the readme if you are extending this part of the script.

var isDOM=document.getElementById?1:0,
 isIE=document.all?1:0,
 isNS4=navigator.appName=='Netscape'&&!isDOM?1:0,
 isOp=self.opera?1:0,
 isDyn=isDOM||isIE||isNS4;

function getRef(i, p)
{
 p=!p?document:p.navigator?p.document:p;
 return isIE ? p.all[i] :
  isDOM ? (p.getElementById?p:p.ownerDocument).getElementById(i) :
  isNS4 ? p.layers[i] : null;
};

function getSty(i, p)
{
 var r=getRef(i, p);
 return r?isNS4?r:r.style:null;
};

if (!self.LayerObj) var LayerObj = new Function('i', 'p',
 'this.ref=getRef(i, p); this.sty=getSty(i, p); return this');
function getLyr(i, p) { return new LayerObj(i, p) };

function LyrFn(n, f)
{
 LayerObj.prototype[n] = new Function('var a=arguments,p=a[0],px=isNS4||isOp?0:"px"; ' +
  'with (this) { '+f+' }');
};
LyrFn('x','if (!isNaN(p)) sty.left=p+px; else return parseInt(sty.left)');
LyrFn('y','if (!isNaN(p)) sty.top=p+px; else return parseInt(sty.top)');


if (typeof addEvent != 'function')
{
 var addEvent = function(o, t, f, l)
 {
  var d = 'addEventListener', n = 'on' + t, rO = o, rT = t, rF = f, rL = l;
  if (o[d] && !l) return o[d](t, f, false);
  if (!o._evts) o._evts = {};
  if (!o._evts[t])
  {
   o._evts[t] = o[n] ? { b: o[n] } : {};
   o[n] = new Function('e',
    'var r = true, o = this, a = o._evts["' + t + '"], i; for (i in a) {' +
     'o._f = a[i]; r = o._f(e||window.event) != false && r; o._f = null;' +
     '} return r');
   if (t != 'unload') addEvent(window, 'unload', function() {
    removeEvent(rO, rT, rF, rL);
   });
  }
  if (!f._i) f._i = addEvent._i++;
  o._evts[t][f._i] = f;
 };
 addEvent._i = 1;
 var removeEvent = function(o, t, f, l)
 {
  var d = 'removeEventListener';
  if (o[d] && !l) return o[d](t, f, false);
  if (o._evts && o._evts[t] && f._i) delete o._evts[t][f._i];
 };
}




// *** CORE MENU OBJECT AND FUNCTIONS ***


function FSMenu(myName, nested, cssProp, cssVis, cssHid)
{
 // This is the base object that users create.
 // It stores menu properties, and has a 'menus' associative array to store a list of menu nodes,
 // and allow timeouts to refer to nodes by name (e.g. menuObject.menus.nodeName).

 this.myName = myName;
 this.nested = nested;
 // Some CSS settings users can specify.
 this.cssProp = cssProp;
 this.cssVis = cssVis;
 this.cssHid = cssHid;
 this.cssLitClass = 'highlighted';
 // The 'root' menu only exists for list menus, and is created in the activation function.
 // For non-nested menus, here's an imaginary node that acts as a parent to other nodes.
 this.menus = { root: new FSMenuNode('root', true, this) };
 this.menuToShow = [];
 this.mtsTimer = null;
 // Other configurable defaults.
 this.showDelay = 0;
 this.switchDelay = 125;
 this.hideDelay = 500;
 this.showOnClick = 0;
 this.hideOnClick = true;
 // Animation speeds: set to a number between 0 and 1. Larger = faster. 1 = disabled.
 this.animInSpeed = 0.2;
 this.animOutSpeed = 0.2;
 this.animations = [];

 // Free memory onunload in IE.
 //if (isIE && !isOp) addEvent(window, 'unload', new Function(myName + ' = null'));
};




FSMenu.prototype.show = function(mN) { with (this)
{
 // Set menuToShow to the function parameters. Use a loop to copy values so we don't leak memory.
 menuToShow.length = arguments.length;
 for (var i = 0; i < arguments.length; i++) menuToShow[i] = arguments[i];
 // Use a timer to call a virtual 'root' menu over() function for non-nested menus.
 // For nested/list menus event bubbling will call the real root menu node over() function.
 clearTimeout(mtsTimer);
 if (!nested) mtsTimer = setTimeout(myName + '.menus.root.over()', 10);
}};


FSMenu.prototype.hide = function(mN) { with (this)
{
 // Clear the above timer and route the hide event to the appropriate menu node.
 clearTimeout(mtsTimer);
 if (menus[mN]) menus[mN].out();
}};


FSMenu.prototype.hideAll = function() { with (this)
{
 // Hides all non-root menus, mercilessly!

 for (var m in menus)
  if (menus[m].visible && !menus[m].isRoot) menus[m].hide(true);
}};




function FSMenuNode(id, isRoot, obj)
{
 // Each menu is represented by a FSMenuNode object.
 // This is the node constructor function, with the properties and functions needed by that node.
 // It's passed its own name in the menus[] array, whether this is a root level menu (boolean),
 // and a reference to the parent FSMenu object.

 this.id = id;
 this.isRoot = isRoot;
 this.obj = obj;
 this.lyr = this.child = this.par = this.timer = this.visible = null;
 this.args = [];
 var node = this;


 // These next per-node over/out functions are an example of closures in JavaScript.
 // Since they're instantiated here, they can use the node's variables as if they were their own.

 this.over = function(evt) { with (node) with (obj)
 {
  // Basically, over() gets called when the onmouseover event reaches the menu container,
  // which might be a DIV or UL tag in the document. The event source is a tag inside
  // that container that calls FSMenu.show() and sets the menuToShow array (see above).
  // Browsers will then 'bubble' the event upwards, reaching this function which is set
  // as the onmouseoover/focus/click handler on a menu container. This picks up the
  // properties in menuToShow and shows the given menu as a child of this one.
  // Note that for non-nested menus there is a default timer (mtsTimer) that will mimic
  // an outermost 'root' menu that picks up the event if no other menus intercept it first.

  // Ensure NS4 calls the show/hide function within this layer first.
  if (isNS4 && evt && lyr.ref) lyr.ref.routeEvent(evt);
  // Stop this menu hiding itself and intercept the default root show handler (if any).
  clearTimeout(timer);
  clearTimeout(mtsTimer);

  // A quick check; if this menu isn't visible, show it (i.e. cancel any animation).
  if (!isRoot && !visible) node.show();

  if (menuToShow.length)
  {
   // Pull information out of menuToShow[].
   var a = menuToShow, m = a[0];
   if (!menus[m] || !menus[m].lyr.ref) menus[m] = new FSMenuNode(m, false, obj);
   // c = reference to new child menu that will be shown.
   var c = menus[m];
   // Just clear the menuToShow array and return if we're "showing" the current menu...!
   if (c == node)
   {
    menuToShow.length = 0;
    return;
   }
   // Otherwise, stop any impending show/hide of the child menu, and check if it's a new child.
   clearTimeout(c.timer);
   if (c != child && c.lyr.ref)
   {
    // We have a genuinely new child menu to show. Give it some properties, set a timer to show it.
    // Again, try and avoid memory leaks, but copy over the a/menuToShow arguments.
    c.args.length = a.length;
    for (var i = 0; i < a.length; i++) c.args[i] = a[i];
    // Decide which delay to use -- switchDelay if we already have a child menu, showDelay otherwise.
    var delay = child ? switchDelay : showDelay;
    c.timer = setTimeout('with(' + myName + ') { menus["' + c.id + '"].par = menus["' +
     node.id + '"]; menus["' + c.id + '"].show() }', delay ? delay : 1);
   }
   // Try, try, try to avoid leaking memory... :).
   menuToShow.length = 0;
  }

  // For non-nested menus, mimic event bubbling.
  if (!nested && par) par.over();
 }};


 this.out = function(evt) { with (node) with (obj)
 {
  // Basically the same as over(), this cancels impending events and sets a hide timer.
  if (isNS4 && evt && lyr && lyr.ref) lyr.ref.routeEvent(evt);
  clearTimeout(timer);
  // We never hide the root menu. Otherwise, mimic event-bubbling for non-nested menus.
  if (!isRoot && hideDelay >= 0)
  {
   timer = setTimeout(myName + '.menus["' + id + '"].hide()', hideDelay);
   if (!nested && par) par.out();
  }
 }};


 // Finally, now we have created our menu node, get a layer object for the right ID'd element
 // in the page, and assign it onmouseout/onmouseover events.
 // Don't do for virtual root node (in the case of non-nested menus).
 if (this.id != 'root') with (this) with (lyr = getLyr(id)) if (ref)
 {
  if (isNS4) ref.captureEvents(Event.MOUSEOVER | Event.MOUSEOUT);
  addEvent(ref, 'mouseover', this.over);
  addEvent(ref, 'mouseout', this.out);
  // For nested UL/LI menus, assign focus/blur events for accessibility.
  if (obj.nested)
  {
   addEvent(ref, 'focus', this.over);
   addEvent(ref, 'click', this.over);
   addEvent(ref, 'blur', this.out);
  }
 }
};




FSMenuNode.prototype.show = function(forced) { with (this) with (obj)
{
 // This is called to show the menu node of which it's a method.
 // It sets the parent's child to this, and hides any existing children of the parent node.
 if (!lyr || !lyr.ref) return;

 if (par)
 {
  if (par.child && par.child != this) par.child.hide();
  par.child = this;
 }

 // This is the positioning routine, it can be deleted if you're not using it.
 // It pulls values out of the stored args[] array, and uses the page.elmPos function in the
 // cross-browser code to find the pixel position of the parent item + menu.
 var offR = args[1], offX = args[2], offY = args[3], lX = 0, lY = 0,
  doX = ''+offX!='undefined', doY = ''+offY!='undefined';
 if (self.page && offR && (doX||doY))
 {
  with (page.elmPos(offR, par.lyr ? par.lyr.ref : 0)) lX = x, lY = y;
  if (doX) lyr.x(lX + eval(offX));
  if (doY) lyr.y(lY + eval(offY));
 }

 // Highlight the triggering element, if any.
 if (offR) lightParent(offR, 1);

 // Show the menu and trigger any 'onshow' events.
 // Also raise the parent <li> to avoid z-index issues in MSIE.
 visible = 1;
 if (obj.onshow) obj.onshow(id);
 lyr.ref.parentNode.style.zIndex = '2';
 setVis(1, forced);
}};


FSMenuNode.prototype.hide = function(forced) { with (this) with (obj)
{
 // Same as show() above, but this clears the child/parent settings and hides the menu.
 if (!lyr || !lyr.ref || !visible) return;

 // This is an NS4 hack as its mouse events are notoriously unreliable. Remove as needed.
 if (isNS4 && self.isMouseIn && isMouseIn(lyr.ref)) return show();
 // Dim the triggering element.
 if (args[1]) lightParent(args[1], 0);

 // Route the hide call through any child nodes, and clear the par/child references.
 if (child) child.hide();
 if (par && par.child == this) par.child = null;

 // Hide the menu node element, trigger an 'onhide' event if set, lower the
 // parent <li> and finally show the menu.
 if (lyr)
 {
  visible = 0;
  if (obj.onhide) obj.onhide(id);
  lyr.ref.parentNode.style.zIndex = '1';
  setVis(0, forced);
 }
}};


FSMenuNode.prototype.lightParent = function(elm, lit) { with (this) with (obj)
{
 // This is passed a reference to the parent triggering element, and whether it is lit or not.

 if (!cssLitClass || isNS4) return;
 // By default the cssLitClass value is appended/removed to any existing class.
 // Otherwise, if hiding, remove all trailing instances of it (in case of script errors).
 if (lit) elm.className += (elm.className?' ':'') + cssLitClass;
 else elm.className = elm.className.replace(new RegExp('(\\s*' + cssLitClass + ')+$'), '');
}};


FSMenuNode.prototype.setVis = function(sh, forced) { with (this) with (obj)
{
 // This is passed two parameteres: whether its menu is shown (boolean), and
 // whether its a "forced" animation (can't be interrupted by an unforced one).
 // It sets the chosen CSS property of the menu element, and repeatedly calls itself if
 // one or more animations have been specified in the animations property.

 if (lyr.forced && !forced) return;
 lyr.forced = forced;
 lyr.timer = lyr.timer || 0;
 lyr.counter = lyr.counter || 0;
 with (lyr)
 {
  clearTimeout(timer);
  if (sh && !counter) sty[cssProp] = cssVis;
  var speed = sh ? animInSpeed : animOutSpeed;

  if (isDOM && speed < 1)
   for (var a = 0; a < animations.length; a++) animations[a](ref, counter, sh);

  counter += speed*(sh?1:-1);
  if (counter>1) { counter = 1; lyr.forced = false }
  else if (counter<0) { counter = 0; sty[cssProp] = cssHid; lyr.forced = false }
  else if (isDOM) { timer = setTimeout(myName + '.menus["' + id + '"].setVis(' +
   sh + ',' + forced + ')', 50) }
 }
}};




// *** ANIMATION FUNCTIONS ***

// Here are some sample animation functions you can customise.
// These functions are called with a reference to the menu element being
// animated, an animation counter variable that changes from 0 to 1 and back,
// and whether or not the element is currently being shown.
// They must set properties of 'ref' each frame of the animation.

FSMenu.animSwipeDown = function(ref, counter, show)
{
 // Backup original top/margin-top, then 'swipe' movement + clipping.
 if (show && (counter == 0))
 {
  ref._fsm_styT = ref.style.top;
  ref._fsm_styMT = ref.style.marginTop;
  ref._fsm_offT = ref.offsetTop || 0;
 }
 var cP = Math.pow(Math.sin(Math.PI * counter / 2), 0.75);
 var clipY = ref.offsetHeight * (1 - cP);
 ref.style.clip = (counter == 1 ?
  ((window.opera || navigator.userAgent.indexOf('KHTML') > -1) ? '' :
   'rect(auto, auto, auto, auto)') :
   'rect(' + clipY + 'px, ' + ref.offsetWidth + 'px, ' + ref.offsetHeight + 'px, 0)');
 if (counter == 1 || (counter < 0.01 && !show))
 {
  ref.style.top = ref._fsm_styT;
  ref.style.marginTop = ref._fsm_styMT;
 }
 else
 {
  ref.style.top = ((0 - clipY) + (ref._fsm_offT)) + 'px';
  ref.style.marginTop = '0';
 }
};

FSMenu.animFade = function(ref, counter, show)
{
 // Use IE's ActiveX alpha filter or the W3C/Mozilla 'opacity' to fade menu.
 var done = (counter == 1);
 if (ref.filters)
 {
  var alpha = !done ? ' alpha(opacity=' + parseInt(counter * 100) + ')' : '';
  if (ref.style.filter.indexOf("alpha") == -1) ref.style.filter += alpha;
  else ref.style.filter = ref.style.filter.replace(/\s*alpha\([^\)]*\)/i, alpha);
 }
 else ref.style.opacity = ref.style.MozOpacity = counter / 1.001;
};

FSMenu.animClipDown = function(ref, counter, show)
{
 // Clip the menu down like a 'blind'.
 var cP = Math.pow(Math.sin(Math.PI * counter / 2), 0.75);
 ref.style.clip = (counter == 1 ?
  ((window.opera || navigator.userAgent.indexOf('KHTML') > -1) ? '' :
   'rect(auto, auto, auto, auto)') :
   'rect(0, ' + ref.offsetWidth + 'px, '+ (ref.offsetHeight * cP) + 'px, 0)');
};

// Alternative animFade function that's faster but conflicts with animSwipeDown.
/*
FSMenu.animFade = function(ref, counter, show)
{
 var f = ref.filters, done = (counter == 1);
 if (f)
 {
  if (!done && ref.style.filter.indexOf("alpha") == -1)
   ref.style.filter += ' alpha(opacity=' + (counter * 100) + ')';
  else if (f.length && f.alpha) with (f.alpha)
  {
   if (done) enabled = false;
   else { opacity = (counter * 100); enabled=true }
  }
 }
 else ref.style.opacity = ref.style.MozOpacity = counter / 1.001;
};
*/




// *** LIST MENU ACTIVATION ***


// This is only required for activating list-type menus.
// You can delete it if you're using div-menus only.

FSMenu.prototype.activateMenu = function(id, subInd) { with (this)
{
 if (!isDOM || !document.documentElement) return;

 // First of all, disable the CSS menu behaviour.
 var fsmFB = getRef('fsmenu-fallback');
 if (fsmFB)
 {
  fsmFB.rel = 'alternate stylesheet';
  fsmFB.disabled = true;
 }

 // References to menu elements for a given level.
 var a, ul, li, parUL, mRoot = getRef(id), nodes, count = 1;

 // Loop through all sub-lists under the given menu.
 var lists = mRoot.getElementsByTagName('ul');
 for (var i = 0; i < lists.length; i++)
 {
  // Find a parent LI node, if any, by recursing upwards from the UL. Quit if not found.
  li = ul = lists[i];
  while (li)
  {
   if (li.nodeName.toLowerCase() == 'li') break;
   li = li.parentNode;
  }
  if (!li) continue;
  // Next, find the parent UL to that LI node.
  parUL = li;
  while (parUL)
  {
   if (parUL.nodeName.toLowerCase() == 'ul') break;
   parUL = parUL.parentNode;
  }

  // Now, find the anchor tag that triggers this menu; it should be a child of the LI.
  a = null;
  for (var j = 0; j < li.childNodes.length; j++)
   if (li.childNodes[j].nodeName.toLowerCase() == 'a') a = li.childNodes[j];
  if (!a) continue;

  // We've found a menu node by now, so give it an ID and event handlers.
  var menuID = myName + '-id-' + count++;
  // Only assign a new ID if it doesn't have one already.
  if (ul.id) menuID = ul.id;
  else ul.setAttribute('id', menuID);

  // Attach focus/mouse events to the triggering anchor tag.
  // Check if this link will be triggered onclick instead of onmouseover.
  // If so, we only respect mouseovers/focuses when the menu is visible from a click.
  var sOC = (showOnClick == 1 && li.parentNode == mRoot) || (showOnClick == 2);
  // Safari 1.x is buggy and crashes when you access "returnValue". Joy.
  // Also Opera defaults to "false" so use something different there.
  var evtProp = navigator.userAgent.indexOf('Safari') > -1 || isOp ?
   'safRtnVal' : 'returnValue';
  // Create the functions that handle show & hide events.
  var eShow = new Function('with (' + myName + ') { ' +
   'var m = menus["'+menuID+'"], pM = menus["' + parUL.id + '"];' +
   (sOC ? 'if ((pM && pM.child) || (m && m.visible))' : '') +
   ' show("' + menuID + '", this) }');
  var eHide = new Function('e', 'if (e.' + evtProp + ' != false) ' +
   myName + '.hide("' + menuID + '")');
  // Assign them to the <a> element.
  addEvent(a, 'mouseover', eShow);
  addEvent(a, 'focus', eShow);
  addEvent(a, 'mouseout', eHide);
  addEvent(a, 'blur', eHide);
  if (sOC) addEvent(a, 'click', new Function('e', myName + '.show("' + menuID +
   '", this); if (e.cancelable && e.preventDefault) e.preventDefault(); ' +
   'e.' + evtProp + ' = false; return false'));

  // Prepend an arrow indicator to the anchor tag content if given.
  if (subInd) a.insertBefore(subInd.cloneNode(true), a.firstChild);
 }

 
 // Because IE sucks, we emulate onfocus/blur event bubbling for accessibility,
 // which allows users to tab/shift+tab through the menus.
 if (isIE && !isOp)
 {
  var aNodes = mRoot.getElementsByTagName('a');
  for (var i = 0; i < aNodes.length; i++)
  {
   // A setTimeout helps ensure the focus is always after any blur.
   addEvent(aNodes[i], 'focus', new Function('e', 'var node = this.parentNode; while(node) { ' +
     'if (node.onfocus) node.onfocus(e); node = node.parentNode }'));
   addEvent(aNodes[i], 'blur', new Function('e', 'var node = this.parentNode; while(node) { ' +
    'if (node.onblur) node.onblur(e); node = node.parentNode }'));
  }
 }

 // If this menu hides its children onclick, setup that now.
 if (hideOnClick) addEvent(mRoot, 'click', new Function(myName + '.hideAll()')); 

 // Finally, create/activate the root node.
 menus[id] = new FSMenuNode(id, true, this);
}};




// *** DIV MENU & v4 BROWSER COMPATIBILITY ***


// You may freely delete this section if you're only using "list" type menus.
// This script will "run" in NS4, but I recommend you use my "Cascading Popup Menus" script if you
// want NS4 users to have an experience comparable to users of modern browsers.
// You can download it from my site, http://www.twinhelix.com if you're interested.

// 'page' object from layer API code, detects positions of page elements.
var page = { win: self, minW: 0, minH: 0, MS: isIE&&!isOp,
 db: document.compatMode&&document.compatMode.indexOf('CSS')>-1?'documentElement':'body' };
page.elmPos=function(e,p)
{
 var x=0,y=0,w=p?p:this.win;
 e=e?(e.substr?(isNS4?w.document.anchors[e]:getRef(e,w)):e):p;
 if(isNS4){if(e&&(e!=p)){x=e.x;y=e.y};if(p){x+=p.pageX;y+=p.pageY}}
 if (e && this.MS && navigator.platform.indexOf('Mac')>-1 && e.tagName=='A')
 {
  e.onfocus = new Function('with(event){self.tmpX=clientX-offsetX;' +
   'self.tmpY=clientY-offsetY}');
  e.focus();x=tmpX;y=tmpY;e.blur()
 }
 else while(e){x+=e.offsetLeft;y+=e.offsetTop;e=e.offsetParent}
 return{x:x,y:y};
};


if (isNS4)
{
 // Various NS4 hacks and tweaks. You can delete this if you don't care about NS4 support.

 var fsmMouseX, fsmMouseY, fsmOR=self.onresize, nsWinW=innerWidth, nsWinH=innerHeight;
 document.fsmMM=document.onmousemove;

 self.onresize = function()
 {
  if (fsmOR) fsmOR();
  if (nsWinW!=innerWidth || nsWinH!=innerHeight) location.reload();
 };

 document.captureEvents(Event.MOUSEMOVE);
 document.onmousemove = function(e)
 {
  fsmMouseX = e.pageX;
  fsmMouseY = e.pageY;
  return document.fsmMM?document.fsmMM(e):document.routeEvent(e);
 };

 function isMouseIn(sty)
 {
  with (sty) return ((fsmMouseX>left) && (fsmMouseX<left+clip.width) &&
   (fsmMouseY>top) && (fsmMouseY<top+clip.height));
 };
}

//	function LightEm()
//	{
//		setTimeout(LightUpCategoryImages, 700);
//	}
//	function LightUpCategoryImages()
//	{
//		<%
//		i = 0.0
//		if IsDefined("ProductCategories"):
//			for pc in ProductCategories:
//			%>
//				new Effect.Appear('ProductCategoryImageContainer_${pc.ProductCategoryId}',{delay:${i},from:0.0,to:1.0} );
//			<%
//			i = i + .10
//			end
//		end%>
//	}

	var theWindow = null;
	var theWindowOpen = false;
	var curPageHeight = 0;
	var curPageWidth = 0;
	var curPageX = 0;
	var curPageY = 0;
	
	//handle all scroll events
	if ("onmousewheel" in document)
	{
		document.onmousewheel = ScrollDetected;
	}
	if (window.addEventListener)
	{
		window.addEventListener("DOMMouseScroll", ScrollDetected, false);
		window.addEventListener("scroll", ScrollDetected, false);
		window.addEventListener("mousemove", ScrollDetected, true);
	}
	else if (document.addEventListener) // Opera 7+
	{
		document.addEventListener("scroll", ScrollDetected, false);
	}
	else if (document.all && document.compatMode && document.compatMode == "CSS1Compat")
	{
		if ("onscroll" in self)
		{	
			window.onscroll = ScrollDetected;
		}
	}
	
	function ScrollDetected()
	{
		if (theWindowOpen)
		{
			getPageDimensions();
			getScroll();
			
			var nTop = curPageY - curPageHeight;
			if(nTop < 0)
				nTop = 0;
				
			var nHeight = curPageHeight * 2;
			$('lightwindow_overlay').setStyle(
				{
					left: 0,
					top: nTop + 'px',
					width: curPageWidth + 'px',
					height: nHeight + 'px'
				});
			
		}
	}
	
	function getPageDimensions()
	{
		var xScroll, yScroll;
		if (window.innerHeight && window.scrollMaxY) 
		{
			xScroll = document.body.scrollWidth;
			yScroll = window.innerHeight + window.scrollMaxY;
		} 
		else if (document.body.scrollHeight > document.body.offsetHeight)
		{
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} 
		else 
		{
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}

		var windowWidth, windowHeight;
		if (self.innerHeight) 
		{
			windowWidth = self.innerWidth;
			windowHeight = self.innerHeight;
		} 
		else if (document.documentElement && document.documentElement.clientHeight) 
		{
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} 
		else if (document.body) 
		{
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}	

		//if (yScroll < windowHeight)
		//{
			curPageHeight = windowHeight;
		//} 
		//else 
		//{
		//	curPageHeight = yScroll;
		//}

		//if (xScroll < windowWidth)
		//{
			curPageWidth = windowWidth;
		//} 
		//else 
		//{
		//	curPageWidth = xScroll;
		//}
	}
	
	function getScroll()
	{
		if ( typeof(window.pageYOffset) == 'number') 
		{
        	curPageX = window.pageXOffset;
        	curPageY = window.pageYOffset;
      	} 
      	else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) 
      	{
	       	curPageX = document.body.scrollLeft;
        	curPageY = document.body.scrollTop;
		} 
		else if (document.documentElement) 
		{
        	curPageX = document.documentElement.scrollLeft;
        	curPageY = document.documentElement.scrollTop;
      	}
	}

	function ShowLightbox(link)
	{	
		if(!theWindowOpen)
		{
			theWindowOpen = true;
			
			if(!theWindow)
				theWindow = new lightwindow();
				
			theWindow.activateWindow(
			{
				href: link,
				title: '',
				type: 'page'
			});
			
			ScrollDetected();
		}
	}

	function ShowLightboxIframe(link)
	{
		if(!theWindowOpen)
		{
			theWindowOpen = true;	
		
			if(!theWindow)
				theWindow = new lightwindow();
				
			theWindow.activateWindow(
			{
				href: link,
				title: '',
				type: 'external'
			});	
			
			ScrollDetected();
		}
	}
	
	function ValidateAndSubmit(area)
	{
		//alert("HI");
		var valid = new Validation('form1', {onSubmit:false});
		var result = valid.validate();
		
		if(result == true)
		{
			//alert("good");
			
			//new Ajax.Updater('AppraisalValue', '/' + area + '/Cart/BeginAppraisal-UpdatePrice.rails', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)});
			
			//valid.reset();
			//$('AcceptButtonImage').show();
			
			new Ajax.Updater('AppraisalValue', '/' + area + '/Cart/BeginAppraisal-UpdatePrice.rails', {parameters:$('form1').serialize(),onComplete:function(){ new Effect.Appear('submitContainer');new Effect.Highlight('AppraisalValue'); setTimeout("$('AcceptButtonImage').focus()",1000)  } });

			
		}
		else
		{
			//alert("bad");
			//$('acceptButtonImage').hide();
			ResetTheElements();
		}
		
		return false;
	}
	
	function ValidateShippingAndSubmit()
	{
		var valid = new Validation('form1', {useTitles : true});

	    
		var result = valid.validate();
		
		if(result == true)
		{
			$('form1').submit();
		}
		else
		{
			//$('AgreeToTermsText').className = 'validation-failed';
			
			 new Effect.Highlight('AgreeToTermsText', {duration:2.0});
			 new Effect.Highlight('AgreeToTermsText2', {duration:2.0});
			
			$('errors').update('Please Complete All Fields.');
			$('errors').className = 'visible';
			$('errors').addClassName('validation-failed');
		}
		
		return false;
	}	
		
	function ResetTheElements()
	{
		new Effect.Fade('submitContainer',{duration:0.4});
		$('AppraisalValue').update('--');
		
		return false;
	}
	
	function ValidateComponentSets(el)
	{
		// Find and set the parents.
		var idOfSelectedItem = $F(el);
		var objectSelectedItem = $(idOfSelectedItem);
		var objectSelectedItemClassSplitArray = $A(objectSelectedItem.classNames())[0];
		var parentIdOfSelectedItem = objectSelectedItemClassSplitArray.split('-')[1];

		// Find all SELECT OPTION items with a VALUE of idOfSelectedItem and select it.
		//console.log($(parentIdOfSelectedItem));
		if($(parentIdOfSelectedItem) != null) {
			$(parentIdOfSelectedItem).selected = true;	
		}
		
		// Find and switch the set for children of set parent.  In the loop of each
		// SELECT element that has the parentSet-[id], find the other SELECT elements
		// with the same modelComponentTypeId-[componentTypeId] as the current.  Hide it,
		// and show the current.

		var childSets = $$('.parentSet-' + parentIdOfSelectedItem + '');
		//console.log(childSets);

		// Hide all of the SELECT elements with the same modelComponentTypeId-[]
		childSets.each(function(s) {
				// Get this SELECT elements current modelComponentTypeId
				var parent_classNamesArray = $A(s.classNames());
				var sibling_componentTypeName = parent_classNamesArray[0];
				//console.log(sibling_componentTypeName);

				// Find the modelComponentTypeId-[] siblings.
				var siblings = $$('.' + sibling_componentTypeName + '');
				//console.log(siblings);
				
				// Hide the siblings.
				siblings.each(function(c) {
						//console.log(c);
						c.hide();
					}
				);
				
				// Show the correct one, with .parentSet-[parentIdOfSelectedItem].
				var correctSet = $$('.parentSet-' + parentIdOfSelectedItem + '').each(function(i) {
						i.show();
					}
				);
				
				// Reset the selectedIndex on all HIDDEN siblings.
				siblings.each(function(c) {
						if(!$(c).visible())
						{
							$(c).selectedIndex = 0;
						}
					}
				);
			}
		);
		
		// Find and switch the set for children of selected item.  In the loop of each
		// SELECT element that has the parentSet-[id], find the other SELECT elements
		// with the same modelComponentTypeId-[componentTypeId] as the current.  Hide it,
		// and show the current.
		var childSets = $$('.parentSet-' + idOfSelectedItem + '');
		//console.log(childSets);

		// Hide all of the SELECT elements with the same modelComponentTypeId-[]
		childSets.each(function(s) {
				// Get this SELECT elements current modelComponentTypeId
				var parent_classNamesArray = $A(s.classNames());
				var sibling_componentTypeName = parent_classNamesArray[0];
				//console.log(sibling_componentTypeName);

				// Find the modelComponentTypeId-[] siblings.
				var siblings = $$('.' + sibling_componentTypeName + '');
				//console.log(siblings);
				
				// Hide the siblings.
				siblings.each(function(c) {
						//console.log(c);
						c.hide();
					}
				);
				
				// Show the correct one, with .parentSet-[parentIdOfSelectedItem].
				var correctSet = $$('.parentSet-' + idOfSelectedItem + '').each(function(i) {
						i.show();
					}
				);
				
				// Reset the selectedIndex on all HIDDEN siblings.
				siblings.each(function(c) {
						if(!$(c).visible())
						{
							$(c).selectedIndex = 0;
						}
					}
				);
			}
		);
	}
	
	function UpdateCondition(conditionId, area, idToUpdate, updateMessage)
	{
		$('ConditionStars').className = 'rating star_' + conditionId;
		$('Condition').value = conditionId;
		$('Condition_DisplayName').value = updateMessage;
		UpdateConditionDescription(idToUpdate, updateMessage);

		//new Effect.Fade('SubmitContainer',{duration:0.1});
		
		ValidateAndSubmit(area);
		
		//var t=setTimeout("$('AcceptButtonImage').focus()",1000);
		//$('AcceptButtonImage').AddClassName('visible');
	}
	
	function UpdateConditionDescription(theElementId, message)
	{
		//new Effect.Fade(theElementId,{duration:0.3});
		$(theElementId).update(message);
		//new Effect.Appear(theElementId,{duration:0.3});
	}
	
	function ResetSelectedDescription(theElementId)
	{
		UpdateConditionDescription(theElementId, $('Condition_DisplayName').value);
	}
	
		
	function ShowModelPopup(modelId, modelName, width, height)
	{
		var day = new Date();
		var id = day.getTime();
		var ww = width;
		var wh = height + 125;
		var params = 'width=' + ww + ',height=' + wh + ',menubar=no,toolbar=no,location=no,directories=no,status=no,resizable=no,scrollbars=no';
		var imgSrc = '/showModelThumb/Show.rails?modelId=' + modelId + '&h=' + height + '&w=' + width;
		var msg = '<html><head><title>' + modelName + '</title></head><body style="margin: 0; padding: 0;"><div style="margin: 0; padding: 0;" align="center"><img style="margin: 0; padding: 0;" src="' + imgSrc + '" alt="' + modelName + '" />\n' +
				  '<hr style="margin: 0; padding: 0;" width="100%" /><form><input style="margin: 0; padding: 0;" type="button" onClick="javascript:window.close()" value="Close Window"></form></div></body></html>\n';
		
		var win = window.open('', id, params);
		win.document.write(msg);
		win.document.close();
	}
	
	function ShowTutorialPopup(url)
	{
		var day = new Date();
		var id = day.getTime();
		var params = 'width=775,height=715,menubar=no,toolbar=no,location=no,directories=no,status=no,resizable=no,scrollbars=no';
		window.open(url, id, params);
	}
	
	function renewSession()
	{
		$("renewSession").src = "/renewSession.aspx?par=" + Math.random();
		//alert("Session Is New Again!");
	}	

	function page_loaded(evt)
	{
	  //Event.observe('my_menu', 'mouseover', menus, false)
	  window.setInterval("renewSession()", 240000);
	}
	
	Event.observe(window, 'load', page_loaded, false);
	
	newimage0 = new Image();
	newimage0.src = "/Content/images/lightwindow/black-80.png";
	newimage1 = new Image();
	newimage1.src = "/Content/images/lightwindow/black.png";
	newimage2 = new Image();
	newimage2.src = "/Content/images/lightwindow/ajax-loading.gif";
	newimage3 = new Image();
	newimage3.src = "/Content/images/cexchange/star_rating/star-matrix2.jpg";
	newimage4 = new Image();
	newimage4.src = "/Content/images/cexchange/body/grdButtonAccept.gif";
	newimage5 = new Image();
	newimage5.src = "/Content/images/cexchange/body/grdButtonAccept_1.gif";
	newimage6 = new Image();
	newimage6.src = "/Content/images/cexchange/body/grdButtonCalc.gif";
	newimage7 = new Image();
	newimage7.src = "/Content/images/cexchange/body/grdButtonCalc_1.gif";

// lightwindow.js v2.0
//
// Copyright (c) 2007 stickmanlabs
// Author: Kevin P Miller | http://www.stickmanlabs.com
// 
// LightWindow is freely distributable under the terms of an MIT-style license.
//
// I don't care what you think about the file size...
//   Be a pro: 
//	    http://www.thinkvitamin.com/features/webapps/serving-javascript-fast
//      http://rakaz.nl/item/make_your_pages_load_faster_by_combining_and_compressing_javascript_and_css_files
//

/*-----------------------------------------------------------------------------------------------*/

if(typeof Effect == 'undefined')
  throw("lightwindow.js requires including script.aculo.us' effects.js library!");

// This will stop image flickering in IE6 when elements with images are moved
try {
	document.execCommand("BackgroundImageCache", false, true);
} catch(e) {}

var lightwindow = Class.create();	
lightwindow.prototype = 
{
	//
	//	Setup Variables
	//
	element : null,
	contentToFetch : null,
	windowActive : false,
	dataEffects : [],
	dimensions : 
	{
		cruft : null,
		container : null,
		viewport : 
		{
			height : null,
			width : null,
			offsetTop : null,
			offsetLeft : null
		}
	},
	pagePosition : 
	{
		x : 0,
		y : 0
	},
	pageDimensions : 
	{
		width : null,
		height : null
	},
	preloadImage : [],
	preloadedImage : [],
	galleries : [],
	resizeTo : 
	{
		height : null,
		heightPercent : null,
		width : null,
		widthPercent : null,
		fixedTop : null,
		fixedLeft : null
	},
	scrollbarOffset : 18,
	navigationObservers : 
	{
		previous : null,
		next : null
	},
	containerChange : 
	{
		height : 0,
		width : 0
	},
	activeGallery : false,
	galleryLocation : 
	{
		current : 0,
		total : 0
	},
	//
	//	Initialize the lightwindow.
	//
	initialize : function(options) 
	{
		this.options = Object.extend(
		{
			resizeSpeed : 8,
			contentOffset : 
			{
				height : 20,
				width : 20
			},
			dimensions : 
			{
				image : {height : 250, width : 250},
				page : {height : 250, width : 760},
				inline : {height : 250, width : 760},
				media : {height : 250, width : 250},
				external : {height : 250, width : 760},
				titleHeight : 25
			},
			classNames : 
			{
				standard : 'lightwindow',
				action : 'lightwindow_action'
			},
			fileTypes : 
			{
				page : ['asp', 'aspx', 'cgi', 'cfm', 'htm', 'html', 'pl', 'php4', 'php3', 'php', 'php5', 'phtml', 'rhtml', 'shtml', 'txt', 'vbs', 'rb', 'rails'],
				media : ['aif', 'aiff', 'asf', 'avi', 'divx', 'm1v', 'm2a', 'm2v', 'm3u', 'mid', 'midi', 'mov', 'moov', 'movie', 'mp2', 'mp3', 'mpa', 'mpa', 'mpe', 'mpeg', 'mpg', 'mpg', 'mpga', 'pps', 'qt', 'rm', 'ram', 'swf', 'viv', 'vivo', 'wav'],
				image : ['bmp', 'gif', 'jpg', 'png', 'tiff']
			},
			mimeTypes : 
			{
				avi : 'video/avi',
				aif : 'audio/aiff',
				aiff : 'audio/aiff',
				gif : 'image/gif',
				bmp : 'image/bmp',
				jpeg : 'image/jpeg',
				m1v : 'video/mpeg',
				m2a : 'audio/mpeg',
				m2v : 'video/mpeg',
				m3u : 'audio/x-mpequrl',
				mid : 'audio/x-midi',
				midi : 'audio/x-midi',
				mjpg : 'video/x-motion-jpeg',
				moov : 'video/quicktime',
				mov : 'video/quicktime',
				movie : 'video/x-sgi-movie',
				mp2 : 'audio/mpeg',
				mp3 : 'audio/mpeg3',
				mpa : 'audio/mpeg',
				mpa : 'video/mpeg',
				mpe : 'video/mpeg',
				mpeg : 'video/mpeg',
				mpg : 'audio/mpeg',
				mpg : 'video/mpeg',
				mpga : 'audio/mpeg',
				pdf : 'application/pdf',
				png : 'image/png',
				pps : 'application/mspowerpoint',
				qt : 'video/quicktime',
				ram : 'audio/x-pn-realaudio-plugin',
				rm : 'application/vnd.rn-realmedia',
				swf	: 'application/x-shockwave-flash',
				tiff : 'image/tiff',
				viv : 'video/vivo',
				vivo : 'video/vivo',
				wav : 'audio/wav',
				wmv : 'application/x-mplayer2'			
			},	
			classids : 
			{
				mov : 'clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B',
				swf : 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000',
				wmv : 'clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6'
			},
			codebases : 
			{
				mov : 'http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0',
				swf : 'http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0',
				wmv : 'http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=6,4,5,715'
			},	
			viewportPadding : 10,
			EOLASFix : 'swf,wmv,fla,flv',
			overlay : 
			{
				opacity : 0.8,
				image : '/Content/images/lightwindow/black.png',
				//presetImage : '/Content/images/lightwindow/black-70.png'
				presetImage : '/Content/images/lightwindow/black-80.png'
			},
			skin : 	
			{
				main : 	'<div id="lightwindow_container" >'+
							'<div id="lightwindow_title_bar" >'+
								'<div id="lightwindow_title_bar_inner" >'+
									'<span id="lightwindow_title_bar_title"></span>'+
									'<a id="lightwindow_title_bar_close_link" >close</a>'+
								'</div>'+
							'</div>'+
							'<div id="lightwindow_stage" >'+
								'<div id="lightwindow_contents" >'+
								'</div>'+
								'<div id="lightwindow_navigation" >'+
									'<a href="#" id="lightwindow_previous" >'+
										'<span id="lightwindow_previous_title"></span>'+
									'</a>'+
									'<a href="#" id="lightwindow_next" >'+
										'<span id="lightwindow_next_title"></span>'+
									'</a>'+
									'<iframe name="lightwindow_navigation_shim" id="lightwindow_navigation_shim" src="javascript:false;" frameBorder="0" scrolling="no"></iframe>'+
								'</div>'+								
								'<div id="lightwindow_galleries">'+
									'<div id="lightwindow_galleries_tab_container" >'+
										'<a href="#" id="lightwindow_galleries_tab" >'+
											'<span id="lightwindow_galleries_tab_span" class="up" >Galleries</span>'+
										'</a>'+
									'</div>'+
									'<div id="lightwindow_galleries_list" >'+
									'</div>'+
								'</div>'+
							'</div>'+
							'<div id="lightwindow_data_slide" >'+
								'<div id="lightwindow_data_slide_inner" >'+
									'<div id="lightwindow_data_details" >'+
										'<div id="lightwindow_data_gallery_container" >'+
											'<span id="lightwindow_data_gallery_current"></span>'+
											' of '+
											'<span id="lightwindow_data_gallery_total"></span>'+
										'</div>'+
										'<div id="lightwindow_data_author_container" >'+
											'by <span id="lightwindow_data_author"></span>'+
										'</div>'+
									'</div>'+
									'<div id="lightwindow_data_caption" >'+
									'</div>'+
								'</div>'+
							'</div>'+
						'</div>',	
				loading : 	'<div id="lightwindow_loading" >'+
								'<img src="/Content/images/lightwindow/ajax-loading.gif" alt="loading" />'+
								'<span>Loading or <a href="javascript: myLightWindow.deactivate();">Cancel</a></span>'+
								'<iframe name="lightwindow_loading_shim" id="lightwindow_loading_shim" src="javascript:false;" frameBorder="0" scrolling="no"></iframe>'+
							'</div>',
				iframe : 	'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'+
							'<html xmlns="http://www.w3.org/1999/xhtml">'+
								'<body>'+
									'{body_replace}'+
								'</body>'+
							'</html>',
				gallery : 
				{
					top :		'<div class="lightwindow_galleries_list">'+
									'<h1>{gallery_title_replace}</h1>'+
									'<ul>',
					middle : 			'<li>'+
											'{gallery_link_replace}'+
										'</li>',
					bottom : 		'</ul>'+
								'</div>'
				}
			},
			formMethod : 'get',
			hideFlash : false,
			hideGalleryTab : false,
			showTitleBar : true,
			animationHandler : false,
			navigationHandler : false,
			transitionHandler : false,
			finalAnimationHandler : false,
			formHandler : false,
			galleryAnimationHandler : false,
			showGalleryCount : true
		}, options || {});
		
		this.duration = ((11-this.options.resizeSpeed)*0.15);
		this._setupLinks();
		this._getScroll();
		this._getPageDimensions();
		this._browserDimensions();
		this._addLightWindowMarkup(false);
		this._setupDimensions(); 
		this.buildGalleryList();
	},
	//
	//	Activate the lightwindow.
	//
	activate : function(e, link)
	{
		// Clear out the window Contents
		this._clearWindowContents(true);
			
		// Add back in out loading panel
		this._addLoadingWindowMarkup();

		// Setup the element properties
		this._setupWindowElements(link);
		
		// Setup everything
		this._getScroll();
		this._browserDimensions();
		this._setupDimensions();
		this._toggleTroubleElements('hidden', false);
		this._displayLightWindow('block', 'hidden');
		this._setStatus(true);
		this._monitorKeyboard(true);
		this._prepareIE(true);
		this._loadWindow();
	},
	//
	//	Turn off the window
	//
	deactivate : function()
	{
		// The window is not active
		this.windowActive = false;
		
		// There is no longer a gallery active
		this.activeGallery = false;
		if (!this.options.hideGalleryTab) 
		{
			this._handleGalleryAnimation(false);
		}
		
		// Kill the animation
		this.animating = false;
		
		// Clear our element
		this.element = null;
		
		// hide the window.
		this._displayLightWindow('none', 'visible');
		
		// Clear out the window Contents
		this._clearWindowContents(false);
		
		// Stop all animation
		var queue = Effect.Queues.get('lightwindowAnimation').each(function(e){e.cancel();});
		
		// Undo the setup
		this._prepareIE(false);
		this._setupDimensions();
		this._toggleTroubleElements('visible', false);	
		this._monitorKeyboard(false);
		
		theWindowOpen = false;
	},
	//
	//  Initialize specific window
	//
	createWindow : function(element, attributes) 
	{
		this._processLink($(element));
	},
	//
	//  Open a Window from a hash of attributes
	//
	activateWindow : function(options) 
	{
		this.element = Object.extend(
		{
			href : null,
			title : null,
			author : null,
			caption : null,
			rel : null,
			top : null,
			left : null,
			type : null,
			showImages : null,
			height : null,
			width : null,
			loadingAnimation : null,
			iframeEmbed : null,
			form : null
		}, options || {});
		
		// Set the window type
		this.contentToFetch = this.element.href;
		this.windowType = this.element.type ? this.element.type : this._fileType(this.element.href);	
		
		// Clear out the window Contents
		this._clearWindowContents(true);
			
		// Add back in out loading panel
		this._addLoadingWindowMarkup();
		
		// Setup everything
		this._getScroll();
		this._browserDimensions();
		this._setupDimensions();
		this._toggleTroubleElements('hidden', false);
		this._displayLightWindow('block', 'hidden');
		this._setStatus(true);
		this._monitorKeyboard(true);
		this._prepareIE(true);
		this._loadWindow();
	},
	//
	//  Fire off our Form handler
	//
	submitForm : function(e) {
		if (this.options.formHandler) {
			this.options.formHandler(e);
		} else {
			this._defaultFormHandler(e);
		}
	},
	//
	//	Reload the window with another location
	//
	openWindow : function(element) {
		var element = $(element);

		// The window is active
		this.windowActive = true;
		
		// Clear out the window Contents
		this._clearWindowContents(true);
		
		// Add back in out loading panel
		this._addLoadingWindowMarkup();
		
		// Setup the element properties
		this._setupWindowElements(element);

		this._setStatus(true);
		this._handleTransition();
	},
	//
	//  Navigate the window
	//
	navigateWindow : function(direction) {
		this._handleNavigation(false);
		if (direction == 'previous') {
			this.openWindow(this.navigationObservers.previous);
		} else if (direction == 'next'){ 
			this.openWindow(this.navigationObservers.next);
		}
	},
	//
	//  Build the Gallery List and Load it
	//
	buildGalleryList : function() {
		var output = '';
		var galleryLink;
		for (i in this.galleries) {
			if (typeof this.galleries[i] == 'object') {
				output += (this.options.skin.gallery.top).replace('{gallery_title_replace}', unescape(i));
				for (j in this.galleries[i]) {
					if (typeof this.galleries[i][j] == 'object') {						
						galleryLink = '<a href="#" id="lightwindow_gallery_'+i+'_'+j+'" >'+unescape(j)+'</a>';
						output += (this.options.skin.gallery.middle).replace('{gallery_link_replace}', galleryLink);
					}
				}
				output += this.options.skin.gallery.bottom;
			}
		}
		new Insertion.Top('lightwindow_galleries_list', output);
		
		// Attach Events
		for (i in this.galleries) {
			if (typeof this.galleries[i] == 'object') {
				for (j in this.galleries[i]) {
					if (typeof this.galleries[i][j] == 'object') {
						Event.observe($('lightwindow_gallery_'+i+'_'+j), 'click', this.openWindow.bind(this, this.galleries[i][j][0]), false);
						$('lightwindow_gallery_'+i+'_'+j).onclick = function() {return false;};	
					}
				}
			}
		}
	},
	// 
	//  Set Links Up
	//
	_setupLinks : function() {
		var links = $$('.'+this.options.classNames.standard);
		links.each(function(link) {
			this._processLink(link);
		}.bind(this));	
	},
	//
	//  Process a Link
	//
	_processLink : function(link) {
		if ((this._fileType(link.getAttribute('href')) == 'image' || this._fileType(link.getAttribute('href')) == 'media')) {
			if (gallery = this._getGalleryInfo(link.rel)) {
				if (!this.galleries[gallery[0]]) {
					this.galleries[gallery[0]] = new Array();
				}
				if (!this.galleries[gallery[0]][gallery[1]]) {
					this.galleries[gallery[0]][gallery[1]] = new Array();
				}
				this.galleries[gallery[0]][gallery[1]].push(link);
			}
		}
		
		// Take care of our inline content
		var url = link.getAttribute('href');
		if (url.indexOf('?') > -1) {
			url = url.substring(0, url.indexOf('?'));
		}
		
		var container = url.substring(url.indexOf('#')+1);
		if($(container)) {
			$(container).setStyle({
				display : 'none'
			});
		}
		
		Event.observe(link, 'click', this.activate.bindAsEventListener(this, link), false);
		link.onclick = function() {return false;};		
	},
	//
	//	Setup our actions
	//
	_setupActions : function() {
		var links = $$('#lightwindow_container .'+this.options.classNames.action);
		links.each(function(link) {
			Event.observe(link, 'click', this[link.getAttribute('rel')].bindAsEventListener(this, link), false);
			link.onclick = function() {return false;};
		}.bind(this));
	},
	//
	//	Add the markup to the page.
	//
	_addLightWindowMarkup : function(rebuild) {
		var overlay = Element.extend(document.createElement('div'));
		overlay.setAttribute('id', 'lightwindow_overlay');		
		// FF Mac has a problem with putting Flash above a layer without a 100% opacity background, so we need to use a pre-made
		if (Prototype.Browser.Gecko) {
			overlay.setStyle({
				backgroundImage: 'url('+this.options.overlay.presetImage+')',
				backgroundRepeat: 'repeat',
				height: this.pageDimensions.height+'px'
			});			
		} else {
			overlay.setStyle({
				opacity: this.options.overlay.opacity,
				backgroundImage: 'url('+this.options.overlay.image+')',
				backgroundRepeat: 'repeat',
				height: this.pageDimensions.height +'px'
			});
		}
		
		var lw = document.createElement('div');
		lw.setAttribute('id', 'lightwindow');
		lw.innerHTML = this.options.skin.main;
		
		var body = document.getElementsByTagName('body')[0];
		body.appendChild(overlay);
		body.appendChild(lw);	
				
		if ($('lightwindow_title_bar_close_link')) {
			Event.observe('lightwindow_title_bar_close_link', 'click', this.deactivate.bindAsEventListener(this));
			$('lightwindow_title_bar_close_link').onclick = function() {return false;};
		}
			
		Event.observe($('lightwindow_previous'), 'click', this.navigateWindow.bind(this, 'previous'), false);
		$('lightwindow_previous').onclick = function() {return false;};		
		Event.observe($('lightwindow_next'), 'click', this.navigateWindow.bind(this, 'next'), false);
		$('lightwindow_next').onclick = function() {return false;};

		if (!this.options.hideGalleryTab) {
			Event.observe($('lightwindow_galleries_tab'), 'click', this._handleGalleryAnimation.bind(this, true), false);
			$('lightwindow_galleries_tab').onclick = function() {return false;};
		}
		
		// Because we use position absolute, kill the scroll Wheel on animations
		if (Prototype.Browser.IE) {
			Event.observe(document, 'mousewheel', this._stopScrolling.bindAsEventListener(this), false);
		} else {
			Event.observe(window, 'DOMMouseScroll', this._stopScrolling.bindAsEventListener(this), false);
		}
				
		Event.observe(overlay, 'click', this.deactivate.bindAsEventListener(this), false);
		overlay.onclick = function() {return false;};
	},
	//
	//  Add loading window markup
	//
	_addLoadingWindowMarkup : function() {
		$('lightwindow_contents').innerHTML += this.options.skin.loading;
	},
	//
	//  Setup the window elements
	//
	_setupWindowElements : function(link) {
		this.element = link;
		this.element.title = null ? '' : link.getAttribute('title');
		this.element.author = null ? '' : link.getAttribute('author');
		this.element.caption = null ? '' : link.getAttribute('caption');
		this.element.rel = null ? '' : link.getAttribute('rel');
		this.element.params = null ? '' : link.getAttribute('params');

		// Set the window type
		this.contentToFetch = this.element.href;
		this.windowType = this._getParameter('lightwindow_type') ? this._getParameter('lightwindow_type') : this._fileType(this.contentToFetch);	
	},
	//
	//  Clear the window contents out
	//
	_clearWindowContents : function(contents) {
		// If there is an iframe, its got to go
		if ($('lightwindow_iframe')) {
			Element.remove($('lightwindow_iframe'));
		}

		// Stop playing an object if its still around
		if ($('lightwindow_media_primary')) {
			try {
				$('lightwindow_media_primary').Stop();
			} catch(e) {}
			Element.remove($('lightwindow_media_primary'));
		}

		// Stop playing an object if its still around		
		if ($('lightwindow_media_secondary')) {
			try {
				$('lightwindow_media_secondary').Stop();
			} catch(e) {}
			Element.remove($('lightwindow_media_secondary'));
		}
		
		this.activeGallery = false;
		this._handleNavigation(this.activeGallery);
		
		if (contents) {
			// Empty the contents
			$('lightwindow_contents').innerHTML = '';
			
			// Reset the scroll bars
			$('lightwindow_contents').setStyle({
				overflow: 'hidden'
			});		
			
			if (!this.windowActive) {
				$('lightwindow_data_slide_inner').setStyle({
					display: 'none'
				});

				$('lightwindow_title_bar_title').innerHTML = '';
			}

			// Because of browser differences and to maintain flexible captions we need to reset this height at close
			$('lightwindow_data_slide').setStyle({
				height: 'auto'
			});
		}
		
		this.resizeTo.height = null;
		this.resizeTo.width = null;
	},
	//
	//	Set the status of our animation to keep things from getting clunky
	//
	_setStatus : function(status) {
		this.animating = status;
		if (status) {
			Element.show('lightwindow_loading');
		}
		if (!(/MSIE 6./i.test(navigator.userAgent))) {
			this._fixedWindow(status);
		}
	},
	//
	//  Make this window Fixed
	//
	_fixedWindow : function(status) {
		if (status) {
			if (this.windowActive) {
				this._getScroll();
				$('lightwindow').setStyle({
					position: 'absolute',
					top: parseFloat($('lightwindow').getStyle('top'))+this.pagePosition.y+'px',
					left: parseFloat($('lightwindow').getStyle('left'))+this.pagePosition.x+'px'
				});		
			} else {
				$('lightwindow').setStyle({
					position: 'absolute'
				});						
			}
		} else {
			if (this.windowActive) {
				this._getScroll();
				$('lightwindow').setStyle({
					position: 'fixed',
					top: parseFloat($('lightwindow').getStyle('top'))-this.pagePosition.y+'px',
					left: parseFloat($('lightwindow').getStyle('left'))-this.pagePosition.x+'px'
				});		
			} else {
				if ($('lightwindow_iframe')) {
					// Ideally here we would set a 50% value for top and left, but Safari rears it ugly head again and we need to do it by pixels
					this._browserDimensions();
				}
				$('lightwindow').setStyle({
					position: 'fixed',
					top: (parseFloat(this._getParameter('lightwindow_top')) ? parseFloat(this._getParameter('lightwindow_top'))+'px' : this.dimensions.viewport.height/2+'px'),
					left: (parseFloat(this._getParameter('lightwindow_left')) ? parseFloat(this._getParameter('lightwindow_left'))+'px' : this.dimensions.viewport.width/2+'px')
				});
			}
		}
	},
	//
	//	Prepare the window for IE.
	//
	_prepareIE : function(setup) {
		if (Prototype.Browser.IE) {
			var height, overflowX, overflowY;
			if (setup) { 
				var height = '100%';
			} else {
				var height = 'auto';
			}
			var body = document.getElementsByTagName('body')[0];
			var html = document.getElementsByTagName('html')[0];
			html.style.height = body.style.height = height;
		}
	},
	_stopScrolling : function(e) {
		if (this.animating) {
			if (e.preventDefault) {
				e.preventDefault();
			}
			e.returnValue = false;		
		}
	},
	//
	//	Get the scroll for the page.
	//
	_getScroll : function(){
      	if(typeof(window.pageYOffset) == 'number') {
        	this.pagePosition.x = window.pageXOffset;
        	this.pagePosition.y = window.pageYOffset;
      	} else if(document.body && (document.body.scrollLeft || document.body.scrollTop)) {
	       	this.pagePosition.x = document.body.scrollLeft;
        	this.pagePosition.y = document.body.scrollTop;
		} else if(document.documentElement) {
        	this.pagePosition.x = document.documentElement.scrollLeft;
        	this.pagePosition.y = document.documentElement.scrollTop;
      	}
	},
	//
	//	Reset the scroll.
	//
	_setScroll : function(x, y) {
		document.documentElement.scrollLeft = x; 
		document.documentElement.scrollTop = y; 
	},
	//
	//	Hide Selects from the page because of IE.
	//     We could use iframe shims instead here but why add all the extra markup for one browser when this is much easier and cleaner
	//
	_toggleTroubleElements : function(visibility, content){
		
		if (content) {
			var selects = $('lightwindow_contents').getElementsByTagName('select');
		} else {
			var selects = document.getElementsByTagName('select');
		}
		
		for(var i = 0; i < selects.length; i++) {
			selects[i].style.visibility = visibility;
		}
		
		if (!content) {
			if (this.options.hideFlash){
				var objects = document.getElementsByTagName('object');
				for (i = 0; i != objects.length; i++) {
					objects[i].style.visibility = visibility;
				}
				var embeds = document.getElementsByTagName('embed');
				for (i = 0; i != embeds.length; i++) {
					embeds[i].style.visibility = visibility;
				}
			}
			var iframes = document.getElementsByTagName('iframe');
			for (i = 0; i != iframes.length; i++) {
				iframes[i].style.visibility = visibility;
			}
		}
	},
	// 
	//  Get the actual page size
	//
	_getPageDimensions : function() {
		var xScroll, yScroll;
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = document.body.scrollWidth;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ 
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { 
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}

		var windowWidth, windowHeight;
		if (self.innerHeight) {	
			windowWidth = self.innerWidth;
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { 
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { 
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}	

		if(yScroll < windowHeight){
			this.pageDimensions.height = windowHeight;
		} else { 
			this.pageDimensions.height = yScroll;
		}

		if(xScroll < windowWidth){	
			this.pageDimensions.width = windowWidth;
		} else {
			this.pageDimensions.width = xScroll;
		}
	},
	//
	//	Display the lightWindow.
	//
	_displayLightWindow : function(display, visibility) {
		$('lightwindow_overlay').style.display = $('lightwindow').style.display = $('lightwindow_container').style.display = display;	
		$('lightwindow_overlay').style.visibility = $('lightwindow').style.visibility = $('lightwindow_container').style.visibility = visibility;
	},
	//
	//	Setup Dimensions of lightwindow.

	//
	_setupDimensions : function() {

		var originalHeight, originalWidth;
		switch (this.windowType) {
			case 'page' :
				originalHeight = this.options.dimensions.page.height;
				originalWidth = this.options.dimensions.page.width;
				break;

			case 'image' :
				originalHeight = this.options.dimensions.image.height;
				originalWidth = this.options.dimensions.image.width;
				break;
				
			case 'media' :
				originalHeight = this.options.dimensions.media.height;
				originalWidth = this.options.dimensions.media.width;
				break;
			
			case 'external' : 
				originalHeight = this.options.dimensions.external.height;
				originalWidth = this.options.dimensions.external.width;
				break;
				
			case 'inline' :
				originalHeight = this.options.dimensions.inline.height;
				originalWidth = this.options.dimensions.inline.width;
				break;
				
			default :
				originalHeight = this.options.dimensions.page.height;
				originalWidth = this.options.dimensions.page.width;
				break;
				
		}

		var offsetHeight = this._getParameter('lightwindow_top') ? parseFloat(this._getParameter('lightwindow_top'))+this.pagePosition.y : this.dimensions.viewport.height/2+this.pagePosition.y;
		var offsetWidth = this._getParameter('lightwindow_left') ? parseFloat(this._getParameter('lightwindow_left'))+this.pagePosition.x : this.dimensions.viewport.width/2+this.pagePosition.x;
		
		// So if a theme has say shadowed edges, they should be consistant and take care of in the contentOffset
		$('lightwindow').setStyle({
			top: offsetHeight+'px',
			left: offsetWidth+'px'
		});
		
		$('lightwindow_container').setStyle({
			height: originalHeight+'px',
			width: originalWidth+'px',
			left: -(originalWidth/2)+'px',
			top: -(originalHeight/2)+'px'
		});

		$('lightwindow_contents').setStyle({
			height: originalHeight+'px',
			width: originalWidth+'px'
		});
	},
	//
	//	Get the type of file.
	//
	_fileType : function(url) {
		var image = new RegExp("[^\.]\.("+this.options.fileTypes.image.join('|')+")\s*$", "i");
		if (image.test(url)) return 'image';
		if (url.indexOf('#') > -1 && (document.domain == this._getDomain(url))) return 'inline';		
		if (url.indexOf('?') > -1) url = url.substring(0, url.indexOf('?'));
		var type = 'unknown';
		var page = new RegExp("[^\.]\.("+this.options.fileTypes.page.join('|')+")\s*$", "i");
		var media = new RegExp("[^\.]\.("+this.options.fileTypes.media.join('|')+")\s*$", "i");
		if (document.domain != this._getDomain(url)) type = 'external';
	  	if (media.test(url)) type = 'media';
		if (type == 'external' || type == 'media') return type;
	  	if (page.test(url) || url.substr((url.length-1), url.length) == '/') type = 'page';
		return type;
	},
	//
	//  Get file Extension
	//
	_fileExtension : function(url) {
		if (url.indexOf('?') > -1) {
			url = url.substring(0, url.indexOf('?'));
		}
		var extenstion = '';
		for (var x = (url.length-1); x > -1; x--) {
			if (url.charAt(x) == '.') {
				return extenstion;
			}
			extenstion = url.charAt(x)+extenstion;
		}
	},
	//
	//	Monitor the keyboard while this lightwindow is up
	//
	_monitorKeyboard : function(status) {
		if (status) document.onkeydown = this._eventKeypress.bind(this); 
		else document.onkeydown = '';
	},
	//
	//  Perform keyboard actions
	//
	_eventKeypress : function(e) {
		if (e == null) {
			var keycode = event.keyCode;
		} else {
			var keycode = e.which;
		}
		
		switch (keycode) { 
			case 27: 
				this.deactivate(); 
				break;
			
			case 13:
				return;
				
			default:
				break;
		}
	
		// Gotta stop those quick fingers
		if (this.animating) {
			return false;
		}
		
		switch (String.fromCharCode(keycode).toLowerCase()) {
			case 'p':
				if (this.navigationObservers.previous) {
					this.navigateWindow('previous');
				}
				break;
				
			case 'n':
				if (this.navigationObservers.next) {
					this.navigateWindow('next');
				}
				break;
				
			default:
				break;
		}
	},
	//
	//	Get Gallery Information
	//
	_getGalleryInfo : function(rel) {
		if (!rel) return false;
		if (rel.indexOf('[') > -1) {
			return new Array(escape(rel.substring(0, rel.indexOf('['))), escape(rel.substring(rel.indexOf('[')+1, rel.indexOf(']'))));
		} else {
			return false;
		}
	},
	//
	//	Get the domain from a string.
	//
	_getDomain : function(url) {    
        var leadSlashes = url.indexOf('//');
        var domainStart = leadSlashes+2;
        var withoutResource = url.substring(domainStart, url.length);
        var nextSlash = withoutResource.indexOf('/');
        var domain = withoutResource.substring(0, nextSlash);
		if (domain.indexOf(':') > -1){
			var portColon = domain.indexOf(':');
			domain = domain.substring(0, portColon);
       	}
		return domain;
    },
	//
	//	Get the value from the params attribute string.
	//
	_getParameter : function(parameter, parameters) {
		if (!this.element) return false;
		if (parameter == 'lightwindow_top' && this.element.top) {
			return unescape(this.element.top);
		} else if (parameter == 'lightwindow_left' && this.element.left) {
			return unescape(this.element.left);
		} else if (parameter == 'lightwindow_type' && this.element.type) {
			return unescape(this.element.type);
		} else if (parameter == 'lightwindow_show_images' && this.element.showImages) {
			return unescape(this.element.showImages);
		} else if (parameter == 'lightwindow_height' && this.element.height) {
			return unescape(this.element.height);
		} else if (parameter == 'lightwindow_width' && this.element.width) {
			return unescape(this.element.width);
		} else if (parameter == 'lightwindow_loading_animation' && this.element.loadingAnimation) {
			return unescape(this.element.loadingAnimation);
		} else if (parameter == 'lightwindow_iframe_embed' && this.element.iframeEmbed) {
			return unescape(this.element.iframeEmbed);
		} else if (parameter == 'lightwindow_form' && this.element.form) {
			return unescape(this.element.form);
		} else {
			if (!parameters) {
				if (this.element.params) parameters = this.element.params;
				else return;
			}
			var value;
			var parameterArray = parameters.split(',');
			var compareString = parameter+'=';
			var compareLength = compareString.length;
			for (var i = 0; i < parameterArray.length; i++) {
				if (parameterArray[i].substr(0, compareLength) == compareString) {
					var currentParameter = parameterArray[i].split('=');
					value = currentParameter[1];
					break;
				}
			}
			if (!value) return false;
			else return unescape(value);
		}
	},
	//
	//  Get the Browser Viewport Dimensions
	//
	_browserDimensions : function() {
		if (Prototype.Browser.IE) {
            this.dimensions.viewport.height = document.documentElement.clientHeight;
            this.dimensions.viewport.width = document.documentElement.clientWidth;   
        } else {
            this.dimensions.viewport.height = window.innerHeight;
            this.dimensions.viewport.width = document.width || document.body.offsetWidth;
        }
	},
	//
	//  Get the scrollbar offset, I don't like this method but there is really no other way I can find.
	//
	_getScrollerWidth : function() {
	    var scrollDiv = Element.extend(document.createElement('div'));
		scrollDiv.setAttribute('id', 'lightwindow_scroll_div');
		scrollDiv.setStyle({
			position: 'absolute',
			top: '-10000px',
			left: '-10000px',
			width: '100px',
			height: '100px',
			overflow: 'hidden'
		});



	    var contentDiv = Element.extend(document.createElement('div'));
		contentDiv.setAttribute('id', 'lightwindow_content_scroll_div');
		contentDiv.setStyle({
			width: '100%',
			height: '200px'
		});

	    scrollDiv.appendChild(contentDiv);

		var body = document.getElementsByTagName('body')[0];
		body.appendChild(scrollDiv);

	    var noScroll = $('lightwindow_content_scroll_div').offsetWidth;
	    scrollDiv.style.overflow = 'auto';
    	var withScroll = $('lightwindow_content_scroll_div').offsetWidth;

	   	Element.remove($('lightwindow_scroll_div'));

	    this.scrollbarOffset = noScroll-withScroll;
	},
	

	//
	//  Add a param to an object dynamically created
	//
	_addParamToObject : function(name, value, object, id) {
		var param = document.createElement('param');
		param.setAttribute('value', value);
		param.setAttribute('name', name);
		if (id) {
			param.setAttribute('id', id);
		}
		object.appendChild(param);
		return object;
	},
	//
	//  Get the outer HTML of an object CROSS BROWSER
	//
	_outerHTML : function(object) {
 		if (Prototype.Browser.IE) {
			return object.outerHTML;
		} else {
			var clone = object.cloneNode(true);
			var cloneDiv = document.createElement('div');
			cloneDiv.appendChild(clone);
			return cloneDiv.innerHTML;
		}
	},
	//
	//  Convert an object to markup
	//
	_convertToMarkup : function(object, closeTag) {
		var markup = this._outerHTML(object).replace('</'+closeTag+'>', '');
		if (Prototype.Browser.IE) {
			for (var i = 0; i < object.childNodes.length; i++){
				markup += this._outerHTML(object.childNodes[i]);
			}
			markup += '</'+closeTag+'>';
		}
		return markup;
	},
	//
	//  Depending what type of browser it is we have to append the object differently... DAMN YOU IE!!
	//
	_appendObject : function(object, closeTag, appendTo) {
		if (Prototype.Browser.IE) {
			appendTo.innerHTML += this._convertToMarkup(object, closeTag);
			
			// Fix the Eolas activate thing but only for specified media, for example doing this to a quicktime film breaks it.
			if (this.options.EOLASFix.indexOf(this._fileType(this.element.href)) > -1) {
				var objectElements = document.getElementsByTagName('object');
				for (var i = 0; i < objectElements.length; i++) {
					if (objectElements[i].getAttribute("data")) objectElements[i].removeAttribute('data');
					objectElements[i].outerHTML = objectElements[i].outerHTML;
					objectElements[i].style.visibility = "visible";
				}
			}
		} else {
			appendTo.appendChild(object);	
		}	
	},
	//
	//  Add in iframe
	//
	_appendIframe : function(scroll) {
		var iframe = document.createElement('iframe');
		iframe.setAttribute('id', 'lightwindow_iframe');
		iframe.setAttribute('name', 'lightwindow_iframe');
		iframe.setAttribute('src', 'about:blank');
		iframe.setAttribute('height', '100%');
		iframe.setAttribute('width', '100%');
		iframe.setAttribute('frameborder', '0');
		iframe.setAttribute('marginwidth', '0');
		iframe.setAttribute('marginheight', '0');
		iframe.setAttribute('scrolling', scroll);	
		
		this._appendObject(iframe, 'iframe', $('lightwindow_contents'));
	},
	//
	//  Write Content to the iframe using the skin
	//
	_writeToIframe : function(content) {
		var template = this.options.skin.iframe;
		template = template.replace('{body_replace}', content); 
		if ($('lightwindow_iframe').contentWindow){
			$('lightwindow_iframe').contentWindow.document.open();
			$('lightwindow_iframe').contentWindow.document.write(template);
			$('lightwindow_iframe').contentWindow.document.close();
		} else {
			$('lightwindow_iframe').contentDocument.open();
			$('lightwindow_iframe').contentDocument.write(template);
			$('lightwindow_iframe').contentDocument.close();
		}
	},
	//
	//  Load the window Information
	//  
	_loadWindow : function() {
		switch (this.windowType) {
			case 'image' :

				var current = 0;
				var images = [];
				this.checkImage = [];
				this.resizeTo.height = this.resizeTo.width = 0;
				this.imageCount = this._getParameter('lightwindow_show_images') ? parseInt(this._getParameter('lightwindow_show_images')) : 1;

				// If there is a gallery get it
				if (gallery = this._getGalleryInfo(this.element.rel)) {	
					for (current = 0; current < this.galleries[gallery[0]][gallery[1]].length; current++) {
						if (this.contentToFetch.indexOf(this.galleries[gallery[0]][gallery[1]][current].href) > -1) {
							break;
						}
					}
					if (this.galleries[gallery[0]][gallery[1]][current-this.imageCount]) {
						this.navigationObservers.previous = this.galleries[gallery[0]][gallery[1]][current-this.imageCount];
					} else {
						this.navigationObservers.previous = false;
					}
					if (this.galleries[gallery[0]][gallery[1]][current+this.imageCount]) {
						this.navigationObservers.next = this.galleries[gallery[0]][gallery[1]][current+this.imageCount];
					} else {
						this.navigationObservers.next = false;
					}
					
					this.activeGallery = true;
				} else {
					this.navigationObservers.previous = false;
					this.navigationObservers.next = false;					

					this.activeGallery = false;
				}
				
				for (var i = current; i < (current+this.imageCount); i++) {
		
					if (gallery && this.galleries[gallery[0]][gallery[1]][i]) {
						this.contentToFetch = this.galleries[gallery[0]][gallery[1]][i].href;
						
						this.galleryLocation = {current: (i+1)/this.imageCount, total: (this.galleries[gallery[0]][gallery[1]].length)/this.imageCount};
											
						if (!this.galleries[gallery[0]][gallery[1]][i+this.imageCount]) {
							$('lightwindow_next').setStyle({
								display: 'none'
							});
						} else {
							$('lightwindow_next').setStyle({
								display: 'block'
							});
							$('lightwindow_next_title').innerHTML = this.galleries[gallery[0]][gallery[1]][i+this.imageCount].title;
						}
						
						if (!this.galleries[gallery[0]][gallery[1]][i-this.imageCount]) {
							$('lightwindow_previous').setStyle({
								display: 'none'
							});
						} else {
							$('lightwindow_previous').setStyle({
								display: 'block'
							});
							$('lightwindow_previous_title').innerHTML = this.galleries[gallery[0]][gallery[1]][i-this.imageCount].title;
						}
					}

					images[i] = document.createElement('img');
					images[i].setAttribute('id', 'lightwindow_image_'+i);
					images[i].setAttribute('border', '0');
					images[i].setAttribute('src', this.contentToFetch);
					$('lightwindow_contents').appendChild(images[i]);

					// We have to do this instead of .onload 
					this.checkImage[i] = new PeriodicalExecuter(function(i) {
						if (!(typeof $('lightwindow_image_'+i).naturalWidth != "undefined" && $('lightwindow_image_'+i).naturalWidth == 0)) {
	
							this.checkImage[i].stop();
	
							var imageHeight = $('lightwindow_image_'+i).getHeight();
							if (imageHeight > this.resizeTo.height) {
								this.resizeTo.height = imageHeight;
							}
							this.resizeTo.width += $('lightwindow_image_'+i).getWidth();
							this.imageCount--;
	
							$('lightwindow_image_'+i).setStyle({
								height: '100%'
							});
	
						 	if (this.imageCount == 0) {
								this._processWindow();
						 	}
						}
					
					}.bind(this, i), 1);			
				}


			break;
		
		case 'media' :			
		
			var current = 0;
			this.resizeTo.height = this.resizeTo.width = 0;

			// If there is a gallery get it
			if (gallery = this._getGalleryInfo(this.element.rel)) {	
				for (current = 0; current < this.galleries[gallery[0]][gallery[1]].length; current++) {
					if (this.contentToFetch.indexOf(this.galleries[gallery[0]][gallery[1]][current].href) > -1) {
						break;
					}
				}
				
				if (this.galleries[gallery[0]][gallery[1]][current-1]) {
					this.navigationObservers.previous = this.galleries[gallery[0]][gallery[1]][current-1];
				} else {
					this.navigationObservers.previous = false;
				}
				if (this.galleries[gallery[0]][gallery[1]][current+1]) {
					this.navigationObservers.next = this.galleries[gallery[0]][gallery[1]][current+1];
				} else {
					this.navigationObservers.next = false;
				}
		
				this.activeGallery = true;
			} else {
				this.navigationObservers.previous = false;
				this.navigationObservers.next = false;
				
				this.activeGallery = false;
			}
		

			if (gallery && this.galleries[gallery[0]][gallery[1]][current]) {
				this.contentToFetch = this.galleries[gallery[0]][gallery[1]][current].href;

				this.galleryLocation = {current: current+1, total: this.galleries[gallery[0]][gallery[1]].length};
				
				if (!this.galleries[gallery[0]][gallery[1]][current+1]) {
					$('lightwindow_next').setStyle({
						display: 'none'
					});
				} else {
					$('lightwindow_next').setStyle({
						display: 'block'
					});
					$('lightwindow_next_title').innerHTML = this.galleries[gallery[0]][gallery[1]][current+1].title;
				}
				
				if (!this.galleries[gallery[0]][gallery[1]][current-1]) {
					$('lightwindow_previous').setStyle({
						display: 'none'
					});
				} else {
					$('lightwindow_previous').setStyle({
						display: 'block'
					});
					$('lightwindow_previous_title').innerHTML = this.galleries[gallery[0]][gallery[1]][current-1].title;
				}
			}
			
			if (this._getParameter('lightwindow_iframe_embed')) {
				this.resizeTo.height = this.dimensions.viewport.height;
				this.resizeTo.width = this.dimensions.viewport.width;	
			} else {
				this.resizeTo.height = this._getParameter('lightwindow_height');
				this.resizeTo.width = this._getParameter('lightwindow_width');				
			}
			
			this._processWindow();
			
			break;

		case 'external' :		

			this._appendIframe('auto');

			this.resizeTo.height = this.dimensions.viewport.height;
			this.resizeTo.width = this.dimensions.viewport.width;
						
			this._processWindow();

			break;
				
		case 'page' :	
			
			var newAJAX = new Ajax.Request(
				this.contentToFetch, {
					method: 'get', 
					parameters: '', 
					onComplete: function(response) {
						$('lightwindow_contents').innerHTML += response.responseText;
						this.resizeTo.height = $('lightwindow_contents').scrollHeight+(this.options.contentOffset.height);
						this.resizeTo.width = $('lightwindow_contents').scrollWidth+(this.options.contentOffset.width);
						this._processWindow();
						if (Prototype.Browser.IE) {
			Event.observe(document, 'mousewheel', this._stopScrolling.bindAsEventListener(this), false);
		} else {
			Event.observe(window, 'DOMMouseScroll', this._stopScrolling.bindAsEventListener(this), false);
		}
					}.bind(this)
				}
			);
			
			break;
			
		case 'inline' : 
		
			var content = this.contentToFetch;
			if (content.indexOf('?') > -1) {
				content = content.substring(0, content.indexOf('?'));
			}
			content = content.substring(content.indexOf('#')+1);
			
			new Insertion.Top($('lightwindow_contents'), $(content).innerHTML);
			
			this.resizeTo.height = $('lightwindow_contents').scrollHeight+(this.options.contentOffset.height);
			this.resizeTo.width = $('lightwindow_contents').scrollWidth+(this.options.contentOffset.width);
			
			this._toggleTroubleElements('hidden', true); 			
			this._processWindow();
			
			break;
			
		default : 
			throw("Page Type could not be determined, please amend this lightwindow URL "+this.contentToFetch);
			break;
		}
	},
	//
	//  Resize the Window to fit the viewport if necessary
	//
	_resizeWindowToFit : function() {
		if (this.resizeTo.height+this.dimensions.cruft.height > this.dimensions.viewport.height) {
			var heightRatio = this.resizeTo.height/this.resizeTo.width;
			this.resizeTo.height = this.dimensions.viewport.height-this.dimensions.cruft.height-(2*this.options.viewportPadding);
			// We only care about ratio's with this window type			
			if (this.windowType == 'image' || (this.windowType == 'media' && !this._getParameter('lightwindow_iframe_embed'))) {
				this.resizeTo.width = this.resizeTo.height/heightRatio;
				$('lightwindow_data_slide_inner').setStyle({
					width: this.resizeTo.width+'px'
				});			
			}
		} 
		if (this.resizeTo.width+this.dimensions.cruft.width > this.dimensions.viewport.width) {
			var widthRatio = this.resizeTo.width/this.resizeTo.height;
			this.resizeTo.width = this.dimensions.viewport.width-2*this.dimensions.cruft.width-(2*this.options.viewportPadding);
			// We only care about ratio's with this window type
			if (this.windowType == 'image' || (this.windowType == 'media' && !this._getParameter('lightwindow_iframe_embed'))) {
				this.resizeTo.height = this.resizeTo.width/widthRatio;
				$('lightwindow_data_slide_inner').setStyle({
					height: this.resizeTo.height+'px'
				});
			}
		}
			
	},
	//
	//  Set the Window to a preset size
	//
	_presetWindowSize : function() {
		if (this._getParameter('lightwindow_height')) {
			this.resizeTo.height = parseFloat(this._getParameter('lightwindow_height'));
		}
		if (this._getParameter('lightwindow_width')) {
			this.resizeTo.width = parseFloat(this._getParameter('lightwindow_width'));
		}
	},
	//
	//  Process the Window
	//
	_processWindow : function() {
		// Clean out our effects
		this.dimensions.dataEffects = [];

		// Set up the data-slide if we have caption information
		if (this.element.caption || this.element.author || (this.activeGallery && this.options.showGalleryCount)) {
			if (this.element.caption) {
				$('lightwindow_data_caption').innerHTML = this.element.caption;
				$('lightwindow_data_caption').setStyle({
					display: 'block'
				});
			} else {
				$('lightwindow_data_caption').setStyle({
					display: 'none'
				});				
			}
			if (this.element.author) {
				$('lightwindow_data_author').innerHTML = this.element.author;
				$('lightwindow_data_author_container').setStyle({
					display: 'block'
				});
			} else {
				$('lightwindow_data_author_container').setStyle({
					display: 'none'
				});				
			}
			if (this.activeGallery && this.options.showGalleryCount) {
				$('lightwindow_data_gallery_current').innerHTML = this.galleryLocation.current;
				$('lightwindow_data_gallery_total').innerHTML = this.galleryLocation.total;
				$('lightwindow_data_gallery_container').setStyle({
					display: 'block'
				});
			} else {
				$('lightwindow_data_gallery_container').setStyle({
					display: 'none'
				});				
			}

			$('lightwindow_data_slide_inner').setStyle({
				width: this.resizeTo.width+'px',
				height: 'auto',
				visibility: 'visible',
				display: 'block'
			});
			$('lightwindow_data_slide').setStyle({
				height: $('lightwindow_data_slide').getHeight()+'px',
				width: '1px',
				overflow: 'hidden',
				display: 'block'
			});
		} else {
			$('lightwindow_data_slide').setStyle({
				display: 'none',
				width: 'auto'
			});
			$('lightwindow_data_slide_inner').setStyle({
				display: 'none',
				visibility: 'hidden',
				width: this.resizeTo.width+'px',
				height: '0px'
			});
		}
				
		if (this.element.title != 'null') {		
			$('lightwindow_title_bar_title').innerHTML = this.element.title;
		} else {
			$('lightwindow_title_bar_title').innerHTML = '';
		}
		
		var originalContainerDimensions = {height: $('lightwindow_container').getHeight(), width: $('lightwindow_container').getWidth()};
		// Position the window
    	$('lightwindow_container').setStyle({
			height: 'auto',
			// We need to set the width to a px not auto as opera has problems with it
			width: $('lightwindow_container').getWidth()+this.options.contentOffset.width-(this.windowActive ? this.options.contentOffset.width : 0)+'px'
		});
		var newContainerDimensions = {height: $('lightwindow_container').getHeight(), width: $('lightwindow_container').getWidth()};
 		
		// We need to record the container dimension changes
		this.containerChange = {height: originalContainerDimensions.height-newContainerDimensions.height, width: originalContainerDimensions.width-newContainerDimensions.width};

		// Get out general dimensions
		this.dimensions.container = {height: $('lightwindow_container').getHeight(), width: $('lightwindow_container').getWidth()};
		this.dimensions.cruft = {height: this.dimensions.container.height-$('lightwindow_contents').getHeight()+this.options.contentOffset.height, width: this.dimensions.container.width-$('lightwindow_contents').getWidth()+this.options.contentOffset.width};
		
		// Set Sizes if we need too
		this._presetWindowSize();
		this._resizeWindowToFit(); // Even if the window is preset we still don't want it to go outside of the viewport

		if (!this.windowActive) {
			// Position the window
		   	$('lightwindow_container').setStyle({
				left: -(this.dimensions.container.width/2)+'px',
				top: -(this.dimensions.container.height/2)+'px'
			});
		}
	   	$('lightwindow_container').setStyle({
			height: this.dimensions.container.height+'px',
			width: this.dimensions.container.width+'px'
		});
		
		/*$('lightwindow_overlay').setStyle({
			left: 0,
			top: this.pagePosition.y+'px'
		});*/
		
		// We are ready, lets show this puppy off!
		this._displayLightWindow('block', 'visible');
		this._animateLightWindow();
		
		if (Prototype.Browser.IE) {
			Event.observe(document, 'mousewheel', this._stopScrolling.bindAsEventListener(this), false);
		} else {
			Event.observe(window, 'DOMMouseScroll', this._stopScrolling.bindAsEventListener(this), false);
		}
	},
	//
	//  Fire off our animation handler
	//
	_animateLightWindow : function() {
		if (this.options.animationHandler) {
			this.options.animationHandler().bind(this);
		} else {
			this._defaultAnimationHandler();
		}
	},
	//
	//  Fire off our transition handler
	//
	_handleNavigation : function(display) {
		if (this.options.navigationHandler) {
			this.options.navigationHandler().bind(this, display);
		} else {
			this._defaultDisplayNavigation(display);
		}
	},
	//
	//  Fire off our transition handler
	//
	_handleTransition : function() {
		if (this.options.transitionHandler) {
			this.options.transitionHandler().bind(this);
		} else {
			this._defaultTransitionHandler();
		}
	},
	//
	//  Handle the finish of the window animation
	// 
	_handleFinalWindowAnimation : function(delay) {
		if (this.options.finalAnimationHandler) {
			this.options.finalAnimationHandler().bind(this, delay);
		} else {
			this._defaultfinalWindowAnimationHandler(delay);
		}		
	},
	//
	//  Handle the gallery Animation
	// 
	_handleGalleryAnimation : function(list) {
		if (this.options.galleryAnimationHandler) {
			this.options.galleryAnimationHandler().bind(this, list);
		} else {
			this._defaultGalleryAnimationHandler(list);
		}		
	},
	//
	//  Display the navigation 
	//
	_defaultDisplayNavigation : function(display) {
		if (display) {
			$('lightwindow_navigation').setStyle({
				display: 'block',
				height: $('lightwindow_contents').getHeight()+'px',
				width: '100%',
				marginTop: this.options.dimensions.titleHeight+'px'
			});			
		} else {
			$('lightwindow_navigation').setStyle({
				display: 'none',
				height: 'auto',
				width: 'auto'
			});			
		}
	},
	//
	//  This is the default animation handler for LightWindow
	//
	_defaultAnimationHandler : function() {	
		// Now that we have figures out the cruft lets make the caption go away and add its effects
		if (this.element.caption || this.element.author || (this.activeGallery && this.options.showGalleryCount)) {
			$('lightwindow_data_slide').setStyle({
				display: 'none',
				width: 'auto'
			});
			this.dimensions.dataEffects.push(
				new Effect.SlideDown('lightwindow_data_slide', {sync: true}),
				new Effect.Appear('lightwindow_data_slide', {sync: true, from: 0.0, to: 1.0})
			);
		}

		// Set up the Title if we have one
		$('lightwindow_title_bar_inner').setStyle({
			height: '0px',
			marginTop: this.options.dimensions.titleHeight+'px'
		});
		
		// We always want the title bar as well
		this.dimensions.dataEffects.push(
			new Effect.Morph('lightwindow_title_bar_inner', {sync: true, style: {height: this.options.dimensions.titleHeight+'px', marginTop: '0px'}}),
		 	new Effect.Appear('lightwindow_title_bar_inner', {sync: true, from: 0.0, to: 1.0})
		);		
		
		if (!this.options.hideGalleryTab) {
			this._handleGalleryAnimation(false);
			if ($('lightwindow_galleries_tab_container').getHeight() == 0) {
				this.dimensions.dataEffects.push(
					new Effect.Morph('lightwindow_galleries_tab_container', {sync: true, style: {height: '20px', marginTop: '0px'}})
				);
				$('lightwindow_galleries').setStyle({
					width: '0px'
				});
			}
		}
		
		var resized = false;
		var ratio = this.dimensions.container.width-$('lightwindow_contents').getWidth()+this.resizeTo.width+this.options.contentOffset.width;
		if (ratio != $('lightwindow_container').getWidth()) {
			new Effect.Parallel([
					new Effect.Scale('lightwindow_contents', 100*(this.resizeTo.width/$('lightwindow_contents').getWidth()), {scaleFrom: 100*($('lightwindow_contents').getWidth()/($('lightwindow_contents').getWidth()+(this.options.contentOffset.width))), sync: true,  scaleY: false, scaleContent: false}),
					new Effect.Scale('lightwindow_container', 100*(ratio/(this.dimensions.container.width)), {sync: true, scaleY: false, scaleFromCenter: true, scaleContent: false})
				], {
					duration: this.duration, 
					delay: 0.25,
					queue: {position: 'end', scope: 'lightwindowAnimation'}
				}
			);		
		}
		
		ratio = this.dimensions.container.height-$('lightwindow_contents').getHeight()+this.resizeTo.height+this.options.contentOffset.height;
		if (ratio != $('lightwindow_container').getHeight()) {
			new Effect.Parallel([
					new Effect.Scale('lightwindow_contents', 100*(this.resizeTo.height/$('lightwindow_contents').getHeight()), {scaleFrom: 100*($('lightwindow_contents').getHeight()/($('lightwindow_contents').getHeight()+(this.options.contentOffset.height))), sync: true, scaleX: false, scaleContent: false}),
					new Effect.Scale('lightwindow_container', 100*(ratio/(this.dimensions.container.height)), {sync: true, scaleX: false, scaleFromCenter: true, scaleContent: false})
				], {
					duration: this.duration, 
					afterFinish: function() {				
						if (this.dimensions.dataEffects.length > 0) {
							if (!this.options.hideGalleryTab) {
								$('lightwindow_galleries').setStyle({
									width: this.resizeTo.width+'px'
								});
							}
							new Effect.Parallel(this.dimensions.dataEffects, {
									duration: this.duration,
									afterFinish: function() {
										this._finishWindow();
									}.bind(this),
									queue: {position: 'end', scope: 'lightwindowAnimation'} 
								}
							);
						}
					}.bind(this), 
					queue: {position: 'end', scope: 'lightwindowAnimation'} 
				}
			);
			resized = true;
		}
		
		// We need to do our data effect since there was no resizing
		if (!resized && this.dimensions.dataEffects.length > 0) {	
			new Effect.Parallel(this.dimensions.dataEffects, {
					duration: this.duration,
					beforeStart: function() {
						if (!this.options.hideGalleryTab) {
							$('lightwindow_galleries').setStyle({
								width: this.resizeTo.width+'px'
							});
						}
						if (this.containerChange.height != 0 || this.containerChange.width != 0) {
							new Effect.MoveBy('lightwindow_container', this.containerChange.height, this.containerChange.width, {transition: Effect.Transitions.sinoidal});
						}
					}.bind(this),			
					afterFinish: function() {
						this._finishWindow();
					}.bind(this),
					queue: {position: 'end', scope: 'lightwindowAnimation'} 
				}
			);
		}			
		
	},
	//
	//  Finish up Window Animation
	//
	_defaultfinalWindowAnimationHandler : function(delay) {
		if (this.windowType == 'media' || this._getParameter('lightwindow_loading_animation')) {	
			// Because of major flickering with the overlay we just hide it in this case
			Element.hide('lightwindow_loading');
			this._handleNavigation(this.activeGallery);
			this._setStatus(false);
		} else {
			Effect.Fade('lightwindow_loading', {
				duration: 0.75,
				delay: 1.0, 
				afterFinish: function() {
					// Just in case we need some scroll goodness (this also avoids the swiss cheese effect)
					if (this.windowType != 'image' && this.windowType != 'media' && this.windowType != 'external') {
						$('lightwindow_contents').setStyle({
							overflow: 'auto'
						});
					}
					this._handleNavigation(this.activeGallery);
					this._defaultGalleryAnimationHandler();
					this._setStatus(false);
				}.bind(this),
				queue: {position: 'end', scope: 'lightwindowAnimation'}
			});
		}
	},
	//
	//  Handle the gallery Animation
	//
	_defaultGalleryAnimationHandler : function(list) {
		if (this.activeGallery) {
			$('lightwindow_galleries').setStyle({
				display: 'block',
				marginBottom: $('lightwindow_data_slide').getHeight()+this.options.contentOffset.height/2+'px'
			});
			$('lightwindow_navigation').setStyle({
				height: $('lightwindow_contents').getHeight()-20+'px'
			});
		} else {
			$('lightwindow_galleries').setStyle({
				display: 'none'
			});	
			$('lightwindow_galleries_tab_container').setStyle({
				height: '0px',
				marginTop: '20px'
			});
			$('lightwindow_galleries_list').setStyle({
				height: '0px'
			});
			return false;
		}
		
		if (list) {
			if ($('lightwindow_galleries_list').getHeight() == 0) {
				var height = $('lightwindow_contents').getHeight()*0.80;
				$('lightwindow_galleries_tab_span').className = 'down';
			} else {
				var height = 0;
				$('lightwindow_galleries_tab_span').className = 'up';
			}

			new Effect.Morph('lightwindow_galleries_list', {
				duration: this.duration,
				transition: Effect.Transitions.sinoidal,
				style: {height: height+'px'},
				beforeStart: function() {
					$('lightwindow_galleries_list').setStyle({
						overflow: 'hidden'
					});					
				},
				afterFinish: function() {
					$('lightwindow_galleries_list').setStyle({
						overflow: 'auto'
					});
				},
				queue: {position: 'end', scope: 'lightwindowAnimation'}
			});	
		}
		
		
	},
	//
	//  Default Transition Handler
	//
	_defaultTransitionHandler : function() {
		// Clean out our effects
		this.dimensions.dataEffects = [];

		// Now that we have figures out the cruft lets make the caption go away and add its effects
		if ($('lightwindow_data_slide').getStyle('display') != 'none') {
			this.dimensions.dataEffects.push(
				new Effect.SlideUp('lightwindow_data_slide', {sync: true}),
				new Effect.Fade('lightwindow_data_slide', {sync: true, from: 1.0, to: 0.0})
			);
		}
		
		if (!this.options.hideGalleryTab) {
			if ($('lightwindow_galleries').getHeight() != 0 && !this.options.hideGalleryTab) {
				this.dimensions.dataEffects.push(
					new Effect.Morph('lightwindow_galleries_tab_container', {sync: true, style: {height: '0px', marginTop: '20px'}})
				);
			}
			
			if ($('lightwindow_galleries_list').getHeight() != 0) {
				$('lightwindow_galleries_tab_span').className = 'up';
				this.dimensions.dataEffects.push(
					new Effect.Morph('lightwindow_galleries_list', {
						sync: true, 
						style: {height: '0px'},
						transition: Effect.Transitions.sinoidal,
						beforeStart: function() {
							$('lightwindow_galleries_list').setStyle({
								overflow: 'hidden'
							});					
						},
						afterFinish: function() {
							$('lightwindow_galleries_list').setStyle({
								overflow: 'auto'
							});
						}
					})
				);
			}
		}
		
		// We always want the title bar as well
		this.dimensions.dataEffects.push(
			new Effect.Morph('lightwindow_title_bar_inner', {sync: true, style: {height: '0px', marginTop: this.options.dimensions.titleHeight+'px'}}),
		 	new Effect.Fade('lightwindow_title_bar_inner', {sync: true, from: 1.0, to: 0.0})
		);

		new Effect.Parallel(this.dimensions.dataEffects, {
				duration: this.duration,
				afterFinish: function() {
					this._loadWindow();
				}.bind(this),
				queue: {position: 'end', scope: 'lightwindowAnimation'} 
			}
		);	
	},
	//
	//	Default Form handler for LightWindow
	//
	_defaultFormHandler : function(e) {
		var element = Event.element(e).parentNode;
		var parameterString = Form.serialize(this._getParameter('lightwindow_form', element.getAttribute('params')));
		if (this.options.formMethod == 'post') {
			var newAJAX = new Ajax.Request(element.href, { 
				method: 'post', 
				postBody: parameterString, 
				onComplete: this.openWindow.bind(this, element)
			});
		} else if (this.options.formMethod == 'get') {
			var newAJAX = new Ajax.Request(element.href, { 
				method: 'get', 
				parameters: parameterString, 
				onComplete: this.openWindow.bind(this, element)
			});
		}
	},
	// 
	//  Wrap everything up
	//
	_finishWindow : function() {
		if (this.windowType == 'external') {
			// We set the externals source here because it allows for a much smoother animation
			$('lightwindow_iframe').setAttribute('src', this.element.href);
			this._handleFinalWindowAnimation(1);	
		} else if (this.windowType == 'media') {

			var outerObject = document.createElement('object');
			outerObject.setAttribute('classid', this.options.classids[this._fileExtension(this.contentToFetch)]);
			outerObject.setAttribute('codebase', this.options.codebases[this._fileExtension(this.contentToFetch)]);
			outerObject.setAttribute('id', 'lightwindow_media_primary');
			outerObject.setAttribute('name', 'lightwindow_media_primary');
			outerObject.setAttribute('width', this.resizeTo.width);
			outerObject.setAttribute('height', this.resizeTo.height);
			outerObject = this._addParamToObject('movie', this.contentToFetch, outerObject);
			outerObject = this._addParamToObject('src', this.contentToFetch, outerObject);
			outerObject = this._addParamToObject('controller', 'true', outerObject);
			outerObject = this._addParamToObject('wmode', 'transparent', outerObject);
			outerObject = this._addParamToObject('cache', 'false', outerObject);
			outerObject = this._addParamToObject('quality', 'high', outerObject);

			if (!Prototype.Browser.IE) {
				var innerObject = document.createElement('object');
				innerObject.setAttribute('type', this.options.mimeTypes[this._fileExtension(this.contentToFetch)]);
				innerObject.setAttribute('data', this.contentToFetch);
				innerObject.setAttribute('id', 'lightwindow_media_secondary');
				innerObject.setAttribute('name', 'lightwindow_media_secondary');
				innerObject.setAttribute('width', this.resizeTo.width);
				innerObject.setAttribute('height', this.resizeTo.height);
				innerObject = this._addParamToObject('controller', 'true', innerObject);
				innerObject = this._addParamToObject('wmode', 'transparent', innerObject);
				innerObject = this._addParamToObject('cache', 'false', innerObject);
				innerObject = this._addParamToObject('quality', 'high', innerObject);
			
				outerObject.appendChild(innerObject);
			}	
			
			if (this._getParameter('lightwindow_iframe_embed')) {
				this._appendIframe('no');
				this._writeToIframe(this._convertToMarkup(outerObject, 'object'));
			} else {
				this._appendObject(outerObject, 'object', $('lightwindow_contents'));
			}

			this._handleFinalWindowAnimation(0);
		} else {
			this._handleFinalWindowAnimation(0);
		}

		// Initialize any actions
		this._setupActions();
	}
}

/*-----------------------------------------------------------------------------------------------*/

//Event.observe(window, 'load', lightwindowInit, false);

//
//	Set up all of our links
//
//var myLightWindow = null;
//function lightwindowInit() {
//	myLightWindow = new lightwindow();
//}

/**
 * Copy the value of an input field's title attribute to its value attribute.
 * Clear the input field on focus if its value is the same as its title.
 * Repopulate the input field on blur if it is empty.
 * Hide the input field's associated label if it has one.
 */
var autoPopulate = {
	sInputClass:'populate', // Class name for input elements to autopopulate
	sHiddenClass:'structural', // Class name that gets assigned to hidden label elements
	bHideLabels:true, // If true, labels are hidden
	/**
	 * Main function
	 */
	init:function() {
		// Check for DOM support
		if (!document.getElementById || !document.createTextNode) {return;}
		// Find all input elements with the given className
		var arrInputs = autoPopulate.getElementsByClassName(document, 'input', autoPopulate.sInputClass);
		var iInputs = arrInputs.length;
		var oInput;
		for (var i=0; i<iInputs; i++) {
			oInput = arrInputs[i];
			// Make sure it's a text input
			if (oInput.type != 'text') { continue; }
			// Hide the input's label
			if (autoPopulate.bHideLabels) { autoPopulate.hideLabel(oInput.id); }
			// If value is empty and title is not, assign title to value
			if ((oInput.value == '') && (oInput.title != '')) { oInput.value = oInput.title; }
			// Add event handlers for focus and blur
			autoPopulate.addEvent(oInput, 'focus', function() {
				// If value and title are equal on focus, clear value
				if (this.value == this.title) {
					this.value = '';
					this.select(); // Make input caret visible in IE
				}
			});
			autoPopulate.addEvent(oInput, 'blur', function() {
				// If the field is empty on blur, assign title to value
				if (!this.value.length) { this.value = this.title; }
			});
		}
	},
	hideLabel:function(sId) {
		var arrLabels = document.getElementsByTagName('label');
		var iLabels = arrLabels.length;
		var oLabel;
		for (var i=0; i<iLabels; i++) {
			oLabel = arrLabels[i];
			if (oLabel.htmlFor == sId) {
				oLabel.className = oLabel.className + ' ' + autoPopulate.sHiddenClass;
			}
		}
	},
	/**
	 * getElementsByClassName function included here for portability.
	 * Remove if you are already using one.
	 * Written by Jonathan Snook, http://www.snook.ca/jonathan
	 * Add-ons by Robert Nyman, http://www.robertnyman.com
	 */
	getElementsByClassName:function(oElm, strTagName, strClassName) {
	    var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
	    var arrReturnElements = new Array();
	    strClassName = strClassName.replace(/\-/g, "\\-");
	    var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	    var oElement;
	    for(var i=0; i<arrElements.length; i++){
	        oElement = arrElements[i];      
	        if(oRegExp.test(oElement.className)){
	            arrReturnElements.push(oElement);
	        }   
	    }
	    return (arrReturnElements)
	},
	/**
	 * addEvent function included here for portability.
	 * Remove if you are already using an addEvent/DOMReady function.
	 * Found at http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
	 */
	addEvent:function(obj, type, fn) {
		if (obj.addEventListener)
			obj.addEventListener(type, fn, false);
		else if (obj.attachEvent) {
			obj["e"+type+fn] = fn;
			obj[type+fn] = function() {obj["e"+type+fn](window.event);}
			obj.attachEvent("on"+type, obj[type+fn]);
		}
	}
};

/**
 * Init on window load.
 * Replace this with a call to your own addEvent/DOMReady function if you use one.
 */
autoPopulate.addEvent(window, 'load', autoPopulate.init);

var listMenu = new FSMenu('listMenu', true, 'display', 'block', 'none');

listMenu.animations[listMenu.animations.length] = FSMenu.animFade;
listMenu.animations[listMenu.animations.length] = FSMenu.animSwipeDown;

var arrow = null;
if (document.createElement && document.documentElement)
{
	arrow = document.createElement('span');
	arrow.appendChild(document.createTextNode(''));
	arrow.className = 'subind';
}

addEvent(window, 'load', new Function('listMenu.activateMenu("listMenuRoot", arrow)'));

