//author: Chaitan (hello _AT_ chaitan.com)

var canFormat = 0;
if (document.selection)
  canFormat = 1;
var ua = navigator.userAgent;
if (ua.indexOf('Gecko') >= 0 && ua.indexOf('Safari') < 0)
  canFormat = 1;

//function to display comment tools such as bold, 
//italicize, quote, etc.
function commentTools() {
  var commentTxBox = "document.commentform.text";
  
  if (canFormat) {
    with (document) {
        write('<img src="/sepia/images/left_endcap.gif" width="8" ' + 
	  'height="24" border=0 />');
        write('<a title="Quote" href="#" onclick="return ' + 
	  'formatStr(' + commentTxBox + ', \'blockquote\')">' +
	  '<img src="/sepia/images/blockquote_button.gif" alt="Quote" ' + 
	  'width="22" height="24" border=0 /></a>');
        write('<a title="Insert Link" href="#" ' + 
	  'onclick="return insertLink(' + commentTxBox + ')">' +
	  '<img src="/sepia/images/hyperlink_button.gif" alt="Insert Link" ' +
	  'width="22" height="24" border=0 /></a>');
        write('<a title="Bold" href="#" ' + 
	  'onclick="return formatStr(' + commentTxBox + ', \'b\')">' +
	  '<img src="/sepia/images/bold_button.gif" alt="Bold" width="22" ' +
	  'height="24" border=0 border=0/></a>');
        write('<a title="Italic" href="#" ' + 
	  'onclick="return formatStr(' + commentTxBox + ', \'i\')">' +
	  '<img src="/sepia/images/italic_button.gif" alt="Italic" ' + 
	  'width="22" height="24" border=0 /></a>');
        write('<a title="Underline" href="#" ' +
	  'onclick="return formatStr(' + commentTxBox + ', \'u\')">' + 
	  '<img src="/sepia/images/underline_button.gif" alt="Underline" ' +
	  'width="22" height="24" border=0 /></a>');
        write('<a title="Strikeout" href="#" ' +
	  'onclick="return formatStr(' + commentTxBox + ', \'strike\')">' +
	  '<img src="/sepia/images/strikeout_button.gif" alt="Strikeout" ' +
	  'width="22" height="24" border=0 /></a>');
        write('<img src="/sepia/images/right_endcap.gif" width="8" ' +
	  'height="24" border=0 /></a>');
    }
  }
}

//fill Blog comment form
//copied over from MT template.
function fillBlogCommentForm() {
    if (document.commentform) { //if comments are still open
      if (document.commentform.email != undefined)
        document.commentform.email.value = getCookie("mtcmtmail");
	
      if (document.commentform.author != undefined) 
        document.commentform.author.value = getCookie("mtcmtauth");
	
      if (document.commentform.url != undefined)
        document.commentform.url.value = getCookie("mtcmthome");
	
      if (document.commentform.bakecookie != undefined) {
        if (getCookie("mtcmtauth") || getCookie("mtcmthome")) {
          document.commentform.bakecookie[0].checked = true;
        } else {
          document.commentform.bakecookie[1].checked = true;
        }
      }
      
    }
}
Event.observe(window, 'load', fillBlogCommentForm);

//AJAX Post event to add Negative Vote
//to a comment in the News section.
function flagComment(commentID, voteType) {
  //disable duplicate request first
  $('commentActions' + commentID).innerHTML = "";
  new Effect.Highlight('commentBody' + commentID,
    {startcolor: '#a36325',
     endcolor: '#ffffff',
     restorecolor: '#ffffff',
     duration: 0.5});
  
  var success = function(t){ flagComplete(t, commentID, voteType); }
  var failure = function(t){ alert('Sorry, update failed.'); }
  
  var url = '/sepia/cgi-bin/AjaxListener.php';
  var pars = 'smOption=commentFlag&commentID=' + commentID + '&voteType=' + voteType;
  var myAjax = new Ajax.Request(url, {method: 'post',
		postBody: pars,
		onSuccess:success, onFailure:failure});
}

//Post-AJAX function called after flagComment succeeds.
function flagComplete(t, obj, voteType) {
  var e = t.responseText.indexOf('success');
  if (e >= 0) {
    toggleComment(obj);
    $('commentFlag'+obj).innerHTML = voteType;
  } else {
    alert('Error! update failed.');
  }
}

//used in Comment tools. gets selected text.
//processes per tool. replaces selected text with
//processed text.
function formatStr (e, v) {
    if (!canFormat) return;
    var str = getSelection(e);
    if (!str) return;
    setSelection(e, '<' + v + '>' + str + '</' + v + '>');
    return false;
}

//used in Comment tools. gets selected text for
//processing by a comment tool.
function getSelection (e) {
    if (document.selection)
        return document.selection.createRange().text;
    else {
        var length = e.textLength;
        var start = e.selectionStart;
        var end = e.selectionEnd;
        if (end == 1 || end == 2) end = length;
        return e.value.substring(start, end);
    }
}

//comment tool to insert a link, i.e., create a hyperlink.
function insertLink (e, isMail) {
    if (!canFormat) return;
    var str = getSelection(e);
    if (!str) return;
    var my_link = isMail ? prompt('Enter email address:') : prompt('Enter URL:', '');
    if (isMail) my_link = 'mailto:' + my_link;
    if (my_link != null)
        setSelection(e, '<a href="' + my_link + '">' + str + '</a>');
    return false;
}    

//news comment submit.
//disable submit button to prevent duplicate comment.
function postNewsComment() {
  //$('post').disabled = true;
  //$('posting-message').style.visibility = 'visible';
  //document.getElementedById('preview').disabled = true;
  //this.form.submit();
  waitShow();
}

//quote News comment. saves time copy-pasting someone's comment
//in response.
function quoteComment(commentId) {
  //check if there is any selection.
  var cSelected;
  if (document.getSelection) {
    cSelected = document.getSelection();
  } else if (document.selection && document.selection.createRange) {
    cSelected = document.selection.createRange().text;
  }
  
  //move focus to text box.
  $('text').focus();
  var cAuthor = $('author' + commentId);
  var cText = "";
  if (cAuthor) {
    cText = "<i>" + cAuthor.innerHTML;
    cText += " <a href=\"" + $('perma' + commentId).getAttribute("href");
    cText += "\">said</a></i>";
  }
  
  //if no selection found, select entire comment.
  if (!cSelected) {
    cSelected = $('commentBody' + commentId).innerHTML;
  }
  
  cText += "<blockquote>" + cSelected.replace(/^[\n,\s]*/, "").replace(/[\n,\s]*$/, "") + "</blockquote>";
  cText = cText.replace(/<p>/gi, ""); //remove <p> tags.
  cText = cText.replace(/<\/p>/gi, "\n"); //replace </p> tags with 2 newlines
  cText = cText.replace(/<br[\s,\/]*>/gi, ""); //replace <br> tags with 1 newline
  $('text').value = cText + "\n\n";
}

//comment tools use this function to replace selected text
//after processed by tool.
function setSelection (e, v) {
    if (document.selection)
        document.selection.createRange().text = v;
    else {
        var length = e.textLength;
        var start = e.selectionStart;
        var end = e.selectionEnd;
        if (end == 1 || end == 2) end = length;
        e.value = e.value.substring(0, start) + v + e.value.substr(end, length);
    }
}

//show hidden news comment input form. 
//probably obsolete since news comments are now allowed only
//for registered users. double check later. (by Chaitan)
function showCommentInputForm() {
  document.getElementById('commentInputForm').style.display = "block";
}

//show / hide a comment.
//hide: used by functions that mark a comment as spam or abusive.
//show: used by functions that mark a comment as immune.
function toggleComment(commentId) {
  var c = $('commentBody'+commentId).style;
  var ctrl = $('toggleComment'+commentId);
  c.display = (ctrl.innerHTML=='+')?'block':'none';
  ctrl.innerHTML = (ctrl.innerHTML=='-')?'+':'-';
}

//AJAX call for a news comment vote.
function updateComment(commentID, voteType) {
  //disable duplicate request first
  $('commentActions' + commentID).innerHTML = "";
  new Effect.Highlight('commentBody' + commentID,
    {startcolor: '#a36325',
     endcolor: '#ffffff',
     restorecolor: '#ffffff',
     duration: 0.5});
  
  var success = function(t){ updateComplete(t, commentID, voteType); }
  var failure = function(t){ alert('Sorry, update failed.'); }
  
  var url = '/sepia/cgi-bin/AjaxListener.php';
  var pars = 'smOption=commentFlag&commentID=' + commentID + '&voteType=' + voteType;
  var myAjax = new Ajax.Request(url, {method: 'post',
		postBody: pars,
		onSuccess:success, onFailure:failure});
}

//post-AJAX call on news comment vote success.
function updateComplete(t, obj, voteType) {
  var e = t.responseText.indexOf('success');
  if (e >= 0) {
    if (voteType == "delete") {
      Effect.Fade('commentDiv' + obj,
        {duration: 5});
    } else {
      //toggleComment(obj);
      $('commentFlag'+obj).innerHTML = voteType;
    }
  } else {
    alert('Error! update failed.');
  }
}

