jQuery(function ($) {

    var $template_categories_container_hardware = $('.wiaas-template-items_hardware'),
        $template_categories_container_software = $('.wiaas-template-items_software'),
        $template_categories_container_services = $('.wiaas-template-items_services'),
        $template_categories_container_isntallation = $('.wiaas-template-items_installation'),

        $template_categories = $('.wc-bundled-item',
            $template_categories_container_services,
            $template_categories_container_software,
            $template_categories_container_hardware,
            $template_categories_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'),
        template_category_objects = {},
        template_category_add_count = $template_categories.length;



    init_event_handlers();

    function init_event_handlers() {


        $template_search_hardware

            .on('change', function () {
                addSearchedTemplateCategory('hardware', $template_search_hardware, $template_categories_container_hardware)
            });

        $template_search_software

            .on('change', function () {
                addSearchedTemplateCategory('software', $template_search_software, $template_categories_container_software)
            });


        $template_search_installation

            .on('change', function () {
                addSearchedTemplateCategory('installation', $template_search_installation, $template_categories_container_isntallation)
            });


        $template_search_services

            .on('change', function () {
                addSearchedTemplateCategory('services', $template_search_services, $template_categories_container_services)
            });


        function addSearchedTemplateCategory(options, search, container) {
            var template_category_ids = search.val(),
                template_category_id = template_category_ids && template_category_ids.length > 0 ? template_category_ids.shift() : false;

            var template_category_title =search.text();

            if (!template_category_id) {
                return false;
            }

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

            template_category_add_count++;

            var data = {
                action: 'wiaas_add_template_product',
                post_id: woocommerce_admin_meta_boxes.post_id,
                id: template_category_add_count,
                title: template_category_title,
                template_category_id: template_category_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_' + template_category_add_count;

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

                    } 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('');

                });

            }, 250);

            return false;
        }

        $template_categories_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 template_category_objects[el_id];

                e.preventDefault();

            });

        $template_categories_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 template_category_objects[el_id];

                e.preventDefault();

            });

        $template_categories_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 template_category_objects[el_id];

                e.preventDefault();

            });

        $template_categories_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 template_category_objects[el_id];

                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 );
            });
        }
    });
    
});

