/*
	File: textile_bar.js
	About: This plugin adds a button bar for textile tag inclusion obove the comments field
  Logahead Version: logahead UNU edition by Klaus Schlichter
	Licence: GPL
*/

function commentinforeplacer()
{
  if (div = document.getElementById('commentcontent')) {
    divpa = div.parentNode;
    
    infotext= 'first select text then click here';
    quicklinks = '<a href="javascript:surroundby(\'*\')" title="'+infotext+'">bold</a> | <a href="javascript:surroundby(\'_\')" title="'+infotext+'">italic</a> | <a href="javascript:surroundby(\'??\')" title="'+infotext+'">cite</a> | <a href="javascript:surroundby(\'-\')" title="'+infotext+'">strike</a> | <a href="javascript:surroundby(\'+\')" title="'+infotext+'">underline</a> | <a href="javascript:includeimg()">img</a> | <a href="javascript:includelink()" title="'+infotext+'">link</a>';    
    
    var commentboxdiv = document.createElement("div");
    commentboxdiv.id="commentbuttons";
    commentboxdiv.className="tooltip";
    commentboxdiv.display="inline;";
    
    divpa.insertBefore(commentboxdiv,div);
    document.getElementById('commentbuttons').innerHTML=quicklinks;
  }
}

function surroundby(textilechar,endtag) {
  if (typeof endtag == "undefined") endtag=textilechar;
  if (textilechar!="") textilechar=" "+textilechar;
  if (endtag!="") endtag=endtag+" ";
  
  commentDiv=document.getElementById('commentcontent');

	if (document.selection) {
		commentDiv.focus();
	  sel=document.selection.createRange();
		sel.text=textilechar+sel.text.replace(/^\s+/g, '').replace(/\s+$/g, '')+endtag;
		commentDiv.focus();
	} else if (commentDiv.selectionStart || commentDiv.selectionStart == '0') {
		var startPos=commentDiv.selectionStart;
		var endPos=commentDiv.selectionEnd;
		var cursorPos=endPos;
		var scrollTop=commentDiv.scrollTop;
	  commentDiv.value=commentDiv.value.substring(0,startPos)
      + textilechar
      + commentDiv.value.substring(startPos,endPos).replace(/^\s+/g, '').replace(/\s+$/g, '')
      + endtag
      + commentDiv.value.substring(endPos,commentDiv.value.length);
		cursorPos+=textilechar.length+endtag.length;
		commentDiv.focus();
		commentDiv.selectionStart=cursorPos;
		commentDiv.selectionEnd=cursorPos;
		commentDiv.scrollTop=scrollTop;
	}
	commentDiv.focus();  
}

function includelink() {
  if (linkURL=prompt('Please enter link URL' ,'http://'))
    surroundby('"','":'+linkURL);
}

function includeimg() {
  if (imgURL=prompt('Please enter image URL','http://'))
    surroundby('!'+imgURL+'! ','');
}

//Use this function to add functions that will be called when the pages loads.
addLoadEvent(commentinforeplacer);