var map = null;
var geocoder = null;
var basePoint = false;
var home_icon;
var store_icon;
var storeMarkers = {};
var storePoints = {};
var storeBubbles = {};
var resultBounds = null;
var homeMarker = null;
var resultsHTML = '';

function load() {
	
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"), {mapTypes:[G_HYBRID_MAP]});
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.enableScrollWheelZoom();
		geocoder = new GClientGeocoder();		

		home_icon = new GIcon();
		home_icon.image = "/static/home_icon.png";
		home_icon.iconSize = new GSize(22, 22);
		home_icon.iconAnchor = new GPoint(11, 11);
		home_icon.infoWindowAnchor = new GPoint(22, 0);

		store_icon = new GIcon();
		store_icon.image = "/static/store_icon.png";
		store_icon.iconSize = new GSize(22, 22);
		store_icon.iconAnchor = new GPoint(11, 11);
		store_icon.infoWindowAnchor = new GPoint(22, 0);

	}
}

function showDefaultAddress() {
	var address = "san diego, ca";
	geocoder.getLatLng(address,
		function(point){
			if(!point){
				alert(address + " not found");
			}else{
				map.setCenter(point, 13);
				homeMarker = new GMarker(point, home_icon);
				map.addOverlay(homeMarker);
			}
		}
	);
}


function searchStores(baseAddress){
	if(baseAddress){
		showSearchAddress(baseAddress);
	}else{
		showSearchAddress("San Diego, CA");
	}
}

function showSearchAddress(address) {
	$("#results").html("Searching...");
	
	geocoder.getLatLng(address,
		function(point){
			if(!point){
				$("#address_input").val("san diego, ca");
				searchStores("san diego, ca");
				return true;
			}else{
				basePoint = point;
				map.setCenter(point, 13);
				
				if(homeMarker){ map.removeOverlay(homeMarker); }
				homeMarker = new GMarker(point, home_icon);
				map.addOverlay(homeMarker);
		 		getStores(point, address);
			}
		}
	);
}


function getStores(point, address){
		$('#result_count').html("Searching...");
		$.getJSON("/static/stores_json.php", {lng: basePoint.x, lat: basePoint.y, distance: $("#distance_input").val(), address: address}, function(json){
			processStoreJSON(json);
		});
}

function processStoreJSON(stores){
	clearMarkers(storeMarkers);
	storeMarkers = {}
	resultBounds = new GLatLngBounds;
	resultBounds.extend(basePoint);
	
	if(stores.length == 0){
		$("#results").html('No stores found.  Try expanding your search!');
		//map.setCenter(resultBounds.getCenter(), 13);
		return true;
	}
	
	resultsHTML = '<table border="0" width="100%" cellpadding="0" cellspacing="0">';
	
	foundString = stores.length + " Stores Found";
	if(stores.length == 0){
		"1 Store Found";
	}
	
	resultsHTML += '<tr><td colspan="3" align="left"><b>' + foundString + '</b></td></tr>';
	
	
	$.each(stores, function(){
		//console.log(this);
		createStorePoint(this);
	});
	
	//console.log(resultsHTML);
	$("#results").html(resultsHTML + "</table>");
	map.setCenter(resultBounds.getCenter(), map.getBoundsZoomLevel(resultBounds));

}



function createStorePoint(store){
	var id = store['id'];
	var address = store['address'];
	//console.log(id + " " + address);
	
	//console.log(store['lat'] + " " + store['lng']);
	var point = new GLatLng(store['lat'], store['lng']);
	//console.log(point);
	storePoints[id] = point;
	storeBubbles[id] = "<h2><b>" + store['name'] + "</b></h2>" + store['address'] + "<br />" + store['distance'] + " miles away<br /><a href='" + store['directions_link'] + "'>Get Directions</a>";
	storeMarkers[id] = new GMarker(point, store_icon);
	
	resultsHTML += "<tr><td><a href='javascript:void(0);' onclick='javascript: displayStoreBubble(" + store['id'] + ") ;'><b>" + store['name'] + "</b></a></td><td>" + store['address'] + "</td><td>" + store['distance'] + " miles away</td>";
	
	map.addOverlay(storeMarkers[id]);
	resultBounds.extend(point);
	//storeMarkers[id].hide();
	GEvent.addListener(storeMarkers[id], "click", function() {
		displayStoreBubble(id);
	});
}

function displayStoreBubble(id){
	storeMarkers[id].show();
	storeMarkers[id].openInfoWindowHtml(storeBubbles[id]);
	map.panTo(storePoints[id]);
}

function clearMarkers(markerObject){
	for (var i in markerObject){
		var marker = markerObject[i];
		map.removeOverlay(marker);
	}
	markerObject = {};
}

load();
showDefaultAddress();


$("#address_form").submit(function(){
	
	searchStores($("#address_input").val());
	return false;
});
