function write()
{
    extract($_REQUEST);
    if ($page_option == "Edit") {
        $sql = "UPDATE cubit.diary_locations SET location='{$location}'\n\t\tWHERE id='{$id}'";
    } else {
        $sql = "INSERT INTO cubit.diary_locations (location) VALUES ('{$location}')";
    }
    db_exec($sql) or errDie("Unable to save location.");
    if (frmupdate_passon()) {
        $newlist = new dbSelect("diary_locations", "cubit");
        $newlist->run();
        $a = array();
        if ($newlist->num_rows() > 0) {
            while ($row = $newlist->fetch_array()) {
                $a[$row["id"]] = "{$row['location']}";
            }
        }
        $js = frmupdate_exec(array($a), true);
    } else {
        $js = "";
    }
    $OUTPUT = "{$js}\n\t<h3>{$page_option} Location</h3>\n\t<table cellpadding='2' cellspacing='0' class='shtable'>\n\t\t<tr>\n\t\t\t<th>Write</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Successfully saved location.</td>\n\t\t</tr>\n\t</table>";
    return $OUTPUT;
}
function confirm($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($department, "string", 0, 50, "Invalid department.");
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>{$e['msg']}</li>";
        }
        return $confirm . "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>\n\t\t\t\t<p>\n\t\t\t\t<table " . TMPL_tblDflts . " width='100'>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><a href='empdepartment-view.php'>View Employee Departments</a></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t</form>\n\t\t\t\t</table>";
    }
    // Layout
    $confirm = "\n\t\t<h3>Add Employee Department</h3>\n\t\t<h4>Confirm entry</h4>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t" . frmupdate_passon() . "\n\t\t\t<input type='hidden' name='key value='write'>\n\t\t\t<input type='hidden' name='department' value='{$department}'>\n\t\t\t<tr>\n\t\t\t\t<th width='40%'>Field</th>\n\t\t\t\t<th width='60%'>Value</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Department</td>\n\t\t\t\t<td>{$department}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td align='right'><input type='button' value='&laquo Back' onClick='javascript:history.back()'></td>\n\t\t\t\t<td align='left'><input type='submit' value='Confirm &raquo'></td>\n\t\t\t</tr>\n\t\t</form>\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . " width='100'>\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='empdepartment-view.php'>View Employee Departments</a></td></tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $confirm;
}
function write()
{
    extract($_REQUEST);
    if ($page_option == "Edit") {
        $sql = "UPDATE cubit.todo_main SET title='{$title}', team_id='{$team_id}'\n\t\tWHERE id='{$id}' AND user_id='" . USER_ID . "'";
    } else {
        $sql = "INSERT INTO cubit.todo_main (title, user_id, team_id)\n\t\tVALUES ('{$title}', '" . USER_ID . "', '{$team_id}')";
    }
    db_exec($sql) or errDie("Unable to save main todo.");
    if (frmupdate_passon()) {
        $newlist = new dbSelect("todo_main", "cubit");
        $newlist->run();
        // are we an admin?
        $sql = "SELECT admin FROM cubit.users WHERE userid='" . USER_ID . "'";
        $admin_rslt = db_exec($sql) or errDie("Unable to check for admin.");
        $admin = pg_fetch_result($admin_rslt, 0);
        $a = array();
        if ($newlist->num_rows() > 0) {
            $a[0] = "[None]";
            while ($row = $newlist->fetch_array()) {
                if (in_team(USER_ID, $row["team_id"])) {
                    $sql = "SELECT * FROM cubit.todo_main WHERE id='{$row['id']}'";
                    $tm_rslt = db_exec($sql) or errDie("Unable to retrieve todo.");
                    $count = pg_num_rows($tm_rslt);
                    $a[$row["id"]] = "{$row['title']} ({$count})";
                } else {
                    continue;
                }
            }
        }
        $js = frmupdate_exec(array($a), true);
    } else {
        $js = "";
    }
    $OUTPUT = "{$js}\n\t<h3>{$page_option} Main Todo</h3>\n\t<table cellpadding='2' cellspacing='0' class='shtable'>\n\t\t<tr>\n\t\t\t<th>Write</th>\n\t\t</tr>\n\t\t<tr class='odd'><td>Successfully saved the main todo.</td></tr>\n\t</table>";
    return $OUTPUT;
}
function write($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($classcode, "string", 1, 255, "Invalid Classification code.");
    $v->isOk($classname, "string", 1, 255, "Invalid Classification name.");
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirmCust .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirmCust;
    }
    # check stock code
    db_connect();
    $sql = "SELECT classcode FROM stockclass WHERE lower(classcode) = lower('{$classcode}') AND div = '" . USER_DIV . "'";
    $cRslt = db_exec($sql);
    if (pg_numrows($cRslt) > 0) {
        $error = "<li class='err'> A Classification with code : <b>{$classcode}</b> already exists.</li>";
        $error .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # connect to db
    db_connect();
    # write to db
    $sql = "INSERT INTO stockclass(classcode, classname, div) VALUES ('{$classcode}', '{$classname}', '" . USER_DIV . "')";
    $catRslt = db_exec($sql) or errDie("Unable to add class to system.", SELF);
    if (pg_cmdtuples($catRslt) < 1) {
        return "<li class='err'>Unable to add classname to database.</li>";
    }
    if (frmupdate_passon()) {
        $newlst = new dbSelect("stockclass", "cubit", grp(m("cols", "clasid, classname"), m("where", "div='" . USER_DIV . "'"), m("order", "classname ASC")));
        $newlst->run();
        $a = array();
        if ($newlst->num_rows() > 0) {
            while ($row = $newlst->fetch_array()) {
                $a[$row["clasid"]] = $row["classname"];
            }
        }
        $js = frmupdate_exec(array($a), true);
    } else {
        $js = "";
    }
    $write = "\n\t\t\t\t{$js}\n\t\t\t\t<table " . TMPL_tblDflts . " width='50%'>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Classification added to system</th>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>New Classification <b>{$classname}</b>, has been successfully added to the system.</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t\t<p>\n\t\t\t\t<table border=0 cellpadding='2' cellspacing='1'>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><a href='stockclass-view.php'>View Classifications</a></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><a href='main.php'>Main Menu</a></td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>";
    return $write;
}
function write($_POST)
{
    # get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($catcod, "string", 0, 50, "Invalid category code.");
    $v->isOk($cat, "string", 1, 255, "Invalid stock category name.");
    $v->isOk($descript, "string", 0, 100, "Invalid stock category descripting.");
    # Display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class=err>{$e['msg']}</li>";
        }
        $confirm .= "</li><p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>\n\t\t\t\t<P>\n\t\t\t\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=100>\n\t\t\t\t<tr><th>Quick Links</th></tr>\n\t\t\t\t\t<tr class='bg-even'><td><a href='stockcat-view.php'>View Stock Category</a></td></tr>\n\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t</form>\n\t\t\t\t</table>";
        return $confirm;
    }
    # check stock code
    db_connect();
    $sql = "SELECT catcod FROM stockcat WHERE lower(catcod) = lower('{$catcod}') AND div = '" . USER_DIV . "'";
    $cRslt = db_exec($sql);
    if (pg_numrows($cRslt) > 0) {
        $error = "<li class=err> A Category with code : <b>{$catcod}</b> already exists.</li>";
        $error .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        //return $error;
    }
    // insert into stock
    db_connect();
    $sql = "INSERT INTO stockcat(catcod, cat, descript, div) VALUES('{$catcod}', '{$cat}', '{$descript}', '" . USER_DIV . "')";
    $rslt = db_exec($sql) or errDie("Unable to insert stock category to Cubit.", SELF);
    if (frmupdate_passon()) {
        $newlst = new dbSelect("stockcat", "cubit", grp(m("cols", "catid, catcod, cat"), m("where", "div='" . USER_DIV . "'"), m("order", "cat ASC")));
        $newlst->run();
        $a = array();
        if ($newlst->num_rows() > 0) {
            while ($row = $newlst->fetch_array()) {
                $a[$row["catid"]] = "({$row['catcod']}) {$row['cat']}";
            }
        }
        $js = frmupdate_exec(array($a), true);
    } else {
        $js = "";
    }
    $write = "\n\t{$js}\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width='50%'>\n\t\t<tr><th>New Stock Category added to database</th></tr>\n\t\t<tr class=datacell><td>New Stock Category, {$cat} ({$catcod}) has been successfully added to Cubit.</td></tr>\n\t</table>\n\t<p>\n\t<table border=0 cellpadding='2' cellspacing='1'>\n\t\t<tr><th>Quick Links</th></tr>\n\t\t<tr class='bg-even'><td><a href='stockcat-view.php'>View Stock Category</a></td></tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $write;
}
function printCust()
{
    global $_SESSION;
    extract($_REQUEST);
    if (!isset($action)) {
        $action = "listcust";
    }
    /* session var prefix */
    $SPRE = "custview_";
    /* max number of customers in list */
    if (isset($viewall_cust)) {
        $offset = 0;
        define("ACT_SHOW_LIMIT", 2147483647);
    } else {
        define("ACT_SHOW_LIMIT", SHOW_LIMIT);
    }
    if (!isset($fval) && isset($_SESSION["{$SPRE}fval"])) {
        $fval = $_SESSION["{$SPRE}fval"];
    }
    if (!isset($filter) && isset($_SESSION["{$SPRE}filter"])) {
        $filter = $_SESSION["{$SPRE}filter"];
    }
    if (!isset($all) && isset($_SESSION["{$SPRE}all"]) && !isset($filter) && !isset($fval)) {
        $all = $_SESSION["{$SPRE}all"];
    }
    if (isset($filter) && isset($fval) && !isset($all)) {
        if (strlen($filter) > 0) {
            if ($filter == "all") {
                $sqlfilter = " AND (lower(accno) LIKE lower('%{$fval}%') OR lower(surname) LIKE lower('%{$fval}%') OR lower(paddr1) LIKE lower('%{$fval}%') OR lower(addr1) LIKE lower('%{$fval}%') OR lower(del_addr1) LIKE lower('%{$fval}%') OR lower(bustel) LIKE lower('%{$fval}%') OR lower(email) LIKE lower('%{$fval}%') OR lower(vatnum) LIKE lower('%{$fval}%') OR lower(contname) LIKE lower('%{$fval}%') OR lower(tel) LIKE lower('%{$fval}%') OR lower(cellno) LIKE lower('%{$fval}%') OR lower(fax) LIKE lower('%{$fval}%') OR lower(url) LIKE lower('%{$fval}%') OR lower(comments) LIKE lower('%{$fval}%') OR lower(bankname) LIKE lower('%{$fval}%') OR lower(branname) LIKE lower('%{$fval}%') OR lower(brancode) LIKE lower('%{$fval}%') OR lower(bankaccno) LIKE lower('%{$fval}%') OR lower(bankaccname) LIKE lower('%{$fval}%') OR lower(bankacctype) LIKE lower('%{$fval}%'))";
            } else {
                $sqlfilter = " AND lower({$filter}) LIKE lower('%{$fval}%')";
            }
        } else {
            $sqlfilter = "";
        }
        if (isset($_SESSION["{$SPRE}all"])) {
            unset($_SESSION["{$SPRE}all"]);
        }
        $_SESSION["{$SPRE}fval"] = $fval;
        $_SESSION["{$SPRE}filter"] = $filter;
    } else {
        if (isset($_SESSION["{$SPRE}fval"])) {
            unset($_SESSION["{$SPRE}fval"]);
        }
        if (isset($_SESSION["{$SPRE}filter"])) {
            unset($_SESSION["{$SPRE}filter"]);
        }
        $filter = "";
        $fval = "";
        $_SESSION["{$SPRE}all"] = "true";
        $sqlfilter = "";
    }
    $filterarr = array("all" => "Detailed", "surname" => "Company/Name", "init" => "Initials", "accno" => "Account Number", "deptname" => "Department", "category" => "Category", "class" => "Classification");
    $filtersel = extlib_cpsel("filter", $filterarr, $filter, "onChange='applyFilter();'");
    if (isset($export)) {
        $pure = true;
    } else {
        $pure = false;
    }
    if (!$pure) {
        # Set up table to display in
        $printCust_begin = "\n\t    <h3>" . (isset($findcust) ? "Find" : "Current") . " Customers</h3>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t<input type='hidden' name='action' value='{$action}' />\n\t\t<tr>\n\t\t\t<th>.: Filter :.</th>\n\t\t\t<th colspan='2'>.: Search :.</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>{$filtersel}</td>\n\t\t\t<td><input type='text' size='20' id='fval' value='{$fval}'></td>\n\t\t\t<td align='center'><input type='button' value='Search' onClick='applyFilter();' /></td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td align='center'><input type='button' name='all' value='View All' onClick='viewAll();' /></td>\n\t\t</tr>\n\t\t</table>\n\t\t<script>\n\t\t\t/* CRM CODE */\n\t\t\tfunction updateAccountInfo(id, name) {\n\t\t\t\twindow.opener.document.frm_con.accountname.value=name;\n\t\t\t\twindow.opener.document.frm_con.account_id.value=id;\n\t\t\t\twindow.opener.document.frm_con.account_type.value='Customer';\n\t\t\t\twindow.close();\n\t\t\t}\n\n\t\t\t/* AJAX filter code */\n\t\t\tfunction viewAll() {\n\t\t\t\tajaxRequest('" . SELF . "', 'cust_list', AJAX_SET, 'all=t');\n\t\t\t}\n\n\t\t\tfunction applyFilter() {\n\t\t\t\tfilter = getObject('filter').value;\n\t\t\t\tfval = getObject('fval').value;\n\n\t\t\t\tajaxRequest('" . SELF . "', 'cust_list', AJAX_SET, 'filter=' + filter + '&fval=' + fval);\n\t\t\t}\n\n\t\t\tfunction updateOffset(noffset, viewall) {\n\t\t\t\tif (viewall && !noffset) {\n\t\t\t\t\tajaxRequest('" . SELF . "', 'cust_list', AJAX_SET, 'viewall_cust=t');\n\t\t\t\t} else {\n\t\t\t\t\tajaxRequest('" . SELF . "', 'cust_list', AJAX_SET, 'offset=' + noffset);\n\t\t\t\t}\n\t\t\t}\n\t\t</script>\n\t\t<p>\n\t\t<div id='cust_list'>";
    } else {
        $printCust_begin = "";
    }
    /* FIND CUSTOMER START */
    if (!isset($findcust)) {
        $ajaxCust = "";
        if (!$pure) {
            $ajaxCust .= "\n\t\t<form action='statements-email.php' method='get'>\n\t\t<input type='hidden' name='key' value='confirm' />";
        }
        if (!isset($offset) && isset($_SESSION["{$SPRE}offset"])) {
            $offset = $_SESSION["{$SPRE}offset"];
        } else {
            if (!isset($offset)) {
                $offset = 0;
            }
        }
        $_SESSION["{$SPRE}offset"] = $offset;
        # connect to database
        db_connect();
        # counting the number of possible entries
        $sql = "SELECT * FROM customers\n    \t\tWHERE (div = '" . USER_DIV . "' OR  ddiv = '" . USER_DIV . "') {$sqlfilter}\n    \t\tORDER BY surname ASC";
        $rslt = db_exec($sql) or errDie("Error counting matching customers.");
        $custcount = pg_num_rows($rslt);
        # Query server
        $tot = 0;
        $totoverd = 0;
        $i = 0;
        if (!isset($ajaxCust)) {
            $ajaxCust = "";
        }
        /* view offsets */
        if ($offset > 0) {
            $poffset = $offset >= ACT_SHOW_LIMIT ? $offset - ACT_SHOW_LIMIT : 0;
            $os_prev = "<a class='nav' href='javascript: updateOffset(\"{$poffset}\");'>Previous</a>";
        } else {
            $os_prev = "&nbsp;";
        }
        if ($offset + ACT_SHOW_LIMIT > $custcount) {
            $os_next = "&nbsp;";
        } else {
            $noffset = $offset + ACT_SHOW_LIMIT;
            $os_next = "<a class='nav' href='javascript: updateOffset(\"{$noffset}\");'>Next</a>";
        }
        if ($os_next != "&nbsp;" || $os_prev != "&nbsp;") {
            $os_viewall = "| <a class='nav' href='javascript: updateOffset(false, true);'>View All</a>";
        } else {
            $os_viewall = "";
        }
        $ajaxCust .= "\n\t<table " . TMPL_tblDflts . ">\n\t<tr>\n\t\t<td colspan='20'>\n\t\t<table width='100%' border='0'>\n\t\t<tr>\n\t\t\t<td align='right' width='50%'>{$os_prev}</td>\n\t\t\t<td align='left' width='50%'>{$os_next} {$os_viewall}</td>\n\t\t</tr>\n\t\t</table>\n\t\t</td>\n\t</tr>\n\t<tr>\n\t\t<th>Acc no.</th>\n\t\t<th>Company/Name</th>\n\t\t<th>Tel</th>\n\t\t<th>Category</th>\n\t\t<th>Class</th>\n\t\t<th colspan='2'>Balance</th>\n\t\t<th>Overdue</th>\n\t\t" . ($pure ? "" : "<th colspan='11'>Options</th>") . "\n\t</tr>";
        /* query object for cashbook */
        $cashbook = new dbSelect("cashbook", "cubit");
        $custRslt = new dbSelect("customers", "cubit", grp(m("where", "(div ='" . USER_DIV . "' or ddiv='" . USER_DIV . "') {$sqlfilter}"), m("order", "surname ASC"), m("offset", $offset), m("limit", ACT_SHOW_LIMIT)));
        $custRslt->run();
        if ($custRslt->num_rows() < 1) {
            $ajaxCust .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='20'><li>There are no Customers matching the criteria entered.</li></td>\n\t\t</tr>";
        } else {
            while ($cust = $custRslt->fetch_array()) {
                if (!user_in_team($cust["team_id"], USER_ID)) {
                    continue;
                }
                # Check type of age analisys
                if (div_isset("DEBT_AGE", "mon")) {
                    $overd = ageage($cust['cusnum'], $cust['overdue'] / 30 - 1, $cust['location']);
                } else {
                    $overd = age($cust['cusnum'], $cust['overdue'] - 1, $cust['location']);
                }
                if ($overd < 0) {
                    $overd = 0;
                }
                if ($overd > $cust['balance']) {
                    $overd = $cust['balance'];
                }
                if ($cust["location"] == "int") {
                    $cur = qryCurrency($cust["fcid"], "rate");
                    $rate = $cur["rate"];
                    if ($rate != 0) {
                        $totoverd += $overd * $rate;
                    } else {
                        $totoverd += $overd;
                    }
                } else {
                    $totoverd += $overd;
                }
                if (!$pure) {
                    /* check if customer may be removed */
                    $cashbook->setOpt(grp(m("where", "cusnum='{$cust['cusnum']}' AND banked='no' AND div='" . USER_DIV . "'")));
                    $cashbook->run();
                    if ($cashbook->num_rows() <= 0 && $cust['balance'] == 0) {
                        $rm = "<td><a href='cust-rem.php?cusnum={$cust['cusnum']}'>Remove</a></td>";
                    } else {
                        $rm = "<td></td>";
                    }
                }
                if (strlen(trim($cust['bustel'])) < 1) {
                    $cust['bustel'] = $cust['tel'];
                }
                $cust['balance'] = sprint($cust['balance']);
                if ($cust["location"] == "int") {
                    if ($rate != 0.0) {
                        $tot = $tot + $cust['fbalance'] * $rate;
                    } else {
                        $tot = $tot + $cust['balance'];
                    }
                } else {
                    $tot = $tot + $cust['balance'];
                }
                /* determine which template to use when printing customer invoices */
                if (templateScript("invoices") != "pdf/cust-pdf-print-invoices.php") {
                    $template = "pdf/pdf-tax-invoice.php?type=cusprintinvoices";
                } else {
                    $template = "pdf/pdf-tax-invoice.php?type=cusprintinvoices";
                }
                $inv = "";
                $inv = "\n\t\t\t<td>\n\t\t\t\t<a href='{$template}&cusnum={$cust['cusnum']}' target='_blank'>Print Invoices</a>\n\t\t\t</td>";
                # Locations drop down
                $locs = array("loc" => "Local", "int" => "International", "" => "");
                $loc = $locs[$cust['location']];
                $fbal = "--";
                $ocurr = CUR;
                $trans = "\n\t\t\t<td>\n\t\t\t\t<a href='core/cust-trans.php?cusnum={$cust['cusnum']}'>Transaction</a>\n\t\t\t</td>";
                if ($cust['location'] == 'int') {
                    $fbal = "{$cust['currency']} {$cust['fbalance']}";
                    $ocurr = CUR;
                    $trans = "\n\t\t\t\t<td>\n\t\t\t\t\t<a href='core/intcust-trans.php?cusnum={$cust['cusnum']}'>Transaction</a>\n\t\t\t\t</td>";
                    $receipt = "<a href='bank/bank-recpt-inv-int.php?cusid={$cust['cusnum']}&amp;cash=yes'>Add Receipt</a>";
                } else {
                    $receipt = "<a href='bank/bank-recpt-inv.php?cusnum={$cust['cusnum']}&amp;cash=yes'>Add Receipt</a>";
                }
                # alternate bgcolor
                $bgColor = bgcolor($i);
                $ajaxCust .= "<tr class='" . bg_class() . "'>";
                if ($action == "contact_acc") {
                    $updatelink = "javascript: updateAccountInfo(\"{$cust['cusnum']}\", \"{$cust['accno']}\");";
                    $ajaxCust .= "\n\t\t\t\t\t<td><a href='{$updatelink}'>{$cust['accno']}</a></td>\n\t\t\t\t\t<td><a href='{$updatelink}'>{$cust['surname']}</a></td>";
                } else {
                    if ($action == "select") {
                        $ajaxCust .= "\n\t\t\t\t\t<td><a href='" . SELF . "?key=select&cusnum={$cust['cusnum']}&" . frmupdate_passon(true) . "'>{$cust['accno']}</a></td>\n\t\t\t\t\t<td><a href='" . SELF . "?key=select&cusnum={$cust['cusnum']}&" . frmupdate_passon(true) . "'>{$cust['surname']}</a></td>";
                    } else {
                        $ajaxCust .= "\n\t\t\t\t\t<td>{$cust['accno']}</td>\n\t\t\t\t\t<td>{$cust['surname']}</td>";
                    }
                }
                $ajaxCust .= "\n\t\t\t\t\t<td>{$cust['bustel']}</td>\n\t\t\t\t\t<td>{$cust['catname']}</td>\n\t\t\t\t\t<td>{$cust['classname']}</td>\n\t\t\t\t\t<td align='right' nowrap>{$ocurr} {$cust['balance']}</td>\n\t\t\t\t\t<td align='center' nowrap>{$fbal}</td>\n\t\t\t\t\t<td align='right' nowrap>{$ocurr} {$overd}</td>";
                if (!$pure) {
                    if ($action == "listcust") {
                        $ajaxCust .= "\n\t\t\t\t\t\t<td>{$receipt}</td>\n\t\t\t\t\t\t<td><a href='delnote-report.php?cusnum={$cust['cusnum']}'>Outstanding Stock</a></td>\n\t\t\t\t\t\t<td><a href='cust-det.php?cusnum={$cust['cusnum']}'>Details</a></td>\n\t\t\t\t\t\t<td><a href='customers-new.php?cusnum={$cust['cusnum']}'>Edit</a></td>\n\t\t\t\t\t\t<td><a href='#' onClick='openPrintWin(\"cust-stmnt.php?cusnum={$cust['cusnum']}\");'>Statement</a></td>\n\t\t\t\t\t\t{$trans} {$inv}";
                        if ($cust['blocked'] == 'yes') {
                            $ajaxCust .= "<td><a href='cust-unblock.php?cusnum={$cust['cusnum']}'>Unblock</a></td>";
                        } else {
                            $ajaxCust .= "<td><a href='cust-block.php?cusnum={$cust['cusnum']}'>Block</a></td>";
                        }
                        $ajaxCust .= "<td><a href='transheks/pricelist_send.php?cusnum={$cust['cusnum']}'>Send Pricelist</a></td>";
                        $ajaxCust .= "{$rm} <td><a href='conper-add.php?type=cust&amp;id={$cust['cusnum']}'>Add Contact</a></td>\n\t\t\t\t\t<td><input type='checkbox' name='cids[]' value='{$cust['cusnum']}' /></td>";
                    } else {
                        $ajaxCust .= "\n\t\t\t\t\t\t<td align=center>\n\t\t\t\t\t\t\t<a href='javascript: popupSized(\"cust-det.php?cusnum={$cust['cusnum']}\", \"custdetails\", 550, 400, \"\");'>Details</a>\n\t\t\t\t\t\t</td>";
                    }
                }
                $ajaxCust .= "</tr>";
            }
            $bgColor = bgcolor($i);
            $tot = sprint($tot);
            $totoverd = sprint($totoverd);
            $i--;
            $ajaxCust .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='5'>Total Amount Outstanding, from {$i} " . ($i > 1 ? "clients" : "client") . "</td>\n\t\t\t<td align='right' nowrap>" . CUR . " {$tot}</td>\n\t\t\t<td></td>\n\t\t\t<td align='right' nowrap>" . CUR . " {$totoverd}</td>\n\t\t\t" . ($pure ? "" : "<td colspan='11' align='right'><input type='submit' value='Email Statements' /></td>") . "\n\t\t</tr>";
            if (!$pure) {
                $ajaxCust .= "\n\t\t\t<tr>\n\t\t\t\t<td colspan='20'>\n\t\t\t\t<table width='100%' border='0'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td align='right' width='50%'>{$os_prev}</td>\n\t\t\t\t\t<td align='left' width='50%'>{$os_next} {$os_viewall}</td>\n\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>";
            }
        }
        if ($pure) {
            $ajaxCust .= "</table>";
        } else {
            $ajaxCust .= "\n\t\t" . TBL_BR . "\n\t\t</table>\n\t\t</form>\n\t\t<form action='" . SELF . "' method='post'>\n\t\t<table>\n\t\t\t<input type='hidden' name='export' value='yes' />\n\t\t\t<input type='hidden' name='filter' value='{$filter}' />\n\t\t\t<input type='hidden' name='fval' value='{$fval}' />\n\t\t\t<tr>\n\t\t\t\t<td colspan='3'><input type='submit' value='Export to Spreadsheet' /></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</form>";
        }
        /* FIND CUSTOMER END */
    } else {
        $ajaxCust = "";
    }
    $printCust_end = "\n\t</div>";
    if (!$pure) {
        $printCust_end .= mkQuickLinks(ql("customers-new.php", "Add New Customer"));
    }
    if (AJAX) {
        return $ajaxCust;
    } else {
        return "{$printCust_begin}{$ajaxCust}{$printCust_end}";
    }
}
function printCust()
{
    global $_SESSION;
    extract($_REQUEST);
    if (!isset($action)) {
        $action = "listcust";
    }
    $sqlfilter = "";
    $printCust_begin = "<h2>View Customers</h2>";
    $ajaxCust = "";
    $ajaxCust .= "\n\t<form action='statements-email.php' method='get'>\n\t<input type='hidden' name='key' value='confirm' />";
    if (!isset($offset) && isset($_SESSION["offset"])) {
        $offset = $_SESSION["offset"];
    } else {
        if (!isset($offset)) {
            $offset = 0;
        }
    }
    $_SESSION["offset"] = $offset;
    # connect to database
    db_connect();
    # counting the number of possible entries
    $sql = "SELECT * FROM customers\n    \t\tWHERE (div = '" . USER_DIV . "' OR  ddiv = '" . USER_DIV . "') {$sqlfilter}\n    \t\tORDER BY surname ASC";
    $rslt = db_exec($sql) or errDie("Error counting matching customers.");
    $custcount = pg_num_rows($rslt);
    # Query server
    $tot = 0;
    $totoverd = 0;
    $i = 0;
    $ajaxCust .= "\n\t<table " . TMPL_tblDflts . ">\n\n\t<tr>\n\t\t<th>Acc no.</th>\n\t\t<th>Company/Name</th>\n\t\t<th>Tel</th>\n\t\t<th>Category</th>\n\t\t<th>Class</th>\n\t\t<th colspan='2'>Balance</th>\n\t\t<th>Overdue</th>\n\t</tr>";
    /* query object for cashbook */
    $cashbook = new dbSelect("cashbook", "cubit");
    $custRslt = new dbSelect("customers", "cubit", grp(m("where", "(div ='" . USER_DIV . "' or ddiv='" . USER_DIV . "') {$sqlfilter}"), m("order", "surname ASC"), m("offset", $offset), m("limit", 100)));
    $custRslt->run();
    if ($custRslt->num_rows() < 1) {
        $ajaxCust .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='20'><li>There are no Customers matching the criteria entered.</li></td>\n\t\t</tr>";
    } else {
        while ($cust = $custRslt->fetch_array()) {
            if (!user_in_team($cust["team_id"], USER_ID)) {
                continue;
            }
            # Check type of age analisys
            if (div_isset("DEBT_AGE", "mon")) {
                $overd = ageage($cust['cusnum'], $cust['overdue'] / 30 - 1, $cust['location']);
            } else {
                $overd = age($cust['cusnum'], $cust['overdue'] - 1, $cust['location']);
            }
            if ($overd < 0) {
                $overd = 0;
            }
            if ($overd > $cust['balance']) {
                $overd = $cust['balance'];
            }
            if ($cust["location"] == "int") {
                $cur = qryCurrency($cust["fcid"], "rate");
                $rate = $cur["rate"];
                if ($rate != 0) {
                    $totoverd += $overd * $rate;
                } else {
                    $totoverd += $overd;
                }
            } else {
                $totoverd += $overd;
            }
            /* check if customer may be removed */
            $cashbook->setOpt(grp(m("where", "cusnum='{$cust['cusnum']}' AND banked='no' AND div='" . USER_DIV . "'")));
            $cashbook->run();
            if (strlen(trim($cust['bustel'])) < 1) {
                $cust['bustel'] = $cust['tel'];
            }
            $cust['balance'] = sprint($cust['balance']);
            if ($cust["location"] == "int") {
                if ($rate != 0.0) {
                    $tot = $tot + $cust['fbalance'] * $rate;
                } else {
                    $tot = $tot + $cust['balance'];
                }
            } else {
                $tot = $tot + $cust['balance'];
            }
            # Locations drop down
            $locs = array("loc" => "Local", "int" => "International", "" => "");
            $loc = $locs[$cust['location']];
            $fbal = "--";
            $ocurr = CUR;
            # alternate bgcolor
            $bgColor = bgcolor($i);
            $ajaxCust .= "<tr class='" . bg_class() . "'>";
            if ($action == "contact_acc") {
                $updatelink = "javascript: updateAccountInfo(\"{$cust['cusnum']}\", \"{$cust['accno']}\");";
                $ajaxCust .= "\n\t\t\t\t\t<td><a href='{$updatelink}'>{$cust['accno']}</a></td>\n\t\t\t\t\t<td><a href='{$updatelink}'>{$cust['surname']}</a></td>";
            } else {
                if ($action == "select") {
                    $ajaxCust .= "\n\t\t\t\t\t<td><a href='" . SELF . "?key=select&cusnum={$cust['cusnum']}&" . frmupdate_passon(true) . "'>{$cust['accno']}</a></td>\n\t\t\t\t\t<td><a href='" . SELF . "?key=select&cusnum={$cust['cusnum']}&" . frmupdate_passon(true) . "'>{$cust['surname']}</a></td>";
                } else {
                    $ajaxCust .= "\n\t\t\t\t\t<td>{$cust['accno']}</td>\n\t\t\t\t\t<td>{$cust['surname']}</td>";
                }
            }
            $ajaxCust .= "\n\t\t\t\t\t<td>{$cust['bustel']}</td>\n\t\t\t\t\t<td>{$cust['catname']}</td>\n\t\t\t\t\t<td>{$cust['classname']}</td>\n\t\t\t\t\t<td align='right' nowrap>{$ocurr} {$cust['balance']}</td>\n\t\t\t\t\t<td align='center' nowrap>{$fbal}</td>\n\t\t\t\t\t<td align='right' nowrap>{$ocurr} {$overd}</td>";
            $ajaxCust .= "</tr>";
        }
        $bgColor = bgcolor($i);
        $tot = sprint($tot);
        $totoverd = sprint($totoverd);
        $i--;
        $ajaxCust .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='5'>Total Amount Outstanding, from {$i} " . ($i > 1 ? "clients" : "client") . "</td>\n\t\t\t<td align='right' nowrap>" . CUR . " {$tot}</td>\n\t\t\t<td></td>\n\t\t\t<td align='right' nowrap>" . CUR . " {$totoverd}</td>\n\t\t</tr>";
    }
    $ajaxCust .= "\n\t\t" . TBL_BR . "\n\t\t</table>\n\t\t</form>";
    $printCust_end = "\n\t</div>";
    if (AJAX) {
        return $ajaxCust;
    } else {
        return "{$printCust_begin}{$ajaxCust}{$printCust_end}";
    }
}