window.address;
window.coords;
window.X;
window.Y;
	
var outletData = {};
window.fieldList = {};	
	
getAddressField = function()
{
	"use strict";
	var obj, sabledata, name = "dummy string", counter = 0;
	var tags = document.querySelectorAll('input, textarea'); 
	//document.getElementsByTagName('textarea');
	for (var i=0; i<tags.length; i++)
	{
		obj = tags[i];
		name = tags[i].id;
		sabledata = obj.getAttribute("sabledata");
		if (sabledata !== null && sabledata.toLowerCase() === "address") {break;}
	}
	return obj;
}

window.mapInitialize = function(x,y,zoom)
{
	var latlng = new google.maps.LatLng(y,x);
	var myOptions = { zoom: zoom, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP };
	window.mapSelector = new google.maps.Map(document.getElementById("mapCanvas"), myOptions);
}

showAddress = function(coords, physAddress, placeId)
{
	coords = coords + "";
	coords = coords.replace(/[\)\(]/g,"").replace(/ /g,"");
	var parts = coords.split(",");
	
	if (window.mapSelector !== undefined)
	{
		window.mapSelector.setCenter(new google.maps.LatLng(parts[0],parts[1]));
		window.mapSelector.setZoom(15);
	}
	
	var myLatlng = new google.maps.LatLng(parts[0]+0,parts[1]+0);
	var mapOptions = 
	{
		zoom: 17,
		center: myLatlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	}
	var map = new google.maps.Map(document.getElementById("mapCanvas"), mapOptions);
	
	var marker = new google.maps.Marker(
	{
		position: myLatlng,
		animation: google.maps.Animation.DROP,
		map: map,
		title:companyTitle
	});
	google.maps.event.addListener(marker, 'click', goGoogleMaps);
	var roAttr = getAddressField().getAttribute('readonly');
	if ((roAttr==null) && (physAddress !== undefined)) getAddressField().value = physAddress;
	
	outletData.latitude 	= parts[0];
	outletData.longitude 	= parts[1];
	outletData.address 		= physAddress;
	outletData.placeId 		= placeId;
	
	getBusinessDetails(placeId);
}		

goGoogleMaps = function()
{
	window.open('http://maps.google.co.za/maps?q='+window.address, '_blank');
}

coordsSearch = function(address)
{
	var geo = new google.maps.Geocoder();
	var geoRequest = {};
	if (address)
		geoRequest.address = address;
	else
		geoRequest.address = getAddressField().value;
	//geoRequest.bounds = new google.maps.LatLngBounds(new google.maps.LatLng(-35.2, 15.2,true), new google.maps.LatLng(-22.1, 33.6,true));
	geoRequest.bounds = new google.maps.LatLngBounds(new google.maps.LatLng(-35.2, 15.2, false), new google.maps.LatLng(-22.1, 33.6, false));
	geo.geocode(geoRequest, mapSearchCallback);
}

mapSearchCallback = function(result, status)
{
	var htmlA = "";
	var htmlB = "";
	var htmlC = "";
	var html = "";
	var cnt = 0;
	
	//console.log(result);
	if (status=="OK")
	{
		htmlA = '<table class="searchResults">';
		htmlB = '<tr><td class="labelResultItem">Please select the correct address to display:</td></tr>';
		for (var i in result)
		{
			console.log(result[i]);
			//we have result[i].place_id
			window.address = result[i].formatted_address.replace(/, South Africa/g,"").replace(/, ZA/g,"");
			window.coords = result[i].geometry.location;
			
			/*
			Details about the address can be gotten from result[i].address_components[x]:
			result[i].address_components[0].long_name = Hartenbos
			result[i].address_components[1].long_name = Mossel Bay
			result[i].address_components[2].long_name = South Africa
			result[i].address_components[3].long_name = 6520
			**Province missing....
			*/
			
			var loc = window.coords + "";
			var mapcoords = document.getElementById('mapCoords');
			if (mapcoords !== null)	mapcoords.innerHTML = loc;
			loc = loc.replace(/[\)\(]/g,"").replace(/ /g,"");
			var parts = loc.split(",");
			window.X = parts[0];
			window.Y = parts[1];
			
			htmlC += '<tr>';
			htmlC += '	<td onclick="showAddress(\''+window.coords+'\', \''+window.address+'\', \''+result[i].place_id+'\')" >';
			htmlC += 		window.address + '&nbsp;&nbsp;' + window.coords;
			htmlC += '	</td>';
			htmlC += '</tr>';
			cnt++;
			
		}
		if (cnt > 1) html = htmlA + htmlB + htmlC; else	html = htmlA + htmlC;
		html += "</table>";
		var srchres = document.getElementById('searchResults');
		if (srchres !== null) srchres.innerHTML = html;
		showAddress(window.coords, window.address, result[i].place_id); //load this address in the map on the screen.
	} //if status == "OK"
	
	if (status=="ZERO_RESULTS")
	{
		document.getElementById("searchResults").innerHTML = '<table class="noResults"><tr><td>The location could not be found. Please ensure the address is correct.</td></tr></table>';
	};
}

updateMapData = function()
{
	coordsSearch(); 
	mapInitialize(window.X, window.Y, 9);
}

function getBusinessDetails(bid)
{
	/*
address_component, adr_address, alt_id, formatted_address, geometry, icon, id, name, permanently_closed, photo, place_id, plus_code, scope, type, url, utc_offset, vicinity

Contact

The Contact category includes the following fields:
formatted_phone_number, international_phone_number, opening_hours, website	
	*/
	var request = 
	{
	  placeId: bid,
	  fields: ['name', 'formatted_phone_number', 'photo', 'website']
	};

	service = new google.maps.places.PlacesService(window.mapSelector);
	service.getDetails(request, placeIdCallback);
}	

function placeIdCallback(place, status) 
{
	//if (status == google.maps.places.PlacesServiceStatus.OK) {createMarker(place);}
	if (status == google.maps.places.PlacesServiceStatus.OK) 
	{
		//wDebug(place.photos);
		/**
			formatted_phone_number=012 460 6813
			geometry= [STRUCT]
				 location=(-25.772236, 28.215920900000015)
				 viewport=((-25.7734610802915, 28.21460936970857), (-25.7707631197085, 28.217307330291533))
			
			name=Liquor City Groenkloof
			photos= [STRUCT]
				 0=[object Object]
				 1=[object Object]
				 2=[object Object]
				 3=[object Object]
				 4=[object Object]
				 5=[object Object]
				 6=[object Object]
				 7=[object Object]
				 8=[object Object]
				 9=[object Object]
			
			website=http://liquorcity.co.za/
			html_attributions= [STRUCT]
		**/
		//wDebug(place.html_attributions);
		//outletData.image 	= place.photos[0].html_attributions;
		outletData.phone 	= place.formatted_phone_number;
		outletData.name 	= place.name;
		outletData.website 	= place.website;
		
		if (Object.keys(window.fieldList).length > 0)
		{
			document.getElementById(window.fieldList.phone).value 		= outletData.phone 		!== undefined ? outletData.phone : '';
			document.getElementById(window.fieldList.name).value 		= outletData.name 		!== undefined ? outletData.name : '';
			document.getElementById(window.fieldList.website).value 	= outletData.website	!== undefined ? outletData.website : '';
			document.getElementById(window.fieldList.address).value 	= outletData.address;
			document.getElementById(window.fieldList.placeId).value 	= outletData.placeId;
			document.getElementById(window.fieldList.latitude).value 	= outletData.latitude;
			document.getElementById(window.fieldList.longitude).value 	= outletData.longitude;			
			if (place.photos.length > 0)
			{
				var iimg = place.photos[0].getUrl({'maxWidth': 800, 'maxHeight': 800 });
				document.getElementById(window.fieldList.imageURL).value 	= iimg;
				document.getElementById(window.fieldList.image).src 		= iimg;
			}
		}
	}
}