
// Define Global varables here.
  var geocoder;
  var map = null;
  var markerClusterer = null;
  var markers = [];

  var postcode ='';
  var customIcons = {
      1: {
        icon: 'http://chart.apis.google.com/chart?cht=mm&chs=12x20&chco=FFFFFF,008CFF,000000&ext=.png',
        shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
      },
      2: {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
        shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
      },
      3: {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
        shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
      },
      4: {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_purple.png',
        shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
      },
      5: {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png',
        shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
      },
      6: {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_yellow.png',
        shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
      },
      7: {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_black.png',
        shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
      },
      8: {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_brown.png',
        shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
      },
      9: {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_grey.png',
        shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
      },
      service: {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png',
        shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
      },
      serviceView: {
        icon: 'http://maps.google.com/mapfiles/arrow.png',
        shadow: 'http://maps.google.com/mapfiles/arrowshadow.png'
      },
      locationView: {
        icon: 'http://maps.google.com/mapfiles/arrow.png',
        shadow: 'http://maps.google.com/mapfiles/arrowshadow.png'
      }
    };


  // Finding out the long and lat of an address (Geocode address)
  function codeAddress(address) {

    //initializeMap();
	geocoder = new google.maps.Geocoder();
	//var address = document.getElementById("address").value;
    geocoder.geocode( { 'address': address + ''}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
      	//console.log(results[0]);
      	document.getElementById("lonlat").value = results[0].geometry.location;
      	jQuery('#map_status_msg').html('Geocoding was successful.');
      	jQuery("#map_status_msg").attr("style", "color:#93A52F");
      } else {
      	if (document.getElementById("lonlat").value != '') {
      		//jQuery('#map_status_msg').html("Geocode was not successful for the following reason: " + status);
      		jQuery("#map_status_msg").attr("style", "color:#f00");
      		jQuery('#map_status_msg').html("Geocoding was not successful, your distance search might not be completely accurate.");
			//document.getElementById("map_status_msg").value = "Geocode was not successful for the following reason: " + status;
      		//console.log("Geocode was not successful for the following reason: " + status);
			//alert("Geocode was not successful for the following reason: " + status);
      	}

      }
    });

  }


  /*

  TNT Travel Map

  */
     function loadGoogleTravelMap() {
		jQuery('#travel_map_canvas').attr("style", "display:block");
		var zoomval = 2;

		map = new google.maps.Map(document.getElementById("travel_map_canvas"), {
	        center: new google.maps.LatLng(25.000, -1.2959),
	        //center: new google.maps.LatLng(lat,lon),
	        zoom: zoomval,
	        minZoom: 2,
   			maxZoom: 15,
	        mapTypeId: google.maps.MapTypeId.SATELLITE
	 	});
      	var infoWindow = new google.maps.InfoWindow;

      	google.maps.event.addListener(map, 'zoom_changed', function() {
			// Update the hidden zoom value  in the form
			//selestiConsole('zoom changed'+map.getZoom());

		});

			google.maps.event.addListener(map, 'zoom_changed', function() {
			// Update the hidden zoom value  in the form
			//selestiConsole('zoom changed'+map.getZoom());

		});



		// Change this depending on the name of your PHP file
		downloadUrl("/travel/googleMapXML",  function(data) {
		//downloadUrl("/drawmap/pointInPolygon?longLat="+longLat+"&keyword="+keyword+"&categories="+categories,  function(data) { // Search in pollygon testing.
			var xml = data.responseXML;
			var markers = xml.documentElement.getElementsByTagName("marker");
		    var markersArray = [];

			for (var i = 0; i < markers.length; i++) {
				var name = markers[i].getAttribute("name");

				var url = markers[i].getAttribute("url");

				var point = new google.maps.LatLng(
					parseFloat(markers[i].getAttribute("lat")),
					parseFloat(markers[i].getAttribute("lon")));
				var html = "<div class='mapBubble'><a href='" + url + "' class='title'><a href='" + url + "'>" + name + "</a> </div>";
				var icon = customIcons[2] || {};
				var marker = new google.maps.Marker({
					map: map,
					position: point,
					icon: icon.icon,
					html: html//,
					//shadow: icon.shadow
				});

				// Set a listing on this marker to open the InfoWindow
				// markerClick can be edited to close all current info windows if
				// required.
				//var fn = markerClick(html, point);
				//google.maps.event.addListener(marker,"click",fn);

				// Add this marker to the markers array.
				//markersArray.push(marker);						// For clustering put each marker in the markersArray
				bindInfoWindow(marker, map, infoWindow, html);		// For non clustering render the marker on the map with the info window
			} // For Loop

			//mc = new MarkerClusterer(map, markersArray);			// Show the clustered markersArray on the selected map
			//var number_of_results = markersArray.length;
			//if (number_of_results == 0) {
			//	jQuery('#noResults').show();
			//}
		}); // Download URL

    }
    /*

     End Travel Map

	 */




    function bindInfoWindow(marker, map, infoWindow, html) {
      google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(html);
        infoWindow.open(map, marker);
      });
    }

    function downloadUrl(url, callback) {
      var request = window.ActiveXObject ?
          new ActiveXObject('Microsoft.XMLHTTP') :
          new XMLHttpRequest;

      request.onreadystatechange = function() {
        if (request.readyState == 4) {
          request.onreadystatechange = doNothing;
          callback(request, request.status);
        }
      };

      request.open('GET', url, true);
      request.send(null);
    }

    function doNothing() {}



   function loadGoogleMapForEventDetail(longLat, zoom, lat,lon,locationId) {
		//jQuery('#map').attr("style", "display:block");

		var zoomval = 5;
		if (zoom) {
			zoomval = zoom;
		}
		else
		{
			// might need to specify them as lon and lat and all ints for  line 81 below.
			lat = 55.000;
			lon = -4.2959;
		}

		map = new google.maps.Map(document.getElementById("eventMap"), {
	        //center: new google.maps.LatLng(55.000, -4.2959),
	        center: new google.maps.LatLng(lat,lon),
	        zoom: zoomval,
	        mapTypeId: 'roadmap'
	      });

      	var infoWindow = new google.maps.InfoWindow;

		// Change this depending on the name of your PHP file
		downloadUrl("/events/googleMapXML?id="+locationId,  function(data) {
			var xml = data.responseXML;
			var markers = xml.documentElement.getElementsByTagName("marker");
			for (var i = 0; i < markers.length; i++) {
				//console.log(markers[i]);
				//var name = markers[i].getAttribute("location_name");
				var point = new google.maps.LatLng(
					parseFloat(markers[i].getAttribute("lat")),
					parseFloat(markers[i].getAttribute("lon")));
				var icon = customIcons['locationView'] || {};
				var marker = new google.maps.Marker({
					map: map,
					position: point,
					icon: icon.icon
				});
				//bindInfoWindow(marker, map, infoWindow);
			} // For Loop
		}); // Download URL
    }

    function loadGoogleMapDirectory(longLat, zoom, lat,lon,keyword,categories) {
		jQuery('#map_canvas').attr("style", "display:block");
		var zoomval = 9;
		if (zoom) {
			zoomval = zoom;
		}
		else
		{
			lat = 52.600;
			lon = 1.400;
		}
		//console.log(lon+" "+lat);

		map = new google.maps.Map(document.getElementById("map_canvas"), {
	        //center: new google.maps.LatLng(55.000, -4.2959),
	        center: new google.maps.LatLng(lat,lon),
	        zoom: zoomval,
	        mapTypeId: 'roadmap'
	      });

		google.maps.event.addListener(map, 'zoom_changed', function() {
				// Update the hidden zoom value  in the form
				jQuery('#directoryMapZoomLevel').val(map.getZoom());
		});

      	var infoWindow = new google.maps.InfoWindow;

      	jQuery('#noResults').hide();

      	// Update the category counts
      	var location = jQuery('#location').val();
      	var zoom = jQuery('#directoryMapZoomLevel').val();

      	jQuery.ajax({
			type: 'POST',
			url: '/directory/json/1',
			dataType: 'json',
			data: ({ lonlat: longLat, location:location , keywords:keyword, zoom :zoom,  categories:categories }),
			success: function (data){
				jQuery.each(data['checkboxOptions'], function(key, val) {
					jQuery('.locationCategoriesCheckboxes').children().find('.checkbox_'+val['location_category_id']).html('('+val['count']+')');
				});
			}

		}); // ajax call

		// Change this depending on the name of your PHP file
		downloadUrl("/directory/googleMapXML?longLat="+longLat+"&keywords="+keyword+"&categories="+categories,  function(data) {
		//downloadUrl("/drawmap/pointInPolygon?longLat="+longLat+"&keyword="+keyword+"&categories="+categories,  function(data) { // Search in pollygon testing.
			var xml = data.responseXML;
			var markers = xml.documentElement.getElementsByTagName("marker");
		    var markersArray = [];

			for (var i = 0; i < markers.length; i++) {
				var name = markers[i].getAttribute("name");
				var address = markers[i].getAttribute("address");
				var url = markers[i].getAttribute("url");
				var logo = markers[i].getAttribute("logo");
				var photos = markers[i].getAttribute("photos");
				var videos = markers[i].getAttribute("videos");
				var reviews = markers[i].getAttribute("reviews");
				var id = markers[i].getAttribute("id");
				var category = markers[i].getAttribute("category");
				var point = new google.maps.LatLng(
					parseFloat(markers[i].getAttribute("lat")),
					parseFloat(markers[i].getAttribute("lon")));
				var html = "<div class='mapBubble'><a href='/directory/view/" + url + "'><img src='/thumb?file=" + logo + "&width=264&height=182&force=yes&crop=yes'></a><h1><a href='/directory/view/" + url + "'>" + name + "</a></h1><ul class='horizontal_menu'><li><a href='/directory/view/" + url + "'>" + photos + " Photos</a></li><li class='bar'>|</li><li><a href='/directory/view/" + url + "'>" + videos + " Videos</a></li><li class='comments_bubble'><a href='/directory/view/" + url + "'>" + reviews + "</a></li></ul><a class='view_profile' href='/directory/view/" + url + "'><img title='View " + name + " Profile' alt='View " + name + " Profile' src='/images/directory_view_profile.png'></a></div>";
				var icon = customIcons[category] || {};
				var marker = new google.maps.Marker({
					map: map,
					position: point,
					icon: icon.icon,
					html: html//,
					//shadow: icon.shadow
				});

				// Set a listing on this marker to open the InfoWindow
				// markerClick can be edited to close all current info windows if
				// required.
				var fn = markerClick(html, point);
				google.maps.event.addListener(marker,"click",fn);

				// Add this marker to the markers array.
				markersArray.push(marker);						// For clustering put each marker in the markersArray
				//bindInfoWindow(marker, map, infoWindow, html);		// For non clustering render the marker on the map with the info window
			} // For Loop

			mc = new MarkerClusterer(map, markersArray);			// Show the clustered markersArray on the selected map
			var number_of_results = markersArray.length;
			if (number_of_results == 0) {
				jQuery('#noResults').show();
			}
		}); // Download URL

    }

	// function to build a function to respond to the click on a marker
	var infowindow = new google.maps.InfoWindow();
	var activeWindow = null;
	function markerClick(html, latlng) {
		return function() {
			var width = jQuery('#map_controls').width();
			if (width) {
				closeSearchMapControls();
			}
			// Close other info window if set.
			if(activeWindow != null) activeWindow.close();
			infowindow = new google.maps.InfoWindow({
				content: html,
				position:latlng
			});
			// open an info window with the information

			//map.setCenter(latlng);
			infowindow.open(map);
			map.panTo(latlng);
			//setCenter(center:latlng);
			activeWindow = infowindow;
		}
	}

   function loadGoogleMapForDirectoryProfile(longLat, zoom, lat,lon,locationId) {
		//jQuery('#map').attr("style", "display:block");

		var zoomval = 5;
		if (zoom) {
			zoomval = zoom;
		}
		else
		{
			// might need to specify them as lon and lat and all ints for  line 81 below.
			lat = 55.000;
			lon = -4.2959;
		}
		map = new google.maps.Map(document.getElementById("map"), {
	        //center: new google.maps.LatLng(55.000, -4.2959),
	        center: new google.maps.LatLng(lat,lon),
	        zoom: zoomval,
	        mapTypeId: 'roadmap'
	      });
      	var infoWindow = new google.maps.InfoWindow;

		// Change this depending on the name of your PHP file
		downloadUrl("/directory/googleMapXML?id="+locationId,  function(data) {
			var xml = data.responseXML;
			var markers = xml.documentElement.getElementsByTagName("marker");
			for (var i = 0; i < markers.length; i++) {
				var name = markers[i].getAttribute("name");
				var address = markers[i].getAttribute("address");
				var url = markers[i].getAttribute("url");
				var logo = markers[i].getAttribute("logo");
				var photos = markers[i].getAttribute("photos");
				var videos = markers[i].getAttribute("videos");
				var reviews = markers[i].getAttribute("reviews");
				var id = markers[i].getAttribute("id");
				var category = markers[i].getAttribute("category");
				var point = new google.maps.LatLng(
					parseFloat(markers[i].getAttribute("lat")),
					parseFloat(markers[i].getAttribute("lon")));
				var html = "<div class='mapBubble'><a href='/directory/view/" + url + "'><img src='/thumb?file=" + logo + "&width=260&height=180&force=yes&crop=yes'></a><h1><a href='/directory/view/" + url + "'>" + name + "</a></h1><ul class='horizontal_menu'><li><a href='/directory/view/" + url + "'>" + photos + " Photos</a></li><li class='bar'>|</li><li><a href='/directory/view/" + url + "'>" + videos + " Videos</a></li><li class='comments_bubble'><a href='/directory/view/" + url + "'>" + reviews + "</a></li></ul><a class='view_profile' href='/directory/view/" + url + "'><img title='View " + name + " Profile' alt='View " + name + " Profile' src='/images/directory_view_profile.png'></a></div>";
				var icon = customIcons['locationView'] || {};
				var marker = new google.maps.Marker({
					map: map,
					position: point,
					icon: icon.icon//,
					//shadow: icon.shadow
				});
				//bindInfoWindow(marker, map, infoWindow, html);
			} // For Loop
		}); // Download URL
    }



    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	// ~~~~~~~~~~~~~~~~~~~~~~ Directy Searching ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   	// Declare these vars as globals, so we can call them from the google map js
	var keyword;
	var checkedBoxesIds;
	postcode = postcode;
    function directorySearch(){

    	keyword 	= jQuery('#keywords').val();
    	postcode 	= jQuery('#location').val();
    	zoom		= parseInt(jQuery('#directoryMapZoomLevel').val());

		var lon = 1.400;
		var	lat = 52.600;

    	var location_category_ids = '';
    	jQuery('.lookingForCheckBox').each(function(index,item) {
    		jQuery(this).attr('id');
    		if (item.checked) {
    			var checkBoxId = jQuery(this).attr('id');
    			var checkboxArray = checkBoxId.split("_");
    			location_category_ids = location_category_ids+checkboxArray[1]+',';
    			//console.log(jQuery(this).attr('id'));
    		}
		});
		//console.log(location_category_ids);

		if (keyword == 'Type a keyword...') {
			keyword = '';
		}
		if (postcode == 'Location (e.g. Norwich)') {
			postcode = '';
		}

		if (map != null) {
			zoom = map.getZoom();
			lat = map.getCenter().lat();
			lon = map.getCenter().lng();
			//console.log(map.getCenter());
		}


		if (postcode.length) {
			var geocoder;
		  	geocoder = new google.maps.Geocoder();
		  	geocoder.geocode( { 'address': postcode + ', UK'}, function(results, status) {
			    if (status == google.maps.GeocoderStatus.OK) {
			    	//console.log('Debug SearchAddress function in googlemap.js');
					//console.log(results[0].geometry);
					//console.log(address);

					var lat = results[0].geometry.location.lat();
					var lon = results[0].geometry.location.lng();
			    	jQuery('#searchPostCode').html('');

			    	// Send the postcode to the directory search script and load the html on  page
			    	// ^^ only needed if we want to show the list of locations in a list or grid view.
					//jQuery.get("/directory/search",{keyword: keyword, tyres: tyres, breakers: breakers, services: services, sales: sales,letter: letter, lon: lon , lat: lat, type: 1 }, function(data){
					//	jQuery(".result").html(data);
					//});

					//load the google map with the markers and zoom to the geocoded address
					// that was entered in the postcode field.
					loadGoogleMapDirectory(results[0].geometry.location,zoom,lat,lon,keyword,location_category_ids);
			      	return true;
			    }
			    else
			    {
			    	jQuery('#searchPostCode').html("Sorry looks like your postcode was not known.");
			    	//jQuery('#searchPostCode').html("Geocode was not successful for the following reason: " + status);
					//alert("Geocode was not successful for the following reason: " + status);
			    	return false;
				}
		 	});
		}
		else
		{
			// No postcode specifed, so lets do a normal search without geocoding the address
			loadGoogleMapDirectory('(52.600, 1.400)',zoom,lat,lon,keyword,location_category_ids);
		}

		return true;
    }


    function directorySearchNoMap(){

    	var keyword 	= jQuery('#keywords').val();
    	var postcode 	= jQuery('#location').val();
    	var zoom		= parseInt(jQuery('#directoryMapZoomLevel').val());

		var lon = 1.400;
		var	lat = 52.600;

    	var location_category_ids = '';
    	jQuery('.lookingForCheckBox').each(function(index,item) {
    		jQuery(this).attr('id');
    		if (item.checked) {
    			var checkBoxId = jQuery(this).attr('id');
    			var checkboxArray = checkBoxId.split("_");
    			location_category_ids = location_category_ids+checkboxArray[1]+',';
    			//console.log(jQuery(this).attr('id'));
    		}
		});
		//console.log(location_category_ids);

		if (keyword == 'Type a keyword...') {
			keyword = '';
		}
		if (postcode == 'Location (e.g. Norwich)') {
			postcode = '';
		}

		if (map != null) {
			zoom = map.getZoom();
			lat = map.getCenter().lat();
			lon = map.getCenter().lng();
			//console.log(map.getCenter());
		}

		//var possplit = strpos(top.location.href, '?');
		//var newHref = rtrim(top.location.href,possplit);

		//top.location.href = "/directory/sortBy/"+sortByVal;

		if (postcode.length) {
			var geocoder;
		  	geocoder = new google.maps.Geocoder();
		  	geocoder.geocode( { 'address': postcode + ', UK'}, function(results, status) {
			    if (status == google.maps.GeocoderStatus.OK) {
			    	//console.log('Debug SearchAddress function in googlemap.js');
					//console.log(results[0].geometry);
					//console.log(address);

					var lat = results[0].geometry.location.lat();
					var lon = results[0].geometry.location.lng();
					jQuery('#lonlat').val(results[0].geometry.location);
			    	jQuery('#searchPostCode').html('');

			    	// Send the postcode to the directory search script and load the html on  page
			    	// ^^ only needed if we want to show the list of locations in a list or grid view.
					//jQuery.get("/directory/search",{keyword: keyword, tyres: tyres, breakers: breakers, services: services, sales: sales,letter: letter, lon: lon , lat: lat, type: 1 }, function(data){
					//	jQuery(".result").html(data);
					//});

					//load the google map with the markers and zoom to the geocoded address
					// that was entered in the postcode field.
					loadGoogleMapDirectory(results[0].geometry.location,zoom,lat,lon,keyword,location_category_ids);
			      	return true;
			    }
			    else
			    {
			    	jQuery('#searchPostCode').html("Sorry looks like your postcode was not known.");
			    	//jQuery('#searchPostCode').html("Geocode was not successful for the following reason: " + status);
					//alert("Geocode was not successful for the following reason: " + status);
			    	return false;
				}
		 	});
		}
		else
		{
			// No postcode specifed, so lets do a normal search without geocoding the address
			loadGoogleMapDirectory('(52.600, 1.400)',zoom,lat,lon,keyword,location_category_ids);
		}

		return true;
    }


	function googleMapGeoCodeLocation(){
	    var address = document.getElementById("location").value;
	    if (address == 'Location (e.g. Norwich)' || address =='') {
			jQuery('#lonlat').val('');
	    }
	    else
	    {
	    	codeAddress(address);
	    }
	    //console.log(address);

	}
function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
