function makeTag(startTag, endTag) {
  var feld = document.getElementById('nachricht');
  var eingefuegt = false;
  if(typeof(feld.caretPos)!='undefined' && feld.createTextRange) {
    if(feld.caretPos.text!='') {
      feld.caretPos.text = startTag+feld.caretPos.text+endTag;
      eingefuegt = true;
    }
  } else if(typeof(feld.selectionStart)!='undefined') {
    if(feld.selectionEnd - feld.selectionStart > 0) {
      var begin = feld.value.substr(0, feld.selectionStart);
      var selection = feld.value.substr(feld.selectionStart, feld.selectionEnd - feld.selectionStart);
      var end = feld.value.substr(feld.selectionEnd);
      feld.value = begin + startTag + selection + endTag + end;
      eingefuegt = true;
    }
  }
  if(!eingefuegt) feld.value = startTag + feld.value + endTag;
  count(null);
}

function returnTag(tag) {
  var feld = document.getElementById('nachricht');
  if(feld.value == 'Nachricht') feld.value = '';
  if(typeof(feld.caretPos)!='undefined') {
    feld.caretPos.text = feld.caretPos.text+endTag;
  } else if(typeof(feld.selectionStart)!='undefined') {
    var begin = feld.value.substr(0, feld.selectionStart);
    var selection = feld.value.substr(feld.selectionStart, feld.selectionEnd - feld.selectionStart);
    var end = feld.value.substr(feld.selectionEnd);
    feld.value = begin + selection + tag + end;
  } else {
    feld.value += tag;
  }
  $('#smiley_box').slideUp();
  count(null);
}

function count(e) {
  if(document.getElementById('nachricht').value=='Nachricht') {
    document.getElementById('zeichen').innerHTML = max_zpn;
    return;
  }
  if(document.getElementById('nachricht').value.length < max_zpn + 1) {
    document.getElementById('zeichen').innerHTML = max_zpn - document.getElementById('nachricht').value.length;
  } else {
    document.getElementById('nachricht').innerHTML = 0;
  }
}

function ajaxreload() {
  $.getJSON('/ajax', {'min_id': ajax_minid}, function(data) {
      if(data) {
        var cnt = parseInt(data['count']);
        if(cnt > 0) {
          ajax_minid = data['min_id'];
          $('#noentries').remove();
          ajax_visible += cnt;
          if(ajax_visible > max_nps) {
            var numremove = max_nps - ajax_visible;
            var todelete = $('#content table').slice(numremove);
            todelete.slideUp('normal', function() {
                todelete.remove();
            });
            ajax_visible += numremove;
          }
          $('#newentries').hide().html(data['html']).fadeIn('normal', function() {
              $('#newentries').children().insertAfter('#newentries');
          });
        }
        if(data['countdown']) ajax_timeout = parseInt(data['countdown']);
        setTimeout('ajaxreload()', ajax_timeout*1000);
      }
  });
}

$(function() {
  count();
  if(!ajax_enabled) return;
  setTimeout('ajaxreload()', ajax_timeout*1000);
});
