/*
 * Tudura javascript
 *
 * $Id: tudura.js,v 1.18 2007/07/27 13:56:13 cut-sea Exp $
 */

/*
 * focus target
 */
Event.observe(window, 'load', focus_initialize);

Event.observe(window, 'load', tag_completion);

/*
 * focus target id
 */
function focus_initialize() {
  // at first, if defaultfocus target exist, then focus it.
  // and next candidate, if initfocus target exist, then focus it.
  // and last candidate, if auxfocus target exits, then focus it
  var target = document.getElementById('defaultfocus');
  if (!target)
    target = document.getElementById('account');
  if (!target)
    target = document.getElementById('nickname');
  if (!target)
    target = document.getElementById('status');
  if (!target)
    target = document.getElementById('theme');
  if (!target)
    target = document.getElementById('title');
  if (!target)
    target = document.getElementById('content');
  if (!target)
    target = document.getElementById('emails');
  if (!target)
    target = document.getElementById('searchkey');

  if (target)
    target.focus();
  return false;
}

/*
 * tag complete
 */
function tag_completion(){
  var t = document.getElementById('tags');
  if (t) {
    new Ajax.Autocompleter('tags', 'suggest',
			   kahua_self_uri_full + 'suggest-tags',
			   {paramName: 'input-chars' , tokens: ' '});
  }
}

/*
 * add tag value to input with attribute text type and target id.
 */
function addTag(target, tag) {
  var input = document.getElementById(target);
  input.focus();
  var len = input.value.length;
  if (len>0 && input.value[len-1]!=" ") {
    input.value += ' ';
  }
  new Effect.Highlight(target);
  input.value += tag;
}

/*
 * insert excerption.
 */
function insert_excerption(self, target){
  var myAjax = new Ajax.Request(
      self.href ,
      {method: 'get',
       onComplete:function(req){
	   var result = eval(req.responseText);
	   var textarea = document.getElementById(target);
	   textarea.focus();
	   var start = textarea.selectionStart;
	   textarea.value = textarea.value.substring(0, start)
             + result
	     + textarea.value.substring(start);
	   textarea.selectionEnd = start + result.length;
       }
      })
      var content = document.getElementById('content');
      new Effect.Highlight(content);
      return false;
}

/*
 * input date from calendar
 */
function inputDate(elem, target, ymd) {
  var input = document.getElementById(target);
  var cal = document.getElementById('limit-calendar');
  var days = cal.getElementsByTagName('TD');
  input.focus();
  new Effect.Highlight(target);
  input.value = ymd;
  refreshCalendar();
  return false;
}

function refreshCalendar() {
  var cal = document.getElementById('limit-calendar');
  var days = cal.getElementsByTagName('TD');
  var lmt = document.getElementById('limit');
  for (var i=0; i<days.length; i++) {
    days[i].className = days[i].className.replace('new-target', '');
  }
  var d = document.getElementById(lmt.value)
  d.className += ' new-target';
}

