document.observe("dom:loaded", function()
{
	if ($('search_submit') != null)
	{
		$('search_submit').observe('click', function()
		{
			$$('#only_numbers', '#address_not_found', '#mapping', '#no_stores_found').each(function(e){e.hide()});
			if ($('search_radius').value == '' || $('search_radius').value.replace(/[^0-9]/g, '') != $('search_radius').value)
			{
				$('only_numbers').show();
			}
			else
			{
				$('stores_list').descendants().each(function(d){d.remove()});
				var address = $('search_address').value;
				var geo = new google.maps.ClientGeocoder();
				geo.getLatLng(address, function(latlng)
				{
					if (!latlng)
					{
						$('address_not_found').show();
					}
					else
					{
						find_nearby(latlng);
					}
				});
			}
		});
	}

	if ($('admin_edit_mode') != null)
	{
		if ($('admin_edit_mode').value == "true")
		{
			load_test_map();
		}
		$$('#store_address','#store_city','#store_state','#store_zip').each(function(input) {
			input.observe('change', blank_coords);
		});
	}
	if ($('find_coords_from_address') != null) $('find_coords_from_address').observe('click', load_test_map);

	if ($('test_coords') != null)
	{
		$('test_coords').observe('click', function(e)
		{
			lat = $('store_latitude').value;
			lng = $('store_longitude').value;
			point = new google.maps.LatLng(lat, lng);

			$('mapping').show();

			map = make_map('test_map', point);
			marker = createMarker({
				'point': point
				, 'name': $('store_title').value
				, 'address': $('store_address').value
				, 'city': $('store_city').value
				, 'state': $('store_state').value
				, 'zip': $('store_zip').value
				, 'phone': $('store_phone').value
				, 'web': $('store_webpage').value
			});
			map.addOverlay(marker);
			google.maps.Event.trigger(marker, click);
		});
	}
});

blank_coords = function(e)
{
	$('store_latitude').value = '';
	$('store_longitude').value = '';
}

load_test_map = function(e)
{
	var address = $('store_address').value + " " + $('store_city').value + " " + $('store_state').value + " " + $('store_zip').value;
	$('address_not_found').hide();
	$('find_coords_loading').show();
	var geo = new google.maps.ClientGeocoder();
	geo.getLatLng(address, function(latlng)
	{
		$('find_coords_loading').hide();
		if (!latlng)
		{
			$('mapping').hide();
			$('address_not_found').show();
		}
		else
		{
			$('mapping').show();
			point = new google.maps.LatLng(latlng.lat(), latlng.lng());
			map = make_map('test_map', point);
			map.addControl(new google.maps.SmallMapControl());
			marker = createMarker({
				'point': point
				, 'name': $('store_title').value
				, 'address': $('store_address').value
				, 'city': $('store_city').value
				, 'state': $('store_state').value
				, 'zip': $('store_zip').value
				, 'phone': $('store_phone').value
				, 'web': $('store_webpage').value
			});
			map.addOverlay(marker);

			google.maps.Event.trigger(marker, 'click');

			//$('set_coords_from_map').observe('click', function(){
				$('store_latitude').value = point.lat();
				$('store_longitude').value = point.lng();
			//});

			//google.maps.Event.trigger($('set_coords_from_map'), 'click');
		}
	});
}

make_map = function(id, point)
{
	var map = new google.maps.Map2($(id));
	map.clearOverlays();
	map.enableScrollWheelZoom();
	map.setCenter(point, 13);
	return map;
}

find_nearby = function(point)
{
	var radius = $('search_radius').value;
	new Ajax.Request('/stores/find_nearby',
	{
		method: 'get'
		, parameters: {lat: point.lat(), lng: point.lng(), radius: radius}
		, onSuccess: function(transport)
		{
			var xml = google.maps.Xml.parse(transport.responseText);
			var chains = xml.documentElement.getElementsByTagName('chain');
			if (chains.length > 0)
			{
				$('mapping').show();
				$('no_stores_found').hide();
				point = transport.request.parameters;
				var point = new google.maps.LatLng(point.lat,point.lng);
				map = make_map('map', point);
				map.addControl(new google.maps.LargeMapControl());
				var bounds = new google.maps.LatLngBounds();

				for(c=0;c<chains.length;c++)
				{
					chain = chains[c];
					stores = chain.getElementsByTagName('store');
					if (stores.length > 0)
					{
					  if (chain.getAttribute('name') != "Logo Placeholder") {
						  $('stores_list').insert(new Element('li').update("<img src=\"" + chain.getAttribute('logo') + "\" alt=\"" + chain.getAttribute('name') + "\"/>"));
					  }

						for (i=0;i<stores.length;i++)
						{
							s = stores[i];
							point = new google.maps.LatLng(s.getAttribute('lat'), s.getAttribute('lng'));
							common_options = {
  							'name': s.getAttribute('name')
  							, 'address': s.getAttribute('address')
  							, 'city': s.getAttribute('city')
  							, 'state': s.getAttribute('state')
  							, 'zip': s.getAttribute('zip')
  							, 'phone' : s.getAttribute('phone')
  							, 'web' : s.getAttribute('web')
  							, 'products' : (s.getElementsByTagName('product') != null ? s.getElementsByTagName('product') : [])
							};
							marker = createMarker($H({
								'point': point
							}).merge(common_options).toObject());

							map.addOverlay(marker);
							bounds.extend(point);
							createSidebarEntry($H({
								'marker':marker
								, 'distance': s.getAttribute('distance')
							}).merge(common_options).toObject());
						}
					}
				}
				map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds)-1);
				new Effect.ScrollTo('search_address', {duration: 0.35, transition: Effect.Transitions.linear});
			}
			else
			{
				$('mapping').hide();
				$('no_stores_found').show();
			}
		}
	});
}

createMarker = function(options)
{
	marker = new google.maps.Marker(options.point);
	google.maps.Event.addListener(marker, 'click', function()
	{
	  products_html = "";
	  for (i=0; i<options.products.length; i++){
	    products_html += "<li><a target='_blank' href='" + options.products[i].getAttribute('url') + "'>" + options.products[i].getAttribute('title') + "</a></li>"
	  }
	  if (products_html.length > 0) {
	    products_html = "<br />Products: <ul>" + products_html + "</ul>";
	  }	  
	  
		this.openInfoWindowHtml("<b>" + options.name + "</b>"
		+ "<br/>" + options.address
		+ "<br/>" + options.city + ", " + options.state + " " + options.zip
		+ (options.phone.length > 0 ? "<br/>Phone: " + options.phone : "")
		+ "<br/>Website: <a href='http://" + options.web.replace("http://", "") + "' target='_blank'>" + options.web + "</a>"
		+ products_html);
	})
	return marker;
}

createSidebarEntry = function(options)
{
	li = new Element('li');
	li.insert(new Element('span', {className: 'name'}).update(options.name));
	li.insert(new Element('span', {className: 'address'}).update(options.address));

	li.insert(new Element('span', {className: 'city_state_zip'}).update(options.city + ", " + options.state + " " + options.zip));

	if (options.phone.length > 0)
	{
		li.insert(new Element('span', {className: 'phone'}).update('Phone: ' + options.phone));
	}

	links = new Element('div', {className: 'links'});
	links.insert(new Element('span', {className: 'map_directions'}).update('Show on map').observe('click', function(){
		google.maps.Event.trigger(options.marker, 'click');
	}));
	links.insert(new Element('span', {className: 'web'}).update(" | <a target='_blank' href='http://" + options.web.replace("http://", "") + "'>Store web page</a>"));
	li.insert(links);

	$('stores_list').insert(li);
}