#!/usr/bin/perl

BEGIN { use lib '/usr/home/cfg' ; require push_inc ; }
    
use CGI qw( :standard );
use CGI::Carp qw(fatalsToBrowser);
    
require cfg ;

print header;   # CGI.pm method

# unless ($username eq 'handre'or  $username eq 'rory') { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; }

#---------------------------------------------------------------------------------------------------------------------------------------------------------------------

use Fcntl qw(:flock);
use File::Copy;
use File::Basename;
use Date::Calc qw(:all);
use Excel::Writer::XLSX;
use LWP::Simple qw($ua get);
use JSON ;

&today;

#---------------------------------------------------------------------------------------------------------------------------------------------------------------------

# INSERT INTO demos 
# (`location_id`,`brief_description`,`id`,`additional_requirements_from_events_dept`,`events_operator_allocated`,`tenant_id`,`pre_demo_testing_requirements`,`demo_type_id`,`events_operator_required`,`calibrator_required`,`additional_requirements_from_support_dept`) VALUES 
# ("1","test","1009","test","132","1","test","1","1","1","test") ;

# INSERT INTO event_quotes 

# (`days_active`,`date_from`,`ref`,`roe`,`office_notes`,`user_id`,`slip`,`demo_id`,`address`,`event_system_id_multiple`,`organisation_ids`,`total_vat_amount_workings_event`,`total_grand_amount_workings_event`,`times_from`,`quote_to`,`operator_ids`,`total_amount_workings_event`,`country_id`,`email`,`last_update`,`contact_name`,`notes`,`club_ids`,`datetime`,`id`,`currency`,`quote_nr`,`date_to`,`tel`) VALUES (
# "1;;;;;;;;;;;;;;;;;;;","2025-07-12 08:00:00","test","1","test","25","","1009","113 Cinsaut St, Steynsrust, Somerset West","277;278;;;;;;;;;;;;;","532","237.60","1821.60",";;;;;;;;;;;;;;;;;;","1:Rory Mathew:rory@kre8it.co.za:0621336752:113 Cinsaut St, Steynsrust, Somerset West","291;189;","1584.00","242","rory@kre8it.co.za","2025-07-07 09:46:34","Rory Mathew","test","727;727;;;;;;;;;;;;;","2025-07-07 09:46:34","10943","ZAR","1009","2025-07-12 17:00:00","0621336752") ;

@ARGV   = split(/\\*\&/, $ENV{'QUERY_STRING'});
$action = $ARGV[0] ;

our ($q)                 = CGI -> new() ;
our $iaction             = $q -> param('iaction')                || $action ;
our $isaved              = $q -> param('isaved')                 || '' ;

# our $testing = 1 ; 
# our $debug = 1 ; 

#---------------------------------------------------------------------------------------------------------------------------------------------------------------------

if ($is_operator && $glod_user_level == 2) { $glod_user_level = 3 ; } # upgrade operators level 2&3 to 3&4

our $nr_of_system_names_and_clubs = 15 ; our @all_select_ids = () ; our $minify_jquery = 1 ;

&db_open_ro ;
	$db_ignore_open_close = 1 ;

		&page_opts ;
		
		if ($iaction eq 'filter' || $iaction eq 'search' || $iaction eq 'report') {
			our $srchscr = 1 ;
			our $savjqy  = 0 ; 
		}

		#------------------------------------------------------------------------------------------------------------------------------------------------------------------

		our $table = 'demos';

		if ($iaction eq 'add') {
			&add_screen ;
			&common_min_screen1 ;
		} elsif ($iaction eq 'edit') {
			&common_min_load_params ;
			# $i{id}  = 1009 ;
			&edit_screen ;
			&common_min_screen1 ;
		} elsif ($iaction eq 'save') {
			&common_min_load_params ;
			&insert ;
			# &log_changes ;
			&edit_or_list ;
		} elsif ($iaction eq 'update') {
			&common_min_load_params ;
			&update ;
			# &log_changes ;
			&edit_or_list ;
		} elsif ($iaction eq 'copy') {
			&common_min_load_params ;
			&duplicate ;
			&edit_screen ;
			&common_min_screen1 ;
		} elsif ($iaction eq 'delete') {
			&common_min_load_params ;
			&delete ;
			&common_min_screen2 ;
		}
		
		&common_min_action ;
		
	$db_ignore_open_close = 0 ;
&db_close_conn ;

exit ;

#------------------------------------------------------------------------------------------

sub edit_or_list {
	
	exit if $testing && substr($username,0,4) eq 'rory' ; 
	$isaved = $i{id} ; 
    &edit_screen ;    
    &common_min_screen1;
	
} #------------------------------------------------------------------------------------------

sub insert {
	
	&build_system_details_table_fields($quote_accepted,$quote_rejected,$quote_cancelled) ;
	&process_multi_select($quote_accepted,$quote_rejected,$quote_cancelled) ;
	&add_db_fields ;
	&default_values ;
	
	$i{id} = &db_min_get_max($table,'id') ;
	
	our %i2 = () ; 
	
	&build_demos_min_fields_1 ;	
	
	&process_daily_details_from_the_events_datails_tab ; 
	
	&db_min_insert($table) ;

	our %ii = %i ;
	%i = () ;
	
	$i{id} 							= &db_min_get_max('event_quotes','id') ;
	$i{id}							= 1000 if $i{id} < 1000 ;
	$i{quote_nr} 					= $i{id} ;
	
	my $i_demo_id 					= $i{demo_id} ;
	my $i_event_id 					= $i{id} ;
	$i{datetime} 					= "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ;
	$i{quote_date} 					= "$now_ccyy_mm_dd" ;
	
	&build_event_quotes_fields ;

	&build_demos_min_fields_2 ;
	
	if ($ii{iattachslip}) {
		my $attachmentdir = $htmlpath . "/uploads/slips/$i_event_id" ;
		mkdir $attachmentdir if not -d $attachmentdir ; 
		&common_upload_files("slips/$i_event_id") ;
	}
	
	$i{quote_created} = 1 if $glod_user_level < 3 ;
	$i{quote_pending} = 1 unless $i{quote_accepted} || $i{quote_cancelled} || $i{quote_completed} || $i{quote_rejected} ;
	$ignore{quote_created} = '' ;
	$i{quote_created} = 0 unless $i{quote_created} ;
	
	$ignore{country_id} = 1 ; 
	
	&db_min_insert('event_quotes') ;
	
	$ignore{quote_created} = 1 ;
	
	my %iii = %i ; 
 
	%i = () ;
	$i{id} = $iii{id} ;
	$i{quote_nr} = $iii{id} ;
	
	if ($ii{custom_set}) {
		&build_demos_min_fields_3 ;
	} else {
		foreach (keys %i2) {
			$i{$_} = $i2{$_} ;
		}		
	}
	
	&db_min_insert('event_quotes_min') ;
	
	%i = %ii ;

	my $to = $email_events{1} ;  my $cc = "$email_events{2};$email_events{3};$email_events{6}" ; my $bcc = '' ; 
	
	if ($useropts{it}{$username}) {
		$to = $email_it_2 ; $cc = $email_it_1 ;  $bcc = '' ; 
	}
	
	&common_send_smtp_mail('',$to,$cc,$bcc,"Demo Created","Please note Demo $i_demo_id has been created as Event Quote $i_event_id",'','html','','','','',0,0) if $to || $cc || $bcc ;
	
} #------------------------------------------------------------------------------------------

sub update {
	
	unless ($i{id}) { 
		$error = qq(NO ID) ; 
		return ; 
	}
	
	&db_min_ro($table,"*","`id`='$i{id}'",'','') ;
	
	&db_min_ro('event_quotes','*',"demo_id='$i{id}'","",'') ; 
	
	our $event_quote_id = 0 ; 
	foreach (keys %{$db{event_quotes}}) {
		$event_quote_id = $_ ; 
	}

	my %iiii = %i ; 
	our %i2 = () ; 
	
	&build_system_details_table_fields($quote_accepted,$quote_rejected,$quote_cancelled) ;
	&process_multi_select($quote_accepted,$quote_rejected,$quote_cancelled) ;
	&add_db_fields ;
	&default_values ;
	
	&build_demos_min_fields_1 ;
	
	&process_daily_details_from_the_events_datails_tab ; 
	
	our $line = qq~~ ; 
	
	$ignore{country_id} = 1 ; 
	
	&common_shared_log_update_changes("demos","demo_changes","changes_demos") ;

	our %ii = %i ;
	%i = () ;
	
	$i{id} = $event_quote_id ;
	
	&build_event_quotes_fields ;
	
	&build_demos_min_fields_2 ;
	
	if ($ii{iattachslip}) {
		my $attachmentdir = $htmlpath . "/uploads/slips/$i{id}" ;
		mkdir $attachmentdir if not -d $attachmentdir ; 
		&common_upload_files("slips/$i{id}") ;
	}
	
 	$line = qq~~ ; 
	
	&common_shared_log_update_changes("event_quotes") ;
	
	%i = () ;
	
	if ($iiii{custom_set}) {
		&build_demos_min_fields_3 ;
	} else {
		foreach (keys %i2) {
			$i{$_} = $i2{$_} ;
		}		
	}
	
	$i{id} = $event_quote_id ;
	$i{quote_nr} = $event_quote_id ;
	
	foreach (keys %i) {
		$i{$_} =~ s/;+$//;
	}
	
	&common_shared_log_update_changes("event_quotes_min","event_quotes_changes","changes") ;
 
	%i = %iiii ;
	
} #------------------------------------------------------------------------------------------

sub build_event_quotes_fields {
	
	$i{last_update} 						= "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ;
	$i{demo_id} 							= $ii{id} ;
	$i{user_id}     						= $userid ;
	$i{date_from}							= $ii{date_from} ;
	$i{date_to}								= $ii{date_to} ;
	$i{ref}									= $ii{name} ;
	$i{event_system_id_multiple}			= $ii{event_system_id_multiple} ;
	$i{club_ids}							= $ii{club_ids} ;
	$i{operator_ids}						= $ii{operator_ids} ;
	$i{organisation_ids}					= $ii{venue_ids} ;
	$i{qty}									= $ii{qty} ;
	$i{slip}		 						= $ii{slip} ;
	$i{notes}		 						= $ii{notes} ;
	$i{office_notes} 						= $ii{office_notes}	;
	$i{email}		 						= $ii{email} ;
	$i{tel}			 						= $ii{tel} ;
	$i{address}		 						= $ii{address} ;
	$i{contact_name} 						= $ii{contact_name}	;
	$i{currency} 							= $ii{currency}	;
	$i{roe} 								= $ii{roe}	;
	$i{region_id}							= $ii{region_id} ;
	$i{quote_to}							= $ii{quote_to} ;
	$i{quote_accepted}						= $ii{quote_accepted} ;
	$i{quote_pending}						= $ii{quote_pending} ;
	$i{quote_cancelled}						= $ii{quote_cancelled} ;
	$i{quote_completed}						= $ii{quote_completed} ;
	# $i{quote_created}						= $ii{quote_created} ;
	$i{quote_rejected}						= $ii{quote_rejected} ;
	$i{times_from}   						= $ii{times_from}   ;
	$i{times_to}	  						= $ii{times_to}	 ;
	$i{days_active}  						= $ii{days_active}  ;
	$i{event_length} 						= $ii{event_length} ;
	$i{custom_set}							= $ii{custom_set}	 ;
	$i{total_amount_workings_event} 	 	= $ii{total_amount_workings_event}  ;
	$i{total_vat_amount_workings_event}		= $ii{total_vat_amount_workings_event}      ;
	$i{total_grand_amount_workings_event}	= $ii{total_grand_amount_workings_event}    ;
	$i{sport_type_ids}						= $ii{sport_type_ids}    ;
	$i{slip} 								= ($ii{iattachslip}) ? "slip-$ii{iattachslip}" : "" ; 
	
	my @quote_to_splt = split(/\:/,$i{quote_to}) ; 
	$i{quote_to} = $quote_to_splt[0] ;
	
  	$ignore{date_from} 							= '' ;
	$ignore{date_to} 							= '' ;
	$ignore{event_system_id_multiple}			= '' ;
	$ignore{club_ids}							= '' ;
	$ignore{operator_ids}						= '' ;
	$ignore{slip}		 						= '' ;
	$ignore{notes}		 						= '' ;
	$ignore{office_notes} 						= '' ;
	$ignore{email}		 						= '' ;
	$ignore{tel}			 					= '' ;
	$ignore{address}		 					= '' ;
	$ignore{contact_name} 						= '' ;
	$ignore{currency} 							= '' ;
	$ignore{quote_nr} 							= '' ;
	$ignore{roe} 								= '' ;
	$ignore{quote_to}							= '' ;
	$ignore{qty}								= '' ;
	$ignore{organisation_ids}					= '' ;
	$ignore{ref}								= '' ;
	$ignore{demo_id}							= '' ;
	$ignore{user_id}							= '' ;
	$ignore{quote_date}							= '' ;
	$ignore{quote_accepted}						= '' ;
	$ignore{quote_pending}						= '' ;
	$ignore{quote_cancelled}					= '' ;
	$ignore{quote_completed}					= '' ;
	# $ignore{quote_created}						= '' ;
	$ignore{quote_rejected}						= '' ;
	$ignore{times_from}   						= '' ;
	$ignore{times_to}	  						= '' ;
	$ignore{days_active}  						= '' ;
	$ignore{event_length} 						= '' ;
	$ignore{custom_set}							= '' ; 
	$ignore{total_amount_workings_event} 		= '' ; 
	$ignore{total_vat_amount_workings_event}	= '' ; 
	$ignore{total_grand_amount_workings_event}  = '' ;
	$ignore{sport_type_ids}						= '' ;
	$ignore{region_id}							= '' ;
	
} #------------------------------------------------------------------------------------------

sub process_daily_details_from_the_events_datails_tab {
		
	my ($id) = @_ ; 
	
	use Time::Piece;
	
	my $final_day = &common_min_calc_day_diff($i{date_to},$i{date_from}) ;
	
	# for (1 .. 20) {
		# $final_day = $_ if $i{"day_$_"} ;
	# }
	
	for my $event_day (1 .. 20) {
		
		$ignore{"time_from_$event_day"} = 1 ;
		$ignore{"time_to_$event_day"} = 1 ;
		$ignore{"day_$event_day"} = 1 ;
		$ignore{"event_length_$event_day"} = 1 ;
		$ignore{"selected_$event_day\_event_length"} = 1 ;
		
		$i{times_from} .= qq~$i{"time_from_$event_day"};~ if $event_day > 1 && $i{"day_$event_day"} ;
		$i{times_from} .= qq~;~ if $event_day > 1 && !$i{"day_$event_day"} ;

		$i{times_to} .= qq~$i{"time_to_$event_day"};~ if $event_day < $final_day && $i{"day_$event_day"} ;
		$i{times_to} .= qq~;~ if $event_day < $final_day && !$i{"day_$event_day"} ;

		$i{days_active} .= qq~$i{"day_$event_day"};~ ;
		$i{event_length} .= ($i{"day_$event_day"}) ? qq~$i{"event_length_$event_day"};~ : qq~;~ ;
	}
	
	# chop $i{times_from} 	if $i{times_from} ;
	# chop $i{times_to} 		if $i{times_to} ;
	# chop $i{days_active} 	if $i{days_active} ;
	# chop $i{event_length} 	if $i{event_length} ;

	$i{times_from}			=~ s/([^;])(;+)\z/$1/;
	$i{times_to}			=~ s/([^;])(;+)\z/$1/;
	$i{days_active}			=~ s/([^;])(;+)\z/$1/;
	$i{event_length}		=~ s/([^;])(;+)\z/$1/;	
	
	# $i{times_from}			=~ s/;+$//;
	# $i{times_to}			=~ s/;+$//;
	# $i{days_active}			=~ s/;+$//;
	# $i{event_length}		=~ s/;+$//;
	
	$ignore{times_from}   	= 1 ;
	$ignore{times_to}	  	= 1 ;
	$ignore{days_active}  	= 1 ;
	$ignore{event_length} 	= 1 ;
	
} #------------------------------------------------------------------------------------------

sub default_values {
	
	$i{events_operator_required} 	= 0 unless $i{events_operator_required} ;
	$i{calibrator_required} 		= 0 unless $i{calibrator_required} ;
	$i{demo_type_id} 				= 0 unless $i{demo_type_id} ;
	$i{calibrator_required} 		= 0 unless $i{calibrator_required} ;
	$i{events_operator_allocated} 	= 0 unless $i{events_operator_allocated} ;
	$i{location_id} 				= 0 unless $i{location_id} ; 
	$i{quote_accepted}				= 0 unless $i{quote_accepted} ;
	$i{quote_pending}				= 0 unless $i{quote_pending} ;
	$i{quote_cancelled}				= 0 unless $i{quote_cancelled} ;
	$i{quote_completed}				= 0 unless $i{quote_completed} ;
	$i{quote_created}				= 0 unless $i{quote_created} ;
	$i{quote_rejected}				= 0 unless $i{quote_rejected} ;
	$i{custom_set} 					= 0 unless $i{custom_set} ; 
	
} #------------------------------------------------------------------------------------------

sub send_email_to_manager {
	
	my ($event_id,$status,$msg) = @_ ; 
	
	return if $username eq 'marizen' ; # don't send to marizen if she did the change.
	
	my $usernametemp = (substr($username,0,4) eq 'rory') ? 'rory' : $username ;
	
	my $attachpath = "$pdfpath/event_details" ;  $attachfile = "Event_Details-$event_id.pdf" ;
	
	my $subj  = 'Event [' . $event_id . ']' ;
	   $subj .= " $status" if $status ;
	   $subj .= " by $username" if $username ;
	   $subj .= " : $i{ref}" if $i{ref} ;

	my $event_details_pdf = get("$useropts{domain}$useropts{'scripts'}/pdf/event_details_pdf.pl?$event_id&&") ;
	my $to  = ($useropts{it}{$usernametemp}) ? "$usernametemp\@kre8it.co.za" : $email_events{1} ; 
	$got_mail_add{$to} = 1 ;
	my $cc  = ($is_schools_manager) ? "$useremail" : (!$got_mail_add{$useremail}) ? "$useremail" : '' ; 
	# my $bcc = ($useropts{it}{$usernametemp}) ? '' : 'rory@kre8it.co.za' ;
	my $bcc = '' ;
	&common_send_smtp_mail('',$to,$cc,$bcc,"$subj","<a href=$useropts{domain}$useropts{scripts}/pdf/event_details_pdf.pl?$event_id&&>Click here to view event details</a><br><br>$msg",'','html','',$attachpath,$attachfile,'',0,0) ;
	
} #------------------------------------------------------------------------------------------

sub build_system_details_table_fields {
	
	my ($quote_accepted,$quote_rejected,$quote_cancelled) = @_ ; 
	
	# $i{operator_ids} .= qq~;\~;~ ; 
	my $cnt_last_row = 0 ; 
	for (1 .. $nr_of_system_names_and_clubs) {
		
		my $system_name        = "system_name_$_" ;
		my $club_name          = "club_name_$_" ;
		my $op_name            = "operator_id_calibration_$_" ;		
 
		$cnt_last_row = $_ if $i{$system_name} || $i{$club_name} ; 
		
		$ignore{$system_name}  = 1 ; 
		$ignore{$club_name}    = 1 ; 
		$ignore{$op_name}      = 1 ; 
	}
	
	return if ($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3 ;
 
	unless ($cnt_last_row) {
		$i{club_ids} = qq~~ ;
		$i{event_system_id_multiple} = qq~~ ;
		return ;
	}
 
	# return if $is_schools_manager ;
	# return if $glod_user_level < 4 ;
	# return if $glod_user_level < 3 ;
	
	$i{operator_ids} = '' ; my $table_row_cnt = 0 ; 
	
	for (1 .. $nr_of_system_names_and_clubs) {
		
		my $system_name        = "system_name_$_" ;
		my $club_name          = "club_name_$_" ;
		my $op_name            = "operator_id_calibration_$_" ;
		
		$i{club_ids}                 .= qq~$i{$club_name};~ ;
		$i{event_system_id_multiple} .= qq~$i{$system_name};~ ;
		$i{operator_ids}             .= qq~$i{$op_name},~ if $_ <= $cnt_last_row ;
		
		$table_row_cnt++ if $i{$club_name} || $i{$system_name} ;
		
	}
 
	my @saved_operator_ids = split(/\,/,$db{event_quotes}{$event_quote_id}{operator_ids}) ;
	
	$i{operator_ids} .= join(',', @saved_operator_ids[$table_row_cnt .. $#saved_operator_ids]);

	$ignore{club_name} = 1 ; 
	# chop $i{club_ids} if $i{club_ids} ; chop $i{event_system_id_multiple} if $i{event_system_id_multiple} ; 
	# chop $i{operator_ids} if $i{operator_ids} ;
 
	$i{club_ids} 					=~ s/;+$//;
	$i{event_system_id_multiple} 	=~ s/;+$//;
	$i{operator_ids} 				=~ s/,+$//; 
 
} #------------------------------------------------------------------------------------------

sub build_demos_min_fields_1 {
	
	my ($id) = @_ ; 
	
	for (1 .. 50) {
			
		$y{7}{$_}  = "excl_workings_event_$_" ;		
		$y{8}{$_}  = "description_workings_event_$_" ;		
		$y{9}{$_}  = "operator_workings_event_$_" ;		
		$y{10}{$_} = "remarks_workings_event_$_" ;
		$y{11}{$_} = "supplier_workings_event_$_" ;		
		$y{12}{$_} = "ref_nr_workings_event_$_" ;	
		$y{13}{$_} = "qty_workings_event_$_" ;		
		$y{14}{$_} = "amount_usd_workings_event_$_" ;		
		$y{15}{$_} = "amount_ttl_workings_event_$_" ;
		$y{16}{$_} = "vat_workings_event_$_" ; 
 
		foreach my $a (keys %y) {
			foreach my $b (keys %{$y{$a}}) {
				$ignore{$y{$a}{$b}} = 1 ; 
				$x{$a}{$b} = $i{$y{$a}{$b}} ; 
			} 
		}
	}

	$ignore{sub_total_workings_event}  	= 1 ;	
	$ignore{vat_total_workings_event}  	= 1 ;	
	$ignore{grand_total_workings_event} = 1 ;	

	$ignore{total_amount_workings_event} 		= 1 ; 
	$ignore{total_vat_amount_workings_event}	= 1 ; 
	$ignore{total_grand_amount_workings_event}  = 1 ;

	if ($i{custom_set}) {
		$i{total_amount_workings_event} = $i{sub_total_workings_event} ; 
		$i{total_vat_amount_workings_event}  = $i{vat_total_workings_event} ; 
		$i{total_grand_amount_workings_event}  = $i{grand_total_workings_event} ; 
		return ; 	
	}

	$i{sub_total_workings_event} = 0 ; 
	$i{vat_total_workings_event} = 0 ; 
	$i{grand_total_workings_event} = 0 ; 
	
	for my $system_name_row_nr (1 .. 15) {
		
		my $field = "operator_id_calibration_$system_name_row_nr" ; 
		next unless $i{$field} ;
				
		for my $days (1 .. 20)  {
			my $day_field = "day_$days" ;
			next unless $i{$day_field} ;
			$operator_day_count{full_day}{$i{$field}}++ if $i{"event_length_$days"} eq '1' ; 
			$operator_day_count{half_day}{$i{$field}}++ if $i{"event_length_$days"} eq '2' ; 
		} 
	}
	
	my %iii = %i ; 
	
	for (1 .. 50) {
		
		if ($i{"description_workings_event_$_"} eq '14' && $i{"operator_workings_event_$_"}) {
			my $op = $i{"operator_workings_event_$_"} ;
			my $day_len = ($i{"amount_usd_workings_event_$_"} eq '1000.00') ? "full_day" : ($i{"amount_usd_workings_event_$_"} eq '750.00') ? "half_day" : "" ;
			if ($day_len && ($operator_day_count{full_day}{$op} || $operator_day_count{half_day}{$op})) {
				$saved_values{$day_len}{$op}{saved_values} 				= 1 ;
				$saved_values{$day_len}{$op}{supplier_workings_event} 	= $i{"supplier_workings_event_$_"} ; 
				$saved_values{$day_len}{$op}{ref_nr_workings_event} 	= $i{"ref_nr_workings_event_$_"} ; 
				$saved_values{$day_len}{$op}{remarks_workings_event} 	= $i{"remarks_workings_event_$_"} ; 
				$saved_values{$day_len}{$op}{vat_workings_event} 		= $i{"vat_workings_event_$_"} ; 		
				$saved_values{$day_len}{$op}{excl_workings_event} 		= $i{"excl_workings_event_$_"} ; 		
				# $saved_values{$day_len}{$op}{amount_usd_workings_event} = $i{"amount_usd_workings_event_$_"} if $day_len eq "other" ; 		
			} 
		}
		$i{"description_workings_event_$_"}	= "" ;
		$i{"operator_workings_event_$_"}	= "" ;
		$i{"qty_workings_event_$_"}	 		= "" ;
		$i{"amount_usd_workings_event_$_"}	= "" ;
		$i{"amount_ttl_workings_event_$_"}	= "" ;
		$i{"excl_workings_event_$_"}		= "1";
		$i{"vat_workings_event_$_"}			= "" ;		
		$i{"supplier_workings_event_$_"}	= "" ;		
		$i{"ref_nr_workings_event_$_"}		= "" ;		
		$i{"remarks_workings_event_$_"}		= "" ;
		
	}
 	
	my $row_cnt = 0 ; 
	
	foreach my $len (sort keys %operator_day_count) {
		
		foreach $op_id (sort keys %{$operator_day_count{$len}}) {
		
			$row_cnt++ ; 
			$i2{description_workings_event} 	.= '14;' ;
			$i2{operator_workings_event}		.= "$op_id;" ;
			$i2{qty_workings_event}	 			.= "$operator_day_count{$len}{$op_id};" ;
			
			# my $custom_saved_amnt = $saved_values{"other"}{$op_id}{amount_usd_workings_event} ;
			
			$i2{amount_usd_workings_event}		.= ($len eq "full_day") ? '1000.00' : ($len eq "half_day") ? '750.00' : '0.00' ;
			$i2{amount_usd_workings_event}		.= qq~;~ ;  
			my $amnt 							= ($len eq "full_day") ? 1000 * $operator_day_count{$len}{$op_id} * $i{roe} : ($len eq "half_day") ? 750 * $operator_day_count{$len}{$op_id} * $i{roe} : 0 ;
			$amnt	 							= sprintf ("%0.2f",$amnt) ; 
			
			$i2{amount_workings_event}			.= "$amnt;" ; 
			$i{sub_total_workings_event} 		+= $amnt if !$saved_values{$len}{$op_id}{excl_workings_event} ;
			if ($saved_values{$len}{$op_id}{saved_values}) {
				foreach (keys %{$saved_values{$len}{$op_id}}) {
					$i2{$_} .= qq~$saved_values{$len}{$op_id}{$_};~ if $_ ne "saved_values" ;
					$i{vat_total_workings_event} += $amnt*0.15 if !$saved_values{$len}{$op_id}{excl_workings_event} && $saved_values{$len}{$op_id}{vat_workings_event} && $_ eq "vat_workings_event" ;
				}
			} else {
				$i2{supplier_workings_event}	.= ";" ; 
				$i2{ref_nr_workings_event}		.= ";" ; 
				$i2{remarks_workings_event}		.= ";" ; 
				$i2{vat_workings_event}			.= "1;" ; 
				$i2{excl_workings_event}		.= "0;" ;
				$i{vat_total_workings_event}	+= $amnt*0.15 ;
			}
		}
	}

	for (1 .. 50) { 
	
		if ($iii{"description_workings_event_$_"} && $iii{"description_workings_event_$_"} ne '14') {
			$row_cnt++ ; 
			$i2{"excl_workings_event"} 			.= qq~$iii{"excl_workings_event_$_"};~ ;
			$i2{"description_workings_event"} 	.= qq~$iii{"description_workings_event_$_"};~ ;
			$i2{"operator_workings_event"}		.= qq~$iii{"operator_workings_event_$_"};~ ; 
			$i2{"remarks_workings_event"} 		.= qq~$iii{"remarks_workings_event_$_"};~ ;
			$i2{"supplier_workings_event"}		.= qq~$iii{"supplier_workings_event_$_"};~ ;
			$i2{"ref_nr_workings_event"} 		.= qq~$iii{"ref_nr_workings_event_$_"};~ ;
			$i2{"qty_workings_event"}	 		.= qq~$iii{"qty_workings_event_$_"};~ ;
			$i2{"amount_usd_workings_event"} 	.= qq~$iii{"amount_usd_workings_event_$_"};~ ;
			$i2{"amount_workings_event"} 		.= qq~$iii{"amount_ttl_workings_event_$_"};~ ;
			$i2{"vat_workings_event"} 			.= qq~$iii{"vat_workings_event_$_"};~ ; 		
			$iii{"amount_ttl_workings_event_$_"} =~ s/\,//g ; 
			$i{sub_total_workings_event} 		+= $iii{"amount_ttl_workings_event_$_"} if !$iii{"excl_workings_event_$_"} ;
			$i{vat_total_workings_event} 		+= $iii{"amount_ttl_workings_event_$_"} * 0.15 if !$iii{"excl_workings_event_$_"} && $iii{"vat_workings_event_$_"} ;
	
		}  
	}
	
	unless ($row_cnt) {
		$i2{excl_workings_event} 		= qq~~ ;
		$i2{description_workings_event} = qq~~ ;
		$i2{operator_workings_event}	= qq~~ ;
		$i2{remarks_workings_event} 	= qq~~ ;
		$i2{supplier_workings_event}	= qq~~ ;
		$i2{ref_nr_workings_event} 		= qq~~ ;
		$i2{qty_workings_event}	 		= qq~~ ;
		$i2{amount_usd_workings_event} 	= qq~~ ;
		$i2{amount_workings_event} 		= qq~~ ;
		$i2{vat_workings_event} 		= qq~~ ;
	}

} #------------------------------------------------------------------------------------------

sub build_demos_min_fields_2 {
	
	$i{total_amount_workings_event} = sprintf("%0.2f",$ii{sub_total_workings_event}) ;
	$i{total_vat_amount_workings_event} = sprintf("%0.2f",$ii{vat_total_workings_event}) ;
	$i{total_grand_amount_workings_event} = sprintf("%0.2f",$ii{sub_total_workings_event}+$ii{vat_total_workings_event}) ;
	
} #------------------------------------------------------------------------------------------

sub build_demos_min_fields_3 {
	
	for (1 .. 50) {
		next unless $x{8}{$_} ;
		$i{excl_workings_event}			.= "$x{7}{$_};";
		$i{description_workings_event} 	.= "$x{8}{$_};";
		$i{operator_workings_event}    	.= "$x{9}{$_};";
		$i{remarks_workings_event} 	   	.= "$x{10}{$_};";
		$i{supplier_workings_event}    	.= "$x{11}{$_};";
		$i{ref_nr_workings_event} 	   	.= "$x{12}{$_};";
		$i{qty_workings_event} 		   	.= "$x{13}{$_};";
		$i{amount_usd_workings_event}  	.= "$x{14}{$_};";
		$i{amount_workings_event} 	   	.= "$x{15}{$_};";
		$i{vat_workings_event} 		   	.= "$x{16}{$_};"; 	
	}
	
	$i{excl_workings_event}			= "" unless $i{excl_workings_event}			;
	$i{description_workings_event} 	= "" unless $i{description_workings_event} ;
	$i{operator_workings_event}    	= "" unless $i{operator_workings_event}    ;
	$i{remarks_workings_event} 	   	= "" unless $i{remarks_workings_event} 	   ;
	$i{supplier_workings_event}    	= "" unless $i{supplier_workings_event}    ;
	$i{ref_nr_workings_event} 	   	= "" unless $i{ref_nr_workings_event} 	   ;
	$i{qty_workings_event} 		   	= "" unless $i{qty_workings_event} 		   ;
	$i{amount_usd_workings_event}  	= "" unless $i{amount_usd_workings_event}  ;
	$i{amount_workings_event} 	   	= "" unless $i{amount_workings_event} 	   ;
	$i{vat_workings_event} 		   	= "" unless $i{vat_workings_event} 		   ;	
	
} #------------------------------------------------------------------------------------------

sub process_multi_select {
	
	my ($quote_accepted,$quote_rejected,$quote_cancelled) = @_ ; 

	local @venueids      				= split(/\,/,$i{venueids}) ;
	my $venueids         				= join(",",@venueids) ;
	$venueids            				=~ s/\s//g; # remove white space
	$ignore{venueids}    				= 1 ;
	$i{venue_ids}       				= $venueids ;
	$i{venue_ids}       				= 0 unless $i{venue_ids} ;
	
	$ignore{eventsoperatorallocated} 	= 1 ;
	$i{events_operator_allocated} 		= $i{eventsoperatorallocated} ;
	$i{events_operator_allocated} 		=~ s/\,/\;/g ;
	$i{events_operator_allocated} 		=~ s/\s//g; # remove white space
	
	$i{sport_type_ids} 					= $i{sporttypeids} ;
	$ignore{sporttypeids} 				= 1 ;
	$i{sport_type_ids} 					=~ s/\s//g; # remove white space
	
} #------------------------------------------------------------------------------------------

sub duplicate {

	unless ($i{id}) { 
		$error = qq~NO ID~ ; 
		return ; 
	}

	my $demo_orig_id = $i{id} ;
	
	&db_min_copy($table,$i{id}) ;
	
	my $demo_copy_id = $i{id} ;

	&db_min_ro('event_quotes','1,id',"demo_id='$demo_orig_id'","",1) ; 
	
	my $orig_event_id = $db{event_quotes}{1}{id} ;
	
	$i{id} = $orig_event_id ;
	
	&db_min_copy('event_quotes',$db{event_quotes}{1}{id}) ;
	
	my $event_copy_id = $i{id} ;
	
	$i{id} = $orig_event_id ;

	&db_min_copy('event_quotes_min',$orig_event_id) ;
	
	my %ii = %i ; 
	
	%i = () ; 
	
	$i{demo_id} = $demo_copy_id ;
	
	&db_min_upd('event_quotes',"id='$event_copy_id'") ; 
	
	%i = () ; 
	
	$i{quote_nr} = $event_copy_id ;
	
	&db_min_upd('event_quotes_min',"id='$event_copy_id'") ; 
	
	%i = %ii ;
	
	$i{id} = $demo_orig_id ;
 
} #------------------------------------------------------------------------------------------

sub delete {

	unless ($i{id}) { $error = uc "NO ID" ; return ; }

	&db_min_ro('event_quotes','1,id',"demo_id = '$i{id}'",'','1') ;
	
	my $event_delete_id = $db{event_quotes}{1}{id} ; 
	
	&db_min_delete('demos',"`id`='$i{id}'") ;
	&db_min_delete('event_quotes',"`id`='$event_delete_id'") ;
	&db_min_delete('event_quotes_min',"`id`='$event_delete_id'") ;
	
} #------------------------------------------------------------------------------------------

sub process_upload_ifields {

	foreach (keys %uploads_file) { $i{$_} = $uploads_file{$_} ; $ignore{$_} = '' ; }

} #------------------------------------------------------------------------------------------

sub set_default_i_vals {

} #----------------------------------------------------------------------------------------

sub list_screen {
	
	&db_min_ro('event_type_details','id,name','','','') ;	
	&db_min_ro('event_quotes_categories','id,category','','','') ;	
	&db_min_ro('event_systems','id,name,description,system_type','','','') ;
	&db_min_ro('clubs','id,name','','','') ;	
	&db_min_ro('cities','id,city,province','','','') ;	
	
	&db_min_ro('users','id,username,name,email','','','') ;	
	foreach my $_id (keys %{$db{users}}) { 
		$username{$_id} = $db{users}{$_id}{username} ; 
		$name{$_id}     = $db{users}{$_id}{name} ; 
		$email{$_id}    = $db{users}{$_id}{email} ; 
	}
		
	&db_min_ro('sport_types','*','','','') ;
	
	&db_min_ro('organisations','id,name','','','') ;
	foreach my $_id (keys %{$db{organisations}}) { $organisation{$_id} = $db{organisations}{$_id}{name} ; }
	
	if ($iaction eq 'completed' or $i{options} eq 'completed')  { push @report_sql, "q.quote_completed='1'" ; }
	if ($iaction eq 'accepted' 	or $i{options} eq 'accepted')  	{ push @report_sql, "q.quote_accepted='1'" ; }
	if ($iaction eq 'rejected' 	or $i{options} eq 'rejected')  	{ push @report_sql, "q.quote_rejected='1'" ; }
	if ($iaction eq 'closed' 	or $i{options} eq 'closed')    	{ push @report_sql, "(q.quote_cancelled='1' OR (q.quote_expiry<'$now_year-$now_mm-$now_dd' AND q.quote_accepted<>'1'))" ; }
	if ($iaction eq 'pending' 	or $i{options} eq 'pending')   	{ push @report_sql, "q.quote_pending='1'" ; }
	if ($iaction eq 'list' 		or $i{options} eq 'list')      	{ push @report_sql, "q.quote_cancelled<>'1'" ; }

	my $t1 = 'event_quotes';
	my $t2 = 'cities' ;		
	my $t3 = 'customers' ;
	my $t4 = 'regions' ;
	my $t5 = 'demos' ;
	my $t6 = 'event_types' ;
	my $t7 = 'demo_tenants' ;
	
	our $tables = "$t1,$t2,$t3,$t4,$t5,$t6,$t7" ;
	
	if ($is_schools_manager || $is_operator) {
		@report_sql_or = () ;
		foreach $_reg_id (keys %{$glob_regids{$userid}}) {
			push @report_sql_or, "q.region_id = '$_reg_id'"
		}
		my $sql_or = join(' OR ',@report_sql_or) ;
		push @report_sql, "($sql_or)" if $sql_or ; 
		push @report_sql, "(q.quote_created='1')" if $is_schools_manager ;  
		# push @report_sql, "(q.user_id='$userid')" if $is_schools_manager ;  
		push @report_sql, "(q.quote_accepted='1')" if $is_operator && !$i{options} ;  
	}
	
	push @report_sql, "(q.quote_completed <> '1')" if $iaction eq 'list' ;  
	push @report_sql, "(q.demo_id <> '0')" if $iaction eq 'list' ;  
	
	my $srch_where_sql = join(' AND ', @report_sql) ; my $sql_where = ($srch_where_sql) ? "WHERE $srch_where_sql" : '' ;
	
	&db_min_raw("
		SELECT 
			q.id AS 'quote_id',
			q.quote_nr,
			q.sport_type_ids,
			q.organisation_ids,							
			q.date_from,
			q.date_to,
			q.ref,
			q.qty,
			q.quote_date,
			q.activetab,
			q.user_id, 
			q.operator_ids,
			q.event_system_id_multiple,
			q.club_ids,
			q.demo_id,
			q.quote_accepted,
			q.quote_pending,
			q.quote_cancelled,
			q.quote_completed,
			q.quote_created,
			q.quote_rejected,
			et.name AS 'event_type',
			t.name AS 'customer',
			y.city,		
			y.province,							
			r.code AS 'reg_code',	
			r.name AS 'region',
			dt.name AS 'tenant',
			demo.location_id AS 'location_id',
			demo.events_operator_allocated
		FROM $t1 q 
		LEFT JOIN $t2 y ON q.city_id    = y.id
		LEFT JOIN $t3 t ON q.quote_to   = t.id
		LEFT JOIN $t4 r ON q.region_id  = r.id
		LEFT JOIN $t5 demo ON q.demo_id = demo.id
		LEFT JOIN $t6 et ON q.type = et.id
		LEFT JOIN $t7 dt ON demo.tenant_id = dt.id
		$sql_where ;
	");
	
	foreach $row (@$rows_array_ref) {        
		for (0 .. $col_cnt){
			# &common_debug("[$_] $col_name{$_} -> @$row[$_]") ;
			$db{$tables}{@$row[0]}{$col_name{$_}} = @$row[$_] ;
		}    
	}
	
	# &tab_hash ; # load for PDF links
	&quote_list ; # load for PDF links

	if ($iaction eq 'update' or $iaction eq 'save'){
		&common_min_extra_crumb("list-$lcpage\s","List $ucfirstpage\s") ;
	}
	
	our $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab
	
} #------------------------------------------------------------------------------------------

sub quote_list {
	
	# our @sql_col_display = ("nr","date","customer","user","event","venue","location","sports_type","date_from","date_to","days","type") ;
	# our @sql_col_display = ("nr","event_start","event_end","date_added","customer","user","event","venue","location","sports_type","days","type") ;
	
	our @col_display_excel = () ; our @sql_col_display = () ;
	
	if ($usertype eq 'support') {
		@sql_col_display   = ("nr","event_start","days","event","location","sport","system_name","club_names","operators") ;
		# @col_display_excel = @sql_col_display ; 
	} else {
		@sql_col_display = ("nr","event_start","event_end","days","date_added","customer","event","venue","location","sport","tenant","operators") ;
		if ($userid eq '24') {
		# if ($glod_user_level > 3) {
			push @sql_col_display, "amount" ;
			push @sql_col_display, "invoice_nr" ;
		}
		# @col_display_excel = ("nr","event","event_start","event_end","days","type_of_system","system_details","system_name","sport_type","cities","region","venue","club_names","operators","client","poc_name","poc_contact_nr","category_1","category_1_details","category_2","category_2_details","format_of_title") ; 
	}
	
	@col_display_excel = @sql_col_display ; 
	
	push @sql_col_display, "" ;
	
	&report_xlsx_export_header("Demos",'demos') ; 
	
	my @month_fullname     = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") ; # if ($i{export_to_excel}) { &report_xls_export_header("Event Quotes",'event_quotes') ; }
	my @day_of_week_text   = ("", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday") ;
	
	our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ;
	
	foreach my $id (sort {$b <=> $a} keys %{$db{$tables}}) {
		
		next unless $id ; 
		
		my $quote_expiry   		= $db{$tables}{$id}{quote_expiry} ; $quote_expiry =~ s/\-//iog ;
		my $invoice_nr     		= $db{$tables}{$id}{invoice_nr} ;
		our $quote_accepted 	= $db{$tables}{$id}{quote_accepted} ;		
		our $quote_pending  	= $db{$tables}{$id}{quote_pending} ;
		our $quote_cancelled	= $db{$tables}{$id}{quote_cancelled} ;
		our $quote_completed	= $db{$tables}{$id}{quote_completed} ;
		our $quote_created  	= $db{$tables}{$id}{quote_created} ;
		our $quote_rejected		= $db{$tables}{$id}{quote_rejected} ;
		my $demo_completed		= $db{$tables}{$id}{demo_completed} ;
		my @cat_details 		= split('\|;\|',$db{$tables}{$id}{category_details}) ;
		
		if ($usertype eq 'support') {
			next unless $quote_accepted && !$quote_completed ;
		}

		$print_tbody .= qq~<tr>~ ;
		
		$xlsxcol=0;
		
		my $quote_nr = $db{$tables}{$id}{quote_nr} ;
# ("nr","event_start","event_end","days","date_added","customer","event","venue","location","sport","type","operators") 
		foreach (@sql_col_display) {
 
			unless ($_) { next ; } # blank for the buttons column
			my $val = $db{$tables}{$id}{$_} ;
			my $align = qq~ class="dt-center"~ ; 
			my $nowrap = '' ;
			my $val_xlsx = '' ;
			my $formating = $format_event_data_2 ;
			
			if ($_ eq 'event_end') {  
				my $sort_val = $db{$tables}{$id}{date_to} =~ s/[\-:\s]//gr;
				$val_xlsx = &common_min_date_as_string(substr($db{$tables}{$id}{date_to},0,16)) ;
				$val   = qq~<span style='display:none;'>$sort_val</span>~ . $val_xlsx ; $align = qq~ class="dt-center"~ ; $nowrap = 'nowrap' ; 
			} elsif ($_ eq 'event_start')	{  
				my $sort_val = $db{$tables}{$id}{date_from} =~ s/[\-:\s]//gr;
				$val_xlsx = &common_min_date_as_string(substr($db{$tables}{$id}{date_from},0,16)) ;
				$val = qq~<span style='display:none;'>$sort_val</span>~ . $val_xlsx ;
				# my ($dy,$dm,$dd,$th,$tm,$ts) = &common_min_split_sql_date_time($db{$tables}{$id}{date_from}) ; my $sccyymmddhrmnsc = $dy . $dm . $dd . $th . $tm . $ts ; $val = "<span style='display:none'>$sortprefix$sccyymmddhrmnsc</span>" . substr($db{$tables}{$id}{date_from},0,16) ; 
				$nowrap = 'nowrap' ; 
			} elsif ($_ eq 'event') {
				$val = $db{$tables}{$id}{ref} ; 
				# $val_xlsx = $val ;
				$nowrap = '' ;
			} elsif ($_ eq 'customer') { 
				$nowrap = 'nowrap' ; 
				$val = "***PLEASE SELECT A CUSTOMER!!!***" unless $val ;
				# $val_xlsx = $val ;
			} elsif ($_ eq 'date_added') {
				my $sort_val = $db{$tables}{$id}{quote_date} =~ s/[\-:\s]//gr;
				$val_xlsx = &common_min_date_as_string($db{$tables}{$id}{quote_date}) ; 
				$val =  qq~<span style='display:none;'>$sort_val</span>~ . $val_xlsx ; 
				$val = qq~<span title data-toggle="tooltip" data-placement="top" data-original-title="Added By: $username{$db{$tables}{$id}{user_id}}">$val</span>~ ; 
				$nowrap = 'nowrap' ; 
			} elsif ($_ eq 'curr') { 
				$val = $db{$tables}{$id}{currency} ; 
			} elsif ($_ eq 'location') { 
				# $val = ($db{$tables}{$id}{city} & $db{$tables}{$id}{reg_code}) ? "$db{$tables}{$id}{city}, $db{$tables}{$id}{reg_code}" : ($db{$tables}{$id}{city}) ? $db{$tables}{$id}{city} : $db{$tables}{$id}{reg_code} ; 
				$nowrap = 'nowrap' ; 
				$val = ($db{$tables}{$id}{location_id} eq '1') ? "In Country" : ($db{$tables}{$id}{location_id} eq '2') ? "Out of Country" : "" ;
			} elsif ($_ eq 'country_id') { 
				$val = $db{$tables}{$id}{country} ; 
			} elsif ($_ eq 'days') { 
				$val = $db{$tables}{$id}{qty} ; 
				# $val_xlsx = $val ;
			} elsif ($_ eq 'type') {  
				my $txt = uc substr($db{$tables}{$id}{event_type},0,1) ; 
				$val_xlsx = $db{$tables}{$id}{event_type} ;
				$val = qq~<a href="#" data-title="$val_xlsx" data-toggle="tooltip" data-placement="left"><strong>$txt</strong></a>~ if $val_xlsx ; 
				$nowrap = 'nowrap' ; 
			} elsif ($_ eq 'tenant') {  
				$val = $db{$tables}{$id}{tenant} ;
				$nowrap = 'nowrap' ; 
			} elsif ($_ eq 'amount') {   
				my $ttl = sprintf("%0.2f",($db{$tables}{$id}{grand_total})) ; 
				$val = &common_commify($ttl) ; 
			} elsif ($_ eq 'system_name') {
				$val = join("<br>", map { "$db{event_systems}{$_}{name} [$db{event_systems}{$_}{description}]" } split(/\;/,$db{$tables}{$id}{event_system_id_multiple})) ;
			} elsif ($_ eq 'club_names') {
				$val = join("<br>", map { "$db{clubs}{$_}{name}" } split(/\;/,$db{$tables}{$id}{club_ids})) ;
			} elsif ($_ eq 'operators') {
				$val = '' ; my $op_cnt = 0 ; my $op_cnt_2 = 0 ; 
				my %seen_op_id = () ;
				# my $ops_orig = $db{$tables}{$id}{operator_ids} ;
				$db{$tables}{$id}{operator_ids} =~ s/\,/\;/g ;
				my @op_ids = split(/\;/,$db{$tables}{$id}{events_operator_allocated} . ';' . $db{$tables}{$id}{operator_ids}) ;
				my @system_ids = split(/\;/,';'.$db{$tables}{$id}{event_system_id_multiple}) ;
				my @club_ids = split(/\,/,';'.$db{$tables}{$id}{club_ids}) ; 
				$valxlsx = '' ; 
				for my $op_id (@op_ids) {
					$op_cnt_2++ ;
					next if $seen_op_id{$op_id} || !$op_id ;
					$seen_op_id{$op_id} = 1 ; 
					if (($system_ids[$op_cnt_2-1] || $club_ids[$op_cnt_2-1] && $op_cnt_2 > 1) || $op_cnt_2 == 1) {
						$op_cnt++;
						$valxlsx .= qq~$name{$op_id};~ ;
					}
				}
				chop $valxlsx if $valxlsx ;
				if ($valxlsx) {
					$valxlsx =~ s/\;/\<br>/g ;
					# $val = qq~<a class="btn btn-primary btn-xs" href="#" data-title="$val" data-toggle="tooltip" data-placement="left"><i class="glyphicon glyphicon-user"></i></a>~ if $val ;
					$glyph_icon = ($op_cnt > 1) ? qq~<i class="glyphicons glyphicons-group"></i>~ : qq~<i class="glyphicons glyphicons-user"></i>~ ;
					$val = qq~<a href="#" data-title="$valxlsx" data-toggle="tooltip" data-placement="left">$glyph_icon</a>~   ;				
				} 
				$db{$tables}{$id}{operator_ids} = $ops_orig ;
			} elsif ($_ eq 'venue') {  
				$nowrap = '' ; 
				$val = join("<br>", map { $organisation{$_} } split(/\,/,$db{$tables}{$id}{organisation_ids})) ;
			} elsif ($_ eq 'sport')  {
				$val = join("<br>", map { $db{sport_types}{$_}{name} } split(/\,/,$db{$tables}{$id}{sport_type_ids})) ;
			} elsif ($_ eq 'nr') {
				$sort_val = sprintf("%06d",$db{$tables}{$id}{demo_id}) ; 
				$sort_val = ($demo_completed) ? qq~4~ : ($quote_accepted) ? qq~5~ . $sort_val : ($quote_completed) ? qq~4~ . $sort_val : ($quote_pending) ? qq~3~ . $sort_val : ($quote_rejected) ? qq~2~ . $sort_val : ($quote_cancelled) ? qq~1~ . $sort_val : qq~0~ . $sort_val  ;
				
				if ($quote_completed) {
					$formating = $format80 ;
				} elsif ($quote_accepted) {
					$formating = $format77 ;
				} elsif ($quote_rejected) {
					$formating = $format102 ;
				} elsif ($quote_cancelled) {
					$formating = $format81 ;
				} elsif ($quote_pending) {
					$formating = $format79 ;
				}

				my $tt = qq~data-toggle="tooltip" data-placement="right" data-title="$tt_txt"~;
				
				$val_xlsx = $db{$tables}{$id}{demo_id} ;
				
				$val = qq~<span style="display:none;">$sort_val</span>~ ; 
				# $val .= qq~<a class="btn btn-$class btn-xs" $style $tt href="javascript:editMinItem('$db{$tables}{$id}{demo_id}','demos');">$db{$tables}{$id}{demo_id}</a>~ ;
				 
				# my $demo_id = $db{$tables}{$id}{id} ;
				# $db{$tables}{$val_xlsx}{id} = $db{$tables}{$id}{demo_id} ;
 
				$val .= &common_min_get_event_quote_button($val_xlsx,$tables,'demos') ; 
				$val .= qq~<span title="EVENT : $id" data-toggle="tooltip" data-placement="top"><a href="javascript:editMinItem('$id','event-quotes');"><i class="glyphicons glyphicons-duplicate icon-white" style="color:black;"></i></a></span>~  ;
			
				# $db{$tables}{$val_xlsx}{id} = $demo_id ;
				
			}
			
			$val_xlsx = $val if $val && !$val_xlsx ;

			&xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_xlsx,$formating) ;  
			$xlsxcol++ ;
			
			$print_tbody .= qq~<td $nowrap $align>$val</td>~ ;  
		}
		$xlsxrow++ ;
		
		my $start_date  = substr($db{$tables}{$id}{date_from},0,10); 
		my $end_date    = substr($db{$tables}{$id}{date_to},0,10); 
		# my @event_dates = () ; 
		
		my $year  = substr($db{$tables}{$id}{date_from}, 0, 4) ; 
		my $month = substr($db{$tables}{$id}{date_from}, 5, 2) ; 
		my $day   = substr($db{$tables}{$id}{date_from}, 8, 2) ; 	
		
		my $year_end = substr($db{$tables}{$id}{date_to}, 0, 4 ) ; 
		my $month_end = substr($db{$tables}{$id}{date_to}, 5, 2 ) ; 
		my $day_end   = substr($db{$tables}{$id}{date_to}, 8, 2 ) ; 	

		my $row_count = 0;  
		# for my $event_date (sort @event_dates) {
		$xlsxcol = 0 ; 
		$row_count++ ; 
		
		my $quote_nr = $quote_nr ; $quote_nr =~ s/'//iog; unless ($quote_nr) { $quote_nr = $id ; }
 		my $edit_butt     = qq~<a class="btn btn-info btn-xs" href="javascript:editMinItem('$db{$tables}{$id}{demo_id}','demos');"><i class="glyphicon glyphicon-edit icon-white"></i></a>~ ;	
 		my $delete_butt   = qq~<a class="btn btn-danger btn-xs" href="javascript:deleteMinItem('$db{$tables}{$id}{demo_id}','$db{$tables}{$id}{demo_id}')"><i class="glyphicon glyphicon-trash icon-white"></i></a>~ ;
		
		my $copy_butt = qq~<a class="btn btn-success btn-xs" href="javascript:copyMinItem('$db{$tables}{$id}{demo_id}');" title="Copy" data-toggle="tooltip" data-placement="top"><i class="glyphicon glyphicon-retweet icon-white"></i></a>~ ;
 
		my %emailed_op_ids = () ; my $all_op_ids = 1 ; my $cnt_op_ids = 0 ; 
		foreach my $op_id (split(/\;/,$db{$tables}{$id}{emailed_op_ids})) {
			$emailed_op_ids{$op_id} = 1 ;	
		}
				
		foreach my $op_id2 (split(/\,/,$db{$tables}{$id}{operator_ids})) {
			$all_op_ids = 0 if $op_id2 and not $emailed_op_ids{$op_id2} ;
			$cnt_op_ids++ if $op_id2 ; 
		}
	 
		if ($all_op_ids and $cnt_op_ids) {
			$trigger_jquery_raw .= qq~
				\$("#email_$id").css({
					"background-color": "lightgrey",
					"border-color": "lightgrey"
				});
			~ ; 			
		}
		
		if ($glod_user_level < 3) {
			$delete_butt = '' ;
			if ($quote_completed || $quote_cancelled || $quote_rejected) {
				$edit_butt = '' ;
			}		
		}
		
		$edit_butt 		= qq~$edit_butt&nbsp;~ 		if $edit_butt ; 
		$copy_butt 		= qq~$copy_butt&nbsp;~ 		if $copy_butt ; 
		$delete_butt    = qq~$delete_butt&nbsp;~ 	if $delete_butt ; 
		$pdf_butt 		= qq~$pdf_butt&nbsp;~ 		if $pdf_butt ; 
		$email_butt 	= qq~$email_butt&nbsp;~ 	if $email_butt ; 
		
		if ($quote_created and not $quote_completed and not $quote_accepted) {
			$pdf_butt = qq~~ ; $email_butt = qq~~ ;
		}
 
		$print_tbody   .= qq~<td nowrap class="dt-center">&nbsp;$edit_butt$copy_butt$delete_butt$pdf_butt$email_butt</td></tr>~ ;
	}
		
	$worksheet{$ws}->set_column(0,0,10) ; 
	$worksheet{$ws}->set_column(1,1,50) ; 
	$worksheet{$ws}->set_column(2,3,20) ; 
	$worksheet{$ws}->set_column(4,4,10) ; 
	$worksheet{$ws}->set_column(5,10,30) ; 
	$worksheet{$ws}->set_column(11,11,75) ; 
	$worksheet{$ws}->set_column(12,21,30) ;	
	
	&report_xlsx_export_footer('L',15,'demos') ; 
	
	if ($usertype eq 'support') {
		$fnsortcol   = 1 ; # start date
		$fnsortorder =  'asc' ;
	}

	&common_min_extra_crumb("filter-$lcpage\s","Search Screen") if $glod_user_level > 3 ;

} #-------------------------------------------------------------------------------

sub thead {

	&common_min_thead ;

} #-------------------------------------------------------------------------------

sub add_db_fields {

	&hidden_fields ;
	$hidden{id} = 2 ; 

} #------------------------------------------------------------------------------------------

sub edit_db_fields {

	&hidden_fields ;
	$hidden{id} = 1 ;
	
	# $readonly{ref} = 'READONLY' ;

} #------------------------------------------------------------------------------------------

sub view_db_fields {

	&hidden_fields ;
	$hidden{id}                = 1 ;
	$label{ref}                = 1 ;
	$label{qty}                = 1 ;
	$label{date_from}          = 1 ;
	$label{date_to}            = 1 ;
	$label{sport_type_ids}     = 1 ;
	$label{region_id}          = 1 ;
	$label{city_id}            = 1 ;
	$label{organisation_ids}   = 1 ;
	 
} #------------------------------------------------------------------------------------------

sub hidden_fields {
 
	$ignore{custom_selected_region}		= 1 ;
	$ignore{custom_selected_country}	= 1 ;
	$ignore{region_id}					= 1 ;
	$ignore{iaction}   					= 1 ;
	$ignore{name} 						= 1 ;
	$ignore{date_from} 					= 1 ;
	$ignore{date_to} 					= 1 ; 
	$ignore{event_system_id_multiple}	= 1 ;
	$ignore{club_ids}					= 1 ;
	$ignore{operator_ids}				= 1 ;
	$ignore{venue_ids}					= 1 ;
	$ignore{sport_type_ids}				= 1 ;
	$ignore{qty}						= 1 ;
	$ignore{slip}						= 1 ;
	$ignore{iattachslip}				= 1 ;
	$ignore{notes}						= 1 ;
	$ignore{office_notes}				= 1 ;
	$ignore{email}						= 1 ;
	$ignore{tel}						= 1 ;
	$ignore{address}					= 1 ;
	$ignore{contact_name}				= 1 ; 
	$ignore{demo_completed}				= 1 ;
	$ignore{demo_accepted}				= 1 ;
	$ignore{demo_rejected}				= 1 ;
	$ignore{demo_cancelled}				= 1 ;
	$ignore{demo_pending}				= 1 ;
	$ignore{currency}					= 1 ;
	$ignore{roe}						= 1 ;
	$ignore{country_id}					= 1 ; 
	$ignore{quote_to}					= 1 ;
	$ignore{quote_nr}					= 1 ;
	$ignore{quote_date}					= 1 ;
	$ignore{custom_set}					= 1 ;
	# $ignore{quote_to}					= 1 ;
	# $ignore{datetime}					= 1 ;
	# $ignore{ref}						= 1 ;
	# $ignore{times_from}					= 1 ;
	# $ignore{last_update}					= 1 ;
	
	$ignore{quote_accepted}				= 1 ;
	$ignore{quote_pending}				= 1 ;
	$ignore{quote_cancelled}			= 1 ;
	$ignore{quote_completed}			= 1 ;
	$ignore{quote_created}				= 1 ;
	$ignore{quote_rejected}				= 1 ;
	
	
	$required{quote_nr}                = 1 ;
	$readonly{quote_nr}                = 'READONLY' ;
	$required{quote_to}                = 1 ;
	$required{region_id}               = 1 ;
	$required{country_id}				= '' ;
	$required{currency} = 1 ; 
	$required{roe} = 1 ; 
	
	for my $event_day (1 .. 20) {
		
		$ignore{"time_from_$event_day"} = 1 ; 
		$ignore{"time_to_$event_day"} = 1 ;
		$ignore{"day_$event_day"} = 1 ;
		
	}	
	
	$required{currency} = 1 ;
	$required{roe} = 1 ;
	
} #------------------------------------------------------------------------------------------

sub add_screen {
	
	our ($lcol,$fcol) = &common_min_columns($label_col,$field_col) ;
 
	&select_opts('') ;

	$db{$table}{''}{quote_nr} = &db_min_get_max($table,'id') ; 
	$db{$table}{''}{qty} = 1 ;

	our $savjqy = 1 ; # incorporate jquery into the save event to accommodate the multiple chosen options
		
	&add_db_fields ;
	
	&build_boxes_edit ;
 
} #------------------------------------------------------------------------------------------

sub build_boxes_edit {

	my ($id) = @_ ;
	
	&edit_db_fields ;
	
	# $allow_deselect{"demo_type_id"} = 1 ;
	# $allow_deselect{"part_number"} = 1 ;
	# $allow_deselect{"customer_id"} = 1 ;
	# $allow_deselect{"rma_status_id"} = 1 ; 

	our %cntxt = () ; 

	$cntxt{1}  = 'one' ; 
	$cntxt{2}  = 'two' ;
	$cntxt{3}  = 'three' ;

	my %tabnames = () ; 
	
	$tabnames{1} = 'Admin'	; 
	$tabnames{2} = 'Demo Details'	; 
	$tabnames{3} = 'Expenses'	; 

	foreach our $col (keys %required) {
		&common_min_forms_required ;
	}

	$print_box_content_rows .= &common_min_forms_start($table) ;

	$print_box_content_rows .= qq~
		<div class='row'>
			<div class='col-md-12'>~ ;
				&build_boxes_top($id);
	$print_box_content_rows .= qq~
			</div>
		</div>
	~ ;

	$print_box_content_rows .= qq~
		<div class='row'>
			<div class='col-md-12'>
		~ ;

	$print_box_content_rows .= qq(<ul class="nav nav-tabs" id="myTab">);
			
	foreach (sort {$a<=>$b} keys %cntxt) {
		
		my $tab_name = $tabnames{$_} ; 
		
		my $c_actv = ($_==1) ? 'class="active"' : '' ; 
	
		$print_box_content_rows .= qq(<li id="$tab_name" $c_actv><a href="#$cntxt{$_}">$tab_name</a></li>);

	}
				
	$print_box_content_rows .= qq(</ul>
				
				<div id="myTabContent" class="tab-content">
		);
	
	foreach (sort {$a<=>$b} keys %cntxt) {

		my $active = ($_==1) ? 'active' : '' ; 
			
		my $colsleft = 12 ; my $showright = '' ;
			
		if ($cntxt{$_} eq 'one') {
			$colsleft = 6 ; 
			$showright = 1 ;
		}
					
		$print_box_content_rows .= qq~
					<div class="tab-pane $active" id="$cntxt{$_}">~;				
		$print_box_content_rows .= qq~
						<div class='row' style="margin: 2px 4px 0 -10px;">~ ;						
		$print_box_content_rows .= qq~
							<div class='col-md-$colsleft'>~ ;
								&build_boxes_left($id,$_,1);
		$print_box_content_rows .= qq~
							</div>~ ;	
		if ($showright) {
			$print_box_content_rows .= qq~
							<div class='col-md-6'>~ ;
								&build_boxes_right($id,$_);
			$print_box_content_rows .= qq~
							</div>~ ;
		}
	
		$print_box_content_rows .= qq~
						</div>~ ;					
		$print_box_content_rows .= qq~
					</div>~ ;					
		
	}
	
	$print_box_content_rows .= qq~
				</div><div class='col-md-0'>~ ;  
		# &build_boxes_right($id);
	$print_box_content_rows  .= qq~
				</div>
			</div>
		</div>~ ;

	$print_box_content_rows .= qq~<input style="display:none;" value="$id" name="id">~ ;

	$print_box_content_rows  .= ($id) ? &common_min_forms_end($id,$table,'update',$skip) : &common_min_forms_end($id,$table,'save',$skip) ;

	my $all_select_ids_str = join(",",@all_select_ids) ;
	
	$trigger_jquery_raw  .= qq~\$("#demos-form select[id^='select']:not(#selectCurrency,#selectQuote_to,#selectCountry_id,#selectTenant_id)").chosen({ allow_single_deselect: true });~ ;
 
} #----------------------------------------------------------------------------------------

sub build_boxes_left {

	my ($id,$tab,$demo_page) = @_ ;

	if ($tab == 1) {  # Cusotmer Details
		&event_tabs_build_qt_left($id,$tab,'',$demo_page)
		
	} elsif ($tab == 2) {

		our ($lcol,$fcol) = &common_min_columns(2,4) ;
		
		my $sec = '_demo_details' ; 
	
		my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ;
		
		$add_form_fields = '' ;

		$preferred_title{quote_to} = "Client" ;
		$add_form_fields .= &common_min_form_select('quote_to',$db{$table}{$id}{quote_to},'') ;
		
		$add_form_fields .= qq~<input type="hidden" name="custom_selected_region" value="$db{$table}{$id}{region_id}">~ ; 
		$add_form_fields .= qq~<input type="hidden" name="custom_selected_country" value="$db{$table}{$id}{country_id}">~ ; 
		
		# $dlg{quote_to} = qq~ 
		# <div class="col-md-1">
			# <a href="javascript:dlgMdl('$useropts{'scripts'}/dialog/add_customer.pl?add&selectQuote_to','Add Customer','','max-dialog');" class="btn btn-primary btn-xs" style="padding:1px 2px 1px 3px;margin-top:0px;" title='Add Customer' data-toggle='tooltip' data-placement='right'>
				# <i class="glyphicon glyphicon-plus" style="padding:0;margin-top:0px;">
				# </i>
			# </a>
		# </div>
		# ~ ;
		
		$trigger_jquery_raw .= qq~
			
			let map_region_to_country = {} ; 
			
			const \$clientSelect  	= \$("#selectQuote_to") ; 
			const \$countrySelect 	= \$("#selectCountry_id") ;
			const \$regionSelect  	= \$("#selectRegion_id") ;
			const \$venuesSelect	= \$("#selectVenue_ids") ;
			
			let prev_region = \$regionSelect.val() ; 
			let prev_country = \$countrySelect.val() ; 
			
			const updateChosen = \$el => \$el.trigger("chosen:updated");
			
			const getClientId = () => {
				const val = \$clientSelect.val();
				return val ? val.toString().split(":")[0] : null;
			} ;
			
			const fetchJSON = async url => {
				try {
					const res = await fetch(url);
					if (!res.ok) throw new Error(`Request failed: \${res.status}`);
					return await res.json();
				} catch (err) {
					console.error("Fetch error:", err);
					return [];
				}
			};	
			
			const populateSelect = (\$field,json_list,getLabel,defaultSelected = () => "") => {
				let isSelected ;
				if (typeof defaultSelected === "function") {
					isSelected = defaultSelected;
				} else if (Array.isArray(defaultSelected)) {
					isSelected = data => defaultSelected.includes(data.id) ? "selected" : "";
				} else {
					isSelected = data => data.id == defaultSelected ? "selected" : "";
				}

				json_list.forEach(data => {
					\$field.append(`<option value="\${data.id}" \${isSelected(data)}>\${getLabel(data)}</option>`);
				});

				updateChosen(\$field);
				return json_list.length;
			};
			
			const getInputValue = name => \$(`input[name='\${name}']`).val();
			
			const getMultiSelectSplitNumbers = (\$field) => {
				
				let field_ = \$field.chosen().val() ;
				field_ = String(field_);
				return field_.split(',') ;
				
			} ;
			
			const clearSelect = (\$el) => {
				\$el.empty();
				\$el.append(`<option value=""></option>`).trigger("chosen:updated");
			};
			 
			async function update_region_drop_down_from_country (countryId) {
			 
				clearSelect(\$regionSelect) ;
				 
				const regionUrl = `$useropts{scripts}/get/get_regions_from_country.pl?country_id=\${countryId}` ;
				
				const regions = await fetchJSON(regionUrl);
			
				for (const data of regions) {
					map_region_to_country[data.id] = countryId ;
				}
				 
				const regionCount = populateSelect(\$regionSelect, regions, r => r.code ? `\${r.name} [\${r.code}]` : r.name , "") ;			
				
				// let selectedRegionId = 0 ;
				
				if (regionCount === 1) { 
					\$regionSelect.val(regions[0].id) 
				} else if (regionCount === 0 && \$countrySelect.val()) {
					// selectedRegionId = 13 ;
					\$regionSelect.append(`<option value="13" selected>Other [OT]</option>`) ;
				}  
				updateChosen(\$regionSelect) ;
				
				const regionId = \$regionSelect.val() ;  
				
				if (regionId != prev_region) {
					await update_cities_from_region_and_country(regionId,countryId) ;
					await update_venues_from_region_and_country(regionId,countryId) ;
				}
				prev_region = regionId ;
				
			}		

			async function update_cities_from_region_and_country (regionId,countryId="") {
 				
			}

			async function update_venues_from_region_and_country (regionId,countryId="") {
				
				let splittedNumbers2 = getMultiSelectSplitNumbers(\$venuesSelect) ;
				clearSelect(\$venuesSelect) ;
				url = `$useropts{scripts}/get/get_venues_from_region.pl?region_id=\${regionId}&country_id=\${countryId}` ;
				const venues = await fetchJSON(url);
				const venuesCount = populateSelect(\$venuesSelect, venues, r => r.venue_name , r => splittedNumbers2.includes(r.id) ? "selected" : "" ) ;	
				// if (venuesCount == 1) \$venuesSelect.val(venues[0].id).trigger("chosen:updated") ; 
				
			}

 			\$clientSelect.change( async function() { 
			
				dispCustomer() ; 
				let clientId = getClientId() ;
				
				// __________________________________________________________________ update_country_region_from_client
				
				const hasCustomRegion = !!getInputValue('custom_selected_region');
				const hasCustomCountry = !!getInputValue('custom_selected_country');
				
				if (clientId) {
					let url1 = `$useropts{scripts}/get/get_region_country_from_client.pl?client_id=\${clientId}` ;
					console.log("1 clientId : "+clientId) ; 
					
					if (!hasCustomRegion || !hasCustomCountry) {
  
						const data = await fetchJSON(url1);
						data.forEach(async ({region_id,country_id}) => {

							if (!hasCustomCountry && country_id && country_id != '0') {
 
								\$countrySelect.val(country_id).trigger("chosen:updated") ;
								if (!hasCustomRegion) await update_region_drop_down_from_country(country_id) ; 
								if (!region_id || region_id == '0') {
									await update_cities_from_region_and_country(0,country_id) ;
									await update_venues_from_region_and_country(0,country_id) ;
								}
							}
							
							if (!hasCustomRegion && region_id && region_id != '0') {
								\$regionSelect.val(region_id).trigger("chosen:updated") ;	
								await update_cities_from_region_and_country(region_id) ;
								await update_venues_from_region_and_country(region_id) ;
							}
							
							// if (!hasCustomCountry && country_id && country_id != '0') 
							// if (!hasCustomRegion && region_id && region_id != '0') \$regionSelect.val(region_id).trigger("chosen:updated") ;
							
						});
					}
				} else {
					if (!hasCustomCountry) \$countrySelect.val("").trigger("chosen:updated") ;
					if (!hasCustomRegion) {
						\$regionSelect.val("").trigger("chosen:updated") ;
						let region_option_count = \$regionSelect.find("option").length ;
						if (region_option_count <= 2) {
							await update_region_drop_down_from_country(clientId) ; 
						}
					}
				}
				
				// __________________________________________________________________ update_country_region_from_client
				
			}) ; 	
			
			\$countrySelect.change( async function() { 
			
				\$("input[name='custom_selected_country']").val("1") ;
				await update_region_drop_down_from_country(\$countrySelect.val()) ; 
				
			}) ;
			
			\$regionSelect.change( async function() {
				
				\$("input[name='custom_selected_region']").val("1") ;
				\$("input[name='custom_selected_country']").val("1") ; 
				const regionId = \$regionSelect.val() ;   
				await update_country_from_region(regionId,1) ; 
				await update_cities_from_region_and_country(regionId) ;
				await update_venues_from_region_and_country(regionId) ;
				
			});
 
			async function update_country_from_region (regionId,update_country=0) {
				
				if (map_region_to_country[regionId] || regionId == '13') {
					\$countrySelect.val(map_region_to_country[regionId]).trigger("chosen:updated") ; 
				} else if (!\$("input[name='custom_selected_country']").val() || update_country) { 
					const lookupUrl = `$useropts{scripts}/get/get_country_from_region.pl?country_id=&region_id=\${regionId}`;
					console.log("update_country_from_region lookupUrl : "+lookupUrl) ; 
					const regionMeta = await fetchJSON(lookupUrl);
					const { country_id } = regionMeta[0] ?? {} ; 
					if (country_id) {
						map_region_to_country[regionId] = country_id;
						\$countrySelect.val(country_id).trigger("chosen:updated");
					} 					
				}		
			}
			
		~ ;
	 
		$preferred_title{name} = "Demo Name" ;

		$add_form_fields .= &common_min_form_input('name',$db{$table}{$id}{name}) ; 
	  
		$opts{demo_type_id} = qq~<option value="1">Standard</option><option value="2">New Solution</option>~ ;
		if ($db{$table}{$id}{demo_type_id}) {
			$opts{demo_type_id} =~ s/value="$db{$table}{$id}{demo_type_id}"/value="$db{$table}{$id}{demo_type_id}" SELECTED/g ;
		}

		# $allow_deselect{demo_type_id} = 1 ;
		# $allow_deselect{location_id} = 1 ;
		# $allow_deselect{events_operator_required} = 1 ;
		# $allow_deselect{events_operator_allocated} = 1 ;
		# $allow_deselect{calibrator_required} = 1 ;
		
		$add_form_fields .= &common_min_form_select('demo_type_id',$db{$table}{$id}{demo_type_id}) ; 
		
		$add_form_fields .= &common_min_form_textarea('brief_description',$db{$table}{$id}{brief_description}) ; 
		
		$preferred_title{date_from} = "Demo Date/Time From" ;
		$preferred_title{date_to} = "Demo Date/Time To" ;
		
		my $current_day_of_week = Day_of_Week($now_year,$now_mm,$now_dd) ; 

		my $delta_days = 6 - $current_day_of_week ;
		$delta_days = 7 unless $delta_days ;
		$delta_days = 6 if $delta_days < 0 ;
		
		my ($def_year,$def_mon,$def_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,$delta_days) ; 
		$def_mon = sprintf("%02d",$def_mon) ; 
		$def_day = sprintf("%02d",$def_day) ; 	
		
		$db{$table}{$id}{date_from}	= "$def_year-$def_mon-$def_day 08:00:00" unless $db{$table}{$id}{date_from} ; 
		$db{$table}{$id}{date_to}	= "$def_year-$def_mon-$def_day 17:00:00" unless $db{$table}{$id}{date_to} ;
		
		$add_form_fields .= &common_min_form_datetimepicker('date_from',$db{$table}{$id}{date_from}) ; 
		
		$add_form_fields .= &common_min_form_datetimepicker('date_to',$db{$table}{$id}{date_to}) ; 

		$preferred_title{qty} = 'Actual Days' ;  $dont_end_row{qty} = 1 ;  
		
		if ((($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) || ($quote_completed && $glod_user_level <= 3)) { $readonly{qty} = "READONLY" ; }
 
		my @times_from 	= split(/\;/,";$db{$table}{$id}{times_from}") ; 
		my @times_to 	= split(/\;/,$db{$table}{$id}{times_to}) ; 
		
		my @default = () ; my $saved_time_from = qq~~ ; my $saved_time_to = qq~~ ;
		
		my $year 	= ($db{$table}{$id}{date_from}) ? substr($db{$table}{$id}{date_from},0,4) : $now_year ; 
		my $month 	= ($db{$table}{$id}{date_from}) ? substr($db{$table}{$id}{date_from},5,2) : $now_mm ; 
		my $day 	= ($db{$table}{$id}{date_from}) ? substr($db{$table}{$id}{date_from},8,2) : $now_dd ; 
		
		$fcol = 1 ;
		
		$radio_opts{event_length} = "Full Day+Half Day" ;

		my @timepicker_ids = () ; my @day_ids = () ; 
		
		my %default_days_selected = () ; our %default_active_event_dates = () ; 

		my ($year1,$month1,$day1) = split(/\-/,substr($db{$table}{$id}{date_from},0,10));
		my ($year2,$month2,$day2) = split(/\-/,substr($db{$table}{$id}{date_to},0,10));

		our $final_day = Delta_Days($year1,$month1,$day1,$year2,$month2,$day2) + 1 ;
		
		our @defaut_days_active = split(/\;/,$db{$table}{$id}{days_active}) ; 
		
		my $event_without_saved_defaults = 0 ; 

		if (!$db{$table}{$id}{days_active}) { 
			$event_without_saved_defaults = 1 ; 
			for (1 .. $final_day) {
				$db{$table}{$id}{days_active} .= "1;" ;
			} 
		}

		my @default_event_length = split(/\;/,$db{$table}{$id}{event_length}) ; my %calc_default_event_length = () ; 
				
		my @days_active =  split(/\;/,$db{$table}{$id}{days_active}) ;

		my $cnt = 0 ; 
		# my $final_day = 0 ; 
		my $no_event_days_cnt = 0 ; 

		my $hide_rows_1 = (substr($db{$table}{$id}{date_from},0,10) eq substr($db{$table}{$id}{date_to},0,10)) ? "style='display:none;'" : "" ;
		my $hide_rows_2 = ($final_day <= 10) ? "style='display:none;'" : "" ;
		
		my %time_label_header_row = () ; 
		
		$time_label_header_row{1} = qq~<div class='row' id="days_drop_downs_1" $hide_rows_1><div class='fieldname col-md-2'><label class="control-label">Individual Dates</label></div>~ ;
		$time_label_header_row{2} = qq~<div class='row' id="days_drop_downs_2" $hide_rows_2><div class='fieldname col-md-2'><label class="control-label">Individual Dates (After 10 Days)</label></div>~ ;
		
		my $nr_of_active_days = 0 ; 
		
		for (1 .. 20) {
			
			my $cnt_row = ($_ <= 10) ? 1 : 2 ; 
			
			$default_days_selected{blank}{$_} = "SELECTED" unless $days_active[$_ - 1] ;
			$default_days_selected{1}{$_} = "SELECTED" if $days_active[$_ - 1] ;
			
			$nr_of_active_days++ if $days_active[$_ - 1] ;
			
			push @timepicker_ids,"#timepickerTime_from_$_" ;
			push @timepicker_ids,"#timepickerTime_to_$_" ;
			push @day_ids,"#day_$_" ;
			
			my ($new_year,$new_month,$new_day) = ($_ > 1) ? Add_Delta_Days($year,$month,$day,$_-1) : ($year,$month,$day) ;
			$new_day = sprintf("%02s",$new_day) ;
			$new_month = sprintf("%02s",$new_month) ;
			
			# $default_active_event_dates{$_} = "$new_year-$new_month-$new_day" if $days_active[$_ - 1] ;
			$default_active_event_dates{$_} = "$new_year-$new_month-$new_day" if $_ <= $final_day ;
			
			my $field = "time_from_$_" ;
			$default[$_ - 1] = $times_from[$_ - 1] ;
			$default[$_ - 1] = substr($db{$table}{$id}{date_from},11) if $db{$table}{$id}{date_from} && (!$times_from[$_ - 1] || $_ == 1) ;
			my $default1 = $default[$_ - 1] ;
			
			$custom_style{$field} = ((!$event_without_saved_defaults && !$defaut_days_active[$_ - 1]) || $_ == 1 || ($_ > $final_day)) ? qq~display:none;~ : ''  ;
			# $days_time_row .= ($glod_user_level > 2) ? &common_min_form_timepicker_col($field,$default[$_ - 1],'',1) : ($readonly{qty} ne "READONLY" || ($final_day >= $_ && !$custom_style{$field})) ? qq~<div class='col-md-$fcol'><div class="controls"><input type="text" name="$field" class="form-control " readonly value="$default[$_ - 1]" style="$custom_style{$field}"></div></div>~ : qq~<div class='col-md-$fcol'></div>~ ;
			$days_time_row{$cnt_row} .= ($readonly{qty} ne "READONLY") ? &common_min_form_timepicker_col($field,$default[$_ - 1],'',1) : ($readonly{qty} eq "READONLY" && ($final_day >= $_ && !$custom_style{$field})) ? qq~<div class='col-md-$fcol'><div class="controls"><input type="text" name="$field" class="form-control " readonly value="$default[$_ - 1]" style="$custom_style{$field}"></div></div>~ : qq~<div class='col-md-$fcol'></div>~;
			
			$trigger_jquery_raw .= qq~\$("#timepickerTime_from_1").css("display","none");~ ;
			
			# $default_time_from .= qq~"$_":"$default[$_ - 1]",~ ; 
			$saved_time_from .= qq~"$_":"$times_from[$_ - 1]",~ if $times_from[$_ - 1] ; 
			# $final_day = $_ if $times_from[$_ - 1] ; 
			$field = "time_to_$_" ;
			
			
			$custom_style{$field} = ((!$event_without_saved_defaults && !$defaut_days_active[$_ - 1]) || $_ >= $final_day) ? qq~display:none;~ : ''  ;
			$default[$_ - 1] = $times_to[$_ - 1] ;
			$default[$_ - 1] = substr($db{$table}{$id}{date_to},11) if $db{$table}{$id}{date_to} && (!$times_to[$_ - 1] || $_ == 6) ;
			#___
			# $days_time_row_2 .= ($readonly{qty} ne "READONLY") ? &common_min_form_timepicker_col($field,$default[$_ - 1],'',1) : ($final_day >= $_ && !$custom_style{$field}) ? &common_min_form_input_col($field,$default[$_ - 1],'',0) : qq~<div class='col-md-$fcol'></div>~ ;
						
			# $days_time_row_2 .= ($glod_user_level > 2) ? &common_min_form_timepicker_col($field,$default[$_ - 1],'',1) : ($readonly{qty} ne "READONLY" || ($final_day >= $_ && !$custom_style{$field})) ? qq~<div class='col-md-$fcol'><div class="controls"><input type="text" name="$field" class="form-control " readonly value="$default[$_ - 1]" style="$custom_style{$field}"></div></div>~ : qq~<div class='col-md-$fcol'></div>~;
			$days_time_row_2{$cnt_row} .= ($readonly{qty} ne "READONLY") ? &common_min_form_timepicker_col($field,$default[$_ - 1],'',1) : ($readonly{qty} eq "READONLY" && ($final_day >= $_ && !$custom_style{$field})) ? qq~<div class='col-md-$fcol'><div class="controls"><input type="text" name="$field" class="form-control " readonly value="$default[$_ - 1]" style="$custom_style{$field}"></div></div>~ : qq~<div class='col-md-$fcol'></div>~ ;
			#___
			
			# if ($default_event_length[$_ - 1] eq '1' && $days_active[$_ - 1]) {
			# 	$def_nr_of_full_days++ ;
			# } elsif ($default_event_length[$_ - 1] eq '2' && $days_active[$_ - 1]) {
			# 	$def_nr_of_half_days++ ;
			# } 
			
			if (!$db{$table}{$id}{event_length}) {
				
				my ($h1,$m1,$s1) = ($_ == 1 || !$times_from[$_ - 1]) ? split(/\:/,substr($db{$table}{$id}{date_from},11)) : split(/\:/,$times_from[$_ - 1]) ;
				my ($h2,$m2,$s2) = split(/\:/,substr($db{$table}{$id}{date_to},11)) ;
				my $time_diff = 3600*($h2-$h1) + 60*($m2-$m1) + ($s2-$s1) ; 
 
				if ($time_diff >= 18000) {
					$calc_default_event_length{$_} = 1 ;
					$trigger_jquery .= qq~
						\$("#radio_$_\_1").prop('checked',true) ;
					~ if $readonly{qty} ne "READONLY" ; 		
					# $def_nr_of_full_days++ if $default_event_length[$_ - 1] ; 			
				} elsif ($time_diff >= 0 && $time_diff < 18000) {
					$calc_default_event_length{$_} = 2 ;
					$trigger_jquery .= qq~
						\$("#radio_$_\_2").prop('checked',true) ;
					~ if $readonly{qty} ne "READONLY" ; 	
					# $def_nr_of_half_days++ if $default_event_length[$_ - 1] ; 		
				}
				
				$trigger_jquery .= qq~
					\$("#day_$_").val("1") ; 
					\$("#day_$_").trigger("chosen:updated") ; 
				~ if $_ <= $final_day && $readonly{qty} ne "READONLY" ;
				
			} elsif ($_ <= $final_day) {
				
				# $days_active[$_ - 1
				
				# my ($h1,$m1,$s1) = split(/\:/,$times_from[$_ - 1]) ;
				# my ($h2,$m2,$s2) = split(/\:/,$times_to[$_ - 1]) ;
				# my $time_diff = 3600*($h2-$h1) + 3600*($m2-$m1) + ($s2-$s1) ; 
				if ($default_event_length[$_ - 1]) {
					if ($default_event_length[$_-1] eq "1") {
						$trigger_jquery .= qq~
							// \$("input[name='selected_$_\_event_length']").val("1") ; 
							\$("#radio_$_\_1").prop('checked',true) ;
						~ ; 
						# $def_nr_of_full_days++ ; 								
					} elsif ($default_event_length[$_-1] eq "2") {
						$trigger_jquery .= qq~
							// \$("input[name='selected_$_\_event_length']").val("2") ; 
							\$("#radio_$_\_2").prop('checked',true) ;
						~ ;  
						# $def_nr_of_half_days++ ; 		
					}					
				} else {
					my ($h1,$m1,$s1) = split(/\:/,substr($db{$table}{$id}{date_from},11)) ;
					my ($h2,$m2,$s2) = split(/\:/,substr($db{$table}{$id}{date_to},11)) ;
					my $time_diff = 3600*($h2-$h1) + 60*($m2-$m1) + ($s2-$s1) ; 

					if ($time_diff >= 18000) {
						$calc_default_event_length{$_} = 1 ;
						$trigger_jquery .= qq~
							\$("#radio_$_\_1").prop('checked',true) ;
						~ if $readonly{qty} ne "READONLY" ; 		
						# $def_nr_of_full_days++ ;
					} elsif ($time_diff >= 0 && $time_diff < 18000) {
						$calc_default_event_length{$_} = 2 ;
						$trigger_jquery .= qq~
							\$("#radio_$_\_2").prop('checked',true) ;
						~ if $readonly{qty} ne "READONLY" ; 	
						# $def_nr_of_half_days++ ;
					}					
				}
			}
			
			if ((!$days_active[$_ - 1] && $_ > $final_day) || ($db{$table}{$id}{days_active} == ";;;;;") || (!$days_active[$_ - 1] && $_ <= $final_day)) {
				$trigger_jquery .= qq~\$("#radio_$_\_1").css("display","none") ; ~ ;
				$trigger_jquery .= qq~\$("#radio_$_\_2").css("display","none") ; ~ ;
			}

			$saved_time_to .= qq~"$_":"$times_to[$_ - 1]",~ if $times_to[$_ - 1] ; 
			
			$field = "day_$_" ;
			$custom_style{$field} = ($final_day < $_ || $final_day == 1) ? qq~display:none;~ : ''  ;
			
			if ($readonly{qty} ne "READONLY") {

				$trigger_jquery .= qq~\$("#day_$_\_chosen").css("display","none");~ if $_ > $final_day || $final_day == 1 ;

				$time_label_header_row{$cnt_row} .= qq~
					<div class='fieldname col-md-1' align="center">
						<select class="form-control" style="margin:2px 0 2px 0;$custom_style{$field}" name="day_$_" id="day_$_" data-rel="chosen" tabindex="$_">
							<option value="" $default_days_selected{blank}{$_}>No Events</option>
							<option value="1" $default_days_selected{1}{$_}>$new_year-$new_month-$new_day</option>
						</select>
					</div>
				~ ;

			} else {
				
				$time_label_header_row{$cnt_row} .= (!$default_days_selected{1}{$_}) ? qq~
					<div class='fieldname col-md-1' align="left" style="$custom_style{$field}"><label class="control-label">&nbsp;&nbsp;No Events</label></div>
				~ : qq~
					<div class='fieldname col-md-1' align="left" style="$custom_style{$field}">
						<input type="text" style="display:none;" name="day_$_" value="1"><label class="control-label">&nbsp;&nbsp;$new_year-$new_month-$new_day</label></div>
				~ ;		
				
			}
		}
		
		$event_length_rows{1} .= &common_min_form_radio_col('event_length',$db{$table}{$id}{event_length},'',10,$final_day,"",1) ;
		my $final_day_second = $final_day - 10 ; 
		$final_day_second = -1 if $final_day_second <= 0 ; 
		$event_length_rows{2} .= &common_min_form_radio_col('event_length',$db{$table}{$id}{event_length},'',10,$final_day_second,"radio_row_id_2",2) ;
		 
		$add_form_fields .= qq~$time_label_header_row{1}</div>~ ;	
		$add_form_fields .= qq~<div class="row" id="start_times_row_1" $hide_rows_1><div class='fieldname col-md-$lcol'><label class='control-label'>Start Time</label></div>$days_time_row{1}</div>~ ; 
		$add_form_fields .= qq~<div class="row" id="end_times_row_1" $hide_rows_1><div class='fieldname col-md-$lcol'><label class='control-label'>End Time</label></div>$days_time_row_2{1}</div>~ ; 		 		
		$add_form_fields .= qq~$event_length_rows{1}~ ; 		

		$add_form_fields .= qq~$time_label_header_row{2}</div>~ ;	
		$add_form_fields .= qq~<div class="row" id="start_times_row_2" $hide_rows_2><div class='fieldname col-md-$lcol'><label class='control-label'>Start Time</label></div>$days_time_row{2}</div>~ ; 
		$add_form_fields .= qq~<div class="row" id="end_times_row_2" $hide_rows_2><div class='fieldname col-md-$lcol'><label class='control-label'>End Time</label></div>$days_time_row_2{2}</div>~ ; 
		$add_form_fields .= qq~$event_length_rows{2}~ ; 
		
		$db{$table}{$id}{qty} = 1 if $iaction eq 'add' ;
		
		# $trigger_jquery .= qq~~ ;
		
		# $add_form_fields .= &common_min_form_input('qty',$db{$table}{$id}{qty},'',1) ;
		
		# $add_form_fields .= qq~</div>~ ;
		
		$add_form_fields .= qq~<input name="qty" id="inputQty" value="$db{$table}{$id}{qty}" style="display:none;">~ ;
		
		$trigger_jquery_raw .= qq~\$("#timepickerTime_to_$final_day").css("display","none");~ if $final_day ;
		
		my $day_ids_string = join(",",@day_ids) ;
		
		my $day_ids_chosen_string = join(",", map { "#day_$_\_chosen" } (1 .. $nr_of_active_days) ) ;
 
		$trigger_jquery .= qq~
			// \$("$day_ids_chosen_string").css("width","100%") ;
			\$("#two [id^='day_']").css("width","100%") ;
		~ ;
		
		$trigger_jquery_raw .= qq~
		
			let saved_time_from = {$saved_time_from} ; 
			let saved_time_to = {$saved_time_to} ;
		
			// \$("$day_ids_string").change( function (e) {	
			\$("#two [id^='day_']").change( function (e) {

				const id = this.id ; 
				let col_nr = get_row_nr(id) ; 
				
				let nr_days = \$("input[name='qty']").val() ; 
				
				let nr_of_active_days = calc_nr_of_active_days() ;
				
				let datesBetween ; 
				
				let date_counter = 0 ; let dates_map = {} ; 
				
				datesBetween = getDatesBetween(\$("input[name='date_from']").val(),\$("input[name='date_to']").val(),0) ;
				for (const date of datesBetween) {
					date_counter++ ; 
					dates_map[date_counter] = date ;
				}					

				let def_val = 0 ; 
				
				let hide_this_1 = '' ; 
				let hide_this_2 = '' ; 
				
				if (!\$\(this).val()) {
				
					\$("#timepickerTime_from_"+col_nr+"").css("display","none") ;
					\$("#timepickerTime_to_"+col_nr+"").css("display","none") ;
					\$("#radio_"+col_nr+"_1").css("display","none") ;
					\$("#radio_"+col_nr+"_2").css("display","none") ;
					nr_days = nr_days - 1 ;
					
				} else {
					
					if (col_nr != "1") {
						\$("#timepickerTime_from_"+col_nr).css("display","") ;
					} 
					\$("#radio_"+col_nr+"_1").css("display","") ;
					\$("#radio_"+col_nr+"_2").css("display","") ;	
					if (col_nr < date_counter ) {
						\$("#timepickerTime_to_"+col_nr).css("display","") ;	
					} 
					nr_days = parseInt(nr_days) + 1 ;

				}

				\$("input[name='qty']").val(nr_days) ; 
				
			}) ;
			
		~ if $readonly{qty} ne "READONLY" ;
					
		my $timepicker_ids_string = join(",",@timepicker_ids) ;
		
		# $trigger_jquery_raw .= qq~ \$("$timepicker_ids_string").datetimepicker({language:'pt-BR',pickDate:false});~ ;

		if ($readonly{qty} ne "READONLY") {
			$trigger_jquery_raw .= qq~	
				
				function set_full_half_day (beforeUnderscore,afterUnderscore) {
					
					let start_time = \$("input[name='time_from_"+afterUnderscore+"']").val() ; 
					let end_time = \$("input[name='time_to_"+afterUnderscore+"']").val() ; 
					 
					let seconds1 = timeStringToSeconds(start_time) ;
					let seconds2 = timeStringToSeconds(end_time) ;
					
					let diffSeconds = seconds2 - seconds1 ;
					
					let changed_a_full_half_day_toggle = 0 ;  
					if (diffSeconds >= 18000) {
						if (\$("#radio_"+afterUnderscore+"_2").is(":checked")) {
							// nr_days["half"]-- ;
						}
						if (!\$("#radio_"+afterUnderscore+"_1").is(":checked")) {
							\$("#radio_"+afterUnderscore+"_1").prop('checked',true) ;
							changed_a_full_half_day_toggle = 1 ; 
							// nr_days["full"]++ ;
						}
					} else if (diffSeconds >= 0 && diffSeconds < 18000) {
						if (\$("#radio_"+afterUnderscore+"_1").is(":checked")) {
							// nr_days["full"]-- ;
						}
						if (!\$("#radio_"+afterUnderscore+"_2").is(":checked")) {
							\$("#radio_"+afterUnderscore+"_2").prop('checked',true) ;
							changed_a_full_half_day_toggle = 1 ; 
							// nr_days["half"]++ ;
						}
					} else {
						if (\$("#radio_"+afterUnderscore+"_1").is(":checked")) {
							\$("#radio_"+afterUnderscore+"_1").prop('checked',false) ;
							changed_a_full_half_day_toggle = 1 ; 
							// nr_days["full"]-- ;
						}
						
						
						if (\$("#radio_"+afterUnderscore+"_2").is(":checked")) {
							\$("#radio_"+afterUnderscore+"_2").prop('checked',false) ;
							changed_a_full_half_day_toggle = 1 ; 
							// nr_days["half"]-- ;
						}
						if (beforeUnderscore == 'timepickerTime_from') {
							\$("input[name='time_from_"+afterUnderscore+"']").val(end_time) ;  
						} else if (beforeUnderscore == 'timepickerTime_to') {
							\$("input[name='time_to_"+afterUnderscore+"']").val(start_time) ; 
						}	 
					}
					if (changed_a_full_half_day_toggle == 1) {
						// changed_radio_cnt++ ; 
					}
					
					
				}
				
				// \$("$timepicker_ids_string").datetimepicker({language:'pt-BR',pickDate:false});
				\$("#two [id^='timepickerTime_']").datetimepicker({language:'pt-BR',pickDate:false});
				
				// \$("#timepickerTime_from_1").on('changeDate', function() {
					// let dateString1 = \$("input[name='time_from").val() ; 		
				// }) ;
				
				// \$("$timepicker_ids_string").on('changeDate', function() {
				\$("#two [id^='timepickerTime_']").on('changeDate', function() {

					// const id = this.id ; 
					// const lastIndex = id.lastIndexOf('_');
					// const beforeUnderscore = id.substring(0,lastIndex);
					// let   afterUnderscore = id.substring(lastIndex+1);
					// afterUnderscore = parseInt(afterUnderscore) ;
					
					// if (id.includes("timepickerTime_from_")) {   
						// saved_time_from[afterUnderscore] = \$("input[name='time_from_"+afterUnderscore+"']").val() ;
					// } else if (id.includes("timepickerTime_to_")) { 
						// saved_time_to[afterUnderscore] = \$("input[name='time_to_"+afterUnderscore+"']").val() ; 
					// }
					// changed_radio_cnt = 0 ; 
					
					// set_full_half_day(beforeUnderscore,afterUnderscore) ; 


					const id = this.id ; 
					const lastIndex = id.lastIndexOf('_');
					const beforeUnderscore = id.substring(0,lastIndex);
					let   afterUnderscore = id.substring(lastIndex+1);
					afterUnderscore = parseInt(afterUnderscore) ;
					if (beforeUnderscore == 'from' && afterUnderscore == 1) {
						
						let dateString = \$("input[name='time_from").val() ; 
						let timePart = dateString.split(' ')[1]; 
						\$("input[name='time_from_1']").val(timePart) ;  
						return ; 
					}
					if (beforeUnderscore == 'to') { 
						let dateString1 = \$("input[name='time_from").val() ; 		
						let dateString2 = \$("input[name='time_to").val() ; 
						const count_dates = getDatesBetween(dateFromInput,dateToInput,1) ;
						if (afterUnderscore == count_dates) {
							let timePart = dateString.split(' ')[1]; 
							\$("input[name='time_to_"+count_dates+"']").val(timePart) ; 
							return ; 							
						} 
					}					

					set_full_half_day(beforeUnderscore,afterUnderscore) ; 
					
				}) ;
			~ ;
		} 			
			# $trigger_jquery_raw .= qq~	
				
				# \$("$timepicker_ids_string").datetimepicker({language:'pt-BR',pickDate:false});
				
			# ~ ;
		# }
		
		$trigger_jquery_raw .= qq~
			
			let prev_date_part_from = \$("input[name='date_from']").val() ; 
			prev_date_part_from = prev_date_part_from.split(' ')[0] ;
			let prev_date_part_to = \$("input[name='date_to']").val() ; 
			prev_date_part_to = prev_date_part_to.split(' ')[0] ;
			
			\$('#datetimepickerDate_from,#datetimepickerDate_to').on('changeDate', function(e) {
				let from_to = get_row_nr(this.id) ;
				if (this.id == "datetimepickerDate_from") {
					let date_new = \$("input[name='date_from']").val() ; 
					let time_part = date_new.split(' ')[1]; 
					\$("input[name='time_from_1']").val(time_part) ;  
				}
				calc_date_diff_in_days(this.id) ;	
			}) ;
			
			function calc_date_diff_in_days (from_to) {

				let dateFromInput		= \$("input[name='date_from']").val(); 
				let dateToInput   		= \$("input[name='date_to']").val() ;
				
				let date_part_from = dateFromInput.split(' ')[0]; 
				let date_part_to = dateToInput.split(' ')[0]; 

				let time_part_from 	= dateFromInput.split(' ')[1]; 
				let time_part_to 	= dateToInput.split(' ')[1];
	
				if (prev_date_part_from == date_part_from && date_part_to == prev_date_part_to) {
					
					changed_radio_cnt = 0 ; 
					
					const datesBetween = getDatesBetween(dateFromInput,dateToInput,0) ; let date_counter = 0 ; 
					
					for (const date of datesBetween) {
						
						date_counter++ ; 
						 
						if (date_counter > 20) { date_counter = 20 ; break ; }
						
						if (((!saved_time_to[date_counter] || datesBetween.length == date_counter) && from_to.includes("Date_to")) || (date_counter > 1 && !saved_time_from[date_counter] && from_to.includes("Date_from"))) {
							
							if (from_to.includes("Date_from")) {
								\$("input[name='time_from_"+date_counter+"']").val(time_part_from) ;  		
							} else {
								\$("input[name='time_to_"+date_counter+"']").val(time_part_to) ;  	
							}
							
							set_full_half_day('',date_counter) ; 	
							
						}
					}
					if (from_to.includes("Date_to")) {
						saved_time_to[date_counter] = time_part_to ; 
					} else {
						saved_time_from["1"] = time_part_from ; 
					}
	
					return ; 
				}
				
				prev_date_part_from = date_part_from ;
				prev_date_part_to = date_part_to ;

				const date1 			= new Date(dateFromInput);
				const date2 			= new Date(dateToInput);
				
				let hide_date_names = "#1" ;
				
				let glod_user_level = parseInt("$glod_user_level") ;

				let y1 = date1.getFullYear() ; let m1 = date1.getMonth() ; let d1 = date1.getDate() ; let y2 = date2.getFullYear() ; let m2 = date2.getMonth() ; let d2 = date2.getDate() ;

				m1 = m1 + 1 ;
				if (m1 < 10) {
					m1 = "0"+m1.toString() ;
				}
				m2 = m2 + 1 ; 
				if (m2 < 10) {
					m2 = "0"+m2.toString() ;
				}

				if ((y1 == y2 && m1 == m2 && d1 == d2) || date1 > date2) {
					
					if (date1 > date2 && from_to == "datetimepickerDate_from") {
						let date_part_from = dateFromInput.split(' ')[0] ;
						\$("#datetimepickerDate_to").datetimepicker("setDate",date_part_from+" "+time_part_to) ;
						\$("#day_1_name label.control-label").text(date_part_from) ;
					} else if (date1 > date2 && from_to == "datetimepickerDate_to") {
						let date_part_to = dateToInput.split(' ')[0] ;
						\$("#datetimepickerDate_from").datetimepicker("setDate",date_part_to+" "+time_part_from) ;
						\$("#day_1_name label.control-label").text(date_part_to) ;
					}
					
					\$("input[name='time_from_1']").val(time_part_from) ;
					\$("input[name='time_to_1']").val(time_part_to) ;
					
					// changed_radio_cnt = 0 ; 
					
					set_full_half_day('',1) ; 
					
					\$("#radio_1_1").css("display","");
					\$("#radio_1_2").css("display","");	
					
					\$("#radio_row_id_2_1").hide() ;  
					\$("#radio_row_id_2_2").hide() 
					
					if (!\$("#days_drop_downs_1").is(":hidden")) { 
						\$("#start_times_row_1").hide() ;  
						\$("#end_times_row_1").hide() ;  
						\$("#days_drop_downs_1").hide() ; 
					}
					
					if (!\$("#days_drop_downs_2").is(":hidden")) {
						\$("#start_times_row_2").hide() ;  
						\$("#end_times_row_2").hide() ;  
						\$("#days_drop_downs_2").hide() ;  
					}
					
					let reduced_nr_of_days = 0 ; 					
					
					for (let i=2; i<=20; i++) {
						
						\$("#day_"+i+"_chosen").css("display","none") ;
						
						if (\$("#day_"+i).val()) {
							\$("#day_"+i).val("") ;
							\$("#day_"+i).trigger("chosen:updated") ;
							\$("#radio_"+i+"_1").css("display","none") ;
							\$("#radio_"+i+"_2").css("display","none") ;
						}
					}
					
					if (!\$("#day_1").val()) {
						\$("#day_1").val("1") ;
						\$("#day_1").trigger("chosen:updated") ; 
					}
					\$("#inputQty").val("1") ;

					if (!\$("#days_drop_downs_1").is(":hidden")) {
						\$("#days_drop_downs_1").hide() ;
					}
					if (!\$("#start_times_row_1").is(":hidden")) {
						\$("#start_times_row_1").hide() ;
					}
					if (!\$("#end_times_row_1").is(":hidden")) {
						\$("#end_times_row_1").hide() ;
					}

					if (!\$("#days_drop_downs_2").is(":hidden")) {
						\$("#days_drop_downs_2").hide() ;
					}
					if (!\$("#start_times_row_2").is(":hidden")) {
						\$("#start_times_row_2").hide() ;
					}
					if (!\$("#end_times_row_2").is(":hidden")) {
						\$("#end_times_row_2").hide() ;
					}

					return ; 
				}
				
				if (\$("#days_drop_downs_1").is(":hidden")) {
					\$("#days_drop_downs_1").css("display","") ;
					\$("#start_times_row_1").css("display","") ;
					\$("#end_times_row_1").css("display","") ;
				}

				\$("input[name='time_from_1']").val(time_part_from) ;

				const datesBetween = getDatesBetween(dateFromInput,dateToInput,0) ;
				let date_counter = 0 ; let dates_count = 0 ; let count_days = 0 ;
				
				let count_days_after = 0 ; let nr_of_active_days = 0 ; 
				
				let dates_map = {} ;
				
				for (const date of datesBetween) {
					
					date_counter++ ;
					
					dates_map[date_counter] = date ;

					if (date_counter > 20) { date_counter = 20 ; break ; }
					if (date_counter > 1 && !saved_time_from[date_counter]) {
						\$("input[name='time_from_"+date_counter+"']").val(time_part_from) ;
					}
					
					if (!saved_time_to[date_counter]) {
						\$("input[name='time_to_"+date_counter+"']").val(time_part_to) ;
					}
					
					set_full_half_day('',date_counter) ; 
					
					if (\$("#day_"+date_counter+"_chosen").is(":hidden")) {
						
						\$("#radio_"+date_counter+"_1").css("display","");
						\$("#radio_"+date_counter+"_2").css("display","");
						\$("#day_"+date_counter).val("1") ;
						\$("#day_"+date_counter).trigger("chosen:updated") ;
						\$("#day_"+date_counter+"_chosen").css("display","") ;
						\$("#day_"+date_counter+"_chosen").css("width","100%") ;
						\$("#day_"+date_counter).val('1') ; 
						\$("#day_"+date_counter).trigger("chosen:updated") ;
						if (date_counter > 1) {
							// console.log("1 . display timepickerTime_from_"+date_counter) ;
							\$("#timepickerTime_from_"+date_counter).css("display","") ;
						}  
					} 					
					
					if (\$("#day_"+date_counter).val()) {
						\$("#timepickerTime_to_"+date_counter).css("display","") ;
						nr_of_active_days++ ;
					}
					
					\$("#day_"+date_counter+" option[value='1']").text(date) ;
					\$("#day_"+date_counter+" option[value='1']").trigger("chosen:updated") ;

					if (\$("#day_"+date_counter).val()) {
						count_days++ ;
					}
				}
				
				// \$("input[name='time_to_"+date_counter+"']").val(time_part_to) ;
				
				if (\$("#days_drop_downs_2").is(":hidden") && date_counter > 10) {
					// if (glod_user_level > 3) {
					\$("#days_drop_downs_2").css("display","") ;
					\$("#start_times_row_2").css("display","") ;
					\$("#end_times_row_2").css("display","") ;
					\$("#radio_row_id_2_1").css("display","") ; 					
					\$("#radio_row_id_2_2").css("display","") ; 	
				} else if (!\$("#days_drop_downs_2").is(":hidden") && date_counter <= 10) {
					\$("#days_drop_downs_2").css("display","none") ;
					\$("#start_times_row_2").css("display","none") ;
					\$("#end_times_row_2").css("display","none") ;
					\$("#radio_row_id_2_1").css("display","none") ; 						
					\$("#radio_row_id_2_2").css("display","none") ; 
				}
				
				if (count_days_after) {
					date2.setDate(date2.getDate() - count_days_after);
					\$("#datetimepickerDate_to").datetimepicker("setDate",date2) ;
				}
				
				let select_raw ;
				
				let select_chosen_ids_1 = '#1' ;
				let select_chosen_ids_2 = '#2' ;
				let names_to_display = '#3' ;
				
				let def_val = 0 ;
			
				\$("#inputQty").val(count_days) ;
				
				\$("#timepickerTime_to_"+date_counter).css("display","none") ;

				if (date_counter <= 20) {
					for (let j=date_counter+1;j<=20;j++) {
						if (\$("#day_"+j).val()) {
							\$("#day_"+j).val("") ;
							\$("#day_"+j).trigger("chosen:updated") ;
						}
						if (!\$("#day_"+j+"_chosen").is(":hidden")) {
							\$("#day_"+j+"_name label.control-label").text('') ;
							\$("#day_"+j+"_name").css("display","none") ;
							\$("#radio_"+j+"_1").css("display","none") ;
							\$("#radio_"+j+"_2").css("display","none") ;							
							\$("#day_"+j+"_chosen").css("display","none") ;
						}
						if (!\$("#timepickerTime_from_"+j).is(":hidden")) {
							\$("#timepickerTime_from_"+j).css("display","none") ; 
						}
						if (!\$("#timepickerTime_to_"+j).is(":hidden")) {
							\$("#timepickerTime_to_"+j).css("display","none") ;
						}
					}
				}
			}
			
			function timeStringToSeconds(timeString) {
				const [hours, minutes, seconds] = timeString.split(':').map(Number);
				return hours * 3600 + minutes * 60 + seconds;
			}

			function getDatesBetween(startDateStr,endDateStr,count_dates) {
				if (!startDateStr || !endDateStr) {
					return ; 
				}
				const dates = [];
				let currentDate = new Date(startDateStr);
				let endDate = new Date(endDateStr) ; 			
				currentDate.setHours(+2);
				currentDate.setMinutes(0);
				currentDate.setSeconds(0);		
				endDate.setHours(+2);
				endDate.setMinutes(59);
				endDate.setSeconds(59);							
			
				// console.log("2 . currentDate : "+currentDate.toISOString().split('T')[0]) ; 
				while (currentDate < endDate) {
					// console.log("3 . currentDate : "+currentDate.toISOString().split('T')[0]) ; 
					dates.push(currentDate.toISOString().split('T')[0]);
					currentDate.setDate(currentDate.getDate() + 1);
					if (count_dates) { count_dates++ ; }
				} 
				if (count_dates) {
					count_dates-- ;
					return count_dates;
				} else {
					return dates;
				}
			}
		
		~ ;
		
		$preferred_title{location_id} = "Demo Location" ;
		
		$selected{events_operator_required}{$db{$table}{$id}{location_id}} = 'SELECTED' ;
		
		$opts{location_id} = qq~<option value="1" $selected{events_operator_required}{1}>In Country</option><option value="2" $selected{events_operator_required}{2}>Out of Country</option>~ ;
		
		# $fcol = 3 ;
		
		$fcol = 4 ;
		
		$add_form_fields .= &common_min_form_select('location_id') ; 
		
		$preferred_title{venue_ids} = "Demo Venue" ;
		
		$multiple{venue_ids} = 1 ;
		
		if ($db{$table}{$id}{venue_ids}) {
			foreach (split(/\,/,$db{$table}{$id}{venue_ids})) {
				$opts{venue_ids} =~ s/value="$_"/value="$_" SELECTED/g ;
			}
		}
		
		$dlg{venue_ids} .= qq~<div class="col-md-1"><a href="javascript:dlgMdl('$useropts{'scripts'}/dialog/add_school.pl?add&selectVenue_ids','Add Demo Venue','','medium-dialog');" class="btn btn-primary btn-xs" style="padding:0px 2px 0px 3px;margin-top:0px;" title='Add Demo Venue' data-toggle='tooltip' data-placement='right'><i class="glyphicon glyphicon-plus" style="padding:0;margin-top:0px;top:0px;"></i></a></div>~ ; 

		$add_form_fields .= qq~<input style="display:none;" name="venueids" id="venue-ids" value="">~ . &common_min_form_select('venue_ids') ; 
	
		$opts{tenant_id} =~ s/value="$db{$table}{$id}{tenant_id}"/value="$db{$table}{$id}{tenant_id}" SELECTED/g ;
		
		# $allow_deselect{tenant_id}  = 1 ;
		
		$dlg{tenant_id}	= qq~<div class="col-md-1"><a href="javascript:dlgMdl('$useropts{'scripts'}/dialog/add_tenant.pl?add&selectTenant_id','Add Tenant','','medium-dialog');" class="btn btn-primary btn-xs" style="padding:0px 2px 0px 3px;margin-top:0px;" title='Add Tenant' data-toggle='tooltip' data-placement='right'><i class="glyphicon glyphicon-plus" style="padding:0;margin-top:0px;top:0px;"></i></a></div>~ ; 		
		
		$add_form_fields .= &common_min_form_select('tenant_id') ; 
		
		$selected{events_operator_required}{$db{$table}{$id}{events_operator_required}} = 'SELECTED' ;
		
		$opts{events_operator_required} = qq~<option value='1' $selected{events_operator_required}{1}>Yes</option><option value='-1' $selected{events_operator_required}{-1}>No</option>~ ;
		
		$add_form_fields .= &common_min_form_select('events_operator_required') ; 
		
		$fcol = 3 ;
		
		$dlg{events_operator_allocated} = qq~~ ;
		
		$dlg{events_operator_allocated} .= qq~<div class="col-md-1"><a href="javascript:dlgMdl('$useropts{'scripts'}/dialog/add_operator.pl?add&selectEvents_operator_allocated','Add Operator','','medium-dialog');" class="btn btn-primary btn-xs" style="padding:0px 2px 0px 3px;margin-top:0px;" title='Add Operator' data-toggle='tooltip' data-placement='right'><i class="glyphicon glyphicon-plus" style="padding:0;margin-top:0px;top:0px;"></i></a></div>~ ; 
		
		if ($db{$table}{$id}{events_operator_allocated} && $db{$table}{$id}{events_operator_allocated} =~ /;/) {
			foreach (split(";",$db{$table}{$id}{events_operator_allocated})) { ## split(";", OR split(/\;/,
				$opts{events_operator_allocated} =~ s/value="$_"/value="$_" SELECTED/g ;
			}
		} elsif ($db{$table}{$id}{events_operator_allocated}) {
			$opts{events_operator_allocated} =~ s/value="$db{$table}{$id}{events_operator_allocated}"/value="$db{$table}{$id}{events_operator_allocated}" SELECTED/g ;
		} 
	
		$multiple{events_operator_allocated} = 1 ;
		
		my $events_operator_allocated_def = $db{$table}{$id}{events_operator_allocated} ; 
		$events_operator_allocated_def =~ s/\;/\,/g ;
		
		$add_form_fields .= qq~<input type='hidden' name='eventsoperatorallocated' value='$events_operator_allocated_def'>~ . &common_min_form_select('events_operator_allocated',$db{$table}{$id}{events_operator_allocated}) ; 
		
		$trigger_jquery_raw .= qq~
			\$("#selectEvents_operator_allocated").on("change", function () {
				let sel_val = \$(this).chosen().val() ;
				\$("input[name='eventsoperatorallocated']").val(sel_val) ;
			}) ;
		~ ; 
		
		$fcol = 4 ;
		
		$add_form_fields .= &common_min_form_textarea('additional_requirements_from_events_dept',$db{$table}{$id}{additional_requirements_from_events_dept}) ; 

		$selected{calibrator_required}{$db{$table}{$id}{calibrator_required}} = 'SELECTED' ;
		
		$opts{calibrator_required} = qq~<option value='1' $selected{calibrator_required}{1}>Yes</option><option value='-1' $selected{calibrator_required}{-1}>No</option>~ ;
		
		$fcol = 3 ;
		
		$add_form_fields .= &common_min_form_select('calibrator_required',$db{$table}{$id}{calibrator_required}) ; 
		
		$fcol = 4 ;
		
		$add_form_fields .= &build_system_name_form($db{$table}{$id}{event_system_id_multiple},$db{$table}{$id}{club_ids},$db{$table}{$id}{operator_ids},$quote_accepted,$quote_rejected,$quote_cancelled,$db{$table}{$id}{quote_completed}) ;
		
		# $fcol = 6 ;
		
		$lcol = 2 ; $fcol = 4 ;
		
		$dlg{sport_type_ids} .= qq~<div class="col-md-1"><a href="javascript:dlgMdl('$useropts{'scripts'}/dialog/add_sport_type.pl?add&selectSport_type_ids','Add Sport','','medium-dialog');" class="btn btn-primary btn-xs" style="padding:0px 2px 0px 3px;margin-top:0px;" title='Add Sport' data-toggle='tooltip' data-placement='right'><i class="glyphicon glyphicon-plus" style="padding:0;margin-top:0px;top:0px;"></i></a></div>~ ; 		

		$multiple{sport_type_ids} = 1 ; $preferred_title{sport_type_ids} = "Sport Type(s)" ;
		 
		$trigger_jquery_raw .= qq~
			\$("#selectSport_type_ids").change( function () {
				let sel_vals = \$(this).chosen().val() ;
				\$("input[name='sporttypeids']").val(sel_vals) ;
			}) ; 
		~ ;
		
		$add_form_fields .= qq~<input type='hidden' name='sporttypeids' value='$db{$table}{$id}{sport_type_ids}'>~ . &common_min_form_select('sport_type_ids','') ;
		
		$add_form_fields .= &common_min_form_textarea('additional_requirements_from_support_dept',$db{$table}{$id}{additional_requirements_from_support_dept}) ; 
		
		$add_form_fields .= &common_min_form_textarea('pre_demo_testing_requirements',$db{$table}{$id}{pre_demo_testing_requirements}) ; 
		
		# $print_box_content_rows .= &common_min_box_top('','&nbsp;Demo&nbsp;Details',$box_right_bg); #film
		# $print_box_content_rows .= $add_form_fields ;                
		# $print_box_content_rows .= &common_min_box_foot;
		
		&event_tabs_content_box($sec_name,$sec_col);
		
		$print_box_content_rows .= qq~
		<div class='row'>
			<div class='col-md-12'>
			</div>
		</div>~ ; # fixes row highlighting issue

		$print_box_content_rows .= qq~<div class='row'><div class='col-md-12'></div></div>~ ; # fixes row highlighting issue
		
		$trigger_jquery .= qq~
			// \$("#two [id^='select']").css("width","100%") ;
			\$("#two [id^='select']").filter( function() {
				return this.id.endsWith("_chosen");
			}).css("width", "100%");
		~ ; 
		
	} elsif ($tab == 3) { # Workings

		# --------------- START Working ----------------------------------------------------------------------------------------------------------------
	
		$add_form_fields = '' ;

		$lcol = 1 ; 
		$fcol = 2 ;

		my @docs = ('Slip') ;
		
		$add_form_fields .= qq~
			<div class='row'>
		~ ;

		foreach (@docs) {
			my $doc = lc $_ ; $doc =~ s/ /\_/ ; $doc =~ s/&/\_/ ; 
			$event_uploads = &common_get_field_uploads($id,"$doc",'id','delete-attached-slip') ;
			if ($event_uploads) {
				$add_form_fields .= qq~
				<div class="col-md-3" id="costings">
					$event_uploads
				</div>
				~; 
			} else {
				$add_form_fields .= qq~
				<div class="col-md-3">
					<div class="form-group">
						<label for="imageInputFile">Attach Document $_</label>
						<input type="file" id="imageInputFile" name='iattach$doc' tabindex='$tindex'>
						<p class="help-block">Upload file from PC.</p>
					</div>
				</div>
				~ ;		
			}
		}
		
		$trigger_jquery_raw .= qq~
			\$('#delete-attached-slip').click(function (e) {
			   BootstrapDialog.confirm({
					title: 'Confirm Delete',
					message: 'Are you sure you want to delete <strong>$doc</strong>?',
					type: BootstrapDialog.TYPE_DANGER, // <-- Default value is BootstrapDialog.TYPE_PRIMARY <-- Default value is BootstrapDialog.TYPE_WARNING
					callback: function(result) {
						if (result) {
							var url = "$useropts{scripts}/get/get_delete_attach.pl?slips/$db{event_quotes}{$id}{id}&$db{event_quotes}{$id}{slip}&event_quotes&$db{event_quotes}{$id}{id}&slip" ;  
							\$.get(url) ;
							\$('#attach-$id-1').hide() ; // CHECK THAT THE FILE CNT IS ALWAYS ONE                    
							\$('#delete-attached-slip').hide() ;                        
						} else {
							// alert('Nope.');
						}
					}
				});           
			});
		~ ; 
		
		$event_uploads = '' ; 
		# $add_form_fields .= &common_min_form_label_col("Custom Set") ; 
		
		my $custom_set_checked = ($db{$table}{$id}{custom_set}) ? "CHECKED" : "" ;
		
		$add_form_fields .= qq~
				<div class="col-md-3">
					<label>Custom Set Operator Amounts : </label> 
					<input type="checkbox" name="custom_set" value="1" $custom_set_checked>
				</div>
		~ ; #  class="control-label"
		# $add_form_fields .= &common_min_form_checkbox_col('custom_set','') ; 
		
		$add_form_fields .= qq~
			</div>
		~ ;

		our %sec_cnt = ('a_event' => "50-List Expenses") ;
		
		my $sec = 'workings' ; 
		my ($sec_name,$sec_cnt_workings,$sec_col) = &tab_sec_det($sec) ;	
		
		$sec_name = "Demo Expenses" if $demo_page ; ;
		
		$ret_pdf_link_sec .= $sec . '+' . $sec_cnt_workings . '|' ;
		
		return if $ret ;
		
		&db_min_ro('event_cost_items','id,name,rates,full_half_day',"excl_from_expenses < 1 AND name NOT LIKE 'Mobile %' AND name NOT LIKE 'Fixed %' AND name NOT LIKE 'Cricket %'") ; 
		our %event_list_name_array_expenses = () ;
	
		foreach my $iid (keys %{$db{event_cost_items}}) { 	
			$event_list_name_array_expenses{$iid} = $db{event_cost_items}{$iid}{name} ; 
		}		
		# &tab_load_vars ;
		
		if ($demo_page) {
		
			$lcol = 1; 
			$fcol = 2;
			
			if ($db{$table}{$id}{currency}) { 
				$selected{currency}{$db{$table}{$id}{currency}} = 'SELECTED' ; 
			} else { 
				$selected{currency}{ZAR} = 'SELECTED' ; 
			}
			
			$opts{currency} = qq~
				<option value="GBP" $selected{currency}{GBP}>GBP</option>
				<option value="USD" $selected{currency}{USD}>USD</option>
				<option value="ZAR" $selected{currency}{ZAR}>ZAR</option>
				<option value="EUR" $selected{currency}{EUR}>EUR</option>
			~ ; 
			
			$preferred_title{currency} = 'Currency' ; 
			$allow_deselect{currency} = "" ;
			# $required{currency} = 1 ; 
			# $required{roe} = 1 ; 
			
			$req_glyph{currency} = qq~<i class="glyphicon glyphicon-asterisk yellow"></i>~ ;
			$req_glyph{roe} = qq~<i class="glyphicon glyphicon-asterisk yellow"></i>~ ;
			
			$add_form_fields          .= &common_min_form_select('currency',$db{$table}{$id}{currency},1) ; # don't end row
			$trigger_jquery           .= qq~\$("#selectCurrency_chosen").css( "width", "96%" );~ ;
			$preferred_title{roe}      = ' ROE ' ; $fcol=1;  # $fcol=2 ;
			$add_form_fields          .= &common_min_form_label_col('roe') ;
			$db{$table}{$id}{roe} = 1 unless $db{$table}{$id}{roe} ; 
			$add_form_fields          .= &common_min_form_input_col('roe',$db{$table}{$id}{roe},1) ;
			$add_form_fields          .= qq~</div>~ ;
		
		}
		
		&event_tabs_build_sec($sec,$tab) ;
		
		foreach (sort keys %sec_cnt) {
			$_k = substr($_, 1) ;
			my @parts = split(/\-/, $sec_cnt{$_}) ;
			$add_form_fields .= qq~
				<div class='row'>
					<div class='col-md-12'>
						<h4>
							$parts[1] :
						</h4>
					</div>
				</div>
			~ if $parts[1] ne 'Operators';
			
			$add_form_fields .= qq~
				<div class='row'>
					<div class='col-md-12'>
						<div class='col-md-1'>
							<h4>
								$parts[1] :
							</h4>
						</div>
						$icon_casuals 
					</div>
				</div>
			~ if $parts[1] eq 'Operators' ;

			&tab_build_qt_col_headers_workings("$sec$_k") ;	
			# # # &db_min_ro('event_quotes_min', 'id, remarks_workings_event, supplier_workings_event, ref_nr_workings_event, qty_workings_event, amount_usd_workings_event, amount_workings_event, vat_workings_event, description_workings_event', "id = $id", '', '') if $id ;
			
			&event_tabs_build_costs_forms($db{event_quotes}{$id}{id},$tab,$parts[0],"$sec$_k") ; 			
		}
		
		$add_form_fields .= qq~
			<div class='row'>
				<div class="box col-md-12">
					&nbsp;
				</div>
			</div>~ ;
		$add_form_fields .= qq~
			<div class='row'>
				<div class="box col-md-8">
					&nbsp;
				</div>
			~ ;
		
		my @ttlarr = ("sub_total", "vat_total", "grand_total") ;
		$lcol = 1;
		$fcol = 1;
		foreach (@ttlarr) {
			$lcol = 1; 
			$add_form_fields .= &common_min_form_label_col($_) ;   
		}
			
		$add_form_fields .= qq~</div>~ ;
		
		$trigger_jquery_raw .= qq~
			\$("#textareaAdditional_notes").change(function () {
				if (\$(this).val()) {
					\$('label[for="additional_notes_expenses"]').text('Additional Notes : ') ;
					\$("#textareaAdditional_notes_expenses_input").html(\$(this).val()) ; 
				} else if (!\$(this).val() && \$('label[for="additional_notes_expenses"]').text()) {
					\$('label[for="additional_notes_expenses"]').text('') ;
					\$("#textareaAdditional_notes_expenses_input").html('') ;					
				}
			}) ;
		~ ; 
		
		my $add1 = ($db{$table}{$id}{additional_notes}) ? "Additional Notes : " : "" ;
		my $add2 = ($db{$table}{$id}{additional_notes}) ? "$db{$table}{$id}{additional_notes}" : "" ;
		
		$add_form_fields .= qq~<div class='row'><div class="box col-md-1"><label for='additional_notes_expenses'>$add1</label></div><div class="box col-md-4"><p id='textareaAdditional_notes_expenses_input' class="help-block">$add2</p></div><div class="box col-md-1"></div>~ ; 
		$lcol = 2;
		$add_form_fields .= &common_min_form_label_col('Total') ; 
		$lcol = 1;
		
		if ($demo_page) {
			my @ttlarr = ("sub_total","vat_total","grand_total");
			foreach (@ttlarr) {			
				my $field_name = "$_\_workings_event" ;
				$readonly{$field_name} = "READONLY"; 
				my $val = ($db{$table}{$id}{$field_name}) ? $db{$table}{$id}{$field_name} : '0.00' ;
				$add_form_fields .= &common_min_form_input_col($field_name,$val) ; 			
			}
		} else {
			my @ttlarr = ("total_amount_workings_event","total_vat_amount_workings_event","total_grand_amount_workings_event");
			$lcol = 1 ; $fcol = 1 ;
			
			my %renamed_totals = ("total_amount_workings_event" => "sub_total_workings_event", "total_vat_amount_workings_event" => "vat_total_workings_event" , "total_grand_amount_workings_event" => "grand_total_workings_event") ; 
			foreach (@ttlarr) {			
				$readonly{$renamed_totals{$_}} = "READONLY"; 
				$input_style{$renamed_totals{$_}} = qq~style="text-align:right;"~ ;
				my $val = $db{$table}{$id}{$_} ? $db{$table}{$id}{$_} : '0.00' ;
				$add_form_fields .= &common_min_form_input_col($renamed_totals{$_},$val) ; 			
			}		
		}
		 
		$add_form_fields .= qq~</div>~ ;
			
		$add_form_fields .= qq~
			<div class='row'>
				<div class="box col-md-12">
					&nbsp;
				</div>
			</div>~ ;
		
		&event_tabs_content_box($sec_name,$sec_col) ;
		
		&event_tabs_build_forms_jquery(1) ;
		
		# --------------- END WORKING ----------------------------------------------------------------------------------------------------------------
	}

} #----------------------------------------------------------------------------------------

sub event_tabs_build_forms_jquery {
	
	my ($demo_page) = @_ ; 
	
	my $description_options_costing = $opts{"description_costing_event_1"} ;
	$description_options_costing =~ s/\SELECTED//g ;
	$description_options_costing =~ s/\"/\'/g ;
	
	my $tab_name_part = "workings_event" ; 
	 
	my $description_options_workings = $opts{"description_$tab_name_part\_1"} ;
	$description_options_workings =~ s/\SELECTED//g ;
	$description_options_workings =~ s/\"/\'/g ;	

	our $operator_options = $opts{"operator_$tab_name_part\_1"} ;
	$operator_options =~ s/\SELECTED//g ;
	$operator_options =~ s/\"/\'/g ;
	
	my $btn_ids_string = join(",",@btn_ids) ; 

	my $excl_field_ids_string			= join(",",@excl_field_ids) ; 
	my $description_field_ids_string 	= join(",",@description_field_ids) ; 
	my $operator_field_ids_string 		= join(",",@operator_field_ids) ; 
	my $vat_field_ids_string 			= join(",",@vat_field_ids) ;
	my $qty_field_ids_string 			= join(",",@qty_field_ids) ;
	my $amount_usd_field_ids_string 	= join(",",@amount_usd_field_ids) ;
 
	$trigger_jquery_raw .= qq~
		
		function get_tab (id) {
			let tab = "" ; 
			if (id.includes("_workings_event")) {
				tab = "workings_event" ;
			} else if (id.includes("_costing_event")) {
				tab = "costing_event" ;
			}		
			return tab ;
		}
		
		function changed_vat (id) {
			let tab = get_tab (id) ;
			let row_nr = get_row_nr(id) ;
			calc_totals(row_nr,tab) ;
		}
		
		function changed_others (id) {
			 
			let row_nr = get_row_nr(id) ;
			let firstIndex = id.indexOf('_');
			let col = id.substring(0,firstIndex); 
			let tab = get_tab (id) ;
			if (col == "inputAmount") {
				let inp = parseFloat(\$("#"+id).val()) ;
				inp = parseFloat(inp) ;
				\$("#"+id).val(inp.toFixed(2)) ;
			} else if (\$("#selectDescription_"+tab+"_"+row_nr).val() && \$("#selectDescription_"+tab+"_"+row_nr).val() != 14 && \$("#selectOperator_"+tab+"_"+row_nr).val()) {
				// \$("#selectOperator_"+tab+"_"+row_nr).val("") ;
				// \$("#selectOperator_"+tab+"_"+row_nr).trigger("chosen:updated") ;
			} 
			// else if (col == "selectOperator" && \$("#selectDescription"+tab+"_"+row_nr).val() != 14) {
				
			// }
			
			if (col == "selectOperator") { // || (col == "selectDescription" && \$("#selectDescription_"+tab+"_"+row_nr).val(
				return ;
			}
			calc_totals(row_nr,tab) ;			
		}
		
		// \$("$vat_field_ids_string").change(function() {
		\$("#myTabContent").on("change","[id^='checkboxVat_']", function () {
			const id = this.id ; 
			changed_vat(id) ; 
		}) ;

		\$("#myTabContent").on("change","[id^='checkboxExcl_'],[id^='selectDescription_'],[id^='inputQty_'],[id^='inputAmount_usd_'],[id^='inputAmount_ttl_']", function () {
		// \$("$excl_field_ids_string,$description_field_ids_string,$qty_field_ids_string,$amount_usd_field_ids_string,$operator_field_ids_string").change(function() {					
			const id = this.id ; 
			changed_others(id) ; 
		}) ; 
		
	~ ;
	
	my $event_quotes_jquery = qq~~ ; 
	
	if (!$demo_page) {
		$event_quotes_jquery .= qq~			
			let profit_loss = parseFloat(\$("input[name='income']").val().replace(/,/g, '')) - parseFloat(\$("input[name='expenses']").val().replace(/,/g, '')) ; 
			\$("input[name='profit_loss']").val(profit_loss.toFixed(2)) ;
		~ ; 
	}
	
	$trigger_jquery_raw .= qq~	
		
		\$("#myTabContent").on("click","[id^='btn_']", function () {
			
		// \$("$btn_ids_string").click(function () {
		
			const id = this.id ; 
			let tab = get_tab (id) ;
			let row_nr = get_row_nr(id) ;
			\$("#"+tab+"_"+row_nr).show();
			let row_html = "" ; 
			if (tab == "workings_event") {
				row_html = add_quote_expenses_row(row_nr,tab,"$description_options_workings","$operator_options") ; 
			} else if (tab == "costing_event") {
				row_html = add_quote_expenses_row(row_nr,tab,"$description_options_costing","") ; 
			}
			\$("#"+tab+"_"+row_nr).html(row_html);
			// \$("#$suffix\_"+row_nr).trigger("chosen:updated") ; 
			
			\$("#selectDescription_"+tab+"_"+row_nr).chosen({ allow_single_deselect:true }) ;
			
			if (tab == "workings_event") {
				\$("#selectOperator_"+tab+"_"+row_nr).chosen({ allow_single_deselect:true });
				\$("#inputRemarks_"+tab+"_"+row_nr).css("text-align","") ;
				\$("#inputSupplier_"+tab+"_"+row_nr).css("text-align","") ;
				\$("#inputRef_nr_"+tab+"_"+row_nr).css("text-align","") ;
			} 
			
			\$("#btn_"+tab+"_"+row_nr).hide();
			var v = row_nr + 1 ;
			
			// \$("#btn_$suffix\_"+v).css("padding-left","16px") ; 
			\$("#btn_"+tab+"_"+v).html("<i class='glyphicon glyphicon-plus blue'></i>") ; 
			\$("#btn_"+tab+"_"+v).show();
			\$("#btn_row_"+tab+"_"+v).show() ;
			\$("#2_"+tab+"_"+row_nr).show() ;
 		
			\$("#checkboxExcl_"+tab+"_"+row_nr).prop('checked',false) ;
			
		});
		
		~ if $btn_ids_string ; 
	
		$trigger_jquery_raw .= qq~	
		
		\$("#selectCurrency").change(function () {
			
		}) ;
		
		\$("input[name='roe']").change(function () {
			
			let roe = \$(this).val() ; 
			if (roe < 0 || !roe) {
				roe = 1 ; 
			}
			\$(this).val(parseFloat(roe).toFixed(2)) ; 
			
			var sub_total = 0 ; var vat_total = 0 ;  var sub_total_quote = 0 ; var vat_total_quote = 0 ;  
			
			[sub_total,vat_total] 				= add_up_totals("workings_event",50,roe,1) ; 
			[sub_total_quote,vat_total_quote] 	= add_up_totals("costing_event",30,roe,1) ; 
			
			// // // \$("input[name='income']").val((sub_total_quote+vat_total_quote).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ;
			// // // \$("input[name='expenses']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ;
			\$("input[name='income']").val((sub_total_quote+vat_total_quote).toFixed(2)) ;
			\$("input[name='expenses']").val((sub_total+vat_total).toFixed(2)) ;
			update_overall_totals(sub_total,vat_total,"workings_event") ; 
			update_overall_totals(sub_total_quote,vat_total_quote,"costing_event") ; 
			
		}) ;
		
		function add_up_totals (tab,nr_of_rows,roe,recalc_totals) {
			
			let sub_total = 0 ; let vat_total = 0 ;
			for (let i=1; i<=nr_of_rows; i++) {
				if (!\$("#"+tab+"_"+i).html()) { break ; }
				if (\$("#selectDescription_"+tab+"_"+i).val()) {
					if (\$("#checkboxExcl_"+tab+"_"+i).is(":checked")) { continue ; } 
					let ttl = 0 ; 
					if (recalc_totals) {
						ttl = parseFloat(\$("#inputAmount_usd_"+tab+"_"+i).val()) * parseFloat(\$("#inputQty_"+tab+"_"+i).val()) * parseFloat(roe) ;
					} else {
						ttl = parseFloat(\$("#inputAmount_ttl_"+tab+"_"+i).val().replace(/,/g, '')) 
					}
					// // // // \$("#inputAmount_ttl_"+tab+"_"+i).val(ttl.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ;
					\$("#inputAmount_ttl_"+tab+"_"+i).val(ttl.toFixed(2)) ;
					if (!\$("#inputAmount_ttl_"+tab+"_"+i).val() || \$("#inputAmount_ttl_"+tab+"_"+i).val() == "NaN") { 
						\$("#inputAmount_ttl_"+tab+"_"+i).val("0.00") ;
						ttl = 0 ;
					}
					sub_total += ttl ;
					if (\$("#checkboxVat_"+tab+"_"+i).is(":checked")) {
						vat_total += ttl*0.15 ;
					}	
				} else if (!\$("#checkboxExcl_"+tab+"_"+i).is(":checked")) {
					\$("#checkboxExcl_"+tab+"_"+i).prop('checked',true) ;
				}
			}
			return [sub_total,vat_total] ;
		}
		
		// function getNum(val) {
			
			// if (isNaN(val)) {
				// return 0;
			 // }
			// return val;
		// }
			
		function calc_totals (row_cnt,tab) {
 
			var qty  = \$("#inputQty_"+tab+"_"+row_cnt) ;	
			var usd  = \$("#inputAmount_usd_"+tab+"_"+row_cnt) ;
			var conv = \$("#inputAmount_ttl_"+tab+"_"+row_cnt) ;
			var excl = \$("#checkboxExcl_"+tab+"_"+row_cnt) ;
			var item = \$("#selectDescription_"+tab+"_"+row_cnt) ;
						
			if (!usd.val() && !conv.val() && !usd.val()) {
				// console.log("skip calc_totals_workings") ;
				if (!item.val()) {
					excl.prop("checked",true) ;
				}
				return ; 
			}

			var vat  = \$("#checkboxVat_"+tab+"_"+row_cnt) ;
		
			if (!item.val()) { 
			 
				excl.prop("checked",true) ;
				vat.prop("checked",true) ; 
				qty.val("")	; 
				usd.val("")	;
				conv.val("");
				if (tab == "workings_event") {
					var rem  = \$("#inputRemarks_"+tab+"_"+row_cnt) ;
					var sup  = \$("#inputSupplier_"+tab+"_"+row_cnt) ;	
					var ref  = \$("#inputRef_nr_"+tab+"_"+row_cnt) ;	
					var op   = \$("#selectOperator_"+tab+"_"+row_cnt) ;		
					rem.val("")	;
					sup.val("")	;
					ref.val("")	;
					op.val("")	;
					op.trigger("chosen:updated") ;
				}
			} else if (excl.is(":checked") && item.val() && conv.val() == "0.00") {
				excl.prop("checked",false) ;
			}
			
			if (!\$("#inputRoe").val()) { \$("#inputRoe").val(1) ; }
			
			let roe = parseFloat(\$("#inputRoe").val()) ;

			let ttl = usd.val() * qty.val() * roe ;
			
			// // // conv.val(ttl.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ;
			conv.val(ttl.toFixed(2)) ;
			
			let sub_total = 0 ; let vat_total = 0 ;  
			
			let nr_of_rows = 50 ; 
			if (tab == "costing_event") {
				nr_of_rows = 30 ; 
			}
			
			[sub_total,vat_total] = add_up_totals (tab,nr_of_rows,roe,0) ; 
			
			console.log("add_up_totals : "+sub_total) ; 
			
			if (tab == "workings_event") {
				// // // \$("input[name='expenses']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ;
				\$("input[name='expenses']").val((sub_total+vat_total).toFixed(2)) ;
				update_overall_totals(sub_total,vat_total,tab) ; 
			} else {
				// // // \$("input[name='income']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; 
				\$("input[name='income']").val((sub_total+vat_total).toFixed(2)) ; 
				update_overall_totals(sub_total,vat_total,tab) ; 
				// update_overall_totals_costings(sub_total,vat_total) ; 
			}
		}
		
		function update_overall_totals (sub_total,vat_total,tab) {
			
			$event_quotes_jquery
			
			// // // \$("input[name='profit_loss']").val(profit_loss.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ;
			// // // \$("input[name='sub_total_"+tab+"']").val(sub_total.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ;
			// // // \$("input[name='vat_total_"+tab+"']").val(vat_total.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ;
			// // // \$("input[name='grand_total_"+tab+"']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ;			
			
			\$("input[name='sub_total_"+tab+"']").val(sub_total.toFixed(2)) ;
			\$("input[name='vat_total_"+tab+"']").val(vat_total.toFixed(2)) ;
			\$("input[name='grand_total_"+tab+"']").val((sub_total+vat_total).toFixed(2)) ;			
		}	
		
		function add_quote_expenses_row (row_nr,tab,options1,options2) {
			
			let tindex = $tindex ; 
			tindex = parseInt(tindex) ;
			row_nr = parseInt(row_nr) ;
			tindex = tindex - 10*(1+50-row_nr) ;
			
			let row = add_checkbox(row_nr,"excl_"+tab+"_"+row_nr,"checkboxExcl_"+tab+"_"+row_nr,tindex,1) ; tindex++ ;

			row = row+add_select(row_nr,"description_"+tab+"_"+row_nr,"selectDescription_"+tab+"_"+row_nr,"Select Description "+row_nr,options1,tindex,2,90,'','') ; tindex++ ;
			if (tab == "workings_event") {
				row = row+add_select(row_nr,"operator_workings_event_"+row_nr,"selectOperator_"+tab+"_"+row_nr,"Select Operator "+row_nr,options2,tindex,2,90,'','') ; tindex++ ;
				row = row+add_input(row_nr,"remarks_workings_event_"+row_nr,"inputRemarks_"+tab+"_"+row_nr,"Remarks "+row_nr,tindex,'',1) ; tindex++ ;
				row = row+add_input(row_nr,"supplier_workings_event_"+row_nr,"inputSupplier_"+tab+"_"+row_nr,"Supplier "+row_nr,tindex,'',1) ; tindex++ ;
				row = row+add_input(row_nr,"ref_nr_workings_event_"+row_nr,"inputRef_nr_"+tab+"_"+row_nr,"Ref Nr "+row_nr,tindex,'',1) ; tindex++ ;				
			}
			row = row+add_input(row_nr,"qty_"+tab+"_"+row_nr,"inputQty_"+tab+"_"+row_nr,"Qty "+row_nr,tindex,'',1) ; tindex++ ;
			row = row+add_input(row_nr,"amount_usd_"+tab+"_"+row_nr,"inputAmount_usd_"+tab+"_"+row_nr,"Amount "+row_nr,tindex,'',1) ; tindex++ ;
			row = row+add_input(row_nr,"amount_ttl_"+tab+"_"+row_nr,"inputAmount_ttl_"+tab+"_"+row_nr,"Total Amount "+row_nr,tindex,"readonly",1) ; tindex++ ;
			row = row+add_checkbox(row_nr,"vat_"+tab+"_"+row_nr,"checkboxVat_"+tab+"_"+row_nr,tindex,1) ; tindex++ ;
			return row ; 
		}
	~ ;
	
} #------------------------------------------------------------------------------------------

sub build_boxes_right {

my ($id,$tab) = @_ ;

tab_build_qt_right($id,$tab) ;

} #----------------------------------------------------------------------------------------

sub view_screen {
	
	&edit_screen ;

} #------------------------------------------------------------------------------------------

sub edit_screen {

	unless ($i{id}) { $warning = qq(NO ID) ; return ; }

	our ($lcol,$fcol) = &common_min_columns($label_col,$field_col) ;
	# called from common_add_screen

	&select_opts($i{id}) ;
	
	our $savjqy = 1 ; # incorporate jquery into the save event to accommodate the multiple chosen options
	
	&build_boxes_edit($i{id}) ;
	
	&common_min_extra_crumb("search-$lcpage\s","Search Screen") ;
	
} #------------------------------------------------------------------------------------------

sub build_boxes_bottom {

	my ($id) = @_ ;

	our ($lcol,$fcol) = &common_min_columns(2,2) ;

	$add_form_fields  = '' ;

	# --------------- START GRAND TOTAL ----------------------------------------------------------------------------------------------------------------------

	$print_box_content_rows .= &common_min_form_input('activetab',$db{$table}{$id}{activetab},'hidden') ;

	# --------------- END RAND TOTAL ------------------------------------------------------------------------------------------------------------------------

} #----------------------------------------------------------------------------------------

sub build_boxes_top {

	my ($id) = @_ ;

	&event_tabs_build_boxes_top($id,1) ; 

} #----------------------------------------------------------------------------------------

sub build_extra_name_row_1 {
	
	my ($row_cnt,$display) = @_ ; 
	my $count_dates_in_first_extra_row = 0 ; 
	$display = ($display) ? "style='display:none;'" : "" ; 
	my $extra_row_hearders_1 = qq~<div class='row' id='day_names_$row_cnt\_extra_1' $display><div class='col-md-2'></div>~ ;
	for (1 .. 20) {
		$count_dates_in_first_extra_row++ if $days_active_arr[$_ - 1] ;
		$date_is_displayed_in_first_extra_row{$_} = 1 if $days_active_arr[$_ - 1] && $count_dates_in_first_extra_row <= 10 ;
		$extra_row_hearders_1 .= ($days_active_arr[$_ - 1] && $count_dates_in_first_extra_row <= 10 && $some_row_has_daily_op_1) ? qq~<div class='col-md-1' id="day_$_\_name_$row_cnt\_extra_1"><label class='control-label'>&nbsp;&nbsp;$default_active_event_dates{$_}</label></div>~ : qq~<div class='col-md-0' id="day_$_\_name_$row_cnt\_extra_1" style='display:none;'><label class='control-label'>&nbsp;&nbsp;$default_active_event_dates{$_}</label></div>~ ;
	}
	$extra_row_hearders_1 .= qq~</div>~ ; 
	return $extra_row_hearders_1 ;
	
} #----------------------------------------------------------------------------------------

sub build_extra_name_row_2 {
	
	my ($row_cnt,$display) = @_ ; 
	$display = ($display) ? "style='display:none;'" : "" ; 
	my $extra_row_hearders_2 = qq~<div class='row' id='day_names_$row_cnt\_extra_2' $display><div class='col-md-2'></div>~ ;
	for (11 .. 20) {
		$extra_row_hearders_2 .= ($some_row_has_daily_op_2 && $days_active_arr[$_ - 1] && !$date_is_displayed_in_first_extra_row{$_}) ? qq~<div class='col-md-1' id="day_$_\_name_$row_cnt\_extra_2"><label class='control-label'>&nbsp;&nbsp;$default_active_event_dates{$_}</label></div>~ : qq~<div class='col-md-0' id="day_$_\_name_$row_cnt\_extra_2" style="display:none;"><label class='control-label'>&nbsp;&nbsp;$default_active_event_dates{$_}</label></div>~ ;				
	}
	$extra_row_hearders_2 .= qq~</div>~ ; 	
	return  $extra_row_hearders_2; 
	
} #----------------------------------------------------------------------------------------

sub build_system_name_form {
	
	my ($system_ids,$club_ids,$op_ids,$quote_accepted,$quote_rejected,$quote_cancelled,$quote_completed) = @_ ; 
	
	my @system_name_ids 	= split(/\;/,$system_ids) ;		
	my @club_ids        	= split(/\;/,$club_ids) ;	
	# our @days_active_arr	= split(/\;/,$days_active) ;
	my @table_op_ids		= ($op_ids =~ /;/) ? split(/\;/,$op_ids) : split(/\,/,$op_ids) ;	
	
	local $system_count = 0 ; local $system_day_cnt = 0 ; my %row_has_daily_op = () ;  my $some_row_has_daily_op = 0 ;  our $some_row_has_daily_op_1 = 0 ; our $some_row_has_daily_op_2 = 0 ; my $active_days_count = 0 ; 
	
	foreach my $row (split(/\|/,$daily_operator_ids)) {
		$system_count++ ; 

		next unless $row ;
		$system_day_cnt = 0 ;
		foreach my $default_op (split(/\;/,$row)) {
			$system_day_cnt++ ;
			# next if !$days_active_arr[$system_day_cnt-1] ;
			# $active_days_count++ ; 
			# $default_op_ids{$system_count}{$system_day_cnt} = $default_op if $default_op ;
		}
	}
	
	# $active_days_count = 0 ; my $total_days = 0 ; 
	
	# foreach (@days_active_arr) {
		# $active_days_count++ if $_ ;
		# $total_days++ ;
	# }
	
	# $some_row_has_daily_op = 0 if $active_days_count > 6 ;
	
	$fcol = 2 ; $lcol = 2 ; 

	# $dlg_add_club = ($glod_user_level < 3 && ($quote_accepted || $quote_rejected || $quote_cancelled)) ? '<div class="col-md-1"></div>' : qq~<div class="col-md-1"><a href="javascript:dlgMdl('$useropts{'scripts'}/dialog/add_club.pl?add&selectClub_ids','Add Club','','medium-dialog');" class="btn btn-primary btn-xs" style="position:absolute;right:0%;padding:0px 2px 0px 3px;margin-top:0px;" title='Add Club' data-toggle='tooltip' data-placement='right'><i class="glyphicon glyphicon-plus" style="padding:0;margin-top:0px;top:0px;"></i></a></div>~ ;
	$dlg_add_club = ((($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) || ($quote_completed && $glod_user_level <= 3)) ? '<div class="col-md-1"></div>' : qq~<div class="col-md-1"><a href="javascript:dlgMdl('$useropts{'scripts'}/dialog/add_club.pl?add&selectClub_ids','Add Club','','medium-dialog');" class="btn btn-primary btn-xs" style="position:absolute;right:0%;padding:0px 2px 0px 3px;margin-top:0px;" title='Add Club' data-toggle='tooltip' data-placement='right'><i class="glyphicon glyphicon-plus" style="padding:0;margin-top:0px;top:0px;"></i></a></div>~ ;
	
	# if ($glod_user_level > 2 || ($glod_user_level < 3 && ($quote_accepted || $quote_rejected || $quote_cancelled))) {		
	$add_form_fields .= qq~
		<div class='row'>
			<div class='col-md-2'>
				<label class="control-label">System&nbsp;Details</label>
			</div>
			<div class='col-md-4'>
				<div class='row'>
					<div class='col-md-4'>
						<label class='control-label'>&nbsp;&nbsp;System&nbsp;Name</label>
					</div>
					<div class='col-md-3'>
						<label class='control-label'>&nbsp;&nbsp;Club&nbsp;Name</label>
					</div>
					$dlg_add_club
					<div class='col-md-4'>
						<label class='control-label'>&nbsp;&nbsp;Operator&nbsp;Name</label>
					</div>
				</div>
			</div>
		</div>
		~ ;
			
	our %date_is_displayed_in_first_extra_row = () ; 	
		
	# if ($active_days_count <= 6) {
		
		# for (1 .. 20) {
			# $add_form_fields .=  ($some_row_has_daily_op && $days_active_arr[$_ - 1]) ? qq~<div class='col-md-1' id="day_$_\_name"><label class='control-label'>&nbsp;&nbsp;$default_active_event_dates{$_}</label></div>~ : ($some_row_has_daily_op && !$days_active_arr[$_ - 1] && $final_day >= $_) ? qq~<div class='col-md-1' id="day_$_\_name" style="display:none;"><label class='control-label'>&nbsp;&nbsp;$default_active_event_dates{$_}</label></div>~ :
			# qq~<div class='col-md-0' id="day_$_\_name" style='display:none;'><label class='control-label'>&nbsp;&nbsp;</label></div>~   ;
		# }
		# $add_form_fields .= qq~</div>~ ; 	
		
	# } else {
		# for (1 .. 20) {
			# $add_form_fields .= qq~<div class='col-md-0' id="day_$_\_name" style="display:none;"><label class='control-label'>&nbsp;&nbsp;</label></div>~  ;
		# }
		# $add_form_fields .= qq~</div>~ ; 
	# } 

	my $note_display_butt = qq~~ ;
	
	my $system_name_id = "" ; my $club_name_id = "" ;	

	my @plus_button_ids = () ; my @event_system_ids = () ; my @event_club_ids = () ; my @event_operator_ids = () ; my @overall_op_ids = () ;
	
	my @table_system_name_ids = () ; my @table_club_name_ids = () ; my @table_operator_calibration_ids = () ;
	
	my $old_op_opts = $opts{operator_ids} ; 
	$opts{operator_ids} =~ s/\SELECTED//g ;
	
	for my $row_cnt (1 .. $nr_of_system_names_and_clubs) {
		
		my $select_sys_name = 0 ; my $select_club_name = 0 ; 

		$add_form_fields .= qq~<div class='row' id="system_name_row_$row_cnt" style="margin-bottom:3px;display:none;"></div>~ if $row_cnt > 1 and not $system_name_ids[$row_cnt - 1] and not $club_ids[$row_cnt - 1] ;
		$add_form_fields .= qq~<div class='row' id="system_name_row_$row_cnt" style="margin-bottom:3px;">~ if $row_cnt == 1 or $system_name_ids[$row_cnt - 1] or $club_ids[$row_cnt - 1] ;
		
		push @plus_button_ids,"#btn_system_name_$row_cnt" ; 
		
		my $input_fields_dates_1 = qq~~ ; 
		my $input_fields_1 = qq~~ ; 
		my $input_fields_dates_2 = qq~~ ; 
		my $input_fields_2 = qq~~ ; 
		
		if ($row_cnt == 1 || $row_has_daily_op{$row_cnt} || $system_name_ids[$row_cnt - 1] || $club_ids[$row_cnt - 1]) {

			# if ($glod_user_level < 3 && ($quote_accepted || $quote_rejected || $quote_cancelled)) {
			if ((($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) || ($quote_completed && $glod_user_level <= 3)) {
				
				$system_name_id = "inputSystem_name_" ; $club_name_id = "inputClub_name_" ;	
				$readonly{"system_name_$row_cnt"} = "READONLY" ; $readonly{"club_name_$row_cnt"} = "READONLY" ; $readonly{"operator_id_calibration_$row_cnt"} = "READONLY" ;
				$add_form_fields .= qq~<div class="col-md-3"></div>~ ; 
				$add_form_fields .= qq~<div class="col-md-8"><div class="row">~ ; 
				$fcol = 4 ;
				$add_form_fields .= &common_min_form_input_col("system_name_$row_cnt",$db{event_systems}{$system_name_ids[$row_cnt - 1]}{name}) ;
				$add_form_fields .= &common_min_form_input_col("club_name_$row_cnt",$db{clubs}{$club_ids[$row_cnt - 1]}{name}) ;
				$add_form_fields .= &common_min_form_input_col("operator_id_calibration_$row_cnt",$db{users}{$table_op_ids[$row_cnt - 1]}{name}) ;			
				$add_form_fields .= qq~</div></div>~ ; 
				
			} else { 
			
				$system_name_id = "selectSystem_name_" ; $club_name_id = "selectClub_name_" ; $op_name_id = "selectOperator_id_calibration_" ;

				push @event_system_ids,"#$system_name_id$row_cnt\_chosen" ; 
				push @event_club_ids,"#$club_name_id$row_cnt\_chosen" ; 
				push @event_operator_ids,"#$op_name_id$row_cnt\_chosen" ; 
				push @overall_op_ids,"#selectOperator_id_calibration_$row_cnt" ;
				
				$opts{"system_name_$row_cnt"} = $opts{event_system_id} ; $opts{"club_name_$row_cnt"} = $opts{club_ids} ;  $opts{"operator_id_calibration_$row_cnt"} = $opts{operator_ids} ; 
				# $allow_deselect{"system_name_$row_cnt"} = 1 ; $allow_deselect{"club_name_$row_cnt"} = 1 ; $allow_deselect{"operator_id_calibration_$row_cnt"} = 1 ; 
				
				my $sys_name_id = $system_name_ids[$row_cnt - 1] ;
				if ($sys_name_id) {
					$trigger_jquery_raw .= qq~\$("#selectSystem_name_$row_cnt").val('$sys_name_id') ; \$("#selectSystem_name_$row_cnt").trigger("chosen:updated") ;	~ ;
				} else {
					push @table_system_name_ids,"#selectSystem_name_$row_cnt" ; 
				}
				
				my $club_id = $club_ids[$row_cnt - 1] ;
				if ($club_id) {
					$trigger_jquery_raw .= qq~\$("#selectClub_name_$row_cnt").val('$club_id') ; \$("#selectClub_name_$row_cnt").trigger("chosen:updated") ;	~ ;
				} else {
					push @table_club_name_ids,"#selectClub_name_$row_cnt" ; 
				}
				
				my $op_id = $table_op_ids[$row_cnt - 1] ;
 
				$preferred_title{"operator_id_calibration_$row_cnt"} = "Operator $row_cnt" ; 
				
				$fcol = 4 ;
				
				$add_form_fields .= qq~<div class="col-md-2"></div>~ ; 
				$add_form_fields .= qq~<div class="col-md-4"><div class="row">~ ; 
				
				$add_form_fields .= &common_min_form_select_col("system_name_$row_cnt",$system_name_ids[$row_cnt - 1]) if $row_cnt == 1 ;
				$add_form_fields .= &common_min_form_select_col("system_name_$row_cnt",'') if $row_cnt > 1 ;
				$add_form_fields .= &common_min_form_select_col("club_name_$row_cnt",$club_ids[$row_cnt - 1]) if $row_cnt == 1 ;
				$add_form_fields .= &common_min_form_select_col("club_name_$row_cnt",'') if $row_cnt > 1 ;
				$add_form_fields .= &common_min_form_select_col("operator_id_calibration_$row_cnt",'') ;
			
				$add_form_fields .= qq~</div></div>~ ; 
				
				$fcol = 2 ;
				
				my $clicked_op_butt = ($row_has_daily_op{$row_cnt}) ? qq~value="1"~ : qq~~ ;
				
				if (!$row_has_daily_op{$row_cnt} && $op_id) {
					$trigger_jquery_raw .= qq~\$("#selectOperator_id_calibration_$row_cnt").val('$op_id') ; \$("#selectOperator_id_calibration_$row_cnt").trigger("chosen:updated") ; ~ ;
				} else {
					push @table_operator_calibration_ids,"#selectOperator_id_calibration_$row_cnt" ; 
				}
		
				for (1 .. 20) {
					push @daily_op_ids,"#selectCustom_operator_$row_cnt\_$_" ;
				}
		
				if ($active_days_count <= 6) {
					
				} else {

				} 
				$select_sys_name = $system_name_ids[$row_cnt] ;
				$select_sys_name = '' unless $select_sys_name ;
			}
			$add_form_fields .= qq~</div>~ ;
		} 
		
		# $add_form_fields .= ($active_days_count > 6 && $some_row_has_daily_op_1 && ($row_cnt == 1 || $row_has_daily_op{$row_cnt} || $system_name_ids[$row_cnt - 1] || $club_ids[$row_cnt - 1] || $table_op_ids[$row_cnt - 1])) ? qq~<div class='row' id='space_row_$row_cnt'>&nbsp;</div>~ : qq~~ ;
			
		$note_display_butt = '' ;
		
		# if ($glod_user_level < 3 && ($quote_accepted || $quote_rejected || $quote_cancelled)) {
		if ((($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) || ($quote_completed && $glod_user_level <= 3)) {
			$note_display_butt = qq~display:none;~ ; 
		} else {
			if ($row_cnt > 1 and not $system_name_ids[$row_cnt-1] and not $club_ids[$row_cnt-1]) {
				$note_display_butt = qq~display:none;~ ; 
			}			
			if ($system_name_ids[$row_cnt] or $club_ids[$row_cnt]) {
				$note_display_butt = qq~display:none;~ ; 
			}
			$add_form_fields .= qq~
				<div class='row' id = "btn_row_$row_cnt">
					<div class='col-md-2'></div>
					<div class='col-md-1'>
						<a id="btn_system_name_$row_cnt" href="#" style="padding-left:16px;$note_display_butt">
							<i class="glyphicon glyphicon-plus blue"></i>
						</a>
					</div>
				</div>
			~ ;
		} 
	}

	$opts{operator_ids} = $old_op_opts ; 

	my $table_system_name_ids_string = join(",",@table_system_name_ids) ; 
	my $table_club_name_ids_string = join(",",@table_club_name_ids) ; 
	my $table_operator_calibration_ids_string = join(",",@table_operator_calibration_ids) ;
	
	my @all_table_ids = () ; 
	push @all_table_ids,$table_system_name_ids_string if $table_system_name_ids_string ;
	push @all_table_ids,$table_club_name_ids_string if $table_club_name_ids_string ;
	push @all_table_ids,$table_operator_calibration_ids_string if $table_operator_calibration_ids_string ;
	
	my $all_table_ids_string = join(",",@all_table_ids) ; 
 
	$trigger_jquery_raw .= qq~ 
		\$("$all_table_ids_string").val('') ; \$("$all_table_ids_string").trigger("chosen:updated") ;
	~ if $all_table_ids_string ;
	
	my $plus_button_ids_string = join(",",@plus_button_ids) ; 
	
	# if ($glod_user_level < 3 && ($quote_accepted || $quote_rejected || $quote_cancelled)) {
	if ((($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) || ($quote_completed && $glod_user_level <= 3)) {
		
	} else {
	
		my $system_name_options = &fix_options_for_javascript($opts{"system_name_1"}) ;
		my $club_name_options = &fix_options_for_javascript($opts{"club_name_1"}) ;
		our $operator_options = &fix_options_for_javascript($opts{"operator_id_calibration_1"}) ;
		my $event_system_ids_string 	= join(",",@event_system_ids) ; 
		my $event_club_ids_string 		= join(",",@event_club_ids) ; 
		my $event_operator_ids_string 	= join(",",@event_operator_ids) ; 
		my $daily_op_ids_string         = join(",",@daily_op_ids) ; 
		my $overall_op_ids_string 		= join(",",@overall_op_ids) ;
		$trigger_jquery .= qq~\$("$event_system_ids_string,$event_club_ids_string").css("width","100%");~ ;		
		$trigger_jquery .= qq~\$("$event_operator_ids_string").css("width","100%");~ ;		
		
		my $table_plus_button_ids_string = join (",",@table_plus_button_ids) ;
		# $table_plus_button_ids_string  = "#selectCustom_operator_1_1,#selectCustom_operator_1_3,#selectCustom_operator_1_2" ;
		# $table_plus_button_ids_string  = "#selectCustom_operator_1_1,#selectCustom_operator_1_3,#selectCustom_operator_1_2" ;

		$trigger_jquery_raw .= qq~ 
			
			function get_row_nr (id) {
				let lastIndex = id.lastIndexOf('_');
				lastIndex = parseInt(lastIndex) ;
				let row_nr = id.substring(1+lastIndex); 
				row_nr = parseInt(row_nr) ;
				return row_nr ; 
			}	
			
			function add_checkbox (row_nr,field_name,field_id,tindex,fcol) {
				let checkbox = "<div class='col-md-"+fcol+" checkbox_checked' id='c_"+field_name+"'><input name='"+field_name+"' data-no-uniform='true' type='checkbox' id='"+field_id+"' checked value='1' tabindex='"+tindex+"'><label for='"+field_id+"'></label></div>" ; 
				return checkbox ; 
			}
			
			function add_input (row_nr,field_name,field_id,placeholder,tindex,readonly,fcol) {
				let input = "<div class='col-md-"+fcol+"'><div class='control-group'><div class='controls'><input type='text' name='"+field_name+"' class='form-control' id='"+field_id+"' style='text-align:right;' placeholder='"+placeholder+"' value='' "+readonly+" tabindex='"+tindex+"'></div></div></div>" ;
				return input ;
			}		
			
			function add_select (row_nr,field_name,field_id,placeholder,options,tindex,fcol,width,div_id,hide_div) {	
				let select = "<div class='col-md-"+fcol+"' "+div_id+" "+hide_div+">" ;
				select = select + add_select_raw(row_nr,field_name,field_id,placeholder,options,tindex,width) ; 
				select = select + "</div>" ; 
				return select ; 	
			}
			
			function add_select_raw (row_nr,field_name,field_id,placeholder,options,tindex,width) {
				let select_raw = "<div class='control-group'><div class='controls'><select class='form-control' style='margin:2px 0 2px 0; width: "+width+"%;' name='"+field_name+"' id='"+field_id+"'data-placeholder='"+placeholder+"' data-rel='chosen' tabindex='"+tindex+"'><option value=''></option>"+options+"</select></div></div>" ;
				return select_raw ;
			}
			
			function add_event_system_extra_row (row_cnt,nr_of_active_days) {
				
			}
			
			function add_event_system_row (row_cnt,nr_of_active_days) {
				
				let new_row = "<div class='col-md-2'></div><div class='col-md-4'><div class='row'>" ; 
				
				new_row = new_row + add_select (row_cnt,"system_name_"+row_cnt,"selectSystem_name_"+row_cnt,"Select System Name "+row_cnt,"$system_name_options",-1,4,100,'','') ;
				new_row = new_row + add_select (row_cnt,"club_name_"+row_cnt,"selectClub_name_"+row_cnt,"Select Club Name "+row_cnt,"$club_name_options",-1,4,100,'','') ;
				new_row = new_row + add_select (row_cnt,"operator_id_calibration_"+row_cnt,"selectOperator_id_calibration_"+row_cnt,"Select Operator "+row_cnt,"$operator_options",-1,4,100,'','') ;
				
				// let glod_user_level = parseInt("$glod_user_level") ; 
				
				// if (glod_user_level < 3) { return new_row ; }
				
				// new_row = new_row +"</div></div><div class='col-md-0'><a href='#' class='dt-center' style='position:absolute;right:49.6%;padding:1px 2px 1px 3px;margin-top:2px;' title='Add Daily Operators' data-toggle='tooltip' data-placement='right' id = 'add_daily_operators_"+row_cnt+"'><i class='glyphicon glyphicon-plus blue' style='padding:0;margin-top:2px;top:-2px;'></i><input type='text' name='clicked_button_"+row_cnt+"' style='display:none;'></a></div>" ;
				
				// let extra_row_1,extra_row_2,extra_name_row_1,extra_name_row_2 ;
				
				// // if (nr_of_active_days <= 6) {
					
					// for (let col=1; col<=20; col++) {
						// // if (\$("#day_"+col).val()) {
							// // new_row = new_row + add_select (row_cnt,"custom_operator_"+row_cnt+"_"+col,"selectCustom_operator_"+row_cnt+"_"+col,"Select an Option","$operator_options",-1,1,100,"id='day_"+row_cnt+"_"+col+"'","style='display:none;'") ;
						// // } else {
							// new_row = new_row + "<div class='col-md-0' id='day_"+row_cnt+"_"+col+"' style='display:none;'></div>" ;
						// // }
					// }
					
					// new_row = new_row+"</div>" ;
					// extra_row_1 = "<div class='row' id='system_name_row_"+row_cnt+"_extra_1' style='display:none;'><div class='col-md-2'></div>" ;
					// extra_name_row_1 = "<div class='row' id='day_names_"+row_cnt+"_extra_1' style='display:none;'><div class='col-md-2'></div>" ;
					// for (let col=1; col<=20; col++) {
						// extra_row_1 = extra_row_1+"<div class='col-md-0' id='day_"+row_cnt+"_"+col+"_extra_1' style='display:none;'></div>" ;
						// extra_name_row_1 = extra_name_row_1+"<div class='col-md-0' id='day_"+col+"_name_"+row_cnt+"_extra_1' style='display:none;'><label class='control-label'>&nbsp;&nbsp;</label></div>" ;
					// }	
					// extra_row_1 = extra_row_1+"</div>" ;
					// extra_row_2 = "<div class='row' id='system_name_row_"+row_cnt+"_extra_2' style='display:none;'><div class='col-md-2'></div>" ;
					// extra_name_row_2 = "<div class='row' id='day_names_"+row_cnt+"_extra_2' style='display:none;'><div class='col-md-2'></div>" ;
					// for (let col=11; col<=20; col++) {
						// extra_row_2 = extra_row_2+"<div class='col-md-1' id='day_"+row_cnt+"_"+col+"_extra_2' style='display:none;'></div>" ;
						// extra_name_row_2 = extra_name_row_2+"<div class='col-md-0' id='day_"+col+"_name_"+row_cnt+"_extra_2' style='display:none;'><label class='control-label'>&nbsp;&nbsp;</label></div>" ;
					// }	
					// extra_row_2 = extra_row_2+"</div>" ;
					// extra_name_row_2 = extra_name_row_2+"</div>" ;
					
				// // } else {
						
					// // const datesBetween = getDatesBetween(\$("input[name='date_from']").val(),\$("input[name='date_to']").val(),0) ;
					
					// // let date_counter = 0 ; let dates_map = {} ; 
					// // for (const date of datesBetween) {
						// // date_counter++ ; 
						// // dates_map[date_counter] = date ;
					// // }
					
					// // let nr_dates_used = 0 ; let dates_used = {} ; 
					
					// // for (let col=1; col<=20; col++) {
						// // new_row = new_row + "<div class='col-md-0' id='day_"+row_cnt+"_"+col+"' style='display:none;'></div>" ;
					// // }
					
					// // extra_row_1 = "<div class='row' id='system_name_row_"+row_cnt+"_extra_1'><div class='col-md-2'></div>" ;
					// // extra_name_row_1 = "<div class='row' id='day_names_"+row_cnt+"_extra_1' style='display:none;'><div class='col-md-2'></div>" ;
					
					// // for (let col=1; col<=20; col++) {
						// // if (\$("#day_"+col).val()) {
							// // nr_dates_used++ ;
							// // dates_used[col] = 1 ; 
							// // if (nr_dates_used > 10) { break ; } 
							// // extra_row_1 = extra_row_1+add_select (row_cnt,"custom_operator_"+row_cnt+"_"+col,"selectCustom_operator_"+row_cnt+"_"+col,"Select an Option","$operator_options",-1,1,100,"id='day_"+row_cnt+"_"+col+"_extra_1'","style='display:none;'") ;
							// // extra_name_row_1 = extra_name_row_1+"<div class='col-md-0' id='day_"+col+"_name_"+row_cnt+"_extra_1'><label class='control-label'>&nbsp;&nbsp;"+dates_map[col]+"</label></div>" ;
							
						// // } else {
							// // extra_row_1 = extra_row_1+"<div class='col-md-0' id='day_"+row_cnt+"_"+col+"_extra_1' style='display:none;'></div>" ;
							// // extra_name_row_1 = extra_name_row_1+"<div class='col-md-0' id='day_"+col+"_name_"+row_cnt+"_extra_1' style='display:none;'><label class='control-label'>&nbsp;&nbsp;</label></div>" ;
						// // }
					// // }
					// // extra_row_1 = extra_row_1+"</div>" ;
					// // extra_name_row_1 = extra_name_row_1+"</div>" ;
					
					// // if (nr_of_active_days > 10 || nr_dates_used < nr_of_active_days) {
						// // extra_row_2 = "<div class='row' id='system_name_row_"+row_cnt+"_extra_2'><div class='col-md-2'></div>" ;
						// // extra_name_row_2 = "<div class='row' id='day_names_"+row_cnt+"_extra_2'><div class='col-md-2'></div>" ;
					// // } else {
						// // extra_row_2	 	 = "<div class='row' id='system_name_row_"+row_cnt+"_extra_2' style='display:none;'><div class='col-md-2'></div>" ;
						// // extra_name_row_2 = "<div class='row' id='day_names_"+row_cnt+"_extra_2' style='display:none;'><div class='col-md-2'></div>" ;
					// // }
					
					// // for (let col=11; col<=20; col++) {
						// // if (\$("#day_"+col).val() && !dates_used[col]) {
							// // extra_row_2 = extra_row_2+add_select (row_cnt,"custom_operator_"+row_cnt+"_"+col,"selectCustom_operator_"+row_cnt+"_"+col,"Select an Option","$operator_options",-1,1,100,"id='day_"+row_cnt+"_"+col+"_extra_2'","style='display:none;'") ;
							// // extra_name_row_2 = extra_name_row_2+"<div class='col-md-0' id='day_"+col+"_name_"+row_cnt+"_extra_2'><label class='control-label'>&nbsp;&nbsp;"+dates_map[col]+"</label></div>" ;
						// // } else {
							// // extra_row_2 = extra_row_2+"<div class='col-md-0' id='day_"+row_cnt+"_"+col+"_extra_2' style='display:none;'></div>" ;
							// // extra_name_row_2 = extra_name_row_2+"<div class='col-md-0' id='day_"+col+"_name_"+row_cnt+"_extra_2' style='display:none;'><label class='control-label'>&nbsp;&nbsp;</label></div>" ;
						// // }
					// // }	
					// // extra_row_2 = extra_row_2+"</div>" ;
					// // extra_name_row_2 = extra_name_row_2+"</div>" ;

				// // } 
				
				// \$("#system_name_row_"+row_cnt).after(extra_row_2) ; 
				// \$("#system_name_row_"+row_cnt).after(extra_name_row_2) ; 
				// \$("#system_name_row_"+row_cnt).after(extra_row_1) ; 
				// \$("#system_name_row_"+row_cnt).after(extra_name_row_1) ; 
				
				let prev_row = row_cnt - 1 ; 
				
				// if (nr_of_active_days > 6 && \$("input[name='clicked_button_"+prev_row+"']").val()) {
					// \$("#system_name_row_"+row_cnt).before("<div class='row' id='extra_heading_"+row_cnt+"'><div class='col-md-3'></div><div class='col-md-8'><div class='row'><div class='col-md-4'><label class='control-label'>&nbsp;&nbsp;System&nbsp;Name</label></div><div class='col-md-4'><label class='control-label'>&nbsp;&nbsp;Club&nbsp;Name</label></div><div class='col-md-4'><label class='control-label'>&nbsp;&nbsp;Operator&nbsp;Name</label></div></div></div></div>") ;
				// }
				
				return new_row ; 
			}
			
			// function process_operators_when_selecting_daily_operator (id) {
				 
				// let lastIndex 	= id.lastIndexOf('_');
				// let id2 		= id.substring(0,lastIndex);  
				// let lastIndex2 	= id2.lastIndexOf('_');
				// lastIndex2		= parseInt(lastIndex2) ;
				// let row_nr 		= id2.substring(lastIndex2+1);
				// let col_nr 		= get_row_nr(id) ;	
				// let sel_val = \$("#"+id).val() ;
 
				// if (sel_val) {
					// deselect_overall_operator_when_selecting_daily_operator(id) ;
					// for (let i=1;i<=20;i++) {
						// if (i == col_nr) { continue ; }
						// if (!\$("#selectCustom_operator_"+row_nr+"_"+i).val() && (\$("#day_"+row_nr+"_"+i).html() || \$("#day_"+row_nr+"_"+i+"_extra_1").html() || \$("#day_"+row_nr+"_"+i+"_extra_2").html())) {
							// \$("#selectCustom_operator_"+row_nr+"_"+i).val(sel_val) ;
							// \$("#selectCustom_operator_"+row_nr+"_"+i).trigger("chosen:updated") ;
						// }
					// }	 
				// }
			// }
 
			function deselect_overall_operator_when_selecting_daily_operator (daily_op_id) {
				
				let lastIndex = daily_op_id.lastIndexOf('_') ;
				lastIndex = parseInt(lastIndex) ;
				const id_2 = daily_op_id.substring(0,lastIndex) ; 
				lastIndex = id_2.lastIndexOf('_') ;
				lastIndex = parseInt(lastIndex) ;
				const col_nr = id_2.substring(lastIndex+1); 
				\$("#selectOperator_id_calibration_"+col_nr).val('') ;
				\$("#selectOperator_id_calibration_"+col_nr).trigger("chosen:updated") ;
				// \$("#selectOperator_id_calibration_"+col_nr+"_chosen").val('') ;
				// \$("#selectOperator_id_calibration_"+col_nr+"_chosen").trigger("chosen:updated") ;	
				
			}
			
			function add_operator_dropdown (date_name_id,select_box_id,select_name,select_id,date,row_nr,do_not_display) {
				
				// console.log("add_operator_dropdown : "+date_name_id+" , "+select_box_id) ; 

				if (!do_not_display) {
					display_non_empty_operator_dropdown (date_name_id,select_box_id) ; 
				}			
				if (\$("#"+select_box_id).html()) { 
					return ;
				}
				\$("#"+date_name_id+" label.control-label").text(date) ;
				let transfer_val = \$("#"+select_id).val() ;
				let select_drop_down =  add_select_raw (row_nr,select_name,select_id,"Select an Option","$operator_options",-1,100) ;		
				\$("#"+select_box_id).html(select_drop_down) ; 
				\$("#"+select_box_id).trigger("chosen:updated") ;
				\$("#"+select_id).chosen({allow_single_deselect:true}) ;
				\$("#"+select_id+"_chosen").css("width","100%") ;						
				
				if (transfer_val) {
					\$("#"+select_id).val(transfer_val) ;
					\$("#"+select_id).trigger("chosen:updated") ;
				}
			}
			
			function display_non_empty_operator_dropdown (date_name_id,select_box_id) {
				
				// console.log("display_non_empty_operator_dropdown : "+date_name_id+" , "+select_box_id) ; 
				
				if (!\$("#"+select_box_id).is(":hidden")) {
					return ;
				} 
				
				// console.log("display_non_empty_operator_dropdown : "+date_name_id+",:::,"+select_box_id) ; 
				 
				\$("#"+date_name_id).show() ;
				\$("#"+date_name_id).removeClass('col-md-0').addClass('col-md-1');	 						
				\$("#"+select_box_id).show() ;
				\$("#"+select_box_id).removeClass('col-md-0').addClass('col-md-1');
			}
			
			function delete_operator_dropdown (date_name_id,select_box_id,do_not_hide) {
				
				// console.log("delete_operator_dropdown : "+date_name_id+" , "+select_box_id) ; 
				
				if (!do_not_hide) {
					hide_non_empty_operator_dropdown (date_name_id,select_box_id) ; 
				}
				if (!\$("#"+select_box_id).html()) { 
					return ;
				}
				\$("#"+date_name_id+" label.control-label").text('&nbsp;&nbsp;') ;	
				\$("#"+select_box_id).html('') ; 
				\$("#"+select_box_id).trigger("chosen:updated") ;	
			}
			
			function hide_non_empty_operator_dropdown (date_name_id,select_box_id) {
				
				// console.log("hide_non_empty_operator_dropdown : "+date_name_id+" , "+select_box_id) ; 
				
				if (\$("#"+select_box_id).is(":hidden")) {
					return ;
				}
				\$("#"+date_name_id).hide() ;
				\$("#"+date_name_id).removeClass('col-md-1').addClass('col-md-0') ;
				\$("#"+select_box_id).removeClass('col-md-1').addClass('col-md-0') ;
				\$("#"+select_box_id).hide() ;
			}
			
			function click_add_daily_operator (id) {
				
				let row_nr = get_row_nr(id) ;	
				\$("#clicked_any_button").text("1") ;
				// \$("input[name='clicked_button_"+row_nr+"']").val("1") ;	
				 
				// console.log("nr_of_active_days : "+nr_of_active_days)  ;
				 
				// let nr_of_active_days = calc_nr_of_active_days() ; 
				
				// console.log(\$("input[name='time_from").val()) ; 
				
				// console.log("time_from : "+\$("input[name='date_from']").val()) ; 
				// console.log("time_to   : "+\$("input[name='date_to']").val()) ; 
				
				// const datesBetween = getDatesBetween(\$("input[name='date_from']").val(),\$("input[name='date_to']").val(),0) ;
				
				// let date_counter = 0 ; let dates_map = {} ; 
				// for (const date of datesBetween) {
					// date_counter++ ; 
					// dates_map[date_counter] = date ;
				// }
				
				if (nr_of_active_days && nr_of_active_days <= 6) {
					// for (let i=1; i<=20; i++) {  
						// if (\$("#day_"+i).val()) {
							// add_operator_dropdown ("day_"+i+"_name","day_"+row_nr+"_"+i,"custom_operator_"+row_nr+"_"+i,"selectCustom_operator_"+row_nr+"_"+i,dates_map[i]) ;
							// if (\$("#selectCustom_operator_"+row_nr+"_"+i).val() && \$("#selectOperator_id_calibration_"+row_nr).val()) {
								// \$("#selectOperator_id_calibration_"+row_nr).val('') ;
								// \$("#selectOperator_id_calibration_"+row_nr).trigger("chosen:updated") ;
							// }
						// } else {
							// delete_operator_dropdown ("day_"+i+"_name","day_"+row_nr+"_"+i) ;						
						// }
					// }							
				} else {
					
					// if (\$("#system_name_row_"+row_nr+"_extra_1").is(":hidden")) {
						// \$("#system_name_row_"+row_nr+"_extra_1").show() ;
					// }
					
					// if (\$("#day_names_"+row_nr+"_extra_1").is(":hidden")) {
						// \$("#day_names_"+row_nr+"_extra_1").show() ;
					// }
					
					
					let next_row = row_nr + 1 ; 
					if (!\$("#extra_heading_"+row_nr).length && row_nr > 1) {
						\$("#system_name_row_"+row_nr).before("<div class='row' id='extra_heading_"+row_nr+"'><div class='col-md-3'></div><div class='col-md-8'><div class='row'><div class='col-md-4'><label class='control-label'>&nbsp;&nbsp;System&nbsp;Name</label></div><div class='col-md-4'><label class='control-label'>&nbsp;&nbsp;Club&nbsp;Name</label></div><div class='col-md-4'><label class='control-label'>&nbsp;&nbsp;Operator&nbsp;Name</label></div></div></div></div>") ;						
					}
					if (!\$("#system_name_row_"+next_row).is(":hidden") && !\$("#extra_heading_"+next_row).length) {
						\$("#system_name_row_"+next_row).before("<div class='row' id='extra_heading_"+next_row+"'><div class='col-md-3'></div><div class='col-md-8'><div class='row'><div class='col-md-4'><label class='control-label'>&nbsp;&nbsp;System&nbsp;Name</label></div><div class='col-md-4'><label class='control-label'>&nbsp;&nbsp;Club&nbsp;Name</label></div><div class='col-md-4'><label class='control-label'>&nbsp;&nbsp;Operator&nbsp;Name</label></div></div></div></div>") ; 
					}
					
					let nr_dates_used = 0 ; let dates_used = {} ;
					
					// let fix_width_ids = "#1" ;
					
					// for (let i=1; i<=20; i++) {
						
						// delete_operator_dropdown ("day_"+i+"_name","day_"+row_nr+"_"+i) ;			
				
						// if (\$("#day_"+i).val() && nr_dates_used < 10) { 
							// nr_dates_used++ ; 
							// dates_used[i] = 1 ;
							// if (\$("#day_"+i+"_name_"+row_nr+"_extra_1").is(":hidden") && \$("#day_"+i).val()) {
								// \$("#day_"+i+"_name_"+row_nr+"_extra_1").show() ;
								// \$("#day_"+i+"_name_"+row_nr+"_extra_1").removeClass('col-md-0').addClass('col-md-1') ;
							// } else if (!\$("#day_"+i+"_name_"+row_nr+"_extra_1").is(":hidden") && !\$("#day_"+i).val()) {
								// \$("#day_"+i+"_name_"+row_nr+"_extra_1").hide() ;
								// \$("#day_"+i+"_name_"+row_nr+"_extra_1").removeClass('col-md-1').addClass('col-md-0') ;								
							// }
							// add_operator_dropdown("day_"+i+"_name_"+row_nr+"_extra_1","day_"+row_nr+"_"+i+"_extra_1","custom_operator_"+row_nr+"_"+i,"selectCustom_operator_"+row_nr+"_"+i,dates_map[i],row_nr) ;
							// fix_width_ids = fix_width_ids+",#selectCustom_operator_"+row_nr+"_"+i+"_chosen" ;
							
						// } else {
							// delete_operator_dropdown("day_"+i+"_name_"+row_nr+"_extra_1","day_"+row_nr+"_"+i+"_extra_1") ; 			
						// }
					// } 
					
					
					// if (nr_of_active_days >  10 || nr_dates_used < nr_of_active_days) {
						
						// if (\$("#system_name_row_"+row_nr+"_extra_2").is(":hidden")) {
							// \$("#system_name_row_"+row_nr+"_extra_2").show() ;
						// }
						
						// if (\$("#day_names_"+row_nr+"_extra_2").is(":hidden")) {
							// \$("#day_names_"+row_nr+"_extra_2").show() ;
						// }	
						
						// for (let i=11; i<=20; i++) {  
							// if (\$("#day_"+i).val() && !dates_used[i]) {
								// nr_dates_used++ ;
								// if (\$("#day_"+nr_dates_used+"_name_"+row_nr+"_extra_2").is(":hidden") && \$("#day_"+i).val()) {
									// \$("#day_"+nr_dates_used+"_name_"+row_nr+"_extra_2").show() ;
									// \$("#day_"+nr_dates_used+"_name_"+row_nr+"_extra_2").removeClass('col-md-0').addClass('col-md-1') ;
								// }
								// add_operator_dropdown("day_"+i+"_name_"+row_nr+"_extra_2","day_"+row_nr+"_"+i+"_extra_2","custom_operator_"+row_nr+"_"+i,"selectCustom_operator_"+row_nr+"_"+i,dates_map[i],row_nr) ;
								// fix_width_ids = fix_width_ids+",#selectCustom_operator_"+row_nr+"_"+i+"_chosen" ; 					
							// }
							// else {
								// delete_operator_dropdown("day_"+i+"_name_"+row_nr+"_extra_2","day_"+row_nr+"_"+i+"_extra_2") ; 				
							// }
						// }						
					// }
					
					// \$(fix_width_ids).css("width","100%") ; 
					
					
				}
				
				// display_non_empty_operator_dropdown("day_1_name","day_"+q+"_"+col) ; 
				
			}		
					
			function deselect_daily_operators (id) {	
			
				if (\$("#"+id).val()) {
					let row_nr = get_row_nr(id) ;
					for (let col=1;col<=20;col++) {
						if (!\$("#day_"+row_nr+"_"+col).html() && !\$("#day_"+row_nr+"_"+col+"_extra_1").html() && !\$("#day_"+row_nr+"_"+col+"_extra_2").html()) { 
							continue ; 
						}
						\$("#selectCustom_operator_"+row_nr+"_"+col).val('') ;
						\$("#selectCustom_operator_"+row_nr+"_"+col).trigger("chosen:updated") ;
					}
				}				
			}		
			
			function calc_nr_of_active_days () {
				
				let nr_of_active_days = 0 ;
				for (let i=1; i<=20; i++) {
					if (\$("#day_"+i).val()) {
						nr_of_active_days++ ;
					}
				}
				return nr_of_active_days ;
			}
			
			\$("$plus_button_ids_string").click( function () {
				
				let row_nr = get_row_nr(this.id) ;
				row_nr = parseInt(row_nr) ;
				
				var v = row_nr + 1 ; var v2 = row_nr + 2 ;		
				\$("#btn_system_name_"+row_nr).hide();	
				if (v < 15 && \$('#system_name_row_'+v2).is(':hidden')) {
					\$("#btn_system_name_"+v).show() ;
				}
				\$("#system_name_row_"+v).show() ;
				\$("#system_name_row_"+v).css("margin-bottom","3px") ;
				
				let nr_of_active_days = 0 ; let custom_operator_ids_list = "#selectCustom_operator_"+v+"_1" ; let custom_operator_ids_list_chosen = "#selectCustom_operator_"+v+"_1_chosen" ;
				
				// for (let i=1; i<=20; i++) {
					// if (i > 1) {
						// custom_operator_ids_list = custom_operator_ids_list+",#selectCustom_operator_"+v+"_"+i ;
						// custom_operator_ids_list_chosen = custom_operator_ids_list_chosen+",#selectCustom_operator_"+v+"_"+i+"_chosen" ;						
					// } 
					// if (\$("#day_"+i).val()) {
						// nr_of_active_days++ ;
					// }
				// }
				
				let add_row = add_event_system_row(v,nr_of_active_days) ; 
				
				\$("#system_name_row_"+v).html(add_row) ; 
				\$("#system_name_row_"+v).trigger("chosen:updated") ;  
 
				\$("#selectSystem_name_"+v).chosen({allow_single_deselect:true}) ;
				\$("#selectClub_name_"+v).chosen({allow_single_deselect:true}) ;
				\$("#selectOperator_id_calibration_"+v).chosen({allow_single_deselect:true}) ;
				
				// // for (let i=1; i<=20; i++) {
					// // \$("#selectCustom_operator_"+v+"_"+i).chosen({allow_single_deselect:true}) ;
					// \$(""+custom_operator_ids_list).chosen({allow_single_deselect:true}) ;
					// \$(""+custom_operator_ids_list_chosen).css("width","100%") ; 
					// // \$("#selectCustom_operator_"+v+"_"+i+"_chosen").css("width","100%") ; 
				// // }
				
				// \$("#system_name_row_"+v).on("click","#add_daily_operators_"+v, function() {
					// event.preventDefault();
					// click_add_daily_operator (this.id) ;
				// }); 
				
				// \$("#system_name_row_"+v).on("change","#selectCustom_operator_"+v+"_1,#selectCustom_operator_"+v+"_2,#selectCustom_operator_"+v+"_3,#selectCustom_operator_"+v+"_4,#selectCustom_operator_"+v+"_5,#selectCustom_operator_"+v+"_6,#selectCustom_operator_"+v+"_7,#selectCustom_operator_"+v+"_8,#selectCustom_operator_"+v+"_9,#selectCustom_operator_"+v+"_10,#selectCustom_operator_"+v+"_11,#selectCustom_operator_"+v+"_12,#selectCustom_operator_"+v+"_13,#selectCustom_operator_"+v+"_14,#selectCustom_operator_"+v+"_15,#selectCustom_operator_"+v+"_16,#selectCustom_operator_"+v+"_17,#selectCustom_operator_"+v+"_18,#selectCustom_operator_"+v+"_19,#selectCustom_operator_"+v+"_20", function() {
					// process_operators_when_selecting_daily_operator(this.id) ; 
				// });
				
				// \$("#system_name_row_"+v).on("change","#selectOperator_id_calibration_"+v, function() {	
					// deselect_daily_operators(this.id) ;
				// }); 
			}); 
			
			// \$("$table_plus_button_ids_string").click( function () {
				
				// click_add_daily_operator (this.id) ;
				
				// let v = get_row_nr(this.id) ;	
				// \$("#system_name_row_"+v).on("change","#selectCustom_operator_"+v+"_1,#selectCustom_operator_"+v+"_2,#selectCustom_operator_"+v+"_3,#selectCustom_operator_"+v+"_4,#selectCustom_operator_"+v+"_5,#selectCustom_operator_"+v+"_6,#selectCustom_operator_"+v+"_7,#selectCustom_operator_"+v+"_8,#selectCustom_operator_"+v+"_9,#selectCustom_operator_"+v+"_10,#selectCustom_operator_"+v+"_11,#selectCustom_operator_"+v+"_12,#selectCustom_operator_"+v+"_13,#selectCustom_operator_"+v+"_14,#selectCustom_operator_"+v+"_15,#selectCustom_operator_"+v+"_16,#selectCustom_operator_"+v+"_17,#selectCustom_operator_"+v+"_18,#selectCustom_operator_"+v+"_19,#selectCustom_operator_"+v+"_20", function() {
					// process_operators_when_selecting_daily_operator(this.id) ; 
				// });
				
			// }) ; 
 
			// \$("$daily_op_ids_string").change( function () {
				// process_operators_when_selecting_daily_operator(this.id) ; 
			// }) ;
			
						
			// \$("$overall_op_ids_string").change( function () {
				// deselect_daily_operators(this.id) ;
			// }) ;
		~ ; 
		
	}

	# my $table_extra_op_ids_string = join(",",@table_extra_op_ids) ; 
	
	# $trigger_jquery_raw .= qq(\$("$table_extra_op_ids_string").chosen({ allow_single_deselect:true });) ;
 
	$fcol = ''  ; 
	
} #----------------------------------------------------------------------------------------

sub fix_options_for_javascript {
	
	my ($options) = @_ ; 
	$options =~ s/\SELECTED//g ;
	$options =~ s/\"/\'/g ;
	return $options ; 
	
} #----------------------------------------------------------------------------------------

sub q_get_val {

	my ($val) = @_ ;

	my $disp_val = $val ;

	if ($val eq '0.00') { 
		$disp_val = '' ; 
	}

	return ($disp_val);

} #------------------------------------------------------------------------------------------

sub set_check_boxes_checked {

	my ($id,$rcnt,$prefix,$suffix) = @_ ;
	
	for (1 .. $rcnt) { 

		my $ifield  = $prefix . '_' . "$_$suffix" ;
		my $val = $db{$table}{$id}{$ifield} ;	
		# &common_debug("set_check_boxes_checked: [prefix=$prefix] [suffix=$suffix] ifield=$ifield, val=$val") ;
		
		$checkit{$ifield} = $val ;
	}
	
} #----------------------------------------------------------------------------------------

sub select_opts {

	my ($id) = @_ ;

	if ($id) {
		
		&db_min_ro('event_quotes',"demo_id,id,region_id,custom_set,event_length,date_from,date_to,ref,organisation_ids,event_system_id_multiple,club_ids,operator_ids,times_from,times_to,days_active,qty,quote_completed,quote_accepted,quote_rejected,quote_cancelled,quote_pending,total_amount_workings_event,total_vat_amount_workings_event,total_grand_amount_workings_event,slip,notes,office_notes,email,tel,contact_name,address,currency,roe,quote_to","`demo_id`='$id'",'','') ; 
		
		&db_min_ro($table,"*","`id`='$id'",'','')  ;  
		
		$db{$table}{$id}{name}	 						= $db{event_quotes}{$id}{ref} ;
		$db{$table}{$id}{date_from} 					= $db{event_quotes}{$id}{date_from} ;
		$db{$table}{$id}{date_to} 						= $db{event_quotes}{$id}{date_to} ;
		$db{$table}{$id}{venue_ids}						= $db{event_quotes}{$id}{organisation_ids} ;
		$db{$table}{$id}{date_to} 						= $db{event_quotes}{$id}{date_to} ;
		$db{$table}{$id}{event_system_id_multiple}		= $db{event_quotes}{$id}{event_system_id_multiple} ;
		$db{$table}{$id}{club_ids} 						= $db{event_quotes}{$id}{club_ids} ;
		$db{$table}{$id}{operator_ids} 					= $db{event_quotes}{$id}{operator_ids} ;
		$db{$table}{$id}{qty}							= $db{event_quotes}{$id}{qty} ;
		$db{$table}{$id}{times_from}					= $db{event_quotes}{$id}{times_from} ;
		$db{$table}{$id}{times_to}						= $db{event_quotes}{$id}{times_to} ;
		$db{$table}{$id}{days_active}					= $db{event_quotes}{$id}{days_active} ;
		$db{$table}{$id}{quote_completed}				= $db{event_quotes}{$id}{quote_completed} ;
		$db{$table}{$id}{quote_accepted}				= $db{event_quotes}{$id}{quote_accepted} ;
		$db{$table}{$id}{quote_rejected}				= $db{event_quotes}{$id}{quote_rejected} ;
		$db{$table}{$id}{quote_cancelled}				= $db{event_quotes}{$id}{quote_cancelled} ;
		$db{$table}{$id}{quote_pending} 				= $db{event_quotes}{$id}{quote_pending} ;
		$db{$table}{$id}{sub_total_workings_event}		= $db{event_quotes}{$id}{total_amount_workings_event} ;
		$db{$table}{$id}{vat_total_workings_event}		= $db{event_quotes}{$id}{total_vat_amount_workings_event} ;
		$db{$table}{$id}{grand_total_workings_event}	= $db{event_quotes}{$id}{total_grand_amount_workings_event} ;
		$db{$table}{$id}{slip}							= $db{event_quotes}{$id}{slip} ;
		$db{$table}{$id}{notes}							= $db{event_quotes}{$id}{notes} ;
		$db{$table}{$id}{office_notes}					= $db{event_quotes}{$id}{office_notes} ;
		$db{$table}{$id}{email}							= $db{event_quotes}{$id}{email} ;
		$db{$table}{$id}{tel}							= $db{event_quotes}{$id}{tel} ;
		$db{$table}{$id}{contact_name}					= $db{event_quotes}{$id}{contact_name} ;
		$db{$table}{$id}{address}						= $db{event_quotes}{$id}{address} ;
		$db{$table}{$id}{currency}						= $db{event_quotes}{$id}{currency} ; 
		$db{$table}{$id}{roe}							= $db{event_quotes}{$id}{roe} ;
		$db{$table}{$id}{quote_to}						= $db{event_quotes}{$id}{quote_to} ;
		$db{$table}{$id}{custom_set}					= $db{event_quotes}{$id}{custom_set} ;
		$db{$table}{$id}{event_length}					= $db{event_quotes}{$id}{event_length} ;
		# $db{$table}{$id}{country_id}					= $db{event_quotes}{$id}{country_id} ;
		$db{$table}{$id}{region_id}						= $db{event_quotes}{$id}{region_id} ;
 
		&db_min_ro('event_quotes_min',"id,amount_workings_event,vat_workings_event,qty_workings_event,amount_usd_workings_event,remarks_workings_event,ref_nr_workings_event,operator_workings_event,excl_workings_event,supplier_workings_event,description_workings_event","`id`='$db{event_quotes}{$id}{id}'",'','') ;
		
	}
	
	$db{$table}{$id}{quote_nr} = $id if $id ;
	
	# &common_min_select_opts('camera_system_id','camera_systems','name','','','name','') ;
	
	&db_min_ro('regions',"id,name,code,country_id","",'','') ; 
	&db_min_ro('users',"id,name,region_ids","user_type LIKE 'casual%' AND block <> 1 AND inactive <> 1",'','') ; 
		
	foreach my $op_id (sort {$db{users}{$a}{name} cmp $db{users}{$b}{name}} keys %{$db{users}}) {	
		my $regions = "" ; 
		foreach (split(",",$db{users}{$op_id}{region_ids})) {
			$regions .= "$db{regions}{$_}{code}," ;
		}
		chop $regions if $regions ;
		my $user_names = $db{users}{$op_id}{name} ;
		$user_names = "$db{users}{$op_id}{name} [$regions]" if $regions ;
		$opts{operator_ids} .= qq~<option value="$op_id">$user_names</option>~ ; 	
		$opts{operators_field} .= qq~<option value="$op_id">$user_names</option>~ ; 	
		
		# for (1 .. $nr_of_system_names_and_clubs) {
			# $opts{"operator_ids_$_"} .= qq~<option value = "$op_id" $selected_table{$_}{$op_id}>$user_names</option>~ ; 	
	}
	

	foreach (sort {$db{regions}{$a}{name} cmp $db{regions}{$b}{name}} keys %{$db{regions}}) {
		my $region_name = ($db{regions}{$_}{code}) ? "$db{regions}{$_}{name} [$db{regions}{$_}{code}]" : "$db{regions}{$_}{name}" ;
		$opts{region_id} .= qq~<option value='$_'>$region_name</option>~ ; 
	}
	
	if ($db{$table}{$id}{region_id}) {
		$db{$table}{$id}{country_id} = $db{regions}{$db{$table}{$id}{region_id}}{country_id} ;
		$opts{region_id} =~ s/value='$db{$table}{$id}{region_id}'/value='$db{$table}{$id}{region_id}' SELECTED/g ;
	}

	my $selcntry = ($db{$table}{$id}{country_id}) ? $db{$table}{$id}{country_id} : 242 ; 
	&common_min_select_opts('country_id','countries','name',$selcntry,1,'country','','id');
	
	# $db{event_quotes}{''}{quote_to} = 5 if $iaction eq 'add' ; # SuperSport Schools (Pty) Ltd
	$db{event_quotes}{''}{quote_to} = 139 if $iaction eq 'add' ; # SuperSport Schools (Pty) Ltd
	$onload = qq~onload=dispCustomer();~ if $iaction eq 'add' ; # SuperSport Schools (Pty) Ltd
 
	my $saved_demo_id = $db{event_quotes}{$id}{quote_to} ;
	$db{event_quotes}{$id}{quote_to} = 139 ;
	# &event_tabs_customer_select_opts('customers','name','','quote_to');
	&event_tabs_customer_select_opts('customers','name',"name='Demo' OR id = '$saved_demo_id'",'quote_to');
	
	
	$trigger_jquery_raw .= qq~
		\$("#selectQuote_to").change(function() {					
			dispCustomer() ;
		});
	~;
	
	my $venue_sql  ;
	
	if ($iaction ne 'add') {
		
		$venue_sql = ($db{$table}{$id}{region_id}) ? "`region_id`='$db{$table}{$id}{region_id}'" : "" ;
		
		if ($db{$table}{$id}{venue_ids}) {
			$venue_sql .= " OR " if $venue_sql ;
			$venue_sql .= join(" OR ",map{ "`id`='$_'" } split(",",$db{$table}{$id}{venue_ids})) ;  ## split works
		}

		if ($selcntry && !$db{$table}{$id}{region_id}) {
			$venue_sql .= " OR " if $venue_sql ;
			foreach  (keys %{$db{regions}}) {
				next if $db{regions}{$_}{country_id} ne $selcntry ;
				$venue_sql .= "`region_id`='$_' OR "  ;
			}
			
			$venue_sql = substr($venue_sql,0,-4) if substr($venue_sql,-4,4) eq " OR " ; 
			
		}		
	}

	&common_min_select_opts('tenant_id','demo_tenants','name','',1,'name','') ;
	&common_min_select_opts('event_system_id','event_systems','name','',1,'description','') ;
	&common_min_select_opts('club_ids','clubs','name','',0,'','') ;
	&common_min_select_opts('venue_ids','organisations','name','',0,'',$venue_sql) ;
	&common_min_select_opts('events_operator_allocated','users','name','',0,'','') ;
	&common_min_select_opts('sport_type_ids','sport_types','name','','','','','','name') ;

	$extra_css .= qq(<style>
	.checkbox_checked label {
		position: absolute;
		width: 20px;
		height: 20px;
		background-color: green;
		-webkit-transition: background-color 1s ease-out 1s;
		-moz-transition: background-color 1s ease-out 1s;
		-o-transition: background-color 1s ease-out 1s;
		transition: background-color 1s ease-out 1s;
		margin:0;
	}

	.checkbox_checked input[type=checkbox]:checked + label {
		background-color:red;
		-webkit-transition: background-color 1s ease-out 1s;
		-moz-transition: background-color 1s ease-out 1s;
		-o-transition: background-color 1s ease-out 1s;
		transition: background-color 1s ease-out 1s;
	}

	.checkbox_checked label:after {
		position: absolute ;
		bottom: 8px ;
		width: 18px ;
		height: 10px ;
		opacity: 0 ;
		content: '' ;
		background: transparent ;
		border: 3px solid #000 ;
		border-top: none ;
		border-right: none ;
		-webkit-transform: rotate(-50deg) ;
		-moz-transform: rotate(-50deg) ;
		-ms-transform: rotate(-50deg) ;
		-o-transform: rotate(-50deg) ;
		transform: rotate(-50deg) ;
		-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
		filter: alpha(opacity=0) ;
	}
	.checkbox_checked input[type=checkbox] {
		visibility: hidden ;
	}
	.checkbox_checked input[type=checkbox]:checked + label:after {
		opacity: 1 ;
		-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)" ;
		filter: alpha(opacity=100) ;    
	}
	</style>) ;
	
	$trigger_jquery_raw .= qq~	
		\$("#savebutt").click( function() {
			let venue_ids = \$("#selectVenue_ids").chosen().val() ;
			\$("#venue-ids").val(venue_ids) ;
			\$('#demos-form').submit() ;
		}) ;
	~ ;

} #-------------------------------------------------------------------------------

sub page_opts {

	our $glyphicon     = 'global' ;
	our $lcpage        = 'demo' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ;
	our $table         = 'demos' ;
	
	our $cust_cols     = 1 ; # display _blank_3.pm
	our $savjqy        = 1 ; 
	our $max_cams      = 10 ;

	&common_min_add_box_icon ;
	
	our %casuals       = (); 

} #-------------------------------------------------------------------------------

sub report_ifields {

	if ($i{event_from} && $i{event_to}) { # check dates
		
		my @srch_ed_from = &common_split_sql_time($i{event_from}) ;
		my @srch_ed_to   = &common_split_sql_time($i{event_to}) ; 
		
		my $event_from_check = "$srch_ed_from[0]$srch_ed_from[1]$srch_ed_from[2]$srch_ed_from[3]$srch_ed_from[4]$srch_ed_from[5]" ;
		my $event_to_check   = "$srch_ed_to[0]$srch_ed_to[1]$srch_ed_to[2]$srch_ed_to[3]$srch_ed_to[4]$srch_ed_to[5]" ;
		if ($event_from_check > $event_to_check) { 
			$error = qq~'$i{event_from}' > '$i{event_to}'~ ; &filter_screen ; 
		}
		
		&common_date_array("$srch_ed_from[0]$srch_ed_from[1]$srch_ed_from[2]","$srch_ed_to[0]$srch_ed_to[1]$srch_ed_to[2]") ;
		
		@report_sql_or = () ;	
		
		foreach my $_srch_date (@common_date_array) {
			my $srch_ccyy_mm_dd = substr($_srch_date,0,4) . '-' . substr($_srch_date,4,2) . '-' . substr($_srch_date,6,2) ;
			push @report_sql_or, "('$srch_ccyy_mm_dd 23:59:59' >= q.date_from AND '$srch_ccyy_mm_dd 00:00:00' <= q.date_to)"
		}
		
		my $sql_or = join(' OR ',@report_sql_or) ;
		push @report_sql, "($sql_or)" if $sql_or ; 
		
		# push @report_sql, "((`event_from` >= '$i{event_from} 00:00:00' AND `event_from` <= '$i{event_to} 23:59:59') OR (`event_to` >= '$i{event_from} 00:00:00' AND `event_to` <= '$i{event_to} 23:59:59'))" ;
		push @report_results, "(WITH DAYS FALLING BETWEEN '$i{event_from}' AND '$i{event_to}')" ;
	} elsif (!$i{event_from} && $i{event_to}) {
		$error = qq~PLEASE ENTER A START DATE!~ ; 
		&filter_screen; 
	} elsif (!$i{event_to} && $i{event_from}) {
		$error = qq~PLEASE ENTER AN END DATE!~ ; 
		&filter_screen; 
	}


	if ($i{customer_name}) {	
		push @report_sql, "(q.quote_to = '$i{customer_name}' OR q.quote_to = '0' OR q.quote_to = '1' OR q.quote_to = '5' OR q.quote_to = '96')" ;
		&db_min_ro('customers','id,name',"`id`='$i{customer_name}'",'','') ;
		push @report_results, "customer = `$db{customers}{$i{customer_name}}{name}`" ;
	}                               

	if ($i{options} eq 'accepted') {
		push @report_sql, "(q.quote_accepted='1' AND q.quote_completed<>'1')" ;
		push @report_results, "Quote Accepted = `Yes`" ;		
	} elsif ($i{options} eq 'completed') {
		push @report_sql, "(q.quote_completed='1')" ;
		push @report_results, "Quote Completed = `Yes`" ;		
	} elsif ($i{options} eq 'pending') {
		push @report_sql, "(q.quote_pending='1')" ;
		push @report_results, "Quote Pnding = `Yes`" ;			
	} elsif ($i{options} eq 'closed') {
		push @report_sql, "(q.quote_cancelled='1' OR (q.quote_expiry<'$now_year-$now_mm-$now_dd' AND q.quote_accepted<>'1'))" ;
		push @report_results, "Quote Closed = `Yes`" ;		
	} elsif ($i{options} eq 'rejected') {
		push @report_sql, "(q.quote_rejected='1')" ;
		push @report_results, "Quote Closed = `Yes`" ;			
	}  elsif ($i{options} eq 'all') {
		push @report_results, "Quote Status = `All`" ;			
	}

	if ($i{region_id}) {
		&db_min_ro('regions',"id,name","`id`='$i{region_id}'",'','') ;
		push @report_sql, "(q.region_id = '$i{region_id}')" ;
		push @report_results, "region = `$db{regions}{$i{region_id}}{name}`" ;
	}
	
	if ($i{city_id}) {
		&db_min_ro('cities',"id,city","`id`='$i{city_id}'",'','') ;
		push @report_sql, "(q.city_id = '$i{city_id}')" ;
		push @report_results, "city = `$db{cities}{$i{city_id}}{city}`" ;
	}
	
	if ($i{organisation_ids}) {
		&db_min_ro('organisations',"id,name","`id`='$i{organisation_ids}'",'','') ;
		# push @report_sql, "(q.organisation_ids LIKE '%$i{organisation_ids}%')" ;
		push @report_sql, "FIND_IN_SET($i{organisation_ids},q.organisation_ids)" ; 
		push @report_results, "venue INCLUDE `$db{organisations}{$i{organisation_ids}}{name}`" ;
	}
	
	if ($i{sport_type_ids}) {
		&db_min_ro('sport_types',"id,name","`id`='$i{sport_type_ids}'",'','') ;
		# push @report_sql, "(q.sport_type_ids LIKE '%$i{sport_type_ids}%')" ;
		push @report_sql, "FIND_IN_SET($i{sport_type_ids},q.sport_type_ids)" ; 
		push @report_results, "sport_types INCLUDE `$db{sport_types}{$i{sport_type_ids}}{name}`" ;
	}
	
	if ($i{system_id}) {
		&db_min_ro('event_systems',"id,name,description","`id`='$i{system_id}'",'','') ;
		# push @report_sql, "(q.event_system_id_multiple LIKE '%;$i{system_id};%' OR q.event_system_id_multiple LIKE '$i{system_id};%' OR q.event_system_id_multiple LIKE '%;$i{system_id}')" ;
		push @report_sql, "FIND_IN_SET($i{system_id},REPLACE(q.event_system_id_multiple,';',','))" ;
		push @report_results, "event_systems = `$db{event_systems}{$i{system_id}}{name} [$db{event_systems}{$i{system_id}}{description}]`" if $db{event_systems}{$i{system_id}}{description} ; 
		push @report_results, "event_systems = `$db{event_systems}{$i{system_id}}{name}`" unless $db{event_systems}{$i{system_id}}{description} ; 
	}
	
	push @report_sql, "(q.demo_id != '0')" ;
	
	$report_results_msg = uc join(', ', @report_results) ;

	unless ($report_results_msg) { 
		$error = qq(ENTER AT LEAST ONE SEARCH PARAMETER) ; 
		&report_screen ; 
	} else { 
		$isaved = qq(SELECT WHERE $report_results_msg) ; 
	}
	 
} #------------------------------------------------------------------------------------------

sub report_screen {
		
	# &filter_screen if $ENV{QUERY_STRING} eq 'filter' ;
	&filter_screen  ;

} #-------------------------------------------------------------------------------

sub filter_screen {

	our $lcol = 2 ;
	our $fcol = 5 ;

	my ($set_year,$set_month,$set_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,-42) ; # 6 weeks back

	$set_month  = sprintf("%02s", $set_month) ;
	$set_day    = sprintf("%02s", $set_day) ;

	my $set_ccyy_dd_mm = $set_year . '-' . $set_month . '-' . $set_day ;

	$print_box_content_rows .= &common_min_forms_start('report') ;
    
	my $defualt_customer = 0 ; $defualt_customer = 139 if $usertype ne 'school_manager' ; 
	
	# &common_min_select_opts('customer_name','customers','name',$defualt_customer,'','',"events='1'") ; # AND name = 'Demo'
	&common_min_select_opts('customer_name','customers','name',$defualt_customer,'','',"events='1' AND name = 'Demo'") ; # AND name = 'Demo'
	
	# $allow_deselect{customer_name} = '' ;
	$print_box_content_rows .= &common_min_form_select('customer_name','') ;

	$preferred_title{event_from} = 'Event Date From' ;
	$print_box_content_rows .= &common_min_form_datetimepicker('event_from','',720) ;
    $preferred_title{event_to} = 'Event Date To'     ;
	$print_box_content_rows .= &common_min_form_datetimepicker('event_to','',0)   ; 
	
	$opts{options}           = qq~
		<option value="all">All (default)</option>
		<option SELECTED value="accepted">Accepted</option>
		<option value="completed">Completed</option>
		<option value="pending">Pending</option>
		<option value="closed">Cancelled</option>
		<option value="rejected">Rejected</option>
	~ ; 
	
	$print_box_content_rows .= &common_min_form_select('options','') ;
    	
	&common_min_select_opts('region_id','regions','name','','','','') ;
	&common_min_select_opts('city_id','cities','city','','','','') ;
	&common_min_select_opts('organisation_ids','organisations','name','','','','') ;
	&common_min_select_opts('sport_type_ids','sport_types','name','','','','') ;

	$trigger_jquery_raw .= qq~
		\$("#selectRegion_id").change(function() {
			var selected_city = \$("#selectCity_id").val() ;
			// console.log("selected_city : "+selected_city) ; 
			var vid = \$("#selectCity_id")  ;
			vid.empty(); // remove old options
			vid.append("<option value='0'></option>");
			vid.trigger("chosen:updated");
			var url = "$useropts{scripts}/get/get_cities_from_region.pl?region_id=" + \$(this).val() ;
			\$.get(url, function(json) {
				\$.each(json, function(key, data) {  
					if (selected_city && selected_city == data.id) {
						vid.append("<option value='"+data.id+"' selected>"+data.city_name+"</option>");
					} else {
						vid.append("<option value='"+data.id+"'>"+data.city_name+"</option>");	
					}
					vid.trigger("chosen:updated");
				});
			},
			'json');
			var selected_venue = \$("#selectOrganisation_ids").val() ;
			var vid2 = \$("#selectOrganisation_ids")  ;
			vid2.empty(); // remove old options
			vid2.append("<option value='0'></option>");
			vid2.trigger("chosen:updated");
			url = "$useropts{scripts}/get/get_venues_from_region.pl?region_id=" + \$(this).val() ;
			\$.get(url, function(json) {
				\$.each(json, function(key, data) {  
					if (selected_venue && selected_venue == data.id) {
						vid2.append("<option value='"+data.id+"' selected>"+data.venue_name+"</option>");
					} else {
						vid2.append("<option value='"+data.id+"'>"+data.venue_name+"</option>");
					}
					vid2.trigger("chosen:updated");
				});
			},
			'json');
		});
	~ ;

	$preferred_title{organisation_ids} = "Venue" ;
	$preferred_title{sport_type_ids} = "Sport Type(s)" ;
	
	&common_min_select_opts('system_id','event_systems','name','','','description','','','','','name') ;
	
	$print_box_content_rows .= &common_min_form_select('system_id','') ;
	$print_box_content_rows .= &common_min_form_select('region_id','') ;
	$print_box_content_rows .= &common_min_form_select('city_id','') ;
	$print_box_content_rows .= &common_min_form_select('organisation_ids','') ;
	$print_box_content_rows .= &common_min_form_select('sport_type_ids','') ;
	
	$print_box_content_rows .= &common_min_forms_end('','','report') ;
	
	# local $all_select_ids_string = join(",",@all_select_ids) ; 
	# $trigger_jquery_raw .= qq~\$("$all_select_ids_string").chosen({ allow_single_deselect:true });~ ; 
	
	$trigger_jquery_raw .= qq~\$("#report-form [id^='select']:not([id^='selectCustomer_name']").chosen({ allow_single_deselect:true });~ ; 
	# $trigger_jquery_raw .= qq~\$("#report-form [id^='select']").chosen({ allow_single_deselect:true });~ ; 
	
	&common_min_search_screen ;

} #-------------------------------------------------------------------------------

use event_email ; 
use event_tabs ;
use common ; 
use common_shared ; 
use today ;
use report ;
use xlsxcreator ;
use mailsend ;

1 ;