var successModal;

$(function()
{
  var $form = $('#dataform');
  $form.ajaxForm({beforeSubmit: validateFormData});
  $form.on('change', function(event)
  {
    $(event.target).closest('td').find('.help-text').remove();
  });
});

function sendSuccess(email)
{
  var successHtml = $($('#sendSuccess').html());
  successHtml.find('.content').html(userLang.sendContent.replace('%s', "<strong>" + email + "</strong>"));
  successModal = new $.zui.ModalTrigger(
  {
    title: userLang.sendTitle,
    icon: 'check',
    width: 400,
    custom: successHtml
  });
  successModal.show();
}

function closeSuccess()
{
  if(successModal) successModal.close();
  window.location.href = createLink('user', 'login');
}

function validateFormData(data, $form)
{
  var hasError = false;
  $form.find('.helper-text').remove();

  data.forEach(function(formItem)
  {
    var isEmpty  = !(!formItem || formItem.value.length);
    var name     = formItem.name;
    var $label   = $('#' + name + 'Label');
    var $control = $('#' + name);
    var label    = $control.closest('tr').find('th').text();
    $label.remove();

    if(isEmpty)
    {
      $label = '<div id="' + name + 'Label" class="text-danger help-text">' + userLang.notEmpty.replace('%s', label) + '</div>';
      $control.closest('td').append($label);
      hasError = true;
      return false;
    }

    if(formItem.name == 'email' && !isEmail(formItem.value))
    {
      $label = '<div id="' + name + 'Label" class="text-danger help-text">' + userLang.emailFormatError + '</div>';
      $control.closest('td').append($label);
      hasError = true;
      return false;
    }
  });

  if(hasError) return false;
  return true;
}

function isEmail(strEmail){
  var reg=/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
  return strEmail != null && strEmail.search(reg) != -1;
}
