<?php

//version 2010-06-01 - addding limits and searches
//version 2010-06-13 - by plabudda login by AUTH MODULE (.config.php $AUTH_API)
//version 2010-09-22 - by abinder, drobne poprawki z wyszukiwaniem i pokazywaniem tabeli
//version 2010-09-30 - by abinder, drobne poprawki z wyszukiwanie w PROCESACH do edycji...
//version 2011-09-12 - by pl, TODO: Obowiazki - menu

require_once dirname(__FILE__) . '/se-lib/bootstrap.php';

if (!Request::isHttps()) {
	header("Location: https://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}");
	exit();
}

error_reporting(E_ALL & ~E_NOTICE);

//session_save_path("../session") ;
session_start();

date_default_timezone_set('Europe/Warsaw');// PHP 5 >= 5.1.0 required by date functions

if (file_exists(".config.php")) include(".config.php");

SEF('DEBUG_S');
SEF('ZAP_SQL');
SEF('ZAP_SQL_UPDATE');
SEF('USERS_COLUMN_INIT');
SEF('GETFORMITEM');
SEF('T_WORKPOINTS_USER_SELECT');

Lib::loadClass('App');
Lib::loadClass('ProcesHelper');
Lib::loadClass('Tree');
Lib::loadClass('TreeHelper');
Lib::loadClass('DB_Image');
Lib::loadClass('TreeSortChildren');
Lib::loadClass('UI');

//   ==========  Task functions  ==============
require_once APP_PATH_ROOT . DS . 'procesy' . DS . 'legacy.php';
require_once APP_PATH_ROOT . DS . 'procesy' . DS . 'proces.php';
require_once APP_PATH_ROOT . DS . 'procesy' . DS . 'zasob.php';
require_once APP_PATH_ROOT . DS . 'procesy' . DS . 'testy.php';// CRM_TESTY_WYNIKI
require_once APP_PATH_ROOT . DS . 'procesy' . DS . 'proces_log.php';
require_once APP_PATH_ROOT . DS . 'procesy' . DS . 'user.php';
require_once APP_PATH_ROOT . DS . 'procesy' . DS . 'ext_ids.php';
require_once APP_PATH_ROOT . DS . 'procesy' . DS . 'search.php';// CRM_SEARCH
// TODO: if (App::is_ajax_request())
require_once APP_PATH_ROOT . DS . 'procesy' . DS . 'ajax.php';


//   ==========  SESSION set default session values  ==============
S::init();

if (!isset($_SESSION['HIDE_ZASOBY'])) $_SESSION['HIDE_ZASOBY'] = true;
if (!isset($_SESSION['HIDE_PROCESY'])) $_SESSION['HIDE_PROCESY'] = true;
if (!isset($_SESSION['ZWIN_DRZEWO'])) $_SESSION['ZWIN_DRZEWO'] = false;
if (!isset($_SESSION['TREE_OPEN_ARRAY'])) $_SESSION['TREE_OPEN_ARRAY'] = array();
if (!isset($_SESSION['TREE_SHOW_P_ID2'])) $_SESSION['TREE_SHOW_P_ID2'] = false;
if (!isset($_SESSION['TREE_SHOW_P_ID3'])) $_SESSION['TREE_SHOW_P_ID3'] = false;
if (!isset($_SESSION['ROZWIN'])) $_SESSION['ROZWIN'] = false;
if (!isset($_SESSION['ROZWIN_OPIS'])) $_SESSION['ROZWIN_OPIS'] = false;
if (!isset($_SESSION['ROZWIN_ZASOBY'])) $_SESSION['ROZWIN_ZASOBY'] = false;

if (!isset($_SESSION['TREE-ZASOBY'])) $_SESSION['TREE-ZASOBY'] = array();
if (!isset($_SESSION['TREE-PROCESY'])) $_SESSION['TREE-PROCESY'] = array();
if (!isset($_SESSION['USER_PARAMS'])) $_SESSION['USER_PARAMS'] = array();

//   ==========  SESSION set values from request  ==============
if(isset($_GET['HIDE_ZASOBY'])   && $_GET['HIDE_ZASOBY'])   $_SESSION['HIDE_ZASOBY'] = true;
if(isset($_GET['UNHIDE_ZASOBY']) && $_GET['UNHIDE_ZASOBY']) $_SESSION['HIDE_ZASOBY'] = false;

if(isset($_GET['HIDE_PROCESY'])   && $_GET['HIDE_PROCESY'])   $_SESSION['HIDE_PROCESY'] = true;
if(isset($_GET['UNHIDE_PROCESY']) && $_GET['UNHIDE_PROCESY']) $_SESSION['HIDE_PROCESY'] = false;

if(isset($_GET['ZWIN_DRZEWO'])   && $_GET['ZWIN_DRZEWO'])   $_SESSION['ZWIN_DRZEWO'] = true;
if(isset($_GET['ROZWIN_DRZEWO']) && $_GET['ROZWIN_DRZEWO']) $_SESSION['ZWIN_DRZEWO'] = false;

if(isset($_GET['TREE_OPEN'])  && $_GET['TREE_OPEN'])  $_SESSION['TREE_OPEN_ARRAY'][$_GET['TREE_OPEN']] = true;
if(isset($_GET['TREE_CLOSE']) && $_GET['TREE_CLOSE']) $_SESSION['TREE_OPEN_ARRAY'][$_GET['TREE_CLOSE']] = false;

if(isset($_GET['TREE_SHOW_P_ID2']) && $_GET['TREE_SHOW_P_ID2']) $_SESSION['TREE_SHOW_P_ID2'] = true;
if(isset($_GET['TREE_HIDE_P_ID2']) && $_GET['TREE_HIDE_P_ID2']) $_SESSION['TREE_SHOW_P_ID2'] = false;
if(isset($_GET['TREE_SHOW_P_ID3']) && $_GET['TREE_SHOW_P_ID3']) $_SESSION['TREE_SHOW_P_ID3'] = true;
if(isset($_GET['TREE_HIDE_P_ID3']) && $_GET['TREE_HIDE_P_ID3']) $_SESSION['TREE_SHOW_P_ID3'] = false;

if(isset($_GET['TREE_ROZWIN']) && $_GET['TREE_ROZWIN']) $_SESSION['ROZWIN'] = true;
if(isset($_GET['TREE_ZWIN'])   && $_GET['TREE_ZWIN'])   $_SESSION['ROZWIN'] = false;

if(isset($_GET['TREE_OPISY_ROZWIN']) && $_GET['TREE_OPISY_ROZWIN']) $_SESSION['ROZWIN_OPIS'] = true;
if(isset($_GET['TREE_OPISY_ZWIN'])   && $_GET['TREE_OPISY_ZWIN'])   $_SESSION['ROZWIN_OPIS'] = false;

if(isset($_GET['TREE_ZASOBY_ROZWIN']) && $_GET['TREE_ZASOBY_ROZWIN']) $_SESSION['ROZWIN_ZASOBY'] = true;
if(isset($_GET['TREE_ZASOBY_ZWIN'])   && $_GET['TREE_ZASOBY_ZWIN'])   $_SESSION['ROZWIN_ZASOBY'] = false;

//   ==========  SESSION timeout  ==============

S::timeout_update();

//   ==========  App state  ==============

App::set_default_task('CRM_PROCES');

//   ==========  DB connection  ==============

//$conn = DB::connect();// TODO: needed?

//   ==========  App auth  ==============

User::auth();// die if not logged in

//   ==========  FUNCTION_INIT  ==============

// ?_ajax_request=FUNCTION
// TODO: if (App::is_ajax_request())
App::exec_ajax_request();


// ?function_init=FUNCTION
//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">';var_dump( headers_sent() );echo'</pre>';
App::exec_function_init();

// column init
Lib::loadClass('Column');
Column::init('CRM_PROCES');
Column::init('CRM_LISTA_ZASOBOW');
//Column::init('CRM_TESTY');


/**
 * Perm/access function.
 *
 * admin - kierownik, $_SESSION['ADM_ADMIN_LEVEL'] in (0,1)
 */
function User_is_admin() {
	return User::hasAccess('procesy_admin');
}

function User_procesy5_check_access() {
	if (!User::hasAccess('procesy')) {
		?>
		<div class="container">
			<div class="alert alert-danger">
				Brak dostępu!
			</div>
		</div>
		<br>.
		<?php
		lay_procesy_dol();
		die();
	}
}

function lay_procesy_gora() {

	$title = UI::getTitle().' procesy';
	if (($id_proces = V::get('id_proces', 0, $_GET, 'int')) > 0) {
		$title = "Proces {{$id_proces}}";
	}

	ob_start();
	App::show_head_css();
	App::show_head_js();
	$app_css_js = ob_get_clean();

	UI::gora([
		'title' => $title,
		'childrens' => implode("\n", [
			UI::h('style', [ 'type' => "text/css" ], 	"
				.popover-with-html .popover-heading {display:none;}
				.popover-with-html .popover-body {display:none;}
			"),
			'<script>
jQuery(document).ready(function(){
	jQuery(".popover-with-html").popover({
		html: true,
		trigger: "hover",
		animation: false,
		container: "body",
		placement: "top",
		content: function() {
			return jQuery(this).children(".popover-body").html();
		},
		title: function() {
			return jQuery(this).children(".popover-heading").html();
		}
	});
});
			</script>',
			$app_css_js,
			lay_procesy_css(),
		]),
	]);
	echo "\n";
}
if ('YES' != V::get('HEADER_NOT_INIT', '', $_REQUEST)) {
	lay_procesy_gora();
}

function ECHOO($VAR) {
	echo "$VAR";
}


//INICJALIZACJA_KOLUMN
if (!isset($_SESSION['CRM_LISTA_ZASOBOW_COLUMN'])) {
	$COLUMN="CRM_LISTA_ZASOBOW";
	$res = DB::query("show fields from $COLUMN");
	$KEY=0;
	while ($h = DB::fetch_row( $res )) {
		$_SESSION[$COLUMN."_COLUMN"]['DESC']["$KEY"] = $h[0];
		$_SESSION[$COLUMN."_COLUMN"]['TYPE'][$_SESSION[$COLUMN."_COLUMN"]['DESC']["$KEY"]] = $h[1];
		if(!isset($_SESSION[$COLUMN."_COLUMN"]['PERMEDIT'][$h[0]])) $_SESSION[$COLUMN."_COLUMN"]['PERMEDIT'][$h[0]] = "RW" ;
		$_SESSION[$COLUMN."_COLUMN"]['DESC_TO_KEY'][$h[0]] = $KEY;
		$_SESSION[$COLUMN."_COLUMN"]['ID']["$KEY"]=$KEY;
		if($_SESSION['USER_PROFILE'][$COLUMN."_COLUMN"]["$KEY"] == "HIDE") {
			$_SESSION[$COLUMN."_COLUMN"]['HIDE']["$KEY"]='HIDE';
		}
		$KEY++;
	}
//	echo "<br>Zainicjalizowano kolumne $COLUMN<br>";
}
//EOF INICJALIZACJA KOLUMN


//   ==========   MENU ==============

lay_procesy_user_panel();

//   ==========  TASK  ==============

App::exec_task();

//   ==========  function_init - funkcje  ==============

function SESSION_DEBUG() {
	if (isset($_GET['arg1_val'])) {
		$_SESSION['DEBUG'] = intval($_GET['arg1_val']);
	}
}


function SESSION_USER_PARAMS() {
	$allowed_user_params = array();
	$allowed_user_params['SHOW_PANEL']= 'int';
	$allowed_user_params['PROCESY_TREE_TYPE_HTML']= 'int';
	$allowed_user_params['ZASOBY_TREE_TYPE_HTML']= 'int';
	if (!isset($_GET['arg1']) || !isset($_GET['arg1_val'])) {
		return;
	} else if (array_key_exists($_GET['arg1'], $allowed_user_params)) {
		$_SESSION['USER_PARAMS'][ $_GET['arg1'] ] = intval($_GET['arg1_val']);
	}
}

function SORT_PRIO_ZASOB() {
	$id = V::get('arg1', '', $_GET, 'int');
	$sort_prio_dir = V::get('arg1_val', '', $_GET);
	TreeSortChildren::sortPrio($id, 'CRM_LISTA_ZASOBOW', 'PARENT_ID', $sort_prio_dir);
}

function SORT_PRIO_WSKAZNIK() {
	$id = V::get('arg1', '', $_GET, 'int');
	$sort_prio_dir = V::get('arg1_val', '', $_GET);
	TreeSortChildren::sortPrio($id, 'CRM_WSKAZNIK', 'ID_PROCES', $sort_prio_dir);
}

function SORT_PRIO_PROCES() {
	$id = V::get('arg1', '', $_GET, 'int');
	//$_GET['arg1_val'] = ($_GET['arg1_val'] == 'up')? 'dw' : 'up';// procesy w odwrotnej kolejnosci, w SQL order by SORT_PRIO DESC
	$sort_prio_dir = V::get('arg1_val', '', $_GET);
	TreeSortChildren::sortPrio($id, 'CRM_PROCES', 'PARENT_ID', $sort_prio_dir);
}

//   ==========  TASK - funkcje  ==============


function task_CRM_ADD_CRM_WSKAZNIK() {
	User_procesy5_check_access();
	// submit form - add wskaznik
	if (V::get('ADD_ID_CRM_PRZYPADEK', '', $_POST)) {
		$sql_obj = new stdClass();
		$sql_obj->ID_PROCES = V::get('ADD_ID_PROCES', '', $_POST);
		$sql_obj->ID_ZASOB = V::get('ADD_ID_ZASOB', '', $_POST);
		$sql_obj->TYP = V::get('ADD_CRM_WSKAZNIK_TYP', '', $_POST);
		$sql_obj->ID_PRZYPADEK = V::get('ADD_ID_CRM_PRZYPADEK', '', $_POST);
		$sql_obj->OPIS_ZASOB = V::get('ADD_CRM_WSKAZNIK_OPIS_ZASOB', '', $_POST);
		$sql_obj->SORT_PRIO = 0;
		// nowy wskaznik na koniec listy pod procesem
		$sql = "select max(cw.`SORT_PRIO`) as MAX_SORT_PRIO
			from `CRM_WSKAZNIK` as cw
			where
				cw.`ID_PROCES`='".$sql_obj->ID_PROCES."'
		";
		$res = DB::query( $sql );
		while ($r = DB::fetch( $res )) {
			$sql_obj->SORT_PRIO = $r->MAX_SORT_PRIO + 1;
		}

		//TODO: POST_VERIFY

		$new_id = DB::ADD_NEW_OBJ('CRM_WSKAZNIK', $sql_obj);
		if (V::get('DEBUG', '', $_SESSION)) echo"PASSED(1) NEW RECORD ID($new_id)<hr>";
		if ($new_id > 0) {
			echo '<p class="sql-msg box box-green">'."Dodano nowy rekord";
		} else {
			echo '<p class="sql-msg box box-red">'."Error przy dodawaniu rekordu";
		}
		echo'<br />'."Wroc do ".App::link("procesow", "?task=CRM_PROCES");
		echo'<br />'."lub ".App::link("dodaj kolejny zasob do procesu ".$sql_obj->ID_PROCES, "?task=ADD_PROCES_ID&id=".$sql_obj->ID_PROCES);
		echo'</p>';// .box
	}

	// show form - add wskaznik
	if (V::get('ADD_ID_ZASOB', '', $_GET)) {

	$id_proces = V::get('ADD_ID_PROCES', 0, $_REQUEST, 'int');
	$id_zasob = V::get('ADD_ID_ZASOB', 0, $_REQUEST, 'int');
	if ($id_proces <= 0) {
		echo'<p class="err">'."Wrong id!".'</p>';
		return;
	}

	if ($id_zasob <= 0) {
		echo'<p class="err">'."Wrong zasob id!".'</p>';
		return;
	}

	$proces = DB::get_by_id( 'CRM_PROCES', $id_proces );
	if (!$proces) {
		echo'<div class="box box-red">';
			echo "Proces [".$id_proces."] not exists.";
		echo'</div>';
		return;
	}

	$zasob = DB::get_by_id( 'CRM_LISTA_ZASOBOW', $id_zasob );
	if (!$zasob) {
		echo'<div class="box box-red">';
			echo "Proces [".$id_zasob."] not exists.";
		echo'</div>';
		return;
	}

	{// pathway
	echo'<h1>';
		echo App::link("Procesy", array('task'=>"CRM_PROCES"));
		if ($id_proces > 0) {
			echo ' &raquo; '.App::link("Dodaj zasob do procesu [".$id_proces."]", array('task'=>'ADD_PROCES_ID', 'id'=>$id_proces));
			if ($id_zasob > 0) {
				echo ' &raquo; '.App::link("Dodaj zasob [".$id_zasob."]", array('task'=>'CRM_ADD_CRM_WSKAZNIK', 'ADD_ID_PROCES'=>$id_proces, 'ADD_ID_ZASOB'=>$id_zasob));
			}
		}
	echo'</h1>';
	}// pathway

	Lib::loadClass('ProcesHelper');
	{// proces info
	$wsk = ProcesHelper::get_wskazniki( $proces->ID );
	echo'<div class="tree-wrap">';
	echo'<ul>';
	echo'<li class="tree-last">';
	echo'<dl>';
	echo'<dt>';
	if (!empty($wsk)) echo'<div class="has_wsk">';
		echo'<b class="item_id btn-box">'.$proces->ID.'</b>';
		echo'<span class="desc"><b>'.$proces->DESC.'</b>';
			echo'<span class="more-desc"> '.$proces->OPIS.' </span>';
		echo'</span>';
	if (!empty($wsk)) echo'</div>';
	echo'</dt>';
	if (!empty($wsk)) {
		$zasoby_id = array();
		echo'<dd>';
		echo'<ul>';
		$wsk_cnt = count( $wsk );
		foreach ($wsk as $w) {

			$w_parents_out = '';
			$w_title_parents_out = '';

			echo'<li'.((--$wsk_cnt)? '' : ' class="tree-last"').'>';
			echo'<p>';
			echo ' <span class="btn-box btn-box-silver">'.$w->CW_ID.'</span>';
			echo'<span class="green"'.$w_title_parents_out.'>['.$w->ID.']</span>';
			echo' <i title="'.$w->CP_PYTANIE.' '.$w->CP_OPIS.'">'.$w->CP_FORM_TREAT.'</i>';
			echo'';
			echo ' '.$w->TYPE.'';
			echo ' <b>'.$w->DESC.'</b> ';

			//if ($tree->get_param('rozwin_opis'))
			echo ' <span class="green">'.$w->OPIS.'</span>';// opis zasobu
			//if ($tree->get_param('rozwin_opis'))
			echo ' <span style="color:#000;">'.$w->OPIS_ZASOB.'</span>';// komentarz wskaznika

			echo'</p>';
			echo'</li>';
		}
		echo'</ul>';
	}
	echo'</dl>';
	echo'</li>';
	echo'</ul>';
	echo'</div>';// .tree-wrap
	}// proces info



	//	echo '<h3>Wybierz okolicznosci procesu <b style="color:red">'.V::get('ADD_ID_PROCES', '', $_GET).'</b> do zasobu <b style="color:green">'.V::get('ADD_ID_ZASOB', '', $_GET).'</b></h3>';
	echo'<h3>'."Wybierz okolicznosci powiazania zasobu ".'<b style="color:green">'.$zasob->ID.'</b>'." do procesu ".'<b style="color:red">'.$proces->ID.'</b>'.'</h3>';

	echo'<div class="tree-wrap">';
		echo'<p> <span class="btn-box btn-box-silver"></span>';
		echo' <span class="green">['.$zasob->ID.']</span>';
		echo' '.$zasob->TYPE.' <b>'.$zasob->DESC.'</b>  <span class="green">'.$zasob->OPIS.'</span>';
		echo'</p>';
	echo'</div>';

		$ZAP_SQL = "select * from CRM_PRZYPADEK ";
		$res = DB::query( $ZAP_SQL );
		echo'<form action="'."?task=CRM_ADD_CRM_WSKAZNIK&ADD_ID_ZASOB=".$_GET['ADD_ID_ZASOB']."&ADD_ID_PROCES=".$_GET['ADD_ID_PROCES'].'" method="POST">';
		echo'<input type="hidden" name="ADD_ID_ZASOB" value="'.V::get('ADD_ID_ZASOB', '', $_GET).'">';
		echo'<input type="hidden" name="ADD_ID_PROCES" value="'.V::get('ADD_ID_PROCES', '', $_GET).'">';

		echo'Rodzaj : <select name="ADD_CRM_WSKAZNIK_TYP"><option value="R">RZECZOWNIK</option><option value="C">CZASOWNIK</option></select><br>Przypadki rzeczownika:';
		echo'<select name="ADD_ID_CRM_PRZYPADEK">';
		while ($DWA = DB::fetch( $res )) {
			echo'<option value="'.$DWA->ID.'">'.$DWA->FORM_TREAT.' | '.$DWA->NAZWA.' | '.$DWA->PYTANIE.' | '.$DWA->OPIS.'</option>'."\n";
		}
		echo'</select>';
		//echo'<br />Komentarz: <input type="text" name="ADD_CRM_WSKAZNIK_OPIS_ZASOB" value="'.$_GET['ADD_CRM_WSKAZNIK_OPIS_ZASOB'].'" size=50>';
		echo'<br />Komentarz:';
			echo'<br /><textarea name="ADD_CRM_WSKAZNIK_OPIS_ZASOB" cols="80" rows="6">'.V::get('ADD_CRM_WSKAZNIK_OPIS_ZASOB', '', $_GET).'</textarea>';
		echo'<br><input type="SUBMIT" value="DODAJ"></form>';
		echo'<hr>';
	}
}


/**
 * @param $_GET['ID'] - ID rekordu do edycji
 */
function task_CRM_EDIT_CRM_WSKAZNIK() {
	global $error;
	User_procesy5_check_access();

	$id = V::get('ID', '', $_GET, 'int');
	if ($id <= 0) {
		echo'<p class="err">'."Wrong ID".'</p>';
		return;
	}

	$R = null;
	$sql = "select * from `CRM_WSKAZNIK` where `ID`='".$id."' limit 1; ";// TODO: use DB::get_by_id
	$res = DB::query($sql);
	if (!$res) die("sql query error $sql");
	$R = DB::fetch($res);
	if (!$R) {
		echo'<p class="err">'."Wrong ID - not exists".'</p>';
		return;
	}

//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">';print_r($R);echo'</pre>';

	// form submit
	if (V::get('EDIT_SUBMIT', '', $_POST)) {
		$sql_obj = new stdClass();
		$sql_obj->ID = $R->ID;
		//$sql_obj->PARENT_ID = V::get('EDIT_PARENT_ID', '', $_POST);
		$sql_obj->TYP = V::get('EDIT_TYP', '', $_POST);
		$sql_obj->ID_PRZYPADEK = V::get('EDIT_ID_PRZYPADEK', '', $_POST);
		$sql_obj->OPIS_ZASOB = V::get('EDIT_OPIS_ZASOB', '', $_POST);
		$sql_obj->ID_PROCES = V::get('EDIT_ID_PROCES', '', $_POST, 'int');
		$sql_obj->ID_ZASOB = V::get('EDIT_ID_ZASOB', '', $_POST, 'int');
		$sql_obj->PARENT_ID = V::get('PARENT_ID', '', $_POST);//todo trzeba sprawdzic czy jest taki wskaznik uzyty w tym procesie
		$sql_obj->EXPORT_WSKAZNIK = V::get('EXPORT_WSKAZNIK', '', $_POST, 'int');//todo musi byc weryfikacja czy jest taki wskaznik w odwolujacej sie funkcji

		//TODO: POST_VERIFY

		$affected = DB::UPDATE_OBJ( 'CRM_WSKAZNIK', $sql_obj );
		if (V::get('DEBUG', '', $_SESSION)) echo"PASSED($affected)<hr>";
		if ($affected == 2) {
			echo '<p class="green box box-green">'."Zmienio rekord";
		} else if ($affected == 1) {
			echo '<p class="err box box-red">'."Zmieniono rekord (Error: nie zapisano hostorii)";
		} else if ($affected < 0) {
			echo '<p class="err box box-red">'."Blad podczas edytowania rekordu - nic nie zmieniono";
		}
		echo'<br />'."Wroc do ".App::link("procesow", "?task=CRM_PROCES");
		echo'</p>';// .box
	}

	// show form - edit wskaznik
	if (V::get('EDIT', '', $_GET)) {
		// overwrite data from POST
		if ($_POST) {
			if (isset($_POST['EDIT_ID_PROCES'])) $R->ID_PROCES = $_POST['EDIT_ID_PROCES'];
			if (isset($_POST['EDIT_ID_ZASOB'])) $R->ID_ZASOB = $_POST['EDIT_ID_ZASOB'];
			if (isset($_POST['EDIT_TYP'])) $R->TYP = $_POST['EDIT_TYP'];
			if (isset($_POST['EDIT_ID_PRZYPADEK'])) $R->ID_PRZYPADEK = $_POST['EDIT_ID_PRZYPADEK'];
			if (isset($_POST['EDIT_OPIS_ZASOB'])) $R->OPIS_ZASOB = $_POST['EDIT_OPIS_ZASOB'];
			if (isset($_POST['PARENT_ID'])) $R->PARENT_ID = $_POST['PARENT_ID'];
			if (isset($_POST['EXPORT_WSKAZNIK'])) $R->EXPORT_WSKAZNIK = $_POST['EXPORT_WSKAZNIK'];
		}

		echo '<h3>Edytuj wskaznik procesu <b style="color:red">'.$R->ID_PROCES.'</b> do zasobu <b style="color:green">'.$R->ID_ZASOB.'</b></h3>';
		$frm_edit_action = "?task=CRM_EDIT_CRM_WSKAZNIK&EDIT=".$R->ID."&ID=".$R->ID;
    echo "<h6>Dane bieżącego rekordu: Stworzono: {$R->A_RECORD_CREATE_DATE}, Stworzył: {$R->A_RECORD_CREATE_AUTHOR} , Aktualizował: {$R->A_RECORD_UPDATE_DATE}, data:{$R->A_RECORD_UPDATE_DATE} </h6>";
		echo '<form action="'.$frm_edit_action.'" method="POST">';
		echo'<input type="hidden" name="EDIT_SUBMIT" value="1">';

		echo '<br />'."Proces ID: ";
		echo'<input type="text" name="EDIT_ID_PROCES" value="'.$R->ID_PROCES.'">';
		echo '<br />'."Zasob ID: ";
		echo'<input type="text" name="EDIT_ID_ZASOB" value="'.$R->ID_ZASOB.'">';
		// TODO: rodzaj array selected - typespecial
		echo'<br />'."Rodzaj: ";
		echo'<select name="EDIT_TYP"><option value="R">RZECZOWNIK</option><option value="C">CZASOWNIK</option></select>';
		echo'<br>Przypadki rzeczownika:';
		echo'<select name="EDIT_ID_PRZYPADEK">';
		$ZAP_SQL = "select * from CRM_PRZYPADEK ";
		$res = DB::query( $ZAP_SQL );
		while ($DWA = DB::fetch( $res )) {
			$sel = ($R->ID_PRZYPADEK == $DWA->ID)? ' selected="selected"' : '';
			echo'<option value="'.$DWA->ID.'"'.$sel.'>'.$DWA->FORM_TREAT.' | '.$DWA->NAZWA.' | '.$DWA->PYTANIE.' | '.$DWA->OPIS.'</option>'."\n";
		}
		echo'</select>';
		//echo'<br />Komentarz: <input type="text" name="EDIT_OPIS_ZASOB" value="'.$R->OPIS_ZASOB.'" size=50>';
		echo'<br />Komentarz:';
			echo'<br /><textarea name="EDIT_OPIS_ZASOB" cols="80" rows="6">'.$R->OPIS_ZASOB.'</textarea>';
		echo'<br><input type="SUBMIT" value="'."ZAPISZ".'">';
		echo'</form>';
		echo'<hr>';
	}
}


function task_CRM_DEL_CRM_WSKAZNIK() {
	User_procesy5_check_access();
	$sql_obj = new stdClass();
	$sql_obj->ID = V::get('ID', '', $_GET, 'int');
	$sql_obj->A_STATUS = 'DELETED';

	//TODO: POST_VERIFY
	if ($sql_obj->ID <= 0) {
		echo'<p class="err">'."Wrong ID".'</p>';
		return;
	}

	$db = DB::getDB();
	$affected = $db->UPDATE_OBJ('CRM_WSKAZNIK', $sql_obj);
	if ($affected == 2) {
		echo '<p class="green box box-green">'."Usunieto wskaznik";
	} else if ($affected == 1) {
		echo '<p class="err box box-red">'."Usunieto wskaznik (Error: nie zapisano hostorii)";
	} else if ($affected < 0) {
		if ($db->has_errors()) {
			try {
				$dsErrors = array();
				$errorsSql = $db->get_errors();
				foreach ($errorsSql as $vErr) {
					if ('SQL QUERY FAILED: ' == substr($vErr, 0, 18)) {
						$vErr = substr($vErr, 18);
					}
					$dsErrors[] = $vErr;
				}
				if (!empty($dsErrors)) {
					Lib::loadClass('StorageException');
					throw new StorageException($dsErrors);
				}
			} catch (Exception $e) {
				?><div class="alert alert-danger">
					Wystąpiły błędy: <?php echo $e->getMessage(); ?>
				</div><?php
			}
		} else {
			echo '<p class="err box box-red">'."Blad podczas usuwaniu wskaznika - nic nie zmieniono";
		}
	}
	echo'<br />'."Wroc do ".App::link("procesow", "?task=CRM_PROCES");
	echo'</p>';// .box
}


/**
 * @param $tree_callback - tree item show function callback
 * @param $tree_params - array of tree params
 */
function action_VIEW_SUBTREE( $tbl, $proces_id, $tree_callback, $tree_params ) {
	$tree = new Tree( $tbl );
	$tree->set_param('show_item_callback', $tree_callback);
	foreach ($tree_params as $key => $val) {
		$tree->set_param($key, $val);
	}
	$tree->showSubTree( $proces_id );
}


function task_VIEW_PROCES_MAP() {
	User_procesy5_check_access();

	$procesMap = new stdClass();
	$procesMap->procesInitAll = array();
	$procesMap->gotoAll = array();
	$procesMap->treeFlat = array();

	$db = DB::getDB();
	$sql = "select p.`ID`, p.`PARENT_ID`
			-- , p.`OPIS`
			, p.`TYPE`, p.`IF_TRUE_GOTO`, p.`IF_TRUE_GOTO_FLAG`
		from `CRM_PROCES` as p
		where
			p.`A_STATUS` in('WAITING', 'NORMAL')
		--	and (p.`TYPE`='PROCES_INIT' or p.`IF_TRUE_GOTO`>0)
	";
	$res = $db->query($sql);
	while ($r = $db->fetch($res)) {
		if ($r->IF_TRUE_GOTO > 0) {
			$procesMap->gotoAll[$r->ID] = $r;
		}
		if ($r->TYPE == 'PROCES_INIT') {
			$procesMap->procesInitAll[$r->ID] = $r;
		}
		$procesMap->treeFlat[$r->PARENT_ID][] = $r->ID;
	}

	// validate goto - goto only to PROCES_INIT
	$procesMap->gotoErrors = array();
	foreach ($procesMap->gotoAll as $kId => $vStep) {
		if (!array_key_exists($vStep->IF_TRUE_GOTO, $procesMap->procesInitAll)) {
			$procesMap->gotoErrors[$kId] = $vStep;
		}
	}
	foreach ($procesMap->gotoErrors as $kId => $vStep) {
		unset($procesMap->gotoAll[$kId]);
	}

	foreach ($procesMap->procesInitAll as $kId => $vProces) {
		$vProces->gotoLinks = array();
		$vProces->sub = array();
		if (array_key_exists($kId, $procesMap->treeFlat)) {
			foreach ($procesMap->treeFlat[$kId] as $childId) {
				$vProces->sub[$childId] = true;
			}
		}
		//$procesMap->procesInitAll[$kId] = $vProces;
	}

	if(V::get('DBG', '', $_GET)){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">procesMap (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($procesMap);echo'</pre>';}

	$loopLimit = 50;// max ilość zagłębień w procesie
	for ($i = 0; $i < $loopLimit; $i++) {
		$breakLoop = true;

		foreach ($procesMap->procesInitAll as $kId => $vProces) {
			if (!empty($vProces->sub)) {
				$breakLoop = false;
				$childrens = array_keys($vProces->sub);
				$vProces->sub = array();
				foreach ($childrens as $childId) {
					if (array_key_exists($childId, $procesMap->treeFlat)) {
						foreach ($procesMap->treeFlat[$childId] as $vId) {
							$vProces->sub[$vId] = true;
						}
					}

					if (array_key_exists($childId, $procesMap->gotoAll)) {
						$gotoId = $procesMap->gotoAll[$childId]->IF_TRUE_GOTO;

						$vProces->gotoLinks[$gotoId] = $procesMap->procesInitAll[$gotoId];

						$procesMap->gotoFrom[$gotoId][$vProces->ID] = $vProces->ID;
					}
				}
			}
		}

		if ($breakLoop) {
			if(V::get('DBG', '', $_GET)){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">breakLoop (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("end by {$i} loops");echo'</pre>';}
			break;
		}
	}

	// fetch DESC i OPIS laters
	$sqlIds = array_keys($procesMap->procesInitAll);
	if (!empty($sqlIds)) {
		$sqlIds = implode(",", $sqlIds);
		$sql = "select p.`ID`, p.`DESC`, p.`OPIS`
			from `CRM_PROCES` as p
			where
				p.`A_STATUS` in('WAITING', 'NORMAL')
				and p.`ID` in({$sqlIds})
		";
		$res = $db->query($sql);
		while ($r = $db->fetch($res)) {
			$procesMap->procesInitAll[$r->ID]->DESC = $r->DESC;
			$procesMap->procesInitAll[$r->ID]->OPIS = $r->OPIS;
		}
	}

	if(V::get('DBG', '', $_GET)){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">procesMap (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($procesMap);echo'</pre>';}


	?>
	<style type="text/css">
.procesMapItem { padding:20px 6px; border-bottom:1px solid #eee; color:rgba(51, 51, 51, 0.6); }
.procesMapItem:hover { color:#333; }
 .procesMapItem li { width:100%; overflow:hidden; clear:left; text-align:left; text-overflow:ellipsis; white-space:nowrap; }
@media print {
	.procesMapItem { color:rgb(51, 51, 51); }
}
	</style>
	<div class="container">

	<?php if (!empty($procesMap->gotoErrors) && !V::get('HIDE_PANEL', 0, $_GET, 'int')) : ?>
		<div class="alert alert-danger">
			<button type="button" class="close" data-dismiss="alert">×</button>
			<strong>Uwaga błędy w GOTO!</strong> GOTO może wywołać jedynie PROCES_INIT. <?php echo count($procesMap->gotoErrors); ?> błędów.
			<ul>
				<?php foreach ($procesMap->gotoErrors as $vStep) : ?>
					<li>Krok <?php echo $vStep->ID; ?> <?php echo $vStep->IF_TRUE_GOTO_FLAG; ?> {<?php echo $vStep->IF_TRUE_GOTO; ?>}</li>
				<?php endforeach; ?>
			</ul>
		</div>
	<?php endif; ?>

	<h1>Mapa procesów

	<?php
		if (!V::get('HIDE_PANEL', 0, $_GET, 'int')) {
			echo App::link("drukuj", array('task'=>'VIEW_PROCES_MAP', 'HIDE_PANEL'=>1), array('target'=>'_blank', 'ico_after_text'=>'print', 'style'=>'font-size:small;'));
		}
	?>

	</h1>
	<?php foreach ($procesMap->procesInitAll as $kId => $vProces) : ?>
		<div class="procesMapItem">
		<h4 id="procesMapId-<?php echo $vProces->ID; ?>">{<?php echo $vProces->ID; ?>} <?php echo $vProces->DESC; ?></h4>
		<p><?php echo strip_tags($vProces->OPIS); ?></p>
		<?php if ($vProces->gotoLinks) : ?>
			<dl>
				<dt>Może wywołać:</dt>
				<dd>
					<ul>
					<?php foreach ($vProces->gotoLinks as $kGotoProcesId => $gotoProces) : ?>
						<li><a href="#procesMapId-<?php echo $gotoProces->ID; ?>">{<?php echo $gotoProces->ID; ?>}</a> <?php echo $gotoProces->DESC; ?></li>
					<?php endforeach; ?>
					</ul>
				</dd>
			</dl>
		<?php endif; ?>
		<?php if (!empty($procesMap->gotoFrom[$vProces->ID])) : ?>
			<dl>
				<dt>Może zostać wywołany przez:</dt>
				<dd>
					<ul>
					<?php foreach ($procesMap->gotoFrom[$vProces->ID] as $kGotoProcesId) : $gotoProces = $procesMap->procesInitAll[$kGotoProcesId]; ?>
						<li><a href="#procesMapId-<?php echo $gotoProces->ID; ?>">{<?php echo $gotoProces->ID; ?>}</a> <?php echo $gotoProces->DESC; ?></li>
					<?php endforeach; ?>
					</ul>
				</dd>
			</dl>
		<?php endif; ?>
		</div>
	<?php endforeach; ?>
	</div>
	<?php

	if (V::get('HIDE_PANEL', 0, $_GET, 'int') == 1) {
		?>
		<script>jQuery(document).ready(function(){
			window.print();
		});
		</script>
		<?php
	}
}


function task_PROCES_VIEW_LIST() {
	$tbl = 'CRM_PROCES';

	$id_proces = V::get('id_proces', '', $_REQUEST, 'int');
	if ($id_proces <= 0) {
		echo '<div class="alert alert-danger">' . "Wrong ID" . '</div>';
		return;
	}

	$p = DB::get_by_id('CRM_PROCES', $id_proces);
	if (!$p) {
		echo '<div class="alert alert-danger">' . "Proces {$id_proces} nie istnieje" . '</div>';
		return;
	}

	$userAcl = User::getAcl();
	if (!$userAcl->canViewProces($id_proces)) {
		echo '<div class="alert alert-danger">' . "Brak uprawnień do procesu" . '</div>';
		return;
	}

	if (!V::get('HIDE_PANEL', 0, $_GET, 'int')) {
		// pathway
		echo'<h1>'.App::link("Menu", "?task=CRM_MENU");
			echo' - ';
			echo "Przegladaj proces <b>".$id_proces."</b>";
			echo ' ';
			echo App::link("drukuj", array('task'=>'PROCES_VIEW_LIST', 'id_proces'=>$id_proces, 'HIDE_PANEL'=>1), array('target'=>'_blank', 'ico_after_text'=>'print', 'style'=>'font-size:small;'));
		echo'</h1>';
	}

	Lib::loadClass('TreeList');
	$treeList = new TreeList('CRM_PROCES', $id_proces, 'PARENT_ID');
	$treeList->fetchTreeFlat();
	$listFlat = $treeList->generateListFlat();
	$treeList->fetchData();

	$ids = $treeList->getListIds();
	$wskazniki = ProcesHelper::getWskaznikiByIds($ids, array('group_stanowiska' => 1));
	if(V::get('DBG_TF', '', $_GET) > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$wskazniki (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($wskazniki);echo'</pre>';}

	$gotoLinks = array();
	$gotoIds = array();
	foreach ($listFlat as $vItem) {
		$item = $treeList->getData($vItem->ID);
		if ($item->IF_TRUE_GOTO > 0) {
			$gotoIds[] = $item->IF_TRUE_GOTO;
		}
	}
	if (!empty($gotoIds)) {
		$db = DB::getDB();
		$sqlIds = implode(",", $gotoIds);
		$sql = "select p.`ID`, p.`DESC`, p.`OPIS`
			from `CRM_PROCES` as p
			where
				p.`A_STATUS` in('WAITING', 'NORMAL')
				and p.`ID` in({$sqlIds})
		";
		$res = $db->query($sql);
		while ($r = $db->fetch($res)) {
			$gotoLinks[$r->ID] = $r->DESC;
		}
	}

	foreach ($listFlat as $vItem) {
		$item = $treeList->getData($vItem->ID);

		if(V::get('DBG_TF', '', $_GET) > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">wskazniki['.$item->ID.'] (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($wskazniki[$item->ID]);echo'</pre>';}

		$vItem->gotoOut = '';
		if ($item->IF_TRUE_GOTO > 0) {
			$gotoLink = "{{$item->IF_TRUE_GOTO}}";
			if (!V::get('HIDE_PANEL', 0, $_GET, 'int')) {
				$gotoLink = App::link($gotoLink, array('task'=>'PROCES_VIEW_LIST', 'id_proces'=>$item->IF_TRUE_GOTO));
			}
			if ($item->IF_TRUE_GOTO_FLAG == 'GOTO') {
				$vItem->gotoOut .= " {$gotoLink}"; //usunąłem Przejdz do Procesu, bo w instrukcji/umowie nie jest to potrzebne
			} else if ($item->IF_TRUE_GOTO_FLAG == 'GOTO_AND_RETURN') {
				$vItem->gotoOut .= "Przejdź do procesu {$gotoLink} i wróć po jego zakończeniu";
			} else if ($item->IF_TRUE_GOTO_FLAG == 'FORK') {
				$vItem->gotoOut .= "Uruchom propces {$gotoLink}";
			}
			if (!empty($vItem->gotoOut) && !empty($gotoLinks[$item->IF_TRUE_GOTO])) {
				$vItem->gotoOut .= ": {$gotoLinks[$item->IF_TRUE_GOTO]}";
			}
			$vItem->gotoOut .= ".";
		}
	}

	$imgSize = (V::get('show_big_img', '', $_GET))? '600x600' : '200x200';

	?>
	<style type="text/css">
.proces-list-item-view { clear:both; }
.proces-list-view-image { float:right; padding:0 0 8px 8px; clear:right; }
	</style>
	<div class="container">
	<?php foreach ($listFlat as $vItem) {
	$item = $treeList->getData($vItem->ID);
	?>
		<div class="proces-list-item-view">
			<h4><?php
			if($item->TYPE=='PROCES_INIT') echo "{".$item->ID."}";
			else if(in_array($item->TYPE,array('TEXT_BREAK'))) echo "&nbsp;&nbsp;&nbsp;";
			else if(strstr($item->TYPE,'PROCES_GROUP')) echo "<font size=+2>§".$vItem->listNrNUM."";
			else
			echo $vItem->listNrNUM."."; ?> <?php echo $item->DESC; ?> <span class="muted"><font size=-2 color=grey><i><?php if(!in_array($item->TYPE,array('TEXT_BREAK','PROCES_INIT'))) echo "{".$item->ID."}"; ?></i></font></span></h4>
			<?php if($item->TYPE=='PROCES_INIT')
				if(!empty($item->A_RECORD_UPDATE_DATE))
				echo "<font size=-5>akt. {$item->A_RECORD_UPDATE_DATE} przez {$item->A_RECORD_UPDATE_AUTHOR}</font>";  //TODO nalezy zabrac informacje o procesie z klasy
				 else
					echo "<font size=-5>utw. {$item->A_RECORD_CREATE_DATE} przez {$item->A_RECORD_CREATE_AUTHOR}</font>";  //TODO nalezy zabrac informacje o procesie z klasy
			?>
			<p style="overflow:hidden">
				<?php if ($item->A_HAS_IMAGE > 0) : ?>
					<?php $tbl = 'CRM_PROCES'; ?>
					<?php for ($i = 0; $i < $item->A_HAS_IMAGE; $i++) : ?>
						<a href="procesy5.php?function_init=fun_SHOW_EXTERNAL_IMAGE&tbl=<?php echo $tbl; ?>&id=<?php echo $item->ID; ?>&number=<?php echo $i; ?>" target="_blank" class="proces-list-view-image lightbox">
							<img src="procesy5.php?function_init=fun_SHOW_EXTERNAL_IMAGE&tbl=<?php echo $tbl; ?>&id=<?php echo $item->ID; ?>&number=<?php echo $i; ?>&resize=<?php echo $imgSize; ?>" />
						</a>
					<?php endfor; ?>
				<?php endif; ?>
				<?php echo $item->OPIS; ?>

			</p>

			<?php
			if(strstr($item->TYPE,'PROCES_GROUP')) echo "</font>";


			 ?></p>
			<?php if (array_key_exists($item->ID, $wskazniki)) : ?>
				<dl class="dl-horizontal">
				<?php if (!empty($wskazniki[$item->ID]['stanowiska'])) : ?>
					<dt>Stanowiska:</dt>
					<dd>
						<ul>
							<?php foreach ($wskazniki[$item->ID]['stanowiska'] as $vWsk) : ?>
								<li><?php echo $vWsk->DESC; ?> <span class="muted">[<?php echo $vWsk->ID; ?>]</span></li>
							<?php endforeach; ?>
						</ul>
					</dd>
				<?php endif; ?>

				<?php if (!empty($wskazniki[$item->ID]['inne'])) : ?>
					<dt>Użyte zasoby:</dt>
					<dd>
						<ul>
						<?php foreach ($wskazniki[$item->ID]['inne'] as $vWsk) : ?>
							<li style="clear:both;">
								<?php if ($vWsk->A_HAS_IMAGE > 0) : ?>
									<?php $tbl = 'CRM_LISTA_ZASOBOW'; ?>
									<?php for ($i = 0; $i < $vWsk->A_HAS_IMAGE; $i++) : ?>
										<a href="procesy5.php?function_init=fun_SHOW_EXTERNAL_IMAGE&tbl=<?php echo $tbl; ?>&id=<?php echo $vWsk->ID; ?>&number=<?php echo $i; ?>" target="_blank" class="proces-list-view-image lightbox">
											<img src="procesy5.php?function_init=fun_SHOW_EXTERNAL_IMAGE&tbl=<?php echo $tbl; ?>&id=<?php echo $vWsk->ID; ?>&number=<?php echo $i; ?>&resize=<?php echo $imgSize; ?>" />
										</a>
									<?php endfor; ?>
								<?php endif; ?>
								<?php if ($vWsk->CW_A_HAS_IMAGE > 0) : ?>
									<?php $tbl = 'CRM_WSKAZNIK'; ?>
									<?php for ($i = 0; $i < $vWsk->CW_A_HAS_IMAGE; $i++) : ?>
										<a href="procesy5.php?function_init=fun_SHOW_EXTERNAL_IMAGE&tbl=<?php echo $tbl; ?>&id=<?php echo $vWsk->CW_ID; ?>&number=<?php echo $i; ?>" target="_blank" class="proces-list-view-image lightbox">
											<img src="procesy5.php?function_init=fun_SHOW_EXTERNAL_IMAGE&tbl=<?php echo $tbl; ?>&id=<?php echo $vWsk->CW_ID; ?>&number=<?php echo $i; ?>&resize=<?php echo $imgSize; ?>" />
										</a>
									<?php endfor; ?>
								<?php endif; ?>

								<strong><?php echo (!empty($vWsk->DESC_PL))? $vWsk->DESC_PL : $vWsk->DESC; ?></strong>
								<?php echo (!empty($vWsk->OPIS))? " <em>({$vWsk->OPIS})</em>." : ''; ?>
								<?php echo (!empty($vWsk->OPIS_ZASOB))? "<br>{$vWsk->OPIS_ZASOB}" : ''; ?>
								<span class="muted">[<?php echo $vWsk->ID; ?>]</span>
							</li>
						<?php endforeach; ?>
						</ul>
					</dd>
				<?php endif; ?>
				</dl>
			<?php endif; ?>

			<?php if ($vItem->gotoOut) : ?>
				<blockquote>
					<small>
						<?php echo $vItem->gotoOut; ?>
					</small>
				</blockquote>
			<?php endif; ?>
		</div>
		<?php
	}
	echo '</div>';// .container

}


function task_PROCES_VIEW() {
	User_procesy5_check_access();

	$id_proces = V::get('id_proces', '', $_REQUEST, 'int');
	if ($id_proces <= 0) {
		echo'<p class="err box box-red">'."Wrong ID".'</p>';
		return;
	}

	if (1 != V::get('HIDE_PANEL', 0, $_GET, 'int')) {
		// pathway
		echo'<h1>'.App::link("Menu", "?task=CRM_MENU");
			echo' - ';
			echo "Przegladaj proces <b>".$id_proces."</b>";
			echo ' ';
			echo App::link("drukuj", array('task'=>'PROCES_VIEW', 'id_proces'=>$id_proces, 'HIDE_PANEL'=>1), array('target'=>'_blank', 'ico_after_text'=>'print', 'style'=>'font-size:small;'));
			echo ' ';
			echo App::link("drukuj większe zdjęcia", array('task'=>'PROCES_VIEW', 'id_proces'=>$id_proces, 'HIDE_PANEL'=>1, 'show_big_img'=>1, 'group_stanowiska'=>1), array('target'=>'_blank', 'ico_after_text'=>'print', 'style'=>'font-size:small;'));
			echo ' ';
			echo App::link("widok listy", array('task'=>'PROCES_VIEW_LIST', 'id_proces'=>$id_proces), array('style'=>'font-size:small;'));
			echo ' ';
			echo "<font size=-1><a href=index.php?FUNCTION_INIT=GRAPH_VIEW_PROCES&id_proces={$id_proces} target=blank>Widok mapy</a></font>";

		echo'</h1>';
	}

	$p = DB::get_by_id( 'CRM_PROCES', $id_proces );
	if (!$p) {
		echo'<p class="err box box-red">'."Process ".$id_proces." not exists".'</p>';
		return;
	}

	$tbl = 'CRM_PROCES';
	$clbk = 'tree_callback__show_item_from_'.$tbl;

	$tree_params = array();
	$tree_params['rozwin'] = true;
	$tree_params['editable'] = false;
	$tree_params['rozwin_proces'] = true;
	$tree_params['filtr_img'] = true;
	$tree_params['rozwin_zasoby'] = true;
	$tree_params['rozwin_opis'] = true;
	$tree_params['style'] = 'NOWY';

	action_VIEW_SUBTREE($tbl, $p->ID, $clbk, $tree_params);
}


function task_CRM_WYSWIETL_OBOWIAZKI() {
	User_procesy5_check_access();

	$_GET['TYPE'] = V::get('TYPE', "%", $_REQUEST);
	$_GET['DESC'] = V::get('DESC', "%", $_REQUEST);
	$_GET['OPIS'] = V::get('OPIS', "%", $_REQUEST);
	$_GET['ADM_AREA'] = V::get('ADM_AREA', "BN%", $_REQUEST);
	$_GET['CLZ_ID'] = V::get('CLZ_ID', '', $_REQUEST);

	if (!$_GET['CLZ_ID']) {
		//echo'<p class="err">'."Brak ID".'</p>';
		task_CRM_MENU();
		//TEST://	echo App::link_ajax_load_on_ready('user menu', 'task_CRM_MENU');
		return;
	}


	$zasob = DB::get_by_id('CRM_LISTA_ZASOBOW', $_GET['CLZ_ID']);
	if (!$zasob) {
		echo'<p class="err">'."Brak danych - zasob ".$_GET['CLZ_ID']." nie istnieje.".'</p>';
		return;
	}

	echo'<p>';
		echo "Procesy powiazane z zasobem: ";
		echo'<b>['.$zasob->ID.']</b>';
		echo'<br />';
		echo ' <b>'.$zasob->TYPE.'</b>';
		echo ' <span>'.$zasob->DESC.'</span>';
		echo '<br /><span>'.$zasob->OPIS.'</span>';
		echo '<br> <a href=index.php?FUNCTION_INIT=GRAPH_VIEW_PROCES&PROCES_INIT_SCAN=1&id_zasob='.$zasob->ID.'&RESOURCES=1><span>Wyświetl mapę </span>';
	echo'</p>';

	$db = DB::getDB();
	$sql = "select
			w.`ID_PROCES` as w__ID_PROCES
			, w.`OPIS_ZASOB` as w__OPIS_ZASOB
			, p.`ID` as p__ID
			, p.`DESC` as p__DESC
			, p.`OPIS` as p__OPIS
			, p_root.`ID` as p_root__ID
			, p_root.`DESC` as p_root__DESC
			, p_root.`OPIS` as p_root__OPIS
		from `CRM_WSKAZNIK` as w
			left join `CRM_PROCES` as p on (p.`ID`=w.`ID_PROCES`)
			left join `CRM_PROCES` as p_root on (p_root.`ID`=p.`PARENT_ID`)
		where
			w.`ID_ZASOB`=".$_GET['CLZ_ID']."
			and w.`A_STATUS` in('WAITING','NORMAL')
			and p.`A_STATUS` in('WAITING','NORMAL')
			order by p.SORT_PRIO
	";
	$res = $db->query($sql);
	while ($r = $db->fetch($res)) {
		$arr [$r->w__ID_PROCES][] = $r;
	}
	echo'<table border="1" cellspacing="0" cellpadding="0" class="tbl-view">';
	echo'<thead>';
	echo'<tr>';
		echo'<th>'."PROCES ID".'</th>';
		echo'<th style="text-align:left">'."NAZWA / OPIS".'</th>';
	echo'</tr>';
	echo'</thead>';
	echo'<tbody>';
	$t = 0;
	foreach ($arr as $k_id => $v_arr) {
		echo'<tr class="row-'.($t = 1 - $t).'">';
			echo'<td>';
				echo App::link($k_id, array('task'=>"CRM_PROCES", 'filtr_id'=>$k_id));
			echo'</td>';
			echo'<td>';
			foreach ($v_arr as $r) {
				echo'<p>';
					echo' <b>'.$r->p__DESC.'</b>';
					echo'<br />';
					echo'<em>'.$r->p__OPIS.'</em>';
					if ($r->w__OPIS_ZASOB) echo'<span class="silver">'.$r->w__OPIS_ZASOB.'</span>';
				echo'</p>';
			}
			echo'</td>';
		echo'</tr>';
	}
	echo'</tbody>';
	echo'</table>';
}


function task_ADD_PROCES_ID() {
	User_procesy5_check_access();

	$id_proces = (isset($_REQUEST['id']))? intval($_REQUEST['id']) : 0;
	//$id_zasob = 0;//(isset($_REQUEST['id']))? intval($_REQUEST['id']) : 0;
	if ($id_proces <= 0) {
		echo'<p class="err">'."Wrong id!".'</p>';
		return;
	}

	$proces = DB::get_by_id( 'CRM_PROCES', $id_proces );
	if (!$proces) {
		echo'<div class="box box-red">';
			echo "Proces [".$id_proces."] not exists.";
		echo'</div>';
		return;
	}

	{// pathway
	echo'<h1>';
		echo App::link("Procesy", array('task'=>"CRM_PROCES"));
		if ($id_proces > 0) {
			echo ' &raquo; '.App::link("Dodaj zasob do procesu [".$id_proces."]", array('task'=>'ADD_PROCES_ID', 'id'=>$id_proces));
			//if ($id_zasob > 0) {
			//	echo ' &raquo; '.App::link("Dodaj zasob [".$id_zasob."]", array('task'=>'CRM_ADD_CRM_WSKAZNIK', 'ADD_ID_PROCES'=>$id_proces, 'ADD_ID_ZASOB'=>$id_zasob));
			//}
		}
	echo'</h1>';
	}// pathway

	Lib::loadClass('ProcesHelper');
	{// proces info
	$wsk = ProcesHelper::get_wskazniki( $proces->ID );
	echo'<div class="tree-wrap">';
	echo'<ul>';
	echo'<li class="tree-last">';
	echo'<dl>';
	echo'<dt>';
	if (!empty($wsk)) echo'<div class="has_wsk">';
		echo'<b class="item_id btn-box">'.$proces->ID.'</b>';
		echo'<span class="desc"><b>'.$proces->DESC.'</b>';
			echo'<span class="more-desc"> '.$proces->OPIS.' </span>';
		echo'</span>';
	if (!empty($wsk)) echo'</div>';
	echo'</dt>';
	if (!empty($wsk)) {
		$zasoby_id = array();
		echo'<dd>';
		echo'<ul>';
		$wsk_cnt = count( $wsk );
		foreach ($wsk as $w) {

			$w_parents_out = '';
			$w_title_parents_out = '';

			echo'<li'.((--$wsk_cnt)? '' : ' class="tree-last"').'>';
			echo'<p>';
			echo ' <span class="btn-box btn-box-silver">'.$w->CW_ID.'</span>';
			echo'<span class="green"'.$w_title_parents_out.'>['.$w->ID.']</span>';
			echo' <i title="'.$w->CP_PYTANIE.' '.$w->CP_OPIS.'">'.$w->CP_FORM_TREAT.'</i>';
			echo'';
			echo ' '.$w->TYPE.'';
			echo ' <b>'.$w->DESC.'</b> ';

			//if ($tree->get_param('rozwin_opis'))
			echo ' <span class="green">'.$w->OPIS.'</span>';// opis zasobu
			//if ($tree->get_param('rozwin_opis'))
			echo ' <span style="color:#000;">'.$w->OPIS_ZASOB.'</span>';// komentarz wskaznika

			echo'</p>';
			echo'</li>';
		}
		echo'</ul>';
	}
	echo'</dl>';
	echo'</li>';
	echo'</ul>';
	echo'</div>';// .tree-wrap
	}// proces info

	echo'<form action="" method="GET">';
		echo'<input type="hidden" name="'."task".'" value="'."CRM_ADD_CRM_WSKAZNIK".'" />';
		echo'<input type="hidden" name="'."ADD_ID_PROCES".'" value="'.$proces->ID.'" />';
	echo'<p>'."Podaj numer zasobu: ";
		echo'<input type="text" name="'."ADD_ID_ZASOB".'" value="'."".'" />';
		echo'<input type="submit" value="'."OK".'" />';
		echo '<br />'." lub wyszukaj ponizej:";
	echo'</p>';
	echo'</form>';

	echo'<pre id="tree">';
		echo "DRZEWO ";
		if ($_SESSION['ZWIN_DRZEWO']) {
			echo App::link("ROZWIN", "?ROZWIN_DRZEWO=1&id={$id_proces}#tree");
		} else {
			echo App::link("ZWIN", "?ZWIN_DRZEWO=1&id={$id_proces}#tree");
		}
		echo " / ";

		$js = "window.location.href='#TREE'+this.form.id.value;return false;";
		echo '<form style="display:inline" action="#" method="GET">';
			echo "Zasob ID: ";
			echo'<input type="text" name="id" value="" />';
			echo'<button onclick="'.$js.'">'."Wyszukaj ID".'</button>';
		echo'</form>'."\n";

	tree_listuj_zasoby(0,0,0);
	echo'</pre>';
}


function fun_SHOW_EXTERNAL_IMAGE() {
	$remote_table = V::get('tbl', '', $_REQUEST);
	$remote_id = V::get('id', '', $_REQUEST, 'int');
	$number = V::get('number', '', $_REQUEST, 'int');
	$imageResize = V::get('resize', '', $_REQUEST);
	$DBG = (V::get('DBG', 0, $_REQUEST, 'int') > 0);

	if ($remote_id <= 0) {
		header('HTTP/1.1 400: Bad Request');
		header('Warning: wrong ID L.' . __LINE__);
		exit;
	}

	if (!DB_Image::tableIsAllowed($remote_table)) {
		header('HTTP/1.1 400: Bad Request');
		header('Warning: table not allowed L.' . __LINE__);
		exit;
	}

	$image_row = DB_Image::getImage($remote_table, $remote_id, $number);
	if (!$image_row) {
		header('HTTP/1.1 400: Bad Request');
		header('Warning: image not found in db L.' . __LINE__);
		exit;
	}

	$etag = md5($image_row->ID . $image_row->A_CREATE_DATE_TS);
	if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $image_row->A_CREATE_DATE_TS
		|| trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) {
		//header("HTTP/1.1 304 Not Modified");
		//exit;
	}
	$expire_date = mktime(0, 0, 0, date('m') + 3, date('d'), date('Y'));

	$maxWidth = 0;
	$maxHeight = 0;
	if ($imageResize) {
		list($maxWidth, $maxHeight) = explode('x', $imageResize, 2);
		$maxWidth = intval($maxWidth);
		$maxHeight = intval($maxHeight);
		if ($maxWidth <= 0 || $maxHeight <= 0) {
			header('HTTP/1.1 400: Bad Request');
			echo'ERROR wrong param resize (WxH)';
			exit;
		}
	}

	if (!$DBG) {
		header("Content-type: {$image_row->TYPE}");
		header("Cache-control: public");
		header("Pragma: public");// default 'no-cache'
		header("Etag: {$etag}");
		if (!$imageResize) {
			header("Content-length: {$image_row->SIZE}");
		}
		header("Expires: " . gmdate("D, d M Y H:i:s", $expire_date) . " GMT");
		header("Last-Modified: " . gmdate("D, d M Y H:i:s", $image_row->A_CREATE_DATE_TS) . " GMT");
	}
	if ($imageResize) {
		print DB_Image::resizeImageFromBlob($image_row->IMAGE, $image_row->TYPE, $maxWidth, $maxHeight);
	} else {
		print $image_row->IMAGE;
	}
	exit;
}


function fun_SHOW_IMAGE() {
	$image_id = V::get('image_id', 0, $_REQUEST, 'int');

	if ($image_id <= 0) {
		header('HTTP/1.1 400: Bad Request');
		header('Warning: wrong id ' . __LINE__);
		exit;
	}

	$image_row = DB_Image::getImageById($image_id);
	if (!$image_row) {
		header('HTTP/1.1 400: Bad Request');
		header('Warning: image not found in db L.' . __LINE__);
		exit;
	}

	header("Content-type: ".$image_row->TYPE);
	header("Content-length: ".$image_row->SIZE);
	print $image_row->IMAGE;
	exit;
}


function fun_IMAGE_ADD() {
	$remote_table = V::get('tbl', '', $_REQUEST);
	$remote_id = V::get('id', 0, $_REQUEST, 'int');
	$task = V::get('task', '', $_REQUEST);

	$thiss = new stdClass();
	$thiss->DETECT_TABLE_NAME = $remote_table;
	$errors = array();
	$msgs = array();

	// check remote id
	if ($remote_id <= 0) {
		echo'<p>';
			echo "Error wrong ID";
			echo'<br />';
			//echo App::link();// TODO: link do ???
		echo'</p>';
		return;
	}

	// check remote table
	if (!DB_Image::tableIsAllowed($remote_table)) {
		$errors[] = "Error table not allowed to add image";
	}

	// task
	$task = V::get('task', '', $_REQUEST);
	if ($task == 'REMOVE') {// TODO: przerobic na funkcje, zwrocic msg, pokazac w body
		$req = array();
		$req['ID'] = V::get('ID', '', $_REQUEST, 'int');
		$req['REMOTE_ID'] = V::get('REMOTE_ID', '', $_REQUEST, 'int');
		$req['REMOTE_TABLE'] = V::get('REMOTE_TABLE', '', $_REQUEST);
		// validate
		if ($req['ID'] <= 0) {
			$errors[] = 'error ID';
		}

		if ($req['REMOTE_ID'] <= 0) {
			$errors[] = 'error REMOTE_ID';
		}

		if ($req['REMOTE_TABLE'] != $remote_table) {
			$errors[] = 'error REMOTE_TABLE';
		}

		if (empty($errors)) {
			$affected = DB_Image::deleteImage($req['ID'], $req['REMOTE_TABLE'], $req['REMOTE_ID']);
			if ($affected == 1) {
				$msgs[] = '<p>'."Usunieto zdjecie ID=".$req['ID'].'</p>';
			} else {
				$erros[] = '<p>'."Wystapil blad podczas usuwania zdjecia ID=".$req['ID'].'</p>';
			}
		}
	}

	// check if a file was submitted
	if (!isset($_FILES['userfile'])) {
		//echo '<p>Please select a file</p>';
	}
	else {
		$errors = DB_Image::uploadImage($remote_table, $remote_id, $_FILES['userfile']);
		// give praise and thanks to the php gods
		if (empty($errors)) {
			$msgs[] = '<p>Thank you for submitting</p>';
		} else {
			$msgs[] = '<p style="border:1px solid red;">' . "Sorry, could not upload file:" . '<br />' . implode('<br />', $errors) .'</p>';
		}
	}

	$title = 'Dodaj plik do rekordu ID='.$remote_id.' z tabeli '.$remote_table;

	lay_procesy_gora();

	echo'<h3>'.$title.'</h3>';

	// show masgs
	if (!empty($msgs)) {
		echo'<div class="box box-green">';
			echo implode('<br />', $msgs);
		echo'</div>';
	}

	// show errors
	if (!empty($errors)) {
		echo'<div class="box box-red">';
			echo implode('<br />', $errors);
		echo'</div>';
		echo'<br /><br />'.'<a href="javascript:window.close()">'."Zamknij to okno".'</a>';
		return;
	}

	echo'<div class="box box-silver">';
	echo'<form enctype="multipart/form-data" action="" method="post">';
		echo'<input type="hidden" name="function_init" value="'. __FUNCTION__ .'" />';
		echo'<input type="hidden" name="REMOTE_ID" value="'.$remote_id.'" />';
		echo'<input type="hidden" name="REMOTE_TABLE" value="'.$remote_table.'" />';
		//echo'<input type="hidden" name="MAX_FILE_SIZE" value="10000000" />';

		echo"Rodzaj obrazka: ";
		echo'<input type="text" name="'."DEST".'" value="'."".'" />';
		$select_arr = array();
		$select_arr = DB_Image::conf_get_options($thiss->DETECT_TABLE_NAME);

		if (!empty($select_arr)) {
			echo' ';
			$js = "if(this.selectedIndex>0){this.form.DEST.value=this.value}";
			echo'<select onchange="'.$js.'">';
				echo'<option value="">'."Wybierz".'</option>';
			foreach ($select_arr as $key => $val) {
				echo'<option value="'.$key.'">'.$val.'</option>';
			}
			echo'</select>';
		}
		echo'<br />';
		echo'<input name="userfile" type="file" />';
		echo'<br />';
		echo'<input type="submit" value="'."Dodaj obrazek".'" />';
	echo'</form>';
	echo'</div>';// .box-silver


// TODO: show images, mv to function {
	$images = DB_Image::getImages($thiss->DETECT_TABLE_NAME, $remote_id);

	echo'<div class="box box-blue" style="overflow:hidden">';
	if (empty($images)) {
		echo'<p class="err">'."Brak obrazkow".'</p>';
	} else {
		echo'<h3>'."Wgrane pliki:".'</h3>';
		foreach ($images as $r) {
			$link_src = '?function_init=fun_SHOW_IMAGE&image_id='.$r->ID.'&HEADER_NOT_INIT=YES';
			$st = array();
			if ($r->WIDTH > 100 || $r->HEIGHT > 100) {
				if ($r->WIDTH > $r->HEIGHT) {
					$st[] = 'width:100px';
				} else {
					$st[] = 'height:100px';
				}
			}
			$st = (empty($st))? '' : ' style="'.implode(';', $st).'"';
			echo'<table style="float:left;border:1px solid silver;">';
			echo'<tr>';
				echo'<td>';
					echo''.$r->NAME.'<br />';
					echo''.$r->DEST.'<br />';
					echo''.$r->A_CREATE_DATE.'<br />';
					echo''.DB_Image::showSize($r->SIZE).' '.$r->WIDTH.'x'.$r->HEIGHT.'<br />';
					echo'<img src="'.$link_src.'" '.$st.'/>';
				echo'</td>';
			echo'</tr>';
			echo'<tr>';
				echo'<td style="text-align:center;">';

					echo'<form action="" method="post" style="display:inline">';
						echo'<input type="hidden" name="task" value="'."REMOVE".'" />';
						echo'<input type="hidden" name="ID" value="'.$r->ID.'" />';
						echo'<input type="hidden" name="REMOTE_ID" value="'.$remote_id.'" />';
						echo'<input type="hidden" name="REMOTE_TABLE" value="'.$remote_table.'" />';
						$js = "if(!confirm('Czy na pewno chcesz usunac obrazek?')) return false;";
						echo'<input type="submit" value="Usun" onclick="'.$js.'" />';
					echo'</form>';

if (0) {// TODO: edytuj
					echo'<form action="" method="post" style="display:inline">';
						echo'<input type="hidden" name="task" value="'."EDIT".'" />';
						echo'<input type="hidden" name="ID" value="'.$r->ID.'" />';
						echo'<input type="hidden" name="REMOTE_ID" value="'.$remote_id.'" />';
						echo'<input type="hidden" name="REMOTE_TABLE" value="'.$remote_table.'" />';
						echo'<input type="submit" value="Edytuj" />';
					echo'</form>';
}

				echo'</td>';
			echo'</tr>';
			echo'</table>';
		}
	}
	echo'</div>';// .box-blue
// } function show images

	echo'<br /><br />'.'<a href="javascript:window.close()">'."Zamknij to okno".'</a>';

	die("\n".'<!-- EOF L.' . __LINE__ . ' -->');
}


// http://se.dev.webone.pl/se-dev/procesy5.php?function_init=fun_SHOW_VIDEO&id=2314&task=CRM_PROCES
function fun_SHOW_VIDEO() {
	$zasob_id = V::get('id', '', $_GET);
	$zasob = DB::get_by_id('CRM_LISTA_ZASOBOW', $zasob_id);

	if ($zasob->TYPE != 'PLIK') {
		die('Wrong type!');
	}
	$movie_ext = array('avi', 'mov', 'm4v');
	if (!in_array(end(explode('.', $zasob->DESC)), $movie_ext)) {
		die('Wrong file name!');
	}

	$zasob_parent = DB::get_by_id('CRM_LISTA_ZASOBOW', $zasob->PARENT_ID);
	if (!$zasob_parent) {
		die('Parent not exists!');
	}

	$zasob_parent2 = DB::get_by_id('CRM_LISTA_ZASOBOW', $zasob_parent->PARENT_ID);
	if (!$zasob_parent2) {
		die('Parent2 not exists!');
	}

	echo'<p>'."[".$zasob->ID."] ".'<i>'.$zasob->TYPE.'</i> '.$zasob->DESC.'</p>';
	echo'<p>'."[".$zasob_parent->ID."] ".'<i>'.$zasob_parent->TYPE.'</i> '.$zasob_parent->DESC.'</p>';
	echo'<p>'."[".$zasob_parent2->ID."] ".'<i>'.$zasob_parent2->TYPE.'</i> '.$zasob_parent2->DESC.'</p>';

	exit;
}


//     ========    TREE    =========


DEBUG_S(5,'SES.USER_PARAMS', $_SESSION['USER_PARAMS'], __FILE__, __FUNCTION__, __LINE__);
DEBUG_S(6,'SES', $_SESSION, __FILE__, __FUNCTION__, __LINE__);
DEBUG_S(6,'SRV', $_SERVER, __FILE__, __FUNCTION__, __LINE__);

echo'<br>.';
lay_procesy_dol();


function lay_procesy_dol() {
	if (1 == V::get('HIDE_PANEL', 0, $_REQUEST, 'int')) {
		return;
	}
	UI::dol();
}


function lay_procesy_user_panel() {
	//echo 'ST-"'.ini_get('session.gc_maxlifetime').'", req_time="'.date('H:i:s').'", end_time="'.date('H:i:s', time() + ini_get('session.gc_maxlifetime')).'", ID="'.session_id().'"<br />'."\n";
	if (!V::get('SHOW_PANEL', '', $_SESSION['USER_PARAMS'])) {
//		return;
	}
	if (1 == V::get('HIDE_PANEL', 0, $_REQUEST, 'int')) {
		return;
	}

	UI::menu();
	return;

	echo "\n".'<div id="GORA">'."\n";
	echo'<table cellspacing="0" cellpadding="0" style="width:100%"><tbody>';
		echo'<tr>';
			echo '<th class="logo" style="width:5%; white-space:nowrap;">';
			echo '<a href="index.php">SE</a>';
			echo ' / ';
			echo App::link("ODSWIEZ", '');
		echo'</th>';
		echo'<td class="main-menu">';// center

$menu = array();
/*
 * ADM_ADMIN_LEVEL = 6;
 * A_STATUS = 'WAITING';
 * ADM_ACCOUNT = 'Kandydat';
 * ADM_AREA = 'KANDYDAT';
 * ADM_ADMIN_DESC = 'Kandydat';
 */
if (User::get('ADM_ADMIN_LEVEL') == 6) {
	$menu ['CRM_TESTY'] = array("TESTY", "?task=CRM_TESTY", array('title'=>'Wyswietlenie testów'));
} else {
	$menu ['CRM_PROCES'] = array("PROCESY", array('task'=>'CRM_PROCES'), array('title'=>'Wyswietlenie procesow'));
	$menu ['CRM_LISTA_ZASOBOW'] = array("ZASOBY", "?task=CRM_LISTA_ZASOBOW", array('title'=>'Wyswietlenie zasobow'));
	$menu ['CRM_WYSWIETL_OBOWIAZKI'] = array("OBOWIAZKI", "?task=CRM_WYSWIETL_OBOWIAZKI", array('title'=>'Wyswietlenie OBOWIAZKOW'));
	$menu ['CRM_TESTY'] = array("TESTY", "?task=CRM_TESTY", array('title'=>'Wyswietlenie testów'));
	if (User::hasAccess('testy_wyniki_read')) {
		$menu ['CRM_TESTY_WYNIKI'] = array("WYNIKI", "?task=CRM_TESTY_WYNIKI", array('title'=>'Wyswietlenie wyników testów'));
	}
	$menu ['USERS'] = array("KONTAKTY", "?task=USERS", array('title'=>'Kontakty'));
}

foreach ($menu as $k_task => $v_menu) {
	if ($k_task == App::get_task()) $v_menu[2] ['class'] = 'current';
	echo App::link($v_menu[0], $v_menu[1], $v_menu[2]);
}

		echo'</td>'."\n";
		echo'<td class="user" style="text-align:right">'."\n";
			{
				$q = V::get('q', '', $_REQUEST);
				echo '<form action="' . "?task=CRM_SEARCH" . '" method="post" class="panel-search">';
					//echo '<input type="hidden" name="task" value="CRM_SEARCH" />';
					echo '<input type="text" name="q" value="' . htmlspecialchars($q) . '" class="q" />';
					echo '<input type="image" src="icon/search.png" class="s" />';
				echo '</form>';
				echo' | ';
			}
			S::show_session_timer();
			//echo'<a href="?function_init=SCREEN">Ekran</a> | ';
			if (V::get('DEBUG', '', $_SESSION)) {
				echo'<b title="'.$_SESSION['DEBUG'].'">DBG('.$_SESSION['DEBUG'].')</b>';
				$js = "if(jQuery(document.body).hasClass('show-DEBUG_S')){jQuery(document.body).removeClass('show-DEBUG_S');this.innerHTML='+';}else{jQuery(document.body).addClass('show-DEBUG_S');this.innerHTML='-'};return false;";
				echo ' <a href="#" onclick="' . $js . '">' . "+" . '</a>';
				echo' | ';
			}
			echo App::link($_SESSION['AUTHORIZE_USER'], array('task'=>"USER"), array('title'=>$_SESSION['ADM_ACCOUNT']));
			echo' | '.User::get('ADM_ADMIN_LEVEL').'';
			echo' | ';
			echo App::link("Wyloguj", "?LOGIN=LOGOUT");
		echo'</td>';
	echo'</tr></tbody></table>';
	echo "\n".'</div>'."\n";// #GORA
}


function lay_procesy_css() {
	return '<style type="text/css">' . "\n" . "
body { margin:0; font-size:small; }
#body_content { padding:10px; }
#body_content h1{ margin:13px 0;color:#000; }
#body_content h1 a{ color:#C53000; }

.err{color:#f00;}
p {margin:6px 0;}
li p {margin:3px 0;}

.panel-search {display:inline; margin:0; padding:0;}
 .panel-search .q {margin:0 2px; padding:0 5px; border:0; background:#eee;}
 .panel-search .s {margin:0 2px; padding:0; border:0; vertical-align:bottom;}

.tbl-view th,
.tbl-view td {font-size:small;border-color:#eee;padding:0 1px;}
.tbl-view thead th,
.tbl-view thead td {background:#f3f3f3;}
.tbl-view tbody tr:hover td {background:#E6FFE6;}
.tbl-view tbody tr.row-0 {background:#f3f3f3;}
.tbl-view tbody tr.row-1 {background:#fff;}
.tbl-view tbody th {text-align:center;}
.tbl-view tbody td {padding:0 2px;}
.tbl-view form {margin:0;padding:0;}
.tbl-view .find th,
.tbl-view .find td,
.tbl-view tfoot th,
.tbl-view tfoot td {background:#E3E3E3;}
.tbl-view .i {margin:0;padding:0;border:1px solid #999;}
.tbl-view .add td .i,
.tbl-view .find td .i {width:100%;}
.tbl-view .find td.selected {border-bottom:2px solid #FF0000;}

.tbl-wsk-view{border-collapse:separate;border:1px solid #fff;}
.tbl-wsk-view th,
.tbl-wsk-view td{padding:0px;border-spacing:1px;background:#E6FFE6;font-size:small;border:1px solid #008000;}
.tree-wrap dd .tbl-wsk-view{margin:0 0 0 10px;}
.tree-wrap .tbl-wsk-view .btn-box{margin:0;}
.tree-wrap .wsk-cell{background:#fff;padding:2px;}

#GORA {margin:0;padding:0;background:#000;color:#fff;border-bottom:2px solid #969696;overflow:hidden;}
/*
#GORA {position:fixed;top:0;left:0;width:100%;}
*/
 #GORA a {margin:0;padding:0px;color:#fff;text-decoration:none;font-size:12px;}
 #GORA a:hover {text-decoration:underline;}
 #GORA th, #GORA td {color:#fff;font-size:12px;}
 #GORA th.logo {padding:2px 3px;background:#C53000;}
 #GORA td.user {padding:2px 3px;}
 #GORA .main-menu {}
 #GORA .main-menu {margin:0;padding:0;list-style:none;}
 #GORA .main-menu li {margin:0;padding:0;display:inline;}
  #GORA .main-menu a {display:block;float:left;margin:0;padding:4px;text-decoration:none;border-top:3px solid #000;font-size:12px;font-weight:bold;font-family:arial;}
  #GORA .main-menu a:hover {border-color:#C53000;text-decoration:none;background:#555;}
  #GORA .main-menu a.current {border-color:#C53000;}
  #GORA .main-menu a.last {border-top:2px solid #C53000;}

fieldset.main { border:1px solid #000; }
fieldset.main, fieldset.main legend { background-color:#eee; }
fieldset.main legend { padding:0 5px; border:1px solid #000; }

p.sql-msg { color:green; }
p.sql-msg-err { color:red; }

tr.add  { background-color:#eee; }
tr.edit { background-color:#ffa; }

a.external {padding:0 13px 0 0;background: url(icon/external.png) center right no-repeat;}
a.btn-p5 {background:#eee;color:#000;text-decoration:none;font-weight:bold;padding:0 3px;border:1px solid #666;white-space:nowrap;}
a.btn-p5:hover {background:#eee;color:#00f;}
a.btn-clean {background:#fff;color:#00f;text-decoration:none;font-weight:bold;padding:0;border:none;}
a.btn-clean:hover {background:#fff;color:#f00;}

a.btn-sm {font-size:x-small;}

.P_ID {color:#f00;}
.P_ID_ACCESS {color:#0E7E0E;}
.P_ID_MAP {color:#A020F0;}
.ALIAS_ID {color:#FF6900;}

.red{color:#f00;}
.green{color:#008000;}
.blue{color:#00f;}
.silver{color:#666;}

.box{border:1px solid #999;padding:5px;margin:5px;}
.box-center{border:1px solid #999;padding:5px;margin:5px auto;}
.box-silver{border-color:#999;}
.box-red{border-color:#f00;}
.box-blue{border-color:#00f;}
.box-green{border-color:#008000;}
.box-hover-active{background:#fff;border-color:#999;}
.box-hover-active:hover{background:#eee;border-color:#000;}
.cmnt {color:#eee;}
.cmnt-small {font-size:small;color:#eee;}

#body_content .pathway{margin:0 0 10px 0;padding:3px 8px;border:1px solid #aaa;font-size:medium;font-weight:bold;background-color:#efefef;}
#body_content .pathway a{text-decoration:none;}
#body_content .pathway a:hover{text-decoration:underline;}

.flexigrid{font-size:small;}
.flexigrid td,
.flexigrid th{font-size:small;}
.flexigrid .tDiv .add { background:url(stuff/i/add.png) no-repeat center left; }
.flexigrid .tDiv .delete { background:url(stuff/i/del.png) no-repeat center left; }
.flexigrid .tDiv .edit { background:url(stuff/i/edit.gif) no-repeat center left; }

.filters{margin:0;padding:2px;background:#F0F0F0 url(./stuff/flexigrid/css/images/bg.gif) repeat-x top;border:1px solid #ccc;border-style:solid solid none solid;clear:both;overflow:hidden;}
.filters {font-size:13px; line-height:16px;}
.filters input {font-size:13px; line-height:16px;}
.filters .btnseparator{float:left;height:22px;border-left:1px solid #CCC;border-right:1px solid #fff;margin:1px;}
.filters form{margin:0;padding:0;}
.filters nobr{display:block;float:left;margin:0;padding:2px;font-weight:normal;font-size:13px;}
.filters nobr:hover{text-decoration:underline;}
.filters nobr.active{color:#f00;font-weight:normal;}
.filters nobr input,
.filters nobr select,
.filters nobr button{margin:0 1px;padding:0 2px;font-size:13px;}

.btn-box{margin:0 2px 0 0;padding:0 3px;background:#bbb;color:#fff;text-decoration:none;border:0;font-weight:bold;}
.btn-box-blue{background:#3A3AFF;color:#fff;}
.btn-box-green{background:#008A00;color:#fff;}
.btn-box-lgreen{background:#97CF97;color:#fff;}
.btn-box-red{background:#FF4646;color:#fff;}
.btn-box-group1{background-color:#9F9FCB;color:#fff;}
.btn-box-group2{background-color:#B8B879;color:#fff;}
/*.tree-wrap .btn-p5{border-radius:3px;-webkit-border-radius:3px;-moz-border-radius:3px;}*/
/*.btn-box{border-radius:3px;-webkit-border-radius:3px;-moz-border-radius:3px;}*/

.user-menu-tree {color:#666;font-weight:normal;}
.user-menu-PROCES_INIT {color:#f00;font-weight:bold;}

" . '</style>' . "\n";
}

function view_CRM_PROCES_Helper__get_class($procesType) {
	switch ($procesType) {
		case 'PROCES_INIT': return 'red';
		case 'PROCES_GROUP_1': return 'group1';
		case 'PROCES_GROUP_2': return 'group2';
		default: return null;
	}
}

function tree_callback__show_item_from_CRM_PROCES( &$r, &$tree ) {
//	$dbg=debug_backtrace();
//	DEBUG_S(-3,'backtrace',$dbg);
	$db = DB::getDB();
	$wsk = array();
	Lib::loadClass('ProcesHelper');
	$tree->log('show item - start');
	if ($tree->get_param('rozwin_proces')) {
		$wsk = ProcesHelper::get_wskazniki($r->ID);
		$tree->log('show item -> get_wskazniki', array('get_wskazniki'));

		foreach ($wsk as $idx => $w) $wsk[$idx]->ACL_TYPE = in_array($w->TYPE, ['STANOWISKO', 'DZIAL', 'PODMIOT']) ? 'GROUP' : '';

		// UI::table([ 'rows' => array_map(function ($w) {
		// 	unset($w->path);
		// 	unset($w->OPIS);
		// 	return (array)$w;
		// }, $wsk) ]);
		$fixedWskList = array();
		foreach ($wsk as $w) {
			if ('GROUP' == $w->ACL_TYPE) $fixedWskList[] = $w;
		}
		if ('PROCES_INIT' == $r->TYPE) {// fetch INHERIT acl groups
			$idGroups = array_reduce($wsk, function ($carry, $w) {
				if ('GROUP' != $w->ACL_TYPE) return $carry;
				return (!empty($carry)) ? "{$carry},{$w->ID}" : $w->ID;
			}, "");
			$sqlFilterIdGroups = (!empty($idGroups)) ? " and gp.ID_GROUP not in({$idGroups})" : "";
			foreach (DB::getPDO()->fetchAll("select z.ID
					, z.PARENT_ID
					, z.`TYPE`
					, z.`DESC`
					, 'INHERIT' as ACL_TYPE
				from CRM_PROCES_idx_GROUP_to_PROCES gp
					join CRM_LISTA_ZASOBOW z on(z.ID = gp.ID_GROUP)
				where gp.ID_PROCES = {$r->ID}
					{$sqlFilterIdGroups}
			") as $aclW) {
				$fixedWskList[] = (object)$aclW;
			}
		}
		foreach ($wsk as $w) {
			if ('GROUP' != $w->ACL_TYPE) $fixedWskList[] = $w;
		}
		$wsk = $fixedWskList;
		$tree->log('show item -> get_wskazniki inherit', array('get_wskazniki'));
	}

	$pytania = array();
	$tblPytaniaId = $tree->get_param('PytaniaTblId');
	if ($tree->get_param('editable') && $tree->get_param('HasAclPytaniaTbl')) {
		$userAcl = User::getAcl();
		$tblAcl = $userAcl->getTableAcl($tblPytaniaId);
		$params = array();
		$params['f_ID_PROCES'] = $r->ID;
		$pytania = $tblAcl->getDataSource()->getItems($params);
		$tree->log('show item -> fetch-pytania', array('fetch-pytania'));
	}

	$show_form = ($tree->get_param('show_form_at_item') == $r->ID);
	$show_form = ($tree->get_param('show_form_at_item') > 0);// TODO: RMME
	$cls = array();
	if (($search_id = $tree->get_param('search_id')) > 0 && $search_id == $r->ID) {
		$cls[] = 'search_id';
	}
	$cls = (!empty($cls))? ' class="'.implode(' ', $cls).'"' : '';
	echo '<dl'.$cls.'>';
	echo '<dt>';

	if (!empty($wsk)) echo'<div class="has_wsk">';

	$out_id = ($r->ID < 10) ? "&nbsp;{$r->ID}" : $r->ID;
	$proces_type_css_class = view_CRM_PROCES_Helper__get_class($r->TYPE);
	echo App::link($out_id, [
		'task' => "CRM_PROCES",
		'filtr_id' => $r->ID,
		'#' => "TREE{$r->ID}"
	], [
		'class' => implode(' ', [
			'item_id',
			'btn-box',
			($proces_type_css_class) ? "btn-box-{$proces_type_css_class}" : ''
		])
	]);

	//if($r->TYPE == 'PROCES_INIT')  {
	$tree->log('show item -> fetch-IF_TRUE_GOTO start');
	$gotoList = ProcesHelper::getGoToProces($r->ID);
	foreach ($gotoList as $gotoId => $gotoFlag) {
		$popupIcon = 'glyphicon glyphicon-chevron-left';
		$popupLink = "procesy5.php?task=PROCES_VIEW&id_proces={$gotoId}";
		$popupTitle = "GOTO";
		$popupContent = "{$gotoId} {$gotoFlag} {$r->ID}";
		$linkStyle = '';
		if ('popover' == $linkStyle) {
			echo UI::h('a', [ 'href' => $popupLink ], [
				UI::h('span', [ 'class' => "wsk-help popover-with-html p5-L" . __LINE__ ], [
					UI::h('i', [ 'class' => $popupIcon ]),
					UI::h('span', [ 'class' => "popover-heading" ], $popupTitle),
					UI::h('span', [ 'class' => "popover-body" ], $popupContent),
				]),
				$gotoId,
			]);
		} else {
			echo ' ';
			echo App::link("&lt;{$gotoId}", array('task'=>'PROCES_VIEW', 'id_proces'=>$gotoId), array('title'=>$popupContent));
			echo ' ';
		}
	}
	$tree->log('show item -> fetch-IF_TRUE_GOTO', array('fetch-IF_TRUE_GOTO'));
	//}

	//echo App::link("&#9873;", array('task'=>"CRM_PROCES", 'filtr_id'=>$r->ID, '#'=>'TREE'.$r->ID), array('class'=>''));
	//echo App::link("&#9872;", array('task'=>"CRM_PROCES", 'filtr_id'=>$r->ID, '#'=>'TREE'.$r->ID), array('class'=>''));
	if ($tree->get_param('editable')) {
		//echo'('.$r->SORT_PRIO.')';//TODO: DBG
		echo App::link("<b>^</b>", array('task'=>'CRM_PROCES', 'function_init'=>'SORT_PRIO_PROCES', 'arg1'=>$r->ID, 'arg1_val'=>'upup','#'=>'TREE'.$r->ID), array('class'=>"btn-clean", 'title'=>"w gore o 5 pol"));
		echo App::link("^", array('task'=>'CRM_PROCES', 'function_init'=>'SORT_PRIO_PROCES', 'arg1'=>$r->ID, 'arg1_val'=>'up','#'=>'TREE'.$r->ID), array('class'=>"btn-clean", 'title'=>"w gore"));
		echo App::link("v", array('task'=>'CRM_PROCES', 'function_init'=>'SORT_PRIO_PROCES', 'arg1'=>$r->ID, 'arg1_val'=>'dw','#'=>'TREE'.$r->ID), array('class'=>"btn-clean", 'title'=>"w dol"));
		echo App::link("V", array('task'=>'CRM_PROCES', 'function_init'=>'SORT_PRIO_PROCES', 'arg1'=>$r->ID, 'arg1_val'=>'downdown','#'=>'TREE'.$r->ID), array('class'=>"btn-clean", 'title'=>"w dol o 5 pol"));
		echo' ';

		if ($tree->get_param('ProcesTblId') > 0) {
			// rem@2016-08 sqix link do nowy edytor:
			if($r->TYPE == 'PROCES_INIT') {
				echo App::link("E", "index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=".$tree->get_param('ProcesTblId')."#EDIT/".$r->ID, array('title'=>'Edytuj', 'class'=>'btn-p5'));
				echo App::link("e", "index.php?_route=UrlAction_ProcesEditor&id=".$r->ID, array('title'=>'Edytuj', 'class'=>'btn-p5'));
			} else {
				echo App::link("E", "index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=".$tree->get_param('ProcesTblId')."#EDIT/".$r->ID, array('title'=>'Edytuj', 'class'=>'btn-p5'));
			}

		}
		else {
			echo App::link("E", array('task'=>"CRM_PROCES", 'EDIT'=>$r->ID), array('title'=>'Edytuj', 'class'=>'btn-p5'));
		}
		if ($tree->get_param('ProcesTblId') > 0) {
			echo App::link("F", "index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=".$tree->get_param('ProcesTblId')."#FILES/".$r->ID, array('title'=>'Pliki', 'class'=>'btn-p5'));
		}

		if (!in_array($r->TYPE, array('PROCES_GROUP_1', 'PROCES_GROUP_2'))) {
			if (!$r->TEST_PYTANIE) {
				echo App::link("P+", array('task'=>"CRM_TESTY_ADD_PYTANIA", 'id_proces'=>$r->ID), array('title'=>'Dodaj pytanie do testow', 'class'=>'btn-p5 btn-red'));
			} else {
				echo App::link("P+", array('task'=>"CRM_TESTY_ADD_PYTANIA", 'id_proces'=>$r->ID), array('title'=>'Dodaj pytanie do testow', 'class'=>'btn-p5'));
				if (!empty($pytania)) {
					foreach ($pytania as $pytanie) {
						if ($tree->get_param('rozwin_proces') && $pytanie->ID_WSKAZNIK != 0) {
							continue;
						}
						$odpowiedzi = array();
						for ($i = 0; $i < 5; $i++) {
							$fldTxt = "ODP_{$i}";
							$fldOdp = "ODP_{$i}_ODP";
							if (!empty($pytanie->{$fldTxt})) {
								if ($pytanie->{$fldOdp} == 'TAK') {
									$odpowiedzi[] = '<span class="text-success">' . htmlspecialchars($pytanie->{$fldTxt}) . '</span>';
								} else {
									$odpowiedzi[] = '<span class="text-error">' . htmlspecialchars($pytanie->{$fldTxt}) . '</span>';
								}
							}
						}
						$popupIcon = ($pytanie->TEST_TYPE=='TEORETYCZNY')? 'glyphicon glyphicon-question-sign' : 'glyphicon glyphicon-exclamation-sign';
						$popupLink = "index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID={$tblPytaniaId}&task=CRM_PROCES#EDIT/{$pytanie->ID}";// TODO: add rand _hash?
						$popupTitle = "#{$pytanie->ID} " . htmlspecialchars($pytanie->PYTANIE);
						$popupContent = implode('<hr style="margin:0.5em 0;">', $odpowiedzi);
						?>
							<a target="_blank" href="<?= $popupLink; ?>"><i class="<?= $popupIcon; ?> wsk-help popover-with-html p5-L<?= __LINE__; ?>">
								<div class="popover-heading"><?= $popupTitle; ?></div>
								<div class="popover-body"><?= $popupContent; ?></div>
							</i></a>
						<?php
					}
				}
			}
		}
	}

	$bold = false;
	if ((!empty($_GET['arg1']) && $_GET['arg1'] == $r->ID)
		|| (!empty($_GET['EDIT']) && $_GET['EDIT'] == $r->ID)
	) {
		$bold = true;
	}
	//if ($bold) echo "***";

	if ($r->IF_TRUE_GOTO > 0) {
		$tree->log('show item -> fetch-proces_flag - start');
		$link_out = ProcesHelper::proces_flag($r->ID, $r->IF_TRUE_GOTO, $r->IF_TRUE_GOTO_FLAG);
		$tree->log('show item -> fetch-proces_flag', array('fetch-proces_flag'));
		echo App::link($link_out, "#TREE".$r->IF_TRUE_GOTO, array('onclick'=>"return scrollToProces('".$r->IF_TRUE_GOTO."');", 'title'=>$r->IF_TRUE_GOTO_FLAG." ".$r->IF_TRUE_GOTO, 'class'=>'btn-p5'));
		echo "<a href=procesy5.php?task=PROCES_VIEW&id_proces=".$r->IF_TRUE_GOTO.">&gt;&gt;</a>";
		if (empty($r->DESC)) {
			$sql = "select `DESC`,`OPIS` from CRM_PROCES where ID='".$r->IF_TRUE_GOTO."' limit 1";
			$rs = DB::query($sql);
			while ($h = DB::fetch($rs)) {
				echo "<font color=grey><b>".$h->DESC."</b>";
				if ($tree->get_param('rozwin_opis') && $h->OPIS) echo ' '.$h->OPIS;
				echo "</font>";
			}
		}
	}

	if ($r->has_childrens) {
		if (!$tree->get_param('rozwin')) {
			$js = "return " . $tree->js_tree_open_rec_fun . "(this," . $r->ID . ");";
			//echo'<a class="open-rec" href="#" onclick="'.$js.'">'."L".'</a>';
			echo App::link("L", '#', array('title'=>'Rozwin wszystko', 'class'=>'btn-p5 open-rec', 'onclick'=>$js));
		}
	}

	echo'<span class="desc">';
		echo UI::h('b', [
			'class' => ($proces_type_css_class) ? "desc-{$proces_type_css_class}" : "",
		], $r->DESC);
		{// status ico
			if ($r->TYPE == 'PROCES_INIT') {
				echo implode(' ', [
					"&nbsp;",
					UI::h('img', [
						'src' => ($r->A_STATUS == 'NORMAL') ? "icon/status-ok.gif" : "icon/status-notok.gif",
						'alt' => $r->A_STATUS,
						'width' => "16",
						'title' => "Status: {$r->A_STATUS} {$r->L_APPOITMENT_DATE}",
						'style' => "vertical-align:middle;cursor:help",
					]),
					UI::h('a', [ 'href' => "procesy5.php?task=PROCES_VIEW&id_proces={$r->ID}&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1",
						'class' => "btn btn-xs btn-default",
						'title' => "Przeglądaj proces {$r->ID} (drzewo)"
					], "P"),
					UI::h('a', [ 'href' => "procesy5.php?task=PROCES_VIEW_LIST&id_proces={$r->ID}&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1",
						'class' => "btn btn-xs btn-default",
						'title' => "Przeglądaj proces {$r->ID} (lista)"
					], "L"),
					UI::h('a', [ 'href' => "index.php?FUNCTION_INIT=GRAPH_VIEW_PROCES&id_proces={$r->ID}",
						'class' => "btn btn-xs btn-default",
						'title' => "Mapa procesu"
					], "M"),
				]);
			} else if ('PROCES_GROUP' === substr($r->TYPE, 0, strlen('PROCES_GROUP'))) {
				echo implode(' ', [
					"&nbsp;",
					// UI::h('a', [ 'href' => "procesy5.php?task=PROCES_VIEW_LIST&id_proces={$r->ID}&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1",
					// 	'class' => "btn btn-xs btn-default",
					// 	'title' => "Przeglądaj proces {$r->ID} (lista)"
					// ], "L"), // Brak upraenień - widok listy tylko dla PROCES_INIT
					UI::h('a', [ 'href' => "index.php?FUNCTION_INIT=GRAPH_VIEW_PROCES&id_proces={$r->ID}&PROCES_INIT_SCAN=1",
						'class' => "btn btn-xs btn-default",
						'target' => "_blank",
					], "M"),
				]);
			}
		}
		//if ($bold) echo "***";
		if ($tree->get_param('editable')) { echo App::link("Z+", "index.php?MENU_INIT=PROCES_ADD_ZASOB&procesID=".$r->ID, array('title'=>'Dodaj', 'class'=>'btn-p5'));
			echo App::link("↵+", "index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=".$tree->get_param('ProcesTblId')."&ff_PARENT_ID=".$r->ID."#CREATE", array('class'=>'btn-p5', 'title'=>'Dodaj dziecko', 'onclick'=>null));
		}
		$opis_before = ''; $opis_after = '';
		$tbl = 'CRM_PROCES';
		if ($tree->get_param('filtr_img')) {
			if ($r->A_HAS_IMAGE) {
				echo'<br />';
				$imgSize = (V::get('show_big_img', '', $_GET))? '600x600' : '200x200';
				for ($i = 0; $i < $r->A_HAS_IMAGE; $i++) {
					$opis_before .= '<a href="'."?function_init=fun_SHOW_EXTERNAL_IMAGE&tbl=".$tbl."&id=".$r->ID."&number=".$i.'" target="_blank" class="lightbox">';
					$opis_before .= '<img src="'."?function_init=fun_SHOW_EXTERNAL_IMAGE&tbl=".$tbl."&id=".$r->ID."&number=".$i."&resize={$imgSize}".'" style="float:left" />';
					$opis_before .= '</a>';
				}
			}
			if ($opis_before != '') $opis_after = '<br style="clear:both"/>';
		}

		echo' <span class="more-desc">';
		echo $opis_before;
		if ($tree->get_param('rozwin_opis') && $r->OPIS) {
			echo ' '.$r->OPIS;
		}
		else if (!empty($r->OPIS)) {
			?>
				<i class="glyphicon glyphicon-info-sign wsk-help popover-with-html p5-L<?= __LINE__; ?>">
					<div class="popover-heading"><?php echo "[{$r->ID}] " . $r->DESC; ?></div>
					<div class="popover-body"><?php echo $r->OPIS; ?></div>
				</i>
			<?php
		 }
		echo $opis_after;
		echo '</span>';

	echo'</span>';

	$tbl = 'CRM_PROCES';
	if ($tree->get_param('filtr_img')) {
		if ($r->A_HAS_IMAGE || $tree->get_param('editable')) {
			echo' <span class="external-ids">{';
			for ($i = 0; $i < $r->A_HAS_IMAGE; $i++) {
				echo App::link("I", array('function_init'=>'fun_SHOW_EXTERNAL_IMAGE', 'tbl'=>$tbl,'id'=>$r->ID, 'number'=>$i), array('target'=>'_blank', 'title'=>"Zdjecie ".($i+1), 'iconBootstrap'=>'glyphicon glyphicon-camera', 'class'=>'lightbox'));
				//echo'<img src="'."?function_init=fun_SHOW_EXTERNAL_IMAGE&tbl=".$tbl."&id=".$r->ID."&number=".$i."&resize=200x200".'" />';
			}
			if ($tree->get_param('editable')) echo App::link("+", "?function_init=fun_IMAGE_ADD&tbl=".$tbl."&id=".$r->ID, array('target'=>'_blank', 'title'=>"Dodaj zdjecia", 'iconBootstrap'=>'glyphicon glyphicon-plus'));
			echo'}</span>';
		}
	}

	if (!empty($wsk)) echo'</div>';// .has_wsk
	echo'</dt>'."\n";

	if (!empty($wsk)) {
		$zasoby_id = array();
		echo'<dd>';
		echo'<ul>';

		if (V::get('group_stanowiska', '', $_GET)) {
			$wsk_stanowiska = array();
			$wsk_inne = array();
			foreach ($wsk as $w) {
				if ($w->TYPE == 'STANOWISKO') {
					$wsk_stanowiska[] = $w;
				} else {
					$wsk_inne[] = $w;
				}
			}

			$wsk = array();
			if (!empty($wsk_stanowiska)) {
				$wsk[] = $wsk_stanowiska;
			}
			if (!empty($wsk_inne)) {
				foreach ($wsk_inne as $w) {
					$wsk[] = $w;
				}
			}
		}

		$wsk_cnt = count( $wsk );
		foreach ($wsk as $w) {
			if (is_array($w)) {// if $_GET['group_stanowiska']
				$stanowiska = array();
				foreach ($w as $vStanowisko) {
					$stanowiska[] = "[{$vStanowisko->ID}] {$vStanowisko->DESC}";
				}
				echo '<li'.((--$wsk_cnt)? '' : ' class="tree-last"').'>';
				echo '<p>';
					echo ' <span class="btn-box btn-box-silver">'."STANOWISKA:".'</span>';
					echo ' <b>' . implode(', ', $stanowiska) . '</b> ';
				echo '</p>';
				echo '</li>';
				continue;
			}

			$w_parents_out = '';
			$w_title_parents_out = '';
			if ($tree->get_param('rozwin_zasoby')) {
				$tree->log('show item -> fetch-get_all_parents - start');
				$w->_parents = TreeHelper::get_all_parents( 'CRM_LISTA_ZASOBOW', $w->PARENT_ID );
				$tree->log('show item -> fetch-get_all_parents', array('fetch-get_all_parents'));
				$w_parents_out = array();
				foreach ($w->_parents as $w_p_id => $w_p) {
					$w_parents_out[] = '[<b>'.$w_p->ID.'</b> '.$w_p->TYPE.' '.$w_p->DESC.']';
					$w_title_parents_out[] = ''.$w_p->ID.' '.$w_p->TYPE.' '.$w_p->DESC.'';
				}
				$w_parents_out = ' <span class="wsk_parents">'.implode(' / ', $w_parents_out).'</span>';
				$w_title_parents_out = (!empty($w_title_parents_out))? implode(' / ', $w_title_parents_out) : '';
			}

			echo'<li'.((--$wsk_cnt)? '' : ' class="tree-last"').'>';
			if ('INHERIT' == $w->ACL_TYPE) {
				UI::startTag('p', ['style' => "color:#aaa", 'title' => "Stanowiska dziedziczone z procesu/ów wywołujących (GOTO)"]);
					UI::tag('span', ['title' => $w_title_parents_out], "[{$w->ID}]");
					echo " {$w->TYPE} ";
					UI::tag('span', [], $w->DESC);
				UI::endTag('p');
				continue;
			} else {

			}

			echo'<p>';
			// echo ' <span class="btn-box btn-box-silver">'.$w->CW_ID.'</span>';
			('GROUP' == $w->ACL_TYPE)
				? UI::startTag('p', ['style' => "color:#daa520"])
				: UI::startTag('p', []);
			('GROUP' == $w->ACL_TYPE)
				? UI::tag('span', ['style' => "color:#daa520", 'title' => $w_title_parents_out], "[{$w->ID}]")
				: UI::tag('span', ['class' => "green", 'title' => $w_title_parents_out], "[{$w->ID}]");

			if ($tree->get_param('editable')) {
				echo App::link("<b>^</b>", array('function_init'=>'SORT_PRIO_WSKAZNIK', 'arg1'=>$w->CW_ID, 'arg1_val'=>'upup','_hash'=>rand(0,9999),'#'=>'TREE'.$r->ID), array('class'=>"btn-clean", 'title'=>"w gore o 5 pol"));
				echo App::link("^", array('function_init'=>'SORT_PRIO_WSKAZNIK', 'arg1'=>$w->CW_ID, 'arg1_val'=>'up','_hash'=>rand(0,9999),'#'=>'TREE'.$r->ID), array('class'=>"btn-clean", 'title'=>"w gore"));
				echo App::link("v", array('function_init'=>'SORT_PRIO_WSKAZNIK', 'arg1'=> $w->CW_ID, 'arg1_val'=>'dw','_hash'=>rand(0,9999),'#'=>'TREE'.$r->ID), array('class'=>"btn-clean", 'title'=>"w dol"));
				echo App::link("V", array('function_init'=>'SORT_PRIO_WSKAZNIK', 'arg1'=> $w->CW_ID, 'arg1_val'=>'downdown','_hash'=>rand(0,9999),'#'=>'TREE'.$r->ID), array('class'=>"btn-clean", 'title'=>"w dol o 5 pol"));
				echo' ';

				if ($tree->get_param('WskaznikTblId')) {
					echo App::link("E", "index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=".$tree->get_param('WskaznikTblId')."#EDIT/".$w->CW_ID, array('title'=>'Edytuj', 'class'=>'btn-p5'));
				} else {
					echo App::link("E", "?task=CRM_EDIT_CRM_WSKAZNIK&EDIT=".$w->CW_ID."&ID=".$w->CW_ID, array('title'=>'Edytuj', 'class'=>'btn-p5'));
				}

				if ($tree->get_param('ZasobTblId') > 0) {
					echo App::link("F", "index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=".$tree->get_param('ZasobTblId')."#FILES/".$w->ID, array('title'=>'Pliki', 'class'=>'btn-p5'));
				}
			}

			if (!empty($pytania)) {
				foreach ($pytania as $pytanie) {
					if ($pytanie->ID_WSKAZNIK != $w->CW_ID) {
						continue;
					}
					$odpowiedzi = array();
					for ($i = 0; $i < 5; $i++) {
						$fldTxt = "ODP_{$i}";
						$fldOdp = "ODP_{$i}_ODP";
						if (!empty($pytanie->{$fldTxt})) {
							if ($pytanie->{$fldOdp} == 'TAK') {
								$odpowiedzi[] = '<span class="text-success">' . htmlspecialchars($pytanie->{$fldTxt}) . '</span>';
							} else {
								$odpowiedzi[] = '<span class="text-error">' . htmlspecialchars($pytanie->{$fldTxt}) . '</span>';
							}
						}
					}
					$popupIcon = ($pytanie->TEST_TYPE=='TEORETYCZNY')? 'glyphicon glyphicon-question-sign' : 'glyphicon glyphicon-exclamation-sign';
					$popupLink = "index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID={$tblPytaniaId}&task=CRM_PROCES#EDIT/{$pytanie->ID}";// TODO: add rand _hash?
					$popupTitle = "#{$pytanie->ID} " . htmlspecialchars($pytanie->PYTANIE);
					$popupContent = implode('<hr style="margin:0.5em 0">', $odpowiedzi);
					echo UI::h('a', [
						'target' => "_blank",
						'class' => "popover-with-html wsk-help",
						'href' => $popupLink,
					], [
						UI::h('i', [ 'class' => "{$popupIcon} p5-L" . __LINE__ ]),
					]);
					?>
							<span class="popover-heading"><?= $popupTitle; ?></span>
							<span class="popover-body"><?= $popupContent; ?></span>
						</a>
					<?php
				}
			}

			if (!empty($w->CP_FORM_TREAT)) echo' <span title="'.$w->CP_PYTANIE.' '.$w->CP_OPIS.'" style="color:#999">'.str_replace(',', '', $w->CP_FORM_TREAT).'</span>';

			echo ' '.$w->TYPE.'';
			echo ' <b>'.$w->DESC.'</b> ';
			if ($tree->get_param('editable')) {
				$js_onclick = "if(!confirm('Czy na pewno usunac wskaznik ".$w->CW_ID." do zasobu ".$w->ID." w procesie ".$r->ID."?')){return false;}";
				echo App::link("Z-", "?task=CRM_DEL_CRM_WSKAZNIK&ID=".$w->CW_ID, array('title'=>'Usun', 'class'=>'btn-p5', 'onclick'=>$js_onclick));
			}

			if ($tree->get_param('filtr_img')) {
				// wskaznik images
				$tbl = 'CRM_WSKAZNIK';
				if ($w->CW_A_HAS_IMAGE > 0 || $tree->get_param('editable')) {
					for ($i = 0; $i < $w->CW_A_HAS_IMAGE; $i++) {
						echo App::link("I", array('function_init'=>'fun_SHOW_EXTERNAL_IMAGE', 'tbl'=>$tbl,'id'=>$w->CW_ID, 'number'=>$i), array('target'=>'_blank', 'title'=>"Zdjecie ".($i+1), 'iconBootstrap'=>'glyphicon glyphicon-camera', 'class'=>'lightbox'));
					}
					if ($tree->get_param('editable')) echo App::link("+", "?function_init=fun_IMAGE_ADD&tbl=".$tbl."&id=".$w->CW_ID, array('target'=>'_blank', 'title'=>"Dodaj zdjecia", 'iconBootstrap'=>'glyphicon glyphicon-plus'));
				}

				// zasob images
				$tbl = 'CRM_LISTA_ZASOBOW';
				if ($w->A_HAS_IMAGE) {
					for ($i = 0; $i < $w->A_HAS_IMAGE; $i++) {
						echo App::link("I", array('function_init'=>'fun_SHOW_EXTERNAL_IMAGE', 'tbl'=>$tbl,'id'=>$w->ID, 'number'=>$i), array('target'=>'_blank', 'title'=>"Zdjecie ".($i+1), 'iconBootstrap'=>'glyphicon glyphicon-camera', 'class'=>'lightbox'));
					}
				}

				// show video link if file is movie type
				if ($w->TYPE == 'PLIK') {
					$movieExtAllowed = array('avi', 'mov', 'm4v');
					$movieExt = explode('.', $w->DESC);
					$movieExt = end($movieExt);
					if (in_array($movie_ext, $movieExtAllowed)) {
						//echo App::link("V", array('function_init'=>'fun_SHOW_VIDEO','id'=>$w->ID), array('target'=>'_blank', 'title'=>"Film", 'ico'=>'video', 'class'=>''));//lightbox video
					}
				}
			}

			if ($tree->get_param('rozwin_opis')) {
				if ($w->TYPE == 'STANOWISKO') {
					if (!empty($w->OPIS)) {
						if (strlen($w->OPIS) > 300) {
							?>
							<!-- Button to trigger modal -->
							<a href="#wsk-<?php echo $w->CW_ID; ?>-Modal" class="wsk-long-desc" data-toggle="modal">
								<i class="glyphicon glyphicon-info-sign" title="Opis stanowiska"></i>
							</a>
							<!-- Modal -->
							<div id="wsk-<?php echo $w->CW_ID; ?>-Modal" class="wsk-modal modal fade" tabindex="-1" role="dialog" aria-labelledby="wsk-<?php echo $w->CW_ID; ?>-ModalLabel" aria-hidden="true">
								<div class="modal-dialog">
									<div class="modal-content">
										<div class="modal-header">
											<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
											<h3 id="wsk-<?php echo $w->CW_ID; ?>-ModalLabel"><?php echo "[{$w->CW_ID}] {$w->DESC}"; ?></h3>
										</div>
										<div class="modal-body">
											<?php echo $w->OPIS; ?>
										</div>
										<div class="modal-footer">
											<button class="btn btn-primary" data-dismiss="modal" aria-hidden="true">Zamknij</button>
										</div>
									</div>
								</div>
							</div>
							<?php
						} else {
							?>
							<i class="glyphicon glyphicon-info-sign wsk-help popover-with-html p5-L<?= __LINE__; ?>">
								<div class="popover-heading"><?php echo "[{$w->CW_ID}] " . $w->OPIS; ?></div>
								<div class="popover-body"><?php echo $w->OPIS_ZASOB; ?></div>
							</i>
							<?php
						}
					}
				} else {
					echo ' <span class="green">'.$w->OPIS.'</span>';// opis zasobu
				}
			}
			if ($tree->get_param('rozwin_opis')) {
				echo ' <span style="color:#000;">'.$w->OPIS_ZASOB.'</span>';// komentarz wskaznika
			}
			else if (!empty($w->OPIS_ZASOB)) {
				echo UI::h('span', [ 'class' => "wsk-help popover-with-html p5-L" . __LINE__ ], [
						UI::h('i', [ 'class' => "glyphicon glyphicon-info-sign" ]),
						UI::h('span', [ 'class' => "popover-heading" ], "[" . $w->CW_ID . "] " . $w->OPIS),
						UI::h('span', [ 'class' => "popover-body" ], "[{$w->ID}]" . $w->OPIS_ZASOB),
				]);
			}
			if ($show_form) $zasoby_id[$w->TYPE][$w->ID] = $w->CW_ID;

			if ($tree->get_param('rozwin_zasoby')) {
				echo $w_parents_out;
			}

			echo'</p>';
			echo'</li>';
		}
		echo'</ul>';


		if(0) {// TODO: grupuj zasoby
			echo'<hr />';
			$zasoby_id = array();
			$wsk_cnt = count( $wsk );
echo'<pre style="max-height:100px;overflow:auto;border:1px solid red;">wsk = ';print_r($wsk);echo'</pre>';
			// TEST parents
			$wsk_parents = array();
			$max_deep = 0;// max parents deep
			foreach ($wsk as $k_wsk_id => $w) {
				$wsk_parents_cur = array_reverse(array_keys($w->_parents));
				$wsk_parents_cur[] = $w->ID;
				if (count($wsk_parents_cur) > $max_deep) $max_deep = count($wsk_parents_cur);
				$wsk_parents_cur ['wsk_id'] = $k_wsk_id;
				$wsk_parents[] = $wsk_parents_cur;
				echo'parents ['.implode(',', $wsk_parents_cur).']<br />';
			}
			$wsk_parents_cnt = count($wsk_parents);
echo'<pre style="max-height:100px;overflow:auto;border:1px solid red;">parents('.$wsk_parents_cnt.'); max_deep('.$max_deep.'); wsk_parents = ';print_r($wsk_parents);echo'</pre>';

			$zasoby_id = array();
			foreach ($wsk as $k_wsk_id => $w) {
				$zasoby_id [$w->ID] =& $wsk[$k_wsk_id];
				foreach ($w->_parents as $k_z_id => $z) {
					$zasoby_id [$k_z_id] =& $wsk[$k_wsk_id]->_parents[$k_z_id];
				}
			}

			$wsk_parents_map = array();// table td: rowspan, colspan, wsk_id
/*
			for ($x = 0, $last_x = 0, $last_y = 0; $x < $max_deep; $x++, $last_x = $x) {
				for ($y = 0; $y < $wsk_parents_cnt; $y++) {
					$z_id = 'x';
					if (isset($wsk_parents[$y][$x])) {
						$z_id = $wsk_parents[$y][$x];
					}
					$wsk_parents_map[$y][$x] = array('rowspan'=>1, 'colspan'=>1, 'z_id'=>$z_id);// default content is 'x'
				}
			}
*/
			for ($y = 0, $last_y = 0, $last_x = 0; $y < $wsk_parents_cnt; $y++, $last_y = $y) {
				for ($x = 0; $x < $max_deep; $x++) {
					$z_id = 'x';
					$wsk_parents_map[$y][$x] = array('rowspan'=>1, 'colspan'=>1, 'z_id'=>$z_id);// default content is 'x'
					if (isset($wsk_parents[$y][$x])) {
						$wsk_parents_map[$y][$x]['z_id'] = $wsk_parents[$y][$x];
					} else if ($x > 0 && $wsk_parents_map[$y][$x - 1]['z_id'] != 'x') {
						//$wsk_parents_map[$y][$x - 1]['z_id'] = 'x';
						$wsk_parents_map[$y][$x - 1]['wsk_id'] = $wsk_parents[$y]['wsk_id'];
					}
				}
				// dodaj wsk_id do ostatniego elementu
				$x = $max_deep - 1;
				if ($wsk_parents_map[$y][$x]['z_id'] != 'x') {
					$wsk_parents_map[$y][$x]['wsk_id'] = $wsk_parents[$y]['wsk_id'];
				}
			}
echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">1:wsk_parents_map = ';print_r($wsk_parents_map);echo'</pre>';
			// set rowspan
			for ($x = 0, $last_x = 0; $x < $max_deep; $x++, $last_x = $x) {
				for ($y = 1, $last_y = 0; $y < $wsk_parents_cnt; $y++) {
					$last_cell_map =& $wsk_parents_map[$last_y][$x];
					$curr_cell_map =& $wsk_parents_map[$y][$x];
					if ($last_cell_map['z_id'] != $curr_cell_map['z_id']) {
						$last_y = $y;
					} else if (isset($last_cell_map['wsk_id'])) {
						$last_y = $y;
					} else {
						$curr_cell_map['z_id'] = 'x';
						$last_cell_map['rowspan'] += 1;
					}
				}
			}
echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">2:wsk_parents_map = ';print_r($wsk_parents_map);echo'</pre>';
			// set colspan
			for ($y = 0, $last_y = 0; $y < $wsk_parents_cnt; $y++, $last_y = $y) {
				for ($x = 1, $last_x = 0; $x < $max_deep; $x++) {
					$last_cell_map =& $wsk_parents_map[$y][$last_x];
					$curr_cell_map =& $wsk_parents_map[$y][$x];
					if ($curr_cell_map['z_id'] == 'x') {
						$curr_cell_map['z_id'] = 'x';
						$last_cell_map['colspan'] += 1;
					} else {
						$last_x = $x;
					}
				}
			}
echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">wsk_parents_map = ';print_r($wsk_parents_map);echo'</pre>';

/*
			foreach ($wsk_parents as $k_i => $v_map) {
				$last_p_id = 0; $last_map_ind = -1;
				foreach ($v_map as $wsk_i => $parent_id) {
					if ($last_map_ind == -1) {
						$last_map_ind = 0;
						$wsk_parents_map[$k_i][$last_map_ind] = array('p_id'=>$parent_id, 'rowspan'=>1);
					} else if ($last_p_id != $parent_id) {
						$last_map_ind++;
						$wsk_parents_map[$k_i][$last_map_ind] = array('p_id'=>$parent_id, 'rowspan'=>1);
					} else {
						$wsk_parents_map[$k_i][$last_map_ind]['rowspan'] += 1;
					}
					$last_p_id = $parent_id;
				}
			}
echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">wsk_parents_map = ';print_r($wsk_parents_map);echo'</pre>';
*/

/*
parents [27,35,57,79 ]
parents [27,35,57,79 ]
parents [27,14,31,355,1070,2365]
parents [27,35,57,79 ]
wsk_parents_map = Array(
    [0] => Array(
            [0] => Array(
                    [p_id] => 27
                    [rowspan] => 3
<table>
  <tr>
    <td rowspan=4> 27 </td>
    <td rowspan=2> 35 </td>
    <td rowspan=2> 57 </td>
    <td rowspan=2> 79 </td>
  </tr>
  <tr>

    <td> 14 </td>
    <td> 31 </td>
    <td> 355 </td>
  </tr>
  <tr>
    <td> 27 </td>
    <td> 35 </td>
    <td> 57 </td>
  </tr>
</table>
 */
echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">zasoby_id: ';print_r($zasoby_id);echo'</pre>';

			echo'<table class="tbl-wsk-view" border="1">';
			echo'<tbody>';
			foreach ($wsk_parents_map as $k_map_y => $v_map_line) {
				$out_row = '';
				foreach ($v_map_line as $k_map_x => $v_map) {
					if ($v_map['z_id'] == 'x') {
						continue;
					}
					$cls = '';
					$out_zasob = '';
					$out_rowspan = ($v_map['rowspan'] > 1)? ' rowspan="'.$v_map['rowspan'].'"' : '';
					$out_colspan = ($v_map['colspan'] > 1)? ' colspan="'.$v_map['colspan'].'"' : '';
					{// get zasob info
						//[TYPE] => NARZEDZIE
						//[DESC] => SUPEREDIT-WWW
						//[OPIS] => http://se.dev.webone.pl/
						$curr_z = V::get($v_map['z_id'], null, $zasoby_id);
						if (!$curr_z) {
							$out_zasob .= 'error brak zasobu {'.$v_map['z_id'].'}';
						} else {
							$out_zasob_title = array();
							$out_zasob_title[] = V::get('DESC', '', $curr_z);
							$out_zasob_title[] = V::get('OPIS', '', $curr_z);
							$out_zasob_title = ''.implode(' ', $out_zasob_title).'';
							$out_zasob .= '<b class="btn-box btn-box-green" title="'.$out_zasob_title.'">'.$v_map['z_id'].'</b>';
						}
					}

					if (isset($v_map['wsk_id'])) {
						$curr_wsk = V::get($v_map['wsk_id'], null, $wsk);
						if (!$curr_wsk) {
							$out_zasob .= 'error brak wskaznika {'.$v_map['wsk_id'].'}';
						} else {
							$out_zasob_opis = V::get('OPIS_ZASOB', '', $curr_wsk);
							$out_zasob .= ' <b class="btn-box" title="'."Wskaznik [".$v_map['wsk_id']."]".'">'.$v_map['wsk_id'].'</b>';
							// TODO: if edit, etc.
							$out_zasob .= ' '.$out_zasob_opis;
						}
						//$out_row .= '<td'.$out_rowspan.''.$out_colspan.'>'.$out_zasob.'</td>';
						$cls = ' class="wsk-cell"';
					}

					$out_row .= '<td'.$cls.''.$out_rowspan.''.$out_colspan.'>'.$out_zasob.'</td>';
				}
				if ($out_row) {
					echo'<tr>';
						echo $out_row;
					echo'</tr>';
				}
			}
			echo'</tbody>';
			echo'</table>';
		}// grupuj zasoby


		if ($show_form) {
//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">zasoby_id = ';print_r($zasoby_id);echo'</pre>';
			if (!empty($zasoby_id['KOMORKA'])) {
				$komorki = array();
				foreach ($zasoby_id['KOMORKA'] as $z_id => $w_id) {
					$komorki[] = $wsk[ $w_id ];
				}

				DEBUG_S(4,'komorki',$komorki, __FILE__, __FUNCTION__, __LINE__);
				// zasoby pobierz info o komorkach: tabela, baza danych; host,login,passwd z configa
				// BAZA_DANYCH -> TABELA -> KOMORKA
				$zasoby_tabele = array();
				$zasoby_db_conf = array();
				$sql = "select
						z.ID as KOMORKA_ID
						, z.DESC as KOMORKA_DESC
						, z.OPIS as KOMORKA_OPIS
						, z2.ID as TABELA_ID
						, z2.DESC as TABELA_DESC
						, z2.OPIS as TABELA_OPIS
						, z3.ID as DB_ID
						, z3.DESC as DB_DESC
						, z3.OPIS as DB_OPIS
					from `CRM_LISTA_ZASOBOW` as z
						left join `CRM_LISTA_ZASOBOW` as z2 on(z2.`ID`=z.`PARENT_ID`)
						left join `CRM_LISTA_ZASOBOW` as z3 on(z3.`ID`=z2.`PARENT_ID`)
					where
						z.`ID` in (".implode(',', array_keys($zasoby_id['KOMORKA'])).")
						and z2.`TYPE`='TABELA'
						-- and z3.`TYPE`='BAZA_DANYCH' -- lub DATABASE_MYSQL, DATABASE_MSSQL
				";
				DEBUG_S(5,'sql', $sql, __FILE__, __FUNCTION__, __LINE__);
				$res = DB::query( $sql );
				while ($z = DB::fetch( $res )) {
					$zasoby_db_conf [$z->DB_ID][] = array($z->KOMORKA_ID, $z->DB_ID, $z->DB_DESC, $z->DB_OPIS);
					$zasoby_tabele [$z->TABELA_ID][] = array($z->KOMORKA_ID, $z->TABELA_ID, $z->TABELA_DESC, $z->TABELA_OPIS);
				}
				DEBUG_S(4,'zasoby_db_conf ['.implode(',',array_keys($zasoby_db_conf)).']', $zasoby_db_conf, __FILE__, __FUNCTION__, __LINE__);
				DEBUG_S(4,'zasoby_tabele ['.implode(',',array_keys($zasoby_tabele)).']', $zasoby_tabele, __FILE__, __FUNCTION__, __LINE__);
				// pogrupuj komorki wg tabel
				// permy z $zasob->CW_TYP
			}
		}
				echo'</dd>';
	}

	echo'</dl>'."\n";
	$tree->log('show item -> end');
}


function tree_callback__show_item_from_CRM_LISTA_ZASOBOW( &$r, &$tree ) {
	// TODO: btn-box zasob type from PARENT_ID
	$cls = array();
	if (($search_id = $tree->get_param('search_id')) > 0 && $search_id == $r->ID) {
		$cls[] = 'search_id';
	}
	if ($tree->_table == 'CRM_LISTA_ZASOBOW') {
		$cls[] = 'type-'.(($r->ALIAS_ID > 0)? 'ALIAS_ID' : $r->PARENT_TYPE);// TODO: Undefined property: stdClass::$PARENT_TYPE przy Filtr ID
	}
	$cls = (!empty($cls))? ' class="'.implode(' ', $cls).'"' : '';
	echo'<dl'.$cls.'>';
	echo'<dt>';

	$out_id = ($r->ID < 10)? '&nbsp;'.$r->ID.'' : $r->ID;
	echo App::link($out_id, array('task'=>"CRM_LISTA_ZASOBOW", 'filtr_id'=>$r->ID, '#'=>'TREE'.$r->ID), array('class'=>'item_id btn-box'));

	if ($tree->get_param('editable')) {
		//echo'('.$r->SORT_PRIO.')';// TODO: DBG
		echo App::link("<b>^</b>", array('task'=>'CRM_LISTA_ZASOBOW', 'function_init'=>'SORT_PRIO_ZASOB', 'arg1'=>$r->ID, 'arg1_val'=>'upup'), array('class'=>"btn-clean", 'title'=>"w gore szybko"));
		echo App::link("^", array('task'=>'CRM_LISTA_ZASOBOW', 'function_init'=>'SORT_PRIO_ZASOB', 'arg1'=>$r->ID, 'arg1_val'=>'up'), array('class'=>"btn-clean", 'title'=>"w gore"));
		echo App::link("v", array('task'=>'CRM_LISTA_ZASOBOW', 'function_init'=>'SORT_PRIO_ZASOB', 'arg1'=>$r->ID, 'arg1_val'=>'dw'), array('class'=>"btn-clean", 'title'=>"w dol"));
		echo App::link("V", array('task'=>'CRM_LISTA_ZASOBOW', 'function_init'=>'SORT_PRIO_ZASOB', 'arg1'=>$r->ID, 'arg1_val'=>'downdown'), array('class'=>"btn-clean", 'title'=>"w dol szybko"));
		echo '('.$r->SORT_PRIO.')';
	}
	if ($tree->get_param('editable')) {
		if($tree->get_param('hasFieldPerm__ID'))
			  echo App::link("E", "index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=".$tree->get_param('getZasobTableID')."#EDIT/".$r->ID, array('title'=>'Pliki', 'class'=>'btn-p5'));
		else echo App::link("E", "?task=CRM_LISTA_ZASOBOW&EDIT=".$r->ID."#".$r->ID, array('title'=>'Edytuj', 'class'=>'btn-p5'));

	}
	if ($tree->get_param('hasFieldPerm__ID')) echo App::link("F", "index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=".$tree->get_param('getZasobTableID')."#FILES/".$r->ID, array('title'=>'Pliki', 'class'=>'btn-p5'));

	// TODO: dodaj obrazek w okienku/ajax
	//if ($tree->get_param('editable')) echo App::link_ajax("+IMG", 'ajax_add_image', array('tbl'=>"CRM_LISTA_ZASOBOW", 'id'=>$r->ID), array('js_result_type'=>'popup', 'class'=>'btn-p5', 'title'=>'Dodaj zdjecie'));

	if ($r->has_childrens) {
		if (!$tree->get_param('rozwin')) {
			$js = "return " . $tree->js_tree_open_rec_fun . "(this," . $r->ID . ");";
			//echo'<a class="open-rec" href="#" onclick="'.$js.'">'."L".'</a>';
			echo App::link("L", '#', array('title'=>'Rozwin wszystko', 'class'=>'btn-p5 open-rec', 'onclick'=>$js));
		}
	}


	if(($r->minOccurs!=1)or ($r->maxOccurs!=1)) echo '('.$r->minOccurs."/".$r->maxOccurs.")";
	else echo "(1)";

	echo'<span class="desc">';
	{
		$outAliasStyle = 'color:#999';
		$outAliasTitle = 'ALIAS INFO';
		$outAliasLink .= '<i class="glyphicon glyphicon-share-alt"></i>';
		if ($r->ALIAS_ID > 0) {
			$outAliasLink .= "{$r->ALIAS_ID}";
			// '<a href="#TREE'.$r->ALIAS_ID.'">'.$r->ALIAS_ID.'</a>'
			// '<a href="#TREE'.$r->ALIAS_ID.'">'.$r->ALIAS_ID.'</a>'
			if ('VIRTUAL' == $r->ALIAS_MODE) {
				$outAliasStyle = 'color:#CA06E2';
				$outAliasTitle = "ALIAS WIRTUALNY DO {$r->ALIAS_ID}";
			} else {
				$outAliasStyle = 'color:#FF6900';
				$outAliasTitle = "ALIAS DO {$r->ALIAS_ID}";
			}
		}
		echo '<span style="' . $outAliasStyle . '">
			<a href="#"
				style="' . $outAliasStyle . '"
				title="' . $outAliasTitle . '"
				data-id="' . $r->ID . '"
				onclick="return showZasobAliasTooltip(this);"
			>' . "{$outAliasLink}" . '</a>'
			. ' <span class="alias-description"></span>'
			. '</span>'
		;
	}
		echo '<b>'.$r->TYPE.'</b>';
		if($r->A_STATUS=='DELETED') echo " (D) ";
		$bold=false;
		if ((!empty($_GET['arg1']) && $_GET['arg1'] == $r->ID)
			|| (!empty($_GET['EDIT']) && $_GET['EDIT']==$r->ID)
		) {
			$bold = true;
		}

		if ($bold) echo "<b>";
		echo ' '.$r->DESC;
		if ($bold) echo "</b>";
		echo '<font size=-3 color=grey> '.$r->DESC_PL.'</font>';

		$opis_before = ''; $opis_after = '';
		$tbl = 'CRM_LISTA_ZASOBOW';
		if ($tree->get_param('filtr_img')) {
			if ($r->A_HAS_IMAGE) {
				echo'<br />';
				for ($i = 0; $i < $r->A_HAS_IMAGE; $i++) {
					$opis_before .= '<a href="'."?function_init=fun_SHOW_EXTERNAL_IMAGE&tbl=".$tbl."&id=".$r->ID."&number=".$i.'" target="_blank" class="lightbox">';
					$opis_before .= '<img src="'."?function_init=fun_SHOW_EXTERNAL_IMAGE&tbl=".$tbl."&id=".$r->ID."&number=".$i."&resize=200x200".'" style="float:left" />';
					$opis_before .= '</a>';
				}
			}
			if ($opis_before != '') $opis_after = '<br style="clear:both"/>';
		}

		echo' <span class="more-desc">';
		echo $opis_before;
		if ($tree->get_param('rozwin_opis') && $r->OPIS) echo ' '.$r->OPIS;
		echo $opis_after;
		echo '</span>';

	echo'</span>';

	$tbl = 'CRM_LISTA_ZASOBOW';
	if ($tree->get_param('filtr_img')) {
		if ($r->A_HAS_IMAGE || $tree->get_param('editable')) {
			echo' <span class="external-ids">{';
			//echo App::link("IMG", array('function_init'=>'ajax_show_images', 'tbl'=>'CRM_LISTA_ZASOBOW','id'=>$r->ID), array('target'=>'_blank', 'title'=>"Zdjecia (".$r->A_HAS_IMAGE.")"));
			//echo App::link_ajax("IMG", 'ajax_show_images', array('tbl'=>'CRM_LISTA_ZASOBOW','id'=>$r->ID), array('js_result_type'=>'override', 'js_result'=>'', 'title'=>"Zdjecia (".$r->A_HAS_IMAGE.")"));
			// TODO: A_HAS_IMAGE - count images, show img icons to show image in new window
			for ($i = 0; $i < $r->A_HAS_IMAGE; $i++) {
				echo App::link("I", array('function_init'=>'fun_SHOW_EXTERNAL_IMAGE', 'tbl'=>$tbl,'id'=>$r->ID, 'number'=>$i), array('target'=>'_blank', 'title'=>"Zdjecie ".($i+1), 'iconBootstrap'=>'glyphicon glyphicon-camera', 'class'=>'lightbox'));
			}
			if ($tree->get_param('editable')) echo App::link("+", "?function_init=fun_IMAGE_ADD&tbl=".$tbl."&id=".$r->ID, array('target'=>'_blank', 'title'=>"Dodaj zdjecia", 'iconBootstrap'=>'glyphicon glyphicon-plus'));
			echo'}</span>';
		}
	}

	if ($tree->get_param('editable')) {
		// TODO:  check table
		$allowed_check_database = array();
		$allowed_check_database[] = 'BAZA_DANYCH';
		$allowed_check_database[] = 'DATABASE_MYSQL';
		$allowed_check_database[] = 'DATABASE_MSSQL';

		if ($r->TYPE == 'TABELA') {
			//echo'{';
			//echo App::link_ajax("check", "ajax_zasob_check_table", array('zasob_id'=>$r->ID), array('js_result_type'=>'override', 'js_result'=>''));
			//echo'}';
		}
		else if (in_array($r->TYPE, $allowed_check_database)) {
			//echo'{';
			//echo App::link_ajax("check", "ajax_zasob_check_db", array('zasob_id'=>$r->ID), array('js_result_type'=>'override', 'js_result'=>''));
			//echo'}';
		}
	}

	// obowiazki
	if ($tree->get_param('filtr_ob')) {
		echo' <span class="external-ids">{';
		echo App::link_ajax("OB", "ajax_zasob_get_obowiazki", array('zasob_id'=>$r->ID), array('js_result_type'=>'override', 'js_result'=>'', 'title'=>"Obowiazki"));
		echo'}</span>';
	}

	// get external ids
	if ($tree->get_param('filtr_ids')) {
		if (in_array($r->TYPE, array('STANOWISKO', 'DZIAL', 'PODMIOT'))) {
			echo '<span class="external-ids">' . "{";
			echo App::link_ajax("kontakty", "ajax_zasob_stanowisko_search_kontakty", array('zasob_id'=>$r->ID), array('js_result_type'=>'override', 'js_result'=>''));
			echo "}" . '</span>';
		} else {
			$external_ids_allowed_type = array();
			$external_ids_allowed_type[] = 'NARZEDZIE';
			$external_ids_allowed_type[] = 'TELBOX';
			$external_ids_allowed_type[] = 'URZADZENIE';
			$external_ids_allowed_type[] = 'SERWER';
			$external_ids_allowed_type[] = 'SEGREGATOR';
			$external_ids_allowed_type[] = 'MAGAZYN';
			$external_ids_allowed_type[] = 'POMIESZCZENIE';
			$external_ids_allowed_type[] = 'ALARM-SATEL';
			$external_ids_allowed_type[] = 'DOSTEP-ZAMEK';
			$external_ids_allowed_type[] = 'DOSTEP-KLUCZ';
			$external_ids_allowed_type[] = 'SZAFA';
			$external_ids_allowed_type[] = 'PIECZATKA';
			$external_ids_allowed_type[] = 'MATERIAL_REKLAMOWY';
			$external_ids_allowed_type[] = 'INNE';
			$external_ids_allowed_type[] = 'DANE';
			$external_ids_allowed_type[] = 'SIP_ACCOUNT';
			$external_ids_allowed_type[] = 'PODMIOT';
			$external_ids_allowed_type[] = 'URZADZENIA_I_OZNACZENIA_BHP';
			$external_ids_allowed_type[] = 'SOFTWARE';
			$external_ids_allowed_type[] = 'WYPOSAZENIE_LOKALU';
			$external_ids_allowed_type[] = 'KUWETA';
			$external_ids_allowed_type[] = 'DOSTEP-UPRAWNIENIA';
			$external_ids_allowed_type[] = 'APLIKACJA';
			$external_ids_allowed_type[] = 'LOKALIZACJA';
			$external_ids_allowed_type[] = 'KOMPUTER';
			$external_ids_allowed_type[] = 'MATERIAL_EKSPLOATACYJNY';
			$external_ids_allowed_type[] = 'SOFTWARE';
			$external_ids_allowed_type[] = 'OBSZAR';
			$external_ids_allowed_type[] = 'REWIR';
			$external_ids_allowed_type[] = 'DOKUMENTY';
			$external_ids_allowed_type[] = 'SEJF';
			$external_ids_allowed_type[] = 'DOSTEP-UPRAWNIENIA';
			$external_ids_allowed_type[] = 'PLYTA_CD';
			$external_ids_allowed_type[] = 'PROJEKT';
			$external_ids_allowed_type[] = 'SPRAWA';
			$external_ids_allowed_type[] = 'DOSTEP-KARTA';
			$external_ids_allowed_type[] = 'OZNACZENIE_LOKALIZACJI';
			$external_ids_allowed_type[] = 'DOSTEP-ZAMEK-ELEKTRONICZNY';
			$external_ids_allowed_type[] = 'POLKA';
			$external_ids_allowed_type[] = 'LOKALIZACJA_USLUGI';
			$external_ids_allowed_type[] = 'SERVICE_POINT';
			$external_ids_allowed_type[] = 'OFFER_GROUP';
			$external_ids_allowed_type[] = 'OFFER';
			$external_ids_allowed_type[] = 'OFFER_COSTS_GROUP';
			$external_ids_allowed_type[] = 'OFFER_COST';



			if (in_array($r->TYPE, $external_ids_allowed_type)) {
				echo '<span class="external-ids">' . "{";
				echo App::link_ajax("get IDS", "ajax_zasob_search_external_ids", array('zasob_id'=>$r->ID), array('js_result_type'=>'override', 'js_result'=>''));
				echo "}" . '</span>';
			}
		}
	}
	if($tree->get_param('editable'))
		echo App::link("↵+", "index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=".$tree->get_param('getZasobTableID')."&ff_PARENT_ID=".$r->ID."#CREATE", array('class'=>'btn-p5', 'title'=>'Dodaj dziecko', 'onclick'=>null));
	echo'</dt>';
	echo'</dl>'."\n";
}



// ========== typespecial functions
//	function typespecial_{$FUN}( $field_name, $cmd, $value, $attrs = array() ) {
//		switch ($cmd) {
//			case 'show': {// show field in form
//					$out = '';
//					return $out;
//				}
//				break;
//			case 'update': {// return field value
//					return $value;
//				}
//				break;
//			default:
//
//		}
//	}


function typespecial_L_APPOITMENT_USER($field_name, $cmd, $user_value, $attrs = array()) {
	static $_users_list;
	if (!$_users_list) {
		$_users_list = array();
		$sql = "select u.*
			from `ADMIN_USERS` as u
			where
				u.`A_STATUS`='NORMAL'
				and u.`ADM_TECH_WORKER`!='NO'
				-- and u.`ADM_COMPANY` like '" . $_SESSION['ADM_COMPANY'] . "'
				order by u.`ADM_NAME`
		";
		$res = DB::query( $sql );
		while ($r = DB::fetch( $res )) {
			$_users_list [$r->ADM_ACCOUNT] = "" . $r->ADM_NAME . " (" . $r->ADM_ACCOUNT . ")";
		}
	}

	$out = '';
	switch ($cmd) {
		case 'show': {
				$out .= '<select name="' . $field_name . '">';
					$out .= ' <option value="">' . " " . '</option>';
					foreach ($_users_list as $key => $val) {
						$sel = ($user_value == $key)? ' selected="selected"' : '';
						$out .= '<option value="' . $key . '"' . $sel . '>' . $val . '</option>';
					}
				$out .= '</select>';
			}
			break;
		case 'search': {
				$out .= '<select name="' . $field_name . '">';
					$out .= ' <option value="'."%".'">' . " % " . '</option>';
					foreach ($_users_list as $key => $val) {
						$sel = ($user_value == $key)? ' selected="selected"' : '';
						$out .= '<option value="' . $key . '"' . $sel . '>' . $val . '</option>';
					}
				$out .= '</select>';
			}
			break;
		case 'update': {
				echo 'TODO: ' . __FUNCTION__ . '(update, '.$field_name.')';
				return $value;
			}
			break;
		default:

	}
	return $out;
}


function typespecial_CRM_TESTY__ID_ORGANIZER( $field_name, $cmd, $user_value, $attrs = array() ) {
	static $_users_list;
	if (!$_users_list) {
		$_users_list = array();
		Lib::loadClass('UsersHelper');
		$params = array();
		$params['ADM_ADMIN_LEVEL'] = 0;
		$organizer_list = UsersHelper::get_users_list( $params, 100, 0, 'ADM_NAME', 'ASC' );
		foreach ($organizer_list as $k => $v_organizer) {
			$_users_list [$v_organizer->ID] = "" . $v_organizer->ADM_NAME . " (" . $v_organizer->ID . ")";
		}
	}

	$out = '';
	switch ($cmd) {
		case 'show': {
				$out .= '<select name="' . $field_name . '">';
					$out .= ' <option value="">' . " " . '</option>';
					foreach ($_users_list as $key => $val) {
						$sel = ($user_value == $key)? ' selected="selected"' : '';
						$out .= '<option value="' . $key . '"' . $sel . '>' . $val . '</option>';
					}
				$out .= '</select>';
			}
			break;
		case 'search': {
				$out .= '<select name="' . $field_name . '">';
					$out .= ' <option value="'."%".'">' . " % " . '</option>';
					foreach ($_users_list as $key => $val) {
						$sel = ($user_value == $key)? ' selected="selected"' : '';
						$out .= '<option value="' . $key . '"' . $sel . '>' . $val . '</option>';
					}
				$out .= '</select>';
			}
			break;
		case 'update': {
				echo 'TODO: ' . __FUNCTION__ . '(update, '.$field_name.')';
				return $value;
			}
			break;
		default:

	}
	return $out;
}


//2007-04-28 KOMENTARZ arek@tx.pl
//
//  PROCES(X,Y)
//   KROK_1     <-(CRM_WSKAZNIK)-----ZASOB(1)
//   KROK_1     <-(CRM_WSKAZNIK)-----CZYNNOSC(1)
//   KROK_2     <-(CRM_WSKAZNIK)-----ZASOB(2)
//   KROK_2     <-(CRM_WSKAZNIK)--ZASOB(3)
//   KROK_2     <-(CRM_WSKAZNIK)--CZYNNOSC(2)
//   KROK_2     <-(CRM_WSKAZNIK)--ZASOB(4)
//
//
//  dodatkowo ZASOBY i CZYNNOSCI maja miec strukture drzewa ID/PARENT_ID
//  i przy rysowaniu procesu ma sie wyswietlac pelne drzewo
//
//
// czyli jest SERWER/DANE/arkusz_zalegllosci, uzyty do procesu windykacji, z flaga UZYWANIE
// a inny proces jest typu zasob=SERWER , ale uzyta jest flaga SERWIS
//
// czyli widac, ze jest serwer serwisowany, oraz kto go uzywa itp...
//
//  trzeba bedzie dobrac odpowiednie flagi oraz odpowiednie elementy,
//  i na tej podstawie opisac wszystkie zdarzenia w firmie i do nich wyrysowac procesy
// zobaczymy jak to sie ulozy organizacyjnie, bo w zasadzie moga wyjsc z tego niezle procedury
// w tym i do prowadzenia inwestycji i wszystkiego.
//Pozdro 600 , zrob do tego ladniejszy interfejs, zeby dalo sie ustalac strukture zasobow, czynnosci oraz procesow
