var save = [];

//Função que carrega os botões do modal de Adicionar 
function load_fields_ajax(field){
    
    save[field] = true;
    
    $('#field-id_'+field).parent().children().wrapAll('<span id="container-'+field+'"></span>');
    
    $('<button/>')
    .text('Adicionar '+fields_ajax[field][0])
    .insertAfter('#container-'+field)
    .css('margin-top','5px')
    .addClass("btn btn-success btn-sm btn-add-modal")
    .data('field',field);
}

$('body').on('click','.btn-add-modal',function (e) { 
    e.preventDefault();
    fieldBtn = $(this).data('field');
    save[fieldBtn] = true;
    $('#modal-'+fieldBtn).modal('show'); 
});

$(".iframe-add").contents().find('form').bind("keypress", function(e) {
  if (e.keyCode == 13) {               
    e.preventDefault();
    return false;
  }
});

//$('.chosen-select').on('select2:select', function (e) {
$(".chosen-select").on('select2:selecting', function (e) {
  console.log(e);  
})

$(window).on('load',function()
{
    
    $(".iframe-add").contents().find("body").css({"overflow-x":"hidden"});
    $(".iframe-add").contents().find(".form-container").css({"border":"none"});
    $(".iframe-add").contents().find(".table-label").remove(); 
    $(".iframe-add").contents().find("button[type=submit]").parents(".form-group").hide(); 
});

$('.save-iframe').click(function()
{
    field = $(this).data('field');
    iframe = $("#iframe-"+field).contents();
    
    iframe.find('#form-button-save').trigger('click');
    iframe.find('#report-success').bind("DOMSubtreeModified",function(){

        var url = iframe.find('#report-success').find('.go-to-edit-form').attr('href');
        if(url != undefined)
            id = url.split("/").pop(-1);
        else 
            console.log('var url is undefined');
        if(id !== 'undefined' && save[field] === true)
        {
            save[field] = false;
            refresh_chosen(id,field);
            $('#modal-'+field).modal('hide');
        }
    });
})

function refresh_chosen(id,field)
{
    var target = base_url+fields_ajax[field][1];
    var data = {
        id: id,
        field: 'id_'+field
    }
    
    $.ajax(
    {
        url: target,
        dataType: 'json',
        type: 'POST',
        data: data,
        success: function(success)
        {
            if (success.valid == true)
            {
                $('#container-'+field).html(success.html);
				$(".chosen-select").select2({width: '100%',allowClear: true})
            }
            if (success.valid == false)
            {
                return 'error';
            }
            $("#iframe-"+field).contents().find('#report-success').hide();;
        },
        error: function(error)
        {
            return 'error';
        }
    });
}