<?php
session_start();
?>
<?
include("user.php");
include("class.php");
include("topic.php");
@include("article.php");

if ($_SESSION['user']) {
	if ($_SESSION['admin'] == 0)
   	header("Location: index.php");
}
else
  header("Location: index.php");

if (!$_GET['class'])
// header("Location: classes.php");

$classid = $_GET['class'];
$class = getClass($classid);
$roster = getRoster_Inst($classid);
$showSearch = false;


if ($_POST['queryaction'] == 'Find Author' && $_POST['authorName']){
	$id = $_POST['topics'.$classid];
	$authors = getAuthors($id);

}

if ($_POST['queryaction'] == 'Find Title' && $_POST['titleName']){
	$id = $_POST['topics'.$classid];
	$titles = getTitles($id);
}


if ($_POST['curSelect'] && $_POST['queryaction'] == 'Query Database') {
	$showSearch = true;
	$type = "all";
	$info = null;
	$comparator = "and";
	$topicID = $info = $_POST['topics'.$classid];
	if ($_POST['curSelect'] == 2) {
		$type = "author";
		$info = $_POST['authorNames'];
	}
	else if ($_POST['curSelect'] == 3) {
		$type = "title";
		$info = $_POST['titleNames'];
	}
	else if ($_POST['curSelect'] == 4) {
		$type = "topic";
		$topicID = $info = $_POST['topics'.$classid];

		if ($_POST['searchPosition']) {
			$type = "position";
			$positionID = $info = $_POST['selPosition'];
      $argsThisPosition="";
			$allPositions = getPositions($_POST['topics'.$classid]);
			$countPositions = count($allPositions);
			//        echo("There are ".$countPositions." positions for topic # ".$_POST['topics'.$classid]."<br>");
			$countArguments = 0;
			$max = $countPositions;
			$argPerPosition = array();
			for ($i = 0; $i < $max; $i++){
				$args = count(getArguments($_POST['topics'.$classid],$allPositions[$i]['ID']));
//        if ($info = $allPositions[$i]['ID']) 
//        {
//            $textPosition = getPositionName($positionID);
//            $thisPosition = $textPosition['Position'];
//        }
//				         echo("For position ".$allPositions[$i]['ID']." ".$positionID." ".$thisPosition." there are ".$args." arguments<br>");
				array_push($argPerPosition,$allPositions[$i]['ID'],$args);
				$countArguments = $countArguments + $args;
			}

			if ($_POST['searchReasons']) {
				$type = 'reason';
				$info = array();
				$comparator = $_POST['comp'];
				$sumReasonLine = "";
				$reasons = getReasons($positionID, false);

				$max = count($reasons);
				$reasonSelected = 0;
				for ($i = 0; $i < $max; $i++) {
					if ($_POST['reasons'.$positionID.'_'.$i]){
						array_push($info, $_POST['reasons'.$positionID.'_'.$i]);
						$reasonSelected = $reasonSelected + 1;
						if ($reasonSelected == 1)
							$sumReasonLine = $sumReasonLine . " <i>".$reasons[$i]['Reason']."</i>";
						else
							$sumReasonLine = $sumReasonLine." ".$comparator." <i>".$reasons[$i]['Reason']."</i>";

					}
				}
			}	
		}
	}

	//// Hardcoded sort order
	$sortOrder = array();
	array_push($sortOrder, "position");
	array_push($sortOrder, "author");
	array_push($sortOrder, "title");
	array_push($sortOrder, "date");
	array_push($sortOrder, "source");

	//Perform search
	$articles = queryLibSearch($type,$info,$comparator,$sortOrder,11);//Public class
	$cart = count($articles);
//	 echo("Total articles ".$cart." ".$info."<br>");
}
?>
<?php
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Query Public Library</title>
<script language='javascript'>
<!-- 

function changeTopic(topicid) {
	oldtopic = document.getElementById('selTopic').value;
	oldposition = document.getElementById('selPosition').value;
	document.getElementById('positions'+oldtopic+'div').style.display = 'none';
	if (oldposition > 0)
		document.getElementById('reasons'+oldposition+'div').style.display = 'none';
	document.getElementById('positions'+topicid+'div').style.display = 'block'; 
	document.getElementById('selTopic').value = topicid;

	var positionid = null;
	var i = 1;
	while ((position = document.getElementById('positions'+topicid+'_'+i)) != null) {
		if (position.checked) {
			positionid = position.value;
			break;
		}
		else
			i++;
	}
	if (!positionid) {
		positionid = -1;
	}
	else
		document.getElementById('reasons'+positionid+'div').style.display = 'block';
	document.getElementById('selPosition').value = positionid;
}

function changePosition(positionid) {
	oldposition = document.getElementById('selPosition').value;
	if (oldposition > 0)
		document.getElementById('reasons'+oldposition+'div').style.display = 'none';
	document.getElementById('reasons'+positionid+'div').style.display = 'block';
	document.getElementById('selPosition').value = positionid;			
}

function changeUp(doShow, curSel) {
	if (doShow)
		document.getElementById('positionDIV').style.display='block';
	else
		document.getElementById('positionDIV').style.display='none';

	document.getElementById('curSelect').value = curSel;
}

function allowReasons(allow) {
	document.getElementById('searchReasons').disabled = !allow;
}

function switchComp(andComp) {
	if (andComp)
		document.getElementById('comp').value = 'and';
	else
		document.getElementById('comp').value = 'or';
}

function goBack() {
	window.location = 'classes.php';
}
// -->
</script>
</head>

<? include("header.php"); 
if ($showSearch) {
	$topicText = "";
	$positionText = "";
	echo("<span style='position:absolute; left:20px'><br><table border=1 style=\"background-color:lightblue;\">");
	if ($_POST['searchPosition'])
  	$count = $countArguments;
	else
	  $count = count($articles);
  if ($count == 0) {
    $tText = getTopic($_POST['topics'.$classid]);
    $topicText = $tText['Topic'];
    echo("</table>");
    echo("</span><br><b><u>Topic: $topicText</u></b><br><br>");
    echo("No articles currently in library for this topic.");
  }
  else {
	foreach($articles as $article) {
		if ($article['Topic'] != $topicText) {
			$topicText = $article['Topic'];
			echo("</table>");
//			echo("</span><br><b><u>Topic: $topicText</u></b><span style='position:relative; left:20px'><br><br>");
			echo("</span><br><b><u>Topic: $topicText</u></b><br>");

			if ($_POST['searchPosition'])
				$count = $countArguments;
			else
				$count = count($articles);
			$firstArticle = true;
			$firstPosition = true;
			echo("<table cellpadding=6px>");
		}
		if ($article['Position'] != $positionText) {
			if ($firstArticle){
				$firstArticle = false;
				$p = 0;
				$positionText = $article['Position'];
				echo("</table><br><b>$positionText</b><br>");

			}
			else {
				if ($p != 0){
					if ($firstPosition){
						$firstPosition = false;
						$percent = round($p/$count*100,1);
						if ($p != 1)
							$sumLine = $p." arguments <i>".$positionText."</i>, ".$percent." percent of ".$count." total arguments";
						else
							$sumLine = $p." argument <i>".$positionText."</i>, ".$percent." percent of ".$count." total arguments";
						echo("</table><br>".$sumLine."<br>");
						echo("<table border=1 cellpadding=6px>");
					}
				}
				$positionText = $article['Position'];
				echo("</table><br><b>$positionText</b><br>");
				$p = 0;
			}
			echo("<table border=1 cellpadding=6px>");
      echo("<col width = '14%'>");
      echo("<col width = '22%'>");
      echo("<col width = '8%'>");
      echo("<col width = '22%'>");
      echo("<col width = '12%'>");
      echo("<col width = '22%'>");
//added
        echo("<tr>");
        echo("<th>Author</th>");
        echo("<th>Article</th>");
        echo("<th>Date</th>");
        echo("<th>Source</th>");
        echo("<th>Web Address</th>");
        echo("<th>Reasons</th>");
        echo("</tr>");
		}
		echo("<td>".$article['Author']."</td>");
		echo("<td>".$article['Title']."</td>");
		echo("<td>".$article['Date']."</td>");
		echo("<td>".$article['Source']."</td>");
    if ($article['URL'] && $article['URL'] != ''){
      if (substr($article['URL'],0,7) != 'http://')
         $article['URL'] = 'http://'.$article['URL'];
         echo("<td><a href='".$article['URL']."' target=_blank>");
         if (strlen($article['URL'])>20)
            $article['URL'] = substr($article['URL'], 0, 20)."...";
         echo($article['URL']."</a></td>");
    }
    else
       echo("<td>No address provided.</td>");
       
// changed		echo("<td width=\"150px\"><a href=\"".$article['URL']."\">".$article['URL']."</a></td>");
//		echo("<td colspan=3><b><i>");
    echo("<td>");
		$reasonList = getArticleReasons($article['ID']);
//		if (count($reasonList) > 1)
//			echo("Reasons:<br>");
//		else
//			echo("Reason:");
//		echo("</i></b>");
		foreach($reasonList as $a_r)
			echo("*".$a_r['Reason']."<br>");
		echo("</td></tr>");
		echo("</tr>");
		$p++;
	}
	if ($_POST['searchReasons']){
		$argcount = count(getArguments($_POST['topics'.$classid],$positionID));
		if ($count != 0){
			$percent = round($p/$argcount*100,1);
      if ($p == 0)
   			$sumLine = "No arguments with reasons ".$sumReasonLine.", found from ".$argcount." arguments for the position<br>";
      else {  
			if ($p != 1)
				$sumLine = $p." arguments with reasons ".$sumReasonLine.", <br> &nbsp &nbsp".$percent."  percent of ".$argcount." arguments for the position<br>";
			else
				$sumLine = $p." argument with reasons ".$sumReasonLine.", <br> &nbsp &nbsp".$percent." percent of ".$argcount." argument for the position<br>";
      }
		}
		else 
			$sumLine = "No arguments with reasons ".$sumReasonLine.", found from ".$argcount." arguments for the position<br>";
	}
	else {       
		if ($firstPosition){
			if ($count !=0 ){
				$percent = round($p/$count*100,1);
        if ($p == 0) {
          $positionText = "FirstPosition";
					$sumLine = "No arguments <i>".$positionText."</i>, ".$percent." percent of ".$count." total arguments";
        }  
        else {
  				if ($p !=1)
  					$sumLine = $p." arguments <i>".$positionText."</i>, ".$percent." percent of ".$count." total arguments";
  				else
  					$sumLine = $p." argument <i>".$positionText."</i>, ".$percent." percent of ".$count." total arguments";
        }
			}
		}
		else {
			if ($count != 0){
				$percent = round($p/$count*100,1);
        if ($p == 0) {
//          $textPosition = getPositionName($positionID);
//          $currentPosition = $textPosition['Position'];
//          if ($currentPosition == $thisPosition) {
//          $tText = getTopic($_POST['topics'.$classid]);
//          $topicText = $tText['Topic'];
//          echo("</table>");
//          echo("</span><br><b><u>Topic: $topicText</u></b><br>"); 
//          echo("<table>");
            $textPosition = getPositionName($positionID);
            $thisPosition = $textPosition['Position'];

            $positionText = $thisPosition;
//   				echo("</table><br><b>$positionText</b><br>");
//          echo("<table>");
					$sumLine = "No arguments <i>".$positionText."</i>, ".$percent." percent of ".$count." total arguments";
//}
        } 
        else { 
			  	if ($p != 1)
			  		$sumLine = $p." arguments <i>".$positionText."</i>, ".$percent." percent of ".$count." total arguments";
				  else
					  $sumLine = $p." argument <i>".$positionText."</i>, ".$percent." percent of ".$count." total arguments";
        }
			}
		}
	}
  if ($p == 0) {
     $tText = getTopic($_POST['topics'.$classid]);
     $topicText = $tText['Topic'];
     echo("</table>");
     echo("</span><br><b><u>Topic: $topicText</u></b><br>"); 
     echo("<table>");
     $textPosition = getPositionName($positionID);
     $thisPosition = $textPosition['Position'];
     $positionText = $thisPosition;
     echo("</table><br><b>$positionText</b><br>");
     echo("<table>");
  }  
	echo("</table><br>".$sumLine."<br>");
	echo("<table>");
	echo("</table>");
  }
	echo("<br><br><input type='button' value='New Query Report' onclick='window.location=\"querylib.php\"'><br><br>");
} else {
	?>
		<div style='position:relative; left:20px'>
		<form name='substantivesearch' id='substantivesearch' method='POST'>
		<input type='hidden' name='curSelect' id='curSelect' value=4>
		<b>Query Library</b><br>
		<div style='position:relative; left:20px'>
		<table cellpadding=3px>
		<tr>
		<td><input type='radio' name='select' id='selectAll' style=display:none onchange='changeUp(false, 1)'></td>
		</tr>
		<tr>
		<td><input type='radio' name='select' id='selectAuthor' style=display:none onchange='changeUp(false, 2)'></td>
		<td><input type='text' name='authorName' id='authorName' style=display:none></td>
		<td><input type='submit' name='queryaction' value='Find Author' style=display:none></td>
		<td>
		<? 
		if (count($authors)){

			echo ("<select id='authorNames' name='authorNames' >");
			$firstname = true;
			foreach ($authors as $a) {
				$pos = stripos($a['Author'],$_POST['authorName']);
				if ($pos !== false) {
					echo("<option value='".$a['Author']."'");
					if ($firstname) {
						echo (" SELECTED");
						$firstname = false;
					}
					echo(">".$a['Author']."</option>");
				}
			}
			if ($firstname) {
				echo("<option value='0' SELECTED>No matching name</option>");
			}

			echo ("</select>");
		}
	?>
		</td>
		</tr>
		<tr>
		<tr>
		<td><input type='radio' name='select' id='selectTitle' style=display:none onchange='changeUp(false, 3)'></td>
		<td><input type='text' name='titleName' id='titleName' style=display:none></td>
		<td><input type='submit' name='queryaction' style=display:none value='Find Title'></td>
		<td>
		<?
		if (count($titles)){
			echo ("<select id='titleNames' name='titleNames' >");
			$firsttitle = true;
			foreach ($titles as $t) {
				$pos = stripos($t['Title'],$_POST['titleName']);
				if ($pos !== false){
					echo("<option value='".$t['Title']."'"); 
					if ($firsttitle){
						echo (" SELECTED");
						$firsttitle = false;
					}
					echo(">".$t['Title']."</option>");

				}
			}
			if ($firsttitle) {
				echo("<option value='0' SELECTED>No matching title</option>");
			}

			echo ("</select>");
		} 
	?> 
		</td>
		</tr>
		<tr>
		<td><input type='radio' name='select' id='selectTopic' style=display:none checked onchange='changeUp(true, 4)'></td>
		<td>Select a Topic &nbsp</td>
		<td>
		<?
		$topics = getAllTopics();
	$seltopic = $topics[0]['ID'];

	echo("<select id='topics".$classid."' name='topics".$classid."' ");
	echo("onchange='changeTopic(this.options[this.selectedIndex].value)'>");
	$first2 = true;
	foreach($topics as $t) {
		if (count(getPositions($t['ID'])) > 0) {
			echo("<option value='".$t['ID']."'");
			if ($first2) {
				echo(" SELECTED");
				$first2 = false;
			}
			echo(">".$t['Topic']."</option>");
		}
	}
	echo("</select>");
	echo("<input type='hidden' id='selTopic' name='selTopic' value='$seltopic'>");
	?>
		</td>
		</tr>
		</table>
		<div style="display:block; position:relative; left:20px" id='positionDIV'>
		<input type='checkbox' name='searchPosition' id='searchPosition' onclick='allowReasons(this.checked)'> By Position:
		<div style="position:relative; left:20px"> <table cellpadding=3px>
		<tr>
		<td colspan=2>
		<?
		$first = true;
	foreach($topics as $t) {
		$positions = getPositions($t['ID']);
		echo("<div id='positions".$t['ID']."div' style='position:relative; left:20px; display:");
		if ($first) {
			echo("block'>");
			$first = false;
			$selposition = $positions[0]['ID'];
		}
		else
			echo("none'>");
		echo("<table><tr>");
		$first2 = true;
		$j = 1;
		for($i = 0; $i < count($positions); $i++) {
			if ($i % 3 === 0)
				echo("</tr><tr>");
			echo("<td colspan=2><input type='radio' name='positions".$t['ID']."' value='".$positions[$i]['ID'].
					"' onclick='changePosition(this.value)' id='positions".$t['ID']."_".$j."' ");
			if ($first2) {
				echo("CHECKED");
				$first2 = false;
			}
			echo(" />".$positions[$i]['Position']." &nbsp; &nbsp;</td>");
			$j++;
		}
		echo("</tr></table></div>");
	}
	echo("<input type='hidden' id='selPosition' name='selPosition' value=$selposition />");
	?>
		</td>
		</tr>
		</table>
		</div>
		<input type='checkbox' name='searchReasons' id='searchReasons' disabled> By Reasons:
		<div style='position:relative; left:20px'>
		<input type='radio' name='and_or' id='and' onclick='switchComp(true)' checked> And &nbsp; &nbsp;
	<input type='radio' name='and_or' id='or' onclick='switchComp(false)'> Or
		<input type='hidden' name='comp' id='comp' value='and'>
		</div>
		<div style='position:relative; left:20px'>
		<?
		$first = true;
	foreach($topics as $t) {
		$positions = getPositions($t['ID']);
		foreach($positions as $p) {
			$reasons = getReasons($p['ID'], false);
			echo("<div id='reasons".$p['ID']."div' style='position:relative; left: 20px; display:");
			if ($first) {
				echo("block'>");
				$first = false;
			}
			else
				echo("none'>");
			for ($i = 0; $i < count($reasons); $i++) {
				echo("<input type='checkbox' id='reasons".$p['ID']."_".$i."' name='reasons".$p['ID']."_".$i.
						"' value='".$reasons[$i]['ID']."'> ".$reasons[$i]['Reason']."<br>");
			}
			echo("</div>");
		}
	}
	?>
		</div>
		</div>
		</div>
		<br><input type='submit' name = 'queryaction' value='Query Database'><br><br>
		</div>

		<?
}

include("footer.php"); ?>
</html>
