try
{
	var debugOutput = window.location.search.indexOf('debug') >= 0;
}
catch(e) { }

function debug()
{
	if ( debugOutput )
	{
		if ( window.opera && !window.console )
			opera.postError(arguments);
		else if ( typeof console != 'undefined' && typeof console.log != 'undefined' )
		{
			console.debug.apply(console,arguments);
			return true;
		}
		else
		{
			try
			{
				if ( typeof dbWindow == 'undefined' )
				{
					dbWindow = openRemote('','dbWindow',300,500);
					dbDoc = dbWindow.document
					style = ''
						+'DIV { font-size:8pt; font-face:Courier; }'+"\n"
						+'BODY { height:100%; margin:0px; padding:0px;  }'+"\n"
						+'#debug { margin:4px; }'+"\n"
						+'#clear{ position:absolute; bottom:0px; width:100%; border-top:#000 solid 1px; background-color:#EEE; }'+"\n"
						+'';
					dbDoc.open();
					// adding style the DOM way is a pain.. just go old school
					dbDoc.write(''
						+'<html><head><title>Debug Output</title>'
						+'<style>'+style+'</style>'
						+'</head><body>'
						+'<div id="debug"></div>'
						+'<div id="clear"><input type="button" value="clear" onclick="document.getElementById(\'debug\').innerHTML=\'\';" /></div>'
						+'</body></html>');
					dbDoc.close();
				}
				dbDoc	= dbWindow.document;		// debug window
				dbCont	= dbDoc.getElementById('debug');// debug container
				var newNode	= dbDoc.createElement('div');
				var argString = '';
				for ( var i = 0; i<debug.arguments.length; i++ )
					argString += debug.arguments[i] + ( i+1 != debug.arguments.length ? ', ' : '' );
				newNode.innerHTML = argString;
				//dbCont.appendChild(newNode); // top-to-bottom
				dbCont.insertBefore(newNode,dbCont.firstChild); // bottom-to-top
			}
			catch(e)
			{
			}
		}
	}
	return null;
}

function getSelfURL(params)
{
	params = $H(params);
	var loc = document.location;
	var url = loc.protocol+'//'+loc.host+loc.pathname;
	var params_current = new Hash;
	$H(loc.search.toQueryParams('&')).each( function(pair) {
		if ( ['page','debug'].indexOf(pair.key) >= 0 )
			params_current.set(pair.key,pair.value);
	});
	//params_current.unset('debug');
	var params = params_current.merge( params );
	//debug('params',params.inspect());
	var QS = params.toQueryString();
	QS = QS.replace(/%5B/g,'[');
	QS = QS.replace(/%5D/g,']');
	QS = QS.replace(/%2F/g,'/');
	QS = QS.replace(/%2C/g,',');
	url += QS
		? '?'+QS
		: '';
	return url;
}

function format_dollar(num)
{
	num = num.toString().replace(/[^\d\.]/g,'');
	positive = (num == Math.abs(num));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	if(cents<10)
		cents = "0" + cents;
	num = Math.floor(num/100).toString();
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+","+num.substring(num.length-(4*i+3));
	num = ( ((positive)?'':'-') + '$' + num + '.' + cents);
	return num;
}

function addEvent(obj, evType, fn)
{
	if (obj.addEventListener)
	{
		obj.addEventListener(evType, fn, false);
		return true;
	}
	else if (obj.attachEvent)
	{
		var r = obj.attachEvent('on'+evType, fn);
		return r;
	}
	else
	{
		return false;
	}
}

// image swapping event handling
// http://www.oreillynet.com/pub/a/javascript/2003/07/01/bonusrecipe.html
function imgSwap(obj_or_event,what)
{
	if ( navigator.appName.indexOf("WebTV")>=0 ) return true;
	if ( obj_or_event.type )
	{
		evt = obj_or_event;
		obj = (evt.target) ? evt.target : evt.srcElement;
	}
	else
	{
		obj = obj_or_event;
		evt = new Array();
		evt.type = (what) ? what : 'mouseout';
	}
	var imgClass, coords;
	if ( obj.map )
	{
		lastmap = obj;
		mapName = obj.map;
	}
	else
	{
		mapName = obj.parentNode.name;	// get map element name
		coords = obj.coords.split(",");	// convert coords to clip
		lastmap = {
			'map' : mapName,
			'l' : Number(coords[0]),
			't' : Number(coords[1]),
			'r' : Number(coords[2]),
			'b' : Number(coords[3])
		};
	}
	var imgStyle;
	switch (evt.type)
	{
		case 'mousedown' :
			clip_show(mapName+'Down',lastmap.l,lastmap.t,lastmap.r,lastmap.b);
		break;
		case 'mouseout' :
		case 'blur' :
			if ( document.getElementById(mapName + 'Over') )
				document.getElementById(mapName + 'Over').style.visibility = 'hidden';
			if ( document.getElementById(mapName + 'Down') )
				document.getElementById(mapName + 'Down').style.visibility = 'hidden';
		break;
		case 'mouseover' :
		case 'focus' :
			clip_show(mapName+'Over',lastmap.l,lastmap.t,lastmap.r,lastmap.b);
		break;
		case 'mouseup' :
			//document.getElementById(mapName + 'Down').style.visibility = 'hidden';
			// guarantee click in IE
			if (evt.click)
				evt.click();
		break;
	}
	evt.cancelBubble = true;
	return false;
}

// coords are same order as img map
function clip_show(objId,clLeft,clTop,clRight,clBottom)
{
	debug('objId',objId);
	if ( navigator.appName.indexOf("WebTV")>=0 ) return true;
	var clipVal = "rect(" +
		(clTop || 0) + "px " +
		(clRight || 0) + "px " +
		(clBottom || 0) + "px " +
		(clLeft || 0) + "px)";
	var divStyle = document.getElementById(objId).style;
	divStyle.clip = clipVal;
	divStyle.visibility = 'visible';
	return true;
}

/*
expand/collapse: shows/hides content
example:  ec(this,e)
2nd param is optional
*/
function ec(evt,cmd)
{
	if ( typeof evt == 'object' )
		container = ( evt.getAttribute && ( evt.getAttribute('class') == 'container' || evt.getAttribute('className') == 'container' ) )
			? evt
			: evt.parentNode;
	else
		container = document.getElementById(evt);
	if ( container.tagName == 'DL' && typeof evt.next == 'function' )
	{
		a_div = evt;
		b_div = evt.next();
	}
	else
	{
		a_div = container.getElementsByTagName('div')[0];
		b_div = container.getElementsByTagName('div')[1];
	}
	img_e_src = '/images/tiny/b_plus.png';
	img_c_src = '/images/tiny/b_minus.png';
	if ( b_div.style.display == '' )
		b_div.style.display = 'none';
	if ( cmd == null )
	{
		cmd = ( b_div.style.display == 'block' )
			? 'c'
			: 'e';
	}
	img_tag = a_div.getElementsByTagName('img')[0];
	image = ( typeof img_tag != 'undefined' && ( img_tag.src.indexOf(img_e_src)>=0 || img_tag.src.indexOf(img_c_src)>=0 ) );	// boolean
	if ( cmd == 'c' )
	{
		b_div.style.display = 'none';
		if ( image )
		{
			a_div.setAttribute('title','Expand');
			img_tag.src = img_e_src;
		}
	}
	else if ( cmd == 'e' )
	{
		b_div.style.display = 'block';
		if ( image )
		{
			a_div.setAttribute('title','Collapse');
			img_tag.src = img_c_src;
		}
	}
	return b_div.style.display;
}

function ec_proto(trigger_node,options)
{
	content_node = trigger_node.next();
	if ( typeof options == 'undefined' )
		options = {};
	//debug('content_node',content_node);
	var vis = content_node.visible();
	if ( typeof Effect == 'object' )
	{
		// use scriptaculous
		if ( vis )
		{
			content_node.setStyle({'position':'relative','overflow':'hidden'});
			new Effect.BlindUp(content_node, {
				duration:.3,
				afterFinish: options.afterCollapse
			});
		}
		else
		{
			new Effect.BlindDown(content_node, {
				duration:.3,
				afterFinish: function(obj){
					content_node.setStyle({'position':'static'});
					options.afterExpand(obj);
				}
			});
		}
	}
	else
	{
		content_node.toggle();
		if ( vis && options.afterCollapse )
			options.afterCollapse({element:content_node});
		else if ( !vis && options.afterExpand )
			options.afterExpand({element:content_node});
	}
	return;
}

//var popupWin;
function openRemote(url, name, w, h)
{
	if (typeof w == 'undefined')
	{
		w = 200;
		h = 260;
	}
	if ( !window.name )
		window.name = "main";
	popupWin = window.open(url, name, 'dependent,resizable=yes,status=0,menubar=0,width='+w+',height='+h);
	if ( popupWin != null )
		popupWin.window.focus()
	return popupWin;
}

/* Image Viewer
*/
function pic(source, w, h, caption)
{
	if ( typeof cbWindow != 'undefined' )
		cbWindow.close();
	cbWindow = openRemote('','pic',w,h);
	margin = ( typeof caption != 'undefined' )
		? 6
		: 0;
	margins = ' leftmargin='+margin+' topmargin='+margin+' marginwidth='+margin+' marginheight='+margin;
	with(cbWindow.document)
	{
		open();
		write('<html><head><title>Photo</title></head>');
		write('<body bgcolor="#FFFFFF"'+margins+'><form>');
		write('<img src="'+source+'" alt="" /><br>');
		if( typeof caption != 'undefined' )
			write('<font face="Verdana, Arial,Helvetica" size="-1" style="font-size:9pt;">'+caption+'</font>')
		write("</form></body></html>");
		close();
	}
	return false;
}

//http://webbugtrack.blogspot.com/2007/08/bug-152-getelementbyid-returns.html
//use browser sniffing to determine if IE or Opera (ugly, but required)
isOpera = ( typeof(window.opera) != 'undefined' );
isIE	= ( !isOpera && /MSIE (\d+\.\d+);/i.test(navigator.userAgent) );
//fix both IE and Opera (adjust when they implement this method properly)
if( ( isOpera || isIE ) && typeof document.nativeGetElementById == "undefined" )
{
	debug('redefining getElementById');
	document.nativeGetElementById = document.getElementById;
	//redefine it!
	document.getElementById = function(id)
	{
		var elem = document.nativeGetElementById(id);
		if(elem)
		{
			//verify it is a valid match!
			if(elem.attributes['id'] && elem.attributes['id'].value == id)
			{
				//valid match!
				return elem;
			}
			else
			{
				//not a valid match!
				//the non-standard, document.all array has keys for all name'd, and id'd elements
				//start at one, because we know the first match, is wrong!
				for(var i=1;i<document.all[id].length;i++)
				{
					if(document.all[id][i].attributes['id'] && document.all[id][i].attributes['id'].value == id)
						return document.all[id][i];
				}
			}
		}
		return null;
	};
}

var debugPrettied = false;
addEvent(window,'load',function(){
	debug('functions.js: window loaded');
	if ( debugPrettied )
		return;
	if ( typeof Prototype == 'object' && $('debug') )
	{
		debug('got prototype.js');
		debugPrettied = true;
		var node_expand_all = new Element('a',{'href':'javascript:void(0);'}).observe('click',function(evt)
		{
			$$('#debug .indent_header').each( function(node_trigger)
			{
				if ( !node_trigger.next().visible() )
					debug_toggle(node_trigger);
			});
		});
		$('debug').insert({'top': node_expand_all});
		node_expand_all.update('Expand All').insert({'after':'<br />'});
		var img_expand		= '<img width="9" height="9" src="/images/tiny/b_plus.png" alt="expand" />';
		var img_collapse	= '<img width="9" height="9" src="/images/tiny/b_minus.png" alt="collapse" />';
		$$('#debug .indent_header').each( function(node_trigger)
		{
			var node_content = node_trigger.next();
			if ( node_content.empty() )
				return;	// continue
			var a_node = new Element('A', { 'href':'javascript:void(0);' }).update(node_trigger.innerHTML);
			a_node.setStyle({'color':node_trigger.getStyle('color')});	// ie doesn't support inherit
			if ( node_content.hasClassName('expanded') || node_content.down('.error, .warn, .indent.expanded') )
			{
				a_node.insert({top:img_collapse+' '});
			}
			else
			{
				a_node.insert({top:img_expand+' '});
				node_content.setStyle({'display':'none'});	//.addClassName('expand_content');
			}
			a_node.observe('click',function(evt) {
				debug_toggle(node_trigger);
			});
			node_trigger.update(a_node);
		});
		function debug_toggle(node_trigger)
		{
			ec_proto(node_trigger,{
				afterExpand: function(obj) {
					node_trigger = obj.element.previous();
					node_trigger.select('img')[0].replace(img_collapse);
				},
				afterCollapse: function(obj) {
					node_trigger = obj.element.previous();
					node_trigger.select('img')[0].replace(img_expand);
				}
			});
		}
	}
});
