var CHK_DashboardSetting = {};
CHK_DashboardSetting.displayItems = [
    { id:'newReport', name: 'chk-new', enabled: true, title:'新規報告', msg: 'dashboardSettingNewRegistrationTitle'},
    { id:'continousWork', name: 'chk-proccess', enabled: true, title:'工程作業', msg: 'dashboardSettingContinousWorkTitle'},
    { id:'reportWarning', name: 'chk-alert', enabled: true, title:'警告を含む作業', msg: 'dashboardSettingReportWarningTitle'},
    { id:'dashboardHome', name: 'chk-home', enabled: false, title:'ダッシュボードをホーム画面にする', msg: 'dashboardSettingDashboardHomeTitle'},
];

CHK_DashboardSetting.loadSettings = function() {
    CHK_DashboardSetting.displayItems.forEach(function(item) {
        let enabled = CHK.dashboardSetting[item.id];
        if (typeof enabled !== 'undefined') {
            item.enabled = enabled;
            let itemElement = $('#' + item.id);
            if (item.enabled) {
                itemElement.addClass('checked');
            } else {
                itemElement.removeClass('checked');
            }   
        }
    });
}

CHK_DashboardSetting.saveSetting = function(key, enabled) {
    CHK_DashboardSetting.displayItems.forEach(function(item) {
        if (item.id == key) {
            item.enabled = enabled;
        }
    });
    CHK.saveDashboardSetting(key, enabled);
}

CHK_DashboardSetting.initDisplays = function() {
    $("#displayItems tbody").empty();
    CHK_DashboardSetting.displayItems.forEach(function(item) {
        var html = CHK_DashboardSetting.initHtmlItem(item);
        $("#displayItems tbody").append(html);
    });
}

CHK_DashboardSetting.initHtmlItem = function(item) {
    var titleDiv = '<div class="font-weight-normal text-dark multi-lang" data-msg="' + item.msg + '">' + item.title +'</div>';
    var toggleClass = 'toggle';
    if (item.enabled) {
        toggleClass += ' checked';
    }
    var toggleDiv = '<div id="' + item.id + '" class="' + toggleClass + '"><input type="checkbox" name="' + item.name + '" /></div>';
    var html = $('<tr>' 
                + '<th>' + titleDiv + '</th>'
                + '<td>' +  toggleDiv + '</td>' 
                + '</tr>');
    return html;
}

CHK_DashboardSetting.bindToggleClick = function() {
    $(".toggle").on("click", function() {
        $(this).toggleClass("checked");
        var id = $(this).attr('id');
        var enabled = false;
        if ($(this).hasClass('checked')) {
            enabled = true;
        }
        CHK_DashboardSetting.saveSetting(id, enabled);
    });
}

CHK_DashboardSetting.init = function() {
    CHK.initCommon();
    CHK_DashboardSetting.initDisplays();
    CHK_DashboardSetting.bindToggleClick();
    $("#footer").load("main-footer.html", function() {
        CHK_Footer.activeDashboardBottomNav();
    });
    CHK.loadDashboardSetting(function() {
        CHK_DashboardSetting.loadSettings();
    });
}

CHK_DashboardSetting.goBack = function() {
    history.back();
}
