$(function()
{
    $('#dashboard .panel').addClass('panel-block');

    $('#dashboard .icon-repeat').click(function()
    {
        $(this).parents('.panel-block').each(function(){refreshBlock($(this))});
    });
    
    /**
     * refresh index block
     * @access public
     * @return void
     */
    var refreshTimer = 1000 * 60 * 5;
    setInterval(function ()
    {
        initDashboard();
    }, refreshTimer);

    initDashboard();
})
$(function()
{
    var sortMessager = new $.zui.Messager({close: false});
    $('#dashboard').sortable(
    {
        selector: '.panel',
        trigger: '.panel-heading,.panel-move-handler',
        containerSelector: '.col-main,.col-side',
        canMoveHere: function($ele, $target)
        {
            var fixedCol = $ele.data('fixed');
            if(fixedCol)
            {
                var $targetCol = $target.closest('.col-main,.col-side');
                var targetCol = $targetCol.hasClass('col-main') ? 'main' : 'side';
                if(targetCol !== fixedCol)
                {
                    !sortMessager.isShow && sortMessager.show(fixedCol === 'main' ? v.cannotPlaceInRight : v.cannotPlaceLeft);
                    return false;
                }
                else
                {
                    sortMessager.isShow && sortMessager.hide();
                }
                return true;
            }
        },
        start: function()
        {
            $('body').css('overflow', 'hidden');
        },
        finish: function(e)
        {
            $('body').css('overflow', 'auto');
            var newOrders = [''];
            var isSideCol = e.element.parent().is('.col-side');
            e.list.each(function(index, data)
            {
                newOrders.push(data.item.data('blockid'));
            });
            sortBlocks(newOrders, function()
            {
                resizeBlock(e.element.data('blockid'), isSideCol ? 4 : 8);
            });

            e.element.toggleClass('block-sm', isSideCol);
        },
        always: function(){sortMessager.isShow && sortMessager.hide();}
    });

    $(window).on('resize', function(){initTableHeader();});

    initDashboard();

  $(document).off('click', 'tr[data-url]');
  $(document).on('click', 'tr[data-url]', function()
  {
      return openEntry($(this));
  });
});

/**
 * Init dashboard
 *
 * @access public
 * @return void
 */
function initDashboard()
{
    loadAllBlocks();
    initTableHeader();
}

/**
 * Load all blocks in dashboard
 * @access public
 * @return void
 */
function loadAllBlocks()
{
    $('#dashboard').find('.panel-block').each(function(){refreshBlock($(this))});
}

/**
 * reload dashboard
 *
 * @access public
 * @return void
 */
function reloadDashboard()
{
    $('#dashboard').load(createLink(config.appName + '.' + config.currentModule, config.currentMethod) + ' #dashboard>.row', function()
    {
        initDashboard();
        $.zui.closeModal();
    });
}

/**
 * Reset block.
 *
 * @param  string    $appName
 * @access public
 * @return void
 */
function resetBlock(appName)
{
    bootbox.confirm(v.confirmReset, function(result)
    {
        if (result)
        {
            $.getJSON(createLink('sys.block', 'reset', 'appName=' + appName), function(data)
            {
                if(data.result != 'success')
                {
                    bootbox.alert(data.message);
                    return false;
                }
                else
                {
                    return location.reload();
                }
            });
        }
    });
}
/**
 * Delete block.
 *
 * @param  int    $id
 * @access public
 * @return void
 */
function deleteBlock(id)
{
    var $block = $('#block' + id);
    bootbox.confirm(config.confirmRemoveBlock.format($block.data('name')), function(result)
    {
        if (result)
        {
            $.getJSON(createLink('block', 'delete', 'id=' + id), function(data)
            {
                if(data.result != 'success')
                {
                    bootbox.alert(data.message);
                    return false;
                }
                else
                {
                    $block.remove();
                }
            });
        }
    });
}

/**
 * Refresh block.
 *
 * @param  $panel
 * @param  afterRefresh
 * @access public
 * @return void
 */
function refreshBlock($panel, afterRefresh)
{
    if(typeof $panel === 'string' || typeof $panel === 'number') $panel = $('#block' + $panel);
    $panel.addClass('load-indicator loading');
    $.ajax({url: $panel.data('url'), dataType: 'html'}).done(function(data)
    {
        var $data = $(data);
        if($data.hasClass('panel')) $panel.empty().append($data.children());
        else
        {
            $panel.children('.panel-move-handler,style,script,.table-header-fixed').remove();
            $panel.find('.panel-body,.empty-tip').replaceWith($data);
        }
        if($.isFunction(afterRefresh))
        {
            afterRefresh.call(this,
            {
                result: true,
                data: data,
                $panel: $panel
            });
        }
        if($.fn.sortTable)
        {
            $panel.find('.tablesorter:not(.table-header-fixed-shadow)').sortTable();
        }
        initTableHeader($panel);
        $.zui.initPage($panel);

        var $entryLoginRequest = $panel.find('.block-entry-login');
        if($entryLoginRequest.length)
        {
            if(!window.entryLoginRequests)
            {
                window.entryLoginRequests = {};
            }
            var entryLoginUrl = $entryLoginRequest.data('url');
            if(!window.entryLoginRequests[entryLoginUrl])
            {
                window.entryLoginRequests[entryLoginUrl] = 1;
                $panel.append('<iframe sandbox="allow-same-origin allow-scripts allow-popups allow-forms allow-pointer-lock" src="' + entryLoginUrl + '" class="hidden" />');
            }
        }
    }).fail(function()
    {
        $panel.addClass('panel-error');
        if($.isFunction(afterRefresh))
        {
            afterRefresh.call(this,
            {
                result: false,
                $panel: $panel
            });
        }
    }).always(function()
    {
        $panel.removeClass('load-indicator loading');
    });
}

/**
 * Init table header
 * @access public
 * @return void
 */
function initTableHeader($wrapper)
{
    ($wrapper || $('#dashboard')).find('.panel-body > table.table-fixed-head').each(function()
    {
        var $table = $(this);
        var $tabPane = $table.closest('.tab-pane');
        if ($tabPane.length && !$tabPane.hasClass('active'))
        {
            $('[data-tab][href="#' + $tabPane.attr('id') + '"]').one('shown.zui.tab', function()
            {
                initTableHeader($tabPane);
            });
            return;
        }

        var $panel = $tabPane.length ? $tabPane : $table.closest('.panel');

        if(!$table.length || !$table.children('thead').length || ($panel.find('#assigntomeBlock').length && $panel.find('#assigntomeBlock > div').length > 1)) return;
        var isFixed = $panel.find('.panel-body').height() < $table.outerHeight();

        $panel.toggleClass('with-fixed-header', isFixed);
        var $header = $panel.children('.table-header-fixed').toggle(isFixed);
        if(!isFixed)
        {
            $table.find('thead').css('visibility', 'visible');
            return;
        }
        var tableWidth = $table.width();
        var $oldTableHead = $table.find('thead');
        var updateTh = function()
        {
            $header.find('thead').empty().append($oldTableHead.find('tr').clone());
        };
        if(!$header.length)
        {
            $header = $('<div class="table-header-fixed" style="position: absolute; left: 10px; top: 0; right: 0; padding: 0 10px 0 0; background: #fff;"><table class="table table-fixed no-margin table-header-fixed-shadow"></table></div>').css('right', $panel.width() - tableWidth - 20);
            $oldTableHead.find('th').each(function(idx)
            {
                $(this).attr('data-idx', idx);
            });
            $header.find('.table').addClass($table.attr('class')).append($oldTableHead.css('visibility', 'hidden').clone().css('visibility', 'visible'));
            $panel.addClass('with-fixed-header').append($header);
            var $heading = $panel.children('.panel-heading');
            if($heading.length) $header.css('top', $heading.outerHeight() - 10);
            if($table.hasClass('tablesorter'))
            {
                $header.on('mousedown mouseup', 'th[data-idx]', function(e)
                {
                    var $th = $(this);
                    $oldTableHead.find('th[data-idx="' + $th.data('idx') + '"]').trigger(e);
                    if(e.type === 'mouseup')
                    {
                        setTimeout(updateTh, 10);
                        setTimeout(updateTh, 200);
                    }
                });
            }
        }
        else
        {
            updateTh();
        }

        var timeoutCall = null;
        $table.parent().off('scroll.initTableHeader').on('scroll.initTableHeader', function()
        {
            clearTimeout(timeoutCall);
            var $tableContainer = $(this);
            timeoutCall = setTimeout(function() {
                $panel.toggleClass('table-scrolled', $tableContainer.scrollTop() > 0);
            }, 200);
        });
    });
}

/**
 * Check refresh progress
 * @param  object $dashboard
 * @access public
 * @return void
 */
function checkRefreshProgress($dashboard, doneCallback)
{
    if($dashboard.find('.panel-loading').length) setTimeout(function() {checkRefreshProgress($dashboard, doneCallback);}, 500);
    else doneCallback();
}

/**
 * Sort blocks.
 *
 * @param  array $orders  format is {'blockid' : 1, 'block1' : 2}
 * @param  function $callback
 * @access public
 * @return void
 */
function sortBlocks(newOrders, callback)
{
    $.getJSON(createLink('block', 'sort', 'orders=' + newOrders.join(',')),  function(data)
    {
        if(data.result != 'success') return false;
        if(callback) callback(newOrders);
    });
}

/**
 * Resize block
 * @param  string $blockId
 * @param  function $callback
 * @access public
 * @return void
 */
function resizeBlock(id, width, callback)
{
    $.getJSON(createLink('block', 'resize', 'id=' + id + '&type=horizontal&data=' + width), function(data)
    {
        callback && callback();
        refreshBlock($('#dashboard .panel-block[data-blockid="' + id + '"]'));
    });
}
