/// <reference path="../jquery.intellisense.js"/>
/// <reference path="../ru.js"/>
var utype = null;
var dlg = null;
var hpid = 0;
var formchanged = false;

var ssid = null; //source status id
var tsid = null; //target status id

var WorkflowApp = {
    customSetTab: function ($form, tabName) {
        if (tabName == 'general') {
            $.cookies.set('wftab', 'general');
            reloadGeneralTab();
        }
        else if (tabName == 'workflow') {
            $.cookies.set('wftab', 'workflow');
            setTab('workflow');
        }
    }
}

$(function () {
    $("#tabs a").on("click.setworkflowid", function () {
        $.cookies.set("wid", $("#id").val());
    });

    $("#ageneral").on("click.tabs", function () {
        if (formchanged) {
            alert(WorkflowResources.MustSave);
            return false;
        }
        WorkflowApp.customSetTab($('form'), 'general'); return false;
    });
    $("#aworkflow").on("click.tabs", function () {
        if (formchanged) {
            alert(WorkflowResources.MustSave);
            return false;
        }
        WorkflowApp.customSetTab($('form'), 'workflow');
        return false;
    });
    $("#anotificationruleroles").on("click.tabs", function () {
        if (formchanged) {
            alert(WorkflowResources.MustSave);
            return false;
        }
        $.cookies.set('wftab', 'notificationruleroles'); return loadNotificationRule(false);
    });
    $("#aworkflowrules").on("click.tabs", function () {
        if (formchanged) {
            alert(WorkflowResources.MustSave);
            return false;
        }
        $.cookies.set('wftab', 'workflowrules'); return loadWorkflowRules(false);
    });
    $("#arecommendedactions").on("click.tabs", function () {
        if (formchanged) {
            alert(WorkflowResources.MustSave);
            return false;
        }
        $.cookies.set('wftab', 'recommendedactions'); return loadRecommendedActions(false);
    });

    $("#agraphicview").on("click.trtabs", function () {
        if (formchanged) {
            alert(WorkflowResources.MustSave);
            return false;
        }
        return setTrTab('graphicview');
    });
    $(document).on("click.trtabs", "#amatrixview", function () { $('#rolesfilter').hide(); return reloadMatrixTab(); });

    if (!$("#create").length && $("#tab").val() != "" && $.cookies.get("wid") == $("#id").val()) {
        if ($("#tab").val() == "notificationruleroles")
            loadNotificationRule();
        else
            if ($("#tab").val() == "recommendedactions")
                loadRecommendedActions();
            else if ($("#tab").val() == "workflowrules")
                loadWorkflowRules(false);
    }

    $('li.bit-box>span.context').live("click", showContextMenu1).live("mouseout", function () {
        clearTimeout(hpid);
        hpid = setTimeout('hideContextMenu1()', 400);
    });
    $('.contextmenu').live("click", hideContextMenu1);
    $("form").bind("invalid-form.validate", function (e, validator) {
        var err = validator.numberOfInvalids();
        var errElement = validator.errorList[0].element.id;
        if (err && errElement.startsWith('sel_conc') && (!$('.tab#workflow').is(':visible')))
            alert(WorkflowResources.CoordinationRequired);
    }).validate();

    initStatusChangeHandlers();

    if ($('#srpopup').val() != "true") {
        $('input.addroles').autocomplete(base + 'workflow.ivp/findroles/' + $('#id').val(), { minChars: 1 }).result(roleSelected);
        $('#rid').change(syncRoles);
        syncRoles();
    }
    /*
    $(".concurrenceType").on("change", function () {
        var radio = $('.concurrenceType input:checked').val();
        if (radio == 0) {
            $('#concOrderRequired').hide();
        } else {
            $('#concOrderRequired').show();
        }
    });
    */
    $("table[id*='conc']").on("change", function () {
        if ($(this).find('tr').length > 0)
            $(this).closest('div').find('.assignCoordinatorsText').hide();
        else {
            $(this).closest('div').find('.assignCoordinatorsText').show();
        }
    });

    $("table[id*='conc']").trigger('change');

    // Пришлось дизейблить жсом, добавляя дизейбл в хамл начинается какой то ад
    $('input.concurrence').attr('disabled', 'disabled');

    jQuery.multipleSelect.initByClassName('.multipleselect');
});

function initStatusChangeHandlers() {
    if ($('#create').length == 0) {
        $('#workflow .msroles').multipleSelect({ onchange: function (ms) { ms.holder.parents('.row').removeClass('new').addClass('changed'); } });
        $('#rid').on("change.test", function () {
            formchanged = true;
            $('#roleswarning').show();
        });
        $('#sid').on("change.test", function () {
            formchanged = true;
            $('#statuswarning').show();
        });
    }
}

function setDrawArea() {
    //  масштабирование окна рисования - г.к.
    $('#rolesfilter').removeClass('hidden'); $('#rolesfilter').show();
    var mh = 590;
    $(".w").each(function () {
        mh = 50 + Math.max(mh, parseInt($(this).css("top")));
    });
    $("#flowchart").height(mh);
    //
    var mL = $(".scrollable").width() - 20;
    $(".w").each(function () {
        var l = parseInt($(this).css("left")) + $(this).children("span").width();
        if (l > mL)
            mL = l;
    });
    $("#flowchart").width(mL);
    $(".addSpace").width(mL);

    $("#graphicOptions").draggable({
        containment: "parent", start: function () {
            $("._jsPlumb_overlay").trigger("mouseleave");
        }, stop: function (e) {
            //save label location
            $.ajax({
                type: "POST",
                url: base + 'workflow.ivp/saveGraphicMenuLocation/' + $('#id').val(),
                data: { left: $(this).position().left, top: $(this).position().top }
            });
        }
    });
    $("#rolelegend").accordion({ heightStyle: "content", collapsible: true }); //.draggable({containment:"parent",});
    $("#rolesfilter").accordion({ heightStyle: "content", collapsible: true }); //.draggable()

    //отображаем связи
    hideRoles();
}

function hideContextMenu1() {
    $('.contextmenu').hide().remove();
}

function showContextMenu1() {
    //var id = $(this).parents('.bit-box:first').parent('.parent').attr('id');
    var id = $(this).closest('.parent').attr('id');
    var roleid = $(this).attr('itemid');
    clearTimeout(hpid);
    hideContextMenu1();

    var popuppath = '#contextmenu';
    var node = $('#' + id);

    if ($(popuppath).length == 0) {
        var popup = $("body").append('<ul id="contextmenu" class="contextmenu"></ul>').children('#contextmenu');

        if ($(this).parents('.bit-box:first').find('.buttonExist').first().hasClass('hidden')) {
            popup.append('<li onclick="return AddButtonName(' + id + ',' + roleid + ');">' + WorkflowResources.AddButton + '</li>');
        }
        else {
            popup.append('<li onclick="return AddButtonName(' + id + ',' + roleid + ');">' + WorkflowResources.RenameButton + '</li>');
            popup.append('<li onclick="return removeButton(' + id + ',' + roleid + ');">' + WorkflowResources.RemoveButton + '</li>');
        }
        if (id.indexOf("_0_") < 0) {
            if ($(this).parents('.bit-box:first').find('.buttonAdditional').first().hasClass('hidden')) {

                popup.append('<li onclick="WorkflowStatuses.selectStatuses($(this));" idul="' + id + '" roleid="' + roleid + '">' + WorkflowResources.AddAdditionalCondition + '</li>');

            }
            else {
                popup.append('<li onclick="return removeAdditional(' + id + ',' + roleid + ');">' + WorkflowResources.RemoveAdditionalConditions + '</li>');
            }


            if ($(this).parents('.bit-box:first').find('.buttonRequiredFields').first().hasClass('hidden')) {
                popup.append('<li onclick="WorkflowRequiredFields.selectRequiredFields($(this));" idul="' + id + '" roleid="' + roleid + '">' + WorkflowResources.AddRequiredFields + '</li>');
            }
            else {
                popup.append('<li onclick="return removeRequiredFields(' + id + ',' + roleid + ');">' + WorkflowResources.RemoveRequiredFields + '</li>');
            }


            if ($(this).parents('.bit-box:first').find('.buttonComment').first().hasClass('hidden')) {
                popup.append('<li onclick="setCommentRequired(' + id + ',' + roleid + ',1);">' + WorkflowResources.AddCommentRequired + '</li>');
            }
            else {
                popup.append('<li onclick="setCommentRequired(' + id + ',' + roleid + ',0);">' + WorkflowResources.RemoveCommentRequired + '</li>');
            }
            popup.append('<li onclick="deleteRoleFromMenu($(\'#' + id + '\'),' + roleid + ',true);return false;">' + CommonResources.Remove + '</li>');
        }
        else {
            popup.append('<li onclick="deleteRoleFromMenu($(\'#' + id + '\'),' + roleid + ',false);return false;">' + CommonResources.Remove + '</li>');
        }
        $(popuppath).mouseover(function () { clearTimeout(hpid); }).mouseout(function () { hpid = setTimeout('hideContextMenu1()', 500); });
    }
    var offset = $(this).offset();
    var parentoffset = $(this).parent('.bit-box').offset();

    if ($('#reportfilter').val() != null) {
        $('#contextmenu').css({ 'left': offset.left + 5, 'top': offset.top + 38 }).show();
    }
    else {
        $('#contextmenu').css({ 'left': offset.left, 'top': parentoffset.top }).show();
    }


    return false;
}

function setCommentRequired(id, roleid, isSet) {
    var img = $('#' + $(id).attr('id') + '_' + roleid + ' img.buttonComment').first();
    var input = $('#comment_' + $(id).attr('id'));
    switch (isSet) {
        case 0:
            var inputArray = $(input.attr("value").split('|'));
            if (inputArray.length - 1 <= 1) {
                input.attr("value", "");
            }
            else {
                var stringValue = '';
                inputArray.each(function (i, id) {

                    if (id != roleid && i != inputArray.length - 1)
                        stringValue += id + '|';
                });
                input.attr("value", stringValue);
            }
            img.addClass('hidden');
            break;
        case 1:
            if (input.attr("value").length <= 0) {
                input.attr("value", roleid + '|');
            }
            else {
                input.attr("value", input.attr("value") + roleid + '|');
            }
            img.removeClass('hidden');
            break;
    }

    $('#' + $(id).attr('id') + '_' + roleid).closest(".row").removeClass('new').addClass('changed');

    return false;
}


function removeButton(id, roleid) {
    var selectid = '#buttons_' + $(id).attr('id');
    var img = '#' + $(id).attr('id') + '_' + roleid;
    $(img + ' img.buttonExist').filter(":first").addClass('hidden');
    $(selectid + ' [value="' + roleid + '|' + $(img + ' img.buttonExist').filter(":first").attr('title') + '|"]').remove();

    $('#' + $(id).attr('id') + '_' + roleid).closest(".row").removeClass('new').addClass('changed');

    return false;
}


function removeAdditional(id, roleid) {


    var select = '#additional_' + $(id).attr('id');
    $(select + ' option').each(function () {
        if (this.value.indexOf('role_' + roleid) >= 0) {
            $(this).remove();
        }
    });

    var img = '#' + $(id).attr('id') + '_' + roleid;
    $(img + ' img.buttonAdditional').filter(":first").addClass('hidden');

    $('#' + $(id).attr('id') + '_' + roleid).closest(".row").removeClass('new').addClass('changed');

    return false;
}

function removeRequiredFields(id, roleid) {
    var select = '#typeFieldRequired_' + $(id).attr('id');
    $(select + ' option').each(function () {
        if (this.value.indexOf('role_' + roleid) >= 0) {
            $(this).remove();
        }
    });

    var mainFieldSelect = '#mainFieldRequired_' + $(id).attr('id');
    $(mainFieldSelect + ' option').each(function () {
        if (this.value.indexOf('role_' + roleid) >= 0) {
            $(this).remove();
        }
    });



    var img = '#' + $(id).attr('id') + '_' + roleid;
    $(img + ' img.buttonRequiredFields').filter(":first").addClass('hidden');

    $('#' + $(id).attr('id') + '_' + roleid).closest(".row").removeClass('new').addClass('changed');

    return false;
}

function AddButtonName(id, roleid) {
    hideContextMenu1();

    $("body").append("<div class='popupwrapper' style='display:block;' id='pop_" + $(id).attr('id') + "_" + roleid + "'><div class='popup'></div></div>");
    popupwrapper = $('#pop_' + $(id).attr('id') + '_' + roleid);
    var parentoffset = $('#' + $(id).attr('id') + '_' + roleid).offset();
    popupwrapper.css('left', parentoffset.left - 5).css('top', parentoffset.top + 20);
    var popup = popupwrapper.children('div.popup');

    // ?wtf? ..переписать..
    var ifExist = 0;
    var img = '#' + $(id).attr('id') + '_' + roleid;
    var selectid = '#buttons_' + $(id).attr('id');
    if ($(selectid + ' [value="' + roleid + '|' + $(img + ' img.buttonExist').attr('title') + '|"]').length != 0)
        ifExist = 1;
    // ***

    var value = $("#" + $(id).attr("id") + "_" + roleid).find("img.buttonExist").attr("title");

    popup.append('<input id="buttonnewname" type="text" value="' + $.trim(value) + '"/><a id="button1" href="#" onclick="renameButton(' + $(id).attr('id') + ',' + roleid + ',' + ifExist + '); return false;"><img class="icons16" src="img/accept.png"/></a><a id="button2" href="#" onclick="cancelRenameButton(' + $(id).attr('id') + ',' + roleid + '); return false;"><img class="icons16" src="img/delete.gif"/></a>');
    return false;
}

function renameButton(id, roleid, ifExist) {
    var newText = '';
    var img = '#' + $(id).attr('id') + '_' + roleid;
    if ($('input#buttonnewname').val().length != 0) {

        switch (ifExist) {
            case 1:
                $('#buttons_' + $(id).attr('id') + ' [value="' + roleid + '|' + $(img + ' img.buttonExist').filter(":first").attr('title') + '|"]').html($('input#buttonnewname').val());
                $('#buttons_' + $(id).attr('id') + ' [value="' + roleid + '|' + $(img + ' img.buttonExist').filter(":first").attr('title') + '|"]').val(roleid + '|' + $('input#buttonnewname').val() + '|');
                $(img + ' img.buttonExist').filter(":first").attr('title', $('input#buttonnewname').val());
                break;
            case 0:
                $('#buttons_' + $(id).attr('id')).append($('<option value="' + roleid + '|' + $('input#buttonnewname').val() + '|" selected="true">' + $('input#buttonnewname').val() + '</option>'));

                $(img + ' img.buttonExist').filter(":first").removeClass('hidden').attr('title', $('input#buttonnewname').val());

                break;
        }
    }

    var popupwrapper = $('#pop_' + $(id).attr('id') + '_' + roleid);
    popupwrapper.remove();

    $('#' + $(id).attr('id') + '_' + roleid).closest(".row").removeClass('new').addClass('changed');

    return false;
}

function cancelRenameButton(id, roleid) {
    var popupwrapper = $('#pop_' + $(id).attr('id') + '_' + roleid);
    popupwrapper.remove();
    return false;
}

function deleteRoleFromMenu(roleId, id, fromstatusbegin) {
    var role = roleId;
    var length = role.find('li').length - 1;
    //раскрас изменений
    role.closest(".row").removeClass('new').addClass('changed');
    var idLi = '#' + roleId.attr('id') + '_' + id;

    $('#sel_' + roleId.attr('id') + ' option[value="' + id + '"]').removeAttr("selected");
    $('#buttons_' + roleId.attr('id') + ' [value="' + id + '|' + $(idLi).children('.buttonExist').attr('title') + '|"]').remove();
    if (fromstatusbegin) {
        setCommentRequired(roleId, id, 0);
        var select = '#additional_' + roleId.attr('id');
        $(select + ' option').each(function () {
            if (this.value.indexOf('role_' + id) >= 0) {
                $(this).remove();
            }
        });
        var selectFieldRequired = '#typeFieldRequired_' + roleId.attr('id');
        $(selectFieldRequired + ' option').each(function () {
            if (this.value.indexOf('role_' + id) >= 0) {
                $(this).remove();
            }
        });
    }
    if (length <= 0)
        role.closest('tr').hide();

    $(idLi).remove();
}

function reloadGeneralTab() {
    var blockId = '#general';
    var blockIdClear = 'general';
    $(blockId).load(base + 'workflow.ivp/loadgeneraltab/' + $('#id').val(), { date: new Date().toString() }, function () {
        setTab(blockIdClear);
        initStatusChangeHandlers();
        $.multipleSelect.initByClassName('.multipleselect');
    });
    setTab(blockIdClear);
    return false;
}

function reloadMatrixTab() {
    $("#workflow").html("").load(base + 'workflow.ivp/loadtransitiontab/' + $('#id').val(), { date: new Date().toString() }, function () {
        setTrTab("matrixview");
        $("#amatrixview").off("click.trtabs");
        $("#agraphicview").off("click");
        enableButtons();

        $("#agraphicview").click(function () {
            if ($("div.changed").length)
                if (!confirm("Сделанные изменения не сохранятся при переходе."))
                    return false;

            setTrTab("graphicview");
            jsPlumbDemo.init();
            initFlowchart();

            $("#agraphicview").off("click");
            $("#agraphicview").on("click.trtabs", function () { return setTrTab('graphicview'); });
            $("#amatrixview").off("click.trtabs");
            $("#amatrixview").on("click.trtabs", function () { $('#rolesfilter').hide(); return reloadMatrixTab(); });

            return false;
        });

        $("#amatrixview").on("click.trtabs", function () { $('#rolesfilter').hide(); return reloadMatrixTab(); });

        $('input.addroles').autocomplete(base + 'workflow.ivp/findroles/' + $('#id').val(), { minChars: 1 }).result(roleSelected);
        $('#rid').change(syncRoles);
        syncRoles();
    });
    return false;
}

function disableButtons() {
    $('#savesubmit').attr('disabled', true);
    $('.saveandreturn').attr('disabled', true);
}
function enableButtons() {
    $('#savesubmit').attr('disabled', false);
    $('.saveandreturn').attr('disabled', false);
}

function loadNotificationRule(reload) {
    var blockId = '#notificationruleroles';
    var blockIdClear = 'notificationruleroles';
    disableButtons();
    //reload ==undefined - >_< но в service.js: function loadNotificationRule(entityType) - подумать на досуге..
    if (reload == undefined || !$.trim($(blockId).html())) {
        $(blockId).load(base + 'workflow.ivp/loadnotificationruleforroles/' + $('#id').val(),
            { date: new Date().toString() },
            function () { setTab(blockIdClear); });
    } else {
        setTab(blockIdClear);
    }

    return false;
}

function loadWorkflowRules(reload) {
    disableButtons();
    var blockId = '#workflowrules';
    var blockIdClear = 'workflowrules';

    if (reload || !$.trim($(blockId).html())) {
        $(blockId).load(base + 'workflowworkflowrule.ivp/list/' + $('#id').val(),
            { date: new Date().toString() },
            function () {
                setTab(blockIdClear);
                var addVal = "?workflowId=" + $('#id').val() + "&back=true";
                $(".btncreate").attr("href", $(".btncreate").attr("href") + addVal);
                $(".openlink").each(function () {
                    $(this).attr("href", $(this).attr("href") + addVal);
                });

            });
    } else {
        setTab(blockIdClear);
    }

    return false;
}

function workflowRuleChangePage(page) {
    if (page) {
        $('#workflowrules').load(base + 'workflowworkflowrule.ivp/list/' + $('#id').val(), { tb_page: page, nolayout: true, timestamp: new Date().toString() }, initTable);
    } else {
        $('#workflowrules').load(base + 'workflowworkflowrule.ivp/list/' + $('#id').val(), { nolayout: true, timestamp: new Date().toString() }, initTable);
    }
    return false;
}

function workflowRuleOrderBy(sort) {
    //На случай если фильтр уже открыт, установим сортировку по выбранной колонке в фильтре
    if ($('#columns').length > 0) {
        var col = sort.substr(0, sort.indexOf(' '));
        var desc = (sort.indexOf('desc') > 0);
        $('select.orderby').val('');
        $('select.orderby[column="' + col + '"]').get(0).selectedIndex = (desc ? 2 : 1);
    }
    var params = { tb_orderby: sort, nolayout: true };
    $('#workflowrules').load(base + 'workflowworkflowrule.ivp/list/' + $('#id').val(), params, initTable);
    return false;
}

function loadRecommendedActions(reload) {
    tableRootDiv = '#recommendedactions';
    disableButtons();
    if (reload || !$.trim($('#recommendedactions').html())) {
        $('#recommendedactions').load(base + 'recommendedaction.ivp/list', { date: new Date().toString(), tb_workflowid: $('#id').val() }, function () { setTab('recommendedactions'); initTable(); });
    }
    else setTab('recommendedactions');

    return false;
}

function createRecommendedAction() {
    openDialog('recommendedaction.ivp/create?workflowid=' + $("#id").val(), 'recommendedaction', { width: 700, height: 300 });
    return false;
}

function editRecommendedAction(aid) {
    openDialog('recommendedaction.ivp/view/' + aid, 'recommendedaction', { width: 700, height: 350 });
    return false;
}

function deleteRecommendedActions() {
    var ids = new Array();
    $('#recommendedactions input[name=id]:checked').each(function (i, el) { ids.push(el.value); });
    if (ids.length == 0) { alert(WorkflowResources.CheckRecommendationToMark); return false; }
    if (!confirm(WorkflowResources.SureDeleteRecommendat)) return false;
    $('#recommendedactions').load(base + 'recommendedaction.ivp/delete', { tb_workflowid: $('#id').val(), ids: ids }, function () { });
    return false;
}

function setTab(id, linkId) {
    if (!documentReady) return false;

    if ($(".popupwrapper").length)
        $(".popupwrapper").hide();

    $("#rolesfilter").hide();

    $('input#tab').val(id);

    $('.tab').each(function (i, el) { if (el.id == id) $(el).show(); else $(el).hide(); });
    $('#tabs>ul>li>a').each(function (i, el) { if (el.id == 'a' + id) $(el).addClass('selected'); else $(el).removeClass('selected'); });
    if ((id == 'workflow' && $("#graphicview").css("display") != "none") || id == 'notificationruleroles' || id == 'recommendedactions' || id == 'workflowrules') {
        $('#savesubmit').attr('disabled', true);
        $('.saveandreturn').attr('disabled', true);
    }
    else {
        $('#savesubmit').attr('disabled', false);
        $('.saveandreturn').attr('disabled', false);
    }


    return false;
}

function setTrTab(id) {
    if (!documentReady) return;

    if ($("#transitiontabs span.activeswitch a").attr("id") == 'a' + id)
        return false;

    $('input#trtab').val(id);
    $('.transitiontab').each(function (i, el) { if (el.id == id) $(el).show(); else $(el).hide(); });
    $('#transitiontabs a').each(function (i, el) {
        if (el.id == 'a' + id)
            $(el)[0].outerHTML = '<span class="activeswitch">' + $(el)[0].outerHTML + '</span>';
        else $(el).closest('span')[0].outerHTML = $(el)[0].outerHTML;
    });

    if (id == 'graphicview') {
        disableButtons();
        setDrawArea();
        if (!flowchartinit)
            initFlowchart();
    } else {
        disableButtons();
    }

    return false;
}

function syncRoles() {
    if ($('#defaultroleid').length) {
        var sel = $('#defaultroleid').get(0);
        var oldval = sel.value;
        sel.options.length = 0;

        $('select#rid option:selected').each(function (i, o) {
            $(sel).append('<option value="' + o.value + '">' + o.text + '</option>');
        });
        $(sel).val(oldval);

    }
}

function askAboutChanges() {
    if (formchanged == true)
        return confirm(WorkflowResources.AskAboutChanges);

    return true;
}

function showAutomaticRule(link) {
    var div = $(link).closest('.tostatus').find('div.auto');
    div.show();
    $('select', div).addClass('required');
    $(link).hide();
    $("div.cancelAuto").show();
    return false;
}

function cancelAuto(link) {
    var div = $(link).closest('.tostatus').find('div.auto');
    div.hide();
    $('select', div).removeClass('required');
    $(link).parents('.tostatus').find('a.autolink').show();
    div.find('input').val(0);
    return false;
}

function deleteAuto(id, link) {
    var div = $(link).closest('.tostatus').find('div.auto');
    $('#time_' + id + '_ajax').val(0); $('#minutes_' + id + '_ajax').val(0);
    $("#createAuto").removeClass("hidden");
    $("#deleteAuto").addClass("hidden");
    div.hide();
    return false;
}
function showAutoLink() {
    $('.divautolink').show();
    $('#changeAuto').hide();
    $('#deleteAuto').hide();
    return false;
}

function createRule(button) {
    var div = button.parentNode;
    var toid = $('#tostatusid', div).val();
    var roles = new Array();
    $('.cb', div).each(function (i, cb) { if (cb.checked) roles.push(cb.value); });

    if (!toid || toid == "0") { alert(WorkflowResources.ChooseStatus); $('#tostatusid', div).focus(); return; }
    if (roles.length == 0) { alert(); return; }

    $.post(base + 'workflow.ivp/createrule', $('.data', div).serializeArray(), ruleCreated, "json");
}

function ruleCreated(result) {
    if (!result.IsOK) alert(result.Description);
    else loadWorkflow(true);
}

function deleteRule(id) {
    $.getJSON(base + 'workflow.ivp/deleterule/' + id, { date: new Date().toString() }, ruleDeleted);
}

function ruleDeleted(result) {
    if (!result.IsOK) alert(result.Description);
    else loadWorkflow(true);
}

function copy() {
    if (!$('#newname').val()) { alert(WorkflowResources.NewNameRequired); return; }
    var name = ($.browser.msie) ? encodeURIComponent($('#newname').val()) : $('#newname').val();
    var url = base + 'workflow.ivp/copy?id=' + $('#id').val() + '&name=' + name;
    document.location.href = url;
    return false;
}

function deleteADGroupService(adGroupServiceId) {
    $('#syncadgroups').load(
        base + 'adgroupservice.ivp/deleteadgroupservice/' + adGroupServiceId,
        {
            adgroupserviceid: adGroupServiceId
        }, function () {
            loadSyncADGroups(true);
        }
    );

    return false;
}

/*roles*/

function deleteRole(roleId, id, onlyItem) {
    var role = roleId;
    var length = role.parent().find('li').length - 1;
    //раскрас изменений
    role.closest(".row").removeClass('new').addClass('changed');
    if (length <= 0)
        role.closest('tr').hide();
    $("#sel_" + roleId.closest("ul").attr("id")).find("option[value='" + id + "']").removeAttr("selected");

    var rowId = role.attr('id');
    if (rowId.indexOf('conc') > -1) {
        var fieldsetId = role.closest('div').find('fieldset').attr('id');
        var table = role.closest("table[id*='conc']");
        //Для табличного вида удаляется вся строка, для графического - только элемент списка
        if (!onlyItem) role.closest('tr').remove();
        else $(roleId).remove();
        if (rowId.indexOf('user') > -1) {
            $('#' + fieldsetId + '_uposition' + id).remove();
        }
        if (rowId.indexOf('group') > -1) {
            $('#' + fieldsetId + '_egposition' + id).remove();
        }
        if (rowId.indexOf('frole') > -1) {
            $('#' + fieldsetId + '_frposition' + id).remove();
        }
        if (rowId.indexOf('role') > -1) {
            $('#' + fieldsetId + '_rposition' + id).remove();
        }
        table.trigger('change');
    } else {
        role.remove();
    }

}

function roleSelected(e, d) {
    var name = d[1];
    var froledescription = d[2];
    var id = d[3];
    var froles = d[4];
    var roles = d[5];
    var users = d[6];
    var holderId = null;
    var type = null;
    var spanName = "";

    if (froles == "True") {
        holderId = $(e.target).closest('div').find('#froles');
        type = "frole";
        spanName = WorkflowResources.FunctionalRoles;
    }
    if (roles == "True") {
        holderId = $(e.target).closest('div').find('#roles');
        type = "role";
        spanName = WorkflowResources.Roles;
    }
    if (users == "True") {
        holderId = $(e.target).closest('div').find('#users');
        type = "user";
        spanName = WorkflowResources.Users;
    }
    $(e.target).val('');
    if (holderId != null && holderId.length > 0)
        addRole(holderId, name, id, froledescription);
    else {
        utype = $('#' + this.id);
        holderId = $(e.target).closest('div');
        addRole(holderId, name, id, froledescription, spanName, type);

    }
}

function addRole(holderId, name, id, description, spanName, type) {

    var ul = holderId.find('ul');
    var html = "";

    //WTF fix #22898: If this user or role or functionnal role is already exist, then cancel adding.
    var exists = false;
    ul.each(function (i, value) {
        if (ul.find('#' + value.id + '_' + id).size())
            exists = true;
    });
    if (exists) return;
    var table = holderId.find("table[id*='conc']");
    if (table.length > 0) {
        addToGroupFieldset(type, id);
        var concId = table.attr('id').replace('conc_', '');
        html += "<tr>";
        html += "<td class='middle' width='27%'>" + spanName + "</td>";
        html += "<td class='middle' width='73%'>";
        html += "<ul class='holder parent' id='conc_" + type + "_" + concId + "'>";
        html += "<li class='bit-box' id='conc_" + type + "_" + concId + "_" + id + "'>" + name;
        html += "<a href='#' class='closebutton' onclick=\"deleteRole($(this).parent(),'" + id + "'); return false;\"></a>";
        html += "</li>" + "</ul>" + "</td>";
        html += "</tr>";
        table.append(html);
        //раскрас изменений
        ul.closest(".row").removeClass('new').addClass('changed');
    } else {
        if (typeof type !== 'undefined') {
            holderId = holderId.find('#' + type + 's');
            ul = holderId.find('ul');
        }

        var select = $('#sel_' + ul.attr('id'));
        var selected = holderId.find("#sel_" + ul.attr('id') + " option[value='" + id + "']:selected");
        ul.closest('tr').show();

        if (ul.length > 0 && ul.hasClass('conc2') || ul.attr('id').indexOf("user") >= 0 || ul.attr('id').indexOf("frole") >= 0) {
            var onlyItem = $('#dialog-form').length > 0 ? true : false;
            if (description == null)
                html += "<li class='bit-box' id='" + ul.attr('id') + "_" + id + "'>" + name;
            else
                html += "<li class='bit-box' id='" + ul.attr('id') + "_" + id + "' title='" + description + "'>" + name;
            html += "<a href='#' class='closebutton' onclick=\"deleteRole($(this).parent(),'" + id + "'," + onlyItem + "); return false;\"></a>";
            html += "</li>";
            ul.append(html);
            //раскрас изменений
            ul.closest(".row").removeClass('new').addClass('changed');
            if (holderId.attr('id') != "users" && holderId.attr('id') != "groups")
                select.find("option[value='" + id + "']").attr("selected", true);
            else {
                if (select.find("option[value='" + id + "']").length <= 0)
                    select.append($("<option></option>").attr("value", id).attr("selected", true).text(name));
                else
                    select.find("option[value='" + id + "']").attr("selected", true);
            }
        } else {
            if (selected.length <= 0) {

                if (description == null)
                    html += "<li class='bit-box padright' id='" + ul.attr('id') + "_" + id + "'>" + name;
                else
                    html += "<li class='bit-box padright' id='" + ul.attr('id') + "_" + id + "' title='" + description + "'>" + name;
                html += " <img src='img/btn.png' class='buttonExist hidden'/>";
                html += " <img src='img/additional.png' class='buttonAdditional hidden'/>";
                html += " <img src='img/RequiredFields.png' class='buttonRequiredFields hidden'/>";
                html += " <img src='img/commentReq.png' class='buttonComment hidden'/>";
                html += " <span class='context' range='role' itemid='" + id + "' id='role'" + id + "><img title='Показать контекстное меню' src='img/contextmenu.gif'/></span>";
                // html += "<a href='#' class='closebutton' onclick=\"deleteRole($(this).parent(),'" + id + "'); return false;\"></a>";
                html += "</li>";
                ul.append(html);
                //раскрас изменений
                ul.closest(".row").removeClass('new').addClass('changed');
                if (holderId.attr('id') != "users")
                    select.find("option[value='" + id + "']").attr("selected", true);
                else {
                    if (select.find("option[value='" + id + "']").length <= 0)
                        select.append($("<option></option>").attr("value", id).attr("selected", true).text(name));
                    else
                        select.find("option[value='" + id + "']").attr("selected", true);
                }
            }
        }
    }
    table.trigger('change');
}

var WorkflowRoles = {
    selectRoles: function selectRoles(link) {
        var url = 'workflow.ivp/selectroles/' + $('#id').val() + '?cbmode=WorkflowRoles';
        /*ssid = null;
        tsid = null;*/
        utype = link;
        dlg = openDialog(url, 'selectroles', { width: 900, height: 650 });
        dlg.callback = WorkflowRoles.workflowsCallback
        return false;
    },
    workflowsCallback: function workflowsCallback(result) {
        var fids = result["selectedFunctionalRoles"];
        var rids = result["selectedRoles"];
        var uids = result["selectedUsers"];
        var gids = result["selectedGroups"];
        var fRolesNames = result["functionalRoleNames"];
        var fRolesDescription = result["functionalRoleDescriptions"];
        var roleNames = result["roleNames"];
        var selectedNames = result["userNames"];
        var selectedGroups = result["groupNames"];
        addSelected(fids, rids, uids, gids, fRolesNames, fRolesDescription, roleNames, selectedNames, selectedGroups);
    }
}

var WorkflowRolesConcurrence = {
    selectRolesConc: function selectRolesConc(link) {
        var url = 'workflow.ivp/selectrolesconcurrence/' + $('#id').val() + '?cbmode=WorkflowRolesConcurrence';
        utype = link;
        ssid = null;
        tsid = null;
        dlg = openDialog(url, 'selectroles', { width: 900, height: 650 });
        dlg.callback = WorkflowRolesConcurrence.workflowsCallback;
        return false;
    },
    workflowsCallback: function workflowsCallback(result) {
        var fids = result["selectedFunctionalRoles"];
        var rids = result["selectedRoles"];
        var uids = result["selectedUsers"];
        var gids = result["selectedGroups"];
        var fRolesNames = result["functionalRoleNames"];
        var fRolesDescription = result["functionalRoleDescriptions"];
        var roleNames = result["roleNames"];
        var selectedNames = result["userNames"];
        var selectedGroups = result["groupNames"];
        addSelected(fids, rids, uids, gids, fRolesNames, fRolesDescription, roleNames, selectedNames, selectedGroups);
    }
}

var WorkflowStatuses = {
    selectStatuses: function selectStatuses(link) {
        var url = 'workflow.ivp/selectstatuses/' + $('#id').val() + '?cbmode=WorkflowStatuses';
        utype = link;
        dlg = openDialog(url, 'selectstatuses', { width: 900, height: 650 });
        dlg.callback = WorkflowStatuses.workflowsCallback;

        return false;
    },
    workflowsCallback: function workflowsCallback(result) {
        var ids = result["selectedIds"];
        var names = result["selectedNames"];
        addSelectedSt(ids, names);
    }        
}

var WorkflowRequiredFields = {
    selectRequiredFields: function selectRequiredFields(link) {
        var url = 'workflow.ivp/SelectRequiredFields/' + $('#id').val() + '?cbmode=WorkflowRequiredFields';
        utype = link;
        dlg = openDialog(url, 'selectRequiredFields', { width: 900, height: 650 });
        dlg.callback = WorkflowRequiredFields.workflowsCallback;                    
        return false;
    },
    workflowsCallback: function workflowsCallback(result) {
        mfids = result["selectedMainFields"];
        fids = result["selectedFields"];
        mainFieldsNames = result["selectedMainFieldsNames"];
        fieldsNames = result["selectedFieldsNames"];
        addSelectedRequiredFields(fids, mfids, fieldsNames, mainFieldsNames);
    }
}


//!!!!делаем заглушку! для согласования не менялось ничего и нужно использовать utype
//переделать под новые селекты
function addSelected(fids, rids, uids, gids, fRolesNames, fRolesDescription, roleNames, userNames, groupNames) {
    if (fids.length > 0) {
        fids.forEach(function (id) {
            var frn = fRolesNames['id' + id];
            var frd = fRolesDescription['id' + id];
            var spanName = "";
            var type = "";
            if (ssid || ssid == 0) {
                var holderId = $("#div_" + ssid + "_" + tsid + " #froles");
            }
            else {
                var holderId = utype.closest('div');
                spanName = WorkflowResources.FunctionalRoles;
                type = 'frole';
            }
            addRole(holderId, frn, id, frd, spanName, type);
        });
    }
    if (rids.length > 0) {
        rids.forEach(function (id) {
            var rn = roleNames['id' + id];
            var spanName = "";
            var type = "";
            if (ssid || ssid == 0) {

                var holderId = $("#div_" + ssid + "_" + tsid + " #roles");
            }
            else {

                var holderId = utype.closest('div');
                spanName = WorkflowResources.Roles;
                type = 'role';
            }
            addRole(holderId, rn, id, null, spanName, type);
        });
    }
    if (uids.length > 0) {
        uids.forEach(function (id) {
            var un = userNames['id' + id];
            var spanName = "";
            var type = "";
            if (ssid || ssid == 0) {
                var holderId = $("#div_" + ssid + "_" + tsid + " #users");
            }
            else {
                var holderId = utype.closest('div');
                spanName = WorkflowResources.Users;
                type = 'user';
            }
            addRole(holderId, un, id, null, spanName, type);
        });
    }
    if (gids.length > 0) {
        gids.forEach(function (id) {            
            var gn = groupNames['id' + id];
            var spanName = "";
            var type = "";
            if (ssid || ssid == 0) {
                var holderId = $("#div_" + ssid + "_" + tsid + " #groups");
            }
            else {
                var holderId = utype.closest('div');
                spanName = WorkflowResources.ExecutorGroups;
                type = 'group';
            }
            addRole(holderId, gn, id, null, spanName, type);
        });
    }
}

//добавление дополнительных условий для перехода
function addSelectedSt(ids, names) {
    if (ids.length > 0) {
        var roleid = utype.attr("roleid");

        var select = $('#additional_' + utype.attr("idul"));        
        var statusString = '';

        statusString += WorkflowResources.ConditionStatuses;
        $.each(ids, function (i, id) {
            //if ('#additional_' + utype.attr("idul"))
            if (select.find("option[value='role_" + roleid + "|" + id + "|']").length <= 0) {
                var rn = names['id' + id];
                select.append($("<option></option>").attr("value", "role_" + roleid + "|" + id + "|").attr("selected", true).text(rn));
            }
            else {
                select.find("option[value='role_" + roleid + "|" + id + "|']").attr("selected", true);
            }
            if (i == ids.length) statusString += rn;
            else statusString += rn + ',';

        });

        var img = '#' + utype.attr("idul") + '_' + roleid;
        $(img + ' img.buttonAdditional').filter(":first").attr('title', statusString);
        $(img + ' img.buttonAdditional').filter(":first").removeClass('hidden');

        select.closest(".row").removeClass('new').addClass('changed');
    }
}

//добавление обязательных полей для перехода
function addSelectedRequiredFields(fids, mfids, fieldsNames, mainFieldsNames) {
    var isMainFieldsRequired = mfids.length > 0;
    var isTypeFieldsRequired = fids.length > 0;
    if (isTypeFieldsRequired || isMainFieldsRequired) {
        var roleid = utype.attr("roleid");
        var statusString = '';
        var tasktypeFielsString = '';
        var mainFieldsString = '';
        if (isTypeFieldsRequired) {
            var selectFields = $('#typeFieldRequired_' + utype.attr("idul"));
            var arrayFieldsLength = fids.length;

            tasktypeFielsString = WorkflowResources.RequiredTaskTypeFieldsImgTitle;
            $.each(fids, function (i, id) {
                //if ('#additional_' + utype.attr("idul"))
                if (selectFields.find("option[value='role_" + roleid + "|" + id + "|']").length <= 0) {
                    var rn = fieldsNames['id' + id];
                    selectFields.append($("<option></option>").attr("value", "role_" + roleid + "|" + id + "|").attr("selected", true).text(rn));
                }
                else {
                    selectFields.find("option[value='role_" + roleid + "|" + id + "|']").attr("selected", true);
                }
                if (i == arrayFieldsLength) tasktypeFielsString += rn;
                else tasktypeFielsString += rn + ', ';

            });
            selectFields.closest(".row").removeClass('new').addClass('changed');
        }
        if (isMainFieldsRequired) {
            var selectmainFields = $('#mainFieldRequired_' + utype.attr("idul"));
            var arrayMainFieldsLength = mfids.length;

            mainFieldsString = WorkflowResources.RequiredMainFieldsImgTitle;
            $.each(mfids, function (i, id) {
                //if ('#additional_' + utype.attr("idul"))
                if (selectmainFields.find("option[value='role_" + roleid + "|" + id + "|']").length <= 0) {
                    var rn = mainFieldsNames['id' + id];
                    selectmainFields.append($("<option></option>").attr("value", "role_" + roleid + "|" + id + "|").attr("selected", true).text(rn));
                }
                else {
                    selectmainFields.find("option[value='role_" + roleid + "|" + id + "|']").attr("selected", true);
                }
                if (i == arrayMainFieldsLength) mainFieldsString += rn;
                else mainFieldsString += rn + ', ';

            });
            selectmainFields.closest(".row").removeClass('new').addClass('changed');
        }

        if (isMainFieldsRequired) statusString = mainFieldsString;
        if (isMainFieldsRequired && isTypeFieldsRequired) statusString += "; ";
        if (isTypeFieldsRequired) statusString += tasktypeFielsString;

        var img = '#' + utype.attr("idul") + '_' + roleid;
        $(img + ' img.buttonRequiredFields').filter(":first").attr('title', statusString);
        $(img + ' img.buttonRequiredFields').filter(":first").removeClass('hidden');
    }
}


function addToGroupFieldset(type, id) {
    var fieldType = "";
    switch (type) {
        case 'user':
            fieldType = 'uposition';
            break;
        case 'role':
            fieldType = 'rposition';
            break;
        case 'frole':
            fieldType = 'frposition';
            break;
        case 'group':
            fieldType = 'egposition';
            break;
    }

    var fieldset = utype.closest('div').find('fieldset');
    var fieldsetId = fieldset.attr('id');
    fieldset.append('<input id="' + fieldsetId + '_' + fieldType + id + '" name="' + fieldsetId + '_' + fieldType + id + '" value="' + id + '" type="hidden"/>');
}