<?php
require_once('DB.php');
require_once "searchS.php";

$siUrl = "http://www.shakertown.net/Shaker-image/display/bio/show/";
$enUrl = "http://www.shakertown.net/enfield/";
$enUrlDirect = "http://www.shakertown.net/enfield/recshow.php?id=";
$maxdoc = 400;
//$showData = 1;

$searchSize = 10;

$answer = Array('pma', 'winterthur');

$whoru = trim($_REQUEST['whoru']);
if(!isset($whoru) || !in_array(strtolower($whoru), $answer) ) {
	print <<<END
This is prototype search of various shaker bios collections and sections
of the Shaker Name Index project of the Shaker-Studies Listserv. 
<br> If you
are not part of that project, you can email 
Christian Goodwillie [cgoodwil@HAMILTON.EDU]
for more details.
<br>
If you are part of the project, you will know the name of one of the museums
that the next seminar is going to visit - enter it here (one word):
<form method=get>
<input name=whoru>
<input name=push value='Say it' type=submit>
</form>
END;

# valid answers:  	Philadelphia Museum of Art  (pma)
#			Winterthur Museum and Gardens (Winterthur)
	exit;

} else {
	print "You are kindly welcome to enter<br>\n";

}

$searchWords = $_REQUEST['searchWords'];
$advSearch   = stripslashes($_REQUEST['advSearch']);

$pick_initial 	= $_REQUEST['pick_initial'];
$pick_last   	= $_REQUEST['pick_last'];
$pick_vil   	= $_REQUEST['pick_vil'];
$pick_start 	= $_REQUEST['pick_start'];

function makeUrl($main, $addN, $addV) {
	$url = '';
	foreach($main as $n => $v) {
		if($url) $url .= '&';
		$url .= $n . '=' . urlencode($v);
	}
	if($addV) {
		if($url) $url .= '&';
		$url .= $addN . '=' . urlencode($addV);
	}
	return $url;
}

//if($pick_last) $searchWords = $pick_last;

$bydb = Array();

$dsn = "mysql://root:@localhost/enshaker";
$db =& DB::connect($dsn);
if (PEAR::isError($db)) 
	die($db->getMessage());

//if($pick_initial) {
//	$initialWhere = "WHERE (substring(lastname, 1, 1) = '$pick_initial')"
//}

$lasts1 =& $db->getAll(
"SELECT lastname  FROM bioinfo $initalWhere GROUP BY lastname ORDER BY lastname");

$bydb['MaH:Enfield'] = count($lasts1);

$village1 =& $db->getAll(
//"SELECT village, count(*) FROM bioinfo GROUP BY village");
"SELECT village FROM bioinfo GROUP BY village");

$lasts3 =& $db->getAll(
"SELECT lastname  FROM sni_work $initalWhere GROUP BY lastname ORDER BY lastname");

$bydb['SNI: New Lebanon'] = count($lasts3);

$village3 =& $db->getAll(
//"SELECT village, count(*) FROM bioinfo GROUP BY village");
"SELECT village FROM sni_work GROUP BY village");

$dsn2 = "mysql://root:@localhost/shaker-image_dev";
$db2 =& DB::connect($dsn2);
$lasts2 =& $db2->getAll(
"SELECT lastname FROM bios $initialWhere GROUP BY lastname ORDER BY lastname");

$bydb['Shaker Image'] = count($lasts2);

/*
// Village fields are very messy
$village2 =& $db2->getAll(
//"SELECT village, count(village) FROM bios GROUP BY village");
"SELECT village FROM bios GROUP BY village");

$villages =  array_merge($village1, $village2);
//print "Village="; print_r($village2);
print "\$villages = Array(\n";
foreach ($villages as $v) {
	print "\t'{$v[0]}'\n";
}
print ")\n";
*/

/* Basic village filter - since field so nosey just use basic name, no state */
$villages = Array(
	'Enfield',
	'Alfred',
	'Canterbury',
	'Hancock',
	'Harvard',
	'Canaan',
	'Lebanon',
	'Union',
	'Pleasant Hill',
	'Sabbath',
	'Shirley',
	'Watervliet',
);
sort($villages);

//$names = array_merge(array_values($lasts1), array_values($lasts2));

$names = array();

for($i=1; $i<=3; ++$i) {
    $aname = 'lasts' . $i;
    foreach($$aname as $l) {
//	print_r($l);
	if($l[0]) $names[] = $l[0];
   }
}
//foreach($lasts2 as $l) {
////	print_r($l);
//	if($l[0]) $names[] = $l[0];
//}

asort($names);
$names = array_unique($names);
$number = count($names);
$initials = Array();
foreach($names as $n) {
	++$initials[substr($n, 0, 1)];
}

//print "<pre>" . print_r($names,true) . "</pre>\n";

$pick_name = '';

$pick_name .= "<SELECT name=pick_vil onChange='submit();'>\n" .
	"<option value=''>Pick Village\n";
foreach($villages as $v ) {
	$sel = ($v == $pick_vil) ? ' selected' : '';
	$pick_name .= "<option value='$v' $sel>$v\n";
}
$pick_name .= "</SELECT>\n";

$pick_name .= "<SELECT name=pick_initial onChange='submit();'>\n" .
	"<option value=''>Pick 1st letter of last name ($pick_initial)\n";
foreach($initials as $n => $c ) {
	$sel = ($n == $pick_initial) ? ' selected' : '';
	$pick_name .= "<option value='$n' $sel>$n [$c]\n";
}
$pick_name .= "</SELECT>\n";

if($pick_initial) {
	$pick_name .= 
		"<SELECT name=pick_last onChange='searchWords.value = pick_last.value; submit();'>\n" .
		"<option value=''>Pick a last name starting with $pick_initial\n";
	foreach($names as $n) {
		if(substr($n, 0, 1) != $pick_initial) continue;
		$sel = ($n == $pick_last) ? ' selected' : '';
		$pick_name .= "<option $sel>$n\n";
	}
	$pick_name .= "</SELECT>\n";
}

/* ************
<ol><b>Data base access</b>
<li><a href="/enfield/" target=_blank> Enfield Bios</a>
<li><a href="http://www.shakertown.net/Shaker-image/display/bio/listing/" target=_blank>Shaker Image</a>
</ol>
   ************ */

?>
<style type="text/css">
.mark_word {
    background-color: yellow;
}
.matchInfo {
    line-height: 1.24;
    font-family: arial,sans-serif;
    font-size: small;
    text-indent: 20;
}
.docShow {
//   border: solid blue 1px;
   text-indent: 5%
   white-space: pre;
}
.showFull {
   background-color: #1CE9ED;
}
</style> 
<script>

/*
//function viewFlip(objName) {
//        obj = $(objName);
*/

function viewFlip(obj) {
        if(obj.style.display=='inline')
                obj.style.display='none';
        else 
                obj.style.display='inline';
}
</script>

The current Shaker Name Search has <?=$number ?> last names represented.
<table>
<tr><th>Dataset<th>Count
<?
foreach($bydb as $dbname => $dbcnt) {
	print "<tr><td>$dbname<td>$dbcnt\n";
}
?>
</table>
<P>
<b>Search Words</b>. An occurance of these terms anywhere in the full entry will
return the entry, all must occur somewhere. <br>
<b>Optional:</b> You can use the pulldowns to select a last name or village<br>
<blockquote>
<b>Lastname:</b> 
the entry is primarily about the given last initial or lastname
<br>
first pick a first letter and then the name starting with that letter,
the value will be put in the search field.  You can then add additional 
keywords, such as first name or village. 
<br>
The count next to last inital
is the number of last names starting with that inital, not the total number
of entries.
<p>
<b>Village:</b> Village select limits the result to only records marked that 
specific village.  This often produces no results, since not all records
are marked with a village or there is no information from that village.
Selecting just a village and no search term will show all entries for that
village.
<p>
<b>Advanced Search:</b>Allows the full search expression of the underlying Solr search engine,
for details see <a href=http://lucene.apache.org/java/2_9_1/queryparsersyntax.html target=_blank>
Full Search expression</a>.  Any entry here will cause ignoring the Search words above,
it all will cause a search error if entered wrong, so use with care.
</blockquote>
<b>Press</b> enter to update search results.
<p>

Disclaimer:
This is prototype search of various shaker bios collections and sections of
the Shaker Name Index project of the Shaker-Studies Listserv.
</address>
<p>
<b>Seach Shaker Names</b><a href='?whoru=<?=$whoru?>'>Start new search</a><p>
<form href="" method=get>
<input type=hidden name=whoru value='<?=$whoru?>'>
Search Words: <input type=input name=searchWords value='<?=$searchWords ?>'>
<?=$pick_name?><br>
Advanced Search: <input type=input name=advSearch value='<?=$advSearch ?>' size=100>
<button>Do advanced search</button>
</form>
<?php
// syntax: http://lucene.apache.org/java/2_9_1/queryparsersyntax.html

  if(!$searchWords && !$pick_vil && !$pick_initial && !$advSearch) return;

// *** SETUP for call to search 
  $startPoint = (isset($pick_start) ? $pick_start : 1);

  $restrict = '';
  if($advSearch) $restrict = $advSearch;
  
  if($pick_vil) {
	if($restrict) $restrict .= " AND ";
	$restrict .= "+village_s:*$pick_vil*";
  }

  if($pick_last) {
	if($restrict) $restrict .= " AND ";
	$restrict .= "+lastname_s:$pick_last";

  } elseif($pick_initial) {
	if($restrict) $restrict .= " AND ";
	$restrict .= "+lastname_s:$pick_initial*";
  }

  $sWords = ($advSearch ? '' : $searchWords); 
  $sresult = doSearch($sWords, $startPoint, $searchSize, 
	$restrict);

  list($searchCount, $qInfo, $matchCases, $allData) = $sresult;

  $spoint = $startPoint;
  $epoint = $spoint+$searchSize-1;
  if($epoint > $searchCount) $epoint = $searchCount;
  print <<<END
<b> $searchCount Results when searching on: $searchWords [$qInfo]</b><BR>
<b>Showing</b> from $spoint to $epoint ($searchSize results)<br>
END;

$links = Array(
	'searchWords' => $searchWords, 'pick_vil' => $pick_vil,
	'pick_initial' => $pick_initial,
	'whoru' => $whoru,
);

if($startPoint > 1) {
	$url = makeUrl($links, 'pick_start', 1);
	print "[<a href='?$url'>Prev</a>] ";
}
for($i=1; $i<$searchCount; $i += $searchSize) {
	$url = makeUrl($links, 'pick_start', $i);
	if($i != $startPoint) 
		print "[<a href='?$url'>$i</a>] ";
	else 
		print "$i ";
}
if($startPoint < ($searchCount-$searchSize)) {
	$url = makeUrl($links, 'pick_start', $startPoint+$searchSize);
	print "[<a href='?$url'>Next</a>] ";
}
print "<br>\n";

//  print "<pre>\n";

//  print_r($matchCases);

  print "<table border=0>\n";
  print "<tr><td height=2>\n";
  $caseNo = 0;
  $rpos = $spoint;
  foreach($matchCases as $case) {
	$thisData = $allData[$caseNo];
	++$caseNo;

	$path  = $case['path'];
	$id    = $case['msgid'];
	$lname = $case['lastname'];
	$fname = $case['firstname'];
        $village = $case['village'];

	$start = $end = $link = '';
	$recid = substr($id, 3);

	$source = 'unk';
	$creditTo = 'Unknown';
	if(substr($case['msgid'],0,2)=='en') {
		$source = 'en';
		$creditTo = "Enfield" ;
		$link = $enUrlDirect . $recid;
	}
	if(substr($case['msgid'],0,2)=='si')  {
		$source = 'si';
		$creditTo = "Shaker Image";
		$link = $siUrl . $recid;
		$links = "<a href='$link' target=_blank>ID=$recid</a>";
	}
	if(substr($case['msgid'],0,3)=='sni')  {
		$source = 'sni';
		$creditTo = "Shaker Name Index";
	}

	$fullDoc = $outdoc = $case['rawDoc'];

	if($path) {
		$parts = split("/", $path);

		$cnt = 2;
		$links = "<a href='$link' target=_blank>ID=$recid</a>";
		$tail = '';
		foreach($parts as $p) {
			$tail .= $p;
			$ul = $enUrl . "?level=$cnt&subset=$tail";
			$links .= " <a href=\"$ul\" target=_blank>[$p]</a> ";

			++$cnt;
			$tail .= "/";
		}
		$fullDoc = preg_replace("/\\n\\n/", "\n", $fullDoc);
//		if($fullDoc == NULL) $fullDoc = "PREG ERROR";
	}

	$name = '';
	If($lname || $fname) $name = $lname . ", " . $fname;

	if(strlen($outdoc)>$maxdoc) {
		$outdoc = substr($outdoc, 0, $maxdoc) . "<b> ...</b>";
	}
	$words = split(" ", $searchWords);
	if(strpos($path, "cas/")!==false || strpos($path, "census/")!==false) {
	    $fullDoc = 	preg_replace('!</[a-z ]+>!i', '', $fullDoc);
	    $fullDoc = 	preg_replace('!<([0-9a-z ]+)>!i', '<b>$1</b>:', $fullDoc);
//	    $fullDoc = $path . "<br>" . 
//			htmlspecialchars($fullDoc);
	}
//        $fullDoc = (strpos($path, "cas/")!==false) . $path . "<br>" . $fullDoc;

	foreach($words as $w) {
	    $fullDoc = 
		str_ireplace($w, 
		"<span class='mark_word'>".$w.'</span>',
		$fullDoc);
	}

	$outdoc = 
		str_ireplace($searchWords, 
		"<span class='mark_word'>".$searchWords.'</span>',
		$outdoc);

	$creditUrl = "http://www.shakerstudies.info/credits";
	
	$dispId = "<a title='Credit:$creditTo' target=_blank href='$creditUrl'><u>Id:</u>{$case['msgid']}</a>";

//	$hl = htmlspecialchars($case['hl']);

	$hl = preg_replace('/<[^>]+$/', '', $case['hl']);

//<cite>$links</cite><br>

	print <<<END
<tr><td>
<span class="nameBar">
<b>{$name}</b>  of $village
(<u>Score:</u>{$case['rawPercent']})
$dispId
</span>
<br> 
<div class="matchInfo">
{$hl}
</div>
<span onclick="viewFlip(full$caseNo);" class="showFull">Click to show Full Entry</span>
<div id="full$caseNo" style="display:none">
<table border=1><tr><td>
{$fullDoc}
END;
	if($source == 'sni') {
	    print "<tr><td>\n";
	    foreach($thisData as $fname => $fval) {
		print "\t<dt><b>$fname:</b><dd>$fval\n";
	    }
	    print "<hr color=red>\n";
	}


	print <<<END
</table>
</div>
<tr><td height=5>
END;

     if($showData) {
	print "<tr><td><pre>" . print_r($case, true) . "</pre>\n";
	print "<tr><td><pre>" . print_r($thisData, true) . "</pre>\n";
	print "<tr><td>";
	foreach($thisData as $fname => $fval) {
		print "\t<dt>$fname =><dd> $fval\n";
	}
	print "<tr height=5 bgcolor=red><td colspan=3>\n";

     }
  }
  print "</table>\n";

print <<<END
<hr>

END;
