$(document).ready(function(){
    $('.relation-inline input:not([name$=-empty_inline])').live(
        'change', function(){
            $(this).parent().find('input[name$=-empty_inline]').attr(
                'checked', false);
    });
    $('.collapse').click(function(){
        $(this).siblings().toggleClass('closed');
        $(this).toggleClass('contentclosed');
    });
    $('.collapse:gt(0)').each(function(){
        // only auto-collapse if nothing important will be hidden:
        if($(this).parent().find('.errors, .errorlist, .modified').length == 0){
            $(this).trigger('click');
        }
    });

    $('input[name="0-type"]').click(function(){
        var val = $(this).val();

        if (val === 'person'){
            $('input#id_0-given_names, .dob, .gender').show();
            $('input#id_0-family_name').attr('placeholder', 'family name');
        }else{
            $('input#id_0-given_names, .dob, .gender').hide();
            $('input#id_0-family_name').attr('placeholder', 'group name');
        }
    });
    $('.relation-inline div.form').hide();
    $('.relation-inline div.summary').show().append(
        '<a href="#" class="edit">[ edit ]</a>');
    $('.relation-inline a.edit').live('click', function(){
        $(this).parent().parent().find('div.form').show();
        $(this).parent().hide(); // hide summary
        return false;
    });
    $('.relation-inline.empty').append(
        '<a href="#" class="add-another">Add another</a>');
    $('.relation-inline .add-another').live('click', function(){
        $(this).parent().find('div.form').show();
        $(this).parent().find('input[name$=-empty_inline]').attr(
            'checked', false);
        $(this).hide();
        return false;
    });
    // don't hide any errors!
    $('.relation-inline div.form').each(function(){
        if($(this).find('.errorlist').length > 0){
            $(this).show();
            $(this).find('.add-another').hide();
        }
    });
});

