window.highlightTest = [];

/**
 * Update analysis method
 * @param {string} methodID   Method ID
 * @param {string} analysisID AnalysisID ID
 */
function updateAnalysisMethod(methodID, analysisID)
{
    $.getJSON(createLink('analysis', 'ajaxGetMethodResult', 'methodID=' + methodID), function(data)
    {
        if(data && data.result === 'success' && data.data)
        {
            var id = 'analysisMethod' + methodID;
            if(!analysisID) analysisID = $('#' + id).closest('.tab-pane').attr('id').replace('tab-', '');

            var $tabPane = $('#tab-' + analysisID);
            var $rightMenu = $tabPane.find('.analysis-right-menu');
            if($rightMenu.length)
            {
                $rightMenu.remove();
                $tabPane.removeClass('no-analysis-method');
            }
            var tml       = $('#analysisMethodTpl').html();
            var $panel    = $($.zui.formatString(tml, data.data)).attr('id', id);
            var $methods  = $tabPane.find('.analysis-methods');
            var $oldPanel = $methods.find('#' + id);
            if($oldPanel.length)
            {
                $oldPanel.replaceWith($panel);
            }
            else
            {
                $panel.appendTo($methods);
                $.zui.asap(function(){$panel[0].scrollIntoView()}, 200);
            }
            $panel.find('a.iframe,.export').initIframeModal();
            $('#mainRow .side-bar-view').removeClass('hidden');

            removeHightlightTest();

            var $highlightBtn = $panel.find('.highlight-points').first();
            if($highlightBtn.length) highlightTestPoints($highlightBtn);
        }
        else if(data && data.message)
        {
            $.zui.messager.danger(data.message);
        }
    });
}

/**
 * Highlight test points.
 *
 * @param  object    $btn
 * @access public
 * @return void
 */
function highlightTestPoints($btn)
{
    var points = $btn.data('points');
    points = points.split(';');
    window.highlightTest = points;
    $btn.addClass('highlight-active');
    updateDTable();
}

/**
 * Update data table.
 *
 * @access public
 * @return void
 */
function updateDTable()
{
    var $dtable = $('.dataframe');
    var dtable = $dtable.data('zui.dtable');
    dtable.render();

    if(window.highlightTest?.length > 0)
    {
        var [col, row] = window.highlightTest[0].split(',');
        dtable.$.scrollTo({row: row, col: col});
    }
}

/**
 * Remove highlight test points.
 *
 * @access public
 * @return void
 */
function removeHightlightTest()
{
    window.highlightTest = [];
    $('.highlight-points').removeClass('highlight-active');
    updateDTable();
}

/**
 * Rename analysis method
 * @param {string} methodID
 * @param {string} name
 */
function renameAnalysisMethod(methodID, name)
{
    $('#analysisMethod' + methodID + ' .analysis-method-heading').text(name);
}

/* Rename analysis */
function renameAnalysis(analysisID, name)
{
    $('#tabs .tab-nav-item[data-id="' + analysisID + '"]>a>span').text(name);
    $('#tabs .tab-nav-item[data-id="' + analysisID + '"]>a').attr('title', name);
    $('#tabs .tab-nav-item[data-id="' + analysisID + '"]>a').attr('stashName', name);
}

/** Request to delete analysis */
function requestDeleteAnaysis(id, event)
{
    bootbox.confirm(confirmDeleteAnalysisText, function(result)
    {
        if(!result) return;
        $.getJSON(createLink('analysis', 'delete', 'analysisID=' + id + '&projectID=' + projectID + '&confirm=yes'), function(data)
        {
            if(data && data.result === 'success')
            {
                $('#tabs').data('zui.tabs').close(id, true);
                $.getJSON(createLink('analysis', 'ajaxGetAnalysisList', 'analysisID=' + analysisID), function(data)
                {
                    window.analysisList = data.data;
                    initTabs();
                });

            }
        });
    })

    event.preventDefault();
}

/* Rename Title */
function renameTitle(id)
{
    var methodID = $('input#' + id).prev().attr('data-methodID');
    var title    = $('input#' + id).val();
    var data     = {'methodID': methodID, 'id': id, 'title': title};
    $.post(createLink('analysis', 'ajaxRenameTitle'), data,  function(data)
    {
        updateAnalysisMethod(methodID);
    });
}

/** Request rename analysis */
function requestRenameAnaysis(id, event)
{
    $.zui.modalTrigger.show(
    {
        type:  'iframe',
        url:   createLink('analysis', 'rename', 'analysisID=' + id),
        width: 650
    });
    event.preventDefault();
}

/** Open analysis in tabs */
function openAnalysis(analysisID, name)
{
    var tabs = $('#tabs').data('zui.tabs');
    tabs.open({title: name, id: analysisID, ajax: createLink('project', 'ajaxgetanalysis', 'analysisID=' + analysisID), forbidClose: true})
    $.getJSON(createLink('analysis', 'ajaxGetAnalysisList', 'analysisID=' + analysisID), function(data)
    {
        window.analysisList = data.data;
        initTabs();
    });
}

/**
 * Check analysis method
 */
function checkAnalysisMethod(id)
{
    var $tab = $('#tab-' + (id || analysisID));
    var $analysisMethods = $tab.find('.analysis-methods');
    if(!$analysisMethods.length || $analysisMethods.children('.analysis-method-panel').length || $tab.find('.analysis-right-menu').length) return $tab.removeClass('no-analysis-method');

    var $menu = $('<div class="analysis-right-menu"></div>').append($('#analysisMenu').html());
    $menu.prepend($('<div class="title"></div>').text($('#analysisMenu').prev('.btn').text()));
    $analysisMethods.append($menu).find('.iframe').initIframeModal();
    $tab.addClass('no-analysis-method');
    $('#mainRow .side-bar-view').addClass('hidden');
}

/* Update dataframe in datagrid */
function updateDataframe(id, dataframe)
{
    if(!id) return;
    if(!isNaN(id)) id = 'dataframe' + id;
    var $datagrid = $('#' + id);
    var dataframeName = $datagrid.data('datagrid');
    if(dataframe) window[dataframeName] = dataframe;
    else dataframe = window[dataframeName];
    renderDataframe($datagrid, dataframe, $datagrid.data());
}

function tryInitDataframe(id)
{
    var $dataframe = $('#dataframe' + (id || analysisID));
    if($dataframe.hasClass('dataframe-inited'))
    {
        $dataframe.data('zui.dtable').$.update({dirtyType: 'layout'});
        return;
    }
    updateDataframe(id);
}

/* Handle after load tab page */
function handleAfterLoadTab(tab)
{
    var $tab = $('#tab-' + tab.id);
    $tab.find('a.iframe,.export').initIframeModal();
    tryInitDataframe(tab.id);
    checkAnalysisMethod(tab.id);
    initSplitRow('tab-' + analysisID);
    initTabEvents(tab.id);
}


/** Handle tab open */
function handleTabOpen(tab)
{
    window.history.pushState({}, null, tab.ajax.replace('ajaxgetanalysis', 'analysis'));
    window.analysisID = tab.id;

    tryInitDataframe(tab.id);

    var $tab = $('#tab-' + (tab.id || analysisID));
    var $analysisMethods = $tab.find('.analysis-methods');
    if(!$analysisMethods.length || $analysisMethods.children('.analysis-method-panel').length)
    {
        $('#mainRow .side-bar-view').removeClass('hidden');
    }
    else
    {
        $('#mainRow .side-bar-view').addClass('hidden');
    }
}

/** Handle render tab */
function handleRenderTab(tab, $a)
{
    var tabName = $a.attr('stashName') || tab.title;
    $a.attr("title", tabName);
    $a.find('span')[0].innerHTML = tabName;
    if($a.next('.analysis-actions-btn').length) return;
    if(hasPriv) $a.after('<button type="button" class="btn btn-link btn-sm analysis-actions-btn"><i class="icon-ellipsis-v"></i></button>');
}

/* Calculate navs width on window resize */
function calculateNavsWidth($nav)
{
    var width = $nav.parent().width() - 40;
    $nav.toggleClass('is-compact', (width / $nav.children().length) < 120);
    return width;
}

/** Init analysis tabs */
function initTabs()
{
    var tabs = analysisList.map(function(analysis)
    {
        return {title: analysis.name, id: analysis.id, ajax: createLink('project', 'ajaxgetanalysis', 'analysisID=' + analysis.id), forbidClose: true, loaded: analysis.id === analysisID};
    });

    var tabConfig = {
        tabs:           tabs,
        type:           'ajax',
        defaultTab:      analysisID,
        defaultTabIcon: 'icon-nav-analysis',
        onOpen:          handleTabOpen,
        onLoad:          handleAfterLoadTab,
        contextMenu:     false,
        autoResizeNavs:  'navbar',
        maxNavsWidth:    calculateNavsWidth,
    };

    /* If renderPriv, show tab title. */
    if(renderPriv || hasPriv) tabConfig.onRenderTab = handleRenderTab;

    var $tabs = $('#tabs').tabs(tabConfig);
    if(hasPriv)
    {
        $tabs.contextmenu(
        {
            selector: '.analysis-actions-btn',
            trigger:  'click',
            items:    function(options)
            {
                var $item = $(options.event.target).closest('.tab-nav-item');
                var id = $item.data('id');

                var action = [{label: renameText, url: 'javascript:;', onClick: requestRenameAnaysis.bind(null, id)}];
                if(analysisList.length != 1) action.push({label: deleteText, url: 'javascript:;', onClick: requestDeleteAnaysis.bind(null, id)});
                return action;
            }
        });
    }
}

/**
 * Resize analysis-report's width to fit notes
 *
 * @param {String} tabID id for each tab
 * @param {Boolean} isCloseNotes is close results-note?
 * @param {Boolean} isJustResize change item's width without handle note's dom
 */

function resizeAnalysisReport(tabID, isCloseNotes, isJustResize)
{
    var dataframeWidth = 350;
    var sideBarWidth = 300;
    var $selector = $('.results-notes', '#' + tabID);
    var sideBarWidth = $('.side-bar', '#' + tabID).width();
    if (isCloseNotes)
    {
        $('.col-dataframe', '#' + tabID).width(dataframeWidth);
        $('.col-methods', '#' + tabID).width($('#mainRow', '#' + tabID).width() - $('.col-dataframe', '#' + tabID).width());
        $selector.parent().width(0);
        $selector.parent().addClass('hidden');
    }
    /* sideBarWidth sometime will very samll like 0.0000012241.*/
    else if (sideBarWidth <= 0.1 || isJustResize)
    {
        $('.col-dataframe', '#' + tabID).width(dataframeWidth);
        $('.col-dataframe', '#' + tabID).css('min-width', sideBarWidth);
        $('.col-methods', '#' + tabID).width($('.split-row', '#' + tabID).width() - dataframeWidth - sideBarWidth - $('.side-bar-view', '#' + tabID).width() );
        $selector.parent().removeClass('hidden');
        $selector.parent().css('height', '100%');
        $selector.css('max-height', $('.row').height());
        $selector.parent().width(sideBarWidth);
    }
    toggleSideBar(tabID);
    resizePlotly();
}

/**
 * use window.dispatch to trigger resize func to resize plotly
 *
 */

function resizePlotly()
{
    var myEvent = new Event('resize');
    window.dispatchEvent(myEvent);
}

function initSplitRow(tabID)
{
    /* Init split row. */
    var NAME = 'zui.splitRow'; // model name.
    /* The SplitRow model class. */
    var SplitRow = function(element, options)
    {
        var that = this;
        that.name = NAME;
        var $element = that.$ = $(element);

        options = that.options = $.extend({}, SplitRow.DEFAULTS, this.$.data(), options);
        var id = options.id || $element.attr('id') || $.zui.uuid();
        var $cols = $element.children('.col');
        var $firstCol = $cols.first();
        var $secondCol = $cols.eq(1);
        var $spliter = $firstCol.next('.col-spliter');
        if (!$spliter.length)
        {
            $spliter = $(options.spliter);
            if (!$spliter.parent().length)
            {
                $spliter.insertAfter($firstCol);
            }
        }
        var spliterWidth      = $spliter.width();
        var minFirstColWidth  = $firstCol.data('minWidth');
        var minSecondColWidth = $secondCol.data('minWidth');
        var rowWidth          = $element.width();
        var paddingWidth      = 20;
        var setFirstColWidth  = function(width)
        {
            var maxFirstWidth = rowWidth - minSecondColWidth - spliterWidth - $('#' + tabID + ' .side-bar').width() - $('#' + tabID + ' .side-bar-view').width() - paddingWidth;
            width = Math.max(minFirstColWidth, Math.min(width, maxFirstWidth));
            $firstCol.width(width);
            $secondCol.width($('#mainRow', '#' + tabID).width() - width);
            $.zui.store.set('splitRowFirstSize:' + id, width);
        };

        var defaultWidth = $.zui.store.get('splitRowFirstSize:' + id);
        if(typeof(defaultWidth) == 'undefined') defaultWidth = $element.width() * 0.33;
        setFirstColWidth(defaultWidth);

        var documentEventName = '.' + id;

        var mouseDownX, isMouseDown, startFirstWidth, rafID;
        $spliter.on('mousedown', function(e)
        {
            startFirstWidth = $firstCol.width();
            mouseDownX = e.pageX;
            isMouseDown = true;
            $element.addClass('row-spliting');
            e.preventDefault();
            var handleMouseMove = function(e)
            {
                if(isMouseDown)
                {
                    var deltaX = e.pageX - mouseDownX;
                    setFirstColWidth(startFirstWidth + deltaX);
                    e.preventDefault();
                }
                else
                {
                    $(document).off(documentEventName);
                    $element.removeClass('row-spliting');
                }
            };
            $(document).on('mousemove' + documentEventName, function(e)
            {
                if(rafID) cancelAnimationFrame(rafID);
                rafID = requestAnimationFrame(function()
                {
                    handleMouseMove(e);
                    rafID = 0;
                });

            }).on('mouseup' + documentEventName + ' mouseleave' + documentEventName, function(e)
            {
                if(rafID) cancelAnimationFrame(rafID);
                isMouseDown = false;
                $(document).off(documentEventName);
                $element.removeClass('row-spliting');
                resizePlotly();
            });
        });

        $spliter.on('dblclick', function(e)
        {
            var sideBarWidth = $('.side-bar', '#' + tabID).width();
            resizeAnalysisReport(tabID, sideBarWidth <= 0, true);
        })
    };

    /* default options. */
    SplitRow.DEFAULTS =
    {
        spliter: '<div class="col-spliter"></div>',
        /*
        smallSize: 700,
        middleSize: 850
        */
    };

    /* Extense jquery element. */
    $.fn.splitRow = function(option)
    {
        return this.each(function()
        {
            var $this = $(this);
            var data = $this.data(NAME);
            var options = typeof option == 'object' && option;
            if(!data) $this.data(NAME, (data = new SplitRow(this, options)));
        });
    };

    SplitRow.NAME = NAME;

    $.fn.splitRow.Constructor = SplitRow;

    /* Auto call splitRow after document load complete. */
    $(function()
    {
        $('.split-row').splitRow();
    });
}

/**
 * Init card footer expand icon.
 *
 * @access public
 * @return void
 */
function initExpand()
{
    var maxContentHeight = Math.ceil(parseFloat($('.card-content').css('line-height')) * 10);
    $('#notes .note-card.view').each(function()
    {
        var $card      = $(this);
        var cardHeight = $card.children('.card-content')[0].scrollHeight;
        if(cardHeight > maxContentHeight)
        {
            $card.find('.expand').removeClass('hidden');
        }
        else
        {
            $card.find('.expand').addClass('hidden');
        }
        $("#notes .note-card.edit[data-id='" + $card.attr('data-id') + "']").find('textarea').height(cardHeight);
        if($card.find('icon-angle-down').length == 0) $card.find('.expand').html("<i class='icon-angle-down'></i>");
    });

    $('.note-card .card-content').css('max-height', maxContentHeight);
}

/**
 * Toggle side view icon.
 *
 * @access public
 * @return void
 */
function toggleSideBar(tabID)
{
    var sideBarWidth = $('.side-bar', '#' + tabID).width();
    var $sideView = $('.side-bar-view', '#' + tabID);
    if($sideView.find('.icon-angle-left').length > 0)
    {
        if (sideBarWidth <= 0) return;
        $sideView.html("<i class='icon-angle-right'></i>");
    }
    else if($sideView.find('.icon-angle-right').length > 0)
    {
        if (sideBarWidth > 0.1) return;
        $sideView.html("<i class='icon-angle-left'></i>");
    }
}

/**
 * Add active for note card.
 *
 * @param  int    $obj
 * @access public
 * @return void
 */
function activeNoteCard($obj)
{
    var resultID     = $obj.attr('data-resultID');
    var $method      = $('[id^="analysisMethod"]').find('.analysis-method-result[data-id="' + resultID + '"]');
    var $otherMethod = $('[id^="analysisMethod"]').find('.analysis-method-result[data-id!="' + resultID + '"]');

    $obj.addClass('active');
    $obj.siblings().removeClass('active');
    $obj.siblings('[data-resultid="' + resultID + '"]').addClass('active');
    $method.addClass('active');
    $otherMethod.removeClass('active');
}

/**
 * Position active card and note.
 *
 * @param  object $obj
 * @access public
 * @return void
 */
function positionActive($obj)
{
    if($obj.hasClass('note-card'))
    {
        var resultID = $obj.attr('data-resultID');
        var $method  =  $('[id^="analysisMethod"]').find('.analysis-method-result[data-id="' + resultID + '"]');
        var $methods = $method.closest('.analysis-methods');
        var $side    = $obj.closest('#sidebar');
        var distance = $obj[0].offsetTop - $side.scrollTop();
        if(distance < 0)
        {
            $side.scrollTop($obj[0].offsetTop);
            distance = 0;
        }

        var realTop = 0;
        for(var $now = $method; !$now.hasClass('analysis-methods'); $now = $now.parent()) realTop += $now[0].offsetTop;
        realTop -= $method.parent()[0].offsetTop;

        var methodScollTop = realTop - distance;
        if(methodScollTop < 0)
        {
            $side.scrollTop($obj[0].offsetTop - distance);
            methodScollTop = 0;
        }
        $methods.scrollTop(methodScollTop);
    }
    else if($obj.hasClass('analysis-method-result'))
    {
        var resultID = $obj.attr('data-id');
        var $note    = $('#notes').find('.note-card[data-resultid="' + resultID + '"]').not('.hidden');
        if($note.length == 0) return;

        var $side    = $('#sidebar');
        var $methods = $obj.closest('.analysis-methods');

        var realTop = 0;
        for(var $now = $obj; !$now.hasClass('analysis-methods'); $now = $now.parent()) realTop += $now[0].offsetTop;
        realTop -= $note.parent()[0].offsetTop;

        var distance = realTop - $methods.scrollTop();
        if(distance < 0)
        {
            $methods.scrollTop(realTop);
            distance = 0;
        }

        var noteScrollTop = $note[0].offsetTop - distance - parseInt($methods.css('padding-top'));
        if(noteScrollTop < 0)
        {
            $methods.scrollTop(realTop - $note[0].offsetTop + parseInt($methods.css('padding-top')) + 3);
            noteScrollTop = 0;
        }
        if(($note.hasClass('add') && $('.note-card.addEdit.active').next().length == 0) || (!$note.hasClass('add') && $('.note-card.view.active').next().length == 0)) $note.css('margin-bottom', $methods.height() - realTop + $methods.scrollTop() - parseFloat($methods.css('padding-top')) - parseFloat($methods.css('padding-bottom')) - $note.height());
        $side.scrollTop(noteScrollTop - 3);
    }
}

/**
 * Set a interval to wait img created.
 *
 * @param  function $callback
 * @param  int      $chartCount
 * @access public
 * @return void
 */
function waitImg(callback, chartCount)
{
    var count = 1;
    var timer = setInterval(function()
    {
        count ++;
        if($('img.plotly_img').length >= chartCount || count > 30)
        {
            callback();
            clearInterval(timer);
        }
    }, 100);
}

/**
 * add events to each tab
 *
 * @param {Number} analysisID tab.id
 */
function initTabEvents(analysisID)
{
    var tabID = 'tab-' + analysisID;
    $(document).on('click','#' + tabID + ' .note-add', function(e)
    {
        $('.table-empty-tip').addClass('hidden');
        var $selector = $('.results-notes', "#" + tabID);

        resizeAnalysisReport(tabID);
        var $result  = $(this).closest('div.analysis-method-result');
        var resultID = $result.attr('data-id');
        var methodID = $(this).closest('div.analysis-method-title').attr('data-methodID');
        var link     = createLink('project', 'ajaxGetNotes', 'analysisID=' + analysisID + '&resultID=' + resultID + '&type=add');
        $selector.load(link, function()
        {
            $selector.find('.note-card.add, .note-card.addView, .note-card.addEdit').attr('data-analysisID', analysisID);
            $selector.find('.note-card.add, .note-card.addView, .note-card.addEdit').attr('data-methodID', methodID);
            $selector.find('.note-card.add, .note-card.addView, .note-card.addEdit').attr('data-resultID', resultID);

            activeNoteCard($('#notes').find('.note-card[data-resultid="' + resultID + '"].add'));

            initExpand();
            positionActive($result);
        });
    });

    $(document).on('click', '#' + tabID + ' .note-view', function(e)
    {
        $('.table-empty-tip').addClass('hidden');
        var $selector = $('.results-notes', '#' + tabID);

        var $result  = $(this).closest('div.analysis-method-result');
        var resultID = $result.attr('data-id');
        var methodID = $(this).closest('div.analysis-method-title').attr('data-methodID');
        var link     = createLink('project', 'ajaxGetNotes', 'analysisID=' + analysisID + '&resultID=' + resultID + '&type=view');
        $selector.load(link, function()
        {
            resizeAnalysisReport(tabID);
            activeNoteCard($('#notes').find('.note-card[data-resultid="' + resultID + '"]'));

            initExpand();
            positionActive($result);
        });
    })

    $(document).on('click', '#' + tabID + ' .side-bar-view', function(e)
    {
        var $selector = $('.results-notes', '#' + tabID);

        if($(this).find('.icon-angle-left').length > 0)
        {
            var link = createLink('project', 'ajaxGetNotes', 'analysisID=' + analysisID);
            $selector.load(link, function()
            {
                resizeAnalysisReport(tabID);
                initExpand();

            });
        }
        else if($(this).find('.icon-angle-right').length > 0)
        {
            resizeAnalysisReport(tabID, true)
        }
    });

    $(document).on('click','#' + tabID + ' .note-card', function(e)
    {
        if($(e.target).not('i').length == 0 || $(e.target).hasClass('btn')) return;
        activeNoteCard($(this));
        positionActive($(this));
    });

    $(document).on('click', '#' + tabID + ' .analysis-method-result', function()
    {
        if($('#sidebar')[0].offsetLeft == 0) return;

        var resultID     = $(this).attr('data-id');
        var $otherMethod = $('[id^="analysisMethod"]').find('.analysis-method-result[data-id!="' + resultID + '"]');
        var $noteCard    = $('#notes').find('.note-card[data-resultid="' + resultID + '"]');
        var $otherCard   = $('#notes').find('.note-card[data-resultid!="' + resultID + '"]');

        $(this).addClass('active');
        $otherMethod.removeClass('active');
        $noteCard.addClass('active');
        $otherCard.removeClass('active');
        positionActive($(this));
    });;

    $(document).on('click', '#' + tabID + ' #notes .note-card .card-head #editButton', function()
    {
        var noteID = $(this).closest('.note-card').attr('data-id');
        if(!noteID) return;

        $(this).closest('#notes').find('.edit[data-id="' + noteID + '"]').removeClass('hidden');
        $(this).closest('.view').addClass('hidden');
    });

    $(document).on('click', '#' + tabID + ' #notes .note-card .card-head #saveButton', function(event)
    {
        var isAdd = $(this).closest('.note-card').hasClass('add');
        if(isAdd)
        {
            var $noteCard  = $(this).closest('.note-card');
            var analysisID = $noteCard.attr('data-analysisID');
            var methodID   = $noteCard.attr('data-methodID');
            var resultID   = $noteCard.attr('data-resultID');
            var desc       = $noteCard.find('div.card-content #comment').val();

            var data = {'analysis': analysisID, 'method': methodID, 'result': resultID, 'desc': desc};
            $.post(createLink('resultnotes', 'add'), data, function(result)
            {
                var result      = JSON.parse(result);
                var noteID      = result.noteID;
                var createdDate = $.zui.formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss');
                if(result.message) $.zui.messager.success(result.message);

                $noteCard.closest('#notes').find('.addView,.addEdit').attr('data-id', noteID);
                $noteCard.closest('#notes').find('.addView').removeClass('hidden').removeClass('addView').addClass('view');
                $noteCard.closest('#notes').find('.addEdit').removeClass('addEdit').addClass('edit');
                $noteCard.closest('#notes').find('.view[data-id="' + noteID + '"]').find('.card-content').text(desc);
                $noteCard.closest('#notes').find('.view[data-id="' + noteID + '"]').find('.edit-date').text(createdDate);
                $noteCard.closest('#notes').find('.edit[data-id="' + noteID + '"]').find('textarea').text(desc);
                $noteCard.closest('.add').addClass('hidden').remove();

                $('.analysis-methods').find('.analysis-method-result[data-id="' + resultID + '"] .block-actions .note-add').removeClass('note-add').addClass('note-view').attr('title', viewNotesTitle).find('i.icon-pencil').removeClass('icon-pencil').addClass('icon-check-notes');

                initExpand();
            });
        }

        var isEdit = $(this).closest('.note-card').hasClass('edit');
        if(isEdit)
        {
            var $noteCard = $(this).closest('.note-card');
            var noteID    = $noteCard.attr('data-id');
            var desc      = $noteCard.find('div.card-content #comment').val();

            var data = {'desc': desc};
            $.post(createLink('resultnotes', 'edit', 'noteID=' + noteID), data, function(result)
            {
                var createdDate = $.zui.formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss');
                $noteCard.closest('#notes').find('.view[data-id="' + noteID + '"]').removeClass('hidden').find('.card-content').text(desc);
                $noteCard.closest('#notes').find('.view[data-id="' + noteID + '"]').find('.edit-date').text(createdDate);
                $noteCard.closest('.edit').addClass('hidden');

                var result = JSON.parse(result);
                if(result.message) $.zui.messager.success(result.message);

                initExpand();
            });
        }
    });

    $(document).on('click', '#' + tabID + ' #notes .note-card .card-head #cancelButton', function()
    {
        if($('.note-card.view').length == 0) $('.table-empty-tip').removeClass('hidden');
        if($(this).closest('.detail-content').find('.add, .addView, .addEdit').length > 0)
        {
            $(this).closest('.detail-content').find('.add, .addView, .addEdit').remove();
            return;
        }

        var $noteCard = $(this).closest('.note-card');
        var noteID    = $noteCard.attr('data-id');
        var $view     = $noteCard.closest('.detail-content').find('.view[data-id="' + noteID + '"]');
        var desc      = $view.find('.card-content').text();
        $view.removeClass('hidden');
        $noteCard.addClass('hidden');
        $noteCard.find('div.card-content #comment').val(desc);

        initExpand();
    });

    $(document).on('click', '#' + tabID + ' #notes .note-card .card-head #deleteButton', function()
    {
        var $noteCard = $(this).closest('.note-card');
        var noteID    = $noteCard.attr('data-id');
        var resultID  = $noteCard.attr('data-resultid');
        if(!noteID) return;

        bootbox.confirm(confirmDeleteNoteText, function(result)
        {
            if(!result) return;
            $.get(createLink('resultnotes', 'delete', 'noteID=' + noteID));
            $noteCard.closest('#notes').find('[data-id="' + noteID + '"]').remove();

            $('.analysis-methods').find('.analysis-method-result[data-id="' + resultID + '"] .block-actions .note-view').removeClass('note-view').addClass('note-add').attr('title', addNotesTitle).find('i.icon-check-notes').removeClass('icon-check-notes').addClass('icon-pencil');
            $('[id^="analysisMethod"]').find('.analysis-method-result[data-id="' + resultID + '"]').removeClass('active');
            if($('.note-card.view').length == 0) $('.table-empty-tip').removeClass('hidden');
        })
    });

    $(document).on('click', '#' + tabID + ' .method-title-edit', function(event)
    {
        var id       = $(this).attr('data-id');
        var title    = $(this).parent();
        var width    = parseInt($(this).prev().css('width')) + 15 + 'px';
        var input    = '<input class="input-border-none analysis-method-title" style="width:' + width + '" id=' + id  + ' onblur="renameTitle(id)"></input>'

        if($('input#' + id)) $('input#' + id).remove();
        $(this).parent().after(input);
        $(title).addClass('hidden');

        var $input =  $('input#' + id);
        $input.val(title[0].innerText);
        $input.focus();
    });

    $(document).on('click', '#' + tabID + ' .method-copy-all', async function(event)
    {
        var methodID   = $(this).attr('data-methodid');
        var chartCount = 0;
        var $tab       = $('#tabs .tabs-container').find('#tab-' + analysisID);

        setTimeout(function(){
          var $e = $(event.target).parent();
          var $original = $e.clone();
          $e.replaceWith($original);
        }, 500);

        var i = 0;

        $('.method-copy-all').each(async function()
        {
            if($(this).attr('data-methodid') == methodID)
            {
                const data = await $.getJSON(createLink('analysis', 'ajaxGetMethodResult', 'methodID=' + methodID));
                if(data.result == 'success')
                {
                    for(var result of data.data.results) if(result.type == 'chart') chartCount ++;
                    for(var j = 1; j <= chartCount + 1; j ++) $tab.append('<div class="hidden" id="plotly_div' + j + '"></div>');

                    for(var result of data.data.results)
                    {
                        if(result.type == 'chart')
                        {
                            $('.analysis-method-result','#collapse' + methodID,'#analysisMethod' + methodID).each(async function()
                            {
                                if(result.id == $(this).attr('data-id'))
                                {
                                    i ++;
                                    const gd = await Plotly.newPlot('plotly_div' + i, eval(result.data.data), eval(result.data.layout));
                                    const res = await Plotly.toImage(gd,{height:500,width:1000});
                                    $(this).find('.plot-container').addClass('hidden');
                                    $(this).find('.plot-container').after('<img class="plotly_img" src=' + res + '></img>');
                                }
                            });
                        }
                    }
                }
                for(var j = 1; j <= chartCount + 1; j ++) $('#plotly_div' + j).remove();

                var node = $(this).parent().parent().parent()[0];
                var range = document.createRange();
                range.selectNode(node);
                window.getSelection().addRange(range);
                if(chartCount)
                {
                    waitImg(function()
                    {
                        document.execCommand('copy');
                        window.getSelection().empty();
                        $('.plotly_img').remove();
                        $('.plot-container').removeClass('hidden');
                        $.zui.messager.success(copySuccess);
                    }, chartCount);
                }
                else
                {
                    document.execCommand('copy');
                    window.getSelection().empty();
                    $.zui.messager.success(copySuccess);
                }
            }
        });
        return false;
    });

    $(document).on('click', '#' + tabID + ' .delete-analysis-method', function(event)
    {
        var $panel  = $(this).closest('.analysis-method-panel').addClass('is-deleting');
        var id      = $panel.data('id');
        var heading = $panel.find('.analysis-method-heading').text();

        var deleteTip = confirmDeleteText;
        if(!$('#sidebar').hasClass('hidden'))
        {
            if($('#notes').find('.note-card[data-methodid="' + id + '"]').length > 0) deleteTip = deleteMethodTip;
        }

        bootbox.confirm(deleteTip + '<div style="margin-top:10px; text-align: center;"><strong class="label ellipsis label-light">' + heading + '</strong></div>', function(result)
        {
            $panel.removeClass('is-deleting');
            if(result)
            {
                $.getJSON(createLink('analysis', 'deleteMethod', 'methodID=' + id + '&confirm=yes'), function(data)
                {
                    if(data && data.result === 'success')
                    {
                        $panel.remove();
                        checkAnalysisMethod();
                        if($('#notes').find('.note-card[data-methodid="' + id + '"]').length > 0) $('#notes').find('.note-card[data-methodid="' + id + '"]').remove();
                        if($('#tab-' + analysisID).find('.analysis-right-menu').length) resizeAnalysisReport('tab-' + analysisID, true);;
                    }
                    else if(data && data.message)
                    {
                        $.zui.messager.danger(data.message);
                    }
                });
            }
        });
        event.preventDefault();
    });

    $(document).on('click', '#' + tabID + ' .method-settings-btn', function()
    {
        $(this).closest('.analysis-method-panel').find('.panel-actions .method-settings-link').click();
    });
}

$(function()
{
    initTabs();
    checkAnalysisMethod();
    initSplitRow('tab-' + analysisID);
    initTabEvents(analysisID);

    $(document).on('hide.zui.collapse', ".block-collapse", function (event) {
        var id = $(event.target).attr('id');
        $("a[href='#" + id + "']").html('<i class="icon icon-expand"></i>');
        $("a[href='#" + id + "']").attr('title', expand);


        setTimeout(function(){
          var str    = 'collapse';
          var dataId = id.slice(str.length);
          var $e = $('#analysisMethod' + dataId + ' .panel-heading .panel-actions').children().first();
          var $original = $e.clone();
          $e.replaceWith($original);
        }, 500);

    });

    $(document).on('show.zui.collapse', ".block-collapse", function (event) {
        var id = $(event.target).attr('id');
        $("a[href='#" + id + "']").html('<i class="icon icon-collapse"></i>');
        $("a[href='#" + id + "']").attr('title', reduce);

        setTimeout(function(){
          var str    = 'collapse';
          var dataId = id.slice(str.length);
          var $e = $('#analysisMethod' + dataId + ' .panel-heading .panel-actions').children().first();
          var $original = $e.clone();
          $e.replaceWith($original);
        }, 500);

    });

    $(document).on('click','.methods-export', function()
    {
        var $a = $(this);
        var width = $a.attr('data-width') || 650;
        var analysisID = $(".nav-divider .active").attr('data-id');
        $.zui.modalTrigger.show(
        {
            name:  'exportModal',
            type:  'iframe',
            url:   $a.attr('href').replace('{id}', analysisID),
            width: width
        });
        event.preventDefault();
    });

    $(document).on('click', '.analysis-method-refreshAll', function(event)
    {
        var analysisID = $(".nav-divider .active").attr('data-id');
        $.getJSON(createLink('analysis', 'refreshAll', 'analysisID=' + analysisID), function(data)
        {
             if(data.methodIDList)
             {
                 methodIDList = data.methodIDList.split(',');
                 methodIDList.forEach((methodID, index) => { updateAnalysisMethod(methodID, analysisID);});
             }

             if(data && data.result === 'success')
             {
                 if(data.message) $.zui.messager.success(data.message);
             }
             else
              {
                  if(data.message)
                  {
                       var message = new $.zui.Messager(data.message,
                       {
                           html: true,
                           icon: 'exclamation-sign',
                           type: 'danger',
                           close: true,
                       });

                       message.show();
                 }
             }
        });
    });

    $(document).on('click', '.method-create-link', function(event)
    {
        var $a = $(this);
        var width = $a.attr('data-width') || 650;
        var analysisID = $(".nav-divider .active").attr('data-id');
        $.zui.modalTrigger.show(
        {
            type:  'iframe',
            url:   $a.attr('href').replace('{id}', analysisID),
            width: width,
            scrollInside: true,
            moveable: true,
            backdrop: 'static'
        });
        event.preventDefault();
    });

    $(document).on('click','.analysis-method-refresh', function(event)
    {
        var methodID   = $(this).attr('data-methodID');
        var analysisID = $(".nav-divider .active").attr('data-id');
        $.getJSON(createLink('analysis', 'refresh', 'methodID=' + methodID), function(data)
        {
            if(data && data.result === 'success')
            {
                updateAnalysisMethod(methodID, analysisID);
                if(data.message) $.zui.messager.success(data.message);
            }
            else
            {
                if(data.message) $.zui.messager.danger(data.message);
            }
        });
        return false;
    });

    $(document).on('click', '.analysis-create-btn', function(e)
    {
        e.preventDefault();
        if($('#tabs .tab-nav-item').length >= maxAnalysisCount)
        {
            return bootbox.alert(createLimitTipText);
        }
        $.zui.modalTrigger.show({type: 'iframe', url: $(this).attr('href'), width: 550});
    });

    $(document).on('click', '.highlight-points', function(e)
    {
        var $btn = $(e.target).closest('.highlight-points');

        var isActive = $btn.hasClass('highlight-active');
        removeHightlightTest();

        if(!isActive) highlightTestPoints($btn);
    });

    resizePlotly();
});
