
    <div class="left-column">
        <div class="col-padding">
            <h4 class="bold float-left">Hosts</h4>
            <a class="refresh float-right" href="#" id="navi-tree-refresh"><i class="bi bi-arrow-clockwise"></i> Refresh</a>
            <div class="clearfix"></div>
            <div id="astrolabe"></div>
        </div>
    </div>
    <div class="right-column">
        <div class="pageTitle">

            <h1 class="astrolabeLocation"> <!-- Necessary for help icon alignment -->

            </h1>

        </div>
        <div id="tabs-layout" class="margin-bottom float-left">

            <ul style="display:none">
                <li class="first">
                    <a class="overview_tab_SE" href="#overview">Overview</a>
                </li>

                <li>
                    <a class="host_info_tab_SE" href="#hosts-info">Host Info</a>
                </li>
            </ul>

            <div id="overview" class="hostTab engineeringStatusContainer" style="padding:0 0 20px 0">
                <div style="display:none" id="hostsComplianceContainer">
                    <div id="compliance" class="row-fluid float-left hostCompliance"></div>
                    <span class="help-block float-left margin-top-small">Total CFEngine compliance level for all hosts during the last reported run.</span>
                </div>

                <div id="hostInfoContainer" class="hostsInfoContainer">
                    <div id="hostInfo" class=""></div>
                </div>

                <div class="row-fluid float-left margin-bottom-small">
                    <div id="complianceHostsInfoContainer" class="compliancehostsInfoContainer hide padding-bottom">

                    <div id="_notification">

                    </div>

                        <div id="jqGridComplianceTable"></div>

                        <div class="row-fluid float-left">
                            <span style="margin-top: 2px;" id="jqgrid-delete-host-btn"
                                  class="btn btn-danger-outline btn-large pull-left">Remove selected hosts</span>
                        </div>

                        <p class="alert alert-info hide" id="jqgrid-no-record">No host to list</p>
                        <div class="clear"></div>
                    </div>

                </div>

            </div>
            <div id="hosts-info" class="pullTop" style="padding:0 0 20px 0">
                <div id="hosts-info" class="hosts-info"></div>
            </div>

        </div>
        <div class="clearfix"></div>
    </div>


<script type="text/javascript">

    var hostkey = '<?= htmlspecialchars($hostkey) ?>';

    var CF = CF || {};

    CF.Plugins= function() {
        var pub = {};

        pub.genericOption = {
            baseUrl: '<?php echo site_url() ?>'
        };

        return pub;

    }();

    // module to delete host used in this page and compliance table grid
    CF.Plugins.deleteHost = function(){

        var pub = {}; // public methods and vars

        var deleteHostMessage = '<?php echo $this->lang->line('host_delete_confirm'); ?>';
        var deleteHostFailedMessage = 'There was some error encountered while deleting the host(s).';
        var deleteHostSuccessMessage = 'Host deleted sucessfully!'

        pub.deleteHosts = function(arrayKeys) {

            var header = (arrayKeys.length>1) ? "<h2>Remove hosts?</h2>" : "<h2>Remove host?</h2>";
            $("<div></div>")
                .dialog_modal({
                    passedArgs: [deleteHostMessage, [{

                        "label" : "Cancel",
                        "class" : "btn btn-large",
                        "callback": function() {}
                    }, {
                        "label" : "Remove",
                        "class" : "btn btn-large btn-primary btn-danger",
                        "callback": function() {
                            var parameters = {'delhosts[]':arrayKeys};
                            processRequest(parameters).then(showHostDeleteSuccess).fail(showHostDeleteFailure);
                        }
                    }],{
                        header:header,
                        'onEscape': function(){}
                    }],
                })

        };

        var showHostDeleteSuccess =  function() {
            common.globalSpinner.hide();
            var errorMessage = $('<p></p>')
            .append(deleteHostSuccessMessage)
            .addClass('alert alert-success');
            bootbox.alert(errorMessage,function() {
                window.location.reload();
            });
        };

        var showHostDeleteFailure= function(jqXHR, textStatus, errorThrown) {
            common.globalSpinner.hide();
            var errorMessage = $('<p></p>')
            .append(deleteHostFailedMessage)
            .append('<br/>')
            .append(jqXHR.responseText)
            .addClass('alert alert-error');

             bootbox.alert(errorMessage);
        };

        var processRequest = function(parameters) {
            common.globalSpinner.show();
            return $.ajax({
                type: "POST",
                url: "<?php echo site_url(); ?>/host/delhosts",
                data: parameters,
                async: true
            });
        };

        return pub;
    }();




    CF.Plugins.HostComplianceGrid = function() {

        var pub = {}; // public methods and vars
        var $wrapper = $('#complianceHostsInfoContainer');
        var $container = $('#jqGridComplianceTable');
        var $dataTable = $('<table id="datatable-table"></table>').addClass('table table-bordered');
        var $titleSelector = $('div.complianceHostsTableTitle');

        var $oTable = null;

        var context = {includes:null,excludes:null,colour:null};

        var setContext = function (includes,excludes,colour) {
            context.includes = includes;
            context.excludes = excludes;
            context.colour = colour;

        }

        var gridFormatterfunctionsMapping = {

            "checkbox_formatter":function (data, type, full) {
                return '<input type="checkbox" class="datatable-select-check-box" />';
            },
            "timestamp_formatter": function(data, type, full) {

                var jsTime = 'unknown';
                var itemDescription = data;
                var intRegex = /^\d+$/;
                if(intRegex.test(itemDescription)) {
                    if (itemDescription > 0) {
                        jsTime =  common.time.format(common.unixTimeToJavascriptTime(itemDescription));
                    }
                }
                return jsTime;
            }
        }

        var urls =  {

            metaData:  function(context) {
                return CF.Plugins.genericOption.baseUrl+'/hostcompliancelist/tablemetadata/'+context.colour;
            },

            dataSource: function(context) {
                return  CF.Plugins.genericOption.baseUrl+'/hostcompliancelist/tabledata/'+context.colour;
            }


        };


        var getTableMetadata = function() {

            return $.ajax( {
                "url": urls.metaData(context),
                "dataType": "json"
            } );
        }

        var initializeDataTables = function(data,meta) {


            $container.empty();
            $wrapper.off(".datatableCustomEvent");
            if ($oTable) {
                $oTable.fnDestroy(true);
                $oTable = null;
                $dataTable.empty();
            }
            $container.append($dataTable);

            var  postData = [
                {"name":"includes","value":context.includes},
                {"name":"excludes","value":context.excludes},
                {"name":"colour","value":context.colour},
            ];

            // modify col defs for server function mapping of formatter
            if (data.aoColumnDefs){
            $.each(data.aoColumnDefs,function(index,entry) {
                if ('mRender' in entry) {
                    var func = entry.mRender;
                    if (gridFormatterfunctionsMapping.hasOwnProperty(func)) {
                        entry.mRender = gridFormatterfunctionsMapping[func]
                    }
                }
            });
        }




            var dataTableParams =  {
                "sDom": "<'row-fluid'rlp><'row-fluid complianceHostsTableTitle'>t<lp>",
                "sPaginationType": "bootstrap",
                "oLanguage": {
                    "sLengthMenu": "_MENU_"
                },
                "sServerMethod": "POST",
                "aoColumnDefs": data.aoColumnDefs,
                "fnServerParams": function ( aoData ) {
                    $.map(postData,function(item) {
                        aoData.push( item );
                    });
                },
                "bProcessing": true,
                "bPaginate":  true,
                "bFilter": false,
                "bInfo": false,
                "bSort": false,
                "bServerSide":  true,
                "sAjaxSource": urls.dataSource(context),
                "bDestroy": true,
                "bFilter":false,
                "fnInitComplete": attachEventHandles

            }

            $oTable = $dataTable.dataTable( dataTableParams );
            var tableTitle = getTableTitle(meta);
            $("div.complianceHostsTableTitle").html('<h4>'+tableTitle+'</h4>');

        };

        function getSelectedRows(oTable) {
            return oTable.$('tr.selected-row');
        }


        var attachEventHandles = function() {
            attachEventHandleForSelectRows.call(this);
            attachEventHandlerForDeleteHostButton.call(this);
        }

        var attachEventHandlerForDeleteHostButton = function() {
            var oTable = this;
            $wrapper.on('click.datatableCustomEvent','#jqgrid-delete-host-btn',function(){
                var rows = getSelectedRows( oTable );
                var id = [];
                var length = rows.length;
                if ( rows && length !== 0 ) {
                    for ( var i = 0; i < length; i++ ) {
                        id.push($(rows[i]).attr('id'));
                    }
                    CF.Plugins.deleteHost.deleteHosts(id);
                } else {
                    // bootbox.alert('Seems like you haven't selected any host to delete');
                }
            });
        }

        var attachEventHandleForSelectRows = function() {

            var oTable = this;

            $wrapper.on('click.datatableCustomEvent','tr',function(){
                $(this).toggleClass('selected-row');
                if ($(this).hasClass('selected-row')) {
                    $(this).find('input.datatable-select-check-box').attr('checked',true);
                } else {
                    $(this).find('input.datatable-select-check-box').attr('checked',false);
                }
            });

            $wrapper.on('click.datatableCustomEvent','input.datatable-select-check-box',function() {
                e.preventDefault();
                e.stopPropagation();
                var thisCheck = $(this);
                var parentTr = $(this).closest('tr');
                if (thisCheck.is(':checked'))
                {
                    parentTr.addClass('selected-row');
                }
                else
                {
                    parentTr.removeClass('selected-row');
                }
            });

            $wrapper.on('click.datatableCustomEvent','#check-all',function() {
                $('input', oTable.fnGetNodes()).attr('checked',this.checked).trigger('change');
            });

            $wrapper.on('change.datatableCustomEvent','input.datatable-select-check-box',function(e) {
                e.preventDefault();
                e.stopPropagation();
                var thisCheck = $(this);
                var parentTr = $(this).closest('tr');
                if (thisCheck.is(':checked'))
                {
                    parentTr.addClass('selected-row');
                }
                else
                {
                    parentTr.removeClass('selected-row');
                }
            });

        }


        var drawTable = function(meta) {
            getTableMetadata().then(
                function(ajaxData) {
                    initializeDataTables(ajaxData,meta);
                }
                ).fail(function(jqXHR, textStatus, errorThrown) {

                    var opt = {
                        statusCode:null,
                        targetDiv: $container,
                        msg:"Cannot fetch data for table initialization."
                    };
                    common.globalSpinner.show();
                });
            }

        var getTableTitle = function(data) {
            if (data.color == 'red') {
            return "Non-compliant hosts";
            } else if (data.color =='bb') {
                return 'Hosts missing data';
            } else if (data.color =='green') {
                return 'Fully compliant hosts';
            }
            return '';
        }

        pub.init = function(data) {
            var includes = encodeURIComponent(data.includes);
            var excludes = encodeURIComponent(data.excludes);
            var colour = data.color;
            setContext(includes,excludes,colour);
            drawTable(data);
        };

        pub.hide = function() {
            $wrapper.hide();
        }

        return pub;




    }();


    /*
     * Abstraction for host compliance plugin
     */
    CF.Plugins.HostCompliance = function() {

        var pub = {}; // public methods and vars
        var $container = $('#hostsComplianceContainer');
        pub.init = function() {
            var hostsComplianceOptions = {
                baseUrl: CF.Plugins.genericOption.baseUrl,
                colorentryclicked: function(e,data) {
                    // load compliance table
                    loadComplianceTable(data);
                }

            };
            $('.hostCompliance').hostsCompliance(hostsComplianceOptions);
            pub.activate(false);
        };

        pub.refresh = function() {
            $('.hostCompliance').hostsCompliance('refresh');
        }

        var loadComplianceTable = function(data) {

            $('.hostCompliance').hostsCompliance('refresh');
            $('#complianceHostsInfoContainer').show();
            CF.Plugins.HostComplianceGrid.init(data);
        }

        pub.show = function() {
            $container.show();
            resetUI();
        };

        var resetUI = function() {

            CF.Plugins.HostComplianceGrid.hide();

        }

        pub.hide = function()  {
            $container.hide();
            resetUI();
        };

        pub.setContext = function(args) {
            $('.hostCompliance').hostsCompliance('setContext', args.includes, []);
            resetUI();
        };

        pub.activate = function(flag) {
            flag = flag || false;
            $('.hostCompliance').hostsCompliance('setActive', flag);
        }


        return pub;
    }();

    /*
     *Abstraction for host info plugin
     */
    CF.Plugins.HostInfo = function() {
        var pub = {}; // public methods and vars
        var $container = $('#hostInfoContainer');
        pub.init = function() {
            $container.hide(); // hide it
            bindRemoveHostButton();
            bindHostClickHeader();
        }

        var bindRemoveHostButton = function() {
            $("#remove-host-button").on("click", function(e){
                e.preventDefault();
                var target = $(this);
                var key = target.attr('key');
                var arrayKeys = [];
                arrayKeys.push(key);
                CF.Plugins.deleteHost.deleteHosts(arrayKeys);
            });
        }

        var bindHostClickHeader = function() {
            // bind the click for info host now to open assets tab
            $('#hostInfo a.headerLabel').click(function(e){
                e.preventDefault();
                CF.Plugins.tabs.openTab('hosts');
            });
        }




        pub.show = function() {
            $container.show();
        };

        pub.hide = function()  {
            $container.hide();
            $('#remove-host-button').hide();
        };

        pub.setContext = function(args) {
            $('#remove-host-button').attr('key',args.hostKey)
        };

        return pub;

    }();

    CF.Plugins.astrolabeLocation = function() {
        var pub = {}; // public methods and vars
        var $container = $('.astrolabeLocation');
        pub.init = function() {
            var astrolableComplianceOptions = {
                defaultLabel: '',
                defaultHostLabel: ' ',
                defaultContextPathLabel: '',
                defaultHeaderWrapper:'<span/>',
                hostBaseUrl: MP_SITE_URL + '/hosts/'
            };

            $container.astrolabeLocation(astrolableComplianceOptions);
        };


        pub.show = function() {
            $container.show();
        };

        pub.hide = function()  {
            $container.hide();
        };

        pub.setContext = function(args) {
            $container.astrolabeLocation('setContextPath', args.path, args.count);
        };

        pub.setHost = function(args) {
            $container.astrolabeLocation('setHostName', args.hostName);
        }



        return pub;



    }();


    CF.Plugins.tabs = function() {
        var pub = {}; // public methods and vars
        var TAB_INDEX = -1;

        // save clicked tab id to prevent reload content multiple times
        var $tabs=$('#tabs-layout');
        var clickedTabs = [];

        var tabIndexMap = {
            status:0,
            hosts:1
        };

        var disableAllWidgetsState = function() {
            CF.Plugins.HostCompliance.activate(false);
        }


        function getTabNoFromName(tabName) {

            if (tabName in tabIndexMap ) {
                return tabIndexMap[tabName];
            }

            return null;

        }

        function getTabNameFromIndex(index) {

            for(var key in tabIndexMap)
            {
                if(tabIndexMap[key]==index) {
                    return key;
                }
            }
            return null;
        }

        /**
         * function to update the help icon and state of widgets
         */
        var updateSeletedWidgets = function(tab) {
            disableAllWidgetsState();
            var tabNo = getTabNoFromName(tab);
            switch(tab) {
                case 'status': {
                        // status tab
                        CF.Plugins.HostCompliance.activate(true);
                        $('#tab-context-help-icon').attr('data-key','status-tab');
                        $('#tab-context-help-icon').attr('data-title','Status');
                        break;
                    }
                case 'hosts': {
                        // assets tab
                        $('#tab-context-help-icon').attr('data-key','assets-tab');
                        $('#tab-context-help-icon').attr('data-title','Host info');
                        break;
                    }
            }
        }

        /**
         * Function to call when tabs are clicked
         */
        pub.tabClicked = function(tab) {

            var tabNo = getTabNoFromName(tab);

            updateSeletedWidgets(tab);

            if($.inArray(tabNo, clickedTabs) === -1) {
                clickedTabs.push(tabNo);


                if (tab === 'status') {
                    // we are in status tab
                    CF.Plugins.HostCompliance.refresh();
                    pub.openTab('status');
                    pub.loadTab('status');
                }

                if (tab === 'hosts' ) {
                    pub.openTab('hosts');
                    pub.loadTab('hosts');
                }
            }

        }

        pub.resetClickedTabs = function () {
            clickedTabs= [];
            disableAllWidgetsState();
        }


        pub.addTabData = function (data) {
            $tabs.data(data);
        }


        pub.setHostTabUrl = function(args) {
            var newAssetUrl = null;
            if (!args) {
                newAssetUrl =  '<?php echo site_url('/assets/node_assets'); ?>';
            } else {
                newAssetUrl = '<?php echo site_url('/assets/host_assets'); ?>'+'/'+args.hostKey;
            }

            var tabNo = getTabNoFromName('hosts');

            $('.host_info_tab_SE').attr('href', newAssetUrl);
        }

        pub.getCurrentIndex = function() {
            return TAB_INDEX;
        }

        pub.getCurrentTab = function() {
            return getTabNameFromIndex(TAB_INDEX);
        }


        pub.openTab = function(identifier) {
            var tabNo = getTabNoFromName(identifier);
            if (tabNo != null ) {
                $tabs.tabs('option', 'active', tabNo);
            }
        }

        pub.loadTab = function(identifier) {
            var tabNo = getTabNoFromName(identifier);
            if (tabNo != null ) {
                $tabs.tabs('load',tabNo);
            }
        }

        pub.init = function () {
            $tabs.tabs({
                cache:true,
                ajaxOptions:
                {
                    beforeSend: function() {
                        common.globalSpinner.show();
                    },
                    complete: function(data) {
                        common.globalSpinner.hide();
                    }
                },
                beforeLoad: function(event, { ajaxSettings: { url } }) {
                    if (pub.currentUrl === url) {
                        // do not load tab if the url is already loaded
                        event.preventDefault();
                    } else {
                        pub.currentUrl = url;
                    }
                },
                select: function(event, ui) {
                    window.location.hash = ui.tab.hash;
                },

                show: function(event, ui) {
                    TAB_INDEX = ui.index;
                    if(TAB_INDEX == false) {
                        TAB_INDEX = 0;
                    }
                    var tabName = getTabNameFromIndex(TAB_INDEX);
                    pub.tabClicked(tabName);
                },
                load: function(event,ui) {
                    common.globalSpinner.hide();
                }
            });
        }

        return pub;
    }();



    CF.Plugins.astroable = function() {
        var pub = {};
        var $container = $('#astrolabe');
        var currentHOSTKEY = ''
        pub.init = function() {
            $container.astrolabe({
                baseUrl: CF.Plugins.genericOption.baseUrl,

                hostSelected: function(event, args) {
                    if (currentHOSTKEY === '') {
                       currentHOSTKEY = $('.host_id_SE:visible').text().trim();
                    }
                    if (currentHOSTKEY !== args.hostKey)
                    {
                        if (currentHOSTKEY !== '') {
                            $('#hosts-info #ngApp').css('opacity', '0.2');
                        }
                        currentHOSTKEY = args.hostKey;
                        CF.Plugins.tabs.resetClickedTabs();
                        CF.Plugins.tabs.addTabData({context:'host',args:args});

                        CF.Plugins.HostCompliance.hide();
                        CF.Plugins.HostInfo.show();


                        CF.Plugins.HostInfo.setContext(args);
                        CF.Plugins.astrolabeLocation.setHost(args);
                        CF.Plugins.tabs.setHostTabUrl(args);

                        CF.Plugins.tabs.tabClicked('hosts');
                    }

                },

                notFoundHostSelected: function (event, hostkey) {
                    CF.Plugins.HostCompliance.hide();
                    CF.Plugins.HostInfo.show();
                    CF.Plugins.tabs.setHostTabUrl({hostKey: hostkey});
                    CF.Plugins.tabs.tabClicked('hosts');
                },

                nodeSelected: function(event, args) {
                    currentHOSTKEY = '';
                    CF.Plugins.tabs.addTabData({context:'node',args:args});
                    CF.Plugins.tabs.resetClickedTabs();

                    CF.Plugins.HostInfo.hide();
                    CF.Plugins.HostCompliance.show();


                    CF.Plugins.HostCompliance.setContext(args);
                    CF.Plugins.astrolabeLocation.setContext(args);
                    CF.Plugins.tabs.setHostTabUrl(false);

                    CF.Plugins.tabs.tabClicked('status');
                }
            });

        };
        pub.refresh = function() {
             $container.astrolabe('refresh');
        };

        return pub;
    }();

    $(document).ready(function(){
        CF.Plugins.tabs.init();
        CF.Plugins.astroable.init();
        CF.Plugins.HostCompliance.init();
        CF.Plugins.HostInfo.init();
        CF.Plugins.astrolabeLocation.init();

        $("#navi-tree-refresh").click(function(){
             CF.Plugins.astroable.refresh();
        });

        // fix for tab jump when open directly page with hash
        setTimeout(function() {
            if (location.hash) {
                window.scrollTo(0, 0);
            }
        }, 1);


    });
</script>
