﻿function contact_data_collect(where) {
    $('.result', where).val(
                    $.toJSON(
                        $('.list div', where)
                            .map(function(i, n) {
                                return { "type": $('.type', n).val(),
                                    "number": $('.number', n).val(),
                                    "indoc": $('.indoc > input', n).is(':checked')
                                }
                            }).get()
                    )
                );
}

function contact_control_add(mod, item) {
    var t = $('.template', mod).clone(true).removeClass('template');
    $('input, select', t).change(function() { contact_data_collect($(this).parents('.contact-type')) });
    $('.type', t).val(item.type);
    $('.indoc > input', t).attr('checked', item.indoc);
    $('.number', t).val(item.number);
    $('.list', mod).append(t);
}

function contact_data_load(where) {
    where.each(function(i, w) {
        var obj = $.parseJSON($('.result', w).val());

        $.each(obj, function(i, n) { contact_control_add(w, n); });
    });
}

$(function() {
    $('.isaccount input[type=checkbox]').click(function() { $('tr.isaccount').toggle(); });

    $('.contact-type .add').live('click', function() {
        var mod = $(this).parents('.contact-type');
        contact_control_add(mod, {});
    });

    $('.contact-type .remove').live('click', function() {
        var par = $(this).parents('.contact-type');
        $(this).parents('.contact-item').remove();
        contact_data_collect(par);
    })
});
