var currentElectionYear = '08';

var graph;
var offsetX;
var offsetY;
var tooltipOffsetX;
var tooltipOffsetY;
var statusCode;
var statusString;
var currentid;
var graphviz;
var debug = 0; //debugging mode on or off
var tooltip;
var current= new Array();
var timeOutLength = 90;
var requests = [];
var useSVG = 0;
var maxNodeLimit = 250;
//test for SVG support
if (document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")) { 
	svgtestdiv = document.createElement('div');
	svgtestdiv.innerHTML = '<svg/>';
	if (svgtestdiv.firstChild && (svgtestdiv.firstChild.namespaceURI == 'http://www.w3.org/2000/svg' || svgtestdiv.firstChild.namespaceURI == 'http://www.w3.org/1999/xhtml') ) {
		useSVG = 1;
	}
}
var nodelookup = new Hash();
var edgelookup = new Hash();
current['network'] = '';
current['candidate'] = '';  //Yikes, sometimes code uses thes globals, sometimes it uses qparams
current['company']='';	
current['congress_num']='';	
current['view'] = 'tables';
current['edge'] = '';

var qparams = window.location.search.toQueryParams();

function getFormData() {
	//Element.extend($('form'));
	var data="";
	data = Form.serialize($('form'), true);
	return data;
}

//Catches mousemove events
function mousemove(e) {
	if($('tooltip').style.visibility == 'visible') { 
		var mousepos = { 'x': Event.pointerX(e), 'y': Event.pointerY(e) };
		$('tooltip').setStyle({'top': (mousepos['y']- tooltipOffsetY - $('tooltip').getHeight()) + 'px', 'left': (mousepos['x']  - tooltipOffsetX) + 'px'});
	}
}

function onLoading(request) {
	if ($('error').visible()) {
		$('error').hide();
	}
}

function timeOutExceeded(request) {
	statusCode=10;
	statusString = "Server took too long to return data, it is either busy or there is a connection problem";
	request.abort();
	reportError(statusCode, statusString);
}

function catchFailure(response) {
		reportError(-1, "There was a problem contacting the server:"+response.status+":"+response.statusText);
}

// look for an error code, display error if found, evaluate json in response 
function checkResponse(response) {
	var statusCode = null;
	var statusString = "Something went wrong";  
	try {   //need this incase there is giberish and eval() throws js errors
		if (eval(response.responseText)) { 
		} else { //probably means it was stopped by time out
		   reportError(statusCode,statusString);
		}
	} catch (e) {}//HEY FIXME, WHY CATCH WITHOUT PRINTING A MESSAGE
		
	if (!statusCode){  //NO STATUS CODE
	   reportError(-1, "Unknown response from server:\n\n"+response.responseText);
	} else if(statusCode == 1) { //EVERYTHING OK
		return 1;
	} else {  //STATUS INDICATES AN ERROR
	   reportError(statusCode, statusString);
	}
	return 0;	
}

function highlightNode(id, text, noshowtooltip) {
	setOffsets();
	if(typeof graphviz[id] == 'undefined') { id = currentid; }
	if (graphviz[id]) {
		var node = graphviz[id];
		currentid = id;
		//$('debug').innerHTML += node['label'];
		if (! noshowtooltip) { 
			showTooltip(text); //Set the tooltip contents
		}
		//tooltip.style.top = parseFloat(node['posy'])-10 + offsetY - tooltip.clientHeight + 'px'; //Move the tooltip, offset 10 pixels from the point
		//tooltip.style.left = parseFloat(node['posx'])+ 10 + offsetX + 'px'; 
		if (useSVG) { 
			highlightSVGnode(id);
		} else { 
			$('highlight').style.width = parseFloat(node['width']) +2 +'px';
			$('highlight').style.height = parseFloat(node['height']) +2 +'px';
			$('highlight').style.top = parseFloat(node['posy']) -1 + offsetY + 'px';
			$('highlight').style.left = parseFloat(node['posx']) -1 + offsetX + 'px';
			$('highlight').style.visibility = 'visible';
			if (node['shape'] != 'circle') { 
				$('highlight').addClassName('selected');
				$('highlightimg').style.visibility = 'hidden';
			} else {
				$('highlight').removeAttribute('class');
				$('highlightimg').style.visibility = 'visible';
			}
		}
		//$('debug').innerHTML += '('+node['posx']+' '+ offsetX;
	}
}

function showTooltip(label) {
	tooltip = $('tooltip');
	if(label) { 
		tooltip.innerHTML = label;
	}
	tooltip.style.visibility='visible'; //show the tooltip
};

function hideTooltip() { 
	$('highlight').style.visibility = 'hidden';
	$('highlightimg').style.visibility = 'hidden';
	$('tooltip').style.visibility='hidden'; //hide the tooltip first - somehow this makes it faster
	$('images').style.cursor = 'default';	
	currentid = "";
}

//Catches click events
function selectNode(id, noscroll) { 
	if (!$(id)) { return; }
	if(typeof graphviz == 'undefined' || graphviz == null ) { return; }
	if(typeof graphviz[id] == 'undefined') { id = currentid; }
	if (
		(id == current['candidate'] || id == current['company']) && 
		(
		 	(useSVG != 1 && $('info').style.display != 'none') || 
			(useSVG == 1 && current['network'] == id)
		)
	) {
		//hideInfo();
		if (useSVG) { 
			hideNetwork(id);
			return;
		}
	} else { 
		//showInfo(id);
		if (useSVG) { 
			showNetwork(id);
		}
	}
	type = 'candidate';
	if (graphviz[id]['type'] == 'Com') { 
		type = 'company';
	}
	if (qparams['type'] == 'search') { 
		ctables = 'tables';
		if (type == 'company') { 
			ctables = 'cotables'; 
		}
		if ($('c'+current[type])) {
			$('c'+current[type]).removeClassName('selected');
			if (current[type] != id) { 
				//$('c'+current[type]+'Details').hide();
			}
		}
		if ($('c'+id)) {
			elem = $('c'+id);
			elem.addClassName('selected');
			new Effect.Highlight(elem, { startcolor: '#9933ff', afterFinish: function(e){ $(e.element.id).setAttribute('style', ''); }});
			if (! noscroll) { 
				elem.parentNode.scrollTop = elem.offsetTop - $(type+'Sort').getHeight();
			}
		}
		//$('c'+id+'Details').toggle();
		current[type] = id;
	} else {
		showDetails(id, type, 0, 1);
	}
}

function selectEdge(e) { 
	var id;
	if (useSVG) { 
		id = e.element().parentNode.id;
	} else { 
		id = e.element().id;
	}
	var nodes = id.split('_');
	hideNetwork(1);
	type = 'candidate';
	if (current['view'] == 'cotables') { type = 'company'; }
	if (qparams['type'] != 'search') { 
		if (type == 'candidate' && current['candidate'] != nodes[1]) { 
			current['network'] = nodes[1];
			showDetails(nodes[1], 'candidate', 1, 1);
		} else if (type == 'company' && current['company'] != nodes[0]) { 
			current['network'] = nodes[0];
			showDetails(nodes[0], 'company', 1, 1);
		}
	}
	showEdge(nodes[0], nodes[1]);
	loadDetails(nodes[0], nodes[1], type);
	current['network'] = '';
	return;
	var mousepos = { 'x': Event.pointerX(e), 'y': Event.pointerY(e) };
	$('info').setStyle({'top': (mousepos['y'] - tooltipOffsetY - 186) + 'px', 'left': (mousepos['x']  - tooltipOffsetX - 66) + 'px'});

	//showInfo(id);
}

function showInfo(id) {
	setOffsets();
	var node = graphviz[id];
	$('info').style.display = 'none'; 
	$('tail').style.display = 'none'; 
	$('tooltip').style.visibility = 'hidden';
	if (! node['fromId']) { 
		var width = parseFloat(node['width']);
		var diff = ((width/2)*Math.sqrt(2)) - (width/2);
		if (node['shape'] == 'box') {
			$('info').style.left = (parseFloat(node['posx']) +  offsetX - 61 + width) + 'px';
			$('info').style.top = (parseFloat(node['posy']) + offsetY- 181) + 'px';
			current['candidate'] = id;
		} else if(node['shape'] == 'circle') {
			$('info').style.left = (parseFloat(node['posx']) +  offsetX - 59 + width) - diff + 'px';
			$('info').style.top = (parseFloat(node['posy']) + offsetY- 183) + diff + 'px';
			current['company'] = id;
		}
	}
	$('tail').style.left = (parseFloat($('info').style.left) + 61) + 'px';
	$('tail').style.top = (parseFloat($('info').style.top) + 146) + 'px';
	Effect.Appear('info', {duration: .8, to: .9});
	Effect.Appear('tail', {duration: .8, to: .9});
	getInfo(id);
}

function hideInfo() {
	Effect.Fade('info', {duration: .5});
	Effect.Fade('tail', {duration: .5});
}

function getInfo(id) {
	if(typeof graphviz[id] == 'undefined') { id = currentid; }
	var node = graphviz[id];
	loading($('infocontenttext'));
	//document.getElementById('infocontenttext').innerHTML ="<p>looking up "+node['label']+"...</p>";
	var response = "lookup error";
	var params = getFormData();
	params['id'] = id;
	params['action'] = 'show'+node['type']+'Info';

	requests[requests.length+1] = new Ajax.Request('request.php', {
		method: 'get',
		parameters: params,
		onComplete: function(resp) {
			pageTracker._trackPageview('request.php?'+$H(params).toQueryString());
			$('infocontenttext').innerHTML =  resp.responseText;
		}
	});
}

//This function runs once the page has loaded, and sets the ball rolling
function setupTooltips() {
	tooltip = document.getElementById('tooltip');
	var img = $('img0');
	graph = new Array();
	graph['items'] = new Array();
	graph['img'] = img;	//store a reference to the image in the nodes object
	graph['mouserange'] = 8;
	Event.observe(img, 'mousemove', mousemove);
	Event.observe($('info'), 'mousemove', mousemove);
	Event.observe($('highlight'), 'mousemove', mousemove);
	Event.observe($('tooltip'), 'mousemove', mousemove);
	Event.observe($('highlight'), 'mouseover', highlightNode);
	Event.observe($('highlightimg'), 'mouseout', hideTooltip);
	Event.observe($('highlight'), 'mouseout', hideTooltip);
	Event.observe($('tooltip'), 'mouseout', hideTooltip);
	Event.observe($('highlight'), 'mousedown', selectNode);
	Event.observe(window, 'resize', setOffsets );
	window.setTimeout("setOffsets()", 250);
}

function setOffsets() {
	if ($('img0')) {
		offsetX = Position.positionedOffset($('img0'))[0] ;
		offsetY = Position.positionedOffset($('img0'))[1] ;
		tooltipOffsetX = Position.cumulativeOffset($('graphs'))[0] - 15;
		//tooltipOffsetY = Position.cumulativeOffset($('graphs'))[1];
		tooltipOffsetY = 5;
	}
}


function lookupGraph(params) {
	//$('title').innerHTML = "";
	hideTooltip();
	$('info').style.display='none';
	$('tail').style.display='none';
	//if ($('images').childNodes[0]) { 
		//`$('imagescreen').clonePosition('images');
		//$('images').style.height = 'auto';
		//$('images').style.display =  'block';
		//$('graphs').style.height = $('imagescreen').style.height;
	//}
	$('imagescreen').innerHTML = "<span id='loading'><img class='loadingimage' src='images/loading.gif' alt='loading file icon' /><br /><span class='message'>Loading...</span></span>";
	Effect.Appear('imagescreen', {duration: .5, to: .9});
	img = "";
	imagemap = "";
	nodeX = 0;
	count = 0;
	params['useSVG'] = useSVG;
	if (1 || $('searchtype')) {
		params['candidateLimit'] = maxNodeLimit;
		params['companyLimit'] = maxNodeLimit;
	}
	var requesttimeout;
	requests[requests.length+1] = new Ajax.Request('request.php', {
		method: 'get', 
		parameters: params,
		timeOut: timeOutLength,
		onLoading: onLoading,
		onTimeOut: timeOutExceeded,
		onComplete: function(response,json) {
			pageTracker._trackPageview('request.php?'+$H(params).toQueryString());
			if (requesttimeout && requesttimeout.currentlyExecuting) { requesttimeout.stop(); }
			if (checkResponse(response)) {
				//$('images').innerHTML = "";
				//$('images').update("<img id='img0' border=0 src='"+img+"' usemap='#G' />"+imagemap);
				if (useSVG) { 
					$('images').update(overlay);
					$('svg').setAttribute('id', 'img0');
					$('svgscreen').setAttribute('id', 'fsvgscreen');
					$A($('img0').getElementsByTagName('g')).each( function(g) { 
						var id = $(g).getAttribute('id');
						$(g).setAttribute('id', $('f'+g.id));
					});
					$('images').innerHTML += overlay;
					$('img0').show();
				} else {
					map = " usemap='#G'";
					$('images').update("<img id='img0' "+map+" border='0' src='"+img+"' />"+overlay);
				}
				setOffsets();
				setupTooltips();
				if (useSVG) { 
					initSVG();
				} else { 
					$('G').descendants().each(function(a) { 
						if (a.id.search('_') != -1) { 
							Event.observe($(a), 'mouseout', hideTooltip, 1); 
							Event.observe($(a), 'mousemove', mousemove);
						}
						if (graphviz[a.id]) { 
							if (graphviz[a.id].onMouseover != '') { Event.observe($(a), 'mouseover', function(eventObject) { eval(graphviz[a.id].onMouseover); }); }
							if (graphviz[a.id].onClick != '') { Event.observe($(a), 'click', function(eventObject) { eval(graphviz[a.id].onClick); }); }
						}
					});
					//$('graphs').style.height = '870px';
				}
				counts = {'Can': 0, 'Com': 0, 'com2can': 0};
				$H(graphviz).keys().each( function (e) { 
					counts[graphviz[e]['type']]++;
				});
				//if the graph has been limited to by the max, make sure the user knows
				if (counts['Can'] >= maxNodeLimit) {
					$('images').insert('<div id ="warning">Overload! We\'re only showing you the top '+maxNodeLimit+ ' politicians.</div>');
				} 
				if (counts['Com'] >= maxNodeLimit) { 
					$('images').insert('<div id ="warning">Overload! We\'re only showing you the top '+maxNodeLimit+ ' companies.</div>');
				}
				
				//deal with empty graphs  SHOULD NEVER REACH THIS BECAUSE RETUREND ERROR CODE 3
				if(graphviz.length==0){
					$('images').innerHTML = "<div class='norelationships'>Great! No Dirty Energy relationships were found to display.</div>";
				}
				Effect.Fade('imagescreen',  {duration: .5});
				$('images').style.height = 'auto';
				$('csvlink').show();
				$('disclaimer').show();
				initQueryParams();
			}
		},
		onFailure: catchFailure
	});
}

function loading(element) {
	$(element).innerHTML = "<span class='loading' style='display: block; text-align: center; margin: 20px; background-color: white;'><img class='loadingimage' src='images/loading.gif' alt='Loading Data' /><br /><span class='message'>Loading...</span></span>";
	$(element).show();
}


function loadform(firstload) {
	killRequests();
	//add listeners to all the form elements so that they will execute the load form events
	if (firstload) { 
		$('form').getElements().each( function (e) {
			e.observe("change", loadform);
		});
	}
	params = getFormData();
	//params['setupfile'] = setupfile;
	if (Prototype.Browser.WebKit == true && ! firstload && useSVG == 0) { 
		var url = updateLink();
		window.location.replace(url);
		return;
	}
	
	if (! firstload) {
		['network', 'candidate', 'company', 'congress_num', 'edge'].each(function(t) { current[t] = ''; } );
	}
	$(current['view']).show();
	lookupGraph(params);
	loadTable(params, 'candidate');
	loadTable(params, 'company');
	loadtitle(params['congress_num']);
}

function initSearch(type) {
	$('graphcontent').hide();
	$('extras').hide();
	$('infographic').hide();
	$('action').hide();
	$('summary').hide();
	$('profile_vote_score_link').hide();
	loading('searchload');
	/*Event.observe($('searchbox'), "keydown",
		function(event) {
			if (event.keyCode == 13) {
				$('candidatebutton').click();
			}		
		}); 	
	*/
	$('form').searchvalue.value = '';
	if (qparams['searchtype']) { 
		$('searchtype').value = qparams['searchtype'];
	}
	if (qparams['zip']) { 
		$('form').searchvalue.value = qparams['zip']; 
		findCandidates();
	} else if (qparams['can'] || qparams['com']) { 
		if (qparams['can']) { 
			$('searchtype').value = 'can';
		} else {
			$('searchtype').value = 'com';
		}

		//$('form').searchvalue.value = qparams['can']; 
		findCandidates(); 
	} else if (qparams['searchvalue']) {
		searchvalue = qparams['searchvalue'].replace(/\+/g, ' ');
		$('form').searchvalue.value = searchvalue;
		findCandidates(); 
	} else if (qparams['district']) {
		$('form').district.value = qparams['district']; 
		findCandidates();
	}
}

	function initDollars() {
		$('ViewChooser').hide();
		$('graphcontent').hide();
		$('viewcotables').hide();
		$('searchresults').innerHTML = "<div style='float: left;'><div style='width: 630px; position: relative; top: 0px; left: 0px;'><div class='viewtab' style='cursor: default; margin-left: 30px; background-color: #f2f2f2; border-bottom: 1px solid #f2f2f2;'>Oil Money Found:</div><div style='line-height: 18px; padding: 5px 0px; visibility: hidden;'>filler</div></div><div style='width: 640px; background-color:#f2f2f2; border: 1px solid #cccccc; margin: 1px;  padding: 2px;'><div id='foundCandidates' style='width: 99%; border: 1px solid #ccc; max-height: 878px; overflow: auto; background-color: #ffffff;'></div></div></div>";
		$('searchresults').setStyle({'margin-left': '254px'}); 
		$('viewtables').innerHTML = 'Table View';
		$('viewhelp').setStyle({'left': '25em'}); 
		Event.observe($('zipcode'), "keydown",
			function(event) {
				if (event.keyCode == 13) {
					$('submitbutton').click();
				}		
			}); 
		Event.observe($('name'), "keydown",
		function(event) {
			if (event.keyCode == 13) {
				$('submitbutton').click();
			}		
		}); 	
	if (qparams['zip']) { 
		$('form').zip.value = qparams['zip']; 
		findDollars();
	} else if (qparams['can']) { findDollars(); }
}

function toggleDisplay(type, noshow) {
	if (type == 'graph') { type = 'tables'; }	
	if (type != current['view']) {
		if(! $('error').visible()) { $(type).show(); }
		$(current['view']).hide();
		current['view'] = type;	
		if (type == 'cotables') { 
			if ($('viewcandidates')) { 
				$('viewcandidates').removeClassName('selected');
				$('viewcompanies').addClassName('selected');
			}
			if (! noshow) { 
				showDetails(current['company'], 'company', 1, 1);
			}
		} else {
			if ($('viewcandidates')) { 
				$('viewcompanies').removeClassName('selected');
				$('viewcandidates').addClassName('selected');
			}
			if (! noshow) { 
				showDetails(current['candidate'], 'candidate', 1, 1);
			}
		}
	}
	if($('error').visible()) { return; }
}

function findCandidates(newSearch) {
	//$('searchresults').show();
	$('images').innerHTML = "";
	$('candidateInfo').innerHTML = "";
	$('candidateList').innerHTML = "";
	$('graph-title').innerHTML = "";
	$('graph-subtitle').innerHTML = "";
	$('graphcontent').hide();
	if (newSearch) { 
		$('candidateids').value = '';
		$('companyids').value = '';
	}
	params = getFormData();
	if ($('searchtype').value == 'com') {  
		params['com'] = qparams['com'];
	} else {
		params['can'] = qparams['can'];
	}

	params['search'] = 1;
	requests[requests.length+1] = new Ajax.Request('request.php', {
	method: 'get',
	parameters: params,
		onComplete: function(resp) { 
			pageTracker._trackPageview('request.php?'+$H(params).toQueryString());
			checkResponse(resp);
			$('foundCandidates').innerHTML = html; 
			$('searchload').innerHTML = ''; 
			$('searchload').hide();
			var resultsnum = $('foundCandidates').getElementsByTagName('li').length;
			if (resultsnum == 0 && ! qparams['searchtype']) {
				//we don't know if it is a company or politician, so say neigher
				$('companytab').removeClassName('active');
			} else if (resultsnum == 1 || qparams['district'] || qparams['zip']) {
				//if only one result returned, just display it
				$('foundCandidates').getElementsByTagName('a')[0].onclick();
				if (qparams['can']) { delete qparams['can']; } 
				if (qparams['com']) { delete qparams['com']; } 
			} 
			if (resultsnum == 0) { 
				$('foundCandidates').innerHTML += '<div style="margin: 0 auto; width: 285px;"><h3>Search</h3> <form id="search" class="search" action="view.php" onsubmit="if ($(\'search404\').value.match(/^Enter /) || $(\'search404\').value == \'\') { return false; }"> <input id="search404" type="text" name="searchvalue" onfocus="this.value=\'\';" value="Zipcode, Politican, Company" /><input type="submit" class="button" value="Search"/> <input type="hidden" name="search" value="1"/> <input type="hidden" name="type" value="search"/> <input type="hidden" class="button" /> </form></div>';
			}
			if (resultsnum == 1) { 
				$('foundCandidates').hide();
			} else { 
				$('foundCandidates').blindDown();
				$('summary').setStyle({borderRadius: '0px', MozBorderRadius: '0px'}); 	
			}
				
		} 
	});
}

//this function formats the overall "summary" header for companies and politicians
function showSingleDetails(id, type, racecode) {
	loading('searchload');
	$('extras').hide();
	$('infographic').hide();
	$('action').hide();
	$('summary').hide();
	$('vote_history_wrapper').hide();
	if (type == 'can') { 
		longtype='candidate';
	} else { 
		longtype='company';
	}
		
	$('graphcontent').show();
	if (longtype == 'candidate') { 
		ctables = 'cotables'; 
		$('tables').hide();
		otype = 'com';
	} else { 
		ctables = 'tables';
		$('cotables').hide();
		otype = 'can';
	}
	$(ctables).show();
	maxyear = 'total';
	if ($('l'+current[longtype])) { 
		$('l'+current[longtype]).removeClassName('selected');
	}
	['network', 'candidate', 'company', 'congress_num', 'edge'].each(function(t) { current[t] = ''; } );
	current[longtype] = id;
	//$('congress_num').setAttribute('value', maxyear);
	if (type == 'can') {
		$('racecode').setAttribute('value', racecode);
	} else if (type == 'com') { 
		$('racecode').setAttribute('value', 'C');
	}	
	/*
	params = getFormData();
	params[longtype+'ids'] = id;
	params['congress_num'] = 'total';
	if (qparams['congress_num']) { 
		params['congress_num'] = qparams['congress_num'];
	}
	lookupGraph(params);
	*/
	$(longtype+'List').style.display = 'none';
	$(longtype+'Info').setStyle({'float': 'none', 'margin': '0px auto', 'display': 'block'}); 
	$(longtype+'ids').setAttribute('value', id);
	$('congress_num').setAttribute('value', params['congress_num']);
	//showDetails(id, longtype, 1);
	$('l'+id).addClassName('selected');
	
	//Fetch the details view of the selected candidate/company
	details_params = {};
	details_params['search'] = 1;
	details_params[longtype+'id'] = id;

	congress_num = 'total';
	if (qparams['congress_num']) { 
		congress_num = qparams['congress_num'];
		delete qparams['congress_num'];
	} 
	loadData(id, congress_num, 'C', type);
	//loadData(id, congress_num, $('racecode').value, type);

	requests[requests.length+1] = new Ajax.Request('request.php', {
		method: 'get',
		parameters: details_params,
		onComplete: function(resp) { 
			pageTracker._trackPageview('request.php?'+$H(params).toQueryString());
			checkResponse(resp);	
			$('searchload').innerHTML = '';
			$('searchload').hide();
			$('graph-title').innerHTML = candidateproperties['name'];
			document.title = "Dirty Energy Money: "+candidateproperties['name'];
			if (candidateproperties['party']) { 
				$('graph-title').innerHTML+= ' <span class="party-state '+candidateproperties['party']+'">('+candidateproperties['partystate']+')</span>';
				$('graph-subtitle').innerHTML = candidateproperties['title'];
				if (candidateproperties['voting_record']['score']!=null){
					$('vote_history_list').update(candidateproperties['voting_record']['history']);
					$('vote_history_wrapper').show();
					$('vote_history_title').update('Dirty Energy Voting Record for '+candidateproperties['name']);
					$('profile_vote_score').update(candidateproperties['voting_record']['score']+'% of selected votes');
					$('profile_vote_score_link').show();
				}
			} else { 
				$('graph-subtitle').innerHTML = ' <span class="industry '+candidateproperties['sitecode']+'">'+candidateproperties['sitecode']+'</span>';
			}
			
			$('profileimage').setAttribute('src', candidateproperties['image']);
			$('profileimage').show();
			$('profilecash').innerHTML = '$'+candidateproperties['nicetotal'];
			$('profilecash').show();
			$('profilelinks').innerHTML=candidateproperties['profilelinks'];
			$('profilelinks').show();
			$('summary').show();
			$('extras').show();
			$('infographic').show();
			$('action').show();
			loadInfoGraphics(longtype);
			$('congresslist').innerHTML = candidateproperties['congresslist'];
			$(id+congress_num).addClassName('selected');
			//$('candidatedetails').innerHTML = resp.responseText; 
			//$(id+maxyear).addClassName('selected');
			//loadtitle('total');
		} 
	});
}

function loadData(id, congress_num, racecode, type) {
	if (type == 'can') { 
		otype = 'com'
		longtype='candidate';
		olongtype='company';
	} else { 
		otype = 'can'
		longtype='company';
		olongtype='candidates';
	}
	if(typeof racecode == 'undefined') { racecode = 'H'; }

	params = getFormData();
	params[longtype+'ids'] = id;
	params['type'] = longtype;
	params['racecode'] = racecode;
	params['congress_num'] = congress_num;
	if( $(current[longtype]+$('congress_num').getAttribute('value')) ) {
			$(current[longtype]+$('congress_num').getAttribute('value')).removeClassName('selected');
	}
	$('congress_num').setAttribute('value', congress_num);
	$('racecode').setAttribute('value', racecode);
	if ($(id+congress_num)) { 
		$(id+congress_num).addClassName('selected');
	}
	loadtitle(congress_num);
	///FIXME?
	//$(current['view']).show();
	lookupGraph(params);
	$(longtype+'List').style.display = 'none';
	$(longtype+'Info').setStyle({'float': 'none', 'margin': '0px auto', 'display': 'block'}); 
	if (qparams[otype]) { current[olongtype] = qparams[otype];  delete qparams[otype]; }
	if (qparams['v']) { 
		toggleDisplay(qparams['v']); 
		delete qparams['v']; 
	} else {
		showDetails(id, longtype);
	}	
}

function loadtitle(congressnum) {
	var subtitle="";
	var title="";
	if(qparams['search'] || qparams['type'] == 'search') {
		return;  //WTF?  if so, why is there still code after this?
		if ($('searchtype').value == 'com') { 
			direction = ' from ';
		} else { 
			direction = ' to ';
		}
		title = 'Contributions '+direction+$('selectedcandidatename').innerHTML;
		if (congressnum == 'total') { 
			title+= " since 1999"; 
		} else if (congressnum == 'pre') { 
			title+= ' before taking office'; 
		} else { 
			title+= ' during the '+congressnum+'th congress'; 
		}
	} else {
		var race = $F($('form').racecode);
		var raceopts = advanced_opts[$F($('form').sitecode)][$('congress_num').value][race];
		contribamount = numberFormat(raceopts['minContribAmount'][$('contribFilterIndex').value]);	
		candidateamount = numberFormat(raceopts['minCandidateAmount'][$('candidateFilterIndex').value]);	
		companyamount = numberFormat(raceopts['minCompanyAmount'][$('companyFilterIndex').value]);	
		if (qparams['type'] == 'presidential') {
			title =  $('congress_num').options[$('congress_num').selectedIndex].innerHTML + ' Presidential Race';
			subtitle = 'Showing contributions greater than '+contribamount+', candidates receiving more than '+candidateamount+', and companies giving more than '+companyamount+'.';
		} else {
			qparams['type'] = 'congress';
		    current['congress_num'] = congressnum; //this is a hack to deal with the fact that we are passing with a global
			chamber = 'Senate';
			if (race == 'H') { chamber = 'House'; }
			title = $('congress_num').options[$('congress_num').selectedIndex].innerHTML +" "+chamber ;
			industry = sitecode == 'carbon' ? 'Dirty Energy' : sitecode;
			subtitle = 'Showing '+ industry + ' contributions greater than '+contribamount+', members receiving more than '+candidateamount+', and companies giving more than '+companyamount+'.';		
		}	
	}
	$('graph-title').innerHTML = title;
	$('graph-subtitle').innerHTML = subtitle;
	loadInfoGraphics(qparams['type'],congressnum);
}

//ERRCODE 1 = everything ok, should not be here
//ERROR CODE 2 =  missing file on server
//ERROR CODE 3 = empty graph
function reportError(code, message){
	$$('.loading').each ( function (e) { $(e).remove(); }); //remove any loading images
	Effect.Fade('imagescreen',  {duration: .5});
	
	if (code == 3) {   //deal with empty graph
		$('images').innerHTML = "<div class='norelationships'>Great! We didn't find any Dirty Energy relationships to display for this politician.</div>";
/*
		['graphs', 'tables', 'cotables', 'help'].each(function (div) { $(div).hide(); });
		['images', 'candidateList', 'candidateInfo', 'companyList', 'companyInfo'].each(function(div) {
				if ($(div)) { $(div).innerHTML = ''; }
		});
		//$('images').innerHTML = "";
		//$('error').show();
		*/
		return;
	}
	//ALL OTHER ERROR STATES
   title = "An error occurred:";
   subtitle = message.escapeHTML()+" [Error code "+code+" ]" ;
   	$('error-title').innerHTML = title;
	$('error-text').innerHTML = subtitle;
	$('images').innerHTML = "<span id='loading'><span style='vertical-align: middle;' class='message'>Network image was not loaded</span></span>";
	$('error').show();
}



function updateOptions(readurl) {
	if (readurl && qparams['c']) { qparams['congress_num'] = qparams['c']; delete qparams['c']; } //This is because I goofed, and urls went out with this param, so we need to handle it
	if (readurl) {
		if (!advanced_opts[qparams['sitecode']]) { qparams['sitecode'] = 'carbon';}
		if (!advanced_opts[qparams['sitecode']][qparams['congress_num']]) { qparams['congress_num'] = $('congress_num').options[0].value;}
		//if (!advanced_opts[qparams['sitecode']][qparams['congress_num']][qparams['racecode']]) { qparams['racecode'] = 'S';}
	}
	if (readurl && qparams['congress_num']) {
		congress_num = qparams['congress_num'];
		$('congress_num').value = congress_num;
		current['congress_num'] = congress_num;
	} else { congress_num = $F('congress_num'); }
	if (readurl && qparams['racecode']) {
		race = qparams['racecode'];
		Field.setValue($('form').racecode, race);
	} else { race = $F($('form').racecode); }
	if (readurl && qparams['sitecode']) {
		sitecode = qparams['sitecode'];
		Field.setValue($('form').sitecode, sitecode);
	} else { sitecode = $F($('form').sitecode); }
	if (! readurl) { oldopts = raceopts; }
	raceopts = advanced_opts[sitecode][congress_num][race];

	labels = new Array('25', '50', '75');

	['company', 'candidate', 'contrib'].each( function(r) {
		var amount = r+'FilterIndex';
		oldValue = $(amount).value;
		if (readurl) { 
			var defaultValue = 0;
			if (qparams[amount]) {
				defaultValue = qparams[amount];
				$(amount).value = defaultValue;
			} else if ($F($('form').racecode) == 'P' && r == 'candidate') { 
				defaultValue = 2;
				$(amount).value = defaultValue;
				$(r+'_range').innerHTML = '75%';
			}
			var slider = new Control.Slider(r.toLowerCase()+'Handle', amount+'Slider', {'values': [0, 1, 2], range: $R(0,2), sliderValue: defaultValue,
				onChange: function(value) { 
					$(r+'_range').innerHTML = ((value+1)*25)+'%';
					//var newValue = raceopts[amount][value];
					$(amount).value = value;
					loadform();
					//$('submitbutton').click();
				},
				onSlide: function(value) {
					$(r+'_range').innerHTML = ((value+1)*25)+'%';
				}
			});
		}
		$(amount).value = defaultValue;
		if (! $(amount).value || $(amount).value == 'undefined') { 
			oldIndex = 0;
			if (typeof oldopts != 'undefined') { 
				oldIndex = oldValue;	
			}
			$(amount).value = oldIndex; 
		}
	});
}

// This function formats numbers by adding commas
function numberFormat(nStr){
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1))
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  return '$'+x1 + x2;
}

//called by share this, and also when the page first loads
function updateLink() {
	var url = window.location.href.replace(window.location.search, '?');
	url = url.replace('#', '');
	params = getFormData();
	params['type'] = qparams['type'];
	if (current['view'] && params['type'] != 'search') { params['v'] = current['view']; }
	if (current['company']) { params['com'] = current['company']; }
	if (current['candidate']) { params['can'] = current['candidate'] ; }
	['candidateids', 'companyids', 'candidatename', 'companyname', 'noheader', 'zip'].each (function(p) { delete params[p]; });
	var cgi = $H(qparams);
	cgi.update($H(params));
	url+= cgi.toQueryString();
	//= url;
	//set up the bit.ly stuff
	BitlyCB.alertResponse = function(data) {
		var first_result;
		// Results are keyed by longUrl, so we need to grab the first one.
		for     (var r in data.results) {
				first_result = data.results[r]; break;
		}
		//copy the contentinto the lightbox
		$('lightboxcontents').innerHTML = $('linkbox').innerHTML;
		//fill in the link files
		$('linklink').value =first_result['shortUrl'];
		//also set the twitter and fb link
		$('fblink').href='http://www.facebook.com/sharer.php?u='+encodeURIComponent(first_result['shortUrl'])+'&t='+encodeURIComponent(document.title);
		$('twitlink').href='http://twitter.com/home?status='+encodeURIComponent(document.title)+" "+encodeURIComponent(first_result['shortUrl']);

	 //and set the widget contents
     widgeparams = "";
     //since it is possible that both are selected, prefer the candidate when on
     //candidate page and vs versa... actually this just sets to show comps on company pages, cans on candidate, and cong on cong
     if (typeof(candidateproperties) != 'undefined' && candidateproperties['type'] == 'company'){
		 if (current['company']){
			widgeparams = "?com="+current['company'];
		 } else if (current['candidate']){
			widgeparams = "?can="+current['candidate'];
		 }
     } else {
     	 if (current['candidate']){
			widgeparams = "?can="+current['candidate'];
		 } else if (current['company']){
			widgeparams = "?com="+current['company'];
		 } 
     }
	var url = window.location.href.replace('view.php'+window.location.search, '/w/index.php');
     
     widgetext = "<iframe src ='"+url+widgeparams+"' width='160px' height='201px'>Widget not working? Vist <a href='http://dirtyenergymoney.com' target='_blank'>http://dirtyenergymoney.com</a></iframe>";
	$('widgetholder').innerHTML = widgetext;
	$('widgetcode').value = widgetext;
		
     }
     BitlyClient.call('shorten', {'longUrl': url}, 'BitlyCB.alertResponse');
     
    
	
	return url;
}

function killRequests() {
	requests.each(function(r, index) {
		if (! r) { return; }
		if (r.transport && r.transport.readyState != 4) { 
			r.abort();
		}
		requests.splice(requests.indexOf(r), 1);
		return; 
	});
}

function initSVG() {
	if (useSVG != 1 ) { return; } 
	nodelookup = new Hash();
	edgelookup = new Hash();
	current['network'] = null;
	$('svg').style.setProperty('position','absolute', '');
	$('svg').style.setProperty('top','2px', '');
	$('svgscreen').style.setProperty('cursor','default', 'important');
	Event.observe($('svgscreen'),'click', hideNetwork);
	Event.observe($('svg'), 'mousemove', mousemove);
	$$('.node').each( function(n) {
		if (! nodelookup[n.id]) { nodelookup[n.id] = new Array(); }
		nodelookup[n.id]['id'] = n.id;
		if (n.childNodes[1]) {
			Event.observe(n,'mouseover', function(e) { eval(graphviz[n.id].onMouseover); });
			Event.observe(n,'mouseout', function(e) { unhighlightSVGnode(n.id); });
			Event.observe(n,'click', function(e) { eval(graphviz[n.id].onClick); });
		}
	});
	$$('.edge').each( function(n) {
		edgeid = n.id;
		if (! edgelookup[edgeid]) { edgelookup[edgeid] = new Array(); }
		edgelookup[edgeid]['id'] = edgeid;
		nodes = edgeid.split('_');
		if (! nodelookup[nodes[0]]) { nodelookup[nodes[0]] = new Array(); nodelookup[nodes[0]]['id'] = 'fake'+nodes[0]}
		if (! nodelookup[nodes[1]]) { nodelookup[nodes[1]] = new Array(); }
		if (! nodelookup[nodes[0]]['edges']) { nodelookup[nodes[0]]['edges'] = {}; }
		if (! nodelookup[nodes[1]]['edges']) { nodelookup[nodes[1]]['edges'] = {}; }
		if (! nodelookup[nodes[0]]['lnodes']) { nodelookup[nodes[0]]['lnodes'] = {}; }
		if (! nodelookup[nodes[1]]['lnodes']) { nodelookup[nodes[1]]['lnodes'] = {}; }
		nodelookup[nodes[0]]['edges'][edgeid] = 1
		nodelookup[nodes[1]]['edges'][edgeid] = 1;
		nodelookup[nodes[0]]['lnodes'][nodes[1]] = 1;
		nodelookup[nodes[1]]['lnodes'][nodes[0]]= 1;
		Event.observe(n,'mouseover', function(eventObject) { eval(graphviz[n.id].onMouseover); });
		Event.observe(n,'mouseout', hideTooltip, 1);
		Event.observe(n,'click', function(eventObject) { eval(graphviz[n.id].onClick); });
		//Event.observe(n,'click', graphviz[n.id].onClick);
	});
	$('graph0').style.setProperty('opacity', '1', '');
	$('svg').style.setProperty('visibility', 'visible', '');
	var left = Math.round((parseInt($('graphs').getStyle('width')) - $('svg').childNodes[0].getAttribute('width').replace('px', ''))/2);
	$('svg').style.setProperty('left',left+'px' , '');
	$('svg').style.setProperty('display', 'block','');
	//$('graphs').style.height = $('svg').childNodes[0].getAttribute('height');
	//$('svg').clonePosition($('img0'), {'setLeft': true});
}

function unhighlight(id) { 
	if (useSVG) { 
		unhighlightSVGnode(id);
	} else {
		hideTooltip();
	}
}

function highlightSVGnode(id) {
	var node = $(id).childNodes[3];
	node.setAttribute('class', 'nhighlight');
	if (current['network']) { 
		//$(id).parentNode.appendChild($(id));
	}
	$(id).style.setProperty('opacity', '1', 'important');
}

function unhighlightSVGnode(id) {
	if (! useSVG) { return; }
	hideTooltip();
	var node = $(id);
	node.childNodes[3].removeAttribute('class');
	if (current['network'] == id || (nodelookup[current['network']] && nodelookup[current['network']]['lnodes'][id] == 1)) {
		return;
	} else {
		node.style.removeProperty('opacity');
	}
}
function showNetwork(id) {
	var node = $(id);
	if (! node) { return; }
	if (current['network'] == node.id) { 
		hideNetwork();
		highlightSVGnode(node.id);
		return;
	}
	if (current['edge']) { 
		hideEdge(1);
	}
	if (current['network']) { 
		hideNetwork(1);
	}
	if ($('img0').getOpacity() == 1) {
		new Effect.Opacity('img0', { from: 1, to: .3, duration: .5});
	}
	node.style.setProperty('opacity', '1', 'important');
	$H(nodelookup[node.id]['edges']).keys().each(function(e) {
		$(e).style.setProperty('opacity', '1', 'important');
	});
	$H(nodelookup[node.id]['lnodes']).keys().each(function(e) {
		$(e).style.setProperty('opacity', '1', 'important');
	});
	current['network'] = node.id	
}

function showEdge(com, can) {
	edgename = com+'_'+can;
	if (current['network']) { 
		hideNetwork(1);
	}
	if (current['edge']) { 
		hideEdge(1);
	}
	if(useSVG) { 
		cannode = $(can);
		comnode = $(com);
		if ($('img0').getOpacity() != '0.3') {
			new Effect.Opacity('img0', { from: 1, to: .3, duration: .5});
		}
		cannode.style.setProperty('opacity', '1', 'important');
		comnode.style.setProperty('opacity', '1', 'important');
		$(edgename).style.setProperty('opacity', '1', 'important');
	}
	if($('t'+current['candidate']) && current['candidate'] != can) {
		$('t'+current['candidate']).removeClassName('selected');
	}
	if($('t'+current['company']) && current['company'] != com) {
		$('t'+current['company']).removeClassName('selected');
	}
	if(qparams['type'] == 'search') { 
		if ($('c'+com)) {
			$('c'+com).addClassName('selected');
			if ($('c'+current['company'])) { $('c'+current['company']).removeClassName('selected'); }
		}
		if ($('c'+can)) {
			$('c'+can).addClassName('selected');
			if ($('c'+current['candidate'])) { $('c'+current['candidate']).removeClassName('selected'); }
		}
	}
	current['candidate'] = can;
	current['company'] = com;
	current['edge'] = edgename
}

function hideEdge(noshowimage) {
	if (useSVG && current['edge']) { 
		if(! noshowimage) { 
			new Effect.Opacity('img0', { from: .3, to: 1, duration: .3});
		}
		if( current['edge'] != null){
		nodes = current['edge'].split('_');
			$(current['edge']).style.removeProperty('opacity');
			$(nodes[0]).style.removeProperty('opacity');
			$(nodes[1]).style.removeProperty('opacity');
		}
	}
	current['edge'] = '';
}

function hideNetwork(noshowimage) {
	if (! useSVG) { return; }
	noshowimage = noshowimage == 1 ? 1 : 0; //cuz sometimes we get event object
	if (current['edge']) {
		hideEdge(noshowimage);
	}
	if (! noshowimage && $('img0').getOpacity() != '1') {
		new Effect.Opacity('img0', { from: .3, to: 1, duration: .3});
	}
	if (current['network']) { 
		$(current['network']).style.removeProperty('opacity');
		$H(nodelookup[current['network']]['edges']).keys().each(function(edge) {
			$(edge).style.removeProperty('opacity');
		});
		$H(nodelookup[current['network']]['lnodes']).keys().each(function(node) {
			$(node).style.removeProperty('opacity');
		});
	}
	current['network'] = null;
}

function searchHelp(hide) {
	currenttype = 'can';
 	if ($('navsearch').getInputs('radio')[1].checked) {
		currenttype = 'com';
	}
	if ($('navsearchvalue').value.match(/^Enter /) || $('navsearchvalue').value == '') {
		value = '';
		if (hide) {
			$('navsearchvalue').removeClassName('searchhelp');
		} else {
			$('navsearchvalue').addClassName('searchhelp');
			if (currenttype == 'can') {
				value = 'Enter Name or Zip Code';
			} else {
				value = 'Enter Company Name';
			}
		}
		$('navsearchvalue').value = value;
	}
}

function loadInfoGraphics(longtype,congressnum) {
	var graphics = {
		'congress': {
			'industries': 'Dirty energy contributions to the NAMEth congress by industry.',
			'party': 'Dirty energy contributions to the NAMEth congress by party.' 
		},
		'company': {
			'party': 'NAME\'s contributions by party',
			'timeline': 'Contributions from NAME by congress term'
		},
		'candidate': {
			'industries': 'NAME\'s dirty energy money by industry',
			'pacs': 'NAME\'s dirty energy money by contributor type', 
			'timeline': 'Dirty energy money accepted by NAME per term',
			'categories': 'NAME\'s dirty energy money by category'
		}
	}
	$('graphics').innerHTML = "";
	url = 'cache/summarychart/';
	type = '';
	if (qparams['type'] == 'congress') { 
		url += 'congresses/';
		value = congressnum;
		name = congressnum;
		type = 'congress';
	} else  {
		if (longtype=='candidate'){
			//determine if candidate or company
			url += 'candidates/';
			value = current['candidate'];
			name = candidateproperties['lastname'];
			type = 'candidate';
		} else if (longtype=='company') {
			url += 'companies/';
			name = candidateproperties['name'];
			value = current['company'];
			type = 'company';
		}
	} 
	if (type && graphics[type]) { 
		$H(graphics[type]).keys().each(function(g) {
			var div = document.createElement('div');
			var img = document.createElement('img');
			div.setAttribute('id', 'graphic'+g);
			text = graphics[type][g].replace(/NAME/, name);
			div.innerHTML = '<span>'+text+'</span>';
			img.setAttribute('src', url+g+'/'+value+'.png');
			$('graphics').insert(div);
			$(div).insert(img);
		});
		//new PeriodicalExecuter(rotateChart, 5);
	}
}

function rotateChart() {
	if ($('tempgraphic')) { return; }
	div = $('graphics');
	count = div.getElementsByTagName('img').length;
	divwidth = $('infographic').getWidth();
	left = div.style.left ? Math.abs(parseInt(div.style.left)) : 0;
	width = 0-(Math.ceil((left/divwidth)+1))*divwidth;
	if (width <= (0-count*divwidth)) { 
		copy =  $(div.getElementsByTagName('div')[0]).clone(1);
		copy.id = 'tempgraphic';
		$('graphics').insert(copy);
		new Effect.Move($('graphics'), {x: width, mode: 'absolute', 
			afterFinish: function() {
				div.setStyle({'left': '0px'});
				$('tempgraphic').remove();
			}
		});
	} else { 
		new Effect.Move($('graphics'), {x: width, mode: 'absolute'});
	}
}

function sortList(type, property, reverse) { 
	if (type == 'Com') { 
		ltype = 'company';
	} else { ltype = 'candidate'; }
	list = $(ltype+'List');
	prefix = 't';
	if (! list.firstChild) { 
		list = $(ltype+'Info');
		prefix = 'c';
	}
	var keys = $H(graphviz).keys();
	if (! reverse ) { keys = keys.reverse(); }
	keys = keys.sortBy(function(s) {
		var node = graphviz[s];
		if (node['type'] != type) { return 'ZZZZ'; }
		if (property == 'cash') { 
			value = parseInt(node[property]);
		} else { 
			value = node[property];
		}
		return value;
	});
	if (reverse) { keys = keys.reverse(); }

	odd = 'odd';
	keys.each(function (k) { 
		if (graphviz[k]['type'] != type) { return; }
		list.firstChild.appendChild($(prefix+k));
		if (odd == 'odd') { 
			$(prefix+k).addClassName('odd');
			odd = '';
		} else {
			$(prefix+k).removeClassName('odd');
			odd = 'odd';
		}
	});
	return;
}

function showCSVLink() {
	lparams = getFormData();
	lparams['csv'] = 1;
	new Array('candidateLimit', 'companyLimit', 'candidateFilterIndex', 'companyFilterIndex', 'contribFilterIndex').each( function(k) {
		delete lparams[k];
	});
	lparams['sitecode'] = 'carbon';
	var link = $H(lparams).toQueryString().escapeHTML();
	$('lightboxcontents').innerHTML = '<h2>CSV Data Download</h2>Oil Change International has aggregated this data from data made available by the <a href="http://opensecrets.org">Center for Responsive Politics</a> under a <a href="http://creativecommons.org/licenses/by-nc-sa/3.0/">Creative Commons license</a>. In short, you can remix, tweak and build upon their work non-commercially, as long as CRP are credited and your new creation is licensed under the identical terms. Proper crediting guidelines can be found <a href="http://www.opensecrets.org/action/credit.php">here</a>.<p style="padding: 10px; text-align: center;"> <a class="download button" onclick="hideLightbox();" href="request.php?'+link+'">Download CSV Data</a></p><img src="images/opensecrets_databy150x53.gif" />';
	showLightbox();
}

function showDollars(id) {
	$('lightboxcontents').innerHTML = "<h2>Souvenir Dirty Energy Dollar</h2><p>Yup, you can print out this image as a convenient way to remember who's interests politicians are representing in Congress.</p><a href='dollars/"+id+"_dollar.pdf'><img src='dollars/"+id+"_dollar.jpg' /></a><a href='dollars/"+id+"_dollar.pdf' class='download button'>Download Dirty Energy Dollar</a>";
	$('lightbox').setStyle({'width': '600px'});
	showLightbox();
} 

function showLightbox() {
	Effect.Appear('lightbox', {duration: .5});
	Effect.Appear('screen', {duration: .5, to: .5});
}

function hideLightbox() {
	Effect.Fade('lightbox',{duration:.3});
	Effect.Fade('screen', {duration: .3});
}

function showSecondaryDetails(id) {
	type = 'candidate';
	if (graphviz[id]['type'] == 'Com') { 
		type = 'company';
	}
	if (qparams['type'] == 'search') { 
		selectNode(id, 1);
	} else {
		if ($('c'+current[type]+'Details')) {
			$('c'+current[type]+'Details').hide();
		}
		$('c'+id+'Details').toggle();
		current[type] = id;
	}
}

function initQueryParams() {
	if (qparams['can']) { 
		current['candidate'] = qparams['can']; 
		delete qparams['can'];
	}
	if (qparams['com']) { 
		current['company'] = qparams['com']; 
		delete qparams['com'];
	}
	if (qparams['v']) { 
		toggleDisplay(qparams['v']); 
		delete qparams['v'];
	}

	if (current['candidate'] && current['view'] == 'tables') { 
		selectNode(current['candidate']);
	} else if (current['company'] && current['view'] == 'cotables') { 
		selectNode(current['company']);
	}
}

Event.observe(window, 'load', function() {
	if ($$('#searchvalue[type=text]')[0]) {
		var quicksearchtype = ''
		if ($('searchvalue').hasClassName('can')) {
			quicksearchtype = 'can';
		} else if ($('searchvalue').hasClassName('com')) {
			quicksearchtype = 'com';
		}
		$('round_loading').clonePosition($('searchvalue'), {setWidth: false, setHeight: false});
		$('round_loading').setStyle({'marginTop': parseInt(($('searchvalue').getHeight()-$('round_loading').getHeight())/2)+'px'});

		new Ajax.Autocompleter('searchvalue', 'searchlist', 'request.php', {
			parameters: 'searchtype=quick&search=1&quicksearchtype='+quicksearchtype,
			select: 'searchstring',
			indicator: 'round_loading',
			afterUpdateElement: function(text, li) {
				$('searchzip').setValue('');
				$('searchcom').setValue('');
				$('searchcan').setValue('');
				var id = li.id.substr(2);
				if (id == 'ank') {
					var value = this.parameters.replace(/searchvalue=([^&]+)&.*/, "$1");
					$('searchvalue').setValue(value);
					$('searchvalue').parentElement.submit();
					return;
				}
				if (li.hasClassName('zip')) {
					$('searchzip').setValue(id);
				} else if(li.hasClassName('company')) {
					$('searchcom').setValue(id);
				} else {
					$('searchcan').setValue(id);
				}
			},
			callback: function(input, query) {
				$('searchzip').setValue('');
				$('searchcom').setValue('');
				$('searchcan').setValue('');
				return query;
			}
		});
	}
});

