// fix console error on IE
if(typeof(console) != "object") {var console = new Object(); console.log = function() {} };

function params(qp) { try{r=unescape(location.search.match(new RegExp(qp+"=+([^&]*)"))[1]);}catch(e){r='';} return r; }		
var msie = navigator.userAgent.toLowerCase().indexOf('msie') > 0;
//$D = function (str) { if (!msie) dump(getTabs() + str + '\n'); }
$D = function (str) { 
	if (is_safari) { window.console.log(str); return; }
	if (!msie) dump(getTabs() + str + '\n');
	console.log(str);
}

clear_debug = function()
{
	for (i = 0; i < 15; i++)
		$D('');
	$D('---------------------------------------------');
}

check_len = function checkLimit(wField, wLimit) { 
			$D('check len called');
     var StrLen = wField.value.length; 
     if (StrLen > wLimit) { 
          var msgText = wField.value; 
          var newText = msgText.substr(0, wLimit); 
          StrLen = wLimit; 
          wField.value = newText;
          alert(sprintf("The length of the text entered is more than the amount allowed, the following\n\n---------------\n%s\n---------------\nwas removed from the end of the text.", msgText.replace(newText, "")));
          return true;
     } 
		 return false;
} 
max_chars = function (obj, maxchars)
{
	//grab the txtbox
	var txtbox = $(obj);
	if (!txtbox) return;

	
	//add the label below the object in question
	var label = document.createElement('DIV');
	label.ID = obj + '_max_char_label';
	txtbox.parentNode.appendChild(label);
	
	var generate_msg = function () { 
		if (!txtbox) return;
		var left = (maxchars - txtbox.value.length);
		left = sprintf('<span style="color:%s;">%s</span>', (left > 0) ? "green;" : "red;font-weight:bold", left);
		return sprintf("Max %s characters, you have %s left", maxchars, left); 
	}
		
	
	//spit out the initial message.
	var str = generate_msg();
	label.innerHTML = str;
	
		
	$D('adding check_len hook');
	txtbox.onblur = function() { 
		if (check_len(txtbox, maxchars) && typeof(generate_msg) != "undefined")
		{
			var str = generate_msg();
			label.innerHTML = str;	
		}
	};
	
	addOnSubmitCheck(txtbox, function() { check_len(txtbox, maxchars);return true; });
	
	//track keypresses
	txtbox.onkeyup = function() { 
	var str = generate_msg();
	label.innerHTML = str;	
	};
}

addOnSubmitCheck = function(theForm, func)
{
	if (theForm.onsubmit)
	{
		var oldfunc = theForm.onsubmit;
		$D('Previous onSubmit existed hooking before...');
		theForm.onsubmit = function() { return (func() && oldfunc()); }
	}
	else
	{
	$D('hooking into onSubmit...');
	theForm.onSubmit = func;
	}
}

toggle_display = function(obj) { obj.style.display = ( obj.style.display == "block") ? "none" : "block"; }

findNextElement = function(obj, element)
{
	var parent = obj.parentNode;
	if (!parent) { $D('error travesing tree..bailing'); return; }
	var findNextDiv;
	for (var curObj = parent.firstChild; curObj != null; curObj = curObj.nextSibling)
	{
		if (curObj == obj) {findNextDiv = true; continue; }
		if (!findNextDiv) continue;
		if (curObj.nodeType != 1) continue;
		
		$D('Current element ' + curObj.nodeName.toLowerCase() + " " + typeof(curObj)	);
		if (typeof(curObj.nodeName) != 'undefined' && curObj.nodeName.toLowerCase() == element)
				return curObj;		
	}
}

var tab = "\t";
var curTab = 0;
getTabs = function() { 
	var tabs=""; 
	for (var i = 0; i < curTab; i++) 
		tabs += tab; 
	return tabs;
}

findElements = function(obj, element, filter, showDebug)
{
	var elements = [];
	curTab++;
	//for (var i = 0; i < obj.childNodes.length; i++)
	for (var curObj = obj.firstChild; curObj != null; curObj = curObj.nextSibling)
	{
		//var curObj = obj.childNodes[i];
		var name = curObj.nodeName ? curObj.nodeName.toLowerCase() : 'unknown';
		if (curObj.nodeType != 1)
		{
			if (showDebug) $D('Skipping ' + name);
			continue;
		}
		
		if (showDebug) $D('Checking ' + name);
		if (name == element && (!filter || filter(curObj)))
		{
				if (showDebug) $D('Found element pushing into array');
				elements.push(curObj);
		}
		
		if (curObj.childNodes && curObj.childNodes.length > 0)
		{
			if (showDebug) $D(sprintf('Stepping inside %s children', name));
			elements = elements.concat(findElements(curObj, element, filter, showDebug));
			if (showDebug) $D('Leaving children of ' + name);
		}
		
	}
	curTab--;
	return elements;
}
dumpObject = function (obj)
{
	$D(sprintf('Dumping object (%s)------------------------------', typeof(obj) ));
	for (i in obj)
	{
			$D(sprintf("Property (%s) %s = %s", typeof(obj[i]), i, (typeof(obj[i]) == 'function' ? '{function}' : obj[i]) ));
	}
	$D('End Dump');
}

GoSearch = function(obj, is_press_room) {
//	var input = obj.parentNode.previousSibling.previousSibling.firstChild;

	var input = obj.form.txt_search;
	var term = escape(input.value).replace(/^\s*|\s*$/g, "");
	if (term == "")
		alert('Please enter text into search field.');
	else
		location.href = "/Search.aspx?search_term=" + term + (is_press_room ? '&press_room=1' : '') ;
}

AddDefaultHook = function(obj, button) {
	default_click(obj, $(button));
}

runAllInputs = function(parentObj, obType, func) {
	findElements(parentObj, 'input', function(obj) { if (obj.type == obType) func(obj); });
}

openNextDiv = function(obj)
{
	var ele = findNextElement(obj, 'div');
	toggle_display(ele); 
}

default_click = function(curObj, buttonObj) {
	curObj.onkeypress = function(e) {
		e = window.event || e;
		if (e.keyCode == 13) {
		
			if (e.preventDefault)
				e.preventDefault();
				
			e.returnValue=false;
			e.cancel = true;
			if (buttonObj.click) {
				buttonObj.click();
			}
			else {
				$J(buttonObj).click();
			}
			
			
		}
	}
}

sprintf = function (str){
    var arg = arguments;
    for(var i=0; i<arg.length; i++) if(arg[i]==undefined) arg[i] = ""; 
    i = 1;
    return str.replace(/(([^\\]?)%(s|d))/g, function(s, a1, a2){ return a2 + arg[i++]; });
}


findCurrentSideNavSubMenu = function(container, menuText) {
	var lis = findElements(container, "li");
	$D('Checking Menu Items: ' + lis.length);
	for (var i = 0; i < lis.length; i++) {
		var li = lis[i];
		var mText = li.firstChild.innerHTML.replace(/<[^>]*>/, "").replace("&amp;", "&").replace("&", "").toLowerCase();
		mText = mText.replace(/\s/g, "");
		menuText = menuText.replace("&amp;", "&").replace("&", "");
		$D(sprintf('Menu item %s value is %s', i, mText));
		li.style.className = "menuOff";
		if (menuText == mText) {
			$D("Match!")
			li.className = "menuOn";
		}
	}
	$D('done');
}

addDropDownOption = function(dropDown, name, value) {
	var oOption = document.createElement("OPTION");
	oOption.text=name;
	oOption.value="" + value;
	try {
    dropDown.add(oOption, null); // standards compliant; doesn't work in IE
  }
  catch(ex) {
    dropDown.add(oOption); // IE only
  }
}

function writeYear() {
	RightNow = new Date();
	var TheYear = RightNow.getYear()
	
	if (TheYear >= 100 && TheYear <= 1999)
	{TheYear=TheYear + 1900}
	else
	{TheYear=TheYear}
	document.write(TheYear)
}

function clearField(wField) {
	if (wField.value == wField.defaultValue) {
		wField.value = "";
	}
	else if (wField.value == "") {
		wField.value = wField.defaultValue;
	}	
}




