var ajax_comment_loading = false;
function ajax_comments_loading(on) { if(on) {
  ajax_comment_loading = true;
  var f = $('commentform');
  f.submit.disabled = true; 
  new Insertion.Before(f, '<div id="ajax_comments_loading" style="display:none;">Espera un momento por favor, estamos guardando tu comentario...</div>'); 

  var l = $('ajax_comments_loading');
  new Effect.Appear(l, { beforeStart: function() { with(l.style) {
    display = 'block';
    margin = '0 auto';
    width = '450px';
    font = 'normal 12px Verdana';
    background = 'url(http://mrfabbianz.com/wp-content/plugins/ajax-comments/loading.gif) no-repeat 0 50%';
    padding = '5px 0 10px 23px';
  }}});
} else {
  new Effect.Fade('ajax_comments_loading', { afterFinish: function() { 
    Element.remove('ajax_comments_loading'); 
  }});
  $('commentform').submit.disabled = false; 
  ajax_comment_loading = false;
}}

function rotate_auth_image() {
  var img = $('auth-image'), input = $('code');
  if(img) img.src += '?'+Math.random(); 
  if(input) input.value = ''; 
}

function find_commentlist() {
  var e = $('commentlist');
  if(e == null) {
    var e = document.getElementsByTagName('ol');
    for(var i=0; i<e.length; i++)
      if(e[i].className=='commentlist')
        return e[i];
  } else return e;


  var f = $('commentform');
  new Insertion.Before(f, '<ol id="commentlist"></ol>'); 
  return $('commentlist');
}


function ajax_comments_submit() {
  if(ajax_comment_loading) return false;

  ajax_comments_loading(true);
  var f = $('commentform'), ol = find_commentlist();
  new Ajax.Request('http://mrfabbianz.com/wp-content/plugins/ajax-comments/ajax-comments.php?submit', {
    method: 'post',
    asynchronous: true,
    postBody: Form.serialize(f),
    onLoading: function(request) {
      request['timeout_ID'] = window.setTimeout(function() {
        switch (request.readyState) {
        case 1: case 2: case 3:
          request.abort();
          alert('Comment Error: Timeout\nEl servidor esta tomando demasiado tiempo en responder. Por favor, disculpa las molestias y vuelve a intentarlo en unos momentos.');
          break;
        }
      }, 25000);
    },
    onFailure: function(request) {
      alert((request.status!=406? 'Comment Error '+request.status+' : '+request.statusText+'\n' : '')+request.responseText);
    },
    onComplete: function(request) { ajax_comments_loading(false);
      window.clearTimeout(request['timeout_ID']);
//      rotate_auth_image();
      if(request.status!=200) return;

      f.comment.value=''; 

      new Insertion.Bottom(ol, request.responseText);
      var li = ol.lastChild, className = li.className, style = li.style;
      new Effect.BlindDown(li, {
        afterFinish: function() { li.className = className; li.style = style; }
      });
    }
  });
  return false;
}
