var pid;
var id;
var showKey;
var center_point;
var map;
var index=0;
var size=0;
var ajax;
var geocoder;
var baseIcon;
var address;
var locationsearch=false;
var criteriasearch=false;
var clearsearch=false;
var firsttime=true;
var allprogarea='1135,1138,1132,1140,1141,1142,1144'.split(',');

var grantid_tag = new Array();
var fundid_tag = new Array();
var pid_tag =  new Array();
var lat_tag =  new Array();
var lng_tag =  new Array();
var title_tag =  new Array();
var grantee_tag =  new Array();
var street_tag =  new Array();
var city_tag =  new Array();
var state_tag =  new Array();
var zip_tag =  new Array();
var phone_tag =  new Array();
var url_tag =  new Array();
var amount_tag =  new Array();

	function firstLoad(){
		Event.observe('textsearch', 'keypress', function(event){ if(event.keyCode == Event.KEY_RETURN){ locationsearch = true; searchMap(); }});
		Event.observe('textgrname', 'keypress', function(event){ if(event.keyCode == Event.KEY_RETURN){ changeCriteriaBool(); searchMap(); }});
		Event.observe('textgrtitle', 'keypress', function(event){ if(event.keyCode == Event.KEY_RETURN){ changeCriteriaBool(); searchMap(); }});
		if( $('textgrprogarea')!=null) Event.observe('textgrprogarea', 'keypress', function(event){ if(event.keyCode == Event.KEY_RETURN){ changeCriteriaBool(); searchMap(); }});
		Event.observe('textgramount', 'keypress', function(event){ if(event.keyCode == Event.KEY_RETURN){ changeCriteriaBool(); searchMap(); }});
		$('textsearch').onfocus=function(){changeTextSearch();changeMileSelector();};
		hidePanels();
		pid = parseInt($('pid').getValue());
		id = trim($('id').getValue() );
		showKey = parseInt( trim($('showKey').getValue() ) );
		geocoder = new GClientGeocoder() ;
		geocoder.setBaseCountryCode('US');
		center_point = new GLatLng(37.700000,-90.333333);      // center point of the map		
		map = new GMap2($('map'));
		map.addControl( new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		map.setCenter(center_point, 4);
		/* CREATE BASE ICON */
		baseIcon = new GIcon();
		baseIcon.iconSize = new GSize(11, 32);
		baseIcon.iconAnchor = new GPoint(5, 32);
		baseIcon.infoWindowAnchor = new GPoint(5, 1);
		markerOptions = { icon:baseIcon };
		document.getElementsByTagName('body')[0].onunload = function(){  new GUnload()};
		if(parseInt($('locvar').value))	locationsearch=true;
		if(parseInt($('nvar').value)) criteriasearch=true;
		firsttime=false;
		if(locationsearch && criteriasearch )searchMap();
		else if(!locationsearch && criteriasearch )searchMap();
		showSearch();
	}

	
	function reLoad(grpid){
		$('textgrprogarea').options[parseInt(grpid)].selected=true;
		pid = parseInt($('textgrprogarea').options[parseInt(grpid)].value);
		changeCriteriaBool();
		searchMap();
		var tds = W.$('keyCode').getElementsByTagName('td');
		for (var i = tds.length; --i >= 0; ) {
			tds[i].className = '';
			if (i == grpid) { tds[i].className = 'selected'; }
		}
	}

	function positionSearchImage(){
		mapEl = $('map');
		yoffset=0;
		xoffset=0;
		while( mapEl != null ){
			yoffset += mapEl.offsetTop;
			xoffset += mapEl.offsetLeft;
			if (mapEl.offsetParent) mapEl = mapEl.offsetParent; else break;
		}
		$('searchingimage').style.top= yoffset + $('map').offsetHeight/2 ;//$('map').offsetTop + ($('map').offsetHeight/2);
		$('searchingimage').style.left= xoffset + $('map').offsetWidth/3;
	}

	function showProgramAreaGrants( externalurl ){
		$('searchingimage').style.display='block';
		map.clearOverlays();
		url = '/map/xml/coordinates.jsp?action=get';
		if( pid )url+='&pid='+escape(pid);
		if( $('npo')!=null)url+='&grnpo='+escape($('npo').value);
		if( $('type')!=null)url+='&grtype='+escape($('type').value);
		url+=externalurl;
		url+='&ms='+new Date().getTime();
		ajax = new Ajax.Request(url,{
			method:'get',
			contentType:'application/xml',
			onSuccess:function(transport) {handlePAGrants( transport.responseXML );},
			onFailure:function(transport){firstLoad();}
		});
	}

	function handlePAGrants(xmldata){
		size= xmldata.getElementsByTagName('size')[0].firstChild.nodeValue;
		if( size <= 0 ){
			alert("Your search criteria did not return any results.\nPlease try again.");
			$('searchingimage').style.display='none';
			return;
		}
		grantid_tag = xmldata.getElementsByTagName('grantid');
		fundid_tag = xmldata.getElementsByTagName('fundid');
		pid_tag = xmldata.getElementsByTagName('pid');
		lat_tag = xmldata.getElementsByTagName('lat');
		lng_tag = xmldata.getElementsByTagName('lng');
		title_tag = xmldata.getElementsByTagName('title');
		grantee_tag = xmldata.getElementsByTagName('grantee');
		street_tag = xmldata.getElementsByTagName('street');
		city_tag = xmldata.getElementsByTagName('city');
		state_tag = xmldata.getElementsByTagName('state');
		zip_tag = xmldata.getElementsByTagName('zip');
		phone_tag = xmldata.getElementsByTagName('phone');
		url_tag = xmldata.getElementsByTagName('url');
		amount_tag = xmldata.getElementsByTagName('amount');
		showPAGrants();
	}

function showPAGrants(){
	if(firsttime){
		setTimeout("showPAGrants()",0.05);
		return;
	}

	i=0;
	var PE=new PeriodicalExecuter(
		function(pe) {
			if( i >= size){
				pe.stop();
				$('searchingimage').style.display='none';
			}
			else for(k=0; k<(size<10?size:10); k++) if( i < grantid_tag.length )displayMarkersOnMap(i++);
		}, 0.001);
}

function createArrays(lat, lng, grpid, grantid,fundid, grtitle, amount, grantee, street, city, url ){
	grantid_tag[index] =grantid;
	fundid_tag[index] =fundid;
	pid_tag[index] =grpid;
	lat_tag[index] =lat;
	lng_tag[index] =lng;
	title_tag[index] =grtitle;
	grantee_tag[index] =grantee;
	street_tag[index] =street;
	city_tag[index] =city;
	url_tag[index] =url;
	amount_tag[index] =amount;
	index++;
}

	function displayMarkersOnMap(index){
			grantid = (grantid_tag[index].firstChild!=null ) ? grantid_tag[index].firstChild.nodeValue : '';
			fundid = (fundid_tag[index].firstChild!=null ) ? fundid_tag[index].firstChild.nodeValue : '0';
			grpid = (pid_tag[index].firstChild!=null ) ? pid_tag[index].firstChild.nodeValue :pid;
			lat = (lat_tag[index].firstChild!=null ) ? lat_tag[index].firstChild.nodeValue: '';
			lng  = (lng_tag[index].firstChild!=null ) ? lng_tag[index].firstChild.nodeValue : '';
			grtitle = (title_tag[index].firstChild!=null ) ? title_tag[index].firstChild.nodeValue : '';
			street =(street_tag[index].firstChild!=null ) ? street_tag[index].firstChild.nodeValue: '';
			city =(city_tag[index].firstChild!=null ) ? city_tag[index].firstChild.nodeValue: '';
			state =(state_tag[index].firstChild!=null ) ? state_tag[index].firstChild.nodeValue: '';
			zip =(zip_tag[index].firstChild!=null ) ? zip_tag[index].firstChild.nodeValue: '';
			phone =(phone_tag[index].firstChild!=null ) ? phone_tag[index].firstChild.nodeValue: '';
			url =(url_tag[index].firstChild!=null ) ? url_tag[index].firstChild.nodeValue: '';
			amount =(amount_tag[index].firstChild!=null ) ? amount_tag[index].firstChild.nodeValue: '';
			try{
				grantee = (grantee_tag[index].firstChild!=null ) ? grantee_tag[index].firstChild.nodeValue: '';
				buildBubbleMarker(lat, lng, grpid, grantid,fundid, grtitle, amount, grantee, street, city,state,zip, url);
			}catch(e){
				buildBubbleMarker(lat, lng, grpid, grantid,fundid, grtitle, amount, '', street, city,state,zip, url);
			}
	}
	function displayMarketsOnMap(){
		for(i=0; i<index; i++){
			grantid = grantid_tag[i];
			fundid = fundid_tag[i];
			grpid = pid_tag[i];
			lat = lat_tag[i];
			lng  = lng_tag[i];
			grantee = grantee_tag[i];
			grtitle = title_tag[i];
			street =amount_tag[i];
			city =amount_tag[i];
			url =amount_tag[i];
			amount = amount_tag[i];
			buildBubbleMarker(lat, lng, grpid, grantid,fundid, grtitle, amount, grantee, street, city, url);
		}
	}
	function buildBubbleMarker(lat, lng, grpid, grantid,fundid, grtitle, amount, grantee, street, city,state,zip, url ){
		if( parseInt(grpid)==0) return;
		var point = new GLatLng(lat,lng);
		commonUrl ='';
		inurl =commonUrl+'grant.jsp?id='+escape(grantid);
		inurlText = 'View Grant Summary';
		npoUrl = commonUrl+'npo.jsp?FUND_ID='+escape(fundid);
		npoUrlText = 'View National Program Summary';

		div = Builder.node('div',{id:'addressInfoDiv', style:'width:250px'});
		div.appendChild(Builder.node('h6', grtitle) );
		p	= Builder.node('p', 'Grant Details: ' + amount);
		p.appendChild(Builder.node('br'));
		p.appendChild(Builder.node('strong', grantee));
		p.appendChild(Builder.node('br'));
		p.appendChild(Builder.node('text', street));
		p.appendChild(Builder.node('br'));
		p.appendChild(Builder.node('text', city+', '+state+' '+zip));
		p.appendChild(Builder.node('br'));
		if( url.length ){
			p.appendChild(Builder.node('a',{href:url, name:'&lid=URL&lpos=map',target:'_blank'},'View Grantee Web Site'));
			p.appendChild(Builder.node('br'));
		}
		div.appendChild(p);
		
		ul	= Builder.node('ul', {'class':'supportlinks'});
		ul.appendChild(Builder.node('li', Builder.node('a',{href:'javascript:redirect('+grpid+','+grantid+')', target:'_self'},inurlText)));
		if(parseInt(fundid))
			ul.appendChild(Builder.node('li', Builder.node('a',{href:npoUrl, target:'_self'},npoUrlText)));
		div.appendChild(ul);

		baseIcon = new GIcon();
		baseIcon.iconSize = new GSize(11, 32);
		baseIcon.iconAnchor = new GPoint(5, 32);
		baseIcon.infoWindowAnchor = new GPoint(5, 1);
		markerOptions = { icon:baseIcon };
		baseIcon.image ='/map/js/icon'+grpid+'.png';
		var point_marker =createMarker(point, div);
		map.addOverlay(point_marker);
		if(id.length && parseInt(id)==parseInt(grantid) ){
			recenterMap(point,15);
			point_marker.openInfoWindowHtml(div);
		}
	}

	function redirect(grpid, grid){
		url = '';
		url +='grant.jsp?id='+escape(grid);
		url+=$('textsearch').getValue()!= 'City, State or ZIP'? '&loc='+ $('textsearch').getValue() :'';
		url+=( $('mileSelector').options[$('mileSelector').selectedIndex].value >4 ) ? '&m='+$('mileSelector').selectedIndex:'';
		url+= $('textgrname').getValue().length ? '&n='+$('textgrname').getValue():'';
		url+= $('textgrtitle').getValue().length ? '&t='+$('textgrtitle').getValue():'';
		url+=$('textgramount').selectedIndex ? '&a='+$('textgramount').selectedIndex:'';
		url+=( $('textgrprogarea')!=null ) ? '&pa='+$('textgrprogarea').selectedIndex:'';
		url+=( $('npo')!=null ) ? '&npo='+$('npo').value:'';
		url+=( $('type')!=null ) ? '&type='+$('type').value:'';
		window.location=url;
	}

	function createMarker(point, html) {
		var marker = new GMarker(point,markerOptions);
		GEvent.addListener(marker, 'click', function(){
			marker.openInfoWindowHtml(html);
		});
		return marker;
	}

	function createDefaultMarker(point, html) {
		var marker = new GMarker(point);
		GEvent.addListener(marker, 'click', function(){
			marker.openInfoWindowHtml(html);
		});
		return marker;
	}

	function changeTextSearch(){
		$('textsearch').value='';
		$('textsearch').style.color='black';
		$('textsearch').onfocus=function(){};
		locationsearch=true;
	}

	function changeCriteriaBool(){criteriasearch = true;}
	function changeLocationBool(){locationsearch = true;}

	function changeTextColor(element){element.style.color = 'black';}

	function rollBackTextColor(element){element.style.color = 'gray';}

	function changeProgramAreaCodeKey(){
		pid = parseInt($('textgrprogarea').options[$('textgrprogarea').selectedIndex].value);
	   	if(pid) $('showall').style.display='block';
	}

	function changeMileSelector(){
		$('mileSelector').onchange=function(){locationsearch=true;};
		$('mileSelector').options[0] = new Option('20 miles',11);
		$('mileSelector').options[1] = new Option('50 miles',10);
		$('mileSelector').options[2] = new Option('100 miles',9);
		$('mileSelector').options[3] = new Option('200 miles',8);
		$('mileSelector').options[2].selected=true;
	}

	function resetSearchValues(){
		$('textsearch').style.color='gray';
		$('textsearch').value='City, State or ZIP';
		for(i=$('mileSelector').options.length;  i>0; i--)
			$('mileSelector').options[i] = null;
		$('mileSelector').options[0] = new Option(' --- ',4);
		$('textsearch').onfocus=function(){changeTextSearch();changeMileSelector();};
	}

	function resetSearchMapValues(){

		if( pid && showKey ){
			window.location='pg.jsp';
			return;
		}
		if(id && pid ){
			window.location='pg.jsp';//?pid='+pid;
			return;
		}
		resetSearchValues();
		$('textgrname').value='';
		$('textgrtitle').value='';
		if($('textgrprogarea')!=null){
			$('textgrprogarea').options[0].selected = true;
			rollBackTextColor($('textgrprogarea') );
		}
		$('textgramount').options[0].selected = true;
		
		rollBackTextColor($('textgrname') );
		rollBackTextColor($('textgrtitle') );
		rollBackTextColor($('textgramount') );
		if( $('showall')!=null ) $('showall').style.display = 'none';
		recenterMap(center_point, 4);
		if( showKey ) pid=0;
		if( clearsearch )showProgramAreaGrants('');
		locationsearch=false;
		criteriasearch=false;
		clearsearch=false;
	}

	function searchMap(){
		if( locationsearch ){
			if ( $('textsearch').value.length ){
				if( $('textsearch').value.length < 3 ) {
					alert("Please enter a full name of city or state"); return;
				}
				geocoder.getLatLng( $('textsearch').getValue(), function(point){
					if (!point) alert("Please try again ");
					else recenterMap(point,  parseInt($('mileSelector').options[$('mileSelector').selectedIndex].value ));
				}) ;
			}
			else{
				resetSearchValues();
				recenterMap(center_point, 4);
				locationsearch = false;
			}
		}
		if(criteriasearch ){
			url='';
			if( $('textgrname').value.length ) url+='&grname='+escape($('textgrname').value);
			if( $('textgrtitle').value.length ) url+='&grtitle='+escape($('textgrtitle').value);

			amountArr  = $('textgramount').options[$('textgramount').selectedIndex].value.split('-');
			if(parseInt(amountArr[1])) url+=parseInt(amountArr[1])==1?'&gramountmin='+escape(amountArr[0]): '&gramountmin='+escape(amountArr[0])+'&gramountmax='+escape(amountArr[1]);
			criteriasearch=false;
			clearsearch=true;
			map.clearOverlays();
			if(id) id=1;
			if( !locationsearch && map.getZoom() > 9 ) map.setZoom(9);
			showProgramAreaGrants(url);
		}
//		HBX_View();
	}

	function recenterMap(point, zoom){
		map.setCenter(point, zoom );
		map.panTo(point);
		map.setZoom(zoom);
	}

	function showSearch(){
		return;
		$('searchMapDiv').style.display='block';
		$('tab_first').style.borderBottom='0';
		$('tab_second').style.borderBottom='1px solid gray';
		if( showKey )$('codedKey').style.display='block';
		
		$('panel_first').style.display='block';
	   	$('panel_second').style.display='none';
		
	}
	function showHints(){
		return;
		$('searchMapDiv').style.display='block';
		$('tab_first').style.borderBottom='1px solid gray';
		$('tab_second').style.borderBottom='0';
		if( showKey )$('codedKey').style.display='block';
		
		$('panel_first').style.display='none';
		$('panel_second').style.display='block';
	}

	function hidePanels(){
		return;
		$('searchMapDiv').style.display='none';
		$('codedKey').style.display='none';
	}


	function trim( string ){
    // trim the string from spaces front & back of string
		string = string.replace(/^\s+/g, "" );
        return string.replace(/\s+$/g, "" );
    }//trim
