//	console.log();

	var default_companies = ['cw_825', 'cw_391', 'cw_1688'];
	var search_limit = 250;
	var locations; 
	var map;
	var bounds;
	var redIcon;
	var company_locations = [];
	var companies = [];
	var current_company;
	var current_parent;
	var current_year;
	var default_year = 2008;
	var markers;
	var filingstimeout;
	var timelinetimeout;
	var timeline_content="";
	var company_notes = null;
	var requests = [];
	var company_years = [];
	var visible_lis;
	var debug = 0;
	var selectedmarker;
	//if (window.console) { debug = 1; }

	function toggleLoading(div, loading) {
		if (!loading  && $(div+'_loading')) {
			$(div+'_loading').remove();
		} else if (loading && ! $(div+'_loading')) {
			var loading = document.createElement('div');
			loading.setAttribute('id', div+'_loading');
			loading.setAttribute('style', 'position: absolute; background-color: #ffffff;');
			$(div).parentNode.insert(loading);
			loading.innerHTML = "<div style='margin: auto; text-align: center; margin: 10px;'><img src='img/loading.gif'> Loading...</div>";
			Position.clone(div, loading);
			loading.setStyle({'zIndex': '1000'});
		}
		return;
			if ($(div).hasClassName('loading')) {
			$(div).removeClassName('loading');
			$(div).innerHTML = "";
		} else {
			$(div).addClassName('loading');
			$(div).innerHTML = "<div style='margin: auto; text-align: center; margin: 10px;'><img src='img/loading.gif'> Loading...</div>";
		}
	}

	function initialize() {
		toggleLoading('info', 1);
		$('info').setStyle({'visibility': 'visible'});
		toggleLoading('tree', 1);
		if(debug) {console.time('init'); }
        dhtmlHistory.initialize();
        dhtmlHistory.addListener(historyListener);
		bounds = new GLatLngBounds();
		redIcon = new GIcon(G_DEFAULT_ICON);
		G_NORMAL_MAP.getMaximumResolution = function() { return 7; }
		if (GBrowserIsCompatible()) {
			map = new GMap2(document.getElementById("map_canvas"));
			var ui = map.getDefaultUI();
			ui.controls.menumaptypecontrol = false;
			map.setUI(ui);
			map.setCenter(new GLatLng(37.02009820136811,-91.0546875), 0);
		}
		resizeResults();
		$$('.helpbox').each( function(elem) {
			elem.observe('mouseover', showHelp);
			elem.observe('mouseout', hideHelp);
		});
		for (var c in locations) {
			var option = new Option(locations[c]['name'], locations[c]['code']);
			$('countrycodesearch').options.add(option);
		}
		for (var g in groups) {
			for (var s in groups[g]['sectors']) {
				var sector = groups[g]['sectors'][s];
				var option = new Option(sector['name'], sector['code']);
				$('sicsector').options.add(option);
			}
		}
		var year;
		var parent;
		var company;
		//if (dhtmlHistory.isFirstLoad()) {
			var location = dhtmlHistory.getCurrentLocation();
			if (location) { 
				company = location.split(',')[0];
				parent = location.split(',')[1];
				year = location.split(',')[2];
			}
			//deal with case where year not set, so defaults to most recent
			
		//}
		if (typeof(year) == 'undefined'){ year = '';}
		//If there's nothing in the url, we give a random company from default_companies
		if (! parent) {
			company = default_companies[Math.floor(Math.random()*default_companies.length)];
			parent = company;
			year = 2009;
		}

		if(debug) { console.timeEnd('init'); }
		showSubsidiaries(company, parent,year);
	}

	function processTree(tree) {
		var list = "";
		for (var cw_id in tree) {
			if (typeof(tree[cw_id]) != 'object') { continue; }
			var company = tree[cw_id];
			if (! company['subdiv_code']) {
				company['subdiv_code'] = 'null';
			}
			sublist = "";
			//recursively process all the branches with children
			if (company['num_children'] > 0) {
				sublist = processTree(company['children']);
				delete(company['children']);
			}
			//prepend the html for this elment before all the elements below it
			list = list + "<li id='l_"+cw_id+"' style='display:none;'>"+ formatCompany(company) + sublist+"</li>\n";
			var location = company['country_code']+'_'+company['subdiv_code'];
			if (! company_locations[location]) { 
				company_locations[location] = [];
			}
			company_locations[location].push(company['cw_id']);
			companies[cw_id] = company;
		}
		return "\n<ul>\n"+list+"</ul>\n";
	}
	
	function getULid(e) {
		return e.id.substr(2);
	}

	function formatCompany(company) {
		var more = "";
		var subcount = "";
		if (company['num_children'] > 0) {
			more = "<img class='more' src='img/plus.gif' />";
			subcount = "&nbsp;<small>("+company['num_children']+")</small>";
		//TODO: fix this so it is total number of subsidiaries, not just immediate children
		}
		output = "<div class='tree_element' id='"+company['cw_id']+"' onClick='highlightCompany(this.id);' onmouseover=\"this.setStyle({background:'#BCE27F'});\" onmouseout=\"this.setStyle({background:''});\"><img class='issue_comment' src='img/issue-comment.gif' />"+more+company['company_name']+subcount+"</div>";
		return output;
	}

	function selectCompany(cw_id) {
		$('tree').scrollTop = $(cw_id).offsetTop;
		highlightCompany(cw_id);
	}

	function resizeResults() {
		$('results').setStyle({'height': $('companydisplay').getHeight()- $('searchform').getHeight() -105+'px'});		
	}

	
	function highlightCompany(cw_id, notnew) {
		if(debug) { console.time('highlight'); }
		if (filingstimeout) { clearTimeout(filingstimeout); }
		if (timelinetimeout) { clearTimeout(timelinetimeout); }
		$('tree').scrollTop = 0;
		if ($('company_list').visible()) { 
			Effect.Fade($('company_list'), { duration: .2 });
		}
		
		if ( ! current_company || cw_id != current_company) { //We need to load a new company
			killRequests(1);
			toggleLoading('info', 1);
			$('timeline').innerHTML = "";
			showTimeline(cw_id, current_year);
		}

		$($(cw_id).parentNode).addClassName('highlighted');
		if(debug) { console.time('getvisible'); }

		var oldparents = visible_lis;
		visible_lis = new Hash();
		var new_li = $($(cw_id).parentNode);
		//find the parents of the highlighted node
		var temp_li = new_li;
		while (temp_li.id != 'treetop') {
			if (temp_li.nodeName == 'LI') {
				visible_lis.set(getULid(temp_li), 1) 
			}
			temp_li = $(temp_li.parentNode);	
		}
		visible_lis.set(cw_id, 1);
		//find the children of the highlighted node
		if (new_li.childElements()[1]) {
			new_li.childElements()[1].childElements().each(function(elem) {
				var e = getULid(elem);
				visible_lis.set(e, 1);	
			});
		}
		var show_fancy = 0;
		var hide_fancy = 0;
		if (! Prototype.Browser.IE && visible_lis.size() < 300) { show_fancy = 1; }
		if (! Prototype.Browser.IE && oldparents && oldparents.size() < 300) { hide_fancy = 1; }

		if(debug) { console.timeEnd('getvisible'); }
		if(debug) { console.time('hidecompanies'); }
		if (current_company !=  cw_id) {
			var count = 0;
			if (current_company && $(current_company) && oldparents) {
				//hide the visible elements
				oldparents.keys().each(function(elem_id) {
					if (! $(elem_id)) { return; }
					if (elem_id == cw_id || count > 100) { hide_fancy = 0; } //if the elem appears after the highlighted, just hide it
					if(! visible_lis.get(elem_id)) { 
						var elem = $($(elem_id).parentNode);
						if (hide_fancy) { 
							Effect.BlindUp(elem, { duration: .3 });
						} else { elem.hide(); }
					}
					count++;
				});

				var old_li = $($(current_company).parentNode);
				old_li.removeClassName('highlighted');
						
				var old_company = companies[current_company];
				if (old_company['country_code'] && old_company['country_code'] != 'null') {
					count = company_locations[old_company['country_code']+'_'+old_company['subdiv_code']].length;
					if (count >= 100) { count = 100; }
					markers[old_company['country_code']+'_'+old_company['subdiv_code']].setImage('markers/marker'+count+'.png');
				}
			}
		}
		if (selectedmarker) { selectedmarker.remove(); }
		if(debug) { console.timeEnd('hidecompanies'); }

		//Display the children and parents
		var count = 0;
		if(debug) { console.time('newchilds'); }
		visible_lis.keys().reverse().each( function(id) { 
			if (count > 100) { show_fancy = 0; }
			var elem = $($(id).parentNode);
			if(! elem.visible()) {
				if(show_fancy && count != 0) { 
					Effect.BlindDown(elem, { duration: .4 });
				} else { elem.show(); }
			}
			count++;
		});
		if(debug) { console.timeEnd('newchilds'); }

		if(debug) { console.time('mapstuff'); }
		var c = companies[cw_id];
		count = company_locations[c['country_code']+'_'+c['subdiv_code']].length;
		if (c['country_code'] && c['country_code'] != 'null') {
			//markers[c['country_code']+'_'+c['subdiv_code']].setImage('markers_selected/marker'+count+'.png');
			addSelectedMarker(markers[c['country_code']+'_'+c['subdiv_code']]);
			var loc = getLocation(c['country_code'], c['subdiv_code']);
			map.panTo(new GLatLng(loc['latitude'], loc['longitude']));
		}
		if(debug) { console.timeEnd('mapstuff'); }

		current_company = cw_id;
		insertIssues(cw_id);
		var parent = c['top_parent_id'];
		dhtmlHistory.add(cw_id+','+parent+","+current_year,cw_id+','+parent+","+current_year );
		if(debug) { console.timeEnd('highlight'); }
		pageTracker._trackPageview("/"+current_parent+"/"+cw_id+"/"+current_year);
	}

	function addSelectedMarker(marker) {
		var selicon = redIcon;
		selicon.image = 'markers_selected/marker'+marker.count+'.png';
		selectedmarker = createMarker(marker.getPoint(), marker.getTitle(), selicon, 'selected'); 
		map.addOverlay(selectedmarker);
	}

	//update the contents of the company info panel wih the given cw id. 
	function updateInfo(c) {
		var cw_id = c['cw_id'];
		//
		//company name as header
		//$('info').toggle();
		$('selected_company_name').innerHTML = c['company_name'];
		$('company_raw_address').innerHTML = "";
		$('filings').innerHTML = "";
		$('sec21s').innerHTML = "";
//if (cw_id != current_company) {
//			$('timeline').innerHTML = "";
//		}
		//if in edit mode, add links for crocodul issues
		if (location.href.split('?edit=')[1]) {
			$('edit_options').innerHTML = '<a target="'+cw_id+'" href="http://www.crocodyl.org/node/add/cw-company?edit[field_cw_id][0][value]='+cw_id+"&edit[field_company_name][0][value]="+c['company_name']+"&edit[field_top_parent_id][0][value]="+c['top_parent_id']+'">Add Crocodyl Issue</a><br/>';
		} else {
			$('edit_options').innerHTML = '';
		}
		//if it is a crocodyl company, include a link to the crocodyl profile
		if (croc_companies[cw_id]) {
			$('croc_profile_link').setAttribute('target', cw_id);
			$('croc_profile_link').setAttribute('href', "http://www.crocodyl.org/wiki/"+croc_companies[cw_id]);
			$('croc_profile_link').show();
		} else {
			$('croc_profile_link').hide();
		}
		$('company_raw_address').innerHTML = c['raw_address'];
		if (c['industry_name']) {
			$('company_industry').innerHTML = c['industry_name']+" : "+c['sector_name'];
			$('industy_row').show();
		} else {
			$('industy_row').hide();
		}

		toggleLoading('info', 0);
		//replaceHtml('info', content);	
		
		//send out a request to get a list of the timeline year
		//but if not reloading, no need to wait
		//if (timeline_conent = ""){
		//showTimeline(cw_id,current_year) 
		//} else {
		//timelinetimeout = window.setTimeout(function() { 	showTimeline(cw_id,current_year) }, 1000);
		//}
		//showFilings(cw_id);
		//send out a request to get the list of filings
		showFilings(cw_id,current_year);
		//filingstimeout = window.setTimeout(function() { showFilings(cw_id,current_year) }, 1000);	
		Effect.Appear($('info'), { duration: .8});
		if(debug) { console.log('update complete: ',cw_id); }
		//toggleLoading('filings');
	}

     //asks server (which asks crocodyl site) if there are any issues for this company, then adds the "issues" icon on the tree
	function fetchCrocInfo(cw_id, parent_cw_id) {
		if (! company_notes ) { 
			requests[requests.length] = new Ajax.Request('request.php', {
				method:'get', 
				parameters: {'cw_id':parent_cw_id, 'info':1 },
				onComplete: function(resp) { 
					company_notes = resp.responseJSON;
					setupIssues(company_notes);
					insertIssues(cw_id);
				}
			});
		} else {
			setupIssues(company_notes);
			insertIssues(cw_id);
		}
	}

	function setupIssues(company_notes) {
		$H(company_notes).keys().each ( function(id) {
			if (! $(id) ) { 
				if (debug) { console.log("couldn't flag issue for "+id+" - doesn't exist"); }
				return; 
			}
			$(id).addClassName('hasissue');
			var parent = $($(id).parentNode);
			while (parent.id != 'treetop') {
				if (parent.nodeName == 'LI') {
					var li_id = getULid(parent);
					if (id != li_id) {
						if (! companies[li_id]['issues']) {
							companies[li_id]['issues'] = [];
						} 	
						companies[li_id]['issues'].push(id);
					}
				}
				parent = $(parent.parentNode);	
			}	
		});
	}
		
	//adjusts the tree around to show the appropriate company and its immediate subsidiaries	
	function showSubsidiaries(cw_id, parent_cw_id, year) {
		current_year = year;
		if (cw_id == '') { return; }
		if(debug) { console.time('total'); }

		toggleLoading('tree', 1);
		if ( ! current_company || cw_id != current_company) { //We need to load a new company
			$('timeline').innerHTML ="";  //this will make the timeline reload for a new company
			toggleLoading('info', 1);
		} 

		if(debug) { console.time('clean'); }
		cleanUp(cw_id);  //this resets the current_company, current_year, etc
		hideScreen();
		map.clearOverlays();
		bounds = new GLatLngBounds();
		markers = []
		companies = []
		company_locations = []
		//if parent and child company are not the same, we have to default to 
		if(debug) { console.timeEnd('clean'); }
		
		showTimeline(cw_id, year);
		fetchSubsidiaryTree(parent_cw_id, cw_id, year);

		return false;
	}
	
	function fetchSubsidiaryTree(parent_cw_id, cw_id, year) {
		if(debug) { console.time('fetch_subs'); }
		if ((year == '') & (cw_id != parent_cw_id)){
			year = default_year;
		}
		requests[requests.length+1] = new Ajax.Request('request.php', {
			method:'get', 
			parameters: 'cw_id='+parent_cw_id+'&year='+year,
			evalJSON: 0,
			onComplete: function(resp) { 
				if(debug) { console.timeEnd('fetch_subs'); }
				eval("var results = "+resp.responseText);
				companies = results['companies'];
				company_locations = results['company_locations'];

				replaceHtml('tree', results['ul']);
				results = null;

				//set up the locations on the map
				loadMapMarkers(company_locations);
				$('map_title').innerHTML = "Subsidiary Locations of "+companies[parent_cw_id]['company_name'];
				var zoom = map.getBoundsZoomLevel(bounds);
				if (zoom > 4) { zoom = 4; }
				map.setZoom(zoom);
				
				current_parent =  parent_cw_id;
				if ( year == ''){
					current_year = companies[parent_cw_id]['max_year'];
				} else {
					current_year = year;
				}

				fetchCrocInfo(cw_id, parent_cw_id);
				highlightCompany(cw_id);
				toggleLoading('tree', 0);
				if(debug) { console.timeEnd('total'); }
			}
		});
	}

    //inserts issue html into company profile
	function insertIssues(cw_id) {
		var text = "";
		if (company_notes && company_notes[cw_id]) {
			$('issue_title').show();
			company_notes[cw_id].each( function (info) {
				editlink = "";
				//if we are in edit mode, add links to edit content on crocodyl
				if (location.href.split('?edit=')[1]) {
					editlink = '&nbsp;&nbsp;<a target="'+cw_id+'" href="http://www.crocodyl.org/node/'+info['croc_node_id']+'/edit/>Edit this issue</a>';
				}

				text += '<div class="issue"><img class="issue_comment" src="img/issue-comment.gif"><a href="'+info['url']+'" title="'+info['url_title']+'">'+info['title']+"</a> "+editlink+"<br/>"+info['description']+'</div>';
			});
			$('notes').innerHTML = text;
		} else { 
			$('issue_title').hide();
			$('notes').innerHTML = "";
		}
		var c = companies[cw_id];
		//also show a list of any subsidary companies that have issues
		if (c['issues']) {
			issueshtml = "<h4>Subsidiary companies with issues</h4>";
			issueshtml += "<ul class='company_list'>";
			c['issues'].each( function (id) {
				issueshtml += "<li><a href='#' onClick='highlightCompany(\""+id+"\"); return false;'>"+companies[id]['company_name']+"</a></li>";
			});
			 issueshtml += "</ul>";
			$('subsidary_issue_list').innerHTML = issueshtml;
			$('subsidary_issue_list').show();
		} else { 
			$('subsidary_issue_list').hide(); 
		}
		//$$('.hasissue .issue_comment').each( function(e) {
	//		Event.observe(e,'mouseover', showHelp);
	//		Event.observe(e,'mouseout', hideHelp);
	//	});
	}

	function topMarker(marker, b) { 
		return 100000;
	}

	function createMarker(point, title, icon, id) {
		var marker;
		if (id == 'selected') {
			marker = new GMarker(point, {icon: icon, zIndexProcess:function() { return 10000;}});
		}else {
			marker = new GMarker(point, {icon: icon});
		}
		marker.id = id;
		marker.tooltip = title;
		GEvent.addListener(marker, "mouseover", function() { showMarkerTooltip(marker); });
		GEvent.addListener(marker, "mouseout", function() { 
			if (marker.id != companies[current_company]['country_code']+'_'+companies[current_company]['subdiv_code']) {
				marker.setImage('markers/marker'+marker.count+'.png');
			}
			hideTooltip(); 
		});
		GEvent.addListener(marker, "click", function() { 
			if (!company_locations[marker.id]) { return; }
			var location = company_locations[marker.id];
			var cs = marker.id.split('_');
			var name = "";
			if (location.length == 1) {
				selectCompany(location[0]);
			} else {
				Effect.Appear($('company_list'), { duration: .2 });
				locale = getLocation(cs[0], cs[1]);
				name = locale['name'];
				$('company_list').innerHTML = "<div class='close' onClick=\"Effect.Fade($('company_list'), { duration: .2 }); return false;\"><img src='img/close.png'/></div><div id='inner_company_list' style='text-align:left; padding:15px;'><div class='searchtitle'><h4>Subsidary Companies ("+location.length+") in "+name+":</h4></div><br /></div>";
				var list = "<div style='overflow-y: scroll; height:110px; padding-left:15px;'><ul style='list-style:square inside;'>";
				location.each( function(cw_id) {
					list += "<li><a href='#' onClick='selectCompany(\""+cw_id+"\"); return false;'>"+companies[cw_id]['company_name']+"</a></li>";	
				});
				list += "</ul></div>";
				list += "<a href='' onClick=\"Effect.Fade($('company_list'), { duration: .2 }); return false;\">[close]</a>";
				$('inner_company_list').innerHTML += list;
				//$('close_company_list').observe('mouseover', showHelp);
				//$('close_company_list').observe('mouseout', hideHelp);
			}
		});
		return marker;
	}

	function fetchLocations() {
	}

	function updateSubs() {
		$('subdivisioncodesearch').innerHTML = "<option></option>";
		var country = $('countrycodesearch').value;
		if (country) { 
			var subdivs = locations['country_'+country]['subdivisions'];
			for (var s in subdivs) {
				var option = new Option(subdivs[s]['name'], subdivs[s]['code']);
				$('subdivisioncodesearch').insert(option);
			}
		}
		if ($('subdivisioncodesearch').innerHTML != "<option></option>") { $('subdivcontrols').show(); } else { $('subdivcontrols').hide(); }
		resizeResults();
 	}

//manage the search proess
		function searchCompany(resetindex) {
			if(resetindex) { $('index').value = 0; }
			//check what search restrictions are used
			var company = $('companynamesearch').value;
			var country = $('countrycodesearch').value;
			var subdivision = $('subdivisioncodesearch').value;
			var category = $('siccategory').value;
			var sector = $('sicsector').value;
			var index = $('index').value;
			var limit = search_limit;
			//$('results').innerHTML = "Search results for '"+company+"':<br\>";
			
			//alter the ui to indicate searching
			$('results_title').show();
			toggleLoading('results', 1);
			Effect.Appear($('screenui'), { duration: .2, to: .7 });
			//Effect.Appear($('screenuitext'), { duration: .2 });
			$('screenuitext').show();
			toggleLoading('screenuitext', 1);
			//$('map_and_info').setOpacity('.3');
			//$('treecontainer').setOpacity('.3');
			
			//send ajax request to server (that will in turn make requests to the api)
			requests[requests.length+1] = new Ajax.Request('request.php', {
				method:'get', 
				parameters: {'search': 1,'company_name': company, 'country_code':country, 'subdiv_code':subdivision, 'sic_code':category, 'sic_sector':sector, 'index':index, 'limit':limit},
				onComplete: function(resp) { 
					searchresults  = checkError(resp, 'results');
					if (! searchresults ) { 
						return; 
					} 
					var num_found = (searchresults['result']['companies']) ? Object.keys(searchresults['result']['companies']).length : '0';

					//show the results popup panel
					toggleLoading('results', 0);
					toggleLoading('screenuitext', 0);
					$('screenuitext').innerHTML = " <div class='close' onClick=\"hideScreen(); return false;\"><img src='img/close.png'/></div><b>Search returned <span id='foundcount'>"+num_found+" of "+searchresults['meta']['total_results']+"</span> results.</b><img style='vertical-align:middle; position:absolute; left: 15px; bottom: 15px;'src='img/leftArrow.png' alt='left arrow' width='50' height='48'> <br/><br/>Choose one of the companies to examine.  <br/><a href='#' onclick='hideScreen(); return false;'>[close]</a></div> ";
					$('screenuitext').setStyle({height: ''});
					if (num_found == 0) { 
						$('results').innerHTML = "No companies found.";
						//TODO: add text to explain criteria searched for
					} else {
						//show the result list on the side results component
						$('results').innerHTML = "<ul id='result_list' class='company_list'></ul>";
						var div = "";
						//if searching on a company name, loop over list to bold the search term
						if (searchresults['meta']['parameters']['company_name']) {
							var company = searchresults['meta']['parameters']['company_name'].toLowerCase();
							var clength = company.length;
						}
						for (var company_id in searchresults['result']['companies']) {
							var c = searchresults['result']['companies'][company_id];
							var name = c['company_name'];
							if (company) { 
								var begin = name.toLowerCase().indexOf(company);
								if (begin >= 0) { 
									name = name.substr(0,begin)+'<b>'+name.substr(begin, clength)+'</b>'+name.substr(begin+clength);
								}
							}
							//var from = name.toLower().indexFrom(company.toLower());
							var div = "<li><div><a href='#' onclick=\"showSubsidiaries('"+company_id+"', '"+c['top_parent_id']+"', '"+c['max_year']+"'); return false;\">"+name+"</a></div></li>";
							$('result_list').insert(div);
						}
					}
					
					//deal with paging, if more results than can fit in div
					if (searchresults['meta']['total_results'] > search_limit) {
						var index = parseInt($('index').value);
						var maxRange = ((index+1)*search_limit);
						if (index >= parseInt(searchresults['meta']['total_results']/search_limit)) {	
							maxRange = searchresults['meta']['total_results'];
						}
						var more_links = '<div style="text-align: center;">Showing <span class="num_found">'+ (index*search_limit+1) + '-'+maxRange +'</span> of <span class="total">'+searchresults['meta']['total_results']+'</span> results <br>';
						if (index > 0) { 
							more_links += '<a href="#" onclick="showResults(1); return false;">Show previous</a> | ';
						}
						if (index < parseInt(searchresults['meta']['total_results']/search_limit)) {	
							more_links += '<a href="#" onclick="showResults(); return false;">Show next</a>';
						}
						$('results').innerHTML += more_links+'</div>';
						
					}
				}
			});
	
		return false;
		}

	//toggle sic search selectors depending on what choice is made
	function updateSICs() {
		$('siccategory').innerHTML = "<option></option>";
		sector = $('sicsector').value;
		if (sector) { 
			for (var g in groups) {
				if (groups[g]['sectors']['sector_'+sector]) {
					var industries = groups[g]['sectors']['sector_'+sector]['industries'];	
					for (var i in industries) {
						var option = new Option(industries[i]['name'], industries[i]['code']);
						$('siccategory').insert(option);
					}
					continue;
				}
			}
		}
		if ($('siccategory').innerHTML != '<option></option>') { $('industrycontrols').show(); } else { $('industrycontrols').hide(); }
		resizeResults();
	}


	function checkError(resp, div) {
		var obj = resp.responseJSON;
		var error = "";
		if (obj == "" || obj == null) {
			error = "An Error Occurred: "+resp.responseText;
		} else if (obj['meta']['success'] != 1) {
			error = obj['meta']['status_string'];
		}
		if (error) { 
			$(div).innerHTML = "<span class='error'>"+error+"</span>";
		} else {
			return obj;
		}
	}

		var currobj; 

		function showTooltip(e, label) {
			currobj = e.element();
			var mousepos = { 'x': Event.pointerX(e), 'y': Event.pointerY(e) };
			mousepos = { 'x': currobj.cumulativeOffset().left, 'y': currobj.cumulativeOffset().top };
			var left = (mousepos['x'] + 5 + currobj.getWidth());
			var top = (mousepos['y']);

			var right = 0;
			if (document.viewport.getWidth() - currobj.cumulativeOffset().left < 200) {
				left = document.viewport.getWidth() - left + currobj.getWidth()+ 10;
				right = 1;
			}
			displayTooltip(left, top, label, right);
		}

		function hideTooltip() {
			$('tooltip').hide(); //show the tooltip
		}	

function showHelp(e) {
	var id = this.id;
	if(! id) { id = this.className; }
	if (helptext[id]) { 
		showTooltip(e, '<div class="help">'+helptext[id]+"</div>");
	} else {
		showTooltip(e);
	}	
}

function hideHelp() {
	hideTooltip();
}

//make a request for "timeline" listing of comany years w appropriate links
function showTimeline(cw_id,year){
	if ($('timeline').innerHTML == ""){
		requests[requests.length+1] = new Ajax.Request('request.php', {
			method:'get', 
			parameters: {'history': 1,'cw_id': cw_id, 'year': year},
			onComplete: function(resp) { 
				//check if user has already changed to another company§
				//if (cw_id != current_company || $('timeline').innerHTML != "") { return; }
	
				company_years = resp.responseJSON;
				//timeline_content = resp.responseText;
				//$('timeline').innerHTML = timeline_content;
				if ( year == '' || ! year || year == undefined || year == 'undefined'){
					year = $H(company_years).keys().sort().reverse()[0].replace('year_', '');
				}
				displayTimeline(year);
				current_company = cw_id;
				current_year = year;
				updateInfo(company_years['year_'+year]);
			}
		});
	} else {
		if (! year && current_year) { 
			year = current_year;
		} else {
			current_year = year;
		}
		displayTimeline(year);
		updateInfo(company_years['year_'+year]);
	}
}


//make a request for filings and display them in the company profile
function showFilings(cw_id,year) {
	//toggleLoading('filings');
	requests[requests.length+1] = new Ajax.Request('request.php', {
		method:'get', 
		parameters: {'filings': 1,'cw_id': cw_id, 'year': year},
		onComplete: function(resp) { 
		    //check if user has already changed to another company§
			if (cw_id != current_company || $('filings').innerHTML != "") { return; }
			//toggleLoading('filings');
			//eval("var filings = "+resp.responseText);
			var filings = resp.responseJSON;
			if (! filings || filings['results'] == 0) {
				$('filings').innerHTML = "<a target='blank' href='http://www.sec.gov/cgi-bin/browse-edgar?company=&match=&CIK="+company_years['year_'+year]['cik']+"&filenum=&State=&Country=&SIC=&owner=exclude&Find=Find+Companies&action=getcompany'>CIK "+company_years['year_'+year]['cik']+"</a> ";
			} else { 
				$('sec21container').show();
				filings.each(function(filing) {
					$('filings').innerHTML += "<a target='blank' href='http://www.sec.gov/cgi-bin/browse-edgar?company=&match=&CIK="+filing['cik']+"&filenum=&State=&Country=&SIC=&owner=exclude&Find=Find+Companies&action=getcompany'>CIK "+filing['cik']+"</a><br/>";
					if (filing['sec_21_url']){
						$('sec21s').innerHTML += filing['year']+" Form 10-K <a target='blank' href='"+filing['sec_21_url']+"'>Section 21</a><br/>";
					}
				});
			}
		}
	});
}

function displayTooltip(left, top, message, right) {
	var tooltip = $('tooltip');
	tooltip.setStyle({top: top+'px'});
	if (right) { 
		tooltip.setStyle({right: left+'px', left:''});
	} else {
		tooltip.setStyle({left: left+'px', right:''});
	}
	if (message) {
		tooltip.innerHTML = message;
	}
	tooltip.show();
}	

function hideScreen() {
	$('screenui').hide();
	$('screenuitext').hide();
}

function showMarkerTooltip(marker) {
	var tooltip = $('tooltip');
	var message = marker.tooltip;
	var point = map.fromLatLngToContainerPixel(marker.getPoint());
	var left = point.x + 10 + $('map_canvas').cumulativeOffset()[0];
	var top = point.y - 34 -36 + $('map_canvas').cumulativeOffset()[1];
	marker.setImage('markers_selected/marker'+marker.count+'.png');
	displayTooltip(left, top, message);
}

function showCompany(cw_id, parent,year) {
   if (current_parent == parent && current_year == year) {
		highlightCompany(cw_id);
	} else {
		showSubsidiaries(cw_id, parent,year);
	}
}

var historyListener = function(newLocation, historyData) {
	if(! newLocation.split(',')) { return; }
	var parent = newLocation.split(',')[1];
	var cw_id = newLocation.split(',')[0];
	var year = newLocation.split(',')[2];
	if (typeof(year)=='undefined'){year=''};
	if (! current_parent) { 
		current_company = cw_id;
		current_parent = parent;
		current_year = year;
		return; 
	}
	showCompany(cw_id, parent,year);
}

function showResults(prev) {
	if (prev) {
		$('index').value--;
	} else {
		$('index').value++;
	}
	searchCompany(); 
}

function cleanUp(cw_id) {
	killRequests();
	if (cw_id != current_company) {
		current_company = null;
		company_years = [];
		company_notes = null
	}
	current_parent = null;
	current_year = null;
	companies = [];
	visible_lis = null;
}


function displayTimeline(year){
	//loop over the elements and change the css class to remove hiliting
	$('timeline').innerHTML = company_years['history'];
	for(var elem in $('timeline').descendants){
		if (Element.hasClassName(elem,'timeline_year_selected')){
			Element.removeClassName(elem,'timeline_year_selected');
			Element.addClassName(elem,'timeline_year');
		}
	}
	//hilite the appropriat year
	
	Element.removeClassName($("year_"+year),'timeline_year');
	Element.addClassName($("year_"+year),'timeline_year_selected');
}

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

Ajax.Request.prototype.abort = function() {
	// prevent and state change callbacks from being issued
    (this.options.onAbort || Prototype.emptyFunction)(this.transport, this.json);
	this.transport.onreadystatechange = Prototype.emptyFunction;
    this.options={};
	// abort the XHR
	this.transport.abort();
	// update the request counter
	Ajax.activeRequestCount--;
};

function getLocation(country, subdiv) {
	if (country != 'null') {
		if (subdiv != 'null') {
			locale = locations['country_'+country]['subdivisions']['subdivision_'+subdiv];
		} else {
			locale = locations['country_'+country];
		}
	}
	return locale;
}

function replaceHtml(el, html) {
	var oldEl = typeof el === "string" ? document.getElementById(el) : el;
	/*@cc_on // Pure innerHTML is slightly faster in IE
		oldEl.innerHTML = html;
		return oldEl;
	@*/
	var newEl = oldEl.cloneNode(false);
	newEl.innerHTML = html;
	oldEl.parentNode.replaceChild(newEl, oldEl);
	/* Since we just removed the old element from the DOM, return a reference
	to the new element, which can be used to restore variable references. */
	return newEl;
};

function loadMapMarkers(company_locations) {
	for (var location in company_locations) {
		if (typeof(company_locations[location]) != 'object') { continue; }
		var cs = location.split('_');
		var country = cs[0];
		var subdiv = cs[1];
		var point;
		var locale;
		var name = "";
		if (country != 'null') {
			locale = getLocation(country, subdiv);
			if (subdiv != 'null') {
				name = locale['name'] + ', ';
			}
			count = company_locations[location].length;
			if (count >= 100) { count = 100; }
			var plural = 'ies';
			if (count == 1) { plural = 'y'; }
			name += locations['country_'+country]['name'] + "<br/>("+ count+" subsidiar"+plural+")";
			name = "<div style='text-align: center'>"+name+"</div>";
			var point = new GLatLng(locale['latitude'], locale['longitude']);
			bounds.extend(point);
			icon = redIcon;
			redIcon.image = 'markers/marker'+count+'.png';
			markers[country+'_'+subdiv] = createMarker(point, name, redIcon, location);
			markers[country+'_'+subdiv].count = count;
			map.addOverlay(markers[country+'_'+subdiv]);
		}
	}
}
