function writeUser($_POST)
{
    # get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($div, "num", 1, 20, "Invalid Branch.");
    $v->isOk($username, "string", 1, 20, "Invalid user name.");
    $v->isOk($password, "string", 1, 20, "Invalid password.");
    //$v->isOk ($tool, "string", 1, 3, "Invalid tooltips selection.");
    if ($postype != 'P' && $postype != 'S') {
        $v->addError("", "Invalid POS user.");
    }
    $v->isOk($username, "string", 1, 20, "Invalid user name.");
    $username2 = str_replace(" ", "", $username);
    if (strlen($username) > strlen($username2)) {
        $v->addError("", "Error : user name must not contain spaces.");
    }
    $v->isOk($div, "num", 1, 20, "Invalid Branch.");
    $v->isOk($password, "string", 1, 20, "Invalid password.");
    if ($postype != 'P' && $postype != 'S') {
        $v->addError("", "Invalid POS user.");
    }
    if (isset($f1)) {
        $v->isOk($password2, "string", 1, 20, "Invalid password 2.");
        $v->pwMatch($password, $password2, "Passwords do not match.");
    }
    # display errors, if any
    if ($v->isError()) {
        $theseErrors = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $theseErrors .= "-" . $e["msg"] . "<br>";
        }
        $theseErrors = "<tr><td class=err colspan=2>{$theseErrors}</td></tr>\n\t\t<tr><td colspan=2><br></td></tr>";
        return enterUser($username, $postype, $manager == "Yes" ? true : false, $theseErrors);
        exit;
    }
    # connect to db
    db_connect();
    if (!isset($admin)) {
        $admin = 0;
    }
    if (isset($f2)) {
        # exit if user exists
        $sql = "SELECT username FROM users WHERE username='******'";
        $usrRslt = db_exec($sql) or errDie("Unable to check database for existing username.");
        if (pg_numrows($usrRslt) > 0) {
            return "User, {$username}, already exists in database.";
        }
        # get md5 hash of password
        $password = md5($password);
        if ($manager == "Yes") {
            $abo = 1000;
        } else {
            $abo = 0;
        }
        $sql = "INSERT INTO users (username, password, services_menu, admin,div, usertype,abo)\n\t\tVALUES ('{$username}', '{$password}', 'L', {$admin}, '{$div}', '{$postype}','{$abo}')";
        $nwUsrRslt = db_exec($sql) or errDie("Unable to add user to database.");
    } else {
        // update the admin variable
        db_exec("UPDATE users SET admin={$admin} WHERE username='******'");
    }
    $Sql = "DELETE FROM userscripts WHERE username='******'";
    $Ex = db_exec($Sql);
    $Sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', 'top_menu.php')";
    $Ex = db_exec($Sql) or errDie("Unable to add user to database.");
    $Sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', 'diary.php')";
    $Ex = db_exec($Sql) or errDie("Unable to add user to database.");
    $Sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', 'diary-day.php')";
    $Ex = db_exec($Sql) or errDie("Unable to add user to database.");
    $Sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', 'glodiary.php')";
    $Ex = db_exec($Sql) or errDie("Unable to add user to database.");
    $Sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', 'glodiary-day.php')";
    $Ex = db_exec($Sql) or errDie("Unable to add user to database.");
    $Sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', 'todo.php')";
    $Ex = db_exec($Sql) or errDie("Unable to add user to database.");
    $Sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', 'index_die.php')";
    $Ex = db_exec($Sql) or errDie("Unable to add user to database.");
    $Sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', 'index-services.php')";
    $Ex = db_exec($Sql) or errDie("Unable to add user to database.");
    $Sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', 'pos-invoice-new.php')";
    $Ex = db_exec($Sql) or errDie("Unable to add user to database.");
    $Sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', 'pos-slip.php')";
    $Ex = db_exec($Sql) or errDie("Unable to add user to database.");
    $Sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', 'pos-invoice-print.php')";
    $Ex = db_exec($Sql) or errDie("Unable to add user to database.");
    $Sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', 'index-sales.php')";
    $Ex = db_exec($Sql) or errDie("Unable to add user to database.");
    # status report
    $writeUser = "******" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width='50%'>\n        <tr><th>New user added to database</th></tr>\n        <tr class=datacell><td>New user, {$username}, was successfully added to Cubit.</td></tr>\n        </table>\n        <p>\n        <tr>\n        <table border=0 cellpadding='2' cellspacing='1'>\n        <tr><th>Quick Links</th></tr>\n        <tr bgcolor='#88BBFF'><td><a href='" . SELF . "'>Add another user</a></td></tr>\n        <tr bgcolor='#88BBFF'><td><a href='main.php'>Main Menu</a></td></tr>\n        </tr>";
    return $writeUser;
}
            $OUTPUT = confirmUser($_POST);
            break;
        case "write":
            $OUTPUT = writeUser($_POST);
            break;
        default:
            $OUTPUT = enterUser();
    }
} elseif (isset($_GET["err"])) {
    # get vars from _GET
    foreach ($_GET as $key => $value) {
        ${$key} = $value;
    }
    $OUTPUT = enterUser($username, $err);
} else {
    $OUTPUT = enterUser();
}
require "template.php";
##
# functions
##
# enter new user's details
function enterUser($username = "", $err = "")
{
    # connect to db
    db_connect();
    $enterUser = "******" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\r\n        <form action='" . SELF . "' method=post>\r\n        <input type=hidden name=key value=confirm>\r\n        {$err}\r\n        <tr><th>Field</th><th>Value</th></tr>\r\n        <tr class='bg-even'><td>Username</td><td><input type=text size=20 name=username value='{$username}'></td></tr>\r\n        <tr class='bg-odd'><td>Password</td><td><input type=password size=20 name=password> (MIN 6 Characters MAX 20 Characters)</td></tr>\r\n        <tr class='bg-even'><td>Confirm password</td><td><input type=password size=20 name=password2></td></tr>\r\n\r\n        <tr><td align=right colspan=2><input type=submit value='Confirm &raquo'></td></tr>\r\n        </form>\r\n        </table>\r\n        <p>\r\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\r\n\t<tr><th>Quick Links</th></tr>\r\n\t<script>document.write(getQuicklinkSpecial());</script>\r\n\t<tr class='bg-odd'><td><a href='main.php'>Main Menu</a></td></tr>\r\n\t</table>";
    return $enterUser;
}
# confirm entered info
function confirmUser($_POST)
function writeUser($_POST)
{
    # get vars
    extract($_POST);
    //	if(!isset($doneBtn))
    //	return confirmUser($_POST);
    # validate input
    require "libs/validate.lib.php";
    $v = new validate();
    $v->isOk($div, "num", 1, 20, "Invalid Branch.");
    $v->isOk($username, "string", 1, 20, "Invalid user name.");
    $v->isOk($password, "string", 1, 20, "Invalid password.");
    $v->isOk($tool, "string", 1, 3, "Invalid tooltips selection.");
    $v->isOk($ispos, "string", 1, 3, "Invalid POS user selection.");
    # display errors, if any
    if ($v->isError()) {
        $theseErrors = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $theseErrors .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $theseErrors .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $theseErrors;
    }
    # connect to db
    db_connect();
    if (!isset($admin)) {
        $admin = 0;
    }
    if (!isset($doneBtn) or $admin == "1") {
        if (isset($f2)) {
            # exit if user exists
            $sql = "SELECT username FROM users WHERE username = '******'";
            $usrRslt = db_exec($sql) or errDie("Unable to check cubit for existing username.");
            if (pg_numrows($usrRslt) > 0) {
                return "\n\t\t\t\t\t<li class='err'>User, {$username}, already exists in cubit.</li>\n\t\t\t\t\t<br>\n\t\t\t\t\t" . mkQuickLinks(ql("admin-usradd.php", "Add New User"));
            }
            # get md5 hash of password
            $password = md5($password);
            $sql = "\n\t\t\t\tINSERT INTO users (\n\t\t\t\t\tusername, password, services_menu, admin, locale, div, help, empnum, payroll_groups\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$username}', '{$password}', 'L', {$admin}, '{$locale}', '{$div}', '{$tool}', '{$empnum}', '" . implode(",", $payroll_group) . "'\n\t\t\t\t)";
            $nwUsrRslt = db_exec($sql) or errDie("Unable to add user to cubit.");
        } else {
            // update the admin variable
            db_exec("UPDATE users SET admin = '{$admin}' WHERE username='******'");
        }
    }
    #remove all entries for seleted department ...
    $get_dept_scripts = "SELECT script FROM deptscripts WHERE dept = '{$old_dept}'";
    $run_dept_scripts = db_exec($get_dept_scripts) or errDie("Unable to get department script information.");
    if (pg_numrows($run_dept_scripts) < 1) {
        #no scripts for this department
    } else {
        while ($ddarr = pg_fetch_array($run_dept_scripts)) {
            $Sql = "DELETE FROM userscripts WHERE username='******' AND script = '{$ddarr['script']}'";
            $Ex = db_exec($Sql) or errDie("Unable to clear old user script permissions.");
        }
    }
    if ($ispos == "No") {
        $Sql = "DELETE FROM userscripts WHERE username = '******'";
        //		$Ex = db_exec($Sql);
        $Sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', 'top_menu.php')";
        $Ex = db_exec($Sql) or errDie("Unable to add user to cubit.");
        $Sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', 'diary.php')";
        $Ex = db_exec($Sql) or errDie("Unable to add user to cubit.");
        $Sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', 'diary-day.php')";
        $Ex = db_exec($Sql) or errDie("Unable to add user to cubit.");
        $Sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', 'glodiary.php')";
        $Ex = db_exec($Sql) or errDie("Unable to add user to cubit.");
        $Sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', 'glodiary-day.php')";
        $Ex = db_exec($Sql) or errDie("Unable to add user to cubit.");
        $Sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', 'todo.php')";
        $Ex = db_exec($Sql) or errDie("Unable to add user to cubit.");
        $Sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', 'index_die.php')";
        $Ex = db_exec($Sql) or errDie("Unable to add user to cubit.");
        $Sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', 'index-services.php')";
        $Ex = db_exec($Sql) or errDie("Unable to add user to cubit.");
        # write permissions
        if (isset($perm)) {
            foreach ($perm as $key => $value) {
                $sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', '{$value}')";
                $nwUsrRslt = db_exec($sql) or errDie("Unable to add user to cubit.");
            }
        }
        if (isset($deps)) {
            foreach ($deps as $key => $value) {
                $sql = "SELECT script FROM deptscripts WHERE dept = '{$key}'";
                $depRs = db_exec($sql);
                while ($depscr = pg_fetch_array($depRs)) {
                    $sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', '{$depscr['script']}')";
                    $nwUsrRslt = db_exec($sql) or errDie("Unable to add user to cubit.");
                }
            }
        }
        if (isset($depsrem)) {
            foreach ($depsrem as $key => $value) {
                $sql = "SELECT script FROM deptscripts WHERE dept = '{$key}'";
                $depRs = db_exec($sql);
                while ($depscr = pg_fetch_array($depRs)) {
                    $sql = "DELETE FROM userscripts WHERE username='******' AND script='{$depscr['script']}'";
                    $nwUsrRslt = db_exec($sql) or errDie("Unable to add user to cubit.");
                }
            }
        }
    } else {
        $Sql = "DELETE FROM userscripts WHERE username='******'";
        //		$Ex = db_exec($Sql);
        $Sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', 'top_menu.php')";
        $Ex = db_exec($Sql) or errDie("Unable to add user to cubit.");
        $Sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', 'diary.php')";
        $Ex = db_exec($Sql) or errDie("Unable to add user to cubit.");
        $Sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', 'diary-day.php')";
        $Ex = db_exec($Sql) or errDie("Unable to add user to cubit.");
        $Sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', 'glodiary.php')";
        $Ex = db_exec($Sql) or errDie("Unable to add user to cubit.");
        $Sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', 'glodiary-day.php')";
        $Ex = db_exec($Sql) or errDie("Unable to add user to cubit.");
        $Sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', 'todo.php')";
        $Ex = db_exec($Sql) or errDie("Unable to add user to cubit.");
        $Sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', 'index_die.php')";
        $Ex = db_exec($Sql) or errDie("Unable to add user to cubit.");
        $Sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', 'index-services.php')";
        $Ex = db_exec($Sql) or errDie("Unable to add user to cubit.");
        $Sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', 'pos-invoice-new.php')";
        $Ex = db_exec($Sql) or errDie("Unable to add user to cubit.");
        $Sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', 'pos-slip.php')";
        $Ex = db_exec($Sql) or errDie("Unable to add user to cubit.");
        $Sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', 'pos-invoice-print.php')";
        $Ex = db_exec($Sql) or errDie("Unable to add user to cubit.");
        $Sql = "INSERT INTO userscripts (username, script) VALUES ('{$username}', 'index-sales.php')";
        $Ex = db_exec($Sql) or errDie("Unable to add user to cubit.");
    }
    //	if(isset($doneBtn)){
    //		$get_real_scripts = "SELECT distinct(script) FROM userscripts WHERE username = '******'";
    //		$run_real_scripts = db_exec($get_real_scripts) or errDie ("Unable to get script information.");
    //		if(pg_numrows($run_real_scripts) < 1){
    //			return "No Scripts Permission For This User Found.";
    //		}
    //		$remove_all_temp = "DELETE FROM userscripts WHERE username = '******'";
    //		$run_remove_temp = db_exec($remove_all_temp) or errDie ("Unable to remove temporary permission files.");
    //
    //		while ($sc_arr = pg_fetch_array ($run_real_scripts)){
    //			$insert_this_perm = "INSERT INTO userscripts (username,script) VALUES ('$username', '$sc_arr[script]')";
    //			$run_insert_perm = db_exec($insert_this_perm) or errDie ("Unable to update permission information.");
    //		}
    //	}
    if (!isset($doneBtn)) {
        return confirmUser($_POST);
    }
    # status report
    $writeUser = "******" . TMPL_tblDflts . " width='50%'>\n\t\t\t<tr>\n\t\t\t\t<th>New user added to cubit</th>\n\t\t\t</tr>\n\t\t\t<tr class='datacell'>\n\t\t\t\t<td>New user, {$username}, was successfully added to Cubit.</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table border='0' cellpadding='2' cellspacing='1'>\n\t\t\t<tr>\n\t\t\t\t<th>Quick Links</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='admin-usradd.php'>Add another user</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return enterUser($username, "<li class='yay'>Successfully added {$username}</li><br>");
    return $writeUser;
}