<?PHP

/** TO DO **

- Allow users to search by start time
- Allow users to search by entry fee

************/

include("config.php");
require_once("rating/classes/include.all.php");

if (!$_POST){ header('Location: '.$site_url); }

// build the SQL query
$sql = 'SELECT onetype, twotype, threetype, oneunit, twounit, threeunit, name, nametag, statetag, swim, bike, run, city, state, uid, UNIX_TIMESTAMP(date) as foo FROM gforum_Triathlons WHERE valid = 1';

// add tri or du or other
if (isset($_POST[type])) {
  // convert the array to a SQL friendly format
  $typelist = "(".implode(",", $_POST[type]).")";
  $sql = $sql." AND type IN $typelist";
}

// add bike surface
if (isset($_POST[bike_surface])) {
  // convert the array to a SQL friendly format
  $surfacelist = "(".implode(",", $_POST[bike_surface]).")";
  $sql = $sql." AND bike_surface IN $surfacelist";
}

// add draft legal surface
if (isset($_POST[draft_legal])) {
  // convert the array to a SQL friendly format
  $draftlegallist = "(".implode(",", $_POST[draft_legal]).")";
  $sql = $sql." AND draft_legal IN $draftlegallist";
}

// add kids race
if (isset($_POST[kids_race])) {
  // convert the array to a SQL friendly format
  $kidsracelist = "(".implode(",", $_POST[kids_race]).")";
  $sql = $sql." AND kids_race IN $kidsracelist";
}

// add reg fees
if (isset($_POST[registration])) {
  // convert the array to a SQL friendly format
  $registrationlist = "(".implode(",", $_POST[registration]).")";
  $sql = $sql." AND registration IN $registrationlist";
}


// add date range
if (isset($_POST['futuredates']) OR $_POST['keyword'] == "") {
	if ($_POST[aftermonth] != 0 AND $_POST[afterday] != 0) { 
	  $afterdate = "$_POST[afteryear]-$_POST[aftermonth]-$_POST[afterday]";
	  $sql = $sql." AND date >= '$afterdate'"; }
	else { $sql = $sql." AND date >= NOW()"; }
	if ($_POST[beforemonth] != 0 AND $_POST[beforeday] != 0) { 
	  $beforedate = "$_POST[beforeyear]-$_POST[beforemonth]-$_POST[beforeday]";
	  $sql = $sql." AND date <= '$beforedate'"; 
	}
} else {
	$last_year = time() - 365*24*60*60;
	$sql = $sql." AND date >=  '".date('Y-m-d', $last_year)."'";
}
  
// regions are checkboxes that then check off all states within that region
// add states
if (isset($_POST[states])) {
  $glue = "','";
  $statelist = "('".implode($glue, $_POST[states])."')";
  $sql = $sql." AND statetag IN $statelist";
}

// add distances
if (isset($_POST[points])) {
  // convert the array to a SQL friendly format
  $glue = ",";
  $pointlist = "(".implode($glue, $_POST[points]).")";
  $sql = $sql." AND pointclass IN $pointlist";
}

$sql = $sql." ORDER BY date ASC";

$results = mysql_query($sql);

$none = FALSE;
if (mysql_num_rows($results) == 0) {
  $none = TRUE;
}
$race_count = mysql_num_rows($results);

// trim redundant keywords: triathlon, duathlon
$trim_words = array(" the ", " a ", " an ", "and ", " half ", "triathlon", "duathlon");
foreach ($trim_words AS $word) {
	$_POST['keyword'] = str_ireplace($word, " ", $_POST['keyword']);
}
$bool_Keywords = false;
if (isset($_POST['keyword']) && $_POST['keyword'] != "") {
//keyword search
	$bool_Keywords = true;
	while($row_races = mysql_fetch_array($results)) {
		// build an array that we can loop through.
		$arr_Races[$i] = $row_races;
		$i++;
	}
	
	$arr_Matches = array();
	foreach ($arr_Races AS $race) {	
			if (stripos($race['name'], $_POST['keyword']) !== false) {
				// push this onto the array of matches
				$race['percent'] = 100;
				array_push($arr_Matches, $race);
			} else {
				$name_nospace = str_replace(" ", "", $race['name']);
				$keyword_nospace = str_replace(" ", "", $_POST['keyword']);
				if (stripos($name_nospace, $keyword_nospace) !== false) {
					// push this onto the array of matches
					$race['percent'] = 90;
					array_push($arr_Matches, $race);
				} else {
					// trim redundant keywords
					$race_name = $race['name'];
					foreach ($trim_words AS $word) {
						$race_name = str_ireplace($word, " ", $race_name);
					}
					//$race_name = str_ireplace(" ", "", $race_name);
					$race_name = strtolower($race_name);
					$arr_race_name = explode(" ", $race_name);
					$_POST['keyword'] = strtolower($_POST['keyword']);
					$_POST['keyword'] = str_replace(" ", "", $_POST['keyword']);
					foreach ($arr_race_name AS $test_word) {					
						similar_text($test_word, $_POST['keyword'], $percent);
						if ($percent >= 65) {
							// push this onto the array of matches
							$race['percent'] = round($percent, 0);
							//$race['trimmed'] = $race_name;
							array_push($arr_Matches, $race);
							break;
						}
					}
				}
			}
	}
	
	if (count($arr_Matches) == 0) {
 		$none = TRUE;
 	}
 	$race_count = count($arr_Matches);
 	
 	//sort the array by keyword match success instead of by date
 	function cmp($a, $b)
	{
		if ($a['percent'] == $b['percent']) {
			return 0;
		}
		return ($a['percent'] > $b['percent']) ? -1 : 1;
	}
	
	usort($arr_Matches, "cmp");
}
//end keyword search

// set the page title
$pagetitle = "Search Results";

// set meta tags
$meta_keywords = "triathlons in matching a user's search query.";
$meta_description = "A list of matching races.";
?>

<? include("include_common_head.php"); ?>
<body class="listings">
  <? include($common_path . "/ads/ad_wallpaper.html"); ?>

  <div class="container">
    <? include($common_path . "/templates/include_header.php"); ?>
    <div class="main">
      <div class="contentwrapper clearfix">
        <? include("include_breadcrumb.php"); ?>

        <section class="section listings section-has-widgets section-static remove-sidebar">
          <div class="sidebar-b">
            <? include("include_sidebar.php"); ?>
          </div>

          <div class="content content-has-widgets">
            <div class="grid">

              <div class="clearfix">
                <h1>Search Results</h1>
                <p><strong><? echo $race_count ?> Races Match Your Search</strong></p>
                <? 
                if ($bool_Keywords == true) {
                    foreach($arr_Matches AS $row){	
                        include("include_race.php");
                    } // end foreach arr_Matches 
                } else { //if bool_Keywords
                    while ($row = mysql_fetch_array($results)) {
                        include("include_race.php");
                    } // end foreach mysql_fetch_array ?>
                <? } // end else ?>


              </div><!-- end col-2/3 -->

            </div><!-- end grid -->
          </div><!-- end content -->
        </section>
          
      </div><!-- end contentwrapper -->
    </div> <!-- end main -->

  <? include($common_path . "/templates/include_footer.php") ?>
  </div> <!-- container  -->
</body>
<? include($common_path . "/templates/include_global_js.php") ?>
</html>

