<?php


if (!class_exists('Lib')) die('404');


function ajax_table() {
	$ajax_req_id = V::get('_ajax_req_id', '', $_REQUEST);
	if (!$ajax_req_id) {
		die('<div>'."Req id error".'</div>');
	}

	Lib::loadClass( 'AjaxReq' );
	$conf = AjaxReq::get_conf( $ajax_req_id );
	if (!$conf) {
		die('<div>'."Req id error - session".'</div>');
	}

	$sql_table = V::get('sql_table', '', $conf);
	if (!$sql_table) {
		die('<div>'."conf error - table".'</div>');
	}

	$sql_cols_conf = V::get('sql_cols', '', $conf);
	if (!$sql_cols_conf) {
		die('<div>'."conf error - cols".'</div>');
	}

	$subtask = V::get('subtask', '', $_REQUEST);
	if ($subtask) {
		// get data by configuration
		header('Content-Type: text/javascript; charset=utf8');
		//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">';print_r($_REQUEST);echo'</pre>';
		/* Array (
			[_ajax_request] => ajax_table
			[_ajax_req_id] => _tbl_4e9ebfeead7e2
			[subtask] => get_data
			[request_mode] => json
			[page] => 1
			[rp] => 20
			[sortname] => id
			[sortorder] => asc
			[query] => 
			[qtype] => 
		 */

		$data = new stdClass();
		$data->page = 1;
		$data->total = 0;
		$data->rows = array();

		// get cols from session config
		$sql_cols = array();
		foreach ($sql_cols_conf as $key => $val) {
			$sql_cols []= $key;
		}//end foreach

		$data->page = V::get('page', '1', $_REQUEST, 'int');
		$limit = V::get('rp', '20', $_REQUEST, 'int');
		$sql_limit = 'limit '.$limit.' ';
		if ($data->page > 0) {
			$sql_limit = 'limit '.$limit.' OFFSET '.(($data->page - 1) * $limit);
		}

		$sql_order_by = strtoupper( V::get('sortname', 'ID', $_REQUEST) );
		$sql_order_sort = strtolower( V::get('sortorder', 'asc', $_REQUEST) );
		if (!in_array($sql_order_by, $sql_cols) || !in_array($sql_order_sort, array('asc', 'desc'))) {
			$sql_order_by = 'ID';
			$sql_order_sort = 'asc';
		}
		$sql_order = 'order by p.`'.$sql_order_by.'` '.$sql_order_sort;

		$sql_where = 'where 1';
		$sql_where_and = array();
		$query = V::get('query', '', $_REQUEST);
		//trigger_error($query, E_USER_NOTICE);
		if ($query) {
			$query = explode('&', $query);
			foreach ($query as $v) {
				$tmp = explode('=', $v);
				if (count($tmp) != 2) continue;
				if (!in_array(strtoupper($tmp[0]), $sql_cols)) continue;
				$sql_where_and []= " p.`" . $tmp[0] . "` like '" . $tmp[1] . "'";
			}//end foreach
		}

		if (!empty($sql_where_and)) {
			$sql_where = 'where '.implode(' and ', $sql_where_and);
		}

		$db = DB::getDB();
		$sql = "select count(1) as cnt from `".$sql_table."` as p $sql_where ";
//trigger_error($sql, E_USER_NOTICE);
		$res = $db->query( $sql );
		if ($r = $db->fetch( $res )) {
			$data->total = $r->cnt;
		}

		$sql_cols_p = array();
		foreach ($sql_cols as $v) {
			$sql_cols_p []= "p.`".$v."`";
		}//end foreach
		$sql_cols_p = implode(",", $sql_cols_p);
		$sql = "select ".$sql_cols_p." from `".$sql_table."` as p $sql_where $sql_order $sql_limit ";
//trigger_error($sql, E_USER_NOTICE);
		$res = $db->query( $sql );
		while ($r = $db->fetch( $res )) {
			$cell = array('id'=>$r->ID, 'cell'=>array());
			foreach ($sql_cols as $v_col_name) {
				$cell['cell'] []= str_replace('"', '&quot;', $r->$v_col_name);
			}//end foreach
			$data->rows []= (object)$cell;
		}

		//echo json_encode($data);
		//echo"\n\n\n";
		echo V::json_encode_latin2( $data );
		die('');
	}

	$tbl = new stdClass();
	$tbl->title = $conf['title'];// TODO: read from session
	$tbl->width = '1000';
	$tbl->height = '250';
	$tbl->id = 'table_view_'.$ajax_req_id;
	$tbl_ajax_request = array();
	$tbl_ajax_request []= "_ajax_request="."ajax_table";
	$tbl_ajax_request []= "_ajax_req_id=".$ajax_req_id;
	$tbl_ajax_request []= "subtask=get_data";
	$tbl_ajax_request []= "request_mode=json";
	$tbl->ajax_request = $_SERVER['PHP_SELF'] . "?" . implode('&', $tbl_ajax_request);

	// scripts with table config: fields,filters,functions, etc
	$tbl->searchitems = array();
	/*
		[
			{label: 'ID', name : 'id', def:'%'},
			{label: 'P_ID', name : 'parent_id', def:'%'},
			{label: 'Name', name : 'desc', def:'%'},
			{label: 'Opis', name : 'opis', def:'%'}
		]
	 */
	$tbl->fields = array();
	/*
		[
			{display: 'ID', name : 'id', width : 40, sortable : true, align: 'center'},
			{display: 'P_ID', name : 'parent_id', width : 40, sortable : true, align: 'center'},
			{display: 'TYPE', name : 'type', width : 70, sortable : true, align: 'center'},
			{display: 'Desc', name : 'desc', width : 300, sortable : true, align: 'left'},
			{display: 'Opis', name : 'opis', width : 350, sortable : true, align: 'left'}
		]
	 */
	// determine columns width
	$used_width = 0;
	$used_cols = 0;
	$col_width = array();
	foreach ($sql_cols_conf as $k => $v_conf) {
		$v_type = $v_conf['Type'];
		if (substr($v_type, 0, 3) == 'int') {
			$col_width[$k] = 60;
			$used_width += $col_width[$k] + 7;
			$used_cols += 1;
		} else {
			//$col_width [$k]= 0;
		}
	}
	$width = round( ($tbl->width - $used_width) / (count($sql_cols_conf) - $used_cols)) - 7;

	$perm_create = false;
	$perm_update = false;
	foreach ($sql_cols_conf as $k => $v_conf) {
		$v_name = $v_conf['Label'];
		$v_width = (isset($col_width[$k]))? $col_width[$k] : $width;
		$tbl->fields []= (object)array('display'=>$v_name, 'name'=>$k, 'width'=>$v_width, 'sortable'=>'true', 'align'=>'center');

		$tbl->searchitems []= (object)array('label'=>$v_name, 'name'=>$k, 'def'=>'%');

		if (strpos($v_conf['Perm'],'C') !== false) $perm_create = true;
		if (strpos($v_conf['Perm'],'W') !== false) $perm_update = true;
	}
	$tbl->js_buttons_callback = 'js_'.$ajax_req_id.'_cmd';

	$tbl->buttons = array();
	if ($perm_create) {// if has perm C
		$tbl->buttons []= (object)array('name'=>'add', 'label'=>'Dodaj', 'bclass'=>'add', 'onpress'=>$tbl->js_buttons_callback);
		$tbl->buttons []= (object)array('separator'=>'true');
	}
	if ($perm_update) {// if has perm W
		$tbl->buttons []= (object)array('name'=>'edit', 'label'=>'Edytuj', 'bclass'=>'edit', 'onpress'=>$tbl->js_buttons_callback);
		$tbl->buttons []= (object)array('separator'=>'true');
	}
//	$tbl->buttons []= (object)array('name'=>'delete', 'label'=>'Delete', 'bclass'=>'delete', 'onpress'=>$tbl->js_buttons_callback);
//	$tbl->buttons []= (object)array('separator'=>'true');
	$tbl->buttons []= (object)array('name'=>'text', 'label'=>'Pełny tekst', 'bclass'=>'edit', 'onpress'=>$tbl->js_buttons_callback);
	$tbl->buttons []= (object)array('separator'=>'true');

	echo"\n".'<link rel="stylesheet" type="text/css" href="./stuff/flexigrid/css/flexigrid.css" />';

	//echo'<script type="text/javascript" src="./stuff/jquery.js"></script>';
	echo"\n".'<script type="text/javascript" src="./stuff/flexigrid/js/flexigrid.js"></script>';
	echo"\n".'<script type="text/javascript" src="./stuff/jquery.cookie.js"></script>';
	echo"\n".'<script type="text/javascript">'."
function ".$tbl->js_buttons_callback."(btn, grid){
	//console.log('function callback ".$tbl->js_buttons_callback."');
	var com = btn.title;
	if (com == 'delete') {
		confirm('Delete ' + jQuery('.trSelected', grid).length + ' items?')
	} else if (com == 'edit') {
		confirm('Edit ' + jQuery('.trSelected', grid).length + ' items?')
	} else if (com == 'add') {
		//console.log('Add New Item');
	} else if (com == 'text') {
		var hasCls = jQuery(grid).toggleClass('long-desc').hasClass('long-desc');
		if(hasCls) btn.innerHTML='Skrócony tekst';
		else btn.innerHTML='Pełny tekst';
	}
}

jQuery(document).ready(function(){
jQuery('#".$tbl->id."').flexigrid({
	id: '".$tbl->id."'
	, url: '".$tbl->ajax_request."'
	, dataType: 'json'
	, colModel : " . V::json_encode_latin2( $tbl->fields ) . "
	, buttons : " . V::json_encode_latin2( $tbl->buttons ) . "
	, searchitems : " . V::json_encode_latin2( $tbl->searchitems ) . "
	, sortname: 'id'
	, sortorder: 'asc'
	, usepager: true
	, title: '".$tbl->title."'
	, useRp: true
	, rp: 10
	, rpOptions: [10, 20, 50]
	, showTableToggleBtn: true
	, width: ".$tbl->width."
	, height: ".$tbl->height."
});
});
	".'</script>';

	echo"\n".'<div id="'.$ajax_req_id.'">';
		//echo'['.$ajax_req_id.']<br />';
		//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">sql_cols_conf = ';print_r($sql_cols_conf);echo'</pre>';
		//echo'<br />';
		echo'<table id="'.$tbl->id.'" style="display:none"></table>';
	echo'</div>'."\n";
}


function ajax_get_subtree() {
	header('Content-Type: text/html; charset=utf8');//utf8

	$id = V::get('id', '', $_GET);
	$tbl = V::get('tbl', '', $_GET);

	//sleep(1);// TODO: DBG

	$tree_filter = get_filter_for_table( $tbl );

	$clbk = 'tree_callback__show_item_from_'.$tbl;
	if (!function_exists($clbk)) {
		$clbk = null;
	}
	$tree = new Tree( $tbl );
	if ($clbk) $tree->set_param('show_item_callback', $clbk);
// TODO: get all filters:
	$tree->set_param('rozwin', ($tree_filter->get_arg('filtr_drzewo') == 'ROZWIN'));
	$tree->set_param('rozwin_proces', ($tree_filter->get_arg('filtr_procesy') == 'ROZWIN'));
	$tree->set_param('rozwin_zasoby', ($tree_filter->get_arg('filtr_zasoby') == 'ROZWIN'));
	$tree->set_param('rozwin_opis', ($tree_filter->get_arg('filtr_opis') == 'ROZWIN'));
	$tree->set_param('filtr_sort_prio', ($tree_filter->get_arg('filtr_sort_prio') == 'SHOW'));
	$tree->set_param('filtr_img', ($tree_filter->get_arg('filtr_img') == 'SHOW'));
	$tree->set_param('filtr_ob', ($tree_filter->get_arg('filtr_ob') == 'SHOW'));
	$tree->set_param('filtr_ids', ($tree_filter->get_arg('filtr_ids') == 'SHOW'));

	$tree->set_param('style', $tree_filter->get_arg('filtr_view'));
	$tree->set_param('search_id', $tree_filter->get_arg('filtr_search_id'));
	//TODO: check perm to edit
	$tree->set_param('editable', ($tree_filter->get_arg('filtr_edit') == 'TAK'));
	$tree->_limit = 100;
	$tree->_deep_limit = 10;

	$open_rec = V::get('open_rec', '', $_REQUEST);
	if ($open_rec == '1') {
		$tree->show_rec_all( $id );
	} else {
		$tree->show_rec( $id );
	}

	exit;
}


function ajax_add_image() {
	//sleep(1);// TODO: TEST
	$tbl = V::get('tbl', '', $_REQUEST);
	$id = V::get('id', '', $_REQUEST);
	//echo $tbl;

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

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

	Lib::loadClass('DB_Image');

	// 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
	$remote_tables = DB_Image::conf_get('remote_tables');
	if (!in_array($remote_table, $remote_tables)) {
		$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::delete_image($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::upload_image($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;

	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>';
		return;
	}

	echo'<div class="box box-silver">';
	$js = "ajax_form(this, 'id', 'tip-popup-box');";
	$js = ' onsubmit="'.$js.'"';
	echo'<form enctype="multipart/form-data" action="" method="post"'.$js.'>';
		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>';
			}//end foreach
			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::get_images($thiss->DETECT_TABLE_NAME, $remote_id);

	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::show_size($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>';

					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>';
		}//end foreach
	}
// } function show images

}


function ajax_zasob_search_external_ids() {
	header('Content-Type: text/html; charset=utf8');

	$zasob_id = V::get('zasob_id', '', $_REQUEST, 'int');
	if ($zasob_id <= 0) {
		echo'Error: Bad request';// TODO: header
		return;
	}
	$DBG = (123 == V::get('DBG', '', $_REQUEST, 'int'));

	$zasob = DB::get_by_id( 'CRM_LISTA_ZASOBOW', $zasob_id );
	if (!$zasob) {
		echo'Error: 404 not found';// TODO: header
		return;
	}
	$cnf = Config::getConfFile('external_ids');
	if (!$cnf) {
		echo'Config error (external_ids)';
		return;
	}

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

	if (!empty($cnf)) {
		$external_ids = array();
		foreach ($cnf as $k_table_name => $v_cnf) {
			$cur_cnf = new stdClass();
			$cur_cnf->id_col = V::get('id_col', 'ID', $v_cnf);
			$cur_cnf->search_col = V::get('search_col', 'CRM_LISTA_ZASOBOW_ID', $v_cnf);
			$cur_cnf->search_col_regex = V::get('search_col_regex', '', $v_cnf);
			$sql_id_col = $cur_cnf->id_col;
			$sql_where = "";
			if ($cur_cnf->search_col_regex) {
				$sql_where = "`".$cur_cnf->search_col."` like '".str_replace('$ID', $zasob->ID, $cur_cnf->search_col_regex)."'";
			} else {
				$sql_where = "`".$cur_cnf->search_col."`='".$zasob->ID."'";
			}

			$sql = "select t.`ID`, {$sql_id_col} as id_col
				from `" . $k_table_name . "` as t
				where " . $sql_where . "
			";
if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sql (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>'; }
			$res = DB::query( $sql );
			while ($r = DB::fetch( $res )) {
				if ('ID' != $sql_id_col) {
					$external_ids []= $r->ID . "(" . $r->id_col . ")";
				} else {
					$external_ids []= "" . $r->id_col;
				}
			}
		}//end foreach
	}

	$out_link = '';
	if (empty($external_ids)) {
		$out_link = '<span class="not-found">'."Brak danych".'</span>';
	} else {
		$out_link = implode(', ', $external_ids);
	}

	echo '<span>';
		echo $out_link;
		echo " ";
		echo App::link_ajax("refresh", "ajax_zasob_search_external_ids", array('zasob_id'=>$zasob->ID), array('js_result_type'=>'override_parent', 'js_result'=>'', 'title'=>'refresh IDS', 'ico'=>"refresh.png"));
	echo '</span>';

	// TODO: add link to CRM_EXT_IDS - rysuj strukture
}


function ajax_zasob_stanowisko_search_kontakty() {
	header('Content-Type: text/html; charset=utf8');

	$zasob_id = V::get('zasob_id', '', $_REQUEST, 'int');
	if ($zasob_id <= 0) {
		echo'Error: Bad request';// TODO: header
		return;
	}
	$DBG = (123 == V::get('DBG', '', $_REQUEST, 'int'));

	$zasob = DB::get_by_id( 'CRM_LISTA_ZASOBOW', $zasob_id );
	if (!$zasob) {
		echo'Error: 404 not found';// TODO: header
		return;
	}

	$external_ids = array();
	$mailto_links = array();
	$sql = "select u.`ID`, u.`ADM_ACCOUNT`, u.`ADM_NAME`, u.`EMAIL`
		from `CRM_AUTH_PROFILE` as up
			left join `ADMIN_USERS` as u on (u.`ID`=up.`REMOTE_ID`)
		where
			up.`ID_ZASOB`='" . $zasob->ID . "'
			and up.`REMOTE_TABLE`='ADMIN_USERS'
			and up.`A_STATUS` in('WAITING', 'NORMAL')
			and u.`A_STATUS` in('WAITING', 'NORMAL')
		group by u.`ID`
	";
if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sql (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>'; }
	$res = DB::query( $sql );
	while ($r = DB::fetch( $res )) {
		$external_ids []= $r->ADM_ACCOUNT . "(" . $r->ADM_NAME . ")";
		if (!empty($r->EMAIL)) {
			$mailto_links[$r->EMAIL] = true;
		}
	}

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

	$out_link = '';
	if (empty($external_ids)) {
		$out_link = '<span class="not-found">'."Brak danych".'</span>';
	} else {
		$out_link = implode(', ', $external_ids);
	}

	echo '<span>';
		echo $out_link;
		echo " ";
		echo App::link_ajax("refresh", "ajax_zasob_stanowisko_search_kontakty", array('zasob_id'=>$zasob->ID), array('js_result_type'=>'override_parent', 'js_result'=>'', 'title'=>'refresh IDS', 'ico'=>"refresh.png"));
		echo " ";
		if (!empty($mailto_links)) {
			$mailto_links = array_keys($mailto_links);
			echo '<a href="' . "mailto:" . implode(', ', $mailto_links) . '"><img src="icon/mail_all.png" height="16" alt=" mail " /></a>';
			echo " ";
		}
		echo App::link(" więcej &raquo; ", array('task'=>"USERS", '_group'=>$zasob_id), array('target'=>"_blank"));
	echo '</span>';

	// TODO: add link to CRM_EXT_IDS - rysuj strukture
}


function ajax_zasob_get_obowiazki() {

	//sleep(1);
	$zasob_id = V::get('zasob_id', '', $_REQUEST, 'int');
	if ($zasob_id <= 0) {
		echo'Error: Bad request';// TODO: header
		return;
	}

	$zasob = DB::get_by_id( 'CRM_LISTA_ZASOBOW', $zasob_id );
	if (!$zasob) {
		echo'Error: 404 not found';// TODO: header
		return;
	}

	$external_ids = array();

	$db = DB::getDB();
	$sql = "select t.`ID_PROCES` as ext_id
		from `CRM_WSKAZNIK` as t
			join `CRM_PROCES` as p on(p.`ID`=t.`ID_PROCES`)
		where
			t.`ID_ZASOB`='{$zasob->ID}'
			and t.`A_STATUS` in('WAITING','NORMAL')
			and p.`A_STATUS` in('WAITING','NORMAL')
	";
	$res = $db->query($sql);
	while ($r = $db->fetch($res)) {
		$external_ids []= $r->ext_id;
	}

	$out_link_ids_limit = 5;
	$out_link = '';
	$out_link_add = '';
	if (empty($external_ids)) {
		$out_link = '<span class="not-found">'."Brak danych".'</span>';
	} else {
		$cnt = count($external_ids);
		if ($cnt > $out_link_ids_limit) {
			$external_ids_tmp = array();
			for ($i = 0; $i < $out_link_ids_limit; $i++) {
				$external_ids_tmp []= $external_ids[$i];
			}//end foreach
			$out_link_add .= implode(' ', $external_ids_tmp);
			$out_link_add .= ' ... ';
			$out_link_add .= App::link("($cnt)", "?task=CRM_WYSWIETL_OBOWIAZKI&CLZ_ID=".$zasob->ID, array('target'=>'_blank', 'title'=>'Procesy powiazane z tym zasobem'));
		} else {
			$out_link_add .= implode(' ', $external_ids);
			$out_link_add .= ' ';
			$out_link_add .= App::link("(OB)", "?task=CRM_WYSWIETL_OBOWIAZKI&CLZ_ID=".$zasob->ID, array('target'=>'_blank', 'title'=>'Procesy powiazane z tym zasobem'));
		}
	}

	if ($out_link) {
		echo App::link_ajax($out_link, "ajax_zasob_get_obowiazki", array('zasob_id'=>$zasob->ID), array('js_result_type'=>'override', 'js_result'=>'', 'title'=>'refresh OB'));
	}

	if ($out_link_add) {
		echo $out_link_add;
	}

}


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

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

	Lib::loadClass('DB_Image');

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

	// check remote table
	$remote_tables = DB_Image::conf_get('remote_tables');
	if (!in_array($remote_table, $remote_tables)) {
		header('HTTP/1.1 400: Bad Request');
		header('Warning: table not allowed L.' . __LINE__);
		exit;
	}

	$db = DB::getDB();
	$sql = "select `ID`, `TYPE`, `SIZE`, `DEST`
		from `".DB_Image::conf_get_table_name()."`
		where
			`REMOTE_ID`='".$remote_id."'
			and `REMOTE_TABLE`='".$remote_table."'
	";

	$res = $db->query($sql);
	if (!$db->num_rows($res)) {
		header('HTTP/1.1 400: Bad Request');
		header('Warning: images not found in db L.' . __LINE__);
		exit;
	}

	echo'<p>'."Zdjecia dla rekordu <b>".$remote_id."</b> z tabeli ".$remote_table.'</p>';

	while ($r = $db->fetch( $res )) {
		$src = "?function_init=fun_SHOW_IMAGE&image_id=".$r->ID;
		echo'<img src="'.$src.'" alt="'.$r->TYPE.'" />';
	}

	exit;
}


function ajax_zasob_check_table() {

	//sleep(1);
	$zasob_id = V::get('zasob_id', '', $_REQUEST, 'int');
	if ($zasob_id <= 0) {
		echo'Error: Bad request';// TODO: header
		return;
	}

	$zasob = DB::get_by_id( 'CRM_LISTA_ZASOBOW', $zasob_id );
	if (!$zasob) {
		echo'Error: 404 not found';// TODO: header
		return;
	}

	// TODO: get config from parent DATABASE%
	$cnf_id = $zasob->PARENT_ID;
	//$ext_db = DB::getDB( $r->PARENT_ID );
	$cnf = Config::getZasobConf( $cnf_id );
	if (!$cnf) {
		echo'<span class="err">'."Brak konfiguracji dla zasobu <b>$cnf_id</b>".'</span>';
		return;
	} else {
		$db = DB::getDB( $cnf_id );
		if ($db->get_errors()) {
			echo'<span class="err">'."Wystapily bledy podczas polaczenia z baza danych (zasob $cnf_id):";
				echo '<br />'.implode('<br />', $db->get_errors());
			echo'</span>';
			return;
		} else {
			//$db;
			echo'CONN OK;';// TODO: msg OK
			//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">';print_r($db);echo'</pre>';
		}
	}

	// conn ok, check if table exists
	$sql = "show tables like '".$zasob->DESC."' ; ";
	$res = $db->query( $sql );
	if ($db->num_rows( $res ) == 1) {
		echo'TABLE NAME OK;';// TODO: msg OK
	} else {
		echo'<span class="err">'."Niepoprawna nazwa tabeli <b>".$zasob->DESC."</b>".'</span>';
		return;
	}

	// conn ok, table exists, check table fields
	$fields = array();
	$sql = "describe `".$zasob->DESC."` ; ";
	$res = $db->query( $sql );
	// Field, Type, Null, Key, Default, Extra
	// ID, int(10), NO, PRI, NULL, auto_increment
	// A_RECORD_CREATE_DATE, varchar(30), NO
	while ($r = $db->fetch( $res )) {
		$params = new stdClass();
		// TODO: analyze field parameters: Type,Length,Default,Null?
		$params->Type = $r->Type;
		if (substr($r->Type, 0, 3) == 'int') {
			$params->Type = 'int';
			$params->Length = substr(substr($r->Type, 3), 1, -1);
		} else if (substr($r->Type, 0, 7) == 'varchar') {
			$params->Type = 'varchar';
			$params->Length = substr(substr($r->Type, 7), 1, -1);
		} else if (substr($r->Type, 0, 4) == 'enum') {
			$params->Type = 'enum';
			$params->Values = substr(substr($r->Type, 4), 1, -1);// TODO: add DANE under KOMORKA
		} else if (substr($r->Type, 0, 4) == 'date') {
			$params->Type = 'date';
		} else if (substr($r->Type, 0, 4) == 'text') {
			$params->Type = 'text';
		} else {
			$params->Type = 'unknown';
		}
		// TODO: ...
		if ($r->Default) $params->Default = $r->Default;
		else if ($r->Null == 'YES') $params->Default = 'Null';
		$fields[ $r->Field ] = $params;
	}

echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">fields=';
foreach ($fields as $f_name => $f_params) {
	echo"\n".'['.$f_name.']='.json_encode($f_params);
}//end foreach
echo'</pre>';

	$komorki = array();
	$sql = "select
			`ID`, `TYPE`, `DESC`
			-- TODO: , `PARAMS`
		from `CRM_LISTA_ZASOBOW`
		where `PARENT_ID`='".$zasob->ID."'
	";
	$res = DB::query( $sql );
	// Field, Type, Null, Key, Default, Extra
	// ID, int(10), NO, PRI, NULL, auto_increment
	// A_RECORD_CREATE_DATE, varchar(30), NO
	while ($r = DB::fetch( $res )) {
		$komorki [$r->DESC] = $r;
	}

	$errors = array();
	foreach ($komorki as $z_name => $z) {
		if ($z->TYPE != 'KOMORKA') {
			$errors [$z->ID] = 'Wrong type ('.$z->TYPE.','.$z->DESC.')';
		} else if (!array_key_exists($z->DESC, $fields)) {
			$errors [$z->ID] = 'Not exists ('.$z->DESC.')';
		} else {
		}
	}//end foreach

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

	$errors = array();
	foreach ($fields as $f_name => $f_params) {
		if (!array_key_exists($f_name, $komorki)) {
			$errors [$f_name] = 'Not exists ('.json_encode($f_params).')';
		} else {
		}
	}//end foreach
echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">2 ';print_r($errors);echo'</pre>';

}


function ajax_get_proces() {
	echo'<p>TODO: test ajax function L' . __LINE__ . '</p>';
}
