jQuery(document).ready(function($) {
    if ($('#product-type').val() === 'simple') {
        $('#general_product_data').find('.pricing').show();
    } else {
        $('#general_product_data').find('.pricing').hide();
    }

    $('#general_product_data').find('.pricing').addClass('hide_if_wiaastemplate hide_if_bundle');
    $('#general_product_data').find('.pricing').removeClass('show_if_bundle show_if_wiaastemplate');


    $( '.wiaas-search-documents' ).each(function() {
        var element = $( this );
        var searchTarget = $('#' + element.data('target'));

        element.autocomplete({
            source: function(request, response) {
                $.get( window.ajaxurl, {
                    action: 'wiaas_json_search_documents',
                    query: request.term,
                    _ajax_nonce: element.data('search-nonce')
                } ).done( function( documents ) {
                        response( documents || []);
                    }
                );
            },
            select: function(event, ui) {
                if (!searchTarget || $('#wiaas_attached_document_' + ui.item.id).length) {
                    return;
                }

                $.get(window.ajaxurl, {
                    action: 'wiaas_link_document',
                    _ajax_nonce: element.data('link-nonce'),
                    id: ui.item.id
                }).done( function (document) {
                    searchTarget.find('tbody').append(document);
                });

            }
        })
            .autocomplete( 'instance' )._renderItem = function( ul, item ) {
            return $( '<li role="option" id="wiaas-document-autocomplete-' + item.id + '">' )
                .text( item.name )
                .appendTo( ul );
        };
    });

    $('#wiaas_attached_documents').delegate('.wiaas-remove-attached-document', 'click', function (e) {
        e.preventDefault();

        var id = $(this).data('id');

        $('#wiaas_attached_document_' + id).remove();
    });

});