<?php
function gslink($id,$ch){
	if (strlen($ch) != 0){
		return "?c=".$ch."&amp;p=".$id;
	}else{
		return "?p=".$id;
	}
}
function gsresults(){
	$q = $_POST[gsearchfield];
	$pattern ="/\b".$q."/i";
	$stitle = true; //search in titles
	$skeywords = true; //search in keywords
	$sdescription = true; //search in description
	$scontent = true; //search in page content
	$spages = glob("data/*.php");
	$results = 0;
	foreach ($spages as $spage){
		require $spage;
		if($stitle){
			if (preg_match($pattern,$page[title])){
				$results ++;
				echo "<strong><a href=\"".gslink($page[id],$page[ch])."\">".$page[title]."</a></strong><br />";
			}else{
				if($skeywords){
					if (preg_match($pattern,$page[keywords])){
						$results ++;
						echo "<strong><a href=\"".gslink($page[id],$page[ch])."\">".$page[title]."</a></strong><br />";
					}else{
						if($sdescription){
							if (preg_match($pattern,$page[description])){
								$results ++;
								echo "<strong><a href=\"".gslink($page[id],$page[ch])."\">".$page[title]."</a></strong><br />";
							}else{
								if($scontent){
									if (preg_match($pattern,$page[content])){
										$results ++;
										echo "<strong><a href=\"".gslink($page[id],$page[ch])."\">".$page[title]."</a></strong><br />";
									}
								}
							}
						}
					}
				}
			}
		}
	}
	if ($results == 0){
		echo "No results for <strong>".$q."</strong>";
	}else{
		echo $results. " results for <strong>".$q."</strong>";
	}
}
function gsearch(){
	echo 	"<form id='gsearch' name='gsearch' method='post' action=''>
			<input type='text' name='gsearchfield' id='gsearchfield' value='".$_POST[gsearchfield]."' />
			<input type='hidden' name='gs' value='true' />
			<input type='submit' name='gsearchsubmit' id='gsearchsubmit' value='Search' />
			</form>";
	if (isset($_POST[gsearchfield]) and strlen($_POST[gsearchfield]) != 0){
		echo gsresults();
	}		
}
?>