$(document).ready(function() {
    var Mailbox = function () {

        var content = $('.inbox-content');
        var loading = $('.inbox-body');
        var mailboxTemplate = $('#tableMailbox tbody');
        var messageTemplate = $('#messageView');
        var mailboxTable = $('.table-mailbox').clone();
        var listListing = 'inbox';
        var storage = {};

        var loadMails = function ( el, name, page, cb ) {
            listListing = name || 'inbox';
            var title = $('.inbox-nav > li.' + name + ' a').attr('data-title');

            toggleButton(el);

            App.ajax({
                type: 'POST',
                url: ajaxUrl_getMessages,
                data: {
                    c: name,
                    page: page || 1
                },
                dataType: 'json',
                block: true,
                blockTarget: loading
            }, function ( result ) {
                var mailboxTableRow = mailboxTemplate.html(),
                    newRow,
                    mailboxTableBody = mailboxTable.find('tbody'),
                    data = result.data.messages, i, item, l = data.length, ik;

                mailboxTableBody.empty();

                if( l ) {

                    for( i = 0; i < l; i++ ) {
                      item = data[ i ];
                      newRow = mailboxTableRow;

                      for( ik in item ) {
                        if( ik === 'starred' ) {
                            newRow = App.replaceAll( newRow, '%' + ik + '%', item[ ik ], '%starred%', function(){
                                if( item[ ik ] ) {
                                    return '';
                                } else {
                                    return '-o';
                                }
                            } );
                        } else {
                            newRow = App.replaceAll( newRow, '%' + ik + '%', item[ ik ] );
                        }
                      }

                      mailboxTableBody.append( newRow );
                    }

                    content.html(mailboxTable);

                } else content.html('<div class="text-center"><h4>' + getTranslate('no_mails') + '</h4></div>');

                storage.paginator = result.paginator;

                refreshCounters( result.data.counters );

                Mailbox.paginator.update({
                  totalPages: result.paginator.totalPages,
                  startPage: result.paginator.currentPage
                });

                $('span.pagination-info').html( 
                    (( result.paginator.currentPage === 1 )
                        ? '1-' + (( result.paginator.all < result.paginator.perPage ) ? result.paginator.all : result.paginator.perPage)
                        : (result.paginator.currentPage * result.paginator.perPage - result.paginator.perPage ) + '-' + result.paginator.currentPage * result.paginator.perPage 
                    ) + ' of ' + result.paginator.all);

                toggleButton(el);

                $('.inbox-nav > li.active').removeClass('active');
                $('.inbox-nav > li.' + name).addClass('active');
                $('.inbox-header > h1').text(title);

                if (Layout.fixContentHeight) Layout.fixContentHeight();

                var test = mailboxTableBody.find("input.mail-checkbox");
                if (test.size() > 0) {
                    test.each(function() {
                        if ($(this).parents(".checker").size() === 0) {
                            $(this).show();
                            $(this).uniform();
                        }
                    });
                }

                if( cb ) cb();


            }, function() {
                toggleButton(el);
            });
        };

        var refreshCounters = function( counters ) {
            $('.inbox-nav > li:not(.divider)').each(function(item){
                var a = $(this).children('a'),
                    b = a.children('span'),
                    c = a.data('category');

                if( counters[c] ) {
                    b.removeClass('hidden').html(counters[c])
                } else {
                    if( !b.hasClass('hidden') ) {
                        b.addClass('hidden').html(0);
                    }
                }
            });
        };

        var loadMessage = function (el, name, resetMenu) {
            var url = ajaxUrl_viewMessage,
                id = el.parent('tr').data('messageid');

            toggleButton(el);

            App.ajax({
                type: 'POST',
                url: url,
                data: {
                    id: id
                },
                dataType: 'json',
                block: true,
                blockTarget: loading
            }, function ( result ) {
                var messageView = messageTemplate.html(), messageContent,
                    message = result.data.message, ik;

                //console.log(message);

                //console.log($('#message-view-delete').attr('data-messageid'));



                //console.log($('#message-view-delete').attr('data-messageid'));//.attr('data-messageid', result.data.message.id);



                toggleButton(el);

                if (resetMenu) {
                    $('.inbox-nav > li.active').removeClass('active');
                }
                $('.inbox-header > h1').text(getTranslate('view_message'));

                messageContent = messageView;

                for( ik in message ) {
                    messageContent = App.replaceAll( messageContent, '%' + ik + '%', message[ ik ] );
                }

                content.html( messageContent );

                refreshCounters( result.data.counters );


               if (Layout.fixContentHeight) {
                    Layout.fixContentHeight();
                }
                App.initUniform();

                $('#message-view-trash').attr('data-messageid', message.id);
                $('#message-view-delete').attr('data-messageid', message.id);

            });
        }

        var setImportant = function(el) {
            var url = ajaxUrl_setImportant,
                id = el.parent('tr').data('messageid'),
                icon = el.children('i');
                var ids = [];
                ids.push(id);

            App.ajax({
                type: 'POST',
                url: url,
                data: {
                    ids: ids
                },
                dataType: 'json',
                block: true,
                blockTarget: loading
            }, function ( result ) {
                var data = result.data.status;

                if( data == 0 ) {
                    icon.removeClass('fa-star').addClass('fa-star-o');
                } else {
                    icon.removeClass('fa-star-o').addClass('fa-star');
                }

                refreshCounters( result.data.counters );
                reloadAfterChange();
            });
        }

        var markSelected = function() {
            var set = $('.table-mailbox tbody .mail-checkbox');
            var ids = [];
            set.each(function () {
                if ($(this).prop('checked') === true) {
                    ids.push($(this).parents('tr').attr('data-messageid'));
                }
            });

            var url = ajaxUrl_setImportant;

            App.ajax({
                type: 'POST',
                url: url,
                data: {
                    ids : ids
                },
                dataType: 'json',
                block: true,
                blockTarget: loading
            }, function ( result ) {
                var data = result.data.status;

                if( data == 0 ) {
                    set.each(function () {
                        if ($(this).prop('checked') === true) {
                            $(this).parents('tr').find('i:first').removeClass('fa-star').addClass('fa-star-o');
                        }
                    });
                }
                else {
                    set.each(function () {
                        if ($(this).prop('checked') === true) {
                            $(this).parents('tr').find('i:first').removeClass('fa-star-o').addClass('fa-star');
                        }
                    });
                }

                refreshCounters( result.data.counters );
                reloadAfterChange();
            });
        }

        var trashSelected = function() {
            var set = $('.table-mailbox tbody .mail-checkbox');
            var ids = [];
            set.each(function () {
                if ($(this).prop('checked') === true) {
                    ids.push($(this).parents('tr').attr('data-messageid'));
                }
            });
            //console.log(ids);

            var url = ajaxUrl_trashMessage;

            App.ajax({
                type: 'POST',
                url: url,
                data: {
                    ids : ids
                },
                dataType: 'json',
                block: true,
                blockTarget: loading
            }, function ( result ) {
                var data = result.data.status;

                refreshCounters( result.data.counters );
                reloadAfterChange();
            });
        }

        var deleteSelected = function() {
            var set = $('.table-mailbox tbody .mail-checkbox');
            var ids = [];
            set.each(function () {
                if ($(this).prop('checked') === true) {
                    ids.push($(this).parents('tr').attr('data-messageid'));
                }
            });
            //console.log(ids);

            var url = ajaxUrl_trashMessage;

            App.ajax({
                type: 'POST',
                url: url,
                data: {
                    ids : ids
                },
                dataType: 'json',
                block: true,
                blockTarget: loading
            }, function ( result ) {
                var data = result.data.status;

                refreshCounters( result.data.counters );
                reloadAfterChange();
            });
        }

        var reloadAfterChange = function(){
            if($('li.inbox').hasClass('active')){
                $('a[data-category=inbox]').click();
            }
            else if($('li.important').hasClass('active')){
                $('a[data-category=important]').click();
            }
            else if($('li.trash').hasClass('active')){
                $('a[data-category=trash]').click();
            }
            else if($('li.promotion').hasClass('active')){
                $('a[data-category=promotion]').click();
            }
        }

        var toggleButton = function(el) {
            if (typeof el == undefined) {
                return;
            }
            if (el.attr("disabled")) {
                el.attr("disabled", false);
            } else {
                el.attr("disabled", true);
            }
        }

        return {
            paginator: App.paginator,
            //main function to initiate the module
            init: function () {

                // handle view message
                $('.inbox-content').on('click', '.view-message', function () {
                    loadMessage($(this));
                });

                $('.inbox-content').on('click', 'td.important', function () {
                    setImportant($(this));
                });

                $('.inbox-content').on('click', 'a#mark-selected', function () {
                    markSelected();
                });

                $('.inbox-content').on('click', 'a#trash-selected', function () {
                    trashSelected();
                });

                $('.inbox-content').on('click', 'a#delete-selected', function () {
                    deleteSelected();
                });

                $('.inbox-content').on('click', 'button#message-view-trash', function () {
                    //console.log($(this).attr('data-messageid'));
                    var url = ajaxUrl_trashMessage;
                    var id = $(this).attr('data-messageid');
                    var ids = [];
                    ids.push(id);
                    //console.log(url);
                    //console.log(id);
                    App.ajax({
                        type: 'POST',
                        url: url,
                        data: {
                            ids: ids
                        },
                        dataType: 'json',
                        block: true,
                        blockTarget: loading
                    }, function ( result ) {
                        refreshCounters( result.data.counters );
                        reloadAfterChange();
                    });

                });

                $('.inbox-content').on('click', 'button#message-view-delete', function () {
                    //console.log($(this).attr('data-messageid'));
                    var url = ajaxUrl_deleteMessage;
                    var id = $(this).attr('data-messageid');
                    var ids = [];
                    ids.push(id);
                    //console.log(url);
                    //console.log(id);
                    App.ajax({
                        type: 'POST',
                        url: url,
                        data: {
                            ids: ids
                        },
                        dataType: 'json',
                        block: true,
                        blockTarget: loading
                    }, function ( result ) {
                        refreshCounters( result.data.counters );
                        reloadAfterChange();
                    });

                });

                // handle inbox listing
                $('.inbox-nav > li.inbox > a').click(function () {
                    loadMails($(this), 'inbox');
                });

                $('.inbox-nav > li.important > a').click(function () {
                    loadMails($(this), 'important');
                });

                // handle trash listing
                $('.inbox-nav > li.trash > a').click(function () {
                    loadMails($(this), 'trash');
                });

                $('.inbox-nav > li.promotions > a').click(function () {
                    loadMails($(this), 'promotions');
                });

                Mailbox.paginator = new Mailbox.paginator( '#mailboxPaginator', {
                    onlyArrows: true,
                    prev: '<i class="fa fa-angle-left"></i>',
                    next: '<i class="fa fa-angle-right"></i>',
                    nextClass: 'btn btn-sm blue btn-outline',
                    prevClass: 'btn btn-sm blue btn-outline',
                    itemContainer: '<a></a>',
                    itemContent: false,
                    container: false,
                    totalPages: 2,
                    dynamic: true,
                    onPageClick: function ( page, next ) {
                      loadMails( $(this), listListing, page, next );
                    }
                });

                //$('.inbox-nav > li.inbox > a').trigger('click');
                loadMails($(this), 'inbox');


                // handle group checkbox:
                content.on('change', 'table thead .mail-group-checkbox', function () {
                    console.log('asdsadsadsadasd');

                    var checked_status = $(this).prop('checked');

                    var set = $('.table-mailbox tbody .mail-checkbox');

                    var checked = $(this).is(":checked");
                    set.each(function () {
                        //$(this).attr("checked", checked);

                        if(checked_status === true){
                            if($(this).prop('checked') !== true) {
                                $(this).click();
                            }
                        }
                        else{
                            if($(this).prop('checked') === true) {
                                $(this).click();
                            }
                        }
                    });
                    $.uniform.update(set);
                });
            }

        };

    }();
    
    Mailbox.init();
});