function handleJSMenu()
{
	var jsMenu = xGetElementById('jsMenu');
	if(jsMenu.style.display == "none")
		jsMenu.style.display = "block";
	else
		jsMenu.style.display = "none";
}


function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_showHideLayers() { //v3.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v='hide')?'hidden':v;}
    obj.visibility=v; }
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function change_z()
{
    var i,v,obj,args = change_z.arguments;
    for (i = 0; i<(args.length-2); i+=3)
    {
        if ((obj = MM_findObj(args[i])) != null)
        {
            v = args[i+2];
            if (obj.style)
            {
                // NN doesn't have this.
                obj = obj.style;
            }
            obj.zIndex = v;  
        }
    }
}

// Currency Dropdown Fxn
function ddToTA(thisSelector,hiddenInput)
{
	var v = thisSelector.options[thisSelector.selectedIndex].value;
	if(v == 'xswitch')
	{
		thisSelector.disabled = true;
		hiddenInput.disabled = false;
		thisSelector.style.display = 'none';
		hiddenInput.style.display = '';
		//document.getElementById('nm').style.display = 'inline';
	}
}

// important! poptitle can only contain alphanumeric and _ ... no spaces!
function openWin(filename, poptitle, popheight, popwidth, scroll)
{  
	window.open(filename,poptitle,'height='+popheight+',width='+popwidth+',dependent=1,directories=0,location=0,menubar=0,resizable=0,scrollbars='+scroll+',noresize,toolbar=0');
}

function toggleBoxes(formNum, ignore)
{
	for (var i = 0; i < document.forms[formNum].elements.length; i++)
	{
		if(document.forms[formNum].elements[i].type == 'checkbox' && document.forms[formNum].elements[i].name != ignore)
		{
			document.forms[formNum].elements[i].checked = !(document.forms[formNum].elements[i].checked);
		}
	}
}

//////// start X Library functions
// Copyright 2001-2005 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL

function xGetElementById(e)
{
  if(typeof(e)!='string') return e;
  if(document.getElementById) e=document.getElementById(e);
  else if(document.all) e=document.all[e];
  else e=null;
  return e;
}

function xDef()
{
  for(var i=0; i<arguments.length; ++i){if(typeof(arguments[i])=='undefined') return false;}
  return true;
}

function xPageX(e)
{
  if (!(e=xGetElementById(e))) return 0;
  var x = 0;
  while (e) {
    if (xDef(e.offsetLeft)) x += e.offsetLeft;
    e = xDef(e.offsetParent) ? e.offsetParent : null;
  }
  return x;
}

function xPageY(e)
{
  if (!(e=xGetElementById(e))) return 0;
  var y = 0;
  while (e) {
    if (xDef(e.offsetTop)) y += e.offsetTop;
    e = xDef(e.offsetParent) ? e.offsetParent : null;
  }

  return y;
}

function xTableColDisplay(bShow, sec, nCol)
{
  var r;
  sec = xGetElementById(sec);
  if (sec && nCol < sec.rows[sec.hRow].cells.length) 
  {
    for (r = 0; r < sec.rows.length; ++r) 
	{
		if(sec.rows[r].cells[nCol])
			sec.rows[r].cells[nCol].style.display = bShow ? '' : 'none';
    }
  }
}

//////// end X Library functions

function enterSubmit(e)
{
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return false;

	if (keycode == 13)
		return true;
	return false;
}


function tableSetup(tname)
{
	return true;
	// create the element that we'll click on
	var but = document.createElement('img');
	but.id='dbut';
	//but.src='images/darrow.gif';
	but.src='images/dhide.gif';
	but.style.position = 'absolute';
	but.onclick = dispOnClick;
	but.onmouseover = dbutOnMouseover;
	but.style.display = 'none';
	but.tname = tname;
	document.body.appendChild(but);
	
	// make the top row of the table "magical"
	var tbl, c, e, r;
	tbl = document.getElementById(tname);
	
	// sometimes the header row is actually the second row.
	r = 0;
	if(tbl.rows[0].cells[0].id == 'nohide')
		r = 1;
	
	tbl.hRow = r;
	
	if (tbl && tbl.rows && tbl.rows[r].cells) 
	{
		for (c = 0; c < tbl.rows[r].cells.length; ++c) 
		{
			e = tbl.rows[r].cells[c];
			e.onmouseover = dispOnMouseover;
			e.onmouseout = dispOnMouseout;
			e.id = 'cell' + c;
		}
	}
}

function unhideAllCols(tname)
{
	var tbl = document.getElementById(tname);
	
	for( var c = 0; c < tbl.rows[tbl.hRow].cells.length; ++c)
	{
		if(tbl.rows[tbl.hRow].cells[c].style.display == 'none')
		{
			for (r = 0; r < tbl.rows.length; ++r) 
			{
				if(tbl.rows[r].cells[c])
					tbl.rows[r].cells[c].style.display = '';
			}
		}
	}
	
	var unhide = document.getElementById('unhidelink');
	if(unhide)
		unhide.style.display = 'none';
}

// make sure this is lit so it doesn't flicker on IE
function dbutOnMouseover()
{
	this.style.display = '';
}

function dispOnClick()
{
	xTableColDisplay(false, this.tname, this.myIndex);
	this.style.display = 'none';
	var unhide = document.getElementById('unhidelink');
	if(unhide)
		unhide.style.display = '';
}

function dispOnMouseover()
{
	var db = document.getElementById('dbut');
	
	if(!db)
		return false;
	
	// have to do this for IE!!!
	var iWidth = db.width;
	if(iWidth == 0)
	{
		if(db.currentStyle && db.currentStyle.width)
			iWidth = parseInt(db.currentStyle.width);
		else
		{
			// realllly sux
			iWidth = 24;
		}
	}
	
	
	//alert(this);
	db.style.left = (xPageX(this) + this.clientWidth - iWidth) + 'px';
	db.style.top = xPageY(this) + 'px';
	db.myIndex = this.cellIndex;
	db.myID = this.id;
	
	// IE doesn't change the array,
	// so need to find the right column number if this isn't it
	var tbl = document.getElementById(db.tname);
	if(tbl.rows[tbl.hRow].cells[db.myIndex].id != db.myID)
	{
		// find our "new" column index.
		for(var c = 0; c < tbl.rows[tbl.hRow].cells.length; ++c)
		{
			if(tbl.rows[tbl.hRow].cells[c].id == db.myID)
			{
				db.myIndex = c;
				break;
			}
		}
	}
	
	db.style.display = '';
}

function dispOnMouseout()
{
	//this.dispButton.style.display = 'none';
	var db = document.getElementById('dbut');
	if(db)
		db.style.display = 'none';
}

function addTimeName(username, inputname)
{
	//I cannot get second param to work.... 
  	var today = new Date();
	var str;
	str = "\n[" + (today.getMonth() + 1) +
		"/" + today.getDate() + "/" + today.getFullYear() + " " +
		(today.getHours() > 12?today.getHours() - 12:(today.getHours() ==
		0?'12':today.getHours())) + ":" + (today.getMinutes() < 10 ? '0' : '') +
		today.getMinutes() + " " + (today.getHours() > 12?"am ":"pm ") +
		username + "]: "; 
	document.forms[0].vec_comments.value += str;
  
 }

// save the scroll position 
// so onLoad we can go back to where we were
function saveScrollCoordinates(formname) 
{
	//var frm = xGetElementById(formname); // doesn't work for forms?
	var frm = document.forms[formname];
	
	frm.scrollx.value = ((navigator.userAgent.indexOf("MSIE") != -1 && document.compatMode && document.compatMode != "BackCompat")?document.documentElement.scrollLeft:((document.all)?document.body.scrollLeft:window.pageXOffset));
	frm.scrolly.value = ((navigator.userAgent.indexOf("MSIE") != -1 && document.compatMode && document.compatMode != "BackCompat")?document.documentElement.scrollTop:((document.all)?document.body.scrollTop:window.pageYOffset));
	//alert(frm.scrollx.value + ', ' + frm.scrolly.value);
}
 
// the following fxn hides or shows an id that you send it
function hideShow(id)
{
	var thing = xGetElementById(id);
	var thing_inst = xGetElementById(id + '_inst');
	var thing_instFilter = xGetElementById(id + '_instFilter');
	if(thing)
	{
		if(thing.style.display == 'none')
		{
			thing.style.display = '';
			if(thing_inst)
				thing_inst.innerHTML = '(click to hide)';
			else if(thing_instFilter)
				thing_instFilter.innerHTML = '(Hide Search Filters)';				
		}
		else
		{
			thing.style.display = 'none';
			if(thing_inst)
				thing_inst.innerHTML = '(click to show)';
			else if(thing_instFilter)
				thing_instFilter.innerHTML = '(Show Search Filters)';				
		}
	}
}

// populate search prefs
// passed a null id will clear out form options
function searchUpdate(type,id)
{
	if (type)
		remoteRequest(BASE_REMOTE_LOOKUP_URL + '/AJAX/target','updateSearchFilters','','id=' + id, type);
	else
		return false;
}

// callback function to update target values
var last_target_id = 0;
function updateSearchFilters(serverResponse, ajaxRequest, clear)
{
	// check for errors
	if(serverResponse.slice(0,4) == 'ERR:')
	{
		// ignore
	}
	else
	{
		var post_id = parseInt(ajaxRequest.postParams.split('=')[1]);
		var type = ajaxRequest.otherParams;

		var savedSearchElem = xGetElementById('target_id');
		
		if (savedSearchElem.type == 'button')
		{
			if (post_id == 0)
			{
				savedSearchElem.value = "Load "+savedSearchElem.value.substring(6);
				savedSearchElem.onclick = new Function('searchUpdate(\''+type+'\','+last_target_id+')');
			}
			else
			{
				last_target_id = post_id;
				savedSearchElem.value = "Clear "+savedSearchElem.value.substring(5);
				savedSearchElem.onclick = new Function('searchUpdate(\''+type+'\',0)');
			}
		}
		
		var responseArray = serverResponse.split('|');
		for (var i = 0; i < responseArray.length; i += 2)
		{
			var form_elem = null;
			switch (responseArray[i])
			{
				case 'state_id' :
					form_elem = xGetElementById('locState_1');
					break;
				case 'country' :
					form_elem = xGetElementById('locCountry_1');
					break;
				default :
					form_elem = xGetElementById(type+'_'+responseArray[i]);
					break;
			}
			
			value = (responseArray[i + 1]?responseArray[i + 1]:'');
			if (form_elem)
			{
				if (form_elem.type == 'text')
					form_elem.value = responseArray[i + 1];
				else
				{
					if(responseArray[i] == 'country') // this should be the first one, always
					{
						if(responseArray[i + 1] != '' && responseArray[i + 1] != 'US' && responseArray[i + 1] != 'CA' && euro != 1)
						{
							var state = xGetElementById('locStateCell_1');
							//alert(serverResponse);
							var stateRow = xGetElementById('stateRow_1');
							var zipBody = xGetElementById('zipBody_1');
							if(stateRow)
								stateRow.style.display = 'none';
							if(zipBody)
								zipBody.style.display = 'none';
							var stateSelect = xGetElementById('locState_1');
							if(stateSelect)
								stateSelect.selectedIndex = 0;
							euro = 1;
							calendar_updateFormat();
						}
						else if((responseArray[i + 1] == 'US' || responseArray[i + 1] == 'CA'))
						{
							var state = xGetElementById('locStateCell_1');
							//alert(serverResponse);
							var stateRow = xGetElementById('stateRow_1');
							var zipBody = xGetElementById('zipBody_1');
							var currCountry = responseArray[i + 1];
							if(stateRow)
								stateRow.style.display = '';
							if(zipBody)
								zipBody.style.display = '';
							//state.innerHTML = serverResponse;
							euro = 0;
							calendar_updateFormat();
							// need to get the list of states for this country
							var id = 1;
							var stateSelect = xGetElementById('locState_1');
							remoteRequest(BASE_REMOTE_LOOKUP_URL + '/AJAX/countrystates','updateStates','','country=' + currCountry + '&input=' + stateSelect.name + '&id=' + id, id,false);
						}
					}
					
					for (var j = 0; j < form_elem.options.length; j++)
					{
						if (form_elem.options[j].value == value)
						{
							form_elem.selectedIndex = j;
							break;
						}
					}
				}
			}
		}
	}
}


///// the following functions deal with getting 
// the zip OR city, state based on the other.

function locUpdate(type,id)
{
	//alert(type);
	var statusName = 'locStatus_' + id;
	var status = xGetElementById('locStatus_' + id);
	
	switch (type)
	{
		case 'zip':
			if(status) 
				status.innerHTML = '<span onclick="locUpdate(\'updateCityState\',\'' + id + '\')" class="zipCityLookupHover"><img src="'+BASE_URL+'/images/findcity.gif"></span>';
			break;
		case 'cityState':
			if(status) 
				status.innerHTML = '<span onclick="locUpdate(\'updateZip\',\'' + id + '\')" class="zipCityLookupHover"><img src="'+BASE_URL+'/images/findpostalcode.gif"></span>';
			break;
		case 'updateStates':
			var country = xGetElementById('locCountry_' + id);
			var state = xGetElementById('locState_' + id);
			if(country && state)
			{
				var currCountry = country.value;
				var inputName = state.name;
				state.enabled = false;
				remoteRequest(BASE_REMOTE_LOOKUP_URL + '/AJAX/countrystates','updateStates','','country=' + currCountry + '&input=' + inputName + '&id=' + id, id);
			}
			break;
		case 'updateZip':
			var city = xGetElementById('locCity_' + id);
			var state = xGetElementById('locState_' + id);
			var country = xGetElementById('locCountry_' + id);
			var zipInput = xGetElementById('locZipInput_' + id);
	
			if(city && state && country && zipInput)
			{
				var currCity = city.value;
				var currState = state.options[state.selectedIndex].innerHTML;
				var currCountry = country.value;
				var inputName = zipInput.name;
				//alert('city: '+city.value+'\n state:'+state.options[state.selectedIndex].innerHTML);
				remoteRequest(BASE_REMOTE_LOOKUP_URL + '/AJAX/citytozip','updateZip',statusName,'city=' + currCity + '&state=' + currState + '&country=' + currCountry + '&input=' + inputName + '&id=' + id, id);
			}
			break;
		case 'updateCityState':
			var zipInput = xGetElementById('locZipInput_' + id);
	
			if(zipInput)
			{
				var zipString = zipInput.value;
				
				// catch zip+4 in US // 
				var re = /(\d{5})-(\d{4})/;
				var m = re.exec(zipString);
				if(m != null)
					zipString = m[1];
				
				remoteRequest(BASE_REMOTE_LOOKUP_URL + '/AJAX/ziptocity','updateCityState',statusName,'zip=' + zipString, id);
			}
			break;
		default:
			return false;
	}
}

// callback function to update the city, state field
function updateCityState(serverResponse, ajaxRequest)
{
	//alert(serverResponse);
	// check for errors
	if(serverResponse.slice(0,4) == 'ERR:')
		ajaxRequest.statusElement.innerHTML = serverResponse.slice(4);
	else
	{
		// the reponse comes as a pipe-separated string.
		var cityParts = serverResponse.split('|');
		
		var city = xGetElementById('locCity_' + ajaxRequest.otherParams);
		var state = xGetElementById('locState_' + ajaxRequest.otherParams);
		city.value = cityParts[0];
		state.value = cityParts[1];
	}
}

// callback function to update the zip field
function updateZip(serverResponse, ajaxRequest)
{
	//alert(serverResponse);
	// check for errors
	if(serverResponse.slice(0,4) == 'ERR:')
		ajaxRequest.statusElement.innerHTML = serverResponse.slice(4);
	else
	{
		var zip = xGetElementById('locZipCell_' + ajaxRequest.otherParams);
		oldZipInputs[ajaxRequest.otherParams] = zip.innerHTML;
		zip.innerHTML = serverResponse;
	}
}

// so we can more easily put back the zip text inputs
var oldZipInputs = Object();

// restore a zip input back to text
function restoreZipInput(id)
{
	var zip = xGetElementById('locZipCell_' + id);
	zip.innerHTML = oldZipInputs[id];
}

// callback function to update a state selector based on country
function updateStates(serverResponse, ajaxRequest)
{
	// check for errors
	if(serverResponse.slice(0,4) == 'ERR:')
		ajaxRequest.statusElement.innerHTML = serverResponse.slice(4);
	else
	{
		var state = xGetElementById('locStateCell_' + ajaxRequest.otherParams);
		//alert(serverResponse);
		var stateRow = xGetElementById('stateRow_' + ajaxRequest.otherParams);
		var zipBody = xGetElementById('zipBody_' + ajaxRequest.otherParams);
		if(serverResponse == '') // country without states, assume euro
		{
			if(stateRow)
				stateRow.style.display = 'none';
			if(zipBody)
				zipBody.style.display = 'none';
			var stateSelect = xGetElementById('locState_' + ajaxRequest.otherParams);
			if(stateSelect)
					stateSelect.selectedIndex = 0;
			if(euro != 1)
			{
				euro = 1;
				calendar_updateFormat();
			}
		}
		else
		{
			if(stateRow)
				stateRow.style.display = '';
			if(zipBody)
				zipBody.style.display = '';
			state.innerHTML = serverResponse;
			if(euro != 0)
			{
				euro = 0;
				calendar_updateFormat();
			}
		}
	}
}

/////// end loc update functions


///////////// these funtions are all for AJAX type functionality.

// Couple of constants
var XMLHTTP_RESPONSE_COMPLETE = 4;
var XMLHTTP_STATUS_SUCCESS = 200;

// This will store our cached requests
var AJAXRequests = new Object();

/**
* This is convenience function for using the AJAXRequest class,
* and also provides some caching.
* (That is, if you've already made a request with a given url and post params, 
* it will not make the request again.)
*
* If a callback function is provided, it will be called with the 
* server result and the AJAXRequest object (mostly so you can access the otherParams).
* If not, it will put the server result in the status element's innerHTML.
*
*@param remoteURL - full absolute URL for the request
*@param callbackFunction - when we've completed the request, we call this function with the response and the AJAXRequest object.
*@param statusElementID - we will update the innerHTML of this element with status messages (loading... etc)
*@param postParams - if these are provided, we will do a POST instead of a GET
*@param otherParams -- anything else you want for future reference; accesible as AJAXRequest.otherParams.
*/
function remoteRequest(remoteURL, callbackFunction, statusElementID, postParams, otherParams, async)
{
	var key = remoteURL + '|' + postParams;
	
	// cached?
	if(AJAXRequests[key])
	{
		// create a new object with our parameters,
		// and just set the response accordingly
		var cached = new AJAXRequest(remoteURL, callbackFunction, statusElementID, postParams, otherParams, async);
		cached.request = AJAXRequests[key].request;
		cached.onStateChange();
	}
	else
	{
		AJAXRequests[key] = new AJAXRequest(remoteURL, callbackFunction, statusElementID, postParams, otherParams, async);
		AJAXRequests[key].go();
	}
}

/**
* The following function is a simplified version 
* of the bind function from the "prototype.js" library.
*@see http://prototype.conio.net/, http://www.sergiopereira.com/articles/prototype.js.html
*
* Returns an instance of the function pre-bound to the 
* function(=method) owner object.
*/
Function.prototype.bind = function(objToOperateOn) 
{
	// stupid lexical scoping makes defining these here necessary.
	var localthis = this;
	return function() 
	{
		return localthis.apply(objToOperateOn);
	}
}

/**
* This is the AJAXRequest class.
*/
function AJAXRequest(remoteURL, callbackFunction, statusElementID, postParams, otherParams, async)
{
	this.remoteURL = remoteURL;
	this.callbackFunction = callbackFunction;
	this.statusElementID = statusElementID;
	this.postParams = postParams;
	this.otherParams = otherParams;
	this.request = null;
	this.async = (async == null) ? true : async;
	
	// did they set a status element ID? convert to an element.
	this.statusElement = null;
	if(this.statusElementID && this.statusElementID.length > 0)
		this.statusElement = xGetElementById(this.statusElementID);
}

/**
* This simply calls the callback function
* and passes the returned result and AJAXRequest object as variables.
* 
* For simplicity, it only calls the callback if the request
* was successful.
*/
AJAXRequest.prototype.onStateChange = function() 
{
	// if the request shows "complete"
	if(this.request.readyState == XMLHTTP_RESPONSE_COMPLETE)
	{
		// if "OK"
		if(this.request.status == XMLHTTP_STATUS_SUCCESS)
		{
			// if we have a callback fn, use it.
			if(this.callbackFunction && this.callbackFunction.length > 0)
			{
				// reset the status
				if(this.statusElement)
					this.statusElement.innerHTML = '';
				
				eval(this.callbackFunction)(this.request.responseText,this);
			}
			else if(this.statusElement)
			{
				// otherwise, just stick the response in the status element.
				this.statusElement.innerHTML = this.request.responseText;
			}
		}
		else
		{
			// uh oh!
			this.statusElement.innerHTML = '[there was a problem loading the requested data]';
		}
	}
}

/**
* This sets things up and makes the request
*/
AJAXRequest.prototype.go = function()
{
	// create a request/transport object
	// this version for Firefox, Safari, etc...
	if (window.XMLHttpRequest)
		this.request = new XMLHttpRequest();
	// this for IE...
	else if (window.ActiveXObject)
		this.request = new ActiveXObject("Microsoft.XMLHTTP");
	else if (this.statusElement)
	{
		this.statusElement.innerHTML = '[dynamic loading not supported; please update your browser]';
		return false;
	}
	
	// set the state change callback function
	this.request.onreadystatechange = this.onStateChange.bind(this);
	
	// update the status
	if(this.statusElement)
		this.statusElement.innerHTML = '[loading...]';
	
	// are we POST'ing or GET'ing?
	if(this.postParams && this.postParams.length > 0)
	{
		this.request.open('POST', this.remoteURL, this.async);
		this.request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		this.request.send(this.postParams);
	}
	else
	{
		// simple GET
		this.request.open('GET', this.remoteURL, this.async);
		this.request.send(null);
	}

}

///// end AJAXRequest class

///////////// end AJAX related stuff

// --------------------------------
// getElementsByClass by dustindiaz
// http://www.dustindiaz.com/getelementsbyclass/
// --------------------------------
function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

var euro = 0;
var firstDayOfWeek = euro; // 0 means sunday, 1 means monday
function calendar_onSelect(calendar, date) {
  //console.log(calendar);
  if(calendar_currInput != null)
  {
	var input_field = calendar_currInput;
  	input_field.value = date;
  	if (calendar.dateClicked) {
	  calendar.callCloseHandler(); // this calls "onClose" (see above)
  	}
  }
};
function calendar_onClose(calendar) {
  calendar.hide();
  // or calendar.destroy();
};
var calendar = null;
var calendar_currInput = null;
var calendar_loaded = false;
var euroDates = false;
function calendar_onLoad()
{
	calendar = new Calendar(firstDayOfWeek, null, calendar_onSelect, calendar_onClose);
	//console.log(calendar);
	calendar.create();
	calendar.hide();
	if(euroDates)
		calendar.setDateFormat("%d/%m/%y");
	else
		calendar.setDateFormat("%m/%d/%y");
	calendar_loaded = true;
}

function calendar_updateInputBox(elementID)
{
	if(calendar_loaded == false)
		calendar_onLoad();
	calendar_currInput = document.getElementById(elementID);
}

function calendar_updateFormat()
{
	if(calendar_loaded == false)
		calendar_onLoad();
	dateFormatLabels = getElementsByClass("dateFormatSpan",document.body,"span");
	if(euro == 1)
	{
		for(var i = 0;i<dateFormatLabels.length;i++)
		{
			if(dateFormatLabels[i].getAttribute('format') == "US")
				dateFormatLabels[i].style.display = "none";
			else
				dateFormatLabels[i].style.display = "";				
		}

		calendar.setDateFormat("%d/%m/%y");
		calendar.setFirstDayOfWeek(1);
	}
	else
	{
		for(var i = 0;i<dateFormatLabels.length;i++)
		{
			if(dateFormatLabels[i].getAttribute('format') == "US")
				dateFormatLabels[i].style.display = "";
			else
				dateFormatLabels[i].style.display = "none";				
		}
		calendar.setDateFormat("%m/%d/%y");
		calendar.setFirstDayOfWeek(0);
	}
	dateInputFields = getElementsByClass("dateInputField",document.body,"input");
	for(var i = 0;i<dateInputFields.length;i++)
	{
		dateInputFields[i].value = '';
	}
}

var expandedLocations = new Array;
var ajaxLoadImg = new Image();
ajaxLoadImg.src = BASE_URL+'/images/loading.gif';
function expandLocations(check)
{
	if(expandedLocations[check] >= 1)
	{
		for(var i = 0; i < expandedLocations[check]; i++)
		{
			var sourceRow = xGetElementById(check+"_"+i);
			sourceRow.parentNode.parentNode.deleteRow(sourceRow.rowIndex);
		}
		expandedLocations[check] = 0;
	}
	else
	{
		var postStr = '';
		postStr = postStr+'filterSet=' + escape(document.lastsearch.filterSet.value);
		postStr = postStr+'&filterHash=' + escape(document.lastsearch.filterHash.value);
		postStr = postStr+'&pagingInfo=' + escape(document.lastsearch.pagingInfo.value);
		postStr = postStr+'&sfs_job_md5=' + escape(check);

		var url = BASE_REMOTE_LOOKUP_URL + '/AJAX/ajaxsfs/jobboard/';
		var params = xGetElementById('ajax_params');
		if (params)
			url = url+escape(params.value);

		var ajaxObj = new AJAXRequest(url, 'handleNewLocations', null, postStr, check, true);
		ajaxObj.go();
		var sourceRow = xGetElementById(check);
		var tempRow = sourceRow.parentNode.parentNode.insertRow(sourceRow.rowIndex+1);
		tempRow.id = check+"_tmp";
		tempRow.setAttribute("class",sourceRow.getAttribute("class"));
		var cell = tempRow.insertCell(0);
		cell.colSpan = 9;
		cell.setAttribute('align','center');
		var img = document.createElement("img");
		img.src=BASE_URL+'/images/loading.gif';

		//var textNode = document.createTextNode('Loading...');
 		cell.appendChild(img);
		expandedLocations[check] = 1;
	}
}

function handleNewLocations(serverResponse, ajaxRequest)
{
	
	var tempRow = xGetElementById(ajaxRequest.otherParams+"_tmp");
	if(tempRow)
	{
		tempRow.parentNode.parentNode.deleteRow(tempRow.rowIndex);
	}
	//console.log(serverResponse);
	var xmlDoc = parseXML(serverResponse);
	
	var sourceRow = xGetElementById(ajaxRequest.otherParams);
	var isPlus = (sourceRow.childNodes.length == 13 || sourceRow.childNodes.length == 6);

	
	var jobResults = xmlDoc.getElementsByTagName("job");
	//alert(jobResults.length);
	//console.log(jobResults);
	for(var i = jobResults.length -1; i >= 0; i -= 1)
	{                                      
		var job = jobResults.item(i);
		var newRow = sourceRow.parentNode.parentNode.insertRow(sourceRow.rowIndex+1);
		newRow.id = ajaxRequest.otherParams+"_"+i;
		newRow.className = sourceRow.className+" sfsExpandedResultRow";

		var cell = newRow.insertCell(newRow.childNodes.length);
		cell.className = 'source_col';
		var imgNode = document.createElement("img");
		imgNode.setAttribute("src",job.getElementsByTagName('JOB_SYSTEM_ICON_PATH').item(0).firstChild.nodeValue);
		cell.appendChild(imgNode);

		var cell = newRow.insertCell(newRow.childNodes.length);
		cell.className = 'dist_col';
		var newSpan = document.createElement('span');

		if(job.getElementsByTagName('JOB_DIST').item(0).firstChild)
		{
			var textNode = document.createTextNode(job.getElementsByTagName('JOB_DIST').item(0).firstChild.nodeValue+' mi - ');
			newSpan.appendChild(textNode);
		}

		var textNode = document.createTextNode(job.getElementsByTagName('JOB_CITY').item(0).firstChild.nodeValue);
		//alert(job.getElementsByTagName('JOB_CITY').item(0).firstChild.nodeValue);
		newSpan.appendChild(textNode);

		if(job.getElementsByTagName('STATE_ABBREV').item(0).firstChild)
		{
			var textNode = document.createTextNode(", "+job.getElementsByTagName('STATE_ABBREV').item(0).firstChild.nodeValue);
			newSpan.appendChild(textNode);
		}
		cell.appendChild(newSpan);

		var newLink = document.createElement("a");
		newLink.setAttribute('href',BASE_URL+'/exec/Bounce/job/'+job.getAttribute('id'));
		newLink.setAttribute('target','_blank');
		var textNode = document.createTextNode(" View Listing");
		newLink.appendChild(textNode);
		cell.appendChild(newLink);
		var cell = newRow.insertCell(newRow.childNodes.length);
		cell.setAttribute('align','center');
		var textNode = document.createTextNode(job.getElementsByTagName('JOB_DATE_BOARD_START').item(0).firstChild.nodeValue);
		cell.appendChild(textNode);
		var cell = newRow.insertCell(newRow.childNodes.length);
		cell.setAttribute('align','center');
		var textNode = document.createTextNode(job.getElementsByTagName('JOB_DATE_SHOP_END').item(0).firstChild.nodeValue);
		cell.appendChild(textNode);

		if (isPlus)
		{
			var cell = newRow.insertCell(newRow.childNodes.length);
			if (job.getElementsByTagName('JOB_FRESH').item(0).firstChild)
			{
				// same image as above here
				var imgNode = document.createElement("img");
				imgNode.setAttribute("src",job.getElementsByTagName('JOB_SYSTEM_ICON_PATH').item(0).firstChild.nodeValue);
				cell.appendChild(imgNode);
			}
			else
			{
				var textNode = document.createTextNode('');
				cell.appendChild(textNode);
			}

		}

		var cell = newRow.insertCell(newRow.childNodes.length);
		cell.setAttribute('class','pay_col');
		var em = document.createElement('em');
		var tmp = '';
		if (job.getElementsByTagName('JOB_CURRENCY').item(0).firstChild)
		{
			tmp = tmp + job.getElementsByTagName('JOB_CURRENCY').item(0).firstChild.nodeValue;
		}
		if (job.getElementsByTagName('JOB_COMBO_PAY').item(0).firstChild)
		{
			tmp = tmp + job.getElementsByTagName('JOB_COMBO_PAY').item(0).firstChild.nodeValue;
		}
		textNode = document.createTextNode(tmp);
		em.appendChild(textNode);
		cell.appendChild(em);

		//console.log(job);
		//console.log(jobResults.childNodes[1]);
	}
	expandedLocations[ajaxRequest.otherParams] = jobResults.length;
	/*var tempRow = sourceRow.parentNode.parentNode.insertRow(sourceRow.rowIndex+1);
	tempRow.id = check+"_tmp";
	var cell = tempRow.insertCell(0);
	cell.colSpan = 9;
	var textNode = document.createTextNode('Loading...');
 	cell.appendChild(textNode);
	*/
}
function verify(doc)
{
  // 0 Object is not initialized
  // 1 Loading object is loading data
  // 2 Loaded object has loaded data
  // 3 Data from object can be worked with
  // 4 Object completely initialized
  if (doc.readyState != 4)
  {
      return false;
  }
}

/**
 * Parse the XML document contained in the string argument and return
 * a Document object that represents it.
 * From: http://www.webreference.com/programming/javascript/definitive2/2.html
 */ 
function parseXML(text) { 
    if (typeof DOMParser != "undefined") { 
        // Mozilla, Firefox, and related browsers 
        return (new DOMParser()).parseFromString(text, "application/xml"); 
    } 
	    else if (typeof ActiveXObject != "undefined") { 
	        // Internet Explorer. 
	        var doc = new ActiveXObject("Microsoft.XMLDOM");
			doc.async="false";
			//doc.onreadystatechange=verify(doc);
			doc.loadXML(text);
			//xmlObj=doc.documentElement;
			//alert(doc.documentElement);
			//var doc = XML.newDocument();  // Create an empty document 
	        //doc.loadXML(text);            // Parse text into it 
	        return doc.documentElement;                   // Return it 
	    } 
	    else { 
	        // As a last resort, try loading the document from a data: URL 
	        // This is supposed to work in Safari. Thanks to Manos Batsis and 
	        // his Sarissa library (sarissa.sourceforge.net) for this technique. 
	        var url = "data:text/xml;charset=utf-8," + encodeURIComponent(text); 
	        var request = new XMLHttpRequest(); 
	        request.open("GET", url, false); 
	        request.send(null); 
	        return request.responseXML; 
	    } 
}
//document.onload = "calendar_onLoad();";
/*
if (document.addEventListener) {
    document.addEventListener("DOMContentLoaded", calendar_onLoad, false);
}
*/
// --------------------

//window.onload = calendar_onLoad;


/**
* Setup our location zip/state toggle
*
*@access public
*@return void
*/
function initLocationToggle()
{
	$('.location_by_state').find('.state, .country').each(function ()
	{
		this.prev = $(this).val();
	});

	$('.location_by_zip').find('.numeric').each(function ()
	{
		this.prev = $(this).val();
	});

	// where do we start off?
	// depends on what is populated.
	$('.location_by_state').each(function()
	{
		// if both zip inputs populated, show zip.
		// if both state/country populated, show them.
		// otherwise, show zip.
		if(	$(this).find('.state').val() &&
			$(this).find('.country').val())
		{
			$(this).find('.numeric').val('');

			$(this).parents('.location_settings').find('.location_by_zip').hide();
		}
		else
		{
			$(this).find('.state').val('');
			$(this).find('.country').val('');

			$(this).hide();
		}
	});
	

	// flip which set of inputs we're looking at
	$('.location_toggle').click(function()
	{
		$(this).parent().hide();
	
		if($(this).parent().hasClass('location_by_state'))
		{
			$(this).parents('.location_settings').find('.location_by_zip').find('.numeric').each(function ()
			{
				if (this.prev)
					$(this).val(this.prev);
			});

			$(this).parents('.location_settings').find('.location_by_state').find('.state, .country').each(function ()
			{
				this.prev = $(this).val();
				$(this).val('');
			});

			$(this).parents('.location_settings').find('.location_by_zip').show();
		}


		if($(this).parent().hasClass('location_by_zip'))
		{
			$(this).parents('.location_settings').find('.location_by_state').find('.state, .country').each(function ()
			{
				if (this.prev)
					$(this).val(this.prev);
			});

			$(this).parents('.location_settings').find('.location_by_zip').find('.numeric').each(function ()
			{
				this.prev = $(this).val();
				$(this).val('');
			});

			$(this).parents('.location_settings').find('.location_by_state').show();
		}

		// don't jump!
		return false;
	});
}

