/*
 * Read from SVN revision 48728 on Tue Aug 10, 2010 at 08:09 AM by r.clein.
 */
function formAsString(form, fields) {
	var form_string = "";

	if(fields)
		var splitFields = fields.split(",");

	for(var i = 0; i < form.elements.length; i++) {
		var yesElement = false;

		if(!fields)
			yesElement = true;
		else {
			for(var x = 0; x < splitFields.length; x++) {
				if(splitFields[x] == form.elements[i].name) {
					yesElement = true;
					break;
				}
			}
		}

		if(yesElement) {
			switch(form.elements[i].type) {
				case "text" :
				case "hidden" :
				case "hidden" :
				case "textarea" :
				case "password" :
				case "button" :
				case "submit" :
					form_string += form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value) + "&";
					
					break;

				case "select-one" :
					form_string += form.elements[i].name + "=" + form.elements[i].options[form.elements[i].selectedIndex].value + "&";
					
					break;
				
				case "select-multiple" :
					form_string += form.elements[i].name + "=";

					for(var x = 0; x < form.elements[i].length; x++)
						if(form.elements[i].options[x].selected)
							form_string += form.elements[i].options[x].value + ",";
					
					if(form_string.substr(form_string.length - 1, form_string.length) == ",")
						form_string = form_string.substr(0, form_string.length - 1);
					
					form_string += "&";
					break;
				
				case "checkbox" :
				case "radio" :
					form_string += form.elements[i].name + "=";

					if(form.elements[i].checked)
						form_string += form.elements[i].value + ",";
					
					if(form_string.substr(form_string.length - 1, form_string.length) == ",")
						form_string = form_string.substr(0, form_string.length - 1);
					
					form_string += "&";
					break;
			}
		}
	}

	form_string = form_string.substr(0, form_string.length - 1);
	return form_string;
}


function zebraLists() {
	var everyList = document.getElementsByTagName('UL');

	for(var i=0;i<everyList.length;i++) {
		if(everyList[i].className.indexOf('stripe') > -1) {
			var listItems = everyList[i].getElementsByTagName('LI');
			var stripe = true;
			for(var q=0;q<listItems.length;q++) {
				if(stripe) {
					listItems[q].style.backgroundColor = '#CFDEEC';
				} else {
					listItems[q].style.backgroundColor = 'transparent';
				}
				stripe = !stripe;
			}
		}
	}
}

function getAbsoluteLeft(objectId) {
	// Get an object left position from the upper left viewport corner
	// Tested with relative and nested objects
	o = document.getElementById(objectId)
	oLeft = o.offsetLeft            // Get left position from the parent object
	while(o.offsetParent!=null) {   // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent    // Get parent object reference
		oLeft += oParent.offsetLeft // Add parent left position
		o = oParent
	}
	// Return left postion
	return oLeft
}

function getAbsoluteTop(objectId) {
	// Get an object top position from the upper left viewport corner
	// Tested with relative and nested objects
	o = document.getElementById(objectId)
	oTop = o.offsetTop            // Get top position from the parent object
	while(o.offsetParent!=null) { // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent  // Get parent object reference
		oTop += oParent.offsetTop // Add parent top position
		o = oParent
	}
	// Return top position
	return oTop
}

function zebraTables() {
	var everyTable = document.getElementsByTagName('TABLE');

	for(var i=0;i<everyTable.length;i++) {
		if(everyTable[i].className.indexOf('stripe') > -1) {
			var tableRows = everyTable[i].getElementsByTagName('TR');
			var stripe = true;
			for(var q=0;q<tableRows.length;q++) {
				if(stripe) {
					var rowCells = tableRows[q].getElementsByTagName('TD');
					for(var c=0;c<rowCells.length;c++) {
						rowCells[c].style.backgroundColor = '#EDE8DA';
					}
				} else {
					var rowCells = tableRows[q].getElementsByTagName('TD');
					for(var c=0;c<rowCells.length;c++) {
						rowCells[c].style.backgroundColor = 'transparent';
					}
				}
				stripe = !stripe;
			}
		}
	}
}

function showFilters(type) {
	switch(type) {
		case 'terms':
			$('jt_filters').innerHTML = $('jt_filters_terms').innerHTML;
			break;
		
		case 'employer':
		break;
		
		case 'time':
		break;
	}
}

function setTab(type) {
	if(type == 'location') {
		//quicksearchLocations();
	}
	['keyword','location','company'].each( function(t) { 
		if($('jt_filter_tabs_' + t)) {
			$('jt_filter_tabs_' + t).className = (type == t)?'jt_focus':'';
			if(type == t) $('jt_filters').innerHTML = $('jt_filters_' + t).innerHTML;
		}
	} );
}

function MakeTableUltraEfficient() {
	var ResultTable = $('jt_search_res') || '';
	if(ResultTable != '') {
		var AllCells = $A(ResultTable.getElementsByTagName('DIV'));
		var WidestCell		= 0;
		var WidestLocCell	= 0;
		AllCells.each( function(cell) {
			if(cell.className.indexOf('jt_employer_cell') > -1) {
				WidestCell = (cell.offsetWidth > WidestCell)?cell.offsetWidth:WidestCell;
			}
			if(cell.className.indexOf('jt_location_cell') > -1) {
				WidestLocCell = (cell.offsetWidth > WidestLocCell)?cell.offsetWidth:WidestLocCell
			}
		} );
		WidestLocCell	+= 20
		WidestCell		+= 20;
		AllCells.each( function(cell) {
			if(cell.className.indexOf('jt_employer_cell') > -1) {
				cell.style.width = WidestCell + 'px';
			}
			if(cell.className.indexOf('jt_location_cell') > -1) {
				cell.style.width = WidestLocCell + 'px';
			}
		} );
	}
}

function ExpandAll() {
	var InterestingElements = $A(document.getElementsByTagName('DIV'));
	InterestingElements.each( function(e) {
		if(e.id.indexOf('res') > -1) {
			if(e.id.indexOf('more') > -1) {
				e.style.display = 'none';
			}
			if(e.id.indexOf('less') > -1) {
				e.style.display = '';
			}
			if(e.id.indexOf('more') == -1 && e.id.indexOf('less') == -1) {
				new Effect.BlindDown(e.id, { duration: .5 } );
			}
		}
	} );
}

function CollapseAll() {
	var InterestingElements = $A(document.getElementsByTagName('DIV'));
	InterestingElements.each( function(e) {
		if(e.id.indexOf('res') > -1) {
			if(e.id.indexOf('more') > -1) {
				e.style.display = '';
			}
			if(e.id.indexOf('less') > -1) {
				e.style.display = 'none';
			}
			if(e.id.indexOf('more') == -1 && e.id.indexOf('less') == -1) {
				new Effect.BlindUp(e.id, { duration: .5 } );
			}
		}
	} );
}

function setKeywordList() {
	var keywordString = $A($('jt_keyword_search_field').value.replace(/\s{2,}/g,' ').split(/\s/));
	keywordString.each( function(keyword) { keyword.replace(/,/g,'') } );
	$('jt_keyword_list').innerHTML = keywordString.join(', ');
}

function setKeywordField() {
	$('jt_keyword_search_field').value = $('jt_keyword_list').innerHTML.replace(/^\s*/,'').replace(/,\s*/g,' ');
}

function hbL(e) {
	while(e.parentNode) {
		if(e.className == 'jt_search_res_job_head_block') {
			e.className = 'jt_search_res_job_head_block_highlight';
			/*
			e.style.border = '1px solid #afcdeb';
			e.style.backgroundColor = '#F4F9FF';
			*/
			break;
		}
		e = e.parentNode;
	}
}

function hbD(e) {
	while(e.parentNode) {
		if(e.className == 'jt_search_res_job_head_block_highlight') {
			e.className = 'jt_search_res_job_head_block';
			/*
			e.style.border = '1px solid white';
			e.style.backgroundColor = 'white';
			*/
			break;
		}
		e = e.parentNode;
	}
}

/* Function: applyEvents
 * 
 * Accepts either a single DOM element, or an Enumerable object
 * containing DOM elements. If the argument is not an Enumerable, give
 * the element two events to watch for.
 */
function applyEvents(e, href, target) {
	/* 2006-09-18 abieber
	 * 
	 * IE won't make it back through the recursion if it comes to an element
	 * that has no tagName, e.g., that it cannot act upon.  Instead (because
	 * this really makes sense), it will silently die and no rollovers
	 * will work at all.
	 * 
	 * So check if the element has a tagName value. Text nodes, for example,
	 * do not.
	 */
	if(e.tagName) {
		if(e.childNodes.length > 0) {
			allChildren = $A(e.childNodes);
			allChildren.each( function(node) {
				applyEvents(node, href, target);
			} );
		}
		if(e.tagName.toLowerCase() != 'tr' && e.tagName.toLowerCase() != 'table' && e.tagName.toLowerCase() != 'tbody') {
			e.onmouseover = function() { hbL(this); };
			e.onmouseout = function() { window.status = ''; hbD(this); };
			if(e.style) e.style.cursor = 'pointer';

			if(target && target.length) {
				e.node = { target: target };
			}

			e.onclick = function(evt) {
				// IE will provide the "event" object globally, which will
				// be predefined with the event object for this event. Moz, et al.
				// will pass the event object into this function as arguments[0].
				var e=(typeof(event)!='undefined')?event:evt;
				var elm = Event.element(e);
				var anhref = hasCompanyDescendent(Event.element(e));
				if(!anhref || (elm.tagName && (elm.tagName.toLowerCase() != 'img' && elm.tagName.toLowerCase() != 'a'))) {
					if(elm.node && elm.node.target && elm.node.target.length &&
						(elm.node.target.match(/_blank/) || elm.node.target.match(/_new/))) {
						var w = window.open(href, 'job_window');
					} else {
						location.href = href;						
					}
				} else if(anhref && elm.tagName && (elm.tagName.toLowerCase() == 'img' || elm.tagName.toLowerCase() == 'a')) {
					if(elm.tagName.toLowerCase() == 'img') {
						if(elm.node && elm.node.target && elm.node.target.length &&
							(elm.node.target.match(/_blank/) || elm.node.target.match(/_new/))) {
							var w = window.open(anhref, 'job_window');
						} else {
							location.href = anhref;						
						}
						Event.stop(e);
					} else if(elm.tagName.toLowerCase() == 'a' && elm.className && elm.className.toLowerCase().match(/more_locations_link/)) {
						var job = elm.id.match(/\d+$/);
						$('res'+job+'more').style.display='none';
						$('res'+job+'less').style.display='';
						new Effect.BlindDown('res'+job, { duration: 0.2 } );
						Event.stop(e);
					}
				}
				return false;
			}
		}
	}
}

function hasCompanyDescendent(e) {
	var within = false;
	if(e.childNodes && e.childNodes.length) {
		$A(e.childNodes).each(function(n) {
			if(!within) within = hasCompanyDescendent(n);
		});
	}
	if(e.tagName && e.className && (e.className.match(/exco_link/) || e.className.match(/more_locations_link/))) {
		return e.href;
	} else if(e.parentNode && e.parentNode.className && (e.parentNode.className.match(/exco_link/) || e.parentNode.className.match(/more_locations_link/))) {
		return e.parentNode.href;
	}
	return within;
}

function d(text) {
	var oB = $('jt_current_filters');
	var tN = document.createTextNode(text + '<br/>');
	var nN = oB.appendChild(tN);
}

/**
 * applyRollovers()
 *
 * Loop through every search result row and set onclick events on every
 * object to simulate the entire heading area being one big link. This
 * function works dynamically, setting the onclick href target to the href
 * of the link within the block.
 *
 * Returns nada.
 */
function applyRollovers() {
	var jobid;
	var href;
	var allDivs = $A(document.getElementsByTagName('DIV'));
	allDivs.each( function(e) {
		if(e.className == 'jt_search_res_job_head_block') {
			/* 2006-09-18 abieber
			 * Get the job id from the id of this div and use it to create onclick
			 * events that simulate the entire heading area being a big link.
			 */
			if(e.getAttribute('id')) {
				var re = /\[(\d+)\]/;
				var matches = re.exec(e.getAttribute('id'));
				jobid = matches[1];
			}
			var anchors = $A(e.getElementsByTagName('A'));
			var target = '';
			anchors.each( function(e) {
				// There are two links inside the head area; we want the href of the link to the job.
				if(e.className == 'jt_search_res_job_title') {
					href = e.getAttribute('href');
					tg = e.getAttribute('target');
					onclick = e.getAttribute('onclick');
					if(onclick && onclick.toString().match(/indeed_clk/i))
						href += '&jsa=' + onclick.toString().match(/indeed_clk\(.+?,'(\d+)'\)/i)[1];
					if(tg && tg.length) target = tg;
				}
			});
			/* Loop through all first-level elements inside this div and send them
			 * along to applyEvents();
			 */
			var divChildren = $A(e.childNodes);
			divChildren.each( function(node) {
				applyEvents(node, href, target);
			});
		}
	});
}

function quicksearchLocations() {
	$('jt_filters_location_content').innerHTML = '<em>Please wait...</em>';
	new Ajax.Request('/c2/includes/quicksearch_locations.cfm',
	{
		method: 'get',
		onSuccess: function(transport) {
			var response = transport.responseText || '';
			if(response.match(/^\s*$/)) {
				$('jt_filters_location_content').innerHTML = 'There was an error while retrieving the locations. Please refresh the page and try again.';
			} else {
				$('jt_filters_location_content').innerHTML = response;
			}
		},
		onFailure: function() {
			$('jt_filters_location_content').innerHTML = 'There was an error while retrieving the locations. Please refresh the page and try again.';
		}
	});
}

function saveJob(job, site) {
	TB_show2('Save Job', '/c2/savingjob.cfm?width=300&height=200', null, function() {
		$('jobsave_status').innerHTML = '<em>Saving this job...</em>';
		new Ajax.Request('/c/functions/savejob.cfm?site_id=' + site,
		{
			method: 'post',
			postBody: 'job='+job,
			onSuccess: function(transport) {
				var response = transport.responseText || '';
				if(response.indexOf('nolog') != -1) {
					$('jobsave_status').innerHTML = 'Your session expired; please log in again to save jobs.';
				} else {
					$('jobsave_status').innerHTML = 'Your job was saved successfully!';
				}
			},
			onFailure: function() {
				$('jobsave_status').innerHTML = 'There was a problem saving your job. Please refresh the page and try again.';
			}
		});
	});
}

function saveSearch(querystring,form) {
	if(!form) {
		// The box hasn't even been shown yet. Show0r it.
		TB_show2('Save Search', '/c2/savingsearch.cfm?width=300&height=300&' + querystring, null, null);
	} else {
		// The box is probably showing right now. We should save that search. Probably.
		var fullquerystring = formAsString(form) + "&" + querystring;
		$('searchsave_status').innerHTML = '<div class="jt_status">Saving Search...</div>';
		new Ajax.Request('/c/functions/savesearch.cfm',
		{
			method: 'post',
			postBody: fullquerystring,
			onSuccess: function(transport) {
				var response = transport.responseText || '';
				if(response.indexOf('nolog') != -1) {
					$('searchsave_status').innerHTML = '<div class="jt_status">Your session expired; please log in again to save searches.';
				} else {
					$('searchsave_status').innerHTML = '<div class="jt_status">Your search was saved.</div>';
				}
			},
			onFailure: function() {
				$('searchsave_status').innerHTML = '<div class="jt_status">There was a problem saving your search. Please refresh the page and try again.';
			}
		});
	}

	// Never return true because sometimes we have to call this function from the
	// form onsubmit event and we have to do "return saveSearch()" but don't want it
	// to submit the form, in fact.
	return false;
}

function emailJob(querystring,form) {
	if(!form) {
		// The box hasn't been shown yet. Show0r it.
		TB_show2('E-mail Job', '/c2/emailjob.cfm?width=300&height=300&' + querystring, null, null);
	} else {
		// The box is showing right now, which means we were called from the form inside of it.
		// Well, probably. So process that stuff and show output.

		// First validate the form's contents.
		// Because this entire thing is contained within an AJAX-powered pop-up window, I think
		// we can make the conservative assumption that JavaScript is enabled... Hence, the emailjob.cfm
		// script doesn't actually do any validation.
		if($('jt_emailjob_email').value.match(/^\s*$/)) {
			$('emailjob_message').innerHTML = 'You must supply at least an e-mail address.';
		} else {
			var fullquerystring = formAsString(form) + "&" + querystring;
			$('emailjob_status').innerHTML = '<div class="jt_status">E-mailing job...</div>';
			new Ajax.Request('/c/functions/emailjob.cfm',
			{
				method: 'post',
				postBody: fullquerystring,
				onSuccess: function(transport) {
					var response = transport.responseText || '';
					// If this particular string is returned, there was some kind of a CF error. Otherwise, I guess it worked.
					// Usually it works.
					if(response.match(/There was an error/)) {
						$('emailjob_status').innerHTML = '<div class="jt_status">There was a problem e-mailing this job. Please refresh the page and try again.</div>';
					} else {
						$('emailjob_status').innerHTML = '<div class="jt_status">The job was e-mailed.</div>';
					}
				},
				onFailure: function() {
					$('emailjob_status').innerHTML = '<div class="jt_status">There was a problem reaching the e-mail service. Please refresh the page and try again.</div>';
				}
			});
		}
	}

	// Never return true.
	return false;
}


