// AJAX-like "find nearest"

function Nearest_Finder(se) {
  var sel = document.getElementById(se);
  var toget = '';
  for(var i=0;i<sel.options.length;i++) {
    if(sel.options[i].selected)
      toget += sel.options[i].value;
  }
  if(toget == '') {
    alert(i18n.noselect);
    return;
  }
  Nearest_Download(sel,toget);
}

function Nearest_Download(sel,what) {
  var xmlhttp=null
  if (window.XMLHttpRequest) {
    xmlhttp=new XMLHttpRequest()
  } else if (window.ActiveXObject) {
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
  }
  if (xmlhttp == null) {
    alert(i18n.browserfail);
    return false;
  }
  xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4) {
	  if (xmlhttp.status==200) {
	      var response = xmlhttp.responseText;
	      var items = eval("("+response+")");
	      Nearest_Output(what,items,sel.options);
	  }
      }
  };
  var dest = document.getElementById('nearest_results');
  dest.innerHTML = '... wait ...';
  xmlhttp.open("GET","../cgi-bin/api.cgi?mode=nearest&id="+cp_info.id+"&as=json&what="+what+'&opts='+cp_info.nearest.distcode,true);
  xmlhttp.send(null);
}

function Nearest_Show_Attr(names,attr) {
  for(var i=0;i<names.length;i++) {
    if(names[i].value == attr) {
	return names[i].text;
    }
  }
  return '**ERROR**';
}

function Nearest_Output(attr,items,selo) {
  var dest = document.getElementById('nearest_results');
  var res = '';
  dest.innerHTML = '';
  // first find items at this spot
  for(i in items) {
    if(items[i]['@'])
	items[i]['O'] = items[i]['@'];
    dest.innerHTML+='<hr>';
    if(i=='*HERE*') {
	dest.innerHTML+='<h3>Here</h3>';
    } else {
	dest.innerHTML+='<h3>In the direction of '+items[i].dirname+'<h3>';
    }
    res = '<ul>';
    for(j=0; j<attr.length;j++) {
	var thit = items[i][attr.charAt(j)];
	if(thit) {
	    if(typeof(thit) == 'string') {
		res+= '<li>The nearest '+Nearest_Show_Attr(selo,attr.charAt(j))+' is here</li>';
	    }else {
		res +='<li>The nearest '+Nearest_Show_Attr(selo,attr.charAt(j))+' is at '+Place_Link(thit.id,thit.name,cp_info.nearest.urlrewrite);
		res += ', '+thit.distance;
		if(thit.locks) {
		    res += ' and '+thit.locks+' lock';
		    if(thit.locks > 1) res += 's';
	    }
		res += ' to the '+thit.compass+'</li>';
	    }
	}
    }
    res+='</ul>';
    dest.innerHTML += res;
  }
  //  dest.innerHTML+='<div></div>';
}

//**CAN MOVE INTO GENERAL AND USE ELSEWHERE
function Place_Link(id,name,rewrite) {
  var toret = '<a class="quiet" href="';
  Load_JS('get_sessionid');
  var sid = Get_Session_ID();
  if(rewrite) {
    toret += '../gazetter/'+id;
    if(sid)
	toret += '?session='+sid;
  } else {
    toret += 'gazetteer.cgi?';
    if(sid)
	toret += 'session='+sid+'&';
    toret += 'id='+id;
  }
  toret += '">'+name+'</a>';
  return toret;
}