// JavaScript Document

var xmlHttp

var params

var map;
var geocoder;

 
 var pcheck = true;

var error;


var gmarkers = []; 

 // arrays to hold variants of the info window html with get direction forms open
var to_htmls = [];
var from_htmls = [];

var lat;
var lng;


function getDirectorySub(cat, field) {
	
	
	if (document.getElementById("cat_main").value != "") {
	
		xmlHttp=GetXmlHttpObject();
		if (xmlHttp==null)
  		{
  		alert ("Your browser does not support AJAX!");
  		return;
  		} 
		params = "cat=" + document.getElementById("cat_main").value + 
				"&select=" + field;
		var url="directorysubcat.php";
		xmlHttp.onreadystatechange=stateChangedtotal;
		xmlHttp.open("POST",url,true);
		//Send the proper header information along with the request
		xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlHttp.setRequestHeader("Content-length", params.length);
		xmlHttp.setRequestHeader("Connection", "close");
		xmlHttp.send(params);
		
	} 
		
}


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, G_NORMAL_MAP);
      }
}
	

/*function searchLocations() {
     var postcode = document.getElementById('postcode').value;
     geocoder.getLatLng(postcode, function(latlng) {
       if (!latlng) {
		 pcheck = false;
		 error = '<span class="red">Postcode not found!</span><div class="search_box_row">&nbsp;</div>';
		
		document.getElementById("search_error").innerHTML=error;
       } else {
         searchLocationsNear(latlng);
       }
     });
   }*/
   

function searchLocationsNear(center, start, numpages) {
	lat = center.lat();
	lng = center.lng();
	
	// Send the details to the php page to get the results
	if((document.getElementById("cat_sub")) && document.getElementById("cat_sub").value != "") {
		var cat = document.getElementById("cat_sub").value;
	} else {
		var cat = document.getElementById("cat_main").value;
	}
		
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null)
  	{
  	alert ("Your browser does not support AJAX!");
  	return;
  	} 
			
			
			var searchUrl = 'directoryresults.php?lat=' + lat + '&lng=' + lng + '&radius=' + document.getElementById("radius").value + '&cat=' + cat + '&cn=' + document.getElementById("company_name").value + '&bc=' + document.getElementById("business_county").value + '&s=' + start + '&np=' + numpages;
			GDownloadUrl(searchUrl, function(data) {
       			var xml = GXml.parse(data);
      			var markers = xml.documentElement.getElementsByTagName('marker');
       			map.clearOverlays();

       			if (markers.length == 0) {
        			map.setCenter(new GLatLng(54.622978,-2.592773), 5, G_NORMAL_MAP);
         			return;
       			}

       			var bounds = new GLatLngBounds();
       			for (var i = 0; i < markers.length; i++) {
        			var name = markers[i].getAttribute('name');
         			var address = markers[i].getAttribute('address');
					var addresstwo = markers[i].getAttribute('addresstwo');
					var tel = markers[i].getAttribute('tel');
					var website = markers[i].getAttribute('website');
         			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, name, address, addresstwo, tel, website, distance);
         			map.addOverlay(marker);
         			bounds.extend(point);
       			}
				var zoomnew = map.getBoundsZoomLevel(bounds);
				if (zoomnew > 14) {
       				map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds) - 2);
				} else {
					map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
				}
     		});
			
			params = "cat=" + cat + 
				"&cn=" + document.getElementById("company_name").value +
				"&bc=" + document.getElementById("business_county").value +
				"&lat=" + lat +
				"&lng=" + lng +
				"&radius=" + document.getElementById("radius").value +
				"&s=" + start +
				"&np=" + numpages;
			var url="directoryresultshtml.php";
			xmlHttp.onreadystatechange=stateChangedtotal4;
			xmlHttp.open("POST",url,true);
			//Send the proper header information along with the request
			xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			xmlHttp.setRequestHeader("Content-length", params.length);
			xmlHttp.setRequestHeader("Connection", "close");
			xmlHttp.send(params);
			showLoader();
	
}



function getDirectoryResults(start, numpages) {
	
	// Check for at least one criteria
	if ((document.getElementById("cat_main").value == "") && (document.getElementById("company_name").value == "")) {
		
		error = '<span class="red">Please select a directory category or enter a company name</span><div class="search_box_row">&nbsp;</div>';
		
		document.getElementById("search_error").style.display = '';
		document.getElementById("search_error").innerHTML=error;
		
	} else {
		
		if (document.getElementById("postcode").value != "") {
			var postcode = document.getElementById('postcode').value;
    		geocoder.getLatLng(postcode, function(latlng) {
       			if (!latlng) {
					pcheck = false;
		 			error = '<span class="red">Postcode not found!</span><div class="search_box_row">&nbsp;</div>';
		
					document.getElementById("search_error").style.display = '';
					document.getElementById("search_error").innerHTML=error;
       			} else {
         			searchLocationsNear(latlng, start, numpages);
       			}
     		});
		} else {
			pcheck = true;
			lat = '';
			lng = '';			
		
			// Send the details to the php page to get the results
			if((document.getElementById("cat_sub")) && document.getElementById("cat_sub").value != "") {
				var cat = document.getElementById("cat_sub").value;
			} else {
				var cat = document.getElementById("cat_main").value;
			}
		
			xmlHttp=GetXmlHttpObject();
			if (xmlHttp==null)
  			{
  			alert ("Your browser does not support AJAX!");
  			return;
  			} 
			
			
			var searchUrl = 'directoryresults.php?lat=' + lat + '&lng=' + lng + '&radius=' + document.getElementById("radius").value + '&cat=' + cat + '&cn=' + document.getElementById("company_name").value + '&bc=' + document.getElementById("business_county").value + '&s=' + start + '&np=' + numpages;
			GDownloadUrl(searchUrl, function(data) {
       			var xml = GXml.parse(data);
      			var markers = xml.documentElement.getElementsByTagName('marker');
       			map.clearOverlays();

       			if (markers.length == 0) {
        			map.setCenter(new GLatLng(54.622978,-2.592773), 5, G_NORMAL_MAP);
         			return;
       			}

       			var bounds = new GLatLngBounds();
       			for (var i = 0; i < markers.length; i++) {
        			var name = markers[i].getAttribute('name');
         			var address = markers[i].getAttribute('address');
					var addresstwo = markers[i].getAttribute('addresstwo');
					var tel = markers[i].getAttribute('tel');
					var website = markers[i].getAttribute('website');
         			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, name, address, addresstwo, tel, website, distance);
         			map.addOverlay(marker);
         			bounds.extend(point);
       			}
				var zoomnew = map.getBoundsZoomLevel(bounds);
				if (zoomnew > 14) {
       				map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds) - 2);
				} else {
					map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
				}
     		});
			
			params = "cat=" + cat + 
				"&cn=" + document.getElementById("company_name").value +
				"&bc=" + document.getElementById("business_county").value +
				"&lat=" + lat +
				"&lng=" + lng +
				"&radius=" + document.getElementById("radius").value +
				"&s=" + start +
				"&np=" + numpages;
			var url="directoryresultshtml.php";
			xmlHttp.onreadystatechange=stateChangedtotal4;
			xmlHttp.open("POST",url,true);
			//Send the proper header information along with the request
			xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			xmlHttp.setRequestHeader("Content-length", params.length);
			xmlHttp.setRequestHeader("Connection", "close");
			xmlHttp.send(params);
			showLoader();
			
		} 
		
	}
		
}



function stateChangedtotal() 
{ 
if (xmlHttp.readyState==4)
{ 
document.getElementById("search_sub").style.display = '';
document.getElementById("search_error").style.display = 'none';
document.getElementById("search_cat_sub").innerHTML=xmlHttp.responseText;
}
}


function stateChangedtotal4() 
{ 
if (xmlHttp.readyState==4)
{ 
document.getElementById("search_error").style.display = 'none';
document.getElementById("result_holder").innerHTML=xmlHttp.responseText;
hideLoader();
}
}

function showLoader(){
 document.getElementById('loader').style.display = 'block';
}
function hideLoader(){
 document.getElementById('loader').style.display = 'none';
}


function createMarker(point, name, address, addresstwo, tel, website, distance) {
	  if (website != "") {
		 var web = '<br/><a href="' + website + '">' + website + '</a>';  
	  } else {
	  	var web = '';
	  }
	  if (distance) {
		var dist = '<br/><br/>Distance: ' + distance.toFixed(2) + ' miles';
	  } else {
		
		 var dist = '';  
	  }
      var marker = new GMarker(point);
	  var b = gmarkers.length;
      var html = '<b>' + name + '</b> <br/>' + address + '<br/>' + addresstwo + '<br/>' + tel + web + dist;
	  
	  // The info window version with the "to here" form open
      to_htmls[b] = html + '<br><br>Directions: <b>To here<\/b> - <a href="javascript:fromhere(' + b + ')">From here<\/a>' +
           '<br><br>Start address:<form action="http://maps.google.com/maps" method="get" target="_blank">' +
           '<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="' + document.getElementById('postcode').value +'" /><br>' +
           '<INPUT value="Get Directions" TYPE="SUBMIT">' +
           '<input type="hidden" name="daddr" value="' + point.lat() + ',' + point.lng() + 
                  // "(" + name + ")" + 
           '"/>';
      // The info window version with the "to here" form open
      from_htmls[b] = html + '<br><br>Directions: <a href="javascript:tohere(' + b + ')">To here<\/a> - <b>From here<\/b>' +
           '<br><br>End address:<form action="http://maps.google.com/maps" method="get"" target="_blank">' +
           '<input type="text" SIZE=40 MAXLENGTH=40 name="daddr" id="daddr" value="' + document.getElementById('postcode').value +'" /><br>' +
           '<INPUT value="Get Directions" TYPE="SUBMIT">' +
           '<input type="hidden" name="saddr" value="' + point.lat() + ',' + point.lng() +
                  // "(" + name + ")" + 
           '"/>';
		   
		// The inactive version of the direction info
        html = html + '<br><br>Directions: <a href="javascript:tohere('+b+')">To here<\/a> - <a href="javascript:fromhere('+b+')">From here<\/a>';
	   
	  
	  
      GEvent.addListener(marker, 'click', function() {
        marker.openInfoWindowHtml(html);
      });
	  gmarkers.push(marker);
      return marker;
    }


// functions that open the directions forms
function tohere(b) {
	gmarkers[b].openInfoWindowHtml(to_htmls[b]);
}
      
function fromhere(b) {
	gmarkers[b].openInfoWindowHtml(from_htmls[b]);
}


function GetXmlHttpObject()
{
var xmlHttp=null;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
return xmlHttp;
}
