$(document).ready(function ()
{
    var $f = $('div.app\\/wishlist-form form');
    var f = $f.get(0);

    
    ///////////////////////////////////////////////////////
    // recipient agreement fields
    ///////////////////////////////////////////////////////

    var f_notify_name = $(f.elements['s2[name]']);
    var f_agree_name = $(f.elements['agreement[contact]']);
    f_notify_name.change(function ()
    {
        f_agree_name.val(f_notify_name.val());
    });
    var f_institution_name = $(f.elements['s1[name_of_facility]']);
    var f_agree_institution = $(f.elements['agreement[institution]']);
    f_institution_name.change(function ()
    {
        f_agree_institution.val(f_institution_name.val());
    });

    
    ///////////////////////////////////////////////////////
    // "other" fields
    ///////////////////////////////////////////////////////
    
    var other_names = {
        'field_s4_type_of_org' : {
                'Other (specify)' : 'field_s4_specify_other_type_of_organization',
                '501(c)3 Non-profit Organization (please attach)' : 'field_s4_attach_501c3'
        }
    };
    function check_other_vis(which)
    {
        if (!which.get(0).other_map)
        {
            return;
        }
        var other_map = which.get(0).other_map;
        var cur_value = which.val();
        for (var a_key in other_map)
        {
            if (cur_value != a_key)
            {
                hide_other(other_map[a_key]);
            }
            else
            {
                show_other(other_map[a_key]);
            }
        }
    }
    function show_other(which)
    {
        $('#'+which).closest('div.field').show();
    }
    function hide_other(which)
    {
        $('#'+which).closest('div.field').hide();
    }
    function check_other_vis_event()
    {
        check_other_vis($(this));
    }
    for (var input_id in other_names)
    {
        var other_field = $('#'+input_id);
        var other_id = other_names[input_id];
        if (typeof other_id == 'string')
        {
            other_id = {'Other':other_id};
        }
        other_field.get(0).other_map = other_id;
        
        other_field.click(check_other_vis_event);
        other_field.keypress(check_other_vis_event);
        other_field.change(check_other_vis_event);
        
        check_other_vis(other_field);
    }
});
