//Request-URI Too Long
$(document).ready(function() {
    function cData(text) {
        var nowy = "<![CDATA[";
        nowy += text;
        nowy += "]]>"
        return nowy;
    }
    var changes = false;
    $("#main").after('<div class="col-xs-4 col-md-3 col-md-offset-9 col-xs-offset-8" id="buttons"></div>')
    $("#buttons").html(
        "<button type=button id=clearBtn style=display:none;margin-left:5px; class='btn btn-danger text-center' >Cofnij zmiany</button>" +
        //"<button type=button id=expBtn class='btn btn-warning text-center' style=margin-right:5px;margin-left:5px;>Import/Export</button>" +
        "<button type=button id=saveBtn class='btn btn-primary text-center' style=margin-left:5px;>Opublikuj zmiany</button>"
    );
    var deletedId = new Array();
    var generatedId = new Array();
    var deletedRes = new Array();
    var usedImg = {};
    var usedVid = [];
    var dialog = 0;
    $("#SE-menu").hide();
    $("#SE-menu-sub").hide();
    var menuShow = false
    var zasobTree = new Array();

    var startInputVal = 0;
    var endInputVal = 0;
    var focusedInput = false;
    var targetVid = false;
    var elementVid = false;

//     var xmlExample = `<?xml version="1.0" encoding="utf-8"?>
// <FeatureCollection xmlns:gml="https://biuro.biall-net.pl/wfs/default_db/gml" xmlns:default_db__x3A__CRM_PROCES="https://biuro.biall-net.pl/wfs/default_db/CRM_PROCES" xmlns:default_db__x3A__CRM_LISTA_ZASOBOW="https://biuro.biall-net.pl/wfs/default_db/CRM_LISTA_ZASOBOW" xmlns:default_db__x3A__CRM_WSKAZNIK="https://biuro.biall-net.pl/wfs/default_db/CRM_WSKAZNIK"  >
// 	<gml:featureMember>
// 	<default_db__x3A__CRM_PROCES:PROCES_INIT>
// 		<default_db__x3A__CRM_PROCES:ID>2224</default_db__x3A__CRM_PROCES:ID>
// 		<default_db__x3A__CRM_PROCES:PARENT_ID>100</default_db__x3A__CRM_PROCES:PARENT_ID>
// 		<default_db__x3A__CRM_PROCES:IF_TRUE_GOTO>100</default_db__x3A__CRM_PROCES:IF_TRUE_GOTO>
// 		<default_db__x3A__CRM_PROCES:IF_TRUE_GOTO_FLAG>GOTO</default_db__x3A__CRM_PROCES:IF_TRUE_GOTO_FLAG>
// 		<default_db__x3A__CRM_PROCES:DESC>CRM_IMAGE</default_db__x3A__CRM_PROCES:DESC>
// 		<default_db__x3A__CRM_PROCES:OPIS>Proces crm_image</default_db__x3A__CRM_PROCES:OPIS>
// 			<default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5282</default_db__x3A__CRM_WSKAZNIK:ID>
// 				<default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB></default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB>
// 				<default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK></default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK>
// 				<default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 					<default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>4</default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>
// 				</default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5282</default_db__x3A__CRM_WSKAZNIK:ID>
// 			</default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 			<default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5283</default_db__x3A__CRM_WSKAZNIK:ID>
// 				<default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB></default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB>
// 				<default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK></default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK>
// 				<default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 					<default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>4</default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>
// 				</default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5283</default_db__x3A__CRM_WSKAZNIK:ID>
// 			</default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 			<default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5284</default_db__x3A__CRM_WSKAZNIK:ID>
// 				<default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB></default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB>
// 				<default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK></default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK>
// 				<default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 					<default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>4</default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>
// 				</default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5284</default_db__x3A__CRM_WSKAZNIK:ID>
// 			</default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 			<default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5285</default_db__x3A__CRM_WSKAZNIK:ID>
// 				<default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB></default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB>
// 				<default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK></default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK>
// 				<default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 					<default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>4</default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>
// 				</default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5285</default_db__x3A__CRM_WSKAZNIK:ID>
// 			</default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 			<default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5286</default_db__x3A__CRM_WSKAZNIK:ID>
// 				<default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB></default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB>
// 				<default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK></default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK>
// 				<default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 					<default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>4</default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>
// 				</default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5286</default_db__x3A__CRM_WSKAZNIK:ID>
// 			</default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 			<default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5287</default_db__x3A__CRM_WSKAZNIK:ID>
// 				<default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB></default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB>
// 				<default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK></default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK>
// 				<default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 					<default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>4</default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>
// 				</default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5287</default_db__x3A__CRM_WSKAZNIK:ID>
// 			</default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 			<default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5288</default_db__x3A__CRM_WSKAZNIK:ID>
// 				<default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB></default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB>
// 				<default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK></default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK>
// 				<default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 					<default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>4</default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>
// 				</default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5288</default_db__x3A__CRM_WSKAZNIK:ID>
// 			</default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 			<default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5289</default_db__x3A__CRM_WSKAZNIK:ID>
// 				<default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB></default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB>
// 				<default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK></default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK>
// 				<default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 					<default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>4</default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>
// 				</default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5289</default_db__x3A__CRM_WSKAZNIK:ID>
// 			</default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 			<default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5290</default_db__x3A__CRM_WSKAZNIK:ID>
// 				<default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB></default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB>
// 				<default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK></default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK>
// 				<default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 					<default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>4</default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>
// 				</default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5290</default_db__x3A__CRM_WSKAZNIK:ID>
// 			</default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 			<default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5291</default_db__x3A__CRM_WSKAZNIK:ID>
// 				<default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB></default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB>
// 				<default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK></default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK>
// 				<default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 					<default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>4</default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>
// 				</default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5291</default_db__x3A__CRM_WSKAZNIK:ID>
// 			</default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 			<default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5292</default_db__x3A__CRM_WSKAZNIK:ID>
// 				<default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB></default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB>
// 				<default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK></default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK>
// 				<default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 					<default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>4</default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>
// 				</default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5292</default_db__x3A__CRM_WSKAZNIK:ID>
// 			</default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 			<default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5293</default_db__x3A__CRM_WSKAZNIK:ID>
// 				<default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB></default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB>
// 				<default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK></default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK>
// 				<default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 					<default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>4</default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>
// 				</default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5293</default_db__x3A__CRM_WSKAZNIK:ID>
// 			</default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 			<default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5294</default_db__x3A__CRM_WSKAZNIK:ID>
// 				<default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB></default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB>
// 				<default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK></default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK>
// 				<default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 					<default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>4</default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>
// 				</default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5294</default_db__x3A__CRM_WSKAZNIK:ID>
// 			</default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 			<default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5295</default_db__x3A__CRM_WSKAZNIK:ID>
// 				<default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB></default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB>
// 				<default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK></default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK>
// 				<default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 					<default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>4</default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>
// 				</default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5295</default_db__x3A__CRM_WSKAZNIK:ID>
// 			</default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 			<default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5296</default_db__x3A__CRM_WSKAZNIK:ID>
// 				<default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB></default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB>
// 				<default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK></default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK>
// 				<default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 					<default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>4</default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>
// 				</default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5296</default_db__x3A__CRM_WSKAZNIK:ID>
// 			</default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 			<default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5297</default_db__x3A__CRM_WSKAZNIK:ID>
// 				<default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB></default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB>
// 				<default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK></default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK>
// 				<default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 					<default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>4</default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>
// 				</default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5297</default_db__x3A__CRM_WSKAZNIK:ID>
// 			</default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 			<default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5298</default_db__x3A__CRM_WSKAZNIK:ID>
// 				<default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB></default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB>
// 				<default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK></default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK>
// 				<default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 					<default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>4</default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>
// 				</default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5298</default_db__x3A__CRM_WSKAZNIK:ID>
// 			</default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 			<default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5299</default_db__x3A__CRM_WSKAZNIK:ID>
// 				<default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB></default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB>
// 				<default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK></default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK>
// 				<default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 					<default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>4</default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>
// 				</default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5299</default_db__x3A__CRM_WSKAZNIK:ID>
// 			</default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 			<default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5308</default_db__x3A__CRM_WSKAZNIK:ID>
// 				<default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB></default_db__x3A__CRM_WSKAZNIK:OPIS_ZASOB>
// 				<default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK></default_db__x3A__CRM_WSKAZNIK:ID_PRZYPADEK>
// 				<default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 					<default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>1</default_db__x3A__CRM_LISTA_ZASOBOW:ID_PRZYPADEK>
// 				</default_db__x3A__CRM_LISTA_ZASOBOW:CRM_LISTA_ZASOBOW>
// 				<default_db__x3A__CRM_WSKAZNIK:ID>5308</default_db__x3A__CRM_WSKAZNIK:ID>
// 			</default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK>
// 		<default_db__x3A__CRM_PROCES:PROCES>
// 			<default_db__x3A__CRM_PROCES:ID>2240</default_db__x3A__CRM_PROCES:ID>
// 			<default_db__x3A__CRM_PROCES:DESC></default_db__x3A__CRM_PROCES:DESC>
// 			<default_db__x3A__CRM_PROCES:OPIS>Test</default_db__x3A__CRM_PROCES:OPIS>
// 			<default_db__x3A__CRM_PROCES:PARENT_ID>2224</default_db__x3A__CRM_PROCES:PARENT_ID>
// 			<default_db__x3A__CRM_PROCES:IF_TRUE_GOTO>0</default_db__x3A__CRM_PROCES:IF_TRUE_GOTO>
// 			<default_db__x3A__CRM_PROCES:IF_TRUE_GOTO_FLAG></default_db__x3A__CRM_PROCES:IF_TRUE_GOTO_FLAG>
// 			<default_db__x3A__CRM_PROCES:SORT_PRIO>1</default_db__x3A__CRM_PROCES:SORT_PRIO>
// 		</default_db__x3A__CRM_PROCES:PROCES>
// 		<default_db__x3A__CRM_PROCES:PROCES>
// 			<default_db__x3A__CRM_PROCES:ID>-1</default_db__x3A__CRM_PROCES:ID>
// 			<default_db__x3A__CRM_PROCES:DESC></default_db__x3A__CRM_PROCES:DESC>
// 			<default_db__x3A__CRM_PROCES:OPIS></default_db__x3A__CRM_PROCES:OPIS>
// 			<default_db__x3A__CRM_PROCES:IF_TRUE_GOTO_FLAG></default_db__x3A__CRM_PROCES:IF_TRUE_GOTO_FLAG>
// 			<default_db__x3A__CRM_PROCES:IF_TRUE_GOTO>0</default_db__x3A__CRM_PROCES:IF_TRUE_GOTO>
// 			<default_db__x3A__CRM_PROCES:PARENT_ID>2224</default_db__x3A__CRM_PROCES:PARENT_ID>
// 			<default_db__x3A__CRM_PROCES:SORT_PRIO>2</default_db__x3A__CRM_PROCES:SORT_PRIO>
// 			<default_db__x3A__CRM_PROCES:PROCES>
// 				<default_db__x3A__CRM_PROCES:ID>2241</default_db__x3A__CRM_PROCES:ID>
// 				<default_db__x3A__CRM_PROCES:DESC></default_db__x3A__CRM_PROCES:DESC>
// 				<default_db__x3A__CRM_PROCES:OPIS></default_db__x3A__CRM_PROCES:OPIS>
// 				<default_db__x3A__CRM_PROCES:PARENT_ID>-1</default_db__x3A__CRM_PROCES:PARENT_ID>
// 				<default_db__x3A__CRM_PROCES:IF_TRUE_GOTO>0</default_db__x3A__CRM_PROCES:IF_TRUE_GOTO>
// 				<default_db__x3A__CRM_PROCES:IF_TRUE_GOTO_FLAG></default_db__x3A__CRM_PROCES:IF_TRUE_GOTO_FLAG>
// 				<default_db__x3A__CRM_PROCES:SORT_PRIO>1</default_db__x3A__CRM_PROCES:SORT_PRIO>
// 			</default_db__x3A__CRM_PROCES:PROCES>
// 		</default_db__x3A__CRM_PROCES:PROCES>
// 	</default_db__x3A__CRM_PROCES:PROCES_INIT>
// 	</gml:featureMember>
// </FeatureCollection>`


    var perms = [
        [1, "Kto wykonuje", "X"],
        [2, "Tylko do odczytu", "R"],
        [3, "Odczyt, zapis, wykonanie", "R,W,X"],
        [4, "Odczyt, zapis, wykonanie, tworzenie", "R,W,X,C"],
        [5, "Odczyt i wykonanie", "R,X"],
        [6, "Tylko do odczytu", "R"],
        [7, "MAPA PROCESU  - opis mapy procesu", ""],
        [9, "Tylko do tworzenia rekordu", "C"],
        [10, "Tylko tworzenie i czytanie rekordów bez edycji", "R,X,C"],
        [11, "Tylko edycja rekordu - ustalanie nowej wartosci", "W"],
        [12, "Tylko edycja i dodanie rekordu - ustalanie nowej wartosci", "W,C"],
        [13, "Nowy rekord i edycja z pominieciem A_ADM_COMPANY", "R,W,X,C,S"],
        [14, "Widok tylko swoich danych z rekordu", "W,O"],
        [15, "Edycja rekordów dla super admina", "R,W,C,S"],
        [16, "Widok i dodawanie rekordów tylko dla swojego ADM_COMPANY", "C,O"],
        [17, "Super widok wszystkich rekordow niezaleznie od uprawnien rekordu", "R,V"],
        [18, "Administracja Edycja i widok wszystkich rekordow z pominieciem A", "R,W,X,S,V"],
        [19, "Administracja Edycja Tworzenie i widok wszystkich rekordow z pom", "R,W,X,C,S,V"],
        [20, "Export", "R,X,E"],
        [21, "Widzenie tylko swoich rekordów", "O"]
    ];
    var gotoType = [
        ["GOTO", "Przejdź do procesu"],
        ["GOTO_AND_RETURN", "Przejdź do procesu i wróć"],
        ["FORK", "FORK"]
    ];
    var state = [];
    var actSite = "none";

    var filtr = 0;
    var selectedArea = false;
    var sZasoby;
    var sProcesy;
    var lastSearch = "";
    var newSteps;
    var newRes = 0;

    var XML_NAMESPACE = "default_db__x3A__";

    showPreview();



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

    function showPath(parent, target, hideEdit, renderTree) {
        var target = target || $(".path")
        var hideEdit = hideEdit || false
        var showEdit = !hideEdit
        var renderTree = renderTree || false

        var link = BASE_URL + "index.php?_route=UrlAction_ProcesEditor&_task=getPathAjax&id=" + parent;
        $.get(link, function(data) {

            var result = "";
            result += '<ol class="breadcrumb">';

            $.each(data, function(i, e) {
                result += '<li class="breadcrumb-item">' + e["DESC"] + " {" + e["ID"] + "}" + '</li>'


            })
            result += '<li ' + (state[0]["PARENT_ID"] <= 0 ? "style=color:red;" : "") + ' class="breadcrumb-item">' + state[0]["DESC"] + " {" + (state[0]["ID"] < 0 ? "?" : state[0]["ID"]) + "}"
            if (showEdit)
                result += '<i class="glyphicon glyphicon-edit ico editPath"></i>'

            result += '</li>'
            result += '</ol>';
            $(target).html(result);
            if (renderTree)
                renderProcesTree(data);

        });



    }

    function findInImages(imagesArray, remote_table, remote_id) {
        var elementObj = [];
        $.each(imagesArray, function(i, e) {
            if (remote_table == e["REMOTE_TABLE"] && remote_id == e["REMOTE_ID"]) {
                var temp = {
                    ID: e.ID,
                    src: e.IMAGE,
                    title: e.NAME
                }
                elementObj.push(temp);

            }
        })
        return elementObj;


    }

    function loadImages() {
        //console.log("loadImages()")
        //console.log(state);
        var sFiltr = "";

        sFiltr += '<ogc:Filter><ogc:Or>';
        $.each(state, function(idp, procesItem) {

            sFiltr += '<ogc:And>';
            sFiltr += '<ogc:PropertyIsEqualTo><ogc:PropertyName>REMOTE_ID</ogc:PropertyName><ogc:Literal>' + procesItem["ID"] + '</ogc:Literal></ogc:PropertyIsEqualTo>'
            sFiltr += '<ogc:PropertyIsEqualTo><ogc:PropertyName>REMOTE_TABLE</ogc:PropertyName><ogc:Literal>CRM_PROCES</ogc:Literal></ogc:PropertyIsEqualTo>'
            sFiltr += '</ogc:And>';

            $.each(procesItem["_res"].concat(procesItem["_prof"]), function(idr, resItem) {
                sFiltr += '<ogc:And>';
                sFiltr += '<ogc:PropertyIsEqualTo><ogc:PropertyName>REMOTE_ID</ogc:PropertyName><ogc:Literal>' + resItem["ID"] + '</ogc:Literal></ogc:PropertyIsEqualTo>'
                sFiltr += '<ogc:PropertyIsEqualTo><ogc:PropertyName>REMOTE_TABLE</ogc:PropertyName><ogc:Literal>CRM_WSKAZNIK</ogc:Literal></ogc:PropertyIsEqualTo>'
                sFiltr += '</ogc:And>';
            })
        });
        sFiltr += '</ogc:Or></ogc:Filter>';
        //console.log("sFiltr")
        //console.log(sFiltr)
        p5WFS_GetFeature('p5_default_db:CRM_IMAGE', {
            'ogc:Filter': sFiltr,
        }).then(function(features) {
            //console.log("loadImages()")
            $.each(state, function(iP, proces) {

                proces["_IMG"] = findInImages(features, "CRM_PROCES", proces["ID"])
                $.each(proces["_res"].concat(proces["_prof"]), function(iR, zasob) {
                    zasob["_IMG"] = findInImages(features, "CRM_WSKAZNIK", zasob["ID"])

                })

            })
            render(state, $("#main"));

        }).catch(function(e) {
            console.log("Error: ", e)
        })
    }

    function loadResources() {
        //render(state, $("#main"));
        showPath(state[0]["PARENT_ID"]);
        $("#main").html("<center>Pobieranie danych o zasobach.</center>");
        var sFiltr = "";
        sFiltr += '    <ogc:And>';
        sFiltr += '      <ogc:Or>';
        $.each(state, function(idx, procesItem) {
            sFiltr += '        <ogc:PropertyIsEqualTo><ogc:PropertyName>ID_PROCES</ogc:PropertyName><ogc:Literal>' + procesItem["ID"] + '</ogc:Literal></ogc:PropertyIsEqualTo>';
        });
        sFiltr += '      </ogc:Or>';
        sFiltr += '      <ogc:Not>';
        sFiltr += '        <ogc:PropertyIsEqualTo><ogc:PropertyName>A_STATUS</ogc:PropertyName><ogc:Literal>DELETED</ogc:Literal></ogc:PropertyIsEqualTo>';
        sFiltr += '      </ogc:Not>';
        sFiltr += '    </ogc:And>';

        if (state[0]["ID"] <= 0) {
            $("#main").html("<center>Generowanie widoku.</center>");
            render(state, $("#main"));
            return true;
        }
        p5WFS_GetFeature('p5_default_db:CRM_WSKAZNIK', {
            'Filter': sFiltr,
            'sortBy': 'SORT_PRIO+A,ID',
        }).then(function(features) {
            //console.log(features)
            $.each(features, function(i, xml) {
                //console.log("xml")
                //console.log(xml)
                if (xml["ID"] == 0) return true;
                var wsk = new Array();
                wsk["ID"] = xml["ID"];
                wsk["ID_ZASOB"] = xml["ID_ZASOB"] || "";
                wsk["ID_PROCES"] = xml["ID_PROCES"] || "";
                wsk["SORT_PRIO"] = xml["SORT_PRIO"] || "";
                wsk["ID_PRZYPADEK"] = xml["ID_PRZYPADEK"] || "";
                wsk["OPIS_ZASOB"] = xml["OPIS_ZASOB"] || "";
                if (!wsk["ID_ZASOB"] || !wsk["ID_PRZYPADEK"]) return true;
                wskazniki.push(wsk);
            });
            var idsZasobyToFetch = [];
            $.each(wskazniki, function(index, wsk) {
                idsZasobyToFetch.push(wsk["ID_ZASOB"]);
            });
            if (idsZasobyToFetch.length > 0) {
                var zasobInfo = new Array();
                $.ajax({
                        type: 'POST',
                        url: BASE_URL + "index.php?_route=UrlAction_ProcesEditor&_task=getSingleResAjax",
                        data: {
                            data: idsZasobyToFetch
                        },
                        dataType: 'json'
                    })
                    .done(function(jsonZasobyTree) {
                        $.each(jsonZasobyTree, function(idx, zasob) {

                            zasobInfo[zasob["ID"]] = new Array();
                            zasobInfo[zasob["ID"]]["DESC"] = zasob["DESC"];
                            zasobInfo[zasob["ID"]]["OPIS"] = zasob["OPIS"];
                            zasobInfo[zasob["ID"]]["TYPE"] = zasob["TYPE"];
                            zasobInfo[zasob["ID"]]["TREE"] = [];
                            for (var i = 3; i > 0; i--) {
                                if (zasob["p" + i + "_ID"] != null) {
                                    var temp = {};
                                    temp["ID"] = zasob["p" + i + "_ID"];
                                    temp["DESC"] = zasob["p" + i + "_DESC"];
                                    zasobInfo[zasob["ID"]]["TREE"].push(temp);
                                }
                            }
                        });

                        $.each(wskazniki, function(index, wsk) {
                            var type,
                                idZasob = wsk["ID_ZASOB"];
                            if (!zasobInfo[idZasob]) {
                                $("#main").html("<center>Generowanie widoku.</center>");
                                render(state, $("#main"));
                                return;
                            }
                            if (zasobInfo[idZasob]["TYPE"] == "DZIAL" || zasobInfo[idZasob]["TYPE"] == "STANOWISKO" || zasobInfo[idZasob]["TYPE"] == "PODMIOT") {
                                type = "_prof";
                            } else {
                                type = "_res";
                            }
                            var id = wsk["ID_PROCES"];
                            var temp = {};
                            temp["ID_ZASOB"] = idZasob
                            temp["ID"] = wsk["ID"];
                            temp["ID_PRZYPADEK"] = wsk["ID_PRZYPADEK"];
                            temp["OPIS_ZASOB"] = wsk["OPIS_ZASOB"];
                            temp["DESC"] = zasobInfo[idZasob]["DESC"];
                            temp["OPIS"] = zasobInfo[idZasob]["OPIS"];
                            temp["_TREE"] = zasobInfo[idZasob]["TREE"];
                            //console.log(getIndexById(id));
                            var newId = state[getIndexById(id)][type].push(temp) - 1;
                        });
                        loadImages();
                        render(state, $("#main"));
                    })
                    .fail(function(xhr) {
                        if (xhr.responseJSON && xhr.responseJSON.msg && xhr.responseJSON.type) jQuery.notify(xhr.responseJSON.msg, xhr.responseJSON.type);
                        else jQuery.notify("Wystąpił nieznany błąd", 'error');
                    });

            } else {
                $("#main").html("<center>Generowanie widoku.</center>");
                loadImages();
                render(state, $("#main"));
            }
        }).catch(function(e) {
            console.log("Error: ", e)
        })
        var wskazniki = new Array();
    }

    $(document).on('click', '#clearBtn', function() {
        swal({
            title: 'Cofnij zmiany',
            text: "Czy chcesz cofnąć wszystkie niezapisane zmiany?",
            type: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            cancelButtonText: "Anuluj",
            confirmButtonText: 'Cofnij zmiany'
        }).then(function() {
            localStorage.removeItem("state" + mainProces_id);
            $.notify("Niezapisane zmiany zostały wycofane.", "success");
            showPreview();
            //Parent_id = -1,
        }).catch(function(e) {})
    });
    //Saveaction
    var makeCRCTable = function() {
        var c;
        var crcTable = [];
        for (var n = 0; n < 256; n++) {
            c = n;
            for (var k = 0; k < 8; k++) {
                c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
            }
            crcTable[n] = c;
        }
        return crcTable;
    }

    var crc32 = function(str) {
        var crcTable = window.crcTable || (window.crcTable = makeCRCTable());
        var crc = 0 ^ (-1);
        for (var i = 0; i < str.length; i++) {
            crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF];
        }
        return (crc ^ (-1)) >>> 0;
    };

    function saveAs(uri, filename) {
        var link = document.createElement('a');
        if (typeof link.download === 'string') {
            link.href = uri;
            link.download = filename;

            document.body.appendChild(link);

            link.click();

            document.body.removeChild(link);
        } else {
            window.open(uri);
        }
    }



    function createOpenTag(table, field, depth) {
        var result = "";
        for (i = 0; i < depth; i++) result += "\t"
        result += "<";

        result += XML_NAMESPACE + table + ":" + field;
        result += ">\n"

        return result;

    }


    function createCloseTag(table, field, depth) {
        var result = "";
        for (i = 0; i < depth; i++) result += "\t"
        result += "</";
        result += XML_NAMESPACE + table + ":" + field;
        result += ">\n"

        return result;

    }

    function createTag(table, field, content, depth) {
        var result = "";
        if (content !== false && content !== true) {
            for (i = 0; i < depth; i++) result += "\t"
            result += "<";

            result += XML_NAMESPACE + table + ":" + field;
            result += ">"
            result += content;
            result += "</";
            result += XML_NAMESPACE + table + ":" + field;
            result += ">\n"
            return result;
        }

        result += "<";
        if (content === false) result += "/";

        result += XML_NAMESPACE + table + ":" + field;
        result += ">\n"

        return result;

    }

    function createXmlWskaznik(index, depth) {
        var arr = state[index];
        var xml = ""
        depth++;
        //console.log("arr")
        //console.log(arr);
        $.each(arr["_res"].concat(arr["_prof"]), function(i, e) {
            xml += createOpenTag("CRM_WSKAZNIK", "CRM_WSKAZNIK", depth);
            xml += createTag("CRM_WSKAZNIK", "ID", e["ID"], depth + 1)
            xml += createTag("CRM_WSKAZNIK", "OPIS_ZASOB", e["OPIS_ZASOB"], depth + 1)
            xml += createTag("CRM_WSKAZNIK", "ID_PRZYPADEK", e["OPIS_ZASOB"], depth + 1)
            xml += createOpenTag("CRM_LISTA_ZASOBOW", "CRM_LISTA_ZASOBOW", depth + 1);
            xml += createTag("CRM_LISTA_ZASOBOW", "ID_PRZYPADEK", e["ID_PRZYPADEK"], depth + 2)
            xml += createCloseTag("CRM_LISTA_ZASOBOW", "CRM_LISTA_ZASOBOW", depth + 1);
            xml += createTag("CRM_WSKAZNIK", "ID", e["ID"], depth + 1)
            xml += createCloseTag("CRM_WSKAZNIK", "CRM_WSKAZNIK", depth);
        })
        return xml;
    }

    function createXmlNormalFields(arr, depth) {
        var xml = ""
        //console.log("!");
        $.each(arr, function(i, e) {
            //console.log(i + "" + e)
            if (i.substr(0, 1) === "_") return true;
            xml += createTag("CRM_PROCES", i, e, depth)
        });
        return xml;
    }

    function createXmlProces(index, depth) {
        var arr = state[index];
        var xml = ""
        xml += createXmlNormalFields(arr, depth);
        xml += createXmlWskaznik(index, depth)
        $.each(state, function(i, e) {
            if (e["PARENT_ID"] != arr["ID"])
                return true;
            xml += createOpenTag("CRM_PROCES", "PROCES", depth)
                xml += createXmlProces(i, depth + 1)

            xml += createCloseTag("CRM_PROCES", "PROCES", depth)
        })
        return xml;
    }


    function saveToXml() {

        var xml = '<?xml version="1.0" encoding="utf-8"?>\n';

        /*
		xml + = 'schema namespace (default): default_db__x3A__CRM_PROCES = "default_db/CRM_PROCES"\n'
	        +   'schema namespace: default_db__x3A__CRM_WSKAZNIK = "default_db/CRM_WSKAZNIK"\n'
	    	+   'schema namespace: default_db__x3A__CRM_IMAGE = "default_db/CRM_IMAGE"\n'
	    */
        var proces_init = state[0];
        xml += '<FeatureCollection xmlns:gml="https://biuro.biall-net.pl/wfs/default_db/gml" ';
        $.each(["CRM_PROCES", "CRM_LISTA_ZASOBOW", "CRM_WSKAZNIK"], function(i, e) {
            xml += 'xmlns:' + XML_NAMESPACE + e + '="https://biuro.biall-net.pl/wfs/default_db/' + e + '" ';
        })
        xml += " >\n\t<gml:featureMember>\n"
        //xml += XML_NAMESPACE+usedTables[e]
        xml += createOpenTag("CRM_PROCES", "PROCES_INIT", 1)
            xml += createXmlProces(0, 2);
        xml += createCloseTag("CRM_PROCES", "PROCES_INIT", 1)
        xml += "\t</gml:featureMember>\n</FeatureCollection>"

        //console.log(xml);
        saveAs('data:Application/octet-stream,' + encodeURIComponent(xml), 'export.xml')
    }



    function customMenu(node) {
        var id = node.id
        //var target = $('#pathList').closest(".p5BModalContent");
        items = {
            "Move_parent": {
                "separator_before": false,
                "separator_after": false,
                "label": "Przepnij proces jako dziecko",
                "action": function(obj) {
                    state[0]["PARENT_ID"] = id;
                    //pathModal(target);
                    showPath(state[0]["PARENT_ID"]);
                }
            },
        }
        return items;

    }

    $(document).on('click', ".checkParent", function() {
        state[0]["PARENT_ID"] = $(this).data("id");
        var target = $(this).closest(".p5bModalModal")
        //pathModal(target);
        //showPath(state[0]["PARENT_ID"]);
        showPath(state[0]["PARENT_ID"], ".pathPreview", true, true);


    })

    function findXmlChildren(xml, tagName) {
        //console.log("tag ", tagName)
        var result = false;
        $.each(xml, function(i, e) {
            if (typeof e[tagName] !== "undefined") {
                result = i;
                return false;
            }
        })
        if (result === false) return false;
        return xml[result][tagName][0];
    }

    function getOnlyLabels(arr, labels) {
        var result = {};
        $.each(labels, function(i, e) {
            if (typeof arr[e] == "undefined")
                result[e] = "";
            else
                result[e] = arr[e];
        })
        return result;

    }

    function loadFromXml(xml) {
        // xml = xmlExample;
        // try {
        //     xml = $.parseXML(xml)
        //     xml = p5WFS_ParseFeatureFieldRecurse(xml)
        //     //console.log(xml);
        //     state = [];
        //     xml = xml.FeatureCollection[0]["gml:featureMember"];
        //     var proces_init = findXmlChildren(xml, XML_NAMESPACE + "CRM_PROCES:PROCES_INIT");
        //     state[0] = getOnlyLabels(proces_init, ["DESC", "ID", "IF_TRUE_GOTO", "IF_TRUE_GOTO_FLAG", "OPIS", "PARENT_ID"])
        //     //state[0] = findChildren(xml.FeatureCollection[0].featureMember, "PROCES_INIT")
        //     //console.log(state);
        //
        // } catch (err) {
        //     console.log("ERROR: " + err)
        // }


    }

    function treeRecursive(data, parent_id, path, tree) {
        $.each(data[parent_id]["childs"], function(i, e) {
            var temp = {}
            temp.id = e.ID;
            if (getIndexById(temp.id, path, "ID") == -1){
                temp["text"] = "<input type=checkbox class='checkParent' style=margin-right:5px; data-id='" + temp.id + "' /> {" + temp.id + "} " + data[temp.id]["DESC"]
            }else {
                temp["text"] = "<input type=checkbox style=margin-right:5px;/><span style=color:#3498db;>{" + temp.id + "} " + data[temp.id]["DESC"] + "</span>"
                temp["state"] = {}
               temp["state"]["opened"] = true;
                if (path[path.length - 1]["ID"] == temp.id) {
                    temp["text"] = "<input type=checkbox style=margin-right:5px; checked /><span style=color:#3498db;>{" + temp.id + "} " + data[temp.id]["DESC"] + "</span>"
                    temp["state"]["selected"] = true;
                    temp["state"]["opened"] = false;
                }
			}
            temp.children = [];
            tree.push(temp)
            treeRecursive(data, temp.id, path, temp.children);
        })
    }

    function renderProcesTree(path) {

        var result = "";
        var link = BASE_URL + "index.php?_route=UrlAction_ProcesEditor&_task=getProcesListAjax";


        $.get(link, function(data) {
            var tree = []
            treeRecursive(data, 0, path, tree)
            $('#pathList').jstree("destroy").empty();
            //console.log(translate(0, data))
            $('#pathList').jstree(

                {
                    'core': {
                        "check_callback": true,
                        "themes": {
                            "stripes": false,
                            "dots": false
                        },
                        "data": tree
                    },
                    "types": {
                        "default": {
                            "icon": "hide",
                        },
                        "proces": {
                            "icon": "hide",
                        },
                    },
                    "plugins": [
                        "contextmenu", "search",
                        "types"
                    ],
                    "contextmenu": {
                        "items": customMenu
                    }

                });


        })

    }

    function pathModal(target) {
        $(target).html("<div style=display:none; class=pathPreview></div>Zaznacz proces nadrzędny: <div id=pathList>" +
            "</div>" +
            "<button type='button' class='btn btn-primary p5BModalButton' id='savePath'>Zachowaj</button>" +
            "<button type='button' class='btn btn-default p5BModalButton' id='previousPath'>Anuluj</button>" +
            "");
        $("#pathList").data("previous", state[0]["PARENT_ID"])
        showPath(state[0]["PARENT_ID"], ".pathPreview", true, true);

    }

    /* START p5BModal */

    $(document).on('click', '.p5BModalDelete, #previousPath,#p5BModalBack', function() {
        if ($(this).closest(".p5BModalModal").find("#pathList").length > 0) {

            state[0]["PARENT_ID"] = $(this).closest(".p5BModalModal").find("#pathList").data("previous")
        }
        showPath(state[0]["PARENT_ID"]);
        hideModal($(this).closest(".p5BModalModal"));

        return false;
    })

    function p5BModalDisplay(title, initFunction, args) {
        var back = '<div id="p5BModalBack" style="display:none"></div>'

        var modal = '<div class="p5BModalHeader">' +
            "<span>" + title + "</span>" +
            '<div class="p5BModalDelete">X</div>' +
            "</div>" +
            '<div class="p5BModalContent"></div>'

        if ($("#p5BModalBack").length <= 0) {
            $("body").prepend(back);
            $("#p5BModalBack").fadeIn('fast');
            // $('html, body').css({
            //     overflow: 'hidden',
            //     height: '100%'
            // });
        }
        var p5BModal = $("<div>", {
            "class": "p5BModalModal"
        });
        $("#p5BModalBack").append(p5BModal);
        $(p5BModal).html(modal);



        $(p5BModal).draggable({
            containment: "body",
            handle: ".p5BModalHeader"
        });
        if (args)
            initFunction($(p5BModal).find(".p5BModalContent"), args)
        else
            initFunction($(p5BModal).find(".p5BModalContent"))

    }



    $(document).on('click', '.editPath', function() {
        p5BModalDisplay("Przepinanie procesu", pathModal);
    });

    function hideModal(which) {
        $(which).remove();
        if ($(".p5BModalModal").length == 0) {
            $("#p5BModalBack").fadeOut('fast', function() {
                $("#p5BModalBack").remove();
            });
            // $('html, body').css({
            //     overflow: 'auto',
            //     height: '100%'
            // });
        }

    }



    $(document).on('click', '#savePath', function() {
        showPath(state[0]["PARENT_ID"]);
        hideModal($(this).closest(".p5BModalModal"));

        return false;
    })




    $(document).on('mousedown', '.p5BModalModal', function() {
        $(".p5BModalModal").css("z-index", 2001)
        $(this).css("z-index", 2002)

    })

    /* END p5BModal */

    $(document).on('click', '#expBtn', function() {
        var exp = {};
        exp["ID"] = mainProces_id;
        exp["time"] = moment().format("YYYY-MM-DD HH:mm:ss");

        var temp = {};
        temp["state"] = state;
        temp["newSteps"] = newSteps;
        temp["newRes"] = newRes;
        temp["deletedId"] = deletedId;
        temp["deletedRes"] = deletedRes;
        exp["data"] = temp;
        var crc = {};
        crc["crc"] = crc32(JSON.stringify(exp));
        crc["content"] = exp;
        swal({
            title: 'Import/Export',
            text: 'Wybierz czynność:',
            type: 'warning',
            cancelButtonText: 'Import',
            confirmButtonText: 'Export',
            cancelButtonColor: '#d33',
            confirmButtonColor: '#3085d6',
            showCancelButton: true,
        }).then(function() {
            saveToXml();
        }, function(dismiss) {
            if (dismiss === 'cancel') {
                swal({
                    title: 'Import',
                    text: 'Wklej dane do zaimportowania:',
                    inputPlaceholder: "Wklej tutaj dane, które otrzymałeś w trakcie eksportu.",
                    input: 'textarea',
                }).then(function(imp) {
                    loadFromXml(imp);
                })
            }
        }).catch(function(e) {
            console.log('Error', e)
        })

    })

    function saveProces() {
        $("#saveBtn").prop('disabled', true);
        $.notify("Rozpoczęto zapisywanie. Nie zamykaj tego okna", "info");
        var genReq = `
  <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_WFS_URL + `/default_db"
    xmlns:gml="http://www.opengis.net/gml">
    `;
        // xsi:schemaLocation="` + BASE_WFS_URL + `/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;"
        $.each(state, function(i, e) {
            if (e['ID'] < 0) {
                genReq += `
            <Insert xmlns="http://www.opengis.net/wfs">
            <CRM_PROCES xmlns="` + BASE_WFS_URL + `/default_db">
            <PARENT_ID xmlns="` + BASE_WFS_URL + `/default_db">-1</PARENT_ID>
            </CRM_PROCES>
            </Insert>`;
            }
        });
        genReq += '</Transaction>';
        var link = BASE_URL + 'wfs-data.php/default_db/?SERVICE=WFS&VERSION=1.0.0&SRSNAME=EPSG:3003&';
        $.ajax({
            url: link,
            data: genReq,
            type: 'POST',
            contentType: "text/xml",
            dataType: "text",
            success: function(data) {
                $(data).find("[fid]").each(function(i, e) {
                    var newId = $(e).attr("fid").substr($(e).attr("fid").indexOf('.') + 1);
                    generatedId.push(newId);
                });
                var i = 0;
                var newIdTab = Array();
                $.each(state, function(z, e) {
                    if (e["ID"] < 0) {
                        newIdTab[e["ID"]] = generatedId[i];
                        i++;
                    }
                });

                var request = `
            <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_WFS_URL + `/default_db"
            xmlns:gml="http://www.opengis.net/gml">
            `;
                $.each(state, function(i, e) {
                    request += `
    <Insert xmlns="http://www.opengis.net/wfs">
      <CRM_PROCES xmlns="` + BASE_WFS_URL + `/default_db">
    `;
                    if (e["ID"] >= 0)
                        request += '<ID xmlns="' + BASE_WFS_URL + '/default_db">' + e["ID"] + '</ID>';
                    else
                        request += '<ID xmlns="' + BASE_WFS_URL + '/default_db">' + newIdTab[e["ID"]] + '</ID>';
                    if (i == 0)
                        request += '<TYPE xmlns="' + BASE_WFS_URL + '/default_db">PROCES_INIT</TYPE>';
                    else
                        request += '<TYPE xmlns="' + BASE_WFS_URL + '/default_db">PROCES</TYPE>';
                    if (e["PARENT_ID"] >= 0)
                        request += '<PARENT_ID xmlns="' + BASE_WFS_URL + '/default_db">' + e["PARENT_ID"] + '</PARENT_ID>';
                    else
                        request += '<PARENT_ID xmlns="' + BASE_WFS_URL + '/default_db">' + newIdTab[e["PARENT_ID"]] + '</PARENT_ID>';
                    request += '<SORT_PRIO xmlns="' + BASE_WFS_URL + '/default_db">' + e["SORT_PRIO"] + '</SORT_PRIO>';

                    if (e["IF_TRUE_GOTO"] != false) {
                        request += '<IF_TRUE_GOTO xmlns="' + BASE_WFS_URL + '/default_db">' + e["IF_TRUE_GOTO"] + '</IF_TRUE_GOTO>';
                        request += '<IF_TRUE_GOTO_FLAG xmlns="' + BASE_WFS_URL + '/default_db">' + e["IF_TRUE_GOTO_FLAG"] + '</IF_TRUE_GOTO_FLAG>';
                    } else {
                        request += '<IF_TRUE_GOTO xmlns="' + BASE_WFS_URL + '/default_db">0</IF_TRUE_GOTO>';
                        request += '<IF_TRUE_GOTO_FLAG xmlns="' + BASE_WFS_URL + '/default_db"></IF_TRUE_GOTO_FLAG>';
                    }
                    request += '<DESC xmlns="' + BASE_WFS_URL + '/default_db">' + cData(e["DESC"]) + '</DESC>';
                    request += '<OPIS xmlns="' + BASE_WFS_URL + '/default_db">' + cData(e["OPIS"]) + '</OPIS>';
                    request += `
    </CRM_PROCES>
  </Insert>
    `;
                    var id;
                    if (e["ID"] >= 0)
                        id = e["ID"];
                    else
                        id = newIdTab[e["ID"]];
                    var sort_prio = 0;
                    $.each(e["_prof"].concat(e["_res"]), function(iR, eR) {
                        sort_prio++;
                        request += `
  <Insert xmlns="http://www.opengis.net/wfs">
    <CRM_WSKAZNIK xmlns="` + BASE_WFS_URL + `/default_db">
  `;
                        if (eR["ID"] >= 0) {
                            request += '<ID xmlns="' + BASE_WFS_URL + '/default_db">' + eR["ID"] + '</ID>';
                        }
                        request += '<ID_ZASOB xmlns="' + BASE_WFS_URL + '/default_db">' + eR["ID_ZASOB"] + '</ID_ZASOB>';
                        request += '<ID_PROCES xmlns="' + BASE_WFS_URL + '/default_db">' + id + '</ID_PROCES>';
                        request += '<ID_PRZYPADEK xmlns="' + BASE_WFS_URL + '/default_db">' + eR["ID_PRZYPADEK"] + '</ID_PRZYPADEK>';

                        var opis = eR["OPIS_ZASOB"];
                        opis = opis.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&apos;');
                        request += '<SORT_PRIO xmlns="' + BASE_WFS_URL + '/default_db">' + sort_prio + '</SORT_PRIO>';
                        request += '<OPIS_ZASOB xmlns="' + BASE_WFS_URL + '/default_db">' + cData(opis) + '</OPIS_ZASOB>';
                        request += `
</CRM_WSKAZNIK>
</Insert>
`;
                    });
                });
                $.each(deletedId, function(key, value) {

                    if (value < 0)
                        return true;

                    request += `
    <Insert xmlns="http://www.opengis.net/wfs">
      <CRM_PROCES xmlns="` + BASE_WFS_URL + `/default_db">
    `;
                    request += '<ID xmlns="' + BASE_WFS_URL + '/default_db">' + value + '</ID>';
                    request += '<PARENT_ID xmlns="' + BASE_WFS_URL + '/default_db">-1</PARENT_ID>';
                    request += '<A_STATUS xmlns="' + BASE_WFS_URL + '/default_db">DELETED</A_STATUS>';
                    request += `
    </CRM_PROCES>
  </Insert>
    `;
                });
                $.each(deletedRes, function(key, value) {
                    if (value < 0)
                        return true;
                    request += `
    <Insert xmlns="http://www.opengis.net/wfs">
      <CRM_WSKAZNIK xmlns="` + BASE_WFS_URL + `/default_db">
    `;
                    request += '<ID xmlns="' + BASE_WFS_URL + '/default_db">' + value + '</ID>';
                    request += '<A_STATUS xmlns="' + BASE_WFS_URL + '/default_db">DELETED</A_STATUS>';
                    request += `
    </CRM_WSKAZNIK>
  </Insert>
    `;
                });

                $.each(usedImg, function(key, value) {
                    //console.log("usedImg()")
                    //console.log(key, value)
                    if (key < 0)
                        return true;
					if(value.action == "ATTACH"){
						request +=
							`
							<Insert xmlns="http://www.opengis.net/wfs">
							<CRM_IMAGE xmlns="` +
							BASE_WFS_URL + `/default_db">
						`;
						request += '<ID xmlns="' + BASE_WFS_URL + '/default_db">' + key + '</ID>';
						request += '<REMOTE_TABLE xmlns="' + BASE_WFS_URL + '/default_db">' + value["type"] + '</REMOTE_TABLE>';
						request += '<REMOTE_ID xmlns="' + BASE_WFS_URL + '/default_db">' + (value["targetID"] >= 0 ? value["targetID"] : newIdTab[value["targetID"]]) + '</REMOTE_ID>';
						request += `
							</CRM_IMAGE>
							</Insert>
						`;
					}else if(value.action == "DELETED"){
						request += '<Delete xmlns="http://www.opengis.net/wfs" typeName="p5_default_db:CRM_IMAGE">'
						request += '<Filter xmlns="http://www.opengis.net/ogc">'
						request += '<FeatureId xmlns="http://www.opengis.net/ogc" fid="CRM_IMAGE.'+key+'" />'
						request += '</Filter>'
						request += '</Delete>'

					}
                });



                request += '</Transaction>';
				        //console.log(request);
                $.ajax({
                    url: link,
                    data: request,
                    type: 'POST',
                    contentType: "text/xml",
                    dataType: "text",
                    success: function(data) {
                        if ($(data).children("serviceException").text() == "") {
                            if (mainProces_id == -1)
                                window.location.replace("index.php?_route=UrlAction_procesEditor&id=" + newIdTab[state[0]["ID"]])
                            deletedRes = [];
                            deletedId = [];
                            usedImg = {};
                            localStorage.removeItem("state" + mainProces_id);
                            showPreview();
                            $.notify("Zmiany zostały zapisane na serwerze.", "success");
                        } else {
                            $.notify("Błąd API. Zmiany zostały zapisane wyłącznie w pamięci Twojej przeglądarki. Skontaktuj się z administratorem.", "error");
                            localStorage.setItem("state" + mainProces_id, JSON.stringify(state));
                            localStorage.setItem("newStep" + mainProces_id, newSteps);
                            localStorage.setItem("newRes" + mainProces_id, newRes);
                            localStorage.setItem("deletedId" + mainProces_id, JSON.stringify(deletedId));
                            localStorage.setItem("usedImg" + mainProces_id, JSON.stringify(usedImg));
                            localStorage.setItem("deletedRes" + mainProces_id, JSON.stringify(deletedRes));
                            localStorage.setItem("date" + mainProces_id, moment().format("YYYY-MM-DD HH:mm:ss"));
                        }
                        $("#saveBtn").prop('disabled', false);
                    },
                    error: function(xhr, ajaxOptions, thrownError) {
                        $.notify("Brak połączenia z bazą danych", "error");
                    }
                });
            },
            error: function(xhr, ajaxOptions, thrownError) {
                $.notify("Brak połączenia z bazą danych", "error");
            }
        });

    }

    $(document).on('click', '#saveBtn', function() {
        if (state[0]["PARENT_ID"] <= 0)
            swal({
                title: 'Brak procesu nadrzędnego',
                text: "proces_init nie został przypięty do żadnego nadrzędnego procesu.",
                type: 'error',
                showCancelButton: true,
                cancelButtonColor: '#3085d6',
                confirmButtonColor: '#d33',
                cancelButtonText: "Edytuj ścieżkę <i style=color:#00cc00;font-weight:bold;>[ZALECANE]</span>",
                confirmButtonText: 'Kontynuuj'
            }).then(function() {
                    saveProces();
                }, function(dismiss) {
                    p5BModalDisplay("Przepinanie procesu", pathModal);

                }

            ).catch(function(e) {})
        else
            saveProces();


    });

    $(document).on('click', '.btnEdit', function() {
        var parentIndex = getIndexById($(this).parents(".drop").data("id"));
        var type;
        if ($(this).parents("li").closest(".professions").length > 0)
            type = "_prof";
        else
            type = "_res";
        var zasobIndex = getResById(parentIndex, $(this).parents("li").data("id"), type);
        var permsOpt = "";
        $.each(perms, function(key, value) {
            if (state[parentIndex][type][zasobIndex]["ID_PRZYPADEK"] == value[0])
                permsOpt = permsOpt + "<option value=" + value[0] + " selected=selected>[" + value[2] + "] " + value[1] + "</option>";
            else
                permsOpt = permsOpt + "<option value=" + value[0] + ">[" + value[2] + "] " + value[1] + "</option>";
        });
        swal({
            showCancelButton: true,
            title: 'Uprawnienia',
            html: 'Uprawnienia<br><select class=form-control id="swal-input1">' + permsOpt + '</select>' +
                'Komentarz<br><input class=form-control id="swal-input2" class="swal2-input" value="' + state[parentIndex][type][zasobIndex]["OPIS_ZASOB"] + '">',
            preConfirm: function() {
                return new Promise(function(resolve) {
                    resolve([
                        $('#swal-input1').val(),
                        $('#swal-input2').val()
                    ]);
                });
            }
        }).then(function(result) {
            state[parentIndex][type][zasobIndex]["ID_PRZYPADEK"] = result[0];
            state[parentIndex][type][zasobIndex]["OPIS_ZASOB"] = result[1];
            state[parentIndex][type][zasobIndex]["changed"] = true;
            updateAll();
        }).catch(function(e) {})
    });

    //Buttony i ich zadania
    $(document).on('click', '.step', function() {
        newSteps--;
        var main = false;
        var temp = {};
        if ($(this).parents(".drop").data("id") === mainProces_id)
            main = true;
        $(this).parents(".drop").after("<div class='drop container-fluid' id='proc" + newSteps + "'></div>");
        temp["ID"] = newSteps;
        temp["DESC"] = "";
        temp["OPIS"] = "";
        var index = getIndexById($(this).parents(".drop").data("id"));
        temp["_step"] = 0;
        temp["_prof"] = new Array();
        temp["_res"] = new Array();
        temp["_C-desc"] = true;
        temp["_C-opis"] = true;
        temp["IF_TRUE_GOTO_FLAG"] = "";
        temp["IF_TRUE_GOTO"] = 0;
        temp["_stepDesc"] = "";
        if (!main) {
            temp["PARENT_ID"] = state[index]["PARENT_ID"];
            temp["_depth"] = state[index]["_depth"];
        } else {
            temp["PARENT_ID"] = mainProces_id;
            temp["_depth"] = 1;
        }
        state.splice(index + 1, 0, temp);
        stepsGenerator();
        updateAll();
    });

    $(document).on('keyup', '#sProcesy', function() {
        if ($(this).val() != lastSearch) {
            lastSearch = $(this).val();
            clearTimeout(sProcesy);
            sProcesy = setTimeout(function() {
                if (lastSearch == "")
                    procesy();
                else
                    searchProc();
            }, 300);
        }
    });
    $(document).on('keyup', '#sZasoby', function() {
        if ($(this).val() != lastSearch) {
            lastSearch = $(this).val();
            clearTimeout(sZasoby);
            sZasoby = setTimeout(function() {
                if (filtr === 0 && lastSearch == "")
                    zasoby();
                else
                    searchRes();
            }, 300);
        }
    });

    function arraymove(arr, fromIndex, toIndex) {
        var element = [];
        var element = arr[fromIndex];
        arr.splice(fromIndex, 1);
        arr.splice(toIndex, 0, element);
    }

    $(document).on('click', '.uArrowRes', function() {
        var parent = getIndexById(($(this).parents(".drop").data("id")));
        if ($(this).closest(".professions").length > 0)
            type = "_prof";
        else
            type = "_res";
        var id = getResById(parent, $(this).closest("li").data("id"), type);
        arraymove(state[parent][type], id, id - 1);
        updateAll();
    });

    $(document).on('click', '.dArrowRes', function() {
        var parent = getIndexById(($(this).parents(".drop").data("id")));
        if ($(this).closest(".professions").length > 0)
            type = "_prof";
        else
            type = "_res";
        var id = getResById(parent, $(this).closest("li").data("id"), type);
        arraymove(state[parent][type], id, id + 1);
        updateAll();
    });

    $(document).on('click', '.uArrow', function() {
        var id = $(this).parents(".drop").data("id");
        var index = getIndexById(id);
        arraymove(state, index, index - 1);
        updateAll();
    });

    $(document).on('click', '.dArrow', function() {
        var id = $(this).parents(".drop").data("id");
        var index = getIndexById(id);
        arraymove(state, index, index + 1);
        updateAll();
    });

    $(document).on('click', '.rArrow', function() {
        var id = $(this).parents(".drop").data("id");
        state[getIndexById(id)]["_depth"]++;
        //var depthWidth = 20 * $(node).data("_depth");
        // $(node).css("padding-left", depthWidth + "px");
        updateAll();
    });

    $(document).on('click', '.lArrow', function() {
        var id = $(this).parents(".drop").data("id");
        state[getIndexById(id)]["_depth"]--;
        //var depthWidth = 20 * $(node).data("_depth");
        // $(node).css("padding-left", depthWidth + "px");
        updateAll();
    });

    $(document).on('click', '#btnZasoby', function(e) {
        e.preventDefault();
        $(".lButton").removeClass("btn-primary");
        if (dialog == 0) {
            zasoby();
            $(this).addClass("btn-primary");
            $("#wrapper").removeClass("toggled");
            dialog = 1;
        } else if (dialog == 1) {
            $("#wrapper").addClass("toggled");
            dialog = 0;
        } else {
            $("#wrapper").addClass("toggled");
            $(this).addClass("btn-primary");
            setTimeout(function() {
                zasoby();
                $("#wrapper").removeClass("toggled");
            }, 500);
            dialog = 1;
        }
    });

    $(document).on('click', '#btnPhotos', function(e) {
        e.preventDefault();
        $(".lButton").removeClass("btn-primary");
        if (dialog == 0) {
            photos();
            $(this).addClass("btn-primary");
            $("#wrapper").removeClass("toggled");
            dialog = 3;
        } else if (dialog == 3) {
            $("#wrapper").addClass("toggled");
            dialog = 0;
        } else {
            $("#wrapper").addClass("toggled");
            $(this).addClass("btn-primary");
            setTimeout(function() {
                photos();
                $("#wrapper").removeClass("toggled");
            }, 500);
            dialog = 3;
        }
    });

    $(document).on('click', '#btnProcesy', function(e) {
        e.preventDefault();
        $(".lButton").removeClass("btn-primary");
        if (dialog == 0) {
            procesy();
            $("#wrapper").removeClass("toggled");
            $(this).addClass("btn-primary");
            dialog = 2;
        } else if (dialog == 2) {
            $("#wrapper").addClass("toggled");
            dialog = 0;
        } else {
            $("#wrapper").addClass("toggled");
            $(this).addClass("btn-primary");
            setTimeout(function() {
                procesy();
                $("#wrapper").removeClass("toggled");
            }, 500);
            dialog = 2;
        }
    });

    $(document).on('click', 'body', function() {
        if (selectedArea != false) {
            var content = $(selectedArea).val();
            var id = (selectedArea).parents(".drop").data("id");
            if ($(selectedArea).parent().hasClass("hdesc")) {
                if (getIndexById(id) == 0) {
                    showPath(state[0]["PARENT_ID"]);
                }
                state[getIndexById(id)]["DESC"] = content;
                state[getIndexById(id)]["_C-desc"] = true;
            }
            if ($(selectedArea).parent().hasClass("sdesc")) {
                state[getIndexById(id)]["OPIS"] = content;
                state[getIndexById(id)]["_C-opis"] = true;
            }
            selectedArea = false;
            updateAll();
        }
    });

    $(document).on('click', '.hdesc', function() {
        if ($(this).find("textarea").is(selectedArea))
            return false;
    });

    $(document).on('click', '.sdesc', function() {
        if ($(this).find("textarea").is(selectedArea))
            return false;
    });

    $(document).on('dblclick', '.sdesc', function() {
        if (selectedArea)
            return;
        if ($(this).find("textarea").length == 0) {
            var content = $(this).html();
            $(this).empty();
            $(this).append("<textarea>" + content + "</textarea>");
            selectedArea = $(this).find("textarea");
        }
    });

    $(document).on('click', '.sDescAdd', function() {
        if (selectedArea)
            return;
        var action = $(this).parents(".drop").find(".sdesc");

        if ($(action).find("textarea").length == 0) {
            $(action).html("<textarea placeholder='Opis kroku'>" + $(action).text() + "</textarea>");
            selectedArea = $(action).find("textarea");
            return false;
        }
    });

    $(document).on('click', '.hDescAdd', function() {
        if (selectedArea)
            return;
        var action = $(this).parents(".drop").find(".hdesc");
        if ($(action).find("textarea").length == 0) {
            $(action).html("<textarea placeholder='Tytuł kroku'>" + $(action).text() + "</textarea>");
            selectedArea = $(action).find("textarea");
            return false;
        }
    });

    $(document).on('dblclick', '.hdesc', function() {
        if ($(this).find("textarea").length == 0) {
            var content = $(this).html();
            $(this).empty();
            $(this).append("<textarea>" + content + "</textarea>");
            selectedArea = $(this).find("textarea");
        }
    });

    $(document).on('click', '.del', function() {
        var id = $(this).parents(".drop").data("id");
        var index = getIndexById(id);
        swal({
            title: 'Usuwanie kroku',
            text: "Czy napewno chcesz usunąć ten krok?",
            type: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            cancelButtonText: "Anuluj",
            confirmButtonText: 'Tak, usuń ten krok'
        }).then(function() {
            state.splice(index, 1);
            deletedId.push(id);
            updateAll();
            //Parent_id = -1,
        }).catch(function(e) {})
    });

    $(document).on('click', '.delGoto', function() {
        //var parent = $(this).parents(".drop");
        var id = $(this).parents("li").data("id");
        var parent = getIndexById($(this).parents(".drop").data("id"));
        swal({
            title: 'Usuwanie bramki',
            text: "Czy napewno chcesz usunąć tę bramkę?",
            type: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            cancelButtonText: "Anuluj",
            confirmButtonText: 'Tak, usuń tę bramkę'
        }).then(function() {
            state[parent]["IF_TRUE_GOTO_FLAG"] = ""
            state[parent]["IF_TRUE_GOTO"] = ""
            updateAll();
            //Parent_id = -1,
        }).catch(function(e) {})
    });

    $(document).on('click', '.delRes', function() {
        //var parent = $(this).parents(".drop");
        var id = $(this).parents("li").data("id");
        var parent = getIndexById($(this).parents(".drop").data("id"));
        var type;
        if ($(this).closest(".professions").length > 0)
            type = "_prof";
        else
            type = "_res";
        var index = getResById(parent, id, type);
        swal({
            title: 'Usuwanie wskaźnika',
            text: "Czy napewno chcesz usunąć ten wskaźnik?",
            type: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            cancelButtonText: "Anuluj",
            confirmButtonText: 'Tak, usuń ten wskaźnik'
        }).then(function() {
            deletedRes.push(id);
            state[parent][type].splice(index, 1);
            updateAll();
            //Parent_id = -1,
        }).catch(function(e) {})
    });

    $(document).on('click', '.fbutton', function(e) {
        e.preventDefault();
        $(".fbutton").removeClass("btn-success");
        if ($(this).data("type") == filtr) {
            filtr = 0;
        } else {
            filtr = $(this).data("type");
            $(this).addClass("btn-success");
        }
        if (filtr === 0)
            $("#xBtn").prop("disabled", true);
        else
            $("#xBtn").prop("disabled", false);
        if (filtr === 0) {
            zasoby();
        } else
            searchRes();
    });

    $(document).on('click', '.showMore', function() {
        var target = $(this).parent().find(".more");
        var id = $(this).data("id");
        if ($(target).parent().hasClass("resSelected")) {
            $(".more").empty();
            $(target).parent().removeClass("resSelected");
            $(target).parent().find(".gIco").addClass("glyphicon-chevron-down");
            $(target).parent().find(".gIco").removeClass("glyphicon-chevron-up");
        } else {
            $(".more").parent().removeClass("resSelected");
            $(".more").parent().find(".gIco").addClass("glyphicon-chevron-down");
            $(".more").parent().find(".gIco").removeClass("glyphicon-chevron-up");
            $(".more").empty();
            $(target).parent().addClass("resSelected");
            $(target).parent().find(".gIco").removeClass("glyphicon-chevron-down");
            $(target).parent().find(".gIco").addClass("glyphicon-chevron-up");

            var link = BASE_URL + "index.php?_route=UrlAction_ProcesEditor&_task=getResByParentAjax&parent_id=" + id;
            $.get(link, function(data) {
                $.each(data, function(i, e) {
                    if (e["ID"] != 0) {
                        var type = 0;
                        $(target).append("<div class='dragStyle drag dragStyle hov' data-id=" +
                            e["ID"] +
                            " data-type=" +
                            type + " data-DESC='" +
                            e["DESC"] +
                            "' data-OPIS='" +
                            e["OPIS"] +
                            "'>" +
                            e["DESC"] +
                            " [" +
                            e["ID"] + "]</div>");
                        for (var i = 3; i > 0; i--) {
                            if (e["p" + i + "_ID"] != null) {
                                var temp = {};
                                temp["ID"] = e["p" + i + "_ID"];
                                temp["DESC"] = e["p" + i + "_DESC"];
                                zasobTree[e["ID"]] = [];
                                zasobTree[e["ID"]].push(temp);
                            }
                        }
                        updateDropZones();
                    }
                });
            });
        }
    });

    function searchProc() {
        var id = lastSearch;
        var link;
        //link = BASE_URL + 'wfs-data.php/default_db/?SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&TYPENAME=p5_default_db:CRM_PROCES&SRSNAME=EPSG:3003&Filter=<ogc:Filter></ogc:Filter>&';
        p5WFS_GetFeature('p5_default_db:CRM_PROCES', {
            'Filter': '<ogc:Or><ogc:PropertyIsLike wildCard="*" singleChar="^" escapeChar="!"><ogc:PropertyName>ID</ogc:PropertyName><ogc:Literal>*' + id + '*</ogc:Literal></ogc:PropertyIsLike><ogc:PropertyIsLike wildCard="*" singleChar="%23" escapeChar="!"><ogc:PropertyName>DESC</ogc:PropertyName><ogc:Literal>*' + id + '*</ogc:Literal></ogc:PropertyIsLike></ogc:Or>',
            'sortBy': 'SORT_PRIO+A,ID',
            'maxFeatures': 100,
        }).then(function(features) {
            var side = $("#side");
            $(side).find("#ulproc").empty();
            $.each(features, function(i, xml) {
                if (xml["ID"] * 1 == 0) {
                    $(side).find("#ulcon").append("<div><center>Brak wyników wyszukiwania</center></div>");
                    return;
                }
                $(side).find("#ulproc").append("<div class='dragStyle drag dragStyle hov' data-droptype=1 data-id=" +
                    xml["ID"] +
                    " > " +
                    xml["DESC"] +
                    " [" +
                    xml["ID"] +
                    "]</div>");
                updateDropZones();
            });
        }).catch(function(e) {
            console.log('Error', e)
        })
    }

    function searchRes() {
        var id = lastSearch;
        var link;
        link = BASE_URL + "index.php?_route=UrlAction_ProcesEditor&_task=getResAjax&word=" + id + "&filter=" + filtr;

        $.get(link, function(data) {
            var side = $("#side");
            $(side).find("#ulcon").empty();
            if (data.length == 0)
                $(side).find("#ulcon").append("<div><center>Brak wyników wyszukiwania</center></div>");
            $.each(data, function(i, e) {
                var tree = "";
                for (var i = 3; i > 0; i--) {
                    if (e["p" + i + "_ID"] != null) {
                        var temp = {};
                        temp["ID"] = e["p" + i + "_ID"];
                        temp["DESC"] = e["p" + i + "_DESC"];
                        zasobTree[e["ID"]] = [];
                        zasobTree[e["ID"]].push(temp);
                        tree += e["p" + i + "_DESC"] + (i > 1 ? " <span class='glyphicon glyphicon-triangle-right'></span>" : "");
                    }
                }
                var type = 0;
                if (e["TYPE"] == "DZIAL" || e["TYPE"] == "PODMIOT" || e["TYPE"] == "STANOWISKO")
                    type = 1;
                if (filtr != 2 || e["TYPE"] != "TABELA")
                    $(side).find("#ulcon").append("<div class='drag dragStyle hov' data-id=" + e["ID"] + " data-type=" + type + " data-DESC='" + e["DESC"] + "' data-OPIS='" + e["OPIS"] + "'><span class=treeInfo ><div>" + tree + "</div></span><br>" + e["DESC"] + " [" + e["ID"] + "]</div>");
                else {
                    $(side).find("#ulcon").append("<div ><span  class='drag dragStyle click' data-id=" + e["ID"] + " data-type=" + type + " data-DESC='" + e["DESC"] + "' data-OPIS='" + e["OPIS"] + "'> # </span>  <div style=width:80%;float:left; data-id=" + e["ID"] + " class=showMore><span class=tabelaName><span class=treeInfo ><div>" + tree + "</div></span><br>" + e["DESC"] + "</span> [" + e["ID"] + "]</div><span class='gIco glyphicon glyphicon-chevron-down' style:float:left;></span><div style=clear:both;></div><div class=more ></div></div>");
                }
            });
            updateDropZones();
        });
    }

    $(document).on('click', '.liProc', function() {
        $(this).parents(".singleAdv").nextAll(".singleAdv").remove();
        $(this).parents(".singleAdv").find(".active").removeClass("active");
        $(this).find(".glyphicon").removeClass("glyphicon-triangle-right");
        $(this).find(".glyphicon").addClass("glyphicon-refresh");
        $(this).find(".glyphicon").addClass("anim-refresh");
        $(this).addClass("active");
        var parent = this;
        var parent_id = $(this).data("id");
        //var link = BASE_URL + 'wfs-data.php/default_db/?SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&TYPENAME=p5_default_db:CRM_PROCES&SRSNAME=EPSG:3003&Filter=<ogc:Filter><ogc:PropertyIsEqualTo><ogc:PropertyName>PARENT_ID</ogc:PropertyName><ogc:Literal>' + parent_id + '</ogc:Literal></ogc:PropertyIsEqualTo></ogc:Filter>';
        var result = "";
        var depth = $(this).parents(".singleAdv").data("_depth") + 1;
        $("#procCon").css("width", depth * 290 + 290);
        $(this).parents(".singleAdv").after("<div class='singleAdv list-group' data-depth=" + depth + " id=depth" + depth + "></div>");
        var childs = true;
        p5WFS_GetFeature('p5_default_db:CRM_PROCES', {
            'Filter': '<ogc:PropertyIsEqualTo><ogc:PropertyName>PARENT_ID</ogc:PropertyName><ogc:Literal>' + parent_id + '</ogc:Literal></ogc:PropertyIsEqualTo>',
            'sortBy': 'SORT_PRIO+A,ID',
        }).then(function(features) {
            $.each(features, function(i, xml) {
                if (xml["ID"] == 0) {
                    childs = false;
                    return;
                }
                var type = 0;
                result += "<div class='list-group-item drag liProc' data-OPIS='" +
                    xml["OPIS"] + "' data-DESC='" +
                    xml["DESC"] +
                    "' data-droptype=1 data-id=" +
                    xml["ID"] +
                    " ><div class=textTable><span class=handle> # </span>" +
                    xml["DESC"] +
                    "</div><div class=detailsTable>[" +
                    xml["ID"] +
                    "]</div><div class='glyphicon glyphicon-triangle-right' style=opacity:0.4;float:right;></div><div class=clearfix></div></div>";
            });
            if (!childs) {
                result += '<div class="panel panel-primary">';
                result += '<div class="panel-heading"><h3 class="panel-title">[' + $(parent).data('ID') + '] ' + $(parent).data("DESC") + '</h3></div>';
                result += '<div class="panel-body pbody">';
                result += '<b>Opis: </b>' + $(parent).data("OPIS");
                result += '</div>';
                result += '</div>'
            }
            $("#depth" + depth).html(result);
            updateDropZones();
            $(parent).find(".glyphicon").addClass("glyphicon-triangle-right");
            $(parent).find(".glyphicon").removeClass("glyphicon-refresh");
            $(parent).find(".glyphicon").removeClass("anim-refresh");
            $("#ulproc").scrollLeft(depth * 290 + 290);
            $("#ulproc").scrollTop(0);
        }).catch(function(e) {
            console.log('Error', e)
        })
    });

    function procesy() {
        var side = $("#side");
        $(side).empty();
        //$(side).append("<h3>Zarządzaj zasobami<h3>");
        $(side).append("<div class='form-group' ><input type='text' class=form-control id=sProcesy placeholder='Szukaj procesów'></div>");
        $(side).append("<div id=ulproc><div id=procCon></div></div>");
        $(side).find("#procCon").append("<div class='singleAdv list-group' data-depth=0 id=depth0></div>");
        $(side).find("#procCon").append("<div class=clearfix></div>");
        //var link = BASE_URL + 'wfs-data.php/default_db/?SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&TYPENAME=p5_default_db:CRM_PROCES&SRSNAME=EPSG:3003&Filter=<ogc:Filter><ogc:PropertyIsEqualTo><ogc:PropertyName>PARENT_ID</ogc:PropertyName><ogc:Literal>0</ogc:Literal></ogc:PropertyIsEqualTo></ogc:Filter>&sortBy=SORT_PRIO+A,ID';
        var result = "";
        p5WFS_GetFeature('p5_default_db:CRM_PROCES', {
            'Filter': '<ogc:PropertyIsEqualTo><ogc:PropertyName>PARENT_ID</ogc:PropertyName><ogc:Literal>0</ogc:Literal></ogc:PropertyIsEqualTo>',
            'sortBy': 'SORT_PRIO+A,ID',
        }).then(function(features) {
            $.each(features, function(i, xml) {
                var type = 0;
                result += "<div class='drag list-group-item liProc' data-droptype=1 data-OPIS='" +
                    (xml["OPIS"] || "") + "' data-DESC='" +
                    (xml["DESC"] || "") + "' data-id=" +
                    (xml["ID"] || "") + " >";
                result += "<div class=textTable><span class=handle> # </span>";
                result += (xml["DESC"] || "")
                result += "</div><div class=detailsTable> [" + (xml["ID"] || "") + "]</div>";
                result += "<div class='glyphicon glyphicon-triangle-right' style=opacity:0.4;float:right;></div><div class=clearfix></div></div>";
            });
            $("#depth0").html(result);
            updateDropZones();

        });
    }

    $(document).on('click', '.liAdv', function() {
        $(this).find(".glyphicon").removeClass("glyphicon-triangle-right");
        $(this).find(".glyphicon").addClass("glyphicon-refresh");
        $(this).parents(".singleAdv").nextAll(".singleAdv").remove();
        $(this).parents(".singleAdv").find(".active").removeClass("active");
        $(this).addClass("active");
        var parent = this;
        var parent_id = $(this).data("id");
        var result = "";
        var depth = $(this).parents(".singleAdv").data("_depth") + 1;
        $("#advCon").css("width", depth * 290 + 290);
        $(this).parents(".singleAdv").after("<div class='singleAdv list-group' data-depth=" + depth + " id=depth" + depth + "></div>");
        var childs = true;
        //var link = BASE_URL + 'wfs-data.php/default_db/?SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&TYPENAME=p5_default_db:CRM_LISTA_ZASOBOW&SRSNAME=EPSG:3003&Filter=<ogc:Filter><ogc:PropertyIsEqualTo><ogc:PropertyName>PARENT_ID</ogc:PropertyName><ogc:Literal>' + parent_id + '</ogc:Literal></ogc:PropertyIsEqualTo></ogc:Filter>&sortBy=SORT_PRIO+A,ID';
        p5WFS_GetFeature('p5_default_db:CRM_LISTA_ZASOBOW', {
            'Filter': '<ogc:PropertyIsEqualTo><ogc:PropertyName>PARENT_ID</ogc:PropertyName><ogc:Literal>' + parent_id + '</ogc:Literal></ogc:PropertyIsEqualTo>',
            'sortBy': 'SORT_PRIO+A,ID',
        }).then(function(features) {
            $.each(features, function(i, xml) {
                if (xml["ID"] == 0) {
                    childs = false;
                    return;
                }
                var type = 0;
                if (xml["TYPE"] == "DZIAL" || xml["TYPE"] == "PODMIOT" || xml["TYPE"] == "STANOWISKO")
                    type = 1;
                result += "<div class='list-group-item drag liAdv' data-typename='" +
                    xml["TYPE"] + "' data-id=" +
                    xml["ID"] + " data-type=" + type + " data-DESC='" +
                    xml["DESC"] + "' data-OPIS='" +
                    xml["OPIS"] + "'  title='" +
                    xml["DESC"] + "'><div class=textTable2><span class=handle> # </span>" +
                    xml["DESC"] + "</div>";
                result += "<div class='glyphicon glyphicon-triangle-right' style=opacity:0.4;float:right;></div>";
                result += "<div class=clearfix></div><div class=detailsTable2>[" + xml["ID"] + "] " + xml["TYPE"] + "</div></div>";
            });
            if (!childs) {
                result += '<div class="panel panel-primary">';
                result += '<div class="panel-heading"><h3 class="panel-title">[' + $(parent).data('ID') + '] ' + $(parent).data("DESC") + '</h3></div>';
                result += '<div class="panel-body pbody">';
                result += '<b>Opis: </b>' + $(parent).data("OPIS");
                result += '<br><b>Typ: </b>' + $(parent).data("typename");
                result += '</div>';
                result += '</div>'
            }
            $("#depth" + depth).html(result);
            updateDropZones();
            $(parent).find(".glyphicon").addClass("glyphicon-triangle-right");
            $(parent).find(".glyphicon").removeClass("glyphicon-refresh");
            $("#ulcon").scrollLeft(depth * 290 + 290);
            $("#ulcon").scrollTop(0);
        });


    });

    function getImg(el) {
        var name = el.files[0].name;
        var size = el.files[0].size;
        var type = el.files[0].type;
        var link = BASE_URL + "wfs-data.php/default_db/?SERVICE=WFS&VERSION=1.0.0&SRSNAME=EPSG:3003";
        var FR = new FileReader();
        FR.onload = function(e) {
            var content = e.target.result;
            var image = new Image();
            image.src = content;
            image.onload = function() {
                var width = el.width;
                var height = el.height;
                var xml =
                    `
                  <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_WFS_URL + `/default_db"
                    xmlns:gml="http://www.opengis.net/gml">

                    <Insert xmlns="http://www.opengis.net/wfs">
                    <CRM_IMAGE xmlns="` + BASE_WFS_URL + `/default_db">
                        <NAME xmlns="` + BASE_WFS_URL + `/default_db">` + name + `</NAME>
                        <IMAGE xmlns="` + BASE_WFS_URL + `/default_db">` + content + `</IMAGE>
                        <TYPE xmlns="` + BASE_WFS_URL + `/default_db">` + type + `</TYPE>
                        <SIZE xmlns="` + BASE_WFS_URL + `/default_db">` + size + `</SIZE>
                        <WIDTH xmlns="` + BASE_WFS_URL + `/default_db">` + width + `</WIDTH>
                        <HEIGHT xmlns="` + BASE_WFS_URL + `/default_db">` + height + `</HEIGHT>
                        <REMOTE_TABLE xmlns="` + BASE_WFS_URL + `/default_db">ADMIN_USERS</REMOTE_TABLE>
                        <REMOTE_ID xmlns="` + BASE_WFS_URL + `/default_db">` + USER_ID + `</REMOTE_ID>
                    </CRM_IMAGE>
                    </Insert>
                  </Transaction>`;
                $.ajax({
                    url: link,
                    data: xml,
                    type: 'POST',
                    contentType: "text/xml",
                    dataType: "xml",
                    success: function(data) {
                        if ($(data).find("ServiceException").text() != "") {
                            $.notify($(data).find("ServiceException").text(), "error");
                        } else {
                            photos();
                        }
                    }
                });
            }
        };
        FR.readAsDataURL(el.files[0]);


    }


    function humanFileSize(bytes) {
        var thresh = 1024;
        if (Math.abs(bytes) < thresh) {
            return bytes + ' B';
        }
        var units = ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
        var u = -1;
        do {
            bytes /= thresh;
            ++u;
        } while (Math.abs(bytes) >= thresh && u < units.length - 1);
        return bytes.toFixed(1) + ' ' + units[u];
    }

    function uploadForm() {
        var form = '<input id="fileupload" type="file" name="files[]" data-url="index.php?_route=UrlAction_procesEditor&_task=uploadVideo" multiple>' +
            "<div id='upload_info'></div>" +
            "<button style=width:100%; type='button' class='btn btn-default' id=upload_button>Umieść na serwerze</button>"


        return form;
    }


    function photos() {
        var side = $("#side");
        $(side).empty();

        $(side).append(uploadForm());

        $('#upload_progress').css(
            'opacity',
            0
        );

        $('#fileupload').fileupload({
            dataType: 'html',
            add: function(e, data) {
                $("#upload_button").off('click').on('click', function() {
                    data.submit();
                });
                var html = '<span class=upload_status></span>'
                html += '<div class="progress" id=upload_progress>' +
                    '<div class="progress-bar"  role="progressbar" aria-valuenow="0"' +
                    'aria-valuemin="0" aria-valuemax="100" style="width:0%">' +
                    '<span>70%</span>' +
                    '</div>' +
                    '</div>'

                $("#upload_info").html(html);

            },
            done: function(e, data) {
                $('#upload_progress').css(
                    'opacity',
                    0
                );
                //console.log("result")
                //console.log(data);
                //console.log(e)
                loadClipboard();
            },
            progressall: function(e, data) {
                var progress = parseInt(data.loaded / data.total * 100, 10);
                $('#upload_progress').find(".progress-bar").css(
                    'width',
                    progress + '%'
                );
                var remaining = Math.ceil((data.total - data.loaded) * 8 / data.bitrate);
                $('#upload_progress').find(".progress-bar").find("span").text(progress + '%');
                var total = humanFileSize(data.total);
                var bitrate = humanFileSize(data.bitrate / 10)
                var loaded = humanFileSize(data.loaded);
                $('#upload_info').find(".upload_status").text(loaded + "/" + total + " - pozostało " + remaining + " sekund [" + bitrate + "/s]");
            }
        });
        var schowek = '<div class="list-group" id=clipboard>';
        schowek += '</div>';
        $(side).append(schowek);
        loadClipboard();

    }

    function showVideo(data) {
        var el = ""


        return el;
    }


    function showMediaElement(data, type, args) {
        args = args || {}
        width = args.width || "165px"
        height = args.height || "165px"
        classes = args.classes || "";

        if (type == "video") {
            start = args.start || true
            end = args.end || true
        }
        var el = ""
        if (!data) return '';

        if ('video' === type && undefined === data['VIDEO_ID']) return '';

        if ('_IMG' === type && undefined === data['IMAGE']) return '';
        //console.log("ps")
        //console.log(data)
        //console.log("data")
        //console.log(type)

        if (type == "video") {

            //el += "<div class=attVid><div class=remImg>X</div>"
            el += "<div class='attVid " + classes + "' style='width:" + width + ";height:" + height + ";'><div class=imgTitle><i class='glyphicon glyphicon-option-vertical dragIcon'></i>"
            el += data["NAME"]
            el += "</div>"
            el += "<div  class='p5VideoPlayer'  id=p1 "
            el += "data-start='" + start + "' data-end='" + end + "' "
            el += "data-videoid=" + data["VIDEO_ID"] + ">"
            el += "<div class=img>"
            el += "<img src='" + "data:" + (data["THUMBNAIL"]["IMAGE"]) + "' / >"
            el += "</div>"
            el += "</div>"
            el += "</div>"
        } else if (type == "_IMG") {

            el += "<div class='attImg " + classes + "' style='width:" + width + ";height:" + height + ";' data-id=" + data["ID"] + ">"
            el += "<div class=imgTitle><i class='remImg glyphicon glyphicon-remove'></i>"
            el += "<i class='glyphicon glyphicon-option-vertical dragIcon'></i>"
            el += data["NAME"] + "</div><div class='img'>"
            el += "<img src='" + data["IMAGE"] + "' / >"
            el += "</div></div>"

        }
        return el;
    }

    function updateDropZones() {
        $('.attImg:not(.no-draggable),.attVid:not(.no-draggable)').draggable({
            appendTo: 'body',
            //revert: true,
            zIndex: 100,
            helper: "clone",
            stack: "div",
            distance: 0,

            handle: '.imgTitle',
            scroll: true,
            start: function(event, ui) {
                $(this).data("startingScrollTop", $(this).parent().scrollTop());
                $(".imageDropper").addClass("imagesDrop")
            },
            drag: function(event, ui) {
                var st = parseInt($(this).data("startingScrollTop"));
                ui.position.top -= $(document).scrollTop() - st;
                ui.helper.css('z-index', 1000);
            },
            stop: function(event, ui) {
                $(".imageDropper").removeClass("imagesDrop")

            }


        });

        $('.drag').draggable({
            appendTo: 'body',
            helper: 'clone',
            stack: "div",
            distance: 0,
            cursor: "copy",
            scroll: true,
            start: function(event, ui) {
                $(this).data("startingScrollTop", $(this).parent().scrollTop());
            },
            drag: function(event, ui) {
                var st = parseInt($(this).data("startingScrollTop"));
                ui.position.top -= $(document).scrollTop() - st;
                ui.helper.css('z-index', 1000);
            }
        });
        $(".drop").droppable({
            tolerance: 'pointer',
            accept: '.drag',
            zIndex: 0,
            hoverClass: "activeDrop",
            drop: function(event, ui) {
                if (ui.draggable.data("droptype") == 1)
                    addProces(ui, this);
                else
                    addResource(ui, this);
            }
        });
        $(".imageDropper").droppable({
            tolerance: 'pointer',
            accept: '.attImg, .attVid',
            zIndex: 0,
            hoverClass: "activeDrop",
            drop: function(event, ui) {
                if ($(ui.draggable).hasClass("attVid"))
                    dropVid(ui, this);
                else if ($(ui.draggable).hasClass("attImg"))
                    dropImg(ui, this);
            }
        });

    }



    function loadClipboard() {
        $("#clipboard").empty();
        //var link = BASE_URL + 'wfs-data.php/default_db/?SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&TYPENAME=p5_default_db:CRM_IMAGE&SRSNAME=EPSG:3003&Filter=<ogc:Filter></ogc:Filter>';
        p5WFS_GetFeature('p5_default_db:CRM_IMAGE', {
			// TODO: propertyName - tylko ID i TYPE, a obrazek wyświtlać jako src: wfs-data.php?SERVICE=WFS&VERSION=1.0.0&REQUEST=GetBlob&namespace=default_db/CRM_IMAGE&primaryKey={ID}&fieldName=IMAGE
            'Filter': '<ogc:And><ogc:PropertyIsEqualTo><ogc:PropertyName>REMOTE_ID</ogc:PropertyName><ogc:Literal>' + USER_ID + '</ogc:Literal></ogc:PropertyIsEqualTo><ogc:PropertyIsEqualTo><ogc:PropertyName>REMOTE_TABLE</ogc:PropertyName><ogc:Literal>ADMIN_USERS</ogc:Literal></ogc:PropertyIsEqualTo></ogc:And>',
            //'sortBy': 'SORT_PRIO+A,ID',
            //'maxFeatures': 100,
        }).then(function(features) {
            var list = "";

            //console.log(features)
            $.each(features, function(i, xml) {
                if (typeof usedImg[xml["ID"]] == "undefined") {
                    var opts = {};
                    opts["ID"] = xml["ID"];
                    opts["IMAGE"] = xml["IMAGE"];
                    opts["NAME"] = xml["NAME"];
                    list += showMediaElement(opts, "_IMG", {
                        classes: "noRemove"
                    });
                }
            });
            $("#clipboard").append(list);
            updateDropZones();

        }).catch(function(e) {
            console.log('Error', e)
        })
        link = BASE_URL + "index.php?_route=UrlAction_ProcesEditor&_task=getVideosClipboardAjax"
        // $.get(link, function(data) {
        //     var list = "";
        //     $.each(data, function(i, e) {
        //         list += showMediaElement(e, "video");
        //         //console.log("el")
        //         //console.log(showMediaElement(e, "video"))
        //     })
        //     //console.log(list);
        //     $("#clipboard").prepend(list);
        //     updateDropZones();
        //
        // });
    }

    function secondsToTime(sec_num) {
        var hours = Math.floor(sec_num / 3600);
        var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
        var seconds = sec_num - (hours * 3600) - (minutes * 60);

        if (hours < 10) {
            hours = "0" + hours;
        }
        if (minutes < 10) {
            minutes = "0" + minutes;
        }
        if (seconds < 10) {
            seconds = "0" + seconds;
        }
        return hours + ':' + minutes + ':' + seconds;
    }


    function zasoby() {
        var side = $("#side");
        $(side).empty();
        $(side).append("<div class='form-group' ><input type='text' class=form-control id=sZasoby placeholder='Szukaj zasobów'></div>");
        $(side).append("<div class='btn-group' style=width:100% id=filtry></div>");
        $("#filtry").append("<button type='button' data-type=1 class='fbutton btn btn-default input-block-level ' style=width:40%>Stanowiska</button>");
        $("#filtry").append("<button type='button' data-type=2 class='fbutton btn btn-default input-block-level ' style=width:40%>Komórki</button>");
        $("#filtry").append("<button type='button' data-type=0 class='fbutton btn btn-danger input-block-level' id=xBtn  style=width:20% disabled>X</button>");
        $(side).append("<div id=ulcon><div id=advCon></div></div>");
        $(side).find("#advCon").append("<div class='singleAdv list-group' data-depth=0 id=depth0></div>");
        $(side).find("#advCon").append("<div class=clearfix></div>");
        //var link = BASE_URL + 'wfs-data.php/default_db/?SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&TYPENAME=p5_default_db:CRM_LISTA_ZASOBOW&SRSNAME=EPSG:3003&Filter=<ogc:Filter></ogc:Filter>&sortBy=SORT_PRIO+A,ID';
        p5WFS_GetFeature('p5_default_db:CRM_LISTA_ZASOBOW', {
            'Filter': '<ogc:PropertyIsEqualTo><ogc:PropertyName>PARENT_ID</ogc:PropertyName><ogc:Literal>0</ogc:Literal></ogc:PropertyIsEqualTo>',
            'sortBy': 'SORT_PRIO+A,ID',
        }).then(function(features) {

            var result = "";

            $.each(features, function(i, xml) {
                var type = 0;
                if (xml["TYPE"] == "DZIAL" || xml["TYPE"] == "PODMIOT" || xml["TYPE"] == "STANOWISKO")
                    type = 1;
                result += "<div class='drag list-group-item liAdv'";
                result += "data-typename='" + xml["TYPE"] + "' data-id=" +
                    xml["ID"] + " data-type=" +
                    type + " data-DESC='" +
                    (xml["DESC"] || "") + "' data-OPIS='" +
                    (xml["OPIS"] || "") + "'"
                result += "title='" +
                    (xml["DESC"] || "") + "'>"
                result += "<div class=textTable2>"
                result += "<span class=handle> # </span>" +
                    (xml["DESC"] || "") + "</div>"
                result += "<div class='glyphicon glyphicon-triangle-right' style=opacity:0.4;float:right; style=float:left;></div>"
                result += "<div class=clearfix></div>"
                result += "<div class=detailsTable2>[" +
                    (xml["ID"] || "") + "] " +
                    (xml["TYPE"] || "") + "</div>"
                result += "</div>";
            });
            $("#depth0").html(result);
            updateDropZones();
        }).catch(function(e) {
            console.log('Error', e)
        })

    }

    function removeImg(content, id) {
        $.each(content, function(i, e) {
            if (e["ID"] == id) {
                content.splice(i, 1);
                return;
            }
        })
    }



    $(document).on('focus click', '#startInput, #endInput', function() {
        focusedInput = this;
        $("#startInputCheckbox, #endInputCheckbox").hide();
        $(this).closest(".form-group").find("#startInputCheckbox, #endInputCheckbox").show()
        $("#startInput, #endInput").removeClass("focused");
        $(this).addClass("focused")
        return false;

    });

    $(document).on("click", "#videoEditorModal .attVid", function() {
        return false;
    })

    $(document).on("click", "#videoEditorModal", function() {
        focusedInput = false;
        $("#startInput, #endInput").removeClass("focused");
    })

    $(document).on("click", "#startInputCheckbox, #endInputCheckbox", function() {
        focusedInput = $(this).closest(".form-group").find("#startInput, #endInput");
        $("#startInputCheckbox, #endInputCheckbox").hide();
        $(this).show()
        $("#startInput, #endInput").removeClass("focused");
        $(this).closest(".form-group").find("#startInput, #endInput").addClass("focused")
        e.stopPropagation();
    })


    $(document).on("click", ".form-group", function() {
        focusedInput = $(this).find("#startInput, #endInput");
        $("#startInputCheckbox, #endInputCheckbox").hide();
        $(this).find("#startInputCheckbox, #endInputCheckbox").show()
        $("#startInput, #endInput").removeClass("focused");
        $(this).find("#startInput, #endInput").addClass("focused")
        return false;
    })

    $(document).on("videoProgress", "#videoEditorModal .p5VideoPlayer", function() {
        //console.log($(focusedInput).closest(".form-group").find("#startInputCheckbox, #endInputCheckbox").is(':checked'));
        if ($(focusedInput).closest(".form-group").find("#startInputCheckbox, #endInputCheckbox").is(':checked')) {
            var time = Math.floor($(this).find('.p5VideoPlayer_vid')[0].currentTime);
            var parsedTime = secondsToTime(time);
            $(focusedInput).val(parsedTime);
            $(focusedInput).trigger("valueUpdated");
        }


    })


    $(document).on("keyup valueUpdated", "#startInput, #endInput", function() {
        var val = $(this).val()
        var patternIsTime = /^([0-9][0-9]*):([0-5][0-9]):([0-5][0-9])$/
        var patternIsInt = /^([0-9]*)$/
        //var patternIsIntOrTime = /^(([0-9]*)|([0-9][0-9]*):([0-5][0-9]):([0-5][0-9]))$/

        //sprawdza czy format HH:MM:SS i zamienia na int
        if (patternIsTime.test(val)) {
            var a = val.split(':');
            val = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
        }

        if (!val) val = 0;

        //Sprawdza poprawność czasu
        if (patternIsInt.test(val)) {
            $(this).removeClass("incorrect");
            if ($(this).is("#startInput")) {
                startInputVal = val;
            } else if ($(this).is("#endInput")) {
                endInputVal = val;
            }
        } else {
            $(this).addClass("incorrect");
        }
        //console.log("startInputVal: ", startInputVal)
        //console.log("endInputVal: ", endInputVal)


    })

    $(document).on("click", "#cutAndSave", function() {
        var id = $(targetVid).closest(".drop").data("id");
        var proces = id;
        var idBefore = $(elementVid).closest(".drop").data("id");
        var procesBefore = idBefore;
        var type = "CRM_PROCES";
        var typeName = "proces";
        var typeNameBefore = "proces";
        if ($(targetVid).closest(".professions").length) {
            id = $(targetVid).closest("li").data("id");
            type = "CRM_WSKAZNIK";
            typeName = "_prof";
        } else if ($(targetVid).closest(".resources").length) {
            id = $(targetVid).closest("li").data("id");

            typeNameBefore = "_res";
            type = "CRM_WSKAZNIK";
            typeName = "_res";
        }
        if ($(elementVid).closest(".professions").length) {
            typeNameBefore = "_prof";
            idBefore = $(elementVid).closest("li").data("id");
        } else if ($(elementVid).closest(".resources").length) {
            typeNameBefore = "_res";
            idBefore = $(elementVid).closest("li").data("id");
        }

        var temp = {};
        temp["THUMBNAIL"] = {};
        temp["THUMBNAIL"]["IMAGE"] = $(elementVid).find("img").attr("src");
        temp["NAME"] = $(elementVid).find(".imgTitle").text();
        temp["START"] = startInputVal
        temp["END"] = endInputVal
        temp["VIDEO_ID"] = $(elementVid).find(".p5VideoPlayer").data("videoid");
        tempUsed = {
            video_id: temp["VIDEO_ID"],
            type: type,
            targetID: id,
            action: "CLONE",
            start: temp["start"],
            end: temp["end"]
        };
        usedVid.push(tempUsed);

        if (typeName != "proces" && typeof state[getIndexById(proces)][typeName][
                [getResById(getIndexById(proces), $(targetVid).closest("li").data("id"), typeName)]
            ]["vid"] == "undefined") {
            state[getIndexById(proces)][typeName][getResById(getIndexById(proces), $(targetVid).closest("li").data("id"), typeName)]["vid"] = Array();
        } else if (typeName == "proces" && typeof state[getIndexById(id)]["_IMG"] == "undefined") {
            state[getIndexById(proces)]["vid"] = Array();
        }
        if (typeof idBefore != "undefined")
            if (typeNameBefore == "proces") {

                removeImg(state[getIndexById(procesBefore)]["vid"], temp["ID"]);
            } else {
                removeImg(state[getIndexById(procesBefore)][typeNameBefore][getResById(getIndexById(procesBefore), $(elementVid).closest("li").data("id"), typeNameBefore)]["_IMG"], temp["ID"]);
            }

        if (typeName == "proces") {
            state[getIndexById(id)]["vid"].push(temp);
        } else {
            state[getIndexById(proces)][typeName][getResById(getIndexById(proces), $(targetVid).closest("li").data("id"), typeName)]["_IMG"].push(temp);
        }
        $(elementVid).remove();
        hideModal($(this).closest(".p5BModalModal"));
        updateAll();
        //console.log(usedVid)
    })




    function videoEditor(wind, args) {
        //console.log(args)
        var ui = args.ui
        var target = args.target
        var temp = {};
        temp["THUMBNAIL"] = {};
        temp["THUMBNAIL"]["IMAGE"] = $(ui.draggable).find("img").attr("src");
        temp["NAME"] = $(ui.draggable).find(".imgTitle").text();
        temp["VIDEO_ID"] = $(ui.draggable).find(".p5VideoPlayer").data("videoid");
        //console.log("temp")
        //console.log(temp);
        var el = "<div class=container-fluid id='videoEditorModal'>" +
            "<div class=row>" +
            "<div class='col-sm-7'>" +
            showMediaElement(temp, "video", {
                width: "100%",
                height: "300px",
                classes: "no-draggable"
            }) +
            "</div>" +
            "<div class='col-sm-5'>"

            +
            "<h3>Przycinanie</h3>" +
            "<br />" +
            "<div class='form-group'>" +
            "<label for='startInput'>Czas rozpoczęcia: </label><input type='checkbox'  id='startInputCheckbox' style=display:none; checked />" +
            '<div class="input-group">' +
            '<input type="text" class="form-control" id="startInput">' +
            '<span class="input-group-addon" id="basic-addon2"><i class="glyphicon glyphicon-time"></i></span>' +
            '</div>' +
            '</div>' +
            "<div class='form-group'>" +
            "<label for='endInput'>Czas końca: </label><input type='checkbox' id='endInputCheckbox' style=display:none; checked />" +
            '<div class="input-group">' +
            '<input type="text" class="form-control" id="endInput">' +
            '<span class="input-group-addon" id="basic-addon2"><i class="glyphicon glyphicon-time"></i></span>' +
            '</div>' +
            "</div>" +
            '<button type="button" style=width:100%; class="btn btn-primary" id="cutAndSave">Przytnij i dodaj</button>'

            +
            "</div>" +
            "</div>" +
            "</div>"
        $(wind).html(el)
        p5VideoPlayer_init($(wind).find(".p5VideoPlayer").find(".img"))

    }

    function dropVid(ui, target) {
        elementVid = ui.draggable
        targetVid = target
        p5BModalDisplay("Edytor video", videoEditor, {
            "ui": ui,
            "target": target
        })
    }

    function getDomLocalization(e) {
        //console.log("getDomLocalization(e)")
        var obj = {}
        obj.type = null;
        obj.typeName = null;
        if ($(e).closest(".drop").length != 0) {
            obj.idProces = $(e).closest(".drop").data("id");
            obj.type = "CRM_PROCES";
            obj.procesObj = state[getIndexById(obj.idProces)];
        }
        if ($(e).closest(".professions").length) {
            obj.id = $(e).closest("li").data("id");
            obj.type = "CRM_WSKAZNIK";
            obj.typeName = "_prof";
            obj.wskObj = obj.procesObj[obj.typeName][getIndexById(obj.id, obj.procesObj[obj.typeName])]
        } else if ($(e).closest(".resources").length) {
            obj.id = $(e).closest("li").data("id");
            obj.type = "CRM_WSKAZNIK";
            obj.typeName = "_res";
            obj.wskObj = obj.procesObj[obj.typeName][getIndexById(obj.id, obj.procesObj[obj.typeName])]
        }
        //console.log(obj)
        return obj;
    }

    function dropImg(ui, target) {

        var targetInfo = getDomLocalization(target)
        var objInfo = getDomLocalization(ui.draggable)
        //console.log("dropImg()")
        //console.log(targetInfo)
        //console.log(objInfo)
        var temp = {};

        temp["src"] = $(ui.draggable).find("img").attr("src");
        temp["title"] = $(ui.draggable).find(".imgTitle").text();
        temp["ID"] = $(ui.draggable).data("id");
        var id;
        if (targetInfo.type == "CRM_PROCES") {
            if (!targetInfo.procesObj._IMG) targetInfo.procesObj._IMG = [];
            targetInfo.procesObj._IMG.push(temp);
            id = targetInfo.idProces;
        } else if (targetInfo.type == "CRM_WSKAZNIK") {
            if (!targetInfo.wskObj._IMG) targetInfo.wskObj._IMG = [];
            targetInfo.wskObj._IMG.push(temp);
            id = targetInfo.id;
        }
        usedImg[temp["ID"]] = {
            type: targetInfo.type,
            targetID: id,
            action: "ATTACH"
        };


        $(ui.draggable).remove();
        updateAll();
    }

    function addProces(ui, target) {
        var id = $(target).data("id");
        var gotoOpt = "";
        $.each(gotoType, function(key, value) {
            gotoOpt += "<option value=" + value[0] + ">" + value[1] + "</option>";
        })
        swal({
            showCancelButton: true,
            cancelButtonText: "Anuluj",
            title: 'Typ łącza',
            html: (
                state[getIndexById(id)]["IF_TRUE_GOTO"] != false ?
                '<span class=class="alert alert-warning"><strong>Uwaga!</strong> Nowe łącze nadpisze już istniejące łącze.</span><br>' :
                ""
            ) + '<br><select class=form-control id="swal-input1">' + gotoOpt + '</select>',
            preConfirm: function() {
                return new Promise(function(resolve) {
                    resolve([
                        $('#swal-input1').val()
                    ]);
                });
            }
        }).then(function(result) {
            newRes--;
            state[getIndexById(id)]["IF_TRUE_GOTO"] = ui.draggable.data("id");
            state[getIndexById(id)]["IF_TRUE_GOTO_FLAG"] = result[0];

            updateAll();
        }).catch(function(e) {})
    }

    function addResource(ui, target) {
        var permsOpt = "";
        $.each(perms, function(key, value) {
            permsOpt = permsOpt + "<option value=" + value[0] + ">[" + value[2] + "] " + value[1] + "</option>";
        })
        swal({
            showCancelButton: true,
            cancelButtonText: "Anuluj",
            title: 'Uprawnienia',
            html: 'Uprawnienia<br><select class=form-control id="swal-input1">' + permsOpt + '</select>' +
                'Komentarz<br><input class=form-control id="swal-input2" class="swal2-input">',
            preConfirm: function() {
                return new Promise(function(resolve) {
                    resolve([
                        $('#swal-input1').val(),
                        $('#swal-input2').val()
                    ]);
                });
            }
        }).then(function(result) {
            newRes--;
            var temp = {};
            temp["ID_ZASOB"] = ui.draggable.data("id");
            temp["ID"] = newRes;
            temp["ID_PRZYPADEK"] = result[0];
            temp["OPIS_ZASOB"] = result[1];
            temp["changed"] = true;
            temp["OPIS"] = ui.draggable.data("opis");
            temp["DESC"] = ui.draggable.data("desc");

            temp["_TREE"] = zasobTree[temp["ID_ZASOB"]];
            var id = $(target).data("id");
            if (ui.draggable.data("type") == 1) {
                state[getIndexById(id)]["_prof"].push(temp);
            } else {
                state[getIndexById(id)]["_res"].push(temp);
            }
            updateAll();
        }).catch(function(e) {})
    }

    //Najwazniejsza funkcja odpalana po kazdej zmianie. Sprawdza, czy wszystkie funkcje maja rodzica,
    //jezeli nie to przesuwa w lewo obiekt
    //Odpowiada tez za ukrywanie guzikow i wywowalanie funkcji generacji krokow
    function updateAll() {
        $.each(state, function(i, e) {
            var pid = getParentNode(e["ID"]);
            if (pid != "NONE" && pid != false && pid != e["PARENT_ID"]) {
                e["PARENT_ID"] = pid;
            } else if (pid === false) {
                e["_depth"]--;
                updateAll();
                return;
            }
        });
        changes = true;
        $("#clearBtn").show();
        /*
        localStorage.setItem("state" + mainProces_id, JSON.stringify(state));
        localStorage.setItem("newStep" + mainProces_id, newSteps);
        localStorage.setItem("newRes" + mainProces_id, newRes);
        localStorage.setItem("deletedId" + mainProces_id, JSON.stringify(deletedId));
        localStorage.setItem("deletedRes" + mainProces_id, JSON.stringify(deletedRes));
        localStorage.setItem("date" + mainProces_id, moment().format("YYYY-MM-DD HH:mm:ss"));
        */
        render(state, $("#main"));
    }

    //Generuje kroki, sprawdza tez czy kolejnosc krokow w danym rodzicow zostala zmieniona
    //Jezeli tak to mozna wyslac ajaxem zmiane kolejnosci dla sort_prio
    function stepsGenerator() {
        $.each(state, function(i, e) {
            e["_step"] = 0;
            if (i == 0)
                e["_stepDesc"] = "";
            else {
                var iParent = getIndexById(e["PARENT_ID"]);
                state[iParent]["_step"] += 1;
                e["SORT_PRIO"] = state[iParent]["_step"];
                e["_stepDesc"] = state[iParent]["_stepDesc"] + state[iParent]["_step"] + ". ";
            }
        });
    }

    //Na potrzeby guzikow dorobilem funkcje sprawdzajaca id rodzica po przesunieciu (przewidywanie).
    //Jezeli nie znajdzie zwraca false, a wtedy blokuje sie odpowiednia strzalka
    function checkParentNode(id, check) {
        var x = getIndexById(id);
        var y = x;
        var result = false;
        while (x > 0) {
            x--;
            if (check == "right")
                if (state[x]["_depth"] == state[y]["_depth"]) {
                    result = state[x]["ID"];
                    break;
                }
            if (check == "left")
                if (state[x]["_depth"] == state[y]["_depth"] - 2) {
                    result = state[x]["ID"];
                    break;
                }

            if (check == "right" && state[x]["_depth"] < state[y]["_depth"])
                break;
        }
        return result;
    }

    //Zwraca id rodzica, jezeli nie ma zwraca false
    function getParentNode(id) {
        var x = getIndexById(id);
        var y = x;
        if (x == 0)
            return "NONE";
        var result = false;
        while (x > 0) {
            x--;
            if (state[x]["_depth"] == state[y]["_depth"] - 1) {
                result = state[x]["ID"];
                break;
            }
            if (state[x]["_depth"] - state[y]["_depth"] == -2)
                break;
        }
        return result;
    }

    function getResById(index, id, type) {
        var result = state[index][type].length - 1;
        $.each(state[index][type], function(i, e) {
            if (e["ID"] == id) {
                result = i;
                return false;
            }
        });
        return result;
    }

    function getIndexById(id, arr, label) {
        var arr = arr || state
        var label = label || "ID"
        var result = arr.length - 1;
        if (label == "ID")
            result = -1;
        $.each(arr, function(i, e) {
            if (e[label] == id) {
                result = i;
                return false;
            }
        });
        return result;
    }

    $(document).on('click', ".remImg", function() {
        //console.log(1);
        obj = getDomLocalization($(this));
        id = $(this).closest(".attImg").data('id');
        if (obj.type == "CRM_PROCES") {
            var index = getIndexById(id, obj.procesObj._IMG, "ID")
            obj.procesObj._IMG.splice(index, 1);

        } else if (obj.type == "CRM_WSKAZNIK") {
            var index = getIndexById(id, obj.wskObj._IMG, "ID")
            obj.wskObj._IMG.splice(index, 1);
        }
        usedImg[id] = {
            type: "",
            targetID: -1,
            action: "DELETED"
        };
        updateAll();
        return false;
    });

    $(document).on('click', '.stateOff', function() {
        $(this).closest(".mx").prev(".tree").show();
        $(this).closest(".mx").remove();
    });

    $(document).on('click', '.tree', function() {
        var type;
        if ($(this).closest("ul").hasClass("resources")) {
            type = "_res";
        } else {
            type = "_prof"
        }
        var id = getIndexById($(this).closest(".drop").data("id"));
        var resId = getResById(id, $(this).closest(".liRes").data("id"), type);
        $(this).hide();
        showTree(state[id][type][resId]["_TREE"], $(this));
    });

    function showTree(arr, target) {
        result = "";
        $.each(arr, function(i, x) {
            result += "<li style=padding-left:" + i * 16 + "px;><span class='glyphicon glyphicon-arrow-right'></span> " + x["DESC"] + "</li>";
        });
        $(target).after("<div class=mx><div class=stateOff><span class='glyphicon glyphicon-chevron-up'></span></div> <ul style=padding-left:0px;>" + result + "</ul></div>");
    }

    function render(arr, target) {
        //console.log("STATE")
        //console.log(arr)
        //console.log("USEDIMG")
        //console.log(usedImg)
        stepsGenerator();
        var result = "";
        $.each(arr, function(i, e) {
            result += "<div class='drop container-fluid' data-id=" + e["ID"] + " id='proc" + e["ID"] + "'>";
            result += "<div class='col-xs-1 options' style=text-align:right;padding-top:2px; id=opt" + e["ID"] + ">";
            if (i > 0) {
                result += "<span class='glyphicon glyphicon-remove-sign ico del' title='Usuń krok' aria-hidden='true'></span>";
                //Arrows
                if (checkParentNode(e["ID"], "right") !== false)
                    result += "<span class='glyphicon glyphicon-arrow-right ico rArrow' aria-hidden='true' title='Przesuń krok w prawo'></span>";
                if (checkParentNode(e["ID"], "left") !== false)
                    result += "<span class='glyphicon glyphicon-arrow-left ico lArrow' aria-hidden='true' title='Przesuń krok w lewo'></span>";
                if (i != 1)
                    result += "<span class='glyphicon glyphicon-arrow-up ico uArrow'  aria-hidden='true' title='Przesuń krok w górę'></span>";
                if (i != state.length - 1)
                    result += "<span class='glyphicon glyphicon-arrow-down ico dArrow' aria-hidden='true' title='Przesuń krok w dół'></span>";
            } else {}
            result += "<span class='hDescAdd glyphicon glyphicon-edit ico' title='Edytuj tytuł'></span>";
            result += "<div class='clearfix'></div>";
            if (e["OPIS"] == "")
                result += "<span class=sDescAdd>Dodaj opis</span>";
            else
                result += "<span class=sDescAdd>Edytuj opis</span>";
            result += "</div>";
            result += "<div class='col-xs-11 desc' id='desc" + e["ID"] + "' ><h4 class='changable " +
                (e["_C-desc"] ? "changed" : "") +
                "'><span class='stepDesc'>" +
                e["_stepDesc"] +
                "</span><span class=hdesc>" +
                e["DESC"] +
                "</span> <span class=ids>{" +
                (e["ID"] >= 0 ? e["ID"] : "?") +
                "}</span></h4><span  class='imageDropper sdesc changable " +
                (e["_C-opis"] ? "changed" : "") + "'>" +
                e["OPIS"] +
                "</span>";

            // }
            // if ($(this).find("OPIS").text() == "") {
            //     $("#proc" + $(this).find("ID").text()).find(".sdesc").after("<span class=sDescAdd>Dodaj opis</span>");
            // }
            result += "<div class='clearfix'></div><div class=imagesHolder>";

            if (typeof e["_IMG"] !== "undefined") {
                //console.log(e["_IMG"])
                $.each(e["_IMG"], function(key, eImg) {
                    var img = showMediaElement({
                        "ID": eImg["ID"],
                        "IMAGE": eImg["src"],
                        "NAME": eImg["title"],
                    }, "_IMG", {
                        classes: "no-draggable"
                    })
                    result += img;
                })
            }

            if (typeof e["vid"] !== "undefined") {
                //console.log(e["_IMG"])
                $.each(e["vid"], function(key, eVid) {
                    var vid = showMediaElement(eVid, "video", {
                        "start": eVid["START"],
                        "end": eVid["END"],
                        classes: "no-draggable"
                    })
                    result += vid;
                })
            }

            result += "<div class=clearfix></div></div><br>";
            var anyProf = false;
            $.each(e["_prof"], function(i2, e2) {
                if (!anyProf) {
                    result += "<div class=row><div class=col-sm-2 style=font-size:1.2em;text-align:right;opacity:1>Stanowiska</div></div><ul class=professions style=padding:0;>";
                    anyProf = true;
                }
                result += "<li style=padding-top:5px;padding-bottom:5px; class='liRes imageDropper' data-zasob=" + e2["ID_ZASOB"] + " data-id=" + e2["ID"] + " data-przypadek=" + e2["ID_PRZYPADEK"] + " data-komentarz='" + e2["OPIS_ZASOB"] + "'><div class=row>";
                result += "<div class=col-sm-2 style=text-align:right;>";
                if (i2 != 0)
                    result += "<span class='glyphicon glyphicon-arrow-up uArrowRes' title='Przesuń wskaźnik w górę' aria-hidden='true'></span>";
                if (i2 != e["_prof"].length - 1)
                    result += "<span class='glyphicon glyphicon-arrow-down dArrowRes' title='Przesuń wskaźnik w dół' aria-hidden='true'></span>";
                result += "<span aria-hidden='true' class='glyphicon glyphicon-edit btnEdit' title='Edytuj wskaźnik' style=font-size:12px;></span><span class='glyphicon glyphicon-remove-sign delRes' title='Usuń wskaźnik' style=font-size:12px; aria-hidden='true' ></span>";
                result += "</div>";
                result += "<div class='col-sm-10 changable " + (e2["changed"] ? "changed" : "") + " '><b>" + e2["DESC"] + "</b> " + e2["OPIS"] + " [" + e2["ID_ZASOB"] + "] <br><span class=tree>";

                if (typeof e2["_TREE"] !== "undefined" && e2["_TREE"].length > 0) { //TO DO DOWNLOAD TREE WHEN NOT EXISTS
                    result += "<span class=state><span class='glyphicon glyphicon-chevron-down'></span></span> ";
                    $.each(e2["_TREE"], function(i, x) {
                        result += x["DESC"] + (i < e2["_TREE"].length - 1 ? "<span class='glyphicon glyphicon-triangle-right'></span> " : "");
                    });
                }
                result += "</span>";
                result += "<div class=clearfix></div><div class=imagesHolder>";
                if (typeof e2["_IMG"] !== "undefined") {
                    //console.log(e["_IMG"])
                    $.each(e2["_IMG"], function(key, eImg) {
                        var img = showMediaElement({
                            "ID": eImg["ID"],
                            "IMAGE": eImg["src"],
                            "NAME": eImg["title"]
                        }, "_IMG", {
                            classes: "no-draggable"
                        })
                        result += img;
                    })
                }
                result += "<div class=clearfix></div></div></div>";
                result += "</div><div class=clearfix></div></li>";
            });
            if (anyProf) {
                result += "</ul>";
            }
            var anyRes = false;
            $.each(e["_res"], function(i2, e2) {

                if (!anyRes) {
                    result += "<div class=row><div class=col-sm-2 style=font-size:1.2em;text-align:right;opacity:1>Użyte zasoby</div></div><ul class=resources style=padding:0;>";
                    anyRes = true;
                }
                result += "<li style=padding-top:5px;padding-bottom:5px; class='liRes imageDropper' data-zasob=" + e2["ID_ZASOB"] + " data-id=" + e2["ID"] + " data-przypadek=" + e2["ID_PRZYPADEK"] + " data-komentarz='" + e2["OPIS_ZASOB"] + "'><div class=row>";
                result += "<div class=col-sm-2 style=text-align:right;>";
                if (i2 != 0)
                    result += "<span class='glyphicon glyphicon-arrow-up uArrowRes' title='Przesuń wskaźnik w górę' aria-hidden='true'></span>";
                if (i2 != e["_res"].length - 1)
                    result += "<span class='glyphicon glyphicon-arrow-down dArrowRes' title='Przesuń wskaźnik w dół' aria-hidden='true'></span>";
                result += "<span aria-hidden='true' class='glyphicon glyphicon-edit btnEdit' title='Edytuj wskaźnik' style=font-size:12px;></span><span class='glyphicon glyphicon-remove-sign delRes' title='Usuń wskaźnik' style=font-size:12px; aria-hidden='true' ></span>";
                result += "</div>";
                result += "<div class='col-sm-10 changable " + (e2["changed"] ? "changed" : "") + " '><b>" + e2["DESC"] + "</b> " + e2["OPIS"] + " [" + e2["ID_ZASOB"] + "] <br><span class=tree>";
                if (typeof e2["_TREE"] !== "undefined" && e2["_TREE"].length > 0) { //TO DO DOWNLOAD TREE WHEN NOT EXISTS
                    result += "<span class=state><span class='glyphicon glyphicon-chevron-down'></span></span> ";
                    $.each(e2["_TREE"], function(i, x) {
                        result += x["DESC"] + (i < e2["_TREE"].length - 1 ? "<span class='glyphicon glyphicon-triangle-right'></span> " : "");
                    });
                }
                result += "</span>";
                result += "<div class=clearfix></div><div class=imagesHolder>";
                if (typeof e2["_IMG"] !== "undefined") {
                    $.each(e2["_IMG"], function(key, eImg) {
                        var img = showMediaElement({
                            "ID": eImg["ID"],
                            "IMAGE": eImg["src"],
                            "NAME": eImg["title"]
                        }, "_IMG", {
                            classes: "no-draggable"
                        })
                        result += img;
                    })
                }
                result += "<div class=clearfix></div></div></div>";
                result += "</div></li>";
            });
            if (anyRes) {
                result += "</ul>";
            }
            if (e["IF_TRUE_GOTO"] != false) {
                var name;
                switch (e["IF_TRUE_GOTO_FLAG"]) {
                    case "GOTO":
                        name = "Przejdź do procesu " + e["IF_TRUE_GOTO"] + ".";
                        break;
                    case "GOTO_AND_RETURN":
                        name = "Przejdź do procesu " + e["IF_TRUE_GOTO"] + ", a następnie wróć.";
                        break;
                    case "FORK":
                        name = "&mdash; FORK" + e["IF_TRUE_GOTO"];
                        break;
                    default:
                        name = e["IF_TRUE_GOTO"];
                }
                result += "<span style=color:grey; class=goto>&mdash; " + name + "</span> <span class='glyphicon glyphicon-remove-sign delGoto' title='Usuń GOTO' style=font-size:12px; aria-hidden='true' ></span>";
            }
            result += "<br><span class=step>Dodaj nowy krok</span>";
            result += "</div>"
            result += "</div>";
        });
        $(target).html(result);


        updateDropZones()



    }

    function genTree(parent_id) {

        return p5WFS_GetFeature('p5_default_db:CRM_PROCES', {
            'Filter': '<ogc:PropertyIsEqualTo><ogc:PropertyName>' + "PARENT_ID" + '</ogc:PropertyName><ogc:Literal>' + parent_id + '</ogc:Literal></ogc:PropertyIsEqualTo>',
            'sortBy': 'SORT_PRIO+A,ID',
        }).then(function(features) {
            return Promise.all(
                features.map(function(feature, i) {
                    var parentIndex = getIndexById(parent_id);
                    var temp = {
                        ID: feature['ID'],
                        DESC: feature['DESC'] || '',
                        OPIS: feature['OPIS'] || '',
                        PARENT_ID: feature['PARENT_ID'] || 0,
                        _depth: state[parentIndex]["_depth"] + 1,
                        _step: 0,
                        _prof: new Array(),
                        _res: new Array(),
                        IF_TRUE_GOTO: feature['IF_TRUE_GOTO'] || 0,
                        IF_TRUE_GOTO_FLAG: feature['IF_TRUE_GOTO_FLAG'] || '',
                        _stepDesc: ""
                    };
                    state.splice(parentIndex + (i + 1), 0, temp);
                    return genTree(feature.ID);
                })
            );

        }).catch(function(e) {
            console.log('Error', e)
        })
    }

    function base64_decode(input) {
        var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = _keyStr.indexOf(input.charAt(i++));
            enc2 = _keyStr.indexOf(input.charAt(i++));
            enc3 = _keyStr.indexOf(input.charAt(i++));
            enc4 = _keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        }

        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while (i < output.length) {
            c = output.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            } else if ((c > 191) && (c < 224)) {
                c2 = output.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            } else {
                c2 = output.charCodeAt(i + 1);
                c3 = output.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }

    //Pierwszy render, tworzy potrzebna strukture
    function showPreview() {
        loadFromXml(true);
        newSteps = (mainProces_id == -1) ? -1 : 0
        changes = false;
        $("#clearBtn").hide();
        lastSearch = "";
        filtr = 0;
        selectedArea = false;
        state = [];
        newRes = 0;
        deletedId = [];
        deletedRes = [];
        generatedId = [];
        if (mainProces_id == -1) {
            temp = {}
            actSite = "preview";
            temp["ID"] = -1;
            temp["_depth"] = 0;
            temp["PARENT_ID"] = 0;
            temp["_stepDesc"] = "";
            temp["_step"] = 0;
            temp["_prof"] = Array();
            temp["_res"] = Array();
            temp["DESC"] = "Tytuł procesu";
            temp["OPIS"] = "Opis procesu";
            temp["_C-desc"] = true;
            temp["_C-opis"] = true;
            temp["IF_TRUE_GOTO"] = "";
            temp["IF_TRUE_GOTO_FLAG"] = 0;
            state[0] = temp;
            loadResources();
        } else if (localStorage.getItem("state" + mainProces_id) !== null) {
            state = JSON.parse(localStorage.getItem("state" + mainProces_id));
            newSteps = localStorage.getItem("newStep" + mainProces_id);
            newRes = localStorage.getItem("newRes" + mainProces_id);
            deletedId = JSON.parse(localStorage.getItem("deletedId" + mainProces_id));
            deletedRes = JSON.parse(localStorage.getItem("deletedRes" + mainProces_id));
            usedImg = JSON.parse(localStorage.getItem("usedImg" + mainProces_id));
            $.notify("Wczytano niezapisany stan z " + localStorage.getItem("date" + mainProces_id), "info");
            render(state, $("#main"));
        } else {
            $("#main").html("<center>Synchronizowanie danych z serwerem.</center>");
            render(state, $("#main"));
            var id = mainProces_id;
            p5WFS_GetFeature('p5_default_db:CRM_PROCES', {
                'featureID': 'CRM_PROCES.' + id,
            }).then(function(features) {
                if (!features) throw "Nie odnaleziono rekordu id = " + id
                if (!features.length) throw "Nie odnaleziono rekordu id = " + id
                if (1 !== features.length) throw "Bład: API zwróciło za dużo rekordów"
                return features[0]
                //console.log('fetched features', features)
            }).then(function(feature) {
                var temp = {};
                temp["ID"] = mainProces_id;
                temp["_depth"] = 0;
                temp["PARENT_ID"] = feature["PARENT_ID"] || ''
                temp["_step"] = 0;
                temp["IF_TRUE_GOTO"] = feature["IF_TRUE_GOTO"] || ''
                temp["IF_TRUE_GOTO_FLAG"] = feature["IF_TRUE_GOTO_FLAG"] || ''
                temp["_stepDesc"] = "";
                temp["_prof"] = Array();
                temp["_res"] = Array();
                temp["DESC"] = feature["DESC"] || ''
                temp["OPIS"] = feature["OPIS"] || ''

                state[0] = temp;
                genTree(mainProces_id).then(function() {
                    loadResources();
                });
            }).catch(function(e) {
                console.log('Error', e)
            })

            actSite = "preview";
        }
    }
});

function unloadPage() {
    if (changes)
        return "";
}

window.onbeforeunload = unloadPage;
