(function($) {
    "use strict";
    /* Navigation */
    $('#exporo').on('click','.exporo-nav',function(){
        var target = $(this).data('target');
        var wrapper = $('#exporo-tabs');
        wrapper.find('> .exporo-tab').removeClass('active');
        $(target).addClass('active');
    });
    
    /* Data Table */
    DataTable.type('num', 'className', 'dt-left');
    var columnCount = $('#exporo-table > thead > tr > th').length;
    var table = $('#exporo-table').DataTable( {
        columnControl: ['order', 'searchDropdown'],
        ordering: {
            indicators: false,
            handler: false
        },
        pageLength: parseInt(exporoParams.rows),
        order: false,
        layout: {
            topStart: {
                buttons: [
                    'pageLength',
                    {
                        text: exporoParams.selectall,
                        action: function () {
                            table.rows().select();
                        }
                    },
                    {
                        text: exporoParams.selectnone,
                        action: function () {
                            table.rows().deselect();
                        }
                    }
                ],
            },
            topEnd: {
                search: {
                    placeholder: exporoParams.searchhere
                }
            },
            bottomStart: 'info',
            bottomEnd: 'paging'
        },
        responsive: true,
        select: {
            style: 'multi'
        },
        columnDefs: [
            {
                targets: columnCount - 1,
                render: DataTable.render.datetime('MMM D, YYYY')
            }
        ]
    } );

    /* Data Table Events */

    table.on('select', function () {
        var btn = $('#exporo-submit');
        var nextBtn = $('#exporo-next');
        var multi = $('#exporo-settings').find('.multi-only');
        var count = table.rows( { selected: true } ).data().length;
        $('#exporo-export-count').html(count);
        if (count > 0) {
            btn.prop('disabled', false);
            nextBtn.prop('disabled', false);
        } else {
            btn.prop('disabled', true);
            nextBtn.prop('disabled', true);
        }
        if (count === 0 || count === 1) {
            multi.hide();
        } else {
            multi.show();
        }
    });

    table.on('deselect', function () {
        var btn = $('#exporo-submit');
        var nextBtn = $('#exporo-next');
        var multi = $('#exporo-settings').find('.multi-only');
        var count = table.rows( { selected: true } ).data().length;
        $('#exporo-export-count').html(count);
        if (count > 0) {
            btn.prop('disabled', false);
            nextBtn.prop('disabled', false);
        } else {
            btn.prop('disabled', true);
            nextBtn.prop('disabled', true);
        }
        if (count === 0 || count === 1) {
            multi.hide();
        } else {
            multi.show();
        }
    });

    /* Submit Button */
    $('#exporo-submit').on('click', function (e) {
        var btn = $(this);
        btn.prop('disabled', true);
        var array = [];
        var products = table.rows( { selected: true } ).data();
        $.each(products, function(index, value) {
            array.push(parseInt(value[0]));
        });
        var jsonString = JSON.stringify(array);
        var title = $('#exporo-title').val();
        var subject = $('#exporo-subject').val();
        var author = $('#exporo-author').val();
        var creator = $('#exporo-creator').val();
        var keywords = $('#exporo-keywords').val();
        var org = $('#exporo').find('input[name="exporo-org"]:checked').val();
        var bookmarks = $('#exporo').find('input[name="exporo-bookmarks"]:checked').val();
        var toc = $('#exporo').find('input[name="exporo-toc"]:checked').val();
        var layout = $('#exporo').find('input[name="exporo-layout"]:checked').val();
        var cover = $('#exporo-image-url').val();
        var data = {
            'action': 'exporoIds',
            'nonce': exporoParams.nonce,
            'data': jsonString,
            'title': title,
            'subject': subject,
            'author': author,
            'creator': creator,
            'keywords': keywords,
            'cover': cover,
            'bookmarks': bookmarks,
            'toc': toc,
            'org': org,
            'layout': layout,
        };
        $.ajax({
            url : exporoParams.ajaxurl,
            data : data,
            type : 'POST',
            success: function(data){
                if (data == 'error') {
                    alert(exporoParams.wrong);
                } else {
                    document.getElementById('jsArrayInput').value = data;
                    $('#exporo-form').submit();
                }
            },
            error: function(jqXHR,error, errorThrown) {
                alert(error + ': ' + errorThrown);
                btn.prop('disabled', false);
            }
        }).done(function() {
            btn.prop('disabled', false);
        });
    });

    /* Notice Dismiss Button */
    $('#exporo').on('click', '.notice-dismiss', function() {
        $(this).closest('.notice').fadeTo(100, 0, function() {
            $(this).slideUp(100, function() {
                $(this).remove();
            });
        });
    });

    /* Media Upload Button */
    $(document).ready(function($){
        var mediaUploader;
        $('#exporo-upload-button').click(function(e) {
            e.preventDefault();
            if (mediaUploader) {
                mediaUploader.open();
                return;
            }
            mediaUploader = wp.media({
                title: exporoParams.chooseImage,
                button: {
                    text: exporoParams.useImage
                },
                multiple: false 
            });
            mediaUploader.on('select', function() {
                var attachment = mediaUploader.state().get('selection').first().toJSON();
                $('#exporo-image-url').val(attachment.url);
            });
            mediaUploader.open();
        });
    });
})(jQuery);