<?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");

// string comparison match percent
$comp_pct = 70;

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

// build the SQL query
$sql = "SELECT fitter_id, fitter_name, fitter_address, fitter_address_two, fitter_city, fitter_state, fitter_zip, fitter_phone, fitter_fax, fitter_email, fitter_website, fitter_certifications, fitter_fitbikes FROM ".$prefix."Fitters WHERE fitter_valid=1 ";

// add fitters

if (isset($_POST[portfolio])) {
	$sql = $sql." AND fitter_portfolio <> ''";
}

if (isset($_POST[methods])) {
  if (in_array("999", $_POST[methods])) {
  		$sql = $sql." AND fitter_method <> '0'";
  } else {
	  	$sql = $sql." AND (";
  	  	$flag = 0;
	  	foreach ($_POST[methods] AS $value) {
	    	if ($flag == 1){
	    		$sql = $sql." OR ";
	    	}
			$sql = $sql."fitter_method = '$value'";
			$flag = 1;
	  	}
	  	$sql = $sql.")";
  }
}

if (isset($_POST[certifications])) {
  if (in_array("999", $_POST[certifications])) {
  		$sql = $sql." AND fitter_certifications <> ',0,'";
  } else {
  	  /**$sql = $sql."AND (";
  	  $flag = 0;
	  foreach ($_POST[certifications] AS $value) {
	    if ($flag == 1){
	    	$sql = $sql." OR ";
	    }
		$sql = $sql."fitter_certifications LIKE '%,$value,%'";
		$flag = 1;
	  }
	  $sql = $sql.")";**/
	  foreach ($_POST[certifications] AS $value) {
		$sql = $sql." AND fitter_certifications LIKE '%,$value,%'";  
	  }
  }
}

if (isset($_POST[fitbikes])) {
  if (in_array("999", $_POST[fitbikes])) {
  		$sql = $sql." AND fitter_fitbikes <> ',0,'";
  } else {
	  $sql = $sql."AND (";
  	  $flag = 0;
	  foreach ($_POST[fitbikes] AS $value) {
	    if ($flag == 1){
	    	$sql = $sql." OR ";
	    }
		$sql = $sql."fitter_fitbikes LIKE '%,$value,%'";
		$flag = 1;
	  }
	  $sql = $sql.")";
	  //foreach ($_POST[fitbikes] AS $value) {
		//$sql = $sql." OR fitter_fitbikes LIKE '%,$value,%'";  
	  //}
  }
}

if (isset($_POST[motioncapture])) {
  if (in_array("999", $_POST[motioncapture])) {
  		$sql = $sql." AND fitter_motioncapture <> ',0,'";
  } else {
	  $sql = $sql."AND (";
  	  $flag = 0;
	  foreach ($_POST[motioncapture] AS $value) {
	    if ($flag == 1){
	    	$sql = $sql." OR ";
	    }
		$sql = $sql."fitter_motioncapture LIKE '%,$value,%'";
		$flag = 1;
	  }
	  $sql = $sql.")";
	  //foreach ($_POST[motioncapture] AS $value) {
		//$sql = $sql." AND fitter_motioncapture LIKE '%,$value,%'";  
	  //}
  }
}

if (isset($_POST[brandfriendly])) {
	if (in_array("999", $_POST[brandfriendly])) {
			$sql = $sql." AND fitter_brandfriendly <> ',0,'";
	} else {
		$sql = $sql."AND (";
		  $flag = 0;
		foreach ($_POST[brandfriendly] AS $value) {
		  if ($flag == 1){
			  $sql = $sql." OR ";
		  }
		  $sql = $sql."fitter_brandfriendly LIKE '%,$value,%'";
		  $flag = 1;
		}
		$sql = $sql.")";
		//foreach ($_POST[motioncapture] AS $value) {
		  //$sql = $sql." AND fitter_motioncapture LIKE '%,$value,%'";  
		//}
	}
  }

// 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 fitter_state_tag IN $statelist";
}


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

//echo $sql;

$results = mysql_query($sql) OR die(mysql_error());

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

//keyword search
// 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'] != "") {
	$bool_Keywords = true;
	while($row_fitteres = mysql_fetch_array($results)) {
		// build an array that we can loop through.
		$arr_fitteres[$i] = $row_fitteres;
		$i++;
	}
	
	$arr_Matches = array();
	foreach ($arr_fitteres AS $fitter) {	
			if (stripos($fitter['fitter_name'], $_POST['keyword']) !== false) {
				// push this onto the array of matches
				$fitter['percent'] = 100;
				array_push($arr_Matches, $fitter);
			} else {
				$name_nospace = str_replace(" ", "", $fitter['fitter_name']);
				$keyword_nospace = str_replace(" ", "", $_POST['keyword']);
				if (stripos($name_nospace, $keyword_nospace) !== false) {
					// push this onto the array of matches
					$fitter['percent'] = 90;
					array_push($arr_Matches, $fitter);
				} else {
					// trim redundant keywords
					$fitter_name = $fitter['fitter_name'];
					foreach ($trim_words AS $word) {
						$fitter_name = str_ireplace($word, " ", $fitter_name);
					}
					//$fitter_name = str_ireplace(" ", "", $fitter_name);
					$fitter_name = strtolower($fitter_name);
					$arr_fitter_name = explode(" ", $fitter_name);
					$_POST['keyword'] = strtolower($_POST['keyword']);
					$_POST['keyword'] = str_replace(" ", "", $_POST['keyword']);
					foreach ($arr_fitter_name AS $test_word) {					
						similar_text($test_word, $_POST['keyword'], $percent);
						if ($percent >= $comp_pct) {
							// push this onto the array of matches
							$fitter['percent'] = round($percent, 0);
							//$fitter['trimmed'] = $fitter_name;
							array_push($arr_Matches, $fitter);
							break;
						}
					}
				}
			}
	}
	
	if (count($arr_Matches) == 0) {
 		$none = TRUE;
 	}
 	$match_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 = "search, fitters, triathlon, results";
$meta_description = "Bike fitters matching a user's search query. A list of matching fitters.";
?>

<? 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 $match_count; ?> Fitters Match Your Search Criteria</strong></p>
                <?

                if ($bool_Keywords == true) {
                    foreach($arr_Matches AS $row){	
                        include("include_store.php");
                    } // end foreach arr_Matches 
                } else { //if bool_Keywords
                    while ($row = mysql_fetch_array($results)) {
                        include("include_store.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>