#!/usr/bin/perl

BEGIN { use lib '/usr/home/cfg' ; require push_inc ; }
    
use CGI qw( :standard ) ;
use CGI::Carp qw(fatalsToBrowser) ;
use LWP::Simple qw($ua get) ;
use Date::Calc qw(:all) ;
use MIME::Lite ;
use Mail::Sendmail ;
use Time::Piece ; 
use Spreadsheet::ParseXLSX ;
use File::Temp qw(tempfile) ;

require cfg ;

print header;   # CGI.pm method

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

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

our ($q)                = CGI -> new() ;
my $iaction             = $q -> param('iaction') ;
my $iattachdoc          = $q -> param('iattachdoc') ;

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

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

&today ;

if ($iaction eq '') {
    &screen1 ;
} elsif ($iaction eq 'upload') {
	&db_open_ro ;
		our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it
			&read_import ;
			&screen2 ;
		$db_ignore_open_close = 0 ; # do one open and one close instead of repeating it
	&db_close_conn ;
}

exit ;

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

sub read_read_import_lines {
	
	our $max_unmatched_id = 0 ; 
	
	my $upload_filehandle = $q->upload('iattachdoc') ;
	
} #------------------------------------------------------------------------------------------

sub read_import {
	
	$print_box_content_rows .= &common_min_forms_start('import-analytics-fixtures') ;
 
	my $upload_filehandle = $q->upload('iattachdoc') ;
		
	unless ($upload_filehandle) {
		$warning = "PLEASE UPLOAD AN EXCEL FILE!!!" ;
		&common_min_alert_type ;
		&screen1 ;
	}

	our %totals = () ; my $line_cnt = 0 ; my %event_cnt = () ;
	
	if ($upload_filehandle !~ /.xlsx/) {
		$error = "PLEASE UPLOAD AN EXCEL TYPE FILE!!!" ;
		&common_min_alert_type ;
		&screen1 ;
	} 

	my $file_total_amnt = 0 ; my $file_nr_of_rows = 0 ;

	our %coding_type 		= ("s" => "Standard","p" => "Premium") ; 
	# our %footage_type 		= ("s" => "SSS","r" => "Raw") ;
	our %footage_type 		= ("s" => "Pixellot","r" => "YouTube") ;
	
	our %coding_type2 		= ("standard" => "s","premium" => "p") ; 
	our %footage_type2 		= ("sss" => "s","raw" => "r","pixellot" => "s","youtube" => "r") ;
	our %service_type2 		= ("live coding" => 1,"individual 48 hrs" => 2,"post coding 24 hrs" => 3) ;

	our %fixtures_input_vals = () ; our %fixtures_input_vals_2 = () ; 

	our $suffix = "fixtures" ;
 
	if ($type eq 'xlsx') {
		
		&db_min_ro('analytics_ht_colors','id,name','','','') ;

		foreach (keys %{$db{analytics_ht_colors}}) {
			$analytics_ht_colors_name_to_id{lc $db{analytics_ht_colors}{$_}{name}} = $_ ;
		}
	
		&db_min_ro('sport_types','id,name','','','') ;

		foreach (keys %{$db{sport_types}}) {
			$sport_type_name_to_id{lc $db{sport_types}{$_}{name}} = $_ ;
		}
		$sport_type_name_to_id{"waterpolo"} = 4 ;
		
		&db_switch_conn('sss');
		
		&db_min_ro('teams','id,name','','','') ;
		
		foreach (keys %{$db{teams}}) {
			$team_name_to_id{lc $db{teams}{$_}{name}} = $_ ;
		}
		
		&db_switch_conn('aisa');
		
		my %seen_col_val = () ; 
		
		if ($type eq 'csv') {
		
			while ( <$upload_filehandle> ) {
			# foreach (@imported_file_data) {
				
				next if $_ !~ /\d+/ ;
				
				$file_nr_of_rows++ ;
				
				chomp $_ ;
				
				$_ =~ s/\R\z// ; # Removes any line-ending character (\n, \r\n, or \r)
				$_ =~ s/\"//g ; 

				my @def_split = split(/\;/,$_) ; 
				
				push @rows, \@def_split;
				 
			}
		} else {

			my ($tmpfh, $tmpfilename) = tempfile(SUFFIX => '.xlsx', UNLINK => 1);
			
			binmode $upload_filehandle ;
			binmode $tmpfh ;
			while (my $bytesread = read($upload_filehandle, my $buffer, 8192)) {
				print $tmpfh $buffer ;
			}
			close $tmpfh ;

			my $parser   = Spreadsheet::ParseXLSX->new() ;
			my $workbook = $parser->parse($tmpfilename) ;

			unless ($workbook) {
				$error = "Failed to parse Excel file: " . $parser->error() ;
				&common_min_alert_type ;
				&screen1 ;
			}

			my $worksheet = ($workbook->worksheets())[0] ;
			my ($row_min,$row_max) = $worksheet->row_range() ;
			my ($col_min,$col_max) = $worksheet->col_range() ;

			for my $row ($row_min .. $row_max) {
	
				my @def_split = ();
				for my $col ( $col_min .. $col_max ) {
					my $cell = $worksheet->get_cell( $row, $col );
					my $val = $cell ? $cell->value() : '';
					push @def_split, $val;
				}
				push @rows, \@def_split if grep { /\S/ } @def_split; # skip empty
			}
			
		}
	 	
		my $row_cnt = 0 ; my $table_row_cnt = 0 ; 
 
		foreach my $def_split_ref (@rows) {
		 
			$row_cnt++;
			my @def_split = @$def_split_ref;
			
			my %seen_row = () ; 
			
			for my $col_cnt (1 .. 13) {
			
				my $val = $def_split[$col_cnt - 1] ;
				 
				next if !$val
					|| $val =~ /Analytics-Fixtures/ 
					|| $val =~ /Analytics Fixtures/ 
					|| $val =~ /Fixture Date/
					|| $val =~ /Fixtures Date/
					|| $val =~ /Time From/ 
					|| $val =~ /Sport/ 
					|| $val =~ /Team/ 
					|| $val =~ /HT Colour/ 
					|| $val =~ /Away Team/ 
					|| $val =~ /Coding Type/ 
					|| $val =~ /Footage Type/ 
					|| $val =~ /Service Type/ 
					|| $val =~ /Age Group/
					|| $val =~ /Stream Forwarding/ 
					|| $val =~ /Stream Key/ 
					|| $val =~ /Stream URL/
					|| $val =~ /Stream url/
					|| $val =~ /Stream Url/
					|| $val =~ /Cant Charge Client/
				;
				 
				$table_row_cnt++ unless $seen_row{$row_cnt} ;
				$seen_row{$row_cnt} = 1 ;
 
				if ($col_cnt == 1) { 
					$val =~ s/\T//g ;
				} elsif ($col_cnt == 2) {
					$val = $sport_type_name_to_id{lc $val} ;
				} elsif ($col_cnt == 3 || $col_cnt == 4) {
					$val = lc $val ;
				} elsif ($col_cnt == 5 || $col_cnt == 7) {
					$fixtures_input_vals_2{$table_row_cnt}{$col_cnt} = $val if $val;
					$val = $team_name_to_id{lc $val} ;
				} elsif ($col_cnt == 6) {
					$val = $analytics_ht_colors_name_to_id{lc $val} ;
				} elsif ($col_cnt == 8) {
					$val = $coding_type2{lc $val} ;
				} elsif ($col_cnt == 9) {
					$val = $footage_type2{lc $val} ; 
				} elsif ($col_cnt == 10) {
					$val = $service_type2{lc $val} ; 
				} elsif ($col_cnt == 11) {
					$val = (lc $val eq 'yes') ? 1 : (lc $val eq 'no') ? 2 : 0 ; 
				} elsif ($col_cnt == 12 || $col_cnt == 13) {
					$val =~ s/_x000D_//g ;
					$val = join("_new_line_character_", map {"$_"} split("\n",$val)) ; 
				}
				
				$fixtures_input_vals{$table_row_cnt}{$col_cnt} = $val if $val;
 
			}	
		 
		}
		
	}
 
	our %col_cnt_field_id = () ; our %col_cnt_field_id_2 = () ; 
	
	$col_cnt_field_id{1}	= "datetimepickerStart_date_time_fixtures_"    	;
	$col_cnt_field_id{2}	= "selectReadonly_sport_fixtures_"				;
	$col_cnt_field_id{3}	= "selectAge_group_fixtures_"                  	;
	$col_cnt_field_id{4}	= "selectTeam_fixtures_"                       	;
	$col_cnt_field_id{5}	= "input[name='home_team_fixtures_"				;
	$col_cnt_field_id_2{5}	= "input[name='typeahead_home_team_fixtures_"	;
	$col_cnt_field_id{6} 	= "selectHt_colour_fixtures_"                  	;
	$col_cnt_field_id{7} 	= "input[name='away_team_fixtures_"				;
	$col_cnt_field_id_2{7} 	= "input[name='typeahead_away_team_fixtures_"	;
	$col_cnt_field_id{8} 	= "selectCoding_type_fixtures_"                	;
	$col_cnt_field_id{9} 	= "selectFootage_type_fixtures_"               	;
	$col_cnt_field_id{10} 	= "selectService_type_fixtures_"				;
	$col_cnt_field_id{11} 	= "selectStream_forwarding_fixtures_"			;
	$col_cnt_field_id{12} 	= "textareaStream_key_fixtures_"				;
	$col_cnt_field_id{13}	= "textareaStream_URL_fixtures_"				;
	
	our $col_cnt_field_id_str = qq~~ ;  our $col_cnt_field_id_str_2 = qq~~ ;

	our $col_cnt_field_id_str2 = qq~"11":"selectStream_forwarding_analytics_","12":"textareaStream_key_analytics_","13":"textareaStream_URL_analytics_"~ ; 
	
	foreach (keys %col_cnt_field_id) {
		$col_cnt_field_id_str .= qq~"$_":"$col_cnt_field_id{$_}",~ ;
	}
	$col_cnt_field_id_str =~ s/\,+$//g ; 	
	
	foreach (keys %col_cnt_field_id_2) {
		$col_cnt_field_id_str_2 .= qq~"$_":"$col_cnt_field_id_2{$_}",~ ;
	}
	$col_cnt_field_id_str_2 =~ s/\,+$//g ; 
	
	our $max_row_cnt = 0 ; 
	
	our $fixtures_input_vals_str = qq~~ ; 
	our $fixtures_input_vals_str_2 = qq~~ ; 
	
	our %add_select_options = () ; 
	
	foreach my $row_cnt (sort {$a <=> $b} keys %fixtures_input_vals_2) {
		$fixtures_input_vals_str_2 .= qq~"$row_cnt":{~ ;
		foreach my $col_cnt (sort {$a <=> $b} keys %{$fixtures_input_vals_2{$row_cnt}}) {
			$fixtures_input_vals_str_2 .= qq~"$col_cnt":"$fixtures_input_vals_2{$row_cnt}{$col_cnt}",~ ;
		}
		$fixtures_input_vals_str_2 =~ s/\,+$//g ;
		$fixtures_input_vals_str_2 .= qq~},~ ;
	}
	$fixtures_input_vals_str_2 =~ s/\,+$//g ;
			
	foreach my $row_cnt (sort {$a <=> $b} keys %fixtures_input_vals) {
		
		$max_row_cnt = $row_cnt if !$max_row_cnt || $row_cnt > $max_row_cnt ;
		$fixtures_input_vals_str .= qq~"$row_cnt":{~ ;
		foreach my $col_cnt (sort {$a <=> $b} keys %{$fixtures_input_vals{$row_cnt}}) {
			$fixtures_input_vals_str .= qq~"$col_cnt":"$fixtures_input_vals{$row_cnt}{$col_cnt}",~ ;
			if ($col_cnt == 2) {
				$add_select_options{selectReadonly_sport_fixtures}{$fixtures_input_vals{$row_cnt}{$col_cnt}} = $db{sport_types}{$fixtures_input_vals{$row_cnt}{$col_cnt}}{name} ;
			} elsif ($col_cnt == 5) {
				# $add_select_options{selectHome_team_fixtures}{$fixtures_input_vals{$row_cnt}{$col_cnt}} = $db{teams}{$fixtures_input_vals{$row_cnt}{$col_cnt}}{name} ;
			} elsif ($col_cnt == 7) {
				# $add_select_options{selectAway_team_fixtures}{$fixtures_input_vals{$row_cnt}{$col_cnt}} = $db{teams}{$fixtures_input_vals{$row_cnt}{$col_cnt}}{name} ;
			} elsif ($col_cnt == 11) {
				
			}
		}
		$fixtures_input_vals_str =~ s/\,+$//g ;
		$fixtures_input_vals_str .= qq~},~ ;
	}

	$fixtures_input_vals_str =~ s/\,+$//g ;
	
	$fixtures_input_vals_str =~ s/\R\z// ; # Removes any line-ending character (\n, \r\n, or \r)
	
	# print "\n fixtures_input_vals_str : $fixtures_input_vals_str" ;
	
	return unless $max_row_cnt ;
	
} #------------------------------------------------------------------------------------------

sub screen1 {

	&common_min_dialog ;

	$print_box_content_rows .= qq~<div class="col-md-6"><div class="form-group"></div></div>~;
	  
	# my $date_inputs = &common_min_form_datepicker() ; 
	  
	print <<ENDOFTEXT;
	$dialog{'common'}{'head'}
		
	<div id="content" class="col-lg-12 col-sm-12">
		<!-- content starts --> 
		
		$alert
		
		<div class="row">
			<div class="box col-md-12">
				<form role="form" name="form_import" id="import-form" action="?$type" method="post" enctype="multipart/form-data">
				<div class='row'>
					<div class='col-md-9'>
						<div class='control-group'>
							<div class='controls'> 
								<label for="imageInputFile">Import EXCEL</label>
								<input type="file" id="imageInputFile" name='iattachdoc' tabindex='1'>
								<p class="help-block">Upload file from PC.</p>
							</div>
						</div>
					</div>
				</div>
				<input type="hidden" name="iaction" id="action" value="upload">
				<div class="row"><div class="col-md-12">&nbsp;</div></div>
				<div class="row">
					<div class="col-md-12">	
						<button type="button" class="btn btn-primary" id="importbutt">Upload</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>
				</form>
			</div>
		</div>
	</div> 
	</div><!--/fluid-row-->   
	</div><!--/.fluid-container-->

	<!-- external javascript -->

	<style>body { font-size: 14px; }.control-label { font-size: 14px; }</style>
	<script src="$useropts{'js'}/jquery.form-validator.min.js"></script>

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

	<script>

	\$.validate();

	\$("#importbutt").click(function() {    
		\$('#action').val('upload');
		\$('#import-form').submit();
	});

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

exit ;

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

sub screen2 {
 
	$trigger_jquery_raw .= qq~let value_exists ; ~ ;
	
	my $sport_options = qq~~ ;
	foreach (keys %{$add_select_options{selectReadonly_sport_fixtures}}) {
		$sport_options = qq~"$_",~ ;
	}
	chop $sport_options if $sport_options ;
	
	foreach my $field (keys %add_select_options) {
		
		my %seen_value = () ;
		$trigger_jquery_raw .= qq~ 
			parent.\$("#selectSport_type_ids").val([$sport_options]).trigger("chosen:updated") ;
		~ if $field eq "selectReadonly_sport_fixtures" && $sport_options ;	
		
		foreach my $value (keys %{$add_select_options{$field}}) {
			
			$trigger_jquery_raw .= qq~
				value_exists = parent.\$("#$field"+"_1 option[value='$value']").length > 0 ;
				if (!value_exists) {
					parent.\$("#$field"+"_1").append("<option value='$value'>$add_select_options{$field}{$value}</option>").trigger("chosen:updated") ;	
					for (let k = 2; k <= 100; k++) {
						if (!parent.\$("#fixtures_"+k).html()) { break ; }
						parent.\$("#$field"+"_"+k).append("<option value='$value'>$add_select_options{$field}{$value}</option>").trigger("chosen:updated") ;
					}
				}
			~ unless $seen_value{$value} ;
			
			$seen_value{$value} = 1 ;
			
		}
	}
	#  let fixtures_input_vals = {$fixtures_input_vals_str} ; 
	$trigger_jquery_raw .= qq~
		 
		let col_cnt_field_id = {$col_cnt_field_id_str} ;
		let col_cnt_field_id_2 = {$col_cnt_field_id_str_2} ;
		let col_cnt_field_id2 = {$col_cnt_field_id_str2} ;
		
		let fixtures_input_vals = {$fixtures_input_vals_str} ; 
		let fixtures_input_vals_2 = {$fixtures_input_vals_str_2} ; 
		
		let max_row_cnt = parseInt("$max_row_cnt") ; 
		let default_val ;
		let earliest_date ; let latest_date ; 
		
		if (!max_row_cnt) {
			 parent.BootstrapDialog.closeAll() ;
		}
		
		for (let j = 1; j <= max_row_cnt; j++) {
 
			if (!parent.\$("#fixtures_"+j).html()) {
				add_row(j) ;
			} else if (parent.\$("#fixtures_"+j).css("display") === "none" && parent.\$("#fixtures_"+j).html()) {
				parent.\$("#fixtures_"+j).show() ;
			}

			default_val = (fixtures_input_vals[j][1]) ? fixtures_input_vals[j][1] : parent.\$("input[name='start_date_time']").val() ;

			parent.\$("#"+col_cnt_field_id[1]+""+j).datetimepicker("setDate",default_val) ;
			
			if (fixtures_input_vals[j][1]) {
				parent.\$("input[name='changed_fixtures_date_"+j+"']").val("1") ;
				let this_date 	= new Date(fixtures_input_vals[j][1]) ;
				this_date   	= new Date(this_date.getTime() + 2 * 60 * 60 * 1000) ; // Add 2 hours 
				earliest_date 	= (!earliest_date || (earliest_date && earliest_date > this_date)) ? this_date : earliest_date ;
				latest_date 	= (!latest_date || (latest_date && latest_date < this_date)) ? this_date : latest_date ;
			} else {
				parent.\$("input[name='changed_fixtures_date_"+j+"']").val("") ;
			}
			
			if (fixtures_input_vals[j][2]) {
				parent.\$("input[name='sport_fixtures_"+j+"']").val(fixtures_input_vals[j][2]) ;
			} else {
				parent.\$("input[name='sport_fixtures_"+j+"']").val("") ;
			}
			
			if (fixtures_input_vals[j][4]) {
				parent.\$("input[name='changed_home_team_"+j+"']").val("1") ;
			} else {
				parent.\$("input[name='changed_home_team_"+j+"']").val("") ;
			}
			
			for (let col_cnt = 2; col_cnt <= 10; col_cnt++) {
				
				if (col_cnt == 5 || col_cnt == 7) {
					continue ;
				}

				if (fixtures_input_vals[j][col_cnt]) {
					parent.\$("#"+col_cnt_field_id[col_cnt]+""+j).val(fixtures_input_vals[j][col_cnt]).trigger("chosen:updated") ;
				}
				
			}
			
			for (let col_cnt = 2; col_cnt <= 10; col_cnt++) {
				
				if (col_cnt != 5 && col_cnt != 7) {
					continue ;
				}
				
				let input_name = col_cnt_field_id[col_cnt] ;
				
				if (fixtures_input_vals[j][col_cnt]) {
					parent.\$(input_name+""+j+"']").val(fixtures_input_vals[j][col_cnt]) ;
				}
				
				input_name = col_cnt_field_id_2[col_cnt] ;
				
				if (fixtures_input_vals_2[j][col_cnt]) {
					parent.\$(input_name+""+j+"']").val(fixtures_input_vals_2[j][col_cnt]) ;
				}
				
			}
			
			for (let col_cnt = 11; col_cnt <= 13; col_cnt++) {
				if (fixtures_input_vals[j][col_cnt]) {
					let input_val = fixtures_input_vals[j][col_cnt] ;
					input_val = input_val.replaceAll("_new_line_character_","\\n") ;
					parent.\$("#"+col_cnt_field_id[col_cnt]+""+j).val(input_val).trigger("chosen:updated") ;
					if (parent.\$("#analytics_"+j).html()) {
						parent.\$("#"+col_cnt_field_id2[col_cnt]+""+j).val(input_val).trigger("chosen:updated") ;
					}
				}
			}
		}
		
		let start_date 	= new Date(parent.\$("input[name='start_date_time']").val()) ;
		let end_date 	= new Date(parent.\$("input[name='end_date_time']").val()) ;
		
		start_date	= new Date(start_date.getTime() + 2 * 60 * 60 * 1000) ; // Add 2 hours 
		end_date   	= new Date(end_date.getTime() + 2 * 60 * 60 * 1000) ; // Add 2 hours 
		
		if (earliest_date) {

			if (earliest_date < start_date) {

				parent.\$("#datetimepickerStart_date_time").datetimepicker("setDate",earliest_date) ;
				
				for (let h = 1; h <= 100; h++) {
					if (!\$("#fixtures_"+h).html()) {
						break ;changed_fixtures_date_4
					}
					if (\$("input[name='changed_fixtures_date_"+h+"']").val() || h == row_nr) {
						continue ;
					}
					\$("#datetimepickerStart_date_time_fixtures_"+h).datetimepicker("setDate",earliest_date) ;
				} 
			}  
			let earliest = new Date(earliest_date);
			parent.\$("#datetimepickerStart_date_time").datetimepicker("setEndDate",earliest);
			
		}
		if (latest_date) {
			if (latest_date > end_date) {
				parent.\$("#datetimepickerEnd_date_time").datetimepicker("setDate",latest_date) ;
			} else {
				
			}
			let latest = new Date(latest_date);
			parent.\$("#datetimepickerEnd_date_time").datetimepicker("setStartDate",latest);
		}
		
	~	;
	
	if ($max_row_cnt) {
		$trigger_jquery_raw .= qq~
			parent.\$("#selectTotal_fixtures").val(max_row_cnt).trigger("chosen:updated") ; 
			for (let k = max_row_cnt+1; k <= 100; k++) {
				if (!parent.\$("#fixtures_"+k).html()) {
					break ;
				} else {
					parent.\$("#fixtures_"+k).css("display","none") ;
				}
			}
		~ ; 
	} 

	$trigger_jquery_raw .= qq~
		 
		function add_row (i) {
								
			parent.\$("input[name='home_team_fixtures_1']").after("<input name='home_team_fixtures_"+i+"' value='' class='hidden'>") ;
			parent.\$("input[name='away_team_fixtures_1']").after("<input name='away_team_fixtures_"+i+"' value='' class='hidden'>") ;
			
			let html = "<div class='row' id='fixtures_"+i+"'>" ;
			
				html += "<input name='changed_fixtures_date_"+i+"' type='hidden' value=''>" ;
				html += "<input name='changed_home_team_"+i+"' type='hidden' value=''>" ;
				
				html += "<div class='col-md-3'><div class='row'>" ;
				
					html += add_datetimepicker(i,"start_date_time_$suffix",1,6,\$("input[name='start_date_time']").val()) ; 
					html += add_select(i,"readonly_sport_$suffix\_"+i,"selectReadonly_sport_$suffix\_"+i,"Select Sport "+i,"",2,4,100,"","") ;
					html += "<input name='sport_$suffix\_"+i+"' value='' style='display:none;'>" ;
					html += add_select(i,"age_group_$suffix\_" + i,"selectAge_group_$suffix\_" + i,"Select Age Group "+i,"",3,2,100,"","") ;
				 
				html += "</div></div>" ; 
				 
				html += "<div class='col-md-6'><div class='row'>" ;
				 
					html += add_select(i,"team_$suffix\_"+i,"selectTeam_$suffix\_"+i, "Select Team "+i,"",4,1,100,"","") ;
					// html += add_select(i,"home_team_$suffix\_"+i,"selectHome_team_$suffix\_"+i, "Select Home Team "+i,"",5,2,100,"","") ;
					html += add_input(i,"typeahead_home_team_$suffix\_" + i, "inputTypeahead_home_team_$suffix\_" + i, "Select Home Team "+i, 5, "", 2,'') ;
					html += add_select(i,"ht_colour_$suffix\_" + i, "selectHt_colour_$suffix\_" + i, "Select Ht Colour "+i, "", 6, 2, 100, "", "") ;
					// html += add_select(i,"away_team_$suffix\_" + i, "selectAway_team_$suffix\_" + i, "Select Away Team "+i, "", 7, 2, 100, "", "") ;
					html += add_input(i,"typeahead_away_team_$suffix\_" + i, "inputTypeahead_away_team_$suffix\_" + i, "Select Away Team "+i, 5, "", 2,'') ;
					html += add_select(i,"coding_type_$suffix\_" + i, "selectCoding_type_$suffix\_" + i, "Select Coding Type "+i,"", 8, 2, 100, "", "") ;
					html += add_select(i,"footage_type_$suffix\_" + i, "selectFootage_type_$suffix\_" + i, "Select Footage Type "+i, "", 9, 1, 100, "", "") ;
					html += add_select(i,"service_type_$suffix\_" + i, "selectService_type_$suffix\_" + i, "Select Service Type "+i, "", 10, 2, 100, "", "") ;
					
				html += "</div></div>" ;
				html += "<div class='col-md-3'><div class='row'>" ;
				
					html += add_select(i,"stream_forwarding_$suffix\_" + i, "selectStream_forwarding_$suffix\_" + i, "Select Stream Forwarding "+i,"", 11, 2, 100, "", "") ;
					html += add_textarea (i,"stream_key_$suffix\_"+i,"textareaStream_key_$suffix\_"+i,"Stream Key "+i,12,"",4) ;
					html += add_textarea (i,"stream_URL_$suffix\_"+i,"textareaStream_URL_$suffix\_"+i,"Stream URL "+i,13,"",4) ;			
					html += add_checkbox (i,"cant_charge_client_$suffix\_"+i,"textareaCant_charge_client_$suffix\_"+i,14,2) ;			
				
				html += "</div></div>" ;
			
			html += "</div>" ;	
			
			parent.\$("#fixtures_table").append(html).trigger("chosen:updated") ;			
			
			parent.create_typeahead('fixtures_table',"[name^='typeahead_away_team_$suffix\_"+i+"'],[name^='typeahead_home_team_$suffix\_"+i+"']") ; 
			
			parent.\$('#datetimepickerStart_date_time_$suffix\_'+i).datetimepicker({language: 'pt-BR'}) ;  

			let options ;
			
	~ ;

	foreach (keys %col_cnt_field_id) {
		
		next if $_ == 1 ;
		
		$trigger_jquery_raw .= qq~
	
			options	= parent.\$("#$col_cnt_field_id{$_}"+"1").children().clone();
			parent.\$("#$col_cnt_field_id{$_}"+i).append(options).trigger("chosen:updated") ;
	
		~ ;
		
	}

	$trigger_jquery_raw .= qq~

			parent.\$("#selectService_type_$suffix\_"+i+",#selectAge_group_$suffix\_"+i+",#selectTeam_$suffix\_"+i+",#selectStream_forwarding_$suffix\_"+i).chosen({ allow_single_deselect:false }) ;
			parent.\$("#selectReadonly_sport_$suffix\_"+i+",#selectHt_colour_$suffix\_"+i+",#selectCoding_type_$suffix\_"+i+",#selectFootage_type_$suffix\_"+i).chosen({ allow_single_deselect:false }) ;
			parent.\$("#selectService_type_$suffix\_"+i+"_chosen,#selectReadonly_sport_$suffix\_"+i+"_chosen,#selectAge_group_$suffix\_"+i+"_chosen,#selectTeam_$suffix\_"+i+"_chosen,#selectHt_colour_$suffix\_"+i+"_chosen,#selectCoding_type_$suffix\_"+i+"_chosen,#selectFootage_type_$suffix\_"+i+"_chosen").css("width","100%") ;
		}
				
		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,checked) {
			let checkbox = "<div class='col-md-"+fcol+"' id='c_cant_charge_client_fixtures_"+row_nr+"'><input name='"+field_name+"' data-no-uniform='true' type='checkbox' id='"+field_id+"' "+checked+" value='1' tabindex='"+tindex+"'></div>" ;
			return checkbox ;
		}
		
		function add_textarea (row_nr,field_name,field_id,placeholder,tindex,readonly,fcol,default_val="",width="100",height="22.5",hide="") {
			let textarea = "<div class='col-md-"+fcol+"'><div class='control-group'><div class='controls'><textarea name='"+field_name+"' class='form-control' id='"+field_id+"' placeholder='"+placeholder+"' "+readonly+" tabindex='"+tindex+"' style='width:"+width+"%;height:"+height+"px;display:"+hide+";'>"+default_val+"</textarea></div></div></div>" ;
			return textarea ;
		}
		
		function add_input (row_nr,field_name,field_id,placeholder,tindex,readonly,fcol,default_val) {
			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+"' placeholder='"+placeholder+"' value='"+default_val+"' "+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_datetimepicker (row_nr,field_name,tindex,fcol,default_val) {
			let ucfirst_field_name = ucfirst(field_name) ;
			let datetimepicker = "<div class='col-md-"+fcol+"'><div class='control-group'><div style='margin:2px 0 2px 0;' class='input-group controls input-append date' data-date='"+default_val+"' id='datetimepicker"+ucfirst_field_name+"_"+row_nr+"'><input style='margin:0;' data-format='yyyy-MM-dd hh:mm:ss' class='form-control' name='"+field_name+"_"+row_nr+"' value='"+default_val+"' tabindex='"+tindex+"'><span class='input-group-addon add-on'><i data-time-icon='icon-time' data-date-icon='icon-calendar' class='icon-calendar'></i></span></div></div></div>" ;
			return datetimepicker ;
		}
		
		function ucfirst(str) {
			if (!str) return str; // Handle empty string
			return str.charAt(0).toUpperCase() + str.slice(1) ;
		}

		parent.BootstrapDialog.closeAll() ;
		
	~ ;
	
	&common_min_dialog_save_screen_test_2 ;

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

sub common_min_dialog_save_screen_test_2 {

print <<ENDOFTEXT;
<!DOCTYPE html>
<html lang="en">
<head>    
    <meta charset="utf-8">
    <title>ITV Admin</title>
    <script src="$useropts{'bower_components'}/jquery/jquery.min.js"></script>   
</head>
<body>
$extra_js
<script>
\$(function () {
	$trigger_jquery_raw
});

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

exit ;

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

sub common_min_dialog_save_screen_test {

print <<ENDOFTEXT;
<!DOCTYPE html>
<html lang="en">
<head>    
    <meta charset="utf-8">
    <title>ITV Admin</title>
    <script src="$useropts{'bower_components'}/jquery/jquery.min.js"></script>   
    <link href="/css/bootstrap-itv.min.css?1.0" rel="stylesheet">
    <link href="/css/custom-itv.css" rel="stylesheet">
    <link href="/css/charisma-app.css" rel="stylesheet">
    <link href="/bower_components/fullcalendar/dist/fullcalendar.css" rel='stylesheet'>
    <link href="/bower_components/fullcalendar/dist/fullcalendar.print.css" rel='stylesheet' media='print'>
    <link href="/bower_components/chosen/chosen.min.css" rel='stylesheet'>
    <link href="/bower_components/colorbox/example3/colorbox.css" rel='stylesheet'>
    <link href="/bower_components/responsive-tables/responsive-tables.css" rel='stylesheet'>
    <link href="/bower_components/bootstrap-tour/build/css/bootstrap-tour.min.css" rel='stylesheet'>
    <link href="/css/jquery.noty.css" rel='stylesheet'>
    <link href="/css/noty_theme_default.css" rel='stylesheet'>
    <link href="/css/elfinder.min.css" rel='stylesheet'>
    <link href="/css/elfinder.theme.css" rel='stylesheet'>
    <link href="/css/jquery.iphone.toggle.css" rel='stylesheet'>
    <link href="/css/uploadify.css" rel='stylesheet'>
    <link href="/css/animate.min.css" rel='stylesheet'>
    <link href="/css/bootstrap-dialog.css" rel='stylesheet'>
	<link href="/css/bootstrap-datetimepicker.min.css" rel='stylesheet'>
    <link href="/css/datepicker.css" rel='stylesheet'>
</head>
<body>
<script>

\$(function () {
	$trigger_jquery_raw
});

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

exit ;

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

use today ;
use common ; 
use common_min ; 
use common_shared ; 