view views/Extractapp/TaggingText.php @ 89:e681d693240e extractapp

new: generated regex to SmartRegex
author Zoe Hong <zhong@mpiwg-berlin.mpg.de>
date Wed, 03 Jun 2015 16:54:09 +0200
parents fb5049fc5dd7
children 94ad33739fa4
line wrap: on
line source

<?php
/*
 * TaggingText.php
 * This file is part of Extraction-interface.
 *
 * Extraction-interface is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Extraction-interface is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Extraction-interface.  If not, see <http://www.gnu.org/licenses/>.
*/

/*! \file 
 * This is the view for TaggingText.
 * It shows the extraction-interface application itself.
 * The input data for this view come from models/extractapp.php which is handled by controllers/extractapp.php.
 * Input data for example, are (1)text string (containing tags if there are any), 
 * (2)taglist for the current topic, (3)book and section information, etc.
 * The output data are passed to backend by controller to corresponding method in model/extractapp.php.
 * Output data is the tagged text string.
 * 
 * The user interface contains tagging area on the left side, and toolbox on the right side.
 * There are popup windows to assist the tagging task, for example RegEx-editors, tag-window, remove-tag-window, etc.
 * 
*/

// --- initialize config file and input text ---
$stringInput = $viewmodel['stringInput'];
$wordlistArray = $viewmodel['wordlistArray'];
$taglistArray = $viewmodel['taglistArray'];
$section_id = $viewmodel['section_id'];
$topiclistArray = $viewmodel['topiclistArray'];
$default_topic_id = $viewmodel['default_topic_id'];
$topic_name = $viewmodel['topic_name']; // array of names
$topic_tag = $viewmodel['topic_tag'];
$topic_tag_ch = $viewmodel['topic_tag_ch'];
$info = $viewmodel['info']; 
$messages = $viewmodel['messages'];

$taglist_infile = $viewmodel['taglist_infile'];
$book_meta = $viewmodel['book_meta'];

?>


<html>
<head>
    <meta charset="UTF-8">
    <title>Extraction Interface</title>
    <meta http-equiv="no-cache">
    <meta http-equiv="Expires" content="-1">
    <meta http-equiv="Cache-Control" content="no-cache">
<style>
dynasty
{
	color:red;
}
nianhao
{
	color:blue;
}
name
{
	color:orange;
}
#editable-area {
	line-height:160%;
	letter-spacing:1.5px;
	font-size:21px;
}

<?php
// color on the tags
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>


</head>

<body>

<script type="text/javascript">

var cjst = window.cjst; // for pinyin from cjst.js

// not use this for now
function _showTagColor(up_to_date) {
    var taglistArray = "";
    if (up_to_date) {
        taglistArray = JSON.parse('<?php echo json_encode($taglistArray) ?>');
    } else {
        taglistArray = JSON.parse('<?php echo json_encode($taglist_infile) ?>');
    }


    for (var i = 0; i < taglistArray.length; i++) {
        var taglistValue = taglistArray[i];
        
        $(taglistValue[2]).css('color', taglistValue[3]);
        /*var element = document.querySelectorAll(taglistValue[2]);
        for (var j = 0; j < element.length; j++) {
            element[j].style.color = taglistValue[3];
        }
        */
    }
}



function reloadText() {
    /**
     * Reload the text when there is a new version of this branch.
    */
    // confirm to reload
    var r = confirm("Are you sure you want to load the latest version (in a new tab)?");
    if (r != true) {
        return;
    }

    var form = document.createElement("form");
    form.setAttribute("method", "post");
    form.setAttribute("action", "./TaggingText");  // hand to controller
    form.setAttribute("target", "_blank");

    var hiddenField = document.createElement("input");      
    hiddenField.setAttribute("name", "topic");
    var topic_id = JSON.parse('<?php echo json_encode($default_topic_id) ?>');
    hiddenField.setAttribute("value", topic_id);
    form.appendChild(hiddenField);

    var hiddenField = document.createElement("input");      
    hiddenField.setAttribute("name", "func");
    hiddenField.setAttribute("value", "ReloadText");
    form.appendChild(hiddenField);

    _postForContineTagging(form);

}

function handleFileVersionConflict() {
    var info = JSON.parse('<?php echo json_encode($info) ?>');
    // if (info['current_fileId'] != 0 && info['current_fileId'] != info['file_id']){
    if (info['current_fileId'] != 0){
        // -- there might be conflicts between different version
        alert("Your saving failed! Someone edited this file and saved before you.");
        $('#reloadTextButton').css("display", "block");

        return;
    }
    return;
    
}

// on click on tagged words, call removeTagNewDiv() for the popup window
// popup-window overlapping issue
var pop_remove_tag_window = true;
var taglistArray = JSON.parse('<?php echo json_encode($taglistArray) ?>');
for (var i = 0; i < taglistArray.length; i++) {
    var taglistValue = taglistArray[i];

    $(document).on("click", taglistValue[2], function (e) {
        if ($("#editTextId").html() != "Edit the text") return 0;
        var tagName = $(this).prop("tagName").toLowerCase();
        /*
        if ($(this).prop("tagName").toLowerCase() != taglistValue[2]) {
            return 0;
        }
        */
        // pop_remove_tag_window is a global variable which indicates if to show the remove-popup-window
        if (pop_remove_tag_window) {
            removeTagNewDiv( e, tagName , $(this));
        };
    });
};

/*
<?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).ready(function(){
    
    // --- for sidebar--- 
    //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);
        el.stop().animate({'top':finaldestination},0);
    });
    // ---


    //--- for popups ---
    //run once
    var el=$('#popups');
    var originalelpos=el.offset().top; // take it where it originally is on the page
    
    //run on scroll
    $(window).scroll(function(){
        var el = $('#popups'); // important! (local)
        var elpos = el.offset().top; // take current situation
        var windowpos = $(window).scrollTop();
        var finaldestination = windowpos+originalelpos;
        //el.stop().animate({'top':finaldestination},500);
        el.stop().animate({'top':finaldestination},0);
    });
    // ---


    // === This case only be possible for developing on local machine ==== 
    var _GET = JSON.parse('<?php echo json_encode($_GET) ?>');
    if (_GET['id']) {
        var info = JSON.parse('<?php echo json_encode($info) ?>');
        var redirectUrl = "http://localhost:1080/localgazetteers-dev/extraction-interface/Extractapp/TaggingText";
        var section_id = info['section_id'];

        var form = $('<form action="' + redirectUrl + '" method="post">' +
            '<input type="hidden" name="sectionId" value="'+section_id+'" />' +
            '</form>');
            $('body').append(form);
            $(form).submit();
    } 
    // --------

    // --- handle file version conflict ---
    var info = JSON.parse('<?php echo json_encode($info) ?>');
    // the first time to this section. without branch_id and file_id
    if (info['file_id'] == 0) {  // or info['branch_id'] == 0, means new file
        $( "#save_text_to_LGService_id").text( "Create(Save) Branch to LGService" );

    }
    handleFileVersionConflict();

    // --- handle taglist deprecation ---
    var taglist_infile = JSON.parse('<?php echo json_encode($taglist_infile) ?>');
    var taglistArray = JSON.parse('<?php echo json_encode($taglistArray) ?>');

    if (taglist_infile == "") {
        console.log("Debug: taglist_infile is empty which means taglist_infile is equal to taglist in db.");
    } else {
        console.log("Debug: taglist_infile length=" + taglist_infile.length);
        console.log(taglist_infile);
        console.log("Debug: taglistArray length=" + taglistArray.length);
        console.log(taglistArray);

        // TOOD: ask user to modify/decide tags
        // showing taglist_infile and taglistArray
        //alert("Warning: taglist is deprecated in the current file.");

    }


});

$(document).on("mouseup", '#editable-area', function (e) {
    $('.questionMarkClass').remove();
    $('.tagItemDivClass').remove();
   
    if ( $("#editTextId").html() != "Edit the text" ) return 0;
    var selection = getSelected();

    range = selection.getRangeAt(0);
    
    container = document.createElement("div");
    container.appendChild(selection.getRangeAt(0).cloneContents());

    if(selection && (selection_plain = new String(selection).replace(/^\s+|\s+$/g,''))) {
        try{
        	var newdiv = document.createElement("div");
            //newdiv.id = "tagItemDivId";
            //newdiv.setAttribute("class", "tagItemDivClass");
            $(newdiv).id = "tagItemDivId";
            $(newdiv).addClass("tagItemDivClass");
            newdiv.style.cssText = 'top:'+e.pageY+'; left:'+e.pageX+';';
            //console.log(selection.getRangeAt(0).cloneContents());
            if ( container.innerHTML.indexOf( "br" ) != -1 ) {
                // when selected words containing tags (i.e. has 'br' in the selected string), 
                // which means user want to apply Title / or tags all in once at each line
                // This may not be the best checking solution, since 'br' also appears between not-tagged words

                var newselect = document.createElement("select");
                newselect.id = "TitletagType";
                //console.log(JSON.parse('<?php echo json_encode($taglistArray) ?>'));

                <?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 {
     			// for pop up window on edit-area for tag list
                // newdiv.innerHTML = "Tagging word: "+String(selection)+"<br>";
                var tagging_words = document.createElement("div");
                $(tagging_words).addClass("bg-info");
                $(tagging_words).text("Tagging words: " + String(selection_plain));

                newdiv.appendChild(tagging_words);

                var tagging_tags = document.createElement("div");
                $(tagging_tags).addClass("bg-white");
                $(tagging_tags).text("Tag as: ");

                tagging_tags.innerHTML += "<button accesskey=\"2\" onclick=\"tagwithtitle( range, '"+String(selection_plain)+"' )\">Title</button></br>";
               
                <?php 
                foreach ( $taglistArray as $taglistValue ) {
                    if ($taglistValue[2] == $topic_tag) {
                    	echo "tagging_tags.innerHTML += \"<button accesskey=\\\"1\\\" onclick=\\\"tagwithOnlytag( range, '\"+String(selection_plain)+\"', '".$taglistValue[2]."2' )\\\">".$taglistValue[1]."</button>\";\n";
                        echo "tagging_tags.innerHTML += \"<button accesskey=\\\"1\\\" onclick=\\\"tagwithOnlytag( range, '\"+String(selection_plain)+\"', '".$taglistValue[2]."' )\\\">".$taglistValue[1]."(without new line)</button>\";\n";
                        echo "tagging_tags.innerHTML += \"<button onclick=\\\"tagStringWithTag( '\"+String(selection_plain)+\"', '".$taglistValue[2]."' )\\\">".$taglistValue[1]."(ALL)</button></br>\";\n";
                        break;
                	}
                }
			    foreach ( $taglistArray as $taglistValue ) {
                    if ($taglistValue[2] == $topic_tag) { 
                		// pass
                	} else if ($taglistValue[2] == "post_time") {
                        echo "tagging_tags.innerHTML += \"<button accesskey=\\\"3\\\" onclick=\\\"tagwithOnlytag( range, '\"+String(selection)+\"', '".$taglistValue[2]."' )\\\">Tag as:".$taglistValue[1]."</button>\";\n";
                        echo "tagging_tags.innerHTML += \"<button onclick=\\\"tagStringWithTag( '\"+String(selection)+\"', '".$taglistValue[2]."' )\\\">Tag as:".$taglistValue[1]."(ALL)</button></br>\";\n";
                    } else if ($taglistValue[2] == "office") {
                        echo "tagging_tags.innerHTML += \"<button accesskey=\\\"4\\\" onclick=\\\"tagwithOnlytag( range, '\"+String(selection)+\"', '".$taglistValue[2]."' )\\\">".$taglistValue[1]."</button>\";\n";
                        echo "tagging_tags.innerHTML += \"<button onclick=\\\"tagStringWithTag( '\"+String(selection)+\"', '".$taglistValue[2]."' )\\\">".$taglistValue[1]."(ALL)</button></br>\";\n";
                    } else {
                        echo "tagging_tags.innerHTML += \"<button onclick=\\\"tagwithOnlytag( range, '\"+String(selection)+\"', '".$taglistValue[2]."' )\\\">".$taglistValue[1]."</button>\";\n";
                        echo "tagging_tags.innerHTML += \"<button onclick=\\\"tagStringWithTag( '\"+String(selection)+\"', '".$taglistValue[2]."' )\\\">".$taglistValue[1]."(ALL)</button></br>\";\n";
                    } 
                }
                ?>

                newdiv.appendChild(tagging_tags);
                // add selected words to generator regex
                genRegexBySelection(newdiv, selection); // append button to newdiv and handle the selection words

            }

            //$('#tagItemDivId').addClass();  // tagItemDivId is newdiv's id
            $('body').append(newdiv);
            $('#TitletagType').val(lastAddTag);

            // selected some words, so hide popping up remove-tag-window
            pop_remove_tag_window = false;   // questionMarkID
        }
        catch(err){
            pop_remove_tag_window = true;   // questionMarkID
            
        }
    } else {
        // without selecting any word, so pop up remove-tag-window
        pop_remove_tag_window = true;
    }

    //e.stopPropagation();
});

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

    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);
    
    var hiddenField2 = document.createElement("input");      
    hiddenField2.setAttribute("name", "topic");
    hiddenField2.setAttribute("value", topic_id);
    form.appendChild(hiddenField2);

    var info = JSON.parse( '<?php echo json_encode($info) ?>');

    if (info) {
        var hiddenField = document.createElement("input");      
        hiddenField.setAttribute("name", "bookId");
        hiddenField.setAttribute("value", info['book_id']);
        form.appendChild(hiddenField);   

        var hiddenField = document.createElement("input");      
        hiddenField.setAttribute("name", "bookName");
        hiddenField.setAttribute("value", info['book_name']);
        form.appendChild(hiddenField);   
        
        var hiddenField = document.createElement("input");      
        hiddenField.setAttribute("name", "sectionName");
        hiddenField.setAttribute("value", info['section_name']);
        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(topic_id) {
    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");
    form.setAttribute("target", "_blank");
    
    var hiddenField = document.createElement("input");      
    hiddenField.setAttribute("name", "func");
    hiddenField.setAttribute("value", "exportFromExtractionInterface");
    form.appendChild(hiddenField); 

    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", "topic");
    hiddenField.setAttribute("value", topic_id);
    form.appendChild(hiddenField);

    _postForContineTagging(form);
   

    /*
    var section_id = JSON.parse('<?php echo json_encode($section_id) ?>');
    console.log("section_id: "+section_id+", topic_id: "+topic_id);

    var hiddenField = document.createElement("input");      
    hiddenField.setAttribute("name", "sectionId");
    hiddenField.setAttribute("value", section_id);
    form.appendChild(hiddenField);   
 
    var info = JSON.parse( '<?php echo json_encode($info) ?>');

    if (info) {
        var hiddenField = document.createElement("input");      
        hiddenField.setAttribute("name", "bookId");
        hiddenField.setAttribute("value", info['book_id']);
        form.appendChild(hiddenField);   

        var hiddenField = document.createElement("input");      
        hiddenField.setAttribute("name", "bookName");
        hiddenField.setAttribute("value", info['book_name']);
        form.appendChild(hiddenField);   
        
        var hiddenField = document.createElement("input");      
        hiddenField.setAttribute("name", "sectionName");
        hiddenField.setAttribute("value", info['section_name']);
        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(topic_id) {
    var el = document.getElementById("editable-area");
    var str= "" + el.innerHTML;
    var form = document.createElement("form");
    form.setAttribute("method", "post");
    form.setAttribute("action", "./ExportTable");//+section_id);  // hand to controller
    form.setAttribute("target", "_blank");
    
    var hiddenField = document.createElement("input");      
    hiddenField.setAttribute("name", "func");
    hiddenField.setAttribute("value", "exportFromExtractionInterface");
    form.appendChild(hiddenField); 
  


    var hiddenField = document.createElement("input");      
    hiddenField.setAttribute("name", "content");
    hiddenField.setAttribute("value", str);
    form.appendChild(hiddenField);

    var hiddenField = document.createElement("input");      
    hiddenField.setAttribute("name", "topic");
    hiddenField.setAttribute("value", topic_id);
    form.appendChild(hiddenField);

    _postForContineTagging(form);

}
// ===========

function tagwithOnlytag( range, stringSelection, tag ) {
    saveUndoText();
    var topic_tag = JSON.parse('<?php echo json_encode($topic_tag) ?>');
    var topic_tag2 = topic_tag+"2";

    range.deleteContents();

    if ( tag==topic_tag2) {
        var newdiv = document.createElement(topic_tag);
        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 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;")
}

function saveTextToLGService() {
    // clean editable-area
    $('.questionMarkClass').remove();
    $('.tagItemDivClass').remove();
 
    // -------------
    var info = JSON.parse('<?php echo json_encode($info) ?>');
    var topic_id = JSON.parse('<?php echo json_encode($default_topic_id) ?>');

    // if this is a new branch, ask for label
    // if (info['branch_id'] == 0) {
    if (info['branch_id'] == 0) {
        //var label = prompt("Please enter your label for this new branch", "section"+info['section_id']);
        var today = new Date();
        var dd = today.getDate();
        var mm = today.getMonth()+1; //January is 0!
        var yyyy = today.getFullYear();

        if(dd<10) {
            dd='0'+dd
        } 
        if(mm<10) {
            mm='0'+mm
        } 
        today = dd+'.'+mm+'.'+yyyy;
        var book_name = info['book_name'];
        var section_name = info['section_name'];
        var period = info['period'];

        var default_label = "";
        if (book_name == "" || section_name == "" || period == "") {
            default_label = today;
        } else {
            default_label = book_name+"("+cjst.chineseToPinyin(book_name).join(' ')+")_"+period+ "_"+section_name
                        + "("+ cjst.chineseToPinyin(section_name).join(' ') + ")_" + today;
        }
        

        var label = prompt("Please enter your label for this new branch", default_label);
        while (label == null) {
            alert("You haven't saved your editing.");
            return;
        }    
    };
    
    var form = document.createElement("form");
    form.setAttribute("method", "post");
    form.setAttribute("action", "./TaggingText");  // hand to controller
    form.setAttribute("target", "_self");
    
    var hiddenField = document.createElement("input");      
    hiddenField.setAttribute("name", "func");
    hiddenField.setAttribute("value", "SaveFullTextToLGService");
    form.appendChild(hiddenField); 
    

    var hiddenField = document.createElement("input");      
    hiddenField.setAttribute("name", "label");
    hiddenField.setAttribute("value", label);
    form.appendChild(hiddenField);
    
    var hiddenField = document.createElement("input");      
    hiddenField.setAttribute("name", "topic_id");
    hiddenField.setAttribute("value", topic_id);
    form.appendChild(hiddenField); 

    _postForContineTagging(form);

    console.log("complete saving to LGService");

}

function chooseTopic(default_topic_id) {
    var t = JSON.parse( '<?php echo json_encode($topiclistArray) ?>' );
    var info = JSON.parse('<?php echo json_encode($info) ?>');

    $('#load_topic_div').html("");
    var popup_status = $('#load_topic_div').css("display");
    if (popup_status == "block") {
        $('#load_topic_div').css("display", "none");
    } else {
        $('#load_topic_div').css("display", "block");
    }
    /*
    $('#load_topic_div').css("border", "1px solid black");
    $('#load_topic_div').css("background-color", "White");
    $('#load_topic_div').css("width", "200px");
    $('#load_topic_div').css("height", "50px");
    $('#load_topic_div').css("top", "20px");
    $('#load_topic_div').css("left", "-200px");
    */

    var topic_select = document.createElement("select");
    topic_select.id = "loadTopiclist";
    var selected_topic = t[0];
    topic_select.onchange = function(){

    	selected_topic = topic_select.options[topic_select.selectedIndex];
    	console.log(selected_topic.text);

    	var topic_id = selected_topic.value;

		var form = document.createElement("form");
        form.setAttribute("method", "post");
        form.setAttribute("action", "./TaggingText");  // hand to controller
        form.setAttribute("target", "_self");

        var hiddenField = document.createElement("input");      
        hiddenField.setAttribute("name", "topic");
        hiddenField.setAttribute("value", topic_id);
        form.appendChild(hiddenField);

        var hiddenField = document.createElement("input");      
        hiddenField.setAttribute("name", "func");
        hiddenField.setAttribute("value", "ContinueTagging");
        form.appendChild(hiddenField);
    
	    _postForContineTagging(form);
           
    };


    //Create and append the options
	for (var i = 0; i < t.length; i++) {
    	var option = document.createElement("option");
    	option.value = t[i]['id'];
	    option.text = t[i]['name_en']+" ("+t[i]['name_ch']+", "+t[i]['name_pinyin']+")";
	    if (option.value == default_topic_id) {
	    	option.selected = true;
	    };
	    topic_select.appendChild(option);
	}

    $('#load_topic_div').append(topic_select);

    var newbutton = document.createElement("button");
    $(newbutton).html("Close");
    $(newbutton).addClass("btn btn-xs btn-default");
    $(newbutton).attr("onclick", "$('#load_topic_div').css(\"display\", \"none\");");
    $('#load_topic_div').append(newbutton);
  
}

function _postForContineTagging(form) {
    var hiddenField = document.createElement("input");      
    hiddenField.setAttribute("name", "text");
    var el = document.getElementById("editable-area");
    var text = el.innerHTML;
    hiddenField.setAttribute("value", text);
    form.appendChild(hiddenField);

    // pass taglist
    var hiddenField = document.createElement("input");      
    hiddenField.setAttribute("name", "taglistArray");
    var taglistObj = JSON.parse('<?php echo json_encode($taglist_infile) ?>');
    // if taglist_infile == "" means the taglist in db is up-to-date, will use taglistArray to save to file

    if (!taglistObj) {
        // TODO: should pass the user-decided taglist to post['taglistArray']
        taglistObj = JSON.parse('<?php echo json_encode($taglistArray) ?>');
    }
    taglistArray = JSON.stringify(taglistObj);
    hiddenField.setAttribute("value", taglistArray);
    form.appendChild(hiddenField);

    // pass book_meta
    var hiddenField = document.createElement("input");      
    hiddenField.setAttribute("name", "book_meta");
    var book_metaObj = JSON.parse('<?php echo json_encode($book_meta) ?>');
    book_metaArray = JSON.stringify(book_metaObj);

    hiddenField.setAttribute("value", book_metaArray);
    form.appendChild(hiddenField);    


    var info = JSON.parse( '<?php echo json_encode($info) ?>');

    if (info) {
        if (info['file_id']) {
            var hiddenField = document.createElement("input");      
            hiddenField.setAttribute("name", "fileId");
            hiddenField.setAttribute("value", info['file_id']);
            form.appendChild(hiddenField);
        };
        if (info['branch_id']) {
            var hiddenField = document.createElement("input");      
            hiddenField.setAttribute("name", "branchId");
            hiddenField.setAttribute("value", info['branch_id']);
            form.appendChild(hiddenField);
        };
        if (info['user_id']) {
            var hiddenField = document.createElement("input");      
            hiddenField.setAttribute("name", "userId");
            hiddenField.setAttribute("value", info['user_id']);
            form.appendChild(hiddenField);
        };
        if (info['section_id']) {
            var hiddenField = document.createElement("input");      
            hiddenField.setAttribute("name", "sectionId");
            hiddenField.setAttribute("value", info['section_id']);
            form.appendChild(hiddenField);
        };
        if (info['book_id']) {
            var hiddenField = document.createElement("input");      
            hiddenField.setAttribute("name", "bookId");
            hiddenField.setAttribute("value", info['book_id']);
            form.appendChild(hiddenField);
        };
        if (info['section_name']) {
            var hiddenField = document.createElement("input");      
            hiddenField.setAttribute("name", "sectionName");
            hiddenField.setAttribute("value", info['section_name']);
            form.appendChild(hiddenField);
        };
        if (info['book_name']) {
            var hiddenField = document.createElement("input");      
            hiddenField.setAttribute("name", "bookName");
            hiddenField.setAttribute("value", info['book_name']);
            form.appendChild(hiddenField);
        };
        if (info['current_fileId']) {
            var hiddenField = document.createElement("input");      
            hiddenField.setAttribute("name", "currentFileId");
            hiddenField.setAttribute("value", info['current_fileId']);
            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 configTagsInTopic(topic_id) {
    var form = document.createElement("form");
    
    form.setAttribute("method", "post");
    form.setAttribute("action", "./ConfigTagsInTopic");  // hand to controller
    form.setAttribute("target", "_blank");
    
    var hiddenField = document.createElement("input");      
    hiddenField.setAttribute("name", "topic");
    hiddenField.setAttribute("value", topic_id);
    form.appendChild(hiddenField);

    _postForContineTagging(form);
    
        
}

$(document).on("change", '#smartRegexPopUpSelectWord', function (e) {
    var wordlistArray = JSON.parse('<?php echo json_encode($wordlistArray) ?>');

    for (var i = 0; i < wordlistArray.length; i++) {
        var wordlistValue = wordlistArray[i];   // wordlistValue is array(id, name, listString)
        if ($('#smartRegexPopUpSelectWord').val() == wordlistValue[0]) {    
            var textarea_text = $('#smartRegexPopUpText').val();
            // insert selected wordlist into textarea at cursor position
            var cursorPosition = $('#smartRegexPopUpText').prop("selectionStart");
            // cut textarea_text by cursorPosition
            var text_before_cursor = textarea_text.substring(0,cursorPosition);
            var text_after_cursor = textarea_text.substring(cursorPosition, textarea_text.length);

            // default length is 1, which means {1,1}
            $('#smartRegexPopUpText').val( text_before_cursor+"["+wordlistValue[2]+"]{1,1}"+text_after_cursor);
        }
    }
});


</script>


<!--
<fieldset class="info-board">
    <legend><h5 class="tool-topic" data-toggle="collapse" data-target="#info_board">Information <span class="caret"></span></h5></legend>
    <div id="info_board" class="collapse in">
        <div class="bg-danger"><strong><?php echo $messages['error']; ?> </strong></div>
        <div class="bg-warning"> <?php echo $messages['warning']; ?> 
            <button id="reloadTextButton" onclick="reloadText(<?php echo $default_topic_id; ?>)" style="display:none;">Latest Version</button>
        </div>
        <div class="bg-info"> <?php echo $messages['info']; ?> </div>
        <div class="bg-default"> <?php echo $messages['debug']; ?> </div>
    </div>
</fieldset>

-->

<div class="info-board">
    <div class="bg-danger"><strong><?php echo $messages['error']; ?> </strong></div>
    <div class="bg-warning"> <?php echo $messages['warning']; ?> 
        <button id="reloadTextButton" onclick="reloadText(<?php echo $default_topic_id; ?>)" style="display:none;">Latest Version</button>
    </div>
    <div class="bg-info"> <?php echo $messages['info']; ?> </div>
    <div class="bg-default"> <?php echo $messages['debug']; ?> </div>
</div>


<table border="1" style="margin:10 30 30 30; width:100%; max-width:1270px; min-width:680px">
    <tr>
        <td style="padding:0 5 0 5; margin: 0 5 0 5;">
            <div id="editable-area" class="area" style="max-width:980px; min-width:400px"><?php echo $stringInput; ?></div>
        </td>
        <td valign="top" style="min-width:280px; padding:0 5 0 5; margin:0 5 0 5;">
            <div id="popups" style="position:absolute; width:300px; ">
                <div id="load_topic_div" class="popup-topic popup-frame"></div>
                <div id="load_regex_div" class="popup-loadregex popup-frame"></div>
                <div id="regex_generator" class="popup-frame">
                    <h3>Gen Regex</h3>
                    <div>Pattern 1: 
                        <div id="regex_pattern1" class="bg-info"></div>
                    </div>
                    <div>Pattern 2:
                        <div id="regex_pattern2" class="bg-info"></div>
                    </div>
                    <div>Suggested Regex: 
                        <div id="generated_regex" class="bg-success"></div>
                    </div>
                    <button onclick="genRegexAddToSmartRegex()" class="btn btn-info">Add it to SmartRegex</button>
                    <button onclick="genRegexWindowClose()" class="btn btn-default">Close</button>
                    <div id="regex_generator_error_msg" class="bg-white"></div>
                </div>
                <div id="smartRegexPopUpDiv" class="popup-frame">
                    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()" class="btn btn-info">Add</button>
                    <button id="smartRegexPopUpEdit" onclick="replaceSmartEdit()" class="btn btn-success">Edit/Update</button>
                    <button id="smartRegexPopUpDel" onclick="replaceSmartDel()" class="btn btn-danger">Delete</button>
                    <button id="smartRegexPopUpBack" onclick="replaceSmartBack()" class="btn btn-default"><<</button>
                    <button id="smartRegexPopUpFor" onclick="replaceSmartFor()" class="btn btn-default">>></button>
                    <button onclick="replaceSmartClose()" class="btn btn-default" >Close</button>
                </div>
            </div>

            <div id="follow-scroll">
                <form action="javascript:void(0);">   
                    <fieldset class="tool-frame">
                        <legend><h5 class="tool-topic" data-toggle="collapse" data-target="#tool_topic"> Topic: <span class="caret"></span></h5></legend>
                        <div id="tool_topic" class="collapse in">
                            <div> Current topic is: <br> 
                                <?php echo $topic_name['name_en']; ?> 
                                (<?php echo $topic_name['name_ch']; ?>, <?php echo $topic_name['name_pinyin']; ?>)
                                <button onclick="chooseTopic(<?php echo $default_topic_id;?>)" class="btn btn-default btn-xs">Change</button>
                            </div>
                            <div>The topic tag is: <?php echo $topic_tag_ch;?>(<?php echo $topic_tag;?>)</div>
                            <button onclick="editTaglist(<?php echo $default_topic_id; ?>)" class="btn btn-default btn-block">Edit Tag List</button>
                            <button onclick="configTagsInTopic(<?php echo $default_topic_id;?>)" class="btn btn-default btn-block">Select Existing Tags</button>
                        </div>
                    </fieldset>

                    <fieldset class="tool-frame">
                        <legend><h5 class="tool-topic" data-toggle="collapse" data-target="#tool_regex"> Replace By <i><b>Smart Regex</b></i>©: <span class="caret"></span></h5></legend>
                        
                        <div id="tool_regex" class="collapse in">
                            <div id="smartRegexShowDiv"></div><br>
                            <!-- <button onclick="smartRegexNew()" class="btn-lg">Add Regex Group</button></br>
                            -->
                            <button onclick="smartRegexNew()" id="smart_regex_new_id" class="btn btn-default btn-block">Search by Patterns (Smart Regex)</button>

                            <button onclick="smartRegexLoad(<?php echo $default_topic_id; ?>)" class="btn btn-default">Load</button>
                            <button onclick="smartRegexSave(<?php echo $default_topic_id; ?>)" class="btn btn-default">Save</button>
                            <button onclick="smartRegexEmpty()" class="btn btn-default">Clear</button></br></br>


                            Range: <input type="text" size="5" id="regexPageStart">to<input type="text" size="5" id="regexPageEnd"><br>
                            <button onclick="replaceSmartRun()" class="btn btn-default btn-block">Run</button>
                            <button onclick="replaceSmartRunWithBr()" class="btn btn-default btn-block">Run(in new line)</button>
                            <!-- <button onclick="replaceSmartRunSpace()" class="btn-lg">Run(Allow space between Group)</button></br>
                            -->
                            <button onclick="replaceSmartRunSpace()" class="btn btn-default">Run(Allow space between block)</button></br>
                            <button onclick="Undo()" class="btn btn-default btn-block" id="buttonUndo" disabled="true">Undo</button>

                            <!-- developing...-->
                            <button onclick="genRegexWindowOpen()" id="gen_regex_window_open_id" class="btn btn-default">Open GenRegex(test)</button></br>
                        </div>
                    </fieldset>
                    

                    <?php
                    if ($default_topic_id == 1) {
                    ?>
                    <fieldset class="tool-frame">
                        <legend><h5 class="tool-topic" data-toggle="collapse" data-target="#tool_rule"> Tag by rule: <span class="caret"></span></h5></legend>
                        <div id="tool_rule" class="collapse out">
                            <button onclick="tagNameWithLastName()" class="btn btn-default">Tag Word Begin With Surname</button></br>
                            <button onclick="tagNameWithLastName2()" class="btn btn-default btn-sm">Tag Word Begin With</button> <input type="text" size="2" id="surname">
                        </div>
                        <!--<button onclick="tagTime()" style="height: 30px; width: 220px">Tag Time</button></br>-->
                        <!--<button onclick="tagBiogAddr()" style="height: 30px; width: 220px">Tag BiogAddr</button></br>-->
                    </fieldset>

                    <?php }?>
                                     
                    <fieldset class="tool-frame">
                        <legend><h5 class="tool-topic" data-toggle="collapse" data-target="#tool_edit"> Edit: <span class="caret"></span></h5></legend>
                        <!--<button onclick="cleanUpTextArea()" style="height: 30px; width: 220px">Reform the text</button></br>-->
                        <!-- save text in local. replaced by saveTextToLGService, which is also saving on copy in local in development stage -->
                        <!-- 
                        <button onclick="saveText(<?php echo $section_id; ?>)" style="height: 30px; width: 220px">Save the text</button></br>
                        -->
                        <div class="collapse out" id="tool_edit">
                            <button onclick="editText()" id="editTextId" class="btn btn-default btn-block">Edit the text</button>
                            <button onclick="window.open('./EditWordlist')" class="btn btn-default btn-block">Edit WordList</button>
                        </div>
                    </fieldset>
                    
                    <fieldset class="tool-frame">
                        <legend><h5 class="tool-topic" data-toggle="collapse" data-target="#tool_save"> Save and Export: <span class="caret"></span></h5></legend>
                        <div class="collapse in" id="tool_save">
                            <button onclick="saveTextToLGService()" id="save_text_to_LGService_id" class="btn btn-default btn-block">Save to LGService</button>
                            <button onclick="exportAll(<?php echo $default_topic_id;?>)" class="btn btn-default btn-block">Export All</button>
                            Page: <input type="text" size="5" id="exportPageStart">to<input type="text" size="5" id="exportPageEnd">
                            <button onclick="exportPage(<?php echo $default_topic_id;?>)" class="btn btn-default btn-sm">Export</button></br>
                        </div>
                    </fieldset>
                
                    <fieldset class="tool-frame">
                        <legend><h5 class="tool-topic" data-toggle="collapse" data-target="#tool_replace_by"> Replace By <i><b>Regex</b></i>: <span class="caret"></span></h5></legend>
                        <div class="collapse out" id="tool_replace_by">
                            Range: <input type="text" size="5" id="regexPageStart2">to<input type="text" size="5" id="regexPageEnd2"><br>
                            Regex: <input type="text" size="23" id="regexText"></br>
                            Replace: <input type="text" size="23" id="replaceText"><br>
                            <button onclick="replaceSmartRegex()" class="btn btn-default btn-sm">Replace!</button>
                        </div>
                    </fieldset>
                </form>
            </div>
        </td>
    </tr>

</table>




</body>

</html>