/* LiveJournal, respect :) */

function SwapNodes(orig, to_swap)
 {
  if (!orig) return false;
  if (!to_swap) return false;

  var orig_pn = xParent(orig, true);
  var next_sibling = orig.nextSibling;
  var to_swap_pn = xParent(to_swap, true);

  if (!to_swap_pn) return false;
  if (!orig_pn) return false;

  if ((to_swap_pn.replaceChild) && (orig_pn.insertBefore))
   {
    to_swap_pn.replaceChild(orig, to_swap);
    orig_pn.insertBefore(to_swap, next_sibling);
   }

  return true;
 }

// xParent / xDef (c) 2004 Michael Foster

function xParent(e, bNode)
 {
  if (!(e = $(e))) return null;
  var p = null;

  if (!bNode && xDef(e.offsetParent)) p = e.offsetParent;
  else if (xDef(e.parentNode)) p = e.parentNode;
  else if (xDef(e.parentElement)) p = e.parentElement;
  return p;
 }

function xDef() 
 {
  for (var i = 0; i < arguments.length; ++i)
   {
    if (typeof(arguments[i]) == 'undefined') 
     return false;
   }

  return true;
 }

/* mypskov js code follows, yeah */

var dumb = function() { }

function GotSelector(s)
 {
  s = s.responseText;
  s = s.split("\x0D\x0A");

  if (s.length == 0) return;
  if (!(target = $(s[0]))) return;

  target.length = 0;

  for (k = 1; k < s.length - 1; k++)
   {
    y = s[k].split("\<\.\>");

    o = new Option();
    o.text = y[1];
    o.value = y[0];
    target.options[target.length] = o;
   }

  if (target.onchange) target.onchange();
 }

function Selector(src, dest, kind)
 {
  target = $(dest);

  o = new Option();  
  o.text = '...';
  o.value = '0';

  target.length = 0;
  target.options[target.length] = o;

  new Ajax.Request('/selector.html',
                   {method: 'get',
                    parameters: 'src=' + escape(src) + 
                                '&dest=' + escape(dest) + 
                                '&kind=' + escape(kind) + 
                                '&value=' + escape($(src).value) + 
                                '&' + Math.random(),
                    onComplete: GotSelector});
 }

function Helper(id)
 {
  width = 400;
  height = 350;

  var left = Math.round((document.body.clientWidth - width) / 2);
  var top = Math.round((document.body.clientHeight - height) / 2);

  var win = window.open('/helper.html?id=' + id,
                        'printhelper', 
                        'toolbar=no,' +
                        'scrollbars=yes,' +
                        'status=no,' +
                        'height=' + height + ',' +
                        'width=' + width + ',' + 
                        'top=' + top + ',' +
                        'left=' + left);

  win.focus();

  return false;
 }

function ReloadCaptcha(id, url)
 {
  $(id).src = url + '&' + Math.random();

  return false;
 }

/* buzzies subsystem */

var buzzies = new Array();
var buzzing = '';
var buzzing_prev = false;
var buzzylocked = false;

function BuzzerLooksLoaded(shit)
 {
  b = $('Buzzer');

  if (buzzies[buzzing]['achtung'])
   HideBanner();

  b.style.left = (buzzies[buzzing]['align'] == 'left') ? buzzies[buzzing]['x'] : 'auto';
  b.style.right = (buzzies[buzzing]['align'] == 'right') ? '10px' : 'auto';

//  b.style.overflow = buzzies[buzzing]['achtung'] ? 'auto' : '';
  b.style.display = 'block';
  buzzies[buzzing]['active'] = true;
 }

function BuzzerStartLoad(id, kind)
 {
  if (buzzies[id]['unloader_timeout']) clearTimeout(buzzies[id]['unloader_timeout']);

  $('Buzzer').style.left = buzzies[id]['x'];
  $('Buzzer').style.right = 'auto';
  $('Buzzer').style.top = buzzies[id]['y'];
  $('Buzzer').innerHTML = '...';
  $('Buzzer').style.display = 'block';

  params = 'kind=' + kind + '&' + 
           'digest=' + digest + '&' +
           'bid=' + id;

  buzzing = id;

  new Ajax.Updater('Buzzer',
                   '/ajax/buzzer.html',
                   {asynchronous: true,
                    onSuccess: BuzzerLooksLoaded,
                    method: 'post',
                    parameters: params });
 }

function BuzzerLoad(id, kind, under_element, right_now, achtung)
 {
  if (buzzylocked)
   return false;

  if (!buzzies[id]) 
   buzzies[id] = new Array();

  if (buzzies[id]['loader_timeout']) clearTimeout(buzzies[id]['loader_timeout']);
  if (buzzies[id]['unloader_timeout']) clearTimeout(buzzies[id]['unloader_timeout']);

/*
  if (buzzing_prev)
   {
    if (buzzies[buzzing_prev]['loader_timeout']) clearTimeout(buzzies[buzzing_prev]['loader_timeout']);
    if (buzzies[buzzing_prev]['unloader_timeout']) clearTimeout(buzzies[buzzing_prev]['unloader_timeout']);
   }
*/

  if (!buzzies[id]['active'])
   {
    if (!under_element) under_element = $(id + 'i');

    Position.prepare();
    coords = Position.cumulativeOffset(under_element);

    buzzing_prev = id;

    buzzies[id]['x'] = coords[0] + under_element.width / 2;
    buzzies[id]['y'] = coords[1] + under_element.height + 3;
    buzzies[id]['align'] = (buzzies[id]['x'] > document.body.clientWidth - 350) ? 'right' : 'left';
    buzzies[id]['achtung'] = achtung ? true : false;

    buzzies[id]['loader_timeout'] = setTimeout('BuzzerStartLoad(\'' + id + '\', \'' + kind + '\');', right_now ? 0 : 1000);
   }

  return false;
 }

function BuzzerDoUnload(id)
 {
  if (id == buzzing) 
   {
    $('Buzzer').style.display = 'none';

    if (buzzies[id]['achtung'])
     ShowBanner();
   }

  buzzies[id]['active'] = false;
 }

function BuzzerUnload(id)
 {
  if (!buzzylocked)
   {
    if (buzzies[id]['loader_timeout']) clearTimeout(buzzies[id]['loader_timeout']);
    if (buzzies[id]['unloader_timeout']) clearTimeout(buzzies[id]['unloader_timeout']);

    buzzies[id]['unloader_timeout'] = setTimeout('BuzzerDoUnload(\'' + id + '\');', 500);
   }
 }

function BuzzerIn()
 {
  if (!buzzylocked)
   {
    if (buzzies[buzzing]['loader_timeout']) clearTimeout(buzzies[buzzing]['unloader_timeout']);
    if (buzzies[buzzing]['unloader_timeout']) clearTimeout(buzzies[buzzing]['unloader_timeout']);
   }
 }

function BuzzerOut()
 {
  if (!buzzylocked)
   BuzzerUnload(buzzing);
 }

function BuzzerLock(bid)
 {
  buzzylocked = bid;
 }

function BuzzerUnlock(bid)
 {
  buzzylocked = false;
 }

/* message sending stuff */

function BuzzerSendMessage(bid)
 {
  BuzzerLock(bid);
  $('bzsndmsg').style.display = 'none';
  $('bzsndmsgf').style.display = 'block';
  $('bzsndmsgta').focus();

  return false;
 }

function BuzzerMessageSent(junk)
 {
  BuzzerUnlock(false);
//  $('bzsndmsg').style.display = 'inline';
//  $('bzsndmsgb1').disabled = false;
//  $('bzsndmsgb2').disabled = false;
 }

function BuzzerDoSendMessage(bid, userID, reallysend)
 {
  if (reallysend)
   {
    params = 'userID=' + userID + '&' + 
             'txt=' + encodeURIComponent($('bzsndmsgta').value) + '&' +
             'bid=' + bid;

    new Ajax.Updater('BuzzerMessageSentMsg',
                     '/ajax/buzzer_sendmessage.html',
                     {asynchronous: true,
                      onSuccess: BuzzerMessageSent,
                      method: 'post',
                      parameters: params });

    $('bzsndmsgb1').disabled = true;
    $('bzsndmsgb2').disabled = true;
   }
  else
   {
    BuzzerUnlock(bid);
    $('bzsndmsgf').style.display = 'none';
    $('bzsndmsg').style.display = 'inline';
   }
 }

/* mood stuff */

function BuzzerChangeMood(bid)
 {
  BuzzerLock(bid);
  $('bzmood').style.display = 'none';
  $('bzmoodf').style.display = 'block';
  $('bzmoodta').focus();

  return false;
 }

function BuzzerMoodChanged(junk)
 {
  BuzzerUnlock(false);
  $('bzmood').style.display = 'inline';
  $('bzmoodf').style.display = 'none';
  $('bzmoodb1').disabled = false;
  $('bzmoodb2').disabled = false;
 }

function BuzzerDoMood(bid, reallyset)
 {
  if (reallyset)
   {
    params = 'txt=' + encodeURIComponent($('bzmoodta').value) + '&' +
             'bid=' + bid;

    new Ajax.Updater('bzcurmood',
                     '/ajax/buzzer_setmood.html',
                     {asynchronous: true,
                      onSuccess: BuzzerMoodChanged,
                      method: 'post',
                      parameters: params });

    $('bzmoodb1').disabled = true;
    $('bzmoodb2').disabled = true;
   }
  else
   {
    BuzzerUnlock(bid);
    $('bzmoodf').style.display = 'none';
    $('bzmood').style.display = 'inline';
   }
 }

/* multifiles processing */

function dropFile(btn)
 {
  if (document.getElementById) 
   {
    tr = btn;

    while (tr.tagName != 'TR') tr = tr.parentNode;

    tr.parentNode.removeChild(tr);

    checkForLast();
   }
 }

function addFile(btn)
 {
  if (document.getElementById) 
   {
    tr = btn;

    while (tr.tagName != 'TR') tr = tr.parentNode;

    var idSuffix = Math.round(Math.random()*1000);
    var newTr = tr.parentNode.insertBefore(tr.cloneNode(true),tr.nextSibling);

    thisChilds = newTr.getElementsByTagName('td');

    for (var i = 0; i < thisChilds.length; i++)
     {
      if (thisChilds[i].className == 'btnFile') thisChilds[i].innerHTML = '<input name="att[]" class="attfile" type="file" onchange="changeFile(this);">';
     }

    checkForLast();
   }
 }

function changeFile(btn)
 {
  btns = document.getElementsByName('att[]');

  filled = 0;

  for (i = 0; i < btns.length; i++)
   if (btns[i].value.length > 0)
    filled++;

  if (filled == btns.length)
   addFile(btn);
 }

function checkForLast()
 {
  btns = document.getElementsByName('drop');

  for (i = 0; i < btns.length; i++)
   {
    btns[i].disabled = (btns.length == 1) ? true : false;
   }
 }

/* voshka subsystem :) */

function StartVoshka()
 {
  if (v = $('voshka'))
   {
    if (v.innerHTML.length >= 10)
     {
      v.innerHTML = '.';
     }
    else
     {
      v.innerHTML += '.';
     }
   }

  setTimeout('StartVoshka();', 250);
 }

/* media title editing routines */

var last_edited_media_title = false;

function CancelMediaTitle(mediaID)
 {
  $('media_' + mediaID + '_title').style.display = 'block';
  $('media_' + mediaID + '_title_editor').style.display = 'none';

  v = $('media_' + mediaID + '_title_value');
  v.value = v.srcvalue;
 }

function EditMediaTitle(mediaID)
 {
  if (last_edited_media_title)
   CancelMediaTitle(last_edited_media_title);

  last_edited_media_title = mediaID;

  $('media_' + mediaID + '_title').style.display = 'none';
  $('media_' + mediaID + '_title_editor').style.display = 'block';

  v = $('media_' + mediaID + '_title_value');
  v.srcvalue = v.value;

  v.focus();
  v.value = v.value;

  return false;
 }

function SavedMediaTitle(r)
 {
  r = r.responseText.split("\x0A");

  if (r.length == 3)
   {
    mediaID = r[0];
    title = r[1];
    title_html = r[2];

    $('media_' + mediaID + '_title_value').srcvalue = title;
    $('media_' + mediaID + '_title_value').value = title;
    $('media_' + mediaID + '_title_data').innerHTML = title_html;

    CancelMediaTitle(mediaID);

    $('media_' + mediaID + '_title_value').disabled = false;
    $('media_' + mediaID + '_title_save').disabled = false;
    $('media_' + mediaID + '_title_cancel').disabled = false;
   }
 }

function SaveMediaTitle(mediaID)
 {
  params = 'mediaID=' + mediaID + '&' + 
           'digest=' + digest + '&' +
           'title=' + encodeURIComponent($('media_' + mediaID + '_title_value').value);

  $('media_' + mediaID + '_title_value').disabled = true;
  $('media_' + mediaID + '_title_save').disabled = true;
  $('media_' + mediaID + '_title_cancel').disabled = true;

  new Ajax.Request('/ajax/media_title_update.html',
                  {asynchronous: true,
                   onSuccess: SavedMediaTitle,
                   method: 'post',
                   parameters: params });
 }

/* media tags editing routines */

var last_edited_media_tags = false;

function CancelMediaTags(mediaID)
 {
  $('media_' + mediaID + '_tags').style.display = 'block';
  $('media_' + mediaID + '_tags_editor').style.display = 'none';

  v = $('media_' + mediaID + '_tags_value');
  v.value = v.srcvalue;
 }

function EditMediaTags(mediaID)
 {
  if (last_edited_media_tags)
   CancelMediaTags(last_edited_media_tags);

  last_edited_media_tags = mediaID;

  $('media_' + mediaID + '_tags').style.display = 'none';
  $('media_' + mediaID + '_tags_editor').style.display = 'block';

  v = $('media_' + mediaID + '_tags_value');
  v.srcvalue = v.value;

  v.focus();
  v.value = v.value;

  return false;
 }

function SavedMediaTags(r)
 {
  r = r.responseText.split("\x0A");

  if (r.length == 3)
   {
    mediaID = r[0];
    tags = r[1];
    tags_html = r[2];

    $('media_' + mediaID + '_tags_value').srcvalue = tags;
    $('media_' + mediaID + '_tags_value').value = tags;
    $('media_' + mediaID + '_tags_data').innerHTML = tags_html;

    CancelMediaTags(mediaID);

    $('media_' + mediaID + '_tags_value').disabled = false;
    $('media_' + mediaID + '_tags_save').disabled = false;
    $('media_' + mediaID + '_tags_cancel').disabled = false;
   }
 }

function SaveMediaTags(mediaID)
 {
  params = 'mediaID=' + mediaID + '&' + 
           'digest=' + digest + '&' +
           'tags=' + encodeURIComponent($('media_' + mediaID + '_tags_value').value);

  $('media_' + mediaID + '_tags_value').disabled = true;
  $('media_' + mediaID + '_tags_save').disabled = true;
  $('media_' + mediaID + '_tags_cancel').disabled = true;

  new Ajax.Request('/ajax/media_tags_update.html',
                  {asynchronous: true,
                   onSuccess: SavedMediaTags,
                   method: 'post',
                   parameters: params });
 }

/* media processing support routines */

function IsMediaProcessing(mediaID)
 {
  return $('media_' + mediaID + '_processing') > 0 ? true : false;
 }

function StartMediaProcessing(mediaID)
 {
  p = $('media_' + mediaID + '_processing');
  p.style.display = 'block';
  p.pcount = p.pcount ? p.pcount + 1 : 1;

  if (p.pcount == 1)
   {
    element = $('media_' + mediaID + '_image');
    element._opacity = Element.getOpacity(element);
    new Effect.Opacity(element, { duration: 0.3, from: element._opacity, to: 0.6 });
   }
 }

function StopMediaProcessing(mediaID)
 {
  p = $('media_' + mediaID + '_processing');
  p.pcount = p.pcount - 1;

  if (p.pcount == 0) 
   {
    p.style.display = 'none';

    element = $('media_' + mediaID + '_image');
    element._opacity = Element.getOpacity(element);
    new Effect.Opacity(element, { duration: 0.2, from: element._opacity, to: 1 });
   }
 }

function ReloadMedia(mediaID)
 {
  m = $('media_' + mediaID + '_image');
  s = m.src.split("?");
  m.src = s[0] + '?' + Math.random() + '&' + Math.random();
 }

/* media processing routines */

function UpdateGalleryWeights(galleryID, weights)
 {
  params = 'galleryID=' + galleryID + '&' + 
           'digest=' + digest + '&' +
           weights;

  new Ajax.Request('/ajax/gallery_weights_update.html',
                   {asynchronous: true,
                    method: 'post',
                    parameters: params });
 }

function MediaDeleted(r)
 {
  r = r.responseText;

  if ($('media_' + r))
   Effect.Fade('media_' + r);
 }

function DeleteMedia(mediaID)
 {
//  if (!confirm('?')) return false;

  params = 'mediaID=' + mediaID + '&' + 
           'digest=' + digest;

  new Ajax.Request('/ajax/delete_media.html',
                   {asynchronous: true,
                    method: 'post',
                    onSuccess: MediaDeleted,
                    parameters: params });

  return false;
 }

function MediaRotated(r)
 {
  r = r.responseText;

  if ($('media_' + r))
   {
    StopMediaProcessing(r);
    ReloadMedia(r);
   }
 }

function RotateMediaCW(mediaID)
 {
  if (IsMediaProcessing(mediaID)) return false;

  params = 'mediaID=' + mediaID + '&' + 
           'digest=' + digest;

  new Ajax.Request('/ajax/rotate_media_cw.html',
                   {asynchronous: true,
                    method: 'post',
                    onSuccess: MediaRotated,
                    parameters: params });

  StartMediaProcessing(mediaID);

  return false;
 }

function RotateMediaCCW(mediaID)
 {
  if (IsMediaProcessing(mediaID)) return false;

  params = 'mediaID=' + mediaID + '&' + 
           'digest=' + digest;

  new Ajax.Request('/ajax/rotate_media_ccw.html',
                   {asynchronous: true,
                    method: 'post',
                    onSuccess: MediaRotated,
                    parameters: params });

  StartMediaProcessing(mediaID);

  return false;
 }

/* "enter" rocks! */

function MediaEditNext1(mediaID, event)
 {
  if (event.keyCode == 13)
   {
    SaveMediaTitle(mediaID);
    EditMediaTags(mediaID);
   }
 }

function MediaEditNext2(mediaID, event)
 {
  if (event.keyCode == 13)
   {
    SaveMediaTags(mediaID);

    var m = $('media_' + mediaID);
    var n = m.nextSibling;

    if (n) EditMediaTitle(n.id.substr(6));
   }
 }

/* ajax pages stuff */

function UpdateFriendingButton(r)
 {
  if (s = $('friending_button_buzzie'))
   s.innerHTML = r.responseText;
 }

function AddFriend(button, userID)
 {
  button.className = 'disabled';
  params = 'userID=' + userID + '&' + 
           'digest=' + digest;

  new Ajax.Updater('friending_button',
                   '/ajax/add_friend.html?' + Math.random(),
                   {asynchronous: true,
                    method: 'post',
                    parameters: params,
                    onSuccess: UpdateFriendingButton });

  return false;
 }

function RemoveFriend(button, userID)
 {
  button.className = 'disabled';
  params = 'userID=' + userID + '&' + 
           'digest=' + digest;

  new Ajax.Updater('friending_button',
                   '/ajax/remove_friend.html?' + Math.random(),
                   {asynchronous: true,
                    method: 'post',
                    parameters: params,
                    onSuccess: UpdateFriendingButton });

  return false;
 }

function AddEnemy(button, userID)
 {
  button.className = 'disabled';
  params = 'userID=' + userID + '&' + 
           'digest=' + digest;

  new Ajax.Updater('friending_button',
                   '/ajax/add_enemy.html?' + Math.random(),
                   {asynchronous: true,
                    method: 'post',
                    parameters: params,
                    onSuccess: UpdateFriendingButton });

  return false;
 }

function RemoveEnemy(button, userID)
 {
  button.className = 'disabled';
  params = 'userID=' + userID + '&' + 
           'digest=' + digest;

  new Ajax.Updater('friending_button',
                   '/ajax/remove_enemy.html?' + Math.random(),
                   {asynchronous: true,
                    method: 'post',
                    parameters: params,
                    onSuccess: UpdateFriendingButton });

  return false;
 }

function UpdateReadingButton(r)
 {
  if (s = $('reading_button_buzzie'))
   s.innerHTML = r.responseText;
 }

function AddRead(button, feedID)
 {
  button.className = 'disabled';
  params = 'feedID=' + feedID + '&' + 
           'digest=' + digest;

  new Ajax.Updater('reading_button',
                   '/ajax/add_read.html?' + Math.random(),
                   {asynchronous: true,
                    method: 'post',
                    parameters: params,
                    onSuccess: UpdateReadingButton });

  return false;
 }

function RemoveRead(button, feedID)
 {
  button.className = 'disabled';
  params = 'feedID=' + feedID + '&' + 
           'digest=' + digest;

  new Ajax.Updater('reading_button',
                   '/ajax/remove_read.html?' + Math.random(),
                   {asynchronous: true,
                    method: 'post',
                    onSuccess: UpdateReadingButton,
                    parameters: params });

  return false;
 }

function UpdateJoiningButton(r)
 {
  if (s = $('joining_button_buzzie'))
   s.innerHTML = r.responseText;
 }

function AddJoin(button, feedID)
 {
  button.className = 'disabled';
  params = 'feedID=' + feedID + '&' + 
           'digest=' + digest;

  new Ajax.Updater('joining_button',
                   '/ajax/add_join.html?' + Math.random(),
                   {asynchronous: true,
                    method: 'post',
                    onSuccess: UpdateJoiningButton,
                    parameters: params });

  return false;
 }

function RemoveJoin(button, feedID)
 {
  button.className = 'disabled';
  params = 'feedID=' + feedID + '&' + 
           'digest=' + digest;

  new Ajax.Updater('joining_button',
                   '/ajax/remove_join.html?' + Math.random(),
                   {asynchronous: true,
                    method: 'post',
                    onSuccess: UpdateJoiningButton,
                    parameters: params });

  return false;
 }

function PostModerated(r)
 {
  r = r.responseText;

  if (r == '<!-- CLEAN -->')
   if (c = $('moderation_cleanup'))
    c.innerHTML = '';
 }

function AcceptPost(feedID, postID, full_body)
 {
  params = 'feedID=' + feedID + '&' + 
           'postID=' + postID + '&' + 
           'mode=accept&' + 
           'digest=' + digest + '&' +
           'full_body=' + full_body;

  new Ajax.Updater('post' + postID,
                   '/ajax/post_moderation.html?' + Math.random(),
                   {asynchronous: true,
                    method: 'post',
                    onSuccess: PostModerated,
                    parameters: params });

  return false;
 }

function DeclinePost(feedID, postID, full_body)
 {
  params = 'feedID=' + feedID + '&' + 
           'postID=' + postID + '&' + 
           'mode=decline&' + 
           'digest=' + digest + '&' +
           'full_body=' + full_body;

  new Ajax.Updater('post' + postID,
                   '/ajax/post_moderation.html?' + Math.random(),
                   {asynchronous: true,
                    method: 'post',
                    onSuccess: PostModerated,
                    parameters: params });

  return false;
 }

/* textarea's shit support routines */

function getCursor(input)
 {
  var result = { start: 0, end: 0, fixup: 0 };

  if (input.setSelectionRange)
   {
    result.start= input.selectionStart;
    result.end = input.selectionEnd;
   }
  else if (!document.selection) 
   { 
    return 0; 
   }
  else if (document.selection && document.selection.createRange)
   {
    var range = document.selection.createRange();
    var stored_range = range.duplicate();

    try { stored_range.moveToElementText(input); }
    catch (wtf) { }

    stored_range.setEndPoint('EndToEnd', range);

    // redmond's suckers must fire and fire in hell
    // ff&opera rulz

    var cnt = 0;

    for (k = 0; k < stored_range.text.length; k++)
     if (stored_range.text.charCodeAt(k) == 13)
      cnt++;

    result.start = stored_range.text.length - range.text.length;
    result.end = result.start + range.text.length;
    result.fixup = cnt;
   }

  return result;
 }

function setCursor(txtarea, start, end, fixup)
 {
  if (txtarea.createTextRange) 
   {
    var range = txtarea.createTextRange();
    range.move("character", start - fixup);
    range.select();
   } 
  else if (txtarea.selectionStart) 
   {
    txtarea.setSelectionRange(start, end);
   }
 }

function taTwin(id, b, starttag, endtag)
 {
  var txtarea = $(id) ? $(id) : id;

  txtarea.focus();

  var scrtop = txtarea.scrollTop;
  var cursorPos = getCursor(txtarea); 
  var nuCursorPos = 0;

  if (cursorPos.start == cursorPos.end)
   {
    if ((b) && (b.tagged = !b.tagged))
     { 
      txtarea.value = txtarea.value.substring(0, cursorPos.start) + starttag + txtarea.value.substr(cursorPos.start); 
      nuCursorPos = cursorPos.start + starttag.length;
     }
    else
     { 
      txtarea.value = txtarea.value.substring(0, cursorPos.start) + endtag + txtarea.value.substr(cursorPos.start); 
      nuCursorPos = cursorPos.start + endtag.length;
     }

    setCursor(txtarea, nuCursorPos, nuCursorPos, cursorPos.fixup);
   }
  else
   {
    var txt_pre = txtarea.value.substring(0, cursorPos.start);
    var txt_sel = txtarea.value.substring(cursorPos.start,cursorPos.end);
    var txt_aft = txtarea.value.substring(cursorPos.end);
    txtarea.value = txt_pre + starttag + txt_sel + endtag + txt_aft;
    var nuCursorPos = String(txt_pre + starttag + txt_sel + endtag).length;
    setCursor(txtarea, nuCursorPos, nuCursorPos, cursorPos.fixup);
   }

  if (scrtop) 
   txtarea.scrollTop = scrtop;

  return false;
 }

function taPut(ta, s)
 {
/*
  if (document.selection && document.selection.createRange)
   {
    window.focus();
    txtarea.focus();
    document.selection ? d.selection.createRange().text += s : ta.value += s;
   }
  else
*/
  taTwin(ta, false, '', s);

  return false;
 }

function taBold(ta, b) { return taTwin(ta, b, '<b>', '</b>'); }
function taItalic(ta, b) { return taTwin(ta, b, '<i>', '</i>'); }
function taUnderline(ta, b) { return taTwin(ta, b, '<u>', '</u>'); }
function taStrike(ta, b) { return taTwin(ta, b, '<s>', '</s>'); }
function taCut(ta, b) { return taPut(ta, '<cut>'); }
function taHelp(kind) { Helper(kind); return false; }

function taURL(ta)
 {
  var ta = $(ta);

  var FoundErrors = '';

  var enterURL = prompt("URL", "http://");

  if (!enterURL) 
   {
    FoundErrors += "\nNo URL.";
   }
  else
   {
    var enterTITLE = prompt("Text", "Text");

    if (!enterTITLE) 
     FoundErrors += "\nNo text.";
   }
 
  if (FoundErrors)
   alert(FoundErrors);
  else
   taPut(ta, '<a href="' + enterURL + '">' + enterTITLE + '</a>');

  return false;
 }

/* comments */

function MediaManager(ta)
 {
  return false;
 }

function LockCommentControls()
 {
  if (s = $('s1')) s.disabled = true;
  if (s = $('s2')) s.disabled = true;
  if (s = $('s3')) s.disabled = true;
 }

function UnlockCommentControls()
 {
  if (s = $('s1')) s.disabled = false;
  if (s = $('s2')) s.disabled = false;
  if (s = $('s3')) s.disabled = false;
 }

function PreviewCommentLoaded(r)
 {
  UnlockCommentControls();
 }

function PreviewComment()
 {
  LockCommentControls();

  new Ajax.Updater('CommentPreview',
                   '/ajax/comment_preview.html?' + Math.random(),
                   {asynchronous: true, 
                    parameters: 'digest=' + digest + '&' + Form.serialize($('EditorForm')), 
                    onSuccess: PreviewCommentLoaded,
                    evalScripts: true });
 }

/* our megacommenting engine :) produced by LJ & Kolbaskin :) */

var prevkapusta = 'abcc';
var prev1 = 0;
var prev2 = 0;
var submitreplycommentID = 0;

function FocusCommenter()
 {
  if (ta = $('ta'))
   ta.focus();
 }

function DelayedFocusCommenter()
 {
  setTimeout('FocusCommenter();', 100);
 }

function ReplyComment(ownerid, skipfocus)
 {
  var atarget = 'qr' + ownerid;
  var target = 'qra' + ownerid;

  if (!(t = $(target))) return;
  if (!(a = $(atarget))) return;
  if (!(c = $('CommentFormContainer'))) return;

  if ((prev1) && (prev2))
   SwapNodes(prev1, prev2);

  SwapNodes(c, t);

  prev1 = c;
  prev2 = t;

  if (prevkapusta)
   if (p = $(prevkapusta))
    p.style.display = 'inline';

  a.style.display = 'none';
  c.style.display = 'block';

  prevkapusta = atarget;

  $('qr0').style.display = (ownerid == 0) ? 'none' : 'block';

  if (o = $('replycommentID'))
   o.value = ownerid;

  if (!skipfocus)
   setTimeout('FocusCommenter();', 100);

  return false;
 }

function SubmitCommentDoneWorker()
 {
  if ($('new_comment'))
   {
//    ReplyComment(0, 1);
    Element.scrollTo('new_comment');
//    $('CommentFormContainer').style.display = 'none';
   }
  else
   {
    ReplyComment(submitreplycommentID);
   }

  if (o = $('replycommentID'))
   o.value = '0';
 }

function SubmitCommentDone(r)
 {
  setTimeout('SubmitCommentDoneWorker()', 50);
 }

function SubmitComment()
 {
  submitreplycommentID = $('replycommentID').value;
  submitreplycommentID = submitreplycommentID ? submitreplycommentID : 0;

  LockCommentControls();

  new Ajax.Updater('comments_data',
                   '/ajax/comment_submit.html?' + Math.random(),
                   {asynchronous: true, 
                    method: 'post',
                    onSuccess: SubmitCommentDone,
                    parameters: 'digest=' + digest + '&' + Form.serialize($('EditorForm')),
                    evalScripts: true });

  return false;
 }

function DeleteComment(commentID)
 {
//  if (confirm('?'))
  if (true)
   {
    LockCommentControls();

    new Ajax.Updater('comments_data',
                     '/ajax/comment_delete.html?' + Math.random(),
                     {asynchronous: true, 
                      method: 'post',
                      onSuccess: SubmitCommentDone,
                      evalScripts: true,
                      parameters: 'digest=' + digest + '&commentID=' + commentID + '&' + Form.serialize($('EditorForm')) });
   }

  return false;
 }

var muccomment = false;

function MoveUpComment(commentID)
 {
  var s = $('c' + commentID);

  if (muccomment)
   muccomment.className = muccomment._className;

  s._className = s.className;
  s.className = 'inner parent_comment';

  Element.scrollTo(s);

  muccomment = s;

  return false;
 }

function Track(ownerID, commentID, small)
 {
  new Ajax.Updater('track-' + ownerID + '-' + commentID + '-' + small,
                   '/ajax/track.html?' + Math.random(),
                   {asynchronous: true, 
                    method: 'post',
                    parameters: 'digest=' + digest + 
                               '&ownerID=' + ownerID + 
                               '&commentID=' + commentID + 
                               '&small=' + small +
                               '&track=1' });

  return false;
 }

function Untrack(ownerID, commentID, small)
 {
  new Ajax.Updater('track-' + ownerID + '-' + commentID + '-' + small,
                   '/ajax/track.html?' + Math.random(),
                   {asynchronous: true, 
                    method: 'post',
                    parameters: 'digest=' + digest + 
                               '&ownerID=' + ownerID + 
                               '&commentID=' + commentID + 
                               '&small=' + small +
                               '&untrack=1' });

  return false;
 }

function Favourite(kind, kindID, small)
 {
  new Ajax.Updater('favourite-' + kind + '-' + kindID + '-' + small,
                   '/ajax/favourite.html?' + Math.random(),
                   {asynchronous: true, 
                    method: 'post',
                    parameters: 'digest=' + digest + 
                               '&kind=' + kind + 
                               '&kindID=' + kindID + 
                               '&small=' + small +
                               '&add=1' });

  return false;
 }

function Unfavourite(kind, kindID, small)
 {
  new Ajax.Updater('favourite-' + kind + '-' + kindID + '-' + small,
                   '/ajax/favourite.html?' + Math.random(),
                   {asynchronous: true, 
                    method: 'post',
                    parameters: 'digest=' + digest + 
                               '&kind=' + kind + 
                               '&kindID=' + kindID + 
                               '&small=' + small +
                               '&remove=1' });

  return false;
 }

/* flash */

function HideBanner()
 {
  if ((rb = $('rightbanner')) && (rbs = $('rightbannerstub')))
   {
    rb.style.display = 'none';
    rbs.style.display = 'block';
   }
 }

function ShowBanner()
 {
  if ((rb = $('rightbanner')) && (rbs = $('rightbannerstub')))
   {
    rb.style.display = 'block';
    rbs.style.display = 'none';
   }
 }

/* rows */

function HilightRow(r)
 {
  r.className = 'hilight';
 }

function UnhilightRow(r)
 {
  r.className = '';
 }

/* misc */

function JustFlip(a, b)
 {
  $(a).style.display = 'none';
  $(b).style.display = 'block';

  return false;
 }

function Aura(userID, hash, value)
 {
  new Ajax.Updater('auradata', '/ajax/aura.html?' + Math.random(), {asynchronous: true, method: 'post', parameters: 'digest=' + digest + '&victimID=' + userID + '&hash=' + hash + '&value=' + value });

  return false;
 }

function VotePost(postID, hash, value, div)
 {
  new Ajax.Updater('voter' + div,
                   '/ajax/postvote.html?' + Math.random(),
                   {asynchronous: true, 
                    method: 'post',
                    parameters: 'digest=' + digest + 
                               '&postID=' + postID + 
                               '&hash=' + hash + 
                               '&value=' + value + 
                               '&div=' + div});

  return false;
 }

function VoteMedia(mediaID, hash, value, div)
 {
  new Ajax.Updater('voter' + div,
                   '/ajax/mediavote.html?' + Math.random(),
                   {asynchronous: true, 
                    method: 'post',
                    parameters: 'digest=' + digest + 
                               '&mediaID=' + mediaID + 
                               '&hash=' + hash + 
                               '&value=' + value + 
                               '&div=' + div});

  return false;
 }

function ToggleVisibility(id)
 {
  $(id).style.display = $(id).style.display == 'block' ? 'none' : 'block';

  return false;
 }

function UnEnemyComment(commentID)
 {
  $('ec' + commentID).style.display = 'block';
  $('eca' + commentID).style.display = 'none';

  return false;
 }

function UnEnemyPost(postID)
 {
  $('ep' + postID).style.display = 'block';
  $('epa' + postID).style.display = 'none';

  return false;
 }

/* ja ja */

function InsertSomething()
 {
  width = 700;
  height = 300;

  var left = Math.round((document.body.clientWidth - width) / 2);
  var top = Math.round((document.body.clientHeight - height) / 2);

  var win = window.open('/misc/insert.html?',
                        'insertsomething', 
                        'toolbar=no,' +
                        'scrollbars=yes,' +
                        'status=no,' +
                        'height=' + height + ',' +
                        'width=' + width + ',' + 
                        'top=' + top + ',' +
                        'left=' + left);

  win.focus();

  return false;
 }

function InsertToOpener(id, content)
 {
  var d = window.opener.document;
  var ta = window.opener.document.getElementById(id);

  taPut(ta, content);

  return true;
 }
