// Create a base icon for all of our markers that specifies the
// shadow, icon dimensions, etc.
var baseIcon = new GIcon();
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
//baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
baseIcon.infoShadowAnchor = new GPoint(18, 25);

var map;

function search(authenticated) {
	$("connectedList").innerHTML = "";
	$("nonConnectedList").innerHTML = "";
	map.clearOverlays();
	
  	var zip = $("zip").value;
  	var radius = $("radius").options[$("radius").selectedIndex].value;

	new Ajax.Request("/facility-locator-data.html", {
		method: "post",
		parameters: {
			zip: zip,
			radius:radius
		},
		onSuccess: function(response) {
			var data = JSON.parse(response.responseText);
			if (data.postalCodeFound == false) {
				alert("No location found for city and state specified.");
				return;
			}

			map.setCenter(new GLatLng(data.location.lat, data.location.long), getZoomLevel(radius));
			
			try {
				if(data.connectedFacilities.length > 0) {
					$("connected_facilities").show();
					for (var i = 0; i < data.connectedFacilities.length; i++) {
						addFacilityToMap(data.connectedFacilities[i], true, $("connectedList"), i, authenticated);
					}
				} else {
					$("connected_facilities").hide();
				}
				
				if(data.nonConnectedFacilities.length > 0) {
					$("nonconnected_facilities").show();
					for (var i = 0; i < data.nonConnectedFacilities.length; i++) {
						addFacilityToMap(data.nonConnectedFacilities[i], false, $("nonConnectedList"), data.connectedFacilities.length + i, authenticated);
				    }
				} else {
					$("nonconnected_facilities").hide();
				}
			}
			catch(e) {
				alert("error: " + e.message);
			}
		},
		onFailure: function(response) {
			alert("Search Error: " + response.status);
		}
	});
}

function addFacilityToMap(f, connected, list, index, authenticated) {
	var icon = new GIcon(baseIcon);
	if (connected) {
		icon.image  = "/ui/img/ndma-map-icon.png";
		icon.shadow = "/ui/img/ndma-map-icon-shadow.png";
	}
	else
		icon.image = "http://www.google.com/mapfiles/marker.png";
	
	var point = new GLatLng(f.lat, f.long);
	map.addOverlay(createMarker(point, f.name, getDetailHtml(f, authenticated), icon));
	
	var listItem = new Element("li");
	
	var description = "";
	if (authenticated) description = "<input type='radio' name='facilityId' value='" + f.id + "' /> ";
	description += "<strong>" + f.name + "</strong> &ndash; "
	                + f.addr + ", " + f.city + ", " + f.state + " &ndash; " + f.zip;

	listItem.update(description);
	list.appendChild(listItem);
}

function createMarker(point, title, html, icon) {
	var marker = new GMarker(point, { title: title, icon: icon });
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html);
	});
	
	return marker;
}

function getDetailHtml(f, authenticated) {
	var detailHtml = "<strong>" + f.name + "</strong><br />"
	               + f.addr + "<br />" + f.city + ", " + f.state + " " + f.zip + "<br />"

	return detailHtml;
}

function getZoomLevel(radius) {
	var zoom;
	switch (radius) {
		case "5": zoom = 11; break;
		case "10": zoom = 10; break;
		case "25": zoom = 9; break;
		case "50": zoom = 8; break;
		case "100": zoom = 7; break;
		default: zoom = 11;
	}

	return zoom;
}

function showFacilityDetails(title, id) {
	Modalbox.show('/patient/facility-details.html?facilityId=' + id, { title: title, width: 650 });
	return false;
}

function showFacilityDetails(title) {
	var selectedRadio = Form.getInputs('facilityForm','radio','facilityId').find(function(radio) { return radio.checked; });
	if (selectedRadio != null) {
		var facilityId = selectedRadio.value;
		Modalbox.show('/patient/facility-details.html?facilityId=' + facilityId, { title: title, width: 650 });
	}
	else {
		alert("Please choose a facility.");
	}
	
	return false;
}

function saveFacilityRelationship(title) {
	var id = $("facilityId").value;
	var mrn = $("mrn").value;
	var description = $("description").value;
	
	Modalbox.show('/patient/facility-save.html?facilityId=' + id + '&mrn=' + mrn + '&description=' + description, {title: title, width: 400});
}

function confirmRemoveFacility(title) {
	var selectedRadio = Form.getInputs('facilityForm','radio','facilityId').find(function(radio) { return radio.checked; });
	if (selectedRadio != null) {
		var facilityId = selectedRadio.value;
		confirmRemoveFacilityById(title, facilityId);
	}
	else {
		alert("Please choose a facility.");
	}
	
	return false;
}

function confirmRemoveFacilityById(title, facilityId) {
	Modalbox.show('/patient/medical-records/facility-confirm-remove.html?facilityId=' + facilityId, { title: title, width: 400 });
	return false;
}

function removeFacility() {
	var facilityId = $("facilityId").value;
	
	new Ajax.Request("/patient/medical-records/facility-remove.html", {
		method: "post",
		parameters: {
			facilityId: facilityId
		},
		onSuccess: function(response) {
			var data = JSON.parse(response.responseText);
			if (data.success) location.href = location.pathname;
			else alert("Error removing facility.");
		},
		onFailure: function(response) {
			alert("Remove Facility Error: " + response.status);
		}
	});
}