function createRule() {
    var link = 'companydocumentrule.ivp/create';
    getRule(link);
}

function viewRule(ruleId) {
    var link = 'companydocumentrule.ivp/view/' + ruleId;
    getRule(link);
}

function getRule(link) {
    $("#dialog").load(base + link, { companyId: $("#id").val() }, function () {
        $("#dialog").dialog("option", "title", FormatString(CompanyResources.DocumentRule));

        setServiceSettings();
        setTaskTypesSettings();
        setActions();

        setDisabledField();

        $(document).on("change", "#listTree input[type=checkbox]", recheckTree);
        $(".disabled").attr("disabled", "disabled");

        setChangeDocument();
        $("#dialog").dialog("option", "minHeight", 520);
        $("#dialog").dialog("open");
    });
}

function setServiceSettings() {

    $('#ServiceIds').multipleSelect();
    $("input[type=radio]").css("margin-right", "5px");

    setHelpLinkEvents($('#linklistServiceHelp'));
}

function setTaskTypesSettings() {
    $("#IsAllTaskTypeTrue").click(function () {
        $("#allblock").show();
        $("#selectedblock").hide();
        $("#aselectedblock").hide();
    });

    $("#IsAllTaskTypeFalse").click(function () {
        $("#allblock").hide();
        $("#selectedblock").show();
        $("#aselectedblock").show();
    });
}

function deleteRule() {
    var selected = $("#documentsrules").find("tr.selected");
    if (selected.length == 0) { alert(CompanyResources.NoDocumentsSelected); return false; }

    if (!confirm(CompanyResources.SureDelete + '(' + selected.length + ')?')) return false;
    var selectedDocumentIds = selected.find(".rowid").map(function () {
        return $(this).val();
    }).get();

    try {
        $.ajax({
                type: "POST",
                url: "companydocumentrule.ivp/delete",
                data: { ids: selectedDocumentIds },
                success: function () {
                    loadDocumentsRules(true);
                }
            });
    } catch (e) {
        alert(e.message);
    }

    return false;
}

function saveRule() {
    $.ajax({
        type: "POST",
        url: "companydocumentrule.ivp/save",
        data: $('#companydocumentrule').serialize(),
        success: function (data) {
            var event = JSON.parse(data);

            if (event.Description != undefined) {
                $(".error").html(event.Description);
            } else {
                loadDocumentsRules(true);
                dialogClose();
            }
        }
    });
    
    return false;
}

function adddetails() {
    var el = $("select[id^='Details']:last");
    if (el != undefined) {

        var i = 0;
        if (el.length) {
            var id = el.attr("id");
            var begin = id.indexOf('[') + 1;
            i = id.substr(begin, id.indexOf(']') - begin);
        }

        $.ajax({
            type: "GET",
            url: base + "companydocumentrule.ivp/adddetails",
            data: { position: i },
            success: function (data) {
                $("#selectedblock").append(data);
                setActions();
                checkDisabledField();
            }
        });
    }
    return false;
}

function deleteDetais(obj) {

    $(obj).closest(".det").remove();

    $("#selectedblock .det").each(function (pos, el) {
        var value = $(el).attr("value");
        if (value != pos) {
            $(el).attr("value", pos);
            setNewIndex(pos, el);
        }
    });
}

function setNewIndex(i, el) {
    $(el).find(".changeIndex").each(function (q, curel) {
        updateAttribute($(curel), "id", i);
        updateAttribute($(curel), "name", i);
    });

    $(el).find("label.radio").each(function (q, curel) {
        updateAttribute($(curel), "for", i);
    });
}

function updateAttribute(el, attrName, i) {
    var attr = $(el).attr(attrName);
    if (attr != undefined) {
        var begin = attr.indexOf('[') + 1;
        var pos = attr.substr(begin, attr.indexOf(']') - begin);
        $(el).attr(attrName, $(el).attr(attrName).replace(pos, i));
    }
}

function setActions() {
    $("div#selectedblock .det").hover(function () {
        $(this).find(".actions").show();
    }, function () {
        $(this).find(".actions").hide();
    });
}

function setDisabledField() {
    checkDisabledField();

    $(document).on("click", ".unlimitedCheck", function () {
        var det = $(this).closest(".det");
        if (det != undefined) {
            det.find(".disabledField").attr("disabled", "disabled");
        }
    });

    $(document).on("click", ".limitedCheck", function () {
        var det = $(this).closest(".det");
        if (det != undefined) {
            det.find(".disabledField").removeAttr("disabled");
        }
    });
}

function checkDisabledField() {
    $(".unlimitedCheck").each(function () {
        var isCheck = $(this).prop('checked');
        if (isCheck) {
            var det = $(this).closest(".det");
            if (det != undefined) {
                det.find(".disabledField").attr("disabled", "disabled");
            }
        }
    });
}

function recheckTree() {

    var handler = $("ul.checklist:visible");
    var checked = $(this).attr("checked");

    //устанавливаем path вместо value, вывод изменен: 1, 1|2, 1|2|2
    var value = $(this).attr("path");

    var selectedIds = new Array();
    if (checked) {
        handler.find("input[path^='" + value + "']").each(function () {
            if ($(this).attr("path") != value) {
                $(this).attr('checked', 'checked');
                $(this).attr('disabled', 'disabled');

                selectedIds.push($(this).val());
            }
        });

        $(selectedIds).each(function () {
            $("#ServiceIds").find("option[value='" + $(this) + "']").attr('selected', 'selected');
        });
        
        
    } else {
        handler.find("input[path^='" + value + "']").each(function () {
            $(this).removeAttr('checked');
            $(this).removeAttr('disabled');
            
            selectedIds.push($(this).val());
        });
        
        $(selectedIds).each(function () {
            $("#ServiceIds").find("option[value='" + $(this) + "']").removeAttr('selected');
        });
    }
}

function setNotActiveRules() {
    $("#documentsrules").find("tr").each(function (i, el) {
        $(el).attr('title', CompanyResources.ActiveCompanyDocument);
    });

    var el = $("#notActiveRuleIds");
    if(el != undefined && el.length) {
        var ids = $(el).val().split(",");
        $(ids).each(function(i, el) {
            var elem = $("#documentsrules").find("input[value='" + el + "']");
            if (elem != undefined && elem.length) {
                var tr = $(elem).parent().parent();
                $(tr).addClass("expired");
                $(tr).attr('title', CompanyResources.NotActiveCompanyDocument);
            }
        });
    }
}

function setChangeDocument() {
    $('#CompanyDocumentId').change(function () {
        var el = $("#activeDocumentsIds");
        if (el != undefined) {
            var ids = $(el).val().split(",");
            var value = $('#CompanyDocumentId').val();
            //if(!$.inArray(value, ids))
            ////if (!$(ids).contains($('#CompanyDocumentId').val()))
            //    $("#IsActiveDocument").addClass("hidden");
            //else {
            //    $("#IsActiveDocument").removeClass("hidden");
            //}

            var isActive = false;
            for (var i = 0; i < ids.length; i++) {
                if (ids[i] == value)
                    isActive = true;
            }
            
            if(isActive)
                $("#IsNotActiveDocument").addClass("hidden");
            else
                $("#IsNotActiveDocument").removeClass("hidden");

        }
    });
}

