 -- /*!40101 SET NAMES cp1250 */;

DELIMITER $$

DROP PROCEDURE IF EXISTS `erp_do_search_similar`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `erp_do_search_similar`(
	IN _MODE VARCHAR(50),		
	IN _SearchText VARCHAR(250),	
	IN _Key VARCHAR(250),	
	IN _ExtParam VARCHAR(250),	
	IN _MinLen_SearchText INTEGER,	
	IN _Return_Std_Cols BOOLEAN,	--	Jesli 1 to zwracamy zawsze te same kolumny 	np. ze zwracamy wynik z `t_erp_search_similar` w sposob wolany z filtrow-lookupow
	IN _Param_A VARCHAR(250),	
	IN _Param_B VARCHAR(250),	
	IN _Param_C VARCHAR(250),	--	Jesli != '' to znaczy ze zwracamy wynik z `t_erp_search_similar` w sposob wolany z filtrow-lookupow
	IN _Param_D VARCHAR(250)
)
/*
	erp_do_search_similar
*/
S_erp_do_search_similar: BEGIN
	DECLARE _SQLText TEXT;
	DECLARE _NewKontrahGUID VARCHAR(38) DEFAULT '';
	DECLARE _SearchTextWithoutSpaces VARCHAR(255) DEFAULT '';
	DECLARE _Search_USER VARCHAR(38) DEFAULT '';
	DECLARE _SearchLen INTEGER;
	DECLARE _SearchLenAddr INTEGER;
	DECLARE _LIMIT INTEGER;
	DECLARE _SearchIsMail BOOLEAN;

	IF _MinLen_SearchText = 0 THEN
		SET _MinLen_SearchText = 3;
	END IF;
/*	
	IF _SearchLen >= _MinLen_SearchText THEN
	    LEAVE;
	END IF;
*/

	DROP TEMPORARY TABLE IF EXISTS `t_erp_search_similar`;
	SET _Return_Std_Cols = IFNULL(_Return_Std_Cols, FALSE);	
	SET _Key = IFNULL(_Key, '');
	SET _SearchText = IFNULL(_SearchText, '');
	SET _SearchTextWithoutSpaces = _varSTR_Flush_Spaces(_SearchText);
	SET _SearchText = REPLACE(REPLACE(_SearchText, ' ', '%'), '%%', ' ');
	SET _SearchLen = LENGTH(_SearchText);
	SET _Param_A = IFNULL(_Param_A, '');
	SET _Param_B = IFNULL(_Param_B, '');
	SET _Param_C = IFNULL(_Param_C, '');
	
	DROP TEMPORARY TABLE IF EXISTS `t_search_dataset`;
	CREATE TEMPORARY TABLE IF NOT EXISTS `t_search_dataset` 
	(
		`LK_srch` VARCHAR(255) DEFAULT '', 
		`LK_Text` VARCHAR(255) DEFAULT '', 
		`Result_Text` VARCHAR(255) DEFAULT '', 
		`Result_Key` VARCHAR(255) DEFAULT '',
		`Result_Key2` VARCHAR(255) DEFAULT '',
		`Fld_1` VARCHAR(255) DEFAULT '',
		`Fld_2` VARCHAR(255) DEFAULT '',
		`Fld_3` VARCHAR(255) DEFAULT '',
		`Fld_4` VARCHAR(255) DEFAULT '',
		UNIQUE KEY (`Result_Key`),
		KEY (`Result_Key2`)
	) 
	;

	DROP TEMPORARY TABLE IF EXISTS `t_search_work`;
	CREATE TEMPORARY TABLE IF NOT EXISTS `t_search_work` 
	(
		`LK_Srch` VARCHAR(255) NOT NULL DEFAULT '', 
		`LK_Key` VARCHAR(150) NOT NULL DEFAULT '',
		`OrderCol` VARCHAR(10) NOT NULL DEFAULT '1',
		PRIMARY KEY (`LK_Key`)
	) 
	;
-- CALL erp_do_search_similar('SEARCH_KONTO_LIKE.Select', 'aker', '', '', 0, 0, '', '2019','','');
	IF _MODE LIKE 'SEARCH_KONTO_LIKE%' AND _SearchLen >= _MinLen_SearchText THEN
		IF _SearchText='***' THEN SET _SearchText=''; END IF;
		INSERT IGNORE INTO t_search_dataset (LK_Srch, LK_Text, Result_Key)
		SELECT	@lk:=IFNULL(CONCAT(p.symbol_fmt,' ',p.nazwa),'?'),@lk,p.symbol
--		SELECT	@lk:=IFNULL(CONCAT(p.nazwa,' (',p.symbol_fmt,')'),'*'),@lk,p.symbol
		FROM plankont p 
		WHERE p.dl_potomka=0 AND p.zablokowane=0 AND p.rok=_VarInt(_Param_B) AND 
		  (p.nazwa LIKE CONCAT('%',_SearchText, '%') OR 
		   p.symbol_fmt LIKE CONCAT('%',_SearchText, '%')) AND
		   p.kategoria LIKE CONCAT('%',_Param_A, '%');
	END IF;
	
	IF _MODE LIKE 'SEARCH_KONTO_WEBDOC_LIKE%' AND _SearchLen >= _MinLen_SearchText THEN
		IF _SearchText='***' THEN SET _SearchText=''; END IF;
		
		IF(@session.globals.Owner IN ('PBUCH')) THEN
		
		INSERT IGNORE INTO t_search_dataset (LK_Srch, LK_Text, Result_Key)
		SELECT	@lk:=IFNULL(CONCAT(p.nazwa,' (',p.symbol_fmt,')'),'*'),@lk,p.symbol
		FROM plankont p 
		WHERE  p.zablokowane=0 AND p.rok=_VarInt(_Param_B) AND p.symbol LIKE '*|5%' AND p.poziom=4 AND
		  (p.nazwa LIKE CONCAT('%',_SearchText, '%') OR 
		   p.symbol_fmt LIKE CONCAT('%',_SearchText, '%')) AND
		   p.kategoria LIKE CONCAT('%',_Param_A, '%');  
		   
		ELSE
		
		INSERT IGNORE INTO t_search_dataset (LK_Srch, LK_Text, Result_Key)
		SELECT	@lk:=IFNULL(CONCAT(p.nazwa,' (',p.symbol_fmt,')'),'*'),@lk,p.symbol
--		SELECT	@lk:=IFNULL(CONCAT(p.symbol_fmt,' ',p.nazwa),'?'),@lk,p.symbol
		FROM plankont p 
		WHERE p.dl_potomka=0 AND p.zablokowane=0 AND p.rok=_VarInt(_Param_B) AND 
		  (p.nazwa LIKE CONCAT('%',_SearchText, '%') OR 
		   p.symbol_fmt LIKE CONCAT('%',_SearchText, '%')) AND
		   p.kategoria LIKE CONCAT('%',_Param_A, '%');
		END IF;	   
	END IF;

	

-- CALL erp_do_search_similar('SEARCH_KATCOL_LIKE.Select', 'aker', '', '', 0, 0, 'v_kkn2','','','');
	IF _MODE LIKE 'SEARCH_KATCOL_LIKE%' AND _SearchLen >= _MinLen_SearchText THEN
		SET _LIMIT=IF(_Param_D='',2000,_varINT(_Param_D));
		IF _SearchText='***' THEN SET _SearchText=''; END IF;
		INSERT IGNORE INTO t_search_dataset (LK_Srch, LK_Text, Result_Key)
		SELECT	@lk:=IFNULL(CONCAT(k.valuex,' ',k.descr,' (',k.klucz,')'),'*'),@lk,k.klucz
		FROM katcols k, v_katcol_names v 
		WHERE v.typ=k.typ AND v.colnr=k.colnr-1 AND _Param_A IN (v.vname,v.user_vname) AND 
		    k.nieaktywna=0 AND (k.rok=0 OR k.rok=_VarInt(_Param_B)) AND 
			k.param5 NOT LIKE '%X%' AND -- w HT aktywna, w webdoc - nie
		   (k.valuex LIKE CONCAT('%',_SearchText, '%')  OR
		    concat('(',k.klucz,')') LIKE CONCAT('%',_SearchText, '%')  OR
		    k.descr LIKE CONCAT('%',_SearchText, '%')
		   ) 
		 LIMIT _LIMIT;
	END IF;
	
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'SEARCH_KONTRAH_LIKE' 
		Przeszukuje kontrahentów po frazie _SearchText (telefon, mail, etc ale ównie nazwisko lub imiona
		Parametry
			_SearchText			Fraza szukana
			_Param_A			gdy <> '' to jest to GUID kontrahenta
		CALL erp_do_search_similar('SEARCH_KONTRAH_LIKE', 'jmam', '', '', 0, 0, '', '', '', '');				-- szukaj wystapienia 'jmam'
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE LIKE 'SEARCH_KONTRAH_LIKE%' AND _SearchLen >= _MinLen_SearchText THEN
		SET @_Value := '??';	--	Tak trzeba!!!!!!!!!!!!! PATRZ PIM_PhoneNumber
		SET _SearchLenAddr = LENGTH(_SearchTextWithoutSpaces);
		SET _SearchIsMail = LOCATE('@', _SearchTextWithoutSpaces) > 0; -- select _SearchIsMail;
		DROP TEMPORARY TABLE IF EXISTS `t_do_search_kontrah`;
		CREATE TEMPORARY TABLE IF NOT EXISTS `t_do_search_kontrah` 
		(
			`Kontrahent_srch` VARCHAR(255) NOT NULL DEFAULT '', 
			`Kontrahent_Descr` VARCHAR(255) NOT NULL DEFAULT '', 
			`KontrGUID` VARCHAR(38) NOT NULL DEFAULT '',
			PRIMARY KEY (`KontrGUID`)
		) 
		;
		IF _SearchLen >= _MinLen_SearchText THEN
		--	1.	Kontrahent	
			-- INSERT INTO `t_do_search_kontrah` 
			--	(Kontrahent_srch, Kontrahent_Descr, KontrGUID)
			INSERT IGNORE INTO `t_search_work`	(LK_Srch, LK_Key)
			SELECT	IFNULL(CONCAT(
				-- IF(@srch_Symbol,CONCAT(kn.Symbol, ' - ', kn.Nazwa, ''),
				-- IF(@srch_Nazwa OR @srch_NazwaFull,CONCAT(kn.Nazwa, ' - ', kn.Symbol),
				kn.Nazwa, ' - ', kn.Symbol,
				IF(kn.Ulica LIKE CONCAT('%', _SearchText, '%'),CONCAT(kn.Ulica, ', Adres: ', kn.zipcode, ' ', kn.NazwaMiasta),
				IF(kn.NazwaMiasta LIKE CONCAT('%', _SearchText, '%'),CONCAT(kn.NazwaMiasta, ' - Miejsc. '),
				IF(kn.zipcode LIKE CONCAT('%', _SearchText, '%'),CONCAT(kn.zipcode, ' ', kn.NazwaMiasta),
				IF(kn.nip LIKE CONCAT('%', _SearchText, '%'),CONCAT(kn.nip, ' NIP'),
				IF(IFNULL(kn.regon,'*') LIKE CONCAT('%', _SearchText, '%'),CONCAT(IFNULL(kn.regon,''), ' REGON'),
				IF(IFNULL(kn.pesel,'*') LIKE CONCAT('%', _SearchText, '%'),CONCAT(IFNULL(kn.pesel,''), ' PESEL'),
				''))))))
				),'*'
			) AS Kontrahent_srch,	
			kn.GUID
			
			FROM `kontrah` kn
			WHERE
				(@srch_Symbol := kn.Symbol LIKE CONCAT(_SearchText, '%')) OR
				(@srch_Nazwa  := IF((_SearchLen < 4), FALSE, kn.Nazwa LIKE CONCAT('%',_SearchText, '%'))) OR
				(@srch_Miasto := IF((_SearchLen < 5), FALSE, kn.NazwaMiasta LIKE CONCAT(_SearchText, '%'))) OR
				(@srch_Ulica  := IF((_SearchLen < 5) OR _SearchIsMail, FALSE, kn.Ulica LIKE CONCAT('%', _SearchText, '%'))) OR
				(@srch_zipcode:= IF((_SearchLen < 5) OR _SearchIsMail, FALSE, kn.zipcode LIKE CONCAT(_SearchText, '%'))) OR
				(@srch_Nip    := IF((_SearchLen < 4) OR _SearchIsMail, FALSE, kn.nip LIKE CONCAT(_SearchText, '%'))) OR
				(@srch_Regon  := IF((_SearchLen < 4) OR _SearchIsMail, FALSE, kn.regon LIKE CONCAT(_SearchText, '%'))) OR
				(@srch_Pesel  := IF((_SearchLen < 4) OR _SearchIsMail, FALSE, kn.pesel LIKE CONCAT(_SearchText, '%')))
			;
			DROP TEMPORARY TABLE IF EXISTS `t_do_search_kontrah`;
			CREATE TEMPORARY TABLE IF NOT EXISTS `t_do_search_kontrah` 
			(
				`Kontrahent_srch` VARCHAR(255) NOT NULL DEFAULT '', 
				`Kontrahent_Descr` VARCHAR(255) NOT NULL DEFAULT '', 
				`KontrGUID` VARCHAR(38) NOT NULL DEFAULT '',
				KEY (`KontrGUID`)
			) 
			;
			
			TRUNCATE `t_do_search_kontrah`;
		--	2.	Kontakty	
			INSERT IGNORE INTO `t_do_search_kontrah` (Kontrahent_srch, Kontrahent_Descr, KontrGUID)
			SELECT
				IFNULL(
				  IF(@srch_Adres,CONCAT(IF(t.media_notify=0,PIM_PhoneNumber('FMT1', k.adres, k.typ_medium), k.adres), ' ', t.Descryption),NULL) 
				  ,'*'),	
				_VarStr(''),
				k.KontrGUID
			
			FROM `kontakty` k
			LEFT JOIN v_pim_media_types t ON t.ID = k.typ_medium
			WHERE	IFNULL(k.KontrGUID,'')<>'' AND
				(@srch_Adres := IF((_SearchLenAddr < 4) and (NOT _SearchIsMail), FALSE, k.Adres LIKE CONCAT('%', _SearchTextWithoutSpaces, '%')))
			;
		--	3.	Osoby	
			INSERT IGNORE INTO `t_do_search_kontrah` (Kontrahent_srch, Kontrahent_Descr, KontrGUID)
			SELECT	IFNULL(LTRIM(CONCAT(o.Imiona, ' ', o.Nazwisko, ' osob.kontr.')),'*'),
				_VarStr(''),
				o.KontrGUID
			FROM `osoby` o
			WHERE	IFNULL(o.KontrGUID, '') != '' AND (
				(@srch_Imie1 := IF((_SearchLen < 5) OR _SearchIsMail, FALSE, CONCAT(o.Imiona, ' ', o.Nazwisko) LIKE CONCAT(_SearchText, '%'))) OR
				(@srch_Nazwisko := IF((_SearchLen < 5) OR _SearchIsMail, FALSE, CONCAT(o.Nazwisko, ' ', o.Imiona) LIKE CONCAT(_SearchText, '%'))) OR
				(@srch_ImionaNazwisko := IF((_SearchLen < 5) OR _SearchIsMail, FALSE, CONCAT(o.Imiona, ' ', o.Nazwisko) LIKE CONCAT(_SearchText, '%'))) OR
				(@srch_NazwiskoImiona := IF((_SearchLen < 5) OR _SearchIsMail, FALSE, CONCAT(o.Nazwisko, ' ', o.Imiona) LIKE CONCAT(_SearchText, '%')))
				)	
			;
		--	4. OBIEKTY/LOKALIZACJE
			INSERT IGNORE INTO `t_do_search_kontrah` (Kontrahent_srch, Kontrahent_Descr, KontrGUID)
			SELECT 	LTRIM(CONCAT(k.Nazwa, ' ', k.Symbol,IFNULL(CONCAT(' ob:',ean.symbol,' ',ean.nazwa),''))),
			REPLACE(REPLACE(IFNULL(
			CONCAT(SUBSTRING_INDEX(adr.adres,'(',1),ean.nazwa,' ',k.nazwamiasta,', ',k.ulica),''),'"',''),"'",'')  AS adres,
			k.guid
			FROM kontrah k 
			INNER JOIN erp_area_nodes ean ON k.guid = ean.KontrGUID AND ean.type = 'LOC' 
			LEFT JOIN geo_int_adr_link adr ON adr.objGUID = ean.guid AND adr.objTable = 'erp_area_nodes'
			WHERE _SearchLen>3 AND (
			      CONCAT(ean.symbol,' ',ean.nazwa) LIKE CONCAT('%',_SearchText, '%') OR
			      IFNULL(adr.adres,'*') LIKE CONCAT('%',_SearchText, '%')
			      );
			      
		--	5. DOKUMENTY
			INSERT IGNORE INTO `t_do_search_kontrah` (Kontrahent_srch, Kontrahent_Descr, KontrGUID)
			SELECT 	LTRIM(CONCAT(k.Nazwa, ' ', k.Symbol,IFNULL(CONCAT(' dok:',d.nazwa),''))),ifnull(d.nazwa,'?'),k.guid
			FROM kontrah k 
			INNER JOIN dokumenty d ON d.klucz = k.GUID
			WHERE _SearchLen>3 AND d.nazwa LIKE CONCAT('%',_SearchText, '%');

			INSERT IGNORE INTO `t_search_work` (LK_Srch, LK_Key)
			SELECT GROUP_CONCAT(DISTINCT Kontrahent_srch SEPARATOR ', '),KontrGUID 
			FROM `t_do_search_kontrah` 
			GROUP BY KontrGUID
			;
			
		END IF;

		IF _Key != '' THEN --	tylko z GUIDA
			INSERT IGNORE INTO `t_search_work` (LK_Srch, LK_Key)
			SELECT CONCAT('', kn.Nazwa, ' - ', kn.Symbol) AS LK_srch,kn.GUID AS Result_Key
			FROM `kontrah` kn
			WHERE kn.GUID = _Key
			;		
		END IF;
		
	--	Final
		-- CREATE TEMPORARY TABLE `t_erp_search_similar`
		IF _ExtParam = 'ALL' THEN
			SET @ALL_Status = 10000;
		ELSE
			SET @ALL_Status = 0;
		END IF;
	--	Gdy w _Param_D !+ '' to badaj UGrpGUID	
		IF @session.globals.Owner = 'TRANSBUD' THEN
			SET _Param_D = '1';
		END IF;
		
		SET _Search_USER = '';
		
		IF _Param_D != '' THEN
			SET _Search_USER = IFNULL(@SYSTEM.Client.Session.log_USER_GUID,'');
			SET _Search_USER = IF(_Search_USER!='',_Search_USER,IFNULL(@session.Registration.UserGUID, ''));
		END IF;
		SET @._Search_USER = _Search_USER, @_Param_D = _Param_D;
		INSERT IGNORE INTO `t_search_dataset` (LK_Text, LK_srch, Result_Text, Result_Key, Fld_1)
		SELECT 	
		-- _VarStr(@LK_Text := LTRIM(CONCAT('', k.Nazwa, ' - ', k.Symbol))) AS LK_Text,
			_VarStr(@LK_Text := LTRIM(CONCAT(IFNULL(NULLIF(_Search_USER, ''),'???'), ' ', k.Nazwa, ' - ', k.Symbol))) AS LK_Text,
			_VarStr(IF(IFNULL(t.LK_Srch, '') = '', @LK_Text, t.LK_Srch)) AS LK_srch,
			@LK_Text AS Result_Text,
			IFNULL(kl.KontrGuid_A, t.LK_Key) AS Result_Key, k.symbol AS Fld_1
		FROM `t_search_work` t
		INNER JOIN `kontrah` k ON k.GUID = t.LK_Key -- KontrGUID
		LEFT JOIN `kontrah_self_links` kl ON kl.KontrGuid_B = k.GUID AND kl.Rel = '='
		WHERE	
			k.Status <= @ALL_Status 
			AND k.Deleted = 0 
			AND
			(_Search_USER = '' 
			OR 
			-- (SELECT COUNT(*) FROM grupy_osob grp WHERE grp.grupaGUID = k.ugrpGUID AND grp.osobaGUID = _Search_USER) > 0
			EXISTS(SELECT grp.grupaGUID FROM `grupy_osob` grp WHERE grp.grupaGUID = k.ugrpGUID AND grp.osobaGUID = _Search_USER)
			)
		GROUP BY t.LK_Key -- t.KontrGUID
		ORDER BY t.OrderCol
		;
		DROP TEMPORARY TABLE IF EXISTS `t_do_search_kontrah`;
	END IF; -- _MODE = 'SEARCH_KONTRAH_LIKE'

/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'SEARCH_OSOBY_LIKE'
		Przeszukuje kontakty po frazie _SearchText (telefon, mail, etc ale ównie nazwisko lub imiona
		Parametry
			_SearchText			Fraza szukana
			_Param_A			= '' to również grupy
								  '' tylko osoby
			_Param_B			
								= '' 	to tylko widoczne w HR
								!= ''	wszystkie osoby 
			_Param_C			
								= '' 	to nie serwisowcy
								!= ''	wszystkie osoby 
		CALL erp_do_search_similar('SEARCH_OSOBY_LIKE', 'jmam', '', '', 0, 0, '', '', '', '');				-- szukaj wystapienia 'jmam'
		CALL erp_search_similar('SEARCH_OSOBY_LIKE', 'jmam', '', '', '', '');				-- szukaj wystapienia 'jmam'
		CALL erp_search_similar('SEARCH_OSOBY_LIKE', 'jmam', '1', '', '', '');			-- szukaj wystapienia 'jmam' ale tylko osoby
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE LIKE 'SEARCH_OSOBY_LIKE%' THEN
		SET @_Value := '??';	--	Tak trzeba!!!!!!!!!!!!! PATRZ PIM_PhoneNumber
		-- SET _SearchTextTrimSpaces = RTrim(_SearchText);
		SET _SearchLenAddr = LENGTH(_SearchTextWithoutSpaces);
		SET _SearchIsMail = LOCATE('@', _SearchTextWithoutSpaces) > 0; -- select _SearchIsMail;
		
		IF RIGHT(_SearchText, 1) = ' ' THEN
			SET _SearchLen = 100;
		END IF;
		
		SET
			@_Param_A = _Param_A,
			@_Param_B = _Param_B,
			@_SearchText = _SearchText,
			@_SearchTextWithoutSpaces = _SearchTextWithoutSpaces,
			-- @_SearchTextTrimSpaces = _SearchTextTrimSpaces,
			@_SearchLen = _SearchLen,
			@_SearchLenAddr = _SearchLenAddr,
			@_SearchIsMail = _SearchIsMail
		;
		
		DROP TEMPORARY TABLE IF EXISTS `t_search_osoby`;
		CREATE TEMPORARY TABLE IF NOT EXISTS `t_search_osoby` 
		(
			`LK_Srch` VARCHAR(255) NOT NULL DEFAULT '', 
			`ImionaNazwisko` VARCHAR(255) NOT NULL DEFAULT '', 
			`OsobaGUID` VARCHAR(38) NOT NULL DEFAULT '',
			`OrderCol` VARCHAR(10) NOT NULL DEFAULT '1',
			PRIMARY KEY (`OsobaGUID`)
		) 
		;
		IF _SearchLen >= _MinLen_SearchText THEN
		--	1.	Osoby	
			-- INSERT IGNORE INTO `t_search_osoby` 
			--	(LK_Srch, ImionaNazwisko, OsobaGUID, OrderCol)
			INSERT IGNORE INTO `t_search_work`
				(LK_Srch, LK_Key, OrderCol)
				SELECT
					_VarStr(
						IFNULL(
							GROUP_CONCAT(DISTINCT 
								IF(@srch_Nazwisko OR @srch_NazwiskoImiona, -- !!! o.Nazwisko LIKE CONCAT(_SearchText, '%'),
									LTRIM(CONCAT(o.Nazwisko, ' ', o.Imiona)),
									IF(@srch_Imie1 OR @srch_ImionaNazwisko, -- !!! o.Nazwisko LIKE CONCAT(_SearchText, '%'),
										LTRIM(CONCAT(o.Imiona, ' ', o.Nazwisko)),
										IF(@srch_NrPesel, -- !!! o.NrPesel LIKE CONCAT('%', _SearchText, '%'),
											CONCAT(o.NrPesel, ' PESEL'),
											IF(@srch_NrNIP, -- !!! o.NrNIP LIKE CONCAT('%', _SearchText, '%'),
												CONCAT(o.NrNIP, ' NIP'),
												IF(@srch_NrSeriaDowoduOsobistego, -- !!! o.NrSeriaDowoduOsobistego LIKE CONCAT('%', _SearchText, '%'),
													CONCAT(o.NrSeriaDowoduOsobistego, ' Nr dok.osob.'),
													IF(@srch_IdnUser, -- !!! o.idnuser LIKE CONCAT('%', _SearchText, '%'),
														CONCAT(o.idnuser, IF(o.Rodzaj, ' NICK', ' GRUPA')),
														NULL
													)	
												)	
											) 
										)	
									) 
								)	
							SEPARATOR ', '
							),
							'*'
						)	
					) AS LK_Srch,
					/*
					_VarStr(
						LTRIM(CONCAT(o.Nazwisko, ' ', o.Imiona))
					),
					*/
					o.GUID,
					IF(@srch_Nazwisko, 0, 1) AS OrderCol
						
				FROM `osoby` o
				WHERE
					IFNULL(o.GUID, '') != ''
					AND
					IF(_Param_A = '', 
						TRUE,
						o.rodzaj != 0
					) AND
					IF(_Param_B != '', 
						TRUE,
						o.niewidoczna_w_HR = 0
					) AND
				--	IF(_Param_C != '', 
				--		TRUE,
				--		o.seriws???? = 0
				--	) AND
					(
						(@srch_Nazwisko := IF((_SearchLen < 2), FALSE, o.Nazwisko LIKE CONCAT(_SearchText, '%')))
						-- o.Nazwisko LIKE CONCAT(_SearchText, '%')
						OR
						(@srch_Imie1 := IF((_SearchLen < 1), FALSE, o.Imie1 LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_IdnUser := (o.idnuser LIKE CONCAT(_SearchText, '%')))
						-- OR
						-- IF((_SearchLen < 5), FALSE, o.Imie2 LIKE CONCAT(_SearchText, '%'))
						OR
						-- CONCAT(o.Imiona, ' ', o.Nazwisko) LIKE CONCAT(_SearchText, '%')	
						(@srch_ImionaNazwisko := IF((_SearchLen < 4) OR _SearchIsMail, FALSE, CONCAT(o.Imiona, ' ', o.Nazwisko) LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_ImionaNazwisko := IF((_SearchLen < 4) OR _SearchIsMail, FALSE, CONCAT(o.Imie1, ' ', o.Nazwisko) LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_NazwiskoImiona := IF((_SearchLen < 4) OR _SearchIsMail, FALSE, CONCAT(o.Nazwisko, ' ', o.Imiona) LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_NazwiskoImiona := IF((_SearchLen < 4) OR _SearchIsMail, FALSE, CONCAT(o.Nazwisko, ' ', o.Imie1) LIKE CONCAT(_SearchText, '%')))
						-- CONCAT(o.Nazwisko, ' ', o.Imiona) LIKE CONCAT(_SearchText, '%')
						OR
						(@srch_NrPesel := IF((_SearchLen < 4) OR _SearchIsMail, FALSE, o.NrPesel LIKE CONCAT(_SearchText, '%')))
						-- o.NrPesel LIKE CONCAT(_SearchText, '%')
						OR
						(@srch_NrNIP := IF((_SearchLen < 4) OR _SearchIsMail, FALSE, o.NrNIP LIKE CONCAT(_SearchText, '%')))
						-- o.NrNIP LIKE CONCAT(_SearchText, '%')
						OR
						(@srch_NrSeriaDowoduOsobistego := IF((_SearchLen < 5) OR _SearchIsMail, FALSE, o.NrSeriaDowoduOsobistego LIKE CONCAT(_SearchText, '%')))
						-- o.NrSeriaDowoduOsobistego LIKE CONCAT(_SearchText, '%')
					)	
			GROUP BY o.GUID
			LIMIT 40
			;
			
		--	2.	Kontakty	
			INSERT IGNORE INTO `t_search_work`
				(LK_Srch, LK_Key)
			-- INSERT IGNORE INTO `t_search_osoby` 
				-- (LK_Srch, ImionaNazwisko, OsobaGUID)
				SELECT
					IFNULL(
						GROUP_CONCAT(DISTINCT 
							IF(@srch_Adres, -- !!! _varSTR_Flush_Spaces(k.Adres) LIKE CONCAT('%', _SearchTextWithoutSpaces, '%'),
							-- bylo	CONCAT('<', IF(t.media_notify = 0, PIM_PhoneNumber('FMT1', k.adres, k.typ_medium), k.adres), '>'), 
								CONCAT('', IF(t.media_notify = 0, PIM_PhoneNumber('FMT1', k.adres, k.typ_medium), k.adres), ' ', t.Descryption), 
								NULL
							) 
						SEPARATOR ', '
						),
						'*'
					) AS LK_Srch,	
					-- _VarStr(''),
					k.OsobaGUID
						
				FROM `kontakty` k
				LEFT JOIN v_pim_media_types t ON t.ID = k.typ_medium
				WHERE
					k.OsobaGUID IS NOT NULL 
					AND
					(
	-- 					(@srch_Adres := IF((_SearchLenAddr < 3) and (NOT _SearchIsMail), FALSE, _varSTR_Flush_Spaces(k.Adres) LIKE CONCAT('%', _SearchTextWithoutSpaces, '%')))
						(@srch_Adres := IF((_SearchLenAddr < 3) and (NOT _SearchIsMail), FALSE, k.Adres LIKE CONCAT('%', _SearchTextWithoutSpaces, '%')))
					)	
			GROUP BY k.OsobaGUID
			LIMIT 40
			;
			
		--	3.	Kontrahent	
			IF IFNULL(@session.globals.hr.HR_SEARCH_BY_hr_kontrah_links, 0) THEN
			--	NOWE szukanie -> by `hr_kontrah_links`
				INSERT IGNORE INTO `t_search_work`
					(LK_Srch, LK_Key)
				-- INSERT IGNORE INTO `t_search_osoby` 
					-- (LK_Srch, ImionaNazwisko, OsobaGUID)
					SELECT
						IFNULL(
							GROUP_CONCAT(DISTINCT 
									IF(@srch_Nazwa OR @srch_NazwaFull, -- !!! kn.Symbol LIKE CONCAT(_SearchText, '%') OR kn.Nazwa LIKE CONCAT('%', _SearchText, '%'),
										CONCAT(kn.Nazwa, ' kontrahent'),
										IF(@srch_Symbol, -- !!! kn.Symbol LIKE CONCAT(_SearchText, '%') OR kn.Nazwa LIKE CONCAT('%', _SearchText, '%'),
											CONCAT(kn.Symbol,' - ', kn.Nazwa, '  kontrahent'),
											NULL
										)	
									) 
							SEPARATOR ', '
							),
							'*'
						) AS LK_Srch,	
						-- _VarStr(''),
						o.GUID
							
					FROM `osoby` o
					INNER JOIN `hr_kontrah_links` hk ON hk.osobaGUID = o.GUID
					INNER JOIN `kontrah` kn ON kn.GUID = hk.KontrGUID
					WHERE
						IFNULL(o.KontrGUID, '') != ''
						AND
						IFNULL(o.GUID, '') != ''
						AND
						IF(_Param_A = '', 
							TRUE,
							o.rodzaj != 0
						) AND
						IF(_Param_B != '', 
							TRUE,
							o.niewidoczna_w_HR = 0
						) AND
						(
						(@srch_Symbol := IF((_SearchLen < 3), FALSE, kn.Symbol LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_Nazwa := IF((_SearchLen < 3), FALSE, kn.Nazwa LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_NazwaFull := IF((_SearchLen < 6), FALSE, kn.Nazwa LIKE CONCAT('%', _SearchText, '%')))
						)
				GROUP BY o.GUID
				LIMIT 40
				;
			ELSE
			--	Stare szukanie -> by osoby.KontrGUID
				INSERT IGNORE INTO `t_search_work`
					(LK_Srch, LK_Key)
				-- INSERT IGNORE INTO `t_search_osoby` 
					-- (LK_Srch, ImionaNazwisko, OsobaGUID)
					SELECT
						IFNULL(
							GROUP_CONCAT(DISTINCT 
									IF(@srch_Nazwa OR @srch_NazwaFull, -- !!! kn.Symbol LIKE CONCAT(_SearchText, '%') OR kn.Nazwa LIKE CONCAT('%', _SearchText, '%'),
										CONCAT(kn.Nazwa, ' kontrahent'),
										IF(@srch_Symbol, -- !!! kn.Symbol LIKE CONCAT(_SearchText, '%') OR kn.Nazwa LIKE CONCAT('%', _SearchText, '%'),
											CONCAT(kn.Symbol,' - ', kn.Nazwa, '  kontrahent'),
											NULL
										)	
									) 
							SEPARATOR ', '
							),
							'*'
						) AS LK_Srch,	
						-- _VarStr(''),
						o.GUID
							
					FROM `osoby` o
					INNER JOIN `kontrah` kn ON kn.GUID = o.KontrGUID
					WHERE
						IFNULL(o.KontrGUID, '') != ''
						AND
						IFNULL(o.GUID, '') != ''
						AND
						IF(_Param_A = '', 
							TRUE,
							o.rodzaj != 0
						) AND
						IF(_Param_B != '', 
							TRUE,
							o.niewidoczna_w_HR = 0
						) AND
						(
						(@srch_Symbol := IF((_SearchLen < 3), FALSE, kn.Symbol LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_Nazwa := IF((_SearchLen < 3), FALSE, kn.Nazwa LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_NazwaFull := IF((_SearchLen < 6), FALSE, kn.Nazwa LIKE CONCAT('%', _SearchText, '%')))
						)
				GROUP BY o.GUID
				LIMIT 40
				;
			END IF; -- kontrah
			
		--	4.	Karty	
			INSERT IGNORE INTO `t_search_work`
				(LK_Srch, LK_Key)
			-- INSERT IGNORE INTO `t_search_osoby` 
				-- (LK_Srch, ImionaNazwisko, OsobaGUID)
				SELECT
					IFNULL(
						GROUP_CONCAT(DISTINCT 
								IF(@srch_Symbol, 
									CONCAT(c.ID, ' - ', c.KindStr),
									NULL
								) 
						SEPARATOR ', '
						),
						'*'
					) AS LK_Srch,	
					-- _VarStr(''),
					o.GUID
						
				FROM `v_hr_cards` c
				INNER JOIN `osoby` o ON c.OsobaGUID = o.GUID
				WHERE
					IFNULL(c.OsobaGUID, '') != ''
					AND
					IFNULL(o.GUID, '') != ''
					AND
					IF(_Param_A = '', 
						TRUE,
						o.rodzaj != 0
					) AND
					IF(_Param_B != '', 
						TRUE,
						o.niewidoczna_w_HR = 0
					) AND
					(
					(@srch_Symbol := IF((_SearchLen < 3), FALSE, c.ID LIKE CONCAT(_SearchText, '%')))
					)
			GROUP BY o.GUID
			LIMIT 40
			;
		END IF;
		
		IF _Key != '' THEN
		--	tylko z GUIDA
			INSERT IGNORE INTO `t_search_work`
			(LK_Srch, LK_Key)
				SELECT
					LTRIM(CONCAT(TRIM(o.Imiona), ' ', TRIM(o.Nazwisko))) AS LK_srch,
					o.GUID AS Result_Key
				FROM `osoby` o 
				WHERE
					o.GUID = _Key
			;		
		END IF;
		
	--	Final
		IF IFNULL(@session.globals.Owner, '') != 'CRIST' THEN
			INSERT INTO `t_search_dataset`
			(LK_srch, LK_Text, Result_Text, Result_Key, Result_Key2)
				SELECT 
					t.LK_Srch,
					_VarStr(@LK_Text := 
						LTRIM(CONCAT(TRIM(o.Imiona), ' ', TRIM(o.Nazwisko)))
					) AS LK_Text,
					@LK_Text AS Result_Text, 
					t.LK_Key AS Result_Key,
					o.IdnUser AS Result_Key2
					
				-- FROM `t_search_osoby` t
				FROM `t_search_work` t
				INNER JOIN `osoby` o ON o.GUID = t.LK_Key
				WHERE
					TRUE -- AND IFNULL(t.OsobaGUID, '') != ''
			-- ORDER BY MIN(OrderCol), ImionaNazwisko
			;
		ELSE
			INSERT INTO `t_search_dataset`
			(LK_srch, LK_Text, Result_Text, Result_Key, Result_Key2)
				SELECT 
					t.LK_Srch,
					_VarStr(@LK_Text := 
						CONCAT(
						LTRIM(CONCAT(TRIM(o.Imiona), ' ', TRIM(o.Nazwisko))),
						' ur. ', o.DataUrodzenia,
						_ConcatSTR(
							CONCAT(' PESEL: ', o.NrPesel),
							IFNULL(GROUP_CONCAT(DISTINCT CONCAT(hc.ID, IF(hc.Status = 1, ' nieakt.', '')) SEPARATOR ', ' ), ''),
							', nr.przep.: '
						)
						)
					) AS LK_Text, 
					@LK_Text AS Result_Text, 
					t.LK_Key AS Result_Key,
					o.IdnUser AS Result_Key2
					
				-- FROM `t_search_osoby` t
				FROM `t_search_work` t
				INNER JOIN `osoby` o ON o.GUID = t.LK_Key
				LEFT JOIN `hr_cards` hc ON hc.OsobaGUID = t.LK_Key AND hc.Kind = 'PASS' AND hc.ID != hc.OsobaGUID
				WHERE
					TRUE -- AND IFNULL(t.OsobaGUID, '') != ''
			-- ORDER BY MIN(OrderCol), ImionaNazwisko
			;
		END IF;
		DROP TEMPORARY TABLE IF EXISTS `t_search_osoby`;
	END IF; -- _MODE = 'SEARCH_OSOBY_LIKE'

/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'SEARCH_FK_LIKE'
		Przeszukuje konta po frazie _SearchText (Symbol_fmt, Nazwa
		Parametry
			_SearchText			Fraza szukana
			_ExtParam			Rok
			_Return_Std_Cols 	Gdy 1 do w ID mamy GUID gdy 2 to Symbol_fmt
		CALL erp_do_search_similar('SEARCH_FK_LIKE', '010-', '', '2012', 0, 1, '', '', '', '');
		CALL erp_do_search_similar('SEARCH_FK_LIKE', 'aparaty', '', '2012', 0, 1, '', '', '', '');		-- szukaj wystapienia 'aparaty' w roku 2012
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE LIKE 'SEARCH_FK_LIKE%' THEN
		SET @_Value := '??';	--	Tak trzeba!!!!!!!!!!!!! PATRZ PIM_PhoneNumber
		IF IFNULL(_ExtParam, '') = '' THEN
			SET _ExtParam = YEAR(CURRENT_DATE());
		END IF;
		SET @IsDigit = (LEFT(_SearchText, 1) IN ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'));
		-- IREG 'Konta_pierwsze_znaki_bez_separatora'  INT\SYSTEM\MOTLAWA\FK  w CDG = 3
	-- 	IF @IsDigit AND LENGTH(_SearchText) <= 3 + 3 + 3 THEN
		IF @IsDigit THEN
				SET @Poziom2 = -1;
				SELECT 
					p.poziom 
				FROM `plankont` p
				WHERE
					p.Rok = _ExtParam
					AND
					p.Symbol_fmt = _SearchText
				INTO @Poziom2	
				;	
				SET @Poziom2 = IFNULL(@Poziom2, -1);
		
			IF LOCATE('-', _SearchText) = 99990 THEN
			-- IF _SearchLen < 3 THEN
				SET @Poziom = 1;
			ELSE	
			
				SELECT 
					MIN(p.poziom) 
				FROM `plankont` p
				WHERE
					p.Rok = _ExtParam
					AND
					p.Symbol_fmt LIKE CONCAT(_SearchText, '%')
				INTO @Poziom	
				;	
				SET @Poziom = IFNULL(@Poziom,1);
			END IF;
			
			IF LOCATE('-', _SearchText) = 0 THEN
				SET @Poziom = @Poziom - 1;
			END IF;
			
			IF @Poziom2 > 0 THEN
				SET @Poziom = @Poziom2;
			END IF; 
			
			-- CREATE TEMPORARY TABLE `t_erp_search_similar`
			INSERT INTO `t_search_dataset`
			(LK_srch, LK_Text, Result_Text, Result_Key, Result_Key2, Fld_1, Fld_2, Fld_3)
				SELECT
					_CutSTR(
						IF(@srch_Nazwa,
							p.Nazwa,
							IF(@srch_Symbol_Fmt,
								CONCAT(Symbol_fmt, IF(p.Dl_potomka > 0, '  (+)', '')),
								CONCAT(Symbol_fmt, IF(p.Dl_potomka > 0, '  (+)', ''))
							)	
						),
						30, '...'
					) AS LK_srch,	
					_VarStr(
						IF(@srch_Symbol_Fmt,
							p.Nazwa,
							CONCAT(CONCAT(Symbol_fmt, IF(p.Dl_potomka > 0, ' (+)', '')), ' ', Nazwa)
						)
					) AS LK_Text,
					_VarStr(
							CONCAT(CONCAT(Symbol_fmt, IF(p.Dl_potomka > 0, ' (+)', '')), ' ', Nazwa)
					) AS Result_Text,
					IF(_Return_Std_Cols = '2', p.Symbol_fmt, p.GUID) AS Result_Key,
					IF(_Return_Std_Cols = '2', p.GUID, p.Symbol_fmt) AS Result_Key2,
					p.Poziom AS Fld_1,
					@Poziom2 AS Fld_2,
					@Poziom AS Fld_3
				FROM `plankont` p
				WHERE
					p.Rok = _ExtParam
					AND
					p.Poziom <= @Poziom	+ 1
					AND
					(
						(@srch_Symbol_Fmt := IF((_SearchLen < 2), FALSE, p.Symbol_fmt LIKE CONCAT(_SearchText, '%')))
					)
				-- ORDER BY KontoSearch	
				LIMIT 500
			;
		ELSE
			-- CREATE TEMPORARY TABLE `t_erp_search_similar`
			INSERT INTO `t_search_dataset`
			(LK_srch, LK_Text, Result_Text, Result_Key, Result_Key2)
				SELECT
					_CutSTR(
						IF(@srch_Nazwa,
							p.Nazwa,
							IF(@srch_Symbol_Fmt,
								CONCAT(Symbol_fmt, IF(p.Dl_potomka > 0, '  (+)', '')),
								CONCAT(Symbol_fmt, IF(p.Dl_potomka > 0, '  (+)', ''))
							)	
						),
						30, '...'
					) AS LK_srch,	
					_VarStr(
						IF(@srch_Symbol_Fmt,
							p.Nazwa,
							CONCAT(CONCAT(Symbol_fmt, IF(p.Dl_potomka > 0, ' (+)', '')), ' ', Nazwa)
						)
					) AS LK_Text,
					_VarStr(
							CONCAT(CONCAT(Symbol_fmt, IF(p.Dl_potomka > 0, ' (+)', '')), ' ', Nazwa)
					) AS Result_Text,
					IF(_Return_Std_Cols = '2', p.Symbol_fmt, p.GUID) AS Result_Key,
					IF(_Return_Std_Cols = '2', p.GUID, p.Symbol_fmt) AS Result_Key2
				FROM `plankont` p
				WHERE
					p.Rok = _ExtParam
					AND
					(
						(@srch_Symbol_Fmt := IF((_SearchLen < 3), FALSE, p.Symbol_fmt LIKE CONCAT(_SearchText, '%')))
					OR
						(@srch_Nazwa := IF((_SearchLen < 4), FALSE, p.Nazwa LIKE CONCAT('%', _SearchText, '%')))
					-- OR
					-- (@srch_NazwaFull := IF((_SearchLen < 6), FALSE, kn.Nazwa LIKE CONCAT('%', _SearchText, '%')))
					)
				-- ORDER BY KontoSearch	
				LIMIT 500
			;
		END IF;
		/*
	--	SELECT	
		IF _Return_Std_Cols = 0 THEN
			SELECT * FROM `t_erp_search_similar`;
		ELSE
			SELECT 
				KontoSearch AS LookupStr, Konto_descr AS Descr, ResultText, IF(_Return_Std_Cols = '2', Symbol_fmt, GUID) AS ID
			FROM `t_erp_search_similar`
			;
		END IF;
	--	DROP 
		*/
		-- DROP TEMPORARY TABLE IF EXISTS `t_erp_search_similar`;
	END IF; -- _MODE = 'SEARCH_FK_LIKE'


/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
'SEARCH_TOWAR_LIKE'
	Przeszukuje towary po frazie _SearchText (nazwa, symbol, symboludost, SymbolProducenta, kod_kreskowy, kod_kreskowy1, kod_kreskowy2
	Parametry
		_SearchText			Fraza szukana
	CALL erp_do_search_similar('SEARCH_TOWAR_LIKE', '23234', '', '', 0, 0, '', '', '', '');
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE LIKE 'SEARCH_TOWAR_LIKE%' THEN
		SET @_Value := '??';	--	Tak trzeba!!!!!!!!!!!!! PATRZ PIM_PhoneNumber
		SET _SearchText = IFNULL(_SearchText, '');
		SET _SearchTextWithoutSpaces = _varSTR_Flush_Spaces(_SearchText);
		SET _SearchLen = LENGTH(_SearchText);
		SET _SearchLenAddr = LENGTH(_SearchTextWithoutSpaces);
		SET _SearchIsMail = LOCATE('@', _SearchTextWithoutSpaces) > 0; -- select _SearchIsMail;

		SET
			@srch_TowrNazwa := FALSE,
			@srch_TowrSymbol := FALSE,
			@srch_TowrSymbol_u_dost := FALSE,
			@srch_TowrSymbol_produc := FALSE,
			@srch_instancje_kod_kreskowy := FALSE,
			@srch_instancje_kod_kreskowy1 := FALSE,
			@srch_instancje_kod_kreskowy2 := FALSE
		;
					DROP TEMPORARY TABLE IF EXISTS `t_erp_search_similar_Towary`;
					CREATE TEMPORARY TABLE `t_erp_search_similar_Towary`
						SELECT 	
							(@srch_TowrNazwa := IF(_SearchLen < 3, FALSE, t.Nazwa LIKE CONCAT('%', _SearchText, '%'))) AS srch_TowrNazwa,
							(@srch_TowrSymbol := (t.Symbol LIKE CONCAT(_SearchText, '%'))) AS srch_TowrSymbol,
							(@srch_TowrSymbol_u_dost := IF(_SearchLen < 3, FALSE, t.symboludost LIKE CONCAT(_SearchText, '%'))) AS srch_TowrSymbol_u_dost,
							(@srch_TowrSymbol_produc := IF(_SearchLen < 3, FALSE, t.SymbolProducenta LIKE CONCAT(_SearchText, '%'))) AS srch_TowrSymbol_produc,
							(@srch_instancje_kod_kreskowy := IF(_SearchLen < 3, FALSE, t.kod_kreskowy LIKE CONCAT(_SearchText, '%'))) AS srch_instancje_kod_kreskowy,
							(@srch_instancje_kod_kreskowy1 := IF(_SearchLen < 3, FALSE, t.kod_kreskowy1 LIKE CONCAT(_SearchText, '%'))) AS srch_instancje_kod_kreskowy1,
							(@srch_instancje_kod_kreskowy2 := IF(_SearchLen < 3, FALSE, t.kod_kreskowy2 LIKE CONCAT(_SearchText, '%'))) AS srch_instancje_kod_kreskowy2,
							t.Symbol, t.Nazwa, t.symboludost, t.SymbolProducenta, t.kod_kreskowy, t.kod_kreskowy1, t.kod_kreskowy2,
							t.GUID
						FROM `TowrNg` t
						WHERE		
							(
								(@srch_TowrNazwa := IF(_SearchLen < 3, FALSE, t.Nazwa LIKE CONCAT('%', _SearchText, '%')))
								OR
								(@srch_TowrSymbol := (t.Symbol LIKE CONCAT(_SearchText, '%')))
								OR
								(@srch_TowrSymbol_u_dost := IF(_SearchLen < 3, FALSE, t.symboludost LIKE CONCAT(_SearchText, '%')))
								OR
								(@srch_TowrSymbol_produc := IF(_SearchLen < 3, FALSE, t.SymbolProducenta LIKE CONCAT(_SearchText, '%')))
								OR
								(@srch_instancje_kod_kreskowy := IF(_SearchLen < 3, FALSE, t.kod_kreskowy LIKE CONCAT(_SearchText, '%')))
								OR
								(@srch_instancje_kod_kreskowy1 := IF(_SearchLen < 3, FALSE, t.kod_kreskowy1 LIKE CONCAT(_SearchText, '%')))
								OR
								(@srch_instancje_kod_kreskowy2 := IF(_SearchLen < 3, FALSE, t.kod_kreskowy2 LIKE CONCAT(_SearchText, '%')))
							)
							AND t.Deleted = 0 and t.promocja_status<>2
							AND (t.usluga in (0, 1, 2, 3, 4, 8, 9 )) 
						GROUP BY t.GUID
						-- ORDER BY Towar
						LIMIT 200
					;	
		CREATE TEMPORARY TABLE `t_erp_search_similar`
			SELECT 	
				CONCAT(
					IF(srch_TowrSymbol,
						t.Symbol,
					IF(srch_TowrNazwa,
						t.Nazwa,
					IF(srch_TowrSymbol_u_dost,
						t.symboludost,
					IF(srch_TowrSymbol_produc,
						t.SymbolProducenta,
					IF(srch_instancje_kod_kreskowy,
						t.kod_kreskowy,
					IF(srch_instancje_kod_kreskowy1,
						t.kod_kreskowy1,
					IF(srch_instancje_kod_kreskowy2,
						t.kod_kreskowy2,
						''
					))))))),	
					-- ' - ',
					IF(srch_TowrSymbol, '-> Symbol', ''),
					IF(srch_TowrNazwa, '-> Nazwa', ''),
					IF(srch_TowrSymbol_u_dost, '-> Symbol u dost.', ''),
					IF(srch_TowrSymbol_produc, '-> Symbol u prod.', ''),
					IF(srch_instancje_kod_kreskowy, '-> Kod kres.', ''),
					IF(srch_instancje_kod_kreskowy1, '-> Kod kres.1', ''),
					IF(srch_instancje_kod_kreskowy2, '-> Kod kres.2', '')
				) AS LkSearch,	
					
				LTRIM(CONCAT(t.Nazwa, ' - ', t.Symbol)) AS ResultText,
				t.GUID
			FROM `t_erp_search_similar_Towary` t
			WHERE		
				TRUE
			GROUP BY t.GUID
			ORDER BY LkSearch
			LIMIT 200
		;	
					
		DROP TEMPORARY TABLE IF EXISTS `t_erp_search_similar_Towary`;
		/*
		CREATE TEMPORARY TABLE `t_erp_search_similar`
			SELECT 	
				(@srch_TowrNazwa := IF(_SearchLen < 4, FALSE, t.Nazwa LIKE CONCAT('%', _SearchText, '%'))) AS srch_TowrNazwa,
				(@srch_TowrSymbol := (t.Symbol LIKE CONCAT(_SearchText, '%'))) AS srch_TowrSymbol,
				(@srch_TowrSymbol_u_dost := IF(_SearchLen < 3, FALSE, t.symboludost LIKE CONCAT(_SearchText, '%'))) AS srch_TowrSymbol_u_dost,
				(@srch_TowrSymbol_produc := IF(_SearchLen < 3, FALSE, t.SymbolProducenta LIKE CONCAT(_SearchText, '%'))) AS srch_TowrSymbol_produc,
				(@srch_instancje_kod_kreskowy := IF(_SearchLen < 3, FALSE, t.kod_kreskowy LIKE CONCAT(_SearchText, '%'))) AS srch_instancje_kod_kreskowy,
				(@srch_instancje_kod_kreskowy1 := IF(_SearchLen < 3, FALSE, t.kod_kreskowy1 LIKE CONCAT(_SearchText, '%'))) AS srch_instancje_kod_kreskowy1,
				(@srch_instancje_kod_kreskowy2 := IF(_SearchLen < 3, FALSE, t.kod_kreskowy2 LIKE CONCAT(_SearchText, '%'))) AS srch_instancje_kod_kreskowy2,
				_VarStr(
					IF(@srch_TowrNazwa,
						LTRIM(CONCAT(t.Nazwa, ' ', t.Symbol)),
						IF(@srch_TowrSymbol_u_dost, 
							LTRIM(CONCAT(t.symboludost, ' - ', t.Nazwa)),
							IF(@srch_TowrSymbol_produc, 
								LTRIM(CONCAT(t.SymbolProducenta, '  ', t.Nazwa)),
								LTRIM(CONCAT(t.Symbol, ' ', t.Nazwa))
							)
						)	
					)
				) AS Towar,
				_VarStr(
					IFNULL(
						GROUP_CONCAT(DISTINCT 
							IF(@srch_TowrSymbol_u_dost, 
								CONCAT('u dostawcy: ', t.symboludost), 
								IF(@srch_TowrSymbol_produc, 
									CONCAT('u producenta: ', t.SymbolProducenta), 
									IF(@srch_instancje_kod_kreskowy, 
										CONCAT('kod kreskowy: ', t.kod_kreskowy), 
										IF(@srch_instancje_kod_kreskowy1, 
											CONCAT('kod kreskowy II: ', t.kod_kreskowy1), 
											IF(@srch_instancje_kod_kreskowy2, 
												CONCAT('kod kreskowy III: ', t.kod_kreskowy2), 
												LTRIM(CONCAT(t.Symbol, ' ', t.Nazwa))
											)	
										)	
									)	
								) 
							)	
						SEPARATOR ', '
						),
						'*'
					)	
				) AS LabelSearch,
				t.GUID AS TowrGUID
			FROM `TowrNg` t
			WHERE		
				(
					(@srch_TowrNazwa := IF(_SearchLen < 4, FALSE, t.Nazwa LIKE CONCAT('%', _SearchText, '%')))
					OR
					(@srch_TowrSymbol := (t.Symbol LIKE CONCAT(_SearchText, '%')))
					OR
					(@srch_TowrSymbol_u_dost := IF(_SearchLen < 3, FALSE, t.symboludost LIKE CONCAT(_SearchText, '%')))
					OR
					(@srch_TowrSymbol_produc := IF(_SearchLen < 3, FALSE, t.SymbolProducenta LIKE CONCAT(_SearchText, '%')))
					OR
					(@srch_instancje_kod_kreskowy := IF(_SearchLen < 3, FALSE, t.kod_kreskowy LIKE CONCAT(_SearchText, '%')))
					OR
					(@srch_instancje_kod_kreskowy1 := IF(_SearchLen < 3, FALSE, t.kod_kreskowy1 LIKE CONCAT(_SearchText, '%')))
					OR
					(@srch_instancje_kod_kreskowy2 := IF(_SearchLen < 3, FALSE, t.kod_kreskowy2 LIKE CONCAT(_SearchText, '%')))
				)
			GROUP BY t.GUID
			ORDER BY Towar
			LIMIT 200
		;	
		*/
	--	Final
		INSERT INTO `t_search_dataset`
		(LK_srch, LK_Text, Result_Text, Result_Key, Result_Key2, Fld_1)
			SELECT 
				LkSearch AS LK_Srch, 
				_VarStr(@LK_Text := t.ResultText) AS LK_Text,
				@LK_Text AS Result_Text, 
				t.GUID AS Result_Key,
				t.GUID AS Result_Key2,
                tw.IDN AS Fld_1
			FROM `t_erp_search_similar` t
            INNER JOIN `TowrNg` tw ON tw.GUID = t.GUID 
			WHERE
				true
		-- ORDER BY MIN(OrderCol), ImionaNazwisko
		;
	/*  wywal
		INSERT INTO `t_search_dataset`
		(LK_srch, LK_Text, Result_Text, Result_Key, Result_Key2)
			SELECT 
				Towar AS LK_Srch, 
				_VarStr(@LK_Text := t.LabelSearch) AS LK_Text,
				@LK_Text AS Result_Text, 
				TowrGUID AS Result_Key,
				TowrGUID AS Result_Key2
			FROM `t_erp_search_similar` t
			WHERE
				true
		-- ORDER BY MIN(OrderCol), ImionaNazwisko
		;
	*/	
	--	DROP 
		DROP TEMPORARY TABLE IF EXISTS `t_erp_search_similar`;
		
	END IF; -- _MODE = 'SEARCH_TOWAR_LIKE'

	
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'SEARCH_LOKALIZACJE_LIKE'
		Przeszukuje egzemplarze po frazie _SearchText (nazwa, symbol, kod_kreskowy etc
		Parametry
			_SearchText			Fraza szukana
		CALL erp_do_search_similar('SEARCH_INSTANCJE_LIKE', '23234', '', '', 0, 0, '', '', '', '');
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE LIKE 'SEARCH_LOKALIZACJE_LIKE%' THEN
		SET @_Value := '??';	--	Tak trzeba!!!!!!!!!!!!! PATRZ PIM_PhoneNumber
		SET _SearchText = IFNULL(_SearchText, '');
		SET _SearchTextWithoutSpaces = _varSTR_Flush_Spaces(_SearchText);
		SET _SearchLen = LENGTH(_SearchText);
		
		CREATE TEMPORARY TABLE `t_erp_search_similar`
			SELECT 	
				_VarStr(CONCAT(
					IF(@FindNazwa, 
						n.Nazwa,
						IF(NOT @Srch_Include_minus,
							SUBSTR(n.Path, LOCATE(_SearchText, n.Path), 255), 
							SUBSTR(@Path := REPLACE(n.Path, '|', '-'), LOCATE(_SearchText, @Path), 255)
						)	
					),
					IF(n.Symbol = n.Nazwa,
						'',
						CONCAT(' / ', TRIM(REPLACE(n.Nazwa, n.Symbol, '')))
					)	
				)) AS Col_Search,
				_VarStr(CONCAT(
					IF(@FindNazwa, 
						n.Nazwa,
						IF(NOT @Srch_Include_minus,
							SUBSTR(n.Path, LOCATE(_SearchText, n.Path), 255), 
							SUBSTR(@Path := REPLACE(n.Path, '|', '-'), LOCATE(_SearchText, @Path), 255)
						)	
					),
					IF(n.Symbol = n.Nazwa,
						'',
						CONCAT(' / ', TRIM(REPLACE(n.Nazwa, n.Symbol, '')))
					)	
				)) AS LabelSearch,
				_VarStr(REPLACE(n.Path, '|', ' - ')) AS Path,
				n.GUID 
			FROM `erp_area_nodes` n 
			WHERE 
				TRUE 
				AND 
				(
					@FindPath := (n.Path LIKE CONCAT('%', _SearchText, '%'))
					OR
					@FindPathB := (REPLACE(n.Path, '|', '-') LIKE CONCAT('%', _SearchText, '%'))
					OR
					@FindNazwa := (n.Nazwa LIKE CONCAT('%', _SearchText, '%'))
				)	
				-- AND n.Type LIKE 'MAG%'
			GROUP BY n.GUID
			ORDER BY Col_Search
			LIMIT 200
		;	
		
	--	Final
		INSERT INTO `t_search_dataset`
		(LK_srch, LK_Text, Result_Text, Result_Key, Result_Key2)
			SELECT 
				t.Col_Search AS LK_Srch,
				_VarStr(@LK_Text := t.LabelSearch) AS LK_Text,
				/*
				_VarStr(@LK_Text := 
					LTRIM(CONCAT(o.Imiona, ' ', o.Nazwisko))
				) AS LK_Text,
				*/
				@LK_Text AS Result_Text, 
				t.GUID AS Result_Key,
				'' AS Result_Key2
				
			FROM `t_erp_search_similar` t
			WHERE
				true
		-- ORDER BY MIN(OrderCol), ImionaNazwisko
		;
		
	--	DROP 
		DROP TEMPORARY TABLE IF EXISTS `t_erp_search_similar`;
	END IF; -- _MODE = 'SEARCH_INSTANCJE_LIKE'

	
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'SEARCH_INSTANCJE_LIKE'
		Przeszukuje egzemplarze po frazie _SearchText (nazwa, symbol, kod_kreskowy etc
		Parametry
			_SearchText			Fraza szukana
		CALL erp_do_search_similar('SEARCH_INSTANCJE_LIKE', '23234', '', '', 0, 0, '', '', '', '');
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE LIKE 'SEARCH_INSTANCJE_LIKE%' THEN
		SET @_Value := '??';	--	Tak trzeba!!!!!!!!!!!!! PATRZ PIM_PhoneNumber
		SET _SearchText = IFNULL(_SearchText, '');
		SET _SearchTextWithoutSpaces = _varSTR_Flush_Spaces(_SearchText);
		SET _SearchLen = LENGTH(_SearchText);
		SET _SearchLenAddr = LENGTH(_SearchTextWithoutSpaces);
		SET _SearchIsMail = LOCATE('@', _SearchTextWithoutSpaces) > 0; -- select _SearchIsMail;
		SET
			@srch_instancje_kod_kreskowy := FALSE,
			@srch_instancje_nr_seryjny := FALSE, 
			@srch_instancje_Opis := FALSE,
			@srch_instancje_nrinwentarz := FALSE,
			@srch_instancje_TowrNazwa := FALSE,
			@srch_instancje_TowrSymbol := FALSE,
			@srch_instancje_nrinwentarzobcy := FALSE
		;
		
		CREATE TEMPORARY TABLE `t_erp_search_similar`
			SELECT 	
				_VarStr(
					IF(@srch_instancje_kod_kreskowy, 
						CONCAT('', ti.kod_kreskowy),
						IF(@srch_instancje_nr_seryjny,
							CONCAT('', ti.nr_seryjny, ' - ', t.Nazwa, ' ', t.Symbol),
							IF(@srch_instancje_Opis,
								CONCAT('', ti.opis),
								IF(@srch_instancje_nrinwentarz,
									CONCAT('', ti.nrinwentarz, ' - ', t.Nazwa, ' ', t.Symbol),
									IF(@srch_instancje_TowrNazwa,
										CONCAT('', t.Nazwa, ' ', t.Symbol),
										IF(@srch_instancje_TowrSymbol, 
											CONCAT('', t.symbol, ' - ', t.Nazwa),
											IF(@srch_instancje_nrinwentarzobcy, 
												CONCAT('', ti.nrinwentarzobcy, ' - ', t.Nazwa, ' ', t.Symbol),
												CONCAT('', ti.kod_kreskowy, ' - ', t.Nazwa, ' ', t.Symbol)
											)
										)	
									)
								)	
							)	
						) 
					)	
				) AS InstancjaSearch,
				_VarStr(
					IFNULL(
						GROUP_CONCAT(DISTINCT 
							IF(@srch_instancje_kod_kreskowy, 
								CONCAT('kod kreskowy: ', ti.kod_kreskowy, ', nr inwen: ', ti.nrinwentarz, ', ', t.Nazwa, ' ', t.Symbol, ', ', ti.opis),
								IF(@srch_instancje_nr_seryjny,
									CONCAT('nr seryjny: ', ti.nr_seryjny, ' - ', ti.opis),
									IF(@srch_instancje_Opis,
										CONCAT('opis: ', ti.opis),
										IF(@srch_instancje_nrinwentarz,
											CONCAT('nr inwen: ', ti.nrinwentarz, ', kod: ', ti.kod_kreskowy, ', ', t.Nazwa, ' ', t.Symbol, ', ', ti.opis),
											IF(@srch_instancje_TowrNazwa,
												CONCAT('urz.: ', t.Nazwa, ' ', t.Symbol, ', nr inwen: ', ti.nrinwentarz, ', kod: ', ti.kod_kreskowy),
												IF(@srch_instancje_TowrSymbol, 
													CONCAT('urz.: ', t.symbol, ' - ', t.Nazwa, ', nr inwen: ', ti.nrinwentarz, ', kod: ', ti.kod_kreskowy),
													IF(@srch_instancje_nrinwentarzobcy, 
														CONCAT('nr inwentarz.obcy: ', ti.nrinwentarzobcy, ' - ', ti.opis),
														NULL
													)
												)	
											)
										)	
									) 
								) 
							)	
						SEPARATOR ', '
						),
						'*'
					)	
				) AS LabelSearch,
				ti.GUID AS GUID,
				ti.IdnTowr,
				ti.is_multi_instancje
			FROM `towrng_instancje` ti
			INNER JOIN `TowrNg` t ON t.GUID = ti.IdnTowr
			WHERE		
				(
					(@srch_instancje_kod_kreskowy := IF(_SearchLen < 3, FALSE, ti.kod_kreskowy LIKE CONCAT(_SearchText, '%') OR ti.kod_kreskowy LIKE CONCAT('%00', _SearchText, '%')))
					OR
					(@srch_instancje_nr_seryjny := IF(_SearchLen < 3, FALSE, ti.nr_seryjny LIKE CONCAT(_SearchText, '%')))
					OR
					(@srch_instancje_Opis := IF(_SearchLen < 4, FALSE, ti.Opis LIKE CONCAT('%', _SearchText, '%')))
					OR
					(@srch_instancje_nrinwentarz := IF(_SearchLen < 3, FALSE, ti.nrinwentarz LIKE CONCAT(_SearchText, '%')))
					OR
					(@srch_instancje_TowrNazwa := IF(_SearchLen < 4, FALSE, t.Nazwa LIKE CONCAT('%', _SearchText, '%')))
					OR
					(@srch_instancje_TowrSymbol := IF(_SearchLen < 4, FALSE, t.Symbol LIKE CONCAT(_SearchText, '%')))
					OR
					(@srch_instancje_nrinwentarzobcy := IF(_SearchLen < 3, FALSE, ti.nrinwentarzobcy LIKE CONCAT(_SearchText, '%')))
				)
			-- GROUP BY ti.GUID
			GROUP BY ti.IdnTowr, ti.Kod_Kreskowy
			ORDER BY InstancjaSearch
			LIMIT 200
		;	
		
	--	Final
		INSERT INTO `t_search_dataset`
		(LK_srch, LK_Text, Result_Text, Result_Key, Result_Key2)
			SELECT 
				t.InstancjaSearch AS LK_Srch,
				_VarStr(@LK_Text := t.LabelSearch) AS LK_Text,
				/*
				_VarStr(@LK_Text := 
					LTRIM(CONCAT(o.Imiona, ' ', o.Nazwisko))
				) AS LK_Text,
				*/
				@LK_Text AS Result_Text, 
				t.GUID AS Result_Key,
				t.IdnTowr AS Result_Key2
				
			FROM `t_erp_search_similar` t
			WHERE
				true
		-- ORDER BY MIN(OrderCol), ImionaNazwisko
		;
		
	--	DROP 
		DROP TEMPORARY TABLE IF EXISTS `t_erp_search_similar`;
	END IF; -- _MODE = 'SEARCH_INSTANCJE_LIKE'

	/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
		'SEARCH_TELEPHON_NUMBERS_LIKE'
			Przeszukuje kontakty po frazie _SearchText (telefon, mail, etc ale ównie nazwisko lub imiona
			Parametry
				_SearchText			Fraza szukana
				_Param_A			= '' to również grupy
									 '' tylko osoby
				_Param_B			
									= '' 	to tylko widoczne w HR
									!= ''	wszystkie osoby 
				_Param_C			
									= '' 	to nie serwisowcy
									!= ''	wszystkie osoby 
			CALL erp_do_search_similar('SEARCH_OSOBY_LIKE', 'jmam', '', '', 0, 0, '', '', '', '');				-- szukaj wystapienia 'jmam'
			CALL erp_search_similar('SEARCH_TELEPHON_NUMBERS_LIKE', 'jmam', '', '', '', '');				-- szukaj wystapienia 'jmam'
			CALL erp_search_similar('SEARCH_TELEPHON_NUMBERS_LIKE', 'jmam', '1', '', '', '');			-- szukaj wystapienia 'jmam' ale tylko osoby
	------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
		IF _MODE LIKE 'SEARCH_TELEPHON_NUMBERS_LIKE%' THEN
			SET @_Value := '??';	--	Tak trzeba!!!!!!!!!!!!! PATRZ PIM_PhoneNumber
			-- SET _SearchTextTrimSpaces = RTrim(_SearchText);
			SET _SearchLenAddr = LENGTH(_SearchTextWithoutSpaces);
			SET _SearchIsMail = LOCATE('@', _SearchTextWithoutSpaces) > 0; -- select _SearchIsMail;
			
			IF RIGHT(_SearchText, 1) = ' ' THEN
				SET _SearchLen = 100;
			END IF;
			
			SET
				@_Param_A = _Param_A,
				@_Param_B = _Param_B,
				@_SearchText = _SearchText,
				@_SearchTextWithoutSpaces = _SearchTextWithoutSpaces,
				-- @_SearchTextTrimSpaces = _SearchTextTrimSpaces,
				@_SearchLen = _SearchLen,
				@_SearchLenAddr = _SearchLenAddr,
				@_SearchIsMail = _SearchIsMail
			;

			DROP TEMPORARY TABLE IF EXISTS `t_search_KO`;
			CREATE TEMPORARY TABLE IF NOT EXISTS `t_search_KO` 
			(
				`GUID` VARCHAR(38) NOT NULL DEFAULT '',
				`LK_Srch` VARCHAR(255) NOT NULL DEFAULT '', 
				`Nazwa` VARCHAR(255) NOT NULL DEFAULT '', 
				`OsobaGUID` VARCHAR(38) NOT NULL DEFAULT '',
				`KontrGUID` VARCHAR(38) NOT NULL DEFAULT '',
				`Src` VARCHAR(38) NOT NULL DEFAULT '',
				`OrderCol` VARCHAR(10) NOT NULL DEFAULT '1',
				`Phase_1` BOOLEAN NOT NULL DEFAULT FALSE,
				`Phase_2` BOOLEAN NOT NULL DEFAULT FALSE,
				`Phase_3` BOOLEAN NOT NULL DEFAULT FALSE,
				PRIMARY KEY (`GUID`),
				UNIQUE KEY (`OsobaGUID`, `KontrGUID`)
			) 
			;
			
			DROP TEMPORARY TABLE IF EXISTS `t_search_osoby`;
			CREATE TEMPORARY TABLE IF NOT EXISTS `t_search_osoby` 
			(
				`LK_Srch` VARCHAR(255) NOT NULL DEFAULT '', 
				`ImionaNazwisko` VARCHAR(255) NOT NULL DEFAULT '', 
				`OsobaGUID` VARCHAR(38) NOT NULL DEFAULT '',
				`OrderCol` VARCHAR(10) NOT NULL DEFAULT '1',
				PRIMARY KEY (`OsobaGUID`)
			) 
			;
		--	1.	Osoby	
			INSERT IGNORE INTO `t_search_KO` 
				(GUID, LK_Srch, OsobaGUID, KontrGUID, Src, OrderCol, Phase_1, Phase_2, Phase_3)
				SELECT
					kn.GUID,
					_VarStr(
						IFNULL(
							GROUP_CONCAT(DISTINCT 
								IF(@srch_Nazwisko OR @srch_NazwiskoImiona, 
									LTRIM(CONCAT(o.Nazwisko, ' ', o.Imiona)),
									IF(@srch_NazwiskoImie1, 
										LTRIM(CONCAT(o.Nazwisko, ' ', o.Imie1)),
										IF(@srch_Imie1 OR @srch_ImionaNazwisko, 
											LTRIM(CONCAT(o.Imiona, ' ', o.Nazwisko)),
											IF(@srch_Imie1Nazwisko, 
												LTRIM(CONCAT(o.Imie1, ' ', o.Nazwisko)),
												IF(@srch_IdnUser, -- !!! o.idnuser LIKE CONCAT('%', _SearchText, '%'),
													CONCAT(o.idnuser, IF(o.Rodzaj, ' NICK', ' GRUPA')),
													NULL
												)
											)
										) 
									)	
								) 
							SEPARATOR ', '
							),
							'*'
						)	
					) AS LK_Srch,
					kn.OsobaGUID, kn.KontrGUID,
					'osoba',
					IF(@srch_Nazwisko, 0, 1) AS OrderCol,
					(_ExtParam IN ('', '1')),
					(_ExtParam = '2'),
					(_ExtParam = '3')
						
				FROM `kontakty` kn
				INNER JOIN `osoby` o ON o.GUID = kn.osobaGUID 
				WHERE
					IFNULL(kn.osobaGUID, '') != ''
					AND
					kn.typ_medium IN (0,2) 
					AND
					IF(_Param_A = '', 
						TRUE,
						o.rodzaj != 0
					) AND
					IF(_Param_B != '', 
						TRUE,
						o.niewidoczna_w_HR = 0
					) AND
					(
						(@srch_Nazwisko := IF((_SearchLen < 2), FALSE, o.Nazwisko LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_Imie1 := IF((_SearchLen < 1), FALSE, o.Imie1 LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_IdnUser := (o.idnuser LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_ImionaNazwisko := IF((_SearchLen < 4) OR _SearchIsMail, FALSE, CONCAT(o.Imiona, ' ', o.Nazwisko) LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_Imie1Nazwisko := IF((_SearchLen < 4) OR _SearchIsMail, FALSE, CONCAT(o.Imie1, ' ', o.Nazwisko) LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_NazwiskoImiona := IF((_SearchLen < 4) OR _SearchIsMail, FALSE, CONCAT(o.Nazwisko, ' ', o.Imiona) LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_NazwiskoImie1 := IF((_SearchLen < 4) OR _SearchIsMail, FALSE, CONCAT(o.Nazwisko, ' ', o.Imie1) LIKE CONCAT(_SearchText, '%')))
					)	
			GROUP BY kn.OsobaGUID, kn.KontrGUID
			LIMIT 40
			ON DUPLICATE KEY 
			UPDATE
				Phase_1 = (_ExtParam IN ('', '1')),
				Phase_2 = (_ExtParam = '2'),
				Phase_3 = (_ExtParam = '3')
			;
			SET @t_search_KO.Osoby = ROW_COUNT();
			
		--	2.	Kontrahent	
			INSERT IGNORE INTO `t_search_KO` 
				(GUID, LK_Srch, OsobaGUID, KontrGUID, Src, OrderCol, Phase_1, Phase_2, Phase_3)
				SELECT
					kn.GUID,
					_VarStr(
						IFNULL(
							GROUP_CONCAT(DISTINCT 
								IF(@srch_Nazwa, -- !!! o.Nazwisko LIKE CONCAT(_SearchText, '%'),
									LTRIM(CONCAT(k.Nazwa, ' ', k.Symbol)),
									IF(@srch_Symbol, -- !!! o.Nazwisko LIKE CONCAT(_SearchText, '%'),
										LTRIM(CONCAT(k.Symbol, ' ', k.Nazwa)),
										NULL
									) 
								)	
								 
							SEPARATOR ', '
							),
							'*'
						)	
					) AS LK_Srch,
					kn.OsobaGUID, kn.KontrGUID,
					'kontrah',
					IF(@srch_Nazwa, 0, 1) AS OrderCol,
					(_ExtParam IN ('', '1')),
					(_ExtParam = '2'),
					(_ExtParam = '3')
						
				FROM `kontakty` kn
				INNER JOIN `kontrah` k ON k.GUID = kn.KontrGUID 
				WHERE
					IFNULL(kn.KontrGUID, '') != ''
					AND
					kn.typ_medium IN (0,2) 
					AND
					(
						(@srch_Nazwa := IF((_SearchLen < 2), FALSE, k.Nazwa LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_Symbol := IF((_SearchLen < 1), FALSE, k.Symbol LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_Nazwa := IF((_SearchLen < 5) OR _SearchIsMail, FALSE, k.Nazwa LIKE CONCAT('%', _SearchText, '%')))
						OR
						(@srch_Symbol := IF((_SearchLen < 5) OR _SearchIsMail, FALSE, k.Symbol LIKE CONCAT('%', _SearchText, '%')))
					)	
			GROUP BY kn.OsobaGUID, kn.KontrGUID
			LIMIT 40
			ON DUPLICATE KEY 
			UPDATE
				Phase_1 = (_ExtParam IN ('', '1')),
				Phase_2 = (_ExtParam = '2'),
				Phase_3 = (_ExtParam = '3')
			;
			SET @t_search_KO.Kontrah = ROW_COUNT();
			
		--	3.	Inne kontakty czyli mailowe
			IF (@t_search_KO.Osoby + @t_search_KO.Kontrah = 0) OR _SearchIsMail THEN
				INSERT IGNORE INTO `t_search_KO` 
					(GUID, LK_Srch, OsobaGUID, KontrGUID, Src, OrderCol, Phase_1, Phase_2, Phase_3)
					

					SELECT
						kn.GUID,
						_VarStr(
							kn_mail.Adres
						) AS LK_Srch,
						kn.OsobaGUID, kn.KontrGUID,
						-- kn.Adres,
						'mail',
						IF(@srch_Nazwa, 0, 1) AS OrderCol,
						(_ExtParam IN ('', '1')),
						(_ExtParam = '2'),
						(_ExtParam = '3')
							
					FROM `kontakty` kn_mail
					INNER JOIN `kontakty` kn ON kn.typ_medium IN (0, 2) AND (kn_mail.OsobaGUID = kn.OsobaGUID)
					WHERE
						kn_mail.typ_medium = 3
						AND
						(
							kn_mail.Adres LIKE CONCAT('%', _SearchText, '%')
						)	
				GROUP BY kn.OsobaGUID, kn.KontrGUID
				LIMIT 40
				ON DUPLICATE KEY 
				UPDATE
					Phase_1 = (_ExtParam IN ('', '1')),
					Phase_2 = (_ExtParam = '2'),
					Phase_3 = (_ExtParam = '3')
				;
			END IF;
		
			DELETE FROM `t_search_KO` WHERE (IFNULL(OsobaGUID, '') = '' AND IFNULL(KontrGUID, '') = '');
		
		
		
		
			INSERT IGNORE INTO `t_search_osoby` 
				(LK_Srch, ImionaNazwisko, OsobaGUID, OrderCol)
				SELECT
					_VarStr(
						IFNULL(
							GROUP_CONCAT(DISTINCT 
								IF(@srch_Nazwisko, -- !!! o.Nazwisko LIKE CONCAT(_SearchText, '%'),
									LTRIM(CONCAT(o.Nazwisko, ' ', o.Imiona)),
									IF(@srch_Imie1, -- !!! o.Nazwisko LIKE CONCAT(_SearchText, '%'),
										LTRIM(CONCAT(o.Imiona, ' ', o.Nazwisko)),
										IF(@srch_IdnUser, -- !!! o.idnuser LIKE CONCAT('%', _SearchText, '%'),
											CONCAT(o.idnuser, IF(o.Rodzaj, ' NICK', ' GRUPA')),
											NULL
										)
									) 
								)	
								 
							SEPARATOR ', '
							),
							'*'
						)	
					) AS LK_Srch,
					_VarStr(
						LTRIM(CONCAT(o.Nazwisko, ' ', o.Imiona))
					),
					o.GUID,
					IF(@srch_Nazwisko, 0, 1) AS OrderCol
						
				FROM `osoby` o
				INNER JOIN `kontakty` k ON o.GUID = k.osobaGUID 
				WHERE
					IFNULL(o.GUID, '') != ''
					AND
					IF(_Param_A = '', 
						TRUE,
						o.rodzaj != 0
					) AND
					IF(_Param_B != '', 
						TRUE,
						o.niewidoczna_w_HR = 0
					) AND
				--	IF(_Param_C != '', 
				--		TRUE,
				--		o.seriws???? = 0
				--	) AND
					(
						(@srch_Nazwisko := IF((_SearchLen < 2), FALSE, o.Nazwisko LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_Imie1 := IF((_SearchLen < 1), FALSE, o.Imie1 LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_IdnUser := (o.idnuser LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_ImionaNazwisko := IF((_SearchLen < 4) OR _SearchIsMail, FALSE, CONCAT(o.Imiona, ' ', o.Nazwisko) LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_ImionaNazwisko := IF((_SearchLen < 4) OR _SearchIsMail, FALSE, CONCAT(o.Imie1, ' ', o.Nazwisko) LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_NazwiskoImiona := IF((_SearchLen < 4) OR _SearchIsMail, FALSE, CONCAT(o.Nazwisko, ' ', o.Imiona) LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_NazwiskoImiona := IF((_SearchLen < 4) OR _SearchIsMail, FALSE, CONCAT(o.Nazwisko, ' ', o.Imie1) LIKE CONCAT(_SearchText, '%')))
						/*
						OR
						(@srch_NrPesel := IF((_SearchLen < 4) OR _SearchIsMail, FALSE, o.NrPesel LIKE CONCAT(_SearchText, '%')))
						-- o.NrPesel LIKE CONCAT(_SearchText, '%')
						OR
						(@srch_NrNIP := IF((_SearchLen < 4) OR _SearchIsMail, FALSE, o.NrNIP LIKE CONCAT(_SearchText, '%')))
						-- o.NrNIP LIKE CONCAT(_SearchText, '%')
						OR
						(@srch_NrSeriaDowoduOsobistego := IF((_SearchLen < 5) OR _SearchIsMail, FALSE, o.NrSeriaDowoduOsobistego LIKE CONCAT(_SearchText, '%')))
						*/
						-- o.NrSeriaDowoduOsobistego LIKE CONCAT(_SearchText, '%')
					)	
			GROUP BY o.GUID
			LIMIT 40
			;
			
		--	2.	Kontakty	
			INSERT IGNORE INTO `t_search_osoby` 
				(LK_Srch, ImionaNazwisko, OsobaGUID)
				SELECT
					IFNULL(
						GROUP_CONCAT(DISTINCT 
							IF(@srch_Adres, -- !!! _varSTR_Flush_Spaces(k.Adres) LIKE CONCAT('%', _SearchTextWithoutSpaces, '%'),
							-- bylo	CONCAT('<', IF(t.media_notify = 0, PIM_PhoneNumber('FMT1', k.adres, k.typ_medium), k.adres), '>'), 
								CONCAT('', IF(t.media_notify = 0, PIM_PhoneNumber('FMT1', k.adres, k.typ_medium), k.adres), ' ', t.Descryption), 
								NULL
							) 
						SEPARATOR ', '
						),
						'*'
					) AS LK_Srch,	
					_VarStr(''),
					k.OsobaGUID
						
				FROM `kontakty` k
				LEFT JOIN v_pim_media_types t ON t.ID = k.typ_medium
				WHERE
					k.OsobaGUID IS NOT NULL 
					AND
					(
	-- 					(@srch_Adres := IF((_SearchLenAddr < 3) and (NOT _SearchIsMail), FALSE, _varSTR_Flush_Spaces(k.Adres) LIKE CONCAT('%', _SearchTextWithoutSpaces, '%')))
						(@srch_Adres := IF((_SearchLenAddr < 3) and (NOT _SearchIsMail), FALSE, k.Adres LIKE CONCAT('%', _SearchTextWithoutSpaces, '%')))
					)	
			GROUP BY k.OsobaGUID
			LIMIT 40
			;
			
		--	3.	Kontrahent	
			IF IFNULL(@session.globals.hr.HR_SEARCH_BY_hr_kontrah_links, 0) THEN
			--	NOWE szukanie -> by `hr_kontrah_links`
				INSERT IGNORE INTO `t_search_osoby` 
					(LK_Srch, ImionaNazwisko, OsobaGUID)
					SELECT
						IFNULL(
							GROUP_CONCAT(DISTINCT 
									IF(@srch_Nazwa OR @srch_NazwaFull, -- !!! kn.Symbol LIKE CONCAT(_SearchText, '%') OR kn.Nazwa LIKE CONCAT('%', _SearchText, '%'),
										CONCAT(kn.Nazwa, ' kontrahent'),
										IF(@srch_Symbol, -- !!! kn.Symbol LIKE CONCAT(_SearchText, '%') OR kn.Nazwa LIKE CONCAT('%', _SearchText, '%'),
											CONCAT(kn.Symbol,' - ', kn.Nazwa, '  kontrahent'),
											NULL
										)	
									) 
							SEPARATOR ', '
							),
							'*'
						) AS LK_Srch,	
						_VarStr(''),
						o.GUID
							
					FROM `osoby` o
					INNER JOIN `kontakty` k ON o.GUID = k.osobaGUID 
					INNER JOIN `hr_kontrah_links` hk ON hk.osobaGUID = o.GUID
					INNER JOIN `kontrah` kn ON kn.GUID = hk.KontrGUID
					WHERE
						IFNULL(o.KontrGUID, '') != ''
						AND
						IFNULL(o.GUID, '') != ''
						AND
						IF(_Param_A = '', 
							TRUE,
							o.rodzaj != 0
						) AND
						IF(_Param_B != '', 
							TRUE,
							o.niewidoczna_w_HR = 0
						) AND
						(
						(@srch_Symbol := IF((_SearchLen < 3), FALSE, kn.Symbol LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_Nazwa := IF((_SearchLen < 3), FALSE, kn.Nazwa LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_NazwaFull := IF((_SearchLen < 6), FALSE, kn.Nazwa LIKE CONCAT('%', _SearchText, '%')))
						)
				GROUP BY o.GUID
				LIMIT 40
				;
			ELSE
			--	Stare szukanie -> by osoby.KontrGUID
				INSERT IGNORE INTO `t_search_osoby` 
					(LK_Srch, ImionaNazwisko, OsobaGUID)
					SELECT
						IFNULL(
							GROUP_CONCAT(DISTINCT 
									IF(@srch_Nazwa OR @srch_NazwaFull, -- !!! kn.Symbol LIKE CONCAT(_SearchText, '%') OR kn.Nazwa LIKE CONCAT('%', _SearchText, '%'),
										CONCAT(kn.Nazwa, ' kontrahent'),
										IF(@srch_Symbol, -- !!! kn.Symbol LIKE CONCAT(_SearchText, '%') OR kn.Nazwa LIKE CONCAT('%', _SearchText, '%'),
											CONCAT(kn.Symbol,' - ', kn.Nazwa, '  kontrahent'),
											NULL
										)	
									) 
							SEPARATOR ', '
							),
							'*'
						) AS LK_Srch,	
						_VarStr(''),
						o.GUID
							
					FROM `osoby` o
					INNER JOIN `kontakty` k ON o.GUID = k.osobaGUID 
					INNER JOIN `kontrah` kn ON kn.GUID = o.KontrGUID
					WHERE
						IFNULL(o.KontrGUID, '') != ''
						AND
						IFNULL(o.GUID, '') != ''
						AND
						IF(_Param_A = '', 
							TRUE,
							o.rodzaj != 0
						) AND
						IF(_Param_B != '', 
							TRUE,
							o.niewidoczna_w_HR = 0
						) AND
						(
						(@srch_Symbol := IF((_SearchLen < 3), FALSE, kn.Symbol LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_Nazwa := IF((_SearchLen < 3), FALSE, kn.Nazwa LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_NazwaFull := IF((_SearchLen < 6), FALSE, kn.Nazwa LIKE CONCAT('%', _SearchText, '%')))
						)
				GROUP BY o.GUID
				LIMIT 40
				;
			END IF; -- kontrah
			
			
		--	Final
			IF IFNULL(@session.globals.Owner, '') != 'CRIST' THEN
				INSERT INTO `t_search_dataset`
				(LK_srch, LK_Text, Result_Text, Result_Key, Result_Key2)
					SELECT 
						t.LK_Srch,
						_VarStr(@LK_Text := 
							LTRIM(CONCAT(TRIM(o.Imiona), ' ', TRIM(o.Nazwisko)))
						) AS LK_Text,
						@LK_Text AS Result_Text, 
						t.OsobaGUID AS Result_Key,
						o.IdnUser AS Result_Key2
						
					FROM `t_search_osoby` t
					INNER JOIN `osoby` o ON o.GUID = t.OsobaGUID
					WHERE
						IFNULL(t.OsobaGUID, '') != ''
				-- ORDER BY MIN(OrderCol), ImionaNazwisko
				;
			ELSE
				INSERT INTO `t_search_dataset`
				(LK_srch, LK_Text, Result_Text, Result_Key, Result_Key2)
					SELECT 
						t.LK_Srch,
						_VarStr(@LK_Text := 
							CONCAT(
							LTRIM(CONCAT(TRIM(o.Imiona), ' ', TRIM(o.Nazwisko))),
							' ur. ', o.DataUrodzenia,
							_ConcatSTR(
								CONCAT(' PESEL: ', o.NrPesel),
								IFNULL(GROUP_CONCAT(DISTINCT CONCAT(hc.ID, IF(hc.Status = 1, ' nieakt.', '')) SEPARATOR ', ' ), ''),
								', nr.przep.: '
							)
							)
						) AS LK_Text, 
						@LK_Text AS Result_Text, 
						t.OsobaGUID AS Result_Key,
						o.IdnUser AS Result_Key2
						
					FROM `t_search_osoby` t
					INNER JOIN `osoby` o ON o.GUID = t.OsobaGUID
					LEFT JOIN `hr_cards` hc ON hc.OsobaGUID = t.OsobaGUID AND hc.Kind = 'PASS' AND hc.ID != hc.OsobaGUID
					WHERE
						IFNULL(t.OsobaGUID, '') != ''
				-- ORDER BY MIN(OrderCol), ImionaNazwisko
				;
			END IF;
		/*	wywal
			CREATE TEMPORARY TABLE `t_erp_search_similar`
				SELECT 
					_VarStr(
						IFNULL(
							GROUP_CONCAT(DISTINCT t.LK_Srch
							SEPARATOR ', '
							),
							'*'
						)	
					) AS LK_srch,
					_VarStr(@LK_Text := 
						IF(MAX(t.ImionaNazwisko) != '',
							MAX(t.ImionaNazwisko),
							LTRIM(CONCAT(o.Imiona, ' ', o.Nazwisko))
						)
					) AS LK_Text,
					@LK_Text AS Result_Text, 
					t.OsobaGUID AS Result_Key,
					o.IdnUser AS Result_Key2
					
				FROM `t_search_osoby` t
				INNER JOIN `osoby` o ON o.GUID = t.OsobaGUID
				WHERE
					IFNULL(t.OsobaGUID, '') != ''
				GROUP BY t.OsobaGUID
			-- ORDER BY MIN(OrderCol), ImionaNazwisko
			;
			*/
			DROP TEMPORARY TABLE IF EXISTS `t_search_osoby`;
			/*  wywal
		--	SELECT	
			IF NOT _Return_Std_Cols  THEN
				SELECT 
					ImionaNazwisko, LK_Srch AS AdrSearch, OsobaGUID, IdnUser
				FROM `t_erp_search_similar`
				;
			ELSE
				SELECT 
					ImionaNazwisko AS LookupStr, LK_Srch AS Descr, ResultText, OsobaGUID AS ID
				FROM `t_erp_search_similar`
				;
			END IF;
		--	DROP 
			DROP TEMPORARY TABLE IF EXISTS `t_erp_search_similar`;
			DROP TEMPORARY TABLE IF EXISTS `t_search_osoby`;
			*/
		END IF; -- _MODE = 'SEARCH_TELEPHON_NUMBERS_LIKE'
	
	IF _MODE LIKE '%Select' OR NOT _MODE LIKE '%Prepare' THEN
		SELECT * FROM t_search_dataset ORDER BY LK_srch;
	END IF;
END$$


DROP PROCEDURE IF EXISTS `erp_search_similar_`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `erp_search_similar_`(
	IN _MODE VARCHAR(50),		
	IN _SearchText VARCHAR(250),	
	IN _Param_A VARCHAR(250),	
	IN _Param_B VARCHAR(250),	
	IN _Param_C VARCHAR(250),	--	Jesli != '' to znaczy ze zwracamy wynik z `t_erp_search_similar` w sposob wolany z filtrow-lookupow
	IN _Param_D VARCHAR(250)
)
S_erp_search_similar: BEGIN

	DECLARE _SQLText TEXT;
	DECLARE _NewKontrahGUID VARCHAR(38) DEFAULT '';
	DECLARE _SearchTextWithoutSpaces VARCHAR(255) DEFAULT '';
	DECLARE _SearchTextTrimSpaces VARCHAR(255) DEFAULT '';
	DECLARE _SearchLen INTEGER;
	DECLARE _SearchLenAddr INTEGER;
	DECLARE _SearchIsMail BOOLEAN;

	DROP TEMPORARY TABLE IF EXISTS `t_erp_search_similar`;
	SET _Param_C = IFNULL(_Param_C, '');	--	Jesli != '' to znaczy ze zwracamy wynik z `t_erp_search_similar` w sposob wolany z filtrow-lookupow
	
	IF _MODE LIKE 'SEARCH%.MULTI' THEN
		SET _SearchLen=4;
		IF _MODE LIKE 'SEARCH_KATCOL%' THEN SET _SearchLen=3; END IF;
		
		SET @chunk:=2,_MODE=REPLACE(_MODE,'.MULTI','.Prepare');
		CALL erp_do_search_similar(_MODE, _Mid_Sep(_SearchText,' ',1), '', '', 0, 1, _Param_A, _Param_B,_Param_C,_Param_D);
		DROP TEMPORARY TABLE IF EXISTS t_search_dataset2;
		ALTER TABLE t_search_dataset RENAME t_search_dataset2;
		SET _SearchTextWithoutSpaces=_Mid_Sep(_SearchText,' ',@chunk);
		WHILE LENGTH(_SearchTextWithoutSpaces)>=_SearchLen and @chunk<7 DO
		      DROP TEMPORARY TABLE IF EXISTS t_search_dataset;
		      CALL erp_do_search_similar(_MODE, _SearchTextWithoutSpaces, '', '', 0, 1, _Param_A, _Param_B,_Param_C,_Param_D);
		      IF _Param_D LIKE '%DEBUG%' THEN
			    SELECT @chunk,_SearchTextWithoutSpaces,
			    (SELECT count(*) FROM t_search_dataset) as d1,(SELECT count(*) FROM t_search_dataset2) as d2,
			    (select count(*) from t_search_dataset t, t_search_dataset2 t2 where t.Result_Key=t2.Result_Key) as wspolne;
		      END IF;    
		      DELETE t FROM t_search_dataset t 
		      WHERE NOT EXISTS (SELECT t.Result_Key FROM t_search_dataset2 t2 WHERE t.Result_Key=t2.Result_Key);
		      DROP TEMPORARY TABLE IF EXISTS t_search_dataset2;
		      ALTER TABLE t_search_dataset RENAME t_search_dataset2;

		      SET @chunk:=@chunk+1;
		      SET _SearchTextWithoutSpaces=_Mid_Sep(_SearchText,' ',@chunk);
		END WHILE;
		DROP TEMPORARY TABLE IF EXISTS t_search_dataset;
		IF _Param_D NOT LIKE '%DEBUG%' THEN
		      SELECT * FROM t_search_dataset2 ORDER BY LK_srch;
		      DROP TEMPORARY TABLE IF EXISTS t_search_dataset2;
		END IF; 
	END IF; 
	
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'SEARCH_KONTRAH_LIKE'
		Przeszukuje kontrahentów po frazie _SearchText (telefon, mail, etc ale ównie nazwisko lub imiona
		Parametry
			_SearchText			Fraza szukana
			_Param_A			gdy <> '' to jest to GUID kontrahenta
		CALL erp_search_similar_('SEARCH_KONTRAH_LIKE', 'jmam', '', '', '', '');				-- szukaj wystapienia 'jmam'
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE = 'SEARCH_KONTRAH_LIKE' THEN
		CALL erp_do_search_similar(_MODE, _SearchText, '', '', 0, 1, '', '', '', _Param_D);
	END IF; -- _MODE = 'SEARCH_KONTRAH_LIKE'

/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'SEARCH_OSOBY_LIKE'
		Przeszukuje kontakty po frazie _SearchText (telefon, mail, etc ale ównie nazwisko lub imiona
		Parametry
			_SearchText			Fraza szukana
			_Param_A			= '' to również grupy
								 '' tylko osoby
			_Param_B			
								= '' 	to tylko widoczne w HR
								!= ''	wszystkie osoby 
			_Param_C			
								= '' 	to nie serwisowcy
								!= ''	wszystkie osoby 
		CALL erp_search_similar('SEARCH_OSOBY_LIKE', 'jmam', '', '', '', '');				-- szukaj wystapienia 'jmam'
		CALL erp_search_similar('SEARCH_OSOBY_LIKE', 'jmam', '1', '', '', '');
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE = 'SEARCH_OSOBY_LIKE' THEN
		CALL erp_do_search_similar('SEARCH_OSOBY_LIKE', _SearchText, '', '', 0, 1, '', '', '', '');				-- szukaj wystapienia 'jmam'
	END IF; -- _MODE = 'SEARCH_OSOBY_LIKE'

/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'SEARCH_ADR_LIKE'
		Przeszukuje kontakty po frazie _SearchText (telefon, mail, etc ale ównie nazwisko lub imiona
		Parametry
			_SearchText		Fraza szukana
			_Param_A			Typ medium np. tylko mail
		CALL erp_search_similar('SEARCH_ADR_LIKE', 'jmam', '', '', '', '');				-- szukaj wystapienia 'jmam'
		CALL erp_search_similar('SEARCH_ADR_LIKE', 'jmam', '3', '', '', '');			-- szukaj wystapienia 'jmam' ale tylko maile
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE = 'SEARCH_ADR_LIKE' THEN
		SET _SearchText = IFNULL(_SearchText, '');
		SET _Param_A = IFNULL(_Param_A, '');
		SET _SearchTextWithoutSpaces = _varSTR_Flush_Spaces(_SearchText);
		CREATE TEMPORARY TABLE `t_erp_search_similar`
			SELECT 
				_VarStr(CONCAT('"', o.Imiona, ' ', o.Nazwisko, '" <', IF(t.media_notify = 0, PIM_PhoneNumber('FMT1', k.adres, k.typ_medium), k.adres), '>')) AS DisplayValue,
				o.GUID AS OsobaGUID, k.GUID AS KontaktGUID, 
				CONCAT(o.Imiona, ' ', o.Nazwisko) As ImionaNazwisko,
				o.IdnUser, k.Adres, k.typ_medium
			FROM `osoby` o
			LEFT JOIN `kontakty` k ON k.OsobaGUID = o.GUID
			LEFT JOIN v_pim_media_types t ON t.ID = k.typ_medium
			WHERE
				IFNULL(k.Adres, '') != '' AND
				IF(_Param_A = '', 
					TRUE,
					k.typ_medium = _Param_A
				) AND
				(
					o.Imiona LIKE CONCAT('%', _SearchText, '%')
					OR
					o.Nazwisko LIKE CONCAT('%', _SearchText, '%')
					OR
					_varSTR_Flush_Spaces(k.Adres) LIKE CONCAT('%', _SearchTextWithoutSpaces, '%')
				)
			GROUP BY o.GUID, k.GUID	
		;	
	--	SELECT	
		IF _Param_C = '' THEN
			SELECT * FROM `t_erp_search_similar`;
		ELSE
			SELECT 
				DisplayValue AS LookupStr, ImionaNazwisko AS Descr, KontaktGUID AS ID
			FROM `t_erp_search_similar`
			;
		END IF;
	--	DROP 
		DROP TEMPORARY TABLE IF EXISTS `t_erp_search_similar`;
	END IF; -- _MODE = 'SEARCH_ADR_LIKE'

/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'SEARCH_TOWAR_LIKE'
		Przeszukuje towary po frazie _SearchText (nazwa, symbol, symboludost, SymbolProducenta, kod_kreskowy, kod_kreskowy1, kod_kreskowy2
		Parametry
			_SearchText			Fraza szukana
		CALL erp_search_similar('SEARCH_TOWAR_LIKE', 'TOWARX', '', '', '', '');				-- szukaj wystapienia 'TOWARX'
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE = 'SEARCH_TOWAR_LIKE' THEN
		SET @_Value := '??';	--	Tak trzeba!!!!!!!!!!!!! PATRZ PIM_PhoneNumber
		SET _SearchText = IFNULL(_SearchText, '');
		SET _SearchTextWithoutSpaces = _varSTR_Flush_Spaces(_SearchText);
		SET _SearchLen = LENGTH(_SearchText);
		SET _SearchLenAddr = LENGTH(_SearchTextWithoutSpaces);
		SET _SearchIsMail = LOCATE('@', _SearchTextWithoutSpaces) > 0; -- select _SearchIsMail;
		
		CREATE TEMPORARY TABLE `t_erp_search_similar`
			SELECT 	
				_VarStr(
					IF(t.Nazwa LIKE CONCAT('%', _SearchText, '%'),
						LTRIM(CONCAT(t.Nazwa, ' ', t.Symbol)),
						IF(t.symboludost LIKE CONCAT(_SearchText, '%'), 
							LTRIM(CONCAT(t.symboludost, ' - ', t.Nazwa)),
							IF(t.SymbolProducenta LIKE CONCAT(_SearchText, '%'), 
								LTRIM(CONCAT(t.SymbolProducenta, '  ', t.Nazwa)),
								LTRIM(CONCAT(t.Symbol, ' ', t.Nazwa))
							)
						)	
					)
				) AS Towar,
				_VarStr(
					IFNULL(
						GROUP_CONCAT(DISTINCT 
							IF(t.symboludost LIKE CONCAT(_SearchText, '%'), 
								CONCAT('u dostawcy: ', t.symboludost), 
								IF(t.SymbolProducenta LIKE CONCAT(_SearchText, '%'), 
									CONCAT('u producenta: ', t.SymbolProducenta), 
									IF(t.kod_kreskowy LIKE CONCAT(_SearchText, '%'), 
										CONCAT('kod kreskowy: ', t.kod_kreskowy), 
										IF(t.kod_kreskowy1 LIKE CONCAT(_SearchText, '%'), 
											CONCAT('kod kreskowy II: ', t.kod_kreskowy1), 
											IF(t.kod_kreskowy2 LIKE CONCAT(_SearchText, '%'), 
												CONCAT('kod kreskowy III: ', t.kod_kreskowy2), 
												NULL
											)	
										)	
									)	
								) 
							)	
						SEPARATOR ', '
						),
						'*'
					)	
				) AS LabelSearch,
				t.GUID AS TowrGUID
			FROM `TowrNg` t
			WHERE t.promocja_status<>2 AND
				(
					IF(_SearchLen < 4, FALSE, t.Nazwa LIKE CONCAT('%', _SearchText, '%'))
					OR
					t.Symbol LIKE CONCAT(_SearchText, '%')
					OR
					IF(_SearchLen < 3, FALSE, t.symboludost LIKE CONCAT(_SearchText, '%'))
					OR
					IF(_SearchLen < 3, FALSE, t.SymbolProducenta LIKE CONCAT(_SearchText, '%'))
					OR
					IF(_SearchLen < 3, FALSE, t.kod_kreskowy LIKE CONCAT(_SearchText, '%'))
					OR
					IF(_SearchLen < 3, FALSE, t.kod_kreskowy1 LIKE CONCAT(_SearchText, '%'))
					OR
					IF(_SearchLen < 3, FALSE, t.kod_kreskowy2 LIKE CONCAT(_SearchText, '%'))
				)
			GROUP BY t.GUID
			ORDER BY Towar
			LIMIT 200
		;	
	--	SELECT	
		IF _Param_C = '' THEN
			SELECT * FROM `t_erp_search_similar`;
		ELSE
			SELECT 
				Towar AS LookupStr, LabelSearch AS Descr, TowrGUID AS ID
			FROM `t_erp_search_similar`
			;
		END IF;
	--	DROP 
		DROP TEMPORARY TABLE IF EXISTS `t_erp_search_similar`;
		
	END IF; -- _MODE = 'SEARCH_TOWAR_LIKE'

/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'SEARCH_INSTANCJE_LIKE'
		Przeszukuje egzemplarze po frazie _SearchText (nazwa, symbol, kod_kreskowy etc
		Parametry
			_SearchText			Fraza szukana
		CALL erp_search_similar('SEARCH_INSTANCJE_LIKE', 'TOWARX', '', '', '', '');				-- szukaj wystapienia 'TOWARX'
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE = 'SEARCH_INSTANCJE_LIKE' THEN
		SET @_Value := '??';	--	Tak trzeba!!!!!!!!!!!!! PATRZ PIM_PhoneNumber
		SET _SearchText = IFNULL(_SearchText, '');
		SET _SearchTextWithoutSpaces = _varSTR_Flush_Spaces(_SearchText);
		SET _SearchLen = LENGTH(_SearchText);
		SET _SearchLenAddr = LENGTH(_SearchTextWithoutSpaces);
		SET _SearchIsMail = LOCATE('@', _SearchTextWithoutSpaces) > 0; -- select _SearchIsMail;
		SET
			@srch_instancje_kod_kreskowy := FALSE,
			@srch_instancje_nr_seryjny := FALSE, 
			@srch_instancje_Opis := FALSE,
			@srch_instancje_nrinwentarz := FALSE,
			@srch_instancje_TowrNazwa := FALSE,
			@srch_instancje_TowrSymbol := FALSE,
			@srch_instancje_nrinwentarzobcy := FALSE
		;
		
		CREATE TEMPORARY TABLE `t_erp_search_similar`
			SELECT 	
				_VarStr(
					IF(@srch_instancje_kod_kreskowy, 
						CONCAT('', ti.kod_kreskowy),
						IF(@srch_instancje_nr_seryjny,
							CONCAT('', ti.nr_seryjny),
							IF(@srch_instancje_Opis,
								CONCAT('', ti.opis),
								IF(@srch_instancje_nrinwentarz,
									CONCAT('', ti.nrinwentarz, ' - ', t.Nazwa, ' ', t.Symbol),
									IF(@srch_instancje_TowrNazwa,
										CONCAT('', t.Nazwa, ' ', t.Symbol),
										IF(@srch_instancje_TowrSymbol, 
											CONCAT('', t.symbol, ' - ', t.Nazwa),
											IF(@srch_instancje_nrinwentarzobcy, 
												CONCAT('', ti.nrinwentarzobcy),
												CONCAT('', ti.kod_kreskowy)
											)
										)	
									)
								)	
							)	
						) 
					)	
				) AS InstancjaSearch,
				_VarStr(
					IFNULL(
						GROUP_CONCAT(DISTINCT 
							IF(@srch_instancje_kod_kreskowy, 
								CONCAT('kod kreskowy: ', ti.kod_kreskowy, ' - ', ti.opis),
								IF(@srch_instancje_nr_seryjny,
									CONCAT('nr seryjny: ', ti.nr_seryjny, ' - ', ti.opis),
									IF(@srch_instancje_Opis,
										CONCAT('opis: ', ti.opis),
										IF(@srch_instancje_nrinwentarz,
											CONCAT('nr inwen: ', ti.nrinwentarz, ' - ', t.Nazwa, ' ', t.Symbol, ' - ', ti.opis),
											IF(@srch_instancje_TowrNazwa,
												CONCAT('towar: ', t.Nazwa, ' ', t.Symbol, ' inw.', ti.nrinwentarz, ' inw.', ti.kod_kreskowy),
												IF(@srch_instancje_TowrSymbol, 
													CONCAT('towar: ', t.symbol, ' - ', t.Nazwa, ' inw.', ti.nrinwentarz, ' inw.', ti.kod_kreskowy),
													IF(@srch_instancje_nrinwentarzobcy, 
														CONCAT('nr inwentarz.obcy: ', ti.nrinwentarzobcy, ' - ', ti.opis),
														NULL
													)
												)	
											)
										)	
									) 
								) 
							)	
						SEPARATOR ', '
						),
						'*'
					)	
				) AS LabelSearch,
				ti.GUID AS GUID,
				ti.IdnTowr,
				ti.is_multi_instancje
			FROM `towrng_instancje` ti
			INNER JOIN `TowrNg` t ON t.GUID = ti.IdnTowr
			WHERE		
				(
					(@srch_instancje_kod_kreskowy := IF(_SearchLen < 3, FALSE, ti.kod_kreskowy LIKE CONCAT(_SearchText, '%')))
					OR
					(@srch_instancje_nr_seryjny := IF(_SearchLen < 3, FALSE, ti.nr_seryjny LIKE CONCAT(_SearchText, '%')))
					OR
					(@srch_instancje_Opis := IF(_SearchLen < 4, FALSE, ti.Opis LIKE CONCAT('%', _SearchText, '%')))
					OR
					(@srch_instancje_nrinwentarz := IF(_SearchLen < 3, FALSE, ti.nrinwentarz LIKE CONCAT(_SearchText, '%')))
					OR
					(@srch_instancje_TowrNazwa := IF(_SearchLen < 4, FALSE, t.Nazwa LIKE CONCAT('%', _SearchText, '%')))
					OR
					(@srch_instancje_TowrSymbol := IF(_SearchLen < 4, FALSE, t.Symbol LIKE CONCAT(_SearchText, '%')))
					OR
					(@srch_instancje_nrinwentarzobcy := IF(_SearchLen < 3, FALSE, ti.nrinwentarzobcy LIKE CONCAT(_SearchText, '%')))
				)
			-- GROUP BY ti.GUID
			GROUP BY ti.IdnTowr, ti.Kod_Kreskowy
			ORDER BY InstancjaSearch
			LIMIT 200
		;	
	--	SELECT	
		IF _Param_C = '' THEN
			SELECT * FROM `t_erp_search_similar`;
		ELSE
			SELECT 
				InstancjaSearch AS LookupStr, LabelSearch AS Descr, GUID AS ID
			FROM `t_erp_search_similar`
			;
		END IF;
	--	DROP 
		DROP TEMPORARY TABLE IF EXISTS `t_erp_search_similar`;
	END IF; -- _MODE = 'SEARCH_INSTANCJE_LIKE'

/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'SEARCH_HR_CARDS_LIKE'
		Przeszukuje egzemplarze po frazie _SearchText (nazwa, symbol, kod_kreskowy etc
		Parametry
			_SearchText			Fraza szukana
			_Param_A			typ karty (Kind)  np 'RCP' 'ID' 'PASS' etc. (definicje znajdziesz w `slowniki_pierwotne` `sp` WHERE `sp`.`Slownik_GUID` = 'HR_CARDS_TYPE' 
		CALL erp_search_similar('SEARCH_HR_CARDS_LIKE', 'AJX', '', '', '', '');				-- szukaj wystapienia 'AJX'
		CALL erp_search_similar('SEARCH_HR_CARDS_LIKE', 'AJX', 'RCP', '', '', '');			-- szukaj wystapienia 'AJX' w kartach RCP
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE = 'SEARCH_HR_CARDS_LIKE' THEN
		SET @_Value := '??';	--	Tak trzeba!!!!!!!!!!!!! PATRZ PIM_PhoneNumber
		SET _SearchText = IFNULL(_SearchText, '');
		SET _SearchTextWithoutSpaces = _varSTR_Flush_Spaces(_SearchText);
		SET _SearchLen = LENGTH(_SearchText);
		SET _SearchLenAddr = LENGTH(_SearchTextWithoutSpaces);
		SET _SearchIsMail = LOCATE('@', _SearchTextWithoutSpaces) > 0; -- select _SearchIsMail;
		SET
			@srch_hr_cards_ID := FALSE,
			@srch_hr_cards_Osoba := FALSE
		;
		CREATE TEMPORARY TABLE `t_erp_search_similar`
			SELECT 
				_VarStr(
					IF(@srch_hr_cards_ID, 
						c.ID,
						IF(@srch_hr_cards_Osoba, 
							c.Nazwisko_Imiona,
							c.ID
						)
					)
				) AS CardSearch,
				_VarStr(
					CONCAT(c.KindStr, ': ', c.ID, ' (', c.Nazwisko_Imiona, ')',
					/*
						IF(@srch_hr_cards_ID, 
							CONCAT(c.KindStr, ': ', c.ID, ' osoby: ', c.Nazwisko_Imiona),
							IF(@srch_hr_cards_Osoba, 
								CONCAT(c.Nazwisko_Imiona, ' ', c.KindStr, ': ', c.ID),
								c.ID
							)
						)
					*/
					''
					)	
				) AS LabelSearch,
				c.Nazwisko_Imiona,
				c.ID, c.Kind
			FROM `v_hr_cards` c
			WHERE
				IF(_Param_A != '', c.Kind = _Param_A, TRUE)
				AND
				(
					(@srch_hr_cards_ID := IF(_SearchLen < 3, FALSE, REPLACE(c.ID, ' ', '') LIKE CONCAT(_SearchTextWithoutSpaces, '%')))
					OR
					(@srch_hr_cards_Osoba := IF(_SearchLen < 3, FALSE, c.Nazwisko_Imiona LIKE CONCAT('%', _SearchText, '%')))
				)
			GROUP BY c.ID, c.Kind
			ORDER BY CardSearch, LabelSearch
			LIMIT 200
		;
	--	SELECT	
		IF _Param_C = '' THEN
			SELECT * FROM `t_erp_search_similar`;
		ELSE
			SELECT 
				CardSearch AS LookupStr, LabelSearch AS Descr, ID AS ID
			FROM `t_erp_search_similar`
			;
		END IF;
	--	DROP 
		DROP TEMPORARY TABLE IF EXISTS `t_erp_search_similar`;
	END IF; -- _MODE = 'SEARCH_HR_CARDS_LIKE'

/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'SEARCH_FK_LIKE'
		Przeszukuje konta po frazie _SearchText (Symbol_fmt, Nazwa
		Parametry
			_SearchText			Fraza szukana
			_Param_A			Rok
		CALL erp_search_similar('SEARCH_FK_LIKE', 'aparaty', '2012', '', '', '');				-- szukaj wystapienia 'aparaty' w roku 2012
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE = 'SEARCH_FK_LIKE' THEN
		SET @_Value := '??';	--	Tak trzeba!!!!!!!!!!!!! PATRZ PIM_PhoneNumber
		SET _SearchText = IFNULL(_SearchText, '');
		SET _SearchTextWithoutSpaces = _varSTR_Flush_Spaces(_SearchText);
		SET _SearchLen = LENGTH(_SearchText);
		SET _SearchLenAddr = LENGTH(_SearchTextWithoutSpaces);
		SET @IsDigit = (LEFT(_SearchText, 1) IN ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'));
		-- IREG 'Konta_pierwsze_znaki_bez_separatora'  INT\SYSTEM\MOTLAWA\FK  w CDG = 3
	-- 	IF @IsDigit AND LENGTH(_SearchText) <= 3 + 3 + 3 THEN
		IF @IsDigit THEN
				SET @Poziom2 = -1;
				SELECT 
					p.poziom 
				FROM `plankont` p
				WHERE
					p.Rok = _Param_A
					AND
					p.Symbol_fmt = _SearchText
				INTO @Poziom2	
				;	
				SET @Poziom2 = IFNULL(@Poziom2, -1);
		
			IF LOCATE('-', _SearchText) = 99990 THEN
			-- IF _SearchLen < 3 THEN
				SET @Poziom = 1;
			ELSE	
			
				SELECT 
					MIN(p.poziom) 
				FROM `plankont` p
				WHERE
					p.Rok = _Param_A
					AND
					p.Symbol_fmt LIKE CONCAT(_SearchText, '%')
				INTO @Poziom	
				;	
				SET @Poziom = IFNULL(@Poziom,1);
			END IF;
			
			IF LOCATE('-', _SearchText) = 0 THEN
				SET @Poziom = @Poziom - 1;
			END IF;
			
			IF @Poziom2 > 0 THEN
				SET @Poziom = @Poziom2;
			END IF; 
			
			CREATE TEMPORARY TABLE `t_erp_search_similar`
				SELECT
					p.GUID,
					_CutSTR(
						IF(@srch_Nazwa,
							p.Nazwa,
							IF(@srch_Symbol_Fmt,
								CONCAT(Symbol_fmt, IF(p.Dl_potomka > 0, '  (+)', '')),
								CONCAT(Symbol_fmt, IF(p.Dl_potomka > 0, '  (+)', ''))
							)	
						),
						30, '...'
					) AS KontoSearch,	
					_VarStr(
						IF(@srch_Symbol_Fmt,
							p.Nazwa,
							CONCAT(CONCAT(Symbol_fmt, IF(p.Dl_potomka > 0, ' (+)', '')), ' ', Nazwa)
						)
					) AS Nazwa,
					p.Poziom,
					p.Symbol_fmt,
					@Poziom2,
					@Poziom
				FROM `plankont` p
				WHERE
					p.Rok = _Param_A
					AND
					p.Poziom <= @Poziom	+ 1
					AND
					(
						(@srch_Symbol_Fmt := IF((_SearchLen < 2), FALSE, p.Symbol_fmt LIKE CONCAT(_SearchText, '%')))
					)
				ORDER BY KontoSearch	
				LIMIT 500
			;
		ELSE
			CREATE TEMPORARY TABLE `t_erp_search_similar`
				SELECT
					p.GUID,
					_CutSTR(
						IF(@srch_Nazwa,
							p.Nazwa,
							IF(@srch_Symbol_Fmt,
								CONCAT(Symbol_fmt, IF(p.Dl_potomka > 0, '  (+)', '')),
								CONCAT(Symbol_fmt, IF(p.Dl_potomka > 0, '  (+)', ''))
							)	
						),
						30, '...'
					) AS KontoSearch,	
					_VarStr(
						IF(@srch_Symbol_Fmt,
							p.Nazwa,
							CONCAT(CONCAT(Symbol_fmt, IF(p.Dl_potomka > 0, ' (+)', '')), ' ', Nazwa)
						)
					) AS Nazwa,
					p.Symbol_fmt
				FROM `plankont` p
				WHERE
					p.Rok = _Param_A
					AND
					(
						(@srch_Symbol_Fmt := IF((_SearchLen < 3), FALSE, p.Symbol_fmt LIKE CONCAT(_SearchText, '%')))
					OR
						(@srch_Nazwa := IF((_SearchLen < 4), FALSE, p.Nazwa LIKE CONCAT('%', _SearchText, '%')))
					-- OR
					-- (@srch_NazwaFull := IF((_SearchLen < 6), FALSE, kn.Nazwa LIKE CONCAT('%', _SearchText, '%')))
					)
				ORDER BY KontoSearch	
				LIMIT 500
			;
		END IF;
	--	SELECT	
		IF _Param_C = '' THEN
			SELECT * FROM `t_erp_search_similar`;
		ELSE
			SELECT 
				KontoSearch AS LookupStr, Nazwa AS Descr, IF(_Param_C = '2', Symbol_fmt, GUID) AS ID
			FROM `t_erp_search_similar`
			;
		END IF;
	--	DROP 
		DROP TEMPORARY TABLE IF EXISTS `t_erp_search_similar`;
	END IF; -- _MODE = 'SEARCH_FK_LIKE'

/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'SEARCH_MAG_LOKALIZACJE_LIKE'
		Przeszukuje towary po frazie _SearchText (nazwa, symbol, symboludost, SymbolProducenta, kod_kreskowy, kod_kreskowy1, kod_kreskowy2
		Parametry
			_SearchText			Fraza szukana
		CALL erp_search_similar('SEARCH_MAG_LOKALIZACJE_LIKE', 'W2-', '', '', '', '');				-- szukaj wystapienia 'W2-'
		CALL erp_search_similar('SEARCH_MAG_LOKALIZACJE_LIKE', 'Mag', '', '', '', '');				-- szukaj wystapienia 'Mag'
		CALL erp_search_similar('SEARCH_MAG_LOKALIZACJE_LIKE', 'Mag II', '', '', '', '');			-- szukaj wystapienia 'Mag II'
		CALL erp_search_similar('SEARCH_MAG_LOKALIZACJE_LIKE', 'Reg.1-', '', '', '', '');			-- szukaj wystapienia 'R1-'
		CALL erp_search_similar('SEARCH_MAG_LOKALIZACJE_LIKE', 'Reg.1|', '', '', '', '');			-- szukaj wystapienia 'R1|'
		CALL erp_search_similar('SEARCH_MAG_LOKALIZACJE_LIKE', 'R', '', '', '', '');				-- szukaj wystapienia 'R'
		CALL erp_search_similar('SEARCH_MAG_LOKALIZACJE_LIKE', 'Sopot', '', '', '', '');			-- szukaj wystapienia 'Sopot'
		CALL erp_search_similar('SEARCH_MAG_LOKALIZACJE_LIKE', 'Drzwiczki', '', '', '', '');			-- szukaj wystapienia 'Drzwiczki'
		CALL erp_search_similar('SEARCH_MAG_LOKALIZACJE_LIKE', 'Miejsce', '', '', '', '');			-- szukaj wystapienia 'Miejsce'
		CALL erp_search_similar('SEARCH_MAG_LOKALIZACJE_LIKE', 'pokrywy', '', '', '', '');			-- szukaj wystapienia 'pokrywy'
		CALL erp_search_similar('SEARCH_MAG_LOKALIZACJE_LIKE', 'Miejsce', 'dbb1c292-8a5e-11e2-b43c-525400b491c0*', '', '', '');			-- z guida
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE = 'SEARCH_MAG_LOKALIZACJE_LIKE' THEN
		SET _Param_A = IFNULL(_Param_A, '');
		SET @_Value := '??';	--	Tak trzeba!!!!!!!!!!!!! PATRZ PIM_PhoneNumber
		SET _SearchText = IFNULL(_SearchText, '');
		SET @Srch_Include_minus = (LOCATE('|', _SearchText) = 0);
		
		SET _SearchTextWithoutSpaces = _varSTR_Flush_Spaces(_SearchText);
		SET _SearchLen = LENGTH(_SearchText);
		SET _SearchLenAddr = LENGTH(_SearchTextWithoutSpaces);
		SET _SearchIsMail = LOCATE('@', _SearchTextWithoutSpaces) > 0; -- select _SearchIsMail;
		
		SET 
			@FindPathA = FALSE,
			@FindPathB = FALSE,
			@FindPathC = FALSE,
			@Search_z_GUIDA = (_Param_A != '')
		;
		
		IF NOT @Search_z_GUIDA AND _SearchText = '' THEN
		--	Gdy Szukamy pustego to szukaj tak by zwrócić pusty rekord
			SET 
				@Search_z_GUIDA = TRUE,
				_Param_A = NEWGUID()	--	to gwarantuje pusty rekord bo nie znajdzie takiego GUID-a (n.GUID = _Param_A)
			;
		END IF;
		
		IF @Search_z_GUIDA THEN
		--	tylko z GUIDA lub gdy chcemy pusty
			SELECT 
				_VarStr(REPLACE(n.Path, '|', '-')) AS IncrText,
				_VarStr(REPLACE(n.Path, '|', ' - ')) AS Path,
				n.GUID 
			FROM `erp_area_nodes` n 
			WHERE 
				TRUE 
				AND 
				(n.GUID = _Param_A)
			LIMIT 1
			;	
		ELSE
		--	zwykly search
			CREATE TEMPORARY TABLE `t_erp_search_similar`
				SELECT 
					_VarStr(CONCAT(
						IF(@FindPathC, n.Nazwa,
							IF(NOT @Srch_Include_minus,
								SUBSTR(n.Path, LOCATE(_SearchText, n.Path), 255), 
								SUBSTR(@Path := REPLACE(n.Path, '|', '-'), LOCATE(_SearchText, @Path), 255)
							)	
						),
						IF(n.Symbol = n.Nazwa,
							'',
							CONCAT(' / ', TRIM(REPLACE(n.Nazwa, n.Symbol, '')))
						)	
					)) AS IncrText,
					_VarStr(REPLACE(n.Path, '|', ' - ')) AS Path,
					n.GUID 
				FROM `erp_area_nodes` n 
				WHERE 
					TRUE 
					AND 
					(
						@FindPathA := (n.Path LIKE CONCAT('%', _SearchText, '%'))
						OR
						@FindPathB := (REPLACE(n.Path, '|', '-') LIKE CONCAT('%', _SearchText, '%'))
						OR
						@FindPathC := (n.Nazwa LIKE CONCAT('%', _SearchText, '%'))
					)	
					AND n.Type LIKE 'MAG%'
				GROUP BY n.GUID
				ORDER BY IncrText
				LIMIT 200
			;	
		--	SELECT	
			IF _Param_C = '' THEN
				SELECT * FROM `t_erp_search_similar`;
			ELSE
				SELECT 
					IncrText AS LookupStr, Path AS Descr, GUID AS ID
				FROM `t_erp_search_similar`
				;
			END IF;
		--	DROP 
			-- DROP TEMPORARY TABLE IF EXISTS `t_erp_search_similar`;
		END IF;
		
	END IF; -- _MODE = 'SEARCH_MAG_LOKALIZACJE_LIKE'

/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'SEARCH_Magazyny'
		Przeszukuje Magazyny po frazie _SearchText 
		Parametry
			_SearchText			Fraza szukana
			_Param_A			gdy <> '' to jest to IdnMagazynu
		CALL erp_search_similar('SEARCH_Magazyny', 'Wyro', '', '', '', '');				-- szukaj wystapienia 'Wyro'
		CALL erp_search_similar('SEARCH_Magazyny', '', '2', '', '', '');			-- pokaz Magazyn IdnMagazynu = 2
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE = 'SEARCH_Magazyny' THEN
		SET _SearchText = TRIM(_SearchText);
		DROP TEMPORARY TABLE IF EXISTS `t_Search_Magazyny`;
		CREATE TEMPORARY TABLE `t_Search_Magazyny`
		(
			SELECT 
				_VarStr('') AS LkSearch,
				CONCAT(m.Opis, ' ', m.Symbol) AS FullName,
				m.IdnMagazynu
			FROM `Magazyny` m
			WHERE
			FALSE
		);
		TRUNCATE `t_Search_Magazyny`;
		ALTER TABLE `t_Search_Magazyny`
			ADD PRIMARY KEY IdnMagazynu(IdnMagazynu)
		;	
		IF _Param_A != '' THEN
			INSERT IGNORE INTO `t_Search_Magazyny`	
				SELECT 
					m.Opis AS LkSearch,
					CONCAT(m.Opis, ' ', m.Symbol) AS FullName,
					m.IdnMagazynu
				FROM `Magazyny` m
				WHERE
					m.IdnMagazynu = _Param_A
			;
		ELSE
			IF SUBSTRING(_SearchText, 1, 1) IN ('0','1','2','3','4','5','6','7','8','9') THEN
				INSERT IGNORE INTO `t_Search_Magazyny`	
					SELECT 
						_VarStr_NotNull(CONCAT(m.IdnMagazynu, ' ', m.Opis)) AS LkSearch,  
						CONCAT(m.Opis, ' ', m.Symbol) AS FullName,
						m.IdnMagazynu
					FROM `Magazyny` m
					WHERE
						m.IdnMagazynu LIKE CONCAT('', _SearchText, '%')
				;
			ELSE
				INSERT IGNORE INTO `t_Search_Magazyny`	
					SELECT 
						_VarStr_NotNull(CONCAT(m.Opis, ' ', m.Symbol)) AS LkSearch,  
						CONCAT(m.Opis, ' ', m.Symbol) AS FullName,
						m.IdnMagazynu
					FROM `Magazyny` m
					WHERE
						m.Opis LIKE CONCAT('', _SearchText, '%')
				;
				INSERT IGNORE INTO `t_Search_Magazyny`	
					SELECT 
						_VarStr_NotNull(CONCAT(m.Symbol, ' ', m.Opis)) AS LkSearch,  
						CONCAT(m.Opis, ' ', m.Symbol) AS FullName,
						m.IdnMagazynu
					FROM `Magazyny` m
					WHERE
						m.Symbol LIKE CONCAT('', _SearchText, '%')
				;
				IF LENGTH(_SearchText) > 4 THEN
					INSERT IGNORE INTO `t_Search_Magazyny`	
						SELECT 
							_VarStr_NotNull(CONCAT(m.Opis, ' ', m.Symbol)) AS LkSearch,  
							CONCAT(m.Opis, ' ', m.Symbol) AS FullName,
							m.IdnMagazynu
						FROM `Magazyny` m
						WHERE
							m.Opis LIKE CONCAT('%', _SearchText, '%')
					;
				END IF;
			END IF;
		END IF;
		
		CREATE TEMPORARY TABLE `t_erp_search_similar`
			SELECT * FROM `t_Search_Magazyny`
		;
	--	SELECT	
		IF _Param_C = '' THEN
			SELECT * FROM `t_erp_search_similar`;
		ELSE
			SELECT 
				LkSearch AS LookupStr, FullName AS Descr, IdnMagazynu AS ID
			FROM `t_erp_search_similar`
			;
		END IF;
	--	DROP 
		DROP TEMPORARY TABLE IF EXISTS `t_erp_search_similar`;
		DROP TEMPORARY TABLE IF EXISTS `t_Search_Magazyny`;
	END IF; -- _MODE = 'SEARCH_Magazyny'
	
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'SEARCH_Kasy'
		Przeszukuje Kasy po frazie _SearchText 
		Parametry
			_SearchText			Fraza szukana
			_Param_A			gdy <> '' to jest to Idn
		CALL erp_search_similar('SEARCH_Kasy', 'Kasa', '', '', '', '');			-- szukaj wystapienia 'Wyro'
		CALL erp_search_similar('SEARCH_Kasy', '', '2', '', '', '');			-- pokaz kasa Idn = 2
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE = 'SEARCH_Kasy' THEN
		SET _SearchText = TRIM(_SearchText);
		DROP TEMPORARY TABLE IF EXISTS `t_Search_Kasy`;
		CREATE TEMPORARY TABLE `t_Search_Kasy`
		(
			SELECT 
				_VarStr('') AS LkSearch,
				CONCAT(k.NazwaKasy, ' ', k.Symbol) AS FullName,
				k.Idn
			FROM `kasy` k
			WHERE
			FALSE
		);
		TRUNCATE `t_Search_Kasy`;
		ALTER TABLE `t_Search_Kasy`
			ADD PRIMARY KEY Idn(Idn)
		;	
		IF _Param_A != '' THEN
			INSERT IGNORE INTO `t_Search_Kasy`	
				SELECT 
					k.NazwaKasy AS LkSearch,
					CONCAT(k.NazwaKasy, ' ', k.Symbol) AS FullName,
					k.Idn
				FROM `kasy` k
				WHERE
					k.Idn = _Param_A
			;
		ELSE
			IF SUBSTRING(_SearchText, 1, 1) IN ('0','1','2','3','4','5','6','7','8','9') THEN
				INSERT IGNORE INTO `t_Search_Kasy`	
					SELECT 
						_VarStr_NotNull(CONCAT(k.Idn, ' ', k.NazwaKasy)) AS LkSearch,  
						CONCAT(k.NazwaKasy, ' ', k.Symbol) AS FullName,
						k.Idn
					FROM `kasy` k
					WHERE
						k.Idn LIKE CONCAT('', _SearchText, '%')
				;
			ELSE
				INSERT IGNORE INTO `t_Search_Kasy`	
					SELECT 
						_VarStr_NotNull(CONCAT(k.NazwaKasy, '', '')) AS LkSearch,  
						CONCAT(k.Symbol) AS FullName,
						k.Idn
					FROM `kasy` k
					WHERE
						k.NazwaKasy LIKE CONCAT('', _SearchText, '%')
				;
				INSERT IGNORE INTO `t_Search_Kasy`	
					SELECT 
						_VarStr_NotNull(CONCAT(k.Symbol, '', '')) AS LkSearch,  
						CONCAT(k.NazwaKasy, '') AS FullName,
						k.Idn
					FROM `kasy` k
					WHERE
						k.Symbol LIKE CONCAT('', _SearchText, '%')
				;
				IF LENGTH(_SearchText) > 3 THEN
					INSERT IGNORE INTO `t_Search_Kasy`	
						SELECT 
							_VarStr_NotNull(CONCAT(k.NazwaKasy, '', '')) AS LkSearch,  
							CONCAT(k.NazwaKasy, ' ', k.Symbol) AS FullName,
							k.Idn
						FROM `kasy` k
						WHERE
							k.NazwaKasy LIKE CONCAT('%', _SearchText, '%')
					;
					INSERT IGNORE INTO `t_Search_Kasy`	
						SELECT 
							_VarStr_NotNull(CONCAT(k.KontoFK, ' ', k.NazwaKasy)) AS LkSearch,  
							CONCAT(k.NazwaKasy, '') AS FullName,
							k.Idn
						FROM `kasy` k
						WHERE
							k.KontoFK LIKE CONCAT('%', _SearchText, '%')
					;
				END IF;
			END IF;
		END IF;
		
		CREATE TEMPORARY TABLE `t_erp_search_similar`
			SELECT * FROM `t_Search_Kasy`
		;
	--	SELECT	
		IF _Param_C = '' THEN
			SELECT * FROM `t_erp_search_similar`;
		ELSE
			SELECT 
				LkSearch AS LookupStr, FullName AS Descr, Idn AS ID
			FROM `t_erp_search_similar`
			;
		END IF;
	--	DROP 
		DROP TEMPORARY TABLE IF EXISTS `t_erp_search_similar`;
		DROP TEMPORARY TABLE IF EXISTS `t_Search_Kasy`;
	END IF; -- _MODE = 'SEARCH_Kasy'
	


/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'SEARCH_TOWAR_NISKOCENNE_LIKE'
		Przeszukuje towary po frazie _SearchText (nazwa, symbol, symboludost, SymbolProducenta, kod_kreskowy, kod_kreskowy1, kod_kreskowy2
		Parametry
			_SearchText			Fraza szukana
		CALL erp_search_similar('SEARCH_TOWAR_NISKOCENNE_LIKE', 'TOWARX', '', '', '', '');				-- szukaj wystapienia 'TOWARX'
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE = 'SEARCH_TOWAR_NISKOCENNE_LIKE' THEN
		SET @_Value := '??';	--	Tak trzeba!!!!!!!!!!!!! PATRZ PIM_PhoneNumber
		SET _SearchText = IFNULL(_SearchText, '');
		SET _SearchTextWithoutSpaces = _varSTR_Flush_Spaces(_SearchText);
		SET _SearchLen = LENGTH(_SearchText);
		SET _SearchLenAddr = LENGTH(_SearchTextWithoutSpaces);
		SET _SearchIsMail = LOCATE('@', _SearchTextWithoutSpaces) > 0; -- select _SearchIsMail;
		
		CREATE TEMPORARY TABLE `t_erp_search_similar`
			SELECT 	
				_VarStr(
					IF(t.Nazwa LIKE CONCAT('%', _SearchText, '%'),
						LTRIM(CONCAT(t.Nazwa, ' ', t.Symbol)),
						IF(t.symboludost LIKE CONCAT(_SearchText, '%'), 
							LTRIM(CONCAT(t.symboludost, ' - ', t.Nazwa)),
							IF(t.SymbolProducenta LIKE CONCAT(_SearchText, '%'), 
								LTRIM(CONCAT(t.SymbolProducenta, '  ', t.Nazwa)),
								LTRIM(CONCAT(t.Symbol, ' ', t.Nazwa))
							)
						)	
					)
				) AS Towar,
				_VarStr(
					IFNULL(
						GROUP_CONCAT(DISTINCT 
							IF(t.symboludost LIKE CONCAT(_SearchText, '%'), 
								CONCAT('u dostawcy: ', t.symboludost), 
								IF(t.SymbolProducenta LIKE CONCAT(_SearchText, '%'), 
									CONCAT('u producenta: ', t.SymbolProducenta), 
									IF(t.kod_kreskowy LIKE CONCAT(_SearchText, '%'), 
										CONCAT('kod kreskowy: ', t.kod_kreskowy), 
										IF(t.kod_kreskowy1 LIKE CONCAT(_SearchText, '%'), 
											CONCAT('kod kreskowy II: ', t.kod_kreskowy1), 
											IF(t.kod_kreskowy2 LIKE CONCAT(_SearchText, '%'), 
												CONCAT('kod kreskowy III: ', t.kod_kreskowy2), 
												NULL
											)	
										)	
									)	
								) 
							)	
						SEPARATOR ', '
						),
						'*'
					)	
				) AS LabelSearch,
				t.GUID AS TowrGUID
			FROM `TowrNg` t
			LEFT JOIN `towrng_instancje` i ON i.IdnTowr = t.GUID	
			LEFT JOIN `TowrPo` tp ON tp.IdnTowr = t.GUID -- AND tp.Magazyn = 1
			WHERE		
				(
					IF(_SearchLen < 4, FALSE, t.Nazwa LIKE CONCAT('%', _SearchText, '%'))
					OR
					t.Symbol LIKE CONCAT(_SearchText, '%')
					OR
					IF(_SearchLen < 3, FALSE, t.symboludost LIKE CONCAT(_SearchText, '%'))
					OR
					IF(_SearchLen < 3, FALSE, t.SymbolProducenta LIKE CONCAT(_SearchText, '%'))
					OR
					IF(_SearchLen < 3, FALSE, t.kod_kreskowy LIKE CONCAT(_SearchText, '%'))
					OR
					IF(_SearchLen < 3, FALSE, t.kod_kreskowy1 LIKE CONCAT(_SearchText, '%'))
					OR
					IF(_SearchLen < 3, FALSE, t.kod_kreskowy2 LIKE CONCAT(_SearchText, '%'))
				) and
				t.is_multi_instancje = 1 and t.deleted = 0 


			GROUP BY t.GUID
			ORDER BY Towar
			LIMIT 200
		;	
	--	SELECT	
		IF _Param_C = '' THEN
			SELECT * FROM `t_erp_search_similar`;
		ELSE
			SELECT 
				Towar AS LookupStr, LabelSearch AS Descr, TowrGUID AS ID
			FROM `t_erp_search_similar`
			;
		END IF;
	--	DROP 
		DROP TEMPORARY TABLE IF EXISTS `t_erp_search_similar`;
	END IF; -- _MODE = 'SEARCH_NISKOCENNE_LIKE'


	
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'SEARCH_EKSPLOATACYJNE_LIKE'
		Przeszukuje towary po frazie _SearchText (nazwa, symbol, symboludost, SymbolProducenta, kod_kreskowy, kod_kreskowy1, kod_kreskowy2
		Parametry
			_SearchText			Fraza szukana
		CALL erp_search_similar('SEARCH_EKSPLOATACYJNE_LIKE', 'TOWARX', '', '', '', '');				-- szukaj wystapienia 'TOWARX'
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE = 'SEARCH_EKSPLOATACYJNE_LIKE' THEN
		SET @_Value := '??';	--	Tak trzeba!!!!!!!!!!!!! PATRZ PIM_PhoneNumber
		SET _SearchText = IFNULL(_SearchText, '');
		SET _SearchTextWithoutSpaces = _varSTR_Flush_Spaces(_SearchText);
		SET _SearchLen = LENGTH(_SearchText);
		SET _SearchLenAddr = LENGTH(_SearchTextWithoutSpaces);
		SET _SearchIsMail = LOCATE('@', _SearchTextWithoutSpaces) > 0; -- select _SearchIsMail;
		
		CREATE TEMPORARY TABLE `t_erp_search_similar`
			SELECT 	
				_VarStr(
					IF(t.Nazwa LIKE CONCAT('%', _SearchText, '%'),
						LTRIM(CONCAT(t.Nazwa, ' ', t.Symbol)),
						IF(t.symboludost LIKE CONCAT(_SearchText, '%'), 
							LTRIM(CONCAT(t.symboludost, ' - ', t.Nazwa)),
							IF(t.SymbolProducenta LIKE CONCAT(_SearchText, '%'), 
								LTRIM(CONCAT(t.SymbolProducenta, '  ', t.Nazwa)),
								LTRIM(CONCAT(t.Symbol, ' ', t.Nazwa))
							)
						)	
					)
				) AS Towar,
				_VarStr(
					IFNULL(
						GROUP_CONCAT(DISTINCT 
							IF(t.symboludost LIKE CONCAT(_SearchText, '%'), 
								CONCAT('u dostawcy: ', t.symboludost), 
								IF(t.SymbolProducenta LIKE CONCAT(_SearchText, '%'), 
									CONCAT('u producenta: ', t.SymbolProducenta), 
									IF(t.kod_kreskowy LIKE CONCAT(_SearchText, '%'), 
										CONCAT('kod kreskowy: ', t.kod_kreskowy), 
										IF(t.kod_kreskowy1 LIKE CONCAT(_SearchText, '%'), 
											CONCAT('kod kreskowy II: ', t.kod_kreskowy1), 
											IF(t.kod_kreskowy2 LIKE CONCAT(_SearchText, '%'), 
												CONCAT('kod kreskowy III: ', t.kod_kreskowy2), 
												NULL
											)	
										)	
									)	
								) 
							)	
						SEPARATOR ', '
						),
						'*'
					)	
				) AS LabelSearch,
				t.GUID AS TowrGUID
			FROM `TowrNg` t
			WHERE		
				(
					IF(_SearchLen < 4, FALSE, t.Nazwa LIKE CONCAT('%', _SearchText, '%'))
					OR
					t.Symbol LIKE CONCAT(_SearchText, '%')
					OR
					IF(_SearchLen < 3, FALSE, t.symboludost LIKE CONCAT(_SearchText, '%'))
					OR
					IF(_SearchLen < 3, FALSE, t.SymbolProducenta LIKE CONCAT(_SearchText, '%'))
					OR
					IF(_SearchLen < 3, FALSE, t.kod_kreskowy LIKE CONCAT(_SearchText, '%'))
					OR
					IF(_SearchLen < 3, FALSE, t.kod_kreskowy1 LIKE CONCAT(_SearchText, '%'))
					OR
					IF(_SearchLen < 3, FALSE, t.kod_kreskowy2 LIKE CONCAT(_SearchText, '%'))
				) and
					t.is_multi_instancje = 0
					AND
					t.Usluga = 0
					AND
					t.deleted = 0
					AND
					NOT EXISTS (
					SELECT i.GUID FROM `towrng_instancje` i WHERE i.IdnTowr = t.GUID
					)

			GROUP BY t.GUID
			ORDER BY Towar
			LIMIT 200
		;	
	--	SELECT	
		IF _Param_C = '' THEN
			SELECT * FROM `t_erp_search_similar`;
		ELSE
			SELECT 
				Towar AS LookupStr, LabelSearch AS Descr, TowrGUID AS ID
			FROM `t_erp_search_similar`
			;
		END IF;
	--	DROP 
		DROP TEMPORARY TABLE IF EXISTS `t_erp_search_similar`;
	END IF; -- _MODE = 'SEARCH_EKSPLOATACYJNE_LIKE'
END$$

DROP PROCEDURE IF EXISTS `erp_do_search_similar_lelephon_numbers`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `erp_do_search_similar_lelephon_numbers`(
	IN _MODE VARCHAR(50),		
	IN _SearchText VARCHAR(250),	
	IN _Key VARCHAR(250),	
	IN _Phase INTEGER,
	IN _ExtParam VARCHAR(250),	
	IN _MinLen_SearchText INTEGER,	
	IN _Return_Std_Cols BOOLEAN,	--	Jesli 1 to zwracamy zawsze te same kolumny 	np. ze zwracamy wynik z `t_erp_search_similar` w sposob wolany z filtrow-lookupow
	IN _Param_A VARCHAR(250),	
	IN _Param_B VARCHAR(250),	
	IN _Param_C VARCHAR(250),	--	Jesli != '' to znaczy ze zwracamy wynik z `t_erp_search_similar` w sposob wolany z filtrow-lookupow
	IN _Param_D VARCHAR(250)
)
/*
	erp_do_search_similar
*/
S_erp_do_search_similar_lelephon_numbers: BEGIN
	DECLARE _SQLText TEXT;
	DECLARE _NewKontrahGUID VARCHAR(38) DEFAULT '';
	DECLARE _SearchTextWithoutSpaces VARCHAR(255) DEFAULT '';
	-- DECLARE _SearchTextTrimSpaces VARCHAR(255) DEFAULT '';
	DECLARE _SearchLen INTEGER;
	DECLARE _SearchLenAddr INTEGER;
	DECLARE _SearchIsMail BOOLEAN;

	DROP TEMPORARY TABLE IF EXISTS `t_erp_search_similar`;
	SET _Return_Std_Cols = IFNULL(_Return_Std_Cols, FALSE);	
	SET _Key = IFNULL(_Key, '');
	SET _SearchText = IFNULL(_SearchText, '');
	SET _SearchLen = LENGTH(_SearchText);
	SET _SearchTextWithoutSpaces = _varSTR_Flush_Spaces(_SearchText);
	SET _Param_A = IFNULL(_Param_A, '');
	SET _Param_B = IFNULL(_Param_B, '');
	SET _Param_C = IFNULL(_Param_C, '');

		IF _MODE LIKE 'SEARCH_TELEPHON_NUMBERS_LIKE%' THEN
			SET @_Value := '??';	--	Tak trzeba!!!!!!!!!!!!! PATRZ PIM_PhoneNumber
			-- SET _SearchTextTrimSpaces = RTrim(_SearchText);
			SET _SearchLenAddr = LENGTH(_SearchTextWithoutSpaces);
			SET _SearchIsMail = LOCATE('@', _SearchTextWithoutSpaces) > 0; -- select _SearchIsMail;
			
			IF RIGHT(_SearchText, 1) = ' ' THEN
				SET _SearchLen = 100;
			END IF;
			
			SET
				@_Param_A = _Param_A,
				@_Param_B = _Param_B,
				@_SearchText = _SearchText,
				@_SearchTextWithoutSpaces = _SearchTextWithoutSpaces,
				-- @_SearchTextTrimSpaces = _SearchTextTrimSpaces,
				@_SearchLen = _SearchLen,
				@_SearchLenAddr = _SearchLenAddr,
				@_SearchIsMail = _SearchIsMail
			;

			DROP TEMPORARY TABLE IF EXISTS `t_search_KO`;
			CREATE TEMPORARY TABLE IF NOT EXISTS `t_search_KO` 
			(
				`GUID` VARCHAR(38) NOT NULL DEFAULT '',
				`LK_Srch` VARCHAR(255) NOT NULL DEFAULT '', 
				`Nazwa` VARCHAR(255) NOT NULL DEFAULT '', 
				`OsobaGUID` VARCHAR(38) NOT NULL DEFAULT '',
				`KontrGUID` VARCHAR(38) NOT NULL DEFAULT '',
				`Src` VARCHAR(38) NOT NULL DEFAULT '',
				`OrderCol` VARCHAR(10) NOT NULL DEFAULT '1',
				`Found_Phase` SET('1','2','3') DEFAULT '1' COMMENT 'Jaka FAZA',
				`Found_Count` INTEGER NOT NULL DEFAULT 0,
				`Phase_1` BOOLEAN NOT NULL DEFAULT FALSE,
				`Phase_2` BOOLEAN NOT NULL DEFAULT FALSE,
				`Phase_3` BOOLEAN NOT NULL DEFAULT FALSE,
				PRIMARY KEY (`GUID`),
				UNIQUE KEY (`OsobaGUID`, `KontrGUID`)
			) 
			;
			
			CALL erp_do_search_similar_lelephon_numbers('Search.for.one', 
				_SearchText,	
				_Key,	
				1, -- IN _Phase INTEGER,
				_ExtParam,	
				_MinLen_SearchText,	
				_Return_Std_Cols,	--	Jesli 1 to zwracamy zawsze te same kolumny 	np. ze zwracamy wynik z `t_erp_search_similar` w sposob wolany z filtrow-lookupow
				_Param_A, _Param_B, _Param_C, _Param_D);
				
			SET 
				@ph.1._SearchText = '', @ph.2._SearchText = '', @ph.3._SearchText = ''
			;
			IF @t_search_KO.Count = 0 THEN
				SET 
					@ph.1._SearchText = '', @ph.2._SearchText = '', @ph.3._SearchText = '', @ph.1.space = 0, @ph.2.space = 0, @ph.3.space = 0 
				;
				
				SET @curr._SearchText = _SearchText;
				SET @ph.1.space = LOCATE(' ',  @curr._SearchText);
				IF @ph.1.space > 0 THEN
					SET @ph.1._SearchText = SUBSTR(@curr._SearchText, 1, @ph.1.space - 1);
					SET @curr._SearchText = SUBSTR(@curr._SearchText, @ph.1.space + 1, 255);
					SET @ph.2.space = LOCATE(' ',  @curr._SearchText);
					IF @ph.2.space > 0 THEN
						SET @ph.2._SearchText = SUBSTR(@curr._SearchText, 1, @ph.2.space - 1);
						SET @curr._SearchText = SUBSTR(@curr._SearchText, @ph.2.space + 1, 255);
						SET @ph.3._SearchText = @curr._SearchText;
					ELSE
						SET @ph.2._SearchText = @curr._SearchText;
					END IF;
				END IF;
				
				IF @ph.1._SearchText != '' THEN
					SET @Found_Phase = '1';
					CALL erp_do_search_similar_lelephon_numbers('Search.for.one', 
						@ph.1._SearchText,	
						_Key,	
						1, -- IN _Phase INTEGER,
						_ExtParam,	
						_MinLen_SearchText,	
						_Return_Std_Cols,	--	Jesli 1 to zwracamy zawsze te same kolumny 	np. ze zwracamy wynik z `t_erp_search_similar` w sposob wolany z filtrow-lookupow
						_Param_A, _Param_B, _Param_C, _Param_D);
				END IF;
					
				IF @ph.2._SearchText != '' THEN
					SET @Found_Phase = '1,2';
					CALL erp_do_search_similar_lelephon_numbers('Search.for.one', 
						@ph.2._SearchText,	
						_Key,	
						2, -- IN _Phase INTEGER,
						_ExtParam,	
						_MinLen_SearchText,	
						_Return_Std_Cols,	--	Jesli 1 to zwracamy zawsze te same kolumny 	np. ze zwracamy wynik z `t_erp_search_similar` w sposob wolany z filtrow-lookupow
						_Param_A, _Param_B, _Param_C, _Param_D);
				END IF;
				
				IF @ph.3._SearchText != '' THEN
					SET @Found_Phase = '1,2,3';
					CALL erp_do_search_similar_lelephon_numbers('Search.for.one', 
						@ph.3._SearchText,	
						_Key,	
						3, -- IN _Phase INTEGER,
						_ExtParam,	
						_MinLen_SearchText,	
						_Return_Std_Cols,	--	Jesli 1 to zwracamy zawsze te same kolumny 	np. ze zwracamy wynik z `t_erp_search_similar` w sposob wolany z filtrow-lookupow
						_Param_A, _Param_B, _Param_C, _Param_D);
				END IF;
				
			ELSE
				SET @Found_Phase = '1';
			END IF;

			SELECT
				KO.*,
				kn.adres, 
				CONCAT(o.Imie1, ' ',o.Nazwisko) AS Osoba_Str, 
				IFNULL(IF(LOCATE(k.Symbol, k.Nazwa) > 0, k.Nazwa, CONCAT(k.Symbol, ' ', k.Nazwa)), 'prywatny') AS Kontakt_Kontrah_Str 
				, kn.opis  
			FROM `t_search_KO` KO
			INNER JOIN `kontakty` kn ON kn.OsobaGUID = KO.OsobaGUID AND kn.KontrGUID = KO.KontrGUID AND kn.typ_medium IN (0,2) 
			LEFT JOIN `osoby` o ON o.GUID = KO.OsobaGUID
			LEFT JOIN `kontrah` k ON k.GUID = KO.KontrGUID
			WHERE
			TRUE
			AND Found_Phase = @Found_Phase -- IN ('1,2')
			GROUP BY kn.GUID
			;
		END IF;
	
	/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
		'SEARCH_TELEPHON_NUMBERS_LIKE'
			Przeszukuje kontakty po frazie _SearchText (telefon, mail, etc ale ównie nazwisko lub imiona
			Parametry
				_SearchText			Fraza szukana
				_Param_A			= '' to również grupy
									 '' tylko osoby
				_Param_B			
									= '' 	to tylko widoczne w HR
									!= ''	wszystkie osoby 
				_Param_C			
									= '' 	to nie serwisowcy
									!= ''	wszystkie osoby 
			CALL erp_do_search_similar('SEARCH_OSOBY_LIKE', 'jmam', '', '', 0, 0, '', '', '', '');				-- szukaj wystapienia 'jmam'
			CALL erp_search_similar('SEARCH_TELEPHON_NUMBERS_LIKE', 'jmam', '', '', '', '');				-- szukaj wystapienia 'jmam'
			CALL erp_search_similar('SEARCH_TELEPHON_NUMBERS_LIKE', 'jmam', '1', '', '', '');			-- szukaj wystapienia 'jmam' ale tylko osoby
	------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
		IF _MODE = 'Search.for.one' THEN
		--	1.	Osoby	
			INSERT IGNORE INTO `t_search_KO` 
				(GUID, LK_Srch, OsobaGUID, KontrGUID, Src, OrderCol, Found_Phase, Phase_1, Phase_2, Phase_3)
				SELECT
					kn.GUID,
					_VarStr(
						IFNULL(
							GROUP_CONCAT(DISTINCT 
								IF(@srch_Nazwisko OR @srch_NazwiskoImiona, 
									LTRIM(CONCAT(o.Nazwisko, ' ', o.Imiona)),
									IF(@srch_NazwiskoImie1, 
										LTRIM(CONCAT(o.Nazwisko, ' ', o.Imie1)),
										IF(@srch_Imie1 OR @srch_ImionaNazwisko, 
											LTRIM(CONCAT(o.Imiona, ' ', o.Nazwisko)),
											IF(@srch_Imie1Nazwisko, 
												LTRIM(CONCAT(o.Imie1, ' ', o.Nazwisko)),
												IF(@srch_IdnUser, -- !!! o.idnuser LIKE CONCAT('%', _SearchText, '%'),
													CONCAT(o.idnuser, IF(o.Rodzaj, ' NICK', ' GRUPA')),
													NULL
												)
											)
										) 
									)	
								) 
							SEPARATOR ', '
							),
							'*'
						)	
					) AS LK_Srch,
					kn.OsobaGUID, kn.KontrGUID,
					'osoba',
					IF(@srch_Nazwisko, 0, 1) AS OrderCol,
					_Phase,
					(_Phase = 1),
					(_Phase = 2),
					(_Phase = 3)
						
				FROM `kontakty` kn
				INNER JOIN `osoby` o ON o.GUID = kn.osobaGUID 
				WHERE
					IFNULL(kn.osobaGUID, '') != ''
					AND
					kn.typ_medium IN (0,2) 
					AND
					IF(_Param_A = '', 
						TRUE,
						o.rodzaj != 0
					) AND
					IF(_Param_B != '', 
						TRUE,
						o.niewidoczna_w_HR = 0
					) AND
					(
						(@srch_Nazwisko := IF((_SearchLen < 2), FALSE, o.Nazwisko LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_Imie1 := IF((_SearchLen < 1), FALSE, o.Imie1 LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_IdnUser := (o.idnuser LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_ImionaNazwisko := IF((_SearchLen < 4) OR _SearchIsMail, FALSE, CONCAT(o.Imiona, ' ', o.Nazwisko) LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_Imie1Nazwisko := IF((_SearchLen < 4) OR _SearchIsMail, FALSE, CONCAT(o.Imie1, ' ', o.Nazwisko) LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_NazwiskoImiona := IF((_SearchLen < 4) OR _SearchIsMail, FALSE, CONCAT(o.Nazwisko, ' ', o.Imiona) LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_NazwiskoImie1 := IF((_SearchLen < 4) OR _SearchIsMail, FALSE, CONCAT(o.Nazwisko, ' ', o.Imie1) LIKE CONCAT(_SearchText, '%')))
					)	
			GROUP BY kn.OsobaGUID, kn.KontrGUID
			LIMIT 40
			ON DUPLICATE KEY 
			UPDATE
				Found_Phase = CONCAT(Found_Phase, ',', _VarStr(_Phase)),
				Phase_1 = (_Phase = 1),
				Phase_2 = (_Phase = 2),
				Phase_3 = (_Phase = 3)
			;
			SET @t_search_KO.Osoby = ROW_COUNT();
			
		--	2.	Kontrahent	
			INSERT IGNORE INTO `t_search_KO` 
				(GUID, LK_Srch, OsobaGUID, KontrGUID, Src, OrderCol, Found_Phase, Phase_1, Phase_2, Phase_3)
				SELECT
					kn.GUID,
					_VarStr(
						IFNULL(
							GROUP_CONCAT(DISTINCT 
								IF(@srch_Nazwa, -- !!! o.Nazwisko LIKE CONCAT(_SearchText, '%'),
									LTRIM(CONCAT(k.Nazwa, ' ', k.Symbol)),
									IF(@srch_Symbol, -- !!! o.Nazwisko LIKE CONCAT(_SearchText, '%'),
										LTRIM(CONCAT(k.Symbol, ' ', k.Nazwa)),
										NULL
									) 
								)	
								 
							SEPARATOR ', '
							),
							'*'
						)	
					) AS LK_Srch,
					kn.OsobaGUID, kn.KontrGUID,
					'kontrah',
					IF(@srch_Nazwa, 0, 1) AS OrderCol,
					_Phase,
					(_Phase = 1),
					(_Phase = 2),
					(_Phase = 3)
						
				FROM `kontakty` kn
				INNER JOIN `kontrah` k ON k.GUID = kn.KontrGUID 
				WHERE
					IFNULL(kn.KontrGUID, '') != ''
					AND
					kn.typ_medium IN (0,2) 
					AND
					(
						(@srch_Nazwa := IF((_SearchLen < 2), FALSE, k.Nazwa LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_Symbol := IF((_SearchLen < 1), FALSE, k.Symbol LIKE CONCAT(_SearchText, '%')))
						OR
						(@srch_Nazwa := IF((_SearchLen < 5) OR _SearchIsMail, FALSE, k.Nazwa LIKE CONCAT('%', _SearchText, '%')))
						OR
						(@srch_Symbol := IF((_SearchLen < 5) OR _SearchIsMail, FALSE, k.Symbol LIKE CONCAT('%', _SearchText, '%')))
					)	
			GROUP BY kn.OsobaGUID, kn.KontrGUID
			LIMIT 40
			ON DUPLICATE KEY 
			UPDATE
				Found_Phase = CONCAT(Found_Phase, ',', _VarStr(_Phase)),
				Phase_1 = (_Phase = 1),
				Phase_2 = (_Phase = 2),
				Phase_3 = (_Phase = 3)
			;
			SET @t_search_KO.Kontrah = ROW_COUNT();
			
		--	3.	Inne kontakty czyli mailowe
			IF (@t_search_KO.Osoby + @t_search_KO.Kontrah = 0) OR _SearchIsMail THEN
				INSERT IGNORE INTO `t_search_KO` 
					(GUID, LK_Srch, OsobaGUID, KontrGUID, Src, OrderCol, Found_Phase, Phase_1, Phase_2, Phase_3)
					

					SELECT
						kn.GUID,
						_VarStr(
							kn_mail.Adres
						) AS LK_Srch,
						kn.OsobaGUID, kn.KontrGUID,
						-- kn.Adres,
						'mail',
						IF(@srch_Nazwa, 0, 1) AS OrderCol,
						_Phase,
						(_Phase = 1),
						(_Phase = 2),
						(_Phase = 3)
							
					FROM `kontakty` kn_mail
					INNER JOIN `kontakty` kn ON kn.typ_medium IN (0, 2) AND (kn_mail.OsobaGUID = kn.OsobaGUID)
					WHERE
						kn_mail.typ_medium = 3
						AND
						(
							kn_mail.Adres LIKE CONCAT('%', _SearchText, '%')
						)	
				GROUP BY kn.OsobaGUID, kn.KontrGUID
				LIMIT 40
				ON DUPLICATE KEY 
				UPDATE
					Found_Phase = CONCAT(Found_Phase, ',', _VarStr(_Phase)),
					Phase_1 = (_Phase = 1),
					Phase_2 = (_Phase = 2),
					Phase_3 = (_Phase = 3)
				;
			END IF;
		
			DELETE FROM `t_search_KO` WHERE (IFNULL(OsobaGUID, '') = '' AND IFNULL(KontrGUID, '') = '');
			SELECT COUNT(*) FROM `t_search_KO` INTO @t_search_KO.Count;
			
		END IF; -- _MODE = 'SEARCH_TELEPHON_NUMBERS_LIKE'
	
END$$

/*
$Log: erp_search_similar_.sql,v $
Revision 1.21  2025/03/25 13:56:22  apro
$SEND$
cofka?

*/


DELIMITER ;

/*
====================================================================================================================================================================================
	NOTATNIK
====================================================================================================================================================================================
	

CALL erp_search_similar('SEARCH_OSOBY_LIKE', 'rud', '', '', '', '');				
CALL erp_search_similar('SEARCH_KONTRAH_LIKE', '341 15', '', '', '', '');				


CALL erp_search_similar('SEARCH_HR_FILTER_KONTRAH_DATASET', '', '', '', '', '');				-- 
CALL erp_search_similar('SEARCH_HR_FILTER_KONTRAH_DATASET', '', 'CHECKTIME', '', '', '');				-- 

CALL erp_search_similar('SEARCH_OSOBY_LIKE', 'to', '', '', '', '');				-- szukaj wystapienia 'jmam'
CALL erp_search_similar('SEARCH_OSOBY_LIKE', 'programi', '1', '', '', '');			-- szukaj wystapienia 'jmam' ale tylko osoby
CALL erp_search_similar('SEARCH_OSOBY_LIKE', 'Jarz', '', '', '', '');
CALL erp_search_similar('SEARCH_OSOBY_LIKE', 'ASTE', '', '', '', '');

CALL erp_search_similar('SEARCH_KONTRAH_LIKE', 'piek', '', '', '', '');
CALL erp_search_similar('SEARCH_KONTRAH_LIKE', 'KON', '', '', '', '');
CALL erp_search_similar('SEARCH_KONTRAH_LIKE', '60268', '', '', '', '');
CALL erp_search_similar('SEARCH_KONTRAH_LIKE', 'Janusz', '', '', '', '');

select CONCAT('"',o.Imie1,'"')AS Imie1, IF((6 < 1), FALSE, o.Imie1 LIKE CONCAT('Tomasz', '%')),niewidoczna_w_HR,o.rodzaj from osoby o 
where GUID = '{BFA09422-3393-11D7-B676-00304F0902E2}';
SET 			@srch_IdnUser := FALSE;

			SELECT
			-- @_SearchText, 
			-- @_SearchText + @srch_IdnUser + @srch_Imie1 + @srch_Nazwisko + @srch_ImionaNazwisko + @srch_NazwiskoImiona AS Wynik,
			-- @srch_IdnUser, @srch_Imie1, @srch_Nazwisko, @srch_ImionaNazwisko, @srch_NazwiskoImiona,
			IF(@srch_IdnUser, 
				'IdnUser',
				IF(@srch_Imie1,
					'Imie',
					IF(@srch_Nazwisko,
						'Nazwisko',
						'?'
					)
				)	
			)
			AS Co,
				_VarStr(
					IF(o.Nazwisko LIKE CONCAT(@_SearchText, '%'),
						LTRIM(CONCAT(	o.Nazwisko, ' ', o.Imiona)),
						IF(o.idnuser LIKE CONCAT(@_SearchText, '%'),
							LTRIM(CONCAT(	o.idnuser, ' - ', o.Imiona, ' ', o.Nazwisko)),
							LTRIM(CONCAT(	o.Imiona, ' ', o.Nazwisko))
						)	
					)
				) AS ImionaNazwisko,
				_VarStr(
					IFNULL(
						GROUP_CONCAT(DISTINCT 
							IF(o.NrPesel LIKE CONCAT('%', @_SearchText, '%'),
								CONCAT('PESEL: ', o.NrPesel),
								IF(o.NrNIP LIKE CONCAT('%', @_SearchText, '%'),
									CONCAT('NIP: ', o.NrNIP),
									IF(o.NrSeriaDowoduOsobistego LIKE CONCAT('%', @_SearchText, '%'),
										CONCAT('Nr dok.osob.: ', o.NrSeriaDowoduOsobistego),
										IF(o.idnuser LIKE CONCAT('%', @_SearchText, '%'),
											CONCAT(IF(o.Rodzaj, 'NICK: "', 'GRUPA: "'), o.idnuser, '"'),
											NULL
										)	
									)	
								) 
							)	
						SEPARATOR ', '
						),
						'*'
					)	
				) AS AdrSearch,
				o.GUID
					
			FROM `osoby` o
			WHERE
				-- IFNULL(o.GUID, '') != ''
				-- AND
				IF(@_Param_A = '', 
					TRUE,
					o.rodzaj != 0
				) AND
				IF(@_Param_B != '', 
					TRUE,
					IFNULL(o.niewidoczna_w_HR, 0) = 0
				) AND
				(
					(@srch_IdnUser := (o.idnuser LIKE CONCAT(@_SearchText, '%')))
					OR
					(@srch_Imie1 := IF((@_SearchLen < 1), FALSE, o.Imie1 LIKE CONCAT(@_SearchText, '%')))
					-- OR
					-- IF((@_SearchLen < 5), FALSE, o.Imie2 LIKE CONCAT(@_SearchText, '%'))
					OR
					(@srch_Nazwisko := IF((@_SearchLen < 2), FALSE, o.Nazwisko LIKE CONCAT(@_SearchText, '%')))
					-- o.Nazwisko LIKE CONCAT(@_SearchText, '%')
					OR
					-- CONCAT(o.Imiona, ' ', o.Nazwisko) LIKE CONCAT(@_SearchText, '%')	
					(@srch_ImionaNazwisko := IF((@_SearchLen < 4) OR @_SearchIsMail, FALSE, CONCAT(o.Imiona, ' ', o.Nazwisko) LIKE CONCAT(@_SearchText, '%')))
					OR
					(@srch_NazwiskoImiona := IF((@_SearchLen < 4) OR @_SearchIsMail, FALSE, CONCAT(o.Nazwisko, ' ', o.Imiona) LIKE CONCAT(@_SearchText, '%')))
					-- CONCAT(o.Nazwisko, ' ', o.Imiona) LIKE CONCAT(@_SearchText, '%')
					OR
					(@srch_NrPesel := IF((@_SearchLen < 5) OR @_SearchIsMail, FALSE, o.NrPesel LIKE CONCAT(@_SearchText, '%')))
					-- o.NrPesel LIKE CONCAT(@_SearchText, '%')
					OR
					(@srch_NrNIP := IF((@_SearchLen < 5) OR @_SearchIsMail, FALSE, o.NrNIP LIKE CONCAT(@_SearchText, '%')))
					-- o.NrNIP LIKE CONCAT(@_SearchText, '%')
					OR
					(@srch_NrSeriaDowoduOsobistego := IF((@_SearchLen < 5) OR @_SearchIsMail, FALSE, o.NrSeriaDowoduOsobistego LIKE CONCAT(@_SearchText, '%')))
					-- o.NrSeriaDowoduOsobistego LIKE CONCAT(@_SearchText, '%')
				)	
		GROUP BY o.GUID
		ORDER by ImionaNazwisko
		;
select Count(*) from snprod.osoby;
select Count(*) from osoby;



SELECT p.Symbol, p.Symbol_fmt, p.poziom, p.* FROM plankont p WHERE rok = 2012 
ORDER BY symbol_fmt
LIMIT 1000
;
SELECT @IsDigit;
-- 125 ms
CALL erp_search_similar('SEARCH_FK_LIKE', 'Fundusz', '2012', '', '', '');				-- szukaj wystapienia 'aparaty' w roku 2012
CALL erp_search_similar('SEARCH_FK_LIKE', '204', '2012', '', '', '');				-- szukaj wystapienia 'aparaty' w roku 2012

SELECT _CutStr('462-07 Fundusze tworzone centralnie-PFRON', 15, '...');

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
*/
