var map;
var geocoder;
var icon_path = '/images/icons/';
var active_marker;

var site_cnt=0;

var first_site_info_done=0;

	//load the google map according to our settings
	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(53.559567, -2.856445), 6);
		}
	}

	function searchLocations(search_type) {
		var address='';
		switch (search_type){
			case 1:
			case 2:
				address = document.getElementById('start_addr').value;
				break;
			case 4:
				address = document.getElementById('near').value;
			break;
		}

		if (address!='') {			
			geocoder.getLatLng(address, function(latlng) {
				if (latlng) {
					switch (search_type){
						case 1:
							search_LocationsNear(latlng);
						break;										
					}							
				} else {
					alert('Unfortunately the address entered was not recognised');
				}
			});
		}
	}
	
	function search_LocationsNear(center) {
		var radius = document.getElementById('radius').value;
		var searchUrl = '/stockists.xml?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
		var site_id = document.getElementById('site_id').value;
		if (!site_id=='' || !site_id==null){
			searchUrl = searchUrl + '&site_id=' + site_id;
		}
		//get xml data		
		GDownloadUrl(searchUrl, function(data) {
			var xml = GXml.parse(data);
			var markers = xml.documentElement.getElementsByTagName('marker');
			map.clearOverlays();
			
			var sidebar = document.getElementById('sidebar');
			sidebar.innerHTML = '';
			if (markers.length == 0) {
				sidebar.innerHTML = 'No results found. Try expanding your search range.';
				map.setCenter(new GLatLng(55.378051,-3.435973), 5);
				DisplayResultCount(0);
				return;
			}
			
			var bounds = new GLatLngBounds();
			for (var i = 0; i < markers.length; i++) {
				var name = cleanData(markers[i].getAttribute('name'));
				var addr1 = cleanData(markers[i].getAttribute('addr1'));
				var addr2 = cleanData(markers[i].getAttribute('addr2'));
				var addr3 = cleanData(markers[i].getAttribute('addr3'));
				var city = cleanData(markers[i].getAttribute('addr4'));
				var county = cleanData(markers[i].getAttribute('addr5'));
				var postcode = cleanData(markers[i].getAttribute('postcode'));
				var phone_number=cleanData(markers[i].getAttribute('phone_number'));
				var www=cleanData(markers[i].getAttribute('www'));
				var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')),
					parseFloat(markers[i].getAttribute('lng'))
				);
				var distance = parseFloat(markers[i].getAttribute('distance'));

				var www_link = www;
				if (www) {
					www_link = '<a href="http://' + www + '" class="yellow_link window_link" target="_blank">' + www + '</a>';	
				}
				
				var marker_html = '<p class="black"><strong>' + name + '</strong><br/>' + addr1 + addr2 + addr3 + city + county + postcode + ' Tel: <strong>' + phone_number + "</strong><br />" + www_link + "<br/><a href='Javascript:void(0)' onclick='map.setZoom(18)'><img src='/images/icons/icon_zoom.gif' width='16' height='16' alt=' View the site location close up ' style='vertical-align:middle; border: 0px;' />Zoom In</a>&nbsp;<a href='Javascript:void(0)' onclick='map.setZoom(8)'>Zoom Out&nbsp;<img src='/images/icons/icon_zoom_out.gif' width='16' height='16' alt='Zoom Out' style='vertical-align:middle; border: 0px;' /></a>";
				
				//build html to add to the sidebar display
				var side_bar_html='<div style="padding: 5px;"><strong>' + name + '</strong> (' + distance.toFixed(1) + ' miles)<br/>' + addr1 + addr2 +  addr3 + postcode +'<br/>' + ' Tel: ' + phone_number + '<br />' + www_link + '</div>';
				//turn off displaying extra site info
				var site_info_html=null;
				//create a new marker with the html above and also send the extra info to be displayed in the site_info_html
				var marker = createMarker(point, icon_path + 'icon_office' + ".png", marker_html, site_info_html);
				map.addOverlay(marker);
				
				var sidebarEntry = createSidebarEntry(marker, side_bar_html, site_info_html);
				
				sidebar.appendChild(sidebarEntry);
				bounds.extend(point);
			}
			DisplayResultCount(site_cnt);
			site_cnt=0;
			map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
		});
	}
	
	function createMarker(point, icon, html, site_info_html) {
		var pahIcon	= new GIcon(G_DEFAULT_ICON);
		pahIcon.iconSize	= new GSize(23, 24);
		pahIcon.shadow	= "";	
		pahIcon.image = icon;
				
		markerOptions = { icon:pahIcon};
		var marker = new GMarker(point, markerOptions);
		GEvent.addListener(marker, 'click', function() {
			marker.openInfoWindowHtml(html);
			displaySiteInfo(site_info_html);
			active_marker = marker;
		});
		if (first_site_info_done==0) {
			displaySiteInfo(site_info_html);
			first_site_info_done=1;
		}
		
		return marker;
	}
	    	    
	function createSidebarEntry(marker, html, site_info_html) {
		var div = document.createElement('div');
		site_cnt++;
		div.innerHTML = html;
		div.style.cursor = 'pointer';
		div.style.borderBottom='1px solid #30704b';
		div.style.marginBottom = '0px'; 
		div.style.marginTop = '0px'; 
		GEvent.addDomListener(div, 'click', function() {
			GEvent.trigger(marker, 'click');
			displaySiteInfo(site_info_html);			
		});
		GEvent.addDomListener(div, 'mouseover', function() {
			div.style.backgroundColor = '#386151';
		});
		GEvent.addDomListener(div, 'mouseout', function() {
			div.style.backgroundColor = '#063925';
			div.style.color = '#FFF';
			div.style.borderBottom='1px solid #30704b';
		});
		return div;
	}
	//function to display how many results were returned
	function DisplayResultCount(Num) {
		var div_counter = document.getElementById("div_counter");
		if (Num==1){
			div_counter.innerHTML = 'Your search returned: ' + Num + ' result.';
		} else {
			div_counter.innerHTML = 'Your search returned: ' + Num + ' results.';
		}
	}
	//function to display the information associated with the returned site
	function displaySiteInfo(html) {
		if (html!=null){
			var supp_info = document.getElementById('finder_map_supp_info');
			supp_info.style.height='320px';
			supp_info.innerHTML=  '<p>' + html + '</p>';		
		}
	}
	//function to convert a post code to a geocode
	function convert() {
		var address = document.getElementById('start_addr').value;
		geocoder.getLatLng(address, function(latlng) {
			if (!latlng) {
				alert(address + ' not found');
			} else {
				alert('Your geocode - ' + latlng);
			}
		});
	}

	function cleanData(data) {
		//check for null and if found set to blank
		if (data==null || data=='') {
			data='';
		}
		return data;
	}

	function createGIcon(img_url) {
		//Setup custom icon for marker
		var newIcon=new GIcon(G_DEFAULT_ICON);
		if (img_url){	
			newIcon.iconSize=new GSize(23, 24);
			newIcon.shadow= "";
			newIcon.image = img_url;	
		}
		return newIcon;
	}

	function createDirTabbedMarker(point,label1, label2, html1, html2, markerOptions, extra_info) {
		html2="<div style='color:#555555;font-size:11px; width:250px'>" + html2;
		html2+="</div>";
		//create new marker
		var marker = new GMarker(point, markerOptions);
		//add click listener
		GEvent.addListener(marker, "click", function() {
			//if a route has been done previously route to new marker if clicked (we already have the postcode)
			if (prev_route_done!='' || prev_route_done!=false){
				GDir_initDirections(prev_route_done, marker.getLatLng(), marker.getTitle());
			}
			//if extra info was sent display it 
			if (extra_info!=''){
				displaySiteInfo(extra_info);
			}
			//open the info window for this marker
			marker.openInfoWindowTabsHtml([new GInfoWindowTab(label1,html1), new GInfoWindowTab(label2,html2)]);
			//set this marker as the active marker
			active_marker=marker;
		});
		//if this is the first site set it as the active marker so no nulls are encountered
		if(first_site_info_done==0){
			active_marker=marker;
			first_site_info_done=1;
		}
		//additional items/features to add to marker
		//if sending coords not latlng object use this... this will create a latlng object 
		//var point 	= 	new GLatLng(point);
		//Add it to the map
		//map.addOverlay(marker);
		//extras
		//open the window once created
		//marker.openInfoWindowTabsHtml([new GInfoWindowTab(label1,html1), new GInfoWindowTab(label2,elig_for_text)]);
		//move and zoom map to the new marker
		//map.setCenter(point, 10);
		//mini_map_opts={ mapType: G_HYBRID_MAP, zoomLevel: 17};
		//marker.showMapBlowup(mini_map_opts)
		//return to calling function to use later
		return marker;
	}
