gmarkers = new Array();
var map;

function getBaseQuery(){
	return '{"query":' +
			'[{' +
				'"/business/company/headquarters":[{' +
					'"/location/location/geolocation":[{"*":null,"optional":true}],' +
					'"citytown":null,' +
					'"postal_code":null,' +
					'"state_province_region":null,' +
					'"street_address":[],' +
					'"optional":true'+
					'}],' +
				'"a:area_of_expertise":[{"name":null,"id":null,"optional":true}],'+
				'"a:develops_treatments_for_disease":[{"name":null,"id":null,"optional":true}],'+
				'"limit":10000,' +
				'"name":null,' +
				'"id":null,' +
				'"sort":"name",' +
				'"type":"/base/bioventurist/science_or_technology_company"' +
			'}]' +
			'}';
}

function loadMapTechnology(filter_topic_id, url){
	
	// First get all the sub-technologies
	var q_technologies = '{"query":' +
			'[{' +
				'"id":"'+filter_topic_id+'",' +
				'"name":null,'+
				'"includes_technology":[{"name":null, "optional":true}],'+				
				'"type":"/base/bioventurist/technology_class"' +
			'}]}'
			
	perform_freebase_read_noasync(
		url,
		q_technologies,
		function (msg) {
        	var technologies = msg.result[0];        	
			
			// Get all of the sub technologies
			var subTechnologyList = technologies.includes_technology;
			var allTechnologies = '"'+technologies.name+'"';
			for(var k=0;k<subTechnologyList.length;k++){
				allTechnologies += ( k < subTechnologyList.length ? ', ' :"");
				allTechnologies += '"'+subTechnologyList[k].name+'"';
			}
			
			//var q = '{"query":[{"name":null,"id":null, "technology_involved|=":['+allTechnologies+'],"type":"'+biov_domain+'product","brand_name":[],"developed_by":[{"name":null,"id":null, "optional":true}],"a:type":[],"stage_of_development":null,"sales":[{"year":null,"amount":null,"area":null, "optional":true}]}]}'; 
			
			var q = '{"query":' +
					'[{' +
						'"/business/company/headquarters":[{' +
							'"/location/location/geolocation":[{"*":null,"optional":true}],' +
							'"citytown":null,' +
							'"postal_code":null,' +
							'"state_province_region":null,' +
							'"street_address":[],' +
							'"optional":true'+
							'}],' +
						'"limit":10000,' +
						'"name":null,' +
						'"id":null,' +
						'"sort":"name",' +
						'"a:area_of_expertise":[{"name":null,"id":null,"optional":true}],'+
						'"a:develops_treatments_for_disease":[{"name":null,"id":null,"optional":true}],'+		
						'"type":"/base/bioventurist/science_or_technology_company",' +
						'"area_of_expertise|=":['+allTechnologies+']'+
					'}]' +
					'}';
						
				loadMap(url, q);
				
				// Give a disclaimer to edit the topic
				var edit_filter_html = 'Companies missing?  Edit <a href="/technology' + technologies.id + '"target="_blank">' + technologies.name + '</a>'
				$('#edit_filter_topic').empty()
				$('#edit_filter_topic').append(edit_filter_html)
					
    	},
			function(m){}
		);

	return 'n/a';
	
}

function loadMapDisease(filter_topic_id, url){
	// First get all the sub-diseases
		var q_diseases = '{"query":' +
				'[{' +
					'"id":"'+filter_topic_id+'",' +
					'"name":null,'+
					'"/medicine/disease/includes_diseases":[{"name":null}],'+				
					'"type":"/base/bioventurist/bv_medical_condition"' +
				'}]}'
		
		
		perform_freebase_read_noasync(
			url,
			q_diseases,
			function (msg) {
				var q;
				if(typeof msg.result[0]=="undefined"){
					q = '{"query":' +
					'[{' +
						'"/business/company/headquarters":[{' +
							'"/location/location/geolocation":[{"*":null,"optional":true}],' +
							'"citytown":null,' +
							'"postal_code":null,' +
							'"state_province_region":null,' +
							'"street_address":[],' +
							'"optional":true'+
							'}],' +
						'"limit":10000,' +
						'"name":null,' +
						'"id":null,' +
						'"sort":"name",' +
						'"a:area_of_expertise":[{"name":null,"id":null,"optional":true}],'+
						'"a:develops_treatments_for_disease":[{"name":null,"id":"'+filter_topic_id+'","optional":false}],'+		
						'"type":"/base/bioventurist/science_or_technology_company"' +
					'}]' +
					'}';
				}else{
					var diseases = msg.result[0];
									
				// Get all of the sub technologies
					var includesDiseaseList = diseases['/medicine/disease/includes_diseases'];
					var allDiseases = '"'+diseases.name+'"';
					for(var k=0;k<includesDiseaseList.length;k++){
						allDiseases += ( k < includesDiseaseList.length ? ', ' :"");
						allDiseases += '"'+includesDiseaseList[k].name+'"';
					}
				
					q = '{"query":' +
						'[{' +
							'"/business/company/headquarters":[{' +
								'"/location/location/geolocation":[{"*":null,"optional":true}],' +
								'"citytown":null,' +
								'"postal_code":null,' +
								'"state_province_region":null,' +
								'"street_address":[],' +
								'"optional":true'+
								'}],' +
							'"limit":10000,' +
							'"name":null,' +
							'"id":null,' +
							'"sort":"name",' +
							'"a:area_of_expertise":[{"name":null,"id":null,"optional":true}],'+
							'"a:develops_treatments_for_disease":[{"name":null,"id":null,"optional":true}],'+		
							'"type":"/base/bioventurist/science_or_technology_company",' +
							'"develops_treatments_for_disease|=":['+allDiseases+']'+
						'}]' +
						'}';
					}	
					
					loadMap(url, q);
					
					// Give a disclaimer to edit the topic
					var edit_filter_html = '<b>Companies missing?  Add them to: <a href="/disease' + diseases.id + '"target="_blank">' + diseases.name + '</a></b>'
					$('#edit_filter_topic').empty()
					$('#edit_filter_topic').append(edit_filter_html)
					
				
	    	},
				function(m){}
			);
	 
		return 'n/a';
	 
	 
	}

function getNodeValue(Element) {
if ((Element.length>0) && Element[0] && Element[0].firstChild && Element[0].firstChild.nodeValue)
   return Element[0].firstChild.nodeValue;
}

function createTabbedMarker(point,tabs,number) {
        var marker;
		/*var icon = new GIcon(); 
	  #icon.image = "http://www.geocodezip.com/mapIcons/marker"+number+".png";
	  #icon.shadow = "/bvmapapp/static/comp_shadow1.png";
	  #icon.iconAnchor = new GPoint(6, 20);
	  #icon.infoWindowAnchor = new GPoint(5, 1);
*/
		//marker = new GMarker(point, {'icon': icon});
        marker = new GMarker(point);
       
        var marker_num = gmarkers.length;
        marker.marker_num = marker_num;
        marker.tabs = tabs;
		gmarkers[marker_num] = marker;
        
        GEvent.addListener(gmarkers[marker_num], "click", function() {
															   
          marker.openInfoWindowTabsHtml(gmarkers[marker_num].tabs);
        });
		
		return marker;
}



	  
var marker_data='<markers>';
var markerCluster;

function loadMap(url, q){
	marker_data='<markers>';
	
// Add the html elements:
/*		var map_html = '<div id="map_container"></div>'+
						'<div id="sidebar">' +
						'<ol id="company_list"></ol>' +
						'</div>';
*/
var markers=[];	

var geocoder;
var temp=null;
 	 var iconBlue = new GIcon(); 
	  iconBlue.image = "/bvmapapp/static/comp_icon1.png";
	  iconBlue.shadow = "/bvmapapp/static/comp_shadow1.png";
	 
	  iconBlue.iconAnchor = new GPoint(6, 20);
	  iconBlue.infoWindowAnchor = new GPoint(5, 1);

	  var isrefresh = false;

		$('#company_list').empty();
		if(map != null){
			map.clearOverlays();
			map.setCenter(new GLatLng(37,-50),1);
			markerCluster.clearMarkers();
			isrefresh = true;
		}else{
			map = new GMap2(document.getElementById("map_container"));
	        map.setCenter(new GLatLng(37,-50),1);
	        map.addControl(new GLargeMapControl());
	    	map.addControl(new GMapTypeControl());
	    	//map.addControl(new GOverviewMapControl(new GSize(90,90)));
	    	//map.enableScrollWheelZoom();
	    	
	    	map.addMapType(G_PHYSICAL_MAP);
	    	map.addMapType(G_NORMAL_MAP); 
	    	//map.addMapType(G_SATELLITE_MAP);
		}
		
	
		perform_freebase_read(
		url,
		q,
		function (msg) {
    
        	companies = msg.result;

			var companies_no_heaquarters_html = '';
        				
        	if(companies.length>0){		
				geocoder = new GClientGeocoder();

				var num_comp_no_headquarters = 0;
        		for(var i=0; i<companies.length; i++){
					

            	var company = companies[i];
		        	var headquartersAll = company["/business/company/headquarters"];
		        	var name = company.name;
		        	var htmlName = '<a href="/company' + company.id + '"target="_blank">' + name + '</a>'
		        	
		        	if(headquartersAll.length > 0){
		        		var headquarters = headquartersAll[0];
			        	var streetAddressAll = headquarters.street_address;
			        	var geolocation = headquarters["/location/location/geolocation"];
			        	var streetAddress = '';
			        	for (var j=0; j<streetAddressAll.length; j++){
			        		streetAddress += streetAddressAll[j];
			        	}
			        	
			        	// Address
			        	var city = (headquarters.citytown != null ? headquarters.citytown : '');
			        	var state = (headquarters.state_province_region != null ? headquarters.state_province_region : '');
			        	var postalCode = (headquarters.postal_code != null ? headquarters.postal_code : '');
						var address = streetAddress + ',' + city + ',' + state + ',' + postalCode;			        	
						var delim = '<br></br>';
						var streetAddressHTML = (streetAddress == '' ? streetAddress : streetAddress + delim);
						var cityHTML = (city == '' ? city : city + delim);
						var stateHTML = (state == '' ? state : state + delim);
						var postalCodeHTML = (postalCode == '' ? postalCode : postalCode + delim);
						var sidebarEntry = name;		
						
						// Technology expertise:
						var technologies = company["a:area_of_expertise"];
						var technology_text = '';
						for(var j=0; j<technologies.length; j++){
							technology_text += '<a href="/technology' + technologies[j].id + '"target="_blank">' + technologies[j].name + '</a>'
							technology_text += (j<technologies.length-1 ? ',': '');
						}
						if(technology_text.length > 0){
							technology_text = delim + '<b>Area of Expertise</b>: ' + technology_text;
						}
						
						// Medical expertise:
						var diseases = company["a:develops_treatments_for_disease"];
						var disease_text = '';
						for(var j=0; j<diseases.length; j++){
							disease_text += '<a href="/disease' + diseases[j].id + '"target="_blank">' + diseases[j].name + '</a>'
							disease_text += (j<diseases.length-1 ? ',': '');
						}
						if(disease_text.length > 0){
							disease_text = delim + '<b>Area of Medical Focus</b>: ' + disease_text;
						}
						
						var text = htmlName + delim + streetAddressHTML + cityHTML + stateHTML + postalCodeHTML + technology_text + disease_text;
						if(geolocation.length > 0) {
							createMarker(geolocation, text, name, sidebarEntry, map, iconBlue);						
						}
						
        			} else { // the company does not have a headquarters
        				if(companies_no_heaquarters_html.length ==0){
        					companies_no_heaquarters_html += '<b>Companies in the search, but with addresses not yet entered: </b>';
        				}
        				if(num_comp_no_headquarters<10){
	        				companies_no_heaquarters_html += htmlName = '<a href="/company' + company.id + '"target="_blank">' + name + '</a>';
    	    				companies_no_heaquarters_html += (i<companies.length-1? ', ' : '');
        				} else {
        					if(num_comp_no_headquarters==10){
        						companies_no_heaquarters_html += '...';
        					}
        				}
    					num_comp_no_headquarters = num_comp_no_headquarters+1;        				
        			}
        			
        		}
				//thise adds the clusters to the map......
				//unbelievably awkward. create xml and then parse it in the same operation?? WTF!
				marker_data+='</markers>';
		
				var xmlDoc = GXml.parse(marker_data);
				var markers_array = xmlDoc.documentElement.getElementsByTagName("marker");
				
				new_markers = new Array();
      			for (var i = 0; i < markers_array.length; i++) 
				{
				 // obtain the attributes of each marker
				 	var count=1;
					 var lat = parseFloat(markers_array[i].getAttribute("lat"));
					 var lng = parseFloat(markers_array[i].getAttribute("lng"));
					 var icon = iconBlue;
					 var point = new GLatLng(lat,lng);
					 var label='Tab';
					 // get the tab info
					 tabInfo = markers_array[i].getElementsByTagName("tab");
					 var tabs = new Array();
					 if (tabInfo.length > 0) 
					 {
						
						for (var j = 0; j < tabInfo.length; j++) 
						{
							   var tabLabel = getNodeValue(tabInfo[j].getElementsByTagName("label"));
							   var tabHtml = getNodeValue(tabInfo[j].getElementsByTagName("contents"));
							   
							   if ((j==0) && (tabInfo.length > 2)){ //  adjust the width so that the info window is large enough for this many tabs
								  tabHtml = '<div style="width:'+tabInfo.length*88+'px">' + tabHtml + '</div>';
							   }	   
							   tabs.push(new GInfoWindowTab(tabLabel,tabHtml));
							   count=j+1;
						}
					 } 
					 else 
					 { 
						
						var tabLabel = "Nothing";
						var tabHtml = 'nothing';
						tabs.push(new GInfoWindowTab(tabLabel,tabHtml));
					 }  
					 var marker = createTabbedMarker(point,tabs, count);
					 for(var k=0; k< count; k++){
						 new_markers.push(marker);   
						 //add directly without clusterer
						//map.addOverlay(marker); 
					 }
				}
				 // create the marker
					 markerCluster = new MarkerClusterer(map, new_markers, {gridSize: 50, maxZoom: 15});


				 companies_no_heaquarters_html += htmlName = '<br /><form action="../mt/headquarter_companies" method="post"><input type="submit" value="Add address for these companies"></form>';
    		}
    		// Add the no_headquarters list to the page
    		$('#companies_no_headquarters').empty();
    		$('#companies_no_headquarters').append(companies_no_heaquarters_html);
    		
    	},
		function(request,error){
			
			if (error = "timeout") {
				alert('timeout occured');
			}
		}
	);
	
}

/**
 * Creates the marker for each point
 */

 
function createMarker(geolocation, text, company_name, sidebarEntry, map, iconBlue) {
	var marker;
	var point;
	if(geolocation.length > 0) {
		var coords = geolocation[0];
		var lat = coords.latitude;
		var lng = coords.longitude;
		if(lat == null || lng == null){
			console.log("lat "+lat);
			console.log("lng "+lng);
			console.log("bad coords for "+company_name);
			return false;
		}
		point = new GLatLng(lat,lng);
		var company_firstname;
		//marker = new GMarker(point, {'icon': iconBlue});
        marker = new GMarker(point);
		var company_index=company_name.indexOf(' ');
		if(company_index !=-1){
			company_firstname=company_name.substring(0,company_index);
		}
		else{
			company_firstname=company_name;
		}
		var temp='<marker lat="'+lat+'" lng="'+lng+'" >';
		
		if(marker_data.indexOf(temp)!=-1)
		{
			var start=marker_data.indexOf(temp);
			var len=temp.length;
			var startString=marker_data.substring(0,start+len);
			var endString=marker_data.substring(start+len);
			startString+=' <tab><label><![CDATA['+company_firstname+']]></label><contents><![CDATA[<br/>'+text+']]></contents></tab>';
			marker_data=startString+endString;
			
		}
		else
		{
			marker_data+='<marker lat="'+lat+'" lng="'+lng+'" ><tab><label><![CDATA['+company_firstname+']]></label><contents><![CDATA['+text+']]></contents></tab></marker>';
		}
		//GEvent.addListener(marker, 'click', function() {
		//marker.openInfoWindow(text);
		//});	
	} 
	else {
		return false;
		//currently, geocoder is superslow. need to add coords to freebase.
		/*if (geocoder) {
			geocoder.getLatLng(
					address,
	        	function(point) {
		        	if (!point) {
		              return false;
		            } else {
		              var marker = new GMarker(point, iconBlue);
		              map.addOverlay(marker);
		              GEvent.addListener(marker, 'click', function() {
		          		marker.openInfoWindow(text);
		          	});	
		                  
	            }
	        }
		)
	}*/		
	}
	//sidebar js here
	var tooltip = new Tooltip(marker,sidebarEntry,4);
	marker.tooltip = tooltip;
	var listItem = document.createElement('li');
	
	var listItemLink = listItem.appendChild(document.createElement('a'));
	listItemLink.href = "#";//"#none";
	//listItemLink.name = "mkr";
	var sidebarIcon = '<img src="' + iconBlue.image + '" height="15" width="15" style="border: none;"/> ';
	listItemLink.innerHTML = sidebarIcon + sidebarEntry;
	
	
	GEvent.addDomListener(listItemLink, 'click', function() {
		map.setCenter(point, 17);
		map.panTo(point);
	  	});
	
	    GEvent.addDomListener(listItemLink, 'mouseover', function() {
	    	GEvent.trigger(marker, 'mouseover');
	  	});
	    GEvent.addDomListener(listItemLink, 'mouseout', function() {
	    	GEvent.trigger(marker, 'mouseout');
	  	});
	 		
	var focusPoint = function() {
		deselectCurrent();
		listItem.className = 'current';
		deselectCurrent = function() {
			listItem.className = '';
		}
		marker.openInfoWindowHtml();
		map.panTo(point);
		return false;
	}
	
	listItemLink.onClick = focusPoint;
	document.getElementById("company_list").appendChild(listItem);
	map.addOverlay(tooltip);
	 GEvent.addListener(marker,'mouseover',function(){
       this.tooltip.show();
	}); 
	GEvent.addListener(marker,'mouseout',function(){ 
       this.tooltip.hide(); 
		 });

	//map.addOverlay(marker);  //  ..... we dont need this line now as we are using clusters now.
	return marker;
}
/**
 * A search suggest box that can be used to filter the companies by any of:
 * 	technology type
 *  bv_medical_condtion
 */
function createCompanyFilter(bioventurist_dir, suggest_html_id, filter_submit_html_id, parent_html_id, url){
	
	//var suggest_html_id = 'company_filter';		
	//var form_html = '<p>Show companies by technology class (eg. monoclonal antibody) or area of medical focus (eg. breast cancer)' +
	//		'<input type="text" name="message" value="search" id="'+suggest_html_id+'"></input>' +
	//		'</p>';
	//$("#"+html_id).append(form_html);	

   jQuery(function($) {
        var options = {
            soft: true,
            ac_param: {
                type: [
                    bioventurist_dir + "bv_medical_condition",
                    bioventurist_dir + "technology_class",
                    ],                 
                //strict: "any",
                start: 0,
                limit: 30
            }
        };
        $('#'+suggest_html_id).freebaseSuggest(options)
        .bind('fb-select', function(e, data) { 
        	$('#'+suggest_html_id+'_topic_id').val(data.id);
        	$('#'+suggest_html_id+'_topic_name').val(data.name);
        	$('#'+suggest_html_id+'_topic_type').val(getType(data.type));
        	//var nextDir = searchSelect_results(data);
        	//location.href = nextDir;
        });
        $('#'+suggest_html_id).focus(function(e) { $(this).val(""); })
        .blur(function(e) { if ($(this).val() == "") $(this).val('search'); })
    });
    
    // Bind what happens when the submit button is pressed:
    $('#'+filter_submit_html_id).bind("click", 
    	function (e,data) {
			if($(this).length > 0) {
				var id = $(this).get(0).id;
				id = id.replace(/_submit/, "");
				// get the information for the filter:
				var filter_topic_id = $('#'+id+'_topic_id').val();
				var filter_topic_name = $('#'+id+'_topic_name').val();
				var filter_topic_type = $('#'+id+'_topic_type').val();
				
				// create the mql query
				var q = null;
				if(filter_topic_type == 'technology'){
					q = loadMapTechnology(filter_topic_id, url);
				} else if (filter_topic_type == 'disease'){
					q = loadMapDisease(filter_topic_id, url);
				}
				
				// Reload the map:
				//  $('#'+parent_html_id).empty();			
				}
		})
}

function getType(types){
	for(var i=0; i<types.length; i++){
		var type = types[i].id;
		if(type == "/base/bioventurist/technology_class"){
			return 'technology';
		} else if (type == "/base/bioventurist/bv_medical_condition"){
			return 'disease';
		}
	}
	return '';
}
