#!/usr/bin/perl

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

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;

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

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

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

# our $redirtype = 'search' ;

# our $testing = 1 ;
# our $debug   = 1 ;
# &common_debug("glod_user_level = $glod_user_level [$usertype]") ;

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

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

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 ;

our $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab

&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 = 'event_quotes';

	# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # use File::Copy;
	# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # use File::Path 'make_path';
	
	# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # my $src_dir = "$htmlpath/uploads/uploads/7408";
	# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # my $dst_dir = "$htmlpath/uploads/uploads/test_copy";
	
	
	
	# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # return unless -d $src_dir ;
	
	# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # mkdir $dst_dir unless -d $dst_dir ; 
	
	# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # opendir(my $dh, $src_dir) or die "Can't open $src_dir: $!";
	# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # my $file_counter = 0 ; 
	
	# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # my @files = readdir($dh);

	# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # foreach my $file (@files) {
		# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # next if $file =~ /^\.\.?$/ ;
		# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # my $src_file = "$src_dir/$file";
		# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # my $dst_file = "$dst_dir/$file";
		# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # if(-f $src_file) {
			 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # copy("$src_file", " $dst_file") or die "File cannot be copied." ;
		# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # }
		
	# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # }
	
	# while (my $file = readdir($dh)) {
		# next if $file =~ /^\.\.?$/;  # Skip '.' and '..'
		# last if !$file || $file_counter >= 3 ;	
		# my $src_file = "$src_dir/$file";
		# my $dst_file = "$dst_dir/$file";
		# # print "\n 21 copy : $src_file, $dst_file" ;
		# # system("cp", $src_file, $dst_file) == 0 or die "Failed to copy $src_file to $dst_file: $!";
		# # print "Successfully copied $src_file to $dst_file\n";
		# # if (copy($src_file, $dst_file)) {
			# # print "Successfully copied $src_file to $dst_file\n";
		# # } else {
			# # print "\nFailed to copy $src_file to $dst_file: $!";
		# # }
		# $file_counter++ ;
	# }

	# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # closedir($dh);
	
	# while (1) {
		# print "\n  Hello World" ;
		# last ; 
	# }
	
	# use File::Copy;
	# use File::Path 'make_path';
	
	# my $src_dir = "$htmlpath/uploads/uploads/7408";
	# my $dst_dir = "$htmlpath/uploads/uploads/test_copy";
	
	# mkdir $dst_dir unless -d $dst_dir ; 
	
	# opendir(my $dh, $src_dir) or die "Can't open $src_dir: $!";
	
	# my $file_count = 0 ; 
	
	# while (my $file = readdir($dh)) {
		# next if $file =~ /^\.\.?$/;  # Skip '.' and '..'
		# $file_count++;
		# last if $file_count == 3 ;
	# }

	
	
	# print "\nfile $file_count" ;
	# while (my $file = readdir($dh)) {
		# my $src_file = "$src_dir/$file";
		# my $dst_file = "$dst_dir/$file";
		# # copy($src_dir, $dst_dir) or warn "Failed to copy $src_file to $dst_file: $!";
		# last ;
	# }

	# closedir($dh);

	# for (7645 .. 20000) {
		# my $src_dir = "$htmlpath/uploads/uploads/$_";
		# if (-d $src_dir) {
			# rmdir $src_dir ;			
		# }
	# }

	if ($iaction eq 'add') {
		&add_screen ; 
		&common_min_screen1 ; 
	} elsif ($iaction eq 'edit') {
		&common_min_load_params ; 
		&edit_screen ; 
		&common_min_screen1 ; 
	} elsif ($iaction eq 'save') {
		# our $testing = 1 ;
		&common_min_load_params ; 
		&insert ; 
		# &log_changes ;
		&edit_or_list ; 
	} elsif ($iaction eq 'update') {  	
		# our $testing = 1 ;
		&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 ; 
		&report_ifields ; 
		&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' ; 

# if ($i{saveandexit} eq 'yes') {	
	# &list_screen ;
    # &common_min_screen3;
    # }
# else
    # {
    &edit_screen ;    
    &common_min_screen1;
    # }
        
} #------------------------------------------------------------------------------------------

sub insert {
	
	# &db_min_ro('users',"id,1 AS 'schools_manager'","`user_type`='schools_manager' AND `id`='$userid'",'','') ;
	
	# $i{quote_created} = 1 if $is_schools_manager ;
	# $i{quote_created} = 1 if $glod_user_level < 4 ;
	$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} ;
	
	our $i_quote_tab_default_full_half_items = qq~~ ;
	
	&process_cost_items_full_half_day ;
	
	&set_default_i_vals;
	
	my $quote_cancelled = $i{quote_cancelled} ; my $quote_accepted = $i{quote_accepted} ; my $quote_rejected = $i{quote_rejected} ;
	
	# $i{operator_ids} = '' ; 
	&build_event_details_fields($quote_accepted,$quote_rejected,$quote_cancelled) ;
	&process_multi_select($quote_accepted,$quote_rejected,$quote_cancelled) ;
	# &process_times_from ;
	&add_db_fields ;

	$i{last_update} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ;
	$i{datetime}    = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ;
	$i{user_id}     = $userid ;
	
	# &creat_db_cols;

	$i{id} = &db_min_get_max($table,'id') ; 
	
	&upload_aisa_files ;
	
	&process_upload_ifields;
	
	&build_working_fields($i{id},$quote_accepted,$quote_rejected,$quote_cancelled) ;
	
	$i{quote_nr} = $i{id} ;
	my $quote_nr = $i{quote_nr} ;	
	
	$ignore{selected_event_length} = 1 ;
	# $i{event_length} = $i{selected_event_length} ;
	
	$i{custom_set} = 0 unless $i{custom_set} ; 
	
	foreach (keys %i) {
		next if $ignore{$_} ;
		&common_debug(" $_ : $i{$_}") ;
	}
	
	&db_min_insert($table) ;
	
	&build_event_quotes_min_fields($quote_accepted,$quote_rejected,$quote_cancelled) ;
	$i{quote_nr} = $quote_nr ;
	
	# our $line = qq~$now_year$now_year$now_mm$now_dd$now_hour$now_min$now_sec|$now_year-$now_mm-$now_dd $now_hour:$now_min:$now_sec|event_quote_id='$i{id}'|user_id=$userid|action='Add'|~  ; 
	# foreach (keys %i) {	
		# next if $hidden{$_} == 1 || $ignore{$_} ;	
		
		# $line .= qq~$_='$i{$_}',~ ;
	# }
	
	$i{quote_tab_default_full_half_items} = $i_quote_tab_default_full_half_items ;
	
	&db_min_insert('event_quotes_min') ;
	
} #------------------------------------------------------------------------------------------

sub update {

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

	&process_cost_items_full_half_day ;
	
	our $quote_accepted = $i{quote_accepted} ;
	our $status         = &common_status_txt($i{quote_completed},$i{quote_accepted},$i{quote_pending},$i{quote_cancelled},$i{quote_rejected}) ;
	
	# &db_min_ro($table,"id,quote_accepted,grand_total,operator_ids,quote_cancelled,quote_rejected,demo_id,poc_id,recipient_id","`id`='$i{id}'",'','') ;
	&db_min_ro($table,"*","`id`='$i{id}'",'','') ;
	
	&set_default_i_vals ;
	
	my $quote_cancelled = $db{$table}{$i{id}}{quote_cancelled} ; 
	my $quote_accepted = $db{$table}{$i{id}}{quote_accepted} ; 
	my $quote_rejected = $db{$table}{$i{id}}{quote_rejected} ;
	
	&build_event_details_fields($quote_accepted,$quote_rejected,$quote_cancelled) ;

	&process_multi_select($quote_accepted,$quote_rejected,$quote_cancelled) ;
	&edit_db_fields ;

	# &creat_db_cols ;

	$i{last_update} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ;
	
	&upload_aisa_files ;
	
	&process_upload_ifields ;
	# &process_times_from ; 
	
	our $hidden_expenses_amounts_exist = 0 ; 

	&build_working_fields($i{id},$quote_accepted,$quote_rejected,$quote_cancelled) ;
	
	$i{quote_nr} = $i{id} ;
	my $quote_nr = $i{quote_nr} ;

	$ignore{selected_event_length} = 1 ;
	# $i{event_length} = $i{selected_event_length} ;

	$i{custom_set} = 0 unless $i{custom_set} ; 

	# &db_min_ro($table,"*","`id`='$i{id}'",'','') ;
	
	# our $line = qq~~ ; 
	
	# my %col_to_be_updated = () ; my %ignore_for_now = () ;
	
	# foreach (keys %i) {		
		# $col_to_be_updated{$_} = 1 ;	
	# }
	
	# foreach my $col (keys %{$db{$table}{$i{id}}}) {	
		# next if $ignore{$col} or $hidden{$col} == 1 or substr($col,0,3) eq 'new' or not $col_to_be_updated{$col} ;
		# if (($i{$col} or $db{$table}{$i{id}}{$col}) and $db{$table}{$i{id}}{$col} ne $i{$col}) {
			# # $line .= qq~$col='$i{$col}',~ ;
			# $line .= qq~$col='$db{$table}{$i{id}}{$col}',~ ;
		# } elsif ((not $i{$col} and not $db{$table}{$i{id}}{$col}) or (($i{$col} or $db{$table}{$i{id}}{$col}) and $db{$table}{$i{id}}{$col} eq $i{$col})) {
			# $ignore{$col} = 1 ; $ignore_for_now{$col} = 1 ;
		# }
	# }

	
	# &db_min_upd($table,"id='$i{id}'") ;
	
	our $line = qq~~ ;
	
	&common_shared_log_update_changes($table) ;
		
	our %sss = %i if $db{$table}{$i{id}}{sss_quote_nr} ; 
	
	&build_event_quotes_min_fields($quote_accepted,$quote_rejected,$quote_cancelled) ;	
	$i{quote_nr} = $quote_nr ;

	&common_shared_log_update_changes("event_quotes_min","event_quotes_changes","changes") ;
	
	# &db_min_ro('event_quotes_min','*',"id='$i{id}'",'','') ;
	
	# foreach (keys %i) {		
		# $col_to_be_updated{$_} = 1 ;	
	# }
	
	# foreach my $col (keys %{$db{event_quotes_min}{$i{id}}}) {	
		# next if $ignore{$col} or $hidden{$col} == 1 or substr($col,0,3) eq 'new' or not $col_to_be_updated{$col} ;
		# if (($i{$col} or $db{event_quotes_min}{$i{id}}{$col}) and $db{event_quotes_min}{$i{id}}{$col} ne $i{$col}) { 
			# # $line .= qq~$col='$i{$col}',~ ; 
			# $line .= qq~$col='$db{event_quotes_min}{$i{id}}{$col}',~ ; 
		# } elsif ((not $i{$col} and not $db{event_quotes_min}{$i{id}}{$col}) or (($i{$col} or $db{event_quotes_min}{$i{id}}{$col}) and $db{event_quotes_min}{$i{id}}{$col} eq $i{$col})) {
			# $ignore{$col} = 1 ; $ignore_for_now{$col} = 1 ;
		# }
	# }	
	
	# $line = qq~$now_year$now_year$now_mm$now_dd$now_hour$now_min$now_sec|$now_year-$now_mm-$now_dd $now_hour:$now_min:$now_sec|event_quote_id='$i{id}'|user_id=$userid|changed_from|~ . $line if $line ;
	
	# $i{quote_tab_default_full_half_items} = $i_quote_tab_default_full_half_items ;
	
	# &db_min_upd('event_quotes_min',"id='$i{id}'") ;

	# foreach (keys %ignore_for_now) {
		# $ignore{$_} = '' ;	
	# }

	&sync_to_sss ;
	
} #------------------------------------------------------------------------------------------

sub upload_aisa_files {

	
	my $attachmentdir = $htmlpath . "/uploads/uploads/$i{id}" ;
	mkdir $attachmentdir if not -d $attachmentdir and ($i{iattachupload_1} or $i{iattachupload_2} or $i{iattachupload_3}) ; 
	
	$ignore_attach{iattachslip} = 1 ;
	
	&common_upload_files("uploads/$i{id}") ;
	
	$attachmentdir = $htmlpath . "/uploads/slips/$i{id}" ;
	mkdir $attachmentdir if not -d $attachmentdir and $i{iattachslip} ; 
	
	$ignore_attach{iattachslip} = '' ;
	$ignore_attach{iattachupload_1} = 1 ;
	$ignore_attach{iattachupload_2} = 1 ;
	$ignore_attach{iattachupload_3} = 1 ;
	
	&common_upload_files("slips/$i{id}") ;	
	
} #------------------------------------------------------------------------------------------

sub process_cost_items_full_half_day {
	
	# &db_min_ro('event_cost_items','id','','','') ; 
	&db_min_ro('event_cost_items','id',"excl_from_expenses < 1",'','') ; 
	
	foreach (keys %{$db{event_cost_items}}) {
		$ignore{"full_costing_event_$_"} = 1 ;
		$ignore{"full_workings_event_$_"} = 1 ;
		$ignore{"half_costing_event_$_"} = 1 ;
		$ignore{"half_workings_event_$_"} = 1 ;
		# $ignore{"prev_item_costing_event_$_"} = 1 ;
		# $ignore{"prev_item_workings_event_$_"} = 1 ;
	}
	
	for (1 .. 100) {
		$ignore{"added_full_day_cost_item_$_"} = 1 ;
		$ignore{"added_half_day_cost_item_$_"} = 1 ;
		$i_quote_tab_default_full_half_items .= ($i{"added_full_day_cost_item_$_"}) ? qq~1:$i{"added_full_day_cost_item_$_"};~ : ($i{"added_half_day_cost_item_$_"}) ? qq~2:$i{"added_half_day_cost_item_$_"};~ :qq~;~ ;
	}
	
	$i_quote_tab_default_full_half_items =~ s/;+$//;
	
} #------------------------------------------------------------------------------------------

sub sync_to_sss {
	
	return unless $db{$table}{$i{id}}{sss_quote_nr} ;
	
	my $sss_quote_nr = $db{$table}{$i{id}}{sss_quote_nr} ;
	
	&db_switch_conn('sss');
	
	my $reload_quote_id = $i{id} ;
	
	%i = () ; %ignore = () ;

	&db_min_ro('event_quotes','1,supplier_type_ids',"id='$sss_quote_nr'",'','') ; 

	my $cnt = 0 ; 
	
	$i{supplier_type_ids} = $sss{supplier_type_ids} ; 
	
	foreach (sort split(/\;/,$db{event_quotes}{1}{supplier_type_ids})) {	
		if ($_ ne '4' && $_ ne '5' && $_ ne '6' && $_ ne '7' && $_ ne '8') {
			$i{supplier_type_ids} .= ($i{supplier_type_ids}) ? qq~;$_~ : qq~$_~ ; 
		}
	}

	# if ($sss{type} eq '10' && $db{event_quotes}{1}{supplier_type_ids} !~ /\b8\b/) {
		# foreach (split(/\;/,$db{event_quotes}{1}{supplier_type_ids})) {
			# $i{supplier_type_ids} .= qq~$_;~ if $_ ne '4' && $_ ne '5' && $_ ne '6' && $_ ne '7' && $_ ne '8' ;
		# }
		# $i{supplier_type_ids} .= qq~8~ ;
	# } elsif ($sss{type} eq '13' && $db{event_quotes}{1}{supplier_type_ids} !~ /\b7\b/) {
		# foreach (split(/\;/,$db{event_quotes}{1}{supplier_type_ids})) {
			# $i{supplier_type_ids} .= qq~$_;~ if $_ ne '4' && $_ ne '5' && $_ ne '6' && $_ ne '7' && $_ ne '8' ;
		# }
		# $i{supplier_type_ids} .= qq~7~ ;		
	# } elsif ($sss{type} eq '3' && $db{event_quotes}{1}{supplier_type_ids} !~ /\b6\b/) {
		# foreach (split(/\;/,$db{event_quotes}{1}{supplier_type_ids})) {
			# $i{supplier_type_ids} .= qq~$_;~ if $_ ne '4' && $_ ne '5' && $_ ne '6' && $_ ne '7' && $_ ne '8' ;
		# }
		# $i{supplier_type_ids} .= qq~6~ ;		
	# } elsif ($sss{type} eq '2' && $db{event_quotes}{1}{supplier_type_ids} !~ /\b5\b/) {
		# foreach (split(/\;/,$db{event_quotes}{1}{supplier_type_ids})) {
			# $i{supplier_type_ids} .= qq~$_;~ if $_ ne '4' && $_ ne '5' && $_ ne '6' && $_ ne '7' && $_ ne '8' ;
		# }
		# $i{supplier_type_ids} .= qq~5~ ;		
	# }

	$i{datetime}  		     = $sss{datetime} ; 
	$i{last_update}  		 = $sss{last_update} ; 
	$i{quote_date}  		 = $sss{quote_date} if $sss{quote_date} ; 
	$i{date_from}  		     = $sss{date_from} if $sss{date_from} ; 
	$i{date_to}  		     = $sss{date_to} if $sss{date_to} ; 
	$i{qty}  		         = $sss{qty} || 1 ; 
	$i{times_from}           = $sss{times_from} if $sss{times_from} ;
	$i{times_to}             = $sss{times_to} if $sss{times_to} ;
	$i{days_active}          = $sss{days_active} if $sss{days_active} ;
	$i{event_length}         = $sss{event_length} if $sss{event_length} ; 
	
	$i{quote_pending}        = $sss{quote_pending} ;
	$i{quote_accepted}       = $sss{quote_accepted} ;
	$i{quote_cancelled}      = $sss{quote_cancelled} ;
	$i{quote_completed}      = $sss{quote_completed} ;
	$i{quote_rejected}       = $sss{quote_rejected} ;
	$i{ref}                  = $sss{ref} ;
	$i{quote_to}             = $sss{quote_to} ;
	$i{notes}                = $sss{notes} ;
	$i{office_notes}         = $sss{office_notes} ;
	$i{poc_id}				 = $sss{poc_id} ;
	# $i{poc_name}             = $sss{poc_name} ;
	# $i{poc_contact_nr}       = $sss{poc_contact_nr} ;
	# $i{festival_league_name} = $sss{festival_league_name} ;
	$i{category_id_1}        = $sss{category_id_1} ;
	$i{category_id_2}        = $sss{category_id_2} ;
	my $category_details     = ($sss{category_1_details} || $sss{category_2_details}) ? qq~$sss{category_1_details}|;|$sss{category_2_details}~ : qq~~ ;	
	$i{category_details}     = $category_details ; 
	$i{recipient_id}       	 = $sss{recipient_id} ;
	# $i{recipient_name}       = $sss{recipient_name} ;
	# $i{recipient_nr}         = $sss{recipient_nr} ; $ignore{recipient_nr} = 0 ; 
	$i{additional_notes}     = $sss{additional_notes} ;
	$i{linear_id}            = $sss{linear_id} ;
	$i{nr_of_units}          = $sss{nr_of_systems} ;
	$i{organisation_ids}     = $sss{organisation_ids} ;
	$i{city_ids}             = $sss{city_id} ; $i{city_ids} =~ s/\,/\;/g ;  $ignore{city_ids} = 0 ;
	$i{region_id}            = $sss{region_id} ;
	$i{sport_type_ids}       = $sss{sport_type_ids} ; $i{sport_type_ids} =~ s/\,/\;/g ;
	
	$i{upload_1}       		 = $sss{upload_1} ; 
	$i{upload_2}       		 = $sss{upload_2} ; 
	$i{upload_3}       		 = $sss{upload_3} ;

	$ignore{upload_1}		 = (!$i{upload_1}) ? 1 : 0 ;   		
	$ignore{upload_2}		 = (!$i{upload_2}) ? 1 : 0 ;   		
	$ignore{upload_3}		 = (!$i{upload_3}) ? 1 : 0 ;    			
	
	$i{event_system_id_multiple}	= $sss{event_system_id_multiple} ; 	
	$i{club_ids}       			 	= $sss{club_ids} ; 	
	
	&db_min_upd($table,"id='$sss_quote_nr'") ; 

	#______________ Copying Files to SSS
	
	$i{iattachupload_1} 	 = $sss{iattachupload_1} ;
	$i{iattachupload_2} 	 = $sss{iattachupload_2} ;
	$i{iattachupload_3} 	 = $sss{iattachupload_3} ;
	
	my $to_dir = $htmlpath_sss . "/uploads/uploads/$sss_quote_nr" ;
	
	our $upload_files_to_sss = 1 ;

	my $from_dir = "$htmlpath/uploads/uploads/$reload_quote_id" ;

	$i{iattachupload_1} = &common_process_uploaded_file_names($i{iattachupload_1},"upload_1") if $i{iattachupload_1} ; 
	$i{iattachupload_2} = &common_process_uploaded_file_names($i{iattachupload_2},"upload_2") if $i{iattachupload_2} ; 
	$i{iattachupload_3} = &common_process_uploaded_file_names($i{iattachupload_3},"upload_3") if $i{iattachupload_3} ; 
	
	&common_min_copy_files($from_dir,$to_dir,"$i{iattachupload_1}") if $i{iattachupload_1} ;
	&common_min_copy_files($from_dir,$to_dir,"$i{iattachupload_2}") if $i{iattachupload_2} ;
	&common_min_copy_files($from_dir,$to_dir,"$i{iattachupload_3}") if $i{iattachupload_3} ;
	
	$upload_files_to_sss = 0 ;
	
	#______________ Copying Files to SSS
	
	&db_switch_conn('aisa');
	
	# foreach (keys %sss) {		
		# $i{$_} = $sss{$_} unless $ignore{$_} ;	
	# }

	$i{id} = $reload_quote_id  ;
	
} #------------------------------------------------------------------------------------------

sub log_changes {
	
	return unless $line ;
	
	chop $line ;
	
	&common_log_changes("events/changes.dat",$line) ; 
	
	if ($db{$table}{$i{id}}{quote_accepted}) { # Can you change it that she only gets emails where an Accepted Event been edited by school manager and when they upload docs afterwards, She just need notification if there been changes to event she or anyone else already accepted it	
		# if (!$quote_accepted || $is_schools_manager || $glod_user_level < 4) {
		if (!$quote_accepted || $is_schools_manager || $glod_user_level < 3) {
			&send_email_to_manager($i{id},$status,$line) ;
		}
	}	
	
} #------------------------------------------------------------------------------------------

sub process_times_from {
	
	# for (1 .. 6) {
		# $ignore{"time_from_$_"} = 1 ; 
		# $ignore{"time_to_$_"} = 1 ;
		# $i{times_from} .= qq~$i{"time_from_$_"};~ if $_ > 1 ;
		# $i{times_to} .= qq~$i{"time_to_$_"};~ if $_ < 6 ;
	# }
	# chop $i{times_from} if $i{times_from} ;
	# chop $i{times_to} if $i{times_to} ;
	
} #------------------------------------------------------------------------------------------

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_event_details_fields {
	
	my ($quote_accepted,$quote_rejected,$quote_cancelled) = @_ ; 
	
	# $i{operator_ids} .= qq~;\~;~ ; 
	
	our $cnt_last_system_row = 0 ; 
	
	for (1 .. $nr_of_system_names_and_clubs) {
		
		$cnt_last_system_row = $_ if $i{"system_name_$_"} || $i{"club_name_$_"} ; 
		
		my $system_name        		= "system_name_$_" ;
		my $club_name          		= "club_name_$_" ;
		my $op_name            		= "operator_id_calibration_$_" ;							   
		# my $sss_fixed_systems  		= "sss_fixed_systems_$_" ;							   
		$ignore{$system_name}  		= 1 ; 
		$ignore{$club_name}    		= 1 ; 
		$ignore{$op_name}      		= 1 ; 
		# $ignore{$sss_fixed_systems}	= 1 ; 
		
	}
	
	return if ($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3 ;
	
	unless ($cnt_last_system_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} = '' ; 
	
	# our $cnt_rows = 0 ; 
	
	my $sss_fixed_systems_exists = 0 ; 
	
	my @saved_system_ids = split(/\;/,$db{$table}{$i{id}}{event_system_id_multiple}) ; 
	
	my %sss_fixed_system = () ; 
	foreach (@saved_system_ids) {
		my $system_id_ = $_ ; 
		$system_id_ =~ s/f-//g ;
		$sss_fixed_system{$system_id_} = 1 if $_ =~ /f-/ ;
	}

	for my $event_row (1 .. $nr_of_system_names_and_clubs) {
		
		my $op_name			= "operator_id_calibration_$event_row" ;					
		$i{operator_ids} 	.= ($event_row <= $cnt_last_system_row || ($event_row > $cnt_last_system_row && $i{$op_name})) ? qq~$i{$op_name},~ : qq~~ ;

		next if $event_row > $cnt_last_system_row ;
		
		# my $sss_fixed_systems	= "sss_fixed_systems_$event_row" ;						
		# $sss_fixed_systems_exists = 1 if $i{$sss_fixed_systems} ;
		# next if $i{$sss_fixed_systems} ;
	 
		my $system_name        	= "system_name_$event_row" ;
		my $club_name          	= "club_name_$event_row" ;
 
		# next if !$i{$system_name} && !$i{$club_name} ;
		
		# $cnt_rows++ ;
		
		$i{club_ids} .= qq~$i{$club_name};~ ;
		
		# $i{event_system_id_multiple} .= ($i{$sss_fixed_systems}) ? qq~f-$i{$system_name};~ : qq~$i{$system_name};~ ;
		
		# my $saved_system_id = $saved_system_ids[$event_row-1] ;
		# $saved_system_id =~ s/f-//g ;
		
		$i{event_system_id_multiple} .= ($i{$system_name} && $sss_fixed_system{$i{$system_name}}) ? qq~f-$i{$system_name};~ : (!$i{$system_name} && $saved_system_ids[$event_row - 1] =~ /f-/) ? qq~$saved_system_ids[$event_row - 1];~ : qq~$i{$system_name};~ ;
		
		# &process_system_club_operator($event_row) ;
	
	}

	# if ($sss_fixed_systems_exists) {
		# for my $event_row (1 .. $nr_of_system_names_and_clubs) {
			
			# my $sss_fixed_systems	= "sss_fixed_systems_$event_row" ;		
			# next if !$i{$sss_fixed_systems} ;
			# process_system_club_operator($event_row) ;
		
		# }			
	# }

	$ignore{club_name} = 1 ; 
	
	$i{club_ids} =~ s/;+$//;
	$i{event_system_id_multiple} =~ s/;+$//;
		
	if ($i{event_system_id_multiple} =~ /f-/) {
		
		my @upd_systems = split(/\;/,$i{event_system_id_multiple}) ; 
		if ($upd_systems[-1] !~ /f-/) {
			$i{event_system_id_multiple} =~ s/f-//g ;
		} else {
			my $cnt__ = 0 ; 
			foreach (@upd_systems) {
				if ($upd_systems[$cnt__] =~ /f-/ && $upd_systems[$cnt__ + 1] && $upd_systems[$cnt__ + 1] !~ /f-/) {
					$i{event_system_id_multiple} =~ s/f-//g ;
					last ;
				}
				$cnt__++ ;
			}
		}
	}
	
	# 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} ;

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

# sub process_system_club_operator {
	
	# my ($event_row) = @_ ;

	# my $system_name        	= "system_name_$event_row" ;
	# my $club_name          	= "club_name_$event_row" ;
	# my $op_name				= "operator_id_calibration_$event_row" ;					   
	
	# return if !$i{$system_name} && !$i{$club_name} ;
	
	# $cnt_rows++ ;
	
	# $i{club_ids}                 .= qq~$i{$club_name};~ ;
	# $i{event_system_id_multiple} .= ($i{$sss_fixed_systems}) ? qq~f-$i{$system_name};~ : qq~$i{$system_name};~ ;
	# $i{operator_ids}             .= qq~$i{$op_name},~ if $cnt_rows <= $cnt_last_row ;
	
# } #------------------------------------------------------------------------------------------

sub process_daily_details_from_the_events_datails_tab {
		
	my ($id) = @_ ; 
	
	use Time::Piece ;
	
	# my $final_day = 0 ; 
	# for (1 .. 20) {
		# $final_day = $_ if $i{"day_$_"} ;
	# }
	
	my $final_day = &common_min_calc_day_diff($i{date_to},$i{date_from}) ;
	
	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~;~ ;

	}	
	
	# my $sss_fixed_systems_exists = 0 ; 
	
	for my $event_row (1 .. $nr_of_system_names_and_clubs) {
		
		# my $sss_fixed_systems	= "sss_fixed_systems_$event_row" ;		
		# $sss_fixed_systems_exists = 1 if $i{$sss_fixed_systems} ;				
		# next if $i{$sss_fixed_systems} ;			
		# &process_daily_operator_ids($event_row) ; 

		$ignore{"clicked_button_$event_row"} = 1 ;
		
		my $system_name        	= "system_name_$event_row" ;
		my $club_name          	= "club_name_$event_row" ;
		
		# if (!$i{$system_name} && !$i{$club_name}) {
		
		if ($cnt_last_system_row < $event_row) {
			for my $event_day (1 .. 20) {
				$ignore{"custom_operator_$event_row\_$event_day"} = 1 ;
			}
			next ;
		}
		
		for my $event_day (1 .. 20) {
			$ignore{"custom_operator_$event_row\_$event_day"} = 1 ; 
			if ($i{"clicked_button_$event_row"}) {
				$i{"custom_operator_$event_row\_$event_day"} = "" unless $i{"day_$event_day"} ;
				$i{daily_operator_ids} .= qq~$i{"custom_operator_$event_row\_$event_day"};~ ; 				
			}
		}
		
		# chop $i{daily_operator_ids} if $i{daily_operator_ids} && $i{"clicked_button_$event_row"} ;
		$i{daily_operator_ids} =~ s/;+$//; 
		$i{daily_operator_ids} .= qq~|~ ;
	 
	}
	
	# if ($sss_fixed_systems_exists) {
		# for my $event_row (1 .. $nr_of_system_names_and_clubs) {
			# my $sss_fixed_systems	= "sss_fixed_systems_$event_row" ;						
			# next if !$i{$sss_fixed_systems} ;
			# &process_daily_operator_ids($event_row) ; 
		# }		
	# }

	$i{daily_operator_ids} =~ s/\|+$//; 

	# chop $i{daily_operator_ids} if $i{daily_operator_ids} ;
	# 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/;	
	
	# $ignore{daily_operator_ids} = 1 if $i{daily_operator_ids} eq $db{$table}{$id}{daily_operator_ids} ;
	# $ignore{times_from} = 1 if $i{times_from} eq $db{$table}{$id}{times_from} ;
	# $ignore{times_to} = 1 if $i{times_to} eq $db{$table}{$id}{times_to} ;
	# $ignore{days_active} = 1 if $i{days_active} eq $db{$table}{$id}{days_active} ;
	# $ignore{event_length} = 1 if $i{event_length} eq $db{$table}{$id}{event_length} ;
	
} #------------------------------------------------------------------------------------------

# sub process_daily_operator_ids {
	
	# my ($event_row) = @_ ; 

	# $ignore{"clicked_button_$event_row"} = 1 ;
	
	# my $system_name        	= "system_name_$event_row" ;
	# my $club_name          	= "club_name_$event_row" ;
	
	# if (!$i{$system_name} && !$i{$club_name}) {
		# for my $event_day (1 .. 20) {
			# $ignore{"custom_operator_$event_row\_$event_day"} = 1 ;
		# }
		# return ;
	# }
	
	# for my $event_day (1 .. 20) {
		# $ignore{"custom_operator_$event_row\_$event_day"} = 1 ; 
		# if ($i{"clicked_button_$event_row"}) {
			# $i{"custom_operator_$event_row\_$event_day"} = "" unless $i{"day_$event_day"} ;
			# $i{daily_operator_ids} .= qq~$i{"custom_operator_$event_row\_$event_day"};~ ; 				
		# } 
	# }
	
	# chop $i{daily_operator_ids} if $i{daily_operator_ids} && $i{"clicked_button_$event_row"} ;
	# $i{daily_operator_ids} .= qq~|~ ;
	
# } #------------------------------------------------------------------------------------------

sub build_working_fields {
	
	my ($id,$quote_accepted,$quote_rejected,$quote_cancelled) = @_ ; 
	
	if (($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) {
		
		### ADD IGNORE WITH EVENT SYSTEM NAME TABLE
		for my $col (1 .. 20) {
			$ignore{"time_from_$col"} = 1 ; 
			$ignore{"time_to_$col"} = 1 ; 
			$ignore{"day_$col"} = 1 ; 
			for (1 .. 15) {
				$ignore{"custom_operator_$_\_$col"} = 1 ; 
			}
		}
		$ignore{total_amount_workings_event} = 1 ;
		$ignore{total_vat_amount_workings_event}  = 1 ; 
		$ignore{total_grand_amount_workings_event}  = 1 ; 
		
		return ; 
	}
	
	# if ($glod_user_level < 3) {
		# $ignore{daily_operator_ids} = 1 ; 
		# $ignore{event_length} = 1 ; 
		# $ignore{times_from} = 1 ; 
		# $ignore{times_to} = 1 ; 
		# $ignore{event_length} = 1 ; 
	# }
	
	&process_daily_details_from_the_events_datails_tab($id) ; 
	
	my $diplayed_exp_tab = 0 ; my $hidden_exp_tab = 0 ;
	if ($glod_user_level > 3) {
	# if ($glod_user_level > 2) {
		$diplayed_exp_tab = 1 ; 
	} elsif ($glod_user_level < 4) {
	# } elsif ($glod_user_level < 3) {
		$hidden_exp_tab = 1 ; 
		# $ignore{sub_total} = 1 ; 
		# $ignore{vat_total} = 1 ;			 
		# $ignore{grand_total} = 1 ;  
	}
	
	# return if !$diplayed_exp_tab && !$hidden_exp_tab ;
	
	$i{sub_total} 							= $i{sub_total_costing_event} ;
	$i{vat_total} 							= $i{vat_total_costing_event} ;
	$i{grand_total} 						= $i{grand_total_costing_event} ;
	# $i{profit_loss}	=~ s/\,//g ;
	# $i{sub_total}	=~ s/\,//g ;
	# $i{vat_total}	=~ s/\,//g ;
	# $i{grand_total}	=~ s/\,//g ;
	
	$ignore{sub_total_workings_event} 	= 1 ;
	$ignore{vat_total_workings_event} 	= 1 ;
	$ignore{grand_total_workings_event} = 1 ;
	$ignore{sub_total_costing_event} 	= 1 ;
    $ignore{vat_total_costing_event} 	= 1 ;
	$ignore{grand_total_costing_event} 	= 1 ;
	$ignore{sub_total}     = 1 if $i{sub_total}	 	eq $db{$table}{$id}{sub_total} ;
	$ignore{vat_total}     = 1 if $i{vat_total} 	eq $db{$table}{$id}{vat_total} ;
	$ignore{grand_total}   = 1 if $i{grand_total} 	eq $db{$table}{$id}{grand_total} ;

	for (1 .. 50) {
		
		$y{1}{$_}  = "excl_costing_event_$_" ;
		$y{2}{$_}  = "description_costing_event_$_" ;
		$y{3}{$_}  = "qty_costing_event_$_" ;
		$y{4}{$_}  = "amount_usd_costing_event_$_" ;		
		$y{5}{$_}  = "amount_ttl_costing_event_$_" ;	
		$y{6}{$_}  = "vat_costing_event_$_" ;		
		$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_$_" ;
		# $y{17}{$_} = "curr_amnt_costing_event_$_" ;
		
		$hidden_expenses_amounts_exist = ($hidden_expenses_amounts_exist || ($glod_user_level < 4 && ($y{8}{$_} || $y{9}{$_} || $y{13}{$_} || $i{$y{14}{$_}} || $i{$y{15}{$_}}))) ? 1 : 0 ; 
		
		foreach my $a (keys %y) {
			foreach my $b (keys %{$y{$a}}) {
				$ignore{$y{$a}{$b}} = 1 ; 
				$x{$a}{$b} = $i{$y{$a}{$b}} ; 
			} 
		}
	}
	
	# return if $i{custom_set} ;
	
	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{total_amount_workings_event} 		= 0 ;
	$i{total_vat_amount_workings_event} 	= 0 ;
	$i{total_grand_amount_workings_event} 	= 0 ;	
	
	my %operator_day_count = () ; my %operator_row = () ; 
	my $operator_count = 0 ; 
	my %ii = () ;
	
	# $i{operator_ids} = $db{$table}{$id}{operator_ids} if $glod_user_level < 3 ;
	
	my @operator_ids = split(/\,/,$i{operator_ids}) ;

	&db_min_ro('event_systems','id,system_type','','','') ; 
	
	for my $system_name_row_nr (1 .. $nr_of_system_names_and_clubs) {
 
		my $field4 = "system_name_$system_name_row_nr" ;
		
		# next if !$i{$field4} || $i{$field4} < 0 ; 
		
		$i{$field4} = -1 if !$i{$field4} && $i{"clicked_button_$system_name_row_nr"} ;
		
		next unless $i{$field4} ; 
		
		for my $days (1 .. 20)  {
			
			my $day_field = "day_$days" ;
			next unless $i{$day_field} ;
			
			my $field1 = "custom_operator_$system_name_row_nr\_$days" ; 
			my $field2 = "operator_id_calibration_$system_name_row_nr" ; 
			my $field3 = "event_length_$days" ;
			 
			if ($i{$field1}) { 
				if ($i{$field4} eq '-1') {
					$operator_day_count{blank_system}{$i{$field1}}++ ; 
				} elsif ($i{$field3} eq '1' && $db{event_systems}{$i{$field4}}{system_type} ne 'fixed') { #full day
					$operator_day_count{afull_day_mobile}{$i{$field1}}++ ; 
				} elsif (($i{$field3} eq '1' && $db{event_systems}{$i{$field4}}{system_type} eq 'fixed') or ($i{$field3} eq '2' && $db{event_systems}{$i{$field4}}{system_type} ne 'fixed')) { #full day
					$operator_day_count{bfull_day_fixed_half_day_mobile}{$i{$field1}}++ ; 
				} elsif ($i{$field3} eq '2' && $db{event_systems}{$i{$field4}}{system_type} eq 'fixed') {
					$operator_day_count{chalf_day_fixed}{$i{$field1}}++ ;
				}
			} 
		}
	}

	if ($i{operator_ids}) {
		my $cnt =  0 ; 
		foreach my $op_id (@operator_ids) {
			$cnt++ ;
			next unless $op_id ;
			my $field5 = "system_name_$cnt" ;
			
			$i{$field5} = -1 if !$i{$field5} && $i{"operator_id_calibration_$cnt"} ;
			
			# if ($i{$field5} && $i{$field5} > 0) {
				
			for my $days (1 .. 20)  {
				my $day_field = "day_$days" ;
				next unless $i{$day_field} ;
				my $field6 = "event_length_$days" ;
				if ($i{$field5} eq '-1') {
					$operator_day_count{blank_system}{$op_id}++ ; 
				} elsif ($i{$field6} eq '1' && $db{event_systems}{$i{$field5}}{system_type} && $db{event_systems}{$i{$field5}}{system_type} ne 'fixed') { #full day
					$operator_day_count{afull_day_mobile}{$op_id}++ ; 
				} elsif (($i{$field6} eq '1' && $db{event_systems}{$i{$field5}}{system_type} eq 'fixed') or ($i{$field6} eq '2' && $db{event_systems}{$i{$field5}}{system_type} && $db{event_systems}{$i{$field5}}{system_type} ne 'fixed')) { #full day
					$operator_day_count{bfull_day_fixed_half_day_mobile}{$op_id}++ ; 
				} elsif ($i{$field6} eq '2' && $db{event_systems}{$i{$field5}}{system_type} eq 'fixed') {
					$operator_day_count{chalf_day_fixed}{$op_id}++ ;
				}
			}		

			next if $i{$field5} eq '-1' || $db{event_systems}{$i{$field5}}{system_type} ;	
				
			# } else { 
			for my $days (1 .. 20)  { 
				my $day_field = "day_$days" ;
				next unless $i{$day_field} ;
				my $field6 = "event_length_$days" ;
				if ($i{$field6} eq '1' && $i{type} ne '3') { #full day
					$operator_day_count{afull_day_mobile}{$op_id}++ ; 
				} elsif (($i{$field6} eq '1' && $i{type} eq '3') or ($i{$field6} eq '2' && $i{type} ne '3')) { #full day
					$operator_day_count{bfull_day_fixed_half_day_mobile}{$op_id}++ ; 
				} elsif ($i{$field6} eq '2' && $i{type} eq '3') {
					$operator_day_count{chalf_day_fixed}{$op_id}++ ;
				}
			}
			# }
		}
	}
	
	my %iii = %i ; 
	our %i2 = () ; 
	
	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' || $db{event_quotes}{$id}{demo_id}) ? "afull_day_mobile" : ($i{"amount_usd_workings_event_$_"} eq '750.00') ? "bfull_day_fixed_half_day_mobile" : ($i{"amount_usd_workings_event_$_"} eq '500.00') ? "chalf_day_fixed" : "" ;
			if ($day_len) {
				$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 'blank_system') ? '0.00' : ($len eq "afull_day_mobile") ? '1000.00' : ($len eq "bfull_day_fixed_half_day_mobile") ? '750.00' : '500.00' ;
			$i2{amount_usd_workings_event}		.= qq~;~ ;  
			my $amnt 							= ($len eq 'blank_system') ? 0 : ($len eq "afull_day_mobile") ? 1000 * $operator_day_count{$len}{$op_id} * $i{roe} : ($len eq "bfull_day_fixed_half_day_mobile") ? 750 * $operator_day_count{$len}{$op_id} * $i{roe} : 500 * $operator_day_count{$len}{$op_id} * $i{roe} ;
			$amnt	 							= sprintf ("%0.2f",$amnt) ; 

			$i2{amount_workings_event}			.= "$amnt;" ; 
			$i{total_amount_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{total_vat_amount_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{total_vat_amount_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{total_amount_workings_event} += $iii{"amount_ttl_workings_event_$_"} if !$iii{"excl_workings_event_$_"} ;
			$i{total_vat_amount_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~~ ;
	}
	
	$i{total_grand_amount_workings_event} = $i{total_vat_amount_workings_event} + $i{total_amount_workings_event} ;
	
	$i{profit_loss} = $db{$table}{$id}{grand_total} - $i{total_grand_amount_workings_event} ; 
	
	$i{total_amount_workings_event} = sprintf("%0.2f",$i{total_amount_workings_event}) ;
	$i{total_vat_amount_workings_event} = sprintf("%0.2f",$i{total_vat_amount_workings_event}) ;
	$i{total_grand_amount_workings_event} = sprintf("%0.2f",$i{total_grand_amount_workings_event}) ;
	$i{profit_loss} = sprintf("%0.2f",$i{profit_loss}) ;
	
	foreach (keys %i2) {
		# chop $i2{$_} if $i2{$_}  ;
		# $i{$_} = $i2{$_} ;
	}

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

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

	my $category_details = qq~$i{category_1_details}|;|$i{category_2_details}~ if $i{category_1_details} || $i{category_2_details} ;	
	$i{category_details} = $category_details ; 

	$ignore{last_update} = 1 ; 
	$ignore{poc_contact_nr} = 1 ; 
	$ignore{poc_name} = 1 ; 
	$ignore{poc_id} = 1 ; 
	$ignore{format_of_title} = 1 ; 
	$ignore{additional_notes} = 1 ;  
	$ignore{upload_1} = 1 ; 
	$ignore{upload_2} = 1 ; 
	$ignore{upload_3} = 1 ; 
	$ignore{email}  = 1 ; 
	$ignore{address} = 1 ; 
	$ignore{country_id} = 1 ; 
	$ignore{quote_date} = 1 ; 
	$ignore{contact_name} = 1 ; 
	$ignore{notes} = 1 ; 
	$ignore{tel} = 1 ; 
	$ignore{category_id_1} = 1 ; 
	$ignore{category_id_2} = 1 ; 
	$ignore{custom_set} = 1 ;
	$ignore{quote_accepted} = 1 ; 
	$ignore{quote_cancelled} = 1 ; 
	$ignore{quote_rejected} = 1 ; 
	$ignore{quote_completed} = 1 ; 
	 
	return if ($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3 ;
	
	$iid = $i{id} ; 
	my $custom_set = $i{custom_set} ;
	%i = %i2 ;
	$i{custom_set} = $custom_set ;
	if ($glod_user_level > 3) {
		
		for (1 .. 50) {
			next unless $x{2}{$_} ;
			$i{excl_costing_event} 		   .= "$x{1}{$_};" ;
			$i{item_costing_event} 		   .= "$x{2}{$_};";
			$i{qty_costing_event} 		   .= "$x{3}{$_};";
			$i{usd_amnt_costing_event} 	   .= "$x{4}{$_};";
			$i{item_ttl_costing_event} 	   .= "$x{5}{$_};";
			$i{vat_costing_event} 		   .= "$x{6}{$_};";

			# $i{curr_amnt_costing_event}    .= "$x{17}{$_};"; 
		}
		if ($i{custom_set}) {
			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_costing_event} 		= "" unless $i{excl_costing_event} 		;
		$i{item_costing_event} 		= "" unless $i{item_costing_event} 		;
		$i{qty_costing_event} 		= "" unless $i{qty_costing_event} 		;
		$i{usd_amnt_costing_event} 	= "" unless $i{usd_amnt_costing_event}	;
		$i{item_ttl_costing_event} 	= "" unless $i{item_ttl_costing_event}	;
		$i{vat_costing_event} 		= "" unless $i{vat_costing_event} 		;
		
		$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} 		 ;

	} elsif ($glod_user_level < 4 && $hidden_expenses_amounts_exist) {

		for (1 .. 50) { 
			# $i{description_workings_event} .= "$x{8}{$_};";
			# $i{operator_workings_event}    .= "$x{9}{$_};";
			# $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}{$_};"; 
		} 
	}
 
	foreach (keys %i) { chop $i{$_} ; }
	
	$i{category_details} = $category_details ; 
	$i{id}               = $iid ; 
	
} #------------------------------------------------------------------------------------------

sub process_multi_select {
	
	my ($quote_accepted,$quote_rejected,$quote_cancelled) = @_ ; 
	
	# $ignore{event_system_id} = 1 ; 
	
	# if ($usertype ne 'schools_manager') {
	# if ($glod_user_level > 3) {
		
	# return if ($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3 ;
	
	if (($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) {
		$ignore{operatorids} = 1 ; 
		$ignore{typedetailsid} = 1 ; 
		$ignore{organisationids} = 1 ; 
		$ignore{sporttypeids} = 1 ; 
		$ignore{operator_ids} = 1 ;
	}
	
	local @operatorids       = split(/\,/,$i{operatorids}) ;
	$i{nr_of_casuals}        = scalar @operatorids || '0' ; $i{nr_of_casuals_2} = '0' ;
	my $operatorids          = join(",",@operatorids) ;
	$operatorids             =~ s/\s//g; # remove white space
	$ignore{operatorids}     = 1 ;
	
	$i{operator_ids}         .= $operatorids ;
	$i{operator_ids}         = 0 unless $i{operator_ids} ;
	chop $i{operator_ids} if substr($i{operator_ids},-1,1) eq ',' ;

	if ($glod_user_level > 2) {
		
		local @typedetailsid      = split(/\,/,$i{typedetailsid}) ;
		my $typedetailsid         = join(",",@typedetailsid) ;
		$typedetailsid            =~ s/\s//g; # remove white space
		$ignore{typedetailsid}    = 1 ;
		$i{type_details_id}       = $typedetailsid ;
		$i{type_details_id}       = 0 unless $i{type_details_id} ;
		
		# @event_system_ids = split(/\,/,$i{event_system_ids}) ;
		# my @db_event_system_ids = () ; foreach (@event_system_ids) { push @db_event_system_ids, $_ ; }
		# my $db_event_system_ids = join(';',@db_event_system_ids) ;
		# $ignore{event_system_ids} = 1 ;
		# $i{event_system_id_multiple} = $db_event_system_ids ;
	} 

	$ignore{city_ids} = 1 ;
	$i{city_id} = $i{city_ids} ;
	
	local @organisationids   = split(/\,/,$i{organisationids}) ;
	my $organisationids      = join(",",@organisationids) ;
	$organisationids         =~ s/\s//g; # remove white space
	$ignore{organisationids} = 1 ;
	$i{organisation_ids}     = $organisationids ;
	$i{organisation_ids}     = 0 unless $i{organisation_ids} ;

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

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

sub duplicate {

	unless ($i{id}) { 
		$error = qq~NO ID~ ; 
		return ; 
	}
	
	my $orig_id = $i{id} ;
	
	&db_min_copy($table,$i{id}) ;
	
	my $copy_id = $i{id} ;
	
	&common_min_copy_files("$htmlpath/uploads/uploads/$orig_id","$htmlpath/uploads/uploads/$copy_id",'') ;
	
	&db_min_ro($table,'1,sss_quote_nr',"id='$copy_id'","","") ; 
	
	my %ii = %i ; 
	
	# if ($db{$table}{1}{sss_quote_nr} || $db{$table}{1}{event_system_calibration_ids} || $db{$table}{1}{set_up_groups_status_ids}) {
		%i = () ; 
		my %ignore_for_now = %ignore ;
		%ignore = () ;
		$i{sss_quote_nr} = '0' ; 
		&common_shared_event_quotes_column_not_to_copy ;
		$ignore{sss_quote_nr}  					= (!$db{$table}{1}{sss_quote_nr})					? 1 : 0 ;
		# $ignore{event_system_calibration_ids}   = (!$db{$table}{1}{event_system_calibration_ids}) 	? 1 : 0 ;
		# $ignore{set_up_groups_status_ids}       = (!$db{$table}{1}{set_up_groups_status_ids}) 		? 1 : 0 ;
		&db_min_upd($table,"id='$copy_id'") ;
		%ignore = %ignore_for_now ;
	# }
	
	%i = %ii ; 
	
	&db_min_copy('event_quotes_min',$orig_id) ;
	
	%ii = %i ; 
	%i = () ; 
	$i{quote_nr} = $copy_id ;
	$i{operator_dates_paid} = '' ; 
	$i{operator_dates_paid_min} = '' ; 
	$i{operator_amounts_paid} = '' ; 
	&db_min_upd('event_quotes_min',"id='$copy_id'") ; 
	%i = %ii ; 
	
} #------------------------------------------------------------------------------------------

# sub copy {

	# unless ($i{id}) { 
		# $error = qq~NO ID~ ; 
		# return ; 
	# }
	
	# my $id = $i{id} ;
	
	# &db_min_copy($table,$i{id}) ;
	
	# my $id2 = $i{id} ;
	
	# $i{id} = $id ;
	
	# &db_min_copy('event_quotes_min',$i{id}) ;
	
	# $i{id} = $id ;
	
	# # use File::Copy;
	# # # use File::Path 'make_path';
	
	
	
	# # my $src_dir = "$htmlpath/uploads/uploads/$id";
	# # my $dst_dir = "$htmlpath/uploads/uploads/$id2";
	
	# # return unless -d $src_dir ;
	
	# # mkdir $dst_dir unless -d $dst_dir ; 
	
	# # opendir(my $dh, $src_dir) or die "Can't open $src_dir: $!";
	# # my $file_counter = 0 ; 
	# # while (my $file = readdir($dh)) {
		# # next if $file =~ /^\.\.?$/;  # Skip '.' and '..'
		# # last if !$file || $file_counter >= 3 ;	
		# # my $src_file = "$src_dir/$file";
		# # my $dst_file = "$dst_dir/$file";
		# # copy($src_dir, $dst_dir) or warn "Failed to copy $src_file to $dst_file: $!";
		# # $file_counter++ ;
	# # }

	# # closedir($dh);
	
# } #------------------------------------------------------------------------------------------


sub delete {

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

	&db_min_ro($table,'1,sss_quote_nr',"id = '$i{id}'",'','') ;
	
	my $sss_delete_id = $db{$table}{1}{sss_quote_nr} ; 

	my $aisa_delete_id = $i{id} ;

	&db_min_delete('event_quotes',"`id`='$aisa_delete_id'") ;
	&db_min_delete('event_quotes_min',"`id`='$aisa_delete_id'") ;
	&common_min_delete_files("$htmlpath/uploads/uploads/$aisa_delete_id") ;
	&common_min_delete_files("$htmlpath/pdf/event_details","Event_Details-$aisa_delete_id.pdf") ;

	if ($sss_delete_id) {

		&db_switch_conn('sss') ;
			&db_min_ro($table,'1,id',"id = '$sss_delete_id' AND aisa_quote_nr = '$aisa_delete_id'",'','') ;
			if ($db{$table}{1}{id}) {
				&db_min_delete($table,"id = '$sss_delete_id'") ;
				&common_min_delete_files("$htmlpath_sss/uploads/uploads/$sss_delete_id") ;			
				&common_min_delete_files("$htmlpath_sss/pdf/event_details","Event_Details-$sss_delete_id.pdf") ;
			}
		&db_switch_conn('aisa') ;
		
	}

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

sub process_upload_ifields {

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

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

sub set_default_i_vals {
		
	my $srch_where_sql = "`id`='$i{id}'" ;

	$iaction eq 'save' ? &db_min_ro($table,'*','','id DESC',1) : &db_min_ro($table,'*',$srch_where_sql,'','') ;

	foreach (sort { $col_name{$a} cmp $col_name{$b} } keys %col_name) {
		$col = $col_name{$_} ;
		
		# &common_min_debug("1. [$col] [$i{$col}]");
		
		if (substr($col,0,4) eq 'vat_' or substr($col,0,5) eq 'excl_' or substr($col,0,4) eq 'qty_') { 
			$i{$col} = 0 unless $i{$col} ;
		} # only create the column if it doesn't exist	
		
		if (substr($col,0,5) eq 'date_') { 
			$i{$col} = 'NULL' unless $i{$col} ;
		} # only create the column if it doesn't exist	
		
		if (substr($col,0,11) eq 'amount_ttl_' or substr($col,0,9) eq 'usd_amnt_' or substr($col,0,10) eq 'curr_amnt_' or substr($col,0,9) eq 'item_ttl_' or substr($col,-6,6) eq '_total') { 
			$i{$col} = '0.00' unless $i{$col} ;
		}
		
		if ((substr($col,6,9) eq '_costing_' and substr($col,0,5) eq 'item_' and $i{$col}) or ($col eq 'quote_to' and $i{$col})) { 
			my @valarr = split(/\:/,$i{$col}) ;
			$i{$col} = $valarr[0] ; # set the value to only be the id
		}
	}
		
	$i{quote_completed}   = 0 unless $i{quote_completed}  ;
	$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_rejected}    = 0 unless $i{quote_rejected} ;
	$i{annual_invoice}    = 0 unless $i{annual_invoice} ;
	$i{nr_of_casuals_2}   = 0 unless $i{nr_of_casuals_2} ;
	$i{linear_id}         = 0 unless $i{linear_id} ;
	$ignore{invoice_date} = 1 unless length($i{invoice_date}) == 10 ;
	
	# if ($i{quote_completed}) {
		# $i{quote_accepted}  = 1 ;
		# $i{quote_cancelled} = 0 ;
		# $i{quote_pending}   = 0 ;
		# $i{quote_rejected}  = 0 ;
	# } elsif ($i{quote_accepted}) {
		# $i{quote_cancelled} = 0 ;
		# $i{quote_completed} = 0 ;
		# $i{quote_pending}   = 0 ;
		# $i{quote_rejected}  = 0 ;
	# } elsif ($i{quote_rejected}) {
		# $i{quote_cancelled} = 0 ;
		# $i{quote_completed} = 0 ;
		# $i{quote_pending}   = 0 ;
		# $i{quote_accepted}  = 0 ;
	# } elsif ($i{quote_pending}) {
		# $i{quote_cancelled} = 0 ;
		# $i{quote_rejected}  = 0 ;
	# }
	
	$i{ligr}                = ($i{ligr}) ? 'Yes' : 'No' ;
						    
	$i{city_id}             = 0 unless $i{city_id}  ;
	$i{region_id}           = 0 unless $i{region_id}  ;
	$i{category_id_1}       = 0 unless $i{category_id_1} ;
	$i{category_id_2}       = 0 unless $i{category_id_2} ;
	$i{po_nr}               = 0 unless $i{po_nr} ;
						    
	# $i{grand_total}       = '0.00' unless $i{grand_total} ;
	$i{format_of_title}     = uc $i{format_of_title} ;
	$i{ref}                 = uc $i{ref} ;
	$i{category_1_details}  = uc $i{category_1_details} ;
	$i{category_2_details}  = uc $i{category_2_details} ;
	
	&common_shared_process_poc_recipients("poc") ;
	&common_shared_process_poc_recipients("recipient") ;
 
} #----------------------------------------------------------------------------------------

sub list_screen {
		
	# my $page2 = 'event-quotes' ; 

	# if ($page2 && $ENV{SCRIPT_NAME} =~ /\_test/) { $page2 .= '-test' ; }
	
	# my $action_delete_2 = qq~delete-$page2~ ;
	
	# $print_footer_forms .= qq~
		# <form name="delete_min_form_custom" id="delete-min-form-custom" action="$action_delete_2" method="post">
			# <input type="hidden" value="delete"					name="iaction">
			# <input type="hidden" value="" 						name="id">
			# <input type="hidden" value="$i{quote_to}"			name="quote_to">
			# <input type="hidden" value="$i{event_from}"			name="event_from">
			# <input type="hidden" value="$i{event_to}"         	name="event_to">
			# <input type="hidden" value="$i{quotes_from}"      	name="quotes_from">
			# <input type="hidden" value="$i{quotes_to}"        	name="quotes_to">
			# <input type="hidden" value="$i{po_nr}"            	name="po_nr">
			# <input type="hidden" value="$i{quote_nr}"         	name="quote_nr">
			# <input type="hidden" value="$i{country}           	name="country"> 
			# <input type="hidden" value="$i{customer_name}"    	name="customer_name">
			# <input type="hidden" value="$i{accepted}"         	name="accepted">
			# <input type="hidden" value="$i{options}"          	name="options">
			# <input type="hidden" value="$i{completed}"        	name="completed">
			# <input type="hidden" value="$i{region_id}"        	name="region_id">
			# <input type="hidden" value="$i{city_id}"          	name="city_id">
			# <input type="hidden" value="$i{organisation_ids}" 	name="organisation_ids">
			# <input type="hidden" value="$i{sport_type_ids}"   	name="sport_type_ids">
			# <input type="hidden" value="$i{type}"             	name="type">
			# <input type="hidden" value="$i{system_id}"        	name="system_id">
		# </form>
	# ~ ;
	
	$trigger_jquery_raw .= qq~
		function deleteMinItem_custom (name,id) {
			BootstrapDialog.confirm({
				title: 'Confirm Delete',
				message: 'Are you sure you want to delete <strong>'+name+'</strong>?',
				type: BootstrapDialog.TYPE_DANGER, // <-- Default value is BootstrapDialog.TYPE_PRIMARY <-- Default value is BootstrapDialog.TYPE_WARNING
				callback: function(result) {            
					if (result) {
						let delete_url = "$useropts{scripts}/get/get_delete_event_quote.pl?"+id ;
						\$.get(delete_url) ; 
						\$("#event_quote_row_"+id).html("") ;
					}
				}
			}) ;
		}
	~ ; 

	&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('analytics_event_bookings','id,event_quote_id',"event_quote_id <> '0'",'','') ;
	
	our %analytics_events = () ;
	foreach (keys %{$db{analytics_event_bookings}}) {
		$analytics_events{$db{analytics_event_bookings}{$_}{event_quote_id}} .= qq~$_;~ ;
	}
	
	&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','*','','','') ;
	foreach my $_id (keys %{$db{sport_types}}) { $sort_type{$_id} = $db{sport_types}{$_id}{name} ; }
	
	&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 = 'countries' ;
	my $t3 = 'cities' ;
	my $t4 = 'customers' ;
	my $t5 = 'event_types' ;
	my $t6 = 'regions' ;
	my $t7 = 'event_quotes_min' ;
	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' ;  
	
	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.city_id,
						q.region_id,
						q.organisation_ids,							
						q.date_from,
						q.date_to,
						q.grand_total,
						q.ref,
						q.qty,
						q.quote_expiry,
						q.quote_to,
						q.invoice_nr,
						q.quote_date,
						q.type,
						q.currency,
						q.country_id,
						q.quote_cancelled,
						q.quote_accepted,
						q.quote_completed,
						q.quote_pending,
						q.quote_created,
						q.quote_rejected,
						q.activetab,
						q.user_id,
						q.category_1,
						q.category_id_1,
						q.category_2,
						q.category_id_2,
						q.additional_notes, 
						q.poc_id,
						q.type_details_id,
						q.club_ids,
						q.event_system_id_multiple,
						q.operator_ids,
						q.format_of_title,
						q.emailed_op_ids,
						q.fixed_system_overall_status, 
						q.daily_operator_ids,
						q.sss_quote_nr,
						q.demo_id,
						c.name AS 'country',
						t.name AS 'customer',
						y.city,		
						y.province,							
						r.code AS 'reg_code',	
						r.name AS 'region',				
						e.name AS 'event_type',
						emin.category_details					
			FROM $t1 q LEFT JOIN $t2 c ON q.country_id = c.id
					   LEFT JOIN $t3 y ON q.city_id    = y.id
					   LEFT JOIN $t4 t ON q.quote_to   = t.id
					   LEFT JOIN $t5 e ON q.type       = e.id
					   LEFT JOIN $t6 r ON q.region_id  = r.id
					   LEFT JOIN $t7 emin ON q.id = emin.quote_nr
			$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") ;
	}

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

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 @sql_col_display   = () ;
	our @col_display_excel = () ;
	
	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 ; 
		&report_xlsx_export_header("Events_Quotes",'events') ; 
	} else {
		@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") ; 
		@sql_col_display = @col_display_excel ; 
		&report_xlsx_export_header("Events_Quotes",'events') ; 
		@sql_col_display = ("nr","event_start","event_end","days","date_added","customer","event","venue","location","sport","type","operators") ;
		if ($userid eq '24') {
		# if ($glod_user_level > 3) {
			push @sql_col_display, "amount" ;
			push @sql_col_display, "invoice_nr" ;
		}
	}
	
	push @sql_col_display, "" ;
	
	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} ;
		my $quote_accepted   = $db{$tables}{$id}{quote_accepted} ;		
		my $quote_pending    = $db{$tables}{$id}{quote_pending} ;
		my $quote_cancelled  = $db{$tables}{$id}{quote_cancelled} ;
		my $quote_completed  = $db{$tables}{$id}{quote_completed} ;
		my $quote_created    = $db{$tables}{$id}{quote_created} ;
		my $quote_rejected   = $db{$tables}{$id}{quote_rejected} ;
		my @cat_details = split('\|;\|',$db{$tables}{$id}{category_details}) ;
		
		if ($quote_completed) {
			$sortprefix = 'd' ;
		} elsif ($quote_accepted) {
			$sortprefix = 'c' ;
		} elsif ($quote_rejected) {
			$sortprefix = 'x' ;
		} elsif ($quote_cancelled) {
			$sortprefix = 'z' ;
		} elsif ($quote_created) { # create by schools_manager
			$sortprefix = 'a' ;
		} elsif ($quote_pending) {
			$sortprefix = 'b' ;
		}
		
		if ($usertype eq 'support') {
			next unless $quote_accepted && !$quote_completed ;
		}
		
		# if ($quote_expiry and $quote_expiry<"$now_year$now_mm$now_dd" and $iaction ne 'report' and $iaction ne 'accepted' and $iaction ne 'closed' and $iaction ne 'all') { next ; }
		
		my $quote_date = $db{$tables}{$id}{quote_date} ; $quote_date =~ s/\-//iog ;
		
		$yr = substr($quote_date, 0, 4) ; 
		$mm = substr($quote_date, 4, 2) ; 
		$dd = substr($quote_date, 6, 2) ;
		
		my ($yr2,$mm2,$dd2) = Add_Delta_Days($yr,$mm,$dd,60); #

		$mm2  = sprintf("%02s", $mm2) ;
		$dd2  = sprintf("%02s", $dd2) ;

		$quote_date = "$yr2$mm2$dd2" ;
		
		if ($quote_date && $quote_date < "$now_year$now_mm$now_dd" && $quote_accepted!=1 &&
			$iaction ne 'report' && $iaction ne 'accepted' && $iaction ne 'closed' && $iaction ne 'all' && 
			$i{options} ne 'accepted' && $i{options} ne 'closed' && $i{options} ne 'all') 
		{ next ; }
		
		$print_tbody .= qq~<tr id="event_quote_row_$id">~ ;
		
		$xlsxcol=0;
		
		my $quote_nr = $db{$tables}{$id}{quote_nr} ;

		foreach (@sql_col_display) { 
			unless ($_) { next ; } # blank for the buttons column
			my $val = $db{$tables}{$id}{$_} ;
			my $align = qq~ class="dt-center"~ ; 
			my $nowrap = '' ;
			
			# if    ($_ eq 'event_end')	{  $val   = substr($db{$tables}{$id}{date_to},0,10) ; $align = qq~ class="dt-center" style="width:6.9%"~ ; } 
			# elsif ($_ eq 'event_start')	{  $val   = substr($db{$tables}{$id}{date_from},0,10) ; $nowrap = 'nowrap' ; } 
			if ($_ eq 'event_end') {  
		
				# my $sort_val = $db{$tables}{$id}{date_to} ;
				# $sort_val =~ s/\-//g ;
				# $sort_val =~ s/\://g ;
				# $sort_val =~ s/ //g ;
				my $sort_val = $db{$tables}{$id}{date_to} =~ s/[\-:\s]//gr;
				$val   = qq~<span style='display:none;'>$sort_val</span>~ . &common_min_date_as_string(substr($db{$tables}{$id}{date_to},0,16)) ; $align = qq~ class="dt-center"~ ; $nowrap = 'nowrap' ; 
			} elsif ($_ eq 'event_start')	{  
				my $sort_val = $db{$tables}{$id}{date_from} =~ s/[\-:\s]//gr;
				$val   = qq~<span style='display:none;'>$sort_val</span>~ . &common_min_date_as_string(substr($db{$tables}{$id}{date_from},0,16)) ;
				# 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} ; 
				$nowrap = '' ;
			} elsif ($_ eq 'customer') { 
				$nowrap = 'nowrap' ; 
			} elsif ($_ eq 'date_added') {
				my $sort_val = $db{$tables}{$id}{quote_date} =~ s/[\-:\s]//gr;
				$val =  qq~<span style='display:none;'>$sort_val</span>~ . &common_min_date_as_string($db{$tables}{$id}{quote_date}) ; 
				$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' ; 
			} elsif ($_ eq 'country_id') { 
				$val = $db{$tables}{$id}{country} ; 
			} elsif ($_ eq 'days') { 
				$val = $db{$tables}{$id}{qty} ; 
			} elsif ($_ eq 'type') {  
				my $txt = uc substr($db{$tables}{$id}{event_type},0,1) ; 
				$val = qq~<a href="#" data-title="$db{$tables}{$id}{event_type}" data-toggle="tooltip" data-placement="left"><strong>$txt</strong></a>~; 
				$nowrap = 'nowrap' ; 
			} elsif ($_ eq 'amount') {   
				my $ttl = sprintf("%0.2f",($db{$tables}{$id}{grand_total})) ; 
				$val = &common_commify($ttl) ; 
			} elsif ($_ eq 'system_name') {
				# $val = '' ; 
				# foreach my $event_id (split(";",$db{$tables}{$id}{event_system_id_multiple})) {			
					# $val .= qq~$db{event_systems}{$event_id}{name} [$db{event_systems}{$event_id}{description}], ~ ;		
				# }
				# chop $val if $val ; chop $val if $val ;
				
				$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 = '' ; 
				# foreach my $club_id (split(/\;/,$db{$tables}{$id}{club_ids})) {			
					# $val .= qq~$db{clubs}{$club_id}{name}, ~ ;		
				# }
				# chop $val if $val ; chop $val if $val ;
				$val = join("<br>",map { "$db{clubs}{$_}{name}" } split(/\;/,$db{$tables}{$id}{club_ids})) ;
				
			} elsif ($_ eq 'operators') {
				$val = '' ; $op_cnt = 0 ;
				my %seen_op_id = () ;
				my @op_ids = split(/\,/,$db{$tables}{$id}{operator_ids}) ;
				for my $op_id (@op_ids) {
					next if $seen_op_id{$op_id} || !$op_id ;
					$seen_op_id{$op_id} = 1 ; $op_cnt++;
					$val .= qq~$name{$op_id}<br>~ ;
				}
				foreach my $op_ids (split(/\|/,$db{$tables}{$id}{daily_operator_ids})) {
					foreach my $opid (split(/\;/,$op_ids)) {
						next if $seen_op_id{$opid} || !$opid ;
						$seen_op_id{$opid} = 1 ; $op_cnt++;
						$val .= qq~$name{$opid}<br>~ ;
					}
				}				
				$val = substr($val,0,-4) if $val ;
				# $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="$val" data-toggle="tooltip" data-placement="left">$glyph_icon</a>~ if $val ;
				
			} elsif ($_ eq 'venue') {  
				# my @oids = split(/\,/,$db{$tables}{$id}{organisation_ids}) ;
				# my @venues = map { $organisation{$_} } @oids;
				# $val = join(" & ",@venues) ;
				$nowrap = '' ; 
				$val = join("<br>", map { $organisation{$_} } split(/\,/,$db{$tables}{$id}{organisation_ids})) ;
				# foreach $_oid (@oids) {
					# $val .= $organisation{$_oid} . ',' ;
				# }
				# chop $val ;
			} elsif ($_ eq 'sport')  {
				# my @sptyps = split(/\,/,$db{$tables}{$id}{sport_type_ids}) ;
				# my @sports = map { $sort_type{$_} } split(/\,/,$db{$tables}{$id}{sport_type_ids}) ;
				# $val = join(", ",@sports) ; # foreach $_sp (@sptyps) { $val .= $sort_type{$_sp} . ', ' ; }
				$val = join("<br>", map { $sort_type{$_} } split(/\,/,$db{$tables}{$id}{sport_type_ids})) ; # foreach $_sp (@sptyps) { $val .= $sort_type{$_sp} . ', ' ; }
				# chop $val if $val ;
			} elsif ($_ eq 'nr') {
				
				$nowrap = 'nowrap' ;
				
				$sort_val = sprintf("%06d",$id) ; 
				$sort_val = ($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  ; 

				# my $event_id = $db{$tables}{$id}{id} ;
				# $db{$tables}{$id}{id} = $db{$tables}{$id}{quote_id} ;
				
				$val = qq~<span style="display:none;">$sort_val</span>~ . &common_min_get_event_quote_button($id,$tables,"event-quotes") ; 
				$val .= qq~<span title="SSS : $db{$tables}{$id}{sss_quote_nr}" data-toggle="tooltip" data-placement="top"><i class="glyphicons glyphicons-pin-flag icon-white"></i></span>~ if $db{$tables}{$id}{sss_quote_nr} ;
				
				# $db{$tables}{$id}{id} = $event_id ; 
				
				if ($analytics_events{$id}) {
					chop $analytics_events{$id} ;
					foreach (sort {$a <=> $b} split(/\;/,$analytics_events{$id})) {
						$val .= qq~<span title="Analytics Event : $_" data-toggle="tooltip" data-placement="top"><a href="javascript:editMinItem('$_','analytics-event-bookings');" style="color:black;"><i class="glyphicons glyphicons-paired icon-white"></i></a></span>~ ;
					}
				}
						
				if ($db{$tables}{$id}{demo_id}) {
					
					my $glod_user_level_eff = ($glod_user_level == 2 && $is_operator) ? 3 : $glod_user_level ;
					
					# $val .= ($glod_user_level_eff < 3 || $db{$table}{$event_id}{quote_cancelled}) ? 
					$val .= ($glod_user_level_eff < 3 || $db{$tables}{$id}{quote_cancelled}) ? 
						qq~<span title="Demo : $db{$tables}{$id}{demo_id}" data-toggle="tooltip" data-placement="top"><a href="javascript:void(0);" style="color:black;"><i class="glyphicons glyphicons-duplicate icon-white"></i></a></span>~ : 
						qq~<span title="Demo : $db{$tables}{$id}{demo_id}" data-toggle="tooltip" data-placement="top"><a href="javascript:editMinItem('$db{$tables}{$id}{demo_id}','demos');" style="color:black;"><i class="glyphicons glyphicons-duplicate icon-white"></i></a></span>~ ;
				}
					
				# my $class = 'info' ; my $style = '' ; 				
				# if ($quote_completed) {
					# $class  = 'success' ; # green
					# $tt_txt = 'Completed' ;
				# } elsif ($quote_accepted) {
					# $class  = 'info' ; # blue
					# $tt_txt = 'Accepted' ;
					# my @fixed_system_overall_statuses = split(/\;/,$db{$tables}{$id}{fixed_system_overall_status}) ;
					# my @event_system_ids              = split(/\;/,$db{$tables}{$id}{event_system_id_multiple}) ;
					# my $event_sys_cnt                 = 0 ; my $event_sys_test_status = 0 ; my $got_some_fixed = 0 ; my $fixed_status_color = '164473' ; # Dark Blue
					# foreach my $event_id (@event_system_ids) {			
						# if ($db{event_systems}{$event_id}{system_type} eq 'fixed') {
							# $tt_txt = 'Accepted and tests show All Clear for the Fixed Systems' if $tt_txt eq 'Accepted' ;
							# $got_some_fixed = 1 ;
							# if ($fixed_system_overall_statuses[$event_sys_cnt] == 3) { # Not Clear
								# $fixed_status_color = '5d09d3' ; # Dark Purple
								# $tt_txt = 'Accepted but Not Clear on some Fixed Systems' ;
							# } elsif ($fixed_system_overall_statuses[$event_sys_cnt] == 2) { # Sound Issue
								# $fixed_status_color = '5d092c' ;
								# $tt_txt = 'Accepted but Sound Issue found on some Fixed Systems' ;
							# }
						# }
						# $event_sys_cnt++;						
					# }
					# if ($got_some_fixed) { $style  = "style='background-color:#$fixed_status_color;border-color:#$fixed_status_color'";  }
				# } elsif ($quote_rejected) {
					# $style  = 'style="background-color:#ca0ad3;border-color:#ca0ad3"'; # purple
					# $tt_txt = 'Rejected' ;
				# } elsif ($quote_cancelled) {
					# $class  = 'danger' ; # red
					# $tt_txt = 'Cancelled' ;
				# } elsif ($quote_created) { # create by schools_manager
					# $style  = 'style="background-color:#f6e305;border-color:#f6e305"'; # yellow
					# $tt_txt = 'Pending, created by School Manager' ;
				# } elsif ($quote_pending) {
					# $class  = 'warning' ; # orange
					# $tt_txt = 'Pending' ;
				# }
				
				# my $tt = qq~data-toggle="tooltip" data-placement="right" data-title="$tt_txt"~;
				
				# # &common_debug("$quote_nr quote_created [$quote_created] $style") if $quote_created ; 

				# # $val = ($is_schools_manager) ? qq~<a class="btn btn-$class btn-xs" href="javascript:void(0);" $style>$quote_nr</a>~ : qq~<a class="btn btn-$class btn-xs" href="javascript:editMinItem('$id');" $style>$quote_nr</a>~  ; 
				# # $val = ($glod_user_level < 4 || $quote_cancelled) ? qq~<a class="btn btn-$class btn-xs" href="javascript:void(0);" $style $tt>$quote_nr</a>~ : qq~<a class="btn btn-$class btn-xs" href="javascript:editMinItem('$id');" $style $tt>$quote_nr</a>~  ; 
				# $val = ($glod_user_level < 3 || $quote_cancelled) ? qq~<a class="btn btn-$class btn-xs" href="javascript:void(0);" $style $tt>$quote_nr</a>~ : qq~<a class="btn btn-$class btn-xs" href="javascript:editMinItem('$id');" $style $tt>$quote_nr</a>~  ; 
			} elsif ($col_name eq 'poc_name') {
				$val = $db{event_quotes_poc}{$db{$tables}{$id}{poc_id}}{name} ;
			} elsif ($col_name eq 'poc_contact_nr') {
				$val = $db{event_quotes_poc}{$db{$tables}{$id}{poc_id}}{contact_nr} ;
			} 
			# elsif ($_ eq 'user') {
				# $val = '' ;
				# # $val = $db{users}{$db{$tables}{$id}{user_id}}{username} if $db{$tables}{$id}{user_id} ;
				# $val = $username{$db{$tables}{$id}{user_id}} ;
			# }
			
			$print_tbody .= qq~<td $nowrap $align>$val</td>~ ;  
		}
		
		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 ) ; 	
		
		# push @event_dates, $year . '-' . $month . '-' . $day ;
		
		# my $Dd = Delta_Days($year,$month,$day, $year_end,$month_end,$day_end);

		my $row_count = 0;  
		# for my $event_date (sort @event_dates) {
		$xlsxcol = 0 ; 
		$row_count++ ; 
		
		if (($quote_created and not $quote_accepted and not $quote_completed) or ($quote_completed and not $quote_created and not $quote_accepted and not $quote_completed)) {
			$xlsxrow-- ;
		}
		
		my @event_sys = split(/;/,$db{$tables}{$id}{event_system_id_multiple}) ;
		my $cnt_event_sys = 0 ; 
		foreach (split(/;/,$db{$tables}{$id}{event_system_id_multiple})) {
			$cnt_event_sys++ ;
		}
		$cnt_event_sys = 1 unless $cnt_event_sys ;
			
		foreach my $col_name (@col_display_excel) { 	
			
			next if ($quote_created and not $quote_accepted and not $quote_completed) or ($quote_completed and not $quote_created and not $quote_accepted and not $quote_completed) ;
			
			$val = $db{$tables}{$id}{$col_name} ;
			
			# $xlsxrow-- if $col_name ne 'event_start' ; 
			
			if    ($col_name eq 'event_end')	{ $val = substr($db{$tables}{$id}{date_to},0,16)   ; } 
			elsif ($col_name eq 'event_start')	{ $val = substr($db{$tables}{$id}{date_from},0,16) ; } 
			elsif ($col_name eq 'nr') { 
				$val = $id ; 	
				if ($db{$table}{$id}{demo_id}) {
					for (1 .. $cnt_event_sys) { &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format108) ; $xlsxrow++; } # green
					$xlsxrow = $xlsxrow - $cnt_event_sys ;					
				} elsif ($analytics_events{$id}) {
					for (1 .. $cnt_event_sys) { &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format107) ; $xlsxrow++; } # green
					$xlsxrow = $xlsxrow - $cnt_event_sys ;					
				} elsif ($quote_completed) {
					for (1 .. $cnt_event_sys) { &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format80) ; $xlsxrow++; } # green
					$xlsxrow = $xlsxrow - $cnt_event_sys ;
				} elsif ($quote_accepted) {
					my $accp_format = $format77 ;
					my @fixed_system_overall_statuses = split(/\;/,$db{$tables}{$id}{fixed_system_overall_status}) ;
					my @event_system_ids              = split(/\;/,$db{$tables}{$id}{event_system_id_multiple}) ;
					my $event_sys_cnt                 = 0 ; my $event_sys_test_status = 0 ; my $got_some_fixed = 0 ; my $possible_format = $format103 ; # '164473' ; # Dark Blue $format103
					foreach my $event_id (@event_system_ids) {			
						if ($db{event_systems}{$event_id}{system_type} eq 'fixed') {
							$tt_txt = 'Accepted and tests show All Clear for the Fixed Systems' if $tt_txt eq 'Accepted' ;
							$got_some_fixed = 1 ;
							if ($fixed_system_overall_statuses[$event_sys_cnt] == 3) { # Not Clear
								# $fixed_status_color = '5d09d3' ; # Dark Purple $format105	
								$possible_format = $format105 ; 
								$tt_txt = 'Accepted but Not Clear on some Fixed Systems' ;   
							} elsif ($fixed_system_overall_statuses[$event_sys_cnt] == 2) { # Sound Issue
								# $fixed_status_color = '5d092c' ; # $format106 
								$possible_format = $format106 ; 
								$tt_txt = 'Accepted but Sound Issue found on some Fixed Systems' ;
							}
						}
						$event_sys_cnt++ ;
					}
					if ($got_some_fixed) { $accp_format = $possible_format ;  }
					for (1 .. $cnt_event_sys) { &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$accp_format) ; $xlsxrow++; } # blue
					$xlsxrow = $xlsxrow - $cnt_event_sys ;
				} elsif ($quote_pending) {
					for (1 .. $cnt_event_sys) { &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format79) ; $xlsxrow++; } # blue
					$xlsxrow = $xlsxrow - $cnt_event_sys ;
					# next ;
					# &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format79) ; # orange
				} elsif ($quote_cancelled) {
					for (1 .. $cnt_event_sys) { &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format81) ; $xlsxrow++; } # red
					$xlsxrow = $xlsxrow - $cnt_event_sys ;
				} elsif ($quote_rejected ) {
					for (1 .. $cnt_event_sys) { &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format104) ; $xlsxrow++; } # red
					$xlsxrow = $xlsxrow - $cnt_event_sys ;		
				} elsif ($quote_created) { # create by schools_manager
					# next ; 
					# &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format78) ; # yellow
				} 	
				$xlsxcol++ ; 
				next ; 
			} elsif ($col_name eq 'event') { 
				$val = $db{$tables}{$id}{ref} ; 
				for (1 .. $cnt_event_sys) { &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format82) ; $xlsxrow++; }
				$xlsxrow = $xlsxrow - $cnt_event_sys ;
				$xlsxcol++; 
				next ;
			} elsif ($col_name eq 'date')  { 
				$val  = substr($event_date, 5, 2 ) ; 
				$val = substr($event_date, 8, 2 ) . ' ' . $month_fullname[$val - 1] . ' ' .  substr($event_date, 0, 4 ) ; 
			} elsif ($col_name eq 'days') {
				$val = $db{$tables}{$id}{qty} ; 			
			} elsif ($col_name eq 'type_of_system') {
				$val = $db{$tables}{$id}{event_type} ; 		
			} elsif ($col_name eq 'system_details') {
				# $val = '' ; 
				# foreach my $type_id (split(",",$db{$tables}{$id}{type_details_id})) {
					# $val .= qq~$db{event_type_details}{$type_id}{name}, ~;
				# }
				# chop $val if $val ; chop $val if $val ; 
				$val = join (", ", map{ "$db{event_type_details}{$_}{name}" } split(",",$db{$tables}{$id}{type_details_id})) ;
			} elsif ($col_name eq 'system_name') {

				for (0 .. $cnt_event_sys-1) {
					$val = qq~$db{event_systems}{$event_sys[$_]}{name}~ unless $db{event_systems}{$event_sys[$_]}{description} ;	
					$val = qq~$db{event_systems}{$event_sys[$_]}{name} [$db{event_systems}{$event_sys[$_]}{description}]~ if $db{event_systems}{$event_sys[$_]}{description} ;	
					if ($event_date ne $end_date){
						&report_write_events($val, 0) ;
					} else {
						&report_write_events($val, 1) ;
					}
					$xlsxrow++;					
				}
				$xlsxrow = $xlsxrow - $cnt_event_sys ;
				
			} elsif ($col_name eq 'sport_type') { 
				my @sptyps2 = split(/\,/,$db{$tables}{$id}{sport_type_ids}) ;
				$val = '' ; 
				foreach $_sp (@sptyps2) {
					$val .= qq~$sort_type{$_sp} & ~ ;
				}
				chop $val if $val ; chop $val if $val ;
			# } elsif ($_ eq 'cities'  && $row_count == 1) {
			} elsif ($col_name eq 'cities') {
				$val = qq~$db{$tables}{$id}{city}~ ; 
				if ($db{$tables}{$id}{city_id} =~ /,/) {
					$val = '' ; 
					foreach my $c_id (split(",",$db{$tables}{$id}{city_id})) {
						$val .= qq~$db{cities}{$c_id}{city}, ~ ;
					}
					chop $val if $val ; chop $val if $val ;
				}
			} elsif ($col_name eq 'region') {
				$val = qq~$db{$tables}{$id}{region}~ ;
			} elsif ($col_name eq 'venue') {
				$val = '' ; 
				foreach my $venue_id (split(",",$db{$tables}{$id}{organisation_ids})) {
					$val .= qq~$organisation{$venue_id} & ~ ;
				}
				chop $val if $val ; chop $val if $val ; chop $val if $val ;
			} elsif ($col_name eq 'club_names') {
				$val = '' ; 
				foreach my $club_id (split(";",$db{$tables}{$id}{club_ids})) {			
					$val .= qq~$db{clubs}{$club_id}{name}, ~ ;		
				}
				chop $val if $val ; chop $val if $val ;
			} 
			
			elsif ($col_name eq 'operators') {
				$val = '' ;
				# my @op_split3 = split(/;~;/,$db{$table}{$id}{operator_ids}) ; 
				# foreach my $op_id (split(/\,/,$op_split3[0])) {
				foreach my $op_id (split(/\,/,$db{$tables}{$id}{operator_ids})) {
					$val .= qq~$name{$op_id} [$email{$op_id}], ~ ;
				}
				chop $val if $val ; chop $val if $val ;
			} 
			elsif ($col_name eq 'client') {
				$val = $db{$tables}{$id}{customer} ;		
			} elsif ($col_name eq 'poc_name') {
				$val = $db{event_quotes_poc}{$db{$tables}{$id}{poc_id}}{name} ;
			} elsif ($col_name eq 'poc_contact_nr') {
				$val = $db{event_quotes_poc}{$db{$tables}{$id}{poc_id}}{contact_nr} ;
			} elsif ($col_name eq 'category_1') {
				$val = $db{event_quotes_categories}{$db{$tables}{$id}{category_id_1}}{category} ;
			} elsif ($col_name eq 'category_1_details') {					 
				$val = $cat_details[0] ;
			} elsif ($col_name eq 'category_2') {
				$val = $db{event_quotes_categories}{$db{$tables}{$id}{category_id_2}}{category} ;
			} elsif ($col_name eq 'category_2_details') {
				$val = $cat_details[1] ;
			} elsif ($row_count != 1) {
				# $val = '' ;
			}
			
			if ($col_name ne 'system_name') {
				
				for (1 .. $cnt_event_sys) {
					if ($event_date ne $end_date){
						&report_write_events($val, 0) ;
					} else {
						&report_write_events($val, 1) ;
					}
					$xlsxrow++; 					
				}	
				$xlsxrow = $xlsxrow - $cnt_event_sys ;				
			}
			
			# }
			# ------------------------------------------------------------------------- HTML AFTER
			$xlsxcol++; 
		}
		
		$xlsxrow = $cnt_event_sys + $xlsxrow ; 
		
		my $quote_nr = $quote_nr ; $quote_nr =~ s/'//iog; unless ($quote_nr) { $quote_nr = $id ; }
		
		# if ($useropts{boss}{$username} or $useropts{super}{$username}) { }
		
		# my $view_butt   = qq~<a class="btn btn-info btn-xs" href="javascript:viewMinItem('$id');"><i class="glyphicon glyphicon-edit icon-white"></i></a>~ ;	
		my $edit_butt     = qq~<a class="btn btn-info btn-xs" href="javascript:editMinItem('$id','event-quotes');"><i class="glyphicon glyphicon-edit icon-white"></i></a>~ ;	
		# my $delete_butt   = ($glod_user_level < 4 || $quote_accepted || $quote_completed || $quote_rejected || $quote_pending) ? '' : qq~<a class="btn btn-danger btn-xs" href="javascript:deleteMinItem('$quote_nr','$id')"><i class="glyphicon glyphicon-trash icon-white"></i></a>~ ;
		my $delete_butt  = ($glod_user_level < 3 || $quote_accepted || $quote_completed || $quote_rejected || $quote_pending) ? '' 
						: ($db{$table}{$id}{demo_id}) ? qq~<a class="btn btn-default btn-xs" href="#" title="Linked to a Demo!" data-toggle="tooltip"><i class="glyphicon glyphicon-trash icon-white"></i></a>~
						: ($analytics_events{$id}) ? qq~<a class="btn btn-default btn-xs" href="#" title="Linked to an Analytics Event!" data-toggle="tooltip"><i class="glyphicon glyphicon-trash icon-white"></i></a>~
						: qq~<a class="btn btn-danger btn-xs" href="javascript:deleteMinItem_custom('$quote_nr','$id')"><i class="glyphicon glyphicon-trash icon-white"></i></a>~ ;
		
		my $copy_butt = qq~<a class="btn btn-success btn-xs" href="javascript:copyMinItem('$id');" title="Copy" data-toggle="tooltip" data-placement="top"><i class="glyphicon glyphicon-retweet icon-white"></i></a>~ ;
		
		# my $copy_butt   = qq~<a class="btn btn-success btn-xs" href="javascript:copyMinItem('$id');" title="Copy" data-toggle="tooltip" data-placement="top"><i class="glyphicon glyphicon-retweet icon-white"></i></a>~;
		# my $pdf_butt    = qq~<a class="btn btn-primary btn-xs" href="javascript:dlgMdl('$useropts{scripts}/pdf/event_quote_pdf.pl?$id&$tabcnt{$db{$tables}{$id}{activetab}}&$tabsec{$db{$tables}{$id}{activetab}}','EVENT QUOTE $quote_nr','','waybill-dialog');"><i class="glyphicon glyphicon-print"></i></a>~;
		my $pdf_butt     .= qq~<a class="btn btn-primary btn-xs" href="javascript:dlgMdl('$useropts{scripts}/pdf/event_details_pdf.pl?$id&&','EVENT DETAILS $quote_nr','','waybill-dialog');" data-title="Event Details PDF" data-toggle="tooltip" data-placement="left"><i class="glyphicon glyphicon-print"></i></a>~;
		
		$email_butt       = qq~<a id="email_$id" class="btn btn-default btn-xs" href="javascript:dlgMdl('$useropts{scripts}/dialog/event_email.pl?$id','EVENT EMAIL $quote_nr','','waybill-dialog');" style="background-color:rgb(70,69,69);border-color:rgb(70,69,69);"><i class="glyphicon glyphicon-envelope"></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 = '' if $usertype eq 'support' ;
		# $edit_butt = '' if $quote_cancelled && !$useropts{it}{$username};	
		
		$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~~ ;
		}
		
		# $email_butt = qq~<a class="btn btn-default btn-xs" href="#"><i class="glyphicon glyphicon-envelope icon-white"></i></a>&nbsp;~ unless $email_butt ;
		# $pdf_butt = qq~<a class="btn btn-default btn-xs" href="#"><i class="glyphicon glyphicon-print icon-white"></i></a>&nbsp;~ unless $pdf_butt ;
		
		$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,'events') ; 
	
	if ($usertype eq 'support') {
		$fnsortcol   = 1 ; # start date
		$fnsortorder =  'asc' ;
	}

	# &common_min_extra_crumb("search-$lcpage\s","Search Screen") if $glod_user_level > 3 ;
	&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 {
	
	# if ($glod_user_level < 4) {	
	if ($glod_user_level < 3) {	
		
		$ignore{type_of_system} = 1 ;
		$ignore{system_details} = 1 ;
		$ignore{system_name} = 1 ;
		$ignore{operators} = 1 ;
		# $ignore{operator_ids} = 1 ;
	}

	if ($glod_user_level < 4) {	
	# if ($glod_user_level < 3) {	
		$ignore{po_nr} = 1 ;		
		$ignore{income} = 1 ;
		$ignore{sub_total} = 1 ; 
		$ignore{vat_total} = 1 ; 
		$ignore{grand_total} = 1 ;
		$ignore{custom_set} = 1 ;		
		
	}
	
	# $ignore{custom_set} = 1 ;
	
	$ignore{event_system_calibration_ids} = 1 ;
	$ignore{event_system_calibration_status} = 1 ;
	
	$ignore{category_1_details}        = 1 ; 
	$ignore{category_2_details}        = 1 ; 
								       
	$ignore{iattachslip}               = 1 ; 
	$ignore{iattachupload_1}           = 1 ; 
	$ignore{iattachupload_2}           = 1 ; 
	$ignore{iattachupload_3}           = 1 ; 
								       
	$ignore{iattachupload_1}           = 1 ; 
	$ignore{iattachupload_2}           = 1 ; 
	$ignore{iattachupload_3}           = 1 ; 
								    
	$ignore{sport_type_ids_readonly}   = 1 ; 
	$ignore{region_id_readonly}        = 1 ;
	$ignore{city_id_readonly}          = 1 ; 
	$ignore{organisation_ids_readonly} = 1 ;	
	$ignore{linear_id_readonly} 	   = 1 ; 	
	$ignore{custom_selected_region}		= 1 ; 
	$ignore{custom_selected_country}	= 1 ; 								
	# $ignore{date_to}                 = 1 ;
	# $ignore{date_from}               = 1 ;
	$ignore{iaction}                   = 1 ;
	$required{qty}                     = 4 ; # number
	$required{quote_nr}                = 1 ;
	$readonly{quote_nr}                = 'READONLY' ;
	$required{quote_to}                = 1 ;
	$required{currency}                = 1 ;
	$required{roe}                     = 1 ;
	$required{ref}                     = 1 ;
	$required{region_id}               = 1 ;
	$required{country_id}               = '' ;
	$required{city_id}                 = 1 ;
								      
	$required{poc_name}                = 1 ;
	$required{poc_contact_nr}          = 1 ;
	$required{category_id_1}           = 1 ;
	$required{category_1_details}      = 1 ;
	$required{category_id_2}           = 1 ;
	$required{category_2_details}      = 1 ;
								      
	$hidden{quote_date}                = 2 ;
	$hidden{last_update}               = 2 ;
	$hidden{user_id}                   = 2 ;
	$hidden{datetime}                  = 2 ;
	$ignore{saveandexit}               = 1 ;
	$ignore{income}                    = 1 ; 
	$ignore{expenses}                  = 1 ; 
	$trigger_jquery_raw               .= qq~var curr_changed=0;~;
	$trigger_jquery_raw               .= qq~var curr_changedW=0;~;
	$trigger_jquery_raw               .= qq~\$.validate();~;
	$extra_js                         .= qq~<script src="$useropts{'js'}/jquery.form-validator.min.js"></script>~;

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

sub add_screen {

	$selected{max_cams}{10} = 'SELECTED';
	&select_opts('') ;
	%col_name = () ;
	&db_min_ro($table,'*',"id > 1 AND id < 10",'','') ;

	$page_title  = substr($page_title,0,-1) ;
	$db{$table}{''}{quote_nr} = &db_min_get_max($table,'quote_nr') ; 
	$db{$table}{''}{qty} = 1 ;
	
	# if ($username eq 'rory') { $db{$table}{''}{quote_nr} = 1000 ; }
	
	&add_db_fields ;
	
	&build_boxes('','save') ;
		
	local $all_select_ids_string = join(",",@all_select_ids) ; 
	$trigger_jquery_raw .= qq~\$("$all_select_ids_string").chosen({ allow_single_deselect:true,search_contains: true });~ ; 

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

sub view_screen {
	
	&edit_screen ;

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

sub edit_screen {
 
	unless ($i{id}) { $warning = qq(NO ID) ; return ; }
	
	# my $users_cols = "id,name,user_type" ; $users_cols = "id,name,user_type,region_ids" if $glod_user_level < 4 ;
	my $users_cols = "id,name,user_type" ; $users_cols = "id,name,user_type,region_ids" if $glod_user_level < 3 ;

	&db_min_ro('users',$users_cols,"`user_type` LIKE 'casual%' OR `user_type` = 'schools_manager'",'','') ;
	foreach (keys %{$db{users}}) { 
		next if $db{users}{$_}{user_type} eq 'schools_manager' ;
		$casual_name{$_} = $db{users}{$_}{name} ; 
		$casual_type{$_} = uc substr($db{users}{$_}{user_type},-1,1) ; 
		$casuals{$_}     = 1 if substr($db{users}{$_}{user_type},0,6) eq 'casual' ; 
	}

	# unless ($iaction eq 'save' or $iaction eq 'update') {
		&db_min_ro($table,'*',"id='$i{id}'",'','') ;
	# }
	
	# if ($glod_user_level < 4) {
		
		# my @abcdef = split(/ /,$db{$table}{$i{id}}{date_from}) ; 
		
		# my ($year1,$month1,$day1) = split(/-/,$abcdef[0]) ; 
		
		# my ($hour1,$min1,$sec1) = split(/:/,$abcdef[1]) ; 
		
		# $trigger_jquery .= qq~
			
			# const date1 = new Date("$year1-$month1-$day1T$hour1:$min1:$sec1");
			# const date2 = new Date("$now_year-$now_mm-$now_ddT$now_hour:$now_min:$now_sec");

			# let timeDiffMillis = Math.abs(date1 - date2);
			# let timeDiffHours = timeDiffMillis / (1000 * 60 * 60);
			
			# if (date1 >= date2 && timeDiffHours <= 18) {
				# \$("#cancelbutt").removeClass('btn btn-danger').addClass('btn btn-void');
			# }

		# ~ ; 
	# }	
	
	my @system_name_ids = split(";",$db{$table}{$i{id}}{event_system_id_multiple}) ;		
	my @club_ids        = split(";",$db{$table}{$i{id}}{club_ids}) ;	
	my @op_ids        	= ($db{$table}{$i{id}}{operator_ids} =~ /,/) ? split(",",$db{$table}{$i{id}}{operator_ids}) : ($db{$table}{$i{id}}{operator_ids} =~ /;/) ? split(";",$db{$table}{$i{id}}{operator_ids}) : $db{$table}{$i{id}}{operator_ids} ;	
	
	my $cnt_rows = 0 ;
	for (1 .. $nr_of_system_names_and_clubs) {
		$cnt_rows = $_ if $system_name_ids[$_ - 1] or $club_ids[$_ - 1] ;  
	}
	
	our @table_op_ids = () ;
	our @multi_select_op_ids = () ;
	
	for (1 .. $cnt_rows) {			
		push @table_op_ids,$op_ids[$_ - 1] if $op_ids[$_ - 1] ;
		push @table_op_ids,0 unless $op_ids[$_ - 1] ;
	}
	for ($cnt_rows+1 .. $nr_of_system_names_and_clubs) {
		push @multi_select_op_ids,$op_ids[$_ - 1] if $op_ids[$_ - 1] ;
	}		

	our $quote_completed  = $db{$table}{$i{id}}{quote_completed} ;
	our $quote_accepted   = $db{$table}{$i{id}}{quote_accepted} ;
	our $quote_pending    = $db{$table}{$i{id}}{quote_pending} ;
	our $quote_cancelled  = $db{$table}{$i{id}}{quote_cancelled} ;
	our $quote_rejected   = $db{$table}{$i{id}}{quote_rejected} ;
	
	# our $cancel_butt = ($d_check[2] > $now_ccyymmddhrmnsc && $iaction eq 'edit' && ($quote_completed || $quote_accepted || $quote_pending) && ($glod_user_level > 2 || $is_schools_manager)) ? 1 : 0 ;
	our $cancel_butt = ($iaction eq 'edit' && ($quote_completed || $quote_accepted || $quote_pending) && ($glod_user_level > 2 || $is_schools_manager)) ? 1 : 0 ;
	our $invoice_exists = 1 if $db{$table}{$i{id}}{invoice_nr} ;
	
	# if ($is_schools_manager) {
	if ($is_schools_manager || $glod_user_level < 4) {
		my @ed_from = &common_split_sql_time($db{$table}{$i{id}}{date_from}) ;
		my @d_check = &common_add_delta_dhms($ed_from[0],$ed_from[1],$ed_from[2],$ed_from[3],$ed_from[4],$ed_from[5],0,-18,0,0) ; # go 18 hours back from event start
		
		if ($d_check[2] < $now_ccyymmddhrmnsc) {
			$cancel_butt = 0 ;
		}
	}
	
	# &common_debug("cancel_butt=$cancel_butt [$i{id}] [$db{$table}{$i{id}}{date_from}] [($d_check[2] > $now_ccyymmddhrmnsc && iaction=$iaction eq 'edit' && (quote_completed=$quote_completed || quote_accepted=$quote_accepted || quote_pending=$quote_pending) && (glod_user_level=$glod_user_level > 2 || is_schools_manager=$is_schools_manager))]");
			
	&db_min_ro('events','id,event_quote_nr,category,user_id,startdate,enddate',"event_quote_nr='$db{$table}{$i{id}}{quote_nr}'",'','') ;
	
	$max_cams = $db{$table}{$i{id}}{max_cams} if $db{$table}{$i{id}}{max_cams} ;

	$page_title  = substr($page_title,0,-1) ;
	$page_title .= " : $i{id}" ;
	
	$custom_back_button = qq~&nbsp;<button type="button" class="btn btn-default" onclick="window.location.assign('$useropts{domain}/list-event-quotes')">Back</button>~ ;
	# $custom_back_button = qq~<a class="btn btn-default btn" href="" style="padding: 0px 3px 0px 3px;font-size:12px;$style" $tooltip>$val</a>~ ;

	# our $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab
	&common_min_footer('id',"$lcpage\s");   

	&edit_db_fields ;
	
	$selected{max_cams}{$db{$table}{$i{id}}{max_cams}}               = 'SELECTED';
	$selected{casual_worker}{$db{$table}{$i{id}}{casual_worker}}     = 'SELECTED';
	$selected{casual_worker_2}{$db{$table}{$i{id}}{casual_worker_2}} = 'SELECTED';
	
	# my @assigned_users_a = split(/\:/,$db{$table}{$i{id}}{operator_names_type_a}) ; 
	# my @assigned_users_b = split(/\:/,$db{$table}{$i{id}}{operator_names_type_b}) ; 
	
	# for (@assigned_users_a){ $selected{operator_names_type_a}{$_}  = 'SELECTED'; }
	# for (@assigned_users_b){ $selected{operator_names_type_b}{$_}  = 'SELECTED'; }
	
	# $selected{operator_names_type_b}{$db{$table}{$i{id}}{operator_names_type_b}}	 = 'SELECTED';

	&select_opts($i{id}) ;

	our $saveandexit = 1 ;

	&build_boxes($i{id},'update') ;
		
	&common_min_extra_crumb("filter-$lcpage\s","Search $ucfirstpage\s") if $glod_user_level > 3 ;

	local $all_select_ids_string = join(",",@all_select_ids) ; 
	$trigger_jquery_raw .= qq~\$("$all_select_ids_string").chosen({ allow_single_deselect:true,search_contains: true });~ ; 
	
} #------------------------------------------------------------------------------------------

sub build_boxes {

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

	our @jquery_trigger_fields = () ; 
	our @jquery_custom_vat_ids = () ;
	our @jquery_duty_ids = () ;
	our @jquery_workings_trigger_fields = () ; 

	push @jquery_trigger_fields, 'inputRoe' ;
	push @jquery_workings_trigger_fields, 'inputRoe' ;
	
	for (1 .. 15) {	
		push @jquery_workings_trigger_fields, "checkboxVat_workings_event_$_" ;	
		push @jquery_workings_trigger_fields, "checkboxExcl_workings_event_$_" ;	
		# push @jquery_workings_trigger_fields, "checkboxVat_$_\_workings_casual_users" ;	
		# push @jquery_workings_trigger_fields, "checkboxExcl_$_\_workings_casual_users" ;	
	}
	&tab_curr_symbols;

	foreach $col(keys %required) {
		&common_min_forms_required ;
	}
		
	our $tab_cnt = 0 ;
	
	&tab_load_vars;

	$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'>~ ;
		
			&tab_cnt;
			
			$print_box_content_rows .= qq(<div class="box col-md-12">
			<ul class="nav nav-tabs" id="myTab">);
			
			foreach (sort {$a<=>$b} keys %cntxt) {
				my $tab_name = &tab_names($_) ; my $c_actv = '' ; # if ($_==1) { $c_actv = 'class="active"' ; }
				
				# # if ($is_schools_manager) { 
				# if ($glod_user_level < 4) { 
					# $c_actv = ($_==2) ? 'class="active"' : '' ; 
				# } else {
					# $c_actv = (($_==1 && $db{$table}{$id}{activetab} eq '') || ($db{$table}{$id}{activetab} eq $tab_name)) ? 'class="active"' : '' ; 
				# }	

				$c_actv = ($_==2) ? 'class="active"' : '' ; 
			
				# if ($_==1 && $db{$table}{$id}{activetab} eq '') { 
					# $c_actv = 'class="active"' ; 
				# } elsif ($db{$table}{$id}{activetab} eq $tab_name) { 
					# $c_actv = 'class="active"' ;
				# }
					
				# &common_min_debug("activetab [$tab_name] $c_actv ");
				
				$print_box_content_rows .= qq(<li id="$tab_name" $c_actv><a href="#$cntxt{$_}">$tab_name</a></li>);
				
				$tab_cnt++;
				}
				
			$print_box_content_rows .= qq(</ul>
			<div id="myTabContent" class="tab-content">);
			
			our %tab_sections = () ;
			
			foreach (keys %cntxt) {
				
				my $tab_name = &tab_names($_) ; my $active = '' ; 
				
				# # if ($is_schools_manager) { 
				# if ($glod_user_level < 4) { 
					# $active = ($_==2) ? 'active' : '' ; 
				# } else {
					# $active = (($_==1 && $db{$table}{$id}{activetab} eq '') || ($db{$table}{$id}{activetab} eq $tab_name)) ? 'active' : '' ; 
				# }	
				
				$active = ($_==2) ? 'active' : '' ; 
				
				# if (($_==1) and ($db{$table}{$id}{activetab} eq '')) { 
					# $active = 'active' ; 
				# }
				# elsif ($db{$table}{$id}{activetab} eq $tab_name) { 
					# $active = 'active' ; 
				# }
					
				my $colsleft = 12 ; my $showright = '' ;
					
				if ($cntxt{$_} eq 'one' or $cntxt{$_} eq 'seven') {
					$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,$_);
						$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 class='row' style="margin: 2px 4px 0 -10px;">~ ;				
						$print_box_content_rows .= qq~<div class='col-md-12'>~ ;
							
							if ($id) { 
								$print_box_content_rows .= qq~
									<div class='row'><div class="box col-md-12"><div class="box-inner">
										<div class="box-content" style="height:47px;">~ ;
								$print_box_content_rows .= ($tab_name eq 'Quote') ? qq~<a class='btn btn-primary btn-xs' href="javascript:dlgMdl('$useropts{scripts}/pdf/event_quote_pdf.pl?$id&$_&$tab_sections{$_}','EVENT QUOTE $db{$table}{$id}{quote_nr}','','waybill-dialog');" data-title="Event Quote PDF" data-toggle="tooltip" data-placement="right"><i class="glyphicon glyphicon-print"></i></a>~ : qq~<a class='btn btn-default btn-xs' href="javascript:dlgMdl('$useropts{scripts}/pdf/event_details_pdf.pl?$id&&','EVENT DETAILS $db{$table}{$id}{quote_nr}','','waybill-dialog');" data-title="Event Details PDF" data-toggle="tooltip" data-placement="right"><i class="glyphicon glyphicon-print"></i></a>~ ; 
								$print_box_content_rows .= &common_min_box_foot;
							}
								
						$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>
		<!--/span-->~ ;
					
		$print_box_content_rows .= qq~</div>~ ;
		
		#--------------------------------------------------------------------------

		$print_box_content_rows .= qq~<div class='row'><div class='col-md-12'>~ ;
			&build_boxes_bottom($id);
		$print_box_content_rows .= qq~</div></div>~ ;
		
		#--------------------------------------------------------------------------
	
	our $skip_save_btn = ($quote_completed && $glod_user_level <= 3) ? 1 : 0 ; 
	
	$print_box_content_rows .= &common_min_forms_end($id,$table,$action,$skip) ;

	my $jquery_trigger_ids = '#' . join(",#",@jquery_trigger_fields) ;
	my $jquery_workings_trigger_ids = '#' . join(",#",@jquery_workings_trigger_fields) ;

	my $jq_tab_var = '' ; 
	my $jq_tab = '' ;  
	my $inp_tab_val = '' ; 
	foreach (keys %cntxt) { 
		$jq_tab_var .= qq(var totalTab_$_=0 ; ) ; 
		$jq_tab .= qq(totalTab_$_=0 ; ) ; 
	} # $inp_tab_val .= qq(\$("#inputTotal_tab_$_").val(totalTab_$_.toFixed(2)) ;) ;

	# $trigger_jquery_raw .= qq~
		# \$("#selectCurrency").change(function() {
			# curr_changed=1;
			# curr_changedW=1;
			# console.log("1. curr_changed: "+curr_changed) ;
			# calcCurr();
		# });

		# \$('#event_quotes-form:checkbox').change(function() {
			# calcAll();
		# });

		# function calcCosting(excl,item,qty,usd,conv,vat,ttl) 
			# {		
				# var itval = item.val();
				# var uval  = usd.val();
				# var cval  = conv.val(); // currency amount
				# var qval  = qty.val();
				# var vval  = vat.val();
				# // var tval  = ttl.val();
				
				# if (excl.val() != 0){
					
					# var xval  = 1;
					
				# }
				
				# else if (excl.val() == 0){
					
					# var xval  = 0;
					
				# }
				# //var xval  = excl.val();
				# var dis   = \$("#selectDiscount").val();
				# var roe   = \$("#inputRoe").val(); // getNum()	
				
				# if (!itval) { 
					# calcAll(); 
					# return ; 
				# }
				
				# var arrP  = itval.split(":"); // 3:0.00:100.00:200.00:223.00:223.00:250.00:250.00:200.00 // id:freight:nett:main_price:gross_10_1_50:gross_10_51_plus:gross_20_1_50:gross_20_51_plus:gross_50 // 
				# var list = { freight:arrP[1], nett:arrP[2], main_price:arrP[3], source_admin:arrP[4], perc3:arrP[5], perc5:arrP[6], perc6:arrP[6], perc8:arrP[7], perc10:arrP[8], perc15:arrP[9], perc20:arrP[10] };
				
				# if (!qval) { 
					# qval=1; 
					# qty.val(qval); 
				# } // set quantity if blank
				
				# if (!uval) // set USD amount if no amount
				# {
					# var uval = list.main_price; 
					# if (dis==3 && qval>0)
					# {
						# uval=list.perc3;  
					# }
					# else if (dis==5 && qval>0)
					# {
						# uval=list.perc5;  
					# }
					# else if (dis==6 && qval>0)
					# {
						# uval=list.perc6;  
					# }
					# else if (dis==8 && qval>0)
					# {
						# uval=list.perc8;  
					# }
					# else if (dis==10 && qval>0)
					# {
						# uval=list.perc10;  
					# }
					# else if (dis==15 && qval>0)
					# {
						# uval=list.perc15;  
					# }
					# else if (dis==20 && qval>0)
					# {
						# uval=list.perc20;  
					# }
				# } 
				
				# var usdAmnt  = uval * 1 ;
				# // var currAmnt = usdAmnt / roe ;
				# var currAmnt = usdAmnt * roe ;
				# var ttlAmnt  = currAmnt * qval ;
				
				# usd.val(usdAmnt.toFixed(2)) ; // set USD currency amount
				# conv.val(currAmnt.toFixed(2)) ; // set foreign currency amount
				# ttl.val(ttlAmnt.toFixed(2)) ; // set total amount
				
				# calcAll(); // recalculate the entire sheet
				
				# console.log("COSTINGS CALCCOSTINGS build boxes : USD AMOUNT="+usdAmnt + "CURR AMOUNT="+currAmnt + "TOTAL AMOUNT="+ttlAmnt) ;
				
				# // alert(usdAmnt+'(inputAmount_usd_$field):'+usd+':'+qty+'(inputQty_$field)') ; // 0.00:100.00:200.00:223.00:223.00:250.00:250.00:200.00 // 
			# }

		# function calcCostingWorkings(excl,item,qty,usd,conv,vat) 
			# {		
				# var itvalW = item.val();
				# var uvalW  = usd.val();
				# var cvalW  = conv.val(); // currency amount
				# var qvalW  = qty.val();
				# var vvalW  = vat.val();
				# var xvalW  = excl.val();
				
				# if (excl.val() != 0){		
					# var xvalW = 1 ;
				# }
				# else if (excl.val() == 0){
					# var xvalW = 0 ;
				# }
				
				# // var disW   = \$("#selectDiscount").val();
				# var roeW   = \$("#inputRoe").val(); // getNum()	
				
				# if (!itvalW) { 
					# calcAllWorkings(); 
					# return ; 
				# }
				
				# if (!qvalW) { 
					# qvalW = 1 ; 
					# qtyW.val(qvalW) ; 
				# } // set quantity if blank
				
				# var usdAmntW  = uvalW * 1 ;
				# var currAmntW = usdAmntW * roeW ;
				# var ttlAmntW  = currAmntW * qvalW ;
				
				# usd.val(usdAmntW.toFixed(2)) ; // set USD currency amount
				# // conv.val(currAmntW.toFixed(2)) ; // set foreign currency amount
				# conv.val(ttlAmntW.toFixed(2)) ; // set foreign currency amount
				# // ttl.val(ttlAmntW.toFixed(2)) ; // set total amount
				
				# calcAllWorkings(); // recalculate the entire sheet				
				
				# // console.log("WORKINGS CALCCOSTINGSWORKINGS build boxes : USD AMOUNT="+usdAmntW + "CURR AMOUNT="+currAmntW + "TOTAL AMOUNT="+ttlAmntW) ;
				
				# console.log("calcCostingWorkings tabs: EXCL="+xvalW+", DESCRIPTION="+item+", AMOUNT USD="+uvalW+", QTY="+qvalW+", AMOUNT="+ttlAmntW+", VAT="+vvalW) ;
				
			# }

		# function calcCurr() 
			# {		
				# var roe  = \$("#inputRoe") ;
				# // roe.val(1); // default currency to 1
				# // var curr = \$("#selectCurrency").val() ;	
				# // var url = "$useropts{scripts}/get/get_roe.pl?" + curr ;
				# // \$.get(url, function(json) {
				  # // \$.each(json, function(key, data) {
					# // roe.val(data.sell_rate);
				  # // });
				  # // calcAll();
				# // },
				# // 'json');
			# }
	# ~;

	# $trigger_jquery_raw .= qq~	
		# var currArr = {}; // var vat_total = {} ; var total_total = {} ; var subtotal = {} ; var fs_total = {} ;
		# var currArrW = {};
		
		# $js_curr_arr
		
		# var currVal  = \$("#selectCurrency").val() ;
		# var prevRoe  = '' ;
		# var curRoe   = '' ;
		
		# var currValW  = \$("#selectCurrency").val() ;
		# var prevRoeW  = '' ;
		# var curRoeW  = '' ;
		
		# var grandTtl = 0 ;
		# var grandSub = 0 ;  
		# var grandVat = 0 ; 
		
		# var grandTtlW = 0 ;
		# var grandSubW = 0 ;  
		# var grandVatW = 0 ; 
		
		# $jq_tab_var
		# \$("$jquery_trigger_ids").change(function() {
			# // calcAll();
		# });

		# function calcAll() 
		# {		
			# if (!\$("#selectCurrency\_chosen").val()) { 
				# \$("#selectCurrency\_chosen").val('ZAR'); 
				# \$("#selectCurrency\_chosen").trigger("chosen:updated"); 
			# } 
			
			# if (!\$("#inputRoe").val() || \$("#inputRoe").val() <= 0) { \$("#inputRoe").val(1) ; }
			
			# grandTtl= 0 ; 
			# grandSub = 0 ; 
			# grandVat = 0 ;  

			# $jq_tab
			# $re_calc_jquery
			
			# \$("#inputSub_total").val(grandSub.toFixed(2)) ;
			# \$("#inputVat_total").val(grandVat.toFixed(2)) ;
			# \$("#inputGrand_total").val(grandTtl.toFixed(2)) ;
			# \$("#inputIncome").val(grandTtl.toFixed(2)) ;
			
			# calcProfitLoss() ;
			
			# console.log("COSTINGS CALC_ALL: SUB TOTAL="+grandSub + "VAT TOTAL="+grandVat + "GRAND TOTAL="+grandTtl ) ;
			
			# curr_changed=0;
			# // console.log("2. curr_changed: "+curr_changed) ;
		# }
		
		# // \$("$jquery_workings_trigger_ids").change(function() {
			# ///calcAllWorkings();
		# // });
		
		# function calcAllWorkings() 
		# {
			# if (!\$("#selectCurrency\_chosen").val()) { 
			# \$("#selectCurrency\_chosen").val('ZAR'); 
			# \$("#selectCurrency\_chosen").trigger("chosen:updated"); 
			# } 
			
			# if (!\$("#inputRoe").val()) { \$("#inputRoe").val(1) ;  }
			
			# grandTtlW = 0 ; 
			# grandSubW = 0 ; 
			# grandVatW = 0 ;  
			
			# $re_calc_jqueryW
			
			# \$("#inputTotal_amount_workings_event").val(grandSubW.toFixed(2)) ;
			# \$("#inputTotal_vat_amount_workings_event").val(grandVatW.toFixed(2)) ;
			# \$("#inputTotal_grand_amount_workings_event").val(grandTtlW.toFixed(2)) ;
			# \$("#inputExpenses").val(grandTtlW.toFixed(2)) ; // Profit loss calculation
			
			# calcProfitLoss() ;
			
			# console.log("WORKINGS CALC_ALLWORKINGS: SUB TOTAL="+grandSubW + "VAT TOTAL="+grandVatW + "GRAND TOTAL="+grandTtlW ) ;
			
			# curr_changedW=0;

		# }
		
		# function calcProfitLoss() 
		# {
		
			# let inc = \$("#inputIncome").val() ;
			# let exp = \$("#inputExpenses").val() ;
			
			# let pl = inc - exp ;
			
			# \$("#inputProfit_loss").val(pl.toFixed(2)) ;
		# }
	# ~ ;
		
	# $onload .= qq(onload="calcAll();");
	if ($iaction eq 'add'){ $onload .= qq~onload="calcCurr();"~ ; }
	# $onload .= qq~onload="calcCurr();"~ ;
	
	&build_workings_costings_forms_jquery if $glod_user_level > 4 ; 	
	
} #----------------------------------------------------------------------------------------

sub build_boxes_top {

	my ($id) = @_ ;

	&event_tabs_build_boxes_top($id) ;
	
	$trigger_jquery .= qq~
		
		let qu_to = \$("select[name='quote_to']").val() ;
		var colonIndex = qu_to.indexOf(":") ; var extractedNumber ;
		if (colonIndex !== -1) {
			extractedNumber = qu_to.substring(0, colonIndex);
		} else {
			extractedNumber = qu_to ; 
		}	
		if (extractedNumber != 5) {
			\$("#inputPoc_name").removeAttr("data-validation") ;
			\$("#inputPoc_contact_nr").removeAttr("data-validation") ;
			\$("#selectCategory_id_1").removeAttr("data-validation") ;
			\$("#textareaCategory_1_details").removeAttr("data-validation") ;
			\$("#selectCategory_id_2").removeAttr("data-validation") ;
			\$("#textareaCategory_2_details").removeAttr("data-validation") ;			
			
			\$("label[for='inputPoc_name'] i.glyphicon-asterisk.yellow").remove();
			\$("label[for='inputPoc_contact_nr'] i.glyphicon-asterisk.yellow").remove();
			\$("label[for='selectCategory_id_1'] i.glyphicon-asterisk.yellow").remove();
			\$("label[for='textareaCategory_1_details'] i.glyphicon-asterisk.yellow").remove();
			\$("label[for='selectCategory_id_2'] i.glyphicon-asterisk.yellow").remove();
			\$("label[for='textareaCategory_2_details'] i.glyphicon-asterisk.yellow").remove();		
		}
	~ ;
	
	$trigger_jquery_raw .= qq~
	
		\$("select[name='quote_to']").change(function() {		
			
			let qu_to = \$("select[name='quote_to']").val() ;
			var colonIndex = qu_to.indexOf(":") ; var extractedNumber ;
			if (colonIndex !== -1) {
				extractedNumber = qu_to.substring(0, colonIndex);
			} else {
				extractedNumber = qu_to ; 
			}	
			
			if (extractedNumber != 5) {
				\$("#inputPoc_name").removeAttr("data-validation") ;
				\$("#inputPoc_contact_nr").removeAttr("data-validation") ;
				\$("#selectCategory_id_1").removeAttr("data-validation") ;
				\$("#textareaCategory_1_details").removeAttr("data-validation") ;
				\$("#selectCategory_id_2").removeAttr("data-validation") ;
				\$("#textareaCategory_2_details").removeAttr("data-validation") ;			
				
				\$("label[for='inputPoc_name'] i.glyphicon-asterisk.yellow").remove();
				\$("label[for='inputPoc_contact_nr'] i.glyphicon-asterisk.yellow").remove();
				\$("label[for='selectCategory_id_1'] i.glyphicon-asterisk.yellow").remove();
				\$("label[for='textareaCategory_1_details'] i.glyphicon-asterisk.yellow").remove();
				\$("label[for='selectCategory_id_2'] i.glyphicon-asterisk.yellow").remove();
				\$("label[for='textareaCategory_2_details'] i.glyphicon-asterisk.yellow").remove();			
			} else if (extractedNumber == 5 && \$("label[for='inputPoc_name']").find("i.glyphicon.glyphicon-asterisk.yellow").length === 0) {

				\$("label[for='inputPoc_name']").append('<i class="glyphicon glyphicon-asterisk yellow"></i>') ;
				\$("label[for='inputPoc_contact_nr']").append('<i class="glyphicon glyphicon-asterisk yellow"></i>') ;
				\$("label[for='selectCategory_id_1']").append('<i class="glyphicon glyphicon-asterisk yellow"></i>') ;
				\$("label[for='textareaCategory_1_details']").append('<i class="glyphicon glyphicon-asterisk yellow"></i>') ;
				\$("label[for='selectCategory_id_2']").append('<i class="glyphicon glyphicon-asterisk yellow"></i>') ;
				\$("label[for='textareaCategory_2_details']").append('<i class="glyphicon glyphicon-asterisk yellow"></i>') ;

				\$("#inputPoc_name").attr("data-validation", "required");
				\$("#inputPoc_contact_nr").attr("data-validation", "required");
				\$("#selectCategory_id_1").attr("data-validation", "required");
				\$("#textareaCategory_1_details").attr("data-validation", "required");
				\$("#selectCategory_id_2").attr("data-validation", "required");
				\$("#textareaCategory_2_details").attr("data-validation", "required");
				
			}			
		});	
	~ ; 

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

sub build_boxes_left {

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

	our ($lcol,$fcol) = &common_min_columns(3,6) ;

	&event_tabs_build_qt_left($id,$tab);

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

sub build_boxes_right {

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

	our ($lcol,$fcol) = &common_min_columns(3,6) ;

	&tab_build_qt_right($id,$tab);
	  
} #----------------------------------------------------------------------------------------

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_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,$quote_accepted,$quote_rejected,$quote_cancelled,$daily_operator_ids,$days_active,$quote_completed) = @_ ; 

	my @system_name_ids = split(";",$system_ids) ;		

	# if ($system_ids =~ /f-/ && ($db{$table}{$i{id}}{supplier_ids} !~ /\b62\b/ || $db{$table}{$i{id}}{supplier_type_ids} !~ /\b6\b/)) {
		
		# $system_ids = "" ; 
		# foreach (@system_name_ids) {
			# $system_ids = "$_;" if $_ !~ /f-/ ; 
		# }
		# $system_ids =~ s/;+$// ;
		# @system_name_ids = split(";",$system_ids) ;		
		
	# }
	
	my @club_ids        = split(";",$club_ids) ;	
	our @days_active_arr	= split(/\;/,$days_active) ;
	my @daily_op_ids 	= () ; 
 
	# # my @arr_fixed_system_online_status 			= split(/\;/,$db{$table}{$i{id}}{fixed_system_online_status}) ;
	# # my @arr_fixed_system_network_test  			= split(/\;/,$db{$table}{$i{id}}{fixed_system_network_test}) ;
	# # my @arr_fixed_system_system_test   			= split(/\;/,$db{$table}{$i{id}}{fixed_system_system_test}) ;
	# # my @arr_fixed_system_test_event   			= split(/\;/,$db{$table}{$i{id}}{fixed_system_test_event}) ;
	# # my @arr_fixed_system_sound_test  			= split(/\;/,$db{$table}{$i{id}}{fixed_system_sound_test}) ;
	# # my @arr_fixed_system_overall_status   		= split(/\;/,$db{$table}{$i{id}}{fixed_system_overall_status}) ;
	# # my @arr_fixed_system_additional_comments 	= split(/\;/,$db{$table}{$i{id}}{fixed_system_additional_comments}) ;
	
	# # my @arr_calibrator_amounts_paid				= split(/\;/,$db{$table}{$i{id}}{calibrator_amounts_paid}) ;
	# # my @arr_calibrator_dates_paid               = split(/\;/,$db{$table}{$i{id}}{calibrator_dates_paid}) ;
	# # my @arr_event_system_calibration_ids        = split(/\;/,$db{$table}{$i{id}}{event_system_calibration_ids}) ;
	# # my @arr_event_system_calibration_status     = split(/\;/,$db{$table}{$i{id}}{event_system_calibration_status}) ;
	
	# # my @arr_set_up_groups_head_operator_ids		= split(/\;/,$db{$table}{$i{id}}{set_up_groups_head_operator_ids}) ;
	# # my @arr_set_up_groups_status_ids        	= split(/\;/,$db{$table}{$i{id}}{set_up_groups_status_ids}) ;
	
	# # for (0 .. $nr_of_system_names_and_clubs - 1) {	
		
		# # my $row_cnt = $_ + 1 ; 
		
		# # $arr_fixed_system_online_status[$_] = "" if $arr_fixed_system_online_status[$_] !~ /(\d+)/g && $arr_fixed_system_online_status[$_] !~ /none/ ; 
		# # $arr_fixed_system_network_test[$_] = "" if $arr_fixed_system_network_test[$_] !~ /(\d+)/g && $arr_fixed_system_network_test[$_] !~ /none/ ; 
		# # $arr_fixed_system_system_test[$_] = "" if $arr_fixed_system_system_test[$_] !~ /(\d+)/g && $arr_fixed_system_system_test[$_] !~ /none/ ; 
		# # $arr_fixed_system_test_event[$_] = "" if $arr_fixed_system_test_event[$_] !~ /(\d+)/g && $arr_fixed_system_test_event[$_] !~ /none/ ; 
		# # $arr_fixed_system_sound_test[$_] = "" if $arr_fixed_system_sound_test[$_] !~ /(\d+)/g && $arr_fixed_system_sound_test[$_] !~ /none/ ; 
		# # $arr_fixed_system_overall_status[$_] = "" if $arr_fixed_system_overall_status[$_] !~ /(\d+)/g && $arr_fixed_system_overall_status[$_] !~ /none/ ; 
		# # $arr_fixed_system_additional_comments[$_] = "" if $arr_fixed_system_additional_comments[$_] !~ /(\d+)/g && $arr_fixed_system_additional_comments[$_] !~ /none/ ; 
		
		# # $arr_calibrator_amounts_paid[$_] = "" if $arr_calibrator_amounts_paid[$_] !~ /(\d+)/g && $arr_calibrator_amounts_paid[$_] !~ /none/ ; 
		# # $arr_calibrator_dates_paid[$_] = "" if $arr_calibrator_dates_paid[$_] !~ /(\d+)/g && $arr_calibrator_dates_paid[$_] !~ /none/ ; 
		# # $arr_event_system_calibration_ids[$_] = "" if $arr_event_system_calibration_ids[$_] !~ /(\d+)/g && $arr_event_system_calibration_ids[$_] !~ /none/ ; 
		# # $arr_event_system_calibration_status[$_] = "" if $arr_event_system_calibration_status[$_] !~ /(\d+)/g && $arr_event_system_calibration_status[$_] !~ /none/ ; 
		
		# # $arr_set_up_groups_head_operator_ids[$_] = "" if $arr_set_up_groups_head_operator_ids[$_] !~ /(\d+)/g && $arr_set_up_groups_head_operator_ids[$_] !~ /none/ ; 
		# # $arr_set_up_groups_status_ids[$_] = "" if $arr_set_up_groups_status_ids[$_] !~ /(\d+)/g && $arr_set_up_groups_status_ids[$_] !~ /none/ ; 
		
		# # $system_used{fixed_report}{$row_cnt} = ($arr_fixed_system_online_status[$_] || $arr_fixed_system_network_test[$_] || $arr_fixed_system_system_test[$_] || $arr_fixed_system_test_event[$_] || $arr_fixed_system_sound_test[$_] || $arr_fixed_system_overall_status[$_] || $arr_fixed_system_additional_comments[$_]) ? 1 : 0 ;
		# # $system_used{calibration_report}{$row_cnt} = ($arr_calibrator_amounts_paid[$_] || $arr_calibrator_dates_paid[$_] || $arr_event_system_calibration_ids[$_] || $arr_event_system_calibration_status[$_]) ? 1 : 0 ;
		# # $system_used{set_up_report}{$row_cnt} = ($arr_set_up_groups_head_operator_ids[$_] || $arr_set_up_groups_status_ids[$_]) ? 1 : 0 ;
	
	# # }
	
	# event_system_head_operator_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 ; $active_days_count = 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 ;
			$row_has_daily_op{$system_count} = 1 if $default_op ;
			$row_has_daily_op_1{$system_count} = 1 if $default_op && $active_days_count <= 10 ; 
			$row_has_daily_op_2{$system_count} = 1 if $default_op && $active_days_count > 10 ; 
			$some_row_has_daily_op = 1 if $default_op ; 
			$some_row_has_daily_op_1 = 1 if $default_op && $active_days_count <= 10 ; 
			$some_row_has_daily_op_2 = 1 if $default_op && $active_days_count > 10 ; 
		
		}
	}
	
	$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>~ ;

	my $dlg_operator_ids = '' ;  
	
	# 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>
					$dlg_operator_ids
				</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) {
 
		if ($system_name_ids[$row_cnt - 1] =~ /f-/ && ($db{$table}{$i{id}}{supplier_ids} !~ /\b62\b/ || $db{$table}{$i{id}}{supplier_type_ids} !~ /\b6\b/)) {
			$system_name_ids[$row_cnt - 1] = "" ;
			$system_name_ids[$row_cnt] = "" if $system_name_ids[$row_cnt] =~ /f-/ ;
			$club_ids[$row_cnt - 1] = "" ;
		}
		
		my $select_sys_name = 0 ; my $select_club_name = 0 ; 
		
		$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='extra_heading_$row_cnt'><div class='col-md-2'></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-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>~ : qq~~ ;
		
		$add_form_fields .= qq~<div class='row' id="system_name_row_$row_cnt" style="margin-bottom:3px;display:none;"></div>~ if $row_cnt > 1 && !$system_name_ids[$row_cnt - 1] && !$club_ids[$row_cnt - 1] && !$row_has_daily_op{$row_cnt} && !$table_op_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 || $system_name_ids[$row_cnt - 1] || $club_ids[$row_cnt - 1] || $row_has_daily_op{$row_cnt} || $table_op_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 ($glod_user_level < 3 && ($quote_accepted || $quote_rejected || $quote_cancelled)) {
			# $add_form_fields .= qq~</div>~ if $row_cnt > 1 and not $system_name_ids[$row_cnt - 1] and not $club_ids[$row_cnt - 1] ;
		# }

		if ($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]) {

			# 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-2"></div>~ ; 
				$add_form_fields .= qq~<div class="col-md-4"><div class="row">~ ; 
				$fcol = 4 ;
				
				my $system_id = $system_name_ids[$row_cnt - 1] ;
				$system_id =~ s/f-//g ;
				
				$add_form_fields .= &common_min_form_input_col("system_name_$row_cnt",$db{event_systems}{$system_id}{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>~ ; 
				$fcol = 1 ;
				if ($row_has_daily_op{$row_cnt} && $some_row_has_daily_op) { 
					for (1 .. 20) {
						$readonly{"custom_operator_$row_cnt\_$_"} = "READONLY" ;
						$add_form_fields .= ($days_active_arr[$_ - 1]) ? &common_min_form_input_col("custom_operator_$row_cnt\_$_",$db{users}{$default_op_ids{$row_cnt}{$_}}{name}) : "" ;	
					}  
					 
				} elsif ($row_has_daily_op{$row_cnt} && $some_row_has_daily_op_1) {
					
					my $displayed_dates = 0 ; 
					# $add_form_fields .= qq~</div>~ ;
					
					$input_fields_dates_1 = qq~<div class='row'><div class='col-md-2'></div>~ ; 
					$input_fields_1 = qq~<div class='row'><div class='col-md-2'></div>~ ; 
					$input_fields_dates_2 = qq~~ ; 
					$input_fields_2 = qq~~ ; 
					
					my %date_used = () ; 
					
					for (1 .. 20) {
						if ($days_active_arr[$_ - 1] && $displayed_dates < 10) {
							$input_fields_dates_1 .= qq~<div class='col-md-1'><label class='control-label'>&nbsp;&nbsp;$default_active_event_dates{$_}</label></div>~ ;
							$readonly{"custom_operator_$row_cnt\_$_"} = "READONLY" ;
							$input_fields_1 .= &common_min_form_input_col("custom_operator_$row_cnt\_$_",$db{users}{$default_op_ids{$row_cnt}{$_}}{name}) ;	
							$displayed_dates++ ;
							$date_used{$_} = 1 ; 
						}
					}  
					
					for (11 .. 20) {
						
						if ($days_active_arr[$_ - 1] && !$date_used{$_}) {
							$input_fields_2 = qq~<div class='row'><div class='col-md-2'></div>~ unless $input_fields_2 ; 
							$input_fields_dates_2 = qq~<div class='row'><div class='col-md-2'></div>~ unless $input_fields_dates_2 ; 
							$input_fields_dates_2 .= qq~<div class='col-md-1'><label class='control-label'>&nbsp;&nbsp;$default_active_event_dates{$_}</label></div>~ ;
							$readonly{"custom_operator_$row_cnt\_$_"} = "READONLY" ;
							$input_fields_2 .= &common_min_form_input_col("custom_operator_$row_cnt\_$_",$db{users}{$default_op_ids{$row_cnt}{$_}}{name}) ;	
						} 
					}
					
					$input_fields_1 .= qq~</div>~ ;
					$input_fields_dates_1 .= qq~</div>~ ;
					$input_fields_2 .= qq~</div>~ if $input_fields_2 ;
					$input_fields_dates_2 .= qq~</div>~ if $input_fields_dates_2 ;
					
				}
				
				
				$fcol = 4 ;
				
			} 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{fixed_event_system_id} .= qq~<option value="$_">$event_system_name</option>~ if $db{event_systems}{$_}{system_type} eq 'fixed' ; 
		# $opts{mobile_event_system_id} .= qq~<option value="$_">$event_system_name</option>~ if $db{event_systems}{$_}{system_type} eq 'mobile' ; 
		# $opts{mobile_or_solo_event_system_id}
				
				# $opts{"system_name_$row_cnt"} = (($system_used{fixed_report}{$row_cnt} && $system_used{set_up_report}{$row_cnt}) || ($system_used{fixed_report}{$row_cnt} && $system_used{calibration_report}{$row_cnt})) ? $opts{event_system_id} : ($system_used{fixed_report}{$row_cnt} || $system_name_ids[$row_cnt - 1] =~ /f-/) ? $opts{fixed_event_system_id} : ($system_used{set_up_report}{$row_cnt}) ? $opts{mobile_or_solo_event_system_id} : ($system_used{calibration_report}{$row_cnt}) ? $opts{mobile_event_system_id} : $opts{event_system_id} ; 
				$opts{"system_name_$row_cnt"} = (($system_used{fixed_report}{$row_cnt} && $system_used{set_up_report}{$row_cnt}) || ($system_used{fixed_report}{$row_cnt} && $system_used{calibration_report}{$row_cnt})) ? $opts{event_system_id} : ($system_used{fixed_report}{$row_cnt} || $system_name_ids[$row_cnt - 1] =~ /f-/) ? $opts{fixed_event_system_id} : ($system_used{set_up_report}{$row_cnt}) ? $opts{mobile_or_solo_event_system_id} : ($system_used{calibration_report}{$row_cnt}) ? $opts{mobile_event_system_id} : $opts{event_system_id} ; 
				
				# $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"} = ($system_used{fixed_report}{$row_cnt} || $system_used{set_up_report}{$row_cnt} || $system_used{calibration_report}{$row_cnt}) ? 0 : 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] ;
				$sys_name_id =~ s/f-//g ;
				
				# my $fixed_system_indication = ($system_name_ids[$row_cnt - 1] =~ /f-/) ? qq~<input value="$sys_name_id" name="sss_fixed_systems_$row_cnt">~ : qq~~ ;
				# my $aisa_system_indication = ($system_name_ids[$row_cnt - 1] !~ /f-/) ? qq~<input value="$sys_name_id" name="aisa_fixed_systems_$row_cnt">~ : qq~~ ;
				
				if ($sys_name_id) { 
					$trigger_jquery_raw .= qq~
						\$("#selectSystem_name_$row_cnt").val('$sys_name_id').trigger("chosen:updated") ;	
						orig_selected_system_names["$row_cnt"] = "$sys_name_id" ;
						if (default_cost_item_rates[get_event_cost_id["$sys_name_id"]]) {
							system_with_cost_item_rates_selected = 1 ;
						}
					~ ;
				} 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').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",$sys_name_id) 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 ($glod_user_level > 2) {
					my $clicked_any_button = ($row_cnt == 1) ? "<span id='clicked_any_button' style='display:none;'></span>" : "" ;
					$add_form_fields  .= qq~<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>$clicked_any_button<input type='text' name="clicked_button_$row_cnt" $clicked_op_butt style="display:none;"></span></a></div>~ ;
					push @table_plus_button_ids,"#add_daily_operators_$row_cnt" ;  # my $daily_op_exists = 0 ; 					
				# } 

				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) {
					
					for (1 .. 20) {
						
						# push @daily_op_ids,"#selectCustom_operator_$row_cnt\_$_" ;
						
						my $style_disp = ($row_has_daily_op{$row_cnt} && $days_active_arr[$_ - 1]) ? "" : "style='display:none;'" ;
				
						if (!$row_has_daily_op{$row_cnt} || ($style_disp && $row_has_daily_op{$row_cnt} && $final_day < $_)) {
							$add_form_fields .= qq~<div class="col-md-0" id="day_$row_cnt\_$_" $style_disp></div>~ ;							
						} else {
							 # $style_disp = ($row_has_daily_op{$row_cnt} && $days_active_arr[$_ - 1]) ? "" : "style='display:none;'" ;
							$style_disp = (!$days_active_arr[$_ - 1]) ? "style='display:none;'" : ""  ;
							my $class = ($style_disp) ? 0 : 1 ; 
							push @all_select_ids,"#selectCustom_operator_$row_cnt\_$_" ; #####CHECK!!!!!!!!!!!!!!!!!!!!!!!!!!
							# push @daily_op_ids,"#selectCustom_operator_$row_cnt\_$_" ;
							$add_form_fields .= qq~<div class="col-md-$class" id="day_$row_cnt\_$_" $style_disp><select class="form-control" name="custom_operator_$row_cnt\_$_" id="selectCustom_operator_$row_cnt\_$_" data-rel="chosen" tabindex="$_"><option value=""></option>$opts{operator_ids}</select></div>~ ;

							$trigger_jquery_raw .= qq~ 
								\$("#selectCustom_operator_$row_cnt\_$_").val("$default_op_ids{$row_cnt}{$_}") ; \$("#selectCustom_operator_$row_cnt\_$_").trigger("chosen:updated") ; 
								
								if (!\$("#clicked_any_button").text()) {
									\$("#clicked_any_button").text("1") ;
								}
								if (!\$("input[name='clicked_button_$row_cnt']").val()){
									\$("input[name='clicked_button_$row_cnt']").val("1") ;
								}  
							~ if $default_op_ids{$row_cnt}{$_}  ;							
						}
					}
					
					my $extra_row_hearders_1 = &build_extra_name_row_1($row_cnt,1) ; 

					$add_form_fields .= qq~</div>$extra_row_hearders_1<div class='row' id="system_name_row_$row_cnt\_extra_1" style="display:none;"><div class="col-md-2"></div>~ ;
					for (1 .. 20) {
						$add_form_fields .= qq~<div class="col-md-0" id="day_$row_cnt\_$_\_extra_1" style='display:none;'></div>~ ;
					}
					my $extra_row_hearders_2 = &build_extra_name_row_2($row_cnt,1) ; 
					$add_form_fields .= qq~</div>$extra_row_hearders_2<div class='row' id="system_name_row_$row_cnt\_extra_2" style="display:none;"><div class="col-md-2"></div>~ ;
					for (11 .. 20) {
						$add_form_fields .= qq~<div class="col-md-0" id="day_$row_cnt\_$_\_extra_2" style='display:none;'></div>~ ;
					}
				} else {
					
					for (1 .. 20) {
						$add_form_fields .= qq~<div class="col-md-0" id="day_$row_cnt\_$_" style='display:none;'></div>~ ;
					}	
					# my $extra_row_hearders_1 = ($row_has_daily_op_1{$row_cnt}) ? &build_extra_name_row_1($row_cnt,0) : &build_extra_name_row_1($row_cnt,1) ; 
					# my $extra_row_hearders_1 = ($some_row_has_daily_op_1) ? &build_extra_name_row_1($row_cnt,0) : &build_extra_name_row_1($row_cnt,1) ; 
					my $extra_row_hearders_1 = ($row_has_daily_op_1{$row_cnt}) ? &build_extra_name_row_1($row_cnt,0) : &build_extra_name_row_1($row_cnt,1) ; 

					my $style_disp = ($row_has_daily_op_1{$row_cnt}) ? "" : "style='display:none;'" ;
					# my $style_disp = ($some_row_has_daily_op_1) ? "" : "style='display:none;'" ;
					$add_form_fields .= qq~</div>$extra_row_hearders_1<div class='row' id="system_name_row_$row_cnt\_extra_1" $style_disp><div class="col-md-2"></div>~ ;
					
					my $final_day_in_extra_row_1 = 0 ; 
					foreach (sort {$a <=> $b} keys %date_is_displayed_in_first_extra_row) {
						$final_day_in_extra_row_1 = $_ ; 
					}
					
					for (1 .. 20) {
						
						 # push @daily_op_ids,"#selectCustom_operator_$row_cnt\_$_" ;
						
						if ($_ <= $final_day_in_extra_row_1) {
							
							my $style_disp = ($days_active_arr[$_ - 1]) ? "" : "style='display:none;'" ;
							my $class = ($style_disp) ? 0 : 1 ;
							
							push @all_select_ids,"#selectCustom_operator_$row_cnt\_$_" ; #####CHECK!!!!!!!!!!!!!!!!!!!!!!!!!!
							# push @daily_op_ids,"#selectCustom_operator_$row_cnt\_$_" ;
							$add_form_fields .= qq~<div class="col-md-$class" id="day_$row_cnt\_$_\_extra_1" $style_disp><select class="form-control" name="custom_operator_$row_cnt\_$_" id="selectCustom_operator_$row_cnt\_$_" data-rel="chosen" tabindex="$_"><option value=""></option>$opts{operator_ids}</select></div>~ ;		
	
							$trigger_jquery_raw .= qq~ 
							\$("#selectCustom_operator_$row_cnt\_$_").val("$default_op_ids{$row_cnt}{$_}") ; \$("#selectCustom_operator_$row_cnt\_$_").trigger("chosen:updated") ; 
							
							if (!\$("#clicked_any_button").text()) {
								\$("#clicked_any_button").text("1") ;
							}
							if (!\$("input[name='clicked_button_$row_cnt']").val()){
								\$("input[name='clicked_button_$row_cnt']").val("1") ;
							}  
						~ if $default_op_ids{$row_cnt}{$_}  ;	
						
						} else {
							$add_form_fields .= qq~<div class="col-md-0" id="day_$row_cnt\_$_\_extra_1" style='display:none;'></div>~ ;							
						}
					}
					
					# $style_disp = ($active_days_count >= 10) ? "" : "style='display:none;'" ;
					$style_disp = ($row_has_daily_op_2{$row_cnt}) ? "" : "style='display:none;'" ;
					# $style_disp = ($some_row_has_daily_op_2) ? "" : "style='display:none;'" ;

					my $extra_row_hearders_2 = ($row_has_daily_op_2{$row_cnt}) ? &build_extra_name_row_2($row_cnt,0) : &build_extra_name_row_2($row_cnt,1) ; 
					$add_form_fields .= qq~</div>$extra_row_hearders_2<div class='row' id="system_name_row_$row_cnt\_extra_2" $style_disp><div class="col-md-2"></div>~ ;

					for (11 .. 20) {

						if (!$date_is_displayed_in_first_extra_row{$_} && $days_active_arr[$_ - 1] && $_ <= $final_day) {
						
							push @all_select_ids,"#selectCustom_operator_$row_cnt\_$_" ; #####CHECK!!!!!!!!!!!!!!!!!!!!!!!!!!
							# push @daily_op_ids,"#selectCustom_operator_$row_cnt\_$_" ;
							$add_form_fields .= qq~<div class="col-md-1" id="day_$row_cnt\_$_\_extra_2" ><select class="form-control" name="custom_operator_$row_cnt\_$_" id="selectCustom_operator_$row_cnt\_$_" data-rel="chosen" tabindex="$_"><option value=""></option>$opts{operator_ids}</select></div>~ ;
							$trigger_jquery_raw .= qq~ 
								\$("#selectCustom_operator_$row_cnt\_$_").val("$default_op_ids{$row_cnt}{$_}") ; \$("#selectCustom_operator_$row_cnt\_$_").trigger("chosen:updated") ; 
								
								if (!\$("#clicked_any_button").text()) {
									\$("#clicked_any_button").text("1") ;
								}
								if (!\$("input[name='clicked_button_$row_cnt']").val()){
									\$("input[name='clicked_button_$row_cnt']").val("1") ;
								}  
							~ if $default_op_ids{$row_cnt}{$_}  ;	
						} else {
							$add_form_fields .= qq~<div class="col-md-0" id="day_$row_cnt\_$_\_extra_2" style='display:none;'></div>~ ;							
						}
					}	
				} 
				$select_sys_name = $system_name_ids[$row_cnt] ;
				$select_sys_name = '' unless $select_sys_name ;
			}
			
			$add_form_fields .= qq~</div>$input_fields_dates_1$input_fields_1$input_fields_dates_2$input_fields_2~ ;
			
		} 
		
		# $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 && !$system_name_ids[$row_cnt-1] && !$club_ids[$row_cnt-1] && !$row_has_daily_op{$row_cnt} && !$table_op_ids[$row_cnt - 1]) {
				$note_display_butt = qq~display:none;~ ; 
			}			
			if ($system_name_ids[$row_cnt] || $club_ids[$row_cnt] || $row_has_daily_op{$row_cnt + 1} || $table_op_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>
			~ ;
		} 
		 
		# $trigger_jquery_raw .= qq~ 
			# \$("#btn_system_name_$row_cnt").click(function () {
				# var v = $row_cnt + 1 ; var v2 = $row_cnt + 2 ;		
				# \$("#btn_row_$row_cnt").hide();	
				# if (v < 15 && \$('#system_name_row_'+v2).is(':hidden')) {
					# \$("#btn_row_"+v).show();
				# }
				# \$("#system_name_row_"+v).show();
			# }); 
		# ~ ; 

		# $trigger_jquery .= qq~\$("#$system_name_id$row_cnt\_chosen").css("width","100%");~ ;		
		# $trigger_jquery .= qq~\$("#$club_name_id$row_cnt\_chosen").css("width","100%");~ ;		
		# $trigger_jquery .= qq~\$("#$op_name_id$row_cnt\_chosen").css("width","90%");~ ;		
		
	}

	$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").css("width","100%");~ ;		
		$trigger_jquery .= qq~\$("$event_club_ids_string").css("width","100%");~ ;		
		$trigger_jquery .= qq~\$("$event_operator_ids_string").css("width","90%");~ ;		
		
		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,90,'','') ;
				
				// 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-2'></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-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,search_contains: 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-2'></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-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-2'></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-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 ;
			}
			
			\$("#content").on("click","[id^='btn_system_name_']", function () {
			
			// \$("$plus_button_ids_string").click( function () {
				
				console.log("clicked : btn_system_name_") ; 
				
				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,search_contains: true}) ;
				\$("#selectClub_name_"+v).chosen({allow_single_deselect:true,search_contains: true}) ;
				\$("#selectOperator_id_calibration_"+v).chosen({allow_single_deselect:true,search_contains: true}) ;
				
				// for (let i=1; i<=20; i++) {
					// \$("#selectCustom_operator_"+v+"_"+i).chosen({allow_single_deselect:true,search_contains: true}) ;
					\$(""+custom_operator_ids_list).chosen({allow_single_deselect:true,search_contains: 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) ;
				// }); 
				
				// \$("#system_name_row_"+v).on("change","#selectSystem_name_"+v, function () {
					// console.log("CALLING auto_select_cost_items_in_quote_tab FROM ADDED ROW") ; 
					// auto_select_cost_items_in_quote_tab(this.id) ;	
				// }) ; 	
				
			}); 
			
			
			
			\$("#content").on("click","[id^='add_daily_operators_']", function () {
			
			// \$("$table_plus_button_ids_string").click( function () {
				
				event.preventDefault();
				
				console.log("changed : add_daily_operators_") ; 
				
				// console.log("2 IS HIDDEN : "+\$("#selectCustom_operator_1_1").is(":hidden")) ;
				
				click_add_daily_operator (this.id) ;
				
				// console.log("2 IS HIDDEN : "+\$("#selectCustom_operator_1_1").is(":hidden")) ;
				
				// 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) ; 
				// });
				
			}) ; 
			
			console.log("1 IS HIDDEN : "+\$("#selectCustom_operator_1_1").is(":hidden")) ; 
			
			\$("#content").on("change","[id^='selectCustom_operator_']", function () {
			// \$("$daily_op_ids_string").change( function () {
				
				console.log("changed : selectCustom_operator_") ; 
				
				// console.log("DAILY CHANGE : "+this.id) ; 
				// console.log("2 IS HIDDEN : "+\$("#"+this.id).is(":hidden")) ; 
				
				process_operators_when_selecting_daily_operator(this.id) ; 
			}) ;
						
			\$("#content").on("change","[id^='selectOperator_id_calibration_']", function () {
			// \$("$overall_op_ids_string").change( function () {
				
				console.log("changed : selectOperator_id_calibration_") ; 
				
				deselect_daily_operators(this.id) ;
			}) ;
			
			// let i = 0 ; let orig_selected_system_names = {} ;  const get_event_cost_id = {"63":"24","286":"25"} ; // TESTING
			// let cnt_systems_per_cost_item = {} ;
			
			// while (true) { 
				// i++ ;
				// if (!\$("#system_name_row_"+i).html()) {
					// break ;
				// }
				// orig_selected_system_names[i] = \$("#selectSystem_name_"+i).val() ;
			// }
			
			// \$("#content").on("change","[id^='selectSystem_name_']", function () {
				
			// 	console.log("CALLING auto_select_cost_items_in_quote_tab FROM EXISTING ROW") ; 
			// 	auto_select_cost_items_in_quote_tab(this.id) ;
					
			// }) ; 		
			
			\$("#two").on("change", "[id^=selectClub_name_]", function () {
		
				let row_nr = get_row_nr(this.id) ;
				row_nr = parseInt(row_nr) ;
				
				let system_id = \$("#selectSystem_name_"+row_nr).val() ;
				if (typeof system_id === 'undefined') {
					system_id = 1 ;
				}
					
				if (!system_id) {
					noty({text:'Please Select a System Before a Selecting a Club!',layout:"center",type:"error",timeout:3000}) ;
					\$("#selectClub_name_"+row_nr).val("").trigger("chosen:updated") ;
				} 
			
			}) ;
			
		~ ; 
		
	}
	
	
	

	# 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 = 6 ; 
	
} #----------------------------------------------------------------------------------------

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

# sub build_workings_costings_form {

	# my ($id,$tab,$rcnt,$suffix) = @_ ;
	
	# $tab_sections{$tab} .= "$suffix+$rcnt|" ;

	# $jq_work_cal = qq~
		# var vat_totalW$suffix = 0 ; 
		# var total_totalW$suffix = 0 ; 
		# var subtotalW$suffix = 0 ; 
		# var vat_amountW = 0 ; 
	# ~ ;
	# $jq_fs  = '' ;

	# %cnt_specific_jquery = () ;
		
	# &set_check_boxes_checked($id,$rcnt,"excl",$suffix);
	# &set_check_boxes_checked($id,$rcnt,"vat",$suffix);

	# my $cntloop = 1;
	# my $field = "";
	# my $val = 0;
	
	# my @excl_old = split(";", $db{event_quotes_min}{$id}{"excl_$suffix"}); 
	# my @qty_old = split(";", $db{event_quotes_min}{$id}{"qty_$suffix"});
	# my @vat_old = split(";", $db{event_quotes_min}{$id}{"vat_$suffix"});
	# my @remarks_old		= () ; 
	# my @supplier_old 	= () ; 
	# my @ref_nr_old 		= () ; 
	# my @amount_usd_old 	= () ; 
	# my @amount_ttl_old 	= () ; 
	# my @des_old 		= () ; 
	# my @curr_amnt_cost 	= () ; 
		
	# if ($suffix eq "workings_event") {
		# @remarks_old	= split(/\;/,$db{event_quotes_min}{$id}{remarks_workings_event});
		# @supplier_old 	= split(/\;/,$db{event_quotes_min}{$id}{supplier_workings_event});
		# @ref_nr_old		= split(/\;/,$db{event_quotes_min}{$id}{ref_nr_workings_event});
		# @amount_usd_old	= split(/\;/,$db{event_quotes_min}{$id}{amount_usd_workings_event});
		# @amount_ttl_old	= split(/\;/,$db{event_quotes_min}{$id}{amount_workings_event});		
		# @des_old 		= split(/\;/,$db{event_quotes_min}{$id}{description_workings_event}) ;
	# } else {
		# @amount_usd_old	= split(/\;/,$db{event_quotes_min}{$id}{usd_amnt_costing_event});
		# @amount_ttl_old	= split(/\;/,$db{event_quotes_min}{$id}{item_ttl_costing_event}); 
		# @des_old      	= split(/\;/,$db{event_quotes_min}{$id}{item_costing_event});
		# @curr_amnt_cost	= split(/\;/,$db{event_quotes_min}{$id}{curr_amnt_costing_event});
		# @quote_tab_default_full_half_items = split(/\;/,$db{event_quotes_min}{$id}{quote_tab_default_full_half_items});
	# }
	
	# for (1 .. $rcnt) {

		# $display_style = '' ; 
		# $display_plus_btn = '' ;
		# my $style_display_butt = "" ;
		# unless ($_ == 1 or $des_old[$_ - 1]) { 
			# $display_style = qq~style='display:none;'~ ; 
			# push @btn_ids,"#btn_$suffix\_$_" ;
			# if ( $_>$cntloop ) { 
				# $display_butt = qq~display:none;~ ;  
				# $style_display_butt = qq~style="display:none;"~ ;
			# } else { 
				# $display_butt = '' ; 
			# }
			# $display_plus_btn = ($_>$cntloop) ? qq~<a id="btn_$suffix\_$_" href="#" style="padding-left:16px"></a>~ : qq~<a id="btn_$suffix\_$_" href="#" style="padding-left:16px;$display_butt"><i class="glyphicon glyphicon-plus blue"></i></a>~;		
		# } else { 
			# $cntloop++ ; 
		# }
		
		# $add_form_fields .= qq~<div class='row' id='$suffix\_$_' $display_style>~ ;
		
		# #----------------------------------------------------------------------------------------------------
		
		# if ($des_old[$_-1] || $_ == 1) {
			
			# push @all_select_ids,"#selectDescription_$suffix\_$_" ;
			# push @all_select_ids,"#selectOperator_$suffix\_$_" if $suffix eq "workings_event" ; 	
			
			# $field = "excl_$suffix\_$_" ; 
			# $fcol = 1;
			# # if ($checkit{$field} == 1) { 
			# if ($excl_old[$_ - 1]){
				# $checked = 'CHECKED'; 
			# } elsif (($excl_tick{$_}) and ($iaction eq 'add')) { 
				# $checked = 'CHECKED'; 
			# } else { 
				# $checked = ''; 
			# }
			# $label{$field} = 1;

			# $add_form_fields .= &common_min_form_checkbox_col($field,$checkit{$field},$checked) ;

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

			# $field = "description_$suffix\_$_" ;
			# $fcol = 2;
			# $allow_deselect{$field} = 1;
			# $preferred_title{$field} = "Description $_" ; #if $suffix ne '_workings_casual_users';	
			# # $add_form_fields .= qq~<input name='prev_item_$suffix\_$_' value='$des_old[$_-1]' style='display:none;'>~ . &common_min_form_select_col($field,'') ; 
			# $add_form_fields .= &common_min_form_select_col($field,'') ; 

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

			# if ($suffix eq "workings_event") {
				
				# $field = "operator_$suffix\_$_" ;
				# $fcol = 2;
				# $allow_deselect{$field} = 1;
				# $preferred_title{$field} = "Operator $_" ;	
				# $add_form_fields .= &common_min_form_select_col($field,'') ; 

				# #----------------------------------------------------------------------------------------------------
				
				# $field = "remarks_$suffix\_$_" ;
				# $fcol = 1;
				# $allow_deselect{$field} = 1;
				# $preferred_placeholder{$field} = "Remarks $_" ;	
				# $add_form_fields .= &common_min_form_input_col($field, $remarks_old[$_ - 1]) ;

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

				# $field = "supplier_$suffix\_$_" ;
				# $fcol = 1;
				# $allow_deselect{$field} = 1;
				# $preferred_placeholder{$field} = "Supplier $_" ;
				# $add_form_fields .= &common_min_form_input_col($field,$supplier_old[$_ - 1]) if $suffix ne '_workings_casual_users'; 	

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

				# $field = "ref_nr_$suffix\_$_" ;
				# $fcol = 1;
				# $allow_deselect{$field} = 1;
				# $preferred_placeholder{$field} = "Ref Nr $_" ;	
				# $add_form_fields .= &common_min_form_input_col($field,$ref_nr_old[$_ - 1]) ;

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

			# $field = "qty_$suffix\_$_" ; 
			# # $field .= '_costing_event';
			# $fcol = 1; 
			# $input_style{$field} = qq(style="text-align:right;");
			# $preferred_placeholder{$field} = "Qty $_" ;
			# $val = $qty_old[$_ - 1] ; 
			# unless ($val) { 
				# $val = $def_qty{$_} ; 
			# } 
			# $val = &q_get_val($val) ;
			# $add_form_fields .= &common_min_form_input_col($field,$val) ;
			
			# #----------------------------------------------------------------------------------------------------
			
			# $field = "amount_usd_$suffix\_$_" ; 
			# $fcol = 1; 
			# $input_style{$field} = qq(style="text-align:right;");
			# $val = $amount_usd_old[$_ - 1] ; 
			# unless ($val) { 
				# $val = $def_usd{$_} ;
			# } 
			# $val = &q_get_val($val) ;
			# $preferred_placeholder{$field} = "Amount $_" ;
			# # $excl_on_change{$field} = 1 ;
			# $val = '0.00' unless $val ;
			# $add_form_fields .= &common_min_form_input_col($field,$val,1) ;
			# # $default_cost_item_rates{$_}{full}
			
			# $add_form_fields .= qq~<input style='display:none;' value='1' name='half_$suffix\_$des_old[$_-1]'>~ if $des_old[$_-1] && $amount_usd_old[$_ - 1] eq $default_cost_item_rates{$des_old[$_-1]}{half} ;
			# $add_form_fields .= qq~<input style='display:none;' value='1' name='full_$suffix\_$des_old[$_-1]'>~ if $des_old[$_-1] && $amount_usd_old[$_ - 1] eq $default_cost_item_rates{$des_old[$_-1]}{full} ;
			
			# #----------------------------------------------------------------------------------------------------
			
			# # if ($suffix eq "costing_event") {
				
				# # $field = "curr_amnt_$suffix\_$_" ; 
				# # # $field .= '_costing_event';
				# # $input_style{$field} = qq(style="text-align:right;"); 
				# # $readonly{$field} = 'READONLY' ; # $fcol=2 ;
				# # $preferred_placeholder{$field} = "ZAR Amnt $_" ;
				# # # $val = &q_get_val($db{$table}{$id}{$field}) ;
				# # $val = &q_get_val($curr_amnt_cost[$_ -1]) ;
				# # our $type = 'hidden' ;
				# # $add_form_fields .= &common_min_form_input_col($field,$val,1) ; $type = '' ;
				# # $type = '' ;				
				
			# # }
			
			# # #----------------------------------------------------------------------------------------------------
			
			# $field = "amount_ttl_$suffix\_$_" ; 
			# $input_style{$field} = qq(style="text-align:right;");
			# $val = $amount_ttl_old[$_ - 1] ;
			# $val = &q_get_val($val) ;
			# # $val = &common_commify($val) ;
			# # $val = sprintf("%0.2f",$val) ; 
			# $preferred_placeholder{$field} = "Total Amount $_" ;
			# # $excl_on_change{$field} = 1 ;
			# $readonly{$field} = 'READONLY' ;
			# $val = '0.00' unless $val ;
			# $add_form_fields .= &common_min_form_input_col($field,$val,1) ;
			
			# #----------------------------------------------------------------------------------------------------
			
			# $field = "vat_$suffix\_$_" ; 
			# $fcol=1 ;
			# # if ($checkit{$field} == 1) { 
			# if($vat_old[$_ - 1]){
				# $checked = 'CHECKED'; 
			# } elsif ($iaction eq 'add') { 
				# $checked = 'CHECKED'; 
			# } else { 
				# $checked = ''; 
			# }
			# $label{$field} = 1 ;
			# if ($no_vat{$suffix}) { 
				# $style_field{$field} = 'style="display:none;"' ; 
			# }
			# # $excl_on_change{$field} = 1 ;
			# $add_form_fields .= &common_min_form_checkbox_col($field,$checkit{$field},$checked) ;
			
			# #----------------------------------------------------------------------------------------------------
		
		# } else {	
			# $tindex+=10 if $suffix eq "workings_event" ; 
			# $tindex+=7 if $suffix eq "costing_event" ; 
		# }
		
		# my $display_hidden_input = ($username eq 'handre') ? "" : "style='display:none;'" ; 
		
		# my $f_h_val = substr($quote_tab_default_full_half_items[$_-1],2) ;
		# $add_form_fields .= (substr($quote_tab_default_full_half_items[$_-1],0,2) eq '1:') ? qq~<input name="added_full_day_cost_item_$_" value="$f_h_val" $display_hidden_input>~ : (substr($quote_tab_default_full_half_items[$_-1],0,2) eq '2:') ? qq~<input name="added_half_day_cost_item_$_" value="$f_h_val" $display_hidden_input>~ : qq~~ ;
		# $add_form_fields .= qq~</div>~ ;

		# $add_form_fields .= qq~
			# <div class='row' id="btn_row_$suffix\_$_" $style_display_butt >
				# <div class="col-md-1">
					# $display_plus_btn
				# </div>
			# </div>
		# ~ ;
		
		# my $style_disp_row = ($des_old[$_-1]) ? "" : "style='display:none;'" ;
		# $add_form_fields .= qq~
			# <div class='row' $style_disp_row id = "2_$suffix\_$_">
				# <div class='col-md-12' style="margin:2px 0 0 0">
				# </div>
			# </div>
		# ~ ;
		
	# }

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

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 ($db{$table}{$id}{sss_quote_nr}) {
		
		my $supplier_type_ids = "" ; my $supplier_ids = "" ;
		
		&db_switch_conn('sss') ;
		
		&db_min_raw("
			SELECT id,supplier_type_ids,supplier_ids FROM `event_quotes` WHERE aisa_quote_nr = '$id' LIMIT 1 ;
		") ;
		
		foreach $row (@$rows_array_ref) {  
			$supplier_type_ids 	= @$row[1] ; 
			$db{$table}{$id}{supplier_ids} = @$row[2] ; 
		}

		%selected_multi = () ;
		
		my @supplier_type_ids_arr 	= split(/\;/,$supplier_type_ids) ; 

		foreach (@supplier_type_ids_arr) {
			$db{$table}{$id}{supplier_type_ids} .= qq~$_;~ ;
			$selected_multi{$_} = 'SELECTED' ;
		}
		
		$db{$table}{$id}{supplier_type_ids} =~ s/;+$// ;
		
		# chop $db{$table}{$id}{supplier_type_ids} if $db{$table}{$id}{supplier_type_ids} ;
		
		$multiple{supplier_type_ids} = 1 ;
		
		&common_min_select_opts('supplier_type_ids','supplier_types','name','','','name',"name LIKE 'AI%' AND name <> 'AI'");
		
		&db_switch_conn('aisa') ;		
	}
	 
	our $savjqy = 1 ;
	
	&db_min_ro('event_quotes_min','*',"`id`='$id'",'','') if $id ;
	
	%filter_val = () ; %filter_select_opts = () ;
	# if ($is_schools_manager) {
	# if ($glod_user_level < 4) {
	if ($glod_user_level < 3) {
		$filter_select_opts{'regions'} = 1 ;
		foreach $_reg_id (keys %{$glob_regids{$userid}}) {
			$filter_val{'regions'}{$_reg_id} = 1 ;
		}
	}
	# &common_debug("[$usertype] filter_select_opts = $filter_select_opts{'regions'}") ; 
	
	local $region_id_where = qq~~ ; local @abcd = () ;

	# if ($is_schools_manager) {
	# if ($glod_user_level < 4) {
	if ($glod_user_level < 3) {
		foreach (split(",",$db{users}{$userid}{region_ids})) {
			push @abcd , "`id` = '$_'" ;
		}
	}
	
	$region_id_where = join (" OR ",@abcd) ;
	
	%selected = () ; 
	%selected_multi = () ; 
	
	# $selected_multi{$db{$table}{$id}{region_id}} = 'SELECTED' ;
	
	my $user_extra_filter = ($is_schools_manager || $is_operator) ? join(' OR ', map { "id = '$_'" } keys %{$glob_regids{$userid}}) : '' ;

	$user_extra_filter = 
		($user_extra_filter && $db{$table}{$id}{country_id}) ? "($user_extra_filter) AND country_id='$db{$table}{$id}{country_id}'" : 
		(!$user_extra_filter && $db{$table}{$id}{country_id}) ? "country_id='$db{$table}{$id}{country_id}'" : 
		$user_extra_filter 
	;

	if ($db{$table}{$id}{region_id}) {
		$user_extra_filter .= " OR " if $user_extra_filter ;
		$user_extra_filter .= "`id` = '$db{$table}{$id}{region_id}'" ;
	}

	
	# &common_min_select_opts('region_id','regions','name',$db{$table}{$id}{region_id},'','code',$region_id_where);
	&common_min_select_opts('region_id','regions','name',$db{$table}{$id}{region_id},'','code',$user_extra_filter);
	
	%filter_val = () ; %filter_select_opts = () ;
	
	my $city_where = qq~~ ; @abcd = () ;

	# if ($is_schools_manager) {
	# if ($glod_user_level < 4) {
	if ($glod_user_level < 3) {
		foreach (keys %{$db{regions}}) {
			push @abcd , "`province` = '$db{regions}{$_}{name}'" ;
		}
	}
	$city_where = join (" OR ",@abcd) ;
	
	%selected_multi = () ;
	$multiple{city_id} = 1 ; 
 
	my @cities_ids = split(/\,/,$db{$table}{$id}{city_id});
	foreach (@cities_ids) { 
		$selected_multi{$_} = 'SELECTED' ; 
		# &common_debug("SELECTED sport_type_ids [$_] : [selected=$selected_multi{$_}]") ;
	}

	if ($city_where and $db{regions}{$db{$table}{$id}{region_id}}{name}) {
		$city_where = qq~($city_where) AND `province` = '$db{regions}{$db{$table}{$id}{region_id}}{name}'~ ;
	} elsif (not $city_where and $db{regions}{$db{$table}{$id}{region_id}}{name}) {
		$city_where = qq~`province` = '$db{regions}{$db{$table}{$id}{region_id}}{name}'~ ;
	}
	
	# $user_extra_filter = ($is_schools_manager || $is_operator) ? join(' OR ', map { "region_id = '$_'" } keys %{$glob_regids{$userid}}) : '' ;
	
	$city_filter = join(" OR ", map { "region_id='$_'" } keys %{$db{regions}}) ; 
	
	&common_min_select_opts('city_id','cities','name',$db{$table}{$id}{city_id},'','',$city_filter);
	
	$preferred_title{sport_type_ids} = "Sport Types" ; 
	%selected_multi = () ;
	$multiple{sport_type_ids} = 1; 
	my @sport_type_ids = split(/\,/,$db{$table}{$id}{sport_type_ids});
	foreach (@sport_type_ids) { 
		$selected_multi{$_} = 'SELECTED' ; 
		# &common_debug("SELECTED sport_type_ids [$_] : [selected=$selected_multi{$_}]") ;
	}
	
	# foreach (sort {$db{sport_types}{$a}{name} cmp $db{sport_types}{$b}{name}} keys %{$db{sport_types}}) {
		# $opts{sport_type_ids} .= qq~<option value="$_" $selected_multi{$_}>$db{sport_types}{$_}{name}</option>~ ; 
	# }
	
	&common_min_select_opts('sport_type_ids','sport_types','name',$db{$table}{$id}{sport_type_ids},'','','','','name') ;
 
	$extra_form_fields .= qq~<input type="hidden" name="sporttypeids" id="sport-type-ids" value="">~;
	
	$preferred_title{organisation_ids} = "Venue" ; 
	%selected_multi = () ;
	$multiple{organisation_ids} = 1; 
	my @organisation_ids = split(/\,/,$db{$table}{$i{id}}{organisation_ids});
	foreach (@organisation_ids) { 
		$selected_multi{$_} = 'SELECTED' ; 
		# &common_debug("SELECTED organisation_ids [$_] : [selected=$selected_multi{$_}]") ;
	}
	
	my $organisations_where = qq~~ ; 
	# $organisations_where = qq~`region_code`='$db{regions}{$db{$table}{$i{id}}{region_id}}{code}'~ if $db{regions}{$db{$table}{$i{id}}{region_id}}{code} ; 
	$organisations_where = qq~`region_id`='$db{$table}{$i{id}}{region_id}'~ if $db{$table}{$i{id}}{region_id} ; 

	&common_min_select_opts('organisation_ids','organisations','name',$db{$table}{$i{id}}{organisation_ids},'','',"$city_filter") ;
	$extra_form_fields .= qq~<input type="hidden" name="organisationids" id="organisation-ids" value="">~;
	%selected_multi = () ;
	
	&common_min_select_opts('type','event_types','name',$db{$table}{$id}{type},1,'','');
	
	# my %selected_table = () ;
	
	# if ($usertype ne 'schools_manager') {
	# if ($glod_user_level > 3) {
	# if ($glod_user_level > 2) {

		%selected_multi = () ;
		$preferred_title{operator_ids} = "Operators" ; 
		$multiple{operator_ids} = 1; 
		# my @op_split = split(/;~;/,$db{$table}{$i{id}}{operator_ids}) ; 
		# my @operator_ids = split(/\,/,$op_split[0]);
		# foreach (@operator_ids) {
		# my $cnt_op_ids = 0 ;
		# foreach (@table_op_ids) {
			# $cnt_op_ids++ ;
			# next unless $_ ; 
			# $selected_table{$cnt_op_ids}{$_} = 'SELECTED' ; 
		# }
			
		foreach (@multi_select_op_ids) { 
			$selected_multi{$_} = 'SELECTED' ; # &common_debug("SELECTED operator_ids [$_] : [selected=$selected_multi{$_}]") ;
		}

		&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" $selected_multi{$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>~ ; 	
		}
		
		# &common_min_select_opts('operator_ids','users','name',$db{$table}{$i{id}}{operator_ids},'','',"user_type LIKE 'casual%'") ;
		$extra_form_fields .= qq~<input type="hidden" name="operatorids" id="operator-ids" value="">~;
	
	if ($glod_user_level > 2) {	
		
		%selected_multi = () ;
		
		$multiple{type_details_id} = 1 ;	
		$preferred_title{type_details_id} = "Type Details" ;
		my @type_details_id = split(/\,/,$db{$table}{$i{id}}{type_details_id});
		foreach (@type_details_id) { $selected_multi{$_} = 'SELECTED' ; }		
		&common_min_select_opts('type_details_id','event_type_details','name',$db{$table}{$id}{type_details_id},0,'','');
		$extra_form_fields .= qq~<input type="hidden" name="typedetailsid" id="type-details-ids" value="">~;	
		%selected_multi = () ;
	}
	
	$trigger_jquery .= qq~\$("#selectType\_chosen").css( "width", "80%" );~ ;

	%selected_multi = () ;

	my @currency_arr = qw( currency );

	foreach my $curr (@currency_arr) {
		if ($db{$table}{$id}{$curr}) { 
			$selected{$curr}{$db{$table}{$id}{$curr}} = 'SELECTED'; 
		} else { 
			$selected{$curr}{ZAR} = 'SELECTED'; 
		}
		$select{$curr} = 1 ;
		$opts{$curr}   = qq~
			<option value="GBP" $selected{$curr}{GBP}>GBP</option>
			<option value="USD" $selected{$curr}{USD}>USD</option>
			<option value="ZAR" $selected{$curr}{ZAR}>ZAR</option>
			<option value="EUR" $selected{$curr}{EUR}>EUR</option>~ ; 
	}
		
	# $select{discount} = 1 ;
	# $selected{discount}{$db{$table}{$id}{discount}} = 'SELECTED' ;
	# $opts{discount}   = qq~<option value="3" $selected{discount}{3}>3%</option><option value="5" $selected{discount}{5}>5%</option><option value="6" $selected{discount}{6}>6%</option><option value="8" $selected{discount}{8}>8%</option><option value="10" $selected{discount}{10}>10%</option><option value="15" $selected{discount}{15}>15%</option><option value="20" $selected{discount}{20}>20%</option>~ ; 

	my $selcntry = ($db{$table}{$id}{country_id}) ? $db{$table}{$id}{country_id} : 242 ; # Default South Africa
	# &common_debug("country_id : $db{$table}{$id}{country_id} [$selcntry]") ;
	&common_min_select_opts('country_id','countries','name',$selcntry,1,'country','','id');
			
	# &common_min_select_opts('event_system_id','event_systems','name','',1,'description','') ;
	
	&db_min_ro('event_cost_items','id,rates,full_half_day,excl_from_expenses',"excl_from_expenses = '0'") ; 
	
	&db_min_ro('event_systems','*',"",'','') ; 
	
	&db_min_ro('event_quotes_poc','id,name,contact_nr','','','') ; 
	
	&db_min_ro('event_quotes_recipient','id,name,contact_nr','','','') ; 
	
	
	# our $event_system_id_to_event_cost_item_id_javascript = qq~~ ; 

	our $get_event_cost_id_from_system_id_javascript = qq~~ ;

	foreach (sort {$db{event_systems}{$a}{name} cmp $db{event_systems}{$b}{name}} keys %{$db{event_systems}}) {

		# next if $username eq 'handre' && !$db{event_cost_items}{$db{event_systems}{$_}{event_cost_item_id}}{rates} ;

		my $event_system_name = "$db{event_systems}{$_}{name}" ;
		$event_system_name .= " [$db{event_systems}{$_}{description}]" if $db{event_systems}{$_}{description} ;
		$opts{event_system_id} .= qq~<option value="$_">$event_system_name</option>~ ; 
		$opts{fixed_event_system_id} .= qq~<option value="$_">$event_system_name</option>~ if $db{event_systems}{$_}{system_type} eq 'fixed' ; 
		$opts{mobile_event_system_id} .= qq~<option value="$_">$event_system_name</option>~ if $db{event_systems}{$_}{system_type} eq 'mobile' ; 
		$opts{mobile_or_solo_event_system_id} .= qq~<option value="$_">$event_system_name</option>~ if $db{event_systems}{$_}{system_type} eq 'mobile' || $db{event_systems}{$_}{system_type} eq 'solo' ; 
		$get_event_cost_id_from_system_id_javascript .= qq~"$_":"$db{event_systems}{$_}{event_cost_item_id}",~ ; 
		# $event_system_id_to_event_cost_item_id_javascript .= qq~"$_":"$db{event_systems}{$_}{event_cost_item_id}",~ ; 
		
	}
	# chop $event_system_id_to_event_cost_item_id_javascript if $event_system_id_to_event_cost_item_id_javascript ;
	chop $get_event_cost_id_from_system_id_javascript if $get_event_cost_id_from_system_id_javascript ;
	
	&common_min_select_opts('club_ids','clubs','name','',0,'','') ;
	
	$db{event_quotes}{''}{quote_to} = 5 if $iaction eq 'add' ; # SuperSport Schools (Pty) Ltd
	$onload = qq~onload=dispCustomer();~ if $iaction eq 'add' ; # SuperSport Schools (Pty) Ltd
	
	&event_tabs_customer_select_opts('customers','name','','quote_to');
	
	# our $default_half_day_cost_item_rates_javascript = qq~~ ;
	# our $default_full_day_cost_item_rates_javascript = qq~~ ;
	our $default_cost_item_rates_javascript = qq~~ ;
	our %default_cost_item_rates = () ; 
	
	foreach (keys %{$db{event_cost_items}}) {
		
		my @full_half_split = split(/\;/,$db{event_cost_items}{$_}{full_half_day}) ; 
		my @rates_split = split(/\;/,$db{event_cost_items}{$_}{rates}) ; 
		$default_cost_item_rates{$_}{full} = ($full_half_split[0] eq '1') ? $rates_split[0] : ($full_half_split[1] eq '1') ? $rates_split[1] : "" ;
		$default_cost_item_rates{$_}{half} = ($full_half_split[0] eq '2') ? $rates_split[0] : ($full_half_split[1] eq '2') ? $rates_split[1] : "" ;
		# $default_full_day_cost_item_rates_javascript .= ($full_half_split[0] eq '1') ? qq~"$_":"$rates_split[0]",~ : ($full_half_split[1] eq '1') ? qq~"$_":"$rates_split[1]",~ : qq~~ ;	
		# $default_half_day_cost_item_rates_javascript .= ($full_half_split[0] eq '2') ? qq~"$_":"$rates_split[0]",~ : ($full_half_split[1] eq '2') ? qq~"$_":"$rates_split[1]",~ : qq~~ ;	
		$default_cost_item_rates_javascript .= ($full_half_split[0] eq '1') ? qq~"full,$_":"$rates_split[0]",~ : ($full_half_split[1] eq '1') ? qq~"full,$_":"$rates_split[1]",~ : qq~~ ;	
		$default_cost_item_rates_javascript .= ($full_half_split[0] eq '2') ? qq~"half,$_":"$rates_split[0]",~ : ($full_half_split[1] eq '2') ? qq~"half,$_":"$rates_split[1]",~ : qq~~ ;	
		$event_cost_items_excl_from_expenses .= qq~"$_":"$db{event_cost_items}{$_}{excl_from_expenses}",~ ; 
	
	}
	
	# chop $default_full_day_cost_item_rates_javascript 	if $default_full_day_cost_item_rates_javascript ;
	# chop $default_half_day_cost_item_rates_javascript 	if $default_half_day_cost_item_rates_javascript ;
	chop $event_cost_items_excl_from_expenses 			if $event_cost_items_excl_from_expenses ;
	chop $default_cost_item_rates_javascript 			if $default_cost_item_rates_javascript ;
 
	$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>) ;
	
	# $extra_form_fields = qq~<input type="hidden" name="operators_type_a" id="operators-type-a" value=""><input type="hidden" name="operators_type_b" id="operators-type-b" value="">~;
	
	
	# if ($usertype ne 'schools_manager') {
	# if ($glod_user_level > 3) {
	if ($glod_user_level > 2) {
		# $extra_form_fields .= qq~<input type="hidden" name="event_system_ids" id="event-system-id" value="">~ ;
		$jquery_chosen_sel .= qq~
			let type_val = \$("#selectType_details_id").chosen().val() ;
			\$('#type-details-ids').val(type_val) ;~ ;
		# $jquery_chosen_sel .= qq~
			# var e_sys_val = \$("#selectEvent_system_id").chosen().val() ;
			# \$('#event-system-id').val(e_sys_val) ; ~ ;
	}	
	
	$jquery_chosen_sel .= qq~
		let op_val = \$("#selectOperator_ids").chosen().val() ; 
		\$('#operator-ids').val(op_val) ;  
	~ ;
	
	
	$extra_form_fields .= qq~<input type="hidden" name="city_ids" id="city-id" value="">~ ;
	$jquery_chosen_sel .= qq~
		var e_sys_val = \$("#selectCity_id").chosen().val() ;
		\$('#city-id').val(e_sys_val) ; 
	~ ;
	
	
	$trigger_jquery    .= qq~\$("#selectSport_type_ids_chosen").css( "width", "100%" );~ ;
	$trigger_jquery    .= qq~\$("#selectOrganisation_ids_chosen").css( "width", "100%" );~ ;
	$trigger_jquery    .= qq~\$("#selectRegion_id_chosen").css( "width", "100%" );~ ;
	$trigger_jquery    .= qq~\$("#selectCity_id_chosen").css( "width", "100%" );~ ;
		
	$trigger_jquery_raw .= qq~
	
	\$("#savebutt").click(async function() {    
		
		// console.log("1. Hello World") ; 
		
		let buttonClass = \$(this).attr("class") ;
		if (buttonClass == "btn btn-custom") { 
			return ; 
		}
		
		var we_can_save_form = check_before_saving() ; 
		
		var checkCompleted = \$("#checkboxQuote_completed").is(":checked") ;
		var checkAccepted  = \$("#checkboxQuote_accepted").is(":checked") ;
		var checkPending   = \$("#checkboxQuote_pending").is(":checked") ;
		var checkClosed    = \$("#checkboxQuote_cancelled").is(":checked") ;
		var checkRejected  = \$("#checkboxQuote_rejected").is(":checked") ;
		
		if (!checkCompleted && !checkAccepted && !checkPending && !checkClosed && !checkRejected) {
			noty({text:'Please select one of Completed / Accepted / Pending / Closed / Rejected',layout:"center",type:"error",timeout:3000}) ;
			we_can_save_form = 0 ;
		}

		var system_ids = "" ; var operator_ids = "" ; var seen_sys_id = {} ;

		// if (\$("#selectSystem_name_1").length) {
		
		for (let i = 1; i <= $nr_of_system_names_and_clubs; i++) {			
			let sys_id = \$("#selectSystem_name_"+i).val() ;
			if (\$("#selectSystem_name_"+i).val() && \$("#selectSystem_name_"+i).val() > 0) {		
				if (seen_sys_id[sys_id]) {
					noty({text:"Please do not select the same System Name more than once in Event Details tab",layout:"center",type:"error",timeout:15000}) ;
				}
				seen_sys_id[sys_id] = 1 ; 
				system_ids = system_ids + \$("#selectSystem_name_"+i).val() + ";" ; 	
			}
			// if (\$("#selectOperator_id_calibration_"+i).val()) {
				// operator_ids = operator_ids + \$("#selectOperator_id_calibration_"+i).val() + "," ; 	
			// }
		}
		
		let multi_select = \$("#selectOperator_ids").chosen().val();
		
		// operator_ids = operator_ids+","+multi_select ;
		
		// let first_op_id = 1 ;
		// for (let j = 1; j <= 50; j++) {		
			// if (\$("#selectOperator_"+j+"_workings_event").val()) {
				// if (first_op_id) {
					// operator_ids = operator_ids + "," ;
					// first_op_id = 0 ;
				// }
				// operator_ids = operator_ids + \$("#selectOperator_"+j+"_workings_event").val() + "," ; 	
			// }			
		// }			
		
		if (system_ids)   { system_ids = system_ids.slice(0,-1) ; }
		// if (operator_ids) { operator_ids = operator_ids.slice(0,-1) ; }

		// console.log("system_ids : "+system_ids+" , operator_ids : "+operator_ids) ; 

		var date_from = \$("input[name='date_from']").val();
		var date_to   = \$("input[name='date_to']").val() ;
		var quote_id = '$id' ; 
		
		if (!quote_id) { quote_id = -1 ; }
		
		// console.log("url_check_periods="+url_check_periods) ; 
		
		var noty_msg_sys = "" ; var noty_msg_ops = "" ;
		
		// if (system_ids || operator_ids) {
		if (system_ids) {
			
			var url_check_periods = "$useropts{scripts}/get/get_event_quote_conflicts_test.pl?date_from="+date_from+"&date_to="+date_to+"&system_ids="+system_ids+"&op_ids="+operator_ids+"&quote_id="+quote_id ;

			await \$.get(url_check_periods, function(json) { 
				let system_cnt = 0 ; 
				\$.each(json, function(key, data) {  
					 
					let systems = "" ; let days = "" ; let multiple_systems = "" ;
					
					for (let system_cnt=1;system_cnt<=15;system_cnt++) {
						let system_key = "system_"+system_cnt ;
						if (data[system_key] && systems) {
							multiple_systems = "s" ;
							systems = systems + ',' + data[system_key]
						} else if (data[system_key] && !systems) {
							systems = data[system_key] ;
						} else {
							break ;
						} 
					}
					for (let day_cnt=1;day_cnt<=20;day_cnt++) {
						let interval_key = "date_interval_day_"+day_cnt ;  
						if (data[interval_key] && days) {
							days = days + ',' + data[interval_key] ;
						} else if (data[interval_key] && !days) {
							days = data[interval_key] ;
						} 
					}					
					
					noty_msg_sys = "Event "+data.event+" Uses System"+multiple_systems+" "+systems+" On "+days ;

				});
			}
			,'json') ; 
			
		}
		
		if (noty_msg_sys) {		
			noty({text:noty_msg_sys,layout:"center",type:"error",timeout:15000}) ;
			we_can_save_form = 0 ; 
		}
 
		if (noty_msg_ops) {		
			noty({text:noty_msg_ops,layout:"center",type:"error",timeout:15000}) ;
			// we_can_save_form = 0 ; 
		}
		
		// console.log("we_can_save_form : "+we_can_save_form) ; 
		
		if (we_can_save_form) {
			\$('#event_quotes-form').submit() ;
		} else {
			return ; 
		}
	}) ;
	
	// \$("#savebutt").hover(function() {
		// let buttonClass = \$(this).attr("class") ; 
		// if (buttonClass == "btn btn-custom") { 
			 // \$("#tooltip").css("position","absolute") ; 
			 // \$("#tooltip").css("top","-50%") ; 
			 // \$("#tooltip").css("left","1%") ; 
			 // // \$("#tooltip").css("","") ; 
			 // // \$("#tooltip").css("","") ; 
			 
			 // // position: absolute; /* Absolute positioning relative to button */
  // // top: 100%; /* Position below the button */
  // // left: 50%; /* Center horizontally */
  // // transform: translateX(-50%); /* Center horizontally (alternative) */
  // // padding: 5px; /* Add some padding to the tooltip */
  // // background-color: #ddd; /* Tooltip background color */
  // // border-radius: 5px; /* Add rounded corners */
  // // box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
		// }
	// });
	
	// \$("#cancelbutt").hover(function() {
		// let buttonClass = \$(this).attr("class") ; 
		// if (buttonClass == "btn btn-custom") { 
			 // # \$(this).append("<span>Hello, World!</span>");
		// }
	// });
	
	
	\$("#cancelbutt").click(function() { 
		
		let buttonClass = \$(this).attr("class") ; 
		if (buttonClass == "btn btn-custom") { 
			return ; 
		}
		
		var we_can_save_form = check_before_saving() ; 
		
		if (we_can_save_form) {
			cancel_quote() ; 		
		} else {
			return ; 
		}		
		
	}) ;
	
	function cancel_quote () {

		BootstrapDialog.confirm({
			title: 'Confirm Cancellation',
			message: 'Are you sure you want to cancel this event?',
			type: BootstrapDialog.TYPE_DANGER, // <-- Default value is BootstrapDialog.TYPE_PRIMARY <-- Default value is BootstrapDialog.TYPE_WARNING
			callback: function(result) {            
				if (result) {
					\$("#checkboxQuote_completed").prop("checked", false) ;
					\$("#checkboxQuote_accepted").prop("checked", false) ;
					\$("#checkboxQuote_pending").prop("checked", false) ;
					\$("#checkboxQuote_rejected").prop("checked", false) ;
					\$("#checkboxQuote_cancelled").prop("checked", true) ;
					\$('#event_quotes-form').submit() ;
				}
			}
		});
	}
		
	function check_before_saving () {
		
		for (let i = 1; i <= 20; i++) {
			if (\$("#selectDescription_workings_event_"+i).val() ==  14 && !\$("#selectOperator_workings_event_"+i).val()) {
				noty({text:"Please select an Operator in Line "+i+" in the Expenses Tab",layout:"center",type:"error",timeout:3000}) ;
				return 0 ; 				
			}
		}
		
		$jquery_chosen_sel

		let st_val = \$("#selectSport_type_ids").chosen().val() ;
		\$('#sport-type-ids').val(st_val) ;
		
		let or_val = \$("#selectOrganisation_ids").chosen().val() ;
		\$('#organisation-ids').val(or_val) ;
		
		let sup_val = \$("#selectSupplier_type_ids").chosen().val() ;
		\$('#supplier-type-ids').val(sup_val) ;

		var dateFromStr = \$("input[name='date_from']").val();
		var dateToStr   = \$("input[name='date_to']").val();
	
		var dateFrom    = new Date(dateFromStr);
		var dateTo      = new Date(dateToStr);
		
		if (dateFrom >= dateTo) {
			noty({text:'`Event Date/Time From` must be before the `Event Date/Time To`',layout:"center",type:"error",timeout:3000}) ;
			return 0 ;
		} 
		return 1 ;
	}
	
	~ ;

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

sub page_opts {

	our $glyphicon     = 'global' ;
	our $lcpage        = 'event-quote' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ;
	our $table         = 'event_quotes' ;
	
	our $cust_cols     = 1 ; # display _blank_3.pm
	our $savjqy        = 1 ; 
	our $max_cams      = 10 ;

	&common_min_add_box_icon ;
	
	our %casuals       = (); 

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

sub creat_db_cols {

	&db_min_ro('event_quotes','*','','','') ;

	my %col_exists ;

	foreach (sort { $col_name{$a} cmp $col_name{$b} } keys %col_name) {
		$col = $col_name{$_} ;
		$col_exists{$col} = 1 ;
	}
		
	my $mysql = "ALTER TABLE  `event_quotes`" ;

	foreach (sort keys %i) { 
		if ($_ eq 'iaction') { next ; }
		
		if ($ignore{$_})     { next ; }
		if ($col_exists{$_}) { next ; } # only create the column if it doesn't exist
		
		if (((substr($_,0,3) eq 'vat') or (substr($_,0,4) eq 'excl')) and (substr($_,0,9) ne 'vat_total')) {
			$mysql .= qq~
			ADD  `$_` INT(1) NOT NULL DEFAULT '0',~ ; 
			} elsif ($_ =~ /qty_/g) {
			 $mysql .= qq~
			ADD  `$_` INT(3) NULL DEFAULT '0',~ ; 
			} elsif ($_ =~ /roe_/g) {
			 $mysql .= qq~
			ADD  `$_` VARCHAR( 120 ) NOT NULL ,~ ;  
			} elsif ($_ =~ /description_/g) {
			 $mysql .= qq~
			ADD  `$_` VARCHAR( 255 ) NOT NULL ,~ ;  
			} elsif (substr($_,0,3) eq 'roe') {
			 $mysql .= qq~
			ADD  `$_` DECIMAL(4,2) NOT NULL ,~ ;  # 999999.99 to -999999.99
			} elsif ($_ =~ /date_/g or $_ =~ /_date/g) {
			 $mysql .= qq~
			ADD  `$_` DATE DEFAULT NULL ,~ ; 
			} elsif ($_ =~ /datetime/g) {
			 $mysql .= qq~
			ADD  `$_` datetime DEFAULT NULL ,~ ; 
			} elsif ($_ =~ /_costing_/g or $_ =~ /_total/g or $_ =~ /total_/g or $_ =~ /year_/g or $_ =~ /_amnt_/g) { # } elsif (substr($_,0,5) eq 'item_') {
			 $mysql .= qq~
			ADD  `$_` DECIMAL( 13, 2 ) NOT NULL ,~ ;  # 999999.99 to -999999.99
			} elsif ($_ =~ /_included/g) { 
				$mysql .= qq~
			ADD  `$_` TEXT NOT NULL ,~ ;  
			} elsif ($_ =~ /_id/g) { 
				$mysql .= qq~
			ADD  `$_` INT( 6 ) NOT NULL DEFAULT '0',~ ; 
			} else {
				$mysql .= qq~
			ADD  `$_` VARCHAR( 120 ) NOT NULL ,~ ;  
		}
	}
		
	print $mysql ; 
	exit ;

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

sub report_ifields {
		
	if ($i{quote_to}) {
		push @report_sql, "(q.quote_to = '$i{quote_to}')" ;
		push @report_results, "quote_to = $i{quote_to}" ;
	}	
		
	if ($i{quotes_from} and $i{quotes_to}) { # check dates
		my $quotes_from_check = $i{quotes_from} ;
		   $quotes_from_check =~ s/\-//g ;
		my $quotes_to_check = $i{quotes_to} ;
		   $quotes_to_check =~ s/\-//g ;
		if ($quotes_from_check > $quotes_to_check) { 
			$error = qq(QUOTES FROM ($i{quotes_from}) > QUOTES TO ($i{quotes_to})) ; 
			&filter_screen ; 
		}
	}
		
	# if ($i{event_from} and $i{event_to}) { # check dates
		# my $event_from_check = $i{event_from} ;
		   # $event_from_check =~ s/\-//g ;
		# my $event_to_check = $i{event_to} ;
		   # $event_to_check =~ s/\-//g ;
		# if ($event_from_check > $event_to_check) { 
			# $error = qq(QUOTES FROM ($i{event_from}) > QUOTES TO ($i{event_to})) ; 
			# &filter_screen ; 
		# }
	# }
		
	# if ($i{event_from}) {
		# push @report_sql, "(q.date_from >= '$i{event_from}')" ;
		# push @report_results, "date_from >= $i{event_from}" ;
	# }

	# if ($i{event_to}) {
		# push @report_sql, "(q.date_from <= '$i{event_to}')" ;
		# push @report_results, "date_from <= $i{event_to}" ;
	# }
	
	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{quotes_from}) {
		push @report_sql, "(q.quote_date >= '$i{quotes_from}')" ;
		push @report_results, "quote_date >= $i{quotes_from}" ;
	}

	if ($i{quotes_to}) {
		push @report_sql, "(q.quote_date <= '$i{quotes_to}')" ;
		push @report_results, "quote_date <= $i{quotes_to}" ;
	}
		
	if ($i{po_nr}) {
		push @report_sql, "(q.po_nr LIKE '%$i{po_nr}%')" ;
		push @report_results, "po_nr LIKE `$i{po_nr}`" ;
	}
		
	if ($i{invoice_nr}) {
		push @report_sql, "(q.invoice_nr LIKE '%$i{invoice_nr}%')" ;
		push @report_results, "invoice_nr LIKE `$i{invoice_nr}`" ;
	}
		
	if ($i{quote_nr}) {
		push @report_sql, "(q.quote_nr LIKE '%$i{quote_nr}%')" ;
		push @report_results, "quote_nr LIKE `$i{quote_nr}`" ;
	}
		
	if ($i{country}) {
		push @report_sql, "(q.country_id = '$i{country}')" ;
		push @report_results, "country_id = `$i{country}`" ;
	}
	if ($i{customer_name}) {
		push @report_sql, "(q.quote_to = '$i{customer_name}')" ;
		&db_min_ro('customers','id,name',"`id`='$i{customer_name}'",'','') ;
		push @report_results, "customer = `$db{customers}{$i{customer_name}}{name}`" ;
	}
	                                  
	if ($i{accepted} || $i{options} eq 'accepted') {
		push @report_sql, "(q.quote_accepted='1' AND q.quote_completed<>'1')" ;
		push @report_results, "quote_accepted = `Yes`" ;
	}
	
	if ($i{completed} || $i{options} eq 'completed') {
		push @report_sql, "(q.quote_completed='1')" ;
		push @report_results, "quote_completed = `Yes`" ;
	}
	
	elsif ($i{closed} || $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}) {
		push @report_results, "quote = `$i{options}`" ;
	}
		
	$preferred_title{region_id} = "Region" ;
	$preferred_title{city_id} = "City" ;
	$preferred_title{organisation_ids} = "Venue" ;
	$preferred_title{sport_type_ids} = "Sport Type" ;	
	
	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{type}) {
		push @report_sql, "(q.type='$i{type}')" ;
		push @report_results, "type = `$i{type}`" ;
	}
	
	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} ; 
	}
	
	$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' ;

	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') ;
	
	$allow_deselect{customer_name} = 1 ;
	$allow_deselect{country} = 1 ;
	$allow_deselect{type} = 1 ;
	$allow_deselect{region_id} = 1 ;
	$allow_deselect{city_id} = 1 ;
	$allow_deselect{organisation_ids} = 1 ;
	$allow_deselect{sport_type_ids} = 1 ;
	
	&common_min_select_opts('customer_name','customers','name','','','',"events='1'") ;
	$print_box_content_rows .= &common_min_form_select('customer_name','') ;
	$print_box_content_rows .= &common_min_form_input('quote_nr','') ;
	# $print_box_content_rows .= &common_min_form_datepicker('quotes_from','') ; $preferred_title{quotes_from} = 'Quote Date From' ;
	# $print_box_content_rows .= &common_min_form_datepicker('quotes_to','') ;   $preferred_title{quotes_to} = 'Quote Date To'     ;
	$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)   ; 
	# $print_box_content_rows .= &common_min_form_input('po_nr','') ;
	$print_box_content_rows .= &common_min_form_input('invoice_nr','') ;
	&common_min_select_opts('country','countries','name','','','','') ;
	$print_box_content_rows .= &common_min_form_select('country','') ;
	$print_box_content_rows .= &common_min_form_checkbox('accepted','','') ; # Display all event_quotes that is Accepted
	$print_box_content_rows .= &common_min_form_checkbox('closed','','') ; # Display all event_quotes that is Cancelled
	
	&common_min_select_opts('type','event_types','name','','','','') ;
	$print_box_content_rows .= &common_min_form_select('type','') ;
	
	&common_min_select_opts('region_id','regions','name','','','','');
	
	&common_min_select_opts('city_id','cities','name','','','','');
	&common_min_select_opts('organisation_ids','organisations','name','','','','') ;
	&common_min_select_opts('sport_type_ids','sport_types','name','','','','') ;
	
	$preferred_title{region_id} = "Region" ;
	$preferred_title{city_id} = "City" ;
	$preferred_title{organisation_ids} = "Venue" ;
	$preferred_title{sport_type_ids} = "Sport Type" ;
	
	# $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,search_contains: true});~ ; 
	
	&common_min_search_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') ;
    
	$allow_deselect{customer_name} = 1 ;
	$allow_deselect{options} = 1 ;
	$allow_deselect{system_id} = 1 ;
	$allow_deselect{region_id} = 1 ;
	$allow_deselect{city_id} = 1 ;
	$allow_deselect{organisation_ids} = 1 ;
	$allow_deselect{sport_type_ids} = 1 ;
	
	my $defualt_customer = 0 ; $defualt_customer = 5 if $usertype ne 'school_manager' ; 
	&common_min_select_opts('customer_name','customers','name',$defualt_customer,'','',"events='1'") ;
	$print_box_content_rows .= &common_min_form_select('customer_name','') ;
	
	# $preferred_title{quotes_from} = 'Quote Date From' ;
    # $print_box_content_rows .= &common_min_form_datepicker('quotes_from','') ; 
    # $preferred_title{quotes_to} = 'Quote Date To'     ;
	# $print_box_content_rows .= &common_min_form_datepicker('quotes_to','')   ; 
	
	$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)   ; 
	
	# &common_min_select_opts('type','event_types','name','','','','');
	# $print_box_content_rows .= &common_min_form_select('type','') ;
	
	# my $options_selected = 'SELECTED' if $useropts{boss}{$username} or $useropts{super}{$username} ;
    
	$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','name','','','','') ;
	&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{region_id} = "Region" ;
	$preferred_title{city_id} = "City" ;
	$preferred_title{organisation_ids} = "Venue" ;
	$preferred_title{sports_type_ids} = "Sport Type" ;
	
	&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,search_contains: 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 ;