/**
 * Carga el listado de comentarios
 */
$().ready( function() {
  if (typeof(commentsTarget) != 'undefined') {
    $.ajax({
      type: "GET",
      url: "/nf/AjaxResponse/itemComments",
      data: "itemId=" + itemId,
      success: function(resp){
        $("#" + commentsTarget).html(resp);
        setFormEvents();
      }
    });
  } else {
    setFormEvents();
  }
});

/**
 * Carga el validador de formulario para los comentarios
 */
function setFormEvents() {

  // Reglas de validacion
  var frmValidate = {
    rules: {
      commentTxt: 'required'
    },
    errorClass: 'errorLbl'
  };
  if ($("#commentUserName").length) {
    frmValidate.rules.commentUserName = 'required';
  }
  if ($("#commentEmail").length) {
    frmValidate.rules.commentEmail = {
      required: true,
      email: true
    };
  }
  if ($("#security_code").length) {
    frmValidate.rules.security_code = "required";
  }


  // Genera los observer de validacion.
  $("#commentsForm").validate(frmValidate);
    
  // Submit del Form
  $("#commentsForm").submit(function () {
    if ($("#commentsForm").valid()) {
      $("#btnSubmit").hide();
      $("#loadingImg").show();
      postComment();
    }
    return false;
  });
  
  // Verifica si se ponen las estrellas
  if ($("#r1").length) {
    setStarts();
  }
}

/**
 * Post de comentario$("#r" + i)
 */
function postComment() {
  $.ajax({
    type: "POST",
    dataType: "json",
    url: $("#commentsForm").attr('action'),
    data: $("#commentsForm").serialize(),
    success: function(resp) {
      if (resp.error) {
        // Valida PHP
        $("#btnSubmit").show();
        $("#loadingImg").hide();
        displayValidationForm(resp);
      } else {
        // Todo Ok
        $("#frmComments").slideUp();
        $("#loadingImg").hide();
        $("#txtOk").show();
      }
    }
  });
}

// Validaciones por PHP
function displayValidationForm(resp) {
  $("label.errorLbl[for=commentUserName]").hide();
  $("label.errorLbl[for=commentEmail]").hide();
  $("label.errorLbl[for=commentTxt]").hide();
  if ($("#security_code")) {
    $("label.errorLbl[for=security_code]").hide();
  }
  if (resp.errorUserName) {
    $("label.errorLbl[for=commentUserName]").show();
  }
  if (resp.errorEmail) {
    $("label.errorLbl[for=commentEmail]").show();
  }
  if (resp.errorTxt) {
    $("label.errorLbl[for=commentTxt]").show();
  }
  if (resp.errorSecurityCode) {
    $("label.errorLbl[for=security_code]").show();
  }
  // Control de spam en el replyAction
  if (resp.errorSpam) {
    $("#spamError").show();
    $("#commentTxt").val('');
  }
}

