// bookmark a resource
function bm (id)
{
	var url = "/cgi-bin/bookmark.cgi?rid=" + id;
	getAjax (function (xhr) {bmUpdate(xhr, id)}, url + "&ajax=1", url);
}

//unbookmark a resource
function ubm (id)
{
	var url = "/cgi-bin/bookmark.cgi?rm=1&rid=" + id;
	getAjax (function (xhr) {bmUpdate(xhr, id)}, url + "&ajax=1", url);
}

//update a bookmark span, according to result of the xhr
function bmUpdate(xhr, id)
{
  if (xhr.readyState==4)
  {
	document.body.style.cursor = 'default';    
	// if "OK"
	if (xhr.status==200)
	{
	  res = xhr.responseText;
      if (res == 'bookmarked')          {bmText(id, 'bm');}
      else if (res == 'not bookmarked') {bmText(id, 'ubm');}
      else { alert ("There has been an error. Please try later."); }
      
    }
    else
    {
      alert ("There has been an error. Please try later.");
    }
  }
}

//nicely change the text of a bookmark, set it to 'bookmark' (action == bm)
// or not bookmarkes (action == ubm)
//I take an hidden element from the html itself, becasue I do not want to write any html straigth into JS.
// then I replace the %% in the hidden html with the proper resource id, and remove the # in href (which is an antibot)
function bmText (id, action)
{

  // somebody cliked on our hidden div, not formatted
  if (id == '%%') {return false;}
  
  var e = document.getElementById('bm_' + id);
  
  //if e not defined
  if (! e) {return false;}
  
  var od= e.style.display;
  e.style.display='none';
  if (action == 'bm')
  {
    e.innerHTML = document.getElementById('bmtmpl').innerHTML.replace (/%%/g, id).replace (/#/, '');
  }
  else
  {
    e.innerHTML = document.getElementById('ubmtmpl').innerHTML.replace (/%%/g, id).replace(/#/, '');
  } 
  
  e.style.display=od;
}
