var map;
var geocoder;
var g_response;
var g_address_point;
var g_address_place;
var m_isGoogleMapInitialised;
var m_baseIcon;
var m_markers = new Array();
var m_txt_address_default_value;

//default country where we searched
var g_search_country = "new zealand";
//the range(km) that we want search
var g_search_range = 50;
//set your own icon of markers on map
var g_custom_icon_path = "/images/google_budget.png";

function gotoLocation()
{
	if(!m_isGoogleMapInitialised)
	{
		initGoogleMap();
	}

	var l_address = document.getElementById("txt_address").value;
	
	if(l_address.length > 0)
	{
		geocoder.getLocations(l_address + ',' + g_search_country, addAddressToMap);
	}
	else
	{
		//alert("no address entered");
	}
	
	return false;
}


function addAddressToMap(response)
{
	map.clearOverlays();
	if (!response || response.Status.code != 200) 
	{
		jAlert("Sorry, we were unable to geocode that address");
	} 
	else
	{
		g_address_place = response.Placemark[0];
		g_address_point = new GLatLng(g_address_place.Point.coordinates[1], g_address_place.Point.coordinates[0]);
		requestLocations("/service/BudgetWS.asmx/ListGoogleMapSearchLocations?latitude="+g_address_place.Point.coordinates[1]+"&longitude="+g_address_place.Point.coordinates[0]+"&radius="+g_search_range + "&siteId=" + m_siteId + "" + "&isCommercial=" + m_isCommercial);
		
	}

}
//mark location on map
function markMap(map_point, intro, index)
{	
	var letter = String.fromCharCode("A".charCodeAt(0) + index);
	var letteredIcon = new GIcon(m_baseIcon);
	letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";

	markerOptions = { icon:letteredIcon };
	var marker = new GMarker(map_point, markerOptions);
	map.addOverlay(marker);
	marker.defaultIntro = intro;
	marker.openDefaultInfoWindowHtml = function(){marker.openInfoWindowHtml(marker.defaultIntro);};
	marker.openInfoWindowHtml(intro);
	GEvent.addListener(marker, "click", function() {marker.openDefaultInfoWindowHtml();});
	m_markers[index] = marker;
}
//set map center 
function gotoCenter()
{
	map.setCenter(g_address_point, 11);
}

var http_request = false;
function requestLocations(url) 
{
	http_request = false;
	if (window.XMLHttpRequest) 
	{ // Mozilla, Safari,...
	 http_request = new XMLHttpRequest();
	 if (http_request.overrideMimeType) 
	 {
		http_request.overrideMimeType('text/xml');
	 }
	} 
	else if (window.ActiveXObject) 
	{ // IE
	 try 
	 {
		http_request = new ActiveXObject("Msxml2.XMLHTTP");
	 } catch (e) 
	 {
		try 
		{
		   http_request = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e) {}
	 }
	}
	if (!http_request) {
	 jAlert('Cannot create XMLHTTP instance');
	 return false;
	}

	http_request.onreadystatechange = listLocations;
	http_request.open('GET', url, true);
	http_request.send(null);
}

function listLocations() 
{	
	var p_node;
	var l_str="";
	m_markers = [];
	
	var l_prefix_string = m_isCommercial?"Budget Truck Rental":"Budget Car Rental";
	
  if (http_request.readyState == 4) 
  {
	 if (http_request.status == 200) 
	 {

		var xmldoc = http_request.responseXML;
		var root = xmldoc.getElementsByTagName('location');
		p_node = root;
			
		var index = root.length-1;
		
		for (var iNode = root.length-1; iNode >=0; iNode--) 
		{
			var node = root[iNode];

			var l_id = "";
			var l_locationcode = "";
			var l_address = "";
			var l_suburb = "";
			var l_city = "";
			var l_state = "";
			var l_postcode = "";
			var l_phone = "";
			var l_fax = "";
			var l_lat = "";
			var l_lng = ""
			var l_distance = "";
			var l_name = "";
		   
			if(node.getElementsByTagName('LL_ID')[0].firstChild != null)
				l_id = node.getElementsByTagName('LL_ID')[0].firstChild.nodeValue;
			if(node.getElementsByTagName('locationcode')[0].firstChild != null)
				l_locationcode = node.getElementsByTagName('locationcode')[0].firstChild.nodeValue;				
			if(node.getElementsByTagName('address')[0].firstChild != null)
				l_address = node.getElementsByTagName('address')[0].firstChild.nodeValue;
			if(node.getElementsByTagName('suburb')[0].firstChild != null)
				l_suburb = node.getElementsByTagName('suburb')[0].firstChild.nodeValue;
			if(node.getElementsByTagName('city')[0].firstChild != null)
				l_city = node.getElementsByTagName('city')[0].firstChild.nodeValue;
			if(node.getElementsByTagName('state')[0].firstChild != null)
				l_state = node.getElementsByTagName('state')[0].firstChild.nodeValue;
			if(node.getElementsByTagName('postcode')[0].firstChild != null)
				l_postcode = node.getElementsByTagName('postcode')[0].firstChild.nodeValue;
			if(node.getElementsByTagName('phone')[0].firstChild != null)
				l_phone = node.getElementsByTagName('phone')[0].firstChild.nodeValue;
			if(node.getElementsByTagName('fax')[0].firstChild != null)
				l_fax = node.getElementsByTagName('fax')[0].firstChild.nodeValue;
			if(node.getElementsByTagName('lat')[0].firstChild != null)
				l_lat = node.getElementsByTagName('lat')[0].firstChild.nodeValue;
			if(node.getElementsByTagName('lng')[0].firstChild != null)
				l_lng = node.getElementsByTagName('lng')[0].firstChild.nodeValue;
			if(node.getElementsByTagName('distance')[0].firstChild != null)
				l_distance = node.getElementsByTagName('distance')[0].firstChild.nodeValue;
			if(node.getElementsByTagName('name')[0].firstChild != null)
				l_name = node.getElementsByTagName('name')[0].firstChild.nodeValue;					
				
			var l_point = new GLatLng(l_lat, l_lng);

			var l_intro = makeIntroInfo(l_name, l_address, l_suburb, l_state, l_postcode, l_phone, l_fax, l_locationcode);

			var letter = String.fromCharCode("A".charCodeAt(0) + iNode);
			var letteredIconImageUrl = "http://www.google.com/mapfiles/marker" + letter + ".png";

			markMap(l_point, l_intro, iNode);
		   
		   
		   //generate links of locations
		   l_str = "<li><img src='" + letteredIconImageUrl + "' /><div><a href='#' onclick='m_markers[" + iNode + "].openDefaultInfoWindowHtml(); return false;'>" + l_prefix_string +" - " + l_name+"</a>"+"<br /> <strong>Distance: "+ Math.round(l_distance * 100)/100+"km</strong></div></li>" + l_str;
		}
	 }
	 else 
	 {
		jAlert('There was a problem with the request.');
	 }
  }
  document.getElementById("div_google_search_locations").innerHTML = "<ul>" + l_str + "<span class='clear'></span></ul>";
  l_str = "";
  
  gotoCenter();
}
//generate info of bubbles
function makeIntroInfo(p_name, p_address, p_suburb, p_state, p_postcode, p_phone, p_fax, p_locatincode)
{
	var l_return = "<div>";
	l_return +="<strong>"+p_name+"</strong><br/>";
	l_return +="<strong>Address: </strong>"+p_address+"<br/>";
	l_return +="<strong>Suburb: </strong>"+p_suburb+"<br/>";
	l_return +="<strong>State: </strong>"+p_state+"<br/>";
	l_return +="<strong>Postcode: </strong>"+p_postcode+"<br/>";
	l_return +="<strong>Phone: </strong>"+p_phone+"<br/>";
	l_return +="<strong>Fax: </strong>"+p_fax+"<br/>";
	
	var l_quoteButton = "<img border='0' alt='' src='/images/btn_" + (m_isCommercial ? "truck" : "car") + "rentalquote.gif' class='lbLocationRentalQuote'/>"
	l_return +="<a href='" +m_redirUrl + "?locationcode=" + p_locatincode + "'>" + l_quoteButton + "</a>";	
	
	l_return +="</div>";
	return l_return;
}




function initGoogleMap()
{
	try
	{
		if(!m_isGoogleMapInitialised)
		{
			if (GBrowserIsCompatible()) 
			{
				// add google map
				map = new GMap2(document.getElementById("div_google_search_map_canvas"));
				// add zooming control
				map.addControl(new GSmallMapControl());
				// add map type control
				map.addControl(new GMapTypeControl());
				// a geocoder talks directly to Google servers to fulfill geocoding requests.
				geocoder = new GClientGeocoder();	
				// will not init again
				m_isGoogleMapInitialised = true;
				
				m_baseIcon = new GIcon(G_DEFAULT_ICON);
				m_baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
				m_baseIcon.iconSize = new GSize(20, 34);
				m_baseIcon.shadowSize = new GSize(37, 34);
				m_baseIcon.iconAnchor = new GPoint(9, 34);
				m_baseIcon.infoWindowAnchor = new GPoint(9, 2);
			}		
		}
		
		
	}
	catch(e)
	{
		//alert(e);
	}
		
}

function loadDefaultMap()
{
	if(!m_isGoogleMapInitialised)
	{
		initGoogleMap();
	}
	
	//var stupid = function(){
	try
	{
		geocoder.getLocations("New Zealand", 
			function (response) 
			{ 
				map.clearOverlays();
				map.setCenter(new GLatLng(response.Placemark[0].Point.coordinates[1], response.Placemark[0].Point.coordinates[0]), 4); 
			});	
	}catch(e)
	{
		// alert(e);
	}
}

function txt_address_focus(sender)
{
	if(typeof(m_txt_address_default_value) == 'undefined')
	{
		m_txt_address_default_value = sender.value;
	}
	
	if(sender.value == m_txt_address_default_value)
	{
		sender.value = "";
	}
}


function txt_address_blur(sender)
{
	if(sender.value == "")
	{
		sender.value = m_txt_address_default_value;
	}
	
}
