jQuery(function ($) {

    var $edit_in_cart = $('.bundle_edit_in_cart'),
        $group_mode_select = $('select#_wc_pb_group_mode'),
        $bundled_products_panel = $('#bundled_product_data'),
        $bundled_products_toolbar = $bundled_products_panel.find('.toolbar'),
        $template_products_container_hardware = $('.wiaas-template-items_hardware'),
        $template_products_container_software = $('.wiaas-template-items_software'),
        $template_products_container_services = $('.wiaas-template-items_services'),
        $template_products_container_isntallation = $('.wiaas-template-items_installation'),

        $template_products = $('.wc-bundled-item',
            $template_products_container_services,
            $template_products_container_software,
            $template_products_container_hardware,
            $template_products_container_isntallation),

        $template_search_hardware = $('#wiaastemplate_products_hardware'),
        $template_search_software = $('#wiaastemplate_products_software'),
        $template_search_services = $('#wiaastemplate_products_services'),
        $template_search_installation = $('#wiaastemplate_products_installation'),
        bundled_product_objects = {},
        bundled_products_add_count = $template_products.length,
        block_params = {
            message: null,
            overlayCSS: {
                background: '#fff',
                opacity: 0.6
            }
        };

    $.fn.wc_bundles_select2 = function () {
        $(document.body).trigger('wc-enhanced-select-init');
    };

    // Bundle type move stock msg up.
    $('.bundle_stock_msg').appendTo('._manage_stock_field .description');

    // Simple type options are valid for bundles.
    $('.show_if_simple:not(.hide_if_bundle)').addClass('show_if_bundle');
    
    $('body').on('woocommerce-product-type-change', function (event, select_val) {

        if ('bundle' === select_val) {

            $('.show_if_external').hide();
            $('.show_if_bundle').show();

            $('input#_manage_stock').change();

            $('#_nyp').change();
        }

    });

    $group_mode_select.change(function () {
        if ($.inArray($group_mode_select.val(), wc_bundles_admin_params.group_modes_with_parent) === -1) {
            $edit_in_cart.hide();
        } else {
            $edit_in_cart.show();
        }
    });

    // Downloadable support.
    $('input#_downloadable').change(function () {
        $('select#product-type').change();
    });

    // Trigger product type change.
    $('select#product-type').change();

    // Trigger group mode change.
    $group_mode_select.change();


    init_event_handlers();

    function init_event_handlers() {


        $template_search_hardware

            .on('change', function () {
                addSearchedProduct('hardware', $template_search_hardware, $template_products_container_hardware)
            });

        $template_search_software

            .on('change', function () {
                addSearchedProduct('software', $template_search_software, $template_products_container_software)
            });


        $template_search_installation

            .on('change', function () {
                addSearchedProduct('services', $template_search_installation, $template_products_container_isntallation)
            });


        $template_search_services

            .on('change', function () {
                addSearchedProduct('installation', $template_search_services, $template_products_container_services)
            });


        function addSearchedProduct(options, search, container) {
            var bundled_product_ids = search.val(),
                bundled_product_id = bundled_product_ids && bundled_product_ids.length > 0 ? bundled_product_ids.shift() : false;

            var template_category_title =search.text();

            if (!bundled_product_id) {
                return false;
            }

            search.val([]).change();

            $bundled_products_panel.block(block_params);

            bundled_products_add_count++;

            var data = {
                action: 'wiaas_add_template_product',
                post_id: woocommerce_admin_meta_boxes.post_id,
                id: bundled_products_add_count,
                title: template_category_title,
                product_id: bundled_product_id,
                security: wc_bundles_admin_params.add_bundled_product_nonce,
                options: options,
            };

            setTimeout(function () {

                $.post(woocommerce_admin_meta_boxes.ajax_url, data, function (response) {

                    if ('' !== response.markup) {

                        container.append(response.markup);

                        var $added = $('.wiaas-template-item', container).last(),
                            added_id = 'bundled_item_' + bundled_products_add_count;

                        $added.data('bundled_item_id', added_id);
                        $added.wc_bundles_select2();

                        $bundled_products_panel.trigger('wc-bundles-added-bundled-product');

                    } else if (response.message !== '') {
                        window.alert(response.message);
                    }

                    // Open and close to resolve "sticky" modal issue.
                    if ('yes' === wc_bundles_admin_params.is_wc_version_gte_3_2) {
                        search.selectWoo('open');
                        search.selectWoo('close');
                    } else {
                        search.select2('open');
                        search.select2('close');
                    }
                    search.text('');

                    $bundled_products_panel.unblock();

                });

            }, 250);

            return false;
        }

        $template_products_container_isntallation

        // Remove Item.
            .on('click', 'a.remove_row', function (e) {

                var $el = $(this).closest('.wc-bundled-item'),
                    el_id = $el.data('bundled_item_id');

                $el.find('*').off();
                $el.remove();

                delete bundled_product_objects[el_id];

                $bundled_products_panel.triggerHandler('wc-bundled-products-changed');

                e.preventDefault();

            });

        $template_products_container_hardware

        // Remove Item.
            .on('click', 'a.remove_row', function (e) {

                var $el = $(this).closest('.wc-bundled-item'),
                    el_id = $el.data('bundled_item_id');

                $el.find('*').off();
                $el.remove();

                delete bundled_product_objects[el_id];

                $bundled_products_panel.triggerHandler('wc-bundled-products-changed');

                e.preventDefault();

            });

        $template_products_container_software

        // Remove Item.
            .on('click', 'a.remove_row', function (e) {

                var $el = $(this).closest('.wc-bundled-item'),
                    el_id = $el.data('bundled_item_id');

                $el.find('*').off();
                $el.remove();

                delete bundled_product_objects[el_id];

                $bundled_products_panel.triggerHandler('wc-bundled-products-changed');

                e.preventDefault();

            });

        $template_products_container_services

        // Remove Item.
            .on('click', 'a.remove_row', function (e) {

                var $el = $(this).closest('.wc-bundled-item'),
                    el_id = $el.data('bundled_item_id');

                $el.find('*').off();
                $el.remove();

                delete bundled_product_objects[el_id];

                $bundled_products_panel.triggerHandler('wc-bundled-products-changed');

                e.preventDefault();

            })

    }

    // Ajax product search box
    $( ':input.wiaas-term-search' ).filter( ':not(.enhanced)' ).each( function() {
        var select2_args = {
            allowClear:  $( this ).data( 'allow_clear' ) ? true : false,
            placeholder: $( this ).data( 'placeholder' ),
            minimumInputLength: $( this ).data( 'minimum_input_length' ) ? $( this ).data( 'minimum_input_length' ) : '3',
            escapeMarkup: function( m ) {
                return m;
            },
            ajax: {
                url:         wc_enhanced_select_params.ajax_url,
                dataType:    'json',
                delay:       250,
                data:        function( params ) {
                    return {
                        term:     params.term,
                        action:  'wiaas_template_category_search',
                        security: wc_enhanced_select_params.search_products_nonce,
                        exclude:  $( this ).data( 'exclude' ),
                        include:  $( this ).data( 'include' ),
                        limit:    $( this ).data( 'limit' )
                    };
                },
                processResults: function( data ) {
                    var terms = [];
                    if ( data ) {
                        $.each( data, function( id, text ) {
                            terms.push( { id: id, text: text } );
                        });
                    }
                    return {
                        results: terms
                    };
                },
                cache: true
            }
        };

        // select2_args = $.extend( select2_args, getEnhancedSelectFormatString() );

        $( this ).selectWoo( select2_args ).addClass( 'enhanced' );

        if ( $( this ).data( 'sortable' ) ) {
            var $select = $(this);
            var $list   = $( this ).next( '.select2-container' ).find( 'ul.select2-selection__rendered' );

            $list.sortable({
                placeholder : 'ui-state-highlight select2-selection__choice',
                forcePlaceholderSize: true,
                items       : 'li:not(.select2-search__field)',
                tolerance   : 'pointer',
                stop: function() {
                    $( $list.find( '.select2-selection__choice' ).get().reverse() ).each( function() {
                        var id     = $( this ).data( 'data' ).id;
                        var option = $select.find( 'option[value="' + id + '"]' )[0];
                        $select.prepend( option );
                    } );
                }
            });
            // Keep multiselects ordered alphabetically if they are not sortable.
        } else if ( $( this ).prop( 'multiple' ) ) {
            $( this ).on( 'change', function(){
                var $children = $( this ).children();
                $children.sort(function(a, b){
                    var atext = a.text.toLowerCase();
                    var btext = b.text.toLowerCase();

                    if ( atext > btext ) {
                        return 1;
                    }
                    if ( atext < btext ) {
                        return -1;
                    }
                    return 0;
                });
                $( this ).html( $children );
            });
        }
    });
    
});

