(function($){

    defaults = {
        field_selector: 'tr'
    ,   error_selector: 'td'
    ,   error_class: 'error'
    ,   exclude_id: null
    ,   email_dup_error: null
    };

    $.fn.checkEmailIsUnique = function(options) {
        var options = $.extend({},
            defaults,
            options
        );

        function do_check() {
            var fc = $(this).closest(options.field_selector)
            ,   td = $(this).closest(options.error_selector)
            ;

            fc.find(".live-error").remove();
            fc.find("span").each(function(){
                if ($(this).attr('style') === 'color:red') {
                    $(this).remove();
                }
            });
            td.css('background-color', null);
            var data = {
                email: $(this).val()
            };
            if (options.exclude_id) {
                data.exclude_id = options.exclude_id;
            }
            if (options.email_dup_error) {
                data.email_dup_error = options.email_dup_error;
            }
            $.getJSON('/members/application/ajax/check_email/', data, function(resp){
                if (resp.status == "error") {
                    fc.addClass(options.error_class);
                    td.append($("<span class=live-error />").html(resp.error));
                } else {
                    fc.removeClass(options.error_class);
                }
            });
        }

        $(this).change(do_check);

        var timeout_to_check;
        $(this).keyup(function(){
            var field = this;
            window.clearTimeout(timeout_to_check);
            timeout_to_check = window.setTimeout(function() {
                do_check.call(field);
            }, 1000);
        });

        if ($(this).val() != "") {
            $(this).trigger('change');
        }
    }

})(jQuery);

