<?php
//##############################################################################
//
//Project:      Runner Search Tool
//Filename:     index.php
//Date:         January 8, 2008
//Description:  This file queries the db for results of the runner
//              search.
//##############################################################################

    //Session start
    session_start();
    
    //Connect to database
    include('config.php');
    
    // Load Smarty Library
    include('smarty_config.php');
    
    //Initialize debug file
    require_once 'KLogger.php';
    $log = new KLogger ( "logs" , KLogger::OFF );  //OFF or DEBUG
    
    
    //Results per page constant
    if(empty($_GET["results_per_page"])){
        $RESULTS_PER_PAGE = 400;
    }else{
        $RESULTS_PER_PAGE = $_GET["results_per_page"];
    }
    
    
    //######################################################################
    //Selection Menu
    //######################################################################
    
    //Selections for Event 
    $smarty->assign('event',$events);
    
    //Selections for Gender 
    $smarty->assign('gender', $genders);
    
    
    //######################################################################
    //Build Division Dropdown
    //######################################################################
    
    $divisions = array( "Overall" => "Overall");
    
    if ($masters_awards) {
        $divisions["Masters"] = "Masters";
    }
    if ($grand_masters_awards) {
        $divisions["Grand Masters"] = "Grand Masters";
    }

    $lower_age_limit = 1;
    $age_cutoff_size = sizeof($age_cutoffs);
    if ($age_cutoff_size) {
        $divisions[0] = "0-0";
    }
    for ($i=0; $i < $age_cutoff_size; $i++) {
        $divisions[$age_cutoffs[$i]] = $lower_age_limit . "-" . $age_cutoffs[$i];
        $lower_age_limit = $age_cutoffs[$i] + 1;
        if ( ($i+1) == $age_cutoff_size ) {
            $divisions[200] = $lower_age_limit . "+";
        }
    }
    
    //Selections for Division
    $smarty->assign('divisions', $divisions);
    
    
    //######################################################################
    //Table
    //######################################################################
    
    //Obtain all variable from select_report form
    $page = $_GET["page"];
    $event_sel = $_GET["event"];
    $smarty->assign('event_sel',$event_sel);
    $gender_sel = $_GET["gender"];
    $smarty->assign('gender_sel',$gender_sel);
    $division_sel = $_GET["division"];
    $smarty->assign('division_sel',$division_sel);
	$active = $_GET["results_active"];
	$smarty->assign('results_active', (!empty($active)) ? "checked" : "");
    
    $bib_sel = $_GET["bib"];
    $smarty->assign('bib_sel',$bib_sel);
    $first_name_sel = $_GET["first_name"];
    $smarty->assign('first_name_sel',$first_name_sel);
    $last_name_sel = $_GET["last_name"];
    $smarty->assign('last_name_sel',$last_name_sel);
    
    //Retrieve type of search
    $search_type = $_GET["search_type"];
    $smarty->assign('search_type',$search_type);
    
    //Get results for the different categories
    
    
    $first = true;
    
    if(empty($page)){
        $page = 1;
    }
	
	$query = "";
    $overall_array = array();
    
	if($search_type == "race_results"){
        include('results.php');
        
        //Check to see any selected
        if (empty($event_sel)) {
            $event_sel = 'Overall';
        }
        if (empty($gender_sel)) {
            $gender_sel = 'Overall';
        }
        
        if ($active) {
            $overall_array = $overall_active_list[$event_sel][$gender_sel];
        } else {
            $overall_array = $overall_list[$event_sel][$gender_sel];
        }
		
	}elseif($search_type == "runner_lookup"){
		if(!empty($bib_sel) || !empty($first_name_sel) || !empty($last_name_sel)){
            include('results.php');
            
			$query = "SELECT * FROM ".$tableName." WHERE";
			
			$query_base = $query;
			if(!empty($bib_sel)){
				if($query == $query_base){
					$query .= " bib = '".$bib_sel."'";
				}else{
					$query .= " AND bib = '".$bib_sel."'";
				}
			}
			if(!empty($first_name_sel)){
				if($query == $query_base){
					$query .= " `first_name` LIKE '".$first_name_sel."%'";
				}else{
					$query .= " AND `first_name` LIKE '".$first_name_sel."%'";
				}
			}
			if(!empty($last_name_sel)){
				if($query == $query_base){
					$query .= " `last_name` LIKE '".$last_name_sel."%'";
				}else{
					$query .= " AND `last_name` LIKE '".$last_name_sel."%'";
				}
			}
            
            if ($query == $query_base){
                $query = str_replace('WHERE','',$query);    
            }
		}
	}
	
     
    
    if($page < 2 && !empty($query)){
        $query_total = str_replace("*","COUNT(*) AS numrows",$query);
        //echo "\n".$query_total;
        $result_total = mysql_query($query_total);
        @$row_total = mysql_fetch_array($result_total);
        $numrows = $row_total["numrows"];
        $num_pages = $numrows/$RESULTS_PER_PAGE;
        
        $_SESSION["num_pages"] = $num_pages;
        
    } elseif ($page < 2 && sizeof($overall_array) > 0) {
        $numrows = sizeof($overall_array);
        
        $num_pages = $numrows/$RESULTS_PER_PAGE;
        
        $_SESSION["num_pages"] = $num_pages;
    }
    
	//Determine way to sort results
    $original_query = $query;
	if($search_type == "race_results" && !empty($query)){
		//race_results
		$query .= " ORDER BY status";
        for($i=$NUM_LAPS;$i>0;$i--){
            $query .= ", lap".$i;
        }
	}elseif(!empty($query)){
		//runner_lookup
		$query .= " ORDER BY last_name DESC";
	
	}
	
    if($page == 1 && !empty($query)){
        $query .= " LIMIT 0, ".$RESULTS_PER_PAGE;
    }elseif(!empty($query)){
        $low_limit = ($page-1)*$RESULTS_PER_PAGE;
        $duration = $RESULTS_PER_PAGE;
        $query .= " LIMIT ".$low_limit.", ".$duration."";
    }
	
	if($search_type == "runner_info"){
        include('results.php');
        
		$query = "SELECT * FROM ".$tableName." WHERE bib = '".$bib_sel."'";
	}


    if((!empty($query) && $query != "") || sizeof($overall_array) > 0){
        //echo "Query:".$query."\n";
        //$log->LogDebug("Live Results Query: " . $query);
		
        $has_overall_array = 0;
        if (!empty($query) && $query != "") {
            //$msc=microtime(true);
            $result = mysql_query($query);
            //$msc=microtime(true)-$msc;
            //echo "Query time:".$msc;
            @$num_rows = mysql_num_rows($result);
            //echo "num rows:".$num_rows;
        } else {
            $has_overall_array = 1;
            $num_rows = $RESULTS_PER_PAGE;
        }
        
        //Display data rows
        if($num_rows >= 1 and $search_type != "runner_info"){
			
            $counter = 0;
            $place_num = (($page-1) * $RESULTS_PER_PAGE)+1;
            for($i=1;$i<=$num_rows;$i++){
                if ($has_overall_array) {
                    $row = $overall_array[$place_num];
                    
                    if (!array_key_exists($place_num, $overall_array)) {
                        break;
                    }
                } else {
                    $row = mysql_fetch_array($result);
                }
                $do_not_show_placing = in_array(strtolower(trim($row["status"])), array("dnf", "dns")) ? 1 : 0;
                if ($do_not_show_placing) {
                    $table_data[$counter] = "&nbsp;";
                } else if ($active) {
					$table_data[$counter] = $place_num; 
                } else {
                    $table_data[$counter] = $overall_nongender_results[$row["bib"]];
                }
                $counter += 1;
                $table_data[$counter] = ($do_not_show_placing) ? "&nbsp;" : $div_results[$row["bib"]];
                $table_data[$counter + 1] = ($do_not_show_placing) ? "&nbsp;" : $overall_results[$row["bib"]];
                $table_data[$counter + 2] = "<a href=\"#\" onClick=\"location.href='index.php?search_type=runner_info&bib=".$row["bib"]."'\">".$row["bib"]."</a>";
                $table_data[$counter + 3] = $row["first_name"];
                $table_data[$counter + 4] = $row["last_name"];
                $table_data[$counter + 5] = $row["gender"];
                $table_data[$counter + 6] = $row["age"];
				$table_data[$counter + 7] = $row["race"];
                $table_data[$counter + 8] = $runner_info[$row["bib"]]["division"];
                
				//Determine number of laps completed
				$laps_completed = 0;
				$lap_time = "N/A";
				for($j=0;$j<$NUM_LAPS;$j++){
					if(!in_array(strtolower(trim($row["lap".($j+1)])), array("dnf","dns","active", ""))){
						$laps_completed++;  
						$lap_time = $row["lap".($j+1)];
					}
				}
                
                $table_data[$counter + 9] = $laps_completed;
                    
                if ($show_chip_time) {
                    $chip_lap_time = "";
                    if ($lap_time && $lap_time != "N/A") {
                        $start_time = trim($row["start_time"]);
                        
                        if($start_time && preg_match('/\d\d[:]\d\d[:]\d\d/', $start_time) && preg_match('/\d\d[:]\d\d[:]\d\d/', $lap_time)) {
                            $chip_lap_time = subtract_times($lap_time, $start_time);
                        }
                    }
                    $table_data[$counter + 10] = $lap_time;
                    $table_data[$counter + 11] = $chip_lap_time;   
                    $table_data[$counter + 12] = $row["status"];
                    $counter = $counter + 13;
                    
                } else {
                    $table_data[$counter + 10] = $lap_time;
                    $table_data[$counter + 11] = $row["status"];
                    $counter = $counter + 12;
                }
				
                $place_num++;
				
            }
            
            $smarty->assign('table_size',($show_chip_time ? 14 : 13));
            
            $tr_attr = array ("", "style='background-color: #F2F2F2;'");
            $smarty->assign('tr_attr', $tr_attr);
            
            //$smarty->assign('search_type', 'runner_lookup');
            $smarty->assign('table_data',$table_data);
        
        }else if ($num_rows == 1 && $search_type == "runner_info"){
			$runner_column = array();
			$runner_data = array();
			$row = mysql_fetch_array($result);
            
            $do_not_show_placing = in_array(strtolower(trim($row["status"])), array("dnf", "dns")) ? 1 : 0;
            
            $smarty->assign('runner_race', $row["race"]);
            $smarty->assign('runner_bib', $row["bib"]);
            $smarty->assign('runner_name', $row["first_name"] . " " . $row["last_name"]);
            $smarty->assign('runner_age', $row["age"]);
            $smarty->assign('runner_gender', $row["gender"]);
            $smarty->assign('runner_division', $runner_info[$row["bib"]]["division"]);
            
            if (!$do_not_show_placing) {
                $smarty->assign('runner_overall_place',$overall_nongender_results[$row["bib"]]);
                $smarty->assign('runner_division_place', $div_results[$row["bib"]]);
                $smarty->assign('runner_gender_place', $overall_results[$row["bib"]]);
            } else {
                $smarty->assign('runner_overall_place', "&nbsp;");
                $smarty->assign('runner_division_place', "&nbsp;");
                $smarty->assign('runner_gender_place', "&nbsp;");
            }
            
            $data_counter = 0;
            $prev_time = "00:00:00";
            $total_time = "00:00:00";
            for($j=0;$j<$NUM_LAPS;$j++){
                $new_time = trim($row["lap".($j+1)]);
                
                $runner_column[$data_counter] = "Lap ".($j+1)." Gun Time";
                
                $time_pattern = '/^\d\d[:]\d\d[:]\d\d/';
                if (preg_match($time_pattern, $new_time)) {
                    $total_time = $new_time;
                    
                    $new_time = subtract_times($new_time, $prev_time);
                    $prev_time = $total_time;
                }
                
				$runner_data[$data_counter] = $new_time;
                $data_counter++;
                
            }
            
            if ($show_chip_time) {
                $prev_time = "00:00:00";
                $total_time = "00:00:00";
                for($j=0;$j<$NUM_LAPS;$j++){
                    $new_time = trim($row["lap".($j+1)]);
                    
                    $runner_column[$data_counter] = "Lap ".($j+1)." Chip Time";
                    

                    $start_time = trim($row["start_time"]);
                        
                    if($start_time && preg_match('/\d\d[:]\d\d[:]\d\d/', $start_time) && preg_match('/\d\d[:]\d\d[:]\d\d/', $new_time)) {
                        $new_time = subtract_times($new_time, $start_time);
                    }          
                    
                    $time_pattern = '/^\d\d[:]\d\d[:]\d\d/';
                    if (preg_match($time_pattern, $new_time)) {
                        $total_time = $new_time;
                        
                        $new_time = subtract_times($new_time, $prev_time);
                        $prev_time = $total_time;
                    }
                    
                    $runner_data[$data_counter] = $new_time;
                    $data_counter++;
                    
                }
            }
            

            $smarty->assign('runner_total_time', $total_time);
			$smarty->assign('search_type', 'runner_info');
			$smarty->assign('runner_column', $runner_column);
			$smarty->assign('runner_data', $runner_data);
		}else{
			//No runner found
			$table_data = array();
			$smarty->assign('table_data',$table_data);
			$smarty->assign('search_type', "no_results");
			
		}
  
        
        $smarty->assign('display_empty', false);
        if($num_rows > 0){
            $smarty->assign('display_table',true);
        }else{
            $smarty->assign('display_table',false);
        }
    }else{
        $smarty->assign('search_type', '');       
    }
    //######################################################################
    //Results per page selection
    //######################################################################
    $page_size_arr[0] = 3;
    $page_size_arr[1] = 5;
    $page_size_arr[2] = 10;
    $page_size_arr[3] = 25;
    $page_size_arr[4] = 50;
    $page_size_arr[5] = 100;
    $page_size_arr[6] = 200;
    $page_size_arr[7] = 400;
    
    $smarty->assign('results_per_page',$page_size_arr);
    $smarty->assign('results_per_page_sel',$RESULTS_PER_PAGE);
    
    //######################################################################
    //Page Numbers (at the bottom of the page)
    //######################################################################
    for($i=0;$i<$_SESSION["num_pages"];$i++){
        if(($i+1) == $page){
            $page_number[$i] = "<span>".($i+1)."</span>";
        }else{
            $page_number[$i] = "<a href=\"#\" onClick=\"location.href='index.php?".$_SERVER['QUERY_STRING']."&page=".($i+1)."'\" title=\"Go to Mask Set ".$Mask_Label[$i]."\">".($i+1)."</a>";
        }
    }
    
    
    $smarty->assign('page_number',$page_number);
    
    $smarty->assign('title_prefix', $title_prefix);
    
    $smarty->assign('show_chip_time', $show_chip_time);
    
    //Display index.php template file
    if ($bib_lookup) {
        //Mobile bib results lookup page
        $smarty->display('biblookup.tpl');
    } else {
        //Live results page
        $smarty->display('index.tpl');
    }
           
?>
