sub analytics_event_bookings_tabs_build_qt_left {

	my ($id,$tab,$ret) = @_ ;
	
	if ($tab == 1) {  # Cusotmer Details

		# --------------- START CUSOTMER DETAILS --------------------------------------------------------------------------------------------------------
		
		my $sec = '_customer_details' ; 
		
		my ($sec_name,$sec_cnt,$sec_col) = &analytics_event_bookings_tabs_sec_det($sec) ;
		
		$ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ;
		
		return if $ret ;
		
		$lcol = 2 ; $fcol = 1 ; $add_form_fields = '' ;
	
	# $add_form_fields .= qq~<div style="display:none;">~ if $is_schools_manager ; 
		$add_form_fields .= qq~<div style="display:none;">~ if $glod_user_level < 3  && $usertype ne 'analytics_client' ; 
			
		my $checked = ($db{$table}{$id}{event_completed}) ? 'CHECKED' : '' ; 
		$preferred_title{event_completed} = "Event Completed" ;
		$add_form_fields .= &common_min_form_checkbox('event_completed',$db{$table}{$id}{event_completed},$checked) ;
		
		# my $checked = 'CHECKED' if $db{$table}{$id}{event_accepted} ;
		my $checked = ($db{$table}{$id}{event_accepted}) ? 'CHECKED' : '' ; 
		$preferred_title{event_accepted} = "Event Accepted" ;
		$add_form_fields .= &common_min_form_checkbox('event_accepted',$db{$table}{$id}{event_accepted},$checked) ;
		
		my $checked = ($db{$table}{$id}{event_rejected}) ? 'CHECKED' : '' ;
		$preferred_title{event_rejected} = "Event Rejected" ;
		$add_form_fields .= &common_min_form_checkbox('event_rejected',$db{$table}{$id}{event_rejected},$checked) ;
				
		# my $checked = 'CHECKED' if $db{$table}{$id}{event_pending} or $iaction eq 'add' ;
		my $checked = ($db{$table}{$id}{event_pending} || $iaction eq 'add') ? 'CHECKED' : '' ;
		$preferred_title{event_pending} = "Event Pending" ;
		$add_form_fields .= &common_min_form_checkbox('event_pending',$db{$table}{$id}{event_pending},$checked) ;
		
		# my $checked = 'CHECKED' if $db{$table}{$id}{event_cancelled} ; 
		my $checked = ($db{$table}{$id}{event_cancelled}) ? 'CHECKED' : '' ;
		$preferred_title{event_cancelled} = "Event Cancelled" ;
		$add_form_fields .= &common_min_form_checkbox('event_cancelled',$db{$table}{$id}{event_cancelled},$checked) ;
			
		# $add_form_fields .= qq~</div>~ if $is_schools_manager ; 
		$add_form_fields .= qq~</div>~ if $glod_user_level < 3 && $usertype ne 'analytics_client' ; 
			
		# $add_form_fields .= qq~</div>~ if $is_schools_manager ; 
		$add_form_fields .= qq~</div>~ if $glod_user_level < 3 && $usertype ne 'analytics_client' ; 

		$fcol = 4 ;
		$add_form_fields .= &common_min_form_input('contact_name',$db{$table}{$id}{contact_name},'') ;
		$add_form_fields .= &common_min_form_input('address',$db{$table}{$id}{address},'') ;
		$add_form_fields .= &common_min_form_input('email',$db{$table}{$id}{email},'') ;
		$add_form_fields .= &common_min_form_input('tel',$db{$table}{$id}{tel},'') ;
		# $fcol = 5 ;

		$add_form_fields .= qq~<div class='row'><div class='col-md-12' style="height:12px;">&nbsp;</div></div>~ ;
		
		&analytics_event_bookings_tabs_content_box($sec_name,$sec_col);

		$trigger_jquery_raw .= qq~

			if (!\$("#checkboxEvent_accepted").is(":checked") && !\$("#checkboxEvent_rejected").is(":checked") && !\$("#checkboxEvent_pending").is(":checked") && !\$("#checkboxEvent_cancelled").is(":checked") && !\$("#checkboxEvent_completed").is(":checked")) {
					\$("#checkboxEvent_pending").prop("checked","true") ;
			}
		
			\$("#checkboxEvent_completed,#checkboxEvent_accepted,#checkboxEvent_rejected,#checkboxEvent_pending,#checkboxEvent_cancelled").click( function () {
				
				if (this.id != 'checkboxEvent_completed' && \$("#checkboxEvent_completed").is(":checked")) {
					\$("#checkboxEvent_completed").prop("checked",false) ;
				}	
				
				if (this.id != 'checkboxEvent_accepted' && \$("#checkboxEvent_accepted").is(":checked")) {
					\$("#checkboxEvent_accepted").prop("checked",false) ;
				}
				
				if (this.id != 'checkboxEvent_rejected' && \$("#checkboxEvent_rejected").is(":checked")) {
					\$("#checkboxEvent_rejected").prop("checked",false) ;
				}	
				
				if (this.id != 'checkboxEvent_pending' && \$("#checkboxEvent_pending").is(":checked")) {
					\$("#checkboxEvent_pending").prop("checked",false) ;
				}
				
				if (this.id != 'checkboxEvent_cancelled' && \$("#checkboxEvent_cancelled").is(":checked")) {
					\$("#checkboxEvent_cancelled").prop("checked",false) ;
				}				
				
				if (this.id == 'checkboxEvent_completed' && !\$("#checkboxEvent_accepted").is(":checked")) {
					\$("#checkboxEvent_accepted").prop("checked",true) ;
				}	
				
				if (!\$("#checkboxEvent_accepted").is(":checked") && !\$("#checkboxEvent_rejected").is(":checked") && !\$("#checkboxEvent_pending").is(":checked") && !\$("#checkboxEvent_cancelled").is(":checked") && !\$("#checkboxEvent_completed").is(":checked")) {
					\$("#checkboxEvent_pending").prop("checked","true") ;
				}
				
			});
		
		~ ; 

		# --------------- END CUSOTMER DETAILS ----------------------------------------------------------------------------------------------------------
	}

	if ($tab == 2) {  # Cusotmer Details

		# --------------- START CUSOTMER DETAILS --------------------------------------------------------------------------------------------------------
		
		return if $ret ;
		
		my $sec = '_event_details' ; 
		
		my ($sec_name,$sec_cnt,$sec_col) = &analytics_event_bookings_tabs_sec_det($sec) ;
		
		$ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ;
		$preferred_title{sport_type_ids} = "Sport Type(s)" ; 
		$preferred_title{start_date_time} = "Event Date/Time From" ; 
		$preferred_title{end_date_time} = "Event Date/Time To" ; 
		$add_form_fields  = "" ;
		
		
		foreach (sort {$a <=> $b} keys %service_types) {
			$opts{service_type_id} .= qq~<option value="$_">$service_types{$_}</option>~ ; 
			$opts{service_type} .= qq~<option value='$_'>$service_types{$_}</option>~ ; 
		} 
		
		foreach (split(/\,/,$db{$table}{$id}{sport_type_ids})) {
			$opts{sport_type_ids} =~ s/value="$_"/value="$_" SELECTED/g ;
		}
		
		$db{$table}{$id}{service_type_id} = 3 unless $db{$table}{$id}{service_type_id};
		
		# $opts{service_type} = $opts{service_type_id} ;
		
		for (1 .. 100) {
			$opts{total_fixtures} .= qq~<option value="$_">$_</option>~ ;
		}
		
		$db{$table}{$id}{total_fixtures} = 1 unless $db{$table}{$id}{total_fixtures} ;
		
		$opts{total_fixtures} =~ s/value="$db{$table}{$id}{total_fixtures}"/value="$db{$table}{$id}{total_fixtures}" SELECTED/g ;
		
		$db{$table}{$id}{start_date_time} = "$now_year-$now_mm-$now_dd 08:00:00" unless $db{$table}{$id}{start_date_time} ;
		$db{$table}{$id}{end_date_time} = "$now_year-$now_mm-$now_dd 17:00:00" unless $db{$table}{$id}{end_date_time} ;

		$allow_deselect{client_id} = 1 ;
		# $allow_deselect{total_fixtures} = 1 ;
		# $allow_deselect{service_type_id} = 1 ;
		
		$lcol = 2 ; $fcol = 4 ;
		 
		# if ($usertype eq 'analytics_client') {
			# &db_min_ro('users','id,name',"id='$userid'") ; 
			# $opts{client_id} = qq~<option value='$userid' SELECTED>$db{users}{$userid}{name}</option>~ ;
		# } else {
			# &common_min_select_opts('client_id','customers','name','','','',"analytics='1'") ;
			# # $db{$table}{$id}{client_id} = $userid if !$db{$table}{$id}{client_id} && $usertype eq 'analytics_client' ;
			# $opts{client_id} =~ s/value="$db{$table}{$id}{client_id}"/value="$db{$table}{$id}{client_id}" SELECTED/g if $db{$table}{$id}{client_id} ;
		# }
	  
		$dlg{client_id} .= qq~<div class="col-md-1"><a href="javascript:dlgMdl('$useropts{'scripts'}/dialog/add_analytics_client.pl?add&selectClient_id','Add Analytics Client','','medium-dialog');" class="btn btn-primary btn-xs" style="padding:0px 2px 0px 3px;margin-top:0px;" title='Add Analytics Client' data-toggle='tooltip' data-placement='right'><i class="glyphicon glyphicon-plus" style="padding:0;margin-top:0px;top:0px;"></i></a></div>~ ; 		
		
		$dlg{sport_type_ids} .= qq~<div class="col-md-1"><a href="javascript:dlgMdl('$useropts{'scripts'}/dialog/add_sport_type.pl?add&selectSport_type_ids','Add Sport','','medium-dialog');" class="btn btn-primary btn-xs" style="padding:0px 2px 0px 3px;margin-top:0px;" title='Add Sport' data-toggle='tooltip' data-placement='right'><i class="glyphicon glyphicon-plus" style="padding:0;margin-top:0px;top:0px;"></i></a></div>~ ; 		
 
		# $onload = qq~onload=dispCustomer();~ if $iaction eq 'add' ; # SuperSport Schools (Pty) Ltd
		
		if ($sql_limit_user_regions) {
			$sql_limit_user_regions =~ s/id/region_id/g ;
			$sql_limit_user_regions .= "region_id='0' OR ($sql_limit_user_regions)" ;
		}
 
		&analytics_event_bookings_tabs_customer_select_opts('customers','name',$sql_limit_user_regions,'client_id');

		# $allow_deselect{client_id} = 1 ;
		
		# $required{client_id} = 1 ;
		# $db{$table}{$id}{total_fixtures} = 2 ;
		 
		$add_form_fields .= &common_min_form_select('client_id',$db{$table}{$id}{client_id}) ;
		$add_form_fields .= &common_min_form_select('sport_type_ids',$db{$table}{$id}{sport_type_ids}) ;
		
		$db{$table}{$id}{default_fixtures_sport} = "0" unless $db{$table}{$id}{default_fixtures_sport} ;
		
		$add_form_fields .= qq~<input name="default_fixtures_sport" value="$db{$table}{$id}{default_fixtures_sport}" type='hidden'>~ ;
		
		$add_form_fields .= &common_min_form_input('event_name',$db{$table}{$id}{event_name}) ;
		$add_form_fields .= &common_min_form_datetimepicker('start_date_time',$db{$table}{$id}{start_date_time}) ;	 	
		$add_form_fields .= &common_min_form_datetimepicker('end_date_time',$db{$table}{$id}{end_date_time}) ;	 	

		$add_form_fields .= &common_min_form_select('total_fixtures',$db{$table}{$id}{total_fixtures}) ;	

		$opts{service_type_id} =~ s/value="$db{$table}{$id}{service_type_id}"/value="$db{$table}{$id}{service_type_id}" SELECTED/g ;

		$add_form_fields .= &common_min_form_select('service_type_id',$db{$table}{$id}{service_type_id}) ;
		
		$trigger_jquery_raw .= qq~
			\$("#selectService_type_id").on("change", function () {
				let this_val = \$(this).val() ; 
				\$("#three [id^='selectService_type_fixtures_']").each( function () {
					let row_nr = get_row_nr(this.id) ;
					\$(this).val(this_val).trigger("chosen:updated") ; 
					if (this_val == "1") {
						\$("#selectFootage_type_fixtures_"+row_nr).val("r").trigger("chosen:updated") ; 
					}
				}) ;
			}) ;
			
		~ ; 
		
		$trigger_jquery_raw .= qq~
			\$("#selectService_type_id").change( function () {
				for (let i = 1; i<=100 ; i++) {
					if (!\$("#fixtures_"+i).html()) {
						break ;
					}
					if (!\$("#selectService_type_fixtures_"+i).val()) {
						\$("#selectService_type_fixtures_"+i).val(\$(this).val()).trigger("chosen:updated") ;
					}
				}
			}) ;
		~ ; 
		
		$db{$table}{$id}{tournament_festival_id} = 1 if !$db{$table}{$id}{derby_day_weekly_fixture_id} && !$db{$table}{$id}{tournament_festival_id} ;
		
		$add_form_fields .= &common_min_form_checkbox('derby_day_weekly_fixture_id',$db{$table}{$id}{derby_day_weekly_fixture_id}) ;
		$add_form_fields .= &common_min_form_checkbox('tournament_festival_id',$db{$table}{$id}{tournament_festival_id}) ;

		$trigger_jquery .= qq~
			// \$('.iPhoneCheckContainer').css("width","76px") ;
			// \$('.iPhoneCheckHandle').css("width","32px") ;
			// \$('.iPhoneCheckHandle').css("left","0px") ;
			// \$('.iPhoneCheckLabelOff').css("width","71px") ;
			// \$('.iPhoneCheckLabelOff').css("top","-5px") ;
			// \$('.iPhoneCheckLabelOn').css("top","-5px") ;
			// \$('.iPhoneCheckLabelOn').css("width","45px") ;
			// \$('.iPhoneCheckLabelOff span').css("font-size","14px");
			// \$('.iPhoneCheckLabelOn span').css("font-size","14px");
		~ ; 
		
		$trigger_jquery_raw .= qq~\$("#checkboxTournament_festival_id").prop("checked",true) ;~ if $db{$table}{$id}{tournament_festival_id} ;
		$trigger_jquery_raw .= qq~\$("#checkboxDerby_day_weekly_fixture_id").prop("checked",true) ;~ if $db{$table}{$id}{derby_day_weekly_fixture_id} ;

		&common_shared_build_select_primary_jquery ;	
		
		$trigger_jquery_raw .= qq~
		
			const getClientId = () => {
				const val = \$clientSelect.val();
				return val ? val.toString().split(":")[0] : null;
			};

			const fillTeamSelect = (\$el, teams) => {
				clearSelect(\$el);
				teams.forEach(({ id, name }) => {
					\$el.append(`<option value="\${id}">\${name}</option>`);
				});
				updateChosen(\$el);
			};	

					
				// if (check_team_names_match_client && client_id == "") {
					// client_id = getClientId() ;
					// if (client_id == null) { 
						// client_id = -1 ; 
					// }	
				// }
				
				// if (client_id == "" || client_id == -1 || client_id == null) {
					// \$("input[name='typeahead_"+field_name+"']").val("") ;
					// \$("input[name='"+field_name+"']").val("") ;	
					// client_id = "" ;
				// } else if (check_team_names_match_client) {
					// let url_teams = `$useropts{scripts}/get/get_sss_teams_from_client.pl?client_id=\${client_id}` ;
					// teams = await fetchJSON(url_teams);
					// const idToCheck = \$("input[name='"+field_name+"']").val() ;
					// console.log("idToCheck : "+idToCheck) ; 
					// if (idToCheck) {
						// const exists = teams.some(item => item.id === idToCheck) ;
						// if (exists == false) {
							// \$("input[name='typeahead_"+field_name+"']").val("") ;
							// \$("input[name='"+field_name+"']").val("") ;								
						// }
					// }
				// }
				


			\$("#checkboxDerby_day_weekly_fixture_id").on("change",async function () {
				
				if (\$(this).is(":checked")) {
					\$("#checkboxTournament_festival_id").prop("checked",false) ;
					\$("#add_existing_home_team").css("display","none") ;
					\$("#add_existing_away_team").css("display","none") ;
					// build_teams_from_client() ; 
					let clientId = getClientId() ;
					if (clientId == null) { 
						clientId = -1 ; 
					}
					create_typeahead("fixtures_table","[name^='typeahead_home_team_']",clientId,1) ;
					
					let found_blank = 0 ; let first_non_blank = "" ;
									
					let teams = [] ;
					
					if (clientId == "" || clientId == -1 || clientId == null) {
					} else {
						let url_teams = `$useropts{scripts}/get/get_sss_teams_from_client.pl?client_id=\${clientId}` ;
						teams = await fetchJSON(url_teams);
					}
	
					\$("#three input[name^='home_team_']").each( function () {

						if ((\$("input[name='"+this.name+"']").val() && teams.some(item => item.id === \$("input[name='"+this.name+"']").val()) === false) || !\$("#selectClient_id").val()) {
							\$("input[name='"+this.name+"']").val("") ;
							\$("input[name='typeahead_"+this.name+"']").val("") ;
						}

						if (!\$("input[name='"+this.name+"']").val() && !found_blank) {
							found_blank = 1 ;
						}
						if (\$("input[name='"+this.name+"']").val() && first_non_blank == "") {
							first_non_blank = this.name ;
						}
						
					}) ;	

					if (found_blank && first_non_blank != "") {
						apply_home_team_to_all_blank(first_non_blank) ;
					}
					
				} else {
					\$("#checkboxTournament_festival_id").prop("checked",true) ;
					\$("#add_existing_home_team").css("display","") ;
					\$("#add_existing_away_team").css("display","") ;
					create_typeahead("fixtures_table","[name^='typeahead_home_team_']","",3) ;
				}
				
			}) ;
			
			\$("#checkboxTournament_festival_id").change( async function () {
				if (\$(this).is(":checked")) {
					\$("#add_existing_home_team").css("display","") ;
					\$("#add_existing_away_team").css("display","") ;
					\$("#checkboxDerby_day_weekly_fixture_id").prop("checked",false) ;
					create_typeahead("fixtures_table","[name^='typeahead_home_team_']","",3) ;
				} else {
					\$("#checkboxTournament_festival_id").prop("checked",false) ;
					\$("#add_existing_home_team").css("display","none") ;
					\$("#add_existing_away_team").css("display","none") ;
					// build_teams_from_client() ; 
					let clientId = getClientId() ;
					if (clientId == null) { 
						clientId = -1 ; 
					}
					create_typeahead("fixtures_table","[name^='typeahead_home_team_']",clientId,0) ;
					
					let found_blank = 0 ; let first_non_blank = "" ;
									
					let teams = "[]" ;
					
					if (clientId == "" || clientId == -1 || clientId == null) {
					} else {
						let url_teams = `$useropts{scripts}/get/get_sss_teams_from_client.pl?client_id=\${clientId}` ;
						teams = await fetchJSON(url_teams);
					}
	
					\$("#three input[name^='home_team_']").each( function () {

						if (\$("input[name='"+this.name+"']").val() && teams.some(item => item.id === \$("input[name='"+this.name+"']").val()) === false) {
							\$("input[name='"+this.name+"']").val("") ;
							\$("input[name='typeahead_"+this.name+"']").val("") ;
						}

						if (!\$("input[name='"+this.name+"']").val() && !found_blank) {
							found_blank = 1 ;
						}
						if (\$("input[name='"+this.name+"']").val() && first_non_blank == "") {
							first_non_blank = this.name ;
						}
						
					}) ;	

					if (found_blank && first_non_blank != "") {
						apply_home_team_to_all_blank(first_non_blank,clientId,1) ;
					}
				}
			}) ;
			
			async function build_teams_from_client () {
				
				const clientId = getClientId() ;
				
				let teams_ = "[]" ;
				
				if (clientId) {
					let url_teams2 = `$useropts{scripts}/get/get_sss_teams_from_client.pl?client_id=\${clientId}` ;
					teams_ = await fetchJSON(url_teams2);					
				}
				
				\$("#fixtures_table select[id^='selectHome_team_']").each( function () {
					let selected_val = (\$(this).val()) ? \$(this).val() : "" ;  
					clearSelect(\$(this));
					fillTeamSelect(\$(this),teams_) ;
					if (teams_.length === 1) {
						\$(this).val(teams_[0].id).trigger("chosen:updated") ;
					} else {
						\$(this).val(selected_val).trigger("chosen:updated") ;
					}
					
				}) ; 
				
			}
			
		~ ; 
		
		$add_form_fields .= &common_min_form_textarea('additional_notes',$db{$table}{$id}{additional_notes}) ;
		
		$trigger_jquery_raw .= qq~
			// let end_time = new Date("$db{$table}{$id}{end_date_time}") ; 
			// let start_time = new Date("$db{$table}{$id}{start_date_time}") ; 
			// \$("#datetimepickerStart_date_time").datetimepicker("setEndDate",end_time) ;
			// \$("#datetimepickerEnd_date_time").datetimepicker("setStartDate",start_time) ;
			
			// let picker = \$("#datetimepickerStart_date_time").data("datetimepicker").endDate.toISOString().slice(0,19).replace('T',' ') ;
			// console.log("endDate : "+picker);
		
		~ ; 
		
		&analytics_event_bookings_tabs_content_box($sec_name,$sec_col);
 	
	# custom_selected_region"
	# custom_selected_country

		$trigger_jquery_raw .= qq~		
		
			let map_client_to_country = {} ;
			let map_region_to_country = {} ; 			
			let map_client_to_region = {} ; 
	
			const \$clientSelect  = \$("#selectClient_id") ; 
			const \$countrySelect = \$("#selectCountry_id") ;
			const \$regionSelect  = \$("#selectRegion_id") ;
			const \$fixturesTable = \$("#fixtures_table");
			
			let regionId = \$regionSelect.val() ;
			let countryId = \$("#selectCountry_id").val() ;
			
			// const populateSelect = (\$el, dataList, labelFn) => {
				// let lastId = null ;
				// for (const data of dataList) {
					// \$el.append(`<option value="\${data.id}">\${labelFn(data)}</option>`);
					// lastId = data.id;
				// }
				// updateChosen(\$el) ;
				// return { count: dataList.length, lastId } ;
			// } ;	
			// const populateSelect = (\$el, list, getLabel) => {
				// list.forEach(data => { \$el.append(`<option value="\${data.id}">\${getLabel(data)}</option>`); }) ;
				// updateChosen(\$el);
				// return list.length;
			// };
			
			// const fillTeamSelect = (\$el, teams) => {
				// \$el.empty().append("<option value=''></option>");
				// teams.forEach(team => {
					// \$el.append(`<option value="\${team.id}">\${team.name}</option>`);
				// });
				// \$el.val("").trigger("chosen:updated");
			// };
			
			const getInputValue = name => \$(`input[name='\${name}']`).val();
			const setInputValue  = (name, val = "") => \$(`input[name='\${name}']`).val(val);

			let prev_country_id = \$countrySelect.val() ;
			let prev_region_id = \$regionSelect.val() ;

			\$clientSelect.on("change", async function () {

				dispCustomer() ;
				
				const hasCustomRegion = !!getInputValue('custom_selected_region') ;
				const clientId = getClientId() ;
				const hasCustomCountry = !!getInputValue('custom_selected_country') ;
				
				if (clientId && !hasCustomRegion) {
					
					let url1 = `$useropts{scripts}/get/get_region_country_from_client.pl?client_id=\${clientId}` ; 

					if (!hasCustomRegion || !hasCustomCountry) {
						const data = await fetchJSON(url1) ;
						data.forEach(({region_id,country_id}) => {
							if (region_id == '0') region_id = '' ;
							if (country_id == '0') country_id = '' ;
							if (\$regionSelect.val() == '13' && (!region_id || hasCustomCountry)) region_id = '13' ;
							if (!hasCustomRegion && region_id != \$regionSelect.val()) \$regionSelect.val(region_id).trigger("chosen:updated") ;
							if (!hasCustomCountry && country_id != \$countrySelect.val()) \$countrySelect.val(country_id).trigger("chosen:updated") ;
						}) ;
					}
					
				} else if (!clientId) {
					
					if (!hasCustomCountry) \$countrySelect.val("").trigger("chosen:updated") ;
					if (!hasCustomRegion && \$regionSelect.val() != '13') \$regionSelect.val("").trigger("chosen:updated") ;
				}
				 
				let cnt = 0 ; let teams = "[]" ;

				if (clientId) {
					
					let url_teams2 = `$useropts{scripts}/get/get_sss_teams_from_client.pl?client_id=\${clientId}` ;

					teams = await fetchJSON(url_teams2);
					
					if (\$("#checkboxDerby_day_weekly_fixture_id").is(":checked")) {

						\$("#three input[name^='home_team_']").each( function () {
							
							let id_name = this.name ; 
							const \$teamSelect = \$("input[name='"+id_name+"']") ;
 
							const idToCheck = \$teamSelect.val() ;
							const exists = teams.some(item => item.id === idToCheck) ;
							if (!exists || exists == false) {
								\$teamSelect.val("") ;
								\$("input[name='typeahead_"+id_name+"']").val("") ;
							} 
							
							// if (!\$teamSelect.val() && teams.length == 1 && teams != "[]") { // only select if 1 in the list
							if (!\$teamSelect.val() && teams != "[]") { // select the first available team
								// \$teamSelect.val(teams[0].name) ;
								// \$("input[name='typeahead_"+id_name+"']").val(teams[0].id) ;
							
								\$teamSelect.val(teams[0].id) ;
								\$("input[name='typeahead_"+id_name+"']").val(teams[0].name) ;
							}
						}) ; 	
						
						create_typeahead("fixtures_table","[name^='typeahead_home_team_']",clientId,1) ;
					} else {
						// create_typeahead("fixtures_table","[name^='typeahead_home_team_']","",3) ;
					}
					// else {
					// 	create_typeahead("fixtures_table","[name^='typeahead_home_team_']",clientId,1) ;
					// }
					
				} else {
					if (\$("#checkboxDerby_day_weekly_fixture_id").is(":checked")) {
						
						\$("#three input[name^='home_team_']").each( function () {
							\$("input[name='"+this.name+"']").val("") ;
							\$("input[name='typeahead_"+this.name+"']").val("") ;
						}) ;
						
						create_typeahead("fixtures_table","[name^='typeahead_home_team_']","-1",1) ;
					
					} else {
						create_typeahead("fixtures_table","[name^='typeahead_home_team_']","",3) ;
					}
					// else {
					// 	create_typeahead("fixtures_table","[name^='typeahead_home_team_']","clientId",1) ;
					// }
					// create_typeahead("fixtures_table","[name^='typeahead_home_team_']",-1,3) ;
				}

				if (teams.length > 0 && teams != "[]") {
					
					\$("input[name='home_teams_built_on_regions']").val("") ;
					// \$("#fixtures_table select[id^='selectHome_team_']").each( function () {
					\$("#fixtures_table input[name^='typeahead_home_team_']").each( function () {
						
						// let selected_val = (\$(this).val()) ? \$(this).val() : "" ;  
						// const \$teamSelect = \$(this) ;  
						
						let id_name = this.name ; 
						
						const \$teamSelect = \$("input[name='"+id_name+"']") ;
						
						console.log("1 id_name : "+id_name) ; 
						
						id_name = id_name.replace("typeahead_","") ;
						
						// console.log("2 id_name : "+id_name) ; 
						// console.log("3 id_name val : "+\$("input[name='"+id_name+"']").val()) ; 
						// console.log("4 teams[0].id : "+teams[0].id) ; 
						// console.log("5 teams[0].name : "+teams[0].name) ; 

						// clearSelect(\$teamSelect);
						// fillTeamSelect(\$teamSelect,teams) ;
						// if (teams.length === 1 && !\$("#checkboxDerby_day_weekly_fixture_id").is(":checked") && !\$("input[name='"+id_name+"']").val()) { // only select if 1 in the list
						if (!\$("#checkboxDerby_day_weekly_fixture_id").is(":checked") && !\$("input[name='"+id_name+"']").val()) { // select the first available team
							\$teamSelect.val(teams[0].name) ; // with _typahead
							\$("input[name='"+id_name+"']").val(teams[0].id) ;// without _typahead
						} else if (\$("#checkboxDerby_day_weekly_fixture_id").is(":checked")) {
							// \$teamSelect.val(selected_val).trigger("chosen:updated") ;
						}
						
					}) ; 
	
					
				} else if (\$regionSelect.val() && \$regionSelect.val() != prev_region_id) {
					\$("input[name='home_teams_built_on_regions']").val("1") ;
					await build_teams_from_region(\$regionSelect.val()) ;
				} else if (\$countrySelect.val() && \$countrySelect.val() != prev_country_id) {
					\$("input[name='home_teams_built_on_regions']").val("1") ;
					await build_teams_from_region("",\$countrySelect.val()) ;					
				} else if (!\$regionSelect.val() && !\$countrySelect.val() && (\$("input[name='home_teams_built_on_regions']").val() || (!\$("input[name='home_teams_built_on_regions']").val() && !clientId))) {
					\$("#fixtures_table select[id^='selectHome_team_']").each(function () {
						clearSelect(\$(this)) ;
					}) ;
				} else if (!\$("input[name='home_teams_built_on_regions']").val() && \$regionSelect.val()) {
					\$("input[name='home_teams_built_on_regions']").val("1") ;
					await build_teams_from_region(\$regionSelect.val()) ;	
				} else if (!\$("input[name='home_teams_built_on_regions']").val() && \$countrySelect.val()) {
					\$("input[name='home_teams_built_on_regions']").val("1") ;
					await build_teams_from_region("",\$countrySelect.val()) ;	
				}
				
				prev_country_id = \$countrySelect.val() ;
				prev_region_id = \$regionSelect.val() ; 
				
				// else {
					// \$("input[name='home_teams_built_on_regions']").val("1") ;
					// const away_team_options = \$("#selectAway_team_fixtures_1").children().clone();
					// \$("#fixtures_table select[id^='selectHome_team_']").each( function () {
						// let \$teamSelect = \$(this) ;
						// clearSelect(\$teamSelect);
						// \$teamSelect.append(away_team_options).trigger("chosen:updated") ;
					// }) ;
				// } 
				
				hide_or_display_buttom_to_add_hometeam_from_existing() ;
				
				if (!\$("#checkboxDerby_day_weekly_fixture_id").is(":checked") && clientId) {
					create_typeahead("fixtures_table","[name^='typeahead_home_team_']","",3) ;
				}
				
			}) ;

			\$countrySelect.on("change", async function () {
				
				\$("input[name='custom_selected_country']").val("1") ; 
				await update_region_drop_down(\$countrySelect.val()) ; 
				if (\$regionSelect.val() && prev_region_id != \$regionSelect.val()) {
					await build_teams_from_region(\$regionSelect.val()) ;
				} else if (!\$regionSelect.val() && \$countrySelect.val() && prev_country_id != \$countrySelect.val()) {
					await build_teams_from_region("",\$countrySelect.val()) ;
				} 
				prev_country_id = \$countrySelect.val() ;
				prev_region_id = \$regionSelect.val() ; 
				
			}) ;
			
			\$regionSelect.on("change", async function () {
				
				\$("input[name='custom_selected_country']").val("") ;
				\$("input[name='custom_selected_region']").val(\$(this).val()) ; 
				// await build_teams_from_region(\$regionSelect.val()) ;
				await select_country_from_region(\$regionSelect.val(),1) ; 
				\$("input[name='custom_selected_country']").val("1") ;
				prev_country_id = \$countrySelect.val() ;
				prev_region_id = \$regionSelect.val() ;
				// hide_or_display_buttom_to_add_hometeam_from_existing() ;
				
			}) ;
			
			function hide_or_display_buttom_to_add_hometeam_from_existing () {
				
				// // // if ((\$clientSelect.val()) && \$("#selectHome_team_fixtures_1 option").length > 0) {
				// // // 	\$("#add_existing_home_team").css("display","none") ;
				// // // } else {
				// // // 	\$("#add_existing_home_team").css("display","") ;
				// // // } 	
			}
			
			async function update_region_drop_down (countryId) {
				
				if (typeof countryId === 'undefined') {
					countryId = "" ;
				}
					
				let region_id = \$regionSelect.val() ; 
				
				clearSelect(\$regionSelect) ;

				const regionUrl = `$useropts{scripts}/get/get_regions_from_country.pl?country_id=\${countryId}`;
				
				// console.log("regionUrl : "+regionUrl) ; 
				
				const regions = await fetchJSON(regionUrl);
			
				for (const data of regions) {
					map_region_to_country[data.id] = countryId;
				}
			
				const regionCount = populateSelect(\$regionSelect, regions, r => r.code ? `\${r.name} [\${r.code}]` : r.name ) ;
				
				let selectedRegionId = 0 ;

				if (regionCount["count"] === 1) {
					selectedRegionId = regions[0].id ;
					\$regionSelect.val(regions[0].id) ;
				} else if (regionCount["count"] === 0 && \$countrySelect.val()) {
					selectedRegionId = 13 ;
					\$regionSelect.append(`<option value="13" selected>Other [OT]</option>`) ;
				}  
				if (selectedRegionId == 0) \$regionSelect.val(region_id) ; 
				updateChosen(\$regionSelect) ;
			}
			
			async function select_country_from_region (regionId,update_country=0) {
 
				if (map_region_to_country[regionId]) {
					\$countrySelect.val(map_region_to_country[regionId]).trigger("chosen:updated") ; 
				} else if (!\$("input[name='custom_selected_country']").val() || update_country) {
					// let url_teams1 = "$useropts{scripts}/get/get_country_from_region.pl?region_id="+regionId ;
					const lookupUrl = `$useropts{scripts}/get/get_country_from_region.pl?country_id=&region_id=\${regionId}`;
					const regionMeta = await fetchJSON(lookupUrl);
					const { country_id } = regionMeta[0] ?? {};
					
					if (country_id) {
						map_region_to_country[regionId] = country_id;
						\$countrySelect.val(country_id).trigger("chosen:updated");
					} 					
				}					
			}
			
			async function build_teams_from_region (regionId="",countryId="") {
				
				return ;
				
				let url_teams1 = `$useropts{scripts}/get/get_sss_teams_from_region.pl?region_id=\${regionId}&country_id=\${countryId}` ;
				// let tabs = (\$("input[name='home_teams_built_on_regions']").val() == "1") ? "#fixtures_table select[id^='selectHome_team_'],#fixtures_table select[id^='selectAway_team_']" : "#fixtures_table select[id^='selectAway_team_']" ;
				
				// console.log("build_teams_from_region URL : "+url_teams1) ; 
				
				let tabs = (\$("input[name='home_teams_built_on_regions']").val() == "1") ? "#fixtures_table select[id^='selectHome_team_']" : "" ;
				const teams = await fetchJSON(url_teams1);
				if (tabs != "") {
					\$(tabs).each(function () {
						const \$teamSelect = \$(this);
						clearSelect(\$teamSelect);
						fillTeamSelect(\$teamSelect, teams);
					});					
				}
 						
			}
			
		~ ;	
 
	} 
	
	if ($tab == 3) {
	
		return if $ret;
		
		our $on_team_change_extra_trigger_jquery_raw = qq~~ ;
		
		$on_team_change_extra_trigger_jquery_raw .= qq~
			apply_home_team_to_all_blank(field_name) ;	
		
		~ ;
		
		our $on_team_change_extra_trigger_jquery_raw_2 = qq~	
			apply_home_team_to_all_blank(field_name) ;
		~ ;
		
		$trigger_jquery_raw .= qq~
		
			// function apply_home_team_to_all_blank (field_name,client_id="",check_team_names_match_client=0) {
			function apply_home_team_to_all_blank (field_name) {

				if (!field_name || !\$("#checkboxDerby_day_weekly_fixture_id").is(":checked")) {
					return ;
				}
				
				\$("#three input[name^='home_team_']").each( function () {
					if (!\$("input[name='typeahead_"+this.name+"']").val() && field_name != this.name) {
						\$("input[name='typeahead_"+this.name+"']").val(\$("input[name='typeahead_"+field_name+"']").val()) ;
						\$("input[name='"+this.name+"']").val(\$("input[name='"+field_name+"']").val()) ;							
					}
				}) ;
				
			}
			
		~ ;
		
		# \$("#fixtures_table input[name^='typeahead_home_team_']").each( function () {
		
		&common_shared_typeahead("fixtures_table","typeahead_away_team_,typeahead_home_team_") ;
		
		my $home_team_client = ($db{$table}{$id}{client_id}) ? $db{$table}{$id}{client_id} : -1 ;
		
		if ($db{$table}{$id}{derby_day_weekly_fixture_id}) {
			$trigger_jquery_raw .= qq~
				create_typeahead("fixtures_table","[name^='typeahead_away_team_']","",3) ;
				create_typeahead("fixtures_table","[name^='typeahead_home_team_']","$home_team_client",1) ;
			~ ;		
		} else {
			$trigger_jquery_raw .= qq~
				create_typeahead("fixtures_table","[name^='typeahead_away_team_'],[name^='typeahead_home_team_']","",3) ; 
				// create_typeahead("fixtures_table","[name^='typeahead_home_team_']","",3) ; 
			~ ; 	
		}
		 
		# $db{$table}{$id}{derby_day_weekly_fixture_id}
		
		my $sec = '_fixtures' ; 
		
		my ($sec_name,$sec_cnt,$sec_col) = &analytics_event_bookings_tabs_sec_det($sec) ;
		
		$sec = 'fixtures' ; 
		
		$add_form_fields = '' ;

		$lcol = 1; 
		$fcol = 2;
		
		our @headers = @fixture_headers ;
		our %custom_header = () ; 
		
		push @headers, "Stream Forwarding" ;
		push @headers, "Stream Key" ;
		push @headers, "Stream URL" ;

		&report_xlsx_export_header("Analytics-Fixtures-$i{id}",'analytics_fixtures') ; 
		
		push @headers, "Can't Charge Client" ;
		
		our $csvpath = "$htmlpath/csv/analytics_fixtures" ;
		our $csvname = "Analytics-Fixtures-$i{id}-" . $now_ccyymmdd . $now_hour . $now_min . $now_sec . '.csv' ; ;
		
		&csv_clear_folder($csvpath,"Analytics-Fixtures-$i{id}") ; 
		&csv_create_new_file($csvpath,$csvname) ;
		
		# $db{$table}{$i{id}}{cant_charge_client_fixtures} = "1;1" ; 
			
		# $db{$table}{$i{id}}{cant_charge_client_reasons} = "Test123:|;123123" ;	
		
		&analytics_event_bookings_tabs_build_fixtures_table_headers(3) ;	
		&analytics_event_bookings_tabs_build_fixtures_table($id,"$sec") ; 	

		
		$db{$table}{$i{id}}{cant_charge_client_reasons} =~ s/\R/\_new_line_character_/g ;
		$db{$table}{$i{id}}{cant_charge_client_reasons} =~ s/ /\&nbsp;/g ; 
		$add_form_fields .= qq~<input name='cant_charge_client_reasons' value='$db{$table}{$i{id}}{cant_charge_client_reasons}' type='hidden'>~ ;
		
		my $add_box_icon = $box_icon ;
		$box_icon = "" ;
				
		$worksheet{$ws}->set_column(0,0,20) ; 
		$worksheet{$ws}->set_column(1,3,10) ; 
		$worksheet{$ws}->set_column(4,4,30) ;
		$worksheet{$ws}->set_column(5,5,10) ;  
		$worksheet{$ws}->set_column(6,6,30) ; 
		$worksheet{$ws}->set_column(7,8,15) ; 
		$worksheet{$ws}->set_column(9,9,20) ; 
		# $worksheet{$ws}->set_column(10,10,25) ; 
		$worksheet{$ws}->set_column(10,10,20) ; 
		$worksheet{$ws}->set_column(11,11,25) ; 
		$worksheet{$ws}->set_column(12,12,50) ; 

		$box_icon .= qq~
			<div class="box-icon">
				<a class="btn btn-primary btn-round" href="javascript:importDoc('xlsx');" style="padding-top:1px;" data-toggle="tooltip" data-placement="left" data-original-title="Import EXCEL">
					<i class="glyphicon glyphicon-upload icon-white"></i>
				</a>
			</div>
		~ ;
		
		&csv_close_file("$csvpath/$csvname") ; 
		
		&report_xlsx_export_footer('L',15,'analytics_fixtures') ; 
		
		if (-f "$csvpath/$csvname") { 
			# $box_icon .= qq(<div class="box-icon" title='Export to CSV' data-toggle="tooltip" data-placement="left"><a class="btn btn-default btn-round" href="/csv/analytics_fixtures/$csvname" style="padding-top:1px;"><i class="glyphicon glyphicon-download-alt icon-white"></i></a></div>) ;
		}
			
		$add_form_fields .= qq~<div class='row'><div class='col-md-12'>&nbsp;</div></div>~ ;
		
		&analytics_event_bookings_tabs_content_box($sec_name,$sec_col,$box_icon);
		
		$box_icon = $add_box_icon ;
		
		$trigger_jquery_raw .= qq~
			\$("#three").on("click","[id^='checkboxCant_charge_client']", function () {
				let row_nr = get_row_nr(this.id) ;
				set_default_fixtures_values(row_nr) ; 
				// console.log("123123123 id : "+this.id) ; 
				if (\$("#"+this.id).is(":checked")) {
					if (\$("#reason_icon_"+row_nr+"_$id").html()) {
						\$("#reason_icon_"+row_nr+"_$id").css("display","") ;
					} else {
						dlgMdl("$useropts{scripts}/dialog/add_fixtures_charge_free_reason.pl?add&&$i{id}&"+row_nr,"Add Reason",'','medium-dialog') ;
						// console.log("$useropts{'scripts'}/dialog/add_fixtures_charge_free_reason.pl?add&&$i{id}&"+row_nr) ; 
					}
				} else {
					// console.log("hide #reason_icon_"+row_nr+"_$id") ; 
					\$("#reason_icon_"+row_nr+"_$id").hide() ;
				}
			}) ;
		~ ;
		
		$trigger_jquery_raw .= qq~
			function importDoc(t,b) {
				dlgMdl("$useropts{'scripts'}/dialog/import_analytics_fixtures.pl?"+t+"&"+b,"Import EXCEL",'height:210px','min-dialog') ;
			}		
		~;	 
		
		$trigger_jquery_raw .= qq~
			\$('[data-toggle="tooltip"]').tooltip({ container: 'body' });
			// \$('<style>').prop('type','text/css').html('.tooltip-inner { white-space: nowrap; } span { font-size:12px; }').appendTo('head') ; 
			\$('<style>').prop('type','text/css').html('.tooltip-inner { white-space: nowrap ; }').appendTo('head') ; 
		~ ;
		
		$trigger_jquery_raw .= qq~
			
			// \$("#datetimepickerStart_date_time").on('changeDate',function() {
			// 	for (let i = 1; i <= 100; i++) {
			// 		if (!\$("#fixtures_"+i).html() || \$("input[name='changed_fixtures_date_"+i+"']").val()) {
			// 			continue ;
			// 		}
			// 		let startDateInput = \$("input[name='start_date_time']").val() ;
			// 		let date_input = new Date(startDateInput) ;
			// 		\$("#datetimepickerStart_date_time_fixtures_"+i).datetimepicker("setDate",date_input) ;
			// 	}
			// }) ; 
			
			\$("#three [id^='selectHome_team_']").on('change',function() {
				auto_select_home_teams(this.id) ;
			}) ;
			
			function auto_select_home_teams (id) {
				if (\$("input[name='home_teams_built_on_regions']").val() == "" || \$("input[name='home_teams_built_on_regions']").val() == "0") {
					let row_nr = get_row_nr(id) ;
					\$("input[name='changed_home_team_"+row_nr+"']").val("1") ;
					for (let i = 1; i <= 100; i++) {
						if (!\$("#fixtures_"+i).html()) {
							break ; 
						}
						if (\$("input[name='changed_home_team_"+i+"']").val() == "1" || row_nr == i) {
							continue ;
						} 
						\$("#selectHome_team_fixtures_"+i).val(\$("#"+id).val()).trigger("chosen:updated") ;
					}
				}
			}
			
		~ ;  
	
		# $worksheet{$ws}->set_column(6,7,20) ; 
	 
	}
	
	if ($tab == 4) {  
	
		return if $ret;
		
		my $sec = '_analytics' ; 
		
		my ($sec_name,$sec_cnt,$sec_col) = &analytics_event_bookings_tabs_sec_det($sec) ;
		
		$sec = 'analytics' ; 
		
		$add_form_fields = '' ;

		$lcol = 1; 
		$fcol = 2;
		
		our @headers = @analytics_headers ;
		
		push @headers, "Stream Forwarding" ;
		push @headers, "Stream Key" ;
		push @headers, "Stream URL" ;
		push @headers, "Can't Charge Client" ;
		
		%custom_header = () ; 
		
		our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; 
		
		$opts{stream_forwarding} = qq~<option value='1'>Yes</option><option value='2'>No</option>~ ; 
		
		&analytics_event_bookings_tabs_build_analytics_table_headers(4) ;	
		&analytics_event_bookings_tabs_build_analytics_table($id,"$sec") ; 	
		
		$add_form_fields .= qq~<div class='row'><div class='col-md-12'>&nbsp;</div></div>~ ;
		
		$fcol = 2 ;
		&common_min_select_opts('event_quote_id','event_quotes','ref',$db{$table}{$id}{event_quote_id},'','id',"demo_id='0'",'','','id,ref') ;
		# $opts{} =
		$allow_deselect{event_quote_id} = 1 ;
		if ($db{$table}{$id}{event_quote_id} && $db{$table}{$id}{event_quote_id} ne '-1') {
			$opts{event_quote_id} .= qq~<option value='-1'>ANALYTICS ONLY</option>~ ;
		} else {
			$opts{event_quote_id} .= qq~<option value='-1' SELECTED >ANALYTICS ONLY</option>~ ;
		}
		
		$allow_deselect{event_quote_id} = '' ;
		
		$add_form_fields .= &common_min_form_select('event_quote_id',$db{$table}{$id}{event_quote_id}) ;
		# $trigger_jquery .= qq~\$("#selectEvent_quote_id").chosen({ allow_single_deselect:true });~ ; 
		$trigger_jquery .= qq~\$("#selectEvent_quote_id_chosen").css("width","100%")~ ; 
		
		&analytics_event_bookings_tabs_content_box($sec_name,$sec_col);	
		
	}
	
} #------------------------------------------------------------------------------------

sub analytics_event_bookings_tabs_build_fixtures_table_headers {
	
	my ($tab_cnt) = @_ ; 
	
	$custom_header{$headers[4]} = qq~<label class='control-label'>$headers[4]</label><a href=javascript:dlgMdl('$useropts{'scripts'}/dialog/add_team.pl?add&&Home','Add&nbsp;Home&nbsp;Team','','medium-dialog'); class='btn btn-primary btn-xs' style='padding:0px 2px 0px 3px;margin-top:0px;position:absolute;right:0;' title='Add Home Team' data-toggle='tooltip' data-placement='top'><i class='glyphicon glyphicon-plus' style='padding:0;margin-top:0px;top:0px;'></i></a>~ ;
	# $custom_header{$headers[4]} .= qq~<a href=javascript:dlgMdl('$useropts{'scripts'}/dialog/add_existing_team.pl?add&&Home','Add&nbsp;Home&nbsp;Team&nbsp;From&nbsp;Existing','','medium-dialog'); id='add_existing_home_team' class='btn btn-default btn-xs' style='padding:0px 2px 0px 3px;margin-top:0px;position:absolute;right:25px;' title='Add Home Team From Existing' data-toggle='tooltip' data-placement='top'><i class='glyphicon glyphicon-plus' style='padding:0;margin-top:0px;top:0px;'></i></a>~ ;
	$custom_header{$headers[5]} = qq~<label class='control-label'>$headers[5]</label><a href=javascript:dlgMdl('$useropts{'scripts'}/dialog/add_ht_colour.pl?add','Add&nbsp;HT&nbsp;Colour','','medium-dialog'); class='btn btn-primary btn-xs' style='padding:0px 2px 0px 3px;margin-top:0px;position:absolute;right:0;' title='Add HT Colour' data-toggle='tooltip' data-placement='top'><i class='glyphicon glyphicon-plus' style='padding:0;margin-top:0px;top:0px;'></i></a>~ ;
	$custom_header{$headers[6]} = qq~<label class='control-label'>$headers[6]</label><a href=javascript:dlgMdl('$useropts{'scripts'}/dialog/add_team.pl?add&&Away','Add&nbsp;Away&nbsp;Team','','medium-dialog'); class='btn btn-primary btn-xs' style='padding:0px 2px 0px 3px;margin-top:0px;position:absolute;right:0;' title='Add Away Team' data-toggle='tooltip' data-placement='top'><i class='glyphicon glyphicon-plus' style='padding:0;margin-top:0px;top:0px;'></i></a>~ ;
	# $custom_header{$headers[6]} .= qq~<a href=javascript:dlgMdl('$useropts{'scripts'}/dialog/add_existing_team.pl?add&&Away','Add&nbsp;Away&nbsp;Team&nbsp;From&nbsp;Existing','','medium-dialog'); id='add_existing_away_team' class='btn btn-default btn-xs' style='padding:0px 2px 0px 3px;margin-top:0px;position:absolute;right:25px;' title='Add Away Team From Existing' data-toggle='tooltip' data-placement='top'><i class='glyphicon glyphicon-plus' style='padding:0;margin-top:0px;top:0px;'></i></a>~ ;
	$custom_header{$headers[13]} .= qq~<a href="#" class='btn btn-primary btn-xs' style='position:relative;padding:20px 20px 0px 0px;' title=\"Can't Charge Client!\" data-toggle='tooltip' data-placement='left'><i class='glyphicon glyphicon-info-sign' style='position:absolute;margin-top:2.5px;right:3.5px;'></i></a>~ ;
	
	&analytics_event_bookings_tabs_build_analytics_table_headers($tab_cnt)  ;
	
} #------------------------------------------------------------------------------------
	
sub analytics_event_bookings_tabs_build_analytics_table_headers {
    
	my ($tab_cnt) = @_ ; 

	$custom_header{$headers[13]} .= qq~<a href="#" class='btn btn-primary btn-xs' style='position:relative;padding:20px 20px 0px 0px;' title=\"Can't Charge Client!\" data-toggle='tooltip' data-placement='left'><i class='glyphicon glyphicon-info-sign' style='position:absolute;margin-top:2.5px;right:3.5px;'></i></a>~ if $tab_cnt == 4 ;
	
	$add_form_fields .= qq~<div class='row' style="margin-bottom:5px;">~ ;
	
	$xlsxcol = 0 ; 
	
	foreach (@headers) {
		
		# my $col_width = 
			# (($_ eq $headers[2] || $_ eq $headers[3]) && $tab_cnt == 4) ? 6 :
			# (($_ eq $headers[4] || $_ eq $headers[6]) && $tab_cnt == 3) ? 3 : 
			# (($_ eq $headers[0] || $_ eq $headers[3] || $_ eq $headers[5] || $_ eq $headers[7]) && $tab_cnt == 3) ? 2 : 1 ;
		
		my $col_width = 
			(($_ eq $headers[2] || $_ eq $headers[3]) 																	&& $tab_cnt == 4) ? 6 :
			(($_ eq $headers[11] || $_ eq $headers[12]) 																&& $tab_cnt == 4) ? 4 :
			(($_ eq $headers[10] || $_ eq $headers[13]) 																&& $tab_cnt == 4) ? 2 :
			(($_ eq $headers[0]) 																						&& $tab_cnt == 3) ? 6 :	
			(($_ eq $headers[1] || $_ eq $headers[11] || $_ eq $headers[12]) 											&& $tab_cnt == 3) ? 4 : 	
			# (($_ eq $headers[4] || $_ eq $headers[6]) 																	&& $tab_cnt == 3) ? 3 : 	
			(($_ eq $headers[4] || $_ eq $headers[6]) 																	&& $tab_cnt == 3) ? 2 : 	
			(($_ eq $headers[2] || $_ eq $headers[5] || $_ eq $headers[7] || $_ eq $headers[9] || $_ eq $headers[10] || $_ eq $headers[13]) 	&& $tab_cnt == 3) ? 2 : 
																																			1 ;
		
		my $header_label = ($custom_header{$_}) ? qq~$custom_header{$_}~ : qq~<label class='control-label'>$_</label>~ ;
		# $add_form_fields .= ($_ eq $headers[2] && $tab_cnt == 4) ? qq~<div class="col-md-1"><div class="row">~ : ($_ eq $headers[3] && $tab_cnt == 3) ? qq~<div class="col-md-6"><div class="row">~ : qq~~ ;
		$add_form_fields .= ($_ eq $headers[2] && $tab_cnt == 4) ? qq~<div class="col-md-1"><div class="row">~ : qq~~ ;
		$add_form_fields .= ($_ eq $headers[10] && $tab_cnt == 4) ? qq~<div class="col-md-3"><div class="row">~ : qq~~ ;
		
		$add_form_fields .= ($_ eq $headers[10] && $tab_cnt == 3) ? qq~<div class="col-md-3"><div class="row">~ : 
		($_ eq $headers[0] && $tab_cnt == 3) ? qq~<div class="col-md-3"><div class="row">~ : 
		($_ eq $headers[3] && $tab_cnt == 3) ? qq~<div class="col-md-6"><div class="row">~ : qq~~ ;
		
		$add_form_fields .= qq~<div class='col-md-$col_width'>$header_label</div>~ ;
		# $add_form_fields .= (($_ eq $headers[3] && $tab_cnt == 4) || ($_ eq $headers[7] && $tab_cnt == 3)) ? qq~</div></div>~ : qq~~ ;
		$add_form_fields .= (($_ eq $headers[13] && $tab_cnt == 4) || ($_ eq $headers[13] && $tab_cnt == 3) || ($_ eq $headers[3] && $tab_cnt == 4) || (($_ eq $headers[2] || $_ eq $headers[9]) && $tab_cnt == 3)) ? qq~</div></div>~ : qq~~ ;
		
		&xlsxcreator_write_xlsx($ws,2,$xlsxcol,$_,$format93) if $_ ne $headers[-1] ;
		$xlsxcol++ ;
	}
	
	&csv_write_in_file(\@headers) ; 
	
	$add_form_fields .= qq~</div>~ ;

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

sub analytics_event_bookings_tabs_build_fixtures_table {

    my ($id,$suffix) = @_;
    
    my $cntloop = 1;
    my $field   = "";
    my $val     = 0;
    
    our @all_selects_tab = (); 
    our @all_selects_ids = (); 
	
    $add_form_fields .= qq~
        <div id='fixtures_table'>	
    ~;
	
    $opts{age_group} .= qq~<option value='open'>Open</option><option value='u19'>U19</option><option value='u17'>U17</option><option value='u16'>U16</option><option value='u15'>U15</option><option value='u14'>U14</option>~; 
	
    $opts{coding_type} .= qq~<option value='s'>Standard</option><option value='p'>Premium</option><option value='i'>Individual</option>~;
	
    $opts{footage_type} .= qq~<option value='s'>$footage_type{"s"}</option><option value='r'>$footage_type{"r"}</option>~;
	
    $opts{team} .= qq~<option value='a'>A</option><option value='b'>B</option><option value='c'>C</option>~;
	
	$opts{teams_id} =~ s/\"/\'/g ;
	
	$opts{client_teams_id} =~ s/\"/\'/g ;
	
	$db{$table}{$id}{home_teams_built_on_regions} = "1" if $iaction eq 'add' ;
	
	if ($db{$table}{$id}{home_teams_built_on_regions}) {
		$opts{home_team} = $opts{teams_id} ;
	} else {
		$opts{home_team} = $opts{client_teams_id} ;
	}
	
	# $opts{away_team} = $opts{away_teams} ;
	
	&common_min_select_opts('ht_colour','analytics_ht_colors','name','','','','') ;

	$opts{ht_colour} =~ s/\"/\'/g ;

	our $nr_of_displayed_rows = ($db{$table}{$id}{total_fixtures}) ? $db{$table}{$id}{total_fixtures} : 1 ;
	
	our %default_val = () ;
	# 1;2025-06-03 08:00:00;5;open;;;a;;;3404;;;1;;;3404;;;s;;;s;;|2;2025-06-03 08:00:00;6;u19;;;b;;;6046;;;1;;;6046;;;p;;;r;;
	my @table_selects_field_keys = ("age_group","team","home_team","ht_colour","away_team","coding_type","footage_type","service_type") ; 
	
	$allow_deselect{age_group} = 0 ;
	$allow_deselect{team} = 0 ;
	
	our $nr_of_rows = 0 ; my $row_cnt = 0 ;
	
	# $db{$table}{$id}{fixtures_saved_values} = "|||" ;
	
	unless ($db{$table}{$id}{fixtures_saved_values}) {
		for (1 .. $db{$table}{$id}{total_fixtures}  - 1) {
			$db{$table}{$id}{fixtures_saved_values} .= qq~|~ ; 
		}
	}

	my @sport_type_ids = split(/\;/,$db{$table}{$id}{sport_type_ids}) ; 
	
	my $row_nr = 0 ; 
	
	my @analytics_saved_values_arr = split(/\|/,$db{$table}{$id}{analytics_saved_values}) ;
	
	my @cant_charge_client_fixtures_arr = split(/\;/,$db{$table}{$id}{cant_charge_client_fixtures}) ;
	my @cant_charge_client_reasons_arr 	= split(/\:\|;/,$db{$table}{$id}{cant_charge_client_reasons}) ;
	my @fixtures_row_split				= split(/\|/,$db{$table}{$id}{fixtures_saved_values}) ;
	
	foreach my $row_defs (@fixtures_row_split) {
		
		my @def_split = split(/\;/,$row_defs) ;
		
		$row_nr++ ;
		
		$default_val{$row_nr}{start_date_time}	= $def_split[0] ;

		$default_val{$row_nr}{readonly_sport}	= $db{sport_types}{$def_split[1]}{name} ;
		$default_val{$row_nr}{sport}   			= $def_split[1] ;
		
		my $cnt = 1 ; my $all_blank = 1 ; 
		foreach my $key (@table_selects_field_keys) {
			$cnt++ ;
			$default_val{$row_nr}{$key} = $def_split[$cnt] ;
			$all_blank = 0 if $def_split[$cnt] ; 
		}

		$default_val{$row_nr}{service_type} = ($default_val{$row_nr}{service_type}) ? $service_types{$default_val{$row_nr}{service_type}} : $service_types{$db{$table}{$id}{service_type_id}} ; 
		# $default_val{$row_nr}{service_type} = ($default_val{$row_nr}{service_type}) ? $service_types{$default_val{$row_nr}{service_type}} : '' ; 
		$all_blank = 0 if $service_types{$db{$table}{$id}{service_type_id}}  ; 
		
		$default_val{$row_nr}{later_readonly_sport} = ($def_split[1]) ? $db{sport_types}{$def_split[1]}{name} : ($db{$table}{$id}{sport_type_ids} !~ /;/) ? $db{sport_types}{$db{$table}{$id}{sport_type_ids}}{name} : "N/A" ;
		$default_val{$row_nr}{label_readonly_sport_id} = $def_split[1] ;
		# $default_val{$row_nr}{later_readonly_sport} = "N/A" if !$default_val{$row_nr}{later_readonly_sport} ;

		if ($all_blank) {
			my $cnt = 2 ;
			$default_val{$row_nr}{later_readonly_sport} = "N/A" if !$default_val{$row_nr}{later_readonly_sport} ;
			
			foreach my $key (@table_selects_field_keys) {
				$default_val{$row_nr}{$key} = "N/A" ;
				$cnt++ ;
			}
			$default_val{$row_nr}{service_type} = "N/A" ;
		}
		  
		$nr_of_rows++ if $row_defs ;
		$row_cnt++ ;

		$xlsxcol = 0 ; my @csv_row = () ;
		
		my @analytics_saved_values_arr_2 = split(/\;/,$analytics_saved_values_arr[$row_nr-1]) ; 
		
		for (1 .. 14) {

			my $val = $def_split[$_ - 1] ;
 
			if ($_ == 1) {
				$val = ($default_val{$row_cnt}{start_date_time}) ? $default_val{$row_cnt}{start_date_time} : $db{$table}{$id}{start_date_time} ;
			} elsif ($_ == 2) {
				$val = $default_val{$row_nr}{later_readonly_sport} ;
			} elsif ($_ == 3 || $_ == 4) {
				$val = ucfirst $val ;
			} elsif ($_ == 5 || $_ == 7) {
				$val = $db{teams}{$val}{name} ;
			} elsif ($_ == 6) {
				$val = $db{analytics_ht_colors}{$val}{name} ;
			} elsif ($_ == 8) {
				$val = $coding_type{$val} ;
			} elsif ($_ == 9) {
				$val = $footage_type{$val} ; 
			}  elsif ($_ == 10) {
				$val = ($val) ? $service_types{$val} : $service_types{$db{$table}{$id}{service_type_id}} ; 
			} elsif ($_ == 11) { 
				$val = ($analytics_saved_values_arr_2[0] eq '1') ? 'Yes' : ($analytics_saved_values_arr_2[0] eq '2') ? 'No' : '' ;
			} elsif ($_ == 12) { 
				$val = $analytics_saved_values_arr_2[1] ;
				$val =~ s/\_semi_colon_character_/\;/g ; 
				$val =~ s/\_pipe_character_/\|/g ;  
			} elsif ($_ == 13) { 
				$val = $analytics_saved_values_arr_2[2] ;
				$val =~ s/\_semi_colon_character_/\;/g ; 
				$val =~ s/\_pipe_character_/\|/g ;  
			} elsif ($_ == 14) { 
				$val = ($cant_charge_client_fixtures_arr[$row_nr-1] eq '1') ? "Yes" : "No" ;
			}
		
			push @csv_row,$val if $_ < 14 ; 
			&xlsxcreator_write_xlsx($ws,$row_nr+2,$_-1,$val,$format82) if $_ < 14 ; 

		}

		&csv_write_in_file(\@csv_row) ; 
		 
	}
	
	$nr_of_rows = 1 unless $nr_of_rows ;
	
	if (scalar @sport_type_ids > $nr_of_rows) {
		$nr_of_rows = scalar @sport_type_ids ;
	}
 
	$nr_of_rows = $db{$table}{$id}{total_fixtures} if $db{$table}{$id}{total_fixtures} > $nr_of_row ;
  
    for my $row_cnt (1 .. $nr_of_rows) {
        
        my $display_save_butt = 0 ;
        my $all_fields_are_filled_in = 0 ;
		
        if ($row_cnt <= $nr_of_rows) {
			
			$default_val{$row_cnt}{later_readonly_sport} = ($db{$table}{$id}{sport_type_ids} !~ /;/ && !$default_val{$row_cnt}{later_readonly_sport}) ? $db{sport_types}{$db{$table}{$id}{sport_type_ids}}{name} : $default_val{$row_cnt}{later_readonly_sport} ;
			
			$default_val{$row_cnt}{later_readonly_sport} = "N/A" if !$default_val{$row_cnt}{later_readonly_sport} ;
			
			my $style = ($nr_of_displayed_rows < $row_cnt) ? qq~style="display:none;"~ : qq~~ ;
			
			my $changed_date = ($default_val{$row_cnt}{start_date_time}) ? 1 : "" ;
			my $changed_home_team = ($default_val{$row_cnt}{home_team}) ? 1 : "" ;
			
            $add_form_fields .= qq~
                <div class='row' id='$suffix\_$row_cnt' $style>
					<input name='changed_fixtures_date_$row_cnt' type='hidden' value='$changed_date'>
					<input name='changed_home_team_$row_cnt' type='hidden' value='$changed_home_team'>
					<div class="col-md-3">
						<div class='row'>
            ~;
			
            $field = "start_date_time_$suffix\_$row_cnt";
            # $fcol = 2;
            $fcol = 6 ;
            $preferred_title{$field} = "Fixture Date, Time From $row_cnt";
			
			$default_val{$row_cnt}{start_date_time} = ($default_val{$row_cnt}{start_date_time}) ? $default_val{$row_cnt}{start_date_time} : $db{$table}{$id}{start_date_time} ;
			
            $add_form_fields .= &common_min_form_datetimepicker_col($field,$default_val{$row_cnt}{start_date_time});
            
            push @all_datetime_ids, "#datetimepickerStart_date_time_$suffix\_$row_cnt";
			
			$field                   	 = "readonly_sport_$suffix\_$row_cnt" ;
			# $fcol                    	 = 1 ;
			$fcol                    	 = 4 ;
			$preferred_title{$field}	 = "Sport $row_cnt" ;
			$readonly{$field} 			 = "READONLY" ;
			
			# $default_val{$row_cnt}{readonly_sport} = $db{sport_types}{$default_val{$row_cnt}{sport}}{name} ;
			
			# $opts{$field} = $opts{sport_type_ids} ;
			$opts{$field} = ($db{$table}{$id}{sport_type_ids}) ? "<option " . join("</option><option ", map { "value='$_'>$db{sport_types}{$_}{name}" } split(/\;/,$db{$table}{$id}{sport_type_ids})) . "</option>" : "" ;
			$opts{$field} =~ s/SELECTED//g ;
			
			# $multiple{$field} = 1 ;
			
			$add_form_fields .= qq~<input name="sport_$suffix\_$row_cnt" value="$default_val{$row_cnt}{sport}" style="display:none;">~ ; 
			
			$default_val{$row_cnt}{sport} = ($default_val{$row_cnt}{sport}) ? $default_val{$row_cnt}{sport} : ($db{$table}{$id}{sport_type_ids} !~ /;/) ? $db{$table}{$id}{sport_type_ids} : "" ;
			
			$opts{$field} =~ s/value='$default_val{$row_cnt}{sport}'/value='$default_val{$row_cnt}{sport}' SELECTED/g ;
			
			$add_form_fields .= &common_min_form_select_col($field,$default_val{$row_cnt}{sport}) ; 
			
			$fcol = 2 ;
			
			my @def_split = split(/\;/,$fixtures_row_split[$row_cnt-1]) ;
			
			my $old_def_val = $default_val{$row_cnt}{service_type} ;
			$default_val{$row_cnt}{service_type} = ($def_split[9]) ? $def_split[9] : $db{$table}{$id}{service_type_id} ; 

            foreach (@table_selects_field_keys) {
				&fixture_table_row_selects($_,$suffix,$row_cnt) ; 
			}
			
			$default_val{$row_cnt}{service_type} = $old_def_val  ;
			
			$fcol = 2 ;
		
			my @analytics_saved_values_arr_2 = split(/\;/,$analytics_saved_values_arr[$row_cnt-1]) ; 
			
			# $analytics_saved_values_arr_2[0] = "1" unless $analytics_saved_values_arr_2[0] ;
			
			$field = "stream_forwarding_fixtures_$row_cnt" ;
			$preferred_title{$field} = "Stream Forwarding $row_cnt" ;
			$opts{$field} = qq~<option value='1'>Yes</option><option value='2'>No</option>~ ; 
			
			$opts{$field} =~ s/value='$analytics_saved_values_arr_2[0]'/value='$analytics_saved_values_arr_2[0]' SELECTED/g ;
			
			$add_form_fields .= qq~<div class="col-md-3"><div class="row">~ ;

			$add_form_fields .= &common_min_form_select_col($field,$analytics_saved_values_arr_2[0]) ;
			
			$fcol = 4 ;
			
			my $hide = ($analytics_saved_values_arr_2[0] eq '2') ? 1 : 0 ; 
			
			$field = "stream_key_fixtures_$row_cnt" ;
			$preferred_title{$field} = "Stream Key $row_cnt" ;
			
			$analytics_saved_values_arr_2[1] =~ s/\_semi_colon_character_/;/g ; 
			$analytics_saved_values_arr_2[1] =~ s/\_pipe_character_/\|/g ; 		
			
			$analytics_saved_values_arr_2[2] =~ s/\_semi_colon_character_/;/g ; 
			$analytics_saved_values_arr_2[2] =~ s/\_pipe_character_/\|/g ; 
			
			$add_form_fields .= &common_min_form_textarea_col($field,$analytics_saved_values_arr_2[1],22.5,$hide) ;
			$field = "stream_URL_fixtures_$row_cnt" ;
			$preferred_title{$field} = "Stream URL $row_cnt" ;
			$add_form_fields .= &common_min_form_textarea_col($field,$analytics_saved_values_arr_2[2],22.5,$hide) ;
			
			$fcol = 2 ;
			
			$field = "cant_charge_client_$suffix\_$row_cnt" ;
			
			my $checked = ($cant_charge_client_fixtures_arr[$row_cnt-1]) ? 'CHECKED' : '' ;
			
			$add_form_fields .= &analytics_event_bookings_tabs_form_checkbox_col($field,'',$checked,'',1) ;
			
			my $disp_reason = ($checked && $cant_charge_client_reasons_arr[$row_cnt-1]) ? "" : "display:none" ; 
		
			$cant_charge_client_reasons_arr[$row_cnt-1] =~ s/ /\&nbsp;/g ;
			
			my $reason_url = $cant_charge_client_reasons_arr[$row_cnt-1] ;
			
			$reason_url =~ s/\R/\_new_line_character_/g ;
			
			$cant_charge_client_reasons_arr[$row_cnt-1] =~ s/\R/\<br>/g ;
			
			$add_form_fields .= qq~&nbsp;&nbsp;<a href=javascript:dlgMdl('$useropts{scripts}/dialog/add_fixtures_charge_free_reason.pl?add&&$i{id}&$row_cnt&$reason_url','Add&nbsp;Reason','','medium-dialog'); class='btn btn-primary btn-xs' style='position:relative;padding:20px 20px 0px 0px;$disp_reason' title='$cant_charge_client_reasons_arr[$row_cnt-1]' data-toggle='tooltip' data-placement='left' id='reason_icon_$row_cnt\_$id'><i class='glyphicon glyphicon-question-sign' style='position:absolute;margin-top:2.5px;right:3.5px;'></i></a>~ if $cant_charge_client_reasons_arr[$row_cnt-1] ;	
				
            $add_form_fields .= qq~</div></div></div></div>~;

            push @team_ids_arr, "#selectHome_team_$suffix\_$_";
            push @team_ids_arr, "#selectAway_team_$suffix\_$_";
            
        }
    }
    
	$trigger_jquery  .= qq~\$("#fixtures_table div[id^='selectReadonly_sport_fixtures_'][id\$='_chosen'],#fixtures_table div[id^='selectStream_forwarding_fixtures_'][id\$='_chosen']").css("width","100%");   ~ ;

	$trigger_jquery_raw .= qq~
		
			let prev_sport_ids = \$("#selectSport_type_ids").chosen().val() ; 
			if (prev_sport_ids == null) { prev_sport_ids = "" ; }
			prev_sport_ids = prev_sport_ids.toString() ;
			prev_sport_ids = prev_sport_ids.split(",") ;

			\$("#selectSport_type_ids").change( function () {
				
				if (\$("input[name='default_fixtures_sport']").val() == "0" && \$(this).chosen().val()) {
					\$("input[name='default_fixtures_sport']").val(\$(this).chosen().val()) ; 
				} else if (\$("input[name='default_fixtures_sport']").val() != "0" && !\$(this).chosen().val()) {
					\$("input[name='default_fixtures_sport']").val("0") ; 
				}
				
				let sport_ids = \$(this).chosen().val() ; 
				if (sport_ids == null) { sport_ids = "" ; }
				sport_ids = sport_ids.toString() ;
				sport_ids = sport_ids.split(",") ;
				 
				let prev_sport_ids_len = (prev_sport_ids != "") ? prev_sport_ids.length : 0 ;
				let sport_ids_len = (sport_ids != "") ? sport_ids.length : 0 ;
				
				if (prev_sport_ids_len < sport_ids_len) {
					
					\$('#selectSport_type_ids option:selected').each( function() {

						let value = \$(this).val();
						let exists = \$('#selectReadonly_sport_fixtures_1 option[value="'+value+'"]').length > 0 ;

						if (!exists) {
							for (let i=1;i<=100;i++) {
								if (!\$("#fixtures_"+i).html()) { break ; }
								\$('#selectReadonly_sport_$suffix\_'+i).append(\$(this).clone()) ;
								\$('#selectReadonly_sport_$suffix\_'+i).trigger("chosen:updated") ;
							} 
						}
					});
				
				} else {
					
					\$('#selectSport_type_ids option:not(:selected)').each( function() {
						let value = \$(this).val(); 
						if (prev_sport_ids.includes(value) && !sport_ids.includes(value)) {
							for (let i = 1; i <= 100; i++) {
								if (!\$("#fixtures_"+i).html()) { break ; }
								\$('#selectReadonly_sport_fixtures_'+i).find('option[value="'+value+'"]').remove() ;
								\$('#selectReadonly_sport_fixtures_'+i).trigger("chosen:updated") ;
							}
						}
					}) ;
				}
				prev_sport_ids = sport_ids ; 
	 
				// for (let i = 1; i <= sport_ids.length; i++) {
					// let j = i - 1 ;
					// if (\$("#fixtures_"+i).html() && !\$("#selectReadonly_sport_fixtures_"+i).val()) {
						// \$("#selectReadonly_sport_fixtures_"+i).val(sport_ids[j]).trigger("chosen:updated") ;
					// }
				// }
				
				for (let i = 1; i <= 100; i++) {
					if (!\$("#fixtures_" + i).html()) {
						break ;
					}
					let select_sport = \$("#selectReadonly_sport_fixtures_" + i) ;
					if (\$("input[name='sport_fixtures_"+i+"']").val()) {
						// if (sport_ids.length === 1 && !select_sport.val()) {
							// select_sport.val(sport_ids[0]).trigger("chosen:updated");
						// }
						// if (sport_ids.length !== 1) {
							select_sport.val(\$("input[name='sport_fixtures_"+i+"']").val()).trigger("chosen:updated") ;
						// }
						continue ;
					}
					// && (!\$("input[name='sport_fixtures_"+i+"']").val() || (\$("input[name='sport_fixtures_"+i+"']").val() && \$("input[name='sport_fixtures_"+i+"']").val() == sport_ids[0]))
					
					if (sport_ids.length === 1) {
						select_sport.val(sport_ids[0]) ;
					} else {
						select_sport.val("") ;
					}
					select_sport.trigger("chosen:updated") ;
					
					if (!select_sport.val() && \$("input[name='default_fixtures_sport']").val() != "0" && \$("#selectAge_group_fixtures_"+i).val()) {
						select_sport.val(\$("input[name='default_fixtures_sport']").val()).trigger("chosen:updated") ;
					}
					
				}	 
				
			}) ;

		~ ;
	
    $add_form_fields .= qq~
        </div>
    ~;
    
    # my $btn_ids_str = join(",", @btn_ids_arr);
    my $team_ids_str = join(",", @team_ids_arr);
    
    my $all_selects_tab_str = join(",", @all_selects_tab);
    my $all_selects_ids_str = join(",", @all_selects_ids);
    
    $trigger_jquery .= qq~\$("$all_selects_tab_str").css("width","100%");~;
	
	$opts{sport_type_ids} =~ s/\"/\'/g ;
	$opts{sport_type_ids} =~ s/SELECTED//g ;
	$opts{coding_type} =~ s/\"/\'/g ;
	$opts{coding_type} =~ s/SELECTED//g ;

	$trigger_jquery_raw .= qq~
				
		function get_row_nr (id) {
			let lastIndex = id.lastIndexOf('_') ;
			lastIndex = parseInt(lastIndex) ;
			let row_nr = id.substring(1+lastIndex) ;
			row_nr = parseInt(row_nr) ;
			return row_nr ; 
		}
			
		function add_checkbox (row_nr,field_name,field_id,tindex,fcol,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) ;
		}

		// \$('#fixtures_table').on('change',"[name^='typeahead_home_team_']", function () {
		// 	
		// 	if (\$("#checkboxDerby_day_weekly_fixture_id").is(":checked")) {
		// 		let row_nr = get_row_nr(this.name) ; 
		// 		for (let i = 1; i <= 100; i++) {
		// 			if (!\$("#fixtures_"+i).html()) {
		// 				break ;
		// 			}
		// 			if (\$("input[name='changed_fixtures_date_"+i+"']").val()) {
		// 				continue ;
		// 			}
		// 			\$("#datetimepickerStart_date_time_fixtures_"+i).datetimepicker("setDate",start_date) ;
		// 		}
		// 		
		// 	}
		// 	
		// ) ;
		
		\$("#selectTotal_fixtures").change( function() {

			let selectedValue = (\$(this).val()) ? parseInt(\$(this).val()) : 1 ;
			
			let select_ids1 = "" ; let select_ids2 = "" ; let select_ids3 = "" ;

			let sport_ids = \$("#selectSport_type_ids").chosen().val() ; 
			if (sport_ids == null) { sport_ids = "" ; }
			sport_ids = sport_ids.toString() ;
			sport_ids = sport_ids.split(",") ;
			
			let sport_field_ids = "" ;
			let home_team_field_ids = "" ;
			let home_team_field_ids_2 = "" ;
			let start_date_time_field_ids = "" ; 
			
			let clientId = getClientId() ;
			if (clientId == null) { 
				clientId = -1 ; 
			}		
			
			let home_team_default_team_id = (\$("#checkboxDerby_day_weekly_fixture_id").is(":checked") && clientId && clientId != -1) ? \$("input[name='home_team_fixtures_1']").val() : "" ;
			let home_team_default_team    = (\$("#checkboxDerby_day_weekly_fixture_id").is(":checked") && clientId && clientId != -1) ? \$("input[name='typeahead_home_team_fixtures_1']").val() : "" ;
			
			for (let i = 1; i <= 100; i++) {

				if (i <= selectedValue && !\$("#fixtures_"+i).html()) {
				
					\$("input[name='home_team_fixtures_1']").after("<input name='home_team_fixtures_"+i+"' value='"+home_team_default_team_id+"' class='hidden'>") ;
					\$("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,"$opts{age_group}",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,home_team_default_team) ;
							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,	7,	"",2,'') ;
							html += add_select(i,"coding_type_$suffix\_" + i, "selectCoding_type_$suffix\_" + i, "Select Coding Type "+i,"$opts{coding_type}", 8, 2, 100, "", "") ;
							html += add_select(i,"footage_type_$suffix\_" + i, "selectFootage_type_$suffix\_" + i, "Select Footage Type "+i, "$opts{footage_type}", 9, 1, 100, "", "") ;
							html += add_select(i,"service_type_$suffix\_" + i, "selectService_type_$suffix\_" + i, "Select Service Type "+i, "", 9, 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,"", 10, 2, 100, "", "") ;
							html += add_textarea (i,"stream_key_$suffix\_"+i,"textareaStream_key_$suffix\_"+i,"Stream Key "+i,11,"",4) ;
							html += add_textarea (i,"stream_URL_$suffix\_"+i,"textareaStream_URL_$suffix\_"+i,"Stream URL "+i,12,"",4) ;
							html += add_checkbox (i,"cant_charge_client_$suffix\_"+i,"checkboxCant_charge_client_"+i,13,2,"")
						html += "</div></div>" ;
					
					// add_textarea
					html += "</div>" ;
					 
					if (select_ids1) { select_ids1 += "," ; }
					select_ids1 += "#selectAge_group_$suffix\_"+i+",#selectTeam_$suffix\_"+i+",#selectStream_forwarding_$suffix\_"+i+",#selectService_type_$suffix\_"+i ;					
					
					if (select_ids2) { select_ids2 += "," ; }
					select_ids2 += "#selectReadonly_sport_$suffix\_"+i+",#selectHt_colour_$suffix\_"+i+",#selectCoding_type_$suffix\_"+i+",#selectFootage_type_$suffix\_"+i ;
					
					if (select_ids3) { select_ids3 += "," ; }
					select_ids3 += "#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,#selectStream_forwarding_$suffix\_"+i+"_chosen" ;		

					\$("#fixtures_table").append(html).trigger("chosen:updated") ;			
					
					if (\$("#checkboxDerby_day_weekly_fixture_id").is(":checked")) {	
						create_typeahead('fixtures_table',"[name^='typeahead_away_team_$suffix\_"+i+"']","",3) ; 
						// let clientId = getClientId() ;
						// if (clientId == null) { 
							// clientId = -1 ; 
						// }
						create_typeahead('fixtures_table',"[name^='typeahead_home_team_$suffix\_"+i+"']",clientId,1) ; 
						
					} else {
						create_typeahead('fixtures_table',"[name^='typeahead_away_team_$suffix\_"+i+"'],[name^='typeahead_home_team_$suffix\_"+i+"']","",3) ; 
						// create_typeahead('fixtures_table',"[name^='typeahead_home_team_$suffix\_"+i+"']",clientId,1) ; 
					}
					
					if (start_date_time_field_ids != "") { start_date_time_field_ids = start_date_time_field_ids+",#datetimepickerStart_date_time_$suffix\_"+i ; } else { start_date_time_field_ids = "#datetimepickerStart_date_time_$suffix\_"+i ; }
					if (sport_field_ids != "") { sport_field_ids = sport_field_ids+",#selectReadonly_sport_$suffix\_"+i ; } else { sport_field_ids = "#selectReadonly_sport_$suffix\_"+i ; }
					
					["Readonly_sport","Team","Ht_colour","Stream_forwarding"].forEach( function (prefix) {
						\$("#select"+prefix+"_$suffix\_" +i).append(\$("#select"+prefix+"_$suffix\_1").children().clone()).trigger("chosen:updated") ; 
					}) ;
					
					\$("#selectService_type_$suffix\_"+i).append(\$("#selectService_type_id").children().clone()).trigger("chosen:updated") ; 
					
					if ((\$("input[name='home_teams_built_on_regions']").val() == "" || \$("input[name='home_teams_built_on_regions']").val() == "0") && \$("#selectHome_team_$suffix\_1").val()) {
						// if (home_team_field_ids != "") { home_team_field_ids = home_team_field_ids+",#selectHome_team_$suffix\_"+i ; } else { home_team_field_ids = "#selectHome_team_$suffix\_"+i ; }
						if (home_team_field_ids != "") { home_team_field_ids = home_team_field_ids+",input[name='typeahead_home_team_$suffix\_"+i+"']" ; } else { home_team_field_ids = "input[name='typeahead_home_team_$suffix\_"+i+"']" ; }
						if (home_team_field_ids_2 != "") { home_team_field_ids_2 = home_team_field_ids_2+",input[name='home_team_$suffix\_"+i+"']" ; } else { home_team_field_ids_2 = "input[name='home_team_$suffix\_"+i+"']" ; }
					}

					\$("#selectHome_team_$suffix\_"+i).change( function () {
						auto_select_home_teams(this.id) ;
					}) ;
				
				} else if (i <= selectedValue && \$("#fixtures_"+i).css("display") === "none" && \$("#fixtures_"+i).html()) {
					\$("#fixtures_"+i).show() ;
				} else if (i > selectedValue && \$("#fixtures_"+i).css("display") !== "none" && \$("#fixtures_"+i).html()) {
					\$("#fixtures_"+i).hide() ;
				}
				
				if (i <= selectedValue) {
					let j = i - 1 ;
					if (\$("#fixtures_"+i).html() && !\$("#selectReadonly_sport_fixtures_"+i).val()) {
						// \$("#selectReadonly_sport_fixtures_"+i).val(sport_ids[j]).trigger("chosen:updated") ;
						if (\$("input[name='sport_fixtures_"+i+"']").val()) {
							\$("#selectReadonly_sport_fixtures_"+i).val(\$("input[name='sport_fixtures_"+i+"']").val()).trigger("chosen:updated") ;
						} else if (sport_ids.length === 1) {
							\$("#selectReadonly_sport_fixtures_"+i).val(sport_ids[0]).trigger("chosen:updated") ; 
						}
					}
				}
			}

			if (start_date_time_field_ids != "") {
				\$(start_date_time_field_ids).datetimepicker({language: 'pt-BR'}) ;  
			}
			if (sport_field_ids != "") {
				\$(sport_field_ids).val(\$("#selectReadonly_sport_$suffix\_1").val()).trigger("chosen:updated") ;   
			}
			
			// console.log("typeahead_home_team_$suffix\_1 : "+\$("input[name='typeahead_home_team_$suffix\_1']").val()) ; 
			
			// if (home_team_field_ids != "") {
				// \$(home_team_field_ids).val(\$("input[name='typeahead_home_team_$suffix\_1']").val()) ;
			// }
			
			// if (home_team_field_ids_2 != "") {
				// \$(home_team_field_ids_2).val(\$("input[name='home_team_$suffix\_1']").val()) ;
			// }
			
			if (select_ids1 != "") {
				\$(select_ids1).chosen({ allow_single_deselect:false }) ;
				\$(select_ids2).chosen({ allow_single_deselect:false }) ;
				\$(select_ids3).css("width","100%") ;
			}
			
		}) ;
		
		let earliest_latest = find_latest_and_earliest_date_in_fixtures() ;	
		
		// let start_date 	= new Date(\$("input[name='start_date_time']").val()) ; 
		// let end_date 	= new Date(\$("input[name='end_date_time']").val()) ; 
		
		if (earliest_latest.earliest_date && earliest_latest.earliest_date  ) {
			\$("#datetimepickerStart_date_time").datetimepicker("setEndDate",earliest_latest.earliest_date);
		}
		if (earliest_latest.latest_date) {
			\$("#datetimepickerEnd_date_time").datetimepicker("setStartDate",earliest_latest.latest_date);
		}
		
		// let some_fixtures_date_was_changed
		
		function set_default_fixtures_values (row_nr) {
			
			if (!\$("#selectFootage_type_fixtures_"+row_nr).val()) {
				\$("#selectFootage_type_fixtures_"+row_nr).val("s").trigger("chosen:updated") ; 
			}
			
			if (!\$("#selectCoding_type_fixtures_"+row_nr).val()) {
				\$("#selectCoding_type_fixtures_"+row_nr).val("s").trigger("chosen:updated") ; 
			}
			
			if (!\$("#selectReadonly_sport_fixtures_"+row_nr).val()) {
				\$("#selectReadonly_sport_fixtures_"+row_nr).val(\$("input[name='default_fixtures_sport']").val()).trigger("chosen:updated") ; 
			}
			
			if (!\$("#selectAge_group_fixtures_"+row_nr).val()) {
				\$("#selectAge_group_fixtures_"+row_nr).val("open").trigger("chosen:updated") ; 
			}
			
			if (!\$("#selectTeam_fixtures_"+row_nr).val()) {
				\$("#selectTeam_fixtures_"+row_nr).val("a").trigger("chosen:updated") ; 
			}
			
			if (!\$("#selectHt_colour_fixtures_"+row_nr).val()) {
				\$("#selectHt_colour_fixtures_"+row_nr).val("5").trigger("chosen:updated") ; 
			}
			
			if (!\$("#selectStream_forwarding_fixtures_"+row_nr).val()) {
				\$("#selectStream_forwarding_fixtures_"+row_nr).val("1").trigger("chosen:updated") ; 
			}
			
		}

		\$("#three").on("change", "[id^='selectAge_group_'],[id^='selectTeam_'],[id^='selectHome_team_'],[id^='selectAway_team_'],[id^='selectCoding_type_'],[id^='selectHt_colour_'],[id^='selectFootage_type_']", function () {

			let row_nr = get_row_nr(this.id) ;
			set_default_fixtures_values(row_nr) ; 
			
		}) ;
		
		\$("#three").on("changeDate", "[id^='datetimepickerStart_date_time_fixtures_']", function () {
			
			let row_nr = get_row_nr(this.id) ;
			set_default_fixtures_values(row_nr) ; 
			\$("input[name='changed_fixtures_date_"+row_nr+"']").val("1") ;	
			
			let this_date = new Date(\$("input[name='start_date_time_fixtures_"+row_nr+"']").val()) ; 
			let end_date = new Date(\$("input[name='end_date_time']").val()) ; 
			let start_date = new Date(\$("input[name='start_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 
			this_date   = new Date(this_date.getTime() + 2 * 60 * 60 * 1000) ; // Add 2 hours 
			
			if (end_date < this_date) {
				earliest_latest = find_latest_and_earliest_date_in_fixtures() ;	
				\$("#datetimepickerStart_date_time").datetimepicker("setEndDate",earliest_latest.earliest_date);
				\$("#datetimepickerEnd_date_time").datetimepicker("setStartDate",earliest_latest.latest_date);
				\$("#datetimepickerEnd_date_time").datetimepicker("setDate",this_date) ;
			} else if (start_date < this_date && this_date < end_date) {
				earliest_latest = find_latest_and_earliest_date_in_fixtures() ;	
				\$("#datetimepickerStart_date_time").datetimepicker("setEndDate",earliest_latest.earliest_date);
				\$("#datetimepickerEnd_date_time").datetimepicker("setStartDate",earliest_latest.latest_date);
			} else  if (this_date < start_date) { 
				earliest_latest = find_latest_and_earliest_date_in_fixtures() ;	
				\$("#datetimepickerStart_date_time").datetimepicker("setEndDate",this_date);
				\$("#datetimepickerEnd_date_time").datetimepicker("setStartDate",earliest_latest.latest_date);
				\$("#datetimepickerStart_date_time").datetimepicker("setDate",this_date);

				for (let h = 1; h <= 100; h++) {
					if (!\$("#fixtures_"+h).html()) {
						break ;
					}
					if (\$("input[name='changed_fixtures_date_"+h+"']").val() || h == row_nr) {
						continue ;
					}
					\$("#datetimepickerStart_date_time_fixtures_"+h).datetimepicker("setDate",this_date);
				}
			}
			
		}) ;	
		
		let prev_start_date_time = new Date(\$("input[name='start_date_time']").val()) ; 
		prev_start_date_time = new Date(prev_start_date_time.getTime() + 2 * 60 * 60 * 1000) ; // Add 2 hours 
		
		\$("#two").on("changeDate", "[id^='datetimepickerStart_date_time']", function () {
			
			let start_date = new Date(\$("input[name='start_date_time']").val()) ; 
			start_date   = new Date(start_date.getTime() + 2 * 60 * 60 * 1000) ; // Add 2 hours 
			
			for (let i = 1; i <= 100; i++) {
				if (!\$("#fixtures_"+i).html()) {
					break ;
				}
				if (\$("input[name='changed_fixtures_date_"+i+"']").val()) {
					continue ;
				}
				\$("#datetimepickerStart_date_time_fixtures_"+i).datetimepicker("setDate",start_date) ;
			}
			
			let end_date = new Date(\$("input[name='end_date_time']").val()) ; 
			end_date   = new Date(end_date.getTime() + 2 * 60 * 60 * 1000) ; // Add 2 hours 
			
			let latest_start_date = \$("#datetimepickerStart_date_time").data("datetimepicker").endDate ;
			let earliest_end_date = \$("#datetimepickerEnd_date_time").data("datetimepicker").startDate ;
			
			if (!isFinite(latest_start_date) || !isFinite(earliest_end_date)) {
				
				earliest_latest = find_latest_and_earliest_date_in_fixtures() ;	
				
				if (!isFinite(latest_start_date)) {
					latest_start_date = earliest_latest.earliest_date ;
					if (!latest_start_date) {
						latest_start_date = "" ;
					} else {
						\$("#datetimepickerStart_date_time").datetimepicker("setEndDate",latest_start_date) ;
					}
				}
				
				if (!isFinite(earliest_end_date)) {
					earliest_end_date = earliest_latest.latest_date ;
					if (!earliest_end_date) {
						earliest_end_date = "" ;
					} else {
						\$("#datetimepickerEnd_date_time").datetimepicker("setStartDate",earliest_end_date);
					}
				}
			}
			
			if (start_date > end_date) {
				if (latest_start_date == "") {
					\$("#datetimepickerEnd_date_time").datetimepicker("setDate",start_date);
					prev_start_date_time = start_date ; 
				} else if (latest_start_date != "" && start_date <= latest_start_date) {
					\$("#datetimepickerEnd_date_time").datetimepicker("setDate",start_date);
					prev_start_date_time = start_date ; 
				} else if (latest_start_date != "" && start_date > latest_start_date) {
					\$("#datetimepickerStart_date_time").datetimepicker("setDate",prev_start_date_time);
				}
			} else if (latest_start_date != "" && start_date > latest_start_date) {
				\$("#datetimepickerStart_date_time").datetimepicker("setDate",prev_start_date_time);
			} else {
				prev_start_date_time = start_date ; 
			}
			 
			 // let picker = \$("#datetimepickerStart_date_time").data("datetimepicker").endDate.toISOString().slice(0,19).replace('T',' ') ;

		}) ;
		
		let prev_end_date_time = new Date(\$("input[name='end_date_time']").val()) ; 
		prev_end_date_time = new Date(prev_end_date_time.getTime() + 2 * 60 * 60 * 1000) ; // Add 2 hours 
		
		\$("#two").on("changeDate", "[id^='datetimepickerEnd_date_time']", function () {
			
			let start_date = new Date(\$("input[name='start_date_time']").val()) ; 
			let end_date = new Date(\$("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 
	
			let latest_start_date = \$("#datetimepickerStart_date_time").data("datetimepicker").endDate ;
			let earliest_end_date = \$("#datetimepickerEnd_date_time").data("datetimepicker").startDate ;

			if (!isFinite(latest_start_date) || !isFinite(earliest_end_date)) {
				
				earliest_latest = find_latest_and_earliest_date_in_fixtures() ;	
				
				if (!isFinite(latest_start_date)) {
					latest_start_date = earliest_latest.earliest_date ;
					if (!latest_start_date) {
						latest_start_date = "" ;
					} else {
						\$("#datetimepickerStart_date_time").datetimepicker("setEndDate",latest_start_date) ;
					}
				}
				
				if (!isFinite(earliest_end_date)) {
					earliest_end_date = earliest_latest.latest_date ;
					if (!earliest_end_date) {
						earliest_end_date = "" ;
					} else {
						\$("#datetimepickerEnd_date_time").datetimepicker("setStartDate",earliest_end_date);
					}
				}
			}
			
			if (start_date > end_date) {
				if (end_date < earliest_end_date && earliest_end_date != "") {
					\$("#datetimepickerEnd_date_time").datetimepicker("setDate",prev_end_date_time);
				} else {
					\$("#datetimepickerStart_date_time").datetimepicker("setDate",end_date);
					for (let h = 1; h <= 100; h++) {
						if (!\$("#fixtures_"+h).html()) {
							break ;
						}
						if (\$("input[name='changed_fixtures_date_"+h+"']").val()) {
							continue ;
						}
						\$("#datetimepickerStart_date_time_fixtures_"+h).datetimepicker("setDate",end_date);
					}	
					prev_end_date_time = end_date ; 
				}
				
			} else if (end_date < earliest_end_date && earliest_end_date != "") {
				\$("#datetimepickerEnd_date_time").datetimepicker("setDate",prev_end_date_time);
			} else {
				prev_end_date_time = end_date ; 
			}
			 
		}) ;

		function find_latest_and_earliest_date_in_fixtures (exclude_row) {
						
			let latest_date ; let latest_date_2 ; let latest_date_row = 1 ;
			
			let earliest_date ; let earliest_date_2 ; let earliest_date_row = 1 ;
			
			for (let i=1;i<=100;i++) {
				
				if (!\$("#fixtures_"+i).html() || \$("#fixtures_"+i).css("display") === 'none') {
					break ;
				}
				if (!\$("input[name='changed_fixtures_date_"+i+"']").val() || (exclude_row && exclude_row == i)) {
					continue ;
				}

				latest_date_2 = new Date(\$("input[name='start_date_time_fixtures_"+i+"']").val()) ; 
				latest_date_2 = new Date(latest_date_2.getTime() + 2 * 60 * 60 * 1000) ; // Add 2 hours 
				
				if ((latest_date_2 > latest_date && latest_date) || !latest_date) {
					latest_date = latest_date_2 ;
					latest_date_row = i ;
				}
				
				earliest_date_2 = latest_date_2 ; 
				
				if ((earliest_date_2 < earliest_date && earliest_date) || !earliest_date) {
					earliest_date = earliest_date_2 ;
					earliest_date_row = i ;
				}
				
			}
			
			return {earliest_date,latest_date} ;
			
		}
		
		\$("#three").on("change", "[id^='selectReadonly_sport_']", function () {
			let row_nr = get_row_nr(this.id) ;
			\$("input[name='sport_fixtures_"+row_nr+"']").val(\$(this).val()) ; 
			// console.log("CHANGED ADDED SPORT "+row_nr) ; 
			set_default_fixtures_values(row_nr) ; 
			
			
		}) ;
		
	~ ;

} #------------------------------------------------------------------------------------------
 
 
# sub common_min_form_datetimepicker_start_end_date_jquery {
	
	# my ($date_from_name,$date_to_name,$allow_number_days_back,$allow_number_days_forward,$allow_all_start_dates,$allow_all_end_dates) = @_ ;
	
	# $date_from_name = "date_from" unless $date_from_name ;
	# $date_to_name = "date_to" unless $date_to_name ;
	# $allow_number_days_back = "60" unless $allow_number_days_back ;
	# $allow_number_days_back = "$allow_number_days_back" ;
	
	# $allow_number_days_forward = "0" unless $allow_number_days_forward ;
	
	# my $date_from_id = "datetimepicker" . ucfirst $date_from_name ;
	# my $date_to_id = "datetimepicker" . ucfirst $date_to_name ;
	
	# $trigger_jquery_raw .= qq~
		
		# var PastAllowDate = new Date();
		# PastAllowDate.setDate(PastAllowDate.getDate() - $allow_number_days_back) ; 
		
		# var futureAllowDate = new Date() ;
		# futureAllowDate.setDate(futureAllowDate.getDate() + $allow_number_days_forward) ; 
		
		# \$('#$date_from_id').datetimepicker({	
			# language: 'pt-BR',
	# ~ ;
	
	# $trigger_jquery_raw .= qq~
			# startDate: PastAllowDate, // disallow past dates
	# ~ unless $allow_all_start_dates ;	
	
	# $trigger_jquery_raw .= qq~
			# endDate: futureAllowDate,
	# ~ unless $allow_all_end_dates ;		
	
	# $trigger_jquery_raw .= qq~
			# autoclose: true,
			# todayBtn: true
		# }).on('changeDate', function (ev) {
			# // When from-date changes, set minDate for to-date
			# \$('#$date_to_id').datetimepicker('setStartDate', ev.date); 
			
			# let date_from = new Date(\$("input[name='$date_from_name']").val()) ;
			# let date_to = new Date(\$("input[name='$date_to_name']").val()) ;
			# if (date_from > date_to) {
				# let date_part_from = \$("input[name='$date_from_name']").val().split(' ')[0]; 
				 # \$("#$date_to_id").datetimepicker("setDate",date_part_from+" 23:59:59") ;
			# }
			
		# });

		# \$('#$date_to_id').datetimepicker({
			# language: 'pt-BR',
	# ~ ;		
	
	# $trigger_jquery_raw .= qq~	
			# startDate: PastAllowDate, // initialize with today
	# ~ unless $allow_all_start_dates ;	
	
	# $trigger_jquery_raw .= qq~
			# endDate: futureAllowDate,
	# ~ unless $allow_all_end_dates ;	
	
	# $trigger_jquery_raw .= qq~
			# autoclose: true,
			# todayBtn: true
		# }).on('changeDate', function (ev) {
			# \$('#$date_from_id').datetimepicker('setEndDate', ev.date); 
			# let date_from = new Date(\$("input[name='$date_from_name']").val()) ;
			# let date_to = new Date(\$("input[name='$date_to_name']").val()) ;
			# if (date_from > date_to) {
				# let date_part_to = \$("input[name='$date_to_name']").val().split(' ')[0] ;  
				# \$("#$date_from_id").datetimepicker("setDate",date_part_to+" 00:00:00") ;
			# }
		# }) ;
	# ~ ;
	 
# } #------------------------------------------------------------------------------------------ 
 
sub fixture_table_row_selects {
	
	my ($field_key,$suffix,$row_nr) = @_ ;
	# ("age_group","team","home_team","ht_colour","away_team","coding_type","footage_type") 
	$field = "$field_key\_$suffix\_$row_nr";

	# $fcol = ($field_key eq 'home_team' || $field_key eq 'away_team') ? 3 : ($field_key eq 'team' || $field_key eq 'ht_colour' || $field_key eq 'coding_type') ? 2 : 1;
	$fcol = ($field_key eq 'home_team' || $field_key eq 'away_team') ? 2 : ($field_key eq 'age_group' || $field_key eq 'ht_colour' || $field_key eq 'coding_type' || $field_key eq 'service_type') ? 2 : 1 ;

	if ($field_key eq 'home_team' || $field_key eq 'away_team') {
		$preferred_placeholder{"typeahead_$field"} = "$field_key\_$row_nr" ;
		$preferred_placeholder{"typeahead_$field"} = "Select " . join(" ", map { ucfirst $_ } split(/\_/,$preferred_placeholder{"typeahead_$field"})) ;
		$print_box_content_rows .= qq~<input name="$field" value="$default_val{$row_nr}{$field_key}" type='hidden'>~ ;
		$add_form_fields .= &common_min_form_input_col("typeahead_$field",$db{teams}{$default_val{$row_nr}{$field_key}}{name}) ;
		return ;
	}

	my $field_key2 = join(" ", map { ucfirst $_ } split(/\_/,$field_key)) ;
	$preferred_title{$field} = "$field_key2 $row_nr" ;
	$opts{$field} = $opts{$field_key} ;
	$opts{$field} =~ s/value='\Q$default_val{$row_nr}{$field_key}\E'/value='$default_val{$row_nr}{$field_key}' SELECTED/g if $default_val{$row_nr}{$field_key} ;
	
	$allow_deselect{$field} = $allow_deselect{$field_key} ;
	$add_form_fields .= qq~<div class="col-md-6"><div class="row">~ if $field_key eq "team" ;
	$add_form_fields .= &common_min_form_select_col($field,$default_val{$row_nr}{$field_key}) ;
	$add_form_fields .= qq~</div></div>~ if $field_key eq "service_type" || $field_key eq "age_group" ;
	$field_key = "#select" . ucfirst $field ;
	push @all_selects_ids,"$field_key" ;
	$field_key = $field_key . "_chosen" ;
	push @all_selects_tab,"$field_key" ;
	
} #------------------------------------------------------------------------------------------

sub analytics_table_row_labels {
	
	my ($field_key,$suffix,$row_nr) = @_ ;
	# ("age_group","team","home_team","ht_colour","away_team","coding_type","footage_type") 
	$field = "$field_key\_$suffix\_$row_nr";
	# $fcol = ($field_key eq 'home_team' || $field_key eq 'away_team') ? 3 : ($field_key eq 'start_date_time' || $field_key eq 'team' || $field_key eq 'ht_colour' || $field_key eq 'coding_type') ? 2 : 1 ;
	$fcol = ($field_key eq 'age_group' || $field_key eq 'team') ? 6 : ($field_key eq 'stream_key' || $field_key eq 'stream_URL') ? 4  : ($field_key eq 'stream_forwarding' || $field_key eq 'cant_charge_client') ? 2 : 1 ;
	my $field_key2 = join(" ", map { ucfirst $_ } split(/\_/,$field_key)) ; 
	$preferred_title{$field} = "$field_key2 $row_nr";
	$opts{$field} = $opts{$field_key};
	$allow_deselect{$field} = $allow_deselect{$field_key} ;
	# $allow_deselect{$field} = $allow_deselect{$field_key} ;
	# $add_form_fields .= qq~<div class="col-md-6"><div class="row">~ if $field_key eq "team" ;	
	$add_form_fields .= qq~<div class="col-md-1"><div class="row">~ if $field_key eq "age_group" ;	
	$add_form_fields .= qq~<div class="col-md-3"><div class="row">~ if $field_key eq "stream_forwarding" ;	
	$default_val{$row_nr}{$field_key} = &common_min_date_as_string($default_val{$row_nr}{$field_key}) if $field_key eq 'start_date_time' ;
	# my @table_selects_field_keys = ("start_date_time","readonly_sport","age_group","team","home_team","ht_colour","away_team","coding_type","footage_type","service_type","stream_forwarding","stream_key","stream_URL","cant_charge_client") ; 

	if ($field_key eq 'stream_forwarding') {
		$opts{$field} = $opts{stream_forwarding} ;
		$allow_deselect{$field} = 0 ; 
		$opts{$field} =~ s/value='$default_val{$row_nr}{$field_key}'/value='$default_val{$row_nr}{$field_key}' SELECTED/g if $default_val{$row_nr}{$field_key} ;
		$add_form_fields .= &common_min_form_select_col($field,$default_val{$row_nr}{$field_key}) ;
	} elsif ($field_key eq 'stream_key' || $field_key eq 'stream_URL') {
		my $hide = ($default_val{$row_nr}{stream_forwarding} eq '2') ? 1 : 0 ; 
		$default_val{$row_nr}{$field_key} =~ s/\_semi_colon_character_/;/g ; 
		$default_val{$row_nr}{$field_key} =~ s/\_pipe_character_/|/g ; 
		$add_form_fields .= &common_min_form_textarea_col($field,$default_val{$row_nr}{$field_key},22.5,$hide) ;
	} elsif ($field_key eq 'cant_charge_client') {
		my $tt = ($default_val{$row_nr}{cant_charge_client_reason} && $default_val{$row_nr}{cant_charge_client} eq 'Yes') ? qq~title data-toggle="tooltip" data-placement="left" data-original-title="$default_val{$row_nr}{cant_charge_client_reason}"~ : qq~~ ;
		$add_form_fields .= qq~<div class="col-md-$fcol"><span style="font-size:12px;" $tt>$default_val{$row_nr}{cant_charge_client}</span></div>~ ;
	} else {
		$add_form_fields .= qq~<div class="col-md-$fcol"><span style="font-size:12px;">$default_val{$row_nr}{$field_key}</span></div>~ ;
	}

	# $add_form_fields .= qq~</div></div>~ if $field_key eq "coding_type" ;	
	$add_form_fields .= qq~</div></div>~ if $field_key eq "team" || $field_key eq "cant_charge_client" ;	
	
} #------------------------------------------------------------------------------------------

sub common_min_form_datetimepicker_col {
	
	my ($field,$val) = @_ ;
	
	$tindex++ ;
	
	my $ucfirst_field = ucfirst $field ;
	
	my $row = qq(
		<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="$val" id="datetimepicker$ucfirst_field">
					<input style="margin:0;" data-format="yyyy-MM-dd hh:mm:ss" class="form-control" name="$field" value="$val" tabindex="$tindex">
					<span class="input-group-addon add-on">
					  <i data-time-icon="icon-time" data-date-icon="icon-calendar">
					  </i>
					</span>
				</div>
			</div>
		</div>
	) ;
			  
	$trigger_jquery_raw .= qq(\$('#datetimepicker$ucfirst_field').datetimepicker({language: 'pt-BR'}); ) ;
	
	return ($row) ;
	
} #----------------------------------------------------------------------------------------

sub analytics_event_bookings_tabs_build_analytics_table {

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

    my $cntloop = 1 ;
    my $field   = "" ;
    my $val     = 0 ;
	
    $add_form_fields .= qq~<div id='analytics_table'>~;
    
	my @table_selects_field_keys = ("start_date_time","readonly_sport","age_group","team","home_team","ht_colour","away_team","coding_type","footage_type","service_type","stream_forwarding","stream_key","stream_URL","cant_charge_client") ; 
	
	my @sport_type_ids = split(/\;/,$db{$table}{$id}{sport_type_ids}) ; 
	
	my @analytics_saved_values_arr = split(/\|/,$db{$table}{$id}{analytics_saved_values}) ;
	# my @analytics_saved_values_arr = split(/\|/,$db{$table}{$id}{analytics_saved_values}) ;
	# my @analytics_saved_values_arr = split(/\|/,$db{$table}{$id}{analytics_saved_values}) ;
 
	my @cant_charge_client_fixtures_arr = split(/\;/,$db{$table}{$id}{cant_charge_client_fixtures}) ;
	my @cant_charge_client_reasons_arr = split(/\:\|;/,$db{$table}{$id}{cant_charge_client_reasons}) ;

    for my $row_cnt (1 .. $nr_of_rows) {

		$default_val{$row_cnt}{readonly_sport} 	= ($default_val{$row_cnt}{later_readonly_sport}) ? $default_val{$row_cnt}{later_readonly_sport} : $db{sport_types}{$db{$table}{$id}{sport_type_ids}}{name} ;
		
		if ($default_val{$row_cnt}{label_readonly_sport_id} && $db{$table}{$id}{sport_type_ids} !~ /\b$default_val{$row_cnt}{label_readonly_sport_id}\b/) {
			$default_val{$row_cnt}{readonly_sport} 	= "N/A" ;
		}
	   
		$default_val{$row_cnt}{age_group} 		= ucfirst $default_val{$row_cnt}{age_group} ;
        $default_val{$row_cnt}{team} 			= uc $default_val{$row_cnt}{team} ;
        $default_val{$row_cnt}{coding_type} 	= $coding_type{$default_val{$row_cnt}{coding_type}} 				if $default_val{$row_cnt}{coding_type} 	ne 'N/A' ;
        $default_val{$row_cnt}{footage_type} 	= $footage_type{$default_val{$row_cnt}{footage_type}} 				if $default_val{$row_cnt}{footage_type} ne 'N/A' ;
        $default_val{$row_cnt}{ht_colour} 		= $db{analytics_ht_colors}{$default_val{$row_cnt}{ht_colour}}{name} if $default_val{$row_cnt}{ht_colour} 	ne 'N/A' ;
        $default_val{$row_cnt}{home_team} 		= $db{teams}{$default_val{$row_cnt}{home_team}}{name} 				if $default_val{$row_cnt}{home_team} 	ne 'N/A' ; 
		$default_val{$row_cnt}{away_team} 		= $db{teams}{$default_val{$row_cnt}{away_team}}{name} 				if $default_val{$row_cnt}{away_team} 	ne 'N/A' ;
			 
		my @analytics_saved_values_arr_2 = split(/\;/,$analytics_saved_values_arr[$row_cnt-1]) ; 
	
		$default_val{$row_cnt}{stream_forwarding}	= $analytics_saved_values_arr_2[0] ; 
		$default_val{$row_cnt}{stream_key}			= $analytics_saved_values_arr_2[1] ; 
		$default_val{$row_cnt}{stream_URL} 			= $analytics_saved_values_arr_2[2] ; 

		$default_val{$row_cnt}{cant_charge_client} 			= ($cant_charge_client_fixtures_arr[$row_cnt-1]) ? "Yes" : "No" ; 
		$default_val{$row_cnt}{cant_charge_client_reason} 	= $cant_charge_client_reasons_arr[$row_cnt-1] ; 

		if ($row_cnt <= $nr_of_rows) {
			my $style = ($nr_of_displayed_rows < $row_cnt) ? qq~style="display:none;"~ : qq~~ ;
            $add_form_fields .= qq~<div class='row' id='$suffix\_$row_cnt' $style>~ ;
			foreach (@table_selects_field_keys) {
				&analytics_table_row_labels($_,$suffix,$row_cnt) ;
			}
            $add_form_fields .= qq~</div>~ ; 
        }
    }
    
    $add_form_fields .= qq~</div>~;
	
	$trigger_jquery .= qq~ 
		\$("#four [id^='selectStream_forwarding_$suffix\_'][id\$='_chosen']").css("width","100%") ;
	~ ;
	
	$trigger_jquery_raw .= qq~
	
		\$("#analytics_event_bookings-form").on("change","[id^='selectStream_forwarding_']", function () {
			
			let row_nr = get_row_nr (this.id) ;  
			set_default_fixtures_values(row_nr) ; 
			let suffix = (this.id.includes("_$suffix\_")) ? "analytics" : "fixtures" ;
			let other_suffix = (this.id.includes("_$suffix\_")) ? "fixtures" : "analytics" ;
			
			\$("#selectStream_forwarding_"+other_suffix+"_"+row_nr).val(\$(this).val()).trigger("chosen:updated") ; 
			
			if (\$(this).val() == '1' && \$("#textareaStream_key_"+suffix+"_"+row_nr).is(":hidden")) {
				\$("#textareaStream_key_"+suffix+"_"+row_nr).show() ;
				\$("#textareaStream_URL_"+suffix+"_"+row_nr).show() ;				
				\$("#textareaStream_key_"+other_suffix+"_"+row_nr).show() ;
				\$("#textareaStream_URL_"+other_suffix+"_"+row_nr).show() ;
			} else if (\$(this).val() == '2' && !\$("#textareaStream_key_"+suffix+"_"+row_nr).is(":hidden")) {
				\$("#textareaStream_key_"+suffix+"_"+row_nr).hide() ;
				\$("#textareaStream_URL_"+suffix+"_"+row_nr).hide() ;				
				\$("#textareaStream_key_"+other_suffix+"_"+row_nr).hide() ;
				\$("#textareaStream_URL_"+other_suffix+"_"+row_nr).hide() ;
			} else if (!\$(this).val() && \$("#textareaStream_key_"+suffix+"_"+row_nr).is(":hidden")) {
				\$("#textareaStream_key_"+suffix+"_"+row_nr).show() ;
				\$("#textareaStream_URL_"+suffix+"_"+row_nr).show() ;
				\$("#textareaStream_key_"+other_suffix+"_"+row_nr).show() ;
				\$("#textareaStream_URL_"+other_suffix+"_"+row_nr).show() ;
			}
			
		}) ;
		
		\$("#analytics_event_bookings-form").on("change","[id^='textareaStream_key_'],[id^='textareaStream_URL_']", function () {
			
			let row_nr = get_row_nr (this.id) ;  
			set_default_fixtures_values(row_nr) ; 
			let other_suffix = (this.id.includes("_analytics_")) ? "fixtures" : "analytics" ;
			
			if (this.id.includes("Stream_key")) {
				\$("#textareaStream_key_"+other_suffix+"_"+row_nr).val(\$(this).val()) ;
			} else if (this.id.includes("Stream_URL")) {
				\$("#textareaStream_URL_"+other_suffix+"_"+row_nr).val(\$(this).val()) ;
			}
			 
		}) ;
		
	~ ;
	
} #------------------------------------------------------------------------------------------

sub analytics_event_bookings_tabs_build_sec {
	
	my ($sec_) = @_ ;
	
	# # # &db_min_ro('event_quotes_min', 'id,description_workings_event,operator_workings_event', "id = $i{id}", '', '') if $i{id};
	
	my @saved_des = () ; my @saved_op = () ; 

	# my %casual_name_dropdown_hash = () ;
	
	if ($sec_ eq "workings") { 
		@saved_des = split(";", $db{event_quotes_min}{$i{id}}{description_workings_event}) ;
		@saved_op = split(";", $db{event_quotes_min}{$i{id}}{operator_workings_event}) ;
		&db_min_ro('users','*',"user_type LIKE 'casual%' AND block <> 1 AND inactive <> 1",'','') if $iaction eq 'add' ;
		foreach my $uid (sort {$db{users}{$a}{name} cmp $db{users}{$b}{name}} keys %{$db{users}}) { 	
			# $casual_name_dropdown_hash{$uid} = $db{users}{$uid}{name} ;
			$opts{operator_field} .= qq~<option value="$uid">$db{users}{$uid}{name}</option>~ ; 
		}
	} else {
		@saved_des = split(";", $db{event_quotes_min}{$i{id}}{item_costing_event}) ;
	}
	
	unless ($opts{description_field}) { 
		my $other_id = 0 ;
		foreach (sort {$db{event_cost_items}{$a}{name} cmp $db{event_cost_items}{$b}{name}} keys %event_list_name_array_expenses) {
			 
			if (lc $db{event_cost_items}{$_}{name} eq "other") {
				$other_id = $_ ;
				next ; 
			}
			$opts{description_field} .= qq~<option value="$_">$event_list_name_array_expenses{$_}</option>~ ; 
		}
		$opts{description_field} .= qq~<option value="$other_id">Other</option>~ ; 	
	} 
	
	my @description_chosen_field_ids = () ; my @operator_chosen_field_ids = () ; my @desriptions_that_are_operators = () ;
	
	foreach ( sort keys %sec_cnt) {
		$_k = substr($_,1) ; $k  = substr($_,2) ;
		
		my @parts = split(/\-/,$sec_cnt{$_}) ;

		for my $p_ (1 .. $parts[0]) { # item_1_costing_systems
			my $field = "$sec_$_k\_$p_" ; 
			
			my $saved_val = $saved_des[$p_ - 1] ;
			next if $p_ > 1 && !$saved_val ;
			my $saved_val_2 = $saved_op[$p_ - 1] ;
			
			if ($_k eq '_event') {
				$opts{"description_$field"} = $opts{description_field} ;
				$trigger_jquery_raw .= qq~\$("#selectDescription_$field").val("$saved_val") ; \$("#selectDescription_$field").trigger("chosen:updated") ; ~ if $saved_val and $saved_val ne "14" ; 
				push @desriptions_that_are_operators,"#selectDescription_$field" if $saved_val eq "14" ; 
				
				if ($sec_ eq "workings") { 
					$opts{"operator_$field"} = $opts{operator_field} ; 
					$trigger_jquery_raw .= qq~\$("#selectOperator_$field").val("$saved_val_2") ; \$("#selectOperator_$field").trigger("chosen:updated") ; ~ if $saved_val_2 ;		 
				}
			}
			
			$item_type = 'input' ;	

			unless ($got{$field}) {
				$got{$field} = 1 ;
				push @excl_field_ids,"#checkboxExcl_$field" ;
				push @description_field_ids,"#selectDescription_$field" ;
				push @operator_field_ids,"#selectOperator_$field" ;
				push @description_chosen_field_ids,"#selectDescription_$field\_chosen" ;
				push @operator_chosen_field_ids,"#selectOperator_$field\_chosen" ;
				push @vat_field_ids,"#checkboxVat_$field" ;
				push @qty_field_ids,"#inputQty_$field" ;
				push @amount_usd_field_ids,"#inputAmount_usd_$field" ;
				
			}
		}
	}
	
	my $desriptions_that_are_operators_string = join (",",@desriptions_that_are_operators) ;

	$trigger_jquery_raw .= qq~\$("$desriptions_that_are_operators_string").val("14") ; \$("$desriptions_that_are_operators_string").trigger("chosen:updated") ; ~ if $desriptions_that_are_operators_string ; 	
	
	my $description_chosen_field_ids_string 	= join(",",@description_chosen_field_ids) ; 
	
	$trigger_jquery .= qq~\$("$description_chosen_field_ids_string").css("width","90%");~ ;
	
	if ($sec_ eq "workings") {
		my $operator_chosen_field_ids_string	 	= join(",",@operator_chosen_field_ids) ;
		$trigger_jquery .= qq~\$("$operator_chosen_field_ids_string").css("width","90%");~ ;		
	}

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

sub analytics_event_bookings_tabs_customer_select_opts {

	my ($customer_table,$dispfield,$where,$field) = @_ ;
	
	$where .= " AND " if $where ;
	$where .= "analytics='1'" ;
	
	&db_min_ro($customer_table,'*',$where,'','') ;

	foreach my $id (sort { $db{$customer_table}{$a}{name} cmp $db{$customer_table}{$b}{name} } keys %{$db{$customer_table}}) {	
			
		my $saved_val = $db{$table}{$i{id}}{$field} ;
			
		if ($saved_val) { my @valarr = split(/\:/,$saved_val) ; $saved_val = $valarr[0] ; }
		
		if ($saved_val eq $id) { 
			$selected = 'SELECTED' ;
			$db{$customer_table}{$id}{contact_name}		= $db{$table}{$i{id}}{contact_name} ;	
			$db{$customer_table}{$id}{contact_email}    = $db{$table}{$i{id}}{email} ;
			$db{$customer_table}{$id}{phone}			= $db{$table}{$i{id}}{tel} ;
			$db{$customer_table}{$id}{physical_address} = $db{$table}{$i{id}}{address} ;
		} else { 
			$selected = '' ; 
		}
		
		$opts{$field} .= qq~<option $selected value="$id:$db{$customer_table}{$id}{contact_name}:$db{$customer_table}{$id}{contact_email}:$db{$customer_table}{$id}{phone}:$db{$customer_table}{$id}{physical_address}">$db{$customer_table}{$id}{$dispfield}</option>~ ; 
		unless ($got{$field}) {
			# $trigger_jquery .= qq~\$("#selectEvent_to_chosen").css("width","100%");~ ; 		
			$got{$field} = 1 ;
			# $trigger_jquery_raw .= qq~ 
				# \$("#selectClient_id").change( function() {
					# dispCustomer() ;
				# }) ;
			# ~;
		}
	}
	
	$trigger_jquery_raw .= qq~
		function dispCustomer() {
			var custval = \$("#selectClient_id").val();
			var arrP = custval.split(":") ;
			\$("#inputContact_name").val(arrP[1]) ;
			\$("#inputEmail").val(arrP[2]) ;
			\$("#inputTel").val(arrP[3]) ;
			\$("#inputAddress").val(arrP[4]) ;
		}
	~;

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

sub analytics_event_bookings_tabs_build_qt_right {

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

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

sub analytics_event_bookings_tabs_curr_symbols {

	$curr_symb{ZAR} = 'R';
	$curr_symb{USD} = '$';
	$curr_symb{GBP} = 'GBP';
	$curr_symb{EUR} = 'EUR';

	our $js_curr_arr = '' ;

	foreach (keys %curr_symb) {
		$js_curr_arr .= qq(currArr['$_'] = "$curr_symb{$_}";) ;
	}

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

sub analytics_event_bookings_tabs_build_qt_col_headers {

	my ($sec) = @_ ;

	my $style_vat = '' ; 
	
	$style_vat = 'style="display:none;"' if $no_vat{$sec} ; 
		
	$add_form_fields .= qq~<div class='row'>~ ;
	$add_form_fields .= qq~<div class='col-md-1'><label class='control-label'>&nbsp;&nbsp;&nbsp;&nbsp;Excl.</label></div>~ ;
	$add_form_fields .= qq~<div class='col-md-2'><label class='control-label'>Item</label></div>~ if $sec eq 'costing_event';
	$add_form_fields .= qq~<div class='col-md-2'><label class='control-label'>Casual User</label></div>~ if $sec eq 'costing_casual_users';
	$add_form_fields .= qq~<div class='col-md-1'><label class='control-label'>Qty</label></div>~ ;
	$add_form_fields .= qq~<div class='col-md-1'><label class='control-label' id='lab_usd_amnt$sec'>Price</label></div>~ ;
	# $add_form_fields .= qq~<div class='col-md-1'><label class='control-label' id='lab_curr_amnt$sec'>Price</label></div>~ ;
	$add_form_fields .= qq~<div class='col-md-1'><label class='control-label'>Total</label></div>~ ;	
	$add_form_fields .= qq~<div class='col-md-1'><label class='control-label' $style_vat>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;VAT&nbsp;[15\%]</label></div>~ ;
	$add_form_fields .= qq~</div>~ ;
	
	%cost_desc = () ; 
	%def_qty = () ;
	%def_zar = () ; 
	%min_zar = () ; 
	%vat_tick = () ; 
	%excl_tick = () ;

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

sub analytics_event_bookings_tabs_content_box {

	my ($sec_name,$sec_col,$cam_box_icon) = @_ ;

	$fcol=9 ;
	$print_box_content_rows .= &common_min_box_top('indent-left',$sec_name,$sec_col,$cam_box_icon);            
	$print_box_content_rows .= qq~$add_form_fields~;                       
	$print_box_content_rows .= &common_min_box_foot;

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

sub analytics_event_bookings_tabs_cnt {

	our %cntxt = () ;
		
	$cntxt{1}  = 'one' ; 
	$cntxt{2}  = 'two' ;
	$cntxt{3}  = 'three' ;	
	$cntxt{4}  = 'four' ;
		
} #----------------------------------------------------------------------------------------

sub analytics_event_bookings_tabs_names {

	my ($tab) = @_ ;

	my $tabname = '' ;

	   if ($tab == 1) { $tabname = 'Customer Details'	; }
	elsif ($tab == 2) { $tabname = 'Event Details'		; }
	elsif ($tab == 3) { $tabname = 'Fixtures'			; }
	elsif ($tab == 4) { $tabname = 'Analytics'			; } 

	return ($tabname) ;

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

sub analytics_event_bookings_tabs_hash {
	
	# &db_min_ro('users',"id","user_type like '%casual%'",'','') ; 
	# &db_min_ro('events',"id,event_quote_nr,user_id,category",'','','') ;
	# &db_min_ro('event_cost_items','*','','name asc','') ;
	
	our @excl_field_ids = () ; our @description_field_ids = () ; our @operator_field_ids = () ; our @vat_field_ids = () ; our @qty_field_ids = () ; our @amount_usd_field_ids = () ; our @excl_field_ids = () ; our @btn_ids = () ;
	
	&analytics_event_bookings_tabs_load_vars;

	for (1 .. 4) {
 
		my $tname = &analytics_event_bookings_tabs_names($_) ;
		our $ret_pdf_link_sec = '' ; # _sa_out+16|_cl_del+13|_sa_in+17|_des_sa+13|

		&analytics_event_bookings_tabs_build_qt_left('',$_,1) ;
		# &analytics_event_bookings_tabs_build_qt_right('',$_,1) ;
		
		$tabcnt{$tname} = $_ ;
		$tabsec{$tname} = $ret_pdf_link_sec ;
	}
		
	# &build_workings_costings_forms_jquery ; 	
		
} #------------------------------------------------------------------------------------

sub analytics_event_bookings_tabs_load_vars {
	
} #------------------------------------------------------------------------------------

sub analytics_event_bookings_tabs_sec_det {

	my ($sec) = @_ ;

	my ($sec_nam,$sec_cnt,$sec_col) ;

	$sec_col = '71919b' ; # '85acb8' ;
	$sec_cnt = 20 ; 
	$sec_nam = substr($sec,1) ; 
	@array   = split(/\_/,$sec_nam); 
	my @sec_nam = map ucfirst, @array;
	$sec_nam = join(" ", @sec_nam) ;

	# if ($sec eq 'costing') {
		# $sec_nam = 'Event Costings' ;  
		# for (1 .. 30) { $vat_tick{$_} = 1 ; }	
	# }
	
	# if ($sec eq 'workings') {
		# $sec_nam = 'Event Expenses' ;  
		# for (1 .. 50) { $vat_tick{$_} = 1 ; }	
	# }

	return ($sec_nam,$sec_cnt,$sec_col) ;

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

sub analytics_event_bookings_tabs_form_checkbox_col {

my ($field,$val,$checked,$classic,$dont_end_col) = @_ ;

my $ucfirst_field = ucfirst $field ;
my $print_field   = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; }
my $field_id      = "checkbox$ucfirst_field" ;
my $check_class   = ($classic) ? 'class="iphone-toggle"' : '' ;

my $label = '' ; if ($label{$field}) { $label = "<label for='$field_id' $style_field{$field}></label>" ; }

$tindex++ ;

my $row = qq~
	<div class="col-md-$fcol" id="c_$field">
		<input name="$field" data-no-uniform="true" type="checkbox" $check_class id="$field_id" $style_field{$field} $checked value="1" tabindex="$tindex">
		$label
~ ;

$row .= qq~</div>~ unless $dont_end_col ; 

unless ($excl_on_change{$field}) { push @jquery_trigger_fields, $field_id ; }
# unless ($excl_on_change{$field}) { push @jquery_workings_trigger_fields, $field_id ; }
    
return ($row) ;

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

sub analytics_event_booking_tabs_update_credits_used {
	
	my ($id,$id2) = @_ ; 

	my %credits_used = () ; my $row_cnt = 0 ;	
	
	my @cnt_charge = split(/\;/,$db{$table}{$id}{cant_charge_client_fixtures}) ;

	if ($db{$table}{$id}{client_id}) {
		foreach my $fixture_row (@fixtures_saved_values_split) {
			$row_cnt++ ;
			last if $row_cnt > $db{$table}{$id}{total_fixtures} ;
			my @fixtures_saved_values_split_2 = split(/\;/,$fixture_row) ;
			my $sport_id = ($db{$table}{$id}{sport_type_ids} !~ /;/) ? $db{$table}{$id}{sport_type_ids} : $fixtures_saved_values_split_2[1] ;

			next unless $sport_id ;
			
			$credits_used{previous}{premium}{$db{$table}{$id}{client_id}}{$sport_id} 	+= 1 if $fixtures_saved_values_split_2[7] eq 'p' && !$cnt_charge[$row_cnt-1] ;
			$credits_used{previous}{standard}{$db{$table}{$id}{client_id}}{$sport_id} 	+= 1 if $fixtures_saved_values_split_2[7] eq 's' && !$cnt_charge[$row_cnt-1] ;
			$credits_used{previous}{individual}{$db{$table}{$id}{client_id}}{$sport_id} += 1 if $fixtures_saved_values_split_2[7] eq 'i' && !$cnt_charge[$row_cnt-1] ;
		}
	}

	if ($i{client_id}) {

		@fixtures_saved_values_split = split(/\|/,$i{fixtures_saved_values}) ;
		$row_cnt = 0 ;
		@cnt_charge = split(/\;/,$i{cant_charge_client_fixtures}) ;
		
		foreach my $fixture_row (@fixtures_saved_values_split) {

			$row_cnt++ ;
			last if $row_cnt > $i{total_fixtures} ;
			my @fixtures_saved_values_split_2 = split(/\;/,$fixture_row) ;
			
			my $sport_id = ($i{sport_type_ids} !~ /;/) ? $db{$table}{$id}{sport_type_ids} : $fixtures_saved_values_split_2[1] ;

			next unless $sport_id ;

			$credits_used{new}{premium}{$i{client_id}}{$sport_id} 		+= 1 if $fixtures_saved_values_split_2[7] eq 'p'	&& !$cnt_charge[$row_cnt-1] ;
			$credits_used{new}{standard}{$i{client_id}}{$sport_id} 		+= 1 if $fixtures_saved_values_split_2[7] eq 's'	&& !$cnt_charge[$row_cnt-1] ;
			$credits_used{new}{individual}{$i{client_id}}{$sport_id} 	+= 1 if $fixtures_saved_values_split_2[7] eq 'i'	&& !$cnt_charge[$row_cnt-1] ;

		}
		
		my %seen = () ; 
	
	}
	
	$seen{client}{$i{client_id}} = 1 if $i{client_id} ; 
	$seen{client}{$db{$table}{$id}{client_id}} = 1 if $db{$table}{$id}{client_id} ; 

	foreach (split(/\;/,$db{$table}{$id}{sport_type_ids})) {
		$seen{sport}{$_} = 1 if $_ ; 
	}
	
	if ($i{sport_type_ids}) {
		foreach (split(/\;/,$i{sport_type_ids})) {
			$seen{sport}{$_} = 1 if $_ ; 
		}
	}
	
	my $sport_sql 	= join(" OR ",map{"sport_type_id='$_'"} keys %{$seen{sport}}) ; 
	my $client_sql 	= join(" OR ",map{"client_id='$_'"} keys %{$seen{client}}) ; 
	my $id_sql 		= ($id2) ? "analytics_event_id='$id2'" : ($id) ? "analytics_event_id='$id'" : "" ; 
	
	my @sql_where_arr = () ; 
	push @sql_where_arr,"($sport_sql)" 	if $sport_sql ;
	push @sql_where_arr,"($client_sql)" if $client_sql ;
	push @sql_where_arr,$id_sql 	if $id_sql ;
	
	my $sql_where = join(" AND ",@sql_where_arr) ;

	&db_min_ro('credits_used','*',$sql_where,'','') ; my %exists = () ; 

	my %db_credits_used = %db ; 

	foreach my $_id (keys %{$db{credits_used}}) {
		$exists{$db{credits_used}{$_id}{sport_type_id}}{$db{credits_used}{$_id}{client_id}} = 1 ; 
	}
	
	my $new_id = 0 ; 
	
	foreach my $client_id (sort {$a <=> $b} keys %{$seen{client}}) {
		foreach my $sport_id (sort {$a <=> $b} keys %{$seen{sport}}) {
			unless ($exists{$sport_id}{$client_id}) {
				if ($new_id) {
					$new_id++ ;
				} else {
					$new_id = &db_min_get_max('credits_used','id') ; 
				}

				$db_credits_used{credits_used}{$new_id}{sport_type_id} = $sport_id ;
				$db_credits_used{credits_used}{$new_id}{client_id} = $client_id ;
				
			}
		}
	} 

	my %hidden_old = %hidden ; 
	%hidden = () ; 
	my %ignore_old = %ignore ; 
	%ignore = () ;
	my %ij = %i ;
	
	# cant_charge_client_fixtures_1
	foreach my $_id (keys %{$db_credits_used{credits_used}}) {

		my $premium_credits 	= ($db_credits_used{credits_used}{$_id}{premium_credits_used}) 		? $db_credits_used{credits_used}{$_id}{premium_credits_used} 	: 0 ;
		my $standard_credits 	= ($db_credits_used{credits_used}{$_id}{standard_credits_used})  	? $db_credits_used{credits_used}{$_id}{standard_credits_used}  	: 0 ;
		my $individual_credits 	= ($db_credits_used{credits_used}{$_id}{individual_credits_used}) 	? $db_credits_used{credits_used}{$_id}{individual_credits_used} : 0 ;
		
		my $sport_id			= $db_credits_used{credits_used}{$_id}{sport_type_id} ;
		my $client_id			= $db_credits_used{credits_used}{$_id}{client_id} ;
		
		%i = () ; 

		$i{premium_credits_used} 	= $credits_used{new}{premium}{$client_id}{$sport_id} ;
		$i{standard_credits_used}	= $credits_used{new}{standard}{$client_id}{$sport_id} ;
		$i{individual_credits_used} = $credits_used{new}{individual}{$client_id}{$sport_id} ;
		
		$i{premium_credits_used} 	= 0 unless $i{premium_credits_used} ; 
		$i{standard_credits_used} 	= 0 unless $i{standard_credits_used} ; 
		$i{individual_credits_used} = 0 unless $i{individual_credits_used} ; 
		
		$ignore{premium_credits_used} 		= ($credits_used{new}{premium}{$client_id}{$sport_id} 		ne $premium_credits) 	? 0 : 1 ; 
		$ignore{standard_credits_used} 		= ($credits_used{new}{standard}{$client_id}{$sport_id} 		ne $standard_credits) 	? 0 : 1 ; 
		$ignore{individual_credits_used} 	= ($credits_used{new}{individual}{$client_id}{$sport_id}	ne $individual_credits) ? 0 : 1 ; 

		if (!$exists{$sport_id}{$client_id} && ($i{premium_credits_used} || $i{standard_credits_used} || $i{individual_credits_used}) && $ij{event_accepted}) {
			$i{id} = "$_id" ;
			$i{sport_type_id} = "$sport_id" ;
			$i{client_id} = "$client_id" ;
			$i{analytics_event_id} = ($id2) ? "$id2" : ($id) ? "$id" : "0" ; 
			&db_min_insert('credits_used') ; 
		} elsif ($exists{$sport_id}{$client_id} && ($i{premium_credits_used} || $i{standard_credits_used} || $i{individual_credits_used}) && $ij{event_accepted}) {
			&db_min_upd('credits_used',"id='$_id'") ; 
		} elsif ($exists{$sport_id}{$client_id} && ((!$i{premium_credits_used} && !$i{standard_credits_used} && !$i{individual_credits_used}) || !$ij{event_accepted})) {
			&db_min_delete('credits_used',"id='$_id'") ; 
		}
	}
	
	%ignore = %ignore_old ;
	%hidden = %hidden_old ;
	%i = %ij ; 

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

1;
