var two_container_count = 1;
var proposal_loading = false;

function addButtonActions() {

    $(".click_plus").parent().each(
            function(elem, a2) {

                  var int_container_num = parseInt($(a2).parent().attr("id").replace('to_container_', ''));
                  two_container_count = int_container_num > two_container_count ? int_container_num : two_container_count;

                  if($(a2).parent().next().attr("id") != "") {
                        $(a2).addClass("hidden");
                  } else {
                        $(a2).removeClass("hidden");
                  }
            }
      );

    $(".click_plus").click( reproduce );
    $(".click_minus").click( remove );

  }

function reproduce(useParent, parent) {

    $ = jQuery;
    two_container_count++;

    useParent = (useParent == false) ? false : true;

    if(useParent) {
        var dolly = $(this).parent().parent();
    } else {
        var dolly = parent;
    }

    var input = dolly.clone();
    var new_id = "to_container_" + two_container_count;

    $(input).attr("id", new_id);
    $(input).removeClass('error');

    // den namen des input feldes anpassen
    $(input).children().each(function(a1, a2) {
        if(a2['nodeName'] == 'INPUT') {
            $(a2).attr('name', 'to_' + two_container_count);

            $(a2).val('');
        }
        if(a2['className'] == 'errors') {
            $(a2).remove();
        }

    });

    input.insertAfter(dolly);
    addButtonActions();
    return(new_id);

}

function remove() {

    if($('.to_container').length <= 1) {
      return;
    }

    $ = jQuery;

    $(this).parent().parent().remove();
    //two_container_count--;
    addButtonActions();
}

function addAddress(name, email) {
    var found = false;

    // schauen, ob noch ein leeres feld verfuegbar ist und ob die e-mail-adresse schon mal eingetragen wurde
    $('.to_input').each(
        function(a1, a2) {
            if($(a2).val() == '' || $(a2).val() == email) {
                $(a2).val(email);
                found = true;
            }
    }
    );

    if(found) {
        return;
    }

    var new_id = reproduce(false, $('#to_container_1'));

    $('#' + new_id).children().each(function(a1, a2) {
        if(a2['nodeName'] == 'INPUT') {
            $(a2).attr('id', email);
            $(a2).attr('value', email);
        }
    });
}

function closeContactLightbox() {
    $('.import_contact').each(function(a1, a2) { if($(a2).attr('checked')) { addAddress('', $(a2).val()); }  });
    closeLightbox();
}
