function XORClick(field) {
    var activeEl = field.attr('id').replace(/_\d+_\d+$/, '_' + field.attr('value'));
    $('input[type=text],select,textarea', field.parent().parent().parent()).each(function() {
        if ($(this).attr('id') == activeEl) {
            $(this).removeAttr('disabled');
        } else {
            $(this).attr('disabled', 'disabled');
            if (this.selectedIndex) {
                this.selectedIndex = 0;
            }
        }
    });
}

if (!Array.indexOf) {
    Array.prototype.indexOf = function(obj) {
        for (var i=0; i<this.length; i++) {
            if (this[i]==obj) {
                return i;
            }
        }
        return -1;
    }
}

function filterFieldOnChange(field, filtered_field, filter_map) {
    var startIndex = filtered_field.multiple ? 0 : 1;
    var selected = field.selectedIndex;
    if (field.all_options) {
        for (var i = 0; i < field.all_options.length; i++) {
            if (field.all_options[i].value == field.options[selected].value) {
                selected = i + startIndex;
                break;
            }
        }
    }

    if (!filtered_field.all_options) {
        filtered_field.all_options = [];
        for (var i = startIndex; i < filtered_field.options.length; i++) {
            filtered_field.all_options.push(filtered_field.options[i]);
        }
    }
    var selectedFilterIndex = 0;
    var selectedFilterValue = null;
    if (!filtered_field.multiple) {
        selectedFilterValue = filtered_field.options[filtered_field.selectedIndex].value;
    }
    filtered_field.options.length = startIndex;
    if (selected) {
        var visible = filter_map[selected];
        $.each(filtered_field.all_options, function(i, option) {
            if (visible.indexOf(parseInt(option.value)) != -1) {
                filtered_field.options[filtered_field.options.length++] = option;
                if (option.value == selectedFilterValue) {
                    selectedFilterIndex = filtered_field.options.length - 1;
                }
            }
        });
    } else {
        if (filtered_field.className == 'initially-empty') {
            filtered_field.options.length = 1;
            selectedFilterIndex = 0;
        } else {
            $.each(filtered_field.all_options, function(i, option) {
                filtered_field.options[filtered_field.options.length++] = option;
                if (option.value == selectedFilterValue) {
                    selectedFilterIndex = filtered_field.options.length - 1;
                }
            });
        }
    }
    if (!filtered_field.multiple) {
        filtered_field.selectedIndex = selectedFilterIndex;
    }
    $(filtered_field).trigger('change');
};
