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