<script type="text/javascript">
    var empty_pool = [];
    var a = [];
    var pool = [];
    var absent_replics = [];
    var saved_description = "";
    var saved_description_unused = "";
    var saved_description_free = "";
    var select_color = "blue";
    var global_id = "";
    var service_cgi = "<?php echo $service_cgi ?>";
    var service_type_cgi = "<?php echo $service_type_cgi ?>";
    var ctype_cgi = "<?php echo $ctype_cgi; ?>";
    var add_replica_selected_dc = [];
    var filter_check_boxes = [
        {"caption" : "sources", "filter":"result.search_sources_count", "default": true},
        {"caption" : "docs in final", "filter":"result.docs_in_final_indexes", "default": true},
        {"caption" : "docs in mem", "filter":"result.docs_in_memory_indexes", "default": true},
        {"caption" : "docs in disk", "filter":"result.docs_in_disk_indexes", "default": false},
        {"caption" : "size", "filter":"result.files_size.__SUM", "default": false},
        {"caption" : "uptime", "filter":"result.controller_uptime", "default": true},
        {"caption" : "mem", "filter":"result.mem_size_real", "default": false},
        {"caption" : "slot size", "filter":"result.slot.container.constraints.memory_limit", "default": false},
        {"caption" : "mem total", "filter":"result.total_mem_size", "default": false},
        {"caption" : "cpu", "filter":"result.cpu_load_user", "default": false},
        {"caption" : "cpu_policy", "filter":"result.slot.container.constraints.cpu_policy", "default": false},
        {"caption" : "cpu_limit", "filter":"result.slot.container.constraints.cpu_limit", "default": false},
        {"caption" : "la", "filter":"result.load_average", "default": false},
        {"caption" : "disk_index_rps", "filter":"result.disk_index_rps.30", "default": false},
        {"caption" : "memory_index_rps", "filter":"result.memory_index_rps.30", "default": false},
        {"caption" : "search_rps_failed", "filter":"result.search_rps_failed.30", "default": false},
        {"caption" : "search_rps_http", "filter":"result.search_rps_http.30", "default": false},
        {"caption" : "search_rps_neh", "filter":"result.search_rps_neh.30", "default": false},
        {"caption" : "search_rps_neh_base", "filter":"result.search_rps_neh_base.30", "default": false},
        {"caption" : "nanny_service", "filter":"result.slot.properties.NANNY_SERVICE_ID", "default": false}
    ];

    var filter_cgi_exists = <?php echo array_key_exists("filter", $_GET) ? "true" : "false";?>;
    var filter_cgi = "<?php if (array_key_exists("filter", $_GET)) echo $_GET["filter"];?>";

    window.onload = function() {
        var filterHtml = "";
        var filters = [];
        if (filter_cgi_exists) {
            filters = filter_cgi.split(",");
        }
        for(var c = 0, l = filter_check_boxes.length; c < l; ++c) {
            var cb = filter_check_boxes[c];
            filterHtml += "<label style=\"white-space:nowrap;\"><input type='checkbox' id='" + cb.filter + "'";
            if ((filter_cgi_exists &&filters.indexOf(cb.filter) >= 0) || (!filter_cgi_exists && cb.default))
                filterHtml += " checked";
            filterHtml += "/>" + cb.caption + "</label> ";
        }
        document.getElementById("filter_cboxes").innerHTML = filterHtml;
        disable_links = false;
        if (service_type_cgi != "metaservice") {
            koolajax.callback(build_cluster_structure(getBuildClusterStructureParams(false)), onDoneRebuild);
            if (service_type_cgi == "rtyserver") {
                koolajax.callback(build_cluster_structure(getBuildClusterStructureParams(true)), onDoneRebuildUnused);
                onDoneRebuildFree(JSON.parse('{"success":false}'));
            }
        }
        koolajax.callback(build_tasks_list(), onDoneRebuildTaskList);
        koolajax.callback(task_check(global_id), onTaskInfoGet);
        a = [];
        refresh_replace_intervals_OnClick();
    };

    function btn_release_OnClick() {
        document.getElementById("release_btn").disabled = true;
        document.getElementById("release_btn").value = "In progress...";
        var shouldDeploy = document.getElementById("deploy_checkbox").checked;
        koolajax.callback(do_release(get_iface_data(a), shouldDeploy), onDoneAction);
    }

    function btn_clear_index_OnClick() {
        var result = confirm("Уверены?!!!!!");
        if (result == true) {
            document.getElementById("clear_index_btn").disabled = true;
            document.getElementById("clear_index_btn").value = "In progress...";
            koolajax.callback(do_clear_index(get_iface_data(a)), onDoneCheck);
        }
    }

    function btn_clear_queues_OnClick() {
        var result = confirm("Уверены?!!!!!");
        if (result == true) {
            document.getElementById("clear_queues_btn").disabled = true;
            document.getElementById("clear_queues_btn").value = "In progress...";
            koolajax.callback(do_clear_queues(), onDoneInfo);
        }
    }

    function btn_restart_OnClick() {
        var result = confirm("Уверены?!!!!!");
        if (result == true) {
            document.getElementById("restart_btn").disabled = true    ;
            document.getElementById("restart_btn").value = "In progress...";
            koolajax.callback(do_restart(get_iface_data(a)), onDoneCheck);
        }
    }

    function build_intervals() {
        var form = document.forms.intervals_list_form;
        var result = "";
        for (var i = 0, l = form.elements.length; i < l; i++) {
            var value = form.elements[i].value;
            var key = form.elements[i].name;
            if (value != "" && key != "" && value != key) {
                result += "&interval=" + key + "->" + value;
            }
        }
        return result;
    }

    function btn_modify_searchmap_OnClick() {
        document.getElementById("modify_searchmap_btn").disabled = true;
        document.getElementById("modify_searchmap_btn").value = "In progress...";
        var searchAction = document.getElementById("enabled_search_checkbox").checked ? "enable_search" : "disable_search";
        var indexAction = document.getElementById("enabled_index_checkbox").checked ? "enable_indexing" : "disable_indexing";
        var action = searchAction + "," + indexAction;
        var intervals = build_intervals();
        if (intervals != "") {
            action += ",replace_intervals" + intervals;
        }
        var shouldDeploy = document.getElementById("deploy_checkbox").checked;
        var degradeLevel = document.getElementById("cmb_percent").value;
        koolajax.callback(do_modify_searchmap(get_iface_data(a), action, shouldDeploy, degradeLevel), onDoneAction);
    }

    function btn_copy_OnClick() {
        document.getElementById("copy_btn").disabled = true;
        document.getElementById("copy_btn").value = "In progress...";
        var degradeLevel = document.getElementById("cmb_percent").value;
        koolajax.callback(do_copy(get_iface_data(a), get_iface_data(pool), degradeLevel), onDoneAction);
    }

    function btn_replace_OnClick() {
        document.getElementById("replace_btn").disabled = true;
        document.getElementById("replace_btn").value = "In progress...";
        var degradeLevel = document.getElementById("cmb_percent").value;
        var shouldDeploy = document.getElementById("deploy_checkbox").checked;
        koolajax.callback(do_replace(get_iface_data(a), get_iface_data(pool), get_iface_data(absent_replics), shouldDeploy, degradeLevel), onDoneAction);
    }

    function btn_restore_OnClick() {
        document.getElementById("restore_btn").disabled = true;
        document.getElementById("restore_btn").value = "In progress...";
        var degradeLevel = document.getElementById("cmb_percent").value;
        var shouldDeploy = document.getElementById("deploy_checkbox").checked;
        koolajax.callback(do_restore(get_iface_data(a), shouldDeploy, degradeLevel), onDoneAction);
    }

    function get_slots_array(arr) {
        var phpInfo = [];
        for (var i = 0; i < arr.length; ++i) {
            if (arr[i] !== "" && arr[i] !== undefined) {
                phpInfo.push(arr[i]);
            }
        }
        return phpInfo;
    }

    function get_iface_data(arr) {
        return JSON.stringify(get_slots_array(arr));
    }

    function getBuildClusterStructureParams(unused) {
        var result = {};
        result.unused = unused;
        result.full_info_about_unused = document.getElementById("full_info_about_unused").checked;
        result.only_problem = document.getElementById(unused ? "only_problem_unused" : "only_problem_used").checked;
        if (filter_cgi_exists) {
            result.filters = filter_cgi.split(",");
        } else {
            result.filters = [];
            for(var c = 0; c < filter_check_boxes.length; ++c) {
                var cb = filter_check_boxes[c];
                if (document.getElementById(cb.filter).checked)
                    result.filters.push(cb.filter);
            }
        }
        return JSON.stringify(result);
    }

    function onDoneRebuild(s) {
        if (s != null && s !== saved_description) {
            document.getElementById("cluster_structure").innerHTML = s;
            saved_description = s;
            for (var i = 0; i < a.length; ++i) {
                var element = document.getElementById(a[i]);
                if (element !== null) {
                    element.style.color = select_color;
                } else {
                    a.splice(i, 1);
                    i--;
                }
            }
            for (var i = 0; i < absent_replics.length; ++i) {
                var element = document.getElementById("absent_replic_" + absent_replics[i]);
                if (element !== null) {
                    element.style.color = select_color;
                } else {
                    absent_replics.splice(i, 1);
                    i--;
                }
            }
        }
        setTimeout(function() {
            koolajax.callback(build_cluster_structure(getBuildClusterStructureParams(false)), onDoneRebuild);
        }, 1000);
    }

    function onDoneRebuildUnused(s) {
        if (s != null && s !== saved_description_unused) {
            document.getElementById("cluster_structure_unused").innerHTML = s;
            saved_description_unused = s;
            for (var i = 0; i < pool.length; ++i) {
                var element = document.getElementById(pool[i]);
                if (element !== null) {
                    element.style.color = select_color;
                } else {
                    pool.splice(i, 1);
                    i--;
                }
            }
        }
        setTimeout(function() {
            koolajax.callback(build_cluster_structure(getBuildClusterStructureParams(true)), onDoneRebuildUnused);
        }, 1000);
    }

    function setAddReplicaFreeSlotsHtml(s) {
        var cluster_free_info = JSON.parse(s);
        var result_html = "<table><tr>";
        if (ctype_cgi in cluster_free_info) {
            var byDc = cluster_free_info[ctype_cgi];
            for (var dc in byDc) {
                var free_slots = 0;
                var servers = 0;
                var cluster = byDc[dc];
                for (var server in cluster) {
                    free_slots += Object.keys(cluster[server]).length;
                    ++servers;
                }
                var checked = add_replica_selected_dc.indexOf(dc) >= 0;
                result_html += "<td><label><input" +
                               " id='add_replica_" + dc + "_cb'" +
                               " type='checkbox'" +
                               " onclick=\"onAddReplicaDcCheckboxClick('" + dc + "')\"" +
                               (checked ? " checked" : "") +
                               "/>";
                result_html += dc + " (" + servers + "/" + free_slots + ")</label></td>";
            }
        }
        result_html += "</tr></table>";
        document.getElementById("add_replica_free_slots").innerHTML = result_html;
    }

    function onDoneRebuildFree(s) {
        if (s !== null && s.success && s.reply !== saved_description_free) {
            setAddReplicaFreeSlotsHtml(s.reply);
            saved_description_free = s.reply;
        }
        var request = "free_slots?" +
                      "&service=" + service_cgi +
                      "&service_type=" + service_type_cgi +
                      "&ctype=" + ctype_cgi;
        setTimeout(function() {
            koolajax.callback(get_request_from_dm(request), onDoneRebuildFree);
        }, 1000);
    }

    function onDoneAction(s) {
        global_id = s.trim();
        if (global_id != "") {
            document.getElementById("status_task").innerHTML = "attaching " + global_id + "...";
        }
        koolajax.callback(task_check(global_id), onDoneCheck);
    }

    function onDoneInfo(s) {
        document.getElementById("status_task").innerHTML = s;
    }

    function enableBtn(name, caption) {
        var btn = document.getElementById(name);
        if (btn != null) {
            btn.value = caption;
            btn.disabled = false;
        }
    }

    function btnInProcess(name) {
        var btn = document.getElementById(name);
        if (btn != null) {
            btn.value = "in progress...";
            btn.disabled = true;
        }
    }

    function onDoneCheck(s) {
        var event = JSON.parse(s);
        if (event.is_finished === true) {
            enableBtn("copy_btn", "copy");
            enableBtn("release_btn", "release");
            enableBtn("restore_btn", "restore");
            enableBtn("replace_btn", "replace");
            enableBtn("restart_btn", "restart");
            enableBtn("clear_index_btn", "clear_index");
            enableBtn("modify_searchmap_btn", "Send");
            enableBtn("btn_add_replica", "Добавить реплики");
            enableBtn("btn_deploy", "Deploy");
            enableBtn("btn_deploy_sp", "Deploy SP");
            enableBtn("btn_deploy_ip", "Deploy IP");
            refresh_replace_intervals_OnClick();
        } else {
            setTimeout(function() {
                koolajax.callback(task_check(event.id_task), onDoneCheck);
            }, 1000);
        }
    }

    function updateSlotsCountsPanel() {
        document.getElementById("used_slots_count").innerHTML = a.length + absent_replics.length;
        document.getElementById("unused_slots_count").innerHTML = pool.length;
        var panelElement = document.getElementById("selected_slots_counts");
        if (a.length == 0 && pool.length == 0 && absent_replics.length == 0) {
            panelElement.style.display = "none";
        } else {
            panelElement.style.display = "inline";
        }
    }

    function click_select(s) {
        var i = a.indexOf(s);
        if (i === -1) {
            a.push(s);
            document.getElementById(s).style.color = select_color;
        } else {
            a.splice(i, 1);
            document.getElementById(s).style.color = "black";
        }
        updateSlotsCountsPanel();
    }

    function click_select_absent(s) {
        var i = absent_replics.indexOf(s);
        if (i === -1) {
            absent_replics.push(s);
            document.getElementById('absent_replic_' + s).style.color = select_color;
        } else {
            absent_replics.splice(i, 1);
            document.getElementById('absent_replic_' + s).style.color = "black";
        }
        updateSlotsCountsPanel();
    }

    function click_select_pool(s) {
        var i = pool.indexOf(s);
        if (i === -1) {
            pool.push(s);
            document.getElementById(s).style.color = select_color;
        } else {
            pool.splice(i, 1);
            document.getElementById(s).style.color = "black";
        }
        updateSlotsCountsPanel();
    }

    function btn_add_replica_OnClick() {
        var form = document.getElementById("add_replica_form");
        var count_slots = form.slots_count.value;
        var count_replicas = form.replicas_count.value;
        var allocator = Object();
        allocator.one_slot_on_server = form.one_slot_on_server.checked;
        allocator.allow_same_host_replica = form.allow_same_host_replica.checked;
        switch(form.add_replica_allocator.value) {
        case "dc":
            allocator.pref_dcs = add_replica_selected_dc;
            allocator.pref_dc_only = true;
            break;
        case "selected":
            allocator.custom_slots = get_slots_array(pool);
            if (allocator.custom_slots.length === 0) {
                alert("select at least one slot");
                return;
            }
            break;
        default:
            alert("unknown allocator type" + form.add_replica_allocator.value);
            return;
        }

        document.getElementById("btn_add_replica").value = "in progress...";
        document.getElementById("btn_add_replica").disabled = true;
        var degradeLevel = document.getElementById("cmb_percent").value;
        koolajax.callback(add_replica_start(count_slots, count_replicas, JSON.stringify(allocator), form.restore.checked ? "1" : "0", form.deploy_proxies.checked ? "1" : "0", degradeLevel), onDoneAction);
    }

    function onAddReplicaDcCheckboxClick(s) {
        var i = add_replica_selected_dc.indexOf(s);
        document.getElementById("add_replica_allocator_dc").checked = true;
        if (i === -1) {
            add_replica_selected_dc.push(s);
        } else {
            add_replica_selected_dc.splice(i, 1);
        }
        document.getElementById("add_replica_replicas_count").value = add_replica_selected_dc.length;
    }

    function onDoneSendTagsInfo(res) {
        var lable = document.getElementById("send_tags_info_result");
        if (res.success) {
            lable.innerHTML = "OK";
        } else {
            lable.innerHTML = "ERROR (" + res.reply + ")";
        }
        enableBtn("btn_send_tags_info", "Отослать");
        enableBtn("btn_invalidate_tags_info", "Сбросить кэш");
    }

    function sendTagsInfo(action) {
        var form = document.getElementById("tags_info_form");
        var slots = form.slots.value;
        var exclude = form.exclude.value;
        var use_containers = form.use_container_names.checked;
        var nanny_services = form.nanny_services.value;
        var endpointsets = form.endpointsets.value;
        document.getElementById("btn_send_tags_info").disabled = true;
        document.getElementById("btn_invalidate_tags_info").disabled = true;
        var request = "modify_tags_info?" +
                      "action=" + action +
                      "&slots=" + slots +
                      "&exclude=" + exclude +
                      "&nanny_services=" + nanny_services +
                      "&endpointsets=" + endpointsets +
                      "&use_container_names=" + use_containers +
                      "&service=" + service_cgi +
                      "&service_type=" + service_type_cgi +
                      "&ctype=" + ctype_cgi;
        koolajax.callback(get_request_from_dm(request), onDoneSendTagsInfo);
    }

    function btn_send_tags_info_OnClick() {
        document.getElementById("btn_send_tags_info").value = "Отсылка...";
        sendTagsInfo("set");
    }

    function btn_invalidate_tags_info_OnClick() {
        document.getElementById("btn_invalidate_tags_info").value = "Сброс...";
        sendTagsInfo("invalidate");
    }

    function btn_deploy_OnClick() {
        document.getElementById("btn_deploy").value = "rty deploing...";
        document.getElementById("btn_deploy").disabled = true;
        if (document.getElementById("btn_deploy_sp") != null)
            document.getElementById("btn_deploy_sp").disabled = true;
        if (document.getElementById("btn_deploy_ip") != null)
            document.getElementById("btn_deploy_ip").disabled = true;
        var slotParam = document.getElementById("cb_only_save").checked ? "&slots=[]" : "";
        koolajax.callback(deploy_start("rtyserver", document.getElementById("cmb_percent").value, slotParam), onDoneAction);
    }

    function btn_deploySP_OnClick() {
        document.getElementById("btn_deploy_sp").value = "sp deploing...";
        document.getElementById("btn_deploy_sp").disabled = true;
        document.getElementById("btn_deploy_ip").disabled = true;
        document.getElementById("btn_deploy").disabled = true;
        var slotParam = document.getElementById("cb_only_save").checked ? "&slots=[]" : "";
        koolajax.callback(deploy_start("searchproxy", document.getElementById("cmb_percent").value, slotParam), onDoneAction);
    }

    function btn_deployIP_OnClick() {
        document.getElementById("btn_deploy_ip").value = "ip deploing...";
        document.getElementById("btn_deploy_ip").disabled = true;
        document.getElementById("btn_deploy_sp").disabled = true;
        document.getElementById("btn_deploy").disabled = true;
        var slotParam = document.getElementById("cb_only_save").checked ? "&slots=[]" : "";
        koolajax.callback(deploy_start("indexerproxy", document.getElementById("cmb_percent").value, slotParam), onDoneAction);
    }

    var disable_links = false;

    function onTaskInfoGet(s) {
        var event = JSON.parse(s);
        if (event !== null && "is_finished" in event && event.is_finished === true) {
            if (event.report != "") {
                document.getElementById("status_task").innerHTML = "FINISHED<br>" + event.report;
                global_id = "";
            }
        } else if (event !== null && "report" in event) {
            document.getElementById("status_task").innerHTML = event.report;
        } else
            document.getElementById("status_task").innerHTML = s;

        setTimeout(function() {
            koolajax.callback(task_check(global_id), onTaskInfoGet);
        }, 1000);

    }

    function btn_attach_task_OnClick(id) {
        global_id = id;
        disable_links = false;
        document.getElementById("status_task").innerHTML = "attaching " + global_id + "...";
        return false;
    }

    function btn_cancel_task_OnClick(id) {
        global_id = id;
        disable_links = true;
        koolajax.callback(task_cancel(global_id), onDoneCancelTasks);
        document.getElementById("status_task").innerHTML = "cancelling...";
        return false;
    }

    function onDoneRebuildTaskList(s) {
        if (disable_links == false)
            document.getElementById("tasks_list").innerHTML = s;

        setTimeout(function() {
            koolajax.callback(build_tasks_list(), onDoneRebuildTaskList);
        }, 1000);
    }

    function onDoneCancelTasks(s) {
        document.getElementById("status_task").innerHTML = s + " Tasks loading...";
        disable_links = false;
    }

    function btn_controller_action_OnClick(backend_url, elem) {
        elem.disabled = true;
        koolajax.callback(do_controller_action(backend_url), function(s) {
            onControllerActionDone(s, elem)
        });
    }

    function onControllerActionDone(s, elem) {
        elem.disabled = false;
    }

    function refresh_replace_intervals_toggle_OnClick() {
        var toggleElement = document.getElementById('refresh_replace_intervals_toggle');
        var containerElement = document.getElementById('refresh_replace_intervals_container');
        if (containerElement.style.display == 'none') {
            toggleElement.style.display='none';
            containerElement.style.display='';
        } //else ...
    }

    function refresh_replace_intervals_OnClick() {
        document.getElementById("modify_searchmap_btn").disabled=true;
        document.getElementById("refresh_replace_intervals").disabled=true;
        document.getElementById("intervals_list_form").innerHTML="Loading...";
        var request = "get_cluster_map?" +
                      "&service=" + service_cgi +
                      "&service_type=" + service_type_cgi +
                      "&ctype=" + ctype_cgi;
        koolajax.callback(get_request_from_dm(request), onRefreshReplaceIntervalsDone);
    }

    function setIntervalValue(name, value) {
        document.getElementById("intervals_list_form")[name].value = value;
    }

    function onRefreshReplaceIntervalsDone(s) {
        document.getElementById("modify_searchmap_btn").disabled=false;
        document.getElementById("refresh_replace_intervals").disabled=false;
        if (!s.success) {
            document.getElementById("intervals_list_form").innerHTML=s.reply;
            return;
        }
        var reply = JSON.parse(s.reply);
        var serviceDescr = reply.cluster[service_cgi];
        if (serviceDescr === undefined) {
            return;
        }
        var configTypes = serviceDescr.config_types;
        if (configTypes === undefined) {
            return;
        }
        var sources = configTypes.default.sources;
        var html = "<table>";
        for (var key in sources) {
            html += "<tr><td>" + key + "</td><td>";
            html += "<input type='text' size=30 name='" + key + "'/>";
            html += "<input type='button' value='c' onclick='setIntervalValue(\"" + key + "\",\"" + key + "\")'/>";
            html += "<input type='button' value='x' onclick='setIntervalValue(\"" + key + "\",\"\")'/>";
            html += "</td></tr>";
        }
        html += "</table>";
        document.getElementById("intervals_list_form").innerHTML = html;

        var toggleElement = document.getElementById('refresh_replace_intervals_toggle');
        var containerElement = document.getElementById('refresh_replace_intervals_container');
        if (toggleElement.style.display == 'none' && containerElement.style.display == 'none') {
            toggleElement.style.display = 'block';
        }
    }
</script>

<?php

function get_slot_list($iface_info) {
    $iface_info_json = json_decode($iface_info, true);
    $slots_list = "";
    foreach ($iface_info_json as $slot) {
        $slots_list .= $slot . ",";
    }
    return $slots_list;
}

function do_clear_queues() {
    global $ctype_cgi;
    global $service_cgi;
    global $service_type_cgi;
    $slots_list = get_slot_list($iface_info);
    $request = "/broadcast?command=purge_queue&service=indexerproxy&purge_queue_service=$service_cgi&ctype=$ctype_cgi";
    $result = "";
    read_reply_from_dm($request, $result);
    return $result;
}

function do_release($iface_info, $deploy_proxies) {
    global $ctype_cgi;
    global $service_cgi;
    global $service_type_cgi;
    $slots_list = get_slot_list($iface_info);
    $request = "/release_slots?slots=$slots_list&ctype=$ctype_cgi&config_type=default&service=$service_cgi&service_type=$service_type_cgi&deploy_proxies=$deploy_proxies";
    read_reply_from_dm($request, $result);
    return $result;
}

function do_clear_index($iface_info) {
    global $ctype_cgi;
    global $service_cgi;
    global $service_type_cgi;
    $request = "/broadcast?ctype=$ctype_cgi&service=$service_cgi&service_type=$service_type_cgi&command=clear_index";
    read_reply_from_dm($request, $result);
    return $result;
}

function do_restart($iface_info) {
    global $ctype_cgi;
    global $service_cgi;
    global $service_type_cgi;
    $request = "/broadcast?ctype=$ctype_cgi&service=$service_cgi&service_type=$service_type_cgi&command=restart";
    read_reply_from_dm($request, $result);
    return $result;
}

function do_modify_searchmap($iface_info, $action, $deploy_proxies, $degradeLevel) {
    global $ctype_cgi;
    global $service_cgi;
    global $service_type_cgi;
    $slots_list = get_slot_list($iface_info);
    $deploy = ($slot_list != "");
    if ($deploy_proxies == "true")
        $deploy = true;
    $request = "/modify_searchmap?action=$action&slots_vector=$slots_list&ctype=$ctype_cgi&service=$service_cgi&service_type=$service_type_cgi&deploy=$deploy&deploy_proxies=$deploy_proxies&may_be_dead_procentage=$degradeLevel";
    read_reply_from_dm($request, $result);
    if ($deploy)
        return $result;
    return "";
}

function do_replace($iface_info, $iface_info_pool, $iface_absent_pool, $deploy_proxies, $percent) {
    global $ctype_cgi;
    global $service_cgi;
    global $service_type_cgi;
    $pool_list = get_slot_list($iface_info_pool);
    $slots_list = get_slot_list($iface_info);
    $absent_list = get_slot_list($iface_absent_pool);
    $request = "/cluster_control?replace_slots=$slots_list&ctype=$ctype_cgi&service=$service_cgi&deploy_proxies=$deploy_proxies&new_slots_pool=$pool_list&absent_replace_slots=$absent_list&may_be_dead_procentage=$percent";
    $result = "";
    read_reply_from_dm($request, $result);
    return $result;
}

function do_copy($iface_info, $iface_info_pool, $percent) {
    global $ctype_cgi;
    global $service_cgi;
    global $service_type_cgi;
    $pool_list = get_slot_list($iface_info_pool);
    $slots_list = get_slot_list($iface_info);
    $request = "/cluster_control?copy_slots=$slots_list&ctype=$ctype_cgi&service=$service_cgi&new_slots_pool=$pool_list&may_be_dead_procentage=$percent";
    $result = "";
    read_reply_from_dm($request, $result);
    return $result;
}

function do_restore($iface_info, $deploy_proxies, $percent) {
    global $ctype_cgi;
    global $service_cgi;
    global $service_type_cgi;
    $slots_list = get_slot_list($iface_info);
    $request = "/cluster_control?restore_slots=$slots_list&ctype=$ctype_cgi&service=$service_cgi&deploy_proxies=$deploy_proxies&may_be_dead_procentage=$percent";
    $result = "";
    read_reply_from_dm($request, $result);
    return $result;
}

function get_doc_count($slot) {
    $slot_doc_count = (int)0;
    if (array_key_exists("result.docs_in_final_indexes", $slot))
        $slot_doc_count += (int)$slot["result.docs_in_final_indexes"];
    if (array_key_exists("result.docs_in_memory_indexes", $slot))
        $slot_doc_count += (int)$slot["result.docs_in_memory_indexes"];
    else if (array_key_exists("result.docs_in_disk_indexes", $slot))
        $slot_doc_count += (int)$slot["result.docs_in_disk_indexes"];
    return $slot_doc_count;
}

function get_slot_buttons_panel($controller_name) {
    global $full_interface;
    $info  = "<span align=\"right\"><input type='button' onclick='btn_controller_action_OnClick(\"http://$controller_name/?command=shutdown\", this)' value='Sh'/></span>";
    $info .= "<span align=\"right\"><input type='button' onclick='btn_controller_action_OnClick(\"http://$controller_name/?command=stop\", this)' value='St'/></span>";
    $info .= "<span align=\"right\"><input type='button' onclick='btn_controller_action_OnClick(\"http://$controller_name/?command=abort\", this)' value='Ab'/></span>";
    $info .= "<span align=\"right\"><input type='button' onclick='btn_controller_action_OnClick(\"http://$controller_name/?command=restart&rigid_level=1\", this)' value='Re'/></span>";
    $info .= "<span align=\"right\"><input type='button' onclick='btn_controller_action_OnClick(\"http://$controller_name/?command=clear_data_status\", this)' value='ClDS'/></span>";
    if ($full_interface) {
        $info .= "<span align=\"right\"><input style='color: red; font-size: larger' type='button' onclick='btn_controller_action_OnClick(\"http://$controller_name/?command=clear_index\", this)' value='Cl'/></span>";
    }
    return $info;
}

function render_absent_replic($interval_id, $replic_num, $dc) {
    $id = $dc . "_". $interval_id . "_" . $replic_num;
    $line = "<td valign='top' id=\"absent_replic_" . $id . "\" onclick=click_select_absent('" . $id . "')>Absent (". $dc . ")</td>";
    return $line;
}

function build_dc_seq($cluster_data) {
    $dc_seq = array();
    foreach ($cluster_data as $interval) {
        if (array_key_exists("slots", $interval)) {
            $slots = $interval["slots"];
            if (count($slots) > count($dc_seq)) {
                $dc_seq = array();
                foreach ($slots as $slot) {
                    $dc = $slot["\$datacenter\$"];
                    $dc_seq[] = $dc;
                }
            }
        }
    }
    return $dc_seq;
}

function find_matching_dc($current_idx, $dc_seq) {
    for ($target_replic_idx = $current_idx; $target_replic_idx < count($dc_seq); $target_replic_idx++) {
        if ($dc_seq[$target_replic_idx] == $dc) {
            return true;
        }
    }
    return false;
}

function build_cluster_structure($par) {
try {
    global $ctype_cgi;
    global $service_cgi;
    global $service_type_cgi;
    global $full_interface;
    global $deploy_manager_up;
    $options = json_decode($par, true);
    $unused = $options["unused"];
    $full_info_about_unused = $options["full_info_about_unused"];
    $only_problem = $options["only_problem"];
    $filters = $options["filters"];
    $filter=join(",", $filters);
    if ($unused)
        $request = "/$deploy_manager_up/api/slots_by_interval/unused_$service_cgi?ctype=$ctype_cgi&service_type=$service_type_cgi&service=unused_$service_cgi&filter=invalid_config_files,result.server_status_global.state,$filter";
    else
        $request = "/$deploy_manager_up/api/slots_by_interval/$service_cgi?ctype=$ctype_cgi&service_type=$service_type_cgi&service=$service_cgi&filter=replics_consistance,invalid_config_files,result.server_status_global.state,result.server_status_global.info,result.search_enabled,result.indexing_enabled,$filter";
    if (!read_reply_from_dm($request, $json_cluster_data))
        return $json_cluster_data;

    $cluster_data = json_decode($json_cluster_data, true);
    if ($cluster_data == null)
        return $json_cluster_data;
    $result = "<table class='cluster_structure'>";
    $empty = true;

    $is_rty = ($service_type_cgi == "rtyserver");
    $dc_seq = build_dc_seq($cluster_data);

    foreach ($cluster_data as $interval) {
        $warning = false;
        $line = "";
        $slots = array();
        $interval_id = $interval["id"];
        if (array_key_exists("slots", $interval))
            $slots = $interval["slots"];
        $replics_idx = 0;
        foreach ($slots as $slot) {
            $dc = $slot["\$datacenter\$"];
            if ($is_rty && !$unused && $dc != $dc_seq[$replics_idx]) {
                if (find_matching_dc($replics_idx, $dc_seq)) {
                    while ($dc != $dc_seq[$replics_idx]) {
                        $line .= render_absent_replic($interval_id, $replics_idx, $dc_seq[$replics_idx]);
                        $replics_idx++;
                    }
                }
            }
            $flags = (array_value($slot, "disable_indexing", false) ? "I" : "")
                    . (array_value($slot, "disable_search", false) ? "S" : "")
            ;
            $backend_flags = (array_value($slot, "result.indexing_enabled", true) ? "" : "I")
                    . (array_value($slot, "result.search_enabled", true) ? "" : "S")
            ;

            $slot_name = $slot["id"];
            $status = $slot["result.controller_status"];
            $status_data = "";
            if (array_key_exists("result.server_status_global.state", $slot)) {
                $status_data = $slot["result.server_status_global.state"];
            }
            $status_info = "";
            if ($status_data == "FailedIndex" || ($status_data ==  "FailedConfig") && array_key_exists("result.server_status_global.info", $slot)) {
                $status_info = $slot["result.server_status_global.info"];
            }

            $slot_size = "";
            if (array_key_exists("slot_size", $slot) && $slot["slot_size"] != 0)
                $slot_size = $slot["slot_size"] . "Gb, ";

            $actuality = "";

            $is_down = ($status == "Down");
            $report = array();
            if (!$is_down) {
                $slot_doc_count = get_doc_count($slot);
                $bkColor = "";
                if (array_key_exists("replics_consistance", $slot)) {
                    $replics_consistance = $slot["replics_consistance"];
                    if($replics_consistance == "shortage_docs")
                        $bkColor = " style='background-color:red;'";
                    else if ($replics_consistance == "overage_docs")
                        $bkColor = " style='background-color:yellow;'";
                }
                $warning |= $bkColor != "";
                array_push($report, "<span$bkColor>" . $slot_doc_count . "</span>");
                foreach ($filters as $one_filter)
                    if (array_key_exists($one_filter, $slot)) {
                        array_push($report, $slot["$one_filter"]);
                    } else
                        array_push($report, "");
                $count = 0;
                if (array_key_exists("invalid_config_files", $slot) && is_array($slot["invalid_config_files"])) {
                    foreach ($slot["invalid_config_files"] as $file) {
                        if ($count == 3) {
                            $actuality .= "...";
                            break;
                        }
                        $actuality .= "<br/>" . $file["id"] . ": <a target='_blank' href='" . get_dm_url() . "check_configs?service=$service_cgi&service_type=$service_type_cgi&ctype=$ctype_cgi&interest=last_deployed,from_host&full_data_limit=2000'>" . $file["error"] . "</a>";
                        $count = $count + 1;
                    }
                }
            }

            $params = explode(":", $slot_name);
            $host = $params[0];
            $short_host = explode(".", $host)[0];
            if ($short_host == $host)
                $host .= ".search.yandex.net";

            $bk_color = "#FFFFFF";
            $warnSlot = true;
            if ($is_down) {
                $bk_color = "#FFCCCC";
                $status = "<a target=\"_blank\" href=\"https://wall-e.yandex-team.ru/?hosts=$host\">$status</a>";
            }
            else if ($status != "Active")
                $bk_color = "#FFDDCC";
            else if ($status == "Active" && $status_data != "OK")
                $bk_color = "#FFFFCC";
            else if ($flags != "" || $backend_flags != "")
                $bk_color = "#CCDDDD";
            else if ($actuality != "")
                $bk_color = "#EEEEAA";
            else if ($status == "Active" && $status_data == "OK") {
                $bk_color = "#CCFFCC";
                $warnSlot = false;
            }
            $warning |= $warnSlot;

            $controller_port = $params[1] + 3;
            $controller_name = "$host:$controller_port";
            $caption = explode(".", $host)[0] . ":" . $params[1] . " (" . $dc . ")";
            if (!$unused || $full_info_about_unused) {
                $info = "<a href=\"http://$controller_name/?command=get_info_server\" target=\"_blank\">$caption</br></a>";
                $info .= get_slot_buttons_panel($controller_name);
                if ($unused)
                    $clck = "click_select_pool";
                else
                    $clck = "click_select";
                $info .= "<br/><div onclick=$clck('" . $slot_name . "')>";
                $backend_flags_txt = ($backend_flags == "") ? "" : "(" . $backend_flags . ")";
                $info .= "<div id=\"flags_$slot_name\">$flags$backend_flags_txt</div>";
                $info .= "<div id=\"info_$slot_name\">" . $slot_size . implode("/", $report) . $actuality . "<br/>";
                $title_entry = "";
                if ($status_info != "") {
                    $title_entry = " title=\"" . htmlspecialchars($status_info) . "\"";
                }
                $info .= "<span $title_entry>$status/$status_data</span></div>";
                $info .= "</div>";
                $line .= "<td valign='top' style='background-color:$bk_color' id=\"" . $slot_name . "\">" . $info . "</td>";
            } else {
                $info = "<span>$caption</span>";
                $line .= "<td style='background-color:$bk_color' id=\"" . $slot_name . "\" onclick=click_select_pool('" . $slot_name . "')>" . $info . "</td>";
            }
            $replics_idx++;
        }
        if ($is_rty && !$unused ) {
            while ($replics_idx < count($dc_seq)) {
                $line .= render_absent_replic($interval_id, $replics_idx, $dc_seq[$replics_idx]);
                $replics_idx++;
            }
        } else {
            if ($replics_idx < count($dc_seq)) {
                $rowspan_str = (string)(count($dc_seq) - $replics_idx);
                $line .= "<td colspan=$rowspan_str></td>";
            }
        }
        if ($only_problem && !$warning)
            continue;
        if (!$unused) {
            $headerColor="white";
            if ($warning)
                $headerColor="yellow";
            $result .= "<tr><td style='background-color:$headerColor'>" . $interval["id"] . "</td>$line</tr>";
        } else {
           $result .= "<tr>$line</tr>";
        }
        $empty = false;
    }
    if ($empty)
        $result .= "<tr><td>EMPTY</td></tr>";
    $result .= "</table>";
    return $result;
} catch (Exception $e) {
    echo "exception:", $e->getMessage(), "\n";
    return $e->getMessage();
}
}

function build_add_replica_report() {
    $result_html = "<form id='add_replica_form'>";
    $result_html .= "<table border=1>";
    $result_html .= "<tr><td colspan=2><input id='btn_add_replica' type='button' value='Добавить реплики' onClick='btn_add_replica_OnClick()'/></td></tr>";
    $result_html .= "<tr><td><input id='add_replica_allocator_dc' form='add_replica_form' value='dc' type='radio' name='add_replica_allocator' checked></input></td>";
    $result_html .= "<td><div id='add_replica_free_slots'></div></td></tr>";
    $result_html .= "<tr><td><input form='add_replica_form' value='selected' type='radio' name='add_replica_allocator'></input></td><td>выбранные слоты</td></tr>";

    $result_html .= "<tr><td colspan=2><table><tr>";
    $result_html .= "<td><input id='add_replica_replicas_count' type='number' max=100 form='add_replica_form' name='replicas_count' min=1 value=1> реплик по </input>";
    $result_html .= "<input id='add_replica_slots_count' type='number' max=1000 form='add_replica_form' name='slots_count' min=1 value=1> cлотов</input></td>";
    $result_html .= "</tr><tr>";
    $result_html .= "<td><label><input id='add_replica_restore' name='restore' type='checkbox'/>Restore</label> ";
    $result_html .= "<label><input name='one_slot_on_server' type='checkbox'/>1 slot per server</label> ";
    $result_html .= "<label><input name='deploy_proxies' type='checkbox' checked/>deploy proxy</label>";
    $result_html .= "<label><input name='allow_same_host_replica' type='checkbox'/>Allow few replicas on the same host</label></td>";
    $result_html .= "</tr></table></td></tr>";
    $result_html .= "</table></form>";
    return $result_html;
}

function build_tags_info_panel() {
    global $ctype_cgi;
    global $service_cgi;
    global $service_type_cgi;

    $slots = "";
    $exclude = "";
    $lable = "";
    $tags_info_json = "";
    $nanny_services = "";
    $endpointsets = "";
    $use_container_names = "";
    if(read_reply_from_dm("modify_tags_info?action=get&ctype=$ctype_cgi&service=$service_cgi&service_type=$service_type_cgi", $tags_info_json)) {
        $tags_info = json_decode($tags_info_json, true);
        if (array_key_exists("nanny_services", $tags_info) && is_array($tags_info["nanny_services"])) {
            foreach ($tags_info["nanny_services"] as $nanny_service) {
                if ($nanny_services !== "") {
                    $nanny_services .= ",";
                }
                $nanny_services .= explode("@", $nanny_service)[0];
            }
        }
        if (array_key_exists("endpointsets", $tags_info) && is_array($tags_info["endpointsets"])) {
            foreach ($tags_info["endpointsets"] as $eps) {
                if ($endpointsets !== "") {
                    $endpointsets .= ",";
                }
                $endpointsets .= $eps;
            }
        }
        if (array_key_exists("use_container_names", $tags_info)) {
            $use_container_names = $tags_info["use_container_names"];
        }
        if (array_key_exists("slots", $tags_info) && is_array($tags_info["slots"]))
            $slots = implode (",", $tags_info["slots"]);
        if (array_key_exists("exclude", $tags_info) && is_array($tags_info["exclude"]))
            $exclude = implode (",", $tags_info["exclude"]);
    } else
        $lable = "ERROR";
    $result_html = "<form id='tags_info_form'>";
    $result_html .= "<table border=1>";
    $result_html .= "<tr><td colspan=2><input id='btn_send_tags_info' type='button' value='Отослать' onClick='btn_send_tags_info_OnClick()'></input>&nbsp;";
    $result_html .= "<input id='btn_invalidate_tags_info' type='button' value='Сбросить кэш' onClick='btn_invalidate_tags_info_OnClick()'></input>&nbsp;";
    $result_html .= "<label id='send_tags_info_result'>$lable</label></td></tr>";
    $result_html .= "<tr><td>Няня</td><td><input form='tags_info_form' size=100 type='text' name='nanny_services' value='$nanny_services'></input></td></tr>";
    $result_html .= "<tr><td>Ходить в контенеры</td><td><input form='tags_info_form' size=100 type='checkbox' name='use_container_names'";
    if ($use_container_names) { $result_html .= " checked" ;}
    $result_html .= "></input></td></tr>";
    $result_html .= "<tr><td>Endpointsets</td><td><input form='tags_info_form' size=100 type='text' name='endpointsets' value='$endpointsets'></input></td></tr>";
    $result_html .= "<tr><td>Слоты</td><td><input form='tags_info_form' size=100 type='text' name='slots' value='$slots'></input></td></tr>";
    $result_html .= "<tr><td>Исключения</td><td><input form='tags_info_form' size=100 type='text' name='exclude' value='$exclude'></input></td></tr>";
    $result_html .= "</table></form>";
    return $result_html;
}

function build_deploy_panel () {
    global $service_cgi;
    $deploy_actions = "<input style='color: red; font-size: larger' id='btn_deploy' type='button' value='Deploy' onclick='btn_deploy_OnClick()'></input>";
    if ($service_cgi != "searchproxy" && $service_cgi != "indexerproxy" && $service_cgi != "deploy_manager") {
        $deploy_actions .= "<input id='btn_deploy_sp' type='button' value='Deploy SP' onclick='btn_deploySP_OnClick()'></input>";
        $deploy_actions .= "<input id='btn_deploy_ip' type='button' value='Deploy IP' onclick='btn_deployIP_OnClick()'></input>";
    }

    $deploy_actions .= " Dead replics fraction:";
    $deploy_actions .= "<select id=\"cmb_percent\">";
    $deploy_actions .= "  <option>0.01</option>";
    $deploy_actions .= "  <option>0.1</option>";
    $deploy_actions .= "  <option>0.25</option>";
    $deploy_actions .= "  <option>0.34</option>";
    $deploy_actions .= "  <option>0.50</option>";
    $deploy_actions .= "  <option>1</option>";
    $deploy_actions .= "</select>";
    $deploy_actions .= "<label><input id='cb_only_save' type='checkbox' checked='true'/>Only save</label>";

    return $deploy_actions;
}

function build_replace_intervals_panel() {
    $result = "<a href='#' style='display:none;font-size:small;text-decoration-style:dotted;' id='refresh_replace_intervals_toggle' onclick='refresh_replace_intervals_toggle_OnClick(); return false;'>Show replace interval panel &#x25BE;</a>";
    $result .= "<table border=1 style='display:none' id='refresh_replace_intervals_container'>";
    $result .= "<tr><td><input id='refresh_replace_intervals' onclick='refresh_replace_intervals_OnClick()' type='button' value='Refresh'/></td></tr>";
    $result .= "<tr><td><form id='intervals_list_form'/></td></tr>";
    $result .= "</table>";
    return $result;
}

function add_replica_start($slots_count, $replicas_count, $slots_alloc_serialization, $restore_be, $deploy_proxy, $degradeLevel) {
    global $ctype_cgi;
    global $service_cgi;
    global $service_type_cgi;

    read_reply_from_dm("add_replica?slots_count=$slots_count&ctype=$ctype_cgi&replicas_count=$replicas_count&service=$service_cgi&slots_allocator=$slots_alloc_serialization&pref_dc=$preffered_dc&&service_type=$service_type_cgi&restore=$restore_be&deploy_proxy=$deploy_proxy&may_be_dead_procentage=$degradeLevel", $result);
    return $result;
}

function deploy_start($type, $percent, $slots) {
    global $ctype_cgi;
    global $service_cgi;
    global $service_type_cgi;
    $result = array();
    if ($type == "searchproxy") {
        read_reply_from_dm("deploy?ctype=$ctype_cgi&service=searchproxy&may_be_dead_procentage=$percent&service_type=searchproxy&force_services=$service_cgi&version=CURRENT$slots", $result);
    } else if ($type == "indexerproxy") {
        read_reply_from_dm("deploy?ctype=$ctype_cgi&service=indexerproxy&may_be_dead_procentage=$percent&service_type=indexerproxy&force_services=$service_cgi&version=CURRENT$slots", $result);
    } else {
        read_reply_from_dm("deploy?ctype=$ctype_cgi&service=$service_cgi&may_be_dead_procentage=$percent&service_type=$service_type_cgi$slots", $result);
    }
    return $result;
}

function task_cancel($task_id) {
    read_reply_from_dm("control_task?task_id=$task_id&action=cancel", $data);
    return $data;
}

function build_tasks_list() {
    global $service_cgi;
    global $ctype_cgi;
    $attach_list = "";
    if (read_reply_from_dm("deploy_info?service=$service_cgi&ctype=$ctype_cgi&exclusion_filter=.*", $data)) {
        $json = json_decode($data, true);
        if ($json != null) {
            $attach_list .= "<table>";
            if (array_key_exists("active", $json)) {
                $tasks_list = $json["active"];
                foreach ($tasks_list as $key => $task) {
                    $attach_list .= "<tr>";
                    $attach_list .= "<td><a onclick=btn_attach_task_OnClick('$key') href='#$key'>$key</a></td>";
                    $attach_list .= "<td><input type='button' onclick=btn_cancel_task_OnClick('$key') value='Cancel'/></td>";
                    $attach_list .= "</tr>";
                }
            }
            $attach_list .= "</table>";
        }
    } else {
        $attach_list = $data;
    }
    return $attach_list;
}

function do_controller_action($backend_url) {
    try {
        $http = HttpRequest::get($backend_url)->connectTimeout(1)->readTimeout(30);
        return ["success" => ($http->ok()), "reply" => ($http->body())];
    } catch (Exception $e) {
        return ["success" => false, "reply" => ($e->getMessage())];
    }
}

function renderClusterReport() {
    global $full_interface;
    global $service_cgi;
    global $service_type_cgi;

    $report_cluster = "";
    if ($full_interface) {
        $report_cluster .= "<p>" . build_tags_info_panel() . "</p>";
        if ($service_cgi != "searchproxy" && $service_cgi != "indexerproxy" && $service_cgi != "deploy_manager" && $service_type_cgi != "metaservice") {
            $report_cluster .= "<p>" . build_add_replica_report() . "</p>";
        }
    }

    $report_cluster .= "<p>" . build_deploy_panel() . "</p>";

    if ($service_type_cgi != "metaservice") {
        if ($full_interface) {
            $report_cluster .= "<table cellspacing=10>";
            $report_cluster .= "<tr><td align='center'><b>Selected slots</b>";
            $report_cluster .=  "<span id='selected_slots_counts' style='display:none;font-size:small;'> (used:&nbsp;<span id='used_slots_count'>0</span>,&nbsp;unused:&nbsp;<span id='unused_slots_count'>0</span>)</span>";
            $report_cluster .=  "</td><td align='center'><b>All slots</b></td></tr>";
            $report_cluster .= "<tr><td align='center'>";
            $report_cluster .= "<input id=\"release_btn\" type=\"button\" value=\"release\" onclick=\"btn_release_OnClick()\"/>";
            $report_cluster .= "<input id=\"replace_btn\" type=\"button\" value=\"replace\" onclick=\"btn_replace_OnClick()\"/>";
            $report_cluster .= "<input id=\"restore_btn\" type=\"button\" value=\"restore\" onclick=\"btn_restore_OnClick()\"/>";
            $report_cluster .= "<input id=\"copy_btn\" type=\"button\" value=\"copy\" onclick=\"btn_copy_OnClick()\"/>";
            $report_cluster .= "</td><td align='center'>";
            $report_cluster .= "<input id=\"clear_index_btn\" type=\"button\" value=\"clear index\" onclick=\"btn_clear_index_OnClick()\"/>";
            $report_cluster .= "<input id=\"clear_queues_btn\" type=\"button\" value=\"clear queues\" onclick=\"btn_clear_queues_OnClick()\"/>";
            $report_cluster .= "<input id=\"restart_btn\" type=\"button\" value=\"restart\" onclick=\"btn_restart_OnClick()\"/>";
            $report_cluster .= "</td></tr>";
            $report_cluster .= "<tr><td align='center'>";
            $report_cluster .= build_replace_intervals_panel();
            $report_cluster .= "<label><input id=\"enabled_search_checkbox\" type=\"checkbox\" checked=\"true\"/>Search enabled</label> ";
            $report_cluster .= "<label><input id=\"enabled_index_checkbox\" type=\"checkbox\" checked=\"true\"/>Index enabled</label>";
            $report_cluster .= "<br/>";
            $report_cluster .= "<label><input id=\"deploy_checkbox\" type=\"checkbox\"/>Deploy proxies</label> ";
            $report_cluster .= "<input id=\"modify_searchmap_btn\" type=\"button\" value=\"Send\" onclick=\"btn_modify_searchmap_OnClick()\"/>";
            $report_cluster .= "</td></tr>";
            $report_cluster .= "</table>";
        }
        $report_cluster .= "<p>Cluster structure for service $service_cgi</p>";
        $report_cluster .= "<label><input id='only_problem_used' type='checkbox'/> Only problem intervals</label>";
        $report_cluster .= "<div id='filter_cboxes' style=\"max-width:1000px\">";
        $report_cluster .= "</div>";
        $report_cluster .= "<div id=\"cluster_structure\" style=\"padding-bottom:5px;\">";
        $report_cluster .= "</div>";
        $report_cluster .= "<label><input id=\"full_info_about_unused\" type=\"checkbox\"/>Full info about unused</label> ";
        $report_cluster .= "<label><input id='only_problem_unused' type='checkbox'/>Only problem intervals</label>";
        $report_cluster .= "<div id=\"cluster_structure_unused\">";
        $report_cluster .= "</div>";
    }
    $report_cluster .= "<p>Tasks list</p>";
    $report_cluster .= "<div id=\"tasks_list\">". build_tasks_list() . "</div>";
    $report_cluster .= "<p>Task information</p>";
    $report_cluster .= "<div id=\"status_task\">Task not started</div><br/>";

    return $report_cluster;
}

$koolajax->scriptFolder = $KoolControlsFolder . "/KoolAjax";
$koolajax->enableFunction("build_cluster_structure");
$koolajax->enableFunction("do_release");
$koolajax->enableFunction("do_restore");
$koolajax->enableFunction("do_restart");
$koolajax->enableFunction("do_replace");
$koolajax->enableFunction("do_copy");
$koolajax->enableFunction("do_clear_index");
$koolajax->enableFunction("do_clear_queues");
$koolajax->enableFunction("task_check");
$koolajax->enableFunction("do_modify_searchmap");
$koolajax->enableFunction("add_replica_start");
$koolajax->enableFunction("deploy_start");
$koolajax->enableFunction("build_tasks_list");
$koolajax->enableFunction("task_cancel");
$koolajax->enableFunction("do_controller_action");


include("check_task.php")
?>
