view interface/tagging_text_20150127.php @ 4:883ad980a43b

add dynasty column to table books
author Zoe Hong <zhong@mpiwg-berlin.mpg.de>
date Tue, 27 Jan 2015 16:40:30 +0100
parents
children
line wrap: on
line source

<?php
header("Content-Type: text/html;charset=utf-8");

if (isset($_GET['id'])) {
	$section_id = $_GET['id'];
} else {
	$get_book_id = $_GET['book'];
	$get_start = $_GET['start'];
	$get_end = $_GET['end'];
}

include_once('Lib_mb_utf8.php');
include_once('config.php');
   
set_time_limit(0);
ini_set('memory_limit', '-1');

$link_mysql = mysql_connect($mysql_server, $mysql_user, $mysql_password);
mysql_query("SET NAMES utf8");

if (!$link_mysql) {
    die('Could not connect: ' . mysql_error());
}

$db_selected = mysql_select_db($mysql_database, $link_mysql);
if (!$db_selected) {
    die ('Can\'t use foo : ' . mysql_error());
}

if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

$query = sprintf("SELECT * FROM `sections` WHERE `id`=\"%s\"", $section_id);
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
	$bookId=$row['books_id'];
	$startPage=$row['start_page'];
	$endPage=$row['end_page'];
}

$contentString="";
if ( file_exists("parsing_files/".$section_id.".txt") ) {
	$contentString=file_get_contents("parsing_files/".$section_id.".txt");
	$stringInput = $contentString;
	$stringInput = preg_replace("/ /u", "○", $stringInput);
	$stringInput = preg_replace("/\n/u", "<br>", $stringInput);
	$stringInput = preg_replace("/【(.*?)】/u", "【<a href=\"review_index_xml_images.php?books_id=".$bookId."&pages=\\1&entry=0\" target=\"_bookImg\">\\1</a>】", $stringInput);
} else {
	$query = sprintf("SELECT `content`, `line`, `books_id` FROM `contents` WHERE `books_id`=\"%s\" AND `line`>=%d AND `line`<=%d", $bookId, $startPage, $endPage);
	$result = mysql_query($query);
	while ($row = mysql_fetch_assoc($result)) {
		$contentString.="【".$row['line']."】".$row['content']."\n";
	}
	$stringInput = $contentString;
	$stringInput = preg_replace("/<(.*?)>/u", "○", $stringInput);
	$stringInput = preg_replace("/ /u", "○", $stringInput);
	$stringInput = preg_replace("/\n/u", "<br>", $stringInput);
	$stringInput = preg_replace("/【(.*?)】/u", "【<a href=\"review_index_xml_images.php?books_id=".$bookId."&pages=\\1&entry=0\" target=\"_bookImg\">\\1</a>】", $stringInput);
}


$taglistArray="";
$query = sprintf("SELECT * FROM `taglist` WHERE `systemName`='%s' ORDER BY `tag` ASC", $systemNAME);
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
	$taglistArray[] = array( $row['id'], $row['name'], $row['tag'], $row['color'] );
}

function sortFunction($a,$b) {
    return strlen($b)-strlen($a);
}

$wordlistArray="";
$query = sprintf("SELECT * FROM `wordlist` WHERE `systemName`='%s' ORDER BY `name` ASC", $systemNAME);
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
	$listString = file_get_contents("wordlist/".$row['id'].".txt");
	$listString = preg_replace("/<div>/u", "\n", $listString);
	$listString = preg_replace("/<\/div>/u", "", $listString);
	$listString = preg_replace("/<span(.*?)>/u", "", $listString);
	$listString = preg_replace("/<\/span>/u", "", $listString);
	//$listString = preg_replace("/\n/u", "|", $listString);
	
	$wordlistArray2 = explode( "\n", $listString );
	usort($wordlistArray2,'sortFunction');
	foreach ( $wordlistArray2 as $index=>$value ) {
		$wordlistArray2[$index] = implode("○?", preg_split("/(?<!^)(?!$)/u", $value));
	}
	foreach ( $wordlistArray2 as $index=>$value ) {
		if ($value=="") unset($wordlistArray2[$index]);
		
	}
	$listString = implode("|", $wordlistArray2);
	
	if ( $listString[0]=="|" ) $listString = substr($listString, 1);
	$wordlistArray[] = array( $row['id'], $row['name'], $listString );
}

?>

<html>
<head>
<title></title>
<script src="./jquery-1.10.2.min.js"></script>
<style>
dynasty
{
	color:red;
}
nianhao
{
	color:blue;
}
name
{
	color:orange;
}
#editable-area {
	line-height:160%;
	letter-spacing:1.5px;
	font-size:21px;
}
<?php 
foreach ( $taglistArray as $taglistValue ) {
	echo $taglistValue[2]."\n{\ncolor:".$taglistValue[3]."\n}\n";
	
	echo ".span_".$taglistValue[2]."\n{\nbackground-color:".$taglistValue[3]."\n}\n";
}
?>
</style>
<script type="text/javascript">
var stringBeforeChange="";
var stringBeforeChangeStack = [];
var lastAddTag="";

window.onbeforeunload = function() {
	return "Are you sure?";
};

$(document).ready(function(){
	//run once
	var el=$('#follow-scroll');
	var originalelpos=el.offset().top; // take it where it originally is on the page

	//run on scroll
	$(window).scroll(function(){
		var el = $('#follow-scroll'); // important! (local)
		var elpos = el.offset().top; // take current situation
		var windowpos = $(window).scrollTop();
		var finaldestination = windowpos+originalelpos;
		el.stop().animate({'top':finaldestination},500);
	});
});

/*
$(document).on("mouseup", function (e) {
    e.stopPropagation();
	$('.questionMarkClass').remove();
	$('.tagItemDivClass').remove();
	alert("Remove");
});


$(document).on("click", '.questionMarkClass', function (e) {
    e.stopPropagation();
});
*/

function removeTagNewDiv( eventObject, tagName, tagObject ) {
	saveUndoText();
	var newdiv = document.createElement("div");
	newdiv.id = "questionMarkId";
	newdiv.setAttribute("class", "questionMarkClass");
	newdiv.style.cssText = 'top:'+eventObject.pageY+'; left:'+eventObject.pageX+'; position:absolute; background-color: white; border:1px solid black; padding: 5px';
	newdiv.innerHTML = "Tag: "+tagName+"<br>Value: "+tagObject.text()+"<br>";
	
	
	var newbutton = $('<button>Remove this</button>').mouseup(function (e2) {
		var textKeep = $(this).parent().parent().html();
		var regexText=/<div(.*?)<\/div>/g;
		var replaceText="";
		textKeep = textKeep.replace(regexText, replaceText);
	
		$(this).parent().parent().replaceWith( textKeep );
    });
	newbutton.appendTo(newdiv);
	
	var newbutton = $('<button>Remove this(with newline)</button>').mouseup(function (e2) {
		var textKeep = $(this).parent().parent().html();
		var regexText=/<div(.*?)<\/div>/g;
		var replaceText="";
		textKeep = textKeep.replace(regexText, replaceText);
	
		var newLineBefore = $(this).parent().parent().prev();
		if ( newLineBefore.prop("tagName") == "BR" ) {
			$(this).parent().parent().prev().replaceWith( );
		}
		$(this).parent().parent().replaceWith( textKeep );
    });
	newbutton.appendTo(newdiv);
	
	var newbutton = $('<button>Remove all</button>').mouseup(function (e2) {
		var textKeep = $(this).parent().parent().html();
		var regexText=/<div(.*?)<\/div>/g;
		var replaceText="";
		textKeep = textKeep.replace(regexText, replaceText);
	
		$(this).parent().parent().replaceWith( textKeep );
		
		var el = document.getElementById("editable-area");
		var regexText=new RegExp("<"+tagName+">("+textKeep+")</"+tagName+">", "g");
		var replaceText="$1";
		var str="" + el.innerHTML;
		
		if ( str.match(regexText)==null ) {
			alert( "Removed 1 entity!" );
		} else {
			alert( "Removed "+(parseInt(str.match(regexText).length)+1)+" entities!" );
		}
		el.innerHTML = str.replace(regexText, replaceText);
    });
	newbutton.appendTo(newdiv);
	
	var newbutton = $('<button>Remove all(with newline)</button>').mouseup(function (e2) {
		var textKeep = $(this).parent().parent().html();
		var regexText=/<div(.*?)<\/div>/g;
		var replaceText="";
		textKeep = textKeep.replace(regexText, replaceText);
	
		$(this).parent().remove();
		
		var el = document.getElementById("editable-area");
		var regexText=new RegExp("<br><"+tagName+">("+textKeep+")</"+tagName+">", "g");
		var replaceText="$1";
		var str="" + el.innerHTML;
		
		alert( "Removed "+str.match(regexText).length+" entities!" );
		el.innerHTML = str.replace(regexText, replaceText);
    });
	newbutton.appendTo(newdiv);
	
	tagObject.append(newdiv);
}


<?php 
foreach ( $taglistArray as $taglistValue ) {
	echo '$(document).on("click", "'.$taglistValue[2].'", function (e) {'."\n";
	echo "\t".'if ( $(this).prop("tagName").toLowerCase() != "'.$taglistValue[2].'" ) return 0;'."\n";
	echo "\t".'if ( $("#editTextId").html() != "Edit the text" ) return 0;'."\n";
	echo "\tremoveTagNewDiv( e, \"".$taglistValue[2]."\", $(this) );\n";
	echo "});\n";
}
?>
$(document).on("click", "name", function (e) {
	if ( $("#editTextId").html() != "Edit the text" ) return 0;
	if ( $(this).prop("tagName").toLowerCase() != "name" ) return 0;
	removeTagNewDiv( e, "name", $(this) );
});

$(document).on("mouseup", '#editable-area', function (e) {
	$('.questionMarkClass').remove();
	$('.tagItemDivClass').remove();
	
	if ( $("#editTextId").html() != "Edit the text" ) return 0;
	var selection = getSelected();
	range = getSelected().getRangeAt(0);
	
	container = document.createElement("div");
	container.appendChild(selection.getRangeAt(0).cloneContents());
	
	if(selection && (selection = new String(selection).replace(/^\s+|\s+$/g,''))) {
		
		var newdiv = document.createElement("div");
		newdiv.id = "tagItemDivId";
		newdiv.setAttribute("class", "tagItemDivClass");
		newdiv.style.cssText = 'top:'+e.pageY+'; left:'+e.pageX+'; position:absolute; background-color: white; border:1px solid black; padding: 5px';
		
		//console.log(selection.getRangeAt(0).cloneContents());
		if ( container.innerHTML.indexOf( "br" ) != -1 ) {
			var newselect = document.createElement("select");
			newselect.id = "TitletagType";
			<?php 
				foreach ( $taglistArray as $taglistValue ) {
					echo "newselect.innerHTML += \"<option value='".$taglistValue[2]."'>".$taglistValue[1]."</option>\";\n";
				}
			?>
			newdiv.appendChild(newselect);
			
			//matchValue =  .match();
			myRegexp = new RegExp("〈(.*?)〉", "g")
			matchValue = myRegexp.exec(String(selection));
			
			if ( matchValue != null ) {
				newdiv.innerHTML += "<input id=\"TitletagName\" value=\""+ matchValue[1] +"\"></br>";
			} else {
				newdiv.innerHTML += "<input id=\"TitletagName\" value=\"\"></br>";
			}
			newdiv.innerHTML += "<button onclick=\"addTagTitle( range, container )\">Add Title Tag To Each Line</button></br>";
			
			newdiv.innerHTML += "<button onclick=\"exportTable( range, container )\">Export As A Table</button></br></br>";
			
			var newselect = document.createElement("select");
			newselect.id = "RemoveTitletagType";
			<?php 
				foreach ( $taglistArray as $taglistValue ) {
					echo "newselect.innerHTML += \"<option value='".$taglistValue[2]."'>".$taglistValue[1]."</option>\";\n";
				}
			?>
			newdiv.appendChild(newselect);
			
			newdiv.innerHTML += "<input id=\"RemoveTitletagName\" value=\"\"></br>";
			newdiv.innerHTML += "<button onclick=\"removeTagTitle( range, container )\">Remove</button></br>";
		} else {
			newdiv.innerHTML = "Tag: "+String(selection)+"<br>";
			
			newdiv.innerHTML += "<button accesskey=\"2\" onclick=\"tagwithtitle( range, '"+String(selection)+"' )\">Tag As Title</button></br>";
			
			<?php 
				foreach ( $taglistArray as $taglistValue ) {
					if ( $taglistValue[2] == "person") {
						echo "newdiv.innerHTML += \"<button accesskey=\\\"1\\\" onclick=\\\"tagwithOnlytag( range, '\"+String(selection)+\"', '".$taglistValue[2]."' )\\\">Tag as:".$taglistValue[1]."(No BR)</button>\";\n";
						echo "newdiv.innerHTML += \"<button accesskey=\\\"1\\\" onclick=\\\"tagwithOnlytag( range, '\"+String(selection)+\"', '".$taglistValue[2]."2' )\\\">Tag as:".$taglistValue[1]."</button>\";\n";
						echo "newdiv.innerHTML += \"<button onclick=\\\"tagStringWithTag( '\"+String(selection)+\"', '".$taglistValue[2]."' )\\\">Tag as:".$taglistValue[1]."(ALL)</button></br>\";\n";
					} else if ($taglistValue[2] == "post_time") {
						echo "newdiv.innerHTML += \"<button accesskey=\\\"3\\\" onclick=\\\"tagwithOnlytag( range, '\"+String(selection)+\"', '".$taglistValue[2]."' )\\\">Tag as:".$taglistValue[1]."</button>\";\n";
						echo "newdiv.innerHTML += \"<button onclick=\\\"tagStringWithTag( '\"+String(selection)+\"', '".$taglistValue[2]."' )\\\">Tag as:".$taglistValue[1]."(ALL)</button></br>\";\n";
					} else if ($taglistValue[2] == "office") {
						echo "newdiv.innerHTML += \"<button accesskey=\\\"4\\\" onclick=\\\"tagwithOnlytag( range, '\"+String(selection)+\"', '".$taglistValue[2]."' )\\\">Tag as:".$taglistValue[1]."</button>\";\n";
						echo "newdiv.innerHTML += \"<button onclick=\\\"tagStringWithTag( '\"+String(selection)+\"', '".$taglistValue[2]."' )\\\">Tag as:".$taglistValue[1]."(ALL)</button></br>\";\n";
					} else {
						echo "newdiv.innerHTML += \"<button onclick=\\\"tagwithOnlytag( range, '\"+String(selection)+\"', '".$taglistValue[2]."' )\\\">Tag as:".$taglistValue[1]."</button>\";\n";
						echo "newdiv.innerHTML += \"<button onclick=\\\"tagStringWithTag( '\"+String(selection)+\"', '".$taglistValue[2]."' )\\\">Tag as:".$taglistValue[1]."(ALL)</button></br>\";\n";
					}				
				}
			?>
		}
		$('body').append(newdiv);
		
		$('#TitletagType').val(lastAddTag);
	}
    //e.stopPropagation();
});

function removeTagTitle( range, container ) {
	saveUndoText();
	range.deleteContents();
	
	lastAddTag = $('#RemoveTitletagType').val();
	
	var stringtemp = container.innerHTML;
	
	if ( $('#RemoveTitletagName').val() == "" ) {
		var regexText="<"+lastAddTag+">〈(.*?)〉</"+lastAddTag+">";
		var replaceText="";
		stringtemp = stringtemp.replace(new RegExp(regexText, "g"), replaceText);
		
		var regexText="<"+lastAddTag+">(.*?)</"+lastAddTag+">";
		var replaceText="$1";
		stringtemp = stringtemp.replace(new RegExp(regexText, "g"), replaceText);
	} else {
		var regexText="<"+lastAddTag+">〈"+$('#RemoveTitletagName').val()+"〉</"+lastAddTag+">";
		var replaceText="";
		stringtemp = stringtemp.replace(new RegExp(regexText, "g"), replaceText);
		
		var regexText="<"+lastAddTag+">("+$('#RemoveTitletagName').val()+")</"+lastAddTag+">";
		var replaceText="$1";
		stringtemp = stringtemp.replace(new RegExp(regexText, "g"), replaceText);
	}
	
	var newdiv = document.createElement("aaaa");
	newdiv.innerHTML = stringtemp;
	range.insertNode(newdiv);
	
	var el = document.getElementById("editable-area");
	
	var regexText=/<aaaa>/gi;
	var replaceText='';
	el.innerHTML = el.innerHTML.replace(regexText, replaceText);
	
	var regexText=/<\/aaaa>/gi;
	var replaceText='';
	el.innerHTML = el.innerHTML.replace(regexText, replaceText);
	
	$('.tagItemDivClass').remove();
}

function addTagTitle( range, container ) {
	saveUndoText();
	lastAddTag = $('#TitletagType').val();
	tag = "<"+$('#TitletagType').val()+">〈"+$('#TitletagName').val()+"〉</"+$('#TitletagType').val()+">";
	range.deleteContents();
	var stringtemp = container.innerHTML;
	var regexText=/<br>/g;
	var replaceText="<br>"+tag;
	stringtemp = stringtemp.replace(regexText, replaceText);
	
	var newdiv = document.createElement("aaaa");
	newdiv.innerHTML = tag+stringtemp;
	range.insertNode(newdiv);
	
	var el = document.getElementById("editable-area");
	
	var regexText=/<aaaa>/gi;
	var replaceText='';
	el.innerHTML = el.innerHTML.replace(regexText, replaceText);
	
	var regexText=/<\/aaaa>/gi;
	var replaceText='';
	el.innerHTML = el.innerHTML.replace(regexText, replaceText);
	
	$('.tagItemDivClass').remove();
}

function exportTable( range, container ) {
	//MsgBox("enter function");
	var form = document.createElement("form");
	form.setAttribute("method", "post");
	form.setAttribute("action", "exportTable.php");
	form.setAttribute("target", "_blank");
	
	var hiddenField = document.createElement("input");		
	hiddenField.setAttribute("name", "content");
	hiddenField.setAttribute("value", container.innerHTML);
	form.appendChild(hiddenField);

	var hiddenField = document.createElement("input");		
	hiddenField.setAttribute("name", "sectionid");
	hiddenField.setAttribute("value", "<?php echo $section_id; ?>");
	form.appendChild(hiddenField);
	
	if(navigator.userAgent.toLowerCase().indexOf('firefox') > -1) {
		document.body.appendChild(form);
		form.submit();
	} else {
		form.submit(); // works under IE and Chrome, but not FF  
	}
}

function exportPage() {
	var startPage = $('#exportPageStart').val();
	var endPage = $('#exportPageEnd').val();

	var el = document.getElementById("editable-area");
	var str="" + el.innerHTML;

	var regexText="【<a([^<>]*?)>"+startPage+"</a>】(.*?)【<a([^<>]*?)>"+endPage+"</a>】";
	
	var form = document.createElement("form");
	form.setAttribute("method", "post");
	form.setAttribute("action", "exportTable.php");
	form.setAttribute("target", "_blank");
	
	var hiddenField = document.createElement("input");		
	hiddenField.setAttribute("name", "content");
	hiddenField.setAttribute("value", str.match(new RegExp(regexText, "g")));
	form.appendChild(hiddenField);

	var hiddenField = document.createElement("input");		
	hiddenField.setAttribute("name", "sectionid");
	hiddenField.setAttribute("value", "<?php echo $section_id; ?>");
	form.appendChild(hiddenField);
	
	if(navigator.userAgent.toLowerCase().indexOf('firefox') > -1) {
		document.body.appendChild(form);
		form.submit();
	} else {
		form.submit(); // works under IE and Chrome, but not FF  
	}
}

function exportAll() {
	var el = document.getElementById("editable-area");
	var str="" + el.innerHTML;

	var form = document.createElement("form");
	form.setAttribute("method", "post");
	form.setAttribute("action", "exportTable.php");
	form.setAttribute("target", "_blank");
	
	var hiddenField = document.createElement("input");		
	hiddenField.setAttribute("name", "content");
	hiddenField.setAttribute("value", str);
	form.appendChild(hiddenField);

	var hiddenField = document.createElement("input");		
	hiddenField.setAttribute("name", "sectionid");
	hiddenField.setAttribute("value", "<?php echo $section_id; ?>");
	form.appendChild(hiddenField);
	
	if(navigator.userAgent.toLowerCase().indexOf('firefox') > -1) {
		document.body.appendChild(form);
		form.submit();
	} else {
		form.submit(); // works under IE and Chrome, but not FF  
	}
}

function cleanUpTextArea() {
	var el = document.getElementById("editable-area");
	
	var regexText=/<div>/gi;
	var replaceText='<br>';
	el.innerHTML = el.innerHTML.replace(regexText, replaceText);
	
	var regexText=/<\/div>/gi;
	var replaceText='';
	el.innerHTML = el.innerHTML.replace(regexText, replaceText);
	
	
	var regexText=/<span style="(.*?)">/gi;
	var replaceText='';
	el.innerHTML = el.innerHTML.replace(regexText, replaceText);
	
	var regexText=/<\/span>/gi;
	var replaceText='';
	el.innerHTML = el.innerHTML.replace(regexText, replaceText);
}

function Undo() {
	if ( stringBeforeChangeStack.length > 0 ) {
		var el = document.getElementById("editable-area");
		el.innerHTML = stringBeforeChangeStack.pop();
	} else {
		var el = document.getElementById("buttonUndo");
		el.disabled = true;
	}
}

function saveUndoText() {
	var el = document.getElementById("editable-area");
	//stringBeforeChange = el.innerHTML;
	stringBeforeChangeStack.push(el.innerHTML); 
	var el = document.getElementById("buttonUndo");
	el.disabled = false;
}

function editText() {
	var el = document.getElementById("editable-area");
	if ( $("#editTextId").html() == "Edit the text" ) {
		saveUndoText();
		el.contentEditable = true;
		$("button").attr("disabled", true);
		$("#editTextId").attr("disabled", false);
		$("#editTextId").html("Edit completed!");
	} else {
		el.contentEditable = false;
		cleanUpTextArea();
		$("button").attr("disabled", false);
		$("#editTextId").html("Edit the text");
	}
}

function saveText() {
	var el = document.getElementById("editable-area");
	
	$.ajax({
		url : 'save_full_text.php',
		async : false,
		type : 'POST',
		data : 'text='+encodeURIComponent(el.innerHTML)+'&filename=<?php echo $section_id; ?>'
	}).done(function(result) {
		alert("Saved!");
	});
	
}

function preg_quote (str, delimiter) {
  // http://kevin.vanzonneveld.net
  // +   original by: booeyOH
  // +   improved by: Ates Goral (http://magnetiq.com)
  // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   bugfixed by: Onno Marsman
  // +   improved by: Brett Zamir (http://brett-zamir.me)
  // *     example 1: preg_quote("$40");
  // *     returns 1: '\$40'
  // *     example 2: preg_quote("*RRRING* Hello?");
  // *     returns 2: '\*RRRING\* Hello\?'
  // *     example 3: preg_quote("\\.+*?[^]$(){}=!<>|:");
  // *     returns 3: '\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:'
  return (str + '').replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\' + (delimiter || '') + '-]', 'g'), '\\$&');
}

function replaceRegex() {
	saveUndoText();
	
	var startPage = $('#regexPageStart2').val();
	var endPage = $('#regexPageEnd2').val();
	var el = document.getElementById("editable-area");
	var str="" + el.innerHTML;
	
	var regexText=document.getElementById("regexText").value;
	var replaceText=document.getElementById("replaceText").value;
	var str="" + el.innerHTML;
	
	if ( startPage == "" ) {
		alert( "Tagged "+str.match(new RegExp(regexText, "g")).length+" entities!" );
		el.innerHTML = str.replace(new RegExp(regexText, "g"), replaceText);
	} else {
		var regexText2="【<a([^<>]*?)>"+startPage+"</a>】(.*?)【<a([^<>]*?)>"+endPage+"</a>】";
		var partString = ""+str.match(new RegExp(regexText2, "g"));
		alert(partString);
		
		alert( "Tagged "+partString.match(new RegExp(regexText, "g")).length+" entities!" );
		var resultString = partString.replace(new RegExp(regexText, "g"), replaceText);
		
		str="" + el.innerHTML;
		el.innerHTML = str.replace(new RegExp(regexText, "g"), resultString);
	}
	
	//document.styleSheets[0].addRule("tag001", "color:green;")
}

function replaceSmartRegex() {
	saveUndoText();
	var startPage = $('#regexPageStart2').val();
	var endPage = $('#regexPageEnd2').val();
	
	var el = document.getElementById("editable-area");
	var regexText=document.getElementById("regexText").value;
	
	<?php 
	foreach ( $wordlistArray as $wordlistValue ) {
		echo "\tvar regexText1=\"List ".$wordlistValue[1]."\";\n";
		echo "\tregexText1 = preg_quote(regexText1);\n";
		echo "\tvar replaceText1=\"".$wordlistValue[2]."\";\n";
		echo "\tregexText = regexText.replace(new RegExp(regexText1, \"g\"), replaceText1);\n\n";
	}
	?>
	
	var replaceText=document.getElementById("replaceText").value;
	var str="" + el.innerHTML;
	
	if ( startPage == "" ) {
		alert( "Tagged "+str.match(new RegExp(regexText, "g")).length+" entities!" );
		el.innerHTML = str.replace(new RegExp(regexText, "g"), replaceText);
	} else {
		var regexText2="【<a([^<>]*?)>"+startPage+"</a>】(.*?)【<a([^<>]*?)>"+endPage+"</a>】";
		var partString = ""+str.match(new RegExp(regexText2, "g"));
		alert(partString);
		
		alert( "Tagged "+partString.match(new RegExp(regexText, "g")).length+" entities!" );
		var resultString = partString.replace(new RegExp(regexText, "g"), replaceText);
		
		str="" + el.innerHTML;
		el.innerHTML = str.replace(new RegExp(regexText2, "g"), resultString);
	}
	//document.styleSheets[0].addRule("tag001", "color:green;")
}

//Tagging Items
function getSelected() {
    if(window.getSelection) {
		return window.getSelection();
	} else if (document.getSelection) { 
		return document.getSelection(); 
	} else {
		var selection = document.selection && document.selection.createRange();
		if(selection.text) {
			return selection.text;
		}
		return false;
	}
	return false;
}

function tagStringWithTag( stringValue, tag ) {
	saveUndoText();
	var el = document.getElementById("editable-area");
	var regexText="("+String(stringValue)+")";
	if ( tag=="person") {
		var replaceText="<br><"+tag+">$1</"+tag+">";
	} else {
		var replaceText="<"+tag+">$1</"+tag+">";
	}
	var str="" + el.innerHTML;

	$('.tagItemDivClass').remove();
	alert( "Tagged "+str.match(new RegExp(regexText, "g")).length+" entities!" );
	el.innerHTML = str.replace(new RegExp(regexText, "g"), replaceText);
}


function tagwithtitle( range, stringSelection ) {
	saveUndoText();
	range.deleteContents();
	//var newdiv = document.createElement("br");
	//range.insertNode(newdiv);
	range.insertNode(document.createTextNode("〈"+stringSelection+"〉"));
	var newdiv = document.createElement("br");
	range.insertNode(newdiv);
	
	$('.tagItemDivClass').remove();
}

function tagwithOnlytag( range, stringSelection, tag ) {
	saveUndoText();
	
	range.deleteContents();
	if ( tag=="person2") {
		var newdiv = document.createElement("person");
		newdiv.innerHTML = stringSelection;
		range.insertNode(newdiv);
		var newdiv = document.createElement("br");
		range.insertNode(newdiv);
	} else {
		var newdiv = document.createElement(tag);
		newdiv.innerHTML = stringSelection;
		range.insertNode(newdiv);
	}
	$('.tagItemDivClass').remove();
}

function tagNameWithLastName() {
	saveUndoText();
	var el = document.getElementById("editable-area");
	var regexText=/(○|】|^)(王|李|張|趙|劉|陳|楊|吳|黃|黄|朱|孫|郭|胡|呂|高|宋|徐|程|林|鄭|范|何|韓|曹|馬|許|田|馮|杜|周|曾|汪|蘇|董|方|蔡|梁|石|謝|賈|薛|彭|崔|唐|潘|鄧|史|錢|侯|魏|羅|葉|沈|孟|姚|傅|丁|章|蕭|蔣|盧|陸|袁|晁|譚|邵|歐陽|孔|詹|俞|尹|廖|閻|洪|夏|雷|葛|文|柳|陶|毛|丘|龔|蒲|邢|郝|龐|安|裴|折|施|游|金|鄒|湯|虞|嚴|鍾)([^○(舉人|縣人|歲貢|間任)]{1,3}|○[^○])(?=(○|$))/g;
	var replaceText="$1<br><person>$2$3</person>$4";
	var str="" + el.innerHTML;
	
	alert( "Tagged "+str.match(regexText).length+" entities!" );
	el.innerHTML = str.replace(regexText, replaceText);
}

function tagNameWithLastName2() {
	saveUndoText();
	var el = document.getElementById("editable-area");
	var regexText="(○|】|^)("+$('#surname').val()+")([^○(舉人|縣人|歲貢|間任)]{1,3}|○[^○])(?=(○|$))";
	var replaceText="$1<br><person>$2$3</person>$4";
	var str="" + el.innerHTML;
	
	alert( "Tagged "+str.match(new RegExp(regexText, "g")).length+" entities!" );
	el.innerHTML = str.replace(new RegExp(regexText, "g"), replaceText);
}

function tagTime() {
	saveUndoText();
	var el = document.getElementById("editable-area");
	var str="" + el.innerHTML;

	var regexText=/(<?php echo $wordlistArray[0][2]; ?>)(○?)(一|二|三|四|五|六|七|八|九)?(○?)(十)?(○?)(一|二|三|四|五|六|七|八|九|元|十)(○?)(年)/g;
	var replaceText="<time>$1$2$3$4$5$6$7$8$9</time>";
	var matchedCount = str.match(regexText).length;
	str = str.replace(regexText, replaceText);
	
	var regexText=/(?!(>))(<?php echo $wordlistArray[0][2]; ?>)/g;
	var replaceText="<time>$1$2</time>";
	matchedCount += str.match(regexText).length;
	el.innerHTML = str.replace(regexText, replaceText);
	
	var regexText=/(一|二|三|四|五|六|七|八|九)?(○?)(十)?(○?)(一|二|三|四|五|六|七|八|九|元|十)(○?)(年)(?!(<))/g;
	var replaceText="<time>$1$2$3$4$5$6$7</time>";
	matchedCount += str.match(regexText).length;
	el.innerHTML = str.replace(regexText, replaceText);
	
	alert( "Tagged "+matchedCount+" entities!" );
}

function tagBiogAddr() {
	saveUndoText();
	var el = document.getElementById("editable-area");
	var str="" + el.innerHTML;

	var regexText=/(○)([^○]{1,6})(○?)(人)/g;
	var replaceText="$1<biog_addr>$2</biog_addr>$3$4";
	el.innerHTML = str.replace(regexText, replaceText);
	
	alert( "Tagged "+str.match(regexText).length+" entities!" );
}

function smartRegexNew() {
	$('#smartRegexPopUpDiv').css("display", "block");
	$('#smartRegexPopUpDiv').css("background-color", "White");
	$('#smartRegexPopUpDiv').css("width", "400px");
	$('#smartRegexPopUpDiv').css("height", "300px");
	$('#smartRegexPopUpDiv').css("top", "100px");
	$('#smartRegexPopUpDiv').css("left", "-200px");
	$('#smartRegexPopUpDiv').css("border", "1px solid black");
	$('#smartRegexPopUpDiv').css("padding", "5px");
	
	$('#smartRegexPopUpAdd').attr("disabled", false);
	$('#smartRegexPopUpEdit').attr("disabled", "disabled");
	$('#smartRegexPopUpDel').attr("disabled", "disabled");
	$('#smartRegexPopUpBack').attr("disabled", "disabled");
	$('#smartRegexPopUpFor').attr("disabled", "disabled");
}

function replaceSmartClose() {
	$('#smartRegexPopUpDiv').css("display", "none");
	$("#smartRegexPopUpSelectWord").val("NULL");
	$("#smartRegexPopUpText").val("");
	$("#smartRegexPopUpName").val("");
}

function replaceSmartEdit(){
	thisObject = $('#smartRegexPopUpDiv').attr("editID");

	$('#smartRegexShowDiv > #'+thisObject).attr("class", "span_"+$("#smartRegexPopUpSelectTag").val());
	$('#smartRegexShowDiv > #'+thisObject).attr("regexText", $("#smartRegexPopUpText").val());
	$('#smartRegexShowDiv > #'+thisObject).attr("regexReplace", $("#smartRegexPopUpSelectTag").val());
}

function replaceSmartDel() {
	thisObject = $('#smartRegexPopUpDiv').attr("editID");
	$('#smartRegexShowDiv > #'+thisObject).remove();
}

function replaceSmartFor() {
	thisObject = $('#smartRegexPopUpDiv').attr("editID");
	//var wahaha = $('#'+thisObject).clone();
	//var hahawa = $('#'+thisObject).next();
	//$('#'+thisObject).remove();
	//wahaha.insertAfter(hahawa);
	$('#smartRegexShowDiv > #'+thisObject).insertAfter( $('#'+thisObject).next() );
}

function replaceSmartBack() {
	thisObject = $('#smartRegexPopUpDiv').attr("editID");
	//var wahaha = $('#'+thisObject).clone();
	//var hahawa = $('#'+thisObject).prev();
	//$('#'+thisObject).remove();
	//wahaha.insertBefore(hahawa);
	$('#smartRegexShowDiv > #'+thisObject).insertBefore( $('#'+thisObject).prev() );
}

function replaceSmartAdd() {
	var newdiv = document.createElement("span");
	newdiv.innerHTML = " "+$("#smartRegexPopUpName").val()+" ";
	$(newdiv).css("border", "1px solid black");
	$(newdiv).css("width", "100px");
	
	$(newdiv).attr("class", "span_"+$("#smartRegexPopUpSelectTag").val());
	$(newdiv).attr("id", "span_"+$("#smartRegexPopUpName").val());
	$(newdiv).attr("regexText", $("#smartRegexPopUpText").val());
	$(newdiv).attr("regexReplace", $("#smartRegexPopUpSelectTag").val());
	
	$('#smartRegexShowDiv').append(newdiv);
	
	replaceSmartClose();
}

$(document).on("click", '#smartRegexShowDiv > span', function (e) {
	$('#smartRegexPopUpDiv').css("display", "block");
	$('#smartRegexPopUpDiv').css("background-color", "White");
	$('#smartRegexPopUpDiv').css("width", "400px");
	$('#smartRegexPopUpDiv').css("height", "300px");
	$('#smartRegexPopUpDiv').css("top", "100px");
	$('#smartRegexPopUpDiv').css("left", "-200px");
	$('#smartRegexPopUpDiv').css("border", "1px solid black");
	$('#smartRegexPopUpDiv').css("padding", "5px");
	
	$('#smartRegexPopUpDiv').attr("editID", $(this).attr("id"));
	
	$('#smartRegexPopUpName').val($(this).html());
	$('#smartRegexPopUpText').val($(this).attr("regexText"));
	$('#smartRegexPopUpSelectTag').val($(this).attr("regexReplace"));
	
	$('#smartRegexPopUpAdd').attr("disabled", "disabled");
	$('#smartRegexPopUpEdit').attr("disabled", false);
	$('#smartRegexPopUpDel').attr("disabled", false);
	$('#smartRegexPopUpBack').attr("disabled", false);
	$('#smartRegexPopUpFor').attr("disabled", false);
});

function smartRegexEmpty() {
	$('#smartRegexShowDiv').html("");
}

function replaceSmartRun() {

	var replaceSmartRegexString = "";
	var replaceSmartReplaceString = "";
	var count=1;
	
	saveUndoText();
	
	$('#smartRegexShowDiv').children('span').each(function () {
		replaceSmartRegexString += "(" + $(this).attr("regexText") + ")";
		if ( $(this).attr("regexReplace") == "notag" ) {
			replaceSmartReplaceString += "$" + count;
		} else if ( $(this).attr("regexReplace") == "title" ) {
			replaceSmartReplaceString += "<br>〈" + "$" + count + "〉<br>";
		} else {
			replaceSmartReplaceString += "<" + $(this).attr("regexReplace") + ">" + "$" + count + "</"+ $(this).attr("regexReplace") +">";
		}
		count++;
	});
		
		
	var startPage = $('#regexPageStart').val();
	var endPage = $('#regexPageEnd').val();
	var el = document.getElementById("editable-area");
	var str="" + el.innerHTML;
	
	if ( startPage == "" ) {
		alert( "Tagged "+str.match(new RegExp(replaceSmartRegexString, "g")).length+" entities!" );
		el.innerHTML = str.replace(new RegExp(replaceSmartRegexString, "g"), replaceSmartReplaceString);
	} else {
		var regexText="【<a([^<>]*?)>"+startPage+"</a>】(.*?)【<a([^<>]*?)>"+endPage+"</a>】";
		var partString = ""+str.match(new RegExp(regexText, "g"));
		alert(partString);
		
		alert( "Tagged "+partString.match(new RegExp(replaceSmartRegexString, "g")).length+" entities!" );
		var resultString = partString.replace(new RegExp(replaceSmartRegexString, "g"), replaceSmartReplaceString);
		
		str="" + el.innerHTML;
		el.innerHTML = str.replace(new RegExp(regexText, "g"), resultString);
	}
}

function replaceSmartRunSpace() {

	var replaceSmartRegexString = "";
	var replaceSmartReplaceString = "";
	var count=1;
	saveUndoText();
	
	$('#smartRegexShowDiv').children('span').each(function () {
		//alert($(this).attr("regexText"));
		replaceSmartRegexString += "(" + $(this).attr("regexText") + ")(○*)";
		if ( $(this).attr("regexReplace") == "notag" ) {
			replaceSmartReplaceString += "$" + count;
		} else if ( $(this).attr("regexReplace") == "title" ) {
			replaceSmartReplaceString += "<br>〈" + "$" + count + "〉<br>";
		} else {
			replaceSmartReplaceString += "<" + $(this).attr("regexReplace") + ">" + "$" + count + "</"+ $(this).attr("regexReplace") +">";
		}
		count++;
		replaceSmartReplaceString += "$" + count;
		count++;
	});
	
	var startPage = $('#regexPageStart').val();
	var endPage = $('#regexPageEnd').val();
	var el = document.getElementById("editable-area");
	var str="" + el.innerHTML;
	
	if ( startPage == "" ) {
		alert( "Tagged "+str.match(new RegExp(replaceSmartRegexString, "g")).length+" entities!" );
		el.innerHTML = str.replace(new RegExp(replaceSmartRegexString, "g"), replaceSmartReplaceString);
	} else {
		var regexText="【<a([^<>]*?)>"+startPage+"</a>】(.*?)【<a([^<>]*?)>"+endPage+"</a>】";
		var partString = ""+str.match(new RegExp(regexText, "g"));
		alert(partString);
		
		alert( "Tagged "+partString.match(new RegExp(replaceSmartRegexString, "g")).length+" entities!" );
		var resultString = partString.replace(new RegExp(replaceSmartRegexString, "g"), replaceSmartReplaceString);
		
		str="" + el.innerHTML;
		el.innerHTML = str.replace(new RegExp(regexText, "g"), resultString);
	}
	
	//alert( "Tagged "+str.match(new RegExp(replaceSmartRegexString, "g")).length+" entities!" );
	//el.innerHTML = str.replace(new RegExp(replaceSmartRegexString, "g"), replaceSmartReplaceString);
}

function smartRegexSave() {
	var x;
	var name=prompt("Please enter this Regex name",RegexLoadedName);
	if (name!=null){
		$.ajax({
			url : 'save_regex.php',
			async : false,
			type : 'POST',
			data : 'text='+encodeURIComponent($('#smartRegexShowDiv').html())+'&filename='+name
		}).done(function(result) {
			alert("Saved!");
		});
	}
}

function smartRegexLoad() {


	$('#load_regex_div').html("");
	$('#load_regex_div').css("display", "block");
	$('#load_regex_div').css("border", "1px solid black");
	$('#load_regex_div').css("background-color", "White");
	$('#load_regex_div').css("width", "200px");
	$('#load_regex_div').css("height", "150px");
	$('#load_regex_div').css("top", "100px");
	$('#load_regex_div').css("left", "-200px");
	
	var newselect = document.createElement("select");
	newselect.id = "loadRegexSelect";
			
	$.ajax({
		type: 'GET', 
		url: 'load_regex.php',
		dataType: 'json',
		cache: false,
		success: function (data) { 
			$.each(data, function(index, element) {
				newselect.innerHTML += "<option value=\""+index+"\">"+index+"</option>\n";
				//alert(index);
				//alert(element);
				var newdiv = document.createElement("div");
				$(newdiv).css("display", "none");
				$(newdiv).html(element);
				$(newdiv).attr("id", "div_"+index);
				$('#load_regex_div').append(newdiv);
			});
		}
	});
	
	$('#load_regex_div').append(newselect);
	var newbutton = document.createElement("button");
	$(newbutton).html("Load");
	$(newbutton).attr("onclick", "loadRegexAdd()");
	$('#load_regex_div').append(newbutton);
	var newbutton = document.createElement("button");
	$(newbutton).html("Close");
	$(newbutton).attr("onclick", "$('#load_regex_div').css(\"display\", \"none\");");
	$('#load_regex_div').append(newbutton);
}

var RegexLoadedName = "";
function loadRegexAdd() {
	RegexLoadedName = $('#loadRegexSelect').val();
	var divName = "div_"+$('#loadRegexSelect').val();
	$('#smartRegexShowDiv').html( $('#'+divName).html() );
	$('#load_regex_div').css("display", "none");
}

$(document).on("change", '#smartRegexPopUpSelectWord', function (e) {
<?php
	foreach ( $wordlistArray as $wordlistValue ) {
		echo "if ( $('#smartRegexPopUpSelectWord').val() == \"".$wordlistValue[0]."\") {";
		echo "$('#smartRegexPopUpText').val(\"".$wordlistValue[2]."\");";
		echo "}";
	}
?>
});

</script>
</head>
<body>
<table width="1250" border="1">
	<tr>
		<td width="980">
			<div id="editable-area" class="area" style="max-width: 980"><?php echo $stringInput; ?></div>
		</td>
		<td width="270" valign="top">
			<div id="follow-scroll" style="position:absolute; width: 220" width="220">
				<div id="load_regex_div" style="position: absolute; display: none"></div>
				<div id="smartRegexPopUpDiv" style="position: absolute; display: none">
					Name: <input id="smartRegexPopUpName"></input><br><br>
					Word List: 
					<select id="smartRegexPopUpSelectWord">
					<option value="NULL" selected>無</option>
					<?php
						foreach ( $wordlistArray as $wordlistValue ) {
							echo "<option value=\"".$wordlistValue[0]."\">".$wordlistValue[1]."</option>\n";
						}
					?>
					</select>
					<br>
					OR (USE "|" TO SEPARATE WORDS):<br>
					<TEXTAREA id="smartRegexPopUpText" COLS=30 ROWS=4></TEXTAREA><br><br>
					Tag:
					<select id="smartRegexPopUpSelectTag">
					<?php
						foreach ( $taglistArray as $taglistValue ) {
							echo "<option value=\"".$taglistValue[2]."\">".$taglistValue[1]."</option>\n";
						}
						echo "<option value=\"title\">Title</option>\n";
					?>
					<option value="NOTAG">不標記</option>
					</select><br>
					<button id="smartRegexPopUpAdd" onclick="replaceSmartAdd()" style="height: 30px; width: 50px">Add</button>
					<button id="smartRegexPopUpEdit" onclick="replaceSmartEdit()" style="height: 30px; width: 50px">Edit</button>
					<button id="smartRegexPopUpDel" onclick="replaceSmartDel()" style="height: 30px; width: 50px">Delete</button>
					<button id="smartRegexPopUpBack" onclick="replaceSmartBack()" style="height: 30px; width: 50px"><<</button>
					<button id="smartRegexPopUpFor" onclick="replaceSmartFor()" style="height: 30px; width: 50px">>></button>
					<button onclick="replaceSmartClose()" style="height: 30px; width: 50px">Close</button>
				</div>
				<form action="javascript:void(0);">
					<fieldset>
						<legend>Replace By <i><b>Smart Regex</b></i>©:</legend>
						<div id="smartRegexShowDiv"></div><br>
						<button onclick="smartRegexNew()" style="height: 30px; width: 220px">Add Regex Group</button></br>
						Range: <input type="text" size="5" id="regexPageStart">to<input type="text" size="5" id="regexPageEnd"><br>
						<button onclick="replaceSmartRun()" style="height: 30px; width: 220px">Run</button></br>
						<button onclick="replaceSmartRunSpace()" style="height: 30px; width: 220px">Run(Allow space between Group)</button></br>
						<button onclick="smartRegexSave()" style="height: 30px; width: 70px">Save</button>
						<button onclick="smartRegexLoad()" style="height: 30px; width: 70px">Load</button>
						<button onclick="smartRegexEmpty()" style="height: 30px; width: 70px">Clear</button></br>
					</fieldset>
					
					<fieldset>
						<legend>Tag by rule:</legend>
						<button onclick="tagNameWithLastName()" style="height: 30px; width: 220px">Tag Word Begin With Surname</button></br>
						<button onclick="tagNameWithLastName2()" style="height: 30px; width: 170px">Tag Word Begin With</button><input type="text" size="2" id="surname"></br>
						<!--<button onclick="tagTime()" style="height: 30px; width: 220px">Tag Time</button></br>-->
						<!--<button onclick="tagBiogAddr()" style="height: 30px; width: 220px">Tag BiogAddr</button></br>-->
						<button onclick="Undo()" style="height: 30px; width: 220px" id="buttonUndo" disabled="true">Undo</button>
					</fieldset>
					
					<fieldset>
						<legend>Edit:</legend>
						<!--<button onclick="cleanUpTextArea()" style="height: 30px; width: 220px">Reform the text</button></br>-->
						<button onclick="saveText()" style="height: 30px; width: 220px">Save the text</button></br>
						<button onclick="editText()" id="editTextId" style="height: 30px; width: 220px">Edit the text</button></br>
						</br>
						<button onclick="window.open('edit_wordlist.php')" style="height: 30px; width: 220px">Manage Word List</button></br>
						<button onclick="window.open('edit_taglist.php')" style="height: 30px; width: 220px">Manage Tag List</button></br>
					</fieldset>
					
					<fieldset>
						<legend>Export:</legend>
						Page: <input type="text" size="5" id="exportPageStart">to<input type="text" size="5" id="exportPageEnd"><br>
						<button onclick="exportPage()" style="height: 30px; width: 220px">Export</button></br>
						<button onclick="exportAll()" style="height: 30px; width: 220px">Export All</button></br>
					</fieldset>
					
					<fieldset>
						<legend>Replace By <i><b>Regex</b></i>:</legend>
						Range: <input type="text" size="5" id="regexPageStart2">to<input type="text" size="5" id="regexPageEnd2"><br>
						Regex: <input type="text" size="30" id="regexText"></br>
						Replace: <input type="text" size="30" id="replaceText"><br>
						<button onclick="replaceSmartRegex()">Replace!</button>
					</fieldset>
				</form>
			</div>
		</td>
	</tr>
</table>
</body>
</html>