
var currentdashboardid="0";var currentdashboardtitle="";(function ensureInframeDefined(){if(typeof window.inframe==='undefined'){try{window.inframe=(window.self!==window.top);}
catch(e){window.inframe=true;}}})();function hard_reload(delay_ms){var go=function(){try{if(window.top&&window.top.location){window.top.location.reload();return;}}catch(e){}
try{window.location.replace(window.location.href);return;}catch(e2){}
window.location.href=window.location.href;};if(delay_ms&&delay_ms>0)setTimeout(go,delay_ms);else go();}
$(document).ready(function(){function collectFormData($form){var params={};$form.find(":input, :password, :radio, :submit, :reset").each(function(){var val=this.value;if($(this).is(":checkbox")&&!$(this).is(":checked")){val=0;}
params[this.name||this.id||this.parentNode.name||this.parentNode.id]=val;});params["nsp"]=nsp_str;return params;}
function generatePopupContent(options){options=options||{};options.title=options.title||'';options.message=options.message||'';options.showSpinner=options.showSpinner||false;options.form=options.form||'';options.headerStyle=options.headerStyle||'margin-bottom: 5px;';var content=`
            <div id='popup_header' style='${options.headerStyle}'>
                <b>${_(options.title)}</b>
            </div>
            <div id='popup_data'>
                ${options.message ? `<p>${_(options.message)}</p>` : ''}
                ${options.showSpinner ? `<i class='fa fa-spinner fa-pulse'></i>` : ''}
            </div>
            ${options.form}
        `;return content;}
$("#mydashboardsinit").each(function(){show_new_dashboard(0);});$("#mydashboards-page #leftnav").off('click.navclean').on('click.navclean','a:not(.mydashboardlink):not(.addnewdashboardlink)',function(){clear_dashboard_controls();update_dashboards_menu();unhighlight_dashboards_menu_items();});$("#leftnav").off('click.adddashboard').on('click.adddashboard','a.addnewdashboardlink',function(e){e.preventDefault();e.stopPropagation();show_throbber();var isDark=$('body').hasClass('xi5dark')||(typeof window.theme!=='undefined'&&window.theme==='xi5dark');var backgroundcolor=isDark?'111111':'ffffff';var apiVersion='v2';var canToggleGlobal=false;var userId=null;var isAdmin=!!(window.NAGIOS_IS_ADMIN);function esc(s){return String(s==null?'':s);}
function globalToggleMarkup(visible){return`
        <div id="globalToggleRow" class="popup-form-box" style="${visible ? '' : 'display:none;'}">
            <label for="is_global" style="margin-right:10px;">${_('Global')}</label>
            <label class="switch" style="vertical-align:middle;">
            <input type="checkbox" id="is_global" name="is_global" />
            <span class="slider round"></span>
            </label>
        </div>
        `;}
function typeSelectorMarkup(){return`
    <div class="popup-form-box">
        <div style="margin-bottom:6px;"><label>${_('Dashboard Type')}</label></div>

        <div class="radio-inline-group">
        <label class="radio-inline">
            <input type="radio" name="api_version" value="v2" checked /> ${_('Smart')}
        </label>
        <label class="radio-inline">
            <input type="radio" name="api_version" value="v1" /> ${_('Legacy')}
        </label>
        </div>
    </div>
    `;}
function legacyOptionsMarkup(){return`
        <div id="legacyOptions">
            <div class='popup-form-box'>
            <label for='backgroundcolor'>${_('Background Color')}</label>
            <input type='hidden' name='background' value='${backgroundcolor}' id='backgroundcolor' />
            <div id='colorpickerHolder2'>
                <div id='colorSelector2' style='float:left;'>
                <div style='background-color: #${backgroundcolor};'></div>
                </div>
                <span class='checkbox' style='float:left; margin: 6px 0 0 10px;'>
                <label>
                    <input type='checkbox' name='transparent' value='1' checked="checked" /> ${_('Transparent')}
                </label>
                </span>
            </div>
            </div>
        </div>
        `;}
var form=`
        <form id='adddashboard_form' method='post' action='${ajax_helper_url}'>
        <input type='hidden' name='cmd' value='adddashboard' />
        <input type='hidden' name='opts' value='' />
        <div class='popup-form-box'>
            <div><label for='adddashboardTitleBox'>${_('Dashboard Title')}</label></div>
            <input type='text' maxlength='255' size='30' name='title' id='adddashboardTitleBox' value='' class='form-control'/>
        </div>

        ${typeSelectorMarkup()}
        ${globalToggleMarkup(false)}
        ${legacyOptionsMarkup()}

        <div id='adddashboardFormButtons'>
            <button type='submit' class='btn btn-sm btn-primary' id='submitAddDashboardButton'>${_('Submit')}</button>
        </div>
        </form>
        <style>
        /* simple switch style for Global toggle */
        .switch{position:relative;display:inline-block;width:46px;height:24px}
        .switch input{display:none}
        .slider{position:absolute;cursor:pointer;top:0;left:0;right:0;bottom:0;background:#ccc;transition:.2s;border-radius:24px}
        .slider:before{position:absolute;content:"";height:18px;width:18px;left:3px;bottom:3px;background:white;transition:.2s;border-radius:50%}
        input:checked + .slider{background:#66bb6a}
        input:checked + .slider:before{transform:translateX(22px)}

        /* inline radio group for Smart/Legacy selector */
        #adddashboard_form .radio-inline-group { display:flex; align-items:center; gap:16px; }
        #adddashboard_form .radio-inline-group > label { display:inline-flex; align-items:center; margin:0; }
        #adddashboard_form .radio-inline-group input[type="radio"] { margin-right:6px; }
        </style>
    `;var content=generatePopupContent({title:_('Add Dashboard'),message:_('Use this to add a new dashboard to your Dashboards page.'),form:form});hide_throbber();set_popup_content(content);display_popup();$('#legacyOptions').hide();maybeShowGlobalToggle();if(typeof window.NAGIOS_IS_ADMIN==='undefined'&&typeof window.NAGIOS_USERLEVEL==='undefined'){$.get('/nagiosxi/ajaxhelper.php',{cmd:'getusermeta',opts:'userlevel',nsp:nsp_str}).done(function(lvl){var num=parseInt(lvl,10);var L_GLOBALADMIN=(typeof window.NAGIOS_L_GLOBALADMIN!=='undefined')?Number(window.NAGIOS_L_GLOBALADMIN):255;if(!isNaN(num)&&num>=L_GLOBALADMIN){isAdmin=true;}}).always(maybeShowGlobalToggle);}
$('#adddashboardTitleBox').focus();$("#colorSelector2").ColorPicker({onSubmit:function(hsb,hex,rgb,el){$("#backgroundcolor").val(hex);$(el).ColorPickerHide();$('#colorSelector2 div').css('backgroundColor','#'+hex);if($("input[name='transparent']").is(":checked")){$("input[name='transparent']").prop("checked",false);}},onBeforeShow:function(){$(this).ColorPickerSetColor($("#backgroundcolor").val());},onShow:function(colpkr){$(colpkr).fadeIn(200);return false;},onHide:function(colpkr){$(colpkr).fadeOut(200);return false;},onChange:function(hsb,hex,rgb){$("#backgroundcolor").val(hex);$('#colorSelector2 div').css('backgroundColor','#'+hex);if($("input[name='transparent']").is(":checked")){$("input[name='transparent']").prop("checked",false);}}});$.get('/nagiosxi/ajaxhelper.php',{cmd:'getusermeta',opts:'global_dashboard_access','default':1,nsp:nsp_str}).done(function(v){var metaNum=parseInt(v,10);if(!isNaN(metaNum)&&metaNum>=2)canToggleGlobal=true;maybeShowGlobalToggle();}).always(maybeShowGlobalToggle);$.get('/nagiosxi/ajaxhelper.php',{cmd:'getuserid',nsp:nsp_str}).done(function(uid){userId=uid;});function maybeShowGlobalToggle(){var show=(apiVersion==='v2')&&(isAdmin||canToggleGlobal);$('#globalToggleRow').toggle(!!show);}
$(document).on('change',"input[name='api_version']",function(){apiVersion=$(this).val()==='v1'?'v1':'v2';if(apiVersion==='v1'){$('#legacyOptions').show();}else{$('#legacyOptions').hide();}
maybeShowGlobalToggle();});$("#adddashboard_form").off('submit').on('submit',function(e){e.preventDefault();var title=esc($('#adddashboardTitleBox').val()).trim();if(!title){$('#adddashboardTitleBox').addClass('input-error');return false;}
var selectedApiVersion=$("input[name='api_version']:checked").val()==='v1'?'v1':'v2';var globalRowVisible=$('#globalToggleRow:visible').length>0;var makeGlobal=globalRowVisible&&$('#is_global').prop('checked');var background=$('#backgroundcolor').val();var transparent=$("input[name='transparent']").is(":checked")?1:0;set_popup_content(generatePopupContent({title:_('Please Wait'),message:_('Processing'),showSpinner:true}));resize_popup();if(selectedApiVersion==='v1'){var params={cmd:'adddashboard',opts:'',title:title,background:background,transparent:transparent,nsp:nsp_str};$.ajax({type:"POST",url:ajax_helper_url,data:params}).done(onSuccess).fail(onError);}else{var payload={name:title,nsp:nsp_str};if(userId!=null&&userId!==''&&!makeGlobal){payload.user_id=userId;}
if(globalRowVisible){payload.is_global=makeGlobal?1:0;}
$.ajax({method:'POST',url:'/nagiosxi/api/v2/dashboards_v2',data:payload,}).done(onSuccess).fail(onError);}
return false;});function onSuccess(){set_popup_content(generatePopupContent({title:_('Dashboard Added'),message:_('Success! Your new dashboard has been added.')}));resize_popup();update_dashboards_menu&&update_dashboards_menu();fade_popup("green");setTimeout(function(){if(currentdashboardid==="nodashboardid"){show_new_dashboard(0);}else{location.reload();}},1200);update_dashboards_menu();fade_popup("green");}
function onError(){set_popup_content(generatePopupContent({title:_('Failed to add dashboard.'),message:_('Please try again.')}));resize_popup();}});$(".edit-dashboard").click(function(){var id=$(this).parent().data('id');var title=$(this).parent().data('title');whiteout();show_throbber();var viewdata=get_ajax_data("getdashboardbyid",id);eval('var viewobj='+viewdata);var backgroundcolor=viewobj.background;var checked="";if(viewobj.transparent){checked=" checked='checked'";}
var editDashboardForm=`
            <form id='editdashboard_form' method='get' action='${ajax_helper_url}'>
                <input type='hidden' name='cmd' value='updatedashboard'>
                <input type='hidden' id='editdashboardId' name='id' value=''>
                <input type='hidden' name='opts' value=''>
                <div class='popup-form-box'>
                    <div>
                        <label for='editdashboardTitleBox'>${_('Dashboard Title')}</label>
                    </div>
                    <input type='text' maxlength='255' size='30' name='title' id='editdashboardTitleBox' value='' class='form-control'>
                </div>
                <div class='popup-form-box'>
                    <label for='backgroundcolor'>${_('Background Color')}</label>
                    <input type='hidden' name='background' value='${backgroundcolor}' id='backgroundcolor'>
                    <div id='colorpickerHolder2'>
                        <div id='colorSelector2' style='float: left;'>
                            <div style='background-color: #${backgroundcolor};'></div>
                        </div>
                        <span class='checkbox' style='float: left; margin: 6px 0 0 10px;'>
                            <label>
                                <input type='checkbox' name='transparent' value='1'${checked}> ${_('Transparent')}
                            </label>
                        </span>
                    </div>
                </div>
                <div id='editdashboardFormButtons'>
                    <input type='submit' class='btn btn-sm btn-primary' name='submitButton' value='${_('Submit')}' id='submitEditDashboardButton'>
                </div>
            </form>
        `;var content=generatePopupContent({title:_('Edit Dashboard'),form:editDashboardForm});hide_throbber();set_child_popup_content(content);$('#editdashboardId').val(id);$('#editdashboardTitleBox').val(title);resize_child_popup();display_child_popup();$("#colorSelector2").ColorPicker({onSubmit:function(hsb,hex,rgb,el){var x=1;$("#backgroundcolor").val(hex);$(el).val(hex);$(el).ColorPickerHide();$('#colorSelector2 div').css('backgroundColor','#'+hex);if($("input[name='transparent']").is(":checked")){$("input[name='transparent']").prop("checked",false);}},onBeforeShow:function(){var y=1;$(this).ColorPickerSetColor($("#backgroundcolor").val());},onShow:function(colpkr){$(colpkr).fadeIn(500);return false;},onHide:function(colpkr){$(colpkr).fadeOut(500);return false;},onChange:function(hsb,hex,rgb){$("#backgroundcolor").val(hex);$('#colorSelector2 div').css('backgroundColor','#'+hex);if($("input[name='transparent']").is(":checked")){$("input[name='transparent']").prop("checked",false);}}});$("#editdashboard_form").submit(function(){hide_throbber();var params=collectFormData($(this));$.ajax({type:"POST",url:this.getAttribute("action"),data:params,beforeSend:function(XMLHttpRequest){set_child_popup_content(generatePopupContent({title:_('Please Wait'),message:_('Processing'),showSpinner:true}));resize_child_popup();},success:function(msg){set_child_popup_content(generatePopupContent({title:_('Dashboard Changes Saved'),message:_('Success! Your dashboard was updated successfully.')}));resize_child_popup();clear_whiteout();hard_reload(200);fade_child_popup("green");update_dashboards_menu();window.location.reload();location.reload();},error:function(msg){set_child_popup_content(generatePopupContent({title:_('Error'),message:_('An error occurred processing your request.')}));resize_child_popup();}});return false;});});$(".remove-dashboard").click(function(){var id=$(this).parent().data('id');whiteout();show_throbber();if(currentdashboardid=="home"){var content=generatePopupContent({title:_('Error'),message:_('You cannot delete your home page dashboard.')});hide_throbber();set_popup_content(content);display_popup();fade_popup("red",2000);return;}
var deleteDashboardForm=`
            <form id='deletedashboard_form' method='get' action='${ajax_helper_url}'>
                <input type='hidden' name='cmd' value='deletedashboardbyid'>
                <input type='hidden' name='opts' value='${id}'>
                <div id='editdashboardFormButtons'>
                    <input type='submit' class='btn btn-sm btn-primary' name='submitButton' value='${_('Delete')}' id='submitDeleteDashboardButton'> 
                    <input type='button' class='btn btn-sm btn-default close_child_popup_btn' name='cancelButton' value='${_('Cancel')}' style='margin-left: 5px;'>
                </div>
            </form>
        `;var content=generatePopupContent({title:_('Confirm Dashboard Deletion'),message:_('Are you sure you want to delete this dashboard and all dashlets it contains?'),headerStyle:'padding-bottom: 10px;',form:deleteDashboardForm});hide_throbber();set_child_popup_content(content);display_child_popup();$("#deletedashboard_form").submit(function(){hide_throbber();var params=collectFormData($(this));$.ajax({type:"POST",url:this.getAttribute("action"),data:params,beforeSend:function(XMLHttpRequest){set_child_popup_content(generatePopupContent({title:_('Please Wait'),showSpinner:true}));},success:function(msg){set_child_popup_content(generatePopupContent({title:_('Dashboard Deleted'),message:_('The requested dashboard has been deleted.')}));clear_whiteout();fade_popup("red");update_dashboards_menu();location.reload();},error:function(msg){set_child_popup_content(generatePopupContent({title:_('Error'),message:_('An error occurred processing your request.')}));}});return false;});});$(".clone-dashboard").click(function(){var id=$(this).parent().data('id');var title=$(this).parent().data('title')+' ('+_('Clone')+')';whiteout();show_throbber();var cloneDashboardForm=`
            <form id='clonedashboard_form' method='get' action='${ajax_helper_url}'>
                <input type='hidden' name='cmd' value='clonedashboardbyid'>
                <input type='hidden' name='opts' value='${id}'>
                <div class='popup-form-box'>
                    <div>
                        <label for='clonedashboardTitleBox'>${_('New Title')}</label>
                    </div>
                    <input type='text' size='30' maxlength="255" name='title' id='clonedashboardTitleBox' value="${title}" class='form-control'>
                </div>
                <div id='clonedashboardFormButtons'>
                    <input type='submit' class='btn btn-sm btn-primary' name='submitButton' value='${_('Clone')}' id='submitCloneDashboardButton'>
                </div>
            </form>
        `;var content=generatePopupContent({title:_('Clone Dashboard'),message:_('Use this to make an exact clone of the current dashboard and all its wonderful dashlets.'),headerStyle:'padding-bottom: 5px;',form:cloneDashboardForm});hide_throbber();set_child_popup_content(content);display_child_popup();$("#clonedashboard_form").submit(function(){hide_throbber();var params=collectFormData($(this));$.ajax({type:"POST",url:this.getAttribute("action"),data:params,beforeSend:function(XMLHttpRequest){set_child_popup_content(generatePopupContent({title:_('Please Wait'),showSpinner:true}));},success:function(msg){set_child_popup_content(generatePopupContent({title:_('Dashboard Cloned'),message:_('Dashboard successfully cloned.')}));fade_child_popup("green");update_dashboards_menu();setTimeout(function(){location.reload();window.parent.location.reload();},1000);},error:function(msg){set_child_popup_content(generatePopupContent({title:_('Error'),message:_('An error occurred processing your request.')}));}});return false;});});$(".export-dashboard").click(function(){var id=$(this).parent().data('id');var title=$(this).parent().data('title')+' dashboard';whiteout();show_throbber();var exportDashboardForm=`
            <form id='exportdashboard_form' method='get' action='${ajax_helper_url}'>
                <input type='hidden' name='cmd' value='getrawdashboardbyid'>
                <input type='hidden' name='opts' value='${id}'>
                <div class='popup-form-box'>
                    <div>
                        <label for='exportdashboardTitleBox'>${_('Title in export file')}</label>
                    </div>
                    <input type='text' size='30' name='title' id='exportdashboardTitleBox' value='${title}' class='form-control'>
                </div>
                <div id='exportdashboardFormButtons'>
                    <input type='submit' class='btn btn-sm btn-primary' name='submitButton' value='${_('Export')}' id='submitExportDashboardButton'>
                </div>
            </form>
        `;var content=generatePopupContent({title:_('Export Dashboard'),message:_('Use this to export an exact clone of the current dashboard and all its wonderful dashlets.'),headerStyle:'padding-bottom: 5px;',form:exportDashboardForm});hide_throbber();set_child_popup_content(content);display_child_popup();$("#exportdashboard_form").submit(function(){hide_throbber();var params=collectFormData($(this));$.ajax({type:"POST",url:this.getAttribute("action"),data:params,beforeSend:function(XMLHttpRequest){set_child_popup_content(generatePopupContent({title:_('Please Wait'),showSpinner:true}));},success:function(msg){if(msg==false||msg==''){set_child_popup_content(generatePopupContent({title:_('Error'),message:_('An error occurred processing your request.')}));return;}
const link=document.createElement("a");const file=new Blob([msg],{type:'text/plain'});link.href=URL.createObjectURL(file);link.download=`${(params.title || "dashboard")}.txt`;link.click();URL.revokeObjectURL(link.href);set_child_popup_content(generatePopupContent({title:_('Dashboard Exported'),message:_('Dashboard successfully Exported.')}));fade_child_popup("green");update_dashboards_menu();$("#whiteout").remove();},error:function(msg){set_child_popup_content(generatePopupContent({title:_('Error'),message:_('An error occurred processing your request.')}));}});return false;});});var dashboard_file_text='';var isValidDashFile=false;$("#importfile").change(function(){var file=$(this).prop('files')[0];if(!file){isValidDashFile=false;return;}
if(file.name.split('.').pop()!='txt'){isValidDashFile=false;return;}
if(file.type!='text/plain'){isValidDashFile=false;return;}
isValidDashFile=true;var fr=new FileReader();fr.onload=function(e){dashboard_file_text=e.target.result;$("#importString").val(file.name);};fr.readAsText(file);});$("#importdashboard_form").submit(function(){hide_throbber();if(!isValidDashFile){alert(_('File Is Not a Valid Dashboard File!'));return false;}
var params={cmd:'importdashboard',importstring:dashboard_file_text,nsp:nsp_str};$.ajax({type:"POST",url:this.getAttribute("action"),data:params,beforeSend:function(XMLHttpRequest){whiteout();show_throbber();set_child_popup_content(generatePopupContent({title:_('Please Wait'),showSpinner:true}));display_child_popup();},success:function(msg){hide_throbber();set_child_popup_content(generatePopupContent({title:_('Dashboard Imported'),message:_('Dashboard successfully Imported.')}));fade_child_popup("green");update_dashboards_menu();$("#importString").val(null);$("#whiteout").remove();},error:function(msg){hide_throbber();set_child_popup_content(generatePopupContent({title:_('Error'),message:_('File Is Not a Valid Dashboard File!')}));display_child_popup();}});return false;});$("#leftnav").on('click','a.mydashboardlink',function(){handle_dashboard_menu_click(this);return;});$(".add-dashlet").click(function(){$("#dashletModal").fadeIn();});});function update_dashboards_menu()
{try{var html=get_ajax_data("getdashboardsmenuhtml","");var targets=['ul#mydashboardsmenu','ul#legacymenu'];function applyTo(doc){var updated=false;for(var i=0;i<targets.length;i++){var $ul=$(targets[i],doc);if($ul.length){$ul.html(html);updated=true;}}
return updated;}
var done=false;if(window.inframe){try{done=applyTo(parent.document);}catch(e){}}
if(!done)applyTo(document);}catch(e){}}
function handle_dashboard_menu_click(obj)
{var theparent=obj.parentNode;var url=obj.href;var title=obj.innerHTML;var rawid=obj.id;var id=rawid.substr(10);fill_dashboard_screen(title,url,id);var x=1;return;}
function fill_dashboard_screen(title,url,id,background)
{update_dashboards_menu();highlight_dashboards_menu_item("dashboard-"+id);$("#trashdashboard").css("visibility","visible");$("#editdashboard").css("visibility","visible");$("#clonedashboard").css("visibility","visible");$("#maincontentframe").attr({src:url});currentdashboardid=id;currentdashboardtitle=title;}
function show_new_dashboard(num)
{var viewdata=get_ajax_data("getdashboardbynum",num);eval('var viewobj='+viewdata);fill_dashboard_screen(viewobj.title,viewobj.url,viewobj.id,viewobj.background);currentdashboardnum=num;}
function show_new_dashboard_id(id)
{var viewdata=get_ajax_data("getdashboardbyid",id);eval('var viewobj='+viewdata);fill_dashboard_screen(viewobj.title,viewobj.url,viewobj.id,viewobj.background);currentdashboardnum=viewobj.number;}
function clear_dashboard_controls()
{$("#trashdashboard").css("visibility","hidden");$("#editdashboard").css("visibility","hidden");$("#clonedashboard").css("visibility","hidden");}
function highlight_dashboards_menu_item(id)
{$("#"+id).addClass("activemenulink");}
function unhighlight_dashboards_menu_items()
{$("#mydashboards-page #leftnav a.mydashboardlink").removeClass("activemenulink");}