function clear_entity(){
	if (data.any_changes()){
		if ( confirm("Changes detected...save?") ) return;
	}

	foreach($("editor"),
		function(control){
			if ((control.tagName=="TEXTAREA") || (control.type=="text")) control.value="";
			//DOM.hide(control.id+"-edit");
		});
//	$("editor").entity.value = "";
	select_link();
	data.clear();
}

function doget(get, entity_name){
	DOM.enable("b:get");
	if (get.status != Http.Status.OK) return;

	var entity = json_response(get);	
	if (!entity) return;
	
	for(key in entity){
		var field = $("e:"+key);
		if (field){
			field.value = entity[key];
		}
	}
	
	$("editor").entity.value = entity_name;
	data.save();
}

function load(link){
	var entity = link.getAttribute("entity") + ".js";
	if (entity == $("editor").entity.value) return;	
	if (data.any_changes()){
		if (window.confirm(
			"There are unsaved changes.\n\nPress 'OK' to save changes.\nPress 'Cancel' to discard changes."
		)){
			// Save the changes first
		}
	}

	DOM.disable("b:get");
	select_link(link);
	
 	Http.get({
 		url: "http://" + location.host + "/EntityMan/" + entity,
 		callback: doget,
 		cache: Http.Cache.GetNoCache
	}, [entity]);
}

function select_link(link){
	if (link) link.className = "selected";
	foreach($("filesys").getElementsByTagName("a"),
		function(aLink){
			if (aLink != link)
				aLink.className = "";
		});
}

function create_list(items, list_type){
	var list = document.createElement(list_type || "ul");
	foreach(items, function(item){
		var li = document.createElement("li");
		li.innerHTML = item;
		list.appendChild(li);
	});
	
	return list;
}

function populate_entity_list(){
	function do_it(get){
		var list = json_response(get);
		
		if (list == null){
			$("filesys-files").innerHTML="Error";
			return;
		}
		
		var alink = "<a entity='{node}' onclick='return load(this);'>{node}</a>";
		var ul = create_list(
			collect(list, function(node){
				var html = alink.template({'node':node});
				return html;})
			);

		DOM.replaceChildren("filesys-files",ul);
	}
	
	$("filesys-files").innerHTML="Loading...";

 	Http.get({
 		url: "http://" + location.host + "/EntityMan/entity-list.js",
 		callback: do_it,
 		cache: Http.Cache.GetNoCache
	});
}

function hook_changes(){
	var img = document.createElement("img");
	img.src = "pencil.png";
	img.align = "top";
	img.style.display="none";
	
	foreach($("editor"),
		function(control){
			if ((control.tagName=="TEXTAREA") || (control.type=="text")) {
/*			
				var changed = img.cloneNode();
				changed.id = control.id+"-edit"
				DOM.after(control, changed);
				control["onchange"] = function(){DOM.show(changed);}
*/
			}
		});
}

var data;
register_onload(
	function(){
		DOM.enable("b:get");
		$("b:clear").onclick = clear_entity;
		$("editor").entity.value = "";
		data = new FormData("editor");

		populate_entity_list();
		
		hook_changes();
	}	
);
