﻿//(function ($) {

var interactivityHandlers = (function () {

  //bindInteractivityPrivate();

  function bindInteractivityPrivate(baseSelector) {
    if (typeof baseSelector === 'undefined') {
      baseSelector = $('body');
    }

    $(baseSelector).find('form.f-ajax').each(function () {
      $(this).addInteractivity({
        onApplyErrorList: onApplyErrorListHandler,
        onFormSubmitted: onFormSubmittedHandler,
        onShowCustomResult: onShowCustomResultHandler
      });
    });
  }

  function onApplyErrorListHandler(form, errorList) {
    var i = 0,
        generalErrors = [],
        $firstErroneousField; // Not tied to a particular input field

    for (i = 0; i < errorList.length; i++) {
      if (errorList[i].FieldName) {
        $(form).find('[name="' + errorList[i].FieldName + '"]').addClass('erroneous').closest('.f-row, .f-col').append('<em class="erroneous"">' + errorList[i].ErrorMessage + '</em>');
      }
      else {
        if (errorList[i].ErrorMessage.length > 0) {
          generalErrors.push(errorList[i].ErrorMessage);
        }
      }

      $firstErroneousField = $('.erroneous:first');
      if ($firstErroneousField.length > 0) {
        $('body').animate({ scrollTop: $firstErroneousField.offset().top - 50 }, 500);
      }
    }

    listGeneralErrors(form, generalErrors);

    $(form).find('.erroneous:first').select();
    //    if (typeof $j.fancybox != 'undefined') {
    //      $j.fancybox.resize(false);
    //    }

    //    if ($(form).closest('#login-box').length > 0) {
    //      TB.autoSizeLoginBox(true);
    //    }
  }

  function onShowCustomResultHandler(form, content) {
    $(form).find('.f-result').html(content).fadeIn('fast');
  }

  function listGeneralErrors(form, generalErrors) {
    var i = 0,
        errorBox = $('<ul></ul>');

    if (generalErrors.length === 0) { return; }

    for (i = 0; i < generalErrors.length; i++) {
      errorBox.append('<li>' + generalErrors[i] + '</li>');
    }

    errorBox = $('<div class="error-box"></div>').html(errorBox);

    $(form).find('.f-result').html(errorBox).fadeIn('fast');
  }

  function onFormSubmittedHandler(form) {
    var $form = $(form);
    $form.find('em.erroneous').remove();
    $form.find('.erroneous').removeClass('erroneous');
  }

  return {
    bindInteractivity: bindInteractivityPrivate
  };
})();

//})(jQuery);

$(function () {
  interactivityHandlers.bindInteractivity();
});
