/// <reference path="../jquery.intellisense.js"/>
/// <reference path="../common.js"/>
/// <reference path="../ru.js"/>
/// <reference path="../workflow/flowchart.js"/>
var flowchartinit = false;
var curvinessX = 0;  // ?
var curvinessY = 40; // ?

$("document").ready(function () {
    if ($.cookies.get("hideGraphicMenu"))
        $(".hideMenu").click();

    $("#marker").live({
        mousedown: markerMouseDown
        //mouseup:markerMouseUp 
    });

  

    $("svg path").live(//just4usability
        {
            click: function () {
                $(this).closest("._jsPlumb_connector").addClass("active");
            },

        }
    );

});

function initFlowchart() {

    // сворачиваемость меню
    $(".hideMenu").on("click", hideMenu);
    $(".showMenu").on("click", showMenu);

    // блокируем кнопки сохранения
    $('#savesubmit').attr('disabled', true);
    $('.saveandreturn').attr('disabled', true);

    //уведомления
    var notyTimer;

    $.noty.defaults = {
        layout: 'inline', theme: 'defaultTheme', type: 'error', text: '', dismissQueue: true, // If you want to use queue feature set this true
        template: '<div class="noty_message" style="z-index:999;"><span class="noty_text"></span><div class="noty_close"></div></div>',
        animation: { open: { height: 'toggle' }, close: { height: 'toggle' }, easing: 'swing', speed: 10 },
        callback: "", modal: false, closeWith: ['click'], buttons: false // an array of buttons
    };

    //скрытие переходов
    $("#rolesfilter input:checkbox").on("change", function () {
        if ($(this).attr("id") != "allTransitions" && $("#allTransitions").attr("checked"))
            $("#allTransitions").removeAttr("checked");

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

        if ($(this).attr("id") != "allTransitions")
            hideRoles();
    });

    $("#allTransitions").on("change", function () {
        if ($(this).attr("checked"))
            $("#rolesfilter input:checkbox").attr("checked", "");
        else
            $("#rolesfilter input:checkbox").removeAttr("checked");

        hideRoles();
    });


    //hover скрытие управляющих элементов
    $(".w").on({
        mouseenter: function () {
            $(this).children(".cbtn").css("visibility", "visible");
            $(this).children(".clear").css("border-bottom", "1px solid #346789");
        },
        mouseleave: function () {
            $(this).children(".cbtn").css("visibility", "hidden");
            $(this).children(".clear").css("border", "none");
        }
    });

    //создание нового перехода
    $(".ep").on({
        click: function (eo) {
            $(".scrollable").append('<div id="noty"></div>');
            $("#noty").css("position", "absolute");
            $("#noty").css("left", eo.pageX + 50);
            $("#noty").css("top", eo.pageY - 120);
            $("#noty").noty({ text: WorkflowResources.MoveArrowToStatus });
        },
        mousedown: function (eo) {
            notyTimer = setTimeout(
            function () {
                $(".scrollable").append('<div id="noty"></div>');
                $("#noty").css("position", "absolute");
                $("#noty").css("left", eo.pageX + 50);
                $("#noty").css("top", eo.pageY - 120);
                $("#noty").noty({ text: WorkflowResources.MoveArrowToStatus });
            }, 600);
        },
        mouseup: function () {
            clearInterval(notyTimer);
            $("#noty").remove();
        },
        mouseout: function () {
            clearInterval(notyTimer);
            $("#noty").remove();
        }
    });

    //согласование
    $(".con").on({
        click: function (eo) {
            var wfsid = $(this).closest(".w").data("sid");

            $(".ui-dialog .ui-dialog-title").html(FormatString(WorkflowResources.ConcurrenceDescription, new Array($.trim($(this).closest(".w").children("span").first().html()))));

            $('#dialog-form').load(base + 'workflow.ivp/ConcurrencePropertiesFormAJAX/' + $('#id').val() + '/' + wfsid, function () {
                $('input.addroles').autocomplete(base + 'workflow.ivp/findroles/' + $('#id').val(), { minChars: 1 }).result(roleSelected);

                $('#editAJAXForm').submit(function () {
                    var str = $(this).serialize();

                    $.ajax({
                        type: "POST",
                        url: $(this).attr("action"),
                        data: str,
                        success: function () {
                            $("#dialog-form").dialog("close");
                            hideRoles();
                        }
                    });
                    return false;
                });
            });
            $("#dialog-form").dialog("open");
            if ($("a.ui-dialog-titlebar-close").length > 0)
                $("a.ui-dialog-titlebar-close").bind("click", editAJAXFormCancel);
        }
    });


    $("#dialog:ui-dialog").dialog("destroy");

    // диалог изменения перехода
    $("#dialog-form").dialog({
        autoOpen: false,
        width: 580,
        modal: true,
        close: function () {
            $("#dialog-form").html("");
            $("#dialog-form div.new").remove();
        }
    });

    flowchartinit = true;
}

function editAJAXFormCancel() {
    $("#dialog-form").dialog("close");
    var wfsid = $("#dialog-form").data("sourceId");
    var wftid = $("#dialog-form").data("targetId");

    if (wfsid && wftid)
        if (jsPlumb.getConnections({ source: wfsid, target: wftid })[0].getOverlay("label").getLabel() == "")
            jsPlumb.select({ source: wfsid, target: wftid }).detach();
    return false;
}

function hideRoles() {
    $("body").append('<div id="HideContentWhileLoading"></div>');
    //костыль для ие, т.к. в нем offset не определен
    if ($("#content").offset()) {
        $("#HideContentWhileLoading").css("top", $("#content").offset().top);
        $("#HideContentWhileLoading").css("left", $("#content").offset().left);
        $("#HideContentWhileLoading").width($("#content").width());
        $("#HideContentWhileLoading").height($("#content").height());
    }

    var roleids = new Array();
    $('.rids:checked').each(function (i, id) { roleids.push($(this).val()); });

    var rids = roleids.join(',');

    $.post(base + '/workflow.ivp/getTransitions/' + $("#id").val(),
            {
                selectRoles: rids,
                showFRoles: $("#froles_null").attr("checked") ? true : false,
                showAuto: $("#autoTransitions").attr("checked") ? true : false,
                showUsers: $("#role_null").attr("checked") ? true : false,
                showConcurrence: $("#ShowConcurrence").attr("checked") || $("#allTransitions").attr("checked") ? true : false,
                showAllTransitions: $("#allTransitions").attr("checked") ? true : false,
                timestamp: new Date().toString()
            },
            function (data) {
                showConnections(data.Connections);
                $("#HideContentWhileLoading").remove();
                setTimeout(function () {
                    if ($("#printpage").val())
                        window.print();
                }, 100);
            }, "json");

    return false;
}

function reScale(increase) {
    var c = increase ? 1 : -1;

    flowchartFontSize = parseInt($("#flowchart").css("fontSize")) + c;
    holderFontSize = parseInt($("._jsPlumb_overlay ul.holder").css("fontSize")) + c;

    $("#flowchart").css({ "fontSize": flowchartFontSize + 'px' });
    //$("#flowchart b").css({ "fontSize": flowchartFontSize + 'px', 'font-weight':'bold'});
    $("#flowchart li").css({ "fontSize": flowchartFontSize + 'px' });

    img = $("#flowchart .w > img").width() + 2 * c;
    $("#flowchart .w > img").width(img);
    $("#flowchart .w > img").height(img);

    img = $("._jsPlumb_overlay li.overlay_title > img").width() + c;
    $("._jsPlumb_overlay li.overlay_title > img").width(img);
    $("._jsPlumb_overlay li.overlay_title > img").height(img);


    var Scale = increase ? 1.25 : 0.8;
    $(".w").each(function () {
        $(this).css("left", Math.round($(this).position().left * Scale));
        $(this).css("top", Math.round($(this).position().top * Scale));
    });

    $.ajax({
        type: "POST",
        data: { "increase": increase },
        url: base + 'workflow.ivp/changescale/' + $('#id').val(),
        success: function () {
            setDrawArea();
            saveStatusPosition($(".w"));
            jsPlumb.repaintEverything();
        }
    });

    return false;
}

function saveStatusPosition(el) {
    var postData = [];

    $(el).each(function () {
        var _i = $(this).data("sid");
        var _t = parseInt($(this).css("top"));
        var _l = parseInt($(this).css("left"));

        postData.push({ 'WorkflowStatusId': _i, 'CorTop': _t, 'CorLeft': _l });
    });

    postData = { 'statuses': postData };

    $.post(base + '/workflow.ivp/savePositions/' + $("#id").val(),
               { 'statuses': JSON.stringify(postData), 'timestamp': new Date().toString() },
               function () { return false; },
               "json");
    return false;
};

function resetgraphicsettings() {
    if (!confirm(WorkflowResources.ResetStatusPositions))
        return false;

    $.ajax({
        type: "POST",
        url: base + 'workflow.ivp/resetgraphicsettings/' + $('#id').val(),
        success: function () {
            hideRoles();
            if (confirm(WorkflowResources.RefreshForResetStatusPositions))
                location.reload();
        }
    });

    return false;
}

function showNoty(eo, text) {
    $("body").append('<div id="noty" style="width:720px;"><div class="popupwrapper indent20"><div class="popup"><div class="details"></div></div></div></div>');
    $("#noty").css("position", "absolute");
    $("#noty").css("left", $(eo).offset().left - 120);
    $("#noty").css("top", $(eo).offset().top + 20);
    $("#noty").css("z-index", 9999);
    $("#noty .details").append(text);
    $("#noty .popupwrapper").show();
}

function showConcurrence(workflow, fromstatus) {
    $(".ui-dialog .ui-dialog-title").html(FormatString(WorkflowResources.ConcurrenceDescription, new Array($.trim($("#" + $('#dialog-form').data("sourceId")).children("span").first().html()))));
    $('#dialog-form').load(base + 'workflow.ivp/ConcurrencePropertiesFormAJAX/' + workflow + '/' + fromstatus,
        function () {
            $('input.addroles').autocomplete(base + 'workflow.ivp/findroles/' + workflow, { minChars: 1 }).result(roleSelected);

            $('#editAJAXForm').submit(function () {
                var str = $(this).serialize();

                $.ajax({
                    type: "POST",
                    url: $(this).attr("action"),
                    data: str,
                    success: function () {
                        $("#dialog-form").dialog("close");
                        hideRoles();
                    }
                });
                return false;
            });
        });
    return false;
}

function getPointOnPath(P0, P1, P2, t) {
    P1 = P1 - P0;
    return (1 - t * t * t) * P0 + 3 * t * (1 - t) * (1 - t) * P1 + 3 * t * t * (1 - t) * P1 + t * t * t * P2;
}

function reBeizerPoint(P0, C, P2) {
    var t = 0.5;
    var d = 3 * t * (1 - t) * (1 - t) + 3 * t * t * (1 - t);
    if (d == 0) return 0;
    return P0 + (C - (1 - t * t * t) * P0 - t * t * t * P2) / d;
}

function hideMenu() {
    $(this).next().hide();
    $(this).removeClass("hideMenu");
    $(this).addClass("showMenu");
    $(this).html('<img src="img/actionPlus.png"/> ' + WorkflowResources.ShowMenu);
    $.cookies.set('hideGraphicMenu', true);
    $(".showMenu").on("click", showMenu);
};
function showMenu() {
    $(this).next().show();
    $(this).removeClass("showMenu");
    $(this).addClass("hideMenu");
    $(this).html('<img src="img/minus.png"/> ' + WorkflowResources.HideMenu);
    $.cookies.set('hideGraphicMenu', false);
    $(".hideMenu").on("click", hideMenu);
}

function markerMouseDown() {
    var circle = $(this);
    var svg = circle.closest("svg");

    document.onmousemove = function (e) {
        var x = e.pageX - svg.offset().left, y = e.pageY - svg.offset().top;

        if ($.browser.mozilla) {
            if ($.browser.version < 19) {
                x = e.pageX - parseInt(svg.css("left")) - 32;
                y = e.pageY - parseInt(svg.css("top")) - 218;
            } else {
                x = e.pageX - parseInt(svg.css("left")) - 0;
                y = e.pageY - parseInt(svg.css("top")) - 25;
            }
        }

        circle.attr("cx", x);
        circle.attr("cy", y);

        var conn = jsPlumb.getConnections({ source: circle.data("sid"), target: circle.data("tid") })[0];

        var x0 = conn.connector.path.pathSegList.getItem(0).x, y0 = conn.connector.path.pathSegList.getItem(0).y,
            x1 = conn.connector.path.pathSegList.getItem(1).x, y1 = conn.connector.path.pathSegList.getItem(1).y;

        var bx = reBeizerPoint(x0, x, x1), by = reBeizerPoint(y0, y, y1);
        var mx = Math.min(x1, x0) + (Math.max(x1, x0) - Math.min(x1, x0)) / 2, my = Math.min(y1, y0) + (Math.max(y1, y0) - Math.min(y1, y0)) / 2;

        curvinessX = bx - mx;
        curvinessY = by - my;

        conn.connector.setCurviness(curvinessX, curvinessY);
        conn.repaint();
    };
    document.onmouseup = function () {
        markerMouseUp();
        document.onmousemove = document.onmouseup = null;
    };
    return false;
}

function markerMouseUp() {
    $.ajax({
        type: "POST",
        url: base + 'workflow.ivp/saveConnectorCurviness/' + $('#id').val(),
        data: { source_id: $("#marker").data("source_id"), target_id: $("#marker").data("target_id"), curvinessX: curvinessX, curvinessY: curvinessY }
    });

    return false;
}

