var herbalist_data = [];

var map;
    var geocoder;

//initial load map and locate the center with lat and lng
    function load() {
      if (GBrowserIsCompatible()) {
        geocoder = new GClientGeocoder();
        map = new GMap2(document.getElementById('map'));
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(54.622978,-2.592773), 5);

      }
    }

    // trim whitespace from beggining and end of string
    function lrtrim(val) {
       r = val.match(/^\s*(.*[^\s])\s*$/);
       r = r ? r[1] : '';
       // console.log('val is: ' + val + " returned: |" + r + "|" );
       return r;
    }

// search location by getting the field variables from the form. 
   function searchLocations() {

	 var firstname = lrtrim(document.getElementById('firstname').value);
	 var lastname =  lrtrim(document.getElementById('lastname').value);
	 var business =  lrtrim(document.getElementById('business').value);
	 var town_city = lrtrim(document.getElementById('town_city').value);
	 var county =    document.getElementById('region').value;
	 var postcode =  lrtrim(document.getElementById('postcode').value);
     var country =   document.getElementById('country').value;
	 

	 //generate the xml file by passing the data with url
	 var searchUrl = 'genxmlformap.php?firstname=' + firstname +'&lastname=' + lastname + '&business=' + business +'&town_city='+town_city+ '&herbalist_region_id='+county+'&postcode='+postcode+'&herbalist_country_id=' + country;
	 
     GDownloadUrl(searchUrl, function(data)
	{
       var xml = GXml.parse(data);
       var markers = xml.documentElement.getElementsByTagName('herbalists');
       map.clearOverlays();

       //var sidebar = document.getElementById('sidebar');
       //sidebar.innerHTML = '';
       if (markers.length == 0) 
	   {
        // sidebar.innerHTML = 'No results found.';
         map.setCenter(new GLatLng(54.622978,-2.592773), 5);
         return;
       }

       var bounds = new GLatLngBounds();
       for (var i = 0; i < markers.length; i++) 
	   {
		   if(markers[i].getAttribute('lat')!= 0 && markers[i].getAttribute('lng')!=0)
		   {
         var firstname = markers[i].getAttribute('firstname');
		 var lastname = markers[i].getAttribute('lastname');
         var address1 = markers[i].getAttribute('address1');
		 var address2 = markers[i].getAttribute('address2');
		 var address3 = markers[i].getAttribute('address3');
		 var postcode = markers[i].getAttribute('postcode');
		 var business = markers[i].getAttribute('business');
		 var country = markers[i].getAttribute('country');
		 var county = markers[i].getAttribute('county');
		 var website = markers[i].getAttribute('website');
		 var phone = markers[i].getAttribute('phone');
         var distance = parseFloat(markers[i].getAttribute('distance'));
         var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')),
                                 parseFloat(markers[i].getAttribute('lng')));
         
         var marker = createMarker(point, firstname, lastname, business,address1, address2,address3, postcode,county,country,website,phone);
		 
         map.addOverlay(marker);
         //var sidebarEntry = createSidebarEntry(marker, firstname, lastname, address1, address2, postcode, distance);
         //sidebar.appendChild(sidebarEntry);
         bounds.extend(point);
		   }
       }
       map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
     });
     
   }


    function createMarker(point, firstname, lastname, business, address1, address2, address3, postcode, county, country,website,phone) {
      var marker = new GMarker(point);
      //var html = '<small>Name: '+firstname + ' '+ lastname + ' </small> <br /> <small>Business: ' + business + '</small> <br /> <small>Address: ' +address1 +' ' +address2 +' '+address3+' '+ country+' '+postcode+'</small><br /><small>Website: <a href="'+website+'">'+website+'</a></small><br /><small>Tel: '+phone+'<small>';
	  //var html = '<div style="width: 210px; padding-right: 10px"><a href="http://www.tanchen.net"> terence studio</a> 12B Argyle Road, St. Pauls, Bristol, UK , BS2 8UU</div>';
	  var html = '<div style="width: 210px; height:100px; padding-right: 10px"><small>Name: '+firstname + ' '+ lastname + ' </small> <br /> <small>Business: ' + business + '</small> <br /> <small>Address: ' +address1 +' ' +address2 +' '+address3+' '+ country+' '+postcode+'</small><br /><small>Website: <a href="http://'+website+'">'+website+'</a></small><br /><small>Tel: '+phone+'<small></div>';
	
      GEvent.addListener(marker, 'click', function() {
        marker.openInfoWindowHtml(html);
      });
	 
      return marker;
    }

    function createSidebarEntry(marker, firstname, lastname, business, address1, address2, address3, postcode, county, country, website) {
      var div = document.createElement('div');
      var html = '<b>' + firstname + '</b> (' + distance.toFixed(1) + ')<br/>' + address1+'<br/>'+postcode;
      div.innerHTML = html;
      div.style.cursor = 'pointer';
      div.style.marginBottom = '5px'; 
      GEvent.addDomListener(div, 'click', function() {
        GEvent.trigger(marker, 'click');
      });
      GEvent.addDomListener(div, 'mouseover', function() {
        div.style.backgroundColor = '#eee';
      });
      GEvent.addDomListener(div, 'mouseout', function() {
        div.style.backgroundColor = '#fff';
      });
      return div;
	}
	
	function addLoadEvent(func) 
{
  var oldonload = window.onload;
  if (typeof window.onload != 'function') 
  {
    window.onload = func;
  } 
  else {
       window.onload = function() 
	      {
            oldonload();
            func();
          }
        }
}

function addUnLoadEvent(func) 
{
	var oldonunload = window.onunload;
	if (typeof window.onunload != 'function') 
	{
	  window.onunload = func;
	} else {
	       window.onunload = function() 
	         {
	          oldonunload();
	          func();
	         }
	      }
}

addLoadEvent(load);
addUnLoadEvent(GUnload);
