CREATE OR REPLACE FUNCTION food600.t_sk_sez_on()
    RETURNS trigger
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE NOT LEAKPROOF
AS $BODY$
declare 
 lc_kas      INTEGER;
 lc_stredisk INTEGER;
 lodecteno   smallint;
 luz_kas     character(19);
 lc_uzaverka INTEGER;
 luzaverka   character(17); 
 lnav        INTEGER;
 lprevedene  INTEGER;
 
begin

select fd.c_stredisk into lc_kas      from food600.food_dat fd WHERE fd.id = new.id_kas;
if lc_kas is null then
	lc_kas=0;
end if;
select fd.c_stredisk into lc_stredisk from food600.food_dat fd WHERE fd.id = new.id_man;
if lc_stredisk is null then
	lc_stredisk=0;
end if;

if new.odecteno = '' THEN
 lodecteno  = 0;
else
 lodecteno  = 1;           
end if;  

luz_kas = '%^&$#@';
luzaverka = food600.uzav_old2new(new.uzaverka); /* !!! */
      luzaverka = new.uzaverka;

IF (new.uzaverka || new.id_kas) <> luz_kas THEN
  luz_kas := new.uzaverka || new.id_kas;
END IF; 

select idriadok INTO lc_uzaverka from food600.sk__uza where uzaverka = luzaverka and c_data = new.c_data and id_kas=new.id_kas;
IF lc_uzaverka IS NULL THEN
 lprevedene = 0;
 insert into food600.sk__uza (uzaverka,c_data, id_kas) values (luzaverka,new.c_data, new.id_kas);
 select idriadok INTO lc_uzaverka from food600.sk__uza where uzaverka = luzaverka and c_data = new.c_data AND id_kas=new.id_kas;
ELSE
 lprevedene = 1;
END IF;

INSERT INTO food600.sk__sez 
       ( c_kas,     id_kas,  c_stredisk,     id_man,     uzaverka,  c_uzaverka,     autor,  odecteno,     uz_cislo         ,     uct_den,     c_mena,     priznak, lastuzav)
values (lc_kas, new.id_kas, lc_stredisk, new.id_man, new.uzaverka, lc_uzaverka, new.autor, lodecteno, new.uz_cislo, new.uct_den, new.c_mena, new.priznak, new.lastuzav);

IF lprevedene = 0 THEN
 select food600.sk__on(luzaverka,lc_uzaverka,new.c_data) INTO lnav;
end if;

RETURN NEW;

end
$BODY$;
