#!/usr/bin/perl

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

require cfg ;

print header; # CGI.pm method

use POSIX;

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

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

our $qid     = $ARGV[0] ;
our $qaction = $ARGV[1] ;

if ($qid eq 'event') {
	$qid     = $qaction ;
	$qaction = 'view' ;
}

our ($q)        = CGI -> new() ;
$iaction        = $q -> param('iaction')       || $qaction ;
$id             = $q -> param('id')            || $qid ;

our $dialog = 1 ;

#------------------------------------------------------------------------------------------
our $savjqy = 1 ;
our $addbkb = 1 ;
# our $testing = 1 ;
# our $debug = 1 ;
our $max_operators = 15 ;

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

# &common_debug("dialog/events.pl [$iaction]") ;

&today ;

#-------- page opts --------------------------------------------------------------------------------------------------------------------------------------------------

$table = 'events' ;

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

if ($iaction eq '') {
    &load_events ;
    &screen1 ;
}
    
if ($iaction eq 'add') {
    &add_form; 
    &screen2 ;
}
    
if ($iaction eq 'edit') {
    &common_min_load_params ;
    &edit_form; 
    &screen2 ;
}
    
if ($iaction eq 'save') {
    &common_min_load_params ;
    &insert_events ;
    &screen3 ;
}
    
if ($iaction eq 'update') {
    &common_min_load_params ;
    &update_events ;
    &screen3 ;
}
    
if ($iaction eq 'delete') {
    &common_min_load_params ;
    &delete_events ;
    &screen3 ;   
}
	
if ($iaction eq 'view') {
    &common_min_load_params ;
    &view_form; 
    &screen2 ; 
}
	
if ($iaction eq 'available' or $iaction eq 'unavailable' or $iaction eq 'confirm') {
    &common_min_load_params ;
    &update_events_staff ;
    &screen3 ;
}
    
# if ($iaction eq 'saveoperator'){
    # &common_min_load_params ;
    # &save_operator ;
    # &screen3 ;
    # }
    
exit ;

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

# sub save_operator {
	
	# $ignore{iaction} = 1 ;
	# $ignore{event_quote_nr} = 1 ;
	
	# &db_open_upd ;
		# our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it
	
		# @operators_a = split(/\,/,$i{operators_type_a}) ;
		# @operators_b = split(/\,/,$i{operators_type_b}) ;
		
		# my %selected_operator_a = () ; 
		# my %selected_operator_b = () ; 

		# for (@operators_a) {
			# $selected_operators{$_} = 1; 
		# }
		# for (@operators_b) {
			# $selected_operators{$_} = 1; 
		# }
		# my %operator_type = () ; 
		# &db_min_ro('users','id,user_type',"user_type LIKE 'casual%'",'','') ;
		# foreach (keys %{$db{users}}) { 
			# $operator_type{$_} = uc substr($db{users}{$_}{user_type},-1,1) ; 
		# }

		# # my @db_operators_a = () ; foreach (@operators_a) { push @db_operators_a, $_ ; }
		# # my @db_operators_b = () ; foreach (@operators_b) { push @db_operators_b, $_ ; }

		# # my $operators_a = join(',',@db_operators_a) ;
		# # my $operators_b = join(',',@db_operators_b) ;

		# $ignore{operators_type_a} = 1 ;
		# $ignore{operators_type_b} = 1 ;
		
		# %exist_col = () ;
		
		# # for (1 .. $max_operators) { 
		# push @sql_fields, "operator_workings_event" ; 
		# push @sql_fields, "description_workings_event" ; 
		# push @sql_fields, "qty_workings_event" ; 
		# push @sql_fields, "amount_usd_workings_event" ; 
		# # }
		
		# my $select = join(",", @sql_fields) ;

		# &db_min_ro('event_quotes_min',"id,$select","quote_nr='$i{event_quote_nr}'",'','') ;
		
		# my %seen_operator = () ; 
		# my $first_avail_col = 0 ;
		# my $col = 0 ; 
		# my @deselected_operator_a = () ; 
		# my @deselected_operator_b = () ; 
		
		# # for (1 .. $max_operators) { 
			# # $col = $max_operators - $_ + 1 ; 
			# # last if $db{event_quotes}{$i{event_quote_nr}}{"description_$col\_workings_event"} ; 
			# # $first_avail_col = $col ;
		# # }
		# # for (1 .. $max_operators) {
		# my $op_id = $db{event_quotes}{$i{event_quote_nr}}{"operator_$_\_workings_event"} ; 
		# if ($op_id and not $selected_operators{$op_id}){
			# $i{"operator_$_\_workings_event"} = '' ;
			# $i{"description_$_\_workings_event"} = '' ;
			# $i{"qty_$_\_workings_event"} = 0 ;
			# $i{"amount_usd_$_\_workings_event"} = '0.00' ;
			# # }
			# # next unless $op_id ; 
			# # $seen_operator{$op_id} = 1 ;	
		# } 
		# # }
		
		# my @new_operators_a = () ; 
		# my @new_operators_b = () ; 
		
		# for (@operators_a){
			# next if $seen_operator{$_} ;
			# push @new_operators_a, $_ ; 
		# }

		# for (@operators_b){
			# next if $seen_operator{$_} ;
			# push @new_operators_b, $_ ; 
		# }
		
		# for (@new_operators_a){
			# $i{"qty_workings_event"} = 1 ;
			# $i{"amount_usd_workings_event"} = '0.00' ;
			# $i{"operator_workings_event"} = $_ ;
			# $i{"description_workings_event"} = '14' ;
			# $first_avail_col++;
		# }
		# for (@new_operators_b){	
			# $i{"qty_workings_event"} = 1  ;
			# $i{"amount_usd_workings_event"} = '0.00' ;
			# $i{"operator_workings_event"} = $_ ;
			# $i{"description_workings_event"} = '14' ;
			# $first_avail_col++;	
		# }
		
		# &db_min_upd('event_quotes',"quote_nr='$i{event_quote_nr}'") ;
		
		# # foreach (keys %i) { 
			# # if (substr($_,0,3) eq 'new') { next ; } 
			# # if ($ignore{$_}) { next ; } 
			# # if ($hidden{$_} == 1) { next ; }     
			# # if ($i{$_} =~ /\"/) { $set .= qq(`$_`='$i{$_}',) ; } elsif ($i{$_} eq 'NULL') { $set .= qq(`$_`=$i{$_},) ; } else { $set .= qq(`$_`="$i{$_}",) ; }    
		# # }
		
		# # &common_debug("UPDATE event_quotes SET $set WHERE quote_nr='$i{event_quote_nr}'") ;
		
	
	
		# # # for (1 .. $max_operators) {
		# # for $op_cnt ($max_operators .. 1) {
			# # my $ex_col = "operator_$op_cnt\_workings_event" ;
			# # my $op_id  = $db{event_quotes}{$eid}{$ex_col} ;
			# # # next unless $op_id ;
			# # $first_avail_col = $op_cnt unless $op_id ;
			
			# # foreach $op_a (@operators_a) { 
				# # if ($op_a eq $op_id) {
					# # $exist_col{$op_a} = $ex_col ;
				# # }
			# # }
			# # foreach $op_b (@operators_b) { 
				# # if ($op_b eq $op_id) {
					# # $exist_col{$op_b} = $ex_col ;
				# # }
			# # }
		# # }
	# # }
	
	# # # return unless $exist_col ;
	
	# # local $avail_col = ($first_avail_col) ? $first_avail_col : 1 ;
	
		# # foreach (@operators_a) { 
			# # next if $exist_col{$_} ;
			# # local $field = "operator_$avail_col\_workings_event" ;
			# # $i{$field} = $_ ;
			# # # &db_min_upd('event_quotes',"quote_nr='$i{event_quote_nr}'") ;
			
			# # $avail_col++
		# # }
		
		# # foreach (@operators_b) { 
			# # next if $exist_col{$_} ;
			# # local $field = "operator_$avail_col\_workings_event" ;
			# # $i{$field} = $_ ;
			# # # &db_min_upd('event_quotes',"quote_nr='$i{event_quote_nr}'") ;
			# # $avail_col++
		# # }
		
		# $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it
	# &db_close_conn ;
	
	# # exit ;

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

# sub process_operators {

# @operators_a = split(/\,/,$i{operators_type_a}) ;
# @operators_b = split(/\,/,$i{operators_type_b}) ;

# my @db_operators_a = () ; foreach (@operators_a) { push @db_operators_a, $_ ; }
# my @db_operators_b = () ; foreach (@operators_b) { push @db_operators_b, $_ ; }

# my $operators_a = join(',',@db_operators_a) ;
# my $operators_b = join(',',@db_operators_b) ;

# $ignore{operators_type_a} = 1 ;
# $ignore{operators_type_b} = 1 ;

# # $i{operator_names_type_a} = $operators_a ;
# # $i{operator_names_type_b} = $operators_b ;
    
# } #------------------------------------------------------------------------------------------

sub update_events_staff {
	
	# local $exist_col = '' ;
	# local $avail_col = '' ;
	
	local $exists = '' ;
	&db_min_ro('events','id,event_quote_nr',"event_quote_nr='$i{event_quote_nr}' AND user_id='$userid'",'','') ;
	foreach my $eid (keys %{$db{events}}) { $exists = 1 if $db{events}{$eid}{event_quote_nr} eq $i{event_quote_nr} ; }
	
	# for (1 .. $max_operators) {
		# push @sql_fields, "operator_$_\_workings_event" ;
	# }
	
	# my $select = join(",", @sql_fields) ;

	# &db_min_ro('event_quotes',"id,$select","quote_nr='$i{event_quote_nr}'",'','') ;
	# foreach my $eid (keys %{$db{event_quotes}}) { 
		# # for (1 .. $max_operators) {
		# for ($max_operators .. 1) {
			# my $ex_col = "operator_$_\_workings_event" ;
			# my $op_id  = $db{event_quotes}{$eid}{$ex_col} ;
			# # next unless $op_id ;
			# $avail_col = $ex_col unless $op_id ;
			# if ($userid eq $op_id) {
				# $exist_col = $ex_col ;
				# # last ;
			# }
		# }
	
	# }
	
	# return unless $exist_col ;
	
	# if ($exist_col and $iaction eq 'unavailable') {
		# $i{"$exist_col"} = '' ; # set unavailable
		# &db_min_upd('event_quotes',"quote_nr='$i{event_quote_nr}'") ;
	# } elsif ($iaction eq 'available' and $exist_col eq '' and $avail_col) {
		# $i{"$avail_col"} = $userid ; # set available
		# &db_min_upd('event_quotes',"quote_nr='$i{event_quote_nr}'") ;
	# }
	
	$ignore{iaction} = 1 ;

	$i{date_time} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ;
	
	# $i{category} = 'available' if $iaction eq 'confirm' ;
		
	if ($exists) {
		&db_min_upd('events',"event_quote_nr='$i{event_quote_nr}' AND user_id='$userid'") ;
	} else {
		&db_min_insert('events') ;
	}

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

sub update_events {

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

&hidden_fields ;

$hidden{id} = 1 ;

# $i{user_id} = $userid ;

# if ($i{completed}) { $i{completeddate} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; } else { $i{completed} = '0' ; }

&db_min_upd('events',"id='$i{id}'") ;

# &update_operators($i{event_quote_nr}) ; 

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

sub delete_events {

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

&db_min_delete('events',"id='$i{id}'") ;

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

sub insert_events {

&hidden_fields ;

# $i{id} = &db_min_get_max('events','id') ;

# $i{user_id} = $userid ;

# $i{operator_names_type_a} = ; 

$i{date_time} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ;

&db_min_insert('events') ;

# &update_operators($i{event_quote_nr}) ; 

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

# sub update_operators {
	
	# my ($iidd) = @_ ; 
	
	# return unless $iidd ; 
	
	# my $operators = qq~~ ;
	# foreach (split(",",$i{operator_names_type_a})) {
		# $operators .= qq~$_;~ ; 
	# }
	
	# foreach (split(",",$i{operator_names_type_b})) {
		# $operators .= qq~$_;~ ; 
	# }
	
	# chop $operators if $operators ; 
	# # my $iidd = ;
	# %i = () ; 
	# $i{id} = $iidd ; 
	# $i{operators_workings_event} = $operators ; 
	
	# &db_common_upd('event_quotes_min',"id='$i{id}'") ; 
	
# } #------------------------------------------------------------------------------------------

sub hidden_fields {

$textarea{notes} = 1 ;
# $required{title} = 1 ;
$required{category} = 1 ;

if ($db{$table}{$id}{category} eq 'leave') {
    $required{days} = 9 ;
} else {
    $ignore{days} = 1 ;
    $ignore{type} = 1 ;
}
    
$datetimepicker{startdate} = 1 ;
$datetimepicker{enddate} = 1 ;

$ignore{iaction} = 1 ;
$ignore{completed} = 1 ;
$ignore{title} = 1 ;
$ignore{operator_names_type_a} = 1 ; 
$ignore{operator_names_type_b} = 1 ; 

$hidden{id} = 2 ;
# $hidden{user_id} = 2 ;
$hidden{date_time} = 2 ;

# $checkbox{completed} = 2 ;

$selected{category}{$db{$table}{$id}{category}} = 'SELECTED' ;

$select{category} = 1 ;

if ($db{$table}{$id}{category} eq 'leave') {
    $opts{category} .= qq(<option value="leave" $selected{category}{leave}>Leave</option>);
} else {
    # $opts{category} .= qq(<option value="meeting" $selected{category}{meeting}>Meeting</option><option value="task" $selected{category}{task}>Task</option>) ; 
    $opts{category} .= qq(<option value="weekend_work" $selected{category}{weekend_work}>Weekend Work</option>) ; 
	$opts{category} .= qq(<option value="public_holiday" $selected{category}{public_holiday}>Public Holiday</option>) ; 
	$opts{category} .= qq(<option value="other" $selected{category}{other}>Other</option>) ; 
}
    
# $opts{category} .= qq(<option value="leave" $selected{leave}>Leave</option><option value="meeting" $selected{meeting}>Meeting</option><option value="task" $selected{task}>Task</option><option value="birthday" $selected{birthday}>Birthday</option>) ; 
# $opts{category} .= qq(<option value=leave" $selected{category}{leave}>Leave</option><option value="meeting" $selected{category}{meeting}>Meeting</option><option value="task" $selected{category}{task}>Task</option>) ; 

&sort_fields ;

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

sub sort_fields {

$sort_field{1}  = 'category' ; 
$sort_field{2}  = 'startdate' ; 
$sort_field{3}  = 'enddate' ;  
$sort_field{4}  = 'user_id' ; 
$sort_field{5}  = 'notes' ;

} #-------------------------------------------------------------------------------
              
sub sort_leave_fields {

$sort_field{1}  = 'category' ; 
$sort_field{2}  = 'startdate' ; 
$sort_field{3}  = 'enddate' ; 
$sort_field{4}  = 'days' ; 
$sort_field{5}  = 'type' ; 
$sort_field{6}  = 'user_id' ; 
$sort_field{7}  = 'notes' ;

} #-------------------------------------------------------------------------------
              
sub edit_form { 

	$boxtitle = 'Edit' ;

	&db_min_ro($table,'*',"id='$i{id}'",'','') ;

	&hidden_fields ;

	if ($db{$table}{$id}{category} eq 'leave') {
		$selected{'type'}{$db{$table}{$i{id}}{type}} = 'SELECTED' ;
		&common_min_opts('leave_type','type',1) ;
		&sort_leave_fields ;
	}
		
	&common_min_select_opts('user_id','users','name',$db{$table}{$id}{user_id},1) ;

	&display_user;

	$print_box_content_rows = &common_min_edit_form($i{id},$table,'update') ; 

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

sub view_form { 

	&db_open_ro ;
		our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it
		 
		# our @month_array = ( "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ) ; 
		our @month_array = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") ; 
		
		our @months = ( "" , "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ) ; 
		
		# @month_array = @months ;
		
		$boxtitle = 'View' ;

		$table = 'event_quotes' ;
		
		# &db_min_ro($table,'quote_nr,nr,quote_date,customer,country_id,ref,date_from,date_to,qty,currency,grand_total,invoice_nr',"quote_nr='$id'",'','') ;
		# &db_min_ro($table,'quote_nr,quote_date,country_id,ref,date_from,date_to,qty,currency,grand_total,invoice_nr',"quote_nr='$id'",'','') ;

		$sort_field{1}	= 'quote_nr'		; 
		$sort_field{2}	= 'ref'				;
		$sort_field{3}	= 'date_from'		; 
		$sort_field{4}	= 'date_to'			; 
		$sort_field{5}	= 'type_of_system'	;
		$sort_field{6}	= 'type_details'	if $usertype ne 'schools_manager' ;
		# $sort_field{7}	= 'system_name'		if $usertype ne 'schools_manager' ;
		$sort_field{7}	= 'system_details'		if $usertype ne 'schools_manager' ;
		# $sort_field{8}	= 'club_name'		; 
		$sort_field{9}	= 'days'			; 
		$sort_field{10}	= 'operators'		;  
		$sort_field{11}	= 'sport_type_ids'	;
		$sort_field{12}	= 'city'			; 
		$sort_field{13}	= 'region'			; 
		$sort_field{14}	= 'venue'			; 
			
		# $sort_field{1}   = 'quote_nr'				; 
		# $sort_field{2}   = 'ref'					;
		# $sort_field{3}   = 'date_from'				; 
		# $sort_field{4}   = 'date_to'				; 
		# $sort_field{5}   = 'type'					; 
		# $sort_field{6}   = 'sport_type_ids'			; 
		# # $sort_field{7}   = 'ligr'					; 
		# $sort_field{8}   = 'location'				; 
		# $sort_field{9}   = 'city_id'				; 
		# $sort_field{10}  = 'organisation_ids'		; 
		# # $sort_field{5} = 'country_id'				; 
		# $sort_field{11}  = 'quote_to'				; 
		# $sort_field{12}  = 'notes'					; 
		# $sort_field{13}  = 'nr_of_casuals'			; 
		# $sort_field{14}  = 'operator_names_type_a'  ; 
		# $sort_field{15}  = 'nr_of_casuals_2'		; 
		# $sort_field{16}  = 'operator_names_type_b'  ; 
		
		$sort_field{17}  = 'poc_name'					;
		$sort_field{18}  = 'poc_contact_nr'				;
		$sort_field{19}  = 'category_1'  				;
		$sort_field{20}  = 'category_1_sub_categories'	; 
		$sort_field{21}  = 'category_2'  				; 		
		$sort_field{22}  = 'category_2_sub_categories'	; 
		$sort_field{23}  = 'recipient_name'  			; 
		$sort_field{24}  = 'recipient_nr'  			; 
		$sort_field{25}  = 'additional_notes'  			; 
		$sort_field{26}  = 'format_of_title'  			; 
		
		$preferred_title{organisation_ids} = "Venue(s)" ;
		$preferred_title{sport_type_ids} = "Sport Types(s)" ;
		
		foreach (sort {$a <=> $b} keys %sort_field) { push @sql_fields, $sort_field{$_} ; }
		
		for (1 .. $max_operators) {
			push @sql_fields, "operator_$_\_workings_event" ;
		}
		
		my $select = join(",", @sql_fields) ;
 
		&db_min_ro('event_quotes_poc','id,name,contact_nr','','','') ;
		
		&db_min_ro('event_quotes_categories','id,category','','','') ;
		
		&db_min_ro('event_systems','id,name,description','','','') ;
		
		&db_min_ro('sport_types','id,name','','','') ;
		
		&db_min_ro('regions','id,name','','','') ;
		
		&db_min_ro('cities','id,name','','','') ;
		
		&db_min_ro('organisations','id,name','','','') ;		
		
		&db_min_ro('event_type_details','id,name','','','') ;		
		
		# &db_min_ro($table,"$select,casual_worker,casual_worker_2,user_id","quote_nr='$id'",'','') ;
		
		&db_min_ro('analytics_event_bookings','id,event_quote_id,fixtures_saved_values,analytics_saved_values,start_date_time,sport_type_ids,event_name',"event_quote_id <> '0' AND event_quote_id = '$id'",'','') ;		

		&db_switch_conn('sss') ;

		&db_min_ro('teams','id,name','','','') ;
		 	
		&db_switch_conn('aisa') ;
	
		my @fixtures_saved_values = () ; 
		my @analytics_saved_values = () ; 
		
		my %analytics_saved_values = () ; 
		
		# our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; 

		our $analytics_table_body = qq~~ ; our $analytics_table = qq~~ ; our $analytics_event_exists = 0 ; 
		
		my $analytics_required = 0 ; 

		foreach my $id (sort { $b <=> $a } keys %{$db{analytics_event_bookings}}) {
			
			$analytics_event_exists = 1 ; 
			# $analytics_event_exists = 0 ; 
			# $db{analytics_event_bookings}{$id}{analytics_saved_values} = "" ;
			# $db{analytics_event_bookings}{$id}{fixtures_saved_values} = "" ;
			
			$analytics_required = 1 if !$db{analytics_event_bookings}{$id}{analytics_saved_values} && !$db{analytics_event_bookings}{$id}{fixtures_saved_values} ;
			
			$sort_field{27}  = 'fixture_date/Time_from' ; 
			$sort_field{28}  = 'sport' ; 
			$sort_field{29}  = 'team' ; 
			$sort_field{30}  = 'home_vs_opp_team' ; 
			$sort_field{31}  = 'stream_forwarding' ; 
			$sort_field{32}  = 'stream_key' ; 
			$sort_field{33}  = 'stream_URL' ; 

			$db{analytics_event_bookings}{$id}{fixtures_saved_values} =~ s/\|+$// ;
			
			$db{analytics_event_bookings}{$id}{fixtures_saved_values} = ";;;" unless $db{analytics_event_bookings}{$id}{fixtures_saved_values} ;
			
			@fixtures_saved_values 	= split(/\|/,$db{analytics_event_bookings}{$id}{fixtures_saved_values}) ; 
			
			my $fixtures_row_cnt = 0 ;
			
			foreach (@fixtures_saved_values) {
				
				my @abc = split(/\;/,$_) ;
				$fixtures_row_cnt++ ;
				$analytics_saved_values{$id}{$fixtures_row_cnt}{$sort_field{27}} = ($abc[0]) ? &common_min_date_as_string($abc[0]) : ($db{analytics_event_bookings}{$id}{start_date_time}) ? &common_min_date_as_string($db{analytics_event_bookings}{$id}{start_date_time}) : &common_min_date_as_string("$now_year-$now_mm-$now_dd 08:00:00") ;
				$analytics_saved_values{$id}{$fixtures_row_cnt}{$sort_field{28}} = ($abc[1]) ? $db{sport_types}{$abc[1]}{name} : ($db{analytics_event_bookings}{$id}{sport_type_ids} && $db{analytics_event_bookings}{$id}{sport_type_ids} !~ /;/) ?  $db{sport_types}{$db{analytics_event_bookings}{$id}{sport_type_ids}}{name} : "N/A" ;
				$analytics_saved_values{$id}{$fixtures_row_cnt}{$sort_field{29}} = ucfirst $abc[2] . ' ' . uc $abc[3] ;
				$analytics_saved_values{$id}{$fixtures_row_cnt}{$sort_field{30}} = ($abc[4] && $abc[6]) ? $db{teams}{$abc[4]}{name} . ' vs ' . $db{teams}{$abc[6]}{name} : ($abc[4]) ? $db{teams}{$abc[4]}{name} . ' vs N/A' : ($abc[6]) ? 'N/A vs ' . $db{teams}{$abc[6]}{name} : "" ;
				
			}
			
			@analytics_saved_values_arr = split(/\|/,$db{analytics_event_bookings}{$id}{analytics_saved_values}) ; 
			 
			my $analytics_row_cnt = 0 ;
			
			foreach (@analytics_saved_values_arr) {
				my @abc = split(/\;/,$_) ;
				$analytics_row_cnt++ ;
				$analytics_saved_values{$id}{$analytics_row_cnt}{$sort_field{31}} = ($abc[0] eq '1') ? "Yes" : ($abc[0] eq "2") ? "No" : "" ;
				$analytics_saved_values{$id}{$analytics_row_cnt}{$sort_field{32}} = $abc[1] ;
				$analytics_saved_values{$id}{$analytics_row_cnt}{$sort_field{33}} = ($abc[2]) ? qq~<a href='$abc[2]' target="_blank" style="color:blue;"><u>Click Here</u></a>~ : qq~~ ; 		
			}
			
			if ($analytics_row_cnt > $fixtures_row_cnt) {
				for ($fixtures_row_cnt + 1 .. $analytics_row_cnt) {
					$analytics_saved_values{$id}{$_}{$sort_field{27}} = ($db{analytics_event_bookings}{$id}{start_date_time}) ? &common_min_date_as_string($db{analytics_event_bookings}{$id}{start_date_time}) : &common_min_date_as_string("$now_year-$now_mm-$now_dd 08:00:00") ;
					$analytics_saved_values{$id}{$_}{$sort_field{28}} = ($db{analytics_event_bookings}{$id}{sport_type_ids} && $db{analytics_event_bookings}{$id}{sport_type_ids} !~ /;/) ?  $db{sport_types}{$db{analytics_event_bookings}{$id}{sport_type_ids}}{name} : "N/A" ;
				}
			}
			
		}
		
		if ($analytics_event_exists) {
	 
			$useropts{'common'}{'css'} .= qq~
				table {
					border-collapse: separate ;
					border-spacing: 12.5px ;
					width: 100% ;
					font-size: 1em ;
				}
				
				tbody tr {
					line-height: 0 ;
				}
				
				thead th {
					line-height: 0 ;
				}
				
				tbody td {
					background-color: rgb(238,238,238) ;
				}
				
			~ ;
			
			my $table_header =  "<thead><tr><th>" .  join ("</th><th>", map { join(" ", map { ucfirst $_ } split (/\_/, $sort_field{$_} ) ) } (27 .. 33) ) . "</th></tr></thead>" ;
				
			foreach my $analytics_id (sort {$b <=> $a} keys %analytics_saved_values) {
			
				my $analytics_table_raw = qq~~ ;
				
				foreach my $row_counter (sort {$a <=> $b} keys %{$analytics_saved_values{$analytics_id}}) {
					
					last if $analytics_required ; 
					
					$analytics_table_raw .= qq~
						<tr>
					~ ; 
					
					foreach my $col_nr (27 .. 33) {
						
						my $nowrap = ($col_nr == 27) ? "nowrap" : "" ;
						
						$analytics_table_raw .= ($analytics_saved_values{$analytics_id}{$row_counter}{$sort_field{$col_nr}}) ? qq~
							<td style='font-size:90%;' $nowrap><span>$analytics_saved_values{$analytics_id}{$row_counter}{$sort_field{$col_nr}}</span></td>
						~ : qq~
							<td><span></span></td>
						~ ; 
					}
					
					$analytics_table_raw .= qq~
						</tr>
					~ ; 
					
				}

				$analytics_table .= qq~<tbody>$analytics_table_raw</tbody>~ if $analytics_table_raw ;

						# <div class='box-header well' data-original-title=''>
							# <h2><i class='glyphicon glyphicon-tasks'></i> Analytics Required</h2>                    
						# </div>
			
				if ($analytics_table_raw) {

					# $analytics_table_body .= qq~ 
						# <div class='row'>
							# &nbsp;
						# </div>
						# <div class='box-inner'>
							# <div class='box-content'>
							# ~ ;
					
					$analytics_table_body .= qq~</div></div></div></div>~ if $analytics_table_body ;
					
					$analytics_table_body .= &common_min_box_top('tasks',"View&nbsp;Analytics&nbsp;-&nbsp;$db{analytics_event_bookings}{$analytics_id}{event_name}&nbsp;[$analytics_id]") ; 					
					
					$analytics_table_body .= qq~ 
								 <table>
									$table_header
									$analytics_table_raw
								</table>
					~ ; 
					
				}	
			}
		}

		&db_min_ro($table,"*","quote_nr='$id'",'','') ;
		
		if ($db{$table}{$id}{city_id} =~ /,/) {
			$sort_field{12}	= 'cities' ; 	
		} else {
			$sort_field{13}	= '' ;
		}
				
		&db_min_ro('event_quotes_min',"*","id='$id'",'','') ;
		
		&db_min_ro('users','id,name,user_type,phone',"user_type LIKE 'casual%'",'','') ;
		foreach (keys %{$db{users}}) { 
			$casual_name{$_} = $db{users}{$_}{name} ; 
			# my $casual_type  = $db{users}{$_}{user_type} ; $casual_type =~ s/_casual//g ; 
			$casual_type{$_} = uc substr($db{users}{$_}{user_type},-1,1) ; 
		}
		# %col_name = () ;
		# &db_min_ro('countries','id,name',"id=$db{$table}{$id}{country_id}",'','') if $db{$table}{$id}{country_id} ;
		# foreach (keys %{$db{countries}}) { $country{$_} = $db{countries}{$_}{name} ; }
		%col_name = () ;
		&db_min_ro('event_types','id,name',"id=$db{$table}{$id}{type}",'','') if $db{$table}{$id}{type} ;
		foreach (keys %{$db{event_types}}) { $event_type{$_} = $db{event_types}{$_}{name} ; }
		%col_name = () ;
		&db_min_ro('customers','id,name',"id=$db{$table}{$id}{quote_to}",'','') if $db{$table}{$id}{quote_to} ;
		foreach (keys %{$db{customers}}) { $customers{$_} = $db{customers}{$_}{name} ; }
		%col_name = () ;
		# &db_min_ro('events','id,event_quote_nr,category,user_id',"event_quote_nr='$id'",'','') ;
		
		# my $user_id    = $db{$table}{$id}{user_id} ; 
		my $quote_nr   = $db{$table}{$id}{quote_nr} ; 
		my $start      = $db{$table}{$id}{date_from} ; 
		my $end        = $db{$table}{$id}{date_to} ;
		my $date_start = substr($start,0,10);
		my $date_end   = substr($end,0,10);
	
		# for (1 .. $max_operators) {
			# local $field = "operator_$_\_workings_event" ;
			# $op_id = $db{$table}{$id}{$field} ;

		my %selected_names = () ; 
		
		# &common_debug("operator_workings_event : $db{event_quotes_min}{$id}{operator_workings_event} , id : $id") ; 
		
		foreach my $op_id (split(";",$db{event_quotes_min}{$id}{operator_workings_event})) {
			next unless $op_id ;
			next if $done_op{$op_id}{$quote_nr} ;
			$this_user_subscribed{$op_id} = 1 ;		
			$cat{$date_start}{$date_end}{$quote_nr}{$op_id} = 'assigned' ; 
			$ccnt{$date_start}{$date_end}{$casual_type{$op_id}}{$quote_nr}++  ; 
			$subscribed_names{$date_start}{$date_end}{$casual_type{$op_id}}{$quote_nr} .= "$casual_name{$op_id}, " ; 
			$done_op{$op_id}{$quote_nr} = 1 ;
			# $selected_names{operator_names_type_a}{$op_id}{$id} = 'SELECTED' if $casual_type{$op_id} eq 'A' ;
			# $selected_names{operator_names_type_b}{$op_id}{$id} = 'SELECTED' if $casual_type{$op_id} eq 'B' ;
			
			# &common_debug("op_id : $op_id , casual_type : $casual_type{$op_id} , id : $id") ;
			
		}
				
		&db_min_ro('events','id,event_quote_nr,category,user_id,startdate,enddate',"user_id='$userid' OR event_quote_nr='$id'",'','') ;
		
		# &db_min_ro('events','id,event_quote_nr,category,user_id,startdate,enddate',"(user_id='$userid' OR event_quote_nr='$id') AND startdate LIKE '$date_start%' AND enddate LIKE '$date_end%'",'','') ;
		foreach (keys %{$db{events}}) { 
			my $start = $db{events}{$_}{startdate} ; my $edate_start = substr($start,0,10);
			my $end   = $db{events}{$_}{enddate}   ; my $edate_end   = substr($end,0,10);
			$qnr = $db{events}{$_}{event_quote_nr} ; 
			$uid = $db{events}{$_}{user_id} ; 
			
			if ($date_start ne $edate_start) { next ; }
			if ($date_end ne $edate_end)     { next ; }
			
			# $booked_this_one{$uid}{$qnr}{$db{events}{$_}{category}} = 1 ;
			
			$cat{$edate_start}{$edate_end}{$qnr}{$uid} = $db{events}{$_}{category} ; 
			# $ccnt{$edate_start}{$edate_end}{$casual_type{$uid}}{$qnr}++ if $cat{$edate_start}{$edate_end}{$qnr}{$uid} eq 'available' ; 
			# $subscribed_names{$edate_start}{$edate_end}{$casual_type{$uid}}{$qnr} .= "$casual_name{$uid}, " if $cat{$edate_start}{$edate_end}{$qnr}{$uid} eq 'available' ; 
			&check_dates_booked($qnr,$uid,$db{events}{$_}{startdate},$db{events}{$_}{enddate}) if $cat{$edate_start}{$edate_end}{$qnr}{$uid} eq 'available' ; 
		}
				
		my $casual_1_type = $db{$table}{$id}{casual_worker} ;
		my $casual_2_type = $db{$table}{$id}{casual_worker_2} ;

		$preferred_title{date_from}       = 'Date From' ;
		$preferred_title{date_to}         = 'Date To' ;
		$preferred_title{quote_to}        = 'Client' ;
		$preferred_title{nr_of_casuals}   = 'Nr of Operators' ; # . $casual_1_type ;
		$preferred_title{nr_of_casuals_2} = 'Nr of Operators' ; # . $casual_2_type ;
		$preferred_title{ref}             = 'Event Name' ;
		
		$lcol = 2 ; $fcol = 8 ;
		
		# foreach (sort { $col_name{$a} cmp $col_name{$b} } keys %col_name) {
			# $col = $col_name{$_} ;
			
		my $casuals_1_subscribed = sprintf("%0.0f",$ccnt{$date_start}{$date_end}{$casual_1_type}{$id}) ;
		my $casuals_2_subscribed = sprintf("%0.0f",$ccnt{$date_start}{$date_end}{$casual_2_type}{$id}) ;
		chop $subscribed_names{$date_start}{$date_end}{$casual_1_type}{$id} ; chop $subscribed_names{$date_start}{$date_end}{$casual_1_type}{$id} ;
		chop $subscribed_names{$date_start}{$date_end}{$casual_2_type}{$id} ; chop $subscribed_names{$date_start}{$date_end}{$casual_2_type}{$id} ;
		my $casual_1_names_subscribed = '[' . $subscribed_names{$date_start}{$date_end}{$casual_1_type}{$id} . ']' if $subscribed_names{$date_start}{$date_end}{$casual_1_type}{$id} ;
		my $casual_2_names_subscribed = '[' . $subscribed_names{$date_start}{$date_end}{$casual_2_type}{$id} . ']' if $subscribed_names{$date_start}{$date_end}{$casual_2_type}{$id} ;
				
		# my $operator_id = 0 ; 
		# my %selected_names = () ; 
		# for (1 .. $max_operators) {
			# $operator_id = $db{$table}{$id}{"operator_$_\_workings_event"} ;
			# $selected_names{operator_names_type_a}{$operator_id}{$id} = 'SELECTED' if $operator_id and $casual_type{$operator_id} eq 'A' ;
			# $selected_names{operator_names_type_b}{$operator_id}{$id} = 'SELECTED' if $operator_id and $casual_type{$operator_id} eq 'B' ;
		# }
		# $selected_names{operator_names_type_a}{48}{$id} = 'SELECTED' ;
		
		foreach my $casual_id (keys %casual_name){
			$opts{operator_names_type_a} .= qq(<option $selected_names{operator_names_type_a}{$casual_id}{$id} value="$casual_id">$casual_name{$casual_id}</option>) if $casual_type{$casual_id} eq 'A' ;
			$opts{operator_names_type_b} .= qq(<option $selected_names{operator_names_type_b}{$casual_id}{$id} value="$casual_id">$casual_name{$casual_id}</option>) if $casual_type{$casual_id} eq 'B' ;
		}	
		
		my @club_ids_arr = () ; 
		foreach (split(";",$db{$table}{$id}{club_ids})) {			
			push @club_ids_arr , "`id` = '$_'"  if $_ ;
		}
		my $club_ids_sql = join(" OR ",@club_ids_arr) ; 
		$club_ids_sql = "($club_ids_sql)" if $club_ids_sql ; 
		
		&db_min_ro('clubs','id,name',"$club_ids_sql",'','');

		if ($date_start eq $date_end) {
			$sort_field{3}	= 'date' ; 
			$sort_field{4}	= '' ; 
			$preferred_title{date_from} = 'Date' ;
		}
		
		my @times_from 	= split(/\;/,$db{$table}{$id}{times_from}) ;
		my @times_to 	= split(/\;/,$db{$table}{$id}{times_to}) ;
		my @times_from_com = () ; my @times_to_com = () ; 
		push @times_from_com,substr($db{$table}{$id}{date_from},11) ;
		
		my @days_active = split(/\;/,$db{$table}{$id}{days_active}) ;
		
		my %dates_hash = () ;

		for (1 .. 10) {
			my ($year,$month,$day) = split(/\-/,substr($db{$table}{$id}{date_from},0,10)) ;
			my ($new_year,$new_month,$new_day) = Add_Delta_Days($year,$month,$day,$_-1) ;
			$new_day = sprintf("%02s",$new_day) ; $new_month = sprintf("%02s",$new_month) ; 
			$dates_hash{$_} = "$new_year-$new_month-$new_day" ;	
			push @times_from_com,$times_from[$_-2] if $times_from[$_-2] && $_ > 1 ;
			push @times_from_com,substr($db{$table}{$id}{date_from},11) if !$times_from[$_-2] && $_ > 1 ;
			last if substr($db{$table}{$id}{date_to},0,10) eq "$new_year-$new_month-$new_day" ;	
			push @times_to_com,$times_to[$_-1] if $times_to[$_-1] ;
			push @times_to_com,substr($db{$table}{$id}{date_to},11) if !$times_to[$_-1] ;
		}

		my $system_count = 0 ; my $system_day_cnt = 0 ; my %system_has_daily_op = () ; 

		foreach my $system_row (split(/\|/,$db{$table}{$id}{daily_operator_ids})) {
			$system_count++ ; 
			next unless $system_row ;
			$system_day_cnt = 0 ;
			foreach my $col (split(/\;/,$system_row)) {
				$system_day_cnt++ ;
				next unless $col ; 
				$default_op_ids{$system_count}{$system_day_cnt} = $col if $col ;
				$system_daily_ops{$system_count} .= qq~Day $system_day_cnt : $db{users}{$col}{name}, ~ if $col ; 
			}
			chop $system_daily_ops{$system_count} if $system_daily_ops{$system_count} ;
			chop $system_daily_ops{$system_count} if $system_daily_ops{$system_count} ;
		}	
		$system_count = 0 ; 
		
		# push @times_to_com, substr($db{$table}{$id}{date_to},11) ;
		
		# my $system_count = 0 ; my $system_day_cnt = 0 ; my %system_has_daily_op = () ; 

		# foreach my $system_row (split(/\|/,$db{$table}{$id}{daily_operator_ids})) {
			# $system_count++ ; 
			# next unless $system_row ;
			# $system_day_cnt = 0 ;
			# foreach my $col (split(/\;/,$system_row)) {
				# $system_day_cnt++ ;
				# next unless $col ; 
				# $default_op_ids{$system_count}{$system_day_cnt} = $col if $col ;
				# $system_daily_ops{$system_count} .= qq~Day $system_day_cnt : $db{users}{$col}{name}, ~ if $col ; 
			# }
			# chop $system_daily_ops{$system_count} if $system_daily_ops{$system_count} ;
			# chop $system_daily_ops{$system_count} if $system_daily_ops{$system_count} ;
		# }	
		# $system_count = 0 ; 
		
		foreach my $cnt (sort {$a <=> $b} keys %sort_field) {
			
			$col = $sort_field{$cnt} ;			 
			
			next if !$col || $col eq 'quote_nr' ;

			$val = $db{$table}{$id}{$col} ;
			# next if not $val and $col ne 'operator_names_type_a' and $col ne 'operator_names_type_b' and $col ne 'category_1_sub-Categories' and $col ne 'category_2_sub-Categories' ;
			# $val = $country{$val}   if $col eq 'country_id' ;
			$val = $customers{$val} if $col eq 'quote_to' ;
			# $val = $event_type{$val} if $col eq 'type' ;
			if ($col eq 'nr_of_casuals')   {
				$casuals_1_subscribed = 0 unless $casuals_1_subscribed ; 
				$db{$table}{$id}{nr_of_casuals} = 0 unless $db{$table}{$id}{nr_of_casuals} ; 
				$val = "$casuals_1_subscribed/$val $casual_1_names_subscribed" ; 
				$fully_substribed{$casual_1_type} = 1 if $casuals_1_subscribed >= $db{$table}{$id}{nr_of_casuals} ; 
			} elsif ($col eq 'nr_of_casuals_2') {
				$casuals_2_subscribed = 0 unless $casuals_2_subscribed ;
				$db{$table}{$id}{nr_of_casuals_2} = 0 unless $db{$table}{$id}{nr_of_casuals_2} ; 
				$val = "$casuals_2_subscribed/$val $casual_2_names_subscribed" ; 
				$fully_substribed{$casual_2_type} = 1 if $casuals_2_subscribed >= $db{$table}{$id}{nr_of_casuals_2} ; 
			} elsif ($col eq 'date_from' || $col eq 'date') {
				$val = &process_date($db{$table}{$id}{date_from}) ;
				$val .= qq~ to ~ . substr($times_to_com[0],0,5) ;
				$val .= substr($db{$table}{$id}{date_to},11,5) if $col eq 'date' ;
			} elsif ($col eq 'date_to') {
				$val = &process_date($db{$table}{$id}{date_to}) ;
				$val = substr($val,0,-5) . substr($times_from_com[-1],0,5) . qq~ to ~ . substr($val,-5,5) ;
			} elsif ($col eq 'operator_names_type_a'){
				next unless $db{$table}{$id}{nr_of_casuals}  ;
				# $preferred_title{$col} = "Operator Names A" ; 
				# $fcol = 3 ;
				# $multiple{$col} = 1 ; 
				# $setmultiple = 'multiple' ;
				# $print_box_content_rows .= &common_min_form_select($col,'') ; 
				# $print_box_content_rows . "</div>" ;		
			} elsif ($col eq 'operator_names_type_b') {
				# next unless $db{$table}{$id}{nr_of_casuals_2} ;
				# $preferred_title{$col} = "Operator Names B" ; 
				# $fcol = 3 ;
				# $multiple{$col} = 1 ; 
				# $setmultiple = 'multiple' ; 
				# $print_box_content_rows .= &common_min_form_select($col,'') ; 
			} elsif ($col eq 'sport_type_ids') {		
				$val = qq~~ ;
				foreach (split(",",$db{$table}{$id}{sport_type_ids})) {			
					$val .= qq~$db{sport_types}{$_}{name}, ~ ;		
				}
				chop $val if $val ; chop $val if $val ; 
			} 
			# elsif ($col eq 'city_id') {
				# $val = $db{cities}{$val}{city} ;
				# $val .= qq~, $db{regions}{$db{$table}{$id}{region_id}}{name}~ if $db{$table}{$id}{region_id} ;
			# } 
			# elsif ($col eq 'organisation_ids') { 
				# $val = qq~~ ;
				# foreach (split(",",$db{$table}{$id}{organisation_ids})) {			
					# $val .= qq~$db{organisations}{$_}{name}, ~ ;		
				# }
				# chop $val if $val ; chop $val if $val ; 
			# } 
 # event_quotes_poc','id,name,contact_nr
			elsif ($col eq 'poc_name') {
				$val = $db{event_quotes_poc}{$db{$table}{$id}{poc_id}}{name} ;
			} elsif ($col eq 'poc_contact_nr') {
				$val = $db{event_quotes_poc}{$db{$table}{$id}{poc_id}}{contact_nr} ;
				$val =~ s/ //g ;
				if (substr($val,0,2) eq '27' && length($val) == 11) {
					$val = "+27 " . substr($val,2,2) . " " .  substr($val,4,3) . " " .  substr($val,7,4) ;
				} elsif ((substr($val,0,2) eq '07' || substr($val,0,2) eq '08' || substr($val,0,2) eq '02') && length($val) == 10) {
					$val = "+27 " . substr($val,1,2) . " " .  substr($val,3,3) . " " .  substr($val,6,4) ;
				} else {
					$val = $db{event_quotes_poc}{$db{$table}{$id}{poc_id}}{contact_nr} ;
				}

			} elsif ($col eq 'category_1_sub_categories') {
				my @a = split('\|;\|',$db{event_quotes_min}{$id}{category_details}) ;
				$a[0] =~ s/\n/<br>/g;
				$a[0] = substr($a[0],0,-4) if substr($a[0],-4,4) eq '<br>' ;
				$val = $a[0] ;
				next unless $val ; 
			} elsif ($col eq 'category_2_sub_categories') {
				my @a = split('\|;\|',$db{event_quotes_min}{$id}{category_details}) ;
				$a[1] =~ s/\n/<br>/g;
				$a[1] = substr($a[1],0,-4) if substr($a[1],-4,4) eq '<br>' ;
				$val = $a[1] ;
				next unless $val ; 
			} elsif ($col eq 'category_1') {
				$val = $db{event_quotes_categories}{$db{$table}{$id}{category_id_1}}{category} ;
			} elsif ($col eq 'category_2') {
				$val = $db{event_quotes_categories}{$db{$table}{$id}{category_id_2}}{category} ;
			} elsif ($col eq 'type_details') {
				# event_system_id_multiple
				$val = qq~~ ;
				foreach my $type_id (split(",",$db{$table}{$id}{type_details_id})) {			
					$val .= qq~$db{event_type_details}{$type_id}{name}, ~ ;		
				}
				chop $val if $val ; chop $val if $val ; 
				
			} elsif ($col eq 'system_details') { 
			# elsif ($col eq 'system_name') { 
				
				$val = qq~~ ;
				# my $cnt_sys      = 0 ; 
				my @club_ids     = split(";",$db{$table}{$id}{club_ids}) ;
				my @operator_ids = ($db{$table}{$id}{operator_ids} =~ /;/) ? split(";",$db{$table}{$id}{operator_ids}) : split(",",$db{$table}{$id}{operator_ids}) ;
				my $cnt_sys = -1 ; 

				foreach my $event_id (split(/\;/,$db{$table}{$id}{event_system_id_multiple})) {
					$cnt_sys++ ; 
					next if not $event_id and not $club_ids[$cnt_sys] ;
					$event_id =~ s/f-//g ;
					$val .= qq~$db{event_systems}{$event_id}{name} ~ if $event_id ;
					$val .= qq~>>> ~ if $event_id and not $db{event_systems}{$event_id}{description} ;
					$val .= qq~($db{event_systems}{$event_id}{description}) >>> ~ if $db{event_systems}{$event_id}{description} and $event_id ;
					$val .= qq~NO SYSTEM >>> ~ unless $event_id ;	

					$val .= qq~$db{clubs}{$club_ids[$cnt_sys]}{name} >>> ~ if $club_ids[$cnt_sys] ;
					$val .= qq~NO CLUB >>> ~ unless $club_ids[$cnt_sys] ;
					
					$val .= qq~$db{users}{$operator_ids[$cnt_sys]}{name}~ if $operator_ids[$cnt_sys] ;
					$cnt_sys++ ;
					$val .= qq~[$system_daily_ops{$cnt_sys}]~ if $system_daily_ops{$cnt_sys} && !$operator_ids[$cnt_sys-1] ;
					$cnt_sys-- ;
					# $val .= qq~>>> $db{clubs}{$club_ids[$cnt_sys]}{name} ~ if $db{clubs}{$club_ids[$cnt_sys]}{name} ;
					# $val .= qq~>>> $db{users}{$operator_ids[$cnt_sys]}{name} ~ if $db{users}{$operator_ids[$cnt_sys]}{name} ;
					# $val .= qq~[$db{users}{$operator_ids[$cnt_sys]}{phone}] ~ if $db{users}{$operator_ids[$cnt_sys]}{name} && $db{users}{$operator_ids[$cnt_sys]}{phone} ;
					$val .= qq~<br>~ ;	
					# $cnt_sys++ ; 			
				}
				# chop $val if $val ; chop $val if $val ; 	
				$val = substr($val,0,-4) if $val ;
			} 
			# elsif ($col eq 'club_name') {
				# $val = '' ;
				# foreach my $club_id (split(";",$db{$table}{$id}{club_ids})) {	
					# $val .= qq~$db{clubs}{$club_id}{name}<br>~ if $club_id ; 
				# }
				# $val =~ s/\n/<br>/g;
				# $val = substr($val,0,-4) if substr($val,-4,-1) eq '<br' ;	
					
			# } 
			elsif ($col eq 'days') {
				$val = $db{users}{$_}{qty} ;
			} elsif ($col eq 'operators') {
				
				$val = qq~~ ; my $cnt_ops = 0 ; 
				
				my @operator_ids = ($db{$table}{$id}{operator_ids} =~ /;/) ? split(";",$db{$table}{$id}{operator_ids}) : split(",",$db{$table}{$id}{operator_ids}) ;
				
				foreach (@operator_ids) {			
					next unless $_ ;
					$cnt_ops++ ; 
					$val .= qq~$db{users}{$_}{name}~ ;	
					
					my $phone = $db{users}{$_}{phone} ;
					$phone =~ s/ //g ;
					if (substr($phone,0,2) eq '27' && length($phone) == 11) {
						$phone = "+27 " . substr($phone,2,2) . " " .  substr($phone,4,3) . " " .  substr($phone,7,4) ;
					} elsif ((substr($phone,0,2) eq '07' || substr($phone,0,2) eq '08' || substr($phone,0,2) eq '02') && length($phone) == 10) {
						$phone = "+27 " . substr($phone,1,2) . " " .  substr($phone,3,3) . " " .  substr($phone,6,4) ;
					} else {
						$phone = $db{users}{$_}{phone} ;
					}

					$val .= qq~ - $phone~ if $phone ;		
					$val .= qq~, ~ ;						
				}
				chop $val if $val ; chop $val if $val ; 
				$val = qq~$cnt_ops [$val]~ if $cnt_ops ; 
			} elsif ($col eq 'region') { 
				$val = $db{regions}{$db{$table}{$id}{region_id}}{name} ;
			} elsif ($col eq 'city') {
				$val = $db{cities}{$db{$table}{$id}{city_id}}{name} ;
				$val .= qq~, $db{regions}{$db{$table}{$id}{region_id}}{name}~ if $db{$table}{$id}{region_id} ;
			} elsif ($col eq 'cities') {
				# $val = '' ;
				# foreach (split(",",$db{$table}{$id}{city_id})) {
					# $val .= qq~$db{cities}{$_}{name},~ ;
				# }
				# chop $val if $val ;	

				$val = join(",", map { "$db{cities}{$_}{name}" } split(/\,/,$db{$table}{$id}{city_id})) ;
				
			} elsif ($col eq 'venue') {
			
				$val = qq~~ ;
				foreach (split(",",$db{$table}{$id}{organisation_ids})) {			
					$val .= qq~$db{organisations}{$_}{name}, ~ ;		
				}
				chop $val if $val ; chop $val if $val ; 
			
			} elsif ($col eq 'type_of_system') {
				$val = $event_type{$db{$table}{$id}{type}} ; 
			} elsif ($col eq 'format_of_title') {
				$val = $db{$table}{$id}{format_of_title} ;
				$val =~ s/\n/<br>/g;
			} elsif ($col eq 'additional_notes') {
				$val = $db{$table}{$id}{additional_notes} ;
				$val =~ s/\n/<br>/g;			
			} elsif ($col eq 'fixture_date/Time_from') {
				
				$val = join(",",map{"$analytics_saved_values{$col}{$_}"} sort {$a <=> $b} keys %{$analytics_saved_values{$col}}) ;
			} elsif ($col eq 'sport') {
				$val = join(",",map{"$analytics_saved_values{$col}{$_}"} keys %{$analytics_saved_values{$col}}) ;
			} elsif ($col eq 'age_group') {
				$val = join(",",map{"$analytics_saved_values{$col}{$_}"} sort {$a <=> $b} keys %{$analytics_saved_values{$col}}) ;
			} elsif ($col eq 'team') {                                           
				$val = join(",",map{"$analytics_saved_values{$col}{$_}"} sort {$a <=> $b} keys %{$analytics_saved_values{$col}}) ;
			} elsif ($col eq 'stream_forwarding') {                              
				$val = join(",",map{"$analytics_saved_values{$col}{$_}"} sort {$a <=> $b} keys %{$analytics_saved_values{$col}}) ;
			} elsif ($col eq 'stream_key') {                                      
				$val = join(",",map{"$analytics_saved_values{$col}{$_}"} sort {$a <=> $b} keys %{$analytics_saved_values{$col}}) ;
			} elsif ($col eq 'stream_URL') {                                      
				$val = join(",",map{"$analytics_saved_values{$col}{$_}"} sort {$a <=> $b} keys %{$analytics_saved_values{$col}}) ;
			}
 
			next unless $val ;
	
			$print_box_content_rows .= &common_min_form_view($col,$val,'') unless $col eq 'operator_names_type_a' or $col eq 'operator_names_type_b' ;
			
			if ($col eq 'date_from' && substr($db{$table}{$id}{date_from},0,10) ne substr($db{$table}{$id}{date_to},0,10)) {
				for (2 .. 9) {	
					last if substr($db{$table}{$id}{date_to},0,10) eq $dates_hash{$_} ;
					next if $db{$table}{$id}{days_active} && !$days_active[$_ - 1] ;
					my ($new_year,$new_month,$new_day) = split(/\-/,$dates_hash{$_}) ;
					$val = $new_day . "-" . $month_array[$new_month - 1] . "-" . $new_year . " @ " . substr($times_from_com[$_ - 1],0,5) . " to " . substr($times_to_com[$_ - 1],0,5) ;
					$print_box_content_rows .= &common_min_form_view("&nbsp;",$val,'') ;
				}
			}
		}
		 
		$dialog = 0 ;
		$addbkb = 0 ;
		# $print_box_content_rows .= &common_min_forms_end('','','report') ;
		
		# my @assigned_users_a = split(/\,/,$db{$table}{$id}{operator_names_type_a}s) ; 
		# my @assigned_users_b = split(/\,/,$db{$table}{$id}{operator_names_type_b}) ; 
		# my %selected_names = () ; 
		# for (@assigned_users_a){ $selected_names{operator_names_type_a}{$_}{$id}  = 'SELECTED'; }
		# for (@assigned_users_b){ $selected_names{operator_names_type_b}{$_}{$id}  = 'SELECTED'; }
		
		# <input type="hidden" name="iaction" value="$db{$table}{$id}{operator_names_type_a}">
		# <input type="hidden" name="iaction" value="$db{$table}{$id}{operator_names_type_b}">
		
		# $print_box_content_rows .= qq~
		$form_for_save .= qq~
			<form role="form" name="form_$table" id="$table-form"  method="post" enctype="multipart/form-data">	
				<input type="hidden" name="iaction" value="saveoperator">
				<input type="hidden" name="event_quote_nr" value="$id">
				<input type="hidden" name="operators_type_a" id="operators-type-a" value="">
				<input type="hidden" name="operators_type_b" id="operators-type-b" value="">
				<div class='row'>
					<div class="col-md-12">
						&nbsp;
					</div>
				</div>
				<div class="row">
					<div class="col-md-12">
						&nbsp;<button type="button" class="btn btn-primary" id="savebuttcalender">Save</button>&nbsp;
					</div>
				</div>
				<div class="row">
					<div class="col-md-12">
						&nbsp;
					</div>
				</div>
			</form>
		~ ;
		
			
	$trigger_jquery_raw .= qq~\$("#savebuttcalender").click(function() {    

		var op_a_val = \$("#selectOperator_names_type_a").chosen().val() ;
		var op_b_val = \$("#selectOperator_names_type_b").chosen().val() ;
		
		// const selected_a = op_a_val.split(",") ;
		// const selected_b = op_b_val.split(",") ;

		// let counter_a = 0 ; 
		// let counter_b = 0 ;
		
		// for (let i = 0; i < selected_a.length; i++) {
			// counter_a++ ; 
		// }
		
		// for (let i = 0; i < selected_b.length; i++) {
			// counter_b++ ; 
		// }

		// var max_ops_a = '$db{$table}{$id}{nr_of_casuals}' ;
		// var max_ops_b = '$db{$table}{$id}{nr_of_casuals_2}' ;
		
		// if (max_ops_a < counter_a && max_ops_b < counter_b) {
			// noty({text:'Operator A names exceed max nr allowed of '+max_ops_a+'! and Operator B names exceed max nr allowed of '+max_ops_b+'!',layout:"center",type:"error",timeout:3000});
			// return;
		// } else if (max_ops_b < counter_b && max_ops_a >= counter_a) {
			// noty({text:'Operator B names exceed max nr allowed of '+max_ops_b+'!',layout:"center",type:"error",timeout:3000});
			// return;
		// } else if (max_ops_a < counter_a && max_ops_b >= counter_b) {
			// noty({text:'Operator A names exceed max nr allowed of '+max_ops_a+'!',layout:"center",type:"error",timeout:3000});
			// return;
		// } else {
			\$('#operators-type-a').val(op_a_val);    
			\$('#operators-type-b').val(op_b_val); 
			\$('#$table-form').submit();
		// }
	});~ ;
	
	# $trigger_jquery_raw .= qq~\$("#savebuttcalender").click(function() {    

		# var max_allowed_a = $db{$table}{$id}{nr_of_casuals} ;
		# var max_allowed_b = $db{$table}{$id}{nr_of_casuals_2} ;
		
		# if (max_allowed_a < counter_a && max_allowed_b < counter_b) {
			# noty({text:'Operator A names exceed max nr allowed of '+max_allowed_a+'! and Operator B names exceed max nr allowed of '+max_allowed_b+'!',layout:"center",type:"error",timeout:3000});
			# return;
		# } else if (max_allowed_b < counter_b && max_allowed_a >= counter_a) {
			# noty({text:'Operator B names exceed max nr allowed of '+max_allowed_b+'!',layout:"center",type:"error",timeout:3000});
			# return;
		# } else if (max_allowed_a < counter_a && max_allowed_b >= counter_b) {
			# noty({text:'Operator A names exceed max nr allowed of '+max_allowed_a+'!',layout:"center",type:"error",timeout:3000});
			# return;
		# } else {
			# \$('#$table-form').submit();
		# }
	# });~ ;
		
		# $print_box_content_rows . "</div>" ;
		$db_ignore_open_close = 0 ; # do one open and one close instead of repeating it
	&db_close_conn ;

	# my $saction = ($cat{$date_start}{$date_end}{$id}{$userid} eq 'available') ? 'unavailable' : 'available' ; my $butttxt = uc $saction ; my $buttcolor = ($saction eq 'available') ? 'success' : 'danger' ;
	
	my $buttcolor = ($saction eq 'available') ? 'success' : 'danger' ;
	
	if ($cat{$date_start}{$date_end}{$id}{$userid} eq 'available') {
		$saction = 'unavailable' ;
	} elsif ($cat{$date_start}{$date_end}{$id}{$userid} eq 'assigned') {
		$saction   = 'available' ;
		# $buttcolor = 'info' ;
		$buttcolor = 'success' ;
	} elsif ($cat{$date_start}{$date_end}{$id}{$userid} eq 'unavailable') {
		$saction   = 'available' ;
		$buttcolor = 'success' ;
	}
	
	my $butttxt = uc $saction ;
	
	my ($dy1,$dm1,$dd1,$th1,$tm1,$ts1) = &common_split_sql_time($db{$table}{$id}{date_from}) ;
	my ($dy2,$dm2,$dd2,$th2,$tm2,$ts2) = &common_split_sql_time($db{$table}{$id}{date_to}) ;
	my $Dd = Delta_Days($dy1,$dm1,$dd1,$dy2,$dm2,$dd2);
	
	# my $nr_of_casuals_1_allowed = sprintf("%0.0f",$db{$table}{$id}{nr_of_casuals}) ;
	# if ($casuals_1_subscribed >= $nr_of_casuals_1_allowed and $saction eq 'available') { return ; } # fully subscribed
	
	# my $nr_of_casuals_2_allowed = sprintf("%0.0f",$db{$table}{$id}{nr_of_casuals_2}) ;
	# if ($casuals_2_subscribed >= $nr_of_casuals_2_allowed and $saction eq 'available') { return ; } # fully subscribed
	
	my $cnow     = $now_ccyymmdd . $now_hour . $now_min . $now_sec ;
	my $cstart   = $db{$table}{$id}{date_from} ; $cstart =~ s/ //g ; $cstart =~ s/-//g ; $cstart =~ s/://g ;
	my $cend     = $db{$table}{$id}{date_to}   ; $cend   =~ s/ //g ; $cend   =~ s/-//g ; $cend   =~ s/://g ;
	my $in_the_past = 0 ;

	our $files_attach = qq~~ ;
	
	
	$files_attach .= qq~
			<div class="col-md-1">
				<br>
					<a class="btn btn-primary btn-xs" href="javascript:parent.dlgMdl('$useropts{domain}$useropts{scripts}/pdf/event_details_pdf.pl?$qid&&','EVENT DETAILS $quote_nr','','waybill-dialog');" data-title="Event Details PDF" data-toggle="tooltip" data-placement="left">
						<i class="glyphicon glyphicon-print"></i>
					</a>
				<br>
				<br>
			</div>~ if $glod_user_level > 1 ;
	
	for  (1 .. 3) {
 
		$working_uploads = &get_event_uploads($qid,"upload_$_",'id') ;
		if ($working_uploads) {
			$files_attach .= qq~
			<div class="col-md-1">
				<br>
				$working_uploads
				<br>
				<br>
			</div>
			~ ; 
		}
	}
	# ;;;;6797|;;;;6797|;;;;6797|;8;;;6797
	if ($cstart < $cnow && $cend < $cnow) { # event in the past
	# if (1) { # event in the past
		
		if ($analytics_event_exists) {

			if ($analytics_table) {
				$analytics_table_body .= qq~
								<div class="row">
									<div class="col-md-2">
										<br>
										<span class="label label-danger">
											Event has past
										</span>
										<br>
										<br>
									</div>
									$files_attach
								</div>
								<div class="row">
									<div class="col-md-12">
										&nbsp;<button type="button" class="btn btn-default" onclick="parent.BootstrapDialog.closeAll();">Close</button>
									</div>
								</div>	
							</div>				
						</div>
					</div>
				</div>
				~ ;				
			} else {
				$print_box_content_rows .= qq~
				<div class="row">
					<div class="col-md-2">
						<br>
							<span class="label label-danger">
								Event has past
							</span>
						<br>
						<br>
					</div>
					$files_attach
				</div>
				<div class="row">	
					<div class="col-md-12">
						&nbsp;<button type="button" class="btn btn-default" onclick="parent.BootstrapDialog.closeAll();">Close</button>
					</div>
				</div>
				~ ; 				
			}
			

		} else {
			$print_box_content_rows .= qq~
			<div class="row">
				<div class="col-md-2">
					<br>
						<span class="label label-danger">
							Event has past
						</span>
					<br>
					<br>
				</div>
				$files_attach
			</div>
			<div class="row">	
				<div class="col-md-12">
					&nbsp;<button type="button" class="btn btn-default" onclick="parent.BootstrapDialog.closeAll();">Close</button>
				</div>
			</div>
			~ ; 			
		}
 
		return ; 
		
	} else {
		
		if ($analytics_event_exists) {
			
			if ($analytics_table) {
				$analytics_table_body .= qq~
								<div class="row">
									<div class="col-md-2">
										<br>
										&nbsp;<button type="button" class="btn btn-default" onclick="parent.BootstrapDialog.closeAll();">Close</button>
										<br>
										<br>
									</div>
									$files_attach
								</div>
							</div>				
						</div>
					</div>
				</div>
				~ ;				
			} else {
				
				$print_box_content_rows .= qq~	
					<div class="row">
						<div class="col-md-2">
							<br>
							<span class="label label-danger">Analytics Required</span>
							<br>
							<br>
						</div>
						$files_attach
					</div>
					<div class="row">	
						<div class="col-md-12">
							&nbsp;<button type="button" class="btn btn-default" onclick="parent.BootstrapDialog.closeAll();">Close</button>
						</div>
					</div>
				~ ;
				
				
			}
			
			# my $analytics_required = ($analytics_table) ? qq~&nbsp;<button type="button" class="btn btn-default" onclick="parent.BootstrapDialog.closeAll();">Close</button>~ : qq~<span class="label label-danger">Analytics Required</span>~ ;
			
			# my $close_button = (!$analytics_table) ? qq~
				# <div class="row">
					# <div class="col-md-12">
						# &nbsp;<button type="button" class="btn btn-default" onclick="parent.BootstrapDialog.closeAll();">Close</button>
					# </div>
				# </div>	
			# ~ : qq~~ ; 
			

			
		} else {
			
			$print_box_content_rows .= qq~	
				<div class="row">
					<div class="col-md-2">
						<br>
						&nbsp;<button type="button" class="btn btn-default" onclick="parent.BootstrapDialog.closeAll();">Close</button>
						<br>
						<br>
					</div>
					$files_attach
				</div>
			~ ;			
			
		}
	
	}
	
	
	if ($time_subscribed{$userid}{"$dy1$dm1$dd1$th1"} and $cat{$date_start}{$date_end}{$id}{$userid} ne 'available') { $print_box_content_rows .= qq~<span class="label label-danger">You're already booked for an event during this time</span>~; return ; } # busy on another event already, avoid double booking
	if ($time_subscribed{$userid}{"$dy2$dm2$dd2$th2"} and $cat{$date_start}{$date_end}{$id}{$userid} ne 'available') { $print_box_content_rows .= qq~<span class="label label-danger">You're already booked for an event during this time</span>~; return ; } # busy on another event already, avoid double booking
	
	return unless substr($usertype,0,6) eq 'casual' ;
	
	# my $is_operator = uc substr($usertype,0,6) ;
	# unless (substr($usertype,0,6) eq 'casual') { $print_box_content_rows .= qq~<span class="label label-danger">$is_operator</span>~; return  ; }
	
	my $casual_type = uc substr($usertype,-1,1) ;

	# return if $fully_substribed{$casual_type} and $cat{$date_start}{$date_end}{$id}{$userid} and $cat{$date_start}{$date_end}{$id}{$userid} ne 'available' ;
	# return if $fully_substribed{$casual_type} and $saction eq 'available' and $this_user_subscribed{$userid} != 1 ;
		
	return unless $butttxt ;

	$print_box_content_rows .= qq~<div class="clear"></div>~ ;

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

sub process_date {
	
	my ($date_string) = @_ ; 
	
	my $year = substr($date_string, 0, 4) ; 
	my $month = substr($date_string, 5, 2) ; 
	$month = int($month); 
	$month = $month_array[$month - 1] ;
	my $day = substr($date_string, 8, 2) ; 
	my $date_return = "$day-" ; 
	$date_return .= "$month-" ;
	$date_return .= "$year" ;
	$date_return .= " @ " . substr($date_string,11,5) ; 
	
	return $date_return ;
	
} #------------------------------------------------------------------------------------------

sub get_event_uploads {

	my ($id,$type,$folder) = @_ ;

	unless ($id and $type) { return() ; }

	my $uploads = '' ; my %uploads = () ;

	my $field = $type ; my ($doctype,$num) = split(/\_/,$field) ; $doctype .= 's' ;

	$table = $doctype unless $table ;

	my $doc = $db{$table}{$id}{$field} ;

	&common_debug("$doc") ;

	if ($doc){
		my $tooltip = qq~data-toggle="tooltip" data-placement="right" data-title="$doc"~ ;
		my @docarr = split(/\./,$doc); my $ext = pop @docarr ; my $file = pop @docarr ;
		my $dlg_title = uc substr($doc,0,4) . ' ' . $ext ;
		$file_cnt++;
		
		my $test_icon_loc = qq~$htmlpath/img/icons/doc/$ext.png~;
		my $icon_loc = qq~/img/icons/doc/$ext.png~; $icon_loc = qq~/img/icons/doc/def.png~ unless -f $test_icon_loc ;
		
		# $uploads{$type} .= qq~<a id="attach-$tag_id-$file_cnt" style='margin-left:10px;' $tooltip href="javascript:dlgMdl('/uploads/$doctype/$db{$table}{$id}{$folder}/$doc','$dlg_title','','max-dialog');"><img src='/img/icons/doc/$ext.png' style='width:40px;height:40px;'></a><a href="javascript:void(0);" id="delete-attach-$id-$file_cnt"><i class="glyphicon glyphicon-trash"></i></a>~ ;
		$uploads{$type} .= qq~<a id="attach-$id-$file_cnt" style='margin-left:10px;' $tooltip href="javascript:parent.dlgMdl('/uploads/$doctype/$db{$table}{$id}{$folder}/$doc','$dlg_title','','max-dialog');"><img src='$icon_loc' style='width:30px;height:30px;'></a>~ ;
			
		# $uploads .= qq~<a id="attach-$tag_id-$file_cnt" style='margin-left:10px;' href="javascript:dlgMdl('/uploads/$doctype\s/$db{$table}{$id}{$folder}/$db{$table}{$id}{$field}','$dlg_title','','max-dialog');"><img src='/img/icons/doc/$ext.png' style='width:40px;height:40px;'></a><a href="javascript:void(0);" id="delete-attach-$tag_id-$file_cnt"><i class="glyphicon glyphicon-trash"></i></a>~;
		}

	if ($uploads{$type}) { $uploads = $uploads{$type} ; }

	return ($uploads) ;

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

sub check_dates_booked {
	
	my ($qnr,$uid,$startdate,$enddate) = @_ ;
	
	my ($dy1,$dm1,$dd1,$th1,$tm1,$ts1) = &common_split_sql_time($startdate) ; my $startccyymmdd = $dy1 . $dm1 . $dd1 ; $start_hour{$uid}{$startccyymmdd} = $th1 ; #my $startccyymmddhr = $startccyymmdd . $th1 ;
	my ($dy2,$dm2,$dd2,$th2,$tm2,$ts2) = &common_split_sql_time($enddate) ;   my $endccyymmdd   = $dy2 . $dm2 . $dd2 ; $end_hour{$uid}{$endccyymmdd} = $th2 ; #my $endccyymmddhr   = $endccyymmdd . $th2 ;
	
	my $array_date = $startccyymmdd ;
	
	while ($array_date < $endccyymmdd) {

		my $date_dd   = substr($array_date,6,2) ;
		my $date_mm   = substr($array_date,4,2) ;
		my $date_ccyy = substr($array_date,0,4) ;

		my ($ccyy,$month,$day)  = Add_Delta_Days($date_ccyy,$date_mm,$date_dd,1) ;
		$month  = sprintf("%02s", $month) ;
		$day    = sprintf("%02s", $day) ;

		$array_date = "$ccyy$month$day" ;
		
		$start_hr = ($start_hour{$uid}{$array_date}) ? $start_hour{$uid}{$array_date} : 0 ;
		$end_hr   = ($end_hour{$uid}{$array_date}) ? $end_hour{$uid}{$array_date} : 23 ;
		
		for ($start_hr .. $end_hr) {
			my $hr = sprintf("%02s", $_) ;
			my ($year,$month,$day, $hour,$min,$sec) = Add_Delta_DHMS($date_ccyy,$date_mm,$date_dd,$hr,'00','00', 0,1,0,0);
			
			$time_subscribed{$uid}{"$array_date$hr"} = 1 ;
		}
		
		# $day_subscribed{$uid}{$array_date} = 1 ;
    }
	
} #------------------------------------------------------------------------------------------

sub display_user {

	&db_min_ro('users','id,name,username','','','') ;
	foreach my $id (keys %{$db{users}}) { 
		$user_name{$id} = $db{users}{$id}{name} ; 
	}
    
} #------------------------------------------------------------------------------------------

sub add_form {

	$boxtitle = 'Add' ;

	@user_excl_sql = () ;

	foreach (keys %{$useropts{it}}) {
		push @user_excl_sql, "username <> '$_'" ;
	}

	my $user_excl_sql = join(" AND ", @user_excl_sql) ;

	&common_min_select_opts('user_id','users','name','',1,'',$user_excl_sql) ;
	# &common_min_opts('leave_type','type',1) ;

	%col_name = () ;

	&db_min_ro($table,'*','id > 1 AND id < 10','','') ;

	&hidden_fields ;

	# $extra_form_fields = qq(<input type="hidden" name="incident_id" value="$id">) ;

	$print_box_content_rows = &common_min_add_form('events','save') ;

} #------------------------------------------------------------------------------------------
                   
sub load_events {
	   
	&db_min_ro($table,'*',"id='$id'",'','') ;
	&common_min_dialog ;
	&display_user;

	my $category = ucfirst $db{$table}{$id}{category} ;

	# my $title_row = qq(<div class="col-md-12"><label class="control-label">Title :</label> <span class="label-success label">$db{$table}{$id}{title}</span></div>) ;

	if ($db{$table}{$id}{category} eq 'leave') {
		# $title_row = '' ;
		$category = ucfirst $db{$table}{$id}{type} . ' ' . $category
		}

	if ($db{$table}{$id}{category} eq 'weekend_work') {
		$category =~ s/\_/ /g ;
		}

	$content = qq(  
		<div class="row">
			<div class="col-md-12">&nbsp;
			</div>
		</div>
		<div class="row">
			<div class="box col-md-12">
				<div class="box-inner">
					<div class="box-header well" data-original-title="">
						<h2><i class="glyphicon glyphicon-tasks"></i> Item</h2>
					</div>
					<div class="box-content">
						<div class="row">                        
							<div class="col-md-12">                                                   
								$title_row             
								<div class="col-md-12"><label class="control-label">Name :</label> $user_name{$db{$table}{$id}{user_id}}</div>                        
								<div class="col-md-12"><label class="control-label">Category :</label> <span class="label-default label">$category</span></div>                  
								<div class="col-md-12"><label class="control-label">Notes :</label> $db{$table}{$id}{notes}</div> 
								<div class="col-md-12"><label class="control-label">Start Time :</label> $db{$table}{$id}{startdate}</div>                  
								<div class="col-md-12"><label class="control-label">End Time :</label> $db{$table}{$id}{enddate}</div>                  
								<div class="col-md-12"><label class="control-label">Date Added :</label> $db{$table}{$id}{date_time}</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div><!--/row--> 
	) ;

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

sub screen1 {

my $buttons = '' ;

if ($useropts{super}{lc $username}){ 
	$buttons = qq(<button type="button" class="btn btn-primary" id="addbutt"><i class="glyphicon glyphicon-plus icon-white"></i></button>&nbsp;
	<button type="button" class="btn btn-info" id="editbutt"><i class="glyphicon glyphicon-edit icon-white"></i></button>&nbsp;
	<button type="button" class="btn btn-danger" id="delbutt"><i class="glyphicon glyphicon-trash icon-white"></i></button>&nbsp;);
	}
   
print <<ENDOFTEXT;
$dialog{'common'}{'head'}
    
<div id="content" class="col-lg-12 col-sm-12">
    <!-- content starts -->   
                       
    $print_top
    
    <div class="row">
        <div class="box col-md-12">
            <div>                    
               $content 
            </div>
        </div>
        <!--/span-->
    </div><!--/row-->
    <div class="row"><div class="box col-md-12">&nbsp;</div></div>
    <div class="row">
        <div class="box col-md-12">
            <form role="form" name="form_events" id="events-form"  method="post">
            <input type="hidden" name="iaction" id="action" value="">
            <input type="hidden" name="id"                  value="$id">
            <div class="row">
				<div class="col-md-12">
					$buttons
					<button type="button" class="btn btn-default" onclick="parent.BootstrapDialog.closeAll();">Close</button></div>
				</div>
			<div class="row"><div class="col-md-12">&nbsp;</div></div>
            </form>
        </div>
    </div>
</div> 
</div><!--/fluid-row-->   
</div><!--/.fluid-container-->

<!-- external javascript -->

<style>body { font-size: 14px; }.control-label { font-size: 14px; }</style>

$dialog{'common'}{'js'}

<script>

\$("#addbutt").click(function() {    
    \$('#action').val('add');
    \$('#events-form').submit();
});

\$("#editbutt").click(function() {    
    \$('#action').val('edit');
    \$('#events-form').submit();
});

\$("#delbutt").click(function() {    
    \$('#action').val('delete');
    \$('#events-form').submit();
});

</script>
</body>
</html>
ENDOFTEXT
#

# <div class="row"><div class="col-md-12"><button type="button" class="btn btn-success" id="addbutt">Add</button>&nbsp;<button type="button" class="btn btn-info" id="editbutt">Edit</button>&nbsp;<button type="button" class="btn btn-danger" id="delbutt"><i class="glyphicon glyphicon-trash icon-white"></i></button>&nbsp;<button type="button" class="btn btn-default" onclick="parent.BootstrapDialog.closeAll();">Close</button></div></div><div class="row"><div class="col-md-12">&nbsp;</div></div>

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

sub screen2 {

$trigger_jquery_raw .= qq(\$("#savebutt").click(function() {    
    var sc_val = \$("#selectAssigned_users").chosen().val() ;
    \$('#assigned-users').val(sc_val);    
    \$('#events-form').submit();
});) ;

&common_min_alert_type ;

&common_min_footer('id','') ;

&common_min_dialog ;
      
print <<ENDOFTEXT;
$dialog{'common'}{'head'}
    
<div id="content" class="col-lg-12 col-sm-12">
    <!-- content starts -->   
                       
    $print_top
    
    <div class="row">
        <div class="box col-md-12">
            $events_content
        </div>
        <!--/span-->
    </div><!--/row-->
    
    <div class="row">
        <div class="box col-md-12">
            <div class="box-inner">
                <div class="box-header well" data-original-title="">
                    <h2><i class="glyphicon glyphicon-tasks"></i> $boxtitle Event</h2>                    
                </div>
                <div class="box-content">
                    $print_box_content_rows
                </div>
            </div>
        </div>
    </div><!--/row--> 
	$analytics_table_body
</div><!--/row-->
    
</div><!--/fluid-row-->
    
</div><!--/.fluid-container-->

<!-- external javascript -->

<style>body { font-size: 14px; }.control-label { font-size: 14px; }</style>
<link href="$useropts{'css'}/bootstrap-dialog.css" rel='stylesheet'>
$dialog{'common'}{'js'}
<script src="$useropts{'js'}/bootstrap-datetimepicker.min.js"></script>
<script src="$useropts{'js'}/jquery.form-validator.min.js"></script>
<script src="$useropts{'js'}/bootstrap-dialog.js"></script>

<script>

\$.validate(); 

\$(document).ready(function () { 
    $trigger_jquery
});

$trigger_jquery_raw

</script>

$print_footer_jscript
$print_footer_forms
</body>
</html>
ENDOFTEXT
#

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

sub screen3 {

if (($username eq 'rory') and ($testing)) { return ; }
     
print <<ENDOFTEXT;
<!DOCTYPE html>
<html lang="en">
<head>    
    <meta charset="utf-8">
    <title>$useropts{title}</title>
    <script src="$useropts{'bower_components'}/jquery/jquery.min.js"></script>   
</head>
<body>
<script>

\$(function () {
    parent.location.reload();
    parent.BootstrapDialog.closeAll() ;
});

</script>
</body>
</html>
ENDOFTEXT
#

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

use db ;
use db_min ;
use today ;
use common ;
use common_min ;

1;