$(document).ready(function() {
  var procesy = {};
  var res = {};
  var state = [];
  var panels = true;
  var menuShow = false;
  var sTimeout = false;
  $("#SE-menu").hide();
  $("#SE-menu-sub").hide();

  function translate(objId, arr) {
    var data = [];
    $.each(arr[objId]["childs"], function(indexChilds, childs) {
      var temp = {};
      var id = childs["ID"];
      var style = "";
      switch (arr[id]["TYPE"]) {
        case "PROCES_INIT":
          style = 'style="background-color:#ffe5e5;color:#333"';
          break;
        case "PROCES":
          style = 'style="background-color:#ededed;color:#333"';
          break;
        case "PROCES_GROUP_1":
          style = 'style="background-color:#9999cc;color:#fff"';
          break;
        case "PROCES_GROUP_2":
          style = 'style="background-color:#d8d8b2;color:#fff"';
          break;
        default:
          style = 'style="background-color:#ededed;color:#333"';
          break;
      }
      temp["id"] = id;
      if (TYPE == "childs") {
        temp["type"] = "proces";
      } else {
        if (arr[id]["TYPE"] == "STANOWISKO" || arr[id]["TYPE"] == "DZIAL" || arr[id]["TYPE"] == "PODMIOT") {
          temp["type"] = "stanowiska";
        } else {
          temp["type"] = "zasoby";
        }
      }
      temp["text"] = "<span class=detailsTable2 " + style + " >" + id + "</span> " + arr[id]["DESC"];
      temp["parent"] = arr[id]["PARENT_ID"];
      data.push(temp);
      //console.log(data);
      $.merge(data, translate(id, arr));
    });
    return data;
  }

  $(document).on('keyup', '#search', function(e) {
    if (sTimeout) {
      clearTimeout(sTimeout);
    }
    sTimeout = setTimeout(function() {
      var val = $('#search').val();
      $('#tree').jstree(true).search(val, false);
    }, 250);
  });

  function customMenu(node) {
    var tree = $("#tree").jstree(true);
    var id = node.id;
    var items = {};
    if (node.type === "proces") {
      items = {
        "ProcesEditor": {
          "separator_before": false,
          "separator_after": false,
          "label": "Edytor procesów",
          "action": function(obj) {
            window.location = BASE_URL + 'index.php?_route=UrlAction_procesEditor&id=' + id;
          }
        },
        "EditProces": {
          "separator_before": false,
          "separator_after": false,
          "label": "Edytuj proces",
          "action": function(obj) {
            window.location = BASE_URL + 'index.php?_route=ViewTableAjax&typeName=p5_default_db:CRM_PROCES#EDIT/' + id;
          }
        },
        "AddPytania": {
          "separator_before": false,
          "separator_after": true,
          "label": "Edytuj pytania",
          "action": function(obj) {
            window.location = BASE_URL + 'procesy5.php?task=CRM_TESTY_ADD_PYTANIA&id_proces=' + id;
          }
        },
        "ProcesMap": {
          "separator_before": false,
          "separator_after": false,
          "label": "Mapa procesu",
          "action": function(obj) {
            window.location = BASE_URL + 'index.php?FUNCTION_INIT=GRAPH_VIEW_PROCES&PROCES_INIT_SCAN=1&id_proces=' + id;
          }
        },
        "ListView": {
          "separator_before": false,
          "separator_after": false,
          "label": "Widok listy",
          "action": function(obj) {
            window.location = BASE_URL + 'procesy5.php?task=PROCES_VIEW_LIST&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1&id_proces=' + id;
          }
        },
        "AddResource": {
          "separator_before": true,
          "separator_after": false,
          "label": "Dodaj zasób",
          "action": function(obj) {
            window.location = BASE_URL + 'index.php?MENU_INIT=PROCES_ADD_ZASOB&task=CRM_PROCES&procesID=' + id;
          }
        },
        "AddChild": {
          "separator_before": false,
          "separator_after": false,
          "label": "Dodaj dziecko",
          "action": function(obj) {
            window.location = BASE_URL + 'index.php?_route=ViewTableAjax&typeName=p5_default_db:CRM_PROCES&ff_PARENT_ID=' + id + '#CREATE';
          }
        },
        "ShowWsk": {
          "separator_before": true,
          "separator_after": false,
          "label": "Pokaż powiązane zasoby",
          "action": function(obj) {
            node = { id:"res"+id, text:"Zasoby"};
            $('#tree').jstree('create_node', id, node, 'first');
            var node = { id:"prof"+id,text:"Stanowiska"};
            $('#tree').jstree('create_node', id, node, 'first');
            var link = BASE_URL + "index.php?_route=UrlAction_ProcesView&_task=getDetailsAjax&id=" + id;

            $.get(link, function(data){
              var isProf = false;
              var isRes = false;
              $.each(data["wsk"], function(i, e){
                //console.log(e);
                var idX = e["ID_ZASOB"];
                var node = { id:"wsk"+e["ID"],text: "["+e["ID_ZASOB"]+"] " + res[idX]["DESC"]};

                if(res[idX]["TYPE"] == "STANOWISKO" || res[idX]["TYPE"] == "DZIAL" || res[idX]["TYPE"] == "PODMIOT"){
                   node["type"] = "stanowiska";
                   isProf = true;
                  $('#tree').jstree('create_node', "prof"+id, node, 'first');
                }else{
                  node["type"] = "zasoby";
                  isRes = false;
                  $('#tree').jstree('create_node', "res"+id, node, 'first');
                }
              });
              if(!isProf)
                $("#tree").jstree('rename_node', "prof"+id , "Stanowiska <b style=color:red>[BRAK]</b>" );
              if(!isRes)
                $("#tree").jstree('rename_node', "res"+id , "Zasoby <b style=color:red>[BRAK]</b>" );
              $("#tree").jstree("open_node", id);
              $("#tree").jstree("open_node", "res"+id);
              $("#tree").jstree("open_node", "prof"+id);
            })
          }
        },
      };
    }

    if (node.type === "zasoby" || node.type === "stanowiska") {
      items = {
        "Edit": {
          "separator_before": false,
          "separator_after": true,
          "label": "Edytuj zasób",
          "action": function(obj) {
            var zId = id.replace("wsk", "");
            window.location = BASE_URL + 'index.php?_route=ViewTableAjax&typeName=p5_default_db:CRM_LISTA_ZASOBOW#EDIT/' + zId;
          }
        },
      };
    }
    return items;
  }

  function renderTree() {
    // jQuery.jstree.defaults.core.themes.responsive = true;
    $('#view').empty();
    $("#view").append("<input id=search type=next class=form-control>")
    $('#view').append("<div id=tree></div>");
    $('#tree').jstree({
      "core": {
        "animation": 0,
        "check_callback": true,
        "themes": {
          "stripes": false,
          "dots": false
        },
        'data': (TYPE == "childs" ? translate(0, procesy) : translate(0, res))
      },
      "types": {
        "default": {
          "icon": "glyphicon glyphicon-folder-open",
        },
        "proces": {
          "icon": "glyphicon glyphicon-file",
        },
        "stanowiska": {
          "icon": "glyphicon glyphicon glyphicon-user",
        },
        "zasoby": {
          "icon": "glyphicon glyphicon glyphicon-hdd",
        },
      },
      "plugins": [
        "contextmenu",  "search",
        "types"
      ],
      "search": {
        // search config
        "show_only_matches": true,
      },
      "contextmenu": {
        "items": customMenu
      }
    });
  }

  function renderPanels() {
    $("#view").html("<div id=ulproc><div id=procCon><div class=clearfix></div></div></div>");
    //console.log(procesy);
    if (localStorage.getItem(TYPE) !== null) {
      var arr = JSON.parse( localStorage.getItem(TYPE) );
      $.each(arr, function(i, e){
        createPanel(e["ID"], i, e["TYPE"]);
      });
    } else {
      createPanel(START_ID, 0, TYPE);
    }
  }

  function createPanel(id, depth, type) {
    state.splice(depth);
    var temp = {};
    temp["ID"] = id;
    var inherit = $("#depth" + (depth - 1)).data("type");
    if ("connect" == inherit) {
      inherit = "childs";
    }
    if ("aliasChilds" == inherit) {
      inherit = "res";
    }
    if ("gotoChilds" == inherit) {
      inherit = "childs";
    }
    if (type == "inherit") {
      type = inherit;
    }
    if (type == "childs" && procesy[id]["childs"].length == 0) {
      type = "details";
    }
    if (type == "alias") {
      type = "detailsRes";
    }
    if (type == "res" && res[id]["childs"].length == 0) {
      type = "detailsRes";
    }
    temp["TYPE"] = type;
    temp["FOCUS"] = 0;
    state[depth] = temp;
    if(depth > 0)
    state[depth-1]["FOCUS"] = id;
    renderPanel(depth);
  }

  function renderPanel(depth) {
    var type = state[depth]["TYPE"];
    var id = state[depth]["ID"];
    var link = BASE_URL + "index.php?_route=UrlAction_ProcesView&_task=getDetailsAjax&id=" + id;
    if ("connect" == type) {
      link = BASE_URL + "index.php?_route=UrlAction_ProcesView&_task=getConnectedProcAjax&id=" + id;
    }
    $("#depth" + (depth - 1)).nextAll(".singleAdv").remove();
    var target = $('<div class="singleAdv" data-depth="' + depth + '" id="depth' + depth + '" data-parent="' + id + '" data-type="' + type + '"></div>');
    target.appendTo("#procCon");
    $("#procCon").css("width", depth * 460 + 460);
    $("#ulproc").scrollLeft(depth * 460 + 460);

    $.get(link, function(exp) {
      var result = "";
      result += "<li ";
      if (id != 0) {
        if ("childs" == type || "goto" == type || "details" == type) {
          result += "data-opis='" + procesy[id]["OPIS"] + "' data-desc='" + procesy[id]["DESC"] + "'  data-id=" + id + " ";
        } else {
          result += "data-opis='" + res[id]["OPIS"] + "' data-desc='" + res[id]["DESC"] + "'  data-id=" + id + " ";
        }
      }
      if ("childs" == type) {
        result += "class='list-group-item disabled-item normalChilds'>" + (id == 0 ? "Procesy" : "{" + id + "} Procesy podrzędne");
      }
      if ("details" == type) {
        result += "class='list-group-item disabled-item normalChilds '>{" + id + "} Szczegóły";
      }
      if ("res" == type || "alias" == type) {
        result += "class='list-group-item disabled-item normalChilds'>" + (id == 0 ? "Zasoby" : "[" + id + "] Zasoby podrzędne");
      }
      if ("detailsRes" == type) {
        result += "class='list-group-item disabled-item normalChilds'>[" + id + "] Szczegóły";
      }
      if ("goto" == type) {
        result += "class='list-group-item disabled-item normalChilds'>{" + id + "} Procesy podrzędne";
      }
      if ("connect" == type) {
        result += "class='list-group-item disabled-item normalChilds'>[" + id + "] Procesy powiązane";
      }
      if(id != 0 && "connect" != type){
        result += "<div style=float:right;><div class='dropdown '>";

        if ("goto" == type || "details" == type || "childs" == type) {
          result += "<span class='glyph glyphicon glyphicon glyphicon-menu-hamburger dropdown-toggle' data-toggle='dropdown' aria-haspopup='true' aria-expanded='true' id='dropdownMenuP" + procesy[id]["ID"] + "'></span>";
          result += '<ul class="dropdown-menu dropdown-menu-right" style=z-index:100 aria-labelledby="dropdownMenuP' + procesy[id]["ID"] + '">';
        }
        if ("res" == type || "alias" == type || "connect" == type || "detailsRes" == type) {
          result += "<span class='glyph glyphicon glyphicon glyphicon-menu-hamburger dropdown-toggle' data-toggle='dropdown' aria-haspopup='true' aria-expanded='true' id='dropdownMenuR" + res[id]["ID"] + "'></span>";
          result += '<ul class="dropdown-menu dropdown-menu-right" style=z-index:100 aria-labelledby="dropdownMenuR' + res[id]["ID"] + '">';
        }

        if("detailsRes" != type && "details" != type)
          result += '<li><a href="" class=details>Szczegóły</a></li>';

          if ("goto" == type || "details" == type || "childs" == type) {
            data = procesy[id];

            result += '<li><a href="' + BASE_URL + 'index.php?_route=UrlAction_procesEditor&id=' + data["ID"] + '">Edytor procesu</a></li>';
            result += '<li><a href="' + BASE_URL + 'index.php?_route=ViewTableAjax&typeName=p5_default_db:CRM_PROCES#EDIT/' + data["ID"] + '">Edytuj proces</a></li>';
            result += '<li><a href="' + BASE_URL + 'index.php?MENU_INIT=PROCES_ADD_ZASOB&task=CRM_PROCES&procesID=' + data["ID"] + '">Dodaj zasób</a></li>';
            result += '<li><a href="' + BASE_URL + 'procesy5.php?task=CRM_TESTY_ADD_PYTANIA&id_proces=' + data["ID"] + '">Edytuj Pytania</a></li>';
            result += '<li><a href="' + BASE_URL + 'index.php?FUNCTION_INIT=GRAPH_VIEW_PROCES&PROCES_INIT_SCAN=1&id_proces=' + data["ID"] + '">Mapa procesu</a></li>';
            result += '<li><a href="' + BASE_URL + 'procesy5.php?task=PROCES_VIEW_LIST&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1&id_proces=' + data["ID"] + '">Widok listy</a></li>';
            result += '<li><a href="' + BASE_URL + 'index.php?_route=ViewTableAjax&typeName=p5_default_db:CRM_PROCES&ff_PARENT_ID=' + data["ID"] + '#CREATE">Dodaj dziecko</a></li>';
          }

          if ("res" == type || "alias" == type || "connect" == type || "detailsRes" == type) {
            data = res[id];
            result += '<li><a href="' + BASE_URL + 'index.php?_route=ViewTableAjax&typeName=p5_default_db:CRM_LISTA_ZASOBOW#EDIT/' + data["ID"] + '">Edytuj zasób</a></li>';
            result += '<li><a href="" class=connect>Procesy powiązane</a></li>';
          }
        result += '</ul>';
        result += "</div><div>";
      }
      result += "</li>";
      result += "<ul class='singleAdvList list-group' style=margin-bottom:0px;>";
      if (("details" == type && "res" != $("#depth" + (depth - 1)).data("type"))) {
        result += getDetails(procesy[id], exp, "proces");
      }
      if (("details" == type && "res" == $("#depth" + (depth - 1)).data("type")) || "detailsRes" == type) {
        result += getDetails(res[id], exp, "res");
      }
      if ("childs" == type || "gotoChilds" == type) {
        if (procesy[id]["childs"].length > 0) {
          $.each(procesy[id]["childs"], function(i, e) {
            result += getView(procesy[e["ID"]], false, "proces", depth);
          });
        } else {
          result += getDetails(procesy[id], exp, "proces");
        }
      }
      if ("goto" == type) {
        result += getDetails(procesy[id], exp);
      }
      if ("connect" == type) {
        if (exp["wsk"].length > 0) {
          $.each(exp["wsk"], function(i, e) {
            result += getView(procesy[e["ID_PROCES"]], false, "childs", depth);
          });
        } else {
          result += "<li class='list-group-item disabled-item list-group-item-danger'>Brak procesów powiązanych.</li>";
        }
      }
      if ("res" == type || "aliasChilds" == type) {
        if (res[id]["childs"].length > 0) {
          $.each(res[id]["childs"], function(i, e) {
            result += getView(res[e["ID"]], false, "res", depth);
          });
        } else {
          result += getDetails(res[id], exp);
        }
      }
      if ("alias" == type) {
        result += getDetails(res[id], exp);
      }
      result += "</ul></div>";
      $("#ulproc").scrollTop(0);
      target.html(result);
      $(".singleAdvList").css("height", $(window).height() - 200 + "px");
    });
    localStorage.setItem( TYPE, JSON.stringify(state) );
  }

  function render() {
    if (panels) {
      renderPanels();
    } else {
      renderTree();
    }
  }

  function updateParent(id, parent, item) {
    var link = BASE_URL + 'wfs-data.php/default_db/?SERVICE=WFS&VERSION=1.0.0&SRSNAME=EPSG:3003&';
    var req = `
<Transaction
xmlns="http://www.opengis.net/wfs"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
version="1.0.0"
service="WFS"
xmlns:p5_default_db="` + BASE_URL + `wfs/default_db/CRM_PROCES"
xsi:schemaLocation="` + BASE_URL + `wfs/default_db/CRM_PROCES ` + BASE_URL + `dev-pl/se-feature-api/wfs.php/xml/wfs/default_db/CRM_PROCES/?SERVICE=WFS&amp;VERSION=1.0.0&amp;REQUEST=DescribeFeatureType&amp;TYPENAME=p5_default_db:CRM_PROCES&amp;SRSNAME=EPSG:4326&amp;"
xmlns:gml="http://www.opengis.net/gml">
<Insert xmlns="http://www.opengis.net/wfs">
<CRM_PROCES xmlns="` + BASE_URL + `wfs/default_db/CRM_PROCES">
<ID xmlns="` + BASE_URL + `wfs/default_db/CRM_PROCES">` + id + `</ID>
<PARENT_ID xmlns="` + BASE_URL + `wfs/default_db/CRM_PROCES">` + parent + `</PARENT_ID>
</CRM_PROCES>
</Insert>
</Transaction>`;
    //console.log(req);
    $.ajax({
      url: link,
      data: req,
      type: 'POST',
      contentType: "text/xml",
      dataType: "text",
      success: function(data) {
        return true;
      },
      error: function(xhr, ajaxOptions, thrownError) {
        $(item).sortable('cancel');
        $.notify("Brak połączenia z bazą danych", "error");
      }
    });
  }

  $(document).on("click", ".toggleRoute", function(){
    var obj = $(this).closest(".singleAdv");
    var id = $(obj).data("parent");
    var type = $(obj).data("type");
    if ($(this).data("state") == 0) {
      $(this).data("state", 1);
      $(this).text("UKRYJ ŚCIEŻKĘ");
      $(this).parent().find(".route").html("<ul style=list-style:none;padding-left:0px;>"+showTree(id, type, 0)+"</ul>");
      var depth = 0;
      $(this).parent().find(".route").find("li").each(function(){
        $(this).css("padding-left", depth);
        depth += 16;
      });
      $(this).parent().find(".route").show();
    } else {
      $(this).data("state", 0);
      $(this).text("POKAŻ ŚCIEŻKĘ");
      $(this).parent().find(".route").hide();
      $(this).parent().find(".route").html("");
    }
  });

  function showTree(id, type, count) {
    if (id == "#" || count >= 100) return "";
    if (type == "detailsRes" || type == "alias") {
      if (typeof res[id]["DESC"] != "undefined") {
        return showTree(res[id]["PARENT_ID"], "detailsRes", count+1)+"<li style=padding-left:0px;><span class='glyphicon glyphicon-arrow-right'></span> " + res[id]["DESC"] + "</li>";
      } else {
        return "";
      }
    } else {
      if (typeof procesy[id]["DESC"] != "undefined") {
        return showTree(procesy[id]["PARENT_ID"], "detailsProc", count+1)+"<li style=padding-left:0px;><span class='glyphicon glyphicon-arrow-right'></span> " + procesy[id]["DESC"] + "</li>";
      } else {
        return "";
      }
    }
  }

  function getDetails(e, data, type) {
    var result = "";
    if (type == "proces") {
      result += '<div class="panel panel-info" style=margin-bottom:0px;>';
    } else {
      result += '<div class="panel panel-success" style=margin-bottom:0px;>';
    }
    result += '<div class="panel-heading"><h3 class="panel-title">' + e["DESC"] + '</h3></div>';
    result += '<div class="panel-body pbody">';
    result += e["OPIS"];
    result += '<div class=toggleRoute data-state=0>POKAŻ ŚCIEŻKĘ</div>';
    result += '<div class=route></div>';
    result += '</div>';
    result += '</div>';

    if (data["wsk"].length > 0 && type == "proces") {
      result += "<li class='list-group-item disabled-item list-group-item-success'>Zasoby powiązane</li>";
      result += "<ul class='singleAdvList list-group' list-group' style=margin-bottom:0px;>";
      $.each(data["wsk"], function(i, e) {
        id = e["ID_ZASOB"];
        if (typeof res[id] !== "undefined") {
          result += "<li class='list-group-item liProc wsk'";
          result += "data-opis='" + res[id]["OPIS"] + "' data-desc='" + res[id]["DESC"] + "'  data-id=" + res[id]["ID"] + " >";
          result += '<div class="textTable">';
          result += "<span class=detailsTable>" + res[id]["ID"] + "</span> ";
          result += res[id]["DESC"];
          result += "</div>"
          result += "<div style=float:right;><span class='glyph glyphicon gl glyphicon-triangle-right'></span>";
          result += "<div class='dropdown '>";
          result += "<span class='glyph glyphicon glyphicon glyphicon-menu-hamburger dropdown-toggle' data-toggle='dropdown' aria-haspopup='true' aria-expanded='true' id='dropdownMenu" + res[id]["ID"] + "'></span>";
          result += '<ul class="dropdown-menu dropdown-menu-right" style=z-index:100 aria-labelledby="dropdownMenu' + res[id]["ID"] + '">';
          result += '<li><a href="" class=details>Szczegóły</a></li>';
          result += '</ul>';
          result += "</div>";
          result += '</div><div class=clearfix></div></li>';
        }
      });
      result += "</ul>";
    }

    return result;
  }

  $(document).on("click", ".goto", function() {
    $(this).parents(".singleAdv").find(".active").removeClass("active");
    $(this).parents(".singleAdv").find(".list-group-item-info").removeClass("list-group-item-info");
    $(this).addClass("list-group-item-info");
    var parent_id = $(this).data("id");
    var id = procesy[parent_id]["ID"];
    var depth = $(this).closest(".singleAdv").data("depth") + 1;
    createPanel(id, depth, "goto");

    return false;
  });

  $(document).on("click", ".alias", function() {
    $(this).parents(".singleAdv").find(".active").removeClass("active");
    $(this).parents(".singleAdv").find(".list-group-item-info").removeClass("list-group-item-info");
    $(this).addClass("list-group-item-info");
    var parent_id = $(this).data("id");
    var id = res[parent_id]["ID"];
    var depth = $(this).closest(".singleAdv").data("depth") + 1;
    createPanel(id, depth, "alias");

    return false;
  });

  function getView(data, active, type, depth) {
    var result = "";
    var style = "";
    switch (data["TYPE"]) {
      case "PROCES_INIT":
        style = 'style="background-color:#ffe5e5;color:#333"';
        break;
      case "PROCES":
        style = 'style="background-color:#ededed;color:#333"';
        break;
      case "PROCES_GROUP_1":
        style = 'style="background-color:#9999cc;color:#fff"';
        break;
      case "PROCES_GROUP_2":
        style = 'style="background-color:#d8d8b2;color:#fff"';
        break;
      default:
        style = 'style="background-color:#ededed;color:#333"';
        break;
    }

    result += "<li class='list-group-item liProc " + (state[depth]["FOCUS"] == data["ID"] ? "active" : "") + "'; ";
    result += "data-opis='" + data["OPIS"] + "' data-desc='" + data["DESC"] + "'  data-id=" + data["ID"] + " >";
    result += '<div class="textTable">'
    result += "<span class=detailsTable " + style + ">" + data["ID"] + "</span> "
    result += data["DESC"];
    result += "</div>"
    result += "<div style=float:right;><span class='glyph glyphicon gl glyphicon-triangle-right'></span>";
    result += "<div class='dropdown '>";
    result += "<span class='glyph glyphicon glyphicon glyphicon-menu-hamburger dropdown-toggle' data-toggle='dropdown' aria-haspopup='true' aria-expanded='true' id='dropdownMenu" + data["ID"] + "'></span>";
    result += '<ul class="dropdown-menu dropdown-menu-right" style=z-index:100 aria-labelledby="dropdownMenu' + data["ID"] + '">';
    if ("proces" == type) {
      result += '<li><a href="' + BASE_URL + 'index.php?_route=UrlAction_procesEditor&id=' + data["ID"] + '">Edytor procesu</a></li>';
      result += '<li><a href="' + BASE_URL + 'index.php?_route=ViewTableAjax&typeName=p5_default_db:CRM_PROCES#EDIT/' + data["ID"] + '">Edytuj proces</a></li>';
      result += '<li><a href="' + BASE_URL + 'index.php?MENU_INIT=PROCES_ADD_ZASOB&task=CRM_PROCES&procesID=' + data["ID"] + '">Dodaj zasób</a></li>';
      result += '<li><a href="' + BASE_URL + 'procesy5.php?task=CRM_TESTY_ADD_PYTANIA&id_proces=' + data["ID"] + '">Edytuj Pytania</a></li>';
      result += '<li><a href="' + BASE_URL + 'index.php?FUNCTION_INIT=GRAPH_VIEW_PROCES&PROCES_INIT_SCAN=1&id_proces=' + data["ID"] + '">Mapa procesu</a></li>';
      result += '<li><a href="' + BASE_URL + 'procesy5.php?task=PROCES_VIEW_LIST&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1&id_proces=' + data["ID"] + '">Widok listy</a></li>';
      result += '<li><a href="' + BASE_URL + 'index.php?_route=ViewTableAjax&typeName=p5_default_db:CRM_PROCES&ff_PARENT_ID=' + data["ID"] + '#CREATE">Dodaj dziecko</a></li>';
    }

    if ("res" == type) {
      result += '<li><a href="' + BASE_URL + 'index.php?_route=ViewTableAjax&typeName=p5_default_db:CRM_LISTA_ZASOBOW#EDIT/' + data["ID"] + '">Edytuj zasób</a></li>';
      result += '<li><a href="" class=connect>Procesy powiązane</a></li>';
    }
    //result += '<li><a href="'+BASE_URL+''+$(this).find("ID").text()+'">Widok listy</a></li>';
    result += '<li><a href="" class=details>Szczegóły</a></li>';
    result += '</ul>';
    result += "</div>";
    result += '</div><div class=clearfix></div></li>';

    if (data["IF_TRUE_GOTO"] != 0 && type == "proces") {
      var goto = data["IF_TRUE_GOTO_FLAG"];
      var id = data["IF_TRUE_GOTO"];
      data = procesy[id];
      result += "<li class='list-group-item goto " + (state[depth]["FOCUS"] == data["ID"] ? "list-group-item-info" : "") + "'; ";
      result += "data-opis='" + data["OPIS"] + "' data-desc='" + data["DESC"] + "'  data-id=" + data["ID"] + " style=border-top-style:none;>";
      result += "";
      result += '<div class="textTable">'
      result += "<span class=gotoInfo><span class='glyphicon glyphicon-arrow-right'></span> " + goto + " </span><span class=gotoWay>" + data["ID"] + "</span>";
      result += "</div>"
      result += "<div style=float:right;><span class='glyph glyphicon gl glyphicon-triangle-right'></span>";
      result += "<div class='dropdown '>";
      result += "<span class='glyph glyphicon glyphicon glyphicon-menu-hamburger dropdown-toggle' data-toggle='dropdown' aria-haspopup='true' aria-expanded='true' id='dropdownMenu" + data["ID"] + "'></span>";
      result += '<ul class="dropdown-menu dropdown-menu-right" style=z-index:100 aria-labelledby="dropdownMenu' + data["ID"] + '">';
      result += '<li><a href="' + BASE_URL + 'index.php?_route=UrlAction_procesEditor&id=' + data["ID"] + '">Edytor procesu</a></li>';
      result += '<li><a href="' + BASE_URL + 'index.php?_route=ViewTableAjax&typeName=p5_default_db:CRM_PROCES#EDIT/' + data["ID"] + '">Edytuj proces</a></li>';
      result += '<li><a href="' + BASE_URL + 'index.php?MENU_INIT=PROCES_ADD_ZASOB&task=CRM_PROCES&procesID=' + data["ID"] + '">Dodaj zasób</a></li>';
      result += '<li><a href="' + BASE_URL + 'procesy5.php?task=CRM_TESTY_ADD_PYTANIA&id_proces=' + data["ID"] + '">Edytuj Pytania</a></li>';
      result += '<li><a href="' + BASE_URL + 'index.php?FUNCTION_INIT=GRAPH_VIEW_PROCES&PROCES_INIT_SCAN=1&id_proces=' + data["ID"] + '">Mapa procesu</a></li>';
      result += '<li><a href="' + BASE_URL + 'procesy5.php?task=PROCES_VIEW_LIST&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1&id_proces=' + data["ID"] + '">Widok listy</a></li>';
      result += '<li><a href="' + BASE_URL + 'index.php?_route=ViewTableAjax&typeName=p5_default_db:CRM_PROCES&ff_PARENT_ID=' + data["ID"] + '#CREATE">Dodaj dziecko</a></li>';
      //result += '<li><a href="'+BASE_URL+''+$(this).find("ID").text()+'">Widok listy</a></li>';
      result += '<li><a href="" class=details>Szczegóły</a></li>';
      result += '</ul>';
      result += "</div>";
      result += '</div><div class=clearfix></div></blockqoute></li>';
    }

    if (data["ALIAS_ID"] != 0 && type == "res") {
      var id = data["ALIAS_ID"];
      if (id in res) {
        data = res[id];
        result += "<li class='list-group-item alias " + (state[depth]["FOCUS"] == data["ID"] ? "list-group-item-info" : "") + "'; ";
        result += "data-opis='" + data["OPIS"] + "' data-desc='" + data["DESC"] + "'  data-id=" + data["ID"] + " style=border-top-style:none;>";
        result += "";
        result += '<div class="textTable">'
        result += "<span class=gotoInfo><span class='glyphicon glyphicon-arrow-right'></span> ALIAS </span><span class=gotoWay>" + data["ID"] + "</span>";
        result += "</div>"
        result += "<div style=float:right;><span class='glyph glyphicon gl glyphicon-triangle-right'></span>";
        result += "<div class='dropdown '>";
        result += "<span class='glyph glyphicon glyphicon glyphicon-menu-hamburger dropdown-toggle' data-toggle='dropdown' aria-haspopup='true' aria-expanded='true' id='dropdownMenu" + data["ID"] + "'></span>";
        result += '<ul class="dropdown-menu dropdown-menu-right" style=z-index:100 aria-labelledby="dropdownMenu' + data["ID"] + '">';
        result += '<li><a href="' + BASE_URL + 'index.php?_route=ViewTableAjax&typeName=p5_default_db:CRM_LISTA_ZASOBOW#EDIT/' + data["ID"] + '">Edytuj zasób</a></li>';
        result += '<li><a href="" class=connect>Procesy powiązane</a></li>';
        result += '<li><a href="" class=details>Szczegóły</a></li>';
        result += '</ul>';
        result += "</div>";
        result += '</div><div class=clearfix></div></blockqoute></li>';
      } else {
        console.log('BUG ALIAS_ID['+data['ALIAS_ID']+'] in ['+data['ID']+'] not in res', data, res);
      }
    }

    return result;
  }

  $(document).on('click', '.connect', function(e) {
    e.preventDefault();
    $(this).parents(".singleAdv").nextAll(".singleAdv").remove();
    $(this).parents(".singleAdv").find(".active").removeClass("active");
    $(this).parents(".singleAdv").find(".list-group-item-info").removeClass("list-group-item-info");
    $(this).parents(".liProc").addClass("active");
    $('.dropdown.open .dropdown-toggle').dropdown('toggle');
    var parent_id = $(this).closest(".list-group-item").data("id");
    var parentOfParent_id = $(this).closest(".singleAdv").data("parent");
    var depth = $(this).closest(".singleAdv").data("depth") + 1;
    createPanel(parent_id, depth, "connect");
  });

  $(document).on('click', '.details', function(e) {
    e.preventDefault();
    $(this).parents(".singleAdv").nextAll(".singleAdv").remove();
    $(this).parents(".singleAdv").find(".active").removeClass("active");
    $(this).parents(".singleAdv").find(".list-group-item-info").removeClass("list-group-item-info");
    $(this).parents(".liProc").addClass("active");
    $('.dropdown.open .dropdown-toggle').dropdown('toggle');
    var parent_id = $(this).closest(".list-group-item").data("id");
    var parentOfParent_id = $(this).closest(".singleAdv").data("parent");
    var depth = $(this).closest(".singleAdv").data("depth") + 1;
    if ($(this).closest(".list-group-item").hasClass("wsk") || $(this).closest(".singleAdv").data("type") == "res" || $(this).closest(".list-group-item").hasClass("alias")) {
      createPanel(parent_id, depth, "detailsRes");
    } else {
      createPanel(parent_id, depth, "details");
    }
    initSortable();
  });

  $(document).on('click', '.dropdown-toggle', function(e) {
    e.stopPropagation();
  });

  $(document).on('click', '.dropdown', function(e) {
    e.stopPropagation();
  });

  $(document).on('click', '#toggleMenu', function(e) {
    e.preventDefault();
    if (!menuShow) {
      $("#SE-menu").show();
      $("#SE-menu-sub").show();
      menuShow = true;
    } else {
      menuShow = false;
      $("#SE-menu").hide();
      $("#SE-menu-sub").hide();
    }
  });

  $(document).on('click', '#toggleView', function(e) {
    e.preventDefault();
    if (!panels) {
      panels = true;
      render();
    } else {
      panels = false;
      render();
    }
  });

  $(document).on('click', '.liProc', function() {
    $(this).parents(".singleAdv").find(".active").removeClass("active");
    $(this).parents(".singleAdv").find(".list-group-item-info").removeClass("list-group-item-info");
    $(this).addClass("active");
    var parent_id = $(this).data("id");
    var parentOfParent_id = $(this).closest(".singleAdv").data("parent");
    var depth = $(this).closest(".singleAdv").data("depth") + 1;
    if ($(this).hasClass("wsk")) {
      createPanel(parent_id, depth, "res");
    } else {
      createPanel(parent_id, depth, "inherit");
    }
    initSortable();
  });

  function initSortable() {
    // $( ".singleAdvList" ).sortable({
    // items: "li",
    // connectWith: ".singleAdvList",
    // cancel: ".disabled-item",
    // beforeStop: function(ev, ui) {
    //     if($(ui.item).data("id") == $(ui.placeholder).closest(".singleAdv").data("parent") || $(ui.item).hasClass("active")){
    //       $(this).sortable('cancel');
    //       $.notify("Nielogiczny ruch.", "error");
    //     }
    //
    //   },
    //   stop: function(ev, ui) {
    //     updateParent($(ui.item).data("id"),$(ui.item).closest(".singleAdv").data("parent"), this);
    //     },
    // }).disableSelection();
  }

  function start() {
    var link = BASE_URL + 'index.php?_route=UrlAction_ProcesView&_task=getAllAjax';
    $.get(link, function(data) {
      procesy = {}
      for (idx in data) {// FIX childs by SORT_PRIO
        var d = data[idx]
        if ('childs' in d) {
          var dataChilds = d['childs'].map(function (child) {
            var idChild = child['ID'];
            var sortPrio = (idChild in data) ? parseInt(data[idChild]['SORT_PRIO']) : 0;
            return {SORT_PRIO: sortPrio, ID: idChild};
          });
          var sortedChilds = dataChilds.sort(function(a, b) {
            if (a['SORT_PRIO'] == b['SORT_PRIO']) {
              return a['ID'] - b['ID'];
            }
            else {
              return a['SORT_PRIO'] - b['SORT_PRIO'];
            }
          });
          d['childs'] = sortedChilds;
        }
        procesy[idx] = d;
      }
      if (TYPE == "childs") render();
    });
    link = BASE_URL + 'index.php?_route=UrlAction_ProcesView&_task=getAllResAjax';
    $.get(link, function(data) {
      res = data;
      if (TYPE == "res") render();
    });
  }

  start();

});
