#!/usr/bin/perl 
# #!/usr/bin/perl -wC62

use strict;
use warnings;

use CGI;
use FCGI;
#use CGI::Carp qw(fatalsToBrowser); #comment in production
use File::Basename qw(dirname);
use Cwd  qw(abs_path);
use lib dirname(dirname abs_path $0) . '/html';
use ModuleBase;
use INNL;
use LocalTemplate;
use Page;
use Session;
use Generiek;
use Design;
use Db;
use Crea;
use Xml;
use Encode;
use MIME::Lite;
use Data::Dumper;
use Text::CSV_XS;
use File::Basename;
use MIME::Base64;
use LWP::UserAgent;
use HTTP::Request::Common;
#use HTML::Tidy;
use CGI::Carp qw(fatalsToBrowser);
use Storable 'dclone';
#use utf8::all;
#use open ":std", ":encoding(UTF-8)";

#use WWW::Google::Translate;


my $request = FCGI::Request();

my $tracefunc	= 0;
my $tracesaving  = 0;
my $tracesession = 0;
my $tracecsi	 = 0;

my $normalshow   = 1;
my $genericshow  = 2;
my $databaseshow = 3;
my $mainversion = '1.6'; #dont forget to change the version in /var/www/html/modules/LocalTemplate.pm
my $currenttemplate = 'templates' . $mainversion;
my $version = 'Version RS1.5.5.6';

#-marker main
main();

sub main {
	my $innl = new INNL();
	$innl->autocommit();
	my $hashmain = {};
	my $_ihs = {};
	my $cgi;
	my $data = '';
	my $tidy;# = HTML::Tidy->new({
#		indent => 'yes',
#		wrap => 0,
#		'char-encoding' => 'utf8',
#		'output-html' => 'yes',
#		'show-warnings' => 'yes',
#		'show-errors' => 20,
#		doctype => 'auto',
#		clean => 'yes',
#		'drop-empty-elements' => 'no',
#		'drop-proprietary-attributes' => 'no',
#	});
	#my $_template = $currenttemplate . '/paginainnl.template.html';
	#print STDERR "Line " . __LINE__ . " " . $_template . "\n" ;
	#my $page = Page->new($innl, {}, '', '', $_template );
	#mmy $page = Page->new($innl, {}, '', '', 'templates/paginainnl.template.html' );my $page = Page->new($innl, {}, '', '', 'templates/paginainnl.template.html' );y $page = Page->new($innl, {}, '', '', 'templates/paginainnl.template.html' );
 	print STDERR "[Ix" . __LINE__ . "] Read solution template paginainnl.template.html \n"  ;
	my $page = Page->new($innl, {}, '', '', ( $currenttemplate . '/paginainnl.template.html' ) );
	
	$$_ihs{_currenttemplate} = $currenttemplate;
	$$_ihs{_genericpath} = '/var/www/html/' . $$_ihs{_currenttemplate} . '/';
	$$_ihs{_mainversion_} = $mainversion;
	while($request->Accept() >= 0){
		eval {		
			#lets's catch all exception's and act accordingly (strange or system errors
			#should really die so fcgi is restarted, other errors should not cause the
			#fcgi deamon to be restarted
			$cgi = new CGI();
			print $cgi->header(-charset => 'utf-8');
			my $dbh = $innl->dbh();
			$dbh->{mysql_enable_utf8} = 1;
			my $browseragent = $cgi->user_agent();
			my $cnt=0;
			my $files = {} ;
			my $filecounter = 0;
			
			$$_ihs{_cgi} = $cgi;
			$$_ihs{_loggedin_startpage} = '_index'; #just in case something goes wrong. this is the default we fall back to.
			$$_ihs{_datasetautorisation}	   = ''; #autorisation cannot be set from outside...
			$$_ihs{__version__} = $version;
			$$_ihs{__database__} = $ModuleBase::DatabaseName;
			#################################################
			$$_ihs{__systemtrace__} = 1; #set $_ihs{__systemtrace__} global (generic)
			$$_ihs{__syssqltrace__} = 1; #set $_ihs{__syssqltrace__} global (sql)
			$$_ihs{__syssubtrace__} = 1; #set $_ihs{__syssubtrace__} global (functions)
			$$_ihs{__sysreftrace__} = 1; #set $_ihs{__sysreftrace__} global (references)
			$$_ihs{__syssestrace__} = 1; #set $_ihs{__syssestrace__} global (sessons)
			$$_ihs{__sqlcontenttrace__} = 1; #set $_ihs{__syssqltrace__} global (sql)
			#################################################

			#listKeys(  $hashmain, $_ihs, 'all', ('start dumper ---' . __LINE__ . '--- start dumper' ), ( "Solutionnextindex" . __LINE__ ) ); 
			$hashmain = test_params($cgi);
			print STDERR Dumper $hashmain;
			$$hashmain{__assets__} = "assets" . $mainversion;
			$$hashmain{__domain__} = $ModuleBase::Domain;

			#print STDERR Dumper $hashmain;
			if ( defined $$hashmain{_session} && ( not defined $$hashmain{session} )){ #temporarily in transition. External _session, internal session.
				$$hashmain{session} = $$hashmain{_session};
			}
			$$_ihs{_actualrequestedaction} = $$hashmain{_action};
			my $sql;
			my $response = {};
			if ( defined $$hashmain{_response} ){
				$sql  = "SELECT * FROM sys_response ";
				$sql .= "WHERE re_key = ? ";  
				$response = ParamPrepAndFetch( $hashmain, $_ihs, $innl, $sql, $$hashmain{_response}, ('Ix' . __LINE__ ) );
				if ( $$response{re_key} ){
					$$hashmain{_action} = $$response{re_action};
					$$hashmain{_language} = $$response{re_language};
					$$hashmain{_appslogin} = '1';
				}
			}
			#listKeys(  $hashmain, $_ihs, 'all', ('after response---' . __LINE__ . '--- after response' ), ( "Ix" . __LINE__ ) ); 
			my @_orgfields = ();
			my @internals = qw( _sortfld _session _maxwidth _maxheigth _prevcsi );
			foreach ( keys %{ $hashmain } ){
				my $orgfield = 1;
				foreach my $i ( @internals ){
					if ( $i eq $_ ){
						$orgfield = 0;
						last;
					} 
				} 
				if ( $_ eq '_sortorder' ){}
				elsif ( /^_/ ){
					$orgfield = 0;
				}
				push @_orgfields, $_ if $orgfield;
			}

			#set sql to handle large queries
			my $dummy = { _tabelnaam => '', _companycode => 'dummy' }; #to prevent warnings
			$sql = "SET SQL_BIG_SELECTS=1";
			PrepAndExecuteQuery( $dummy, $_ihs, $innl, $sql, ('Ix' . __LINE__ ) );

			#define the internal keys
			my @ihsSettoZero = qw( _allSessionsInMemory _allReferencesInMemory _copyrecord _csiFound _errorcount _hiddenstdactionsdefined _javauniqinit _multilanguagetable
				_navbarset _primarydatasets _profiel_id _refCnt _sortFldExists _tab_nr _tabbedforms _tbprevid _throwingerror _topgoodMessageSet _warn_errorcount _validuser 
				_countLogDefinitions _prevcsiFound _prevVolgNr _java_multiselect _javalink_jquery_ui _lastsavedidentity _finaltemplatemethod
			);
			foreach ( @ihsSettoZero ){
				$$_ihs{$_} = 0;
			}
			my @ihsSettoEmpty = qw( 
				_actualaction _actualsqlaction _back _languagefield _previousaction _tab_grp _References _tableattribute _tbprev _parentcsi _parentaction 
				_designcommit _hashorg _errormessagecode _tbAuth _goodmessage _finaltemplate );
			foreach ( @ihsSettoEmpty ){
				$$_ihs{$_} = '' if not exists $$_ihs{$_};
			}
			traceme( $hashmain, $_ihs, "_tbprev: $$_ihs{_tbprev}", __LINE__ ) if ( $$_ihs{__systemtrace__} );
			#traceme( $hashmain, $_ihs, "_goto_overview_page exists", __LINE__ ) if (defined $$hashmain{_goto_overview_page});

			if ( $$hashmain{_action} eq 'insert' ){
				$$_ihs{_actualsqlaction} = 'I';
			}
			elsif ( $$hashmain{_action} eq 'update' ){
				$$_ihs{_actualsqlaction} = 'U';
			}
			elsif ( $$hashmain{_action} eq 'delete' ){
				$$_ihs{_actualsqlaction} = 'D';
			}
			$$_ihs{_captcharequired}	= 1;
			$$_ihs{_browseragent}	   = $browseragent;
			$$_ihs{_cLevNr}			 = 1;  #new to confirm: the current level (if _stay)
			$$_ihs{_cPrimary}		   = 0;  #new to confirm: this is the primary item in the tabstyle
			$$_ihs{_cStart}			 = 0;  #new to confirm: this is the start item in the tabstyle
			$$_ihs{_prevcsiIntSeqNr}	= -1;

			$$_ihs{_curIntSeqNr}		= -1; #the current entry in the sessionsequence array, always 1 less then _curVolgNr
			$$_ihs{_curVolgNr}		  =  0; #the current volgnr in the sessionsequence array
			$$_ihs{_lastSeqNr}		  = -1; #points to the last IntSeqNr in the sessionsequence array

			$$_ihs{_databasename}	   = $ModuleBase::DatabaseName;
			$$_ihs{_orgfields}		  = \@_orgfields;
			$$_ihs{_orgsearchwordstat}  = 0; # 1 = not exists, 2 = empty, 3 = with keyword
			$$_ihs{_sortorder}		  = exists $$hashmain{_sortorder} ? $$hashmain{_sortorder} : ''; #input from user
			$$_ihs{_twocolumnsystem}	= 1;
			if ( defined $$hashmain{_sortfld} ){
				traceme( $hashmain, $_ihs, "Sortfield $$hashmain{_sortfld}", __LINE__ ) if ( $$_ihs{__systemtrace__} );
				$$_ihs{_sortFldExists}  = 1;
			}
			my @hashmainSettoEmpty = qw( _action _copyid _companycode _error _errorplaceholder _extrahiddncntnt _fieldformatloggedin 
				_menu_loggedin _menu_logoff _menu_notloggedin _menu_contact _menu_register
				_javascript_head_all _javascriptbottomfunctions _javabottomfunctions _nextaction _nxtaction _nextparam _page _reffilter _sortorder _sortfld _selectkey _selectedsort 
				_taken _tbnaam _toperrormessage _internalsqlerror  _lastsavedidentity _recordissaved
			);
			foreach ( @hashmainSettoEmpty ){
				$$hashmain{$_} = '' if not exists $$hashmain{$_};
			}
			#set a number of keys to prevent warnings.
			$$hashmain{_adjustedheigth}  = 700  if not exists $$hashmain{_adjustedheigth};
			$$hashmain{_buttonclass}	 = 'c_btn';
			$$hashmain{_captcha_check}   = 'Ja';
			$$hashmain{_csi}			 = Functions::GenPass(24); #current session identifier
			$$hashmain{_cssforfields}	= 'form_template';
			$$hashmain{_errorcount}	  = 0;
			$$hashmain{_formsilverborder}= 'c_reg';
			$$hashmain{_fstart}		  = 0  if not exists $$hashmain{_fstart};
			$$hashmain{_ftli}			= 0  if not exists $$hashmain{_ftli}; #first time login
			$$hashmain{_ignorewarning}   = 0  if not exists $$hashmain{_ignorewarning};
			$$hashmain{_mit}			 = 0  if not exists $$hashmain{_mit};
			$$hashmain{_modifyts}		= time();
			$$hashmain{_offset}		  = 'empty' if not exists $$hashmain{_offset};
			$$hashmain{_recordiscopied}  = 0;
			$$hashmain{_remoteipaddress} = $ENV{REMOTE_ADDR};
			#$$hashmain{_script}		  = 'index.pl';
			$$hashmain{_script}		  = '/';
			$$hashmain{_warningcount}	= 0  if not exists $$hashmain{_warningcount};
			$$hashmain{_tab}			 = 0  if not exists $$hashmain{_tab};
			$$hashmain{_sortorderflipped}= $$hashmain{_sortorder} ne '' && $$_ihs{_sortFldExists} ? 1 : 0; #user selected different sortorder
			$$hashmain{_servicename}	 = getSysMessage( $hashmain, $innl, 'customerservice');
			$$hashmain{_customerservice} = "<a href=\"mailto:customerservice\@raplico.com\" >%%_servicename%%</a>" ;
			$$hashmain{_javascriptreadystart} = '';
			$$hashmain{_servicename}	 = '' if ( ! defined $$hashmain{_servicename} );

			traceme( $hashmain, $_ihs, "_offset $$hashmain{_offset} init", __LINE__ ) if ( $$_ihs{__systemtrace__} > 1 );
			traceme( $hashmain, $_ihs, "_csi: $$hashmain{_csi}, _prevcsi: $$hashmain{_prevcsi} init", __LINE__ ) if $tracecsi;
			traceme( $hashmain, $_ihs, "_browsersize $$hashmain{_maxheigth}", __LINE__ ) if ( $$_ihs{__systemtrace__} > 2 );
			traceme( $hashmain, $_ihs, "Host $ModuleBase::Host, Version: $version", __LINE__ ) ;
			setYearMonth($hashmain, $_ihs, $innl);
			if ( exists $$hashmain{_searchkeyword} ){ #default is not exists
				if ( $$hashmain{_searchkeyword} ne '' ){ 
					$$_ihs{_orgsearchwordstat} = 3; #search word exists
				}
				else{
					$$_ihs{_orgsearchwordstat} = 2; #search term exists but is emtied. 
				}
			}
			else{
				$$hashmain{_searchkeyword} = '';
				$$_ihs{_orgsearchwordstat} = 1;
			}

			#end of definitions
			#so, if we do a inter system login.... lets check
			#this only we the configuration has multiple servers
			if ( $$hashmain{qUezZ90av1Ol355wNpeE76xVCa234h} ){ #we need to regenerate this key every hour. future work todo
				traceme( $hashmain, $_ihs, "inter system login", __LINE__ ) if ( $$_ihs{__systemtrace__} );
				$sql  = "SELECT * FROM custmdbm.sys_interlogin ";
				$sql .= "WHERE session = ? ";
				$sql .= "AND date_inserted > DATE_SUB(NOW(),INTERVAL 1 MINUTE ) ";
				traceme( $hashmain, $_ihs, $sql, __LINE__ ) if $$_ihs{__syssqltrace__} || $tracesession ;
				my $params = ParamPrepAndFetch( $hashmain, $_ihs, $innl, $sql, $$hashmain{qUezZ90av1Ol355wNpeE76xVCa234h}, ('Ix' . __LINE__ ) );
				if ( $$params{id} ){
					$$_ihs{_companycode} = $$hashmain{_companycode} = $$params{companycode};
					$$hashmain{_gb_id} = $$params{gb_id};
					$$hashmain{_password} = $$params{password};
				}	
			}
			getActiveLanguages( $hashmain, $_ihs, $innl, '' ); #this is still in custmdbm, so not customer dependent!
			my $sth;
			if ( ! $$hashmain{_language} && $$hashmain{session} ){ #language not give but session is
				$sql = "SELECT _language FROM  sys_session WHERE  session = \"" . $$hashmain{session} . "\" ";
				traceme( $hashmain, $_ihs, $sql, __LINE__ ) if $$_ihs{__syssqltrace__} || $tracesession ;
				$$hashmain{_language} = $dbh->selectrow_array( $sql );
				traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} > 2 );
			}
			$$hashmain{_language} = 'en' if ( ! $$hashmain{_language} );
			if ( exists $$hashmain{_tgrndds} ){ #this holds the id for the tablename
				$$hashmain{_tbnaam} = '';
				if ( $$hashmain{_tgrndds} ne '' ){
					traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
					$$hashmain{_tbnaam} = provideTablenameFromId( $hashmain, $_ihs, $innl, $$hashmain{_tgrndds}, __LINE__ );
				}
			}
			else{
				traceme( $hashmain, $_ihs, "action: $$hashmain{_action} NO _tgrndds", __LINE__ ) if ( $$_ihs{__systemtrace__} > 2 );
			}

			#get the layout sizes from the bootstrap frame
			$sql  = "SELECT * FROM custmdbm.sys_bootstrapsize ";
			$sql .= "WHERE _dbcp = '" . $ModuleBase::DatabaseName . "' "; #we need to fix this. we are mixing companycd and databasename.
			traceme( $hashmain, $_ihs, $sql, __LINE__ ) if $$_ihs{__syssqltrace__};
			my $bsvalues = PrepAndFetchQuery( $hashmain, $_ihs, $innl, $sql, ('Ix' . __LINE__ ) );
			if ( $$bsvalues{_dbcp} ){ #succes
				$hashmain = { %$hashmain, %$bsvalues };
			}
			if ( $$hashmain{_nextparam} ne '' ){
				$$_ihs{_tbprev} = $$hashmain{_tbnaam};
				$$_ihs{_tbprevid} = $$hashmain{_tgrndds};
				traceme( $hashmain, $_ihs, "_tbprev $$_ihs{_tbprev}", __LINE__ ) if ( $$_ihs{__systemtrace__} );
			}
			my $session = new Session($hashmain, $innl);		
			$hashmain = {%$hashmain, %{$session->export()} };
			$$_ihs{_session} = $$hashmain{session}; #need to finish the move from session to _session
			$$hashmain{_session} = $$hashmain{session}; 
			$sql = "SELECT DATE_FORMAT(now(), '%W %D %M %Y');";
			$$hashmain{_today} = $dbh->selectrow_array( $sql );
			$$hashmain{_today} = translate( $$hashmain{_today}, 'en', $$hashmain{_language} ); #TODO make translate fit for mor languages
			if ( $$hashmain{_error} ){
				traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
			}
			elsif ( $$hashmain{_error} ne '' ){
				traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
			}
			else{
				traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__} > 2;
				$hashmain = gebruikerTest( $hashmain, $_ihs, $innl ); #valid user, password and aktief?
				traceme( $hashmain, $_ihs, "_loginerrorreason = " . $$_ihs{_loginerrorreason} . 'valid: ' . $$_ihs{_validuser} , __LINE__ ) if ( $$_ihs{__systemtrace__} );
				if ( $$hashmain{_action} eq 'chklogin'  && $$_ihs{_validuser} == 1 ){
					traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__} > 2;
					$$hashmain{_language} = $$_ihs{_defaultlanguage};
				}
				elsif ( $$_ihs{_validuser} == 0 ){
					traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__} > 2;
					$sql = "UPDATE sys_session ";
					$sql .= "SET _companycode = '', ";
					$sql .= " _gb_id = '' ";
					$sql .= "WHERE session = ? ";
					ParamPrepAndExecute( $hashmain, $_ihs, $innl, $sql, $$hashmain{_session}, ('Ix' . __LINE__ ) );
				}
				#$sql = "SELECT * FROM sys_session ";
				#B
				#$sql .= "WHERE session = ?";
				#my $ses = ParamPrepAndFetch( $hashmain, $_ihs, $innl, $sql, $$hashmain{_session}, ('Ix' . __LINE__ ) );

			}
			#see if database exists 
			$sql = "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '" . $$_ihs{_databasename} . "' ";
			traceme( $hashmain, $_ihs, $sql, __LINE__ ) if $$_ihs{__syssqltrace__};
			my $checkdbname = $dbh->selectrow_array( $sql );
			
			if( $$hashmain{_action} eq 'switchlang' && $$hashmain{_gb_id} eq '' ){
				readAllSessionSequence( $hashmain, $_ihs, $innl );
				my $sessiondata = readLastSession ( $hashmain, $_ihs, $innl, '' );
				if ( $$sessiondata{_action} ne '' ){
					$$hashmain{_action} = $$sessiondata{_action};
					$$hashmain{_page} = $$sessiondata{_page};
				}
			}
			#traceme( $hashmain, $_ihs, "Language set. Country = $$hashmain{_languagename}", __LINE__ ) if ( $langset );#if $$_ihs{__systemtrace__} > 2;
			my $langset = 0;
			my @_langs = @{$$_ihs{_languages}};
			foreach my $lang ( @_langs ){
				if ( $$hashmain{_language} eq $$lang{_language} ){
					$$hashmain{_languagename} = $$lang{_languagename};
					$$hashmain{_countryflag} = $$lang{_countryflag};
					$$hashmain{_currentflag} = showPage($innl, 'language', $hashmain );
					$langset = 1;
					last;
				}
			}
			traceme( $hashmain, $_ihs, "Language set. Country = $$hashmain{_languagename}", __LINE__ ) if ( $langset );#if $$_ihs{__systemtrace__} > 2;
			if ( $langset == 0 ){
				$$hashmain{_language} = 'en';
				$$hashmain{_languagename} = 'English';
				$$hashmain{_countryflag} = "gb";
				$$hashmain{_currentflag} = showPage( $innl, 'language', $hashmain );
				traceme( $hashmain, $_ihs, "Language not set. Country = default", __LINE__ ) ;#if $$_ihs{__systemtrace__} > 2;
			}
			if ( $$hashmain{_fstart} == 1 && $$_ihs{_validuser} == 0 ){ #not logged in 
				initToFirstSession( $hashmain, $_ihs, $innl );
			}
			getPageDefaults( $hashmain, $_ihs, $innl, $ModuleBase::DatabaseName );
			$$hashmain{_browsersize}	 = $$hashmain{_maxheigth} - 70;
			$$hashmain{_logopicture} = getLogo ( $hashmain, $_ihs, $innl ); #and orgcss is set
			traceme( $hashmain, $_ihs, "Validuser: $$_ihs{_validuser} Last one for block", __LINE__ ) if $$_ihs{__systemtrace__} > 2;
			#
			# documentation around _loginstate
			# 0 - no action or message to display
			# 1 - username / password combination is not recognized
			# 2 - Access restrictions 
			# 3 - This user is marked as not active
			# 4 - response to reset request
			# 5 - subscription completed successfully
			# 6 - subscription not ok
			# 7 - subscription already completed
			# 8 - new member succesfull password added
			# 9 - password reset ok
			#10 - reset or new member not ok, to late?.
			#11 - reset not ok. not active user
			BLOCK: {
				traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__} >= 1;
				if ( $$_ihs{_validuser} != 1 ){
					if( $$hashmain{_appslogin} eq '1' || $$hashmain{_action} eq '' ){
						$$_ihs{_companycode} = $$hashmain{_companycode} = '' if ( $$hashmain{_companycode} eq 'custmdbm' );
						if ( $$hashmain{_action} eq 'forgotpasswd'){
							$$hashmain{_loginstate} = '0';
							traceme( $hashmain, $_ihs, "forgot password", __LINE__ ) if $$_ihs{__systemtrace__} >= 1;
 							print STDERR "[Ix" . __LINE__ . "] Read solution template forgot.template.html \n"  ;
							$page = Page->new($innl, {}, '', '', ( $currenttemplate . '/forgot.template.html' ) );
						}
						elsif ( $$hashmain{_action} eq 'rqpw'){#request password reset
							$$hashmain{rcv_companycode} = $$hashmain{_fg_cc};
							$$hashmain{rcv_gb_id} = $$hashmain{_gb_id};
							sendPasswordResetLink( $hashmain, $_ihs, $innl, $$hashmain{_action} );
							$$hashmain{_loginstate} = '4';
							traceme( $hashmain, $_ihs, "reset password", __LINE__ ) if $$_ihs{__systemtrace__} >= 1;
 							print STDERR "[Ix" . __LINE__ . "] Read solution template basic.template.html \n"  ;
							$page = Page->new($innl, {}, '', '', ( $currenttemplate . '/basic.template.html' ) );
						}
						elsif ( $$hashmain{_action} eq '_extrspw' || $$hashmain{_action} eq '_extpwnem' ){#execute password reset
							traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__} >= 1;
							resetPasswordrequest( $hashmain, $_ihs, $innl, $response );
							if ( $$hashmain{_action} eq '_extrspw' ){
								$$hashmain{_passwdtitles} = showLocalPage($hashmain, $innl, 'request_password.reset' );
							}
							else{
								traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__} >= 1;
								$$hashmain{_passwdtitles} = showLocalPage($hashmain, $innl, 'request_password.new' );
							}
 							print STDERR "[Ix" . __LINE__ . "] Read solution template request.template.html \n"  ;
							$page = Page->new($innl, {}, '', '', ( $currenttemplate . '/request_password.template.html' ) );
						}
						elsif ( $$hashmain{_action} eq 'chklogin' && $$_ihs{_loginerror} ){
							if ( $$_ihs{_loginerrorreason} == 5 ){ 
								$$hashmain{_loginstate} = 2; #ip restriction
							}
							elsif ( $$_ihs{_loginerrorreason} == 7 ){ 
								$$hashmain{_loginstate} = 3; #not active
							}
							else{
								$$hashmain{_loginstate} = 1;
							}
							traceme( $hashmain, $_ihs, "chklogin but failed. show login page", __LINE__ ) if $$_ihs{__systemtrace__} >= 1;
 							print STDERR "[Ix" . __LINE__ . "] Read solution template basic.template.html \n"  ;
							$page = Page->new($innl, $hashmain, '', '', ( $currenttemplate . '/basic.template.html' ) );
						}
						elsif($$hashmain{_action} eq 'resetpw' ){
							traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__} >= 1;
							$sql  = "SELECT * FROM sys_response ";
							$sql .= "WHERE re_key = ? ";  
							my $response = ParamPrepAndFetch( $hashmain, $_ihs, $innl, $sql, $$hashmain{_rspn}, ('Ix' . __LINE__ ) );
							if ( $$response{re_action} eq '_extrspw' || $$response{re_action} eq '_extpwnem' ){
								traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__} >= 1;
								$$hashmain{rs_pw}  = $$hashmain{rg_pw};
								$$hashmain{rs_pw2} = $$hashmain{rg_pw2};
							}
							if ( $$response{re_key} ){
								traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__} >= 1;
								if( !resetPassword( $hashmain, $_ihs, $innl, $response ) ){
									traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__} >= 1;
									if ( $$response{re_action} eq '_extpwnem' ){
										traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__} >= 1;
										$$hashmain{_loginstate} = 8;
										$$hashmain{_javaloginstate} = showPage($innl, 'javascript.pw.new.ok', $hashmain );
										#$$hashmain{_indexbody} = showDbPage($hashmain, $innl, '_subdone' );
									}
									elsif ( $$response{re_action} eq '_extrspw' ){
										traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__} >= 1;
										$$hashmain{_loginstate} = 9;
										$$hashmain{_javaloginstate} = showPage($innl, 'javascript.pw.reset.ok', $hashmain );
										#$$hashmain{_indexbody} = showDbPage($hashmain, $innl, '_rstdone' );
									}
								}
								else{#no success
									traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__} >= 1;
									if ( $$_ihs{_loginerrorreason} == 1 ){ #record not exists. probably to late with reset action
										traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__} >= 1;
										$$hashmain{_javaloginstate} = showPage($innl, 'javascript.pw.not.ok', $hashmain );
										$$hashmain{_loginstate} = 10;
									}
									elsif ( $$_ihs{_loginerrorreason} == 2 ){ # not active
										traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__} >= 1;
										$$hashmain{_javaloginstate} = showPage($innl, 'javascript.pw.not.active', $hashmain );
										$$hashmain{_loginstate} = 11;
									}
									traceme( $hashmain, $_ihs, "No succes", __LINE__ ) if ( $$_ihs{__systemtrace__} );
									$$hashmain{_response} = $$hashmain{_rspn};
									resetPasswordrequest( $hashmain, $_ihs, $innl, $response );
									if ( $$hashmain{_action} eq '_extrspw' ){
										$$hashmain{_passwdtitles} = showLocalPage($hashmain, $innl, 'request_password.reset' );
									}
									else{
										$$hashmain{_passwdtitles} = showLocalPage($hashmain, $innl, 'request_password.new' );
									}
 									print STDERR "[Ix" . __LINE__ . "] Read solution template request.template.html \n"  ;
									$page = Page->new($innl, {}, '', '', ( $currenttemplate . '/request_password.template.html' ) );
								}
							}
							$page = Page->new($innl, {}, '', '', ( $currenttemplate . '/basic.template.html' ) );
 							print STDERR "[Ix" . __LINE__ . "] Read solution template basic.template.html \n"  ;
						}
						elsif ( $$hashmain{_action} eq 'activate'){
							traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
							$sql  = "SELECT * FROM custmdbm.in_register ";
							$sql .= "WHERE rg_activation = '" . $$hashmain{_activationkey} . "' ";
							$sql .= "AND   rg_user = '" . $$hashmain{_i3P84hdyW374625Z} . "' ";
							$sql .= "AND date_inserted >= DATE_SUB(NOW(), INTERVAL 1 HOUR) ";
							traceme( $hashmain, $_ihs, $sql, __LINE__ ) if $$_ihs{__syssqltrace__};
							my $activate = PrepAndFetchQuery( $hashmain, $_ihs, $innl, $sql, ('Ix' . __LINE__ ) );
							if ( $$activate{rg_id} ){
								#activation exists
								traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__} >= 2;
								if ( $$activate{rg_activated} eq "Nee" || $$activate{rg_activated} eq "Dbr" || $$activate{rg_activated} eq "Busy" ){#database is ready or busy creating
									if ( validateSystemName(  $activate, $_ihs, $innl ) ){
										#systemname already exists.....
										$$hashmain{act_companycode} = $$activate{rg_companycode};
										$$hashmain{_indexbody} = showDbPage($hashmain, $innl, '_newsys' );
										traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__} >= 2;
									}
									else{
										traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__} >= 2;
										#lets create the new environment. yeah, new customer ;)
										$$_ihs{_internalLogWarning} = '';
										#create the new database should already have started
										my $retval = connectDatabase( $hashmain, $_ihs, $innl, $activate );
										if ( $retval == 2 || $retval == 3 ){
											traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__} >= 3;
											if ( $retval == 3 ){
												$$hashmain{_finishpercentage} = createDbProgress( $hashmain, $_ihs, $innl, $$hashmain{_newdbname} );
											}
											else{
												$$hashmain{_finishpercentage} = 0;
											}
											#database is still being created
											#need to change this
											$$hashmain{_postselect} = showGenericPage($hashmain, $innl, $_ihs, 'javascript._activate.postselect' );
											$$hashmain{_javascript_bottom_all} .= showGenericPage($hashmain, $innl, $_ihs, 'javascript.wait.auto' );
											$$hashmain{_indexbody} = showDbPage($hashmain, $innl, '_actwait.auto' );
											$$hashmain{_cssfile}   = showGenericPage($hashmain, $innl, $_ihs, 'pagina.spinner.css' );
										}
										elsif ( $retval == 0 ){
											traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__} >= 3;
											#system error. the database is in use.
											#need to change this
											$$hashmain{_indexbody} = showDbPage($hashmain, $innl, '_actwait' );
										}
										else { #everything ok (retval =1 )
											traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__} >= 3;
	
											#invite the user to login to raplico 
											#need to change this
											setButtonOk( $hashmain, $_ihs, $innl );
											$sql  = "SELECT * FROM  custmdbm.in_register ";
											$sql .= "WHERE rg_activation = '" . $$hashmain{_activationkey} . "' ";
											$sql .= "AND   rg_user = '" . $$hashmain{_i3P84hdyW374625Z} . "' ";
											my $rg = PrepAndFetchQuery( $hashmain, $_ihs, $innl, $sql, ('Ix' . __LINE__ ) );
											$$_ihs{_companycode} = $$hashmain{_companycode} = $$rg{rg_companycode};
											$$hashmain{_gb_id}  = $$rg{rg_user};
											$$hashmain{rg_user} = $$rg{rg_user};
											$$hashmain{_loginstate} = 5;
											$$hashmain{_javaloginstate} = showPage($innl, 'javascript._h_tryitnow.ok', $hashmain );
											traceme( $hashmain, $_ihs, $sql, __LINE__ ) if $$_ihs{__syssqltrace__};
										}
									}
								}
								else{
									$$hashmain{_loginstate} = 6;
									$$hashmain{_gb_id} = $$activate{rg_user};
									$$_ihs{_companycode} = $$hashmain{_companycode} = $$activate{rg_companycode};
									$$hashmain{_javaloginstate} = showPage($innl, 'javascript._h_tryitnow.not.ok', $hashmain );
									traceme( $hashmain, $_ihs, "Activation already done", __LINE__ );
								}		
								traceme( $hashmain, $_ihs, "", __LINE__ );
							}
							else{
								$sql  = "SELECT * FROM custmdbm.in_register ";
								$sql .= "WHERE rg_activation = '" . $$hashmain{_activationkey} . "' ";
								$sql .= "AND   rg_user = '" . $$hashmain{_i3P84hdyW374625Z} . "' ";
								$sql .= "AND   rg_activated = 'Ja' ";
								traceme( $hashmain, $_ihs, $sql, __LINE__ ) if $$_ihs{__syssqltrace__};
								my $activate = PrepAndFetchQuery( $hashmain, $_ihs, $innl, $sql, ('Ix' . __LINE__ ) );
								if ( $$activate{rg_id} ){
									traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
									#show form activation failed
									$$hashmain{rg_user} = $$activate{rg_user};
									$$hashmain{_gb_id} = $$activate{rg_user};
									$$_ihs{_companycode} = $$hashmain{_companycode} = $$activate{rg_companycode};
									$$hashmain{_loginstate} = 7;
									$$hashmain{_javaloginstate} = showPage( $innl, 'javascript._h_tryitnow.allreadydone', $hashmain );
								}
								else{
									traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
									#show form activation failed
									$$hashmain{_loginstate} = 6;
									$$hashmain{_javaloginstate} = showPage($innl, 'javascript._h_tryitnow.not.ok', $hashmain );
								}
							}
							traceme( $hashmain, $_ihs, "", __LINE__ );
							$page = Page->new($innl, {}, '', '', ( $currenttemplate . '/basic.template.html' ) );
						}
						elsif ( $$hashmain{_action} eq '' ){
							$$hashmain{_loginstate} = '0';
							$$_ihs{_companycode} = $$hashmain{_companycode} = '' if ( $$hashmain{_companycode} eq 'custmdbm' );
							traceme( $hashmain, $_ihs, "No action selected. show login page", __LINE__ ) if ( $$_ihs{__systemtrace__} );
							$page = Page->new($innl, {}, '', '', ( $currenttemplate . '/basic.template.html' ) );
						}
						#do the final print, check for messages.
						if ( $$_ihs{_finaltemplate} ne '' ) {
							if ( $$_ihs{_finaltemplatemethod} == $genericshow ){
								$data = showGenericPage( $hashmain, $innl, $$_ihs{_finaltemplate} );
							}
							elsif ( $$_ihs{_finaltemplatemethod} == $normalshow ){
								$data = showPage($innl, $$_ihs{_finaltemplate}, $hashmain);
							}
							elsif ( $$_ihs{_finaltemplatemethod} == $databaseshow ){
								$data = showDbPage($hashmain, $innl, $$_ihs{_finaltemplate} );
							}
						}
						traceme( $hashmain, $_ihs, "Final print", __LINE__ ) if ( $$_ihs{__systemtrace__} );
						my $output = $page->FinalPrint( $data, $hashmain ); #for development 
						#print $cgi->header(), $tidy->clean($output); #for development 
						print $cgi->header(), $page->FinalPrint( $data, $hashmain); #for production 
						return;
					}
					else{
						$$hashmain{_loginstate} = '0';
						$$_ihs{_companycode} = $$hashmain{_companycode} = '' if ( $$hashmain{_companycode} eq 'custmdbm' );
						traceme( $hashmain, $_ihs, "No action selected. show login page", __LINE__ ) if ( $$_ihs{__systemtrace__} );
 						print STDERR "[Ix" . __LINE__ . "] Read solution template basic.template.html \n"  ;
						$page = Page->new($innl, {}, '', '', ( $currenttemplate . '/basic.template.html' ) );
						traceme( $hashmain, $_ihs, "Final print", __LINE__ ) if ( $$_ihs{__systemtrace__} );
						#print $cgi->header(), $tidy->clean( $page->FinalPrint( $data, $hashmain ));
						print $cgi->header(), $page->FinalPrint( $data, $hashmain);
						return;
						last BLOCK;
					}
				}
				#valid login session. first check if user doesnt want to logoff before switching to customer database.
				traceme( $hashmain, $_ihs, "---------------------------------- start login with valid user --------------------", __LINE__ ) if ( $$_ihs{__systemtrace__} );
				traceme( $hashmain, $_ihs, "-----------------------------------------------------------------------------------", __LINE__ ) if ( $$_ihs{__systemtrace__} );

				traceme( $hashmain, $_ihs, "valid login for user $$hashmain{_gb_id} for system $$hashmain{_companycode}", __LINE__ ) if $tracefunc;
				my $activesession;
				if ( $$hashmain{_action} eq 'logoff' ){
					$data = executeactionLogoff( $hashmain, $_ihs, $innl, $cgi, $tidy );
				}
				else{
					$dbh->disconnect();
#-marker MAIN switch to new database
					$ModuleBase::DatabaseName = $$_ihs{_databasename};
					$$hashmain{__database__} = $ModuleBase::DatabaseName;
					$innl = new INNL();
					$innl->autocommit();
					$dbh = $innl->dbh( ); # make sure that it connects to the new database
					$hashmain = initEnableCustomerDb( $hashmain, $_ihs, $innl, $session );
					traceme( $hashmain, $_ihs, "table: $$hashmain{_tbnaam}", __LINE__ ) if ( $$_ihs{__systemtrace__} );
				}
				$sql  = "SELECT id FROM sys_user ";
				$sql .= "WHERE gb_id = ? ";
				my $userrec = ParamPrepAndFetch( $hashmain, $_ihs, $innl, $sql, $$hashmain{_gb_id}, ('Ix' . __LINE__ ) );
				$$_ihs{_userid} = $$userrec{id};
				$sql = "SELECT org_defaultcss FROM " . $$_ihs{_databasename} . ".sys_organization";
				$$hashmain{_cssorgown} = ExecuteQuery( $_ihs, $dbh, $sql,  '', __LINE__ );
				traceme( $hashmain, $_ihs, $$hashmain{_cssorgown},  __LINE__ ) ;#if ( $$_ihs{__systemtrace__} );
				#listKeys( $hashmain, $_ihs, 'all', ('--- ' . __LINE__ . ' --- ' ), ( "Ix" . __LINE__ ) ); 
#-marker main handle back action
				if ( $$hashmain{_action} eq 'backsession' ){
					traceme( $hashmain, $_ihs, "backsession", __LINE__ ) if ( $$_ihs{__systemtrace__} );
					$$_ihs{_curVolgNr} = $$hashmain{_sid};
					$$_ihs{_curIntSeqNr} = $$_ihs{_curVolgNr} - 1;
					$activesession = readSessionSequenceCurrent( $hashmain, $_ihs, $innl );
					#set previous
					$$_ihs{_tbprev} = $$activesession{_tbprev};
					$$_ihs{_tbprevid} = $$activesession{_tbprevid};
					traceme( $hashmain, $_ihs, "_tbprev $$_ihs{_tbprev}", __LINE__ ) if ( $$_ihs{__systemtrace__} );
					#set new
					$$hashmain{_action}	 = $$activesession{_action};
					$$hashmain{_prevcsi}	= $$activesession{_csi};
					$$hashmain{_tab}		= $$activesession{_tab_nr};
					$$hashmain{_tbnaam}	 = $$activesession{tb_id};
					$$hashmain{_tgrndds}	= $$activesession{_tgrndds};
					$$_ihs{_tab_grp}		= $$activesession{_tab_grp};
					$$_ihs{_actualaction}   = $$hashmain{_action};
					readTableAttributes( $hashmain, $_ihs, $innl, $$hashmain{_tbnaam} );
					traceme( $hashmain, $_ihs, "nxtaction: table $$hashmain{_tbnaam}, $$hashmain{_action} $$_ihs{_tbprev}", __LINE__ ) if ( $$_ihs{__systemtrace__} );
					traceme( $hashmain, $_ihs, "_csi: $$hashmain{_csi}, _prevcsi: $$hashmain{_prevcsi} new _prevcsi when going back", __LINE__ ) if $tracecsi;
				}
				elsif ( $$hashmain{_tab} ){
					traceme( $hashmain, $_ihs, "An tab was found tab ($$hashmain{_tab}), volgnummer $$_ihs{_curVolgNr} csi: $$hashmain{_csi}", __LINE__ ) if ( $$_ihs{__systemtrace__} );
					readSessionSequenceFromTab( $hashmain, $_ihs, $innl );
					traceme( $hashmain, $_ihs, "An tab was found tab ($$hashmain{_tab}), volgnummer $$_ihs{_curVolgNr} csi: $$hashmain{_csi}", __LINE__ ) if ( $$_ihs{__systemtrace__} );
				}
				else{
					traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
					$$hashmain{_sid} = 0; #DONT WANT WARNINGS
				}
				if ( $$hashmain{_action} eq 'back' ){
					traceme( $hashmain, $_ihs, "back", __LINE__ ) if $$_ihs{__systemtrace__} || $tracesession;
					if ( $$_ihs{_prevcsiFound} ){
						traceme( $hashmain, $_ihs, "We know which session we should go", __LINE__ ) if $$_ihs{__systemtrace__} || $tracesession;
						$$_ihs{_curVolgNr} = $$_ihs{_prevVolgNr};
						$$_ihs{_curIntSeqNr} = $$_ihs{_prevcsiIntSeqNr};
					}
					else{
						$$_ihs{_parentcsi} = @{$$_ihs{_SessSeq}}[$$_ihs{_curIntSeqNr}]->{_prevcsi};
						traceme( $hashmain, $_ihs, ( "previous session not found. now taking one step back." ), __LINE__ ) if ( $$_ihs{__systemtrace__} );
						traceme( $hashmain, $_ihs, ( "_csi " . $$hashmain{_prevcsi} . ", parent " . $$_ihs{_parentcsi} ), __LINE__ ) if ( $$_ihs{__systemtrace__} );
						if ( intelligentGetPreviousSequence( $hashmain, $_ihs, $innl) != 1 ){#if not found, then we go one step back
							if ( @{$$_ihs{_SessSeq}}[$$_ihs{_curIntSeqNr}]->{_tab_nr} > 0 ){#find and go to lower level
								traceme( $hashmain, $_ihs, "$$activesession{volg_nr} - $$activesession{_level_nr}", __LINE__ );
								my $found = 0;
								foreach ( reverse( @{$$_ihs{_SessSeq}} ) ){ #first see if we can find the previous _csi
									if ( $$hashmain{_prevcsi} eq @{$$_ihs{_SessSeq}}[$$_ihs{_curIntSeqNr}]->{_csi} ){
										$$_ihs{_curVolgNr} = @{$$_ihs{_SessSeq}}[$$_ihs{_curIntSeqNr}]->{volg_nr} - 1;
										$$_ihs{_curIntSeqNr} = $$_ihs{_curVolgNr} - 1;
										traceme( $hashmain, $_ihs, "csi found", __LINE__ );
										$found = 1;
										last;
									}
								}
								if ( $found == 0 ){
									foreach ( reverse( @{$$_ihs{_SessSeq}} ) ){
										if ( $$_{_level_nr} < @{$$_ihs{_SessSeq}}[$$_ihs{_curIntSeqNr}]->{_level_nr} ){
											$$_ihs{_curVolgNr} = $$_{volg_nr};
											$$_ihs{_curIntSeqNr} = $$_ihs{_curVolgNr} - 1;
											last;
										}
									}
								}
								traceme( $hashmain, $_ihs, "$$activesession{volg_nr} - $$activesession{_level_nr}", __LINE__ );
							}
							else{
								$$_ihs{_curVolgNr}--;
								$$_ihs{_curIntSeqNr} = $$_ihs{_curVolgNr} - 1;
							}
						}
						else{
							traceme( $hashmain, $_ihs, "previous csi found", __LINE__ ) if ( $$_ihs{__systemtrace__} );
							#listKeys(  @{$$_ihs{_SessSeq}}[$$_ihs{_curIntSeqNr}], $_ihs, 'all', '', ( "Ix" . __LINE__ ) ); 
							#$$_ihs{_parentcsi} = @{$$_ihs{_SessSeq}}[$$_ihs{_curIntSeqNr}]->{_prevcsi};
							#intelligentGetPreviousSequence( $hashmain, $_ihs, $innl) ;
						}
					}
					$activesession = readSessionSequenceCurrent( $hashmain, $_ihs, $innl );
					#set previous
					$$_ihs{_tbprev} = $$activesession{_tbprev};
					$$_ihs{_tbprevid} = $$activesession{_tbprevid};
					traceme( $hashmain, $_ihs, "_tbprev $$_ihs{_tbprev}", __LINE__ ) if ( $$_ihs{__systemtrace__} );
					#set new
					$$hashmain{_csi} = $$activesession{_csi};
					$$hashmain{_action} = $$activesession{_action};
					$$hashmain{_tbnaam} = $$activesession{tb_id};
					$$hashmain{_tab}	  = $$activesession{_tab_nr};
					$$hashmain{_tgrndds}  = $$activesession{_tgrndds};
					$$_ihs{_tab_grp}	  = $$activesession{_tab_grp};
					$$_ihs{_actualaction} = $$hashmain{_action};
					traceme( $hashmain, $_ihs, "_csi: $$hashmain{_csi}, _prevcsi: $$hashmain{_prevcsi} new _csi ", __LINE__ ) if $tracecsi;
					traceme( $hashmain, $_ihs, "nxtaction: table $$hashmain{_tbnaam}, $$hashmain{_action} $$_ihs{_tbprev}", __LINE__ ) if ( $$_ihs{__systemtrace__} );
					$$_ihs{_back} = 'Ja';
				}
				else{
					$$_ihs{_back} = 'Nee';
				}
				if ( $$hashmain{_nxtaction} ne '' ){
					traceme( $hashmain, $_ihs, "nxtaction: table $$hashmain{_tbnaam}, $$hashmain{_action} $$_ihs{_tbprev}", __LINE__ ) if ( $$_ihs{__systemtrace__} );
					#set previous
					$$_ihs{_tbprev} = $$hashmain{_tbnaam};
					$$_ihs{_tbprevid} = $$hashmain{_tgrndds};
					traceme( $hashmain, $_ihs, "_tbprev $$_ihs{_tbprev}", __LINE__ ) if ( $$_ihs{__systemtrace__} );
					#set new
					$$hashmain{_action} = $$hashmain{_nxtaction};
					$$_ihs{_actualaction} = $$hashmain{_action};
					traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
					$$hashmain{_tbnaam} = provideTablenameFromId( $hashmain, $_ihs, $innl, $$hashmain{_xsplimn}, __LINE__ );
					$$hashmain{_tgrndds} = $$hashmain{_xsplimn};
					traceme( $hashmain, $_ihs, "nxtaction: table $$hashmain{_tbnaam}, $$hashmain{_action} $$_ihs{_tbprev}", __LINE__ ) if ( $$_ihs{__systemtrace__} );
				}

#marker where we determined which session we are. Need to validate this
				
				if ( $$_ihs{_orgsearchwordstat} == 2 && defined $$hashmain{_tbnaam} && $$_ihs{_validuser }){
					#this is a special case. the searchkey is emptied and needs to be reset in the sys_sessionsequence
					resetSearchKeysinceEmpty( $hashmain, $_ihs, $innl );
				}
				if ( $$hashmain{_action} ne 'logoff'  ){
					$$hashmain{_cssforfields}	= 'table_template';
					traceme( $hashmain, $_ihs, "table $$hashmain{_tbnaam}, $$hashmain{_action} ", __LINE__ ) if ( $$_ihs{__systemtrace__} );
					$activesession = readSessionSequenceCurrent( $hashmain, $_ihs, $innl );
					intelligentSetRecordValueKey( $hashmain, $_ihs, $innl );
					determineTabStyle( $hashmain, $_ihs, $innl, ( 'Ix' . __LINE__ ) ) if ( $$hashmain{_tbnaam} ne '' );
					$$_ihs{_previousaction} =$$activesession{_action}; 
					$$_ihs{_parentcsi} =$$activesession{_prevcsi}; 
					$$_ihs{_parentaction} =$$activesession{_action}; 
					traceme( $hashmain, $_ihs, "_csi: $$hashmain{_csi}, _prevcsi: $$hashmain{_prevcsi} new _parentcsi $$_ihs{_parentcsi} ", __LINE__ ) if $tracecsi;
				}

				traceme( $hashmain, $_ihs, "we know that we are working with internal sequence number$$_ihs{_curIntSeqNr} ", __LINE__ ) if ( $$_ihs{__systemtrace__} );

				if ( $$hashmain{_action} eq 'copyrecord'  ){
					traceme( $hashmain, $_ihs, $$hashmain{_action}, __LINE__ ) if ( $$_ihs{__systemtrace__} );
					$$_ihs{_copyrecord} = 1;
					$hashmain = copyrecord( $hashmain, $_ihs, $innl);
				}
				if ( $$hashmain{_action} eq 'savelist'  ){
					traceme( $hashmain, $_ihs, $$hashmain{_action}, __LINE__ ) if ( $$_ihs{__systemtrace__} );
					$$hashmain{_savelist} = 'savelist';
					$$hashmain{_action} = 'select';
					$$hashmain{_actualaction} = $$hashmain{_action};
				}
				if ( $$hashmain{_action} eq 'commitselect'  ){ #designchange by moving rows.
					traceme( $hashmain, $_ihs, $$hashmain{_action}, __LINE__ ) if ( $$_ihs{__systemtrace__} );
					commitDesignChange( $hashmain, $_ihs, $innl, $$hashmain{_tbnaam} ); 
					$$hashmain{_action}  = $$activesession{_action};
					$$hashmain{_tab}	 = $$activesession{_tab_nr};
					$$hashmain{_csi}	 = $$activesession{_csi};
					$$hashmain{_prevcsi} = $$activesession{_prevcsi};
					$$_ihs{_tab_grp}	 = $$activesession{_tab_grp};
					traceme( $hashmain, $_ihs, "_csi: $$hashmain{_csi}, _prevcsi: $$hashmain{_prevcsi} new _csi and _prevcsi ", __LINE__ ) if $tracecsi;
					determineTabStyle( $hashmain, $_ihs, $innl, ( 'Ix' . __LINE__ ) ) if ( $$hashmain{_tbnaam} ne '' );
				}
#-marker main start executing the actions
				if ( $$hashmain{_action} eq 'select' || $$hashmain{_action} eq 'show' ){
					#listKeys(  $hashmain, $_ihs, 'int', 'select action', ( "Ix" . __LINE__ ) ); 
					traceme( $hashmain, $_ihs, $$hashmain{_action}, __LINE__ ) if ( $$_ihs{__systemtrace__} );
					( $data, $hashmain ) = showContentInTable( $hashmain, $_ihs, $innl);
					traceme( $hashmain, $_ihs, $$hashmain{_action} . "exit showContentInTable" , __LINE__ ) if $$_ihs{__systemtrace__} || $tracesaving;
				}
				elsif( $$hashmain{_action} eq 'read' ){
					( $data, $hashmain) = selectrecord( $hashmain, $_ihs, $innl, 'read' );
					traceme( $hashmain, $_ihs, $$hashmain{_action} . "exit selectrecord" , __LINE__ ) if $$_ihs{__systemtrace__} || $tracesaving;
					if ( $data eq '' ){
						traceme( $hashmain, $_ihs, ($$hashmain{_action} . " empty result"), __LINE__ ) if $$_ihs{__systemtrace__} >= 2;
						$$hashmain{_action} = 'select';
						$$_ihs{_actualaction} = $$hashmain{_action};
						( $data, $hashmain ) = showContentInTable( $hashmain, $_ihs, $innl);
						traceme( $hashmain, $_ihs, $$hashmain{_action} . "exit showContentInTable" , __LINE__ ) if $$_ihs{__systemtrace__} || $tracesaving;
					}
				}
				elsif( $$hashmain{_action} eq 'reference' ){
					traceme( $hashmain, $_ihs, "Show references", __LINE__ ) if ( $$_ihs{__systemtrace__} );
					$data = showIndexPage( $hashmain, $_ihs, $innl, __LINE__ );
				}
				elsif( $$hashmain{_action} eq 'zoek' ){
					$data = searchTemplate( $hashmain, $_ihs, $innl );
				}
				elsif( $$hashmain{_action} eq 'export' ){
					traceme( $hashmain, $_ihs, "huidig sequence: $$_ihs{_curIntSeqNr}", __LINE__ ) ;
					doExport( $hashmain, $_ihs, $innl, $cgi );
				}
				elsif( $$hashmain{_action} eq 'zoeknext' ){
					$data = searchResult( $hashmain, $_ihs, $innl );
				}
				elsif( $$hashmain{_action} eq 'nieuwsmeer'){#extend the news
					showSelectedNewsItem( $hashmain, $_ihs, $innl );
					genNieuws( $hashmain, $_ihs, $innl );
					genPresence( $hashmain, $_ihs, $innl );
					$data = showLocalPage($hashmain, $innl, $$_ihs{_loggedin_startpage} );
				}
				elsif( $$hashmain{_action} eq '_impgo' || $$hashmain{_action} eq '_impugo' ){ #last import screen
					traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
					$$hashmain{_tbnaam} = '';
					$$hashmain{_tgrndds} = 0;
					determineTabStyle( $hashmain, $_ihs, $innl, ( 'Ix' . __LINE__ ) ); #again since _tbnaam is empty now
					#setIdentifier( $hashmain, $session, $innl );
					traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
					$hashmain = getSessionFields ( $hashmain, $_ihs, $innl );
					if ( intelligentGetSequence( $hashmain, $_ihs, $innl ) == -1 ){
						intelligentInsertSequence( $hashmain, $_ihs, $innl, __LINE__ );
					}
					traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
					$hashmain = newBootstrapValues( $hashmain, $_ihs );
					showTabStyle( $hashmain, $_ihs, $innl ) if ( $$_ihs{_tabbedforms} );
					traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
					$$hashmain{_showbutback} = getSyslable( $dbh, $$hashmain{_language}, 'butback' );
					$$hashmain{_buttonlable} = getButtonLableOverride( $hashmain, $_ihs, $innl, 'generic', 'go', 'C', __LINE__ ); 
					$$hashmain{_buttontop} .= showGenericPage( $hashmain, $innl , $_ihs, 'button.back.top' );
					$$hashmain{_topbuttonssmall} = showGenericPage($hashmain, $innl, $_ihs, 'form.button.top' );
					$$hashmain{_extrabutton} .= showGenericPage( $hashmain, $innl , $_ihs, 'button.back' );
					addExtraButtonContent(   $hashmain, $innl, '_imp', '_3tvA2yW1rC0L', $$hashmain{imp_code}, '				' );
					addExtraButtonContent(   $hashmain, $innl, '_imp', '_Uq1lapI4n9W3', $$hashmain{imp_id}, '				' );
					if ( $$hashmain{_action} eq '_impgo' ){
						addGenericButtonContent( $hashmain, $innl, '_imp', '_impdoit', '				' );
					}
					elsif ( $$hashmain{_action} eq '_impugo' ){
						addGenericButtonContent( $hashmain, $innl, '_imp', '_impuseit', '				' );
					}
					traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
					$$hashmain{_buttons} .= showGenericPage( $hashmain, $innl , $_ihs, 'button.submit' );
					$$hashmain{_mapopenbanner} = intelligentBreadcrumLabel( $hashmain, $_ihs, $innl, $$hashmain{_action} );
					$$hashmain{_indexpagecontent} = showDbPage($hashmain, $innl, $$hashmain{_action} );
					$$hashmain{_javascript_bottom_all} = showGenericPage($hashmain, $innl, $_ihs, 'javascript.head' );
					#$$hashmain{_loggedinpagetitle} = '';
					$data = showLocalPage($hashmain, $innl, '_indexloggedin.page' );
					traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
				}
				elsif( $$hashmain{_action} eq '_impuseit'){ #do the actual import
					$$hashmain{_tbnaam} = 'sys_importuser';
					$$hashmain{imp_type} = 'U';
					executeactionDoImport( $hashmain, $_ihs, $innl ); #ready to do the second step of the import
					( $data, $hashmain) = waitforImportToFinish( $hashmain, $_ihs, $innl );
				}
				elsif( $$hashmain{_action} eq '_impdoit'){ #do the actual import
					$$hashmain{_tbnaam} = 'sys_import';
					$$hashmain{imp_type} = 'D';
					executeactionDoImport( $hashmain, $_ihs, $innl ); #ready to do the second step of the import
					( $data, $hashmain) = waitforImportToFinish( $hashmain, $_ihs, $innl );
				}
				elsif( $$hashmain{_action} eq '_waitforimport'){ 
					( $data, $hashmain ) = waitforImportToFinish( $hashmain, $_ihs, $innl );
				}
				elsif( $$hashmain{_action} eq '_chpw' || $$hashmain{_action} eq '_chpwtop' ){ #change password
					$$hashmain{_action} = '_chpw';
					$data = executeactionChangePassword( $hashmain, $_ihs, $innl );
				}
				elsif( $$hashmain{_action} eq '_rspwtop' || $$hashmain{_action} eq '_rspw' ){ #request to reset the password request coming from beheerder
					( $data, $hashmain) = executeactionResetPassword( $hashmain, $_ihs, $innl );
					$$hashmain{_action} = '_rspw';
				}
				elsif( $$hashmain{_action} eq '_svpw'){ #save password
					( $data, $hashmain ) = executeactionSavePassword( $hashmain, $_ihs, $innl );
				}
				elsif( $$hashmain{_action} eq 'shpg'){ #showpage
					traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
					showTabStyle( $hashmain, $_ihs, $innl ) if ( $$_ihs{_tabbedforms} );
					$data = showDbPage($hashmain, $innl, $$hashmain{_page} );
				}
				elsif($$hashmain{_action} eq 'index' || $$hashmain{_action} eq 'chklogin' || $$hashmain{_action} eq 'home' ){
					deleteSessionSequence ( $hashmain, $_ihs, $innl, 0, ( 'Ix' . __LINE__ )  );
					showWorkList( $hashmain, $_ihs, $innl, __LINE__ );
					traceme( $hashmain, $_ihs, "before showIndexPage", __LINE__ ) if ( $$_ihs{__systemtrace__} );
					$data = showIndexPage( $hashmain, $_ihs, $innl, __LINE__ );
					$activesession = readSessionSequenceCurrent( $hashmain, $_ihs, $innl );
				}
				elsif( $$hashmain{_action} eq 'update'  || $$hashmain{_action} eq 'next' || $$hashmain{_action} eq 'insert' || $$hashmain{_action} eq '' ){
					traceme( $hashmain, $_ihs, "_prevcsiIntSeqNr $$_ihs{_prevcsiIntSeqNr}", __LINE__ ) if ( $$_ihs{__systemtrace__} );
					( $data, $hashmain ) = executeactionSelectRecord( $hashmain, $_ihs, $innl, $session );
				}
				elsif( $$hashmain{_action} =~ /showcontent/ ){
					traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
					$data = showDbPage( $hashmain, $innl, $$hashmain{_action} );
				}
				elsif($$hashmain{_action} eq 'bewaar' || $$hashmain{_action} eq 'commitrecord' ){
					( $data, $hashmain ) = executeactionSaveRecord( $hashmain, $_ihs, $innl, $cgi, $session );
				}
				elsif($$hashmain{_action} eq 'delete' ){
					( $data, $hashmain ) = executeactionDeleteRecord( $hashmain, $_ihs, $innl, $session );
				}
				if( $$hashmain{_action} ne 'logoff' ){
					if ( $$_ihs{_goodmessage} ne '' ){
						throwTopGoodMessage( $hashmain, $_ihs, $innl, $$_ihs{_goodmessage} );
					}
					#$data = showGenericPage( $hashmain, $innl, $_ihs, $$_ihs{_finaltemplate} );
					traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
					showWorkList( $hashmain, $_ihs, $innl, __LINE__ );
					$hashmain = genNewMenuItem( $hashmain, $_ihs, $innl );
					$$hashmain{_metadescription} =  'metadescription' ;
					$$hashmain{_metakeywords}	=  'metakeywords' ;
					$$hashmain{_menu_logoff} = showDbPage($hashmain, $innl, 'home.menu.logoff' ); #internal menuitem to logoff.
				}
 
			};
			#2nd step of the process. all options are worked upon. now finalize the page, add a menu and show it
			traceme( $hashmain, $_ihs, "step 2", __LINE__ ) if ( $$_ihs{__systemtrace__} );
			if ( !$data || $$hashmain{_internalsqlerror} ){ #something went wrong here or its the index page!!
				$$hashmain{_tabstyle} = '';
				if ($$hashmain{_internalsqlerror} ) {
					traceme( $hashmain, $_ihs, "Catch Error. Error handler is showing a die message.... ", __LINE__ );
				}
				traceme( $hashmain, $_ihs, "before showIndexPage", __LINE__ ) if ( $$_ihs{__systemtrace__} );
				$data = showIndexPage( $hashmain, $_ihs, $innl, __LINE__ );
				warn "no body" if !$data;
				$hashmain = genNewMenuItem( $hashmain, $_ihs, $innl );
			}
			showHtml($hashmain, $_ihs, $innl, $cgi, $page, $data, $tidy );
		};
		if($@){
			print STDERR "Error handler is showing a die message.... Line " . __LINE__  . "\n" ;
			print STDERR Dumper $@;
			if (ref($@) eq 'Error'){
				sendSystemError( $hashmain, $_ihs, $innl, $@->throw() );
			}
			$$hashmain{_tabstyle} = '';
			if ($$hashmain{_internalsqlerror} ) {
				traceme( $hashmain, $_ihs, "Catch Error. Error handler is showing a die message.... ", __LINE__ );
			}
			
			#listKeys(  $hashmain, $_ihs, 'int', 'select action', ( "Ix" . __LINE__ ) ); 
			my $data = '';
			if ( $$_ihs{_validuser} ){
				$data = showIndexPage( $hashmain, $_ihs, $innl, __LINE__ );
				$hashmain = genNewMenuItem( $hashmain, $_ihs, $innl );
			}
			else{
				$page = Page->new($innl, $hashmain, '', '', ( $currenttemplate . '/basic.template.html' ) );
			}
			showHtml($hashmain, $_ihs, $innl, $cgi, $page, $data, $tidy );
			#if (ref($@) eq 'Error'){
				#print "Content-type: text/html\r\n\r\n",
				#	 $@->throw();
				#$request->Finish(); #end but don't cause the fcgi child to be restarted
			#}
			#die "Couldn't procesError in $0 : $@";
		}
	}	
}

sub copyhashref {
	my ( $hashmain ) = @_;
	return $hashmain;
}

sub resetPasswordrequest {
	my ( $hashmain, $_ihs, $innl, $response ) = @_;

	traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
	my $rspw;
	my $sql;
	if( $$hashmain{_action} eq '_extpwnem'){ #new user password
		$sql  = "SELECT * FROM sys_user ";
		$sql .= "WHERE gb_id = ? ";
		$sql .= "AND gb_resetkey = ? ";
		$sql .= "AND gb_resettime >= DATE_SUB(NOW(), INTERVAL 1 WEEK ) "; #reset not older then one week
		$$hashmain{_formtitle} = getSysMessage( $hashmain, $innl, 'password-set');
		traceme( $hashmain, $_ihs, "SQL $sql (id:$$response{re_gb_id})(key: $$response{re_charkey})", __LINE__ ) if ( $$_ihs{__systemtrace__} );
		$rspw = TwoParamPrepAndFetch( $hashmain, $_ihs, $innl, $sql, $$response{re_gb_id}, $$response{re_charkey}, ( 'Ix' .__LINE__ )  );
	}
	else{
		$sql  = "SELECT * FROM sys_user ";
		$sql .= "WHERE gb_resetkey = ? ";
		$sql .= "AND id = ? ";
		$sql .= "AND gb_resettime >= DATE_SUB(NOW(), INTERVAL 1 HOUR) ";
		$$hashmain{_formtitle} = getSysMessage( $hashmain, $innl, 'password-reset');
		traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
		$rspw = TwoParamPrepAndFetch( $hashmain, $_ihs, $innl, $sql, $$response{re_charkey}, $$response{re_tbkey}, ( 'Ix' .__LINE__ )  );
	}
	$$hashmain{_mainformheadingtitle} = showGenericPage($hashmain, $innl, $_ihs, 'tabelrecordinhoud.tabel.pw.title' );
	traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
	if ( $$rspw{id} ){#the reset request exists....
		traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
		$$hashmain{_gxw7xpe2ebda2abfb09f60e9} = $$rspw{id};
		$$hashmain{frgpwkey} = $$rspw{gb_resetkey};
		if ( $$rspw{gb_active} eq 'Nee' ){ #apparently in between actions the user is deactivated
			traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__} >= 2;
			throwTopErrorMessage( $hashmain, $_ihs, $innl, 'rstcode-user-notactive'); 
			$$_ihs{_throwingerror} = 1;
		}
		else{#ok. we can show the password reset form
			$$hashmain{_gebruikernaam} = $$rspw{gb_id};
			traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
			newExecuteactionResetPassword( $hashmain, $_ihs, $innl );
		}	
	}	
	else{
		traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
		throwTopErrorMessage( $hashmain, $_ihs, $innl, 'rstcode-user-noreginfo'); 
		$$_ihs{_throwingerror} = 1;
	}
}

#-marker SUB showHtml

sub showHtml {
	my ( $hashmain, $_ihs, $innl, $cgi, $page, $data, $tidy ) = @_;

	traceme( $hashmain, $_ihs, "error $$_ihs{_throwingerror}", __LINE__ ) if ( $$_ihs{__systemtrace__} );
	$$hashmain{_activelanguageitems} = '';
	my @languages = @{$$_ihs{_languages}};
	foreach my $lang ( @languages ){
		$$lang{session} = $$hashmain{session};
		$$hashmain{_activelanguageitems} .= showPage($innl, 'language.active', $lang );
	}
	$$hashmain{_cssfile} .= showGenericPage($hashmain, $innl, $_ihs, 'pagina.incontrol.css' );
	$$hashmain{_cssfile} .= showGenericPage($hashmain, $innl, $_ihs, 'pagina.mobirise.css' );
	$$hashmain{_title} = ExpandString( $hashmain, $$hashmain{_title} ) if ( $$hashmain{_title} =~ /\%/ );
	
	if ( $$_ihs{_validuser} ){
		$$hashmain{_homemenu}   = showDbPage($hashmain, $innl, 'home.menu' );
	}
	else{
		$$hashmain{_menu_register} = showDbPage($hashmain, $innl, 'home.menu.register' );
		$$hashmain{_homemenu}	  = showGenericPage($hashmain, $innl, $_ihs, 'home.menu' );
		$$hashmain{_bodyclass}	 = showGenericPage($hashmain, $innl, $_ihs, 'bodyclass.notloggedin' ) ;
	}
	#traceme( $hashmain, $_ihs, $$hashmain{_menu_register}, __LINE__ ) if ( $$_ihs{__systemtrace__} );
	#do the final print, check for messages.
	if ( $$_ihs{_finaltemplate} ne '' ) {
		if ( $$_ihs{_finaltemplatemethod} == $genericshow ){
			$data = showGenericPage( $hashmain, $innl, $_ihs, $$_ihs{_finaltemplate} );
		}
		elsif ( $$_ihs{_finaltemplatemethod} == $normalshow ){
			$data = showPage($innl, $$_ihs{_finaltemplate}, $hashmain);
		}
		elsif ( $$_ihs{_finaltemplatemethod} == $databaseshow ){
			$data = showDbPage($hashmain, $innl, $$_ihs{_finaltemplate} );
		}
	}
	$$hashmain{_bodycontent} = $data;
	traceme( $hashmain, $_ihs, "Final print", __LINE__ ) if ( $$_ihs{__systemtrace__} );
	$page = $page->FinalPrint( $$hashmain{_bodycontent}, $hashmain);
	#$page = $tidy->clean( $page->FinalPrint( $$hashmain{_bodycontent}, $hashmain) ); #for development 
	binmode(STDOUT, ":utf8");
	print decode_utf8($page);
	#print $cgi->header( -charset => 'utf-8'), $page;
}

#-marker SUB traceme

sub traceme {
	my ( $hashmain, $_ihs, $txt, $line ) = @_;
	my $subline = __LINE__;

	my $cpnc = $$hashmain{_companycode} eq '' ? 'custmdbm' : $$hashmain{_companycode};
	my $type = 'TPT';
	foreach( qw( SQL WHR SOR TRC ) ){
		if ( $txt =~ /^$_/ ){
			$type = "$_";
			$txt =~ s/^$_//;
		}
	}
	my $lb0 = $$_ihs{_curVolgNr};
	my $lb1 = $$hashmain{_recordvalue};
	my $lb2 = $$hashmain{_fieldname};
	my $lb3 = $$_ihs{_tab_nr};
	$lb1 = defined $lb1 ? $lb1 : 'ND';
	$lb2 = defined $lb2 ? $lb2 : 'ND';
	$lb3 = defined $lb3 ? $lb3 : 'ND';
	if ( $line > $subline ){  
		print STDERR "[Sb$line][" . $cpnc . "][$lb0][$lb1][$lb2][$lb3] --------  $txt -------\n";
	}
	else{
		print STDERR "[Ix$line][" . $cpnc . "][$lb0][$lb1][$lb2][$lb3] --------  $txt -------\n";
	}
}

#-marker SUB executeactionDeleteRecord

sub executeactionDeleteRecord {
	my ( $hashmain, $_ihs, $innl, $session ) = @_;
	my $dbh = $innl->dbh();
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	my $sql;
	my $data;

	traceme( $hashmain, $_ihs, "$$hashmain{_recordkey}: $$hashmain{_recordvalue}", __LINE__ ) if ( $$_ihs{__systemtrace__} );
	readTableAttributes( $hashmain, $_ihs, $innl, $$hashmain{_tbnaam} );
	if ( $$_ihs{_csiFound} == 1 ){
		traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
		$hashmain = getSessionFields ( $hashmain, $_ihs, $innl );
		$data = deleterecord( $hashmain, $_ihs, $innl);
	}
	if ( $data eq '' ){ #delete went well, no errors
		if ( $$_ihs{_tableattribute} =~ /D/ ){ # design table 
			commitDesignChange( $hashmain, $_ihs, $innl, $$hashmain{_tbnaam} ); 
		}
		if ( $$_ihs{_parentcsi} ne '' ){ #we need to go back to this csi.
			if ( intelligentGetPreviousSequence( $hashmain, $_ihs, $innl) == 1 ){#found
				$$hashmain{_action} = $$_ihs{_parentaction};
			}
			else{
				$$hashmain{_action} = 'select';
			}
		}
		else{
			$$_ihs{_curVolgNr}--;
			$$_ihs{_curIntSeqNr} = $$_ihs{_curVolgNr} - 1;
			$$hashmain{_action} = 'select';
			intelligentGetSequence( $hashmain, $_ihs, $innl );
		}
		intelligentUpdateSequence( $hashmain, $_ihs, $innl,{ _gotorow => 0 } ); #deleted row cannot be highlighted
		$$hashmain{_selectyear} = $$_ihs{_year};
		$$hashmain{_selmaand} = $$_ihs{_month};
		$$_ihs{_actualaction} = $$hashmain{_action};
		determineTabStyle( $hashmain, $_ihs, $innl, ( 'Ix' . __LINE__ ) );
		( $data, $hashmain ) = showContentInTable( $hashmain, $_ihs, $innl);
		traceme( $hashmain, $_ihs, $$hashmain{_action} . "exit showContentInTable" , __LINE__ ) if $$_ihs{__systemtrace__} || $tracesaving;
	}
	elsif ( $$_ihs{_throwingerror} ){
		traceme( $hashmain, $_ihs, " _prevcsi: $$hashmain{_prevcsi}, prev Volg: $$_ihs{_prevVolgNr}. Current: $$_ihs{_curVolgNr}", __LINE__ ) if $$_ihs{__systemtrace__} || $tracesaving;
		$$hashmain{_csi} = $$hashmain{_prevcsi}; #csi should stay the same
		$$hashmain{_action} = 'update';
		( $data, $hashmain ) = selectrecord ( $hashmain, $_ihs, $innl, $$hashmain{_action} );
	}
	return ( $data, $hashmain );
}

#-marker SUB executeactionSaveRecord

sub executeactionSaveRecord {
	my ( $hashmain, $_ihs, $innl, $cgi, $session ) = @_;
	my $dbh = $innl->dbh();
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	my $sql;
	my $data;
	$$_ihs{_designcommit} = 1 if ( $$hashmain{_action} eq 'commitrecord' );
	traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
	if ( $$_ihs{_csiFound} == 1 ){
		traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
		$$hashmain{__recordcount} = 1;
		#if ( $$hashmain{identifier} eq $$hashmain{_identifier} && $$_ihs{_back} eq 'Nee' ){
		readTableAttributes( $hashmain, $_ihs, $innl, $$hashmain{_tbnaam} );
		traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__} >= 2;
		#listKeys( $hashmain, $_ihs, '', ('--- just before getSessionFields --- ' ), ( "Ix" . __LINE__ ) ); 
		$hashmain = getSessionFields ( $hashmain, $_ihs, $innl );
		if ( $$_ihs{_tableattribute} =~ /M/ ){ # meerdere talen
			traceme( $hashmain, $_ihs, "$$_ihs{_languagefield}", __LINE__ ) if ( $$_ihs{__systemtrace__} );
			$$_ihs{_languagefield} = getLanguageField( $hashmain, $_ihs, $innl, $$hashmain{_tbnaam} );
			my @languages = @{$$_ihs{_languages}};
			$$hashmain{$$_ihs{_languagefield}} = $languages[0]->{_language};
			$data = bewaarrecord( $hashmain, $_ihs, $innl, 1); # de eerste kan altijd geupdate worden
			traceme( $hashmain, $_ihs, "exit multilanguage bewaarrecord", __LINE__ ) if $$_ihs{__systemtrace__} || $tracesaving;
			if ( $data eq '' ){
				my $newrecordfound = 1;
				my $teller = 1;
				my $orgfield;
				while ( $newrecordfound == 1 ){
					$newrecordfound = 0;
					my $fldkey = 'xxx' . $teller;
					foreach my $fld ( $cgi->param ){
						if ( $fld =~ /$fldkey$/ ){
							$newrecordfound = 1;
							$orgfield = $fld;
							$orgfield =~ s/(.*)($fldkey)/$1/;
							$$hashmain{$orgfield} = $$hashmain{$fld};
							$$hashmain{$$_ihs{_languagefield}} = $languages[$teller]->{_language};
							traceme( $hashmain, $_ihs, "$fldkey FOUND for $orgfield, language key $$_ihs{_languagefield} = $languages[$teller]->{_language}", __LINE__ ) if $$_ihs{__systemtrace__};
						}	
					}
					if ( $newrecordfound == 1 ){
						traceme( $hashmain, $_ihs, "bewaaarrecord", __LINE__ ) if ( $$_ihs{__systemtrace__} );
						if ( $$hashmain{_action} eq 'insert' ){
							$$hashmain{_recordvalue} = 0;
							traceme( $hashmain, $_ihs, "_recordkey = $$hashmain{_recordkey}", __LINE__ ) if ( $$_ihs{__systemtrace__} );
						}
						#listKeys( $hashmain, $_ihs, '', ('--- just before bewaarrecord --- ' ), ( "Ix" . __LINE__ ) ); 
						traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__} >= 3;
						$$hashmain{__recordcount}++;
						$data = bewaarrecord( $hashmain, $_ihs, $innl, 1);
						traceme( $hashmain, $_ihs, "exitbewaarrecord", __LINE__ ) if $$_ihs{__systemtrace__} || $tracesaving;
						last if ( $data ne '' );
					}	
					$teller++;
				}
			}
		}
		else{ #action bewaar, not multilangual	
			traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
			if ( $$hashmain{_tbnaam} eq 'sys_import' ){
				traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
				my $languageselected = 0;
				$$hashmain{imp_type} = 'D'; #data import
				my @flds = qw( 
					imp_langenglish imp_langdutch imp_langchinese imp_langspanish imp_langarabic imp_langhindi imp_langportugese imp_langrussian imp_langgerman 
				);
				foreach ( @flds ){
					if ( defined $$hashmain{$_} ){
						traceme( $hashmain, $_ihs, "$_ = $$hashmain{$_}", __LINE__ ) if $$_ihs{__systemtrace__} >= 3;
						$languageselected++ if ( $$hashmain{$_} == 1 );
					}
				}
				traceme( $hashmain, $_ihs, "languageselected $languageselected", __LINE__ ) if ( $$_ihs{__systemtrace__} );
				$$hashmain{_csi} = $$hashmain{_prevcsi}; #csi should stay the same
				if ( ! (defined $$hashmain{imp_sepcomma} || defined $$hashmain{imp_sepnone} ||
						defined $$hashmain{imp_septab} || defined $$hashmain{imp_sepsemic} )){ #none of the choices is made
					throwTopErrorMessage( $hashmain, $_ihs, $innl, 'import-choose-divider'); 
					$$_ihs{_errormessagecode} = 'import-choose-divider';
					$$_ihs{_throwingerror} = 1;
					( $data, $hashmain) = selectrecord( $hashmain, $_ihs, $innl, 'update' );
					traceme( $hashmain, $_ihs, $$hashmain{_action} . "exit selectrecord" , __LINE__ ) if $$_ihs{__systemtrace__} || $tracesaving;
				}
				elsif ( $languageselected == 0 ){#no language selected
					traceme( $hashmain, $_ihs, "languageselected $languageselected", __LINE__ ) if ( $$_ihs{__systemtrace__} );
					throwTopErrorMessage( $hashmain, $_ihs, $innl, 'import-choose-language'); 
					$$_ihs{_throwingerror} = 1;
					$$_ihs{_errormessagecode} = 'import-choose-language';
					( $data, $hashmain) = selectrecord( $hashmain, $_ihs, $innl, 'update' );
					traceme( $hashmain, $_ihs, $$hashmain{_action} . "exit selectrecord" , __LINE__ ) if $$_ihs{__systemtrace__} || $tracesaving;
				}
				else{ #all ok!
					traceme( $hashmain, $_ihs, "languageselected $languageselected", __LINE__ ) if ( $$_ihs{__systemtrace__} );
					traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__} >= 2;
					$$hashmain{imp_status} = 1;
					$data = bewaarrecord( $hashmain, $_ihs, $innl, 1);
					traceme( $hashmain, $_ihs, "exitbewaarrecord", __LINE__ ) if $$_ihs{__systemtrace__} || $tracesaving;
				}
			}
			#elsif ( $$hashmain{_tbnaam} eq 'sys_importuser' ){
			#	$data = bewaarrecord( $hashmain, $_ihs, $innl, 1);
			#	traceme( $hashmain, $_ihs, "exitbewaarrecord", __LINE__ ) if $$_ihs{__systemtrace__} || $tracesaving;
			#}
			else{
				$data = bewaarrecord( $hashmain, $_ihs, $innl, 1);
				traceme( $hashmain, $_ihs, "exitbewaarrecord", __LINE__ ) if $$_ihs{__systemtrace__} || $tracesaving;
			}
			if ( $$hashmain{_tbnaam} eq 'sys_importuser' ){
				$$hashmain{imp_type} = 'U'; #user import
				#$$hashmain{imp_code} = "";
				#$$hashmain{imp_id} = $$hashmain{ui_id};
				$$hashmain{imp_name} = "User import";
				doStepofImport( $hashmain, $_ihs, $innl, 1 ); #ready to configure
				traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
				( $data, $hashmain) = waitforImportToFinish( $hashmain, $_ihs, $innl );
			}
			if ( $$hashmain{_tbnaam} eq 'sys_import' && $$_ihs{_throwingerror} == 0 ){
				doStepofImport( $hashmain, $_ihs, $innl, 1 ); #ready to configure
				#while import is still being bust
				traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
				( $data, $hashmain) = waitforImportToFinish( $hashmain, $_ihs, $innl );
			}
		}
		#action bewaar
		traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
		if ( exists $$hashmain{_stay} && $$_ihs{_throwingerror} == 0 ){ 
			if ( $$hashmain{_stay} eq 'yes' ){ 
				#setIdentifier( $hashmain, $session, $innl );
			}
		}
	}
	#action bewaar
	my $_exitpointtxt = "END POINT. SAVE OF RECORD COMPLETED. Errors: " . $$hashmain{_errorcount} . ", Warnings: " . $$hashmain{_warningcount};
	traceme( $hashmain, $_ihs, $_exitpointtxt, __LINE__ ) if ( $$_ihs{__systemtrace__} );
	if ( $$hashmain{_errorcount} == 0 && $$hashmain{_warningcount} == 0 && $$_ihs{_designcommit} ){
		traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
		commitDesignChange( $hashmain, $_ihs, $innl, $$hashmain{_tbnaam} ); 
		if ( $$_ihs{_throwingerror} ){
			$$hashmain{_csi} = $$hashmain{_prevcsi}; #csi should stay the same
			traceme( $hashmain, $_ihs, "_csi: $$hashmain{_csi}, _prevcsi: $$hashmain{_prevcsi} new _csi ", __LINE__ ) if $tracecsi || $$_ihs{__systemtrace__};
			determineTabStyle( $hashmain, $_ihs, $innl, ( 'Ix' . __LINE__ ) );
			( $data, $hashmain) = selectrecord( $hashmain, $_ihs, $innl, 'update' );
			traceme( $hashmain, $_ihs, $$hashmain{_action} . "exit selectrecord" , __LINE__ ) if $$_ihs{__systemtrace__} || $tracesaving;
		}
	}
	if ( $data eq '' && $$_ihs{_throwingerror} == 0 ){ #data is saved and no errors
		traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
		if ( $$hashmain{_nextaction} ne '' ){ #continuation after button action f.i. next page
			traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__};
			$$hashmain{_action} = $$hashmain{_nextaction};
			$$_ihs{_actualaction} = $$hashmain{_action};
			traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__};
			$$hashmain{_tbnaam} = provideTablenameFromId( $hashmain, $_ihs, $innl, $$hashmain{_xsplimn}, __LINE__ );
			$$hashmain{_tgrndds} = $$hashmain{_xsplimn};
			determineTabStyle( $hashmain, $_ihs, $innl, ( 'Ix' . __LINE__ ) );
			if($$hashmain{_action} eq 'update'  || $$hashmain{_action} eq 'insert'){
				traceme( $hashmain, $_ihs, "_recordkey = $$hashmain{_recordkey}", __LINE__ ) if $$_ihs{__systemtrace__};
				#setIdentifier( $hashmain, $session, $innl );
				( $data, $hashmain) = selectrecord( $hashmain, $_ihs, $innl, $$hashmain{_action} );
				traceme( $hashmain, $_ihs, $$hashmain{_action} . "exit selectrecord" , __LINE__ ) if $$_ihs{__systemtrace__} || $tracesaving;
				if ( $data eq '' ){
					$$hashmain{_action} = 'select';
					$$_ihs{_actualaction} = $$hashmain{_action};
					( $data, $hashmain ) = showContentInTable( $hashmain, $_ihs, $innl);
					traceme( $hashmain, $_ihs, $$hashmain{_action} . "exit showContentInTable" , __LINE__ ) if $$_ihs{__systemtrace__} || $tracesaving;
				}
			}
			elsif ( $$hashmain{_action} eq 'select' || $$hashmain{_action} eq 'show' ){
				( $data, $hashmain ) = showContentInTable( $hashmain, $_ihs, $innl);
				traceme( $hashmain, $_ihs, $$hashmain{_action} . "exit showContentInTable" , __LINE__ ) if $$_ihs{__systemtrace__} || $tracesaving;
			}
		}
		#action bewaar
		else{ #this is the standard way of continuation, without button action
			traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__};
			$$hashmain{_selectyear} = $$_ihs{_year};
			$$hashmain{_selmaand} = $$_ihs{_month};
			traceme( $hashmain, $_ihs, "TRC ", __LINE__ ) if $tracesession;
			my $sessionFound = 0;
			if ( $$_ihs{_parentcsi} ne '' ){ #we need to go back to this csi.
				if ( intelligentGetPreviousSequence( $hashmain, $_ihs, $innl) == 1 ){#found
					$sessionFound =  1;
					$$hashmain{_action} = $$_ihs{_parentaction};
				}
				else{
					$$hashmain{_action} = 'select';
				}
			}
			else{
				traceme( $hashmain, $_ihs, "TRC This can only happen if table is directly updated without select first.", __LINE__ );
				my $tabnr  = @{$$_ihs{_SessSeq}}[$$_ihs{_curIntSeqNr}]->{_tab_nr};
				my $tabgrp = @{$$_ihs{_SessSeq}}[$$_ihs{_curIntSeqNr}]->{_tab_grp};
				foreach ( reverse( @{$$_ihs{_SessSeq}} ) ){
					if ( $tabnr > 0 ){
						if ( $$_{_action} eq 'select' && $$_{_tab_nr} == $tabnr && $$_{_tab_grp} eq $tabgrp ){
							$$_ihs{_curVolgNr} = $$_{volg_nr};
							$$_ihs{_curIntSeqNr} = $$_{volg_nr} - 1;
							$sessionFound = 1;
							last;
						}
					}
					else{
						if ( $$_{_action} eq 'select' ){
							$$_ihs{_curVolgNr} = $$_{volg_nr};
							$$_ihs{_curIntSeqNr} = $$_{volg_nr} - 1;
							$sessionFound = 1;
							last;
						}
					}
				}
				$$hashmain{_action} = 'select';
			}
			$$_ihs{_actualaction} = $$hashmain{_action};
			traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
			if ( $sessionFound ){
			traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
				$$hashmain{_tbnaam} = @{$$_ihs{_SessSeq}}[$$_ihs{_curIntSeqNr}]->{tb_id};
				$$hashmain{_mit} = @{$$_ihs{_SessSeq}}[$$_ihs{_curIntSeqNr}]->{_mit};
				$$hashmain{_tab} = @{$$_ihs{_SessSeq}}[$$_ihs{_curIntSeqNr}]->{_tab_nr};
				$$_ihs{_tab_grp} = @{$$_ihs{_SessSeq}}[$$_ihs{_curIntSeqNr}]->{_tab_grp};
				$$hashmain{_recordvalue} = @{$$_ihs{_SessSeq}}[$$_ihs{_curIntSeqNr}]->{_recordvalue};
				$$hashmain{_searchkeyword} = @{$$_ihs{_SessSeq}}[$$_ihs{_curIntSeqNr}]->{_searchkeyword} if ( $$_ihs{_orgsearchwordstat} == 1 ); #not exist
				$$hashmain{_sortorder} = @{$$_ihs{_SessSeq}}[$$_ihs{_curIntSeqNr}]->{_sortorder};
			}
			determineTabStyle( $hashmain, $_ihs, $innl, ( 'Ix' . __LINE__ ) );
			traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
			( $data, $hashmain ) = showContentInTable( $hashmain, $_ihs, $innl);
			traceme( $hashmain, $_ihs, $$hashmain{_action} . "exit showContentInTable" , __LINE__ ) if $$_ihs{__systemtrace__} || $tracesaving;
		}
	}
	return ( $data, $hashmain );
}

#-marker SUB executeactionSelectRecord

sub executeactionSelectRecord {
	my ( $hashmain, $_ihs, $innl, $session ) = @_;
	my $dbh = $innl->dbh();
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	my $sql;
	my $data;
	if ( $$hashmain{_nextaction} ne '' ){# we don't want to do an insert, we want to switch to _tbnaam initiated by a button
		traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__};
		$$hashmain{_action}		= $$hashmain{_nextaction};
		$$_ihs{_actualaction}	 = $$hashmain{_action};
		$$_ihs{_tbprev}		   = $$hashmain{_tbnaam};
		$$_ihs{_tbprevid}		 = $$hashmain{_tbprevid};
		$$hashmain{_tbnaam}	   = $$hashmain{_nextparam};
		$$hashmain{_tabelnaam}	= $$hashmain{_nextparam};
		$$hashmain{_recordvalue}  = $$hashmain{_nextid};
		$$hashmain{_recordkey}	= $$hashmain{_nextkey};
		traceme( $hashmain, $_ihs, "_tbprev: $$_ihs{_tbprev}", __LINE__ ) if $$_ihs{__systemtrace__};
		traceme( $hashmain, $_ihs, "_recordkey = $$hashmain{_recordkey}", __LINE__ ) if $$_ihs{__systemtrace__};
		determineTabStyle( $hashmain, $_ihs, $innl, ( 'Ix' . __LINE__ ) );
		if( $$hashmain{_action} eq 'insert' || $$hashmain{_action} eq 'insert'){ #the new action that is
			traceme( $hashmain, $_ihs, "_recordkey = $$hashmain{_recordkey}", __LINE__ ) if $$_ihs{__systemtrace__};
			#setIdentifier( $hashmain, $session, $innl );
			( $data, $hashmain) = selectrecord( $hashmain, $_ihs, $innl, $$hashmain{_action} );
			traceme( $hashmain, $_ihs, $$hashmain{_action} . "exit selectrecord" , __LINE__ ) if $$_ihs{__systemtrace__} || $tracesaving;
			if ( $data eq '' ){
				$$hashmain{_action} = 'select';
				$$_ihs{_actualaction} = $$hashmain{_action};
				( $data, $hashmain ) = showContentInTable( $hashmain, $_ihs, $innl);
				traceme( $hashmain, $_ihs, $$hashmain{_action} . "exit showContentInTable" , __LINE__ ) if $$_ihs{__systemtrace__} || $tracesaving;
			}
		}
		elsif ( $$hashmain{_action} eq 'select' || $$hashmain{_action} eq 'show' ){
			( $data, $hashmain ) = showContentInTable( $hashmain, $_ihs, $innl);
			traceme( $hashmain, $_ihs, $$hashmain{_action} . "exit showContentInTable" , __LINE__ ) if $$_ihs{__systemtrace__} || $tracesaving;
		}
	}
	elsif( $$hashmain{_action} eq 'update'  || $$hashmain{_action} eq 'next' || $$hashmain{_action} eq 'insert'  ){#exclude select
		traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__};
		traceme( $hashmain, $_ihs, "_recordkey = $$hashmain{_recordkey}", __LINE__ ) if $$_ihs{__systemtrace__};
		#setIdentifier( $hashmain, $session, $innl );
		if ( ( $$hashmain{_tbnaam} eq 'sys_import' || $$hashmain{_tbnaam} eq 'sys_importuser' ) && ( $$hashmain{_action} eq 'update'  || $$hashmain{_action} eq 'next' )){
			$$hashmain{imp_type} = $$hashmain{_tbnaam} eq 'sys_import' ? 'D' : 'U';
			getSessionFields ( $hashmain, $_ihs, $innl );
			if ( not defined $$hashmain{imp_code} ){#we re-enter the import record
				$$hashmain{$$hashmain{_recordkey}}   = $$hashmain{_recordvalue};
				#my $fld = $$hashmain{_tbnaam} eq 'sys_import' ? 'imp_code' : 'ui_impcode';
				$$hashmain{imp_type} = $$hashmain{_tbnaam} eq 'sys_import' ? 'D' : 'U';
				$sql  = "SELECT imp_code FROM " . $$hashmain{_tbnaam} . " ";
				$sql .= "WHERE " . $$hashmain{_recordkey} . " = " . $$hashmain{_recordvalue} ;
				traceme( $hashmain, $_ihs, "SQL $sql", __LINE__ ) if $$_ihs{__systemtrace__};
				$$hashmain{imp_code} = $dbh->selectrow_array( $sql );
			}
			( $data, $hashmain ) = waitforImportToFinish( $hashmain, $_ihs, $innl );
		}
		else{
			( $data, $hashmain) = selectrecord( $hashmain, $_ihs, $innl, $$hashmain{_action} );
			traceme( $hashmain, $_ihs, $$hashmain{_action} . "exit selectrecord" , __LINE__ ) if $$_ihs{__systemtrace__} || $tracesaving;
		}
		if ( $data eq '' ){
			$$hashmain{_action} = 'select';
			$$_ihs{_actualaction} = $$hashmain{_action};
			( $data, $hashmain ) = showContentInTable( $hashmain, $_ihs, $innl);
			traceme( $hashmain, $_ihs, $$hashmain{_action} . "exit showContentInTable" , __LINE__ ) if $$_ihs{__systemtrace__} || $tracesaving;
		}
	}
	return ( $data, $hashmain );
}

sub executeactionSavePassword {
	my ( $hashmain, $_ihs, $innl ) = @_;
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	my $sql;
	my $data;
	#we dont get the id of the user so we collect it from the previous record
	$$hashmain{_recordvalue} = @{$$_ihs{_SessSeq}}[$$_ihs{_curIntSeqNr} - 1]->{_recordvalue};
	$$hashmain{_gebruikernaam} = @{$$_ihs{_SessSeq}}[$$_ihs{_curIntSeqNr} - 1]->{gb_id};
	if( ! savePassword( $hashmain, $_ihs, $innl ) ){
		$$hashmain{_action} = 'update';
		$$hashmain{_tbnaam} = 'sys_user';
		$$_ihs{_actualaction} = $$hashmain{_action};
		$$hashmain{_recordkey} = 'id';
		traceme( $hashmain, $_ihs, "_recordkey = $$hashmain{_recordkey}", __LINE__ ) if $$_ihs{__systemtrace__};
		#$$hashmain{_recordvalue} = $$hashmain{_dwXbxPpw5oeWqR};
		( $data, $hashmain) = selectrecord( $hashmain, $_ihs, $innl, $$hashmain{_action} );
		traceme( $hashmain, $_ihs, $$hashmain{_action} . "exit selectrecord" , __LINE__ ) if $$_ihs{__systemtrace__} || $tracesaving;
		if ( $data eq '' ){
			$$hashmain{_action} = 'select';
			$data = showContentInTable( $hashmain, $innl);
			traceme( $hashmain, $_ihs, $$hashmain{_action} . "exit showContentInTable" , __LINE__ ) if $$_ihs{__systemtrace__} || $tracesaving;
		}
	}
	else{#no success
		$$hashmain{_psswrdnomatch} = getSysMessage( $hashmain, $innl, 'psswrdnomatch');
		$$hashmain{_action} = '_chpw';
		$data = executeactionChangePassword( $hashmain, $_ihs, $innl );
	}
	return ( $data, $hashmain );
}

sub showIndexPage {
	my ( $hashmain, $_ihs, $innl, $line ) = @_;
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	genNieuws( $hashmain, $_ihs, $innl );
	genPresence( $hashmain, $_ihs, $innl );
	if ( $$hashmain{_action} eq 'reference' ){
		createReferenceTiles( $hashmain, $_ihs, $innl );
		if ( intelligentGetSequence( $hashmain, $_ihs, $innl ) == -1 ){
			intelligentInsertSequence( $hashmain, $_ihs, $innl, __LINE__ );
		}
	}
	else{
		createTiles( $hashmain, $_ihs, $innl );
	}
	$$_ihs{_finaltemplatemethod} = $normalshow;
	$$_ihs{_finaltemplate} = $$_ihs{_loggedin_startpage};
	return showPage($innl, $$_ihs{_loggedin_startpage}, $hashmain);
}

sub executeactionResetPassword {
	my ( $hashmain, $_ihs, $innl ) = @_;
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	my $sql;
	my $data;
	$$hashmain{_tbnaam} = 'sys_user';
	$$hashmain{_tgrndds} = provideTableId( $hashmain, $_ihs, $innl, $$hashmain{_tbnaam} ); 
	$sql  = "SELECT * FROM sys_user "; #the reset link will look for id while logged in....
	$sql .= "WHERE id = ? ";
	traceme( $hashmain, $_ihs, "SQL $sql", __LINE__ ) if $$_ihs{__systemtrace__};
	my $tmpuser = ParamPrepAndFetch( $hashmain, $_ihs, $innl, $sql, $$hashmain{_recordvalue}, ('Ix' . __LINE__ ) );
	if ( $$tmpuser{gb_email} eq '' ){#if imported the email can be empty
		throwTopErrorMessage( $hashmain, $_ihs, $innl, 'user-reset-nomail'); 
		$$_ihs{_errormessagecode} = 'user-reset-nomail';
		$$_ihs{_throwingerror} = 1;
		traceme( $hashmain, $_ihs, "_throwingerror ", __LINE__ ) ;
		( $data, $hashmain) = selectrecord( $hashmain, $_ihs, $innl,  'update'); 
		traceme( $hashmain, $_ihs, $$hashmain{_action} . "exit selectrecord" , __LINE__ ) if $$_ihs{__systemtrace__} || $tracesaving;
		return ( $data, $hashmain );
	}
	$sql  = "SELECT * FROM custmdbm.sys_user ";
	$sql .= "WHERE companycode = '" . $$hashmain{_companycode} . "' ";
	$sql .= "AND gb_id = '" . $$tmpuser{gb_id} . "' ";
	traceme( $hashmain, $_ihs, "SQL $sql", __LINE__ ) if $$_ihs{__systemtrace__};
	my $curuser = PrepAndFetchQuery( $hashmain, $_ihs, $innl, $sql, ('Ix' . __LINE__ ) );
	$hashmain = {%$hashmain, %$curuser};
	traceme( $hashmain, $_ihs, "_functie: $$hashmain{_functie}", __LINE__ ) if $$_ihs{__systemtrace__};
	if(  ! validRolePermission( $hashmain, $_ihs, "16" ) && $$hashmain{_gb_id} ne $$hashmain{gb_id} ){ #only beheerder isallowed to request a reset for someone else 
		traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__};
		throwTopErrorMessage( $hashmain, $_ihs, $innl, 'user-reset-error'); 
		$$_ihs{_errormessagecode} = 'user-reset-error';
		traceme( $hashmain, $_ihs, "_throwingerror ", __LINE__ ) ;
		$$_ihs{_throwingerror} = 1;
		( $data, $hashmain) = selectrecord( $hashmain, $_ihs, $innl,  'update'); #$$hashmain{_action} );
		traceme( $hashmain, $_ihs, $$hashmain{_action} . "exit selectrecord" , __LINE__ ) if $$_ihs{__systemtrace__} || $tracesaving;
	}
	else{
		traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__};
		if ( sendPasswordResetLink( $hashmain, $_ihs, $innl, 'existinguser' ) == 0 ){
			$$_ihs{_errormessagecode} = 'user-reset';
			traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__};
			$$_ihs{_goodmessage} = 'user-reset';
			#throwTopGoodMessage( $hashmain, $_ihs, $innl, 'user-reset');
		}
		else {#something went wrong. Errormessage is set
			traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__};
			$$_ihs{_errormessagecode} = 'user-reset-error';
			$$_ihs{_throwingerror} = 1;
			traceme( $hashmain, $_ihs, "_throwingerror ", __LINE__ ) ;
			throwTopErrorMessage( $hashmain, $_ihs, $innl, 'user-reset-error'); 
		}
		( $data, $hashmain) = selectrecord( $hashmain, $_ihs, $innl,  'update'); #$$hashmain{_action} );
		traceme( $hashmain, $_ihs, $$hashmain{_action} . "exit selectrecord" , __LINE__ ) if $$_ihs{__systemtrace__} || $tracesaving;
	}
	traceme( $hashmain, $_ihs, $$hashmain{_action} . " $$_ihs{_throwingerror}" , __LINE__ ) if $$_ihs{__systemtrace__} || $tracesaving;
	return ( $data, $hashmain );
}

sub newExecuteactionResetPassword {
	my ( $hashmain, $_ihs, $innl ) = @_;
	my $dbh = $innl->dbh();
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	my $sql;
	my $data;
	if ( intelligentGetSequence( $hashmain, $_ihs, $innl ) == -1 ){
		intelligentInsertSequence( $hashmain, $_ihs, $innl, __LINE__ );
		intelligentUpdateSequence( $hashmain, $_ihs, $innl,{ _recordvalue => $$hashmain{_response} } );
	}
	my $password = { _passwordfield  => 'rs_pworg' };
	$$password{_passwordnomatch}	 = getSysMessage( $hashmain, $innl, 'psswrdnomatch');
	$$password{_passworderrortext}   = getSysMessage( $hashmain, $innl, 'password-not-empty');
	$$password{_passworderrortext2}  = getSysMessage( $hashmain, $innl, 'password-min-requirement');
	$$password{_passwordlongerrtext} = getSysMessage( $hashmain, $innl, 'password-longerror');
	if ( $$hashmain{_action} eq '_chpw'){#we are logged in
		$$hashmain{_mapopenbanner}   = intelligentBreadcrumLabel( $hashmain, $_ihs, $innl, $$hashmain{_action} );
		$$hashmain{_showbutback}	 = getSyslable( $dbh, $$hashmain{_language}, 'butback' );
		$$hashmain{_extrabutton}	 = showGenericPage( $hashmain, $innl , $_ihs, 'button.back' );
		$$hashmain{_buttontop}	  .= showGenericPage( $hashmain, $innl , $_ihs, 'button.back.top' );
		$$hashmain{_topbuttonssmall} = showGenericPage($hashmain, $innl, $_ihs, 'form.button.top' );
		$$hashmain{_action} = "_svpw";
		#first passwordfield
		$$password{_passwordlable}   = getSyslable( $dbh, $$hashmain{_language}, 'oldpw' );
		$$hashmain{_savetext}		= getSyslable( $dbh, $$hashmain{_language}, 'save' );
		$$password{_passwordrow_old} = showLocalPage($password, $innl, 'tabelrecordinhoud.form.password.row' );
	
		$$hashmain{_javabottomfunctions} .= showGenericPage($password, $innl, $_ihs, 'javascript.bottom.pw.eye' );
		$$hashmain{_javafieldvalidatie}  .= showGenericPage($password, $innl, $_ihs, 'javascript.bottom.pw.validate.len' );
		#$$hashmain{_javafieldvalidatie}  .= showGenericPage($password, $innl, $_ihs, 'javascript.bottom.pw.validate.strength' );
	}
	else{
		$$hashmain{_action} = "bewaar";
	}
	#first passwordfield
	my $password1 = { _passwordfield  => 'rs_pw' };
	$$password1{_passwordlable}	   = getSyslable( $dbh, $$hashmain{_language}, 'newpw' );
	$$password1{_passwordsecondfield} = 'rs_pw2';
	$$hashmain{_savetext}			 = getSyslable( $dbh, $$hashmain{_language}, 'save' );
	$$password1{_passworderrortext}   = $$password{_passworderrortext};
	$$password1{_passworderrortext2}  = $$password{_passworderrortext2};
	$$password1{_passwordnomatch}	 = $$password{_passwordnomatch};
	$$password1{_passwordstrenght}	= showLocalPage($password1, $innl, 'tabelrecordinhoud.form.password.strength' );
	$$password{_passwordrow_a}	   = showLocalPage($password1, $innl, 'tabelrecordinhoud.form.password.row' );

	$$hashmain{_javabottomfunctions} .= showGenericPage($password1, $innl, $_ihs, 'javascript.bottom.pw.eye' );
	$$hashmain{_javabottomfunctions} .= showGenericPage($password1, $innl, $_ihs, 'javascript.bottom.pw.strength' );
	$$hashmain{_javabottomfunctions} .= showGenericPage($password1, $innl, $_ihs, 'javascript.bottom.pw.confirm' );
	$$hashmain{_javafieldvalidatie}  .= showGenericPage($password1, $innl, $_ihs, 'javascript.bottom.pw.validate.len' );
	$$hashmain{_javafieldvalidatie}  .= showGenericPage($password1, $innl, $_ihs, 'javascript.bottom.pw.validate.strength' );

	#second passwordfield
	my $password2 = { _passwordfield  => $$password1{_passwordsecondfield} };
	$$password2{_passwordlable}	   = getSyslable( $dbh, $$hashmain{_language}, 'repeatpw' );
	$$password2{_passworderrortext}   = $$password1{_passworderrortext};
	$$password2{_passworderrortext}   = $$password{_passworderrortext};
	$$password2{_passworderrortext2}  = $$password{_passworderrortext2};
	$$password2{_passwordnomatch}	 = $$password{_passwordnomatch};
	$$password2{_passwordstrenght}	= ''; #strength meter only with first pw

	$$password{_passwordrow_b}	   = showLocalPage($password2, $innl, 'tabelrecordinhoud.form.password.row' );
	$$hashmain{_javabottomfunctions} .= showGenericPage($password2, $innl, $_ihs, 'javascript.bottom.pw.eye' );
	$$hashmain{_javafieldvalidatie}  .= showGenericPage($password2, $innl, $_ihs, 'javascript.bottom.pw.validate.len' );
	$$hashmain{_javafieldvalidatie}  .= showGenericPage($password1, $innl, $_ihs, 'javascript.bottom.pw.compare' );
	#get the javascript completed
	$$hashmain{_javascriptotherfunctions} .= showGenericPage( $hashmain, $innl, $_ihs, 'javascript.bottom.formvalidate' );
	$$hashmain{_indexbody}  = showLocalPage( {%$password, %$hashmain}, $innl, 'tabelrecordinhoud.form.password' );
}

sub executeactionChangePassword {
	my ( $hashmain, $_ihs, $innl ) = @_;
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	my $sql;
	my $data;
	#$$hashmain{_dwXbxPpw5oeWqR}  = $$hashmain{_recordvalue};
	$$hashmain{_psswrdnomatch}   = getSysMessage( $hashmain, $innl, 'psswrdnomatch');
	newExecuteactionResetPassword( $hashmain, $_ihs, $innl );
	$data = $$hashmain{_indexbody};
	return $data;
}

sub provideTablenameFromId {
	my ( $hashmain, $_ihs, $innl, $id, $line ) = @_;
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	my $sql;
	return '' if ( $id <= 0 );
	$sql  = "SELECT tb_id AS _tbnaam FROM sys_tableadmin ";
	$sql .= "WHERE ds_id = " . $id . " ";
	$sql .= "AND aktief = 'Ja' ";
	traceme( $hashmain, $_ihs, $sql, __LINE__ ) if $$_ihs{__syssqltrace__};
	my $tbres = PrepAndFetchQuery( $hashmain, $_ihs, $innl, $sql, ('Ix' . __LINE__ ) );
	traceme( $hashmain, $_ihs, "[$line] provideTablenameFromId with id ($id), found $$tbres{_tbnaam}", __LINE__ ) if $$_ihs{__systemtrace__};
	return $$tbres{_tbnaam};
}

sub findPrevious_csi {
	my ( $hashmain, $_ihs, $innl, $csi ) = @_;
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  || $tracecsi );

	#if a refresh is done the _csi will be refreshed and not found
	my $sql;
	foreach my $p ( reverse( @{$$_ihs{_SessSeq}} ) ){#is it a refresh?
		if ( $$p{volg_nr} >= $$_ihs{_curVolgNr} ){ #previous one has a smaller volgnr.
		}
		else{
			if ( $csi eq $$p{_csi} ){
				$$_ihs{_prevVolgNr} = $$p{volg_nr};
				$$_ihs{_prevcsiIntSeqNr} = $$p{volg_nr} - 1;
				$$_ihs{_prevcsiFound} = 1;
				traceme( $hashmain, $_ihs, "_csi: $$hashmain{_csi}, _prevcsi: $$hashmain{_prevcsi} FOUND $$p{_csi}  at volgnr $$p{volg_nr} ", __LINE__ ) if $tracecsi;
				return 1;
			}
		}
	}
	return 0;
}

sub validatePrevious_csi {
	my ( $hashmain, $_ihs, $innl ) = @_;
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	#if a refresh is done the _csi will be refreshed and not found
	traceme( $hashmain, $_ihs, "_csi: $$hashmain{_csi}, _prevcsi: $$hashmain{_prevcsi} Looking for _prevcsi ", __LINE__ ) if $tracecsi;
	my $sql;
	if ( not defined $$hashmain{_prevcsi} ){
		#listKeys( $hashmain, $_ihs, 'all', ('--- missing (' . __LINE__ . ') _prevcsi at start--- ' ), ( "Ix" . __LINE__ ) ); 
	}
	elsif ( $$_ihs{_curIntSeqNr} >= 0 ){
		traceme( $hashmain, $_ihs, "_csi: $$hashmain{_csi}, _prevcsi: $$hashmain{_prevcsi} _curIntSeqNr >= 0?", __LINE__ ) if $tracecsi;
		foreach ( reverse( @{$$_ihs{_SessSeq}} ) ){#is it a refresh?
			#if ( $$_{_prevcsi} eq  $$hashmain{_prevcsi} && $$_{_action} eq  $$hashmain{_action} ){
			if ( $$_{_csi} eq  $$hashmain{_prevcsi} && $$_{_action} eq  $$hashmain{_action} ){
				$$_ihs{_csiFound} = 1;
				$$_ihs{_curIntSeqNr} = $$_{volg_nr} - 1;
				$$_ihs{_curVolgNr} = $$_{volg_nr};
				$$_ihs{_tab_grp} = $$_{_tab_grp};
				#$$hashmain{_csi} = $$_{_csi};
				traceme( $hashmain, $_ihs, "_csi: $$hashmain{_csi}, _prevcsi: $$hashmain{_prevcsi} FOUND with action $$hashmain{_action}", __LINE__ ) if $tracecsi;
				findPrevious_csi( $hashmain, $_ihs, $innl, $$_{_prevcsi} );
				last;
			}
		}
		if ( $$_ihs{_csiFound} == 0 ){
			traceme( $hashmain, $_ihs, "_csi: $$hashmain{_csi}, _prevcsi: $$hashmain{_prevcsi} NOT FOUND ", __LINE__ ) if $tracecsi;
			foreach ( reverse( @{$$_ihs{_SessSeq}} ) ){	
				traceme( $hashmain, $_ihs, "_csi: $$hashmain{_csi}, _prevcsi: $$hashmain{_prevcsi} ", __LINE__ ) if $tracecsi;
				if ( $$_{_csi} eq  $$hashmain{_prevcsi} ){
					traceme( $hashmain, $_ihs, "_csi: $$hashmain{_csi}, _prevcsi: $$hashmain{_prevcsi} ", __LINE__ ) if $tracecsi;
					$$_ihs{_csiFound} = 1;
					$$_ihs{_curIntSeqNr} = $$_{volg_nr} - 1;
					$$_ihs{_curVolgNr} = $$_{volg_nr};
					$$_ihs{_tab_grp} = $$_{_tab_grp};
					findPrevious_csi( $hashmain, $_ihs, $innl, $$_{_prevcsi} );
					traceme( $hashmain, $_ihs, "_csi: $$hashmain{_csi}, _prevcsi: $$hashmain{_prevcsi} FOUND without action $$hashmain{_action}", __LINE__ ) if $tracecsi;
					last;
				}
			}
			if ( $$_ihs{_csiFound} == 0 ){
				traceme( $hashmain, $_ihs, "_csi: $$hashmain{_csi}, _prevcsi: $$hashmain{_prevcsi} NOT FOUND ", __LINE__ ) if $tracecsi;
			}
		}
		else{
			traceme( $hashmain, $_ihs, "_csi: $$hashmain{_csi}, _prevcsi: $$hashmain{_prevcsi} FOUND ", __LINE__ ) if $tracecsi;
		}
	}
}
	
sub initEnableCustomerDb {
	my ( $hashmain, $_ihs, $innl, $session ) = @_;
	my $dbh = $innl->dbh();
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	my $sql;
	$dbh->{'mysql_enable_utf8'} = 1;
	$dbh->do('set names utf8');
	#I'm in the right database now
	$$_ihs{_captcharequired} = 0; #once logged in a captcha is no longer required.
	$$hashmain{_cssfile}   .= showGenericPage($hashmain, $innl, $_ihs, 'raplico.loggedin' );
	$$hashmain{_captcha_check}  = 'Nee';
	$$hashmain{_fieldformatloggedin} = 'c_qm_r';
	$$hashmain{_logopicture} = getLogo ( $hashmain, $_ihs, $innl );
	
	$$hashmain{_showlogo} = showLocalPage($hashmain, $innl, 'showlogo' );
	if ( $$hashmain{_tgrndds} ){ #this holds the id for the tablename
		traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__};
		$$hashmain{_tbnaam} = provideTablenameFromId( $hashmain, $_ihs, $innl, $$hashmain{_tgrndds}, __LINE__ );
		#my $log = "_tgrndds = $$hashmain{_tgrndds}, tbnaam: $$hashmain{_tbnaam}, action $$hashmain{_action}, _recordkey $$hashmain{_recordkey}, _recordvalue $$hashmain{_recordvalue} ";
		#$log   .= "_sortfld $$hashmain{_sortfld} " if ( defined $$hashmain{_sortfld} );
		#$log   .= "_sortorder $$hashmain{_sortorder} " if ( defined $$hashmain{_sortorder} );
		#traceme( $hashmain, $_ihs, $log, __LINE__ ) if $$_ihs{__systemtrace__};
	}
	else{
		#traceme( $hashmain, $_ihs, "action: $$hashmain{_action} NO _tgrndds", __LINE__ ) if $$_ihs{__systemtrace__};
	}
	newBootstrapValues( $hashmain, $_ihs );
	#fetching the new values
	getPageDefaults( $hashmain, $_ihs, $innl, $ModuleBase::DatabaseName );
	getActiveLanguages( $hashmain, $_ihs, $innl, '' );
	$$hashmain{_usertableid} = provideTableId( $hashmain, $_ihs, $innl, 'sys_user' ); #we need this multiple times.

	#copySession($hashmain, $_ihs,$innl,$session);

	readAllSessionSequence( $hashmain, $_ihs, $innl );
	intelligentUpdateSequence( $hashmain, $_ihs, $innl,{ _gotorow => $$hashmain{_row} } ) if ( defined $$hashmain{_row} );
	validatePrevious_csi( $hashmain, $_ihs, $innl );
	traceme( $hashmain, $_ihs, "initEnableCustomerDb _lastSeqNr: $$_ihs{_lastSeqNr} Current position = $$_ihs{_curVolgNr}", __LINE__ ) if $$_ihs{__systemtrace__};
	if( $$hashmain{_action} eq 'switchlang'){
		my $sessiondata = readLastSession ( $hashmain, $_ihs, $innl, '' );
		#listKeys( $sessiondata, $_ihs, 'all', ('sessiondata switchlang---' . __LINE__ . '--- sessiondata switchlang' ), ( "Ix" . __LINE__ ) ); 
		if ( $$sessiondata{_action} ne '' ){
			$$hashmain{_action}		 = $$sessiondata{_action};
			$$hashmain{_page}		   = $$sessiondata{_page};
			$$hashmain{_tbnaam}		 = $$sessiondata{tb_id};
			$$hashmain{_tgrndds}		= $$sessiondata{_tgrndds};
			$$hashmain{_tbnaam}		 = $$sessiondata{tb_id};
			$$hashmain{_tbprev}		 = $$sessiondata{_tbprev};
			$$hashmain{_tbprevid}	   = $$sessiondata{_tbprevid};
			$$hashmain{_gebruikernaam}  = $$sessiondata{gb_id};
			$$hashmain{_recordkey}	  = $$sessiondata{_recordkey};
			$$hashmain{_recordvalue}	= $$sessiondata{_recordvalue};
			$$hashmain{_selectedrule}   = $$sessiondata{selectrule};
			$$hashmain{_searchkeyword}  = $$sessiondata{_searchkeyword}; 
			traceme( $hashmain, $_ihs, "_recordkey = $$hashmain{_recordkey}", __LINE__ ) if $$_ihs{__systemtrace__};
			traceme( $hashmain, $_ihs, "_tbprev: $$_ihs{_tbprev}", __LINE__ ) if $$_ihs{__systemtrace__};
		}
	}
	traceme( $hashmain, $_ihs, "", __LINE__ ) if ( $$_ihs{__systemtrace__} );
	if ( $$hashmain{_fstart} == 1 ){ #clear all but in the actual database
		initToFirstSession( $hashmain, $_ihs, $innl );
	}
	#these action still can be done when people are logged in
	if ( $$hashmain{_action} eq 'register' ){
		$$hashmain{_tbnaam} = 'in_register';
		$$hashmain{_action} = 'insert';
	}
	elsif ( $$hashmain{_action} eq 'contact' ){
		$$hashmain{_tbnaam} = 'in_contact';
		$$hashmain{_action} = 'insert';
	}
	elsif ( $$hashmain{_action} eq 'example' ){
		$$hashmain{_tbnaam} = 'in_example';
		$$hashmain{_action} = 'insert';
	}
	setBrowser( $hashmain, $_ihs, $innl );
	$sql  = "SET AUTOCOMMIT=1";
	PrepAndExecuteQuery( $hashmain, $_ihs, $innl, $sql, ( "Ix" . __LINE__ ) );

	#add the checkbox and radio buttons that are missing in formfields when we have save action
	if ( $$hashmain{_action} eq 'bewaar' ){
		addCheckRadiobox( $hashmain, $_ihs, $innl );
	}
	#update the last activity stamp for this user
	$sql = "UPDATE sys_user SET gb_lastactivity = NOW(), gb_online = 'Ja' WHERE gb_id = '" . $$hashmain{_gb_id} . "' ";
	PrepAndExecuteQuery( $hashmain, $_ihs, $innl, $sql, ( "Ix" . __LINE__ ) );
	$$_ihs{_gb_id} = $$hashmain{_gb_id};
	$$hashmain{_glyphiconuser} = showGenericPage($hashmain,  $innl , $_ihs, 'user.glyphicon.action' );
	$$hashmain{_logintxt} = getSyslable ( $dbh, $$hashmain{_language}, "ingelogd" );

	#and determine the _copyid in case of copyrecord
	$$hashmain{_copyid} = '';
	my $ss = @{$$_ihs{_SessSeq}}[$$_ihs{_curIntSeqNr}]; #new SessionSequence
	$$hashmain{_copyid} = $$ss{_copyid};
	readTableAttributes( $hashmain, $_ihs, $innl, $$hashmain{_tbnaam} );
	#little bit of code for tab style layout
	#determineTabStyle( $hashmain, $_ihs, $innl, ( 'Ix' . __LINE__ ) );
	$$hashmain{_documentationtableid} = provideTableId( $hashmain, $_ihs, $innl, 'sys_documentation' ); #we need this multiple times.
	return $hashmain;
}

sub resetSearchKeysinceEmpty {
	my ( $hashmain, $_ihs, $innl ) = @_;
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	my $sql;
	if ( intelligentGetSequence( $hashmain, $_ihs, $innl ) != -1 ){
		traceme( $hashmain, $_ihs, "resetSearchKeysinceEmpty", __LINE__ ) if $$_ihs{__systemtrace__};
		intelligentUpdateSequence( $hashmain, $_ihs, $innl,{ _searchkeyword => '' } );
	}
}

sub initToFirstSession {
	my ( $hashmain, $_ihs, $innl ) = @_;
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	my $sql;
	deleteSessionSequence ( $hashmain, $_ihs, $innl, 1, ( 'Ix' . __LINE__ )  ); #preserve the allready created first home session
	$sql = "DELETE FROM sys_sessionfields WHERE sf_session = '" . $$hashmain{_session} . "' ";
	PrepAndExecuteQuery( $hashmain, $_ihs, $innl, $sql, ('Ix' . __LINE__ ) );
	
	$$_ihs{_tbprev} = '';
	$$_ihs{_tbprevid} = 0;
	traceme( $hashmain, $_ihs, "_tbprev: $$_ihs{_tbprev}", __LINE__ ) if $$_ihs{__systemtrace__};
}

sub executeactionDoImport {
	my ( $hashmain, $_ihs, $innl ) = @_;
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	my $sql;
	$$hashmain{imp_code} = $$hashmain{_3tvA2yW1rC0L};
	$$hashmain{imp_id} = $$hashmain{_Uq1lapI4n9W3};
	$sql  = "UPDATE custmdbm.sys_importbatch ";
	$sql .= "SET imp_busy	 = 'Nee', ";
	$sql .= "	imp_status   = 60, ";
	$sql .= "	date_changed = NOW() ";
	$sql .= "WHERE imp_id = " . $$hashmain{imp_id} . " ";
	$sql .= "AND imp_code = '" . $$hashmain{imp_code} . "' "; 
	$sql .= "AND imp_type = '" . $$hashmain{imp_type} . "' "; 
	traceme( $hashmain, $_ihs, "SQL $sql", __LINE__ ) if $$_ihs{__systemtrace__};
	PrepAndExecuteQuery( $hashmain, $_ihs, $innl, $sql, "Csv" . __LINE__ );
}

sub executeactionLogoff {
	my ( $hashmain, $_ihs, $innl, $cgi, $tidy ) = @_;
	my $dbh = $innl->dbh();
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	$$hashmain{_topmessagecontainer} = '';
	my $localdata;
	my $sql = "UPDATE " . $$_ihs{_databasename} . ".sys_user SET gb_lastactivity = NOW(), gb_online = 'Nee' WHERE gb_id = '" . $$hashmain{_gb_id} . "' ";
	PrepAndExecuteQuery( $hashmain, $_ihs, $innl, $sql, ('Ix' . __LINE__ ) );
	$sql = "DELETE FROM sys_sessionfields WHERE sf_session = '" . $$hashmain{_session} . "' ";
	PrepAndExecuteQuery( $hashmain, $_ihs, $innl, $sql, ('Ix' . __LINE__ ) );

	deleteSessionSequence ( $hashmain, $_ihs, $innl, 0, ( 'Ix' . __LINE__ )  ); #dit fixen
	$$_ihs{_validuser} = 0;

	$sql  = "UPDATE custmdbm.sys_session ";
	$sql .= "SET _password = '' ";
	$sql .= "WHERE session = ? ";
	ParamPrepAndExecute( $hashmain, $_ihs, $innl, $sql, $$hashmain{_session}, ('Ix' . __LINE__ ) );

	$$hashmain{_password} = "";
	$$hashmain{session} = "";
	$$hashmain{_session} = "";
	$$hashmain{_gebruikernaam} = '';
	$$hashmain{_logintxt} = "";
	$$hashmain{_nieuws} = "";

	if ( not exists $$hashmain{_error} ){
		$$hashmain{_gb_id} = "";	   # to avoid program warnings
		$$_ihs{_companycode} = $$hashmain{_companycode} = "";
	}
	#get the layout sizes from the bootstrap frame
	$sql  = "SELECT * FROM sys_bootstrapsize "; #moet dit wel?
	$sql .= "WHERE _dbcp = 'custmdbm' ";
	my $bsvalues = PrepAndFetchQuery( $hashmain, $_ihs, $innl, $sql, ('Ix' . __LINE__ ) );
	foreach ( keys %{ $bsvalues } ){
		$$hashmain{$_} = $$bsvalues{$_};
	}
	$$hashmain{_loginstate} = '0';
	traceme( $hashmain, $_ihs, "No action selected. show login page", __LINE__ ) if $$_ihs{__systemtrace__} >= 1;
	my $page = Page->new($innl, {}, '', '', ( $currenttemplate . '/basic.template.html' ) );
	print $cgi->header(), $page->FinalPrint( '', $hashmain);
	#print $cgi->header(), $tidy->clean( $page->FinalPrint( '', $hashmain )); #for development 
	traceme( $hashmain, $_ihs, "Final print", __LINE__ ) if $$_ihs{__systemtrace__} >= 1;
	exit(0);
}

sub prepareLoginFunction {
	my ( $hashmain, $_ihs, $innl ) = @_;
	my $dbh = $innl->dbh();
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	$$hashmain{_companydblable} = getSyslable( $dbh, $$hashmain{_language}, 'solution' );
	$$hashmain{_userlable}	  = getSyslable( $dbh, $$hashmain{_language}, 'user' );
	$$hashmain{_pswdlable}	  = getSyslable( $dbh, $$hashmain{_language}, 'password' );
	$$hashmain{_loginlable}	 = getSyslable( $dbh, $$hashmain{_language}, 'login' );
	$$hashmain{_fgpwlable}	  = getSyslable( $dbh, $$hashmain{_language}, 'forgotpasswd' );
	$$hashmain{_loginform}	  = showGenericPage($hashmain, $innl, $_ihs, 'login' );
	$$hashmain{_glyphiconuser}  = showGenericPage($hashmain,  $innl , $_ihs, 'user.glyphicon.login' );
}

sub waitforImportToFinish {
	my ( $hashmain, $_ihs, $innl ) = @_;
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	my $data;
	my $sql  = "SELECT * FROM custmdbm.sys_importbatch ";
	$sql	.= "WHERE ib_database = '" . $ModuleBase::DatabaseName . "' ";
	$sql	.= "AND imp_id = " . $$hashmain{imp_id} . " ";
	$sql	.= "AND imp_type = '" . $$hashmain{imp_type} . "' ";
	$sql	.= "AND imp_code = '" . $$hashmain{imp_code} . "' "; 
	traceme( $hashmain, $_ihs, $sql, __LINE__ ) ;#if $$_ihs{__syssqltrace__};
	my $result = PrepAndFetchQuery( $hashmain, $_ihs, $innl, $sql, ('Ix' . __LINE__ ) );
	if ( not defined $$result{imp_status} ){#there is no record
		$$result{imp_status} = 55;
	}
	elsif ( $$result{imp_status} > 55 ){
		$$hashmain{_stepinimportprocess} = $$result{imp_status};
		$$hashmain{_totalsteps} = $$result{imp_steps2};
	}
	else{
		$$hashmain{_stepinimportprocess} = $$result{imp_status};
		$$hashmain{_totalsteps} = $$result{imp_steps1};
	}
	if ( $$result{imp_status} == 55 || $$result{imp_status} == 99 ){ #ready with step 1 || step 2
		#we might be going directly from insert to update, not normal step. so we need to replace the insert action
		#TODO debug csi and prevcsi. we need to update the csi since we stay on the update form...
		$$hashmain{_tbnaam} = $$hashmain{imp_type} eq 'D' ? 'sys_import' : 'sys_importuser';
		$$hashmain{_tgrndds} = provideTableId( $hashmain, $_ihs, $innl, $$hashmain{_tbnaam}  );
		foreach my $res ( reverse( @{ $_ihs->{_SessSeq} } ) ){
			if ( $$res{tb_id} eq 'sys_import' &&  $$res{_action} eq 'insert' ){
				my $curseq = $$_ihs{_curIntSeqNr};
				my $curvlg = $$_ihs{_curVolgNr};
				$$_ihs{_curIntSeqNr} = $$res{volg_nr} - 1;
				$$_ihs{_curVolgNr} = $$res{volg_nr};
				intelligentUpdateSequence( $hashmain, $_ihs, $innl,{ _action => 'update', _tab_nr => '1', _tab_grp => '_importtab' } );
				$$_ihs{_curIntSeqNr} = $curseq;
				$$_ihs{_curVolgNr} = $curvlg;
				last;
			}
			elsif ( $$res{tb_id} eq 'sys_import' &&  $$res{_action} eq 'update' && $$result{imp_status} == 99 ){
				$$_ihs{_curIntSeqNr} = $$res{volg_nr} - 1;
				$$_ihs{_curVolgNr} = $$res{volg_nr};
				my $activesession = readSessionSequenceCurrent( $hashmain, $_ihs, $innl );
				readTableAttributes( $hashmain, $_ihs, $innl, 'sys_import' );
				last;
			}
		}
		if ( $$hashmain{_action} ne 'update' ){
			$$hashmain{_action} = 'update';
			$$hashmain{_recordvalue} = $$hashmain{imp_id};
			$$hashmain{_recordkey} = 'imp_id';
			traceme( $hashmain, $_ihs, "_recordkey = $$hashmain{_recordkey}", __LINE__ ) if $$_ihs{__systemtrace__};
		}
		$$hashmain{_tab} = 1;
		$$_ihs{_actualaction} = $$hashmain{_action};
		determineTabStyle( $hashmain, $_ihs, $innl, ( 'Ix' . __LINE__ ) );
		showTabStyle( $hashmain, $_ihs, $innl ) if ( $$_ihs{_tabbedforms} );
		( $data, $hashmain ) = selectrecord( $hashmain, $_ihs, $innl, $$hashmain{_action} );
		traceme( $hashmain, $_ihs, $$hashmain{_action} . "exit selectrecord" , __LINE__ ) if $$_ihs{__systemtrace__} || $tracesaving;
		return ( $data, $hashmain );
	}
	else{
		$$hashmain{_csi} = $$hashmain{_prevcsi}; 
		$$hashmain{_action} = '_waitforimport';
		$$hashmain{_postselect} = showGenericPage($hashmain, $innl, $_ihs, 'javascript._import.postselect' );
		$$hashmain{_javascript_bottom_all} .= showGenericPage($hashmain, $innl, $_ihs, 'javascript.wait.auto' );
		$$hashmain{_indexpagecontent} = showDbPage($hashmain, $innl, '_impwait.auto' );
		$$hashmain{_cssfile}   = showGenericPage($hashmain, $innl, $_ihs, 'pagina.spinner.css' );
		$$hashmain{_javascript_bottom_all} .= showGenericPage($hashmain, $innl, $_ihs, 'javascript.head' );
		traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__};
		traceme( $hashmain, $_ihs, "_csi: $$hashmain{_csi}, _prevcsi: $$hashmain{_prevcsi} new _csi ", __LINE__ ) if $tracecsi;
		return ( showLocalPage($hashmain, $innl, '_indexloggedin.page' ), $hashmain );
	}
}

sub getPageDefaults {
	my ( $hashmain, $_ihs, $innl, $db ) = @_;
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	my $sql = '';
	$sql  = "SELECT * FROM sys_companydb c ";
	$sql .= "WHERE dbnaam = '". $db . "' ";
	$sql .= "AND aktief = 'Ja' ";
	traceme( $hashmain, $_ihs, $sql, __LINE__ ) if $$_ihs{__syssqltrace__};
	my $result = PrepAndFetchQuery( $hashmain, $_ihs, $innl, $sql, ('Ix' . __LINE__ ) );
	$$_ihs{_startpage}			= $$result{startpage};
	$$_ihs{_startpagelang}		= $$result{startpagelang};
	$$_ihs{_loggedin_startpage}   = $$result{loggedin_startpage};
	$$_ihs{_defaultpageloggedout} = $$result{defaultpageloggedout};
	$$hashmain{_title}	 = $$result{title};
	$$hashmain{_page}	  = $$result{startpage}  if ( $$hashmain{_page} eq '' );
	$$hashmain{_logotitle} = showDbPage($hashmain, $innl, '_title' ) if ( $$_ihs{_startpagelang} eq 'Ja' );

}

sub getActiveLanguages {
	my ( $hashmain, $_ihs, $innl, $db ) =@_;
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	my @ll = ();
	my $sql = '';
	$sql  = "SELECT language_cd AS _language, referentie AS _languagename, flag_cd AS _countryflag ";
	$sql .= "FROM sys_language ";
	$sql .= "WHERE active = 'Ja' ";
	$sql .= "ORDER BY ln_order_id ";
	traceme( $hashmain, $_ihs, $sql, __LINE__ ) if $$_ihs{__syssqltrace__};
	my $sth = PrepAndExecuteQuery( $hashmain, $_ihs, $innl, $sql, ( 'Ix' . __LINE__ ) );
	while ( my $Language = $sth->fetchrow_hashref() ){
		push @ll, $Language;
	}
	$$_ihs{_languages} = \@ll;
	#set the language for existing session
}

#-marker SUB addCheckRadiobox

sub addCheckRadiobox {  
	my ( $hashmain, $_ihs, $innl ) = @_;
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	my $sql = '';
	my @_internalflds = @{$$_ihs{_orgfields}};
	my ( $kf, $ds, $cr, $dbtbflds ) = getFieldsAndAttributes( $hashmain, $_ihs, $innl, $$hashmain{_tbnaam}, 'select', ('Ix' . __LINE__ ) );
	foreach my $fld ( @$dbtbflds ){
		if ( not exists $$hashmain{$$fld{_fieldname}} ){
			if ( ( $$fld{_attr_checkbox} ||  $$fld{_attr_radiobutton} ) && $$fld{_attr_radiobutton} == 0 ){
				$$hashmain{$$fld{_fieldname}} = 0;
				push @_internalflds, $$fld{_fieldname};
				traceme( $hashmain, $_ihs, "Added field $$fld{_fieldname}, value 0", __LINE__ ) if $$_ihs{__systemtrace__};
			}
		}
	}
	$$_ihs{_orgfields} = \@_internalflds;
}

#-marker SUB setBrowser

sub setBrowser{
	my ( $hashmain, $_ihs, $innl ) = @_;
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	if ( $$_ihs{_browseragent} =~ /Firefox/ ){
		$$_ihs{_browser} = 'Firefox';
		$$_ihs{_browserversion} = $$_ihs{_browseragent};
		$$_ihs{_browserversion} =~ s/^.*Firefox\///;
	}
	elsif ( $$_ihs{_browseragent} =~ /Trident/ ){
		$$_ihs{_browser} = 'InternetExplorer';
		$$_ihs{_browserversion} = $$_ihs{_browseragent};
		$$_ihs{_browserversion} =~ s/^.*Trident\///;
		$$_ihs{_browserversion} =~ s/;.*$//;
	}
	elsif ( $$_ihs{_browseragent} =~ /Win64/ ){
		$$_ihs{_browser} = 'MicrosoftEdge';
		$$_ihs{_browserversion} = '';
	}
	elsif ( $$_ihs{_browseragent} =~ /OPR/ ){
		$$_ihs{_browser} = 'Opera';
		$$_ihs{_browserversion} =~ s/^.*OPR\///;
	}
	elsif ( $$_ihs{_browseragent} =~ /AppleWebKit/ ){
		$$_ihs{_browser} = 'Chrome';
		$$_ihs{_browserversion} =~ s/^.*Chrome\///;
		$$_ihs{_browserversion} =~ s/ S.*$//;
	}
	else{
		$$_ihs{_browser} = 'Other';
		$$_ihs{_browserversion} = '';
	}
	my $sql = '';
	$sql  = "UPDATE sys_session ";
	$sql .= "SET _browser = '" . $$_ihs{_browser} . "', ";
	$sql .= "_browserversion = '" . $$_ihs{_browserversion} . "' ";
	$sql .= "WHERE session = '" . $$hashmain{_session} . "'" ;
	PrepAndExecuteQuery( $hashmain, $_ihs, $innl, $sql, ( "Ix" . __LINE__ ) );
	
}

#-marker SUB setButtonOk

sub setButtonOk{
	my ( $hashmain, $_ihs, $innl ) = @_;
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	$$hashmain{_keyparameter1} = '_' . Functions::GenPass(30) if not exists $$hashmain{_keyparameter1};
	$$hashmain{_keyvalue1} = Functions::GenPass(16) if not exists $$hashmain{_keyvalue1};
	$$hashmain{_keyparameter2} = '_' . Functions::GenPass(20) if not exists $$hashmain{_keyparameter2};
	$$hashmain{_keyvalue2} = Functions::GenPass(24) if not exists $$hashmain{_keyvalue2};
	$$hashmain{_button}  = showGenericPage($hashmain, $innl, $_ihs, 'button.ok' );
}

#-marker SUB newBootstrapValues

sub newBootstrapValues{
	my ( $hashmain, $_ihs ) = @_;
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	#layout sizes from the bootstrap frame
	$$hashmain{_left_col_lg} = 0;
	$$hashmain{_left_col_md} = 0;
	$$hashmain{_left_col_sm} = 0;
	$$hashmain{_left_col_xs} = 0;
	$$hashmain{_body_col_lg} = 12;
	$$hashmain{_body_col_md} = 12;
	$$hashmain{_body_col_sm} = 12;
	$$hashmain{_body_col_xs} = 12;
	$$hashmain{_right_col_lg} = 0;
	$$hashmain{_right_col_md} = 0;
	$$hashmain{_right_col_sm} = 0;
	$$hashmain{_right_col_xs} = 0;
	return $hashmain;
}

#-marker SUB doStepofImport

sub doStepofImport {  
	my ( $hashmain, $_ihs, $innl, $status ) = @_;
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	my $sth;
	my $steps = 9;
	foreach ( qw( imp_langenglish imp_langchinese imp_langspanish imp_langarabic imp_langhindi imp_langportugese imp_langrussian imp_langgerman imp_langdutch ) ){
		$steps += $$hashmain{$_};
	}
	my $sql  = "SELECT * FROM custmdbm.sys_importbatch ";
	$sql	.= "WHERE ib_database = '" . $ModuleBase::DatabaseName . "' ";
	$sql	.= "AND imp_id = " . $$hashmain{imp_id} . " ";
	$sql	.= "AND imp_type = '" . $$hashmain{imp_type} . "' ";
	$sql	.= "AND imp_code = '" . $$hashmain{imp_code} . "' "; 
	traceme( $hashmain, $_ihs, "SQL $sql", __LINE__ ) if $$_ihs{__systemtrace__};
	my $result = PrepAndFetchQuery( $hashmain, $_ihs, $innl, $sql, ('Ix' . __LINE__ ) );
	if ( $$result{imp_code} ){ # the record exists
		$sql  = "UPDATE custmdbm.sys_importbatch ";
		$sql .= "SET imp_busy   = 'Nee', ";
		$sql .= "	imp_status = " . $status . ", ";
		$sql .= "	imp_steps1 = " . $steps . ", ";
		$sql .= "	imp_steps2 =  90, ";
		$sql .= "	ib_gb_id   = '" . $$hashmain{_gb_id} . "', ";
		$sql .= "	date_changed = NOW() ";
		$sql .= "WHERE ib_id = " . $$result{ib_id} . " ";
		$sth = PrepAndExecuteQuery( $hashmain, $_ihs, $innl, $sql, ('Ix' . __LINE__ ) );
	}
	else{
		$sql  = "INSERT INTO custmdbm.sys_importbatch ";
		$sql .= "VALUES ( 0, ";
		$sql .= "'" . $$hashmain{_companycode} . "', ";
		$sql .= "'" . $ModuleBase::DatabaseName . "', ";
		$sql .= "'" . $$hashmain{imp_name} . "', ";
		$sql .= "'" . $$hashmain{_gb_id} . "', ";
		$sql .= "'Nee', ";
		$sql .= "1, $steps, 90, ";
		$sql .= $$hashmain{imp_id} . ", ";
		$sql .= "'" . $$hashmain{imp_code} . "', ";
		$sql .= "'" . $$hashmain{imp_type} . "', ";
		$sql .= "NOW(), '' ) ;";
		$sth = PrepAndExecuteQuery( $hashmain, $_ihs, $innl, $sql, ('Ix' . __LINE__ ) );
	}
	#csvcrea is a batch process defined in crontab
}

#-marker SUB showTableForm

sub showTableForm {  
	my ( $hashmain, $_ihs, $innl ) = @_;
	my $dbh = $innl->dbh();
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );
	
	my $sql = '';
	my $_data = '';
	#temporarily give permission to be able to edit the table
	if ( $$hashmain{_action} eq 'register' ){
		$$hashmain{_tbnaam} = 'in_register';
	}
	elsif ( $$hashmain{_action} eq 'contact' ){
		$$hashmain{_tbnaam} = 'in_contact';
	}
	elsif ( $$hashmain{_action} eq 'example' ){
		$$hashmain{_tbnaam} = 'in_example';
	}
	elsif ( $$hashmain{_action} eq 'in_rpw' ){
		$$hashmain{_tbnaam} = 'in_rpw';
	}
	#$$_ihs{_profiel_id} = 0;
	$$hashmain{_action} = 'insert';
	$$hashmain{_fstart} = 1;
	$$_ihs{_validuser} = 1;
	$$hashmain{_tgrndds} = provideTableId( $hashmain, $_ihs, $innl, $$hashmain{_tbnaam} ); #we need this multiple times.
	intelligentUpdateSequence( $hashmain, $_ihs, $innl,{ _action => 'insert', _tgrndds => $$hashmain{_tgrndds}, tb_id => $$hashmain{_tbnaam} }  );
	#if ( intelligentGetSequence( $hashmain, $_ihs, $innl ) == -1 ){
	#	intelligentInsertSequence( $hashmain, $_ihs, $innl, __LINE__ );
	#}
	( $_data, $hashmain) = selectrecord( $hashmain, $_ihs, $innl, 'insert' );
	traceme( $hashmain, $_ihs, $$hashmain{_action} . "exit selectrecord" , __LINE__ ) if $$_ihs{__systemtrace__} || $tracesaving;
	$$_ihs{_validuser} = 0;
	#$$_ihs{_autorisatielevel} = 0;
	#$$hashmain{_cssforfields} = 'form_template';
	$$_ihs{_finaltemplate} = 'tabelrecordinhoud.tabel';
	$$_ihs{_finaltemplatemethod} = $genericshow;
	my $data = showGenericPage( $hashmain, $innl, $_ihs, 'tabelrecordinhoud.tabel' );
	return ( $_data, $hashmain );
}

#-marker SUB validateSystemName

sub validateSystemName {  
	my ( $hashmain, $_ihs, $innl ) = @_;
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	my $sql = "SELECT * FROM custmdbm.sys_companydb " ;
	$sql   .= "WHERE companycode = '" . $$hashmain{rg_companycode} . "' ";

	my $hashresult = PrepAndFetchQuery( $hashmain, $_ihs, $innl, $sql, ('Ix' . __LINE__ ) );

	if ( exists $$hashresult{companycode} ){
		return 1;
	}
	return 0;
}

#-marker SUB sendSystemError

sub sendSystemError{
	my ( $hashmain, $_ihs, $innl, $err ) = @_;
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	my $From = 'noreply@raplico.com';
	my $To = 'f.boerefijn\@sententia.nl';
	my $Subject;
	my $Msg = '';
	my $newline = "<BR />";
	$Subject = "Error occurred in raplico";

	$$hashmain{_throwerror} = "Dumper"  . $newline;
	my @keys = keys %{ $hashmain };
	foreach ( @keys ){
		if ( $$hashmain{$_} =~ /\<.*\>/ ){
			$$hashmain{_throwerror} .= $_ . ": Contains html content." . $newline;
		}
		else{
			$$hashmain{_throwerror} .= $_ . ": " . $$hashmain{$_} . $newline;
		}
	}
	$$hashmain{_throwerror} .= $newline;

	$$hashmain{_throwerror} .= $err . $newline;
	$Msg = showGenericPage($hashmain, $innl, $_ihs, 'mail.notify.error' );
	

	my $MailMessage = MIME::Lite->new (
	  From => $From,
	  To => $To,
	  Subject => $Subject,
	  Type =>'multipart/mixed',
	) or die "$!\n";

	$MailMessage->attach(
		Type	 =>'text/html',
		Data	 => $Msg
	);
	$MailMessage->send();

}
#-marker SUB sendSystemReminder

sub sendSystemReminder{
	my ( $hashmain, $_ihs, $innl, $action ) = @_;
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	my $From = 'noreply@raplico.com';
	my $To = 'f.boerefijn\@sententia.nl';
	my $Subject;
	my $Msg = '';
	if ( $action eq 'register' ){
		$Subject = $$hashmain{rg_firstname} . ' ' . $$hashmain{rg_lastname} . ' registered at raplico ';
		$Msg = showGenericPage($hashmain, $innl, $_ihs, 'mail.notify.register' );
	}
	elsif ( $action eq 'contact' ){
		$Subject = $$hashmain{ct_username} . ' contacted you.';
		$Msg = showGenericPage($hashmain, $innl, $_ihs, 'mail.notify.contact' );
	}

	my $MailMessage = MIME::Lite->new (
	  From => $From,
	  To => $To,
	  Subject => $Subject,
	  Type =>'multipart/mixed',
	) or die "$!\n";

	$MailMessage->attach(
		Type	 =>'text/html',
		Data	 => $Msg
	);

	$MailMessage->send();

}

#-marker SUB getLogo

sub getLogo {
	my ($hashmain, $_ihs, $innl) = @_;
	my $dbh = $innl->dbh();
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	my $db = '';
	if ( $$_ihs{_validuser} == 0 ){
		$db = 'custmdbm.';
	}
	my $sql = "SELECT org_id AS _recordvalue, org_no_strech AS _stretch  FROM " . $db . "sys_organization";
	my $hashtmp = PrepAndFetchQuery( $hashmain, $_ihs, $innl, $sql, ('Ix' . __LINE__ ) );
	$$hashtmp{_orgtableid} = provideTableId( $hashmain, $_ihs, $innl, 'sys_organization' );
	if ( defined $$hashtmp{_stretch} ){
		$$hashtmp{_session} = $$hashmain{_session};
		$$hashtmp{_fieldname} = 'org_logo';
		return showGenericPage ( $hashtmp,  $innl, $_ihs, 'logo.custom' );
	}
	else{
		return '';
	}
}

#-marker SUB showSelectedNewsItem
#-showSelectedNewsItem shows the full news item if requested more info via the news line item.
sub showSelectedNewsItem {
	my ($hashmain, $_ihs, $innl) = @_;
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	my $sql = "SELECT * FROM sys_news WHERE nws_id = " . $$hashmain{id} . " AND  nws_active = 'Ja' ";  
	my $hashnieuws = PrepAndFetchQuery( $hashmain, $_ihs, $innl, $sql, ('Ix' . __LINE__ ) );
	$$hashnieuws{_language} = $$hashmain{_language};
	$$hashnieuws{session} = $$hashmain{_session};
	if (! $$_ihs{_validuser} == 1 ){
		traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__} >= 2;
		$$hashmain{_newsitemfull} = showGenericPage ( $hashnieuws, $innl, $_ihs, 'nieuws.show.nli' );
	}
	else{
		traceme( $hashmain, $_ihs, "", __LINE__ ) if $$_ihs{__systemtrace__} >= 2;
		$$hashmain{_newsitemfull} = showGenericPage ( $hashnieuws, $innl, $_ihs, 'nieuws.show' );
	}
}
	
#-marker SUB genNieuws
#-generates short news items that can be clicked for more information
sub genNieuws {
	my ($hashmain, $_ihs, $innl) = @_;
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	my ($string, $string2, $teller) = ('','',1);
	my $sql = "SELECT * FROM sys_news WHERE nws_active = 'Ja' order by nws_seqnr";  
	
	my $sthNieuws = PrepAndExecuteQuery( $hashmain, $_ihs, $innl, $sql, ( 'Ix' . __LINE__ ) );
	$$hashmain{_nieuwsall} = '';
	$$hashmain{_width}  = '100%'; #int( 0.15 * $$hashmain{maxwidth} ) -30;
	$$hashmain{_height} = int( 0.3 * $$hashmain{_browsersize} );
	$$hashmain{_widthtd} = '100%';
	my $records = -1;
	while(my $hashnieuws = $sthNieuws->fetchrow_hashref()){
		$records++;
		$$hashnieuws{rowclass} = ( $records % 2 == 1 ) ? 'presrij2' : 'presrij0';
		$$hashnieuws{_language} = $$hashmain{_language};
		$$hashnieuws{session} = $$hashmain{_session};
		   if( $teller <= 5 ){
			$$hashmain{_nieuwsall} .= showDbPage ( $hashnieuws, $innl, 'nieuws.lijst' );
			$teller++;
		}	
		else {
			$$hashmain{_nieuwsall} .= showPage ( $innl, 'nieuws.lijst.kort', $hashnieuws );
		}
	}
	if ( $$hashmain{_nieuwsall} eq '' ){
		$$hashmain{_nieuwsall} .= showDbPage ( $hashmain, $innl, 'nieuws.geen' );
	}
	$$hashmain{_nieuwslegend} = showDbPage ( $hashmain, $innl, 'nieuws.legend' );
	$$hashmain{_newsblock} = showPage ( $innl, 'nieuws', $hashmain );
}

#-marker SUB genPresence

sub genPresence {
	my ($hashmain, $_ihs, $innl) = @_;
	my $dbh = $innl->dbh();
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	my $sql = "SELECT gb_id, gb_online, gb_first, gb_last, ";
	$sql .= "TIMEDIFF( NOW(), gb_lastactivity ) AS hours, ";
	$sql .= "DATEDIFF( NOW(), gb_lastactivity ) AS days ";
	$sql .= "FROM sys_user ";
	$sql .= "WHERE gb_active = 'Ja' ";	
	$sql .= "ORDER BY hours ";
	traceme( $hashmain, $_ihs, "SQL $sql", __LINE__ ) if $$_ihs{__systemtrace__};
	my $sth = PrepAndExecuteQuery( $hashmain, $_ihs, $innl, $sql, ('Ix' . __LINE__ ) );
	my $records = -1;
	while(my $presence = $sth->fetchrow_hashref() ){
		$records++;
		my $imnr = ($records % 2 == 1 )+1; # 1 or 2
		$$presence{minutes} = $$presence{hours};
		$$presence{hours} =~ s/([0-9]*):([0-9]*):([0-9]*)/$1/;
		$$presence{minutes} =~ s/([0-9]*):([0-9]*):([0-9]*)/$2/;
		$$presence{rowclass} = ( $records % 2 == 1 ) ? 'presrij2' : 'presrij1';
		$$presence{_rij}   = 'presence.' . ( $records % 2 == 1 ) ? '.rij2' : '.rij1';
		$$presence{gb_online} = 'Nee' if ( $$presence{hours} > 23 );
		$$presence{days} = 0 if ( not defined $$presence{days}  );

		
		if ( $$presence{gb_first} ne '' && $$presence{gb_last} ne '' ){ 
			$$presence{gb_id} = $$presence{gb_first} . ' ' . $$presence{gb_last};
		}
		if ( $$presence{gb_online} eq 'Nee' ){ #not online
			$$presence{_pres_image} = 'na_' . $imnr . '.jpg';
			$$presence{_colorclass} = 'c_red';
			my $time = '';
			if ( $$presence{hours} <= 23 ){
				if ( $$presence{hours} == 1 ){
					$time = getSyslable( $dbh, $$hashmain{_language}, 'houronline' );
				}
				else{
					$time = getSyslable( $dbh, $$hashmain{_language}, 'hoursonline' );
				}
				$$presence{_offline} = 'Online ' . int( $$presence{hours} ) . $time;
			}
			else{
				if ( $$presence{days} == 1 ){
					$time = getSyslable( $dbh, $$hashmain{_language}, 'dayonline' );
				}
				else{
					$time = getSyslable( $dbh, $$hashmain{_language}, 'daysonline' );
				}
				$$presence{_offline} = 'Online ' . int( $$presence{days} ) . $time if $$presence{days} > 0;
			}
		}
		elsif ( $$presence{minutes} > 10 ){ #last activity longer then 10 minutes ago
			$$presence{_pres_image} = 'ma_' . $imnr . '.jpg';
			$$presence{_colorclass} = 'c_amb';
			
		}
		else {# if( $$presence{gb_online} eq 'Ja' ) {#yeeeh, online ;)
			$$presence{_pres_image} = 'av_' . $imnr . '.jpg';
			$$presence{_colorclass} = 'c_grn';
		}
		$$hashmain{_presenceall} .= showGenericPage ($presence,  $innl, $_ihs, 'presence.rij.new' );
		#$$hashmain{_presenceall} .= showGenericPage ($presence,  $innl, $_ihs, 'presence.rij' );
	}
	$$hashmain{_javascriptotherfunctions} .= showGenericPage ($hashmain,  $innl, $_ihs, 'javascript.presence' );
	$$hashmain{_javascriptreadystart} .= showGenericPage ( $hashmain, $innl, $_ihs, 'javascript.presence.init' );
	$$hashmain{_presencesearch} = showDbPage ( $hashmain, $innl, 'presence.search' ) if ( $records > 10 );
	$$hashmain{_presence} = showDbPage ( $hashmain, $innl, 'presence.new' );
	#$$hashmain{_presence} = showDbPage ( $hashmain, $innl, 'presence' );

}

#-marker SUB showWorkList

sub showWorkList {
	my ($hashmain, $_ihs, $innl, $line ) = @_;
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	return; #for now work todo is not yet completely implemented.
	my $sql = "SELECT * FROM sys_worktodo WHERE usertowork = '" . $$hashmain{_gb_id} . "' order by date_inserted";  
	my $sthWork = PrepAndExecuteQuery( $hashmain, $_ihs, $innl, $sql, ('Ix' . __LINE__ ) );
	
	$$hashmain{_takenall} = '';
	while(my $hashwork = $sthWork->fetchrow_hashref()){
		$$hashwork{_language} = $$hashmain{_language};
		$$hashwork{_tbnaam} = $$hashwork{tb_id};
		$$hashwork{_recordkey} = $$hashwork{recordkey};
		$$hashwork{_recordvalue} = $$hashwork{recordvalue};
		$$hashmain{_action} = 'update';
		$$hashmain{_takenall}   .= showDbPage ( { %$hashwork, %$hashmain}, $innl, 'work.actions' );
		traceme( $hashmain, $_ihs, "_recordkey = $$hashmain{_recordkey}", __LINE__ ) if $$_ihs{__systemtrace__};
	}
	if ( $$hashmain{_takenall} eq '' ){
		$$hashmain{_takenall} = showDbPage ( $hashmain, $innl, 'work.none' );
	}
	$$hashmain{_taken} .= showDbPage ( $hashmain, $innl, 'work' );
}

#-marker SUB doExport

sub doExport {
	my ($hashmain, $_ihs, $innl, $Cgi ) = @_;
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	my $sql;
	if ( !($$_ihs{_tableattribute} =~ /E/ )){
		print STDERR "[Ix" . __LINE__ . "][" . $$hashmain{_companycode} . "] Table export is not allowed. Normaly this would not happen. A hack? \n" ;
		exit;
	}
	$hashmain = getSessionFields ( $hashmain, $_ihs, $innl );
	if ( $$_ihs{_allReferencesInMemory} == 0 ){
		readAllReferences( $hashmain, $_ihs, $innl);
	}
	my $fromsql  = @{$$_ihs{_SessSeq}}[$$_ihs{_curIntSeqNr}]->{_fromsql};
	my $wheresql = @{$$_ihs{_SessSeq}}[$$_ihs{_curIntSeqNr}]->{_wheresql};
	my $ordersql = @{$$_ihs{_SessSeq}}[$$_ihs{_curIntSeqNr}]->{_ordersql};
	my $tables = {};
	my @base = split(/,/, $fromsql);
	my $nextTbLetter = 'a';
	foreach ( @base ){
		s/ $//;
		my ( $tb, $letter ) = split( / /, $_ );
		$$tables{$tb} = $letter;
		$nextTbLetter++;
	}
	$nextTbLetter++;
	my @columntitles = ();
	my @remains = ();
	$$_ihs{_refincluded} = 1; #for now we develop exportselect which uses references.
	if ( $$_ihs{_refincluded} == 1 ){#query with references
		my ( $keyfield, $ds, $cr, $refdbkeys ) = getFieldsAndAttributes( $hashmain, $_ihs, $innl, $$hashmain{_tbnaam}, 'update', ('Ix' . __LINE__ ) );

		#provide the dataset name the user knows, not the internal database name
		$$hashmain{_tabelnaam} = readTableLableName( $hashmain, $_ihs, $innl );
		my @dbkeys = @$refdbkeys;
		my $tableletter = 'a';
		my $sqlselect = "SELECT DISTINCT ";
		my @tablefields = ();
		my @columns = ();
		my $reccnt  = 0;
		#add all the columns to the sql statement
		foreach ( @dbkeys ){
			if ( $$_{_attr_hidden} == 1 || $$_{_attr_password} == 1 ){ #if not hidden or passwd then include them in the export.
			} else {
				my $hashsql = {};
				$$hashsql{_fieldname}   = $$_{_fieldname};
				$$hashsql{_tablename}   = $$hashmain{_tbnaam};
				$sqlselect .= "a." . $$_{_fieldname} . ", ";
				push @tablefields, $$_{_fieldname};
				push @columntitles, $$_{_fieldtitle};
				push @columns, $hashsql;
			}
		}
		$sqlselect =~ s/, $/ /;

		$tableletter = '';
		my $cnt = 0;
		foreach my $Ref ( @{$$_ihs{_References}} ){ 
			if ( $$Ref{veldnaam} ne $$Ref{waarde} ){#only if key and value differ....
				if ( not defined $$tables{$$Ref{tabelnaam}} ){#this reference field was not in the overview
					$tableletter = $nextTbLetter;
					foreach ( @dbkeys ){
						if ( $$_{_fieldname} eq $$Ref{veld_id} ){
							push @remains, { 
								table => $$Ref{tabelnaam}, letter => $tableletter, 
								field => $$Ref{veld_id},   language => $$Ref{options},
								reffld => $$Ref{veldnaam}, refval => $$Ref{waarde}
							};
							last;
						}
					}
					$nextTbLetter++;
				}
				else{
					$tableletter = $$tables{$$Ref{tabelnaam}};
				}
			}
			$cnt++;
		}
		$sql = $sqlselect . " FROM " . $fromsql . " " . $wheresql . ' ' . $ordersql;
		traceme( $hashmain, $_ihs, $sql, __LINE__ ) if $$_ihs{__syssqltrace__};
		if ( $sql !~ /WHERE/ ){
			$sql =~ s/AND/WHERE/;
		}
	}
	else{
		$sql = 'SELECT * FROM ' . $$hashmain{_tbnaam};
	}
	traceme( $hashmain, $_ihs, $sql, __LINE__ )  if $$_ihs{__syssqltrace__};
	$$hashmain{_name} = $$hashmain{_tabelnaam} . '.' . $$hashmain{_zendmethode};
	if ( $$hashmain{_zendmethode} eq 'XML' ){
		XmlInitialise( $hashmain, $innl );
		XmlExecute( $hashmain, $innl, $sql, \@remains );
		print "Content-Type:application/x-download\n";
		print "Content-Disposition:attachment;filename=$$hashmain{_name}\n\n";
		print $$hashmain{_output};
	}
	else{
		my $csv = Text::CSV_XS->new ({ binary => 1, auto_diag => 1, eol => "\r\n" });
		open my $fh , ">", \my $data;
		my $sth = PrepAndExecuteQuery( $hashmain, $_ihs, $innl, $sql, ('Ix' . __LINE__ ) );
		$$hashmain{_options} = '';
		my $curcolumn = 0;
		$csv->print ($fh, \@columntitles );
		$$hashmain{_records} = '';
		my $Regels = 1;
		while ( my $row = $sth->fetch ){
			$csv->print ($fh, $row);
			$Regels++;
		}
		close $fh;
		binmode(STDOUT, ":utf8");
		print $Cgi->header( -type => 'text/plain', -charset => 'UTF-8', -attachment => $$hashmain{_name} ), $data;
	}
	exit;
}

#-marker SUB setIdentifier

sub setIdentifier{
	my ($hashmain, $session , $innl) = @_;
	$$hashmain{_identifier} = $$hashmain{identifier} = Functions::GenPass(20);
	$session->copy( {%$hashmain, identifier => $$hashmain{_identifier}}, $innl );
}

#-marker SUB searchResult

sub searchResult {
	my ($hashmain, $_ihs, $innl ) = @_;
	my $dbh = $innl->dbh();
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	my $tabel = '';
	my $key = '';
	my @fldstosearch = ();
	my @sqlarray = ();
	my $sql = "SELECT * FROM sys_searchdef WHERE zk_id IN (" .  $dbh->quote($$hashmain{list})  . ")";
	$sql =~ s/,\)/\)/;
	#my $sthzoek = PrepAndExecuteQuery( $hashmain, $_ihs, $innl, $sql, ( 'Ix' . __LINE__ ) );
	#before changing we need to figure out how and when zoek (search) is used
	my $sthzoek = $dbh->prepare( $sql );
	$sthzoek->execute() or return showDBPage( $hashmain, $innl, 'geentabel' );
	while (my $hashzoek = $sthzoek->fetchrow_hashref() ){
		if ( $$hashzoek{tb_id} ne $tabel ){
			# a new table
			if ( $tabel ne '' ){ # the fields are already known 
				my $sth = $dbh->prepare("DESCRIBE " . $tabel) or warn $DBI::errstr;
				$sth->execute() or return $hashmain;
				while ( my $res = $sth->fetchrow_hashref() ){
					if ( $$res{Extra} eq 'auto_increment' ){
						$key = $$res{Field};	
						#last;	
					}
				}
				#print DEBUG "Id No key in tabel $tabel\n\n" and warn if ( $key eq '' );
				$sql  = " SELECT * FROM $tabel ";
				$sql .= " WHERE " . join map {" $_ = '%$$hashmain{zoekterm}' " } @fldstosearch, ' AND ';
				$sql .= " 1 = 1";
				push @sqlarray, $sql;
				$tabel = $$hashzoek{tb_id};
				@fldstosearch = ();
				$key = '';
			}
			$tabel = $$hashzoek{tb_id};
		}
		push @fldstosearch, $$hashzoek{veld_id};
	}
	return ; #ExecuteSomething( $hashmain, $innl, @sqlarray);
}

#-marker SUB searchTemplate

sub searchTemplate {
	my ($hashmain, $_ihs, $innl ) = @_;
	my $dbh = $innl->dbh();
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	# check for labels 
	my $sqll = "SELECT * FROM sys_lable WHERE language = '" . $$hashmain{_language} . "' AND tb_id = '?' AND fld_id = '?' ";
	my $sthLabel = PrepareQuery( $hashmain,  $hashmain,  $_ihs, $dbh, $sqll );

	#my $sthzoek = PrepAndExecuteQuery( $hashmain, $_ihs, $innl, $sql, ( 'Ix' . __LINE__ ) );
	#before changing we need to figure out how and when zoek (search) is used
	my $sthzoek = PrepareQuery( $hashmain,  $hashmain,  $_ihs, $dbh, "SELECT * FROM sys_searchdef" );
	$sthzoek->execute() or return showDBPage( $hashmain, $innl, 'geentabel' );
	my $tabel = '';
	my $Label = '';
	$$hashmain{zoektabellen} = '';
	$$hashmain{items} = '';
	while (my $hashzoek = $sthzoek->fetchrow_hashref() ){
		if ( $$hashzoek{tb_id} ne $tabel ){
			if ( $tabel eq '' ){ # not the first table
				$tabel = $$hashzoek{tb_id};
			}
			else{
				$sqll = "SELECT lable FROM sys_lable WHERE language = '" . $$hashmain{_language} . "' AND tb_id = '$tabel' AND fld_id = '$tabel'";
				$$hashmain{_tbnaam_label} = $dbh->selectrow_array( $sqll ) || "\u$tabel";
				$$hashmain{zoektabellen} .= showPage($innl, 'zoek.tabel', $hashmain );
				$$hashmain{items} = '';
				$tabel = $$hashzoek{tb_id};
			}
		}
		$sqll = "SELECT lable FROM sys_lable WHERE language = '" . $$hashmain{_language} . "' AND tb_id = '$tabel' AND fld_id = '$$hashzoek{veld_id}'";
		$$hashzoek{_fieldtitle} = $dbh->selectrow_array( $sqll ) || "\u$$hashzoek{veld_id}";
		$$hashmain{items} .= showPage($innl, 'zoek.item', $hashzoek );
	}
	$$hashmain{_javascript_bottom_all} .= showGenericPage($hashmain, $innl, $_ihs, 'javascript.listcheck' );
	$sqll = "SELECT lable FROM sys_lable WHERE language = '" . $$hashmain{_language} . "' AND tb_id = '$tabel' AND fld_id = '$tabel'";
	$$hashmain{_tbnaam_label} = $dbh->selectrow_array( $sqll ) || "\u$tabel";
	$$hashmain{zoektabellen} .= showPage($innl, 'zoek.tabel', $hashmain );
	$$hashmain{_button} .= showPage($innl, 'button.zoek', $hashmain);
	$$hashmain{_button} .= showGenericPage( $hashmain, $innl, $_ihs, 'button.history.back' );
	$$hashmain{_buttons} .= showPage($innl, 'button', $hashmain);
	return showPage($innl, 'zoek', $hashmain );
}

#-marker SUB copyrecord

sub copyrecord {
	my ($hashmain, $_ihs, $innl) = @_;
	traceme( $hashmain, $_ihs, (caller(0))[3], __LINE__ ) if ( $$_ihs{__syssubtrace__}  );

	my @copyfields = ();
	my $sql = "SELECT * FROM " . $$hashmain{_tbnaam} . " WHERE " . $$hashmain{_recordkey} . " = " . $$hashmain{_recordvalue};
	my $hashrecord = PrepAndFetchQuery( $hashmain, $_ihs, $innl, $sql, ('Ix' . __LINE__ ) );
	$hashmain = {%$hashmain, %$hashrecord};
	$$hashmain{_action} = 'insert';
	$$hashmain{_copyid} = $$hashmain{_recordvalue};
	deleteSessionSequence ( $hashmain, $_ihs, $innl, ($$_ihs{_curVolgNr} - 1), ( 'Ix' . __LINE__ )  );
	$$hashmain{_recordiscopied} = 1;
	return $hashmain;
}

#-marker SUB translate

sub translate {
	my ( $string, $langfrom, $langto ) = @_;
	my @days1 = qw( Saturday Sunday Monday Thuesday Wednesday Thursday Friday );
	my @days2 = qw( Zaterdag Zondag Maandag Dinsdag Woensdag Donderdag Vrijdag );

	my @mont1 = qw( January February March April May June July August September October November December );
	my @mont2 = qw( Januari Februari Maart April Mei Juni Juli Augustus September Oktober November December );

	$string =~ s/([0-9])(th)/$1/;
	$string =~ s/([0-9])(st)/$1/;
	if ( $langfrom eq $langto ){
		return $string; # no translation needed
	}
	foreach my $recnr ( 0 .. $#days1 ){
		$string =~ s/$days1[$recnr]/$days2[$recnr]/g;
	}
	foreach my $recnr ( 0 .. $#mont1 ){
		$string =~ s/$mont1[$recnr]/$mont2[$recnr]/g;
	}
	return $string;
}

#-marker SUB test_params

sub test_params {
	#Let's test de params the user submitted
	my ($cgi) = @_;

	my %hash = $cgi->Vars;
	my $actionset = 0;
	my $nextset = 0;
	my $buttonpressed = 0;
	foreach my $key (keys %hash){
		$_ = $hash{$key};
		if( $key eq '_tbnaam' || $key eq '_gebruikernaam' || $key eq '_session' ){
			tr/a-zA-Z0-9_ //cd ;
			#$cgi->param($key, $_);
		}
		elsif( $key eq '_sortfld' && $nextset == 1 ){ #if sortfield already set 
			next;
		}
		elsif( $key eq '_action' && $actionset == 0 ){
			tr/a-zA-Z0-9_ //cd ;
			#$cgi->param($key, $_);
		}
		elsif ( $key =~ /^_fst_act_to_/ ){ #button action 
			$buttonpressed = 1;
			my @base = split(/:/, $key);
			$_ = $base[0];
			$_ =~ s/^_fst_act_to_//;
			$key = '_action';
			$hash{$key} = $_;
			#$cgi->param($key, $_);
			if ( $_ eq 'back' ){
				$key = '_fstacttodo';
				$_ = $base[1];
			}
			elsif ( $_ eq 'insert' ){
				$key = '_recordvalue';
				$_ = '';
			}	
			$actionset = 1;
		}
		elsif ( $key =~ /^_nxt_act_to_/ ){
			$buttonpressed = 1;
			$nextset = 1;
			$hash{_sortfld} = ''; #reset sortfield if you go to the next table
			#$cgi->param('_sortfld', '');
			my @base = split(/:/, $key); #determine which action to take
			$_ = $base[0];
			$_ =~ s/^_nxt_act_to_//;
			#print STDERR "[Ix" . __LINE__ . " input = $_\n";
			if ( $_ eq 'selectstay' || $_ eq 'updatestay' ){ #the forms stays on the same level, jumping sideways to other forms
				$key = '_stay';
				$hash{$key} = 'yes';
				#$cgi->param($key, 'yes');
				$_ =~ s/_stay//;
				if ( $#base == 4 ){ #followup parameter
					$_ = $base[1];
					 $key = '_nextparam';
					 $hash{$key} = $_;
					 #$cgi->param($key, $_);
					$_ = $base[2];
					 $key = '_nextaction';
					 $hash{$key} = $_;
					 #$cgi->param($key, $_);
					$_ = $base[2];
					 $key = '_nextkey';
					 $hash{$key} = $_;
					 #$cgi->param($key, $_);
					$_ = $base[3];
					 $key = '_nextid';
				}
			}
			elsif ($_ =~ /shpg/ ){
				#first the action
				$key = '_action';
				$hash{$key} = 'shpg';
				#$cgi->param($key, 'shpg' );
				#then the _page
				$key = '_page';
				my $tmpkey = $_;
				$tmpkey =~ s/shpg//;
				$hash{$key} = $tmpkey;
				#$cgi->param($key, $tmpkey );
			}
			elsif ( ( $_ =~ /select/ ) || ( $_ =~ /update/  ) || ( $_ =~ /insert/  ) ){
				$key = '_nextaction';
				$hash{$key} = $_;
				#$cgi->param($key, $_);
				$_ = $base[1];
				$key = '_nextparam';
				$hash{$key} = $_;
				#$cgi->param($key, $_);
				$_ = $base[2];
				$key = '_nextkey';
				$hash{$key} = $_;
				#$cgi->param($key, $_);
				$_ = $base[3];
				$key = '_nextid';
			}
			else{
				$key = '_action';
				$hash{$key} = $_;
				#$cgi->param($key, $_ );
				$_ = $base[1];
				$key = '_nextparam';
				$hash{$key} = $_;
				#$cgi->param($key, $_);
				$_ = $base[2];
				$key = '_nextkey';
				$hash{$key} = $_;
				#$cgi->param($key, $_);
				$_ = $base[3];
				$key = '_nextid';
			}
		}
		$hash{$key} = $_;
		#$cgi->param($key, $_);
	}
	$hash{_buttonpressed} = $buttonpressed ;
	return \%hash;
}

