// Ajax Comment Posting
// WordPress plugin
// version 1.2.2
// author: regua
// http://regua.biz

jQuery(document).ready(function(){

  jQuery.noConflict();

  var _status = null;
  function Status(readonly) {
    if ((!_status) || (!_status.length)) {
      _status = jQuery('#comment-error');
      if ((!readonly) && (!_status.length)) {
        jQuery('#commentform').after('<div id="comment-error" class="comment-status"></div>');
        _status = jQuery('#comment-error');
        _status.click(function() {
          _status.fadeOut('slow').hide();
          return false;
        });
      }
    }
    return _status;
  }
  function Error(message) {
    var stat = Status();
    if (message) {
      stat.text(message).removeClass('success').addClass('error').show().fadeIn('slow');
    }
    return stat;
  }
  function Success(message) {
    var stat = Status();
    if (message) {
      stat.text(message).removeClass('error').addClass('success').show().fadeIn('slow');
    }
    return stat;
  }
  function hideStatus() {
    var stat = Status(true);
    if (stat.length) {
      stat.fadeOut('slow').empty().hide();
    }
    return stat;
  }

  function beginLoading() {
    var loading = jQuery('#comment-loading');
    if (!loading.length)
      jQuery('#submit').after('<span id="comment-loading"><img src="/wordpress/wp-content/plugins/ajax-comment-posting/loading.gif" alt="Loading..." /></span>');
    jQuery('#submit').addClass('loading').attr('disabled','disabled');
    loading.show();
  }
  function endLoading() {
    var loading = jQuery('#comment-loading');
    if (!loading.length)
      jQuery('#submit').after('<span id="comment-loading"><img src="/wordpress/wp-content/plugins/ajax-comment-posting/loading.gif" alt="Loading..." /></span>');
    loading.hide();
    jQuery('#submit').removeClass('loading').removeAttr("disabled");
  }

  function processError(response) {
    if (response.search(/<title>WordPress &rsaquo; Error<\/title>/) != -1) {
      var data = response.match(/<p>(.*)<\/p>/);
      Error(data[1]);
    } else
    if (response.search(/<body>[\s\S]*<\/body>/i) != -1) {
      try {
        var doc = jQuery("<ol>").html(response);
        // 1) Replace runs of linefeed/whitespace with single linefeed
        // 2) Remove terminating linefeed
        // 3) Replace linefeeds with BR tags.
        Error(doc.text().replace(/\s*\n+\s*/g, '\n').replace(/^([\s\S]*)\n$/m, '$1').replace(/\.?\n/g, '. '));
      } catch(e) {
        alert(e);
        Error(response);
      }
    } else {
      Error(response);
    }
  }

  var form = jQuery('#commentform');

  // WP Ajax Edit Comments hook
  if (window.AjaxEditComments) {
    AjaxEditComments.init();
  }

  form.submit(function() {

  // Force tinyMCE to update the textarea
  if (window.tinyMCE);
    tinyMCE.triggerSave();

  function validateField(fieldname, description, mask) {
    var field = form.find(fieldname);
    var valid = true;
    if (field)
      field.removeClass('error');
    else
      return valid;

    valid = (field.val() != '');
    if (valid) {
      if (mask) {
        valid = mask.test(field.val());
        if (!valid)
          Error('Please enter a valid '+description+'.');
      }
    } else
      Error('Please enter your '+description+'.');

    if (!valid)
      field.addClass('error');
      return valid;
    }

    if(form.find('#author')[0]) {
      if (!validateField('#author', 'name')) return false;
      if (!validateField('#email', 'email address', /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/)) return false;
    }
    if (!validateField('#comment', 'comment')) return false;

    jQuery(this).ajaxSubmit({

      beforeSubmit: function() {
        hideStatus();
        beginLoading();
      },

      error: function(request){
        processError(request.responseText);
        endLoading();
        return false;
      },

      success: function(request) {
        try {
          response = jQuery("<ol>").html(request);
          if (response.find('.commentlist')[0]) {
            if (jQuery(document).find('.commentlist')[0]) {
              jQuery('.commentlist').empty();
              jQuery('.commentlist').html(response.find('.commentlist').html());
            } else {
              jQuery('#respond').before(response.find('.commentlist'));
            }
            // REMOVE THIS IF YOU DON'T WANT THE FORM TO DISAPPEAR
            /*
            form.remove();
            jQuery('#respond').hide();
            */
            Success('Your comment has been added.');
            if (jQuery(document).find('#comments')[0]) {
              jQuery('#comments').html(response.find('#comments').html());
            } else {
              jQuery('.commentlist').before(response.find('#comments'));
            }
          } else
            processError(request);
          endLoading();

        } catch (e) {
          endLoading();
          alert(e);
        }

        // WP Ajax Edit Comments hook
        if (window.AjaxEditComments) {
          AjaxEditComments.init();
        }

      }
    });

    return false;

  });
});

