//ensure that all onload events are executed
function addEvent(obj, evType, fn){
	if (obj.addEventListener){
		obj.addEventListener(evType, fn, true);
		return true;
		} else if (obj.attachEvent){
			var r = obj.attachEvent('on'+evType, fn);
			return r;
			} else {
			return false;
			}
	}


// admin section scripts

var url;
addEvent(window, 'load', admin);


function swapthumb() {
	var x=document.getElementById("existingfiles");
	var picname = x.value + x.options[x.selectedIndex].text;
	document.getElementById("imgpreview").src = url + picname;
}
function collapsinate() {
	x = this.parentNode;
	
	for(i=0; i<x.childNodes.length; i++) {
		if(x.childNodes[i].nodeType == 1 && x.childNodes[i].nodeName != "LEGEND" ) {	
			if(x.childNodes[i].className.indexOf("nein") == -1) {
				x.childNodes[i].className += " nein";
				} else {
				var classes = x.childNodes[i].className.split(" ");
				x.childNodes[i].className = x.childNodes[i].className.substring(0,x.childNodes[i].className.indexOf("nein"));
				}
			}
		}
	}
function sluginate() {
		var headline = document.getElementById("headline").value;

		var slug = document.getElementById("slug");
		var temp = headline.replace(/[^[:alnum:]]/gi,"_");
		temp = temp.replace(/[_]+/gi,"_");
		slug.value = temp.toLowerCase();

		}
function admin() {
	var exfi = document.getElementById("existingfiles");
	if(!exfi) return;
	exfi.onchange = swapthumb;
	url = document.getElementById("imgpreview").src
	if(url != "") {
		url = url.split("/");
		url.pop();
		url = url.join("/");
		url+="/";
	} else {
		url = "";
	}

	var legends = document.getElementsByTagName("legend");
	for(i=0; i<legends.length; i++) {
		legends[i].style.cursor = "pointer";
		legends[i].onclick = collapsinate;
	}

	document.getElementById("headline").onblur = sluginate;
}

// COMMENT SECTION
addEvent(window, 'load', prepComments);

function superTextile(s) {
    var r = s;
    // quick tags first
    qtags = [['\\*', 'strong'],
             ['\\?\\?', 'cite'],
             ['\\+', 'ins'],  //fixed
             ['~', 'sub'],   
             ['\\^', 'sup'], // me
             ['@', 'code']];
    for (var i=0;i<qtags.length;i++) {
        ttag = qtags[i][0]; htag = qtags[i][1];
        re = new RegExp(ttag+'\\b(.+?)\\b'+ttag,'g');
        r = r.replace(re,'<'+htag+'>'+'$1'+'</'+htag+'>');
    }
    // underscores count as part of a word, so do them separately
    re = new RegExp('\\b_(.+?)_\\b','g');
    r = r.replace(re,'<em>$1</em>');
	
	//jeff: so do dashes
    re = new RegExp('[\s\n]-(.+?)-[\s\n]','g');
    r = r.replace(re,'<del>$1</del>');

    // links
    re = new RegExp('"\\b(.+?)\\(\\b(.+?)\\b\\)":([^\\s]+)','g');
    r = r.replace(re,'<a href="$3" title="$2">$1</a>');
    re = new RegExp('"\\b(.+?)\\b":([^\\s]+)','g');
    r = r.replace(re,'<a href="$2">$1</a>');

    // images
    re = new RegExp('!\\b(.+?)\\(\\b(.+?)\\b\\)!','g');
    r = r.replace(re,'<img src="$1" alt="$2">');
    re = new RegExp('!\\b(.+?)\\b!','g');
    r = r.replace(re,'<img src="$1">');
    
    // block level formatting
	
		// Jeff's hack to show single line breaks as they should.
		// insert breaks - but you get some....stupid ones
	    re = new RegExp('(.*)\n([^#\*\n].*)','g');
	    r = r.replace(re,'$1<br />$2');
		// remove the stupid breaks.
	    re = new RegExp('\n<br />','g');
	    r = r.replace(re,'\n');
	
    lines = r.split('\n');
    nr = '';
    for (var i=0;i<lines.length;i++) {
        line = lines[i].replace(/\s*$/,'');
        changed = 0;
        if (line.search(/^\s*bq\.\s+/) != -1) { 
			line = line.replace(/^\s*bq\.\s+/,'\t<blockquote>')+'</blockquote>'; 
			changed = 1; 
		}
		
		// jeff adds h#.
        if (line.search(/^\s*h[1|2|3|4|5|6]\.\s+/) != -1) { 
	    	re = new RegExp('h([1|2|3|4|5|6])\.(.+)','g');
	    	line = line.replace(re,'<h$1>$2</h$1>');
			changed = 1; 
		}
		
		if (line.search(/^\s*\*\s+/) != -1) { line = line.replace(/^\s*\*\s+/,'\t<liu>') + '</liu>'; changed = 1; } // * for bullet list; make up an liu tag to be fixed later
        if (line.search(/^\s*#\s+/) != -1) { line = line.replace(/^\s*#\s+/,'\t<lio>') + '</lio>'; changed = 1; } // # for numeric list; make up an lio tag to be fixed later
        if (!changed && (line.replace(/\s/g,'').length > 0)) line = '<p>'+line+'</p>';
        lines[i] = line + '\n';
    }
	
    // Second pass to do lists
    inlist = 0; 
	listtype = '';
    for (var i=0;i<lines.length;i++) {
        line = lines[i];
        if (inlist && listtype == 'ul' && !line.match(/^\t<liu/)) { line = '</ul>\n' + line; inlist = 0; }
        if (inlist && listtype == 'ol' && !line.match(/^\t<lio/)) { line = '</ol>\n' + line; inlist = 0; }
        if (!inlist && line.match(/^\t<liu/)) { line = '<ul>' + line; inlist = 1; listtype = 'ul'; }
        if (!inlist && line.match(/^\t<lio/)) { line = '<ol>' + line; inlist = 1; listtype = 'ol'; }
        lines[i] = line;
    }

    r = lines.join('\n');
	// jeff added : will correctly replace <li(o|u)> AND </li(o|u)>
    r = r.replace(/li[o|u]>/g,'li>');

    return r;
}

function fillinusername() {
	var dd = document.getElementById('bywhom');
	while(dd.firstChild) { dd.removeChild(dd.firstChild); }

	var fromwhere = document.getElementById('c_www');
	var whom = document.getElementById('c_name');
	var username = "";
	var userwww;
	if(whom.value) {
		username = whom.value;
		}
		var u = document.createTextNode(username);
	
	if(fromwhere.value) {
		var a = document.createElement("a");
		a.href = fromwhere.value;
		a.appendChild(u)
		} else {
		a = document.createTextNode(username);
		}
	dd.appendChild(a);
	}

function reloadPreviewDiv() { 
	var commentString = document.getElementById('c_text').value;
	var con = superTextile(commentString);
	//document.getElementById('livecode').value = con;
	var c = document.getElementById('commentpreview');
	c.innerHTML = con;
}

function findPosY(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop
			obj = obj.offsetParent;
			}
		} 
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}
var cf;
var cp;
	function followcomment() {
		cp = document.getElementById("commentsection");
		cpy = findPosY(cp); // y position of the parent
		
		if(!document.all) { var sp = window.pageYOffset } 
			else { var sp = document.body.scrollTop }

		if(cpy < sp ) {
			cf.style.top = Math.floor(sp-cpy) + "px";
			} else {
			cf.style.top = 0;
			}
		}
			
	function prepComments() {
		var ct = document.getElementById('c_text');
		if(!ct) return;
		ct.onkeyup = reloadPreviewDiv;

		cf = document.getElementById("commentform");
		cf.className="follower";
		followcomment();
		addEvent(window, 'scroll', followcomment);
	//	window.onscroll = followcomment;

		var fromwhere = document.getElementById('c_www');
		fromwhere.onblur = fillinusername;
		var whom = document.getElementById('c_name');
		whom.onblur = fillinusername;
		}

//NEW WINDOW ICONS
addEvent(window, 'load', iconLink);

function iconLink() {
	if(document.all || !document.getElementById) return;

	if (document.appendChild && document.replaceChild && document.getElementsByTagName && document.createElement) {
		if(w = document.getElementById('main')) var links = w.getElementsByTagName('a');
		if(w = document.getElementById('fullmain')) var links = w.getElementsByTagName('a');
		if(!links || links.length == 0) return;
	
			for (var i = 0; i < links.length; i++) {
				//only alter links that have a different hostname and that haven't been already crawled, and aren't newWindow already.
				var host = "pennypacker.net"; //replace("www.", window.location.hostname);
				//var host = "pennypacker.local"; //replace("www.", window.location.hostname);
				if(links[i].hostname && links[i].hostname.indexOf(host) == -1 && links[i].className.substring(0,7) != 'nocrawl' && !links[i].onclick) {
					//create a new span
					var s = document.createElement('span');
					//recreate the link
					var o = document.createElement('a');
						o.setAttribute('href', links[i].href);
						if(links[i].title != "") {
							o.setAttribute('title', links[i].title);
							} else {
							o.setAttribute('title', links[i].href);
							}
						o.setAttribute('class', 'nocrawl');
					//populate the o link with the text from the original link
						o.appendChild(links[i].firstChild);
						
					//create a new link
					var a = document.createElement('a');
						a.setAttribute('href', links[i].href);
						a.setAttribute('onclick', "window.open(this.href, 'newwin'); return false;");
						a.setAttribute('class', 'nocrawl newwin');
						a.setAttribute('title', 'Open this link in a New Window');
					//create a child of the link, the image
					var icon = document.createElement('img');
						icon.setAttribute('src', '/s/jp/i/new_win_icon.png');
						icon.setAttribute('alt', 'Open this link in a New Window');
		
					//compile the new span
					a.appendChild(icon);
					s.appendChild(o);
					s.appendChild(a);
		
					//replace original links
					links[i].parentNode.replaceChild(s, links[i]);
					
					}
						
			}
	}
}


// HEADLINE REPLACEMENT

function com_stewartspeak_replacement() {

/*
	Dynamic Heading Generator
    By Stewart Rosenberger
    http://www.stewartspeak.com/headings/

	This script searches through a web page for specific or general elements
	and replaces them with dynamically generated images, in conjunction with
	a server-side script.
*/

//replaceSelector("h2","/ir.php",true);
replaceSelector("h2 a","/ir.php",true);
replaceSelector(".art_title","/ir.php",true);
//replaceSelector("#headlines li a","/ir.php",true);


var testURL = "/i/x.png";

var doNotPrintImages = false;
var printerCSS = "/s/replacement-print.css";

var hideFlicker = true;
var hideFlickerCSS = "/s/replacement-screen.css";
var hideFlickerTimeout = 3000;




/* ---------------------------------------------------------------------------
    For basic usage, you should not need to edit anything below this comment.
    If you need to further customize this script's abilities, make sure
	you're familiar with Javascript. And grab a soda or something.
*/

var items;
var imageLoaded = false;
var documentLoaded = false;
var escapeText = (typeof(encodeURIComponent) != 'undefined') ? encodeURIComponent : function(text){ return escape(text).replace(/\+/g,'%2B'); } ;

function replaceSelector(selector,url,wordwrap)
{
	if(typeof items == "undefined")
		items = new Array();

	items[items.length] = {selector: selector, url: url, wordwrap: wordwrap};
}

if(hideFlicker)
{		
	document.write('<link id="hide-flicker" rel="stylesheet" media="screen" href="' + hideFlickerCSS + '" />');		
	window.flickerCheck = function()
	{
		if(!imageLoaded)
			setStyleSheetState('hide-flicker',false);
	};
	setTimeout('window.flickerCheck();',hideFlickerTimeout)
}

if(doNotPrintImages)
	document.write('<link id="print-text" rel="stylesheet" media="print" href="' + printerCSS + '" />');

var test = new Image();
test.onload = function() { imageLoaded = true; if(documentLoaded) replacement(); };
test.src = testURL + "?date=" + (new Date()).getTime();

addLoadHandler(function(){ documentLoaded = true; if(imageLoaded) replacement(); });


function documentLoad()
{
	documentLoaded = true;
	if(imageLoaded)
		replacement();
}

function rollover() {
	var x = this.parentNode;
	for(i=0; i<x.childNodes.length; i++) {
		if(x.childNodes[i].className == "replacement" && x.childNodes[i].nodeName == "IMG") {
			x.childNodes[i].src += ":hover";
			}
		}
	}
function rollout() {
	var regex = /\:hover/g;
	var x = this.parentNode;
	for(i=0; i<x.childNodes.length; i++) {
		if(x.childNodes[i].className == "replacement" && x.childNodes[i].nodeName == "IMG") {
			x.childNodes[i].src = x.childNodes[i].src.replace(regex,"");
			}
		}
	}
function replacement()
{
	for(var i=0;i<items.length;i++)
	{
		var elements = getElementsBySelector(items[i].selector);
		if(elements.length > 0) for(var j=0;j<elements.length;j++)
		{
			if(!elements[j])
				continue ;
		
			var text = extractText(elements[j]);
    		while(elements[j].hasChildNodes())
				elements[j].removeChild(elements[j].firstChild);

			var tokens = items[i].wordwrap ? text.split(' ') : [text] ;
			for(var k=0;k<tokens.length;k++)
			{
				var url = items[i].url + "?text="+escapeText(tokens[k]+' ')+"&selector="+escapeText(items[i].selector);
				var image = document.createElement("img");
				image.className = "replacement";
				image.alt = tokens[k] ;
				image.title = text ; //used to be elements[j] -jp
				if(elements[j].nodeName == "A") {
					image.onmouseover = rollover;
					image.onmouseout = rollout;
						var pic = new Image(); 
						pic.src = url+":hover";
					}
				image.src = url;
				elements[j].appendChild(image);
			}

			if(doNotPrintImages)
			{
				var span = document.createElement("span");
				span.style.textIndent = '-9999px';
				span.className = "print-text";
				span.appendChild(document.createTextNode(text));
				elements[j].appendChild(span);
			}
		}
	}

	if(hideFlicker)
		setStyleSheetState('hide-flicker',false);
}

function addLoadHandler(handler)
{
	if(window.addEventListener)
	{
		window.addEventListener("load",handler,false);
	}
	else if(window.attachEvent)
	{
		window.attachEvent("onload",handler);
	}
	else if(window.onload)
	{
		var oldHandler = window.onload;
		window.onload = function piggyback()
		{
			oldHandler();
			handler();
		};
	}
	else
	{
		window.onload = handler;
	}
}

function setStyleSheetState(id,enabled) 
{
	var sheet = document.getElementById(id);
	if(sheet)
		sheet.disabled = (!enabled);
}

function extractText(element)
{
	if(typeof element == "string")
		return element;
	else if(typeof element == "undefined")
		return element;

	var text = "";
	var kids = element.childNodes;
	for(var i=0;i<kids.length;i++)
	{
		if(kids[i].nodeType == 1)
		text += extractText(kids[i]);
		else if(kids[i].nodeType == 3)
		text += kids[i].nodeValue;
	}

	return text;
}

/*
	Finds elements on page that match a given CSS selector rule. Some
	complicated rules are not compatible.
	Based on Simon Willison's excellent "getElementsBySelector" function.
	Original code (with comments and description):
		http://simon.incutio.com/archive/2003/03/25/getElementsBySelector
*/
function getElementsBySelector(selector)
{
	var tokens = selector.split(' ');
	var currentContext = new Array(document);
	for(var i=0;i<tokens.length;i++)
	{
		token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');
		if(token.indexOf('#') > -1)
		{
			var bits = token.split('#');
			var tagName = bits[0];
			var id = bits[1];
			var element = document.getElementById(id);
			if(tagName && element.nodeName.toLowerCase() != tagName)
				return new Array();
			currentContext = new Array(element);
			continue;
		}

		if(token.indexOf('.') > -1)
		{
			var bits = token.split('.');
			var tagName = bits[0];
			var className = bits[1];
			if(!tagName)
				tagName = '*';

			var found = new Array;
			var foundCount = 0;
			for(var h=0;h<currentContext.length;h++)
			{
				var elements;
				if(tagName == '*')
					elements = currentContext[h].all ? currentContext[h].all : currentContext[h].getElementsByTagName('*');
				else
					elements = currentContext[h].getElementsByTagName(tagName);

				for(var j=0;j<elements.length;j++)
					found[foundCount++] = elements[j];
			}

			currentContext = new Array;
			var currentContextIndex = 0;
			for(var k=0;k<found.length;k++)
			{
				if(found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b')))
					currentContext[currentContextIndex++] = found[k];
			}

			continue;
	    }

		if(token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/))
		{
			var tagName = RegExp.$1;
			var attrName = RegExp.$2;
			var attrOperator = RegExp.$3;
			var attrValue = RegExp.$4;
			if(!tagName)
				tagName = '*';

			var found = new Array;
			var foundCount = 0;
			for(var h=0;h<currentContext.length;h++)
			{
				var elements;
	        	if(tagName == '*')
					elements = currentContext[h].all ? currentContext[h].all : currentContext[h].getElementsByTagName('*');
				else
					elements = currentContext[h].getElementsByTagName(tagName);

				for(var j=0;j<elements.length;j++)
					found[foundCount++] = elements[j];
			}

			currentContext = new Array;
			var currentContextIndex = 0;
			var checkFunction;
			switch(attrOperator)
			{
				case '=':
					checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
					break;
				case '~':
					checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
					break;
				case '|':
					checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
					break;
				case '^':
					checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
					break;
				case '$':
					checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
					break;
				case '*':
					checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
					break;
				default :
					checkFunction = function(e) { return e.getAttribute(attrName); };
			}

			currentContext = new Array;
			var currentContextIndex = 0;
			for(var k=0;k<found.length;k++)
			{
				if(checkFunction(found[k]))
					currentContext[currentContextIndex++] = found[k];
			}

			continue;
		}

		tagName = token;
		var found = new Array;
		var foundCount = 0;
		for(var h=0;h<currentContext.length;h++)
		{
			if(!currentContext[h]) continue; // line added to avoid errors if a replacement selector isn't found -jp
			var elements = currentContext[h].getElementsByTagName(tagName);
			for(var j=0;j<elements.length; j++)
				found[foundCount++] = elements[j];
		}

		currentContext = found;
	}

	return currentContext;
}


}// end of scope, execute code
if(document.createElement && document.getElementsByTagName && !navigator.userAgent.match(/opera\/?6/i))
	com_stewartspeak_replacement();

//  THUMBNAIL ROLL OVERS

var thumbs;
function setroll() {
	thumbs = document.getElementById("thumbnails");
	var ta = thumbs.getElementsByTagName("a");
		for(i=0; i<ta.length; i++) {
			ta[i].onmouseover = bright;
			ta[i].onmouseout = dim;
			setOpacity(ta[i],20);
			} 
	}

function dim() {
	setOpacity(this, 20);
	}
function bright() {
	setOpacity(this, 100);
	}

function setOpacity(obj,opacity) {
	opacity = (opacity == 100)?99.999:opacity; // IE/Win
	obj.style.filter = "alpha(opacity:"+opacity+")"; // Safari<1.2, Konqueror
	obj.style.KHTMLOpacity = opacity/100; // Older Mozilla and Firefox
	obj.style.MozOpacity = opacity/100; // Safari 1.2, newer Firefox and Mozilla, CSS3
	obj.style.opacity = opacity/100; 
	//alert(opacity/100 + " on: " + obj.innerHTML);
	}

// VALIDATE EMAIL
	addEvent(window, 'load', validate);
	var fade = true; //set this to false to disable the fade effect, true to enable it.
	var emailInput = "replyto"; // set this to the id attribute of the input element that accepts an email address.
	var errorText = "Error: This email address appears to be invalid, please correct it.";
	var emptyText = "Error: Please enter your e-mail address.";
	var re = /^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/;

	function validate() {
		var email = document.getElementById("replyto");
		if(!email) {
			var email = document.getElementById("c_email");
			}
		if(!email) {
			return
			}
		email.onblur = validateEmail;
		}
	function validateEmail() {
		var v = this.value;
		var elid = this.id.toString();
		if(!re.test(v)) {
			showError(this);
			} else {
			if(errorExists(this)) {
				document.getElementById("scriptgenerror" + elid).innerHTML = "";
				errorStyle(this);
				}
			}
		}
	function errorExists(el) {
		var elid = el.id.toString();
		if(document.getElementById("scriptgenerror" + elid) && document.getElementById("scriptgenerror" + elid).innerHTML !== "" ) {
			flashError("scriptgenerror" + elid);
			return true;
			}
		}
	function errorStyle(el) {
		if(el.className == "highlighted") {
			el.className = "";
			} else {
			el.className = "highlighted";
			}
		}
	function showError(el) {
		var elid = el.id.toString();
		if (el.value == ""){
			var theError = emptyText;
			} else {
			var theError = errorText;
			}
		if(errorExists(el)) { //first check for error messages
			document.getElementById("scriptgenerror" + elid).innerHTML = theError;
			} else { //create new error
			var emessage = document.createTextNode(theError);
			var eel = document.createElement("strong");
			eel.className = "validateerror";
			eel.id = "scriptgenerror" + elid;
			eel.appendChild(emessage);
			el.parentNode.appendChild(eel);
			if(fade == true) { 
				eel.style.visibility = "hidden";
				flashError(eel.id);
				}
			errorStyle(el);
			}
		}
		
	var bgi = 0;
	function flashError(id) {
		if (fade != true) return;
		var el = document.getElementById(id);
		
		if (el.style.visibility == "hidden") {
			el.style.visibility = "visible";
			}

		if(bgi < 255) {
			el.style.backgroundColor = "rgb(255,255," + bgi + ")";
			bgi+=10;
			setTimeout("flashError('" + id + "')", 30);
			} else {
			el.style.backgroundColor = "rgb(255,255,255)";
			bgi = 0;
			}
		}



// LIGHTBOX

/*
	Lightbox JS: Fullsize Image Overlays 
	by Lokesh Dhakar - http://www.huddletogether.com

	For more information on this script, visit:
	http://huddletogether.com/projects/lightbox/
*/

var loadingImage = '/i/logo.gif';		
var closeButton = '/i/x.png';		





//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
//
function getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}



//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){
	
	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){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

//
// pause(numberMillis)
// Pauses code execution for specified time. Uses busy code, not good.
// Code from http://www.faqts.com/knowledge_base/view.phtml/aid/1602
//
function pause(numberMillis) {
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true) {
		now = new Date();
		if (now.getTime() > exitTime)
			return;
	}
}





//
// showLightbox()
// Preloads images. Pleaces new image in lightbox then centers and displays.
//
function showLightbox(objLink)
{
	// prep objects
	var objOverlay = document.getElementById('overlay');
	var objLightbox = document.getElementById('lightbox');
	var objCaption = document.getElementById('lightboxCaption');
	var objImage = document.getElementById('lightboxImage');
	var objLoadingImage = document.getElementById('loadingImage');
	
	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();

	// center loadingImage if it exists
	if (objLoadingImage) {
		objLoadingImage.style.top = (arrayPageScroll[1] + ((arrayPageSize[3] - 35 - objLoadingImage.height) / 2) + 'px');
		objLoadingImage.style.left = (((arrayPageSize[0] - 20 - objLoadingImage.width) / 2) + 'px');
		objLoadingImage.style.display = 'block';
	}

	// set height of Overlay to take up whole page and show
	objOverlay.style.height = (arrayPageSize[1] + 'px');
	objOverlay.style.display = 'block';

	// preload image
	imgPreload = new Image();

	imgPreload.onload=function(){
		objImage.src = objLink.href;

		// center lightbox and make sure that the top and left values are not negative
		// and the image placed outside the viewport
		var lightboxTop = arrayPageScroll[1] + ((arrayPageSize[3] - 35 - imgPreload.height) / 2);
		var lightboxLeft = ((arrayPageSize[0] - 20 - imgPreload.width) / 2);
		
		objLightbox.style.top = (lightboxTop < 0) ? "0px" : lightboxTop + "px";
		objLightbox.style.left = (lightboxLeft < 0) ? "0px" : lightboxLeft + "px";


		
			objCaption.style.display = 'block';
			objCaption.style.width = imgPreload.width + 'px';
			objCaption.innerHTML = "click anywhere to close";
		
		// A small pause between the image loading and displaying is required with IE,
		// this prevents the previous image displaying for a short burst causing flicker.
		if (navigator.appVersion.indexOf("MSIE")!=-1){
			pause(250);
		} 

		objLoadingImage.style.display = 'none';
		objLightbox.style.display = 'block';

		// After image is loaded, update the overlay height as the new image might have
		// increased the overall page height.
		arrayPageSize = getPageSize();
		objOverlay.style.height = (arrayPageSize[1] + 'px');

		return false;
	}

	imgPreload.src = objLink.href;
	
}





//
// hideLightbox()
//
function hideLightbox()
{
	// get objects
	objOverlay = document.getElementById('overlay');
	objLightbox = document.getElementById('lightbox');

	// hide lightbox and overlay
	objOverlay.style.display = 'none';
	objLightbox.style.display = 'none';
}




//
// initLightbox()
// Function runs on window load, going through link tags looking for rel="lightbox".
// These links receive onclick events that enable the lightbox display for their targets.
// The function also inserts html markup at the top of the page which will be used as a
// container for the overlay pattern and the inline image.
//
function initLightbox()
{
	
	if (!document.getElementsByTagName){ return; }
	var anchors = document.getElementsByTagName("a");

	// loop through all anchor tags
	for (var i=0; i<anchors.length; i++){
		var anchor = anchors[i];

		if (anchor.getAttribute("href") && (anchor.getAttribute("rel") == "lightbox")){
			anchor.onclick = function () {showLightbox(this); return false;}
			anchor.onkeypress = function () {showLightbox(this); return false;}
		}
	}

	// the rest of this code inserts html at the top of the page that looks like this:
	//
	// <div id="overlay">
	//		<a href="#" onclick="hideLightbox(); return false;"><img id="loadingImage" /></a>
	//	</div>
	// <div id="lightbox">
	//		<a href="#" onclick="hideLightbox(); return false;" title="Click anywhere to close image">
	//			<img id="closeButton" />		
	//			<img id="lightboxImage" />
	//		</a>
	//		<div id="lightboxCaption"></div>
	// </div>
	
	var objBody = document.getElementsByTagName("body").item(0);
	
	// create overlay div and hardcode some functional styles (aesthetic styles are in CSS file)
	var objOverlay = document.createElement("div");
	objOverlay.setAttribute('id','overlay');
	objOverlay.onclick = function () {hideLightbox(); return false;}
	objOverlay.onkeypress = function () {hideLightbox(); return false;}
	objOverlay.style.display = 'none';
	objOverlay.style.position = 'absolute';
	objOverlay.style.top = '0';
	objOverlay.style.left = '0';
	objOverlay.style.zIndex = '90';
 	objOverlay.style.width = '100%';
	objBody.insertBefore(objOverlay, objBody.firstChild);
	
	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();

	// preload and create loader image
	var imgPreloader = new Image();
	
	// if loader image found, create link to hide lightbox and create loadingimage
	imgPreloader.onload=function(){

		var objLoadingImageLink = document.createElement("a");
		objLoadingImageLink.setAttribute('href','#');
		objLoadingImageLink.onclick = function () {hideLightbox(); return false;}
		objOverlay.appendChild(objLoadingImageLink);
		
		var objLoadingImage = document.createElement("img");
		objLoadingImage.src = loadingImage;
		objLoadingImage.setAttribute('id','loadingImage');
		objLoadingImage.style.position = 'absolute';
		objLoadingImage.style.zIndex = '150';
		objLoadingImageLink.appendChild(objLoadingImage);

		imgPreloader.onload=function(){};	//	clear onLoad, as IE will flip out w/animated gifs

		return false;
	}

	imgPreloader.src = loadingImage;

	// create lightbox div, same note about styles as above
	var objLightbox = document.createElement("div");
	objLightbox.setAttribute('id','lightbox');
	objLightbox.style.display = 'none';
	objLightbox.style.position = 'absolute';
	objLightbox.style.zIndex = '100';	
	objBody.insertBefore(objLightbox, objOverlay.nextSibling);
	
	// create link
	var objLink = document.createElement("a");
	objLink.setAttribute('href','#');
	objLink.setAttribute('title','Click to close');
	objLink.onclick = function () {hideLightbox(); return false;}
	objLightbox.appendChild(objLink);

	// preload and create close button image
	var imgPreloadCloseButton = new Image();

	// if close button image found, 
	imgPreloadCloseButton.onload=function(){

		var objCloseButton = document.createElement("img");
		objCloseButton.src = closeButton;
		objCloseButton.setAttribute('id','closeButton');
		objCloseButton.style.position = 'absolute';
		objCloseButton.style.zIndex = '200';
		objCloseButton.style.top = '5px';		
		objCloseButton.style.right = '5px';		
		objLink.appendChild(objCloseButton);

		return false;
	}

	imgPreloadCloseButton.src = closeButton;

	// create image
	var objImage = document.createElement("img");
	objImage.setAttribute('id','lightboxImage');
	objLink.appendChild(objImage);
	
	// create caption
	var objCaption = document.createElement("div");
	objCaption.setAttribute('id','lightboxCaption');
	objCaption.style.display = 'none';
	objLightbox.appendChild(objCaption);

}


	addEvent(window, 'load', initLightbox);