var gmap, gcode, gcenter, gmgr;
var blueIcon = [];
var marker_xml = '/becker/markers.php';
for (i = 1; i < 11; i++) {
	blueIcon[i] = new GIcon(G_DEFAULT_ICON);
	blueIcon[i].image = "http://gmaps-samples.googlecode.com/svn/trunk/markers/blue/marker"+i+".png";
}

$(document).ready(function(){
	$('#btn-go').click(function(){
		if ($('#gmaps').length > 0) {
		if (!/^\d{5}([\-\s]?\d{4})?$/.test($('#zip').val())) {
			alert('Please enter a valid 5-digit ZIP code.');
			return false;
		}
		if ($('#filter').val() == 'delivery') {
			marker_xml = '/tools/markers_delivery.php';
		}
		gcode = new GClientGeocoder();
		gcode.getLocations($('#zip').val(), function(response){
			if (!response || response.Status.code != 200) {
				$('#zip').val('Not found');
			}
			else {
				/*$('#gmaps').animate({
					height: '432px'
				}, 1500);*/
				gmap = new GMap2($('#map').get(0));
				gmap.clearOverlays();
				place = response.Placemark[0];
				gcenter = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
				gmap.setCenter(gcenter, 13);
				getNearby();
				$('#gmaps').css('height','auto').show();
			}
		});
	}
	});
	var zipcode=false;
	if ($('body').attr('id') == 'offer') {
  	zipcode = $('#zip').val();
  }
  else {
  	zipcode = getQueryValue('zip');
  }
	if (zipcode !== false && $('#gmaps').length > 0){
		$('#zip').val(zipcode);
		$('#btn-go').trigger('click');
	}
});


function getNearby(){
	/**
	 * markers.xml (to be generated from addresses in ams) format
	 * <markers>
	 *   <marker name="My VCA Hospital" address="1521 1st Ave, Seattle, WA" phone="1-234-567-8901" shortname="myvca" lat="47.608940" lng="-122.340141" />
	 * <markers>
	 * @param {Object} response
	 */
	var loading = $('<img />').attr({src: '/img/ajax-loader.gif', id:'loading'}).css({position:'absolute', left:'187px', top:'150px'});
	$('#map').append(loading);
	
	var loc = document.location;
	var limit = (loc.pathname.indexOf('offer') >= 0 || loc.search.indexOf('ffe') >=0) ? '&ffe' : '';

	$.get(marker_xml +'?lat='+gcenter.lat()+'&lng='+gcenter.lng()+limit, function(response){
		gmgr = new MarkerManager(gmap);
		var markers = [];
		var bounds = new GLatLngBounds();
// 		Alex: changed from 0 to 1 so that the source zip would be included
		var i = 1;
		$('#nearby').empty();
		$('marker', response).each(function(){
	    var name = this.getAttribute("name");
	    var address = this.getAttribute("address");
	    var phone = this.getAttribute("phone");
	    var distance = this.getAttribute("distance");
	    var url = 'http://'+window.location.host+'/'+this.getAttribute("shortname");
	    var point = new GLatLng(parseFloat(this.getAttribute("lat")), parseFloat(this.getAttribute("lng")));
			bounds.extend(point);
// 			Alex: added i < 5 to only show 4 entried becuase I could not find where the 5 elements max was being set			
			if (i>0 && i < 7){
		  	var marker = new GMarker(point, { icon: blueIcon[i] });
				var html = '<li>'
						+ '<img src="'+blueIcon[i].image+'" alt="marker" />'
						+ '<b>' + name + '</b>'
						+ ' (' + Math.round(distance*10)/10 + ' miles)<br/>' 
						+ address + '<br />'
						+ 'Phone: ' + phone + '<br />';
						if (limit == '&ffe'){
							html += '<a href="' + url + '/appt.html" class="external">Request an Appointment</a><br />';
						} 
						else {
							html += '<a href="' + url + '/maps-directions.html" class="external">Map &amp; Driving Directions</a><br />';
						}
						html += '<a href="' + url + '" class="external">Official Website</a></li>';
						$('#nearby').append(html);
		  	GEvent.addListener(marker, 'click', function(){
		  		marker.openInfoWindowHtml('<div class="mapinfo"><b>' + name + '</b><br/>' 
						+ address + '<br />'
						+ 'Phone: ' + phone + '<br />'
						+ '<a href="' + url + '/maps-directions.html" class="external">Map &amp; Driving Directions</a><br />'
						+ '<a href="' + url + '" class="external">Official Website</a></div>');
		  	});			
			markers.push(marker);
			}
			i++;
		});
		gmgr.addMarkers(markers, 1);
		$('#loading').hide();
		gmgr.refresh();
		gmap.setCenter(bounds.getCenter(), gmap.getBoundsZoomLevel(bounds));
	});
}

$('body').unload(function(){
	GUnload();
});

