var bgm_toggle_addremove_to_collection_icon = toggle_addremove_to_collection_icon || '';

if(typeof toggle_addremove_to_collection_icon == 'undefined'){
    function toggle_addremove_to_collection_icon(icon){
        console.log(icon);
    }
}
var bgmSearch = (function($){  
    var fn = {
        addLoading : function (){
            //$('.bgm-ajax-loading').addClass('bgm-loading');
            $('#LoadingBox').show();
            $('#modal_overlay').show();
            $('.error-collection').html('');
        },
        removeLoading : function(){
            //$('.bgm-ajax-loading').removeClass('bgm-loading');
            $('#LoadingBox').hide();
            $('#modal_overlay').hide();
        },
        ajaxUrl : function (task){
            return baseurl_short + 'pages/content.php?content=bgm-call-ajax&task='+task
        },
       
        removeCollection : function(bnt){
            var tr = $(bnt).parents('tr'),
                id = tr.data('id')
            ;
            bgm_post_data.id = id;
            $.confirm({
                title: 'Are you Sure!',
                content: 'When you delete Collection all products will be removed',
                buttons: {
                    confirm: {
                        text: 'OK',
                        btnClass: 'btn-blue',
                        keys: ['enter', 'shift'],
                        action: function(){
                            tr.hide();
                            $.ajax({
                                'type': 'POST',
                                'url' : bgmSearch.ajaxUrl('removecollection'),
                                data: bgm_post_data,
                                success: function(data) {
                                    $('#CollectionMinDiv select[name="collection"] option[value="'+id+'"]').remove();
                                    $('.BrowseBarItem[data-browse-id="C-C:'+id+'"]').remove();
                                }
                            });

                        }
                    },
                    cancel: {
                        text: 'Cancel',
                        btnClass: 'btn-orange'
                    }
                }
            });
        },
        checkCollection : function(select){
            
            var collection_id = select.val();
            if(collection_id && collection_id != 'new'){
                $('.bgm_page_collection_items table tr').removeClass('bgm-collection-selected');
                $('.bgm_page_collection_items table tr[data-id="'+collection_id+'"]').addClass('bgm-collection-selected');
            }
            // check if add new collection
            if(!$('.bgm_page_collection_items table tr[data-id="'+collection_id+'"]').length && collection_id != 'new'){
                var el_id = 'added-' + $.now(),
                    name = select.find('option:selected').text(),
                    href = baseurl_short + 'pages/search.php?search=!collection' + collection_id
                ;
                var html = '<tr id="'+el_id+'" class="bgm-collection-selected" data-id="'+collection_id+'">';
                html += '<td><span class="collection-name">'+name+'</span><span class="collection-edit"><input class="bgm-hidden" value="'+name+'" /></span></td>';
                html += '<td><span class="bgm-total-product">0</span></td>';
                html += '<td><a class="bgm-link-button bgm-button" href="'+href+'" >View</a>';
                html += '<input data-id="'+collection_id+'" onclick="bgmSearch.clickEdit(this);" class="bgm-button" type="button" value="Edit"/>';
                html += '<input data-id="'+collection_id+'" onclick="bgmSearch.removeCollection(this);" class="bgm-button" type="button" value="Delete"/></td>';
                html += '</tr>';
                $('.bgm_page_collection_items table tbody').append(html);
                $('#' + el_id).find('.collection-edit input').focusout(function(){
                    bgmSearch.editCollection($(this));
                });
            }
        },
        clickEdit : function(bnt){
            var tr = $(bnt).parents('tr');
            tr.find('.collection-name').hide();
            tr.find('.collection-edit input').show().focus();
        },
        
        checkboxChecked : function(box){
            var val = $(box).val(),
                product = $('#bgmTickBox5'),
                select = $('#bgmSelectSearch_91')
            ;
            if(product.is(':checked')){
                select.show();
            }else{
                select.hide();
            }
            select.find('select').val('');
        },
        
        typeImageChange : function(select){
            var val = $(select).val(),
                product = $('#bgmTickBox5'),
                checkboxs = $('.bgmsearch-input')
            ;
            if(val){
                checkboxs.prop('checked', false);
                product.prop('checked', true);
            }
        },
        
        editCollection : function(input){
            bgmSearch.addLoading();
            var tr = input.parents('tr'),
                val = input.val(),
                id = tr.data('id')
            ;
            bgm_post_data.id = id;
            bgm_post_data.name = val;
            input.hide();
            if(val){
                tr.find('.collection-name').show().html(val);
                $.ajax({
                    type: 'POST',
                    'url' : bgmSearch.ajaxUrl('editcollection'),
                    data: bgm_post_data,
                    success: function(data) {
                        bgmSearch.removeLoading();
                        $('#CollectionMinDiv select[name="collection"] option[value="'+id+'"]').text(val);
                        $('.BrowseBarItem[data-browse-id="C-C:'+id+'"] a .BrowseBarLink').text(val);
                    }
                });
            }else{
                tr.find('.collection-name').show();
                val = tr.find('.collection-name').text();
                input.val(val);
            }
        },
        submitSearch : function(){
            var codes = $('.bgm-search-area').val(),
                errorCode = $('.bgm-search-code-error'),
                errorType = $('.bgm-search-type-error'),
                collection_id = $('#CollectionMinDiv select[name="collection"]').val(),
                checkboxs = $('.bgmsearch-input'),
                types = []
            ;
            checkboxs.each(function(i, checkbox){
                if($(checkbox).is(':checked')) types[i] = $(checkbox).val();
            });
            bgm_post_data.bgmimage = $('.bgmsearch-select').val();
            bgm_post_data.bgmtype = types;
            bgm_post_data.codes = codes;
            bgm_post_data.collection_id = collection_id;
            errorType.hide();errorCode.hide();
            if(!codes || !types.length){
                if(!codes) errorCode.show();
                if(!types.length) errorType.show();
            }else{
                bgmSearch.addLoading();
                $.ajax({
                    type: 'POST',
                    'url' : bgmSearch.ajaxUrl('bgmSearching'),
                    data: bgm_post_data,
                    success: function(data) {
                        
                        data = $.parseJSON(data);
                        var tr = $('tr[data-id="'+data.collection_id+'"]'),
                            result = $('.bgm-results-ok'),
                            fail = $('.bgm-results-fail'),
                            fHtml = '',
                            html = '',
                            event = {'shiftKey' : true}
                        ;
                        result.find('.results-list').html('');
                        fail.find('.results-list').html('');
                        fail.hide();
                        result.hide();
                        if(data.found.length){
                            //tr.find('.bgm-total-product').html(data.total);
                            html += '<ol>';
                            
                            $(data.found).each(function(i, pp){
                                html += '<li>'+pp.title+'</li>';
                                //bgmSearch.AddResourceToCollection(event, pp.ref, '' , data.collection_id);
                            })
                            html += '</ol>';
                            result.find('.results-list').html(html);
                            result.show();
                        }
                        if(data.notFound.length){
                            fHtml += '<ol>';
                            $(data.notFound).each(function(ii, kk){
                                fHtml += '<li>'+kk+'</li>';
                            })
                            fHtml += '</ol>';
                            fail.find('.results-list').html(fHtml);
                            fail.show();
                        }
                        if(data.download){
                            window.location.href = data.download;
                        }
                        bgmSearch.removeLoading();
                    }
                });
            }
        },
        AddResourceToCollection : function(event,resource,size, collection_id) {

            // Optional params
            if(typeof collection_id === 'undefined') {
                collection_id = '';
            }

            if(event.shiftKey == true) {
                if (typeof prevadded != 'undefined') {
                    lastchecked = jQuery('#check' + prevadded);
                    if (lastchecked.length != 0) {
                        var resource_list = [];
                        addresourceflag = false;
                        jQuery('.checkselect').each(function () {
                            if(jQuery(this).attr("id") == lastchecked.attr("id")) {
                                if(addresourceflag == false) {   
                                    // Set flag to mark start of resources to add
                                    addresourceflag = true;
                                }
                                else { 
                                    // Clear flag to mark end of resources to add
                                    addresourceflag = false;  
                                }
                            }
                            else if(jQuery(this).attr("id") == 'check'+resource) {
                                // Add resource to list before clearing flag
                                resourceid = jQuery(this).attr("id").substring(5)
                                resource_list.push(resourceid);
                                if(addresourceflag == false) {
                                    addresourceflag = true;
                                }
                                else {
                                    addresourceflag = false;
                                }
                            }

                            if(addresourceflag) {
                                // Add resource to list 
                                resourceid = jQuery(this).attr("id").substring(5)
                                resource_list.push(resourceid);
                                jQuery("#ResourceShell" + resourceid).addClass("Selected");
                            }
                        });
                        resource = resource_list.join(",");
                    }
                }
            }
            prevadded = resource;

            thumbs = getCookie("thumbs");
            PopCollection(thumbs);

            searchstring = '';
            if(typeof searchParams !== "undefined")
                {
                searchstring = searchParams.get("search");
                if (searchstring == null)
                    {
                    searchstring = '';
                    }
                }
            post_data = {
                'resource'   : resource,
                'collection' : collection_id,
                'search'     : searchstring
             };

            api("add_resource_to_collection",post_data,function(response) {
                if(typeof response == 'string')
                    {
                    styledalert("", response);
                    UpdateSelColSearchFilterBar();
                    CentralSpaceHideLoading();
                    }
                else
                    {
                    CollectionDivLoad(baseurl_short + 'pages/collections.php?collection='+collection_id);
                    jQuery("#CentralSpace").trigger("resourceremovedfromcollection",[resource_list]);
                    }
            });

            delete prevremoved;
            if(collection_bar_hide_empty){
                CheckHideCollectionBar();
            }
        }
        
    };
    return fn;
})(jQuery);
                        