//None of page-specific functions should be placed here.
/// <reference path="jquery.intellisense.js"/>
/// <reference path="ru.js"/>

var dynamicAnchors = [[0, 1, 0, 1, 10, -24], [0, 1, 0, 1, 20, -24], [0, 1, 0, 1, 30, -24],  // низ иконки
                        [0, 0, -0.2, -1, 10, 0], [0, 0, 0, -1, 20, 0], [0, 0, 0.2, 1, 30, 0],  // верх иконки
                        [0, 0.5, -1, 0, 0, -12], [0, 0.5, -1, 0, 0, -5], [0, 0.5, -1, 0, 0, -20],
                        [1, 0.5, 1, 0, 0, -12], [1, 0.5, 1, 0, 0, -12], [1, 0.5, 1, 0, 0, -22]];


; (function () {

    window.jsPlumbDemo = {

        init: function () {


            jsPlumb.importDefaults({
                RenderMode: "svg",
                Endpoint: ["Blank"],
                PaintStyle: { strokeStyle: "rgb(160,160,160)", lineWidth: 2 },
                Connector: ["StateMachine", { proximityLimit: 300 }],
                HoverPaintStyle: { strokeStyle: "#42a62c", lineWidth: 2, opacity: 0.2 },
                ConnectionOverlays: [
                    ["PlainArrow", {
                        location: 1,
                        id: "arrow",
                        length: 14,
                        width: 10,
                        length: 10
                    }],
	                ["Label", { label: WorkflowResources.MoveArrowToStatus, id: "label", location: 0.9 }]
                ]
            });

            jsPlumb.draggable(jsPlumb.getSelector(".w"), {
                handle: ".dh", containment: "parent", scroll: false, stop: function () {
                    saveStatusPosition($(this));
                }
            });

            jsPlumbDemo.initEndpoints();

            jsPlumb.bind("jsPlumbConnection", function (conn) {
                conn.connection.getOverlay("label").setLabel('');
            });

            jsPlumb.makeTarget(jsPlumb.getSelector(".w"), {
                dropOptions: { hoverClass: "dragHover" }
            });
        }
    };

    jsPlumbDemo.initEndpoints = function () {
        $(".ep").each(function (i, e) {
            var p = $(e).parent();
            jsPlumb.makeSource($(e), {
                parent: p,
                maxConnections: 0
            });
        });
    };

    jsPlumb.bind("beforeDrop", function (params) {
        var _target = $("#" + params.targetId);

        var _ssid = $("#" + params.sourceId).data("sid");
        var _tsid = _target.data("sid");

        if (_ssid == _tsid)
            return false;

        if (_tsid == 0) // запрет перевода в статус "Новая заявка"
        {
            alert(WorkflowResources.AlertTransitionToNewStatus);
            return false;
        }

        $(".ui-dialog .ui-dialog-title").html(FormatString(WorkflowResources.TransitionDescription, new Array($.trim($("#" + params.sourceId + " span").first().html()), $.trim($("#" + params.targetId + " span").first().html()))));

        $('#dialog-form').data("sourceId", params.sourceId);
        $('#dialog-form').data("targetId", params.targetId);

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



            $('#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);

        if (jsPlumb.select({ source: params.sourceId, target: params.targetId }).length > 0) // уже заданы пользовательские переходы и автопереходы
            return false;
        else
            return true;
    });

    jsPlumb.bind("ready", function () {
        document.onselectstart = function(obj) {
            if (!($.browser.msie && $.browser.version <= "8")
                && obj != undefined && obj.target != undefined
                && obj.target.localName != "input" && obj.target.localName != "textarea")
            {
                return false;
            }
        };
        jsPlumbDemo.init();
    });

    jsPlumb.bind();
    $("a.cancel").live("click", function () {
        $("#ssdialog").remove();
        return false;
    });
    $("a.ok").live("click", function () {
        $("#ssdialog").remove();
        return true;
    });

})();

/*positions*/


function showConnections(data) {

    jsPlumb.deleteEveryEndpoint();

    ns = {
        svg: "http://www.w3.org/2000/svg",
        xhtml: "http://www.w3.org/1999/xhtml"
    };
    _attr = function (node, attributes) {
        for (var i in attributes)
            node.setAttribute(i, "" + attributes[i]);
    };

    _node = function (name, attributes) {
        var n = document.createElementNS(ns.svg, name);
        attributes = attributes || {};
        attributes["version"] = "1.1";
        attributes["xmlns"] = ns.xhtml;
        _attr(n, attributes);
        return n;
    };

    _getPointOnPath = function (P0, P1, P2, t) {
        return (1 - t * t * t) * P0 + 3 * t * (1 - t) * (1 - t) * P1 + 3 * t * t * (1 - t) * P1 + t * t * t * P2;
    };
    _reBeizerPoint = function (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 (C - (1 - t * t * t) * P0 - t * t * t * P2) / d;
    };
    $.each(data, function () {
        var sid = $(this).attr("SourceId");
        var tid = $(this).attr("TargetId");

        var wfsid = "sid_" + sid;
        var wftid = "sid_" + tid;

        if (wfsid == wftid)
            return true;

        var _wfsid = $("#flowchart #" + wfsid).data("sid");
        var _wftid = $("#flowchart #" + wftid).data("sid");

        if (typeof (_wfsid) == "undefined" || typeof (_wftid) == "undefined")
            return true;

        var label = '<ul class="holder parent" data-sid=' + sid + ' data-tid=' + tid + ' data-wfsid=' + _wfsid + ' data-wftid=' + _wftid + '>';
        label += $(this).attr("Title") + '</ul>';

        var paintStyle = { lineWidth: 2, strokeStyle: "rgb(130,130,130)" };
        if ($(this).attr("IsAuto") == 2)
            paintStyle = { lineWidth: 2, strokeStyle: "rgb(60,60,60)", dashstyle: "4 2", joinstyle: "miter" };
        else if ($(this).attr("IsAuto") == 1)
            paintStyle = { lineWidth: 2, strokeStyle: "rgb(130,130,130)", dashstyle: "10 2", joinstyle: "miter" };


        var e1 = jsPlumb.addEndpoint(wfsid, {
            isSource: true,
            endpoint: "Blank",
            anchor: "Continuous"
        });

        var e2 = jsPlumb.addEndpoint(wftid, {
            isTarget: true,
            endpoint: "Blank",
            anchor: "Continuous"
        });

        var conn = jsPlumb.connect({
            source: e1, target: e2, paintStyle: paintStyle,
            connector: ["StateMachine", { curvinessX: $(this).attr("CurvinessX"), curvinessY: $(this).attr("CurvinessY"), proximityLimit: 0 }]
        });

        conn.bind("click", function (el, e) {
            if (e.target.nodeName != "path")
                return;

            $("._jsPlumb_overlay").show();
            //$("._jsPlumb_connector").css("z-index", 998);
            $(el.canvas).attr("id", "activeSVG");

            $("#marker").remove();
            $("#flowchart").off("mousedown.marker");

            var x0 = el.connector.path.pathSegList.getItem(0).x; // start
            var y0 = el.connector.path.pathSegList.getItem(0).y; // 

            var x1 = el.connector.path.pathSegList.getItem(1).x1; // middle
            var y1 = el.connector.path.pathSegList.getItem(1).y1; // 

            var x2 = el.connector.path.pathSegList.getItem(1).x; // end
            var y2 = el.connector.path.pathSegList.getItem(1).y; // 

            var c = _node("circle", {
                "cx": getPointOnPath(x0, x1, x2, 0.5),
                "cy": getPointOnPath(y0, y1, y2, 0.5),
                "r": 4,
                "pointer-events": "all",
                "id": "marker",
                "data-source_id": sid,
                "data-target_id": tid,
                "data-sid": wfsid,
                "data-tid": wftid
            });

            el.canvas.appendChild(c);
            $("#marker").css("z-index", 999);
            var overlay = $(el.canvas).next("div");
            overlay.hide();

            $("body").on("mousedown.marker", function (el) {
                if (el.target.nodeName != "circle" && el.target != conn.connector.path) {
                    overlay.show();
                    $("#marker").remove();
                    $("body").off("mousedown.marker");
                    $("#activeSVG").removeAttr("id");
                    $("._jsPlumb_overlay").on("mouseenter", overlayMouseEnter);
                }
            });

            $("._jsPlumb_overlay").off("mouseenter");

        });

        conn.getOverlay("label").setLabel(label);
        conn.getOverlay("label").setLocation($(this).attr("LabelLocation"));

    });
    
    
    // просмотр / изменение параметров перехода
    $("._jsPlumb_overlay").on(
        {
            mouseenter: overlayMouseEnter,
            mouseleave: overlayMouseLeave,
            click: function () { return false; }
        });
}

function overlayMouseEnter() {
    if ($(this).find("li.editTransition").length)
        return;
    $("._jsPlumb_overlay").css({ "border": "none", "background": "transparent" });
    $("li.editTransition").remove();

    var left = $(this).position().left;
    $(this).css({ "left": left, "border": "1px solid #aaa", 'border-radius': '10px', 'background-color': '#eee' });
    $(this).children("ul").append('<li class="editTransition" style="text-align:right; width:180px; margin-top:10px;">' +
                '<div class="dh cbtn" style="display:inline; margin-top:10px; visibility:visible;" title="' + WorkflowResources.Move + '"></div>' +
                '<a id="editTransition" href=# onclick="return false;">' + WorkflowResources.ChangeTransition + '</a>' +
                '<a id="deleteTransition" href=# onclick="return false;">' + WorkflowResources.DeleteTransition + '</a>' +
                '</li>');

    var holder = $(this).find("ul").first();
    var wfsid = "sid_" + holder.data("sid");
    var wftid = "sid_" + holder.data("tid");

    $(this).draggable({
        containment: "parent", handle: ".dh",
        stop: function (e) {
            //calculate location
            conn = jsPlumb.getConnections({ source: wfsid, target: wftid })[0];

            var _cleft = $(conn.canvas).offset().left, _ctop = $(conn.canvas).offset().top;
            var xl = $(this).offset().left, yl = $(this).offset().top;

            if (navigator.userAgent.search(/Firefox/) > -1) {
                _cleft = parseInt($(conn.canvas).css("left")) + 32;
                _ctop = parseInt($(conn.canvas).css("top")) + 218;

                xl = parseInt($(this).css("left")) + 32;
                yl = parseInt($(this).css("top")) + 218;
            }

            var x1 = conn.connector.path.pathSegList.getItem(0).x + _cleft, y1 = conn.connector.path.pathSegList.getItem(0).y + _ctop,
                x2 = conn.connector.path.pathSegList.getItem(1).x1 + _cleft, y2 = conn.connector.path.pathSegList.getItem(1).y1 + _ctop,
                x3 = conn.connector.path.pathSegList.getItem(1).x + _cleft, y3 = conn.connector.path.pathSegList.getItem(1).y + _ctop;

            var _pos = 0.01, _t = 0.01;
            var _d = (x1 - xl) * (x1 - xl) + (y1 - yl) * (y1 - yl);

            do {
                var _tx = getPointOnPath(x1, x2, x3, _t);
                var _ty = getPointOnPath(y1, y2, y3, _t);
                if (_d > ((xl - _tx) * (xl - _tx) + (yl - _ty) * (yl - _ty)))
                    _pos = _t;

                _d = (xl - _tx) * (xl - _tx) + (yl - _ty) * (yl - _ty);
                _t += 0.005;
            } while (_t <= 0.99);

            //save label location
            $.ajax({
                type: "POST",
                url: base + 'workflow.ivp/saveLabelLocation/' + $('#id').val(),
                data: { source_id: $("#" + wfsid).data("sid"), target_id: $("#" + wftid).data("sid"), labelLocation: _pos },
                success: function () {
                    jsPlumb.getConnections({ source: wfsid, target: wftid })[0].getOverlay("label").setLocation(_pos);
                }
            });
        }
    });

    //удаляем с перехода выбранные роли/фроли/пользователей/автопереходы
    $("#deleteTransition").click(function () {
        if (!confirm(WorkflowResources.SureDeleteTransition))
            return false;

        $.ajax({
            type: "POST",
            url: base + 'workflow.ivp/deleteSelectedFromTransition/' + $('#id').val(),
            data: { target_id: holder.data("tid"), source_id: holder.data("sid") },
            success: function () {
                hideRoles();
            }
        });
        return false;
    });

    $("#editTransition").click(function () {
        $(".ui-dialog .ui-dialog-title").html(FormatString(WorkflowResources.TransitionDescription, new Array($.trim($("#" + wfsid + " span").first().html()), $.trim($("#" + wftid + " span").first().html()))));
        $('#dialog-form').data("sourceId", wfsid);
        $('#dialog-form').data("targetId", wftid);

        $('#dialog-form').load(base + 'workflow.ivp/TransitionPropertiesFormAJAX/' + $('#id').val() + '/' + holder.data("sid") + '/' + holder.data("tid"), function () {
            $('input.addroles').autocomplete(base + 'workflow.ivp/findroles/' + $('#id').val(), { minChars: 1 }).result(roleSelected).focus();

            $('#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);
    });
}

function overlayMouseLeave(e) {
    if (e.target.nodeName.toUpperCase() == "SPAN")
        return;
    $(this).css({ "border": "none", "background": "transparent" });
    $(this).find("li.editTransition").remove();
}