function talkform($section, $talkline, $limit = 10, $schema = false)
{
    require_once "lib/forms.php";
    global $REQUEST_URI, $session, $translation_namespace, $chatsonpage;
    if ($schema === false) {
        $schema = $translation_namespace;
    }
    tlschema("commentary");
    $jump = true;
    if (isset($session['user']['prefs']['nojump']) && $session['user']['prefs']['nojump'] == true) {
        $jump = false;
    }
    if ($jump && httpget('comment') && httppost('focus') == $section) {
        $focus = true;
    } else {
        $focus = false;
    }
    if (!isset($session['user']['prefs']['ucol'])) {
        $session['user']['prefs']['ucol'] = false;
    }
    if (translate_inline($talkline, $schema) != "says") {
        $tll = strlen(translate_inline($talkline, $schema)) + 11;
    } else {
        $tll = 0;
    }
    $req = buildcommentarylink("&comment=1");
    if ($jump) {
        $req .= "#commentaryjump_" . $section;
    }
    addnav("", $req);
    // *** AJAX CHAT MOD START ***
    output_notl("<form action=\"{$req}\" method='POST' autocomplete='false'>", true);
    $args1 = array("formline" => "<form action=\"{$req}\" id='commentaryform' method='post' autocomplete='false'", "section" => $section, "talkline" => $talkline, "schema" => $schema);
    // $args1 = modulehook("commentarytalkline",$args1);
    //rawoutput('<div id="commentaryformcontainer">');
    output_notl($args1['formline'] . ">", true);
    // *** AJAX CHAT MOD END ***
    global $fiveminuteload;
    if ($session['user']['prefs']['commentary_auto_update'] && !httpget('comscroll') && $fiveminuteload < 8) {
        $jsec = strtolower($section);
        $jsec = str_replace("_", "", $jsec);
        $jsec = str_replace("-", "", $jsec);
        $jsec = str_replace(",", "0", $jsec);
        //debug($jsec);
        previewfield("insertcommentary", $session['user']['name'], $talkline, true, array("size" => "30", "maxlength" => 255 - $tll), false, $jsec, $session['user']['prefs']['ucol'], $focus);
        rawoutput("<script type=\"text/javascript\">\r\n\t\t\tvar typetimelimit" . $jsec . " = 0;\r\n\t\t\tvar timebetween" . $jsec . " = 1500;\r\n\t\t\tvar oldchars" . $jsec . " = 'xxxxx';\r\n\t\t\tvar newchars" . $jsec . " = 'xxxxx';\r\n\t\t\tvar newchars" . $jsec . " = document.getElementById('input" . $jsec . "').value;\r\n\t\t\tvar oldchars" . $jsec . " = newchars" . $jsec . ";\r\n\t\t\tfunction typedisplay" . $jsec . "() {\r\n\t\t\t\ttypetimelimit" . $jsec . " ++;\r\n\t\t\t\tnewchars" . $jsec . " = document.getElementById('input" . $jsec . "').value;\r\n\t\t\t\t\r\n\t\t\t\tif (window.XMLHttpRequest){\r\n\t\t\t\t\t// code for IE7+, Firefox, Chrome, Opera, Safari\r\n\t\t\t\t\ttxmlhttp" . $jsec . "=new XMLHttpRequest();\r\n\t\t\t\t} else {\r\n\t\t\t\t\t// code for IE6, IE5\r\n\t\t\t\t\ttxmlhttp" . $jsec . "=new ActiveXObject(\"Microsoft.XMLHTTP\");\r\n\t\t\t\t}\r\n\t\t\t\ttxmlhttp" . $jsec . ".onreadystatechange=function(){\r\n\t\t\t\t\tif (txmlhttp" . $jsec . ".readyState==4 && txmlhttp" . $jsec . ".status==200 && typetimelimit" . $jsec . " < 600){\r\n\t\t\t\t\t\tdocument.getElementById(\"typedisplay" . $jsec . "\").innerHTML = txmlhttp" . $jsec . ".responseText;\r\n\t\t\t\t\t\tttimer" . $jsec . "=setTimeout(\"typedisplay" . $jsec . "()\",timebetween" . $jsec . ");\r\n\t\t\t\t\t\tttimeopen" . $jsec . " = typetimelimit" . $jsec . " * 2;\r\n\t\t\t\t\t\tttimeleft" . $jsec . " = 600 - ttimeopen" . $jsec . ";\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif (oldchars" . $jsec . ".length!=newchars" . $jsec . ".length){\r\n\t\t\t\t\ttxmlhttp" . $jsec . ".open(\"GET\",\"whostyping.php?section=" . $section . "&updateplayer=1\",true);\r\n\t\t\t\t} else {\r\n\t\t\t\t\ttxmlhttp" . $jsec . ".open(\"GET\",\"whostyping.php?section=" . $section . "&updateplayer=0\",true);\r\n\t\t\t\t}\r\n\t\t\t\ttxmlhttp" . $jsec . ".send();\r\n\t\t\t\toldchars" . $jsec . " = newchars" . $jsec . ";\r\n\t\t\t}\r\n\t\t\ttypedisplay" . $jsec . "();\r\n\t\t</script>");
    } else {
        if ($fiveminuteload >= 8) {
            output("Server load is currently too high for auto-update chat.  This will hopefully balance out in a few minutes.`n");
        }
        previewfield("insertcommentary", $session['user']['name'], $talkline, true, array("size" => "30", "maxlength" => 255 - $tll), false, false, $session['user']['prefs']['ucol']);
        //debug("System load too high at ".$fiveminuteload);
    }
    rawoutput("<input type='hidden' name='talkline' value='{$talkline}'>");
    rawoutput("<input type='hidden' name='schema' value='{$schema}'>");
    rawoutput("<input type='hidden' name='focus' value='{$section}'>");
    rawoutput("<input type='hidden' name='counter' value='{$session['counter']}'>");
    $session['commentcounter'] = $session['counter'];
    if ($section == "X") {
        $vname = getsetting("villagename", LOCATION_FIELDS);
        $iname = getsetting("innname", LOCATION_INN);
        $sections = commentarylocs();
        reset($sections);
        output_notl("<select name='section'>", true);
        while (list($key, $val) = each($sections)) {
            output_notl("<option value='{$key}'>{$val}</option>", true);
        }
        output_notl("</select>", true);
    } else {
        output_notl("<input type='hidden' name='section' value='{$section}'>", true);
    }
    $add = htmlentities(translate_inline("Add"), ENT_QUOTES, getsetting("charset", "ISO-8859-1"));
    // *** DRAGONBG.COM CORE PATCH START***
    output_notl("<input type='submit' class='button' value='{$add}'>\t", true);
    // *** DRAGONBG.COM CORE PATCH END***
    rawoutput("</form>");
    tlschema();
}
function talkform($section, $talkline, $limit = 10, $schema = false)
{
    require_once "lib/forms.php";
    global $REQUEST_URI, $session, $translation_namespace;
    if ($schema === false) {
        $schema = $translation_namespace;
    }
    tlschema("commentary");
    $jump = false;
    if (isset($session['user']['prefs']['nojump']) && $session['user']['prefs']['nojump'] == true) {
        $jump = true;
    }
    $counttoday = 0;
    if (substr($section, 0, 5) != "clan-") {
        $sql = "SELECT author FROM " . db_prefix("commentary") . " WHERE section='{$section}' AND postdate>'" . date("Y-m-d 00:00:00") . "' ORDER BY commentid DESC LIMIT {$limit}";
        $result = db_query($sql);
        while ($row = db_fetch_assoc($result)) {
            if ($row['author'] == $session['user']['acctid']) {
                $counttoday++;
            }
        }
        if (round($limit / 2, 0) - $counttoday <= 0 && getsetting('postinglimit', 1)) {
            if ($session['user']['superuser'] & ~SU_DOESNT_GIVE_GROTTO) {
                output("`n`)(You'd be out of posts if you weren't a superuser or moderator.)`n");
            } else {
                output("`n`)(You are out of posts for the time being.  Once some of your existing posts have moved out of the comment area, you'll be allowed to post again.)`n");
                return false;
            }
        }
    }
    if (translate_inline($talkline, $schema) != "says") {
        $tll = strlen(translate_inline($talkline, $schema)) + 11;
    } else {
        $tll = 0;
    }
    $req = comscroll_sanitize($REQUEST_URI) . "&comment=1";
    $req = str_replace("?&", "?", $req);
    if (!strpos($req, "?")) {
        $req = str_replace("&", "?", $req);
    }
    if ($jump) {
        $req .= "#{$section}";
    }
    addnav("", $req);
    // *** AJAX CHAT MOD START ***
    //output_notl("<form action=\"$req\" method='POST' autocomplete='false'>",true);
    $args1 = array("formline" => "<form action=\"{$req}\" id='commentaryform' method='post' autocomplete='false'", "section" => $section, "talkline" => $talkline, "schema" => $schema);
    $args1 = modulehook("commentarytalkline", $args1);
    rawoutput('<div id="commentaryformcontainer">');
    output_notl($args1['formline'] . ">", true);
    // *** AJAX CHAT MOD END ***
    previewfield("insertcommentary", $session['user']['name'], $talkline, true, array("size" => "40", "maxlength" => 200 - $tll));
    rawoutput("<input type='hidden' name='talkline' value='{$talkline}'>");
    rawoutput("<input type='hidden' name='schema' value='{$schema}'>");
    rawoutput("<input type='hidden' name='counter' value='{$session['counter']}'>");
    $session['commentcounter'] = $session['counter'];
    if ($section == "X") {
        $vname = getsetting("villagename", LOCATION_FIELDS);
        $iname = getsetting("innname", LOCATION_INN);
        $sections = commentarylocs();
        reset($sections);
        output_notl("<select name='section'>", true);
        while (list($key, $val) = each($sections)) {
            output_notl("<option value='{$key}'>{$val}</option>", true);
        }
        output_notl("</select>", true);
    } else {
        output_notl("<input type='hidden' name='section' value='{$section}'>", true);
    }
    $add = htmlentities(translate_inline("Add"), ENT_QUOTES, getsetting("charset", "ISO-8859-1"));
    // *** DRAGONBG.COM CORE PATCH START***
    output_notl("<input type='submit' class='button' value='{$add}'>\t", true);
    modulehook("commentarytrail", array());
    // *** DRAGONBG.COM CORE PATCH END***
    // *** AJAX CHAT MOD START ***
    //if (round($limit/2,0)-$counttoday < 3 && getsetting('postinglimit',1)){
    //	output("`)(You have %s posts left today)`n`0",(round($limit/2,0)-$counttoday));
    //}
    rawoutput("<div id='previewtext'></div></form>");
    rawoutput('</div>');
    // *** AJAX CHAT MOD END ***
    tlschema();
}
function getcommentary($section, $limit = 25, $talkline = "says", $commentid = 0)
{
    global $session, $REQUEST_URI, $doublepost, $translation_namespace, $counttoday;
    $textreturn = "";
    if ((int) getsetting("expirecontent", 180) > 0 && e_rand(1, 1000) == 1) {
        $sql = "DELETE FROM " . db_prefix("commentary") . " WHERE postdate<'" . date("Y-m-d H:i:s", strtotime("-" . getsetting("expirecontent", 180) . " days")) . "'";
        db_query($sql);
    }
    $sql = "SELECT COUNT(commentid) AS newadded FROM " . db_prefix("commentary") . " LEFT JOIN " . db_prefix("accounts") . " ON " . db_prefix("accounts") . ".acctid = " . db_prefix("commentary") . ".author WHERE section='{$section}' AND " . db_prefix("accounts") . ".locked=0 AND commentid > '{$commentid}'";
    $result = db_query($sql);
    $row = db_fetch_assoc($result);
    if ($row['newadded'] < 1) {
        return $commentid;
    }
    $newadded = $row['newadded'];
    $commentbuffer = array();
    //		if ($commentid == 0) {
    $sql = "SELECT " . db_prefix("commentary") . ".*, " . db_prefix("accounts") . ".name, " . db_prefix("accounts") . ".acctid, " . db_prefix("accounts") . ".clanrank, " . db_prefix("clans") . ".clanshort FROM " . db_prefix("commentary") . " LEFT JOIN " . db_prefix("accounts") . " ON " . db_prefix("accounts") . ".acctid = " . db_prefix("commentary") . ".author LEFT JOIN " . db_prefix("clans") . " ON " . db_prefix("clans") . ".clanid=" . db_prefix("accounts") . ".clanid WHERE " . ($section ? "section='{$section}' AND " : '') . "( " . db_prefix("accounts") . ".locked=0 OR " . db_prefix("accounts") . ".locked is null ) " . "AND commentid > '{$cid}' " . "ORDER BY commentid DESC LIMIT {$limit}";
    $result = db_query($sql);
    while ($row = db_fetch_assoc($result)) {
        $commentbuffer[] = $row;
    }
    /*		} else {
    			$sql = "SELECT " . db_prefix("commentary") . ".*, " .
    				db_prefix("accounts").".name, " . 
    				db_prefix("accounts").".login, " . 
    				db_prefix("accounts").".clanrank, " .
    				db_prefix("clans").".clanshort FROM " .
    				db_prefix("commentary") . " INNER JOIN " .
    				db_prefix("accounts") . " ON " .
    				db_prefix("accounts").".acctid = " .
    				db_prefix("commentary"). ".author LEFT JOIN " .
    				db_prefix("clans") . " ON " .
    				db_prefix("clans") . ".clanid=" .
    				db_prefix("accounts") .".clanid WHERE section = '$section' AND " .
    				db_prefix("accounts") . ".locked=0 AND commentid > '$commentid' ORDER BY commentid ASC LIMIT $limit";
    				$result = db_query($sql);
    				while ($row = db_fetch_assoc($result)) $commentbuffer[] = $row;
    				$commentbuffer = array_reverse($commentbuffer);
    		}
    */
    $rowcount = count($commentbuffer);
    if ($rowcount > 0) {
        $session['lastcommentid'] = $commentbuffer[0]['commentid'];
        $lastcommentid = $commentbuffer[0]['commentid'];
    }
    $counttoday = 0;
    for ($i = 0; $i < $rowcount; $i++) {
        $row = $commentbuffer[$i];
        $row['comment'] = comment_sanitize($row['comment']);
        $commentids[$i] = $row['commentid'];
        if (date("Y-m-d", strtotime($row['postdate'])) == date("Y-m-d")) {
            if ($row['name'] == $session['user']['name']) {
                $counttoday++;
            }
        }
        $x = 0;
        $ft = "";
        for ($x = 0; strlen($ft) < 5 && $x < strlen($row['comment']); $x++) {
            if (substr($row['comment'], $x, 1) == "`" && strlen($ft) == 0) {
                $x++;
            } else {
                $ft .= substr($row['comment'], $x, 1);
            }
        }
        $location = get_module_pref("location", "ajaxcommentary");
        if ($location) {
            $link = "bio.php?char=" . $row['author'] . "&ret=" . $location;
            addnav("", $link);
        } else {
            $link = '';
        }
        if (substr($ft, 0, 2) == "::") {
            $ft = substr($ft, 0, 2);
        } elseif (substr($ft, 0, 1) == ":") {
            $ft = substr($ft, 0, 1);
        } elseif (substr($ft, 0, 3) == "/me") {
            $ft = substr($ft, 0, 3);
        }
        $row['comment'] = holidayize($row['comment'], 'comment');
        $row['name'] = holidayize($row['name'], 'comment');
        $clanrankcolors = array(CLAN_APPLICANT => "`!", CLAN_MEMBER => "`#", CLAN_OFFICER => "`^", CLAN_LEADER => "`&", CLAN_FOUNDER => "`\$");
        if ($row['clanrank']) {
            $row['name'] = ($row['clanshort'] ? "{$clanrankcolors[$row['clanrank']]}&lt;`2{$row['clanshort']}{$clanrankcolors[$row['clanrank']]}&gt; `&" : "") . $row['name'];
        }
        if ($ft == "::" || $ft == "/me" || $ft == ":") {
            $x = strpos($row['comment'], $ft);
            if ($x !== false) {
                $op[$i] = str_replace("&amp;", "&", HTMLEntities(substr($row['comment'], 0, $x), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0" . ($link ? "<a href='{$link}' style='text-decoration: none'>\n" : "") . "`&{$row['name']}`0" . ($link ? "</a>" : "") . "\n`& " . str_replace("&amp;", "&", HTMLEntities(substr($row['comment'], $x + strlen($ft)), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`n";
                $rawc[$i] = str_replace("&amp;", "&", HTMLEntities(substr($row['comment'], 0, $x), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`&{$row['name']}`0`& " . str_replace("&amp;", "&", HTMLEntities(substr($row['comment'], $x + strlen($ft)), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`n";
            }
        }
        if ($ft == "/game" && !$row['name']) {
            $x = strpos($row['comment'], $ft);
            //if ($x!==false){
            $op[$i] = str_replace("&amp;", "&", htmlentities(substr($row['comment'], 0, $x), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`&" . str_replace("&amp;", "&", htmlentities(substr($row['comment'], $x + strlen($ft)), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`n";
            //}
        }
        if (!isset($op) || !is_array($op)) {
            $op = array();
        }
        if (!array_key_exists($i, $op) || $op[$i] == "") {
            $op[$i] = "`0" . ($link ? "<a href='{$link}' style='text-decoration: none'>\n" : "") . "`&{$row['name']}`0" . ($link ? "</a>" : "") . "`3 says, \"`#" . str_replace("&amp;", "&", HTMLEntities($row['comment'], ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`3\"`0`n";
            $rawc[$i] = "`&{$row['name']}`3 says, \"`#" . str_replace("&amp;", "&", HTMLEntities($row['comment'], ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`3\"`0`n";
        }
        if (!array_key_exists('timestamp', $session['user']['prefs'])) {
            $session['user']['prefs']['timestamp'] = 0;
        }
        if ($session['user']['prefs']['timestamp'] == 1) {
            if (!isset($session['user']['prefs']['timeformat'])) {
                $session['user']['prefs']['timeformat'] = "[m/d h:ia]";
            }
            $time = strtotime($row['postdate']) + $session['user']['prefs']['timeoffset'] * 60 * 60;
            $s = "`7" . date($session['user']['prefs']['timeformat'], $time) . "`0 ";
            $op[$i] = $s . $op[$i];
        } elseif ($session['user']['prefs']['timestamp'] == 2) {
            $s = reltime(strtotime($row['postdate']));
            $op[$i] = "`7({$s})`0 " . $op[$i];
        }
        if ($row['postdate'] >= $session['user']['recentcomments']) {
            $op[$i] = "<img src='images/new.gif' alt='&gt;' width='3' height='5' align='absmiddle'> " . $op[$i];
        }
        $auth[$i] = $row['author'];
        $rawc[$i] = full_sanitize($rawc[$i]);
        $rawc[$i] = htmlentities($rawc[$i], ENT_QUOTES, getsetting("charset", "ISO-8859-1"));
    }
    $outputcomments = array();
    $sect = "x";
    for (; $i > -1; $i--) {
        $out = "";
        $out .= $op[$i];
        if (!array_key_exists($sect, $outputcomments) || !is_array($outputcomments[$sect])) {
            $outputcomments[$sect] = array();
        }
        array_push($outputcomments[$sect], $out);
    }
    ksort($outputcomments);
    reset($outputcomments);
    $sections = commentarylocs();
    while (list($sec, $v) = each($outputcomments)) {
        reset($v);
        while (list($key, $val) = each($v)) {
            $args = array('commentline' => $val);
            $args = modulehook("viewcommentary", $args);
            $val = $args['commentline'];
            output_notl($val, true);
        }
    }
    return $lastcommentid;
}