var comment = function () {
  var newForm, newContainer, replyForm, replyContainer, parentPosition, 
  changeCaptcha = function () {
    $('#comment_captcha,#reply_comment_captcha').attr('src', '/captcha?reload=1&rand='+Math.floor( Math.random () * 999999 + 1));
  },
  initForms = function () {
    if (newForm) return;
    newForm = $('#new_comment_form');
    newContainer = $('#new_comment');
    replyForm = $('#reply_comment_form');
    replyContainer = $('#reply_comment');
  },
  c = function(reply) {
    initForms();
    if (working) return false;
    working = true;
    var resp = '', form, container;
    form = !reply ? newForm : replyForm;
    container = !reply ? newContainer : replyContainer;
    $.ajax({
      url: form[0].action, 
      data: form.serialize(), 
      type: 'post',
      success: function (data) {
        resp = data;
      },
      complete: function (xhr) {
        if (xhr.status == 201) {
          $(resp).insertBefore(container);
          reply && container.hide();
          form.find(':input').val('');
          form.find('.error_list').remove();
          changeCaptcha();
        } else {
          form.html(resp);
          $('#'+(reply?'reply_':'')+'comment_message').markItUp(settings);
          changeCaptcha();
          FB && FB.XFBML.parse(container[0]);
        }
        working = false;
      }
    })
     
    return false; 
  },
  settings = {
    markupSet: [
      {name:'Bold', openWith:'[b]', closeWith:'[/b]'},
      {name:'Italic', openWith:'[i]', closeWith:'[/i]'},
      {name:'Underline', openWith:'[u]', closeWith:'[/u]'},
      {separator:'---------------' }/*,
      {name:'Youtube', replaceWith:'[youtube][![Url]!][/youtube]'},
      {name:'Vimeo', replaceWith:'[vimeo][![Url]!][/vimeo]'}*/
    ]
  },
  working = false;

  $(function () {
    $('#reply_comment_message,#comment_message').markItUp(settings);
    $(':input[name=\'comment[media_link]\']').focus(function () { this.select() });
  });                                                          
  
  c.addvideo = function (a) {
    a = $(a);
    a.hide().closest('div').find('div.comment_video').show(100);
    return false;
  }
  c.reply = function (parent) {
    initForms();

    replyForm.find(':input').val('').filter(':input[name$=\'parent_id]\']').val(parent);

    if (parentPosition != parent) {
      var temp = $('#replies'+parent);
      if (!temp.length) {
        $('<div id="replies'+parent+'" class="replies"></div>').insertAfter('#comment'+parent);
      }        
      replyContainer.appendTo('#replies'+parent).show();
      parentPosition = parent;
      changeCaptcha();
    } else {
      replyContainer.toggle();
    }
    return false;
  }
  c.captcha = changeCaptcha;

  return c;
}()
