/*
debug()
getSelfURL()
addEvent()
fireEvt()
format_dollar
show_hide
imgSwap
clip_show
ec
ec_proto
openRemote
*/

var placeHolderSupport = typeof placeHolderSuport != 'undefined'
	? placeHolderSupport
	: ( 'placeholder' in document.createElement('input') );

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

if ( typeof window.console == 'undefined' )
{
	window.console = {
	}
}
if ( window.opera && typeof window.console.log == 'undefined' )
	window.console.log = opera.postError;
else if ( typeof window.console.log == 'undefined' )
{
	window.console.log = function()
	{
		if ( debugOutput )
		{
			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
				var dbCont	= dbDoc.getElementById('debug');// debug container
				var newNode	= dbDoc.createElement('div');
				/*
				var args = Array.prototype.slice.call(arguments);
				for ( i=0; i<args.length; i++ )
					if ( args[i].inspect )
						args[i] = args[i].inspect().escapeHTML();
				var argString = args.join(', ');
				*/
				var argString = '';
				for ( var i = 0; i<arguments.length; i++ )
					argString += arguments[i] + ( i+1 != arguments.length ? ', ' : '' );
				newNode.innerHTML = argString;
				dbCont.appendChild(newNode); // top-to-bottom
				//dbCont.insertBefore(newNode,dbCont.firstChild); // bottom-to-top
			}
			catch(e)
			{
			}
		}
	}
}
if ( typeof window.console.debug == 'undefined' )
	window.console.debug = window.console.log;

function debug()
{
	if ( typeof window.console.debug.apply != 'undefined' )
		window.console.debug.apply(window.console,arguments);
	else
	{
		var args = Array.prototype.slice.call(arguments);
		window.console.debug(args.join(', '));
	}
}

function getSelfURL(params)
{
	//console.debug('getSelfURL');
	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);
	});
	//console.debug('params_current',Object.toJSON(params_current));
	var params = params_current.merge( params );
	params.each( function(pair){
		if ( pair.value === null )
			params.unset(pair.key);
	});
	//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 addEvent(obj, evType, fn)
{
	if ( typeof obj == 'string' )
		obj = document.getElementById(obj);
	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;
	}
}

function fireEvt(node,evt) {
	//console.debug('fireEvt');
	if ( document.createEvent && node.dispatchEvent ) {
		//console.debug('dispatchEvent');
		var doc_event = document.createEvent("HTMLEvents");
		doc_event.initEvent(evt, true, true);
		node.dispatchEvent(doc_event); // for DOM-compliant browsers
	}
	else if ( node.fireEvent ) {
		//console.debug('fireEvent');
		node.fireEvent('on'+evt); // for IE
	}
}

function format_dollar(num)
{
	num = num.toString().replace(/[^\d\.-]/g,'');
	positive = (num == Math.abs(num));
	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 show_hide(node,show_or_hide)
{
	var node = $(node);
	if ( typeof show_or_hide == 'boolean' )
		show_or_hide = show_or_hide ? 'show' : 'hide';
	if ( typeof Effect != 'undefined' ) {
		if ( show_or_hide == 'hide' )
			Effect.BlindUp(node,{ duration:.3 });
		else if ( !node.visible() )
			Effect.BlindDown(node,{ duration:.3 });
	}
	else {
		if ( show_or_hide == 'hide' )
			node.hide();
		else
			node.show();
	}
	if ( show_or_hide == 'hide' ) {
		node.select('[required]').each( function(node) {
			if ( node.form ) {
				var name = node.readAttribute('name');
				var form_id = node.up('form').readAttribute('id');
				set_required(form_id,name,false);
			}
		});
		node.select('input').each( function(node) {
			if ( ph = node.getAttribute('placeholder') ) {
				if ( !placeHolderSupport ) {
					classNameAdd(node,'placeholder');
					node.value = ph;
				}
			}
			else if ( node.getAttribute('type') == 'text' && node.value !== '')
				node.clear();
		});
	}
}

// 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)
{
	console.debug('clip_show',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)
{
	var container, children, a_div, b_div, img_tag, image;
	var img_e_src = '/images/tiny/b_plus.png';
	var img_c_src = '/images/tiny/b_minus.png';
	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
	{
		children = container.children;
		//debug('children',children);
		a_div = children[0];
		b_div = children[children.length-1];
	}
	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 = {};
	//console.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, opts_passed)
{
	if ( typeof opts_passed == 'number' )
	{
		// previously 3rd & 4th params were width & height
		opts_passed = {
			width	: openRemote.arguments[2],
			height	: openRemote.arguments[3]
		}
	}
	var opts = {
		dependent	: 1,
		resizeable	: 0,
		status		: 0,
		menubar		: 0,
		scrollbars	: 1,
		width		: 200,
		height		: 260
	};
	var opt_str = '';
	var val = null;
	for ( k in opts_passed )
	{
		val = opts_passed[k];
		if ( val === true || val === 'yes' )
			val = 1;
		else if ( val === false || val === 'no' )
			val = 0;
		else if ( val === null )
			val = 0;
		opts[k] = val;
	}
	for ( k in opts )
	{
		opt_str += k+'='+opts[k]+',';
	}
	opt_str = opt_str.substr(0,opt_str.length-1);
	if ( !window.name )
		window.name = "main";
	var popupWin = window.open(url, name, opt_str);
	if ( popupWin != null )
		popupWin.window.focus()
	return popupWin;
}

//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" )
{
	console.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(){
	console.debug('functions.js: window loaded');
	if ( debugPrettied )
		return;
	if ( typeof Prototype == 'object' && $$('.debug') )
	{
		console.debug('got prototype.js');
		debugPrettied = true;
		$$('.debug').each( function(node) {
			var node_expand_all = new Element('a',{'href':'javascript:void(0);'}).observe('click',function(evt) {
				node.select('.indent_header').each( function(node_trigger) {
					if ( !node_trigger.next().visible() )
						debug_toggle(node_trigger);
				});
			});
			node.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);
				}
			});
		}
	}
});

