function details($_POST, $error = "")
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    if (isset($invid)) {
        $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    }
    if (isset($deptid)) {
        $v->isOk($deptid, "num", 1, 20, "Invalid department number.");
    }
    if (isset($letters)) {
        $v->isOk($letters, "string", 0, 5, "Invalid First 3 Letters.");
    }
    # display errors, if any
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $error .= "<li class='err'>{$e['msg']}</li>";
        }
        $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    if (!isset($deptid)) {
        $deptid = 0;
    } else {
        if (isset($invid)) {
            db_conn("cubit");
            $sql = "UPDATE rec_invoices SET deptid='{$deptid}' WHERE invid='{$invid}' AND deptid<>'{$deptid}'";
            db_exec($sql) or errDie("Error updating invoice department.");
        }
    }
    if (!isset($invid)) {
        $invid = create_dummy($deptid);
        $stkerr = "0,0";
    }
    if (!isset($done)) {
        $done = "";
    }
    if (!isset($stkerr)) {
        $stkerr = "0,0";
    }
    # Get invoice info
    db_connect();
    $sql = "SELECT * FROM rec_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<li class='err'>Invoice Not Found</li>";
    }
    $inv = pg_fetch_array($invRslt);
    # Get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$inv['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<li class='err'>Department not Found.</li>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    # Get selected Customer info
    if (isset($letters)) {
        db_connect();
        $sql = "SELECT * FROM customers WHERE cusnum = '{$inv['cusnum']}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to view customer");
        if (pg_numrows($custRslt) < 1) {
            db_connect();
            if ($inv['deptid'] == 0) {
                $searchdept = "";
            } else {
                $searchdept = "deptid = '{$inv['deptid']}' AND ";
            }
            # Query server for customer info
            $sql = "\n\t\t\t\tSELECT * FROM customers \n\t\t\t\tWHERE {$searchdept} location != 'int' AND lower(surname) LIKE lower('{$letters}%') AND blocked != 'yes' AND div = '" . USER_DIV . "' \n\t\t\t\tORDER BY surname";
            $custRslt = db_exec($sql) or errDie("Unable to view customers");
            if (pg_numrows($custRslt) < 1) {
                $ajax_err = "<li class='err'>No customer names starting with <b>{$letters}</b> in database.</li>";
                //return view_err($_POST, $err);
            } else {
                $customers = "<select name='cusnum' onChange='javascript:document.form.submit();'>";
                $customers .= "<option value='-S' selected>Select Customer</option>";
                while ($cust = pg_fetch_array($custRslt)) {
                    $customers .= "<option value='{$cust['cusnum']}'>{$cust['cusname']} {$cust['surname']}</option>";
                }
                $customers .= "</select>";
            }
            # Take care of the unset vars
            $cust['addr1'] = "";
            $cust['cusnum'] = "";
            $cust['vatnum'] = "";
            $cust['accno'] = "";
        } else {
            $cust = pg_fetch_array($custRslt);
            $sql = "SELECT * FROM customers WHERE deptid = '{$inv['deptid']}' AND location != 'int' AND lower(surname) LIKE lower('{$letters}%') AND blocked != 'yes' AND div = '" . USER_DIV . "' ORDER BY surname";
            $cusRslt = db_exec($sql) or errDie("Unable to view customers");
            # Moarn if customer account has been blocked
            if ($cust['blocked'] == 'yes') {
                $error .= "<li class='err'>Error : Selected customer account has been blocked.</li>";
            }
            // $customers = "<input type=hidden name=cusnum value='$cust[cusnum]'>$cust[cusname]  $cust[surname]";
            $cusnum = $cust['cusnum'];
            $customers = "<select name='cusnum' onChange='javascript:document.form.submit();'>";
            // $customers .= "<option value='-S' selected>Select Customer</option>";
            while ($cus = pg_fetch_array($cusRslt)) {
                $sel = "";
                if ($cust['cusnum'] == $cus['cusnum']) {
                    $sel = "selected";
                }
                $customers .= "<option value='{$cus['cusnum']}' {$sel}>{$cus['cusname']} {$cus['surname']}</option>";
            }
            $customers .= "</select>";
        }
    }
    /* --- Start Drop Downs --- */
    # Select warehouse
    db_conn("exten");
    //	$whs = "<select name='whidss[]' onChange='javascript:document.form.submit();'>";
    $whs = "<select name='whidss[]'>";
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "' ORDER BY whname ASC";
    $whRslt = db_exec($sql);
    if (pg_numrows($whRslt) < 1) {
        return "<li class='err'> There are no Stores found in Cubit.</li>";
    } else {
        $whs .= "<option value='-S' disabled selected>Select Store</option>";
        while ($wh = pg_fetch_array($whRslt)) {
            if (!user_in_store_team($wh["whid"], USER_ID)) {
                continue;
            }
            $whs .= "<option value='{$wh['whid']}'>({$wh['whno']}) {$wh['whname']}</option>";
        }
    }
    $whs .= "</select>";
    # Get sales people
    db_conn("exten");
    $sql = "SELECT * FROM salespeople WHERE div = '" . USER_DIV . "' ORDER BY salesp ASC";
    $salespRslt = db_exec($sql) or errDie("Unable to get sales people.");
    if (pg_numrows($salespRslt) < 1) {
        return "<li class='err'> There are no Sales People found in Cubit.</li>";
    } else {
        $salesps = "<select name='salespn'>";
        while ($salesp = pg_fetch_array($salespRslt)) {
            if ($salesp['salesp'] == $inv['salespn']) {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $salesps .= "<option value='{$salesp['salesp']}' {$sel}>{$salesp['salesp']}</option>";
        }
        $salesps .= "</select>";
    }
    # Days drop downs
    $days = array("0" => "0", "7" => "7", "14" => "14", "30" => "30", "60" => "60", "90" => "90", "120" => "120");
    $termssel = extlib_cpsel("terms", $days, $inv['terms']);
    # Keep the charge vat option stable
    if ($inv['chrgvat'] == "inc") {
        $chin = "checked=yes";
        $chex = "";
        $chno = "";
    } elseif ($inv['chrgvat'] == "exc") {
        $chin = "";
        $chex = "checked=yes";
        $chno = "";
    } else {
        $chin = "";
        $chex = "";
        $chno = "checked=yes";
    }
    # Format date
    list($rinv_year, $rinv_month, $rinv_day) = explode("-", $inv['odate']);
    /* --- End Drop Downs --- */
    // get the ID of the first warehouse
    db_conn("exten");
    $sql = "SELECT whid FROM warehouses ORDER BY whid ASC LIMIT 1";
    $rslt = db_exec($sql) or errDie("Error reading warehouses (FWH).");
    if (pg_num_rows($rslt) > 0) {
        $FIRST_WH = pg_fetch_result($rslt, 0, 0);
    } else {
        $FIRST_WH = "-S";
    }
    /* --- Start Products Display --- */
    # Select all products
    $products = "\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t<tr>\n\t\t\t\t<th>STORE</th>\n\t\t\t\t<th>ITEM NUMBER</th>\n\t\t\t\t<th>VAT CODE</th>\n\t\t\t\t<th>DESCRIPTION</th>\n\t\t\t\t<th>QTY</th>\n\t\t\t\t<th>UNIT PRICE</th>\n\t\t\t\t<th>UNIT DISCOUNT</th>\n\t\t\t\t<th>AMOUNT</th>\n\t\t\t\t<th>Remove</th>\n\t\t\t<tr>";
    # get selected stock in this invoice
    db_connect();
    $sql = "SELECT * FROM recinv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $i = 0;
    $key = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        $stkd['account'] += 0;
        if ($stkd['account'] != 0) {
            # Keep track of selected stock amounts
            $amts[$i] = $stkd['amt'];
            $i++;
            db_conn('core');
            $Sl = "SELECT accid,topacc,accnum,accname FROM accounts WHERE acctype='I' ORDER BY accname";
            $Ri = db_exec($Sl) or errDie("Unable to get accounts.");
            $Accounts = "\n\t\t\t\t<select name='accounts[]'>\n\t\t\t\t\t<option value='0'>Select Account</option>";
            while ($ad = pg_fetch_array($Ri)) {
                if (isb($ad['accid'])) {
                    continue;
                }
                if ($ad['accid'] == $stkd['account']) {
                    $sel = "selected";
                } else {
                    $sel = "";
                }
                $Accounts .= "<option value='{$ad['accid']}' {$sel}>{$ad['accname']}</option>";
            }
            $Accounts .= "</select>";
            $sernos = "";
            # Input qty if not serialised
            $qtyin = "<input type='text' size='3' name='qtys[]' value='{$stkd['qty']}'>";
            $viewcost = "<input type='text' size='8' name='unitcost[]' value='{$stkd['unitcost']}'>";
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes ORDER BY code";
            $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
            $Vatcodes = "\n\t\t\t\t<select name='vatcodes[]'>\n\t\t\t\t\t<option value='0'>Select</option>";
            while ($vd = pg_fetch_array($Ri)) {
                if ($stkd['vatcode'] == $vd['id']) {
                    $sel = "selected";
                } else {
                    $sel = "";
                }
                $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
            }
            $Vatcodes .= "</select>";
            # Put in product
            $products .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='2'>{$Accounts}<input type='hidden' name='whids[]' value='{$stkd['whid']}'></td>\n\t\t\t\t\t<td><input type='hidden' name='stkids[]' value='{$stkd['stkid']}'>{$Vatcodes}</td>\n\t\t\t\t\t<td><input type='text' size='20' name='descriptions[]' value='{$stkd['description']}'> {$sernos}</td>\n\t\t\t\t\t<td>{$qtyin}</td>\n\t\t\t\t\t<td>{$viewcost}</td>\n\t\t\t\t\t<td><input type='hidden' name='disc[]' value='{$stkd['disc']}'><input type='hidden' name='discp[]' value='{$stkd['discp']}'></td>\n\t\t\t\t\t<td nowrap><input type='hidden' name='amt[]' value='{$stkd['amt']}'> " . CUR . " " . sprint($stkd['amt']) . "</td>\n\t\t\t\t\t<td><input type='checkbox' name='remprod[]' value='{$key}'><input type='hidden' name='SCROLL' value='yes'></td>\n\t\t\t\t</tr>";
            $key++;
        } else {
            # Keep track of selected stock amounts
            $amts[$i] = $stkd['amt'];
            $i++;
            # Get warehouse name
            db_conn("exten");
            $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            # Get selected stock in this warehouse
            db_connect();
            $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql);
            $stk = pg_fetch_array($stkRslt);
            $sernos = "<input type='hidden' name='sernos[]' value='{$stkd['serno']}'>{$stkd['serno']}";
            # check permissions
            if (perm("invoice-unitcost-edit.php")) {
                $viewcost = "<input type='text' size='8' name='unitcost[]' value='{$stkd['unitcost']}'>";
            } else {
                $viewcost = "<input type='hidden' size='8' name='unitcost[]' value='{$stkd['unitcost']}'>{$stkd['unitcost']}";
            }
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes ORDER BY code";
            $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
            $Vatcodes = "\n\t\t\t\t<select name='vatcodes[]'>\n\t\t\t\t\t<option value='0'>Select</option>";
            while ($vd = pg_fetch_array($Ri)) {
                if ($stkd['vatcode'] == $vd['id']) {
                    $sel = "selected";
                } else {
                    $sel = "";
                }
                $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
            }
            $Vatcodes .= "</select>";
            # Put in product
            $products .= "\n\t\t\t\t<input type='hidden' name='accounts[]' value='0'>\n\t\t\t\t<input type='hidden' name='descriptions[]' value=''>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><input type='hidden' name='whids[]' value='{$stkd['whid']}'>{$wh['whname']}</td>\n\t\t\t\t\t<td><input type='hidden' name='stkids[]' value='{$stkd['stkid']}'><a href='#bottom' onclick='openwindow(\"stock-amt-det.php?stkid={$stk['stkid']}\")'>{$stk['stkcod']}</a></td>\n\t\t\t\t\t{$sernos}\n\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t<td>" . extlib_rstr($stk['stkdes'], 30) . "</td>\n\t\t\t\t\t<td><input type='text' size='3' name='qtys[]' value='{$stkd['qty']}'></td>\n\t\t\t\t\t<td>{$viewcost}</td>\n\t\t\t\t\t<td><input type='text' size='4' name='disc[]' value='{$stkd['disc']}'> OR <input type='text' size='4' name='discp[]' value='{$stkd['discp']}' maxlength='5'>%</td>\n\t\t\t\t\t<td nowrap><input type='hidden' name='amt[]' value='{$stkd['amt']}'> " . CUR . " " . sprint($stkd['amt']) . "</td>\n\t\t\t\t\t<td><input type='checkbox' name='remprod[]' value='{$key}'><input type='hidden' name='SCROLL' value='yes'></td>\n\t\t\t\t</tr>";
            $key++;
        }
    }
    # Look above(remprod keys)
    $keyy = $key;
    # Look above(if i = 0 then there are no products)
    if ($i == 0) {
        $done = "";
    } else {
        $SCROLL = "yes";
    }
    # check if stock warehouse was selected
    if (isset($whidss)) {
        foreach ($whidss as $key => $whid) {
            if (isset($stkidss[$key]) && $stkidss[$key] != "-S" && isset($cust['pricelist'])) {
                # skip if not selected
                if ($whid == "-S") {
                    continue;
                }
                # Get selected warehouse name
                db_conn("exten");
                $sql = "SELECT whname FROM warehouses WHERE whid = '{$whid}' AND div = '" . USER_DIV . "'";
                $whRslt = db_exec($sql);
                $wh = pg_fetch_array($whRslt);
                # Get selected stock in this warehouse
                db_connect();
                $sql = "SELECT * FROM stock WHERE stkid = '{$stkidss[$key]}' AND div = '" . USER_DIV . "' ORDER BY stkcod ASC";
                $stkRslt = db_exec($sql);
                $stk = pg_fetch_array($stkRslt);
                $sernos = "<input type='hidden' name='sernos[]' value=''>";
                # Get price from price list if it is set
                if (isset($cust['pricelist'])) {
                    # get selected stock in this warehouse
                    db_conn("exten");
                    $sql = "SELECT price FROM plist_prices WHERE listid = '{$cust['pricelist']}' AND stkid = '{$stk['stkid']}' AND div = '" . USER_DIV . "'";
                    $plRslt = db_exec($sql);
                    if (pg_numrows($plRslt) > 0) {
                        $pl = pg_fetch_array($plRslt);
                        $stk['selamt'] = $pl['price'];
                    }
                }
                /* -- Start Some Checks -- */
                # check if they are selling too much
                if ($stk['units'] - $stk['alloc'] < $qtyss[$key]) {
                    if (!in_array($stk['stkid'], explode(",", $stkerr))) {
                        if ($stk['type'] != 'lab') {
                            $stkerr .= ",{$stk['stkid']}";
                            $error .= "<li class='err'>Warning :  Item number <b>{$stk['stkcod']}</b> does not have enough items available.</li>";
                        }
                    }
                }
                /* -- End Some Checks -- */
                # Calculate the Discount discount
                if ($discs[$key] < 1) {
                    if ($discps[$key] > 0) {
                        $discs[$key] = round($discps[$key] / 100 * $stk['selamt'], 2);
                    }
                } else {
                    $discps[$key] = round($discs[$key] * 100 / $stk['selamt'], 2);
                }
                # Calculate amount
                $amt[$key] = $qtyss[$key] * ($stk['selamt'] - $discs[$key]);
                $stk['selamt'] = sprint($stk['selamt']);
                # Check permissions
                if (perm("invoice-unitcost-edit.php")) {
                    $viewcost = "<input type='text' size='8' name='unitcost[]' value='{$stk['selamt']}'>";
                } else {
                    $viewcost = "<input type='hidden' size='8' name='unitcost[]' value='{$stk['selamt']}'>{$stk['selamt']}";
                }
                db_conn('cubit');
                $Sl = "SELECT * FROM vatcodes ORDER BY code";
                $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                $Vatcodes = "\n\t\t\t\t\t<select name='vatcodes[]'>\n\t\t\t\t\t\t<option value='0'>Select</option>";
                while ($vd = pg_fetch_array($Ri)) {
                    if ($stk['vatcode'] == $vd['id']) {
                        $sel = "selected";
                    } else {
                        $sel = "";
                    }
                    $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
                }
                $Vatcodes .= "</select>";
                $amt[$key] = sprint($amt[$key]);
                # Put in selected warehouse and stock
                $products .= "\n\t\t\t\t\t<input type='hidden' name='accounts[]' value='0'>\n\t\t\t\t\t<input type='hidden' name='descriptions[]' value=''>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><input type='hidden' name='whids[]' value='{$whid}'>{$wh['whname']}</td>\n\t\t\t\t\t\t<td><input type='hidden' name='stkids[]' value='{$stk['stkid']}'><a href='#bottom' onclick='openwindow(\"stock-amt-det.php?stkid={$stk['stkid']}\")'>{$stk['stkcod']}</a></td>\n\t\t\t\t\t\t{$sernos}\n\t\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t\t<td>" . extlib_rstr($stk['stkdes'], 30) . "</td>\n\t\t\t\t\t\t<td><input type='text' size='3' name='qtys[]' value='{$qtyss[$key]}'></td>\n\t\t\t\t\t\t<td>{$viewcost}</td>\n\t\t\t\t\t\t<td><input type='text' size='4' name='disc[]' value='{$discs[$key]}'> OR <input type='text' size='4' name='discp[]' value='{$discps[$key]}' maxlength='5'>%</td>\n\t\t\t\t\t\t<td nowrap><input type='hidden' name='amt[]' value='{$amt[$key]}'> " . CUR . " {$amt[$key]}</td>\n\t\t\t\t\t\t<td><input type='checkbox' name='remprod[]' value='{$keyy}'></td>\n\t\t\t\t\t</tr>";
                $keyy++;
            } elseif (isset($accountss[$key]) && $accountss[$key] != "0" && isset($cust['pricelist'])) {
                db_conn('core');
                $Sl = "SELECT * FROM accounts WHERE accid='{$accountss[$key]}'";
                $Ri = db_exec($Sl) or errDie("Unable to get account data.");
                if (pg_num_rows($Ri) < 1) {
                    return "invalid.";
                }
                $ad = pg_fetch_array($Ri);
                # Calculate amount
                $amt[$key] = sprint($qtyss[$key] * $unitcosts[$key]);
                # Input qty if not serialised
                $qtyin = "<input type='text' size='3' name='qtys[]' value='{$qtyss[$key]}'>";
                # Check permissions
                $viewcost = "<input type='text' size='8' name='unitcost[]' value='{$unitcosts[$key]}'>";
                db_conn('cubit');
                $Sl = "SELECT * FROM vatcodes ORDER BY code";
                $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                $Vatcodes = "\n\t\t\t\t\t<select name='vatcodes[]'>\n\t\t\t\t\t\t<option value='0'>Select</option>";
                while ($vd = pg_fetch_array($Ri)) {
                    if ($vatcodess[$key] == $vd['id']) {
                        $sel = "selected";
                    } else {
                        $sel = "";
                    }
                    $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
                }
                $Vatcodes .= "</select>";
                # Put in selected warehouse and stock
                $products .= "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td colspan='2'>{$ad['accname']}<input type='hidden' name='accounts[]' value='{$accountss[$key]}'><input type='hidden' name='whids[]' value='0'></td>\n\t\t\t\t\t\t<td>{$Vatcodes}<input type='hidden' name='stkids[]' value='0'></td>\n\t\t\t\t\t\t<td><input type='text' size='20' name='descriptions[]' value='{$descriptionss[$key]}'></td>\n\t\t\t\t\t\t<td>{$qtyin}</td>\n\t\t\t\t\t\t<td>{$viewcost}</td>\n\t\t\t\t\t\t<td><input type='hidden' name='disc[]' value='0'><input type='hidden' name='discp[]' value='0'></td>\n\t\t\t\t\t\t<td nowrap><input type='hidden' name='amt[]' value='{$amt[$key]}'> " . CUR . " {$amt[$key]}</td>\n\t\t\t\t\t\t<td><input type='checkbox' name='remprod[]' value='{$keyy}'></td>\n\t\t\t\t\t</tr>";
                $keyy++;
            } else {
                if (!isset($diffwhBtn)) {
                    # skip if not selected
                    if ($whid == "-S") {
                        continue;
                    }
                    if (!isset($addnon)) {
                        # get warehouse name
                        db_conn("exten");
                        $sql = "SELECT whname FROM warehouses WHERE whid = '{$whid}' AND div = '" . USER_DIV . "'";
                        $whRslt = db_exec($sql);
                        $wh = pg_fetch_array($whRslt);
                        if (isset($ria) && $ria != "") {
                            $len = strlen($ria);
                            if ($ria == "Show All") {
                                $Wh = "";
                                $ria = "";
                            } else {
                                $Wh = "AND (lower(stkdes) LIKE lower('%{$ria}%')) OR (lower(stkcod) LIKE lower('%{$ria}%'))";
                                //								$Wh = "AND lower(substr(stkcod,1,'$len'))=lower('$ria')";
                            }
                        } else {
                            $Wh = "AND FALSE";
                            $ria = "";
                        }
                        # get stock on this warehouse
                        db_connect();
                        $sql = "SELECT * FROM stock WHERE whid = '{$whid}' AND blocked = 'n' AND div = '" . USER_DIV . "' AND serd = 'no' {$Wh} ORDER BY stkcod ASC";
                        $stkRslt = db_exec($sql) or errDie("Unable to retrieve stocks from database.");
                        if (pg_numrows($stkRslt) < 1) {
                            $error .= "<li class='err'>There are no stock items in the selected warehouse.</li>";
                            continue;
                        }
                        if (pg_numrows($stkRslt) == 1) {
                            $ex = "selected";
                        } else {
                            $ex = "";
                        }
                        if (!isset($sel_frm) || $sel_frm == "stkcod") {
                            $cods = "<select class='width : 15'name='stkidss[]' onChange='javascript:document.form.submit();'>";
                            $cods .= "<option value='-S' disabled selected>Select Number</option>";
                            $count = 0;
                            while ($stk = pg_fetch_array($stkRslt)) {
                                $cods .= "<option value='{$stk['stkid']}'>{$stk['stkcod']} (" . sprint3($stk['units'] - $stk['alloc']) . ")</option>";
                            }
                            $cods .= "</select> ";
                            $descs = "";
                        } else {
                            $descs = "<select class='width : 15'name='stkidss[]' onChange='javascript:document.form.submit();'>";
                            $descs .= "<option value='-S' disabled selected>Select Description</option>";
                            $count = 0;
                            while ($stk = pg_fetch_array($stkRslt)) {
                                $descs .= "<option value='{$stk['stkid']}'>{$stk['stkdes']} (" . sprint3($stk['units'] - $stk['alloc']) . ")</option>";
                            }
                            $descs .= "</select> ";
                            $cods = "";
                        }
                        # put in drop down and warehouse
                        $products .= "\n\t\t\t\t\t\t\t<input type='hidden' name='accountss[]' value='0'>\n\t\t\t\t\t\t\t<input type='hidden' name='descriptionss[]' value=''>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td><input type='hidden' name='whidss[]' value='{$whid}'>{$wh['whname']}</td>\n\t\t\t\t\t\t\t\t<td>{$cods}</td>\n\t\t\t\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t\t\t\t<td>{$descs}</td>\n\t\t\t\t\t\t\t\t<td><input type='text' size='3' name='qtyss[]'  value='1'></td>\n\t\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t\t\t<td><input type='text' size='4' name='discs[]' value='0'> OR <input type='text' size='4' name='discps[]' value='0' maxlength='5'>%</td>\n\t\t\t\t\t\t\t\t<td><input type='hidden' name='amts[]' value='0.00'>" . CUR . " 0.00</td>\n\t\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t</tr>";
                    } else {
                        db_conn('core');
                        $Sl = "SELECT accid,topacc,accnum,accname FROM accounts WHERE acctype='I' ORDER BY accname";
                        $Ri = db_exec($Sl) or errDie("Unable to get accounts.");
                        $Accounts = "\n\t\t\t\t\t\t\t<select name='accountss[]'  onChange='javascript:document.form.submit();'>\n\t\t\t\t\t\t\t\t<option value='0'>Select Account</option>";
                        while ($ad = pg_fetch_array($Ri)) {
                            if (isb($ad['accid'])) {
                                continue;
                            }
                            $Accounts .= "<option value={$ad['accid']}>{$ad['accname']}</option>";
                        }
                        $Accounts .= "</select>";
                        db_conn('cubit');
                        $Sl = "SELECT * FROM vatcodes ORDER BY code";
                        $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                        $Vatcodes = "\n\t\t\t\t\t\t\t<select name='vatcodess[]'>\n\t\t\t\t\t\t\t\t<option value='0'>Select</option>";
                        while ($vd = pg_fetch_array($Ri)) {
                            if ($vd['del'] == "Yes") {
                                $sel = "selected";
                            } else {
                                $sel = "";
                            }
                            $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
                        }
                        $Vatcodes .= "</select>";
                        //<input type='hidden' name='stkidss[]' value=''>
                        $products .= "\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td colspan='2'>{$Accounts}<input type='hidden' name='whidss[]' value='{$FIRST_WH}'></td>\n\t\t\t\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t\t\t\t<td><input type='text' size='20' name='descriptionss[]'></td>\n\t\t\t\t\t\t\t\t<td><input type='text' size='3' name='qtyss[]' value='1'></td>\n\t\t\t\t\t\t\t\t<td><input type='text' name='unitcosts[]' size='7'></td>\n\t\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t\t\t\t\t<td><input type='hidden' name='discs[]' value='0'><input type='hidden' name='discps[]' value='0' ></td>\n\t\t\t\t\t\t\t</tr>";
                    }
                }
            }
        }
    } else {
        if (!(isset($diffwhBtn) || isset($addnon))) {
            # check if setting exists
            db_connect();
            $sql = "SELECT value FROM set WHERE label = 'DEF_WH' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to check database for existing settings.");
            if (pg_numrows($Rslt) > 0) {
                $set = pg_fetch_array($Rslt);
                $whid = $set['value'];
                if (isset($wtd) && $wtd != 0) {
                    $whid = $wtd;
                }
                # get selected warehouse name
                db_conn("exten");
                $sql = "SELECT whname FROM warehouses WHERE whid = '{$whid}' AND div = '" . USER_DIV . "'";
                $whRslt = db_exec($sql);
                $wh = pg_fetch_array($whRslt);
                if (isset($ria) && $ria != "") {
                    $len = strlen($ria);
                    if ($ria == "Show All") {
                        $Wh = "";
                        $ria = "";
                    } else {
                        $Wh = "AND lower(substr(stkcod,1,'{$len}'))=lower('{$ria}')";
                        $ria = "";
                    }
                } else {
                    $Wh = "";
                    $ria = "";
                }
                # get stock on this warehouse
                db_connect();
                $sql = "SELECT * FROM stock WHERE whid = '{$whid}' AND blocked = 'n' AND div = '" . USER_DIV . "' AND serd = 'no' {$Wh} ORDER BY stkcod ASC";
                $stkRslt = db_exec($sql) or errDie("Unable to retrieve stocks from database.");
                if (pg_numrows($stkRslt) < 1) {
                    if (!isset($err)) {
                        $err = "";
                    }
                    $err .= "<li>There are no stock items in the selected store.</li>";
                    //ontinue;
                }
                $stks = "<select name='stkidss[]' onChange='javascript:document.form.submit();'>";
                $stks .= "<option value='-S' disabled selected>Select Number</option>";
                $count = 0;
                while ($stk = pg_fetch_array($stkRslt)) {
                    $stks .= "<option value='{$stk['stkid']}'>{$stk['stkcod']} (" . sprint3($stk['units'] - $stk['alloc']) . ")</option>";
                }
                $stks .= "</select> ";
                $products .= "\n\t\t\t\t\t<input type='hidden' name='descriptionss[]' value=''>\n\t\t\t\t\t<input type='hidden' name='vatcodess[]' value=''>\n\t\t\t\t\t<input type='hidden' name='accountss[]' value='0'>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><input type='hidden' name='whidss[]' value='{$whid}'>{$wh['whname']}</td>\n\t\t\t\t\t\t<td>{$stks}</td>\n\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t<td><input type='hidden' size='3' name='qtyss[]' value='1'>1</td>\n\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t<td><input type='text' size='4' name='discs[]' value='0'> OR <input type='text' size='4' name='discps[]' value='0' maxlength='5'>%</td>\n\t\t\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t\t\t<td></td>\n\t\t\t\t\t</tr>";
            } else {
                $products .= "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>{$whs}</td>\n\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t<td><input type='text' size='4' name='discs[]' value='0'> OR <input type='text' size='4' name='discps[]' value='0' maxlength='5'>%</td>\n\t\t\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t\t\t<td></td>\n\t\t\t\t\t</tr>";
            }
        } else {
            if (isset($addnon)) {
                db_conn('core');
                $Sl = "SELECT accid,topacc,accnum,accname FROM accounts WHERE acctype='I' ORDER BY accname";
                $Ri = db_exec($Sl) or errDie("Unable to get accounts.");
                $Accounts = "\n\t\t\t\t<select name='accountss[]'>\n\t\t\t\t\t<option value='0'>Select Account</option>";
                while ($ad = pg_fetch_array($Ri)) {
                    if (isb($ad['accid'])) {
                        continue;
                    }
                    $Accounts .= "<option value='{$ad['accid']}'>{$ad['accname']}</option>";
                }
                $Accounts .= "</select>";
                db_conn('cubit');
                $Sl = "SELECT * FROM vatcodes ORDER BY code";
                $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                $Vatcodes = "\n\t\t\t\t<select name='vatcodess[]'>\n\t\t\t\t\t<option value='0'>Select</option>";
                while ($vd = pg_fetch_array($Ri)) {
                    if ($vd['del'] == "Yes") {
                        $sel = "selected";
                    } else {
                        $sel = "";
                    }
                    $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
                }
                $Vatcodes .= "</select>";
                $products .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='2'>{$Accounts}<input type='hidden' name='whidss[]' value='{$FIRST_WH}'></td>\n\t\t\t\t\t<input type='hidden' name='stkidss[]' value='-S'>\n\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t<td><input type='text' size='20' name='descriptionss[]'></td>\n\t\t\t\t\t<td><input type='text' size='3' name='qtyss[]' value='1'></td>\n\t\t\t\t\t<td><input type='text' name='unitcosts[]' size='7'></td>\n\t\t\t\t\t<td></td>\n\t\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t\t<td><input type='hidden' name='discs[]' value='0'><input type='hidden' name='discps[]' value='0'></td>\n\t\t\t\t</tr>";
            }
        }
    }
    /* -- start Listeners -- */
    if (isset($diffwhBtn)) {
        $products .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$whs}</td>\n\t\t\t\t<td> </td>\n\t\t\t\t<td></td>\n\t\t\t\t<td> </td>\n\t\t\t\t<td> </td>\n\t\t\t\t<td><input type='text' size='4' name='discs[]' value='0'> OR <input type='text' size='4' name='discps[]' value='0' maxlength='5'>%</td>\n\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t<td></td>\n\t\t\t</tr>";
    }
    /* -- End Listeners -- */
    $products .= "</table>";
    /* --- End Products Display --- */
    /* --- Start Some calculations --- */
    # Calculate subtotal
    $SUBTOT = sprint($inv['subtot']);
    # Calculate tradediscm
    if ($inv['traddisc'] > 0) {
        $traddiscm = sprint($inv['traddisc'] / 100 * ($SUBTOT + $inv['delchrg']));
    } else {
        $traddiscm = "0.00";
    }
    $VATP = TAX_VAT;
    # Calculate subtotal
    $SUBTOT = sprint($inv['subtot']);
    $VAT = sprint($inv['vat']);
    $TOTAL = sprint($inv['total']);
    $inv['delchrg'] = sprint($inv['delchrg']);
    /* --- End Some calculations --- */
    /*--- Start checks --- */
    # check only if the customer is selected
    if (isset($cusnum) && $cusnum != "-S") {
        #check againg credit limit
        if ($TOTAL + $cust['balance'] > $cust['credlimit']) {
            $error .= "<li class='err'>Warning : Customers Credit limit of <b>" . CUR . " " . sprint($cust["credlimit"]) . "</b> has been exceeded";
        }
        $avcred = $cust['credlimit'] - $cust['balance'];
    } else {
        $avcred = "0.00";
    }
    $inv['delvat'] += 0;
    if ($inv['delvat'] == 0) {
        $Sl = "SELECT * FROM vatcodes WHERE del='Yes'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $vd = pg_fetch_array($Ri);
        $inv['delvat'] = $vd['id'];
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes ORDER BY code";
    $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
    $Vatcodes = "\n\t\t<select name='delvat'>\n\t\t\t<option value='0'>Select</option>";
    while ($vd = pg_fetch_array($Ri)) {
        if ($vd['id'] == $inv['delvat']) {
            $sel = "selected";
        } else {
            $sel = "";
        }
        $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
    }
    $Vatcodes .= "</select>";
    db_conn('cubit');
    $Sl = "SELECT * FROM costcenters";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) > 0) {
        $ctd = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Cost Center</th>\n\t\t\t\t\t<th>Percentage</th>\n\t\t\t\t</tr>";
        $i = 0;
        while ($data = pg_fetch_array($Ri)) {
            $Sl = "SELECT * FROM invc WHERE inv='{$invid}' AND cid='{$data['ccid']}'";
            $Rq = db_exec($Sl);
            $cd = pg_fetch_array($Rq);
            $ctd .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$data['centername']}</td>\n\t\t\t\t\t<td><input type='text' name='ct[{$data['ccid']}]' size='5' value='{$cd['amount']}'>%</td>\n\t\t\t\t</tr>";
            $i++;
        }
        $ctd .= "</table>";
    } else {
        $ctd = "";
    }
    // Retrieve default comments from Cubit
    if (empty($inv["comm"])) {
        db_conn("cubit");
        $sql = "SELECT value FROM settings WHERE constant='DEFAULT_COMMENTS'";
        $commRslt = db_exec($sql) or errDie("Unable to retrieve default comment from Cubit.");
        $comment = base64_decode(pg_fetch_result($commRslt, 0));
    } else {
        $comment = $inv["comm"];
    }
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    // Which display method was selected
    if (isset($sel_frm) && $sel_frm == "stkdes") {
        $sel_frm_cod = "";
        $sel_frm_des = "checked";
    } else {
        $sel_frm_cod = "checked";
        $sel_frm_des = "";
    }
    /*--- Start checks --- */
    /* -- Final Layout -- */
    $details_begin = "\n\t\t<center>\n\t\t<h3>Recurring Invoice</h3>\n\t\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t\t<input type='hidden' name='key' value='update'>\n\t\t\t<input type='hidden' name='invid' value='{$invid}'>\n\t\t\t<input type='hidden' name='stkerr' value='{$stkerr}'>\n\t\t<table " . TMPL_tblDflts . " width='95%'>\n\t\t\t<tr>\n\t\t\t\t<td valign='top'>\n\t\t\t\t\t<div id='cust_selection'>";
    if (empty($ajax_err) && (isset($cusnum) || AJAX)) {
        if (isset($cusnum)) {
            $OTS_OPT = onthespot_encode(SELF, "cust_selection", "deptid={$inv['deptid']}&letters={$letters}&cusnum={$cusnum}&invid={$invid}");
            $custedit = "\n\t\t\t\t<td nowrap>\n\t\t\t\t\t<a href='javascript: popupSized(\"cust-edit.php?cusnum={$cusnum}&onthespot={$OTS_OPT}\", \"edit_cust\", 700, 630);'>\n\t\t\t\t\t\tEdit Customer Details\n\t\t\t\t\t</a>\n\t\t\t\t</td>";
        } else {
            $custedit = "";
        }
        $ajaxOut = "\n\t\t\t<input type='hidden' name='letters' value='{$letters}'>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th colspan='2'> Customer Details </th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Department</td>\n\t\t\t\t\t<td valign='center'>{$dept['deptname']}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Account No.</td>\n\t\t\t\t\t<td valign='center'>{$cust['accno']}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Customer</td>\n\t\t\t\t\t<td valign='center'>{$customers}</td>\n\t\t\t\t\t{$custedit}\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td valign='top'>Customer Address</td>\n\t\t\t\t\t<td valign='center'>" . nl2br($cust['addr1']) . "</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Customer Order number</td>\n\t\t\t\t\t<td valign='center'><input type='text' size='10' name='cordno' value='{$inv['cordno']}'></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Customer VAT Number</td>\n\t\t\t\t\t<td>{$cust['vatnum']}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<th colspan='2'>Point of Sale</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Barcode</td>\n\t\t\t\t\t<td><input type='text' size='13' name='bar' value=''></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Select Using</td>\n\t\t\t\t\t<td>Stock Code<input type='radio' name='sel_frm' value='stkcod' onChange='javascript:document.form.submit();' {$sel_frm_cod}><br>Stock Description<input type='radio' name='sel_frm' value='stkdes' onChange='javascript:document.form.submit();' {$sel_frm_des}></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "' " . ass("Type the first letters of the stock code you are looking for.") . ">\n\t\t\t\t\t<td>Stock Filter</td>\n\t\t\t\t\t<td nowrap><input type='text' size='13' name='ria' value='{$ria}'> <input type='submit' value='Search'> <input type='submit' name='ria' value='Show All'></td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    } else {
        # Query server for depts
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE div = '" . USER_DIV . "' ORDER BY deptname ASC";
        $deptRslt = db_exec($sql) or errDie("Unable to view customers");
        if (pg_numrows($deptRslt) < 1) {
            return "<li class='err'>There are no Departments found in Cubit.</li>";
        } else {
            $depts = "<select id='deptid'>";
            $depts .= "<option value='0'>All Departments</option>";
            while ($dept = pg_fetch_array($deptRslt)) {
                $depts .= "<option value='{$dept['deptid']}'>{$dept['deptname']}</option>";
            }
            $depts .= "</select>";
        }
        if (!isset($ajax_err)) {
            $ajax_err = "";
        }
        $ajaxOut = "\n\t\t\t<script>\n\t\t\t\tfunction updateCustSelection() {\n\t\t\t\t\tdeptid = getObject('deptid').value;\n\t\t\t\t\tletters = getObject('letters').value;\n\t\t\t\t\tajaxRequest('" . SELF . "', 'cust_selection', AJAX_SET, 'letters='+letters+'&deptid='+deptid+'&invid={$invid}');\n\t\t\t\t}\n\t\t\t</script>\n\t\t\t{$ajax_err}\n\t\t\t<table " . TMPL_tblDflts . " width='400'>\n\t\t\t\t<tr>\n\t\t\t\t\t<th colspan='2'>New Recurring Invoice</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Select Department</td>\n\t\t\t\t\t<td valign='center'>{$depts}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>First Letters of customer</td>\n\t\t\t\t\t<td valign='center'><input type='text' size='5' id='letters' maxlength='5'></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t<td valign='center'><input type='button' value='Update' onClick='updateCustSelection();'></td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    }
    if (isset($diffwhBtn) or isset($addprodBtn) or isset($addnon) or isset($upBtn) or isset($saveBtn) or isset($ria)) {
        $jump_bot = "\n\t\t\t<script>\n\t\t\t\twindow.location.hash='bottom';\n\t\t\t</script>";
    } else {
        $jump_bot = "";
    }
    $details_end = "\n\t\t\t\t\t</div>\n\t\t\t\t</td>\n\t\t\t\t<td valign='top' align='right'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th colspan='2'> Invoice Details </th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Invoice No.</td>\n\t\t\t\t\t\t\t<td valign='center'>RI {$inv['invid']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Document Ref No.</td>\n\t\t\t\t\t\t\t<td valign='center'><input type='text' size='5' name='docref' value='{$inv['docref']}'></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Sales Order No.</td>\n\t\t\t\t\t\t\t<td valign='center'><input type='text' size='5' name='ordno' value='{$inv['ordno']}'></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>VAT Inclusive</td>\n\t\t\t\t\t\t\t<td valign='center'>Yes <input type='radio' size='7' name='chrgvat' value='inc' {$chin}> No<input type='radio' size='7' name='chrgvat' value='exc' {$chex}></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Terms</td>\n\t\t\t\t\t\t\t<td valign='center'>{$termssel} Days</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Sales Person</td>\n\t\t\t\t\t\t\t<td valign='center'>{$salesps}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Invoice Date</td>\n\t\t\t\t\t\t\t<td valign='center'>" . mkDateSelect("rinv", $rinv_year, $rinv_month, $rinv_day) . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Available Credit</td>\n\t\t\t\t\t\t\t<td>" . CUR . " " . sprint($avcred) . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Trade Discount</td>\n\t\t\t\t\t\t\t<td valign='center'><input type='text' size='5' name='traddisc' value='{$inv['traddisc']}'>%</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Delivery Charge</td>\n\t\t\t\t\t\t\t<td valign='center'><input type='text' size='7' name='delchrg' value='{$inv['delchrg']}'>{$Vatcodes}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td colspan='2'>{$ctd}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'>{$products}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>\n\t\t\t\t\t<p>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td rowspan='2'>" . mkQuickLinks(ql("cust-credit-stockinv.php", "New Invoice"), ql("rec-invoice-view.php", "View Recurring Invoices"), ql("customers-new.php", "New Customer")) . "\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<th width='25%'>Comments</th>\n\t\t\t\t\t\t\t<td rowspan='5' valign='top' width='50%'>{$error}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td class='" . bg_class() . "' rowspan='4' align='center' valign='top'><textarea name='comm' rows='4' cols='20'>{$comment}</textarea></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t\t<td align='right' valign='top'>\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>SUBTOTAL</td>\n\t\t\t\t\t\t\t<td align='right'>" . CUR . " <input type='hidden' name='SUBTOT' value='{$SUBTOT}'>{$SUBTOT}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Trade Discount</td>\n\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$inv['discount']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Delivery Charge</td>\n\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$inv['delivery']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td><b>VAT {$vat14}</b></td>\n\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$VAT}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<th>GRAND TOTAL</th>\n\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$TOTAL}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td align='right'><input name='diffwhBtn' type='submit' value='Different Store'> | <input name='addprodBtn' type='submit' value='Add Product'> | <input name='addnon' type='submit' value='Add Non stock Product'> | <input type='submit' name='upBtn' value='Update'> </td>\n\t\t\t\t<td> | <input type='submit' name='saveBtn' value='Save &raquo'></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<a name='bottom'>\n\t\t</form>\n\t\t</center>\n\t\t{$jump_bot}";
    if (AJAX) {
        return $ajaxOut;
    } else {
        return "{$details_begin}{$ajaxOut}{$details_end}";
    }
}
function details($_POST, $error = "")
{
    # Get vars
    extract($_POST);
    $v = new validate();
    if (isset($invid)) {
        $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    } else {
        $client = "";
        $vatnum = "";
        $cordno = "";
        $deptid = 2;
        $v->isOk($deptid, "num", 1, 20, "Invalid department number.");
    }
    # display errors, if any
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $error .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    // Initial values
    if (!isset($invid)) {
        $invid = create_dummy($deptid);
        $stkerr = "0,0";
        $cusnum = 0;
    }
    # Get invoice info
    db_connect();
    $sql = "SELECT * FROM pinvoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<li class='err'>Invoice Not Found</li>";
    }
    $inv = pg_fetch_array($invRslt);
    if (!isset($vatnum)) {
        $vatnum = $inv['vatnum'];
    }
    if (!isset($cordno)) {
        $cordno = $inv['cordno'];
    }
    # check if invoice has been printed
    if ($inv['printed'] == "y") {
        $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has already been printed.";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    // get the ID of the first warehouse
    db_conn("exten");
    $sql = "SELECT whid FROM warehouses ORDER BY whid ASC LIMIT 1";
    $rslt = db_exec($sql) or errDie("Error reading warehouses (FWH).");
    if (pg_num_rows($rslt) > 0) {
        $FIRST_WH = pg_fetch_result($rslt, 0, 0);
    } else {
        $FIRST_WH = "-S";
    }
    # Get selected Customer info
    db_connect();
    $sql = "SELECT * FROM customers WHERE cusnum = '{$inv['cusnum']}' AND location != 'int' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to view customer");
    if (pg_numrows($custRslt) < 1) {
        db_connect();
        # Query server for customer info   AND lower(surname) LIKE lower('$letters%')
        $sql = "SELECT cusnum,cusname,surname FROM customers WHERE location != 'int' AND blocked != 'yes' AND div = '" . USER_DIV . "' ORDER BY surname";
        $custRslt = db_exec($sql) or errDie("Unable to view customers");
        if (pg_numrows($custRslt) < 1) {
            $customers = "<select name='cusnum' onChange='javascript:document.form.submit();'>";
            $customers .= "<option value='0' selected>Select Customer</option>";
            while ($cust = pg_fetch_array($custRslt)) {
                $customers .= "<option value='{$cust['cusnum']}'>{$cust['cusname']} {$cust['surname']}</option>";
            }
            $customers .= "</select>";
        } else {
            $customers = "<select name='cusnum' onChange='javascript:document.form.submit();'>";
            $customers .= "<option value='0' selected>Select Customer</option>";
            while ($cust = pg_fetch_array($custRslt)) {
                $customers .= "<option value='{$cust['cusnum']}'>{$cust['cusname']} {$cust['surname']}</option>";
            }
            $customers .= "</select>";
        }
        # Take care of the unset vars
        $cust['addr1'] = "";
        $cust['cusnum'] = "";
        $cust['vatnum'] = "";
        $cust['accno'] = "";
        $cust["bustel"] = $inv["telno"];
        $cust["tel"] = "";
        $cust["cellno"] = "";
    } else {
        $cust = pg_fetch_array($custRslt);
        $sql = "SELECT cusnum, cusname, surname FROM customers WHERE deptid = '{$inv['deptid']}' AND location != 'int' AND blocked != 'yes' AND div = '" . USER_DIV . "' ORDER BY surname";
        $cusRslt = db_exec($sql) or errDie("Unable to view customers");
        # Moarn if customer account has been blocked   AND lower(surname) LIKE lower('$letters%')
        if ($cust['blocked'] == 'yes') {
            $error .= "<li class=err>Error : Selected customer account has been blocked.";
        }
        // $customers = "<input type=hidden name=cusnum value='$cust[cusnum]'>$cust[cusname]  $cust[surname]";
        $cusnum = $cust['cusnum'];
        $customers = "<select name='cusnum' onChange='javascript:document.form.submit();'>";
        $customers .= "<option value='0' selected>Select Customer</option>";
        // $customers .= "<option value='-S' selected>Select Customer</option>";
        while ($cus = pg_fetch_array($cusRslt)) {
            $sel = "";
            if ($cust['cusnum'] == $cus['cusnum']) {
                $sel = "selected";
            }
            $customers .= "<option value='{$cus['cusnum']}' {$sel}>{$cus['cusname']} {$cus['surname']}</option>";
        }
        $customers .= "</select>";
    }
    /* after first customer selection, set telno to customer's (if any) */
    if (isset($prev_cusnum) && $prev_cusnum != $cusnum) {
        if (trim($cust["bustel"]) != "") {
            $inv["telno"] = $cust["bustel"];
        } else {
            if (trim($cust["tel"]) != "") {
                $inv["telno"] = $cust["tel"];
            } else {
                $inv["telno"] = $cust["cellno"];
            }
        }
    }
    /* --- Start Drop Downs --- */
    # Select warehouse
    db_conn("exten");
    $whs = "<select name='whidss[]' onChange='javascript:document.form.submit();'>";
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "' ORDER BY whname ASC";
    $whRslt = db_exec($sql);
    if (pg_numrows($whRslt) < 1) {
        return "<li class='err'> There are no Stores found in Cubit.</li>";
    } else {
        $whs .= "<option value='-S' disabled selected>Select Store</option>";
        while ($wh = pg_fetch_array($whRslt)) {
            if (!user_in_store_team($wh["whid"], USER_ID)) {
                continue;
            }
            $whs .= "<option value='{$wh['whid']}'>({$wh['whno']}) {$wh['whname']}</option>";
        }
    }
    $whs .= "</select>";
    # get sales people
    db_conn("exten");
    $sql = "SELECT * FROM salespeople WHERE div = '" . USER_DIV . "' ORDER BY salesp ASC";
    $salespRslt = db_exec($sql) or errDie("Unable to get sales people.");
    if (pg_numrows($salespRslt) < 1) {
        return "<li class='err'> There are no Sales People found in Cubit.</li>";
    } else {
        $salesps = "<select name='salespn'>";
        while ($salesp = pg_fetch_array($salespRslt)) {
            if ($salesp['salesp'] == $inv['salespn']) {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $salesps .= "<option value='{$salesp['salesp']}' {$sel}>{$salesp['salesp']}</option>";
        }
        $salesps .= "</select>";
    }
    # Keep the charge vat option stable
    if ($inv['chrgvat'] == "inc") {
        $chin = "checked=yes";
        $chex = "";
        $chno = "";
    } elseif ($inv['chrgvat'] == "exc") {
        $chin = "";
        $chex = "checked=yes";
        $chno = "";
    } else {
        $chin = "";
        $chex = "";
        $chno = "checked=yes";
    }
    /* we came as a correction from receive payment page */
    if (isset($_POST["key"]) && $_POST["key"] == "recvpayment_write") {
        $inv["odate"] == $_POST["date"];
        $inv["pcc"] = $_POST["pcc"];
        $inv["pcheque"] = $_POST["pcheque"];
        $inv["pcash"] = $_POST["pcash"];
    } else {
        list($pinv_year, $pinv_month, $pinv_day) = explode("-", $inv['odate']);
    }
    /* --- End Drop Downs --- */
    /* --- Start Products Display --- */
    # select all products
    $products = "\n\t<table " . TMPL_tblDflts . " width='100%'>\n\t<tr>\n\t\t<th>STORE</th>\n\t\t<th>ITEM NUMBER</th>\n\t\t<th>VAT CODE</th>\n\t\t<th>SERIAL NO.</th>\n\t\t<th>DESCRIPTION</th>\n\t\t<th>QTY</th>\n\t\t<th>UNIT PRICE</th>\n\t\t<th>UNIT DISCOUNT</th>\n\t\t<th>AMOUNT</th>\n\t\t<th>Remove</th>\n\t<tr>";
    # get selected stock in this invoice
    db_connect();
    $sql = "SELECT * FROM pinv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $line_count = pg_num_rows($stkdRslt);
    $i = 0;
    $key = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        $stkd['account'] += 0;
        if ($stkd['account'] != 0) {
            # Keep track of selected stock amounts
            $amts[$i] = $stkd['amt'];
            $i++;
            db_conn('core');
            $Sl = "SELECT accid,topacc,accnum,accname FROM accounts WHERE acctype='I' ORDER BY accname";
            $Ri = db_exec($Sl) or errDie("Unable to get accounts.");
            $Accounts = "<select name='accounts[]'>\n\t\t\t<option value='0'>Select Account</option>";
            while ($ad = pg_fetch_array($Ri)) {
                if (isb($ad['accid'])) {
                    continue;
                }
                if ($ad['accid'] == $stkd['account']) {
                    $sel = "selected";
                } else {
                    $sel = "";
                }
                $Accounts .= "<option value='{$ad['accid']}' {$sel}>{$ad['accname']}</option>";
            }
            $Accounts .= "</select>";
            $sernos = "\n\t\t\t\t<input type='hidden' name='sernos[]' value='{$stkd['serno']}'>\n\t\t\t\t<input type='hidden' name='sernos_ss[]' value='{$stkd['serno']}'>";
            # Input qty if not serialised
            $qtyin = "<input type='text' size='3' name='qtys[]' value='{$stkd['qty']}'>";
            $viewcost = "<input type='text' size='8' name='unitcost[]' value='" . sprint($stkd["unitcost"]) . "'>";
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes ORDER BY code";
            $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
            $Vatcodes = "<select name='vatcodes[]'>";
            while ($vd = pg_fetch_array($Ri)) {
                if ($stkd['vatcode'] == $vd['id']) {
                    $sel = "selected";
                } else {
                    $sel = "";
                }
                $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
            }
            $Vatcodes .= "</select>";
            # Put in product
            $products .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td colspan='2'>{$Accounts}<input type='hidden' name='whids[]' value='{$stkd['whid']}'></td>\n\t\t\t\t<td><input type='hidden' name='stkids[]' value='{$stkd['stkid']}'>{$Vatcodes}</td>\n\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t<td><input type='text' size='20' name='descriptions[]' value='{$stkd['description']}'> {$sernos}</td>\n\t\t\t\t<td>{$qtyin}</td>\n\t\t\t\t<td>{$viewcost}</td>\n\t\t\t\t<td>\n\t\t\t\t\t<input type='hidden' name='disc[]' value='{$stkd['disc']}'>\n\t\t\t\t\t<input type='hidden' name='discp[]' value='{$stkd['discp']}'>\n\t\t\t\t</td>\n\t\t\t\t<td><input type='hidden' name='amt[]' value='" . sprint($stkd["amt"]) . "'> " . CUR . " {$stkd['amt']}</td>\n\t\t\t\t<td>\n\t\t\t\t\t<input type='checkbox' name='remprod[]' value='{$key}'>\n\t\t\t\t</td>\n\t\t\t</tr>";
            $key++;
        } else {
            # keep track of selected stock amounts
            $amts[$i] = $stkd['amt'];
            $i++;
            # get warehouse name
            db_conn("exten");
            $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            # get selected stock in this warehouse
            db_connect();
            $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql);
            $stk = pg_fetch_array($stkRslt);
            if ($stk['units'] <= $stk['minlvl']) {
                $error .= "<li class='err'>{$stk['stkcod']} is below minimum level, please notify stock controller.</li>";
            }
            # Serial number
            if ($stk['serd'] == 'yes' && ($inv['serd'] == 'n' || $stkd["serno"] == "")) {
                $sers = ext_getavserials($stkd['stkid']);
                $sernos = "<select name='sernos[]'>";
                foreach ($sers as $skey => $ser) {
                    $sernos .= "<option value='{$ser['serno']}'>{$ser['serno']}</option>";
                }
                $sernos .= "</select>\n\t\t\t\t\t\t\t<input type='hidden' name='sernos_ss[]' value='*_*_*CUBIT_SERIAL_SELECT_BOX*_*_*' />";
            } else {
                $sernos = "\n\t\t\t\t\t<input type='hidden' name='sernos_ss[]' value='{$stkd['ss']}' />\n\t\t\t\t\t<input type='hidden' name='sernos[]' value='{$stkd['serno']}'>{$stkd['ss']}";
            }
            # Input qty if not serialised
            $qtyin = "<input type='text' size='3' name='qtys[]' value='{$stkd['qty']}'>";
            if ($stk['serd'] == 'yes') {
                $qtyin = "<input type='hidden' size='3' name='qtys[]' value='{$stkd['qty']}'>{$stkd['qty']}";
            }
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes ORDER BY code";
            $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
            $Vatcodes = "<select name='vatcodes[]'>";
            while ($vd = pg_fetch_array($Ri)) {
                if ($stkd['vatcode'] == $vd['id']) {
                    $sel = "selected";
                } else {
                    $sel = "";
                }
                $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
            }
            $Vatcodes .= "</select>";
            # check permissions
            if (perm("invoice-unitcost-edit.php")) {
                $viewcost = "<input type='text' size='8' name='unitcost[]' value='" . sprint($stkd["unitcost"]) . "'>";
            } else {
                $viewcost = "<input type='hidden' size='8' name='unitcost[]' value='" . sprint($stkd["unitcost"]) . "'>" . sprint($stkd["unitcost"]);
            }
            # put in product
            $products .= "\n\t\t\t<input type='hidden' name='accounts[]' value='0'>\n\t\t\t<input type='hidden' name='descriptions[]' value=''>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><input type='hidden' name='whids[]' value='{$stkd['whid']}'>{$wh['whname']}</td>\n\t\t\t\t<td>\n\t\t\t\t\t<input type='hidden' name='stkids[]' value='{$stkd['stkid']}'>\n\t\t\t\t\t<a href='#bottom' onclick='openwindow(\"stock-amt-det.php?stkid={$stk['stkid']}\")'>{$stk['stkcod']}</a>\n\t\t\t\t</td>\n\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t<td>{$sernos}</td>\n\t\t\t\t<td>" . extlib_rstr($stk['stkdes'], 30) . "</td>\n\t\t\t\t<td>{$qtyin}</td>\n\t\t\t\t<td>{$viewcost}</td>\n\t\t\t\t<td>\n\t\t\t\t\t<input type='text' size='4' name='disc[]' value='{$stkd['disc']}'><b> OR </b>\n\t\t\t\t\t<input type='text' size='4' name='discp[]' value='{$stkd['discp']}' maxlength='5'>%\n\t\t\t\t</td>\n\t\t\t\t<td><input type='hidden' name='amt[]' value='" . sprint($stkd["amt"]) . "'> " . CUR . sprint($stkd["amt"]) . "</td>\n\t\t\t\t<td>\n\t\t\t\t\t<input type='checkbox' name='remprod[]' value='{$key}'>\n\t\t\t\t</td>\n\t\t\t</tr>";
            $key++;
        }
    }
    # Look above(remprod keys)
    $keyy = $key;
    # Look above(if i = 0 then there are no products)
    if ($i == 0) {
        $done = "";
    } else {
        $SCROLL = "yes";
    }
    # check if stock warehouse was selected
    if (isset($whidss)) {
        foreach ($whidss as $key => $whid) {
            if (isset($stkidss[$key]) && $stkidss[$key] != "-S" && strlen($stkidss[$key]) > 0) {
                # skip if not selected
                if ($whid == "-S") {
                    continue;
                }
                # get selected warehouse name
                db_conn("exten");
                $sql = "SELECT whname FROM warehouses WHERE whid = '{$whid}' AND div = '" . USER_DIV . "'";
                $whRslt = db_exec($sql);
                $wh = pg_fetch_array($whRslt);
                # get selected stock in this warehouse
                db_connect();
                $sql = "SELECT * FROM stock WHERE stkid = '{$stkidss[$key]}' AND div = '" . USER_DIV . "' ORDER BY stkcod ASC";
                $stkRslt = db_exec($sql);
                $stk = pg_fetch_array($stkRslt);
                if ($stk['serd'] == 'yes') {
                    $sers = ext_getavserials($stkidss[$key]);
                    $sernos = "<select name='sernos[]' onChange='javascript:document.form.submit();'>";
                    foreach ($sers as $skey => $ser) {
                        $sernos .= "<option value='{$ser['serno']}'>{$ser['serno']}</option>";
                    }
                    $sernos .= "</select>\n\t\t\t\t\t\t\t\t<input type='hidden' name='sernos_ss[]' value='*_*_*CUBIT_SERIAL_SELECT_BOX*_*_*' />";
                } else {
                    $sernos = "\n\t\t\t\t\t\t<input type='hidden' name='sernos_ss[]' value=''>\n\t\t\t\t\t\t<input type='hidden' name='sernos[]' value=''>";
                }
                /* -- Start Some Checks -- */
                # check if they are selling too much
                if ($stk['units'] - $stk['alloc'] < $qtyss[$key]) {
                    if (!in_array($stk['stkid'], explode(",", $stkerr))) {
                        if ($stk['type'] != 'lab') {
                            $stkerr .= ",{$stk['stkid']}";
                            $error .= "<li class='err'>Warning :  Item number <b>{$stk['stkcod']}</b> does not have enough items available.</li>";
                        }
                    }
                }
                /* -- End Some Checks -- */
                # Calculate the Discount discount
                if ($discs[$key] < 1) {
                    if ($discps[$key] > 0) {
                        $discs[$key] = round($discps[$key] / 100 * $stk['selamt'], 2);
                    }
                } else {
                    $discps[$key] = round($discs[$key] * 100 / $stk['selamt'], 2);
                }
                # Calculate amount
                $amt[$key] = $qtyss[$key] * ($stk['selamt'] - $discs[$key]);
                # Input qty if not serialised
                $qtyin = "<input type='text' size='3' name='qtys[]' value='{$qtyss[$key]}'>";
                if ($stk['serd'] == 'yes') {
                    $qtyin = "<input type='hidden' size='3' name='qtys[]' value='{$qtyss[$key]}'>{$qtyss[$key]}";
                }
                db_conn('cubit');
                $Sl = "SELECT * FROM vatcodes ORDER BY code";
                $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                $Vatcodes = "<select name='vatcodes[]'>";
                while ($vd = pg_fetch_array($Ri)) {
                    if ($stk['vatcode'] == $vd['id']) {
                        $sel = "selected";
                    } else {
                        $sel = "";
                    }
                    $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
                }
                $Vatcodes .= "</select>";
                if (perm("invoice-unitcost-edit.php")) {
                    $viewcost = "<input type='text' size='8' name='unitcost[]' value='" . sprint($stk["selamt"]) . "'>";
                } else {
                    $viewcost = "<input type='hidden' size='8' name='unitcost[]' value='" . sprint($stk["selamt"]) . "'>" . sprint($stk["selamt"]);
                }
                # put in selected warehouse and stock
                $products .= "\n\t\t\t\t<input type='hidden' name='accounts[]' value='0'>\n\t\t\t\t<input type='hidden' name='descriptions[]' value=''>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><input type='hidden' name='whids[]' value='{$whid}'>{$wh['whname']}</td>\n\t\t\t\t\t<td>\n\t\t\t\t\t\t<input type='hidden' name='stkids[]' value='{$stk['stkid']}'>\n\t\t\t\t\t\t<a href='#bottom' onclick='openwindow(\"stock-amt-det.php?stkid={$stk['stkid']}\")'>{$stk['stkcod']}</a>\n\t\t\t\t\t</td>\n\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t<td>{$sernos}</td>\n\t\t\t\t\t<td>" . extlib_rstr($stk['stkdes'], 30) . "</td>\n\t\t\t\t\t<td>{$qtyin}</td>\n\t\t\t\t\t<td>{$viewcost}</td>\n\t\t\t\t\t<td>\n\t\t\t\t\t\t<input type='text' size='4' name='disc[]' value='{$discs[$key]}'><b> OR </b>\n\t\t\t\t\t\t<input type='text' size='4' name='discp[]' value='{$discps[$key]}' maxlength='5'>%\n\t\t\t\t\t</td>\n\t\t\t\t\t<td><input type='hidden' name='amt[]' value='" . sprint($amt[$key]) . "'> " . CUR . sprint($amt[$key]) . "</td>\n\t\t\t\t\t<td><input type='checkbox' name='remprod[]' value='{$keyy}'></td>\n\t\t\t\t</tr>";
                $line_count = 1;
                $keyy++;
            } else {
                if (isset($accountss[$key]) && $accountss[$key] != "0") {
                    db_conn('core');
                    $Sl = "SELECT * FROM accounts WHERE accid='{$accountss[$key]}'";
                    $Ri = db_exec($Sl) or errDie("Unable to get account data.");
                    if (pg_num_rows($Ri) < 1) {
                        return "invalid.";
                    }
                    $ad = pg_fetch_array($Ri);
                    # Calculate amount
                    $amt[$key] = sprint($qtyss[$key] * $unitcosts[$key]);
                    # Input qty if not serialised
                    //$qtyin = "<input type=text size=3 name=qtemp value='$qtyss[$key]'>";
                    $qtyin = "<input type='text' size='3' name='qtys[]' value='{$qtyss[$key]}'>";
                    # Check permissions
                    $viewcost = "<input type='text' size='8' name='unitcost[]' value='" . sprint($unitcosts[$key]) . "'>";
                    db_conn('cubit');
                    $Sl = "SELECT * FROM vatcodes ORDER BY code";
                    $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                    $Vatcodes = "<select name='vatcodes[]'>";
                    while ($vd = pg_fetch_array($Ri)) {
                        if ($vatcodess[$key] == $vd['id']) {
                            $sel = "selected";
                        } else {
                            $sel = "";
                        }
                        $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
                    }
                    $Vatcodes .= "</select>";
                    # Put in selected warehouse and stock
                    $products .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan=2>\n\t\t\t\t\t\t{$ad['accname']}<input type='hidden' name='accounts[]' value='{$accountss[$key]}'>\n\t\t\t\t\t\t<input type='hidden' name='whids[]' value='0'>\n\t\t\t\t\t</td>\n\t\t\t\t\t<td>{$Vatcodes}<input type='hidden' name='stkids[]' value='0'></td>\n\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t<td><input type='text' size='20' name='descriptions[]' value='{$descriptionss[$key]}'></td>\n\t\t\t\t\t<td>{$qtyin}</td>\n\t\t\t\t\t<td>{$viewcost}</td>\n\t\t\t\t\t<td>\n\t\t\t\t\t\t<input type='hidden' name='disc[]' value='0'>\n\t\t\t\t\t\t<input type='hidden' name='discp[]' value='0'>\n\t\t\t\t\t</td>\n\t\t\t\t\t<td><input type='hidden' name='amt[]' value='" . sprint($amt[$key]) . "'> " . CUR . sprint($amt[$key]) . "</td>\n\t\t\t\t\t<td><input type='checkbox' name='remprod[]' value='{$keyy}'></td>\n\t\t\t\t</tr>";
                    $keyy++;
                } else {
                    if (!isset($diffwhBtn)) {
                        # skip if not selected
                        if ($whid == "-S") {
                            continue;
                        }
                        if (!isset($addnon)) {
                            # get warehouse name
                            db_conn("exten");
                            $sql = "SELECT whname FROM warehouses WHERE whid = '{$whid}' AND div = '" . USER_DIV . "'";
                            $whRslt = db_exec($sql);
                            $wh = pg_fetch_array($whRslt);
                            if (isset($des) and $des != "") {
                                $len = strlen($des);
                                if ($des == "Show All") {
                                    $Wh = "";
                                    $des = "";
                                } else {
                                    $Wh = "AND (lower(substr(stkdes,1,'{$len}'))=lower('{$des}') OR lower(substr(stkcod,1,'{$len}'))=lower('{$des}'))";
                                }
                            } else {
                                $Wh = "AND FALSE";
                                $des = "";
                            }
                            # get stock on this warehouse
                            db_connect();
                            $sql = "SELECT * FROM stock WHERE whid = '{$whid}' AND blocked = 'n' AND div = '" . USER_DIV . "' {$Wh} ORDER BY {$sel_frm} ASC";
                            $stkRslt = db_exec($sql) or errDie("Unable to retrieve stocks from database.");
                            if (pg_numrows($stkRslt) < 1) {
                                $error .= "<li class='err'>There are no stock items in the selected warehouse.";
                                continue;
                            }
                            /*						# get selected stock in this warehouse
                            						db_connect();
                            						$sql = "SELECT * FROM stock WHERE stkid = '$stkidss[$key]' AND div = '".USER_DIV."' ORDER BY stkcod ASC";
                            						$stkRslt = db_exec($sql);
                            						$stk = pg_fetch_array($stkRslt);
                            						if($stk['serd'] == 'yes'){
                            							$sers = ext_getavserials($stkidss[$key]);
                            							$sernos = "<select class='width : 15'name='sernos[]' onChange='javascript:document.form.submit();'>";
                            							foreach($sers as $skey => $ser){
                            								$sernos .= "<option value='$ser[serno]'>$ser[serno]</option>";
                            							}
                            							$sernos .= "</select>";
                            						}else{
                            							$sernos = "<input type=hidden name=sernos[] value=''>";
                            						}
                            */
                            if (isset($sel_frm) && $sel_frm == "stkdes") {
                                $descs = "<select class='width : 15'name='stkidss[]' onChange=\"document.form.des.value=''; javascript:document.form.submit();\">";
                                $descs .= "<option value='-S' disabled selected>Select Description</option>";
                                $count = 0;
                                while ($stk = pg_fetch_array($stkRslt)) {
                                    // Check if this stock item has been blocked
                                    if (stock_is_blocked($stk["stkid"])) {
                                        continue;
                                    }
                                    if ($stk["units"] <= 0) {
                                        continue;
                                    }
                                    $descs .= "<option value='{$stk['stkid']}'>{$stk['stkdes']} (" . ($stk['units'] - $stk['alloc']) . ")</option>";
                                }
                                $descs .= "</select> ";
                                $cods = "";
                            } else {
                                $cods = "<select class='width : 15'name='stkidss[]' onChange=\"document.form.des.value=''; javascript:document.form.submit();\">";
                                $cods .= "<option value='-S' disabled selected>Select Number</option>";
                                $count = 0;
                                while ($stk = pg_fetch_array($stkRslt)) {
                                    // Check if this stock item has been blocked
                                    if (stock_is_blocked($stk["stkid"])) {
                                        continue;
                                    }
                                    if ($stk["units"] <= 0) {
                                        continue;
                                    }
                                    $cods .= "<option value='{$stk['stkid']}'>{$stk['stkcod']} (" . ($stk['units'] - $stk['alloc']) . ")</option>";
                                }
                                $cods .= "</select> ";
                                $descs = "";
                            }
                            # put in drop down and warehouse
                            $products .= "\n\t\t\t\t\t\t<input type='hidden' name='accountss[]' value='0'>\n\t\t\t\t\t\t<input type='hidden' name='descriptionss[]' value=''>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t<input type='hidden' name='whidss[]' value='{$whid}'>\n\t\t\t\t\t\t\t\t{$wh['whname']}\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td>{$cods}</td>\n\t\t\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t\t\t<td>{$descs}</td>\n\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t<input type='text' size='3' name='qtyss[]' value='1'>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t<input type='text' size='4' name='discs[] value='0'>\n\t\t\t\t\t\t\t\t<b> OR </b>\n\t\t\t\t\t\t\t\t<input type='text' size='4' name='discps[] value='0' maxlength='5'>%\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t<input type='hidden' name='amts[]' value='0.00'>\n\t\t\t\t\t\t\t\t" . CUR . " 0.00\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t\t</tr>";
                        } else {
                            db_conn('core');
                            $Sl = "SELECT accid,topacc,accnum,accname FROM accounts\n\t\t\t\t\t\t\tWHERE acctype='I' ORDER BY accname";
                            $Ri = db_exec($Sl) or errDie("Unable to get accounts.");
                            $Accounts = "<select name='accountss[]' onChange='javascript:document.form.submit();'>\n\t\t\t\t\t\t<option value='0'>Select Account</option>";
                            while ($ad = pg_fetch_array($Ri)) {
                                if (isb($ad['accid'])) {
                                    continue;
                                }
                                $Accounts .= "\n\t\t\t\t\t\t\t<option value={$ad['accid']}>\n\t\t\t\t\t\t\t\t{$ad['accname']}\n\t\t\t\t\t\t\t</option>";
                            }
                            $Accounts .= "</select>";
                            db_conn('cubit');
                            $Sl = "SELECT * FROM vatcodes ORDER BY code";
                            $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                            $Vatcodes = "<select name='vatcodess[]'>";
                            while ($vd = pg_fetch_array($Ri)) {
                                if ($vd['del'] == "Yes") {
                                    $sel = "selected";
                                } else {
                                    $sel = "";
                                }
                                $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
                            }
                            $Vatcodes .= "</select>";
                            $products .= "\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td colspan='2'>{$Accounts}<input type='hidden' name='whidss[]' value='{$FIRST_WH}'></td>\n\t\t\t\t\t\t\t<input type='hidden' name='stkidss[]' value=''>\n\t\t\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t\t\t<td><input type='text' size='20' name='descriptionss[]'></td>\n\t\t\t\t\t\t\t<td><input type='text' size='3' name='qtyss[]' value='1'></td>\n\t\t\t\t\t\t\t<td><input type='text' name='unitcosts[]' size='7'></td>\n\t\t\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t<input type='hidden' name='discs[]' value='0'>\n\t\t\t\t\t\t\t\t<input type='hidden' name='discps[]' value='0' >\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>";
                        }
                    }
                }
            }
        }
    } else {
        if (!(isset($diffwhBtn) || isset($addnon))) {
            # check if setting exists
            db_connect();
            $sql = "SELECT value FROM set WHERE label = 'DEF_WH' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to check database for existing settings.");
            if (pg_numrows($Rslt) > 0) {
                $set = pg_fetch_array($Rslt);
                $whid = $set['value'];
                if (isset($wtd) && $wtd != 0) {
                    $whid = $wtd;
                }
                # get selected warehouse name
                db_conn("exten");
                $sql = "SELECT whname FROM warehouses WHERE whid = '{$whid}' AND div = '" . USER_DIV . "'";
                $whRslt = db_exec($sql);
                $wh = pg_fetch_array($whRslt);
                if (isset($des) and $des != "") {
                    $len = strlen($des);
                    if ($des == "Show All") {
                        $Wh = "";
                        $des = "";
                    } else {
                        $Wh = "AND (lower(substr(stkdes,1,'{$len}'))=lower('{$des}') OR lower(substr(stkcod,1,'{$len}'))=lower('{$des}'))";
                    }
                } else {
                    $Wh = "AND FALSE";
                    $des = "";
                }
                # get stock on this warehouse
                db_connect();
                $sql = "SELECT * FROM stock WHERE whid = '{$whid}' AND blocked = 'n' AND div = '" . USER_DIV . "' {$Wh} ORDER BY stkcod ASC";
                $stkRslt = db_exec($sql) or errDie("Unable to retrieve stocks from database.");
                if (pg_numrows($stkRslt) < 1) {
                    if (!isset($err)) {
                        $err = "";
                    }
                    $err .= "<li>There are no stock items in the selected store.";
                }
                $stks = "<select name='stkidss[]' onChange=\"document.form.des.value=''; javascript:document.form.submit();\">";
                $stks .= "<option value='-S' disabled selected>Select Number</option>";
                $count = 0;
                while ($stk = pg_fetch_array($stkRslt)) {
                    // Check if this stock item has been blocked
                    if (stock_is_blocked($stk["stkid"])) {
                        continue;
                    }
                    if ($stk["units"] <= 0) {
                        continue;
                    }
                    $stks .= "<option value='{$stk['stkid']}'>{$stk['stkcod']} (" . ($stk['units'] - $stk['alloc']) . ")</option>";
                }
                $stks .= "</select> ";
                $products .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<input type='hidden' name='accountss[]' value='0'>\n\t\t\t\t\t<input type='hidden' name='descriptionss[]' value=''>\n\t\t\t\t\t<input type='hidden' name='vatcodess[]' value=''>\n\t\t\t\t\t<td><input type='hidden' name='whidss[]' value='{$whid}'>{$wh['whname']}</td>\n\t\t\t\t\t<td>{$stks}</td>\n\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t<td><input type='text' size='3' name='qtyss[]' value='1'></td>\n\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t<td>\n\t\t\t\t\t\t<input type='text' size='4' name='discs[]' value='0'><b> OR </b>\n\t\t\t\t\t\t<input type='text' size='4' name='discps[]' value='0' maxlength='5'>%</td><td>" . CUR . " 0.00</td>\n\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t</tr>";
            } else {
                $products .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$whs}</td>\n\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t<td>\n\t\t\t\t\t\t<input type='text' size='4' name='discs[]' value='0'><b> OR </b>\n\t\t\t\t\t\t<input type='text' size='4' name='discps[]' value='0' maxlength='5'>%\n\t\t\t\t\t</td>\n\t\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t</tr>";
            }
        } else {
            if (isset($addnon)) {
                db_conn('core');
                $Sl = "SELECT accid,topacc,accnum,accname FROM accounts WHERE acctype='I' ORDER BY accname";
                $Ri = db_exec($Sl) or errDie("Unable to get accounts.");
                $Accounts = "<select name='accountss[]' onChange='javascript:document.form.submit();'>\n\t\t\t<option value='0'>Select Account</option>";
                while ($ad = pg_fetch_array($Ri)) {
                    if (isb($ad['accid'])) {
                        continue;
                    }
                    $Accounts .= "<option value='{$ad['accid']}'>{$ad['accname']}</option>";
                }
                $Accounts .= "</select>";
                db_conn('cubit');
                $Sl = "SELECT * FROM vatcodes ORDER BY code";
                $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                $Vatcodes = "<select name='vatcodess[]'>";
                while ($vd = pg_fetch_array($Ri)) {
                    if ($vd['del'] == "Yes") {
                        $sel = "selected";
                    } else {
                        $sel = "";
                    }
                    $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
                }
                $Vatcodes .= "</select>";
                //				<input type=hidden name='stkidss[]' value=''>
                $products .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td colspan=2>\n\t\t\t\t\t{$Accounts}<input type='hidden' name='whidss[]' value='{$FIRST_WH}'>\n\t\t\t\t</td>\n\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t<td><input type='text' size='20' name='descriptionss[]'></td>\n\t\t\t\t<td><input type='text' size='3' name='qtyss[]' value='1'></td>\n\t\t\t\t<td><input type='text' name='unitcosts[]' size='7'></td>\n\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t<td>\n\t\t\t\t\t<input type='hidden' name='discs[]' value='0'>\n\t\t\t\t\t<input type='hidden' name='discps[]' value='0' >\n\t\t\t\t</td>\n\t\t\t</tr>";
            }
        }
    }
    /* -- start Listeners -- */
    if (isset($diffwhBtn)) {
        $products .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>{$whs}</td>\n\t\t\t<td>&nbsp;</td>\n\t\t\t<td>&nbsp;</td>\n\t\t\t<td>&nbsp;</td>\n\t\t\t<td>&nbsp;</td>\n\t\t\t<td>&nbsp;</td>\n\t\t\t<td>\n\t\t\t\t<input type='text' size='4' name='discs[]' value='0'><b> OR </b>\n\t\t\t\t<input type='text' size='4' name='discps[]' value='0' maxlength='5'>%\n\t\t\t</td>\n\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t<td>&nbsp;</td>\n\t\t</tr>";
    }
    /* -- End Listeners -- */
    $products .= "</table>";
    /* --- End Products Display --- */
    /* --- Start Some calculations --- */
    $SUBTOT = sprint($inv['subtot']);
    # Calculate tradediscm
    if ($inv['traddisc'] > 0) {
        $traddiscm = sprint($inv['traddisc'] / 100 * ($SUBTOT + $inv['delchrg']));
    } else {
        $traddiscm = "0.00";
    }
    $VATP = TAX_VAT;
    # Calculate subtotal
    $SUBTOT = sprint($inv['subtot']);
    $VAT = sprint($inv['vat']);
    $TOTAL = sprint($inv['total']);
    $inv['delchrg'] = sprint($inv['delchrg']);
    if (!isset($done)) {
        $done = "";
    }
    /* --- End Some calculations --- */
    if ($inv['terms'] == 1) {
        $tc1 = "";
        $tc2 = "checked";
    } else {
        $tc1 = "checked";
        $tc2 = "";
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM settings WHERE constant='PSALES'";
    $Ri = db_exec($Sl) or errDie("Unable to get settings.");
    $data = pg_fetch_array($Ri);
    if ($data['value'] == "Yes") {
        $sc = "checked";
    } else {
        $sc = "";
    }
    $sales = "<td>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<td>{$salesps}</td>\n\t\t\t\t<td>Print</td>\n\t\t\t\t<td><input type='checkbox' name='printsales' {$sc}></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</td>";
    # Query server for depts
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE div = '" . USER_DIV . "' ORDER BY deptname ASC";
    $deptRslt = db_exec($sql) or errDie("Unable to view customers");
    if (pg_numrows($deptRslt) < 1) {
        return "<li class='err'>There are no Departments found in Cubit.</li>";
    } else {
        $depts = "<select name='deptid'>";
        while ($dept = pg_fetch_array($deptRslt)) {
            if ($dept['deptid'] == $inv['deptid']) {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $depts .= "<option value='{$dept['deptid']}' {$sel}>{$dept['deptname']}</option>";
        }
        $depts .= "</select>";
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM users WHERE username='******'";
    $Ri = db_exec($Sl);
    $data = pg_fetch_array($Ri);
    if ($data['help'] != "S") {
        $save = "|<input type='submit' name='saveBtn' value='Save'>";
    } else {
        $save = "";
    }
    if ($inv['rounding'] > 0) {
        $due = sprint($inv['total'] - $inv['rounding']);
        $rd = "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Rounding</td>\n\t\t\t\t\t<td align='right'>R {$inv['rounding']}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<th>Amount Due</th>\n\t\t\t\t\t<td align='right'>R {$due}</td>\n\t\t\t\t</tr>";
    } else {
        $rd = "";
    }
    $inv['delvat'] += 0;
    if ($inv['delvat'] == 0) {
        $Sl = "SELECT * FROM vatcodes WHERE del='Yes'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $vd = pg_fetch_array($Ri);
        $inv['delvat'] = $vd['id'];
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes ORDER BY code";
    $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
    $Vatcodes = "<select name='delvat'>";
    while ($vd = pg_fetch_array($Ri)) {
        if ($vd['id'] == $inv['delvat']) {
            $sel = "selected";
        } else {
            $sel = "";
        }
        $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
    }
    $Vatcodes .= "</select>";
    if (strlen($client) < 1) {
        $client = $inv['cusname'];
    }
    if ($inv['cusnum'] == 0) {
        $cd = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Customer</td>\n\t\t\t\t<td valign='center'><input type='text' size='20' name='client' value='{$client}'></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>VAT Number</td>\n\t\t\t\t<td valign='center'><input type='text' size='20' name='vatnum' value='{$vatnum}'></td>\n\t\t\t</tr>\n\t\t\t";
        $pc = "<input type='hidden' name='pcredit' value='0'>";
    } else {
        $cd = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td valign=top>Customer Address</td>\n\t\t\t\t<td valign=center>" . nl2br($cust['addr1']) . "</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Customer VAT Number</td>\n\t\t\t\t<td>{$cust['vatnum']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Customer Balance</td>\n\t\t\t\t<td nowrap='t'>\n\t\t\t\t\t" . CUR . " {$cust['balance']}\n\t\t\t\t\t<a href='javascript: printer(\"cust-stmnt.php?cusnum={$cusnum}&print=t\");'>Print Statement</a>\n\t\t\t\t</td>\n\t\t\t</tr>";
        $pc = "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Amount On Credit</td>\n\t\t\t<td nowrap='t'>\n\t\t\t\t<input size='12' type='text' name='pcredit' id='pcredit' value='{$inv['pcredit']}' onchange='ptot_update();'>\n\t\t\t\t<input type='button' value='&laquo Total' onclick='paytotal(\"pcredit\");' />\n\t\t\t</td>\n\t\t</tr>";
        if ($line_count > 0) {
            $recvpay = "";
        } else {
            $recvpay = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td colspan='2' align='center'><input type='submit' name='recvpay' id='recvpay' onclick='return ptot_recvpay();' value='Receive Payment: " . CUR . " " . sprint($inv["pcc"] + $inv["pcheque"] + $inv["pcash"]) . "' /></td>\n\t\t\t</tr>";
        }
    }
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    if (!isset($des)) {
        $des = "";
    }
    if (isset($sel_frm) && $sel_frm == "stkdes") {
        $sel_frm_cod = "";
        $sel_frm_des = "checked";
    } else {
        $sel_frm_cod = "checked";
        $sel_frm_des = "";
    }
    if (!isset($recvpay)) {
        $recvpay = "";
    }
    if (empty($inv["comm"])) {
        db_conn("cubit");
        $sql = "SELECT value FROM settings WHERE constant='DEFAULT_POS_COMMENTS'";
        $rslt = db_exec($sql) or errDie("Unable to retrieve default comments from Cubit.");
        $inv["comm"] = base64_decode(pg_fetch_result($rslt, 0));
    }
    /* -- Final Layout -- */
    $details = "\n\t<script language=\"JavaScript\"><!--\n\t\tvar windowReference;\n\n\tfunction openRFPopup() {\n\t\twindowReference = window.open('rfid_batch.php?invid={$invid}','windowName','height=500,width=700,toolbar=no,menubar=no,scrollbars=no');\n\t\tif (!windowReference.opener)\n\t\t\twindowReference.opener = self;\n\t\t}\n\t//--></script>\n\n\t<center><h3>New Point of Sale Invoice</h3>\n\t<form method='POST' name='formName'>\n\t<input type='hidden' name='key' value='update' />\n\t<input type='hidden' name='invid' value='{$invid}' />\n\t<input type='hidden' name='SCROLL' value='yes'>\n\t</form>\n\t<script>\n\tfunction ptot_recvpay() {\n\t\tif (ptot_amt() > 0) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\talert('Enter amounts received by customer above.');\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tfunction pfld_num(fn) {\n\t\ti = getObject(fn).value;\n\n\t\tif (i) {\n\t\t\treturn parseFloat(i);\n\t\t} else {\n\t\t\treturn 0;\n\t\t}\n\t}\n\tfunction ptot_amt(nocredit) {\n\t\ti = pfld_num('pcash');\n\t\ti += pfld_num('pcc');\n\t\ti += pfld_num('pcheque');\n\n\t\tif (!nocredit && getObject('pcredit')) {\n\t\t\ti += pfld_num('pcredit');\n\t\t}\n\n\t\treturn i.toFixed(2);\n\t}\n\n\tfunction ptot_update() {\n\t\tgetObject('ptot').innerHTML = '" . CUR . " ' + ptot_amt();\n\n\t\tif (o = getObject('recvpay')) {\n\t\t\to.value = 'Receive Payment: " . CUR . " ' + ptot_amt(true);\n\t\t}\n\t}\n\n\tfunction paytotal(id) {\n\t\tgetObject('pcash').value = '0.00';\n\t\tgetObject('pcc').value = '0.00';\n\t\tgetObject('pcheque').value = '0.00';\n\t\tif (getObject('pcredit')) getObject('pcredit').value = '0.00';\n\n\t\tgetObject(id).value = getObject('itotal').value;\n\n\t\tptot_update();\n\t}\n\t</script>\n\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t<input type='hidden' name='key' value='update'>\n\t\t<input type='hidden' name='invid' value='{$invid}'>\n\t\t<input type='hidden' name='stkerr' value='{$stkerr}'>\n\t\t<input type='hidden' id='itotal' value='{$TOTAL}' />\n\t\t<input type='hidden' name='prev_cusnum' value='{$cusnum}' />\n\t\t<input type='hidden' name='SCROLL' value='yes'>\n\t<table " . TMPL_tblDflts . " width='95%'>\n \t\t<tr>\n \t\t\t<td valign='top'>\n\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th colspan='2'> Customer Details </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>Department</td>\n\t\t\t\t\t\t<td valign='center'>{$depts}</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>Customer</td>\n\t\t\t\t\t\t<td valign='center'>{$customers}</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t{$cd}\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Customer Telephone Number</td>\n\t\t\t\t\t\t<td valign='center'><input type='text' size='20' name='telno' value='{$inv['telno']}'></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>Customer Order number</td>\n\t\t\t\t\t\t<td valign='center'><input type='text' size='10' name='cordno' value='{$cordno}'></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th colspan='2'>Point of Sale</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>Barcode</td>\n\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t<input type='text' size='13' name='bar' value=''>\n\t\t\t\t\t\t\t<input type='button' onClick='javascript:openRFPopup();' value='RFID Batch'>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th colspan='2'>Options</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>Select Using</td>\n\t\t\t\t\t\t<td>Stock Code<input type='radio' name='sel_frm' value='stkcod' onChange='javascript:document.form.submit();' {$sel_frm_cod}> Stock Description<input type='radio' name='sel_frm' value='stkdes' onChange='javascript:document.form.submit();' {$sel_frm_des}></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Stock Filter</td>\n\t\t\t\t\t\t<td><input type='text' size='13' name='des' value='{$des}'> <input type='submit' value='Search'> <input type='submit' name='des' value='Show All'></td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t</td>\n\t\t\t<td valign='top' align='right'>\n\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th colspan='2'>Invoice Details</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>Invoice No.</td>\n\t\t\t\t\t\t<td valign='center'>{$inv['invid']}</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>Sales Order No.</td>\n\t\t\t\t\t\t<td valign='center'><input type='text' size='5' name='ordno' value='{$inv['ordno']}'></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>Invoice Date</td>\n\t\t\t\t\t\t<td valign='center' nowrap='t'>" . mkDateSelect("pinv", $pinv_year, $pinv_month, $pinv_day) . "</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 nowrap='t'>VAT Inclusive</td>\n\t\t\t\t\t\t<td valign='center'>Yes <input type='radio' size='7' name='chrgvat' value='inc' {$chin}> No<input type='radio' size='7' name='chrgvat' value='exc' {$chex}></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>Sales Person</td>\n\t\t\t\t\t\t{$sales}\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>Trade Discount</td>\n\t\t\t\t\t\t<td valign='center'><input type='text' size='5' name='traddisc' value='{$inv['traddisc']}'>%</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>Delivery Charge</td>\n\t\t\t\t\t\t<td valign='center'><input type='text' size='7' name='delchrg' value='{$inv['delchrg']}'>{$Vatcodes}</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th colspan='2'>Payment Details </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>User</td>\n\t\t\t\t\t\t<td><input type='hidden' name='user' value='" . USER_NAME . "'>" . USER_NAME . "</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 nowrap='t'>Amount Paid Cash</td>\n\t\t\t\t\t\t<td nowrap='t'>\n\t\t\t\t\t\t\t<input size='12' type='text' name='pcash' id='pcash' value='{$inv['pcash']}' onchange='ptot_update();'>\n\t\t\t\t\t\t\t<input type='button' value='&laquo Total' onclick='paytotal(\"pcash\");' />\n\t\t\t\t\t\t</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 nowrap='t'>Amount Paid Cheque</td>\n\t\t\t\t\t\t<td nowrap='t'>\n\t\t\t\t\t\t\t<input size='12' type='text' name='pcheque' id='pcheque' value='{$inv['pcheque']}' onchange='ptot_update();'>\n\t\t\t\t\t\t\t<input type='button' value='&laquo Total' onclick='paytotal(\"pcheque\");' />\n\t\t\t\t\t\t</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 nowrap='t'>Amount Paid Credit Card</td>\n\t\t\t\t\t\t<td nowrap='t'>\n\t\t\t\t\t\t\t<input size='12' type='text' name='pcc' id='pcc' value='{$inv['pcc']}' onchange='ptot_update();'>\n\t\t\t\t\t\t\t<input type='button' value='&laquo Total' onclick='paytotal(\"pcc\");' />\n\t\t\t\t\t\t</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t{$recvpay}\n\t\t\t\t\t{$pc}\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td nowrap='t'>Total Covered</td>\n\t\t\t\t\t\t<td nowrap='t' id='ptot'>" . CUR . " " . sprint($inv["pcash"] + $inv["pcheque"] + $inv["pcc"] + $inv["pcredit"]) . "</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t</td>\n\t\t</tr>\n\t\t<tr><td><br></td></tr>\n\t\t<tr>\n\t\t\t<td colspan='2'>{$products}</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td width='70%' valign='top'>\n\t\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td rowspan='2'>" . mkQuickLinks(ql("pos-invoice-new-no-neg.php", "New POS Invoice"), ql("pos-invoice-list.php", "View POS Invoices"), ql("customers-new.php", "New Customer")) . "\n\t\t\t\t\t\t</td>\n\t\t\t\t\t\t<th width='30%'>Comments</th>\n\t\t\t\t\t\t<td rowspan='5' valign='top' width='40%'>{$error}</td></tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td rowspan='4' align='center' valign='top'><textarea name='comm' rows='4' cols='20'>{$inv['comm']}</textarea></td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t</td>\n\t\t\t<td align='right' valign='top' width='30%'>\n\t\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>SUBTOTAL</td>\n\t\t\t\t\t\t<td align='right'>" . CUR . " <input type='hidden' name='SUBTOT' value='{$SUBTOT}'>{$SUBTOT}</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>Trade Discount</td>\n\t\t\t\t\t\t<td align='right'>" . CUR . " {$inv['discount']}</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>Delivery Charge</td>\n\t\t\t\t\t\t<td align='right'>" . CUR . " {$inv['delivery']}</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><b>VAT {$vat14}</b></td>\n\t\t\t\t\t\t<td align='right'>" . CUR . " {$VAT}</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<th>GRAND TOTAL</th>\n\t\t\t\t\t\t<td align='right'>" . CUR . " {$TOTAL}</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t{$rd}\n\t\t\t\t</table>\n\t\t\t</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td align='right'><input name='diffwhBtn' type='submit' value='Different Store'> | <input name='addprodBtn' type='submit' value='Add Product'>| <input name='addnon' type='submit' value='Add Non stock Product'>{$save} </td>\n\t\t\t<td>| <input type='submit' name='upBtn' value='Update'>{$done}</td>\n\t\t</tr>\n\t</table>\n\t<a name='bottom'>\n\t</form>\n\t</center>";
    return $details;
}
function details($_POST, $error = "")
{
    extract($_POST);
    # validate input
    include "libs/validate.lib.php";
    $v = new validate();
    if (isset($sordid)) {
        $v->isOk($sordid, "num", 1, 20, "Invalid sales order number.");
    }
    if (isset($deptid)) {
        $v->isOk($deptid, "num", 1, 20, "Invalid department number.");
    }
    if (isset($letters)) {
        $v->isOk($letters, "string", 0, 5, "Invalid First 3 Letters.");
    }
    # display errors, if any
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $error .= "<li class='err'>{$e['msg']}</li>";
        }
        $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    if (!isset($sordid)) {
        $sordid = create_dummy($deptid);
        $stkerr = "0,0";
    }
    if (!isset($proforma)) {
        $proforma = "";
    }
    if (!isset($done)) {
        $done = "";
    }
    # Get Sales Order info
    db_connect();
    $sql = "SELECT * FROM sorders WHERE sordid = '{$sordid}' AND div = '" . USER_DIV . "'";
    $sordRslt = db_exec($sql) or errDie("Unable to get Sales Order information");
    if (pg_numrows($sordRslt) < 1) {
        return "<li class='err'>Sales Order Not Found</li>";
    }
    $sord = pg_fetch_array($sordRslt);
    # check if Sales Order has been printed
    if ($sord['accepted'] == "y") {
        $error = "<li class='err'> Error : Sales Order number <b>{$sordid}</b> has already been printed.";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$sord['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<li class='err'>Department not Found.</li>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    # Get selected customer info
    db_connect();
    $sql = "SELECT * FROM customers WHERE cusnum = '{$sord['cusnum']}' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to view customer");
    if (pg_numrows($custRslt) < 1) {
        db_connect();
        if ($deptid == "0") {
            $searchdept = "";
        } else {
            $searchdept = "deptid = '{$sord['deptid']}' AND ";
        }
        # Query server for customer info
        $sql = "SELECT cusnum, cusname, surname FROM customers WHERE {$searchdept} location != 'int' AND lower(surname) LIKE lower('{$letters}%') AND div = '" . USER_DIV . "' ORDER BY surname";
        $custRslt = db_exec($sql) or errDie("Unable to view customers");
        if (pg_numrows($custRslt) < 1) {
            $err = "<li class='err'>No customer names starting with <b>{$letters}</b> in database.</li>";
            return view_err($_POST, $err);
        } else {
            $customers = "<select name='cusnum' onChange='javascript:document.form.submit();'>";
            $customers .= "<option value='-S' selected>Select Customer</option>";
            while ($cust = pg_fetch_array($custRslt)) {
                $customers .= "<option value='{$cust['cusnum']}'>{$cust['cusname']} {$cust['surname']}</option>";
            }
            $customers .= "</select>";
        }
        # take care of the unset vars
        $cust['addr1'] = "";
        $cust['cusnum'] = "";
        $cust['vatnum'] = "";
        $cust['accno'] = "";
    } else {
        $cust = pg_fetch_array($custRslt);
        # moarn if customer account has been blocked
        if ($cust['blocked'] == 'yes') {
            return "<li class='err'>Error : Selected customer account has been blocked.</li>";
        }
        $customers = "<input type='hidden' name='cusnum' value='{$cust['cusnum']}'>{$cust['cusname']}  {$cust['surname']}";
        $cusnum = $cust['cusnum'];
    }
    /* --- Start Drop Downs --- */
    # Select warehouse
    db_conn("exten");
    //	$whs = "<select name='whidss[]' onChange='javascript:document.form.submit();'>";
    $whs = "<select name='whidss[]'>";
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "' ORDER BY whname ASC";
    $whRslt = db_exec($sql);
    if (pg_numrows($whRslt) < 1) {
        return "<li class='err'> There are no Stores found in Cubit.</li>";
    } else {
        $whs .= "<option value='-S' disabled selected>Select Store</option>";
        while ($wh = pg_fetch_array($whRslt)) {
            if (!user_in_store_team($wh["whid"], USER_ID)) {
                continue;
            }
            $whs .= "<option value='{$wh['whid']}'>({$wh['whno']}) {$wh['whname']}</option>";
        }
    }
    $whs .= "</select>";
    # get sales people
    db_conn("exten");
    $sql = "SELECT * FROM salespeople WHERE div = '" . USER_DIV . "' ORDER BY salesp ASC";
    $salespRslt = db_exec($sql) or errDie("Unable to get sales people.");
    if (pg_numrows($salespRslt) < 1) {
        return "<li class='err'> There are no Sales People found in Cubit.</li>";
    } else {
        $salesps = "<select name='salespn'>";
        while ($salesp = pg_fetch_array($salespRslt)) {
            if ($salesp['salesp'] == $sord['salespn']) {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $salesps .= "<option value='{$salesp['salesp']}' {$sel}>{$salesp['salesp']}</option>";
        }
        $salesps .= "</select>";
    }
    # days drop downs
    $days = array("0" => "0", "7" => "7", "14" => "14", "30" => "30", "60" => "60", "90" => "90", "120" => "120");
    $termssel = extlib_cpsel("terms", $days, $sord['terms']);
    # Keep the charge vat option stable
    if ($sord['chrgvat'] == "inc") {
        $chin = "checked=yes";
        $chex = "";
        $chno = "";
    } elseif ($sord['chrgvat'] == "exc") {
        $chin = "";
        $chex = "checked=yes";
        $chno = "";
    } else {
        $chin = "";
        $chex = "";
        $chno = "checked=yes";
    }
    if ($sord["display_costs"] == "yes") {
        $dc_sel["yes"] = "checked";
        $dc_sel["no"] = "";
    } else {
        $dc_sel["yes"] = "";
        $dc_sel["no"] = "checked";
    }
    # format date
    list($sord_year, $sord_month, $sord_day) = explode("-", $sord['odate']);
    list($ddate_year, $ddate_month, $ddate_day) = explode("-", $sord["ddate"]);
    /* --- End Drop Downs --- */
    // get the ID of the first warehouse
    db_conn("exten");
    $sql = "SELECT whid FROM warehouses ORDER BY whid ASC LIMIT 1";
    $rslt = db_exec($sql) or errDie("Error reading warehouses (FWH).");
    if (pg_num_rows($rslt) > 0) {
        $FIRST_WH = pg_fetch_result($rslt, 0, 0);
    } else {
        $FIRST_WH = "-S";
    }
    /* --- Start Products Display --- */
    # select all products
    $products = "\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t<tr>\n\t\t\t\t<th>STORE</th>\n\t\t\t\t<th>ITEM NUMBER</th>\n\t\t\t\t<th>VAT CODE</th>\n\t\t\t\t<th>DESCRIPTION</th>\n\t\t\t\t<th>QTY</th>\n\t\t\t\t<th>UNIT PRICE</th>\n\t\t\t\t<th>UNIT DISCOUNT</th>\n\t\t\t\t<th>AMOUNT</th>\n\t\t\t\t<th>Remove</th>\n\t\t\t</tr>";
    # get selected stock in this Sales Order
    db_connect();
    $sql = "SELECT * FROM sorders_items  WHERE sordid = '{$sordid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $i = 0;
    $key = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        $stkd['account'] += 0;
        if ($stkd['account'] != 0) {
            # Keep track of selected stock amounts
            $amts[$i] = $stkd['amt'];
            $i++;
            $Accounts = "\n\t\t\t\t<select name='accounts[]'>\n\t\t\t\t\t<option value='0'>Select Account</option>";
            $useaccdrop = getCSetting("USE_NON_STOCK_ACCOUNTS");
            if (isset($useaccdrop) and $useaccdrop == "yes") {
                db_connect();
                $acc_sql = "SELECT * FROM non_stock_account_list ORDER BY accname";
                $run_acc = db_exec($acc_sql) or errDie("Unable to get account information.");
                if (pg_numrows($run_acc) > 0) {
                    while ($acc = pg_fetch_array($run_acc)) {
                        if ($acc['accid'] == $stkd['account']) {
                            $Accounts .= "<option value='{$acc['accid']}' selected>{$acc['accname']}</option>";
                        } else {
                            $Accounts .= "<option value='{$acc['accid']}'>{$acc['accname']}</option>";
                        }
                    }
                    $Accounts .= "</select>";
                }
            } else {
                db_conn('core');
                $Sl = "SELECT accid, topacc, accnum, accname FROM accounts WHERE acctype='I' ORDER BY accname";
                $Ri = db_exec($Sl) or errDie("Unable to get accounts.");
                while ($ad = pg_fetch_array($Ri)) {
                    if (isb($ad['accid'])) {
                        continue;
                    }
                    if ($ad['accid'] == $stkd['account']) {
                        $sel = "selected";
                    } else {
                        $sel = "";
                    }
                    $Accounts .= "<option value='{$ad['accid']}' {$sel}>{$ad['accname']}</option>";
                }
                $Accounts .= "</select>";
            }
            $sernos = "";
            # Input qty if not serialised
            $qtyin = "<input type='text' size='3' name='qtys[]' value='{$stkd['qty']}'>";
            $stkd['unitcost'] = sprint($stkd['unitcost']);
            $viewcost = "<input type='text' size='8' name='unitcost[]' value='{$stkd['unitcost']}'>";
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes ORDER BY code";
            $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
            $Vatcodes = "\n\t\t\t\t<select name='vatcodes[]'>\n\t\t\t\t\t<option value='0'>Select</option>";
            while ($vd = pg_fetch_array($Ri)) {
                if ($stkd['vatcode'] == $vd['id']) {
                    $sel = "selected";
                } else {
                    $sel = "";
                }
                $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
            }
            $Vatcodes .= "</select>";
            $stkd['amt'] = sprint($stkd['amt']);
            # Put in product
            $products .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='2'>\n\t\t\t\t\t\t{$Accounts}\n\t\t\t\t\t\t<input type='hidden' name='whids[]' value='{$stkd['whid']}'>\n\t\t\t\t\t</td>\n\t\t\t\t\t<td><input type='hidden' name='stkids[]' value='{$stkd['stkid']}'>{$Vatcodes}</td>\n\t\t\t\t\t<td><input type='text' size='20' name='descriptions[]' value='{$stkd['description']}'> {$sernos}</td>\n\t\t\t\t\t<td>{$qtyin}</td>\n\t\t\t\t\t<td>{$viewcost}</td>\n\t\t\t\t\t<td><input type='hidden' name='disc[]' value='{$stkd['disc']}'><input type='hidden' name='discp[]' value='{$stkd['discp']}'></td>\n\t\t\t\t\t<td nowrap><input type='hidden' name='amt[]' value='{$stkd['amt']}'> " . CUR . " {$stkd['amt']}</td>\n\t\t\t\t\t<td><input type='checkbox' name='remprod[]' value='{$key}'><input type='hidden' name='SCROLL' value='yes'></td>\n\t\t\t\t</tr>";
            $key++;
        } else {
            # keep track of selected stock amounts
            $amts[$i] = $stkd['amt'];
            $i++;
            # get selected stock in this warehouse
            db_connect();
            $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql);
            $stk = pg_fetch_array($stkRslt);
            # get warehouse name
            db_conn("exten");
            $sql = "SELECT whname FROM warehouses WHERE whid = '{$stk['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes ORDER BY code";
            $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
            $Vatcodes = "\n\t\t\t\t<select name='vatcodes[]'>";
            //<option value='0'>Select</option>";
            while ($vd = pg_fetch_array($Ri)) {
                if ($stkd['vatcode'] == $vd['id']) {
                    $sel = "selected";
                } else {
                    $sel = "";
                }
                $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
            }
            $Vatcodes .= "</select>";
            $stkd['unitcost'] = sprint($stkd['unitcost']);
            $stkd['amt'] = sprint($stkd['amt']);
            //			$sql = "SELECT * FROM manufact.jobcards WHERE recipe!='yes' AND completion!='1'";
            //			$job_rslt = db_exec($sql) or errDie("Unable to retrieve jobs.");
            //
            //			$job_sel = "<select name='job_id[]' style='width: 100%'>";
            //			while ($job_data = pg_fetch_array($job_rslt)) {
            //				if ($stkd["jobcard_id"] == $job_data["id"]) {
            //					$sel = "selected";
            //				} else {
            //					$sel = "";
            //				}
            //
            //				$job_sel .= "<option value='$job_data[id]' $sel>
            //					$job_data[id] $job_data[description]
            //				</option>";
            //			}
            //			$job_sel .= "</select>";
            //	<tr>
            //				<td bgcolor='#ff0000' width='10%'>
            //					$job_sel<br />
            //					<input type='submit' name='pur[]' value='Add To Purchase Resource Planning'>
            //				</td>
            //			</tr>
            // rowspan='2'
            # put in product
            $products .= "\n\t\t\t\t<input type='hidden' name='accounts[]' value='0'>\n\t\t\t\t<input type='hidden' name='descriptions[]' value=''>\n\t\t\t\t<input type='hidden' name='amt[]' value='{$stkd['amt']}'>\n\t\t\t\t<input type='hidden' name='pqty[{$stk['stkid']}]' value='{$stkd['qty']}' />\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><input type='hidden' name='whids[]' value='{$stkd['whid']}'>{$wh['whname']}</td>\n\t\t\t\t\t<td><input type='hidden' name='stkids[]' value='{$stkd['stkid']}'><a href='#' onclick='openwindow(\"stock-amt-det.php?stkid={$stk['stkid']}\")'>{$stk['stkcod']}</a></td>\n\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t<td>" . extlib_rstr($stk['stkdes'], 30) . "</td>\n\t\t\t\t\t<td><input type='text' size='3' name='qtys[]' value='{$stkd['qty']}'></td>\n\t\t\t\t\t<td><input type='text' size='8' name='unitcost[]' value='{$stkd['unitcost']}'></td>\n\t\t\t\t\t<td><input type='text' size='4' name='disc[]' value='{$stkd['disc']}'> OR <input type='text' size='4' name='discp[]' value='{$stkd['discp']}' maxlength=5>%</td>\n\t\t\t\t\t<td>" . CUR . " {$stkd['amt']}</td>\n\t\t\t\t\t<td><input type='checkbox' name='remprod[]' value='{$key}'><input type='hidden' name='SCROLL' value='yes'></td>\n\t\t\t\t</tr>";
            $key++;
        }
    }
    # Look above(remprod keys)
    $keyy = $key;
    # look above(if i = 0 then there are no products)
    if ($i == 0) {
        $done = "";
    }
    #get negative stock setting
    $neg_setting = getCsetting("SORDER_NEG_STOCK");
    if (!isset($neg_setting) or strlen($neg_setting) < 1) {
        $neg_setting = "yes";
    }
    if ($neg_setting == "yes") {
        $search_neg_stock = "";
    } else {
        $search_neg_stock = " AND (units > 0) ";
    }
    # check if stock warehouse was selected
    if (isset($whidss)) {
        foreach ($whidss as $key => $whid) {
            if (isset($stkidss[$key]) && $stkidss[$key] != "-S" && isset($cust['pricelist'])) {
                # skip if not selected
                if ($whid == "-S") {
                    continue;
                }
                # get selected stock in this warehouse
                db_connect();
                $sql = "SELECT * FROM stock WHERE stkid = '{$stkidss[$key]}' AND div = '" . USER_DIV . "' ORDER BY stkcod ASC";
                $stkRslt = db_exec($sql);
                $stk = pg_fetch_array($stkRslt);
                # get selected warehouse name
                db_conn("exten");
                $sql = "SELECT whname FROM warehouses WHERE whid = '{$stk['whid']}' AND div = '" . USER_DIV . "'";
                $whRslt = db_exec($sql);
                $wh = pg_fetch_array($whRslt);
                # get price from price list if it is set
                if (isset($cust['pricelist'])) {
                    # get selected stock in this warehouse
                    db_conn("exten");
                    $sql = "SELECT price FROM plist_prices WHERE listid = '{$cust['pricelist']}' AND stkid = '{$stk['stkid']}' AND div = '" . USER_DIV . "'";
                    $plRslt = db_exec($sql);
                    if (pg_numrows($plRslt) > 0) {
                        $pl = pg_fetch_array($plRslt);
                        $stk['selamt'] = $pl['price'];
                    }
                }
                /* -- Start Some Checks -- */
                # check if they are selling too much
                if ($stk['units'] - $stk['alloc'] < $qtyss[$key]) {
                    if (!in_array($stk['stkid'], explode(",", $stkerr))) {
                        if ($stk['type'] != 'lab') {
                            $stkerr .= ",{$stk['stkid']}";
                            $error .= "<li class='err'>Warning :  Item number <b>{$stk['stkcod']}</b> does not have enough items available.</li>";
                        }
                    }
                }
                /* -- End Some Checks -- */
                # Calculate the Discount discount
                if ($discs[$key] < 1) {
                    if ($discps[$key] > 0) {
                        $discs[$key] = round($discps[$key] / 100 * $stk['selamt'], 2);
                    }
                } else {
                    $discps[$key] = round($discs[$key] * 100 / $stk['selamt'], 2);
                }
                # Calculate amount
                $amt[$key] = $qtyss[$key] * ($stk['selamt'] - $discs[$key]);
                db_conn('cubit');
                $Sl = "SELECT * FROM vatcodes ORDER BY code";
                $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                $Vatcodes = "\n\t\t\t\t\t<select name='vatcodes[]'>\n\t\t\t\t\t\t<option value='0'>Select</option>";
                while ($vd = pg_fetch_array($Ri)) {
                    if ($stk['vatcode'] == $vd['id']) {
                        $sel = "selected";
                    } else {
                        $sel = "";
                    }
                    $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
                }
                $Vatcodes .= "</select>";
                $amt[$key] = sprint($amt[$key]);
                $stk['selamt'] = sprint($stk['selamt']);
                # put in selected warehouse and stock
                $products .= "\n\t\t\t\t\t<input type='hidden' name='accounts[]' value='0'>\n\t\t\t\t\t<input type='hidden' name='descriptions[]' value=''>\n\t\t\t\t\t<input type='hidden' name='whids[]' value='{$whid}'>\n\t\t\t\t\t<input type='hidden' name='stkids[]' value='{$stk['stkid']}'>\n\t\t\t\t\t<input type='hidden' name='amt[]' value='{$amt[$key]}'>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>{$wh['whname']}</td>\n\t\t\t\t\t\t<td><a href='#' onclick='openwindow(\"stock-amt-det.php?stkid={$stk['stkid']}\")'>{$stk['stkcod']}</a></td>\n\t\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t\t<td>" . extlib_rstr($stk['stkdes'], 30) . "</td>\n\t\t\t\t\t\t<td><input type='text' size='3' name='qtys[]' value='{$qtyss[$key]}'></td>\n\t\t\t\t\t\t<td><input type='text' size='8' name='unitcost[]' value='{$stk['selamt']}'></td>\n\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t<input type='text' size='4' name='disc[]' value='{$discs[$key]}'>\n\t\t\t\t\t\t\tOR\n\t\t\t\t\t\t\t<input type='text' size='4' name='discp[]' value='{$discps[$key]}' maxlength=5>%\n\t\t\t\t\t\t</td>\n\t\t\t\t\t\t<td nowrap>" . CUR . " {$amt[$key]}</td>\n\t\t\t\t\t\t<td><input type='checkbox' name='remprod[]' value='{$keyy}'></td>\n\t\t\t\t\t</tr>";
                $keyy++;
            } else {
                if (isset($accountss[$key]) && $accountss[$key] != "0" && isset($cust['pricelist'])) {
                    db_conn('core');
                    $Sl = "SELECT * FROM accounts WHERE accid='{$accountss[$key]}'";
                    $Ri = db_exec($Sl) or errDie("Unable to get account data.");
                    if (pg_num_rows($Ri) < 1) {
                        return "invalid.";
                    }
                    $ad = pg_fetch_array($Ri);
                    # Calculate amount
                    $amt[$key] = sprint($qtyss[$key] * $unitcosts[$key]);
                    # Input qty if not serialised
                    $qtyin = "<input type='text' size='3' name='qtys[]' value='{$qtyss[$key]}'>";
                    # Check permissions
                    $unitcosts[$key] = sprint($unitcosts[$key]);
                    $viewcost = "<input type='text' size='8' name='unitcost[]' value='{$unitcosts[$key]}'>";
                    db_conn('cubit');
                    $Sl = "SELECT * FROM vatcodes ORDER BY code";
                    $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                    $Vatcodes = "\n\t\t\t\t\t<select name='vatcodes[]'>\n\t\t\t\t\t\t<option value='0'>Select</option>";
                    while ($vd = pg_fetch_array($Ri)) {
                        if ($vatcodess[$key] == $vd['id']) {
                            $sel = "selected";
                        } else {
                            $sel = "";
                        }
                        $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
                    }
                    $Vatcodes .= "</select>";
                    $amt[$key] = sprint($amt[$key]);
                    # Put in selected warehouse and stock
                    $products .= "\n\t\t\t\t\t<input type='hidden' name='accounts[]' value='{$accountss[$key]}'>\n\t\t\t\t\t<input type='hidden' name='whids[]' value='0'>\n\t\t\t\t\t<input type='hidden' name='stkids[]' value='0'>\n\t\t\t\t\t<input type='hidden' name='disc[]' value='0'>\n\t\t\t\t\t<input type='hidden' name='discp[]' value='0'>\n\t\t\t\t\t<input type='hidden' name='amt[]' value='{$amt[$key]}'>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td colspan='2'>{$ad['accname']}</td>\n\t\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t\t<td><input type='text' size='20' name='descriptions[]' value='{$descriptionss[$key]}'></td>\n\t\t\t\t\t\t<td>{$qtyin}</td>\n\t\t\t\t\t\t<td>{$viewcost}</td>\n\t\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t\t<td nowrap> " . CUR . " {$amt[$key]}</td>\n\t\t\t\t\t\t<td><input type='checkbox' name='remprod[]' value='{$keyy}'></td>\n\t\t\t\t\t</tr>";
                    $keyy++;
                } else {
                    # skip if not selected
                    if ($whid == "-S") {
                        continue;
                    }
                    if (!isset($addnon)) {
                        if (isset($filter_store) and $filter_store != "0") {
                            # get warehouse name
                            db_conn("exten");
                            $sql = "SELECT whname FROM warehouses WHERE whid = '{$filter_store}' AND div = '" . USER_DIV . "'";
                            $whRslt = db_exec($sql);
                            $wh = pg_fetch_array($whRslt);
                        }
                        # get stock on this warehouse
                        db_connect();
                        if (isset($ria) and $ria != "") {
                            $len = strlen($ria);
                            if ($ria == "Show All") {
                                $Wh = "";
                                $ria = "";
                            } else {
                                $Wh = "AND (lower(stkdes) LIKE lower('%{$ria}%')) OR (lower(stkcod) LIKE lower('%{$ria}%'))";
                                $ria = "";
                            }
                        } else {
                            $Wh = "AND FALSE";
                            $ria = "";
                        }
                        $check_setting = getCSetting("OPTIONAL_STOCK_FILTERS");
                        if (isset($check_setting) and $check_setting == "yes") {
                            if (isset($filter_class) and $filter_class != "0") {
                                $Wh .= " AND prdcls = '{$filter_class}'";
                            }
                            if (isset($filter_cat) and $filter_cat != "0") {
                                $Wh .= " AND catid = '{$filter_cat}'";
                            }
                        }
                        if (isset($filter_store) and $filter_store != "0") {
                            $Wh .= " AND whid = '{$filter_store}'";
                        }
                        $sql = "SELECT * FROM stock WHERE blocked = 'n' {$search_neg_stock} AND div = '" . USER_DIV . "' {$Wh} ORDER BY stkcod ASC";
                        $stkRslt = db_exec($sql) or errDie("Unable to retrieve stocks from database.");
                        if (pg_numrows($stkRslt) < 1) {
                            $error .= "<li class='err'>There are no stock items in the selected store.</li>";
                            continue;
                        }
                        if ($sel_frm == "stkcod") {
                            $cods = "<select name='stkidss[]' onChange='javascript:document.form.submit();'>";
                            $cods .= "<option value='-S' disabled selected>Select Number</option>";
                            $count = 0;
                            while ($stk = pg_fetch_array($stkRslt)) {
                                $cods .= "<option value='{$stk['stkid']}'>{$stk['stkcod']} (" . sprint3($stk['units'] - $stk['alloc']) . ")</option>";
                            }
                            $cods .= "</select> ";
                            $descs = "";
                        } else {
                            $descs = "<select style='width:250px' name='stkidss[]' onChange='javascript:document.form.submit();'>";
                            $descs .= "<option value='-S' disabled selected>Select Description</option>";
                            $count = 0;
                            while ($stk = pg_fetch_array($stkRslt)) {
                                $descs .= "<option value='{$stk['stkid']}'>{$stk['stkdes']} (" . sprint3($stk['units'] - $stk['alloc']) . ")</option>";
                            }
                            $descs .= "</select> ";
                            $cods = "";
                        }
                        db_conn('cubit');
                        $Sl = "SELECT * FROM vatcodes ORDER BY code";
                        $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                        $Vatcodes = "\n\t\t\t\t\t\t<select name='vatcodess[]'>\n\t\t\t\t\t\t\t<option value='0'>Select</option>";
                        while ($vd = pg_fetch_array($Ri)) {
                            if ($vd['del'] == "Yes") {
                                $sel = "selected";
                            } else {
                                $sel = "";
                            }
                            $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
                        }
                        $Vatcodes .= "</select>";
                        # put in drop down and warehouse
                        $products .= "\n\t\t\t\t\t\t<input type='hidden' name='accountss[]' value='0'>\n\t\t\t\t\t\t<input type='hidden' name='descriptionss[]' value=''>\n\t\t\t\t\t\t<input type='hidden' name='whidss[]' value='{$filter_store}'>\n\t\t\t\t\t\t<input type='hidden' name='amts[]' value='0.00'>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t<td>{$cods}<input type='hidden' name='vatcodess' value='0'></td>\n\t\t\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t\t\t<td>{$descs}</td>\n\t\t\t\t\t\t\t<td><input type='text' size='3' name='qtyss[]'  value='1'></td>\n\t\t\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t" . CUR . " <input type='text' size='4' name='discs[]' value='0'>\n\t\t\t\t\t\t\t\tOR\n\t\t\t\t\t\t\t\t<input type='text' size='4' name='discps[]' value='0' maxlength='5'>%\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t\t</tr>";
                    } else {
                        $Accounts = "\n\t\t\t\t\t\t<select name='accountss[]'>\n\t\t\t\t\t\t\t<option value='0'>Select Account</option>";
                        $useaccdrop = getCSetting("USE_NON_STOCK_ACCOUNTS");
                        if (isset($useaccdrop) and $useaccdrop == "yes") {
                            db_connect();
                            $acc_sql = "SELECT * FROM non_stock_account_list ORDER BY accname";
                            $run_acc = db_exec($acc_sql) or errDie("Unable to get account information.");
                            if (pg_numrows($run_acc) > 0) {
                                while ($acc = pg_fetch_array($run_acc)) {
                                    $Accounts .= "<option value='{$acc['accid']}'>{$acc['accname']}</option>";
                                }
                                $Accounts .= "</select>";
                            }
                        } else {
                            db_conn('core');
                            $Sl = "SELECT accid,topacc,accnum,accname FROM accounts WHERE acctype='I' ORDER BY accname";
                            $Ri = db_exec($Sl) or errDie("Unable to get accounts.");
                            while ($ad = pg_fetch_array($Ri)) {
                                if (isb($ad['accid'])) {
                                    continue;
                                }
                                $Accounts .= "<option value='{$ad['accid']}'>{$ad['accname']}</option>";
                            }
                            $Accounts .= "</select>";
                        }
                        db_conn('cubit');
                        $Sl = "SELECT * FROM vatcodes ORDER BY code";
                        $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                        $Vatcodes = "\n\t\t\t\t\t\t<select name='vatcodess[]'>\n\t\t\t\t\t\t\t<option value='0'>Select</option>";
                        while ($vd = pg_fetch_array($Ri)) {
                            if ($vd['del'] == "Yes") {
                                $sel = "selected";
                            } else {
                                $sel = "";
                            }
                            $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
                        }
                        $Vatcodes .= "</select>";
                        $products .= "\n\t\t\t\t\t\t<input type='hidden' name='whidss[]' value='{$FIRST_WH}'>\n\t\t\t\t\t\t<inpu type='hidden' name='stkidss[]' value=''>\n\t\t\t\t\t\t<input type='hidden' name='discs[]' value='0'>\n\t\t\t\t\t\t<input type='hidden' name='discps[]' value='0' >\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td colspan='2'>{$Accounts}</td>\n\t\t\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t\t\t<td><input type='text' size='20' name='descriptionss[]'></td>\n\t\t\t\t\t\t\t<td><input type='text' size='3' name='qtyss[]' value='1'></td>\n\t\t\t\t\t\t\t<td><input type='text' name='unitcosts[]' size='7'></td>\n\t\t\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t\t</tr>";
                    }
                }
            }
        }
    } else {
        if (!isset($addnon)) {
            if (isset($filter_store) and $filter_store != "0") {
                # get selected warehouse name
                db_conn("exten");
                $sql = "SELECT whname FROM warehouses WHERE whid = '{$filter_store}' AND div = '" . USER_DIV . "'";
                $whRslt = db_exec($sql);
                $wh = pg_fetch_array($whRslt);
            }
            # get stock on this warehouse
            db_connect();
            if (isset($ria) and $ria != "") {
                $len = strlen($ria);
                if ($ria == "Show All") {
                    $Wh = "";
                    $ria = "";
                } else {
                    $Wh = "AND (lower(stkdes) LIKE lower('%{$ria}%')) OR (lower(stkcod) LIKE lower('%{$ria}%'))";
                    $ria = "";
                }
            } else {
                $Wh = "AND FALSE";
                $ria = "";
            }
            $check_setting = getCSetting("OPTIONAL_STOCK_FILTERS");
            if (isset($check_setting) and $check_setting == "yes") {
                if (isset($filter_class) and $filter_class != "0") {
                    $Wh .= " AND prdcls = '{$filter_class}'";
                }
                if (isset($filter_cat) and $filter_cat != "0") {
                    $Wh .= " AND catid = '{$filter_cat}'";
                }
            }
            if (isset($filter_store) and $filter_store != "0") {
                $Wh .= " AND whid = '{$filter_store}'";
            }
            $sql = "SELECT * FROM stock WHERE blocked = 'n' {$search_neg_stock} AND div = '" . USER_DIV . "' {$Wh} ORDER BY stkcod ASC";
            $stkRslt = db_exec($sql) or errDie("Unable to retrieve stocks from database.");
            if (pg_numrows($stkRslt) < 1) {
                if (!isset($err)) {
                    $err = "";
                }
                $err .= "<li>There are no stock items in the selected warehouse.</li>";
            }
            $stks = "<select name='stkidss[]' onChange='javascript:document.form.submit();'>";
            $stks .= "<option value='-S' disabled selected>Select Number</option>";
            $count = 0;
            while ($stk = pg_fetch_array($stkRslt)) {
                $stks .= "<option value='{$stk['stkid']}'>{$stk['stkcod']} (" . sprint3($stk['units'] - $stk['alloc']) . ")</option>";
            }
            $stks .= "</select> ";
            $products .= "\n\t\t\t\t<input type='hidden' name='accountss[]' value='0'>\n\t\t\t\t<input type='hidden' name='descriptionss[]' value=''>\n\t\t\t\t<input type='hidden' name='vatcodess[]' value=''>\n\t\t\t\t<input type='hidden' name='whidss[]' value='{$filter_store}'>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td></td>\n\t\t\t\t\t<td>{$stks}</td>\n\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t<td><input type='text' size='3' name='qtyss[]' value='1'></td>\n\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t<td>\n\t\t\t\t\t\t<input type='text' size='4' name='discs[]' value='0'>\n\t\t\t\t\t\tOR\n\t\t\t\t\t\t<input type='text' size='4' name='discps[]' value='0' maxlength='5'>%</td>\n\t\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t</tr>";
        } else {
            if (isset($addnon)) {
                $Accounts = "\n\t\t\t\t<select name='accountss[]'>\n\t\t\t\t\t<option value='0'>Select Account</option>";
                $useaccdrop = getCSetting("USE_NON_STOCK_ACCOUNTS");
                if (isset($useaccdrop) and $useaccdrop == "yes") {
                    db_connect();
                    $acc_sql = "SELECT * FROM non_stock_account_list ORDER BY accname";
                    $run_acc = db_exec($acc_sql) or errDie("Unable to get account information.");
                    if (pg_numrows($run_acc) > 0) {
                        while ($acc = pg_fetch_array($run_acc)) {
                            $Accounts .= "<option value='{$acc['accid']}'>{$acc['accname']}</option>";
                        }
                        $Accounts .= "</select>";
                    }
                } else {
                    db_conn('core');
                    $Sl = "SELECT accid,topacc,accnum,accname FROM accounts WHERE acctype='I' ORDER BY accname";
                    $Ri = db_exec($Sl) or errDie("Unable to get accounts.");
                    while ($ad = pg_fetch_array($Ri)) {
                        if (isb($ad['accid'])) {
                            continue;
                        }
                        $Accounts .= "<option value='{$ad['accid']}'>{$ad['accname']}</option>";
                    }
                    $Accounts .= "</select>";
                }
                db_conn('cubit');
                $Sl = "SELECT * FROM vatcodes ORDER BY code";
                $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                $Vatcodes = "\n\t\t\t\t<select name='vatcodess[]'>\n\t\t\t\t\t<option value='0'>Select</option>";
                while ($vd = pg_fetch_array($Ri)) {
                    if ($vd['del'] == "Yes") {
                        $sel = "selected";
                    } else {
                        $sel = "";
                    }
                    $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
                }
                $Vatcodes .= "</select>";
                $products .= "\n\t\t\t\t<inpu type='hidden' name='stkidss[]' value=''>\n\t\t\t\t<input type='hidden' name='whidss[]' value='{$FIRST_WH}'>\n\t\t\t\t<input type='hidden' name='discs[]' value='0'>\n\t\t\t\t<input type='hidden' name='discps[]' value='0' >\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='2'>{$Accounts}</td>\n\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t<td><input type='text' size='20' name='descriptionss[]'></td>\n\t\t\t\t\t<td><input type='text' size='3' name='qtyss[]' value='1'></td>\n\t\t\t\t\t<td><input type='text' name='unitcosts[]' size='7'></td>\n\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t</tr>";
            }
        }
    }
    // 	$products .= "</table>";
    /* --- End Products Display --- */
    /* --- Start Some calculations --- */
    # Calculate subtotal
    $SUBTOT = sprint($sord['subtot']);
    # Calculate tradediscm
    if ($sord['traddisc'] > 0) {
        $traddiscm = sprint($sord['traddisc'] / 100 * ($SUBTOT + $sord['delchrg']));
    } else {
        $traddiscm = "0.00";
    }
    $VATP = TAX_VAT;
    # Calculate subtotal
    $SUBTOT = sprint($sord['subtot']);
    $VAT = sprint($sord['vat']);
    $TOTAL = sprint($sord['total']);
    $sord['delchrg'] = sprint($sord['delchrg']);
    /* --- End Some calculations --- */
    /*--- Start checks --- */
    # check only if the customer is selected
    if (isset($cusnum) && $cusnum != "-S") {
        #check againg credit limit
        if ($cust['credlimit'] != 0 && $TOTAL + $cust['balance'] > $cust['credlimit']) {
            $error .= "<li class='err'>Warning : Customers Credit limit of <b>" . CUR . " {$cust['credlimit']}</b> has been exceeded:</li>";
        }
        $avcred = $cust['credlimit'] - $cust['balance'];
    } else {
        $avcred = "0.00";
    }
    /*--- Start checks --- */
    if (!isset($letters)) {
        $letters = "";
    }
    $sord['delvat'] += 0;
    if ($sord['delvat'] == 0) {
        $Sl = "SELECT * FROM vatcodes WHERE del='Yes'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $vd = pg_fetch_array($Ri);
        $sord['delvat'] = $vd['id'];
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes ORDER BY code";
    $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
    $Vatcodes = "\n\t\t<select name='delvat'>\n\t\t\t<option value='0'>Select</option>";
    while ($vd = pg_fetch_array($Ri)) {
        if ($vd['id'] == $sord['delvat']) {
            $sel = "selected";
        } else {
            $sel = "";
        }
        $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
    }
    $Vatcodes .= "</select>";
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    $psel1 = "";
    $psel2 = "";
    if (isset($proforma) and $proforma == "yes") {
        $psel1 = "checked=yes";
    } else {
        $psel2 = "checked=yes";
    }
    if ($proforma == "yes") {
        #generate a unique id IF it hasnt been done yet
        if (!isset($pinvnum) or $pinvnum == 0) {
            pglib_transaction("BEGIN") or errDie("Could not start database transaction");
            #get unique id
            $get_uni = "INSERT INTO unique_id (entry) VALUES ('value')";
            $run_uni = db_exec($get_uni) or errDie("Unable to get unique id");
            $pinvnum = pglib_lastid("unique_id", "id");
            $rem_sql = "DELETE FROM unique_id WHERE id = '{$pinvnum}'";
            $run_rem = db_exec($rem_sql) or errDie("Unable to remove unique id check");
            #further check to see if an invoice has this is should be done here...
            pglib_transaction("COMMIT") or errDie("Could not commit database transaction");
        }
        $getpinvnum = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Proforma Invoice Number</td>\n\t\t\t\t<td><input type='hidden' name='pinvnum' value='{$pinvnum}'>{$pinvnum}</td>\n\t\t\t</tr>";
    } else {
        $getpinvnum = "<input type='hidden' name='pinvnum' value='0'>";
    }
    // Which display method was selected
    if (isset($sel_frm) && $sel_frm == "stkdes") {
        $sel_frm_cod = "";
        $sel_frm_des = "checked";
    } else {
        $sel_frm_cod = "checked";
        $sel_frm_des = "";
    }
    // Retrieve VAT Setting
    $sql = "SELECT value FROM cubit.settings WHERE constant='VAT_INC'";
    $vatinc_rslt = db_exec($sql) or errDie("Unable to retrieve vat setting.");
    $vatinc = pg_fetch_result($vatinc_rslt, 0);
    if ($vatinc != "yes" && $vatinc != "no") {
        $vatinc = "no";
    }
    if ($vatinc == 'yes') {
        $chrgvat = "inc";
    } else {
        $chrgvat = "exc";
    }
    if (isset($diffwhBtn) or isset($addprodBtn) or isset($addnon) or isset($saveBtn) or isset($upBtn) or isset($doneBtn) or isset($donePrnt) or isset($ria)) {
        $jump_bot = "\n\t\t\t<script>\n\t\t\t\twindow.location.hash='bottom';\n\t\t\t</script>";
    } else {
        $jump_bot = "";
    }
    $optional_filter_setting = getCSetting("OPTIONAL_STOCK_FILTERS");
    if (isset($optional_filter_setting) and $optional_filter_setting == "yes") {
        db_connect();
        $catsql = "SELECT catid, cat, catcod FROM stockcat WHERE div = '" . USER_DIV . "' ORDER BY cat ASC";
        $catRslt = db_exec($catsql);
        if (pg_numrows($catRslt) < 1) {
            $cat_drop = "<input type='hidden' name='filter_cat' value='0'>";
        } else {
            $cat_drop = "<select name='filter_cat'>";
            $cat_drop .= "<option value='0'>All Categories</option>";
            while ($cat = pg_fetch_array($catRslt)) {
                if (isset($filter_cat) and $filter_cat == $cat['catid']) {
                    $cat_drop .= "<option value='{$cat['catid']}' selected>({$cat['catcod']}) {$cat['cat']}</option>";
                } else {
                    $cat_drop .= "<option value='{$cat['catid']}'>({$cat['catcod']}) {$cat['cat']}</option>";
                }
            }
            $cat_drop .= "</select>";
        }
        # Select classification
        $classsql = "SELECT * FROM stockclass WHERE div = '" . USER_DIV . "' ORDER BY classname ASC";
        $clasRslt = db_exec($classsql);
        if (pg_numrows($clasRslt) < 1) {
            $class_drop = "<input type='hidden' name='filter_class' value='0'>";
        } else {
            $class_drop = "<select name='filter_class' style='width: 167'>";
            $class_drop .= "<option value='0'>All Classifications</option>";
            while ($clas = pg_fetch_array($clasRslt)) {
                if (isset($filter_class) and $filter_class == $clas['clasid']) {
                    $class_drop .= "<option value='{$clas['clasid']}' selected>{$clas['classname']}</option>";
                } else {
                    $class_drop .= "<option value='{$clas['clasid']}'>{$clas['classname']}</option>";
                }
            }
            $class_drop .= "</select>";
        }
        $display_optional_filters = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Select Category</td>\n\t\t\t\t<td>{$cat_drop}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Select Classification</td>\n\t\t\t\t<td>{$class_drop}</td>\n\t\t\t</tr>";
    }
    db_conn("exten");
    $sql = "SELECT whid, whname, whno FROM warehouses WHERE div = '" . USER_DIV . "' ORDER BY whname ASC";
    $whRslt = db_exec($sql);
    if (pg_numrows($whRslt) < 1) {
        $store_drop = "<input type='hidden' name='filter_store' value='0'>";
    } else {
        if (!isset($filter_store)) {
            # check if setting exists
            db_connect();
            $sql = "SELECT value FROM set WHERE label = 'DEF_WH' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to check database for existing settings.");
            if (pg_numrows($Rslt) > 0) {
                $set = pg_fetch_array($Rslt);
                $filter_store = $set['value'];
            }
        }
        $store_drop = "<select name='filter_store'>";
        $store_drop .= "<option value='0'>All Stores</option>";
        while ($wh = pg_fetch_array($whRslt)) {
            if (isset($filter_store) and $filter_store == $wh['whid']) {
                $store_drop .= "<option value='{$wh['whid']}' selected>({$wh['whno']}) {$wh['whname']}</option>";
            } else {
                $store_drop .= "<option value='{$wh['whid']}'>({$wh['whno']}) {$wh['whname']}</option>";
            }
        }
        $store_drop .= "</select>";
    }
    $cust_del_addr = $sord['del_addr'];
    $details = "\n\t\t<center>\n\t\t<h3>New Sales Order</h3>\n\t\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t\t<input type='hidden' name='key' value='update'>\n\t\t\t<input type='hidden' name='sordid' value='{$sordid}'>\n\t\t\t<input type='hidden' name='letters' value='{$letters}'>\n\t\t\t<input type='hidden' name='stkerr' value='{$stkerr}'>\n\t\t\t<input type='hidden' name='chrgvat' value='{$chrgvat}' />\n\t\t<table " . TMPL_tblDflts . " width='95%'>\n\t\t\t\t<tr>\n\t\t\t\t<td valign='top'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th colspan='2'> Customer Details </th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Department</td>\n\t\t\t\t\t\t\t<td valign='center'>{$dept['deptname']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Account No.</td>\n\t\t\t\t\t\t\t<td valign='center'>{$cust['accno']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Customer</td>\n\t\t\t\t\t\t\t<td valign='center'>{$customers}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td valign='top'>Customer Address</td>\n\t\t\t\t\t\t\t<td valign='center'>" . nl2br($cust['addr1']) . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td valign='top'>Current Delivery Address</td>\n\t\t\t\t\t\t\t<td valign='center'>" . nl2br($cust_del_addr) . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td valign='top'>Delivery Address</td>\n\t\t\t\t\t\t\t<td valign='center'>\n\t\t\t\t\t\t\t\t<input type='button' onClick=\"\n\t\t\t\t\t\t\t\t\tvar windowReference;\n\t\t\t\t\t\t\t\t\tfunction openPopup() {\n\t\t\t\t\t\t\t\t\t\twindowReference = window.open('sorder-new-deladdr.php?sordid={$sordid}','windowName','width=500,height=400,status=1');\n\t\t\t\t\t\t\t\t\t\tif (!windowReference.opener)\n\t\t\t\t\t\t\t\t\t\t\twindowReference.opener = self;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\topenPopup();\" value='Change Delivery Address'>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Customer Order number</td>\n\t\t\t\t\t\t\t<td valign='center'><input type='text' size='10' name='cordno' value='{$sord['cordno']}'></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Customer VAT Number</td>\n\t\t\t\t\t\t\t<td>{$cust['vatnum']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Select Using</td>\n\t\t\t\t\t\t\t<td>Stock Code<input type='radio' name='sel_frm' value='stkcod' onChange='javascript:document.form.submit();' {$sel_frm_cod}><br>Stock Description<input type='radio' name='sel_frm' value='stkdes' onChange='javascript:document.form.submit();' {$sel_frm_des}></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th colspan='2'>Additional Filters</th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Select Store</td>\n\t\t\t\t\t\t\t<td>{$store_drop}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t{$display_optional_filters}\n\t\t\t\t\t\t<tr class='" . bg_class() . "' " . ass("Type the first letters of the stock code you are looking for.") . ">\n\t\t\t\t\t\t\t<td>Stock Filter</td>\n\t\t\t\t\t\t\t<td nowrap><input type='text' size='13' name='ria' value='{$ria}'> <input type='submit' value='Search'> <input type='submit' name='ria' value='Show All'></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t\t<td valign='top' align='right'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th colspan='2'> Sales Order Details </th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Sales Order No.</td>\n\t\t\t\t\t\t\t<td valign='center'>{$sord['sordid']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Proforma Invoice</td>\n\t\t\t\t\t\t\t<td valign='center'>Yes <input type='radio' name='proforma' value='yes' {$psel1} onChange='javascript:document.form.submit();'> No <input type='radio' name='proforma' value='no' {$psel2} onChange='javascript:document.form.submit();'></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t{$getpinvnum}\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Display Costs</td>\n\t\t\t\t\t\t\t<td>Yes <input type='radio' name='costs' value='yes' {$dc_sel['yes']}> No <input type='radio' name='costs' value='no' {$dc_sel['no']}></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Order No.</td>\n\t\t\t\t\t\t\t<td valign='center'><input type='text' size='5' name='ordno' value='{$sord['ordno']}'></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>VAT Inclusive</td>\n\t\t\t\t\t\t\t<td valign='center'>Yes <input type='radio' size='7' name='chrgvat' value='inc' {$chin}> No<input type='radio' size='7' name='chrgvat' value='exc' {$chex}></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Terms</td>\n\t\t\t\t\t\t\t<td valign='center'>{$termssel} Days</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Sales Person</td>\n\t\t\t\t\t\t\t<td valign='center'>{$salesps}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Sales Order Date</td>\n\t\t\t\t\t\t\t<td valign='center'>" . mkDateSelect("sord", $sord_year, $sord_month, $sord_day) . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Delivery/Due Date</td>\n\t\t\t\t\t\t\t<td valign='center'>\n\t\t\t\t\t\t\t\t" . mkDateSelect("ddate", $ddate_year, $ddate_month, $ddate_day) . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Available Credit</td>\n\t\t\t\t\t\t\t<td>" . CUR . " " . sprint($avcred) . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Trade Discount</td>\n\t\t\t\t\t\t\t<td valign='center'><input type='text' size='5' name='traddisc' value='{$sord['traddisc']}'>%</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Delivery Charge</td>\n\t\t\t\t\t\t\t<td valign='center'><input type='text' size='7' name='delchrg' value='{$sord['delchrg']}'>{$Vatcodes}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t" . TBL_BR . "\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><table " . TMPL_tblDflts . ">{$products}</table></td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>\n\t\t\t\t\t<p>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td rowspan='2'>" . mkQuickLinks(ql("sorder-view.php", "View Sales Orders"), ql("customers-new.php", "New Customer")) . "\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<th width='25%'>Comments</th>\n\t\t\t\t\t\t\t<td rowspan='5' valign='top' width='50%'>{$error}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td class='" . bg_class() . "' rowspan='4' align='center' valign='top'><textarea name='comm' rows='4' cols='20'>{$sord['comm']}</textarea></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t\t<td align='right'>\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>SUBTOTAL</td>\n\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " <input type='hidden' name='SUBTOT' value='{$SUBTOT}'>{$SUBTOT}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Trade Discount</td>\n\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$sord['discount']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Delivery Charge</td>\n\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$sord['delivery']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td><b>VAT {$vat14}</b>\n\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$VAT}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<th>GRAND TOTAL</th>\n\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$TOTAL}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2' align='center'><input name='addprodBtn' type='submit' value='Add Product'>| <input name='addnon' type='submit' value='Add Non stock Product'> | <input type='submit' name='saveBtn' value='Save'> | <input type='submit' name='upBtn' value='Update'>{$done}</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<a name='bottom'>\n\t\t</form>\n\t\t</center>\n\t\t{$jump_bot}";
    return $details;
}
function details($_POST, $error = "")
{
    extract($_POST);
    # validate input
    include "libs/validate.lib.php";
    $v = new validate();
    if (isset($quoid)) {
        $v->isOk($quoid, "num", 1, 20, "Invalid quote number.");
    }
    if (isset($deptid)) {
        $v->isOk($deptid, "num", 1, 20, "Invalid department number.");
    }
    if (isset($letters)) {
        $v->isOk($letters, "string", 0, 5, "Invalid First 3 Letters.");
    }
    # display errors, if any
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $error .= "<li class='err'>{$e['msg']}</li>";
        }
        $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    if (!isset($deptid)) {
        $deptid = 0;
    } else {
        if (isset($quoid)) {
            db_conn("cubit");
            $sql = "UPDATE quotes SET deptid='{$deptid}' WHERE quoid='{$quoid}' AND deptid<>'{$deptid}'";
            db_exec($sql) or errDie("Error updating invoice department.");
        }
    }
    if (!isset($quoid)) {
        $quoid = create_dummy($deptid);
    }
    if (!isset($stkerr)) {
        $stkerr = "0,0";
    }
    if (!isset($done)) {
        $done = "";
    }
    if (!isset($sel_frm)) {
        $sel_frm = "stkcod";
    }
    # Get quote info
    db_connect();
    $sql = "SELECT * FROM quotes WHERE quoid = '{$quoid}' AND div = '" . USER_DIV . "'";
    $quoRslt = db_exec($sql) or errDie("Unable to get quote information");
    if (pg_numrows($quoRslt) < 1) {
        return "<li class='err'>Quote Not Found</li>";
    }
    $quo = pg_fetch_array($quoRslt);
    # check if quote has been printed
    if ($quo['accepted'] == "y") {
        $error = "<li class='err'> Error : Quote number <b>{$quoid}</b> has already been printed.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    if (!isset($lead)) {
        $lead = $quo["lead"];
    }
    //manual error handling
    if (!isset($quo['ncdate'])) {
        $quo['ncdate'] = "";
    }
    if (strlen($quo['ncdate']) < 1) {
        $ncdate_year = date("Y");
        $ncdate_month = date("m", mktime(0, 0, 0, date("m"), date("d") + 5, date("Y")));
        $ncdate_day = date("d", mktime(0, 0, 0, date("m"), date("d") + 5, date("Y")));
    } else {
        $darr = explode("-", $quo['ncdate']);
        $ncdate_year = $darr['0'];
        $ncdate_month = $darr['1'];
        $ncdate_day = $darr['2'];
    }
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$quo['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<li class='err'>Department not Found.</li>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    # Get selected customer info
    if (isset($letters)) {
        db_connect();
        $sql = "SELECT * FROM customers WHERE cusnum = '{$quo['cusnum']}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to view customer");
        if (pg_numrows($custRslt) < 1) {
            db_connect();
            if ($inv['deptid'] == 0) {
                $searchdept = "";
            } else {
                $searchdept = "deptid = '{$quo['deptid']}' AND ";
            }
            # Query server for customer info
            $sql = "SELECT cusnum,cusname,surname FROM customers WHERE {$searchdept} location != 'int' AND lower(surname) LIKE lower('{$letters}%') AND div = '" . USER_DIV . "' ORDER BY surname";
            $custRslt = db_exec($sql) or errDie("Unable to view customers");
            if (pg_numrows($custRslt) < 1) {
                $ajax_err = "<li class='err'>No customer names starting with <b>{$letters}</b> in database.</li>";
                //return view_err($_POST, $err);
            } else {
                $customers = "<select name='cusnum' onChange='javascript:document.form.submit();'>";
                $customers .= "<option value='-S' selected>Select Customer</option>";
                while ($cust = pg_fetch_array($custRslt)) {
                    $customers .= "<option value='{$cust['cusnum']}'>{$cust['cusname']} {$cust['surname']}</option>";
                }
                $customers .= "</select>";
            }
            # take care of the unset vars
            $cust['addr1'] = "";
            $cust['cusnum'] = "";
            $cust['vatnum'] = "";
            $cust['accno'] = "";
        } else {
            $cust = pg_fetch_array($custRslt);
            # moarn if customer account has been blocked
            if ($cust['blocked'] == 'yes') {
                return "<li class='err'>Error : Selected customer account has been blocked.</li>";
            }
            $customers = "<input type='hidden' name=cusnum value='{$cust['cusnum']}'>{$cust['cusname']}  {$cust['surname']}";
            $cusnum = $cust['cusnum'];
        }
    }
    /* --- Start Drop Downs --- */
    # Select warehouse
    db_conn("exten");
    //no good ... breaks the search feature because it doesnt send search with
    // onChange='javascript:document.form.submit();'
    $whs = "<select name='whidss[]'>";
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "' ORDER BY whname ASC";
    $whRslt = db_exec($sql);
    if (pg_numrows($whRslt) < 1) {
        return "<li class='err'> There are no Stores found in Cubit.</li>";
    } else {
        $whs .= "<option value='-S' disabled selected>Select Store</option>";
        while ($wh = pg_fetch_array($whRslt)) {
            if (!user_in_store_team($wh["whid"], USER_ID)) {
                continue;
            }
            $whs .= "<option value='{$wh['whid']}'>({$wh['whno']}) {$wh['whname']}</option>";
        }
    }
    $whs .= "</select>";
    # get sales people
    db_conn("exten");
    $sql = "SELECT * FROM salespeople WHERE div = '" . USER_DIV . "' ORDER BY salesp ASC";
    $salespRslt = db_exec($sql) or errDie("Unable to get sales people.");
    if (pg_numrows($salespRslt) < 1) {
        return "<li class='err'> There are no Sales People found in Cubit.</li>";
    } else {
        $salesps = "<select name='salespn'>";
        while ($salesp = pg_fetch_array($salespRslt)) {
            if ($salesp['salesp'] == $quo['salespn']) {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $salesps .= "<option value='{$salesp['salesp']}' {$sel}>{$salesp['salesp']}</option>";
        }
        $salesps .= "</select>";
    }
    # days drop downs
    $days = array("0" => "0", "7" => "7", "14" => "14", "30" => "30", "60" => "60", "90" => "90", "120" => "120");
    $termssel = extlib_cpsel("terms", $days, $quo['terms']);
    # Keep the charge vat option stable
    if ($quo['chrgvat'] == "inc") {
        $chin = "checked=yes";
        $chex = "";
        $chno = "";
    } elseif ($quo['chrgvat'] == "exc") {
        $chin = "";
        $chex = "checked=yes";
        $chno = "";
    } else {
        $chin = "";
        $chex = "";
        $chno = "checked=yes";
    }
    # format date
    list($quote_year, $quote_month, $quote_day) = explode("-", $quo['odate']);
    //	list($followon_year, $followon_month, $followon_day) = explode("-", $quo['ncdate']);
    /* --- End Drop Downs --- */
    // get the ID of the first warehouse
    db_conn("exten");
    $sql = "SELECT whid FROM warehouses ORDER BY whid ASC LIMIT 1";
    $rslt = db_exec($sql) or errDie("Error reading warehouses (FWH).");
    if (pg_num_rows($rslt) > 0) {
        $FIRST_WH = pg_fetch_result($rslt, 0, 0);
    } else {
        $FIRST_WH = "-S";
    }
    /* --- Start Products Display --- */
    # select all products
    $products = "\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t<tr>\n\t\t\t\t<th>STORE</th>\n\t\t\t\t<th>ITEM NUMBER</th>\n\t\t\t\t<th>VAT CODE</th>\n\t\t\t\t<th>DESCRIPTION</th>\n\t\t\t\t<th>QTY</th>\n\t\t\t\t<th>UNIT PRICE</th>\n\t\t\t\t<th>UNIT DISCOUNT</th>\n\t\t\t\t<th>AMOUNT</th>\n\t\t\t\t<th>Remove</th>\n\t\t\t<tr>";
    # get selected stock in this quote
    db_connect();
    $sql = "SELECT * FROM quote_items  WHERE quoid = '{$quoid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $i = 0;
    $key = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        $stkd['account'] += 0;
        if ($stkd['account'] != 0) {
            # Keep track of selected stock amounts
            $amts[$i] = $stkd['amt'];
            $i++;
            db_conn('core');
            $Sl = "SELECT accid,topacc,accnum,accname FROM accounts WHERE acctype='I' ORDER BY accname";
            $Ri = db_exec($Sl) or errDie("Unable to get accounts.");
            $Accounts = "\n\t\t\t\t<select name='accounts[]'>\n\t\t\t\t\t<option value='0'>Select Account</option>";
            while ($ad = pg_fetch_array($Ri)) {
                if (isb($ad['accid'])) {
                    continue;
                }
                if ($ad['accid'] == $stkd['account']) {
                    $sel = "selected";
                } else {
                    $sel = "";
                }
                $Accounts .= "<option value='{$ad['accid']}' {$sel}>{$ad['accname']}</option>";
            }
            $Accounts .= "</select>";
            $sernos = "";
            $stkd['unitcost'] = sprint($stkd['unitcost']);
            $stkd['amt'] = sprint($stkd['amt']);
            # Input qty if not serialised
            $qtyin = "<input type='text' size='3' name='qtys[]' value='{$stkd['qty']}'>";
            $viewcost = "<input type='text' size='8' name='unitcost[]' value='{$stkd['unitcost']}'>";
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes ORDER BY code";
            $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
            $Vatcodes = "\n\t\t\t\t<select name='vatcodes[]'>\n\t\t\t\t\t<option value='0'>Select</option>";
            while ($vd = pg_fetch_array($Ri)) {
                if ($stkd['vatcode'] == $vd['id']) {
                    $sel = "selected";
                } else {
                    $sel = "";
                }
                $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
            }
            $Vatcodes .= "</select>";
            //print "fo";
            # Put in product
            $products .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='2'>{$Accounts}<input type='hidden' name='whids[]' value='{$stkd['whid']}'></td>\n\t\t\t\t\t<td><input type='hidden' name='stkids[]' value='{$stkd['stkid']}'>{$Vatcodes}</td>\n\t\t\t\t\t<td><input type='text' size='20' name='descriptions[]' value='{$stkd['description']}'> {$sernos}</td>\n\t\t\t\t\t<td>{$qtyin}</td>\n\t\t\t\t\t<td>{$viewcost}</td>\n\t\t\t\t\t<td><input type='hidden' name='disc[]' value='{$stkd['disc']}'><input type='hidden' name='discp[]' value='{$stkd['discp']}'></td>\n\t\t\t\t\t<td nowrap><input type='hidden' name='amt[]' value='{$stkd['amt']}'> " . CUR . " {$stkd['amt']}</td>\n\t\t\t\t\t<td><input type='checkbox' name='remprod[]' value='{$key}'><input type='hidden' name='SCROLL' value='yes'></td>\n\t\t\t\t</tr>";
            $key++;
        } else {
            # keep track of selected stock amounts
            $amts[$i] = $stkd['amt'];
            $i++;
            # get selected stock in this warehouse
            db_connect();
            $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql);
            $stk = pg_fetch_array($stkRslt);
            # get warehouse name
            db_conn("exten");
            $sql = "SELECT whname FROM warehouses WHERE whid = '{$stk['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes ORDER BY code";
            $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
            $Vatcodes = "\n\t\t\t\t<select name='vatcodes[]'>\n\t\t\t\t\t<option value='0'>Select</option>";
            while ($vd = pg_fetch_array($Ri)) {
                if ($stkd['vatcode'] == $vd['id']) {
                    $sel = "selected";
                } else {
                    $sel = "";
                }
                $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
            }
            $Vatcodes .= "</select>";
            $stkd['unitcost'] = sprint($stkd['unitcost']);
            $stkd['amt'] = sprint($stkd['amt']);
            # put in product
            $products .= "\n\t\t\t\t<input type='hidden' name='accounts[]' value='0'>\n\t\t\t\t<input type='hidden' name='descriptions[]' value=''>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><input type='hidden' name='whids[]' value='{$stkd['whid']}'>{$wh['whname']}</td>\n\t\t\t\t\t<td><input type='hidden' name='stkids[]' value='{$stkd['stkid']}'><a href='#' onclick='openwindow(\"stock-amt-det.php?stkid={$stk['stkid']}\")'>{$stk['stkcod']}</a></td>\n\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t<td>" . extlib_rstr($stk['stkdes'], 30) . "</td>\n\t\t\t\t\t<td><input type='text' size='3' name='qtys[]' value='{$stkd['qty']}'></td>\n\t\t\t\t\t<td><input type='text' size='8' name='unitcost[]' value='{$stkd['unitcost']}'></td>\n\t\t\t\t\t<td><input type='text' size='4' name='disc[]' value='{$stkd['disc']}'> OR <input type='text' size='4' name='discp[]' value='{$stkd['discp']}' maxlength=5>%</td>\n\t\t\t\t\t<td nowrap><input type='hidden' name='amt[]' value='{$stkd['amt']}'> " . CUR . " {$stkd['amt']}</td>\n\t\t\t\t\t<td><input type='checkbox' name='remprod[]' value='{$key}'><input type='hidden' name='SCROLL' value='yes'></td>\n\t\t\t\t</tr>";
            $key++;
        }
    }
    # Look above(remprod keys)
    $keyy = $key;
    # look above(if i = 0 then there are no products)
    if ($i == 0) {
        $done = "";
    }
    # check if stock warehouse was selected
    if (isset($whidss)) {
        foreach ($whidss as $key => $whid) {
            if (isset($stkidss[$key]) && $stkidss[$key] != "-S" && isset($cust['pricelist'])) {
                # skip if not selected
                if ($whid == "-S") {
                    continue;
                }
                # get selected stock in this warehouse
                db_connect();
                $sql = "SELECT * FROM stock WHERE stkid = '{$stkidss[$key]}' AND div = '" . USER_DIV . "' ORDER BY stkcod ASC";
                $stkRslt = db_exec($sql);
                $stk = pg_fetch_array($stkRslt);
                # get selected warehouse name
                db_conn("exten");
                $sql = "SELECT whname FROM warehouses WHERE whid = '{$stk['whid']}' AND div = '" . USER_DIV . "'";
                $whRslt = db_exec($sql);
                $wh = pg_fetch_array($whRslt);
                # get price from price list if it is set
                if (isset($cust['pricelist'])) {
                    # get selected stock in this warehouse
                    db_conn("exten");
                    $sql = "SELECT price FROM plist_prices WHERE listid = '{$cust['pricelist']}' AND stkid = '{$stk['stkid']}' AND div = '" . USER_DIV . "'";
                    $plRslt = db_exec($sql);
                    if (pg_numrows($plRslt) > 0) {
                        $pl = pg_fetch_array($plRslt);
                        $stk['selamt'] = $pl['price'];
                    }
                }
                /* -- Start Some Checks -- */
                # check if they are selling too much
                if ($stk['units'] - $stk['alloc'] < $qtyss[$key]) {
                    if (!in_array($stk['stkid'], explode(",", $stkerr))) {
                        if ($stk['type'] != 'lab') {
                            $stkerr .= ",{$stk['stkid']}";
                            $error .= "<li class='err'>Warning :  Item number <b>{$stk['stkcod']}</b> does not have enough items available.</li>";
                        }
                    }
                }
                /* -- End Some Checks -- */
                # Calculate the Discount discount
                if ($discs[$key] < 1) {
                    if ($discps[$key] > 0) {
                        $discs[$key] = round($discps[$key] / 100 * $stk['selamt'], 2);
                    }
                } else {
                    $discps[$key] = round($discs[$key] * 100 / $stk['selamt'], 2);
                }
                # Calculate amount
                $amt[$key] = $qtyss[$key] * ($stk['selamt'] - $discs[$key]);
                db_conn('cubit');
                $Sl = "SELECT * FROM vatcodes ORDER BY code";
                $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                $Vatcodes = "\n\t\t\t\t\t<select name='vatcodes[]'>\n\t\t\t\t\t\t<option value='0'>Select</option>";
                while ($vd = pg_fetch_array($Ri)) {
                    if ($stk['vatcode'] == $vd['id']) {
                        $sel = "selected";
                    } else {
                        $sel = "";
                    }
                    $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
                }
                $Vatcodes .= "</select>";
                $stk['selamt'] = sprint($stk['selamt']);
                $amt[$key] = sprint($amt[$key]);
                # put in selected warehouse and stock
                $products .= "\n\t\t\t\t\t<input type='hidden' name='accounts[]' value='0'>\n\t\t\t\t\t<input type='hidden' name='descriptions[]' value=''>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><input type='hidden' name='whids[]' value='{$whid}'>{$wh['whname']}</td>\n\t\t\t\t\t\t<td><input type='hidden' name='stkids[]' value='{$stk['stkid']}'><a href='#' onclick='openwindow(\"stock-amt-det.php?stkid={$stk['stkid']}\")'>{$stk['stkcod']}</a></td>\n\t\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t\t<td>" . extlib_rstr($stk['stkdes'], 30) . "</td>\n\t\t\t\t\t\t<td><input type='text' size='3' name='qtys[]' value='{$qtyss[$key]}'></td>\n\t\t\t\t\t\t<td><input type='text' size='8' name='unitcost[]'  value='{$stk['selamt']}'></td>\n\t\t\t\t\t\t<td><input type='text' size='4' name='disc[]' value='{$discs[$key]}'> OR <input type='text' size='4' name='discp[]' value='{$discps[$key]}' maxlength='5'>%</td>\n\t\t\t\t\t\t<td nowrap><input type='hidden' name='amt[]' value='{$amt[$key]}'> " . CUR . " {$amt[$key]}</td>\n\t\t\t\t\t\t<td><input type='checkbox' name='remprod[]' value='{$keyy}'></td>\n\t\t\t\t\t</tr>";
                $keyy++;
            } elseif (isset($accountss[$key]) && $accountss[$key] != "0" && isset($cust['pricelist'])) {
                db_conn('core');
                $Sl = "SELECT * FROM accounts WHERE accid='{$accountss[$key]}'";
                $Ri = db_exec($Sl) or errDie("Unable to get account data.");
                if (pg_num_rows($Ri) < 1) {
                    return "invalid.";
                }
                $ad = pg_fetch_array($Ri);
                # Calculate amount
                $amt[$key] = sprint($qtyss[$key] * $unitcosts[$key]);
                # Input qty if not serialised
                $qtyin = "<input type='text' size='3' name='qtys[]' value='{$qtyss[$key]}'>";
                $unitcosts[$key] = sprint($unitcosts[$key]);
                $amt[$key] = sprint($amt[$key]);
                # Check permissions
                $viewcost = "<input type='text' size='8' name='unitcost[]' value='{$unitcosts[$key]}'>";
                db_conn('cubit');
                $Sl = "SELECT * FROM vatcodes ORDER BY code";
                $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                $Vatcodes = "\n\t\t\t\t\t<select name='vatcodes[]'>\n\t\t\t\t\t\t<option value='0'>Select</option>";
                while ($vd = pg_fetch_array($Ri)) {
                    if ($vatcodess[$key] == $vd['id']) {
                        $sel = "selected";
                    } else {
                        $sel = "";
                    }
                    $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
                }
                $Vatcodes .= "</select>";
                # Put in selected warehouse and stock
                $products .= "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td colspan='2'>{$ad['accname']}<input type='hidden' name='accounts[]' value='{$accountss[$key]}'><input type='hidden' name='whids[]' value='0'></td>\n\t\t\t\t\t\t<td>{$Vatcodes}<input type='hidden' name='stkids[]' value='0'></td>\n\t\t\t\t\t\t<td><input type='text' size='20' name='descriptions[]' value='{$descriptionss[$key]}'></td>\n\t\t\t\t\t\t<td>{$qtyin}</td>\n\t\t\t\t\t\t<td>{$viewcost}</td>\n\t\t\t\t\t\t<td><input type='hidden' name='disc[]' value='0'><input type='hidden' name='discp[]' value='0'></td>\n\t\t\t\t\t\t<td nowrap><input type='hidden' name='amt[]' value='{$amt[$key]}'> " . CUR . " {$amt[$key]}</td>\n\t\t\t\t\t\t<td><input type='checkbox' name='remprod[]' value='{$keyy}'></td>\n\t\t\t\t\t</tr>";
                $keyy++;
            } else {
                # skip if not selected
                if ($whid == "-S") {
                    continue;
                }
                if (!isset($addnon)) {
                    if (isset($filter_store) and $filter_store != "0") {
                        # get warehouse name
                        db_conn("exten");
                        $sql = "SELECT whname FROM warehouses WHERE whid = '{$filter_store}' AND div = '" . USER_DIV . "'";
                        $whRslt = db_exec($sql);
                        $wh = pg_fetch_array($whRslt);
                    }
                    if (isset($des) and $des != "") {
                        $len = strlen($des);
                        if ($des == "Show All") {
                            $Wh = "";
                            $des = "";
                        } else {
                            $Wh = "AND (lower(substr(stkdes,1,'{$len}'))=lower('{$des}') OR lower(substr(stkcod,1,'{$len}'))=lower('{$des}'))";
                        }
                    } else {
                        $Wh = "AND FALSE";
                        $des = "";
                    }
                    $check_setting = getCSetting("OPTIONAL_STOCK_FILTERS");
                    if (isset($check_setting) and $check_setting == "yes") {
                        if (isset($filter_class) and $filter_class != "0") {
                            $Wh .= " AND prdcls = '{$filter_class}'";
                        }
                        if (isset($filter_cat) and $filter_cat != "0") {
                            $Wh .= " AND catid = '{$filter_cat}'";
                        }
                    }
                    if (isset($filter_store) and $filter_store != "0") {
                        $Wh .= " AND whid = '{$filter_store}'";
                    }
                    # get stock on this warehouse
                    db_connect();
                    $sql = "SELECT * FROM stock WHERE blocked = 'n' AND div = '" . USER_DIV . "' {$Wh} ORDER BY stkcod ASC";
                    $stkRslt = db_exec($sql) or errDie("Unable to retrieve stocks from database.");
                    if (pg_numrows($stkRslt) < 1) {
                        $error .= "<li class='err'>There are no stock items in the selected store.</li>";
                        continue;
                    }
                    if ($sel_frm == "stkcod") {
                        $cods = "<select name='stkidss[]' onChange='javascript:document.form.submit();'>";
                        $cods .= "<option value='-S' disabled selected>Select Number</option>";
                        $count = 0;
                        while ($stk = pg_fetch_array($stkRslt)) {
                            $cods .= "<option value='{$stk['stkid']}'>{$stk['stkcod']} (" . sprint3($stk['units'] - $stk['alloc']) . ")</option>";
                        }
                        $cods .= "</select> ";
                        $descs = "";
                    } else {
                        $descs = "<select style='width:250px' name='stkidss[]' onChange='javascript:document.form.submit();'>";
                        $descs .= "<option value='-S' disabled selected>Select Description</option>";
                        $count = 0;
                        while ($stk = pg_fetch_array($stkRslt)) {
                            $descs .= "<option value='{$stk['stkid']}'>{$stk['stkdes']} (" . sprint3($stk['units'] - $stk['alloc']) . ")</option>";
                        }
                        $descs .= "</select> ";
                        $cods = "";
                    }
                    db_conn('cubit');
                    $Sl = "SELECT * FROM vatcodes ORDER BY code";
                    $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                    $Vatcodes = "\n\t\t\t\t\t\t<select name='vatcodess[]'>\n\t\t\t\t\t\t\t<option value='0'>Select</option>";
                    while ($vd = pg_fetch_array($Ri)) {
                        if ($vd['del'] == "Yes") {
                            $sel = "selected";
                        } else {
                            $sel = "";
                        }
                        $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
                    }
                    $Vatcodes .= "</select>";
                    # put in drop down and warehouse
                    $products .= "\n\t\t\t\t\t\t<input type='hidden' name='accountss[]' value='0'>\n\t\t\t\t\t\t<input type='hidden' name='descriptionss[]' value=''>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td><input type='hidden' name='whidss[]' value='{$filter_store}'></td>\n\t\t\t\t\t\t\t<td>{$cods}<input type='hidden' name='vatcodess' value='0'></td>\n\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t<td>{$descs}</td>\n\t\t\t\t\t\t\t<td><input type='text' size='3' name='qtyss[]'  value='1'></td>\n\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t\t<td><input type='text' size='4' name='discs[]' value='0'> OR <input type='text' size='4' name='discps[]' value='0' maxlength='5'>%</td>\n\t\t\t\t\t\t\t<td><input type='hidden' name='amts[]' value='0.00'>" . CUR . " 0.00</td>\n\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t</tr>";
                } else {
                    db_conn('core');
                    $Sl = "SELECT accid,topacc,accnum,accname FROM accounts WHERE acctype='I' ORDER BY accname";
                    $Ri = db_exec($Sl) or errDie("Unable to get accounts.");
                    $Accounts = "\n\t\t\t\t\t\t<select name='accountss[]'>\n\t\t\t\t\t\t\t<option value='0'>Select Account</option>";
                    while ($ad = pg_fetch_array($Ri)) {
                        if (isb($ad['accid'])) {
                            continue;
                        }
                        $Accounts .= "<option value='{$ad['accid']}'>{$ad['accname']}</option>";
                    }
                    $Accounts .= "</select>";
                    db_conn('cubit');
                    $Sl = "SELECT * FROM vatcodes ORDER BY code";
                    $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                    $Vatcodes = "\n\t\t\t\t\t\t<select name='vatcodess[]'>\n\t\t\t\t\t\t\t<option value='0'>Select</option>";
                    while ($vd = pg_fetch_array($Ri)) {
                        if ($vd['del'] == "Yes") {
                            $sel = "selected";
                        } else {
                            $sel = "";
                        }
                        $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
                    }
                    $Vatcodes .= "</select>";
                    $products .= "\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td colspan='2'>{$Accounts}<input type='hidden' name='whidss[]' value='{$FIRST_WH}'></td>\n\t\t\t\t\t\t\t<inpu type='hidden' name='stkidss[]' value=''>\n\t\t\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t\t\t<td><input type='text' size='20' name='descriptionss[]'></td>\n\t\t\t\t\t\t\t<td><input type='text' size='3' name='qtyss[]' value='1'></td>\n\t\t\t\t\t\t\t<td><input type='text' name='unitcosts[]' size='7'></td>\n\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t\t\t\t<td><input type='hidden' name='discs[]' value='0'><input type='hidden' name='discps[]' value='0' ></td>\n\t\t\t\t\t\t</tr>";
                }
            }
        }
    } else {
        if (!isset($addnon) && !isset($upBtn)) {
            if (isset($filter_store) and $filter_store != "0") {
                # get selected warehouse name
                db_conn("exten");
                $sql = "SELECT whname FROM warehouses WHERE whid = '{$filter_store}' AND div = '" . USER_DIV . "'";
                $whRslt = db_exec($sql);
                $wh = pg_fetch_array($whRslt);
            }
            if (isset($des) and $des != "") {
                $len = strlen($des);
                if ($des == "Show All") {
                    $Wh = "";
                    $des = "";
                } else {
                    $Wh = "AND (lower(substr(stkdes,1,'{$len}'))=lower('{$des}') OR lower(substr(stkcod,1,'{$len}'))=lower('{$des}'))";
                }
            } else {
                $Wh = "AND FALSE";
                $des = "";
            }
            $check_setting = getCSetting("OPTIONAL_STOCK_FILTERS");
            if (isset($check_setting) and $check_setting == "yes") {
                if (isset($filter_class) and $filter_class != "0") {
                    $Wh .= " AND prdcls = '{$filter_class}'";
                }
                if (isset($filter_cat) and $filter_cat != "0") {
                    $Wh .= " AND catid = '{$filter_cat}'";
                }
            }
            if (isset($filter_store) and $filter_store != "0") {
                $Wh .= " AND whid = '{$filter_store}'";
            }
            # get stock on this warehouse
            db_connect();
            $sql = "SELECT * FROM stock WHERE blocked = 'n' AND div = '" . USER_DIV . "' {$Wh} ORDER BY stkcod ASC";
            $stkRslt = db_exec($sql) or errDie("Unable to retrieve stocks from database.");
            if (pg_numrows($stkRslt) < 1) {
                if (!isset($err)) {
                    $err = "";
                }
                $err .= "<li>There are no stock items in the selected warehouse.</li>";
            }
            $stks = "<select name='stkidss[]' onChange='javascript:document.form.submit();'>";
            $stks .= "<option value='-S' disabled selected>Select Number</option>";
            $count = 0;
            while ($stk = pg_fetch_array($stkRslt)) {
                $stks .= "<option value='{$stk['stkid']}'>{$stk['stkcod']} (" . sprint3($stk['units'] - $stk['alloc']) . ")</option>";
            }
            $stks .= "</select> ";
            $products .= "\n\t\t\t\t<input type='hidden' name='descriptionss[]' value=''>\n\t\t\t\t<input type='hidden' name='vatcodess[]' value=''>\n\t\t\t\t<input type='hidden' name='accountss[]' value='0'>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><input type='hidden' name='whidss[]' value='{$filter_store}'></td>\n\t\t\t\t\t<td>{$stks}</td>\n\t\t\t\t\t<td></td>\n\t\t\t\t\t<td></td>\n\t\t\t\t\t<td><input type='text' size='3' name='qtyss[]' value='1'></td>\n\t\t\t\t\t<td> </td>\n\t\t\t\t\t<td><input type='text' size='4' name='discs[]' value='0'> OR <input type='text' size='4' name='discps[]' value='0' maxlength='5'>%</td>\n\t\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t\t<td></td>\n\t\t\t\t</tr>";
        } else {
            if (isset($addnon)) {
                db_conn('core');
                $Sl = "SELECT accid,topacc,accnum,accname FROM accounts WHERE acctype='I' ORDER BY accname";
                $Ri = db_exec($Sl) or errDie("Unable to get accounts.");
                $Accounts = "\n\t\t\t\t<select name='accountss[]'>\n\t\t\t\t\t<option value='0'>Select Account</option>";
                while ($ad = pg_fetch_array($Ri)) {
                    if (isb($ad['accid'])) {
                        continue;
                    }
                    $Accounts .= "<option value='{$ad['accid']}'>{$ad['accname']}</option>";
                }
                $Accounts .= "</select>";
                db_conn('cubit');
                $Sl = "SELECT * FROM vatcodes ORDER BY code";
                $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                $Vatcodes = "\n\t\t\t\t<select name='vatcodess[]'>\n\t\t\t\t\t<option value='0'>Select</option>";
                while ($vd = pg_fetch_array($Ri)) {
                    if ($vd['del'] == "Yes") {
                        $sel = "selected";
                    } else {
                        $sel = "";
                    }
                    $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
                }
                $Vatcodes .= "</select>";
                $products .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='2'>{$Accounts}<input type='hidden' name='whidss[]' value='{$FIRST_WH}'></td>\n\t\t\t\t\t<inpu type='hidden' name='stkidss[]' value=''>\n\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t<td><input type='text' size='20' name='descriptionss[]'></td>\n\t\t\t\t\t<td><input type='text' size='3' name='qtyss[]' value='1'></td>\n\t\t\t\t\t<td><input type='text' name='unitcosts[]' size='7'></td>\n\t\t\t\t\t<td></td>\n\t\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t\t<td><input type='hidden' name='discs[]' value='0'><input type='hidden' name='discps[]' value='0'></td>\n\t\t\t\t</tr>";
            }
        }
    }
    $products .= "</table>";
    /* --- End Products Display --- */
    /* --- Start Some calculations --- */
    # Calculate subtotal
    $SUBTOT = sprint($quo['subtot']);
    $VATP = TAX_VAT;
    # Calculate subtotal
    $SUBTOT = sprint($quo['subtot']);
    $VAT = sprint($quo['vat']);
    $TOTAL = sprint($quo['total']);
    /* --- End Some calculations --- */
    /*--- Start checks --- */
    # check only if the customer is selected
    if (isset($cusnum) && $cusnum != "-S") {
        #check againg credit limit
        if ($cust['credlimit'] != 0 && $TOTAL + $cust['balance'] > $cust['credlimit']) {
            $error .= "<li class='err'>Warning : Customers Credit limit of <b>" . CUR . " {$cust['credlimit']}</b> has been exceeded</li>";
        }
        $avcred = $cust['credlimit'] - $cust['balance'];
    } else {
        $avcred = "0.00";
    }
    $quo['delvat'] += 0;
    if ($quo['delvat'] == 0) {
        $Sl = "SELECT * FROM vatcodes WHERE del='Yes'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $vd = pg_fetch_array($Ri);
        $quo['delvat'] = $vd['id'];
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes ORDER BY code";
    $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
    $Vatcodes = "\n\t\t<select name='delvat'>\n\t\t\t<option value='0'>Select</option>";
    while ($vd = pg_fetch_array($Ri)) {
        if ($vd['id'] == $quo['delvat']) {
            $sel = "selected";
        } else {
            $sel = "";
        }
        $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
    }
    $Vatcodes .= "</select>";
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    // Which display method was selected
    if (isset($sel_frm) && $sel_frm == "stkdes") {
        $sel_frm_cod = "";
        $sel_frm_des = "checked";
    } else {
        $sel_frm_cod = "checked";
        $sel_frm_des = "";
    }
    $sel = "";
    if (isset($lead) and strlen($lead) > 0) {
        $sel = "checked=yes";
    }
    /*--- Start checks --- */
    /* -- Final Layout --No VAT<input type=radio size=7 name=chrgvat value='nov' $chno> */
    $details_begin = "\n\t\t<center>\n\t\t<h3>New Quote</h3>\n\t\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t\t<input type='hidden' name='key' value='update'>\n\t\t\t<input type='hidden' name='quoid' value='{$quoid}'>\n\t\t<table " . TMPL_tblDflts . " width='95%'>\n\t\t\t<tr>\n\t\t\t\t<td valign='top'>\n\t\t\t\t\t<div id='cust_selection'>";
    if (empty($ajax_err) && (isset($cusnum) || AJAX)) {
        if (isset($cusnum)) {
            $OTS_OPT = onthespot_encode(SELF, "cust_selection", "deptid={$quo['deptid']}&letters={$letters}&cusnum={$cusnum}&quoid={$quoid}");
            $custedit = "\n\t\t\t\t<td nowrap>\n\t\t\t\t\t<a href='javascript: popupSized(\"cust-edit.php?cusnum={$cusnum}&onthespot={$OTS_OPT}\", \"edit_cust\", 700, 630);'>Edit Customer Details</a>\n\t\t\t\t</td>";
        } else {
            $custedit = "";
        }
        $optional_filter_setting = getCSetting("OPTIONAL_STOCK_FILTERS");
        if (isset($optional_filter_setting) and $optional_filter_setting == "yes") {
            db_connect();
            $catsql = "SELECT catid, cat, catcod FROM stockcat WHERE div = '" . USER_DIV . "' ORDER BY cat ASC";
            $catRslt = db_exec($catsql);
            if (pg_numrows($catRslt) < 1) {
                $cat_drop = "<input type='hidden' name='filter_cat' value='0'>";
            } else {
                $cat_drop = "<select name='filter_cat'>";
                $cat_drop .= "<option value='0'>All Categories</option>";
                while ($cat = pg_fetch_array($catRslt)) {
                    if (isset($filter_cat) and $filter_cat == $cat['catid']) {
                        $cat_drop .= "<option value='{$cat['catid']}' selected>({$cat['catcod']}) {$cat['cat']}</option>";
                    } else {
                        $cat_drop .= "<option value='{$cat['catid']}'>({$cat['catcod']}) {$cat['cat']}</option>";
                    }
                }
                $cat_drop .= "</select>";
            }
            # Select classification
            $classsql = "SELECT * FROM stockclass WHERE div = '" . USER_DIV . "' ORDER BY classname ASC";
            $clasRslt = db_exec($classsql);
            if (pg_numrows($clasRslt) < 1) {
                $class_drop = "<input type='hidden' name='filter_class' value='0'>";
            } else {
                $class_drop = "<select name='filter_class' style='width: 167'>";
                $class_drop .= "<option value='0'>All Classifications</option>";
                while ($clas = pg_fetch_array($clasRslt)) {
                    if (isset($filter_class) and $filter_class == $clas['clasid']) {
                        $class_drop .= "<option value='{$clas['clasid']}' selected>{$clas['classname']}</option>";
                    } else {
                        $class_drop .= "<option value='{$clas['clasid']}'>{$clas['classname']}</option>";
                    }
                }
                $class_drop .= "</select>";
            }
            $display_optional_filters = "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Select Category</td>\n\t\t\t\t\t<td>{$cat_drop}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Select Classification</td>\n\t\t\t\t\t<td>{$class_drop}</td>\n\t\t\t\t</tr>";
        }
        db_conn("exten");
        $sql = "SELECT whid, whname, whno FROM warehouses WHERE div = '" . USER_DIV . "' ORDER BY whname ASC";
        $whRslt = db_exec($sql);
        if (pg_numrows($whRslt) < 1) {
            $store_drop = "<input type='hidden' name='filter_store' value='0'>";
        } else {
            if (!isset($filter_store)) {
                # check if setting exists
                db_connect();
                $sql = "SELECT value FROM set WHERE label = 'DEF_WH' AND div = '" . USER_DIV . "'";
                $Rslt = db_exec($sql) or errDie("Unable to check database for existing settings.");
                if (pg_numrows($Rslt) > 0) {
                    $set = pg_fetch_array($Rslt);
                    $filter_store = $set['value'];
                }
            }
            $store_drop = "<select name='filter_store'>";
            $store_drop .= "<option value='0'>All Stores</option>";
            while ($wh = pg_fetch_array($whRslt)) {
                if (isset($filter_store) and $filter_store == $wh['whid']) {
                    $store_drop .= "<option value='{$wh['whid']}' selected>({$wh['whno']}) {$wh['whname']}</option>";
                } else {
                    $store_drop .= "<option value='{$wh['whid']}'>({$wh['whno']}) {$wh['whname']}</option>";
                }
            }
            $store_drop .= "</select>";
        }
        $ajaxOut = "\n\t\t\t<input type='hidden' name='letters' value='{$letters}'>\n\t\t\t<input type='hidden' name='stkerr' value='{$stkerr}'>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th colspan='2'> Customer Details </th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Department</td>\n\t\t\t\t\t<td valign='center'>{$dept['deptname']}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Account No.</td>\n\t\t\t\t\t<td valign='center'>{$cust['accno']}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Customer</td>\n\t\t\t\t\t<td valign='center'>{$customers}</td>\n\t\t\t\t\t{$custedit}\n\t\t\t\t\t<td><input type='button' onClick=\"javascript:document.location=('pos-quote-new.php')\" value='Quote Non Customer'></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td valign='top'>Customer Address</td>\n\t\t\t\t\t<td valign='center'>" . nl2br($cust['addr1']) . "</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Customer Req number</td>\n\t\t\t\t\t<td valign='center'><input type='text' size='10' name='cordno' value='{$quo['cordno']}'></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Customer VAT Number</td>\n\t\t\t\t\t<td>{$cust['vatnum']}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td valign='top'>Next Contact Date</td>\n\t\t\t\t\t<td valign='center'>" . mkDateSelect("ncdate", $ncdate_year, $ncdate_month, $ncdate_day) . "</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td valign='top'>Add As Lead</td>\n\t\t\t\t\t<td valign='center'><input type='checkbox' name='lead' {$sel} value='yes'></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Select Using</td>\n\t\t\t\t\t<td>Stock Code<input type='radio' name='sel_frm' value='stkcod' onChange='javascript:document.form.submit();' {$sel_frm_cod}><br>Stock Description<input type='radio' name='sel_frm' value='stkdes' onChange='javascript:document.form.submit();' {$sel_frm_des}></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<th colspan='2'>Additional Filters</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Select Store</td>\n\t\t\t\t\t<td>{$store_drop}</td>\n\t\t\t\t</tr>\n\t\t\t\t{$display_optional_filters}\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Stock Filter</td>\n\t\t\t\t\t<td><input type='text' size='13' name='des' value='{$des}'> <input type='submit' value='Search'> <input type='submit' name='des' value='Show All'></td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    } else {
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE div = '" . USER_DIV . "' ORDER BY deptname ASC";
        $deptRslt = db_exec($sql) or errDie("Unable to view customers");
        if (pg_numrows($deptRslt) < 1) {
            return "<li class='err'>There are no Departments found in Cubit.</li>";
        } else {
            $depts = "<select id='deptid'>";
            $depts .= "<option value='0'>All Departments</option>";
            while ($dept = pg_fetch_array($deptRslt)) {
                $depts .= "<option value='{$dept['deptid']}'>{$dept['deptname']}</option>";
            }
            $depts .= "</select>";
        }
        if (!isset($ajax_err)) {
            $ajax_err = "";
        }
        $ajaxOut = "\n\t\t\t<script>\n\t\t\t\tfunction updateCustSelection() {\n\t\t\t\t\tdeptid = getObject('deptid').value;\n\t\t\t\t\tletters = getObject('letters').value;\n\t\t\t\t\tajaxRequest('" . SELF . "', 'cust_selection', AJAX_SET, 'letters='+letters+'&deptid='+deptid+'&quoid={$quoid}');\n\t\t\t\t}\n\t\t\t</script>\n\t\t\t{$ajax_err}\n\t\t\t<table " . TMPL_tblDflts . " width='400'>\n\t\t\t<tr>\n\t\t\t\t<th colspan='2'>New Quote</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>" . REQ . "Select Department</td>\n\t\t\t\t<td valign='center'>{$depts}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>First Letters of customer</td>\n\t\t\t\t<td valign='center'><input type='text' size='5' id='letters' maxlength='5'></td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>&nbsp;</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t<td valign='center'><input type='button' value='Update &raquo' onClick='updateCustSelection();'></td>\n\t\t\t</tr>\n\t\t</table>";
    }
    $avcred = sprint($avcred);
    if (isset($addprodBtn) or isset($addnon) or isset($saveBtn) or isset($upBtn) or isset($doneBtn) or isset($donePrnt) or isset($des)) {
        $jump_bot = "\n\t\t\t<script>\n\t\t\t\twindow.location.hash='bottom';\n\t\t\t</script>";
    } else {
        $jump_bot = "";
    }
    $details_end = "\n\t\t\t\t\t</div>\n\t\t\t\t</td>\n\t\t\t\t<td valign='top' align='right'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th colspan='2'> Quote Details </th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Quote No.</td>\n\t\t\t\t\t\t\t<td valign='center'>{$quo['quoid']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Order No.</td>\n\t\t\t\t\t\t\t<td valign='center'><input type='text' size='5' name='ordno' value='{$quo['ordno']}'></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>VAT Inclusive</td>\n\t\t\t\t\t\t\t<td valign='center'>Yes <input type='radio' size='7' name='chrgvat' value='inc' {$chin}> No<input type='radio' size='7' name='chrgvat' value='exc' {$chex}> </td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Terms</td>\n\t\t\t\t\t\t\t<td valign='center'>{$termssel} Days</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Sales Person</td>\n\t\t\t\t\t\t\t<td valign='center'>{$salesps}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Quote Date</td>\n\t\t\t\t\t\t\t<td valign='center'>" . mkDateSelect("quote", $quote_year, $quote_month, $quote_day) . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Available Credit</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$avcred}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Trade Discount</td>\n\t\t\t\t\t\t\t<td valign='center'><input type='text' size='5' name='traddisc' value='{$quo['traddisc']}'>%</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Delivery Charge</td>\n\t\t\t\t\t\t\t<td valign='center'><input type='text' size='7' name='delchrg' value='{$quo['delchrg']}'>{$Vatcodes}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'>{$products}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td rowspan='2'>" . mkQuickLinks(ql("quote-view.php", "View Quotes"), ql("customers-new.php", "New Customer")) . "\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<th width='25%'>Comments</th>\n\t\t\t\t\t\t\t<td rowspan='5' valign='top' width='50%'>{$error}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td class='" . bg_class() . "' rowspan='4' align='center' valign='top'>\n\t\t\t\t\t\t\t\t<textarea name='comm' rows='4' cols='20'>{$quo['comm']}</textarea>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t\t<td align='right'>\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>SUBTOTAL</td>\n\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " <input type='hidden' name='SUBTOT' value='{$SUBTOT}'>{$SUBTOT}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Trade Discount</td>\n\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$quo['discount']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Delivery Charge</td>\n\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$quo['delivery']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td><b>VAT {$vat14}</b></td>\n\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$VAT}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<th>GRAND TOTAL</th>\n\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$TOTAL}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td align='center' colspan='2' nowrap><input name='addprodBtn' type='submit' value='Add Product'> | <input name='addnon' type='submit' value='Add Non stock Product'> | <input type='submit' name='saveBtn' value='Save'> | <input type='submit' name='upBtn' value='Update'>{$done}</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<a name='bottom'>\n\t\t</form>\n\t\t</center>\n\t\t{$jump_bot}";
    if (AJAX) {
        return $ajaxOut;
    } else {
        return "{$details_begin}{$ajaxOut}{$details_end}";
    }
}
function details($_POST, $error = "")
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    if (isset($invid)) {
        $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    }
    if (isset($letter)) {
        $v->isOk($letters, "string", 0, 5, "Invalid First 3 Letters.");
    }
    if (isset($deptid)) {
        $v->isOk($deptid, "num", 1, 20, "Invalid department number.");
    }
    if (isset($sel_frm)) {
        $v->isOk($sel_frm, "string", 6, 6, "Invalid select from selection.");
    }
    # display errors, if any
    if ($v->isError()) {
        $error = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $error .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return $error . view_err($_POST);
    }
    if (isset($deptid) && isset($letters)) {
        db_connect();
        if ($deptid == "0") {
            $searchdept = "";
        } else {
            $searchdept = "deptid = '{$deptid}' AND ";
        }
        # Query server for customer info
        $sql = "SELECT cusnum,cusname,surname FROM customers WHERE {$searchdept} location != 'int' AND lower(surname) LIKE lower('{$letters}%') AND blocked != 'yes' AND div = '" . USER_DIV . "' ORDER BY surname";
        $custRslt = db_exec($sql) or errDie("Unable to view customers");
        if (pg_numrows($custRslt) < 1) {
            $ajax_err = "<li class='err'>No customer names starting with <b>{$letters}</b> in database.</li>";
            //return view_err($_POST, $err);
        }
    }
    if (!isset($deptid)) {
        $deptid = 2;
    } else {
        if (isset($invid)) {
            db_conn("cubit");
            $sql = "UPDATE invoices SET deptid='{$deptid}' WHERE invid='{$invid}' AND deptid<>'{$deptid}'";
            db_exec($sql) or errDie("Error updating invoice department.");
        }
    }
    if (!isset($invid)) {
        $invid = create_dummy($deptid);
    }
    if (!isset($stkerr)) {
        $stkerr = "0,0";
    }
    if (!isset($done)) {
        $done = "";
    }
    if (!isset($cust_del_addr)) {
        $cust_del_addr = "";
    }
    if (!isset($sel_frm)) {
        $sel_frm = "stkcod";
    }
    # Get invoice info
    db_connect();
    $sql = "SELECT * FROM invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<li class='err'>Invoice Not Found</li>";
    }
    $inv = pg_fetch_array($invRslt);
    if (!isset($branch)) {
        $branch = $inv['branch'];
    }
    # Check if invoice has been printed
    if ($inv['printed'] == "y") {
        $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has already been printed.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # Get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$inv['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<li class='err'>Department not Found.</li>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    # Get selected Customer info
    if (isset($letters)) {
        db_connect();
        $sql = "SELECT * FROM customers WHERE cusnum = '{$inv['cusnum']}' AND location != 'int' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to view customer");
        if (pg_numrows($custRslt) < 1) {
            db_connect();
            if ($inv['deptid'] == 0) {
                $searchdept = "";
            } else {
                $searchdept = "deptid = '{$inv['deptid']}' AND ";
            }
            # Query server for customer info
            $sql = "SELECT cusnum,cusname,surname FROM customers WHERE {$searchdept} location != 'int' AND lower(surname) LIKE lower('{$letters}%') AND blocked != 'yes' AND div = '" . USER_DIV . "' ORDER BY surname";
            $custRslt = db_exec($sql) or errDie("Unable to view customers");
            if (pg_numrows($custRslt) < 1) {
                $ajax_err = "<li class=err>No customer names starting with <b>{$letters}</b> in database.</li>";
                //return view_err($_POST, $err);
            } else {
                $customers = "<select name='cusnum' onChange='javascript:document.form.submit();'>";
                $customers .= "<option value='-S' selected>Select Customer</option>";
                while ($cust = pg_fetch_array($custRslt)) {
                    $customers .= "<option value='{$cust['cusnum']}'>{$cust['cusname']} {$cust['surname']}</option>";
                }
                $customers .= "</select>";
            }
            # Take care of the unset vars
            $cust['addr1'] = "";
            $cust['cusnum'] = "";
            $cust['vatnum'] = "";
            $cust['accno'] = "";
            $cust_del_addr = "";
            $branchdrop = "<input type='hidden' name='branch' value='0'>";
        } else {
            $cust = pg_fetch_array($custRslt);
            #override address
            if ($branch != 0) {
                $get_addr = "SELECT branch_descrip FROM customer_branches WHERE id = '{$branch}' AND div = '" . USER_DIV . "' LIMIT 1";
                $run_addr = db_exec($get_addr);
                if (pg_numrows($run_addr) < 1) {
                    #address missing ... do nothing
                } else {
                    $arr = pg_fetch_array($run_addr);
                    $cust['addr1'] = $arr['branch_descrip'];
                    if ($inv['del_addr'] != $arr['branch_descrip']) {
                        $update_addr = "UPDATE invoices SET del_addr  = '{$arr['branch_descrip']}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
                    }
                }
            }
            #if the del_addr of invoice if empty, add the customer's entry and display button so user can edit anyway
            if (strlen($inv['del_addr']) < 1) {
                $cust_del_addr = $cust['del_addr1'];
                #we need to write this to the db ... now
                $update_addr = "UPDATE invoices SET del_addr  = '{$cust_del_addr}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
                //				$run_update = db_exec($update_addr) or errDie("Unable to update invoice information");
            } else {
                $cust_del_addr = $inv['del_addr'];
            }
            $sql = "SELECT cusnum, cusname, surname FROM customers WHERE deptid = '{$inv['deptid']}' AND location != 'int' AND lower(surname) LIKE lower('{$letters}%') AND blocked != 'yes' AND div = '" . USER_DIV . "' ORDER BY surname";
            $cusRslt = db_exec($sql) or errDie("Unable to view customers");
            # Moarn if customer account has been blocked
            if ($cust['blocked'] == 'yes') {
                $error .= "<li class='err'>Error : Selected customer account has been blocked.</li>";
            }
            // $customers = "<input type=hidden name=cusnum value='$cust[cusnum]'>$cust[cusname]  $cust[surname]";
            $cusnum = $cust['cusnum'];
            $customers = "<select name='cusnum' onChange='javascript:document.form.submit();'>";
            // $customers .= "<option value='-S' selected>Select Customer</option>";
            while ($cus = pg_fetch_array($cusRslt)) {
                $sel = "";
                if ($cust['cusnum'] == $cus['cusnum']) {
                    $sel = "selected";
                }
                $customers .= "<option value='{$cus['cusnum']}' {$sel}>{$cus['cusname']} {$cus['surname']}</option>";
            }
            $customers .= "</select>";
            #get list of branches
            $get_branches = "SELECT * FROM customer_branches WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
            $run_branches = db_exec($get_branches);
            if (pg_numrows($run_branches) < 1) {
                $branchdrop = "<input type='hidden' name=branch value='0'>No Branches For This Customer";
            } else {
                $branchdrop = "<select name='branch' onChange='javascript:document.form.submit();'>";
                $branchdrop .= "<option value='0'>Head Office</option>";
                while ($barr = pg_fetch_array($run_branches)) {
                    $sel2 = "";
                    if ($barr['id'] == $branch) {
                        $sel2 = "selected";
                    }
                    $branchdrop .= "<option {$sel2} value='{$barr['id']}'>{$barr['branch_name']}</option>";
                }
                $branchdrop .= "</select>";
            }
            /*			#override address
            			if($branch != 0){
            				$get_addr = "SELECT branch_descrip FROM customer_branches WHERE id = '$branch' AND div = '".USER_DIV."' LIMIT 1";
            				$run_addr = db_exec($get_addr);
            				if(pg_numrows($run_addr) < 1){
            					#address missing ... do nothing
            				}else {
            					$arr = pg_fetch_array($run_addr);
            					$cust['addr1'] = $arr['branch_descrip'];
            				}
            			}*/
        }
    }
    /* --- Start Drop Downs --- */
    # Select warehouse
    db_conn("exten");
    //old
    //$whs = "<select name='whidss[]' onChange='javascript:document.form.submit();'>";
    //fixes broken store function
    $whs = "<select name='whidss[]'>";
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "' ORDER BY whname ASC";
    $whRslt = db_exec($sql);
    if (pg_numrows($whRslt) < 1) {
        return "<li class='err'> There are no Stores found in Cubit.</li>";
    } else {
        $whs .= "<option value='-S' disabled selected>Select Store</option>";
        while ($wh = pg_fetch_array($whRslt)) {
            if (!user_in_store_team($wh["whid"], USER_ID)) {
                continue;
            }
            $whs .= "<option value='{$wh['whid']}'>({$wh['whno']}) {$wh['whname']}</option>";
        }
    }
    $whs .= "</select>";
    // Is the customer linked to a sales rep
    if (!empty($cust["sales_rep"])) {
        db_conn("exten");
        $sql = "SELECT salesp FROM salespeople WHERE salespid='{$cust['sales_rep']}'";
        $sr_rslt = db_exec($sql) or errDie("Unable to retrieve sales rep from Cubit.");
        $salespname = pg_fetch_result($sr_rslt, 0);
        $salesps = "<input type='hidden' name='salespn' value='{$salespname}'><b>[{$salespname}]</b>";
    } else {
        db_conn("exten");
        $sql = "SELECT * FROM salespeople WHERE div = '" . USER_DIV . "' ORDER BY salesp ASC";
        $salespRslt = db_exec($sql) or errDie("Unable to get sales people.");
        if (pg_numrows($salespRslt) < 1) {
            return "<li class='err'> There are no Sales People found in Cubit.</li>";
        } else {
            $salesps = "<select name='salespn'>";
            while ($salesp = pg_fetch_array($salespRslt)) {
                if ($salesp['salesp'] == $inv['salespn']) {
                    $sel = "selected";
                } else {
                    $sel = "";
                }
                $salesps .= "<option value='{$salesp['salesp']}' {$sel}>{$salesp['salesp']}</option>";
            }
            $salesps .= "</select>";
        }
    }
    # Days drop downs
    $days = array("0" => "0", "7" => "7", "14" => "14", "30" => "30", "60" => "60", "90" => "90", "120" => "120");
    $termssel = extlib_cpsel("terms", $days, $inv['terms']);
    $sql = "SELECT value FROM cubit.settings WHERE constant='VAT_INC'";
    // 2007-05-09 New VAT setting in admin menu
    # Keep the charge vat option stable
    if ($inv['chrgvat'] == "inc") {
        $chin = "checked=yes";
        $chex = "";
        $chno = "";
    } elseif ($inv['chrgvat'] == "exc") {
        $chin = "";
        $chex = "checked=yes";
        $chno = "";
    } else {
        $chin = "";
        $chex = "";
        $chno = "checked=yes";
    }
    # Format date
    list($inv_date_year, $inv_date_month, $inv_date_day) = explode("-", $inv['odate']);
    /* --- End Drop Downs --- */
    /* --- Start Products Display --- */
    # Select all products
    $products = "\n\t\t<table " . TMPL_tblDflts . "' width='100%'>\n\t\t\t<tr>\n\t\t\t\t<th>STORE</th>\n\t\t\t\t<th>ITEM NUMBER</th>\n\t\t\t\t<th>VAT CODE</th>\n\t\t\t\t<th>SERIAL NO.</th>\n\t\t\t\t<th>DESCRIPTION</th>\n\t\t\t\t<th>QTY</th>\n\t\t\t\t<th>UNIT PRICE</th>\n\t\t\t\t<th>UNIT DISCOUNT</th>\n\t\t\t\t<th>AMOUNT</th>\n\t\t\t\t<th>Remove</th>\n\t\t\t<tr>";
    # get selected stock in this invoice
    db_connect();
    $sql = "SELECT * FROM inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $i = 0;
    $key = 0;
    $ai = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        $stkd['account'] += 0;
        if ($stkd['account'] != 0) {
            # Keep track of selected stock amounts
            $stkd["amt"] = sprint($stkd["amt"]);
            $amts[$i] = $stkd['amt'];
            $i++;
            db_conn('core');
            $Sl = "SELECT accid,topacc,accnum,accname FROM accounts WHERE acctype='I' ORDER BY accname";
            $Ri = db_exec($Sl) or errDie("Unable to get accounts.");
            $Accounts = "\n\t\t\t\t<select name='accounts[{$ai}]'>\n\t\t\t\t\t<option value='0'>Select Account</option>";
            while ($ad = pg_fetch_array($Ri)) {
                if ($ad['accid'] == $stkd['account']) {
                    $sel = "selected";
                } else {
                    $sel = "";
                }
                if (isb($ad['accid'])) {
                    continue;
                }
                $Accounts .= "<option value='{$ad['accid']}' {$sel}>{$ad['accname']}</option>";
            }
            $Accounts .= "</select>";
            $sernos = "\n\t\t\t\t<input type='hidden' name='sernos[{$ai}]' value='{$stkd['serno']}'>\n\t\t\t\t<input type='hidden' name='sernos_ss[{$ai}]' value='{$stkd['serno']}'>";
            # Input qty if not serialised
            $qtyin = "<input type='text' size='3' name='qtys[{$ai}]' value='{$stkd['qty']}'>";
            $viewcost = "<input type='text' size='8' name='unitcost[{$ai}]' value='{$stkd['unitcost']}'>";
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes ORDER BY code";
            $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
            $Vatcodes = "\n\t\t\t\t<select name='vatcodes[{$ai}]'>\n\t\t\t\t\t<option value='0'>Select</option>";
            while ($vd = pg_fetch_array($Ri)) {
                if ($stkd['vatcode'] == $vd['id']) {
                    $sel = "selected";
                } else {
                    $sel = "";
                }
                $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
            }
            $Vatcodes .= "</select>";
            # Put in product
            $products .= "\n\t\t\t\t<input type='hidden' name='stkids[{$ai}]' value='{$stkd['stkid']}'>\n\t\t\t\t<input type='hidden' name='discp[{$ai}]' value='{$stkd['discp']}'>\n\t\t\t\t<input type='hidden' name='whids[{$ai}]' value='{$stkd['whid']}'>\n\t\t\t\t<input type='hidden' name='amt[{$ai}]' value='{$stkd['amt']}'>\n\t\t\t\t<input type='hidden' name='disc[{$ai}]' value='{$stkd['disc']}'>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='2'>{$Accounts}</td>\n\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t<td></td>\n\t\t\t\t\t<td><input type='text' size='20' name='descriptions[{$ai}]' value='{$stkd['description']}'> {$sernos}</td>\n\t\t\t\t\t<td>{$qtyin}</td>\n\t\t\t\t\t<td>{$viewcost}</td>\n\t\t\t\t\t<td></td>\n\t\t\t\t\t<td nowrap> " . CUR . " {$stkd['amt']}</td>\n\t\t\t\t\t<td><input type='checkbox' name='remprod[{$ai}]' value='{$key}'></td>\n\t\t\t\t</tr>";
            $key++;
            ++$ai;
        } else {
            # Keep track of selected stock amounts
            $amts[$i] = $stkd['amt'];
            $i++;
            # Get warehouse name
            db_conn("exten");
            $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            # Get selected stock in this warehouse
            db_connect();
            $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql);
            $stk = pg_fetch_array($stkRslt);
            # Serial number
            if ($stk['serd'] == 'yes' && ($inv['serd'] == 'n' || $stkd["serno"] == "")) {
                $sers = ext_getavserials($stkd['stkid']);
                $sernos = "<select name='sernos[{$ai}]'>";
                foreach ($sers as $skey => $ser) {
                    $sernos .= "<option value='{$ser['serno']}'>{$ser['serno']}</option>";
                }
                $sernos .= "</select>\n\t\t\t\t\t\t\t<input type='hidden' name='sernos_ss[]' value='*_*_*CUBIT_SERIAL_SELECT_BOX*_*_*' />";
            } else {
                $sernos = "\n\t\t\t\t\t<input type='hidden' name='sernos_ss[]' value='{$stkd['ss']}' />\n\t\t\t\t\t<input type='hidden' name='sernos[{$ai}]' value='{$stkd['serno']}'>{$stkd['ss']}";
            }
            # Input qty if not serialised
            $qtyin = "<input type='text' size='3' name='qtys[{$ai}]' value='{$stkd['qty']}'>";
            if ($stk['serd'] == 'yes') {
                $qtyin = "<input type='hidden' size='3' name='qtys[{$ai}]' value='{$stkd['qty']}'>{$stkd['qty']}";
            }
            # check permissions
            if (perm("invoice-unitcost-edit.php")) {
                $viewcost = "<input type='text' size='8' name='unitcost[{$ai}]' value='{$stkd['unitcost']}'>";
            } else {
                $viewcost = "<input type='hidden' size='8' name='unitcost[{$ai}]' value='{$stkd['unitcost']}'>{$stkd['unitcost']}";
            }
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes ORDER BY code";
            $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
            $Vatcodes = "\n\t\t\t\t<select name='vatcodes[{$ai}]'>\n\t\t\t\t\t<option value='0'>Select</option>";
            while ($vd = pg_fetch_array($Ri)) {
                if ($stkd['vatcode'] == $vd['id']) {
                    $sel = "selected";
                } else {
                    $sel = "";
                }
                $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
            }
            $Vatcodes .= "</select>";
            $products .= "\n\t\t\t\t<input type='hidden' name='accounts[{$ai}]' value='0'>\n\t\t\t\t<input type='hidden' name='descriptions[{$ai}]' value=''>\n\t\t\t\t<input type='hidden' name='whids[{$ai}]' value='{$stkd['whid']}'>\n\t\t\t\t<input type='hidden' name='stkids[]' value='{$stkd['stkid']}'>\n\t\t\t\t<input type='hidden' name='amt[{$ai}]' value='{$stkd['amt']}'>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$wh['whname']}</td>\n\t\t\t\t\t<td><a href='#bottom' onclick='openwindow(\"stock-amt-det.php?stkid={$stk['stkid']}\")'>{$stk['stkcod']}</a></td>\n\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t<td>{$sernos}</td>\n\t\t\t\t\t<td>" . extlib_rstr($stk['stkdes'], 30) . "</td>\n\t\t\t\t\t<td>{$qtyin}</td>\n\t\t\t\t\t<td>{$viewcost}</td>\n\t\t\t\t\t<td><input type='text' size='4' name='disc[{$ai}]' value='{$stkd['disc']}'> OR <input type='text' size='4' name='discp[{$ai}]' value='{$stkd['discp']}' maxlength='5'>%</td>\n\t\t\t\t\t<td nowrap>" . CUR . " {$stkd['amt']}</td>\n\t\t\t\t\t<td><input type='checkbox' name='remprod[{$ai}]' value='{$key}'></td>\n\t\t\t\t</tr>";
            $key++;
            ++$ai;
        }
    }
    # Look above(remprod keys)
    $keyy = $key;
    # Look above(if i = 0 then there are no products)
    if ($i == 0) {
        $done = "";
    } else {
        $SCROLL = "yes";
    }
    # check if stock warehouse was selected
    if (isset($whidss)) {
        foreach ($whidss as $key => $whid) {
            if (isset($stkidss[$key]) && $stkidss[$key] != "-S" && isset($cust['pricelist'])) {
                # skip if not selected
                if ($whid == "-S") {
                    continue;
                }
                # Get selected warehouse name
                db_conn("exten");
                $sql = "SELECT whname FROM warehouses WHERE whid = '{$whid}' AND div = '" . USER_DIV . "'";
                $whRslt = db_exec($sql);
                $wh = pg_fetch_array($whRslt);
                # Get selected stock in this warehouse
                db_connect();
                $sql = "SELECT * FROM stock WHERE stkid = '{$stkidss[$key]}' AND div = '" . USER_DIV . "' ORDER BY stkcod ASC";
                $stkRslt = db_exec($sql);
                $stk = pg_fetch_array($stkRslt);
                if ($stk['serd'] == 'yes') {
                    $sers = ext_getavserials($stkidss[$key]);
                    $sernos = "<select name='sernos[]' onChange='javascript:document.form.submit();'>";
                    foreach ($sers as $skey => $ser) {
                        $sernos .= "<option value='{$ser['serno']}'>{$ser['serno']}</option>";
                    }
                    $sernos .= "</select>\n\t\t\t\t\t\t<input type='hidden' name='sernos_ss[]' value='*_*_*CUBIT_SERIAL_SELECT_BOX*_*_*' />";
                } else {
                    $sernos = "\n\t\t\t\t\t\t<input type='hidden' name='sernos_ss[]' value=''>\n\t\t\t\t\t\t<input type='hidden' name='sernos[{$ai}]' value=''>";
                }
                # Get price from price list if it is set
                if (isset($cust['pricelist'])) {
                    # get selected stock in this warehouse
                    db_conn("exten");
                    $sql = "SELECT price FROM plist_prices WHERE listid = '{$cust['pricelist']}' AND stkid = '{$stk['stkid']}' AND div = '" . USER_DIV . "'";
                    $plRslt = db_exec($sql);
                    if (pg_numrows($plRslt) > 0) {
                        $pl = pg_fetch_array($plRslt);
                        $stk['selamt'] = $pl['price'];
                    }
                }
                /* -- Start Some Checks -- */
                # check if they are selling too much
                if ($stk['units'] - $stk['alloc'] < $qtyss[$key]) {
                    if (!in_array($stk['stkid'], explode(",", $stkerr))) {
                        if ($stk['type'] != 'lab') {
                            $stkerr .= ",{$stk['stkid']}";
                            $error .= "<li class='err'>Warning :  Item number <b>{$stk['stkcod']}</b> does not have enough items available.</li>";
                        }
                    }
                }
                if ($stk['units'] <= $stk['minlvl'] && $stk['minlvl'] != 0) {
                    $error .= "<li class='err'>{$stk['stkcod']} is below minimum level, please notify stock controller.</li>";
                }
                /* -- End Some Checks -- */
                # Calculate the Discount discount
                if ($discs[$key] < 1) {
                    if ($discps[$key] > 0) {
                        $discs[$key] = round($discps[$key] / 100 * $stk['selamt'], 2);
                    }
                } else {
                    $discps[$key] = round($discs[$key] * 100 / $stk['selamt'], 2);
                }
                # Calculate amount
                $amt[$key] = $qtyss[$key] * ($stk['selamt'] - $discs[$key]);
                # Input qty if not serialised
                $qtyin = "<input type='text' size='3' name='qtemp' value='{$qtyss[$key]}'>";
                if ($stk['serd'] == 'yes') {
                    $qtyin = "<input type='hidden' size='3' name='qtemp' value='{$qtyss[$key]}'>{$qtyss[$key]}";
                }
                #clean some vars
                $stk['selamt'] = sprint($stk['selamt']);
                $amt[$key] = sprint($amt[$key]);
                # Check permissions
                if (perm("invoice-unitcost-edit.php")) {
                    $viewcost = "<input type='text' size='8' name='unitcost[{$ai}]' value='{$stk['selamt']}'>";
                } else {
                    $viewcost = "<input type='hidden' size='8' name='unitcost[{$ai}]' value='{$stk['selamt']}'>{$stk['selamt']}";
                }
                db_conn('cubit');
                $Sl = "SELECT * FROM vatcodes ORDER BY code";
                $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                $Vatcodes = "\n\t\t\t\t\t<select name='vatcodes[{$ai}]'>\n\t\t\t\t\t\t<option value='0'>Select</option>";
                while ($vd = pg_fetch_array($Ri)) {
                    if ($stk['vatcode'] == $vd['id']) {
                        $sel = "selected";
                    } else {
                        $sel = "";
                    }
                    $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
                }
                $Vatcodes .= "</select>";
                # Put in selected warehouse and stock
                $products .= "\n\t\t\t\t\t<input type='hidden' name='accounts[{$ai}]' value='0'>\n\t\t\t\t\t<input type='hidden' name='descriptions[{$ai}]' value=''>\n\t\t\t\t\t<input type='hidden' name='whids[]' value='{$whid}'>\n\t\t\t\t\t<input type='hidden' name='stkids[{$ai}]' value='{$stk['stkid']}'>\n\t\t\t\t\t<input type='hidden' name='amt[{$ai}]' value='{$amt[$key]}'>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>{$wh['whname']}</td>\n\t\t\t\t\t\t<td><a href='#bottom' onclick='openwindow(\"stock-amt-det.php?stkid={$stk['stkid']}\")'>{$stk['stkcod']}</a></td>\n\t\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t\t<td>{$sernos}</td>\n\t\t\t\t\t\t<td>" . extlib_rstr($stk['stkdes'], 30) . "</td>\n\t\t\t\t\t\t<td>{$qtyin}</td>\n\t\t\t\t\t\t<td>{$viewcost}</td>\n\t\t\t\t\t\t<td><input type='text' size='4' name='disc[{$ai}]' value='{$discs[$key]}'> OR <input type='text' size='4' name='discp[{$ai}]' value='{$discps[$key]}' maxlength='5'>%</td>\n\t\t\t\t\t\t<td nowrap>" . CUR . " {$amt[$key]}</td>\n\t\t\t\t\t\t<td><input type='checkbox' name='remprod[{$ai}]' value='{$keyy}'></td>\n\t\t\t\t\t</tr>";
                $keyy++;
                ++$ai;
            } elseif (isset($accountss[$key]) && $accountss[$key] != "0" && isset($cust['pricelist'])) {
                db_conn('core');
                $Sl = "SELECT * FROM accounts WHERE accid='{$accountss[$key]}'";
                $Ri = db_exec($Sl) or errDie("Unable to get account data.");
                if (pg_num_rows($Ri) < 1) {
                    return "invalid.";
                }
                $ad = pg_fetch_array($Ri);
                # Calculate amount
                $amt[$key] = sprint($qtyss[$key] * $unitcosts[$key]);
                # Input qty if not serialised
                $qtyin = "<input type='text' size='3' name='qtemp' value='{$qtyss[$key]}'>";
                # Check permissions
                $viewcost = "<input type='text' size='8' name=unitcost[{$ai}] value='{$unitcosts[$key]}'>";
                db_conn('cubit');
                $Sl = "SELECT * FROM vatcodes ORDER BY code";
                $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                $Vatcodes = "\n\t\t\t\t\t<select name='vatcodes[{$ai}]'>\n\t\t\t\t\t\t<option value='0'>Select</option>";
                while ($vd = pg_fetch_array($Ri)) {
                    if ($vatcodess[$key] == $vd['id']) {
                        $sel = "selected";
                    } else {
                        $sel = "";
                    }
                    $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
                }
                $Vatcodes .= "</select>";
                # Put in selected warehouse and stock
                $products .= "\n\t\t\t\t\t<input type='hidden' name='accounts[{$ai}]' value='{$accountss[$key]}'>\n\t\t\t\t\t<input type='hidden' name='whids[{$ai}]' value='0'>\n\t\t\t\t\t<input type='hidden' name='stkids[{$ai}]' value='0'>\n\t\t\t\t\t<input type='hidden' name='disc[{$ai}]' value='0'>\n\t\t\t\t\t<input type='hidden' name='discp[{$ai}]' value='0'>\n\t\t\t\t\t<input type='hidden' name='amt[{$ai}]' value='{$amt[$key]}'>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td colspan='2'>{$ad['accname']}</td>\n\t\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t<td><input type='text' size='20' name='descriptions[{$ai}]' value='{$descriptionss[$key]}'></td>\n\t\t\t\t\t\t<td>{$qtyin}</td>\n\t\t\t\t\t\t<td>{$viewcost}</td>\n\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t<td nowrap>" . CUR . " {$amt[$key]}</td>\n\t\t\t\t\t\t<td><input type='checkbox' name=remprod[{$ai}] value='{$keyy}'></td>\n\t\t\t\t\t</tr>";
                $keyy++;
                ++$ai;
            } else {
                # skip if not selected
                if ($whid == "-S") {
                    continue;
                }
                if (!isset($addnon)) {
                    if (isset($filter_store) and $filter_store != "0") {
                        # get warehouse name
                        db_conn("exten");
                        $sql = "SELECT whname FROM warehouses WHERE whid = '{$filter_store}' AND div = '" . USER_DIV . "'";
                        $whRslt = db_exec($sql);
                        $wh = pg_fetch_array($whRslt);
                    }
                    if (isset($ria) and $ria != "") {
                        $len = strlen($ria);
                        if ($ria == "Show All") {
                            $Wh = "";
                            $ria = "";
                        } else {
                            $Wh = "AND (lower(stkdes) LIKE lower('%{$ria}%')) OR (lower(stkcod) LIKE lower('%{$ria}%'))";
                            $ria = "";
                        }
                    } else {
                        $Wh = "AND FALSE";
                        $ria = "";
                    }
                    $check_setting = getCSetting("OPTIONAL_STOCK_FILTERS");
                    if (isset($check_setting) and $check_setting == "yes") {
                        if (isset($filter_class) and $filter_class != "0") {
                            $Wh .= " AND prdcls = '{$filter_class}'";
                        }
                        if (isset($filter_cat) and $filter_cat != "0") {
                            $Wh .= " AND catid = '{$filter_cat}'";
                        }
                    }
                    if (isset($filter_store) and $filter_store != "0") {
                        $Wh .= " AND whid = '{$filter_store}'";
                    }
                    # get stock on this warehouse
                    db_connect();
                    $sql = "SELECT * FROM stock WHERE blocked = 'n' AND div = '" . USER_DIV . "' {$Wh} ORDER BY {$sel_frm} ASC";
                    $stkRslt = db_exec($sql) or errDie("Unable to retrieve stocks from database.");
                    if (pg_numrows($stkRslt) < 1) {
                        // May 3 2007 - Don't think this is needed any more
                        // as this now gets checked on each update.
                        // $error .= "<li class='err'>There are no stock items in the selected warehouse.";
                        continue;
                    }
                    if (pg_numrows($stkRslt) == 1) {
                        $ex = "selected";
                    } else {
                        $ex = "";
                    }
                    if ($sel_frm == "stkcod") {
                        $cods = "<select name='stkidss[{$ai}]' onChange='javascript:document.form.submit();'>";
                        $cods .= "<option value='-S' disabled selected>Select Number</option>";
                        $count = 0;
                        while ($stk = pg_fetch_array($stkRslt)) {
                            // Check if this stock item has been blocked
                            if (stock_is_blocked($stk["stkid"])) {
                                continue;
                            }
                            $units = sprint3($stk["units"] - $stk_alloc["alloc"]);
                            if ($units <= 0) {
                                continue;
                            }
                            $cods .= "<option value='{$stk['stkid']}'>{$stk['stkcod']} ({$units})</option>";
                        }
                        $cods .= "</select> ";
                        $descs = "";
                    } else {
                        $descs = "<select style='width:250px' name='stkidss[{$ai}]' onChange='javascript:document.form.submit();'>";
                        $descs .= "<option value='-S' disabled selected>Select Description</option>";
                        $count = 0;
                        while ($stk = pg_fetch_array($stkRslt)) {
                            // Check if this stock item has been blocked
                            if (stock_is_blocked($stk["stkid"])) {
                                continue;
                            }
                            $units = $stk['units'] - $stk['alloc'];
                            if ($units <= 0) {
                                continue;
                            }
                            $descs .= "<option value='{$stk['stkid']}'>{$stk['stkdes']} ({$units})</option>";
                        }
                        $descs .= "</select> ";
                        $cods = "";
                    }
                    db_conn('cubit');
                    $Sl = "SELECT * FROM vatcodes ORDER BY code";
                    $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                    $Vatcodes = "\n\t\t\t\t\t\t<select name='vatcodess[{$ai}]'>\n\t\t\t\t\t\t\t<option value='0'>Select</option>";
                    while ($vd = pg_fetch_array($Ri)) {
                        if ($vd['del'] == "Yes") {
                            $sel = "selected";
                        } else {
                            $sel = "";
                        }
                        $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
                    }
                    $Vatcodes .= "</select>";
                    # put in drop down and warehouse
                    $products .= "\n\t\t\t\t\t\t<input type='hidden' name='accountss[{$ai}]' value='0'>\n\t\t\t\t\t\t<input type='hidden' name='descriptionss[{$ai}]' value=''>\n\t\t\t\t\t\t<input type='hidden' name='whidss[{$ai}]' value='{$filter_store}'>\n\t\t\t\t\t\t<input type='hidden' name='vatcodess' value='0'>\n\t\t\t\t\t\t<input type='hidden' size='3' name='qtyss[{$ai}]' value='1'>\n\t\t\t\t\t\t<input type='hidden' name='amts[{$ai}]' value='0.00'>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t<td>{$cods}</td>\n\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t\t<td>{$descs}</td>\n\t\t\t\t\t\t\t<td>1</td>\n\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t\t<td><input type='text' size='4' name=discs[{$ai}] value='0'> OR <input type='text' size='4' name=discps[{$ai}] value='0' maxlength='5'>%</td>\n\t\t\t\t\t\t\t<td nowrap>" . CUR . " 0.00</td>\n\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t</tr>";
                    ++$ai;
                } else {
                    db_conn('core');
                    $Sl = "SELECT accid,topacc,accnum,accname FROM accounts WHERE acctype='I' ORDER BY accname";
                    $Ri = db_exec($Sl) or errDie("Unable to get accounts.");
                    $Accounts = "\n\t\t\t\t\t\t<select name='accountss[{$ai}]' onChange='javascript:document.form.submit();'>\n\t\t\t\t\t\t\t<option value='0'>Select Account</option>";
                    while ($ad = pg_fetch_array($Ri)) {
                        if (isb($ad['accid'])) {
                            continue;
                        }
                        $Accounts .= "<option value='{$ad['accid']}'>{$ad['accname']}</option>";
                    }
                    $Accounts .= "</select>";
                    db_conn('cubit');
                    $Sl = "SELECT * FROM vatcodes ORDER BY code";
                    $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                    $Vatcodes = "\n\t\t\t\t\t\t<select name='vatcodess[{$ai}]'>\n\t\t\t\t\t\t\t<option value='0'>Select</option>";
                    while ($vd = pg_fetch_array($Ri)) {
                        if ($vd['del'] == "Yes") {
                            $sel = "selected";
                        } else {
                            $sel = "";
                        }
                        $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
                    }
                    $Vatcodes .= "</select>";
                    $products .= "\n\t\t\t\t\t\t<input type='hidden' name='whidss[{$ai}]' value='1'>\n\t\t\t\t\t\t<inpu type='hidden' name='stkidss[{$ai}]' value=''>\n\t\t\t\t\t\t<input type='hidden' name='discs[{$ai}]' value='0'>\n\t\t\t\t\t\t<input type='hidden' name='discps[{$ai}]' value='0'>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td colspan='2'>{$Accounts}</td>\n\t\t\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t<td><input type='text' size='20' name='descriptionss[{$ai}]'></td>\n\t\t\t\t\t\t\t<td><input type='text' size='3' name='qtyss[{$ai}]' value='1'></td>\n\t\t\t\t\t\t\t<td><input type='text' name='unitcosts[{$ai}]' size='7'></td>\n\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t<td nowrap>" . CUR . " 0.00</td>\n\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t</tr>";
                    ++$ai;
                }
            }
        }
    } else {
        if (!isset($addnon)) {
            if (isset($filter_store) and $filter_store != "0") {
                # get selected warehouse name
                db_conn("exten");
                $sql = "SELECT whname FROM warehouses WHERE whid = '{$filter_store}' AND div = '" . USER_DIV . "'";
                $whRslt = db_exec($sql);
                $wh = pg_fetch_array($whRslt);
            }
            if (isset($ria) and $ria != "") {
                $len = strlen($ria);
                if ($ria == "Show All") {
                    $Wh = "";
                    $ria = "";
                } else {
                    $Wh = "AND (lower(substr(stkdes,1,'{$len}'))=lower('{$ria}') OR lower(substr(stkcod,1,'{$len}'))=lower('{$ria}'))";
                    $ria = "";
                }
            } else {
                $Wh = "AND FALSE";
                $ria = "";
            }
            $check_setting = getCSetting("OPTIONAL_STOCK_FILTERS");
            if (isset($check_setting) and $check_setting == "yes") {
                if (isset($filter_class) and $filter_class != "0") {
                    $Wh .= " AND prdcls = '{$filter_class}'";
                }
                if (isset($filter_cat) and $filter_cat != "0") {
                    $Wh .= " AND catid = '{$filter_cat}'";
                }
            }
            if (isset($filter_store) and $filter_store != "0") {
                $Wh .= " AND whid = '{$filter_store}'";
            }
            # get stock on this warehouse
            db_connect();
            $sql = "SELECT * FROM stock WHERE blocked = 'n' AND div = '" . USER_DIV . "' {$Wh} ORDER BY {$sel_frm} ASC";
            $stkRslt = db_exec($sql) or errDie("Unable to retrieve stocks from database.");
            if (pg_numrows($stkRslt) < 1) {
                if (!isset($err)) {
                    $err = "";
                }
                $err .= "<li>There are no stock items in the selected store.";
                //ontinue;
            }
            if ($sel_frm == "stkcod") {
                $cods = "<select name='stkidss[{$ai}]' onChange='javascript:document.form.submit();'>";
                $cods .= "<option value='-S' disabled selected>Select Number</option>";
                $count = 0;
                while ($stk = pg_fetch_array($stkRslt)) {
                    // Check if this stock item has been blocked
                    if (stock_is_blocked($stk["stkid"])) {
                        continue;
                    }
                    $units = sprint3($stk['units'] - $stk['alloc']);
                    if ($units <= 0) {
                        continue;
                    }
                    $cods .= "<option value='{$stk['stkid']}'>{$stk['stkcod']} ({$units})</option>";
                }
                $cods .= "</select> ";
                $descs = "";
            } else {
                $descs = "<select style='width:250px' name='stkidss[{$ai}]' onChange='javascript:document.form.submit();'>";
                $descs .= "<option value='-S' disabled selected>Select Description</option>";
                $count = 0;
                while ($stk = pg_fetch_array($stkRslt)) {
                    // Check if this stock item has been blocked
                    if (stock_is_blocked($stk["stkid"])) {
                        continue;
                    }
                    $units = $stk['units'] - $stk['alloc'];
                    if ($units <= 0) {
                        continue;
                    }
                    $descs .= "<option value='{$stk['stkid']}'>{$stk['stkdes']} ({$units})</option>";
                }
                $descs .= "</select> ";
                $cods = "";
            }
            $products .= "\n\t\t\t\t<input type='hidden' name='accountss[{$ai}]' value='0'>\n\t\t\t\t<input type='hidden' name='descriptionss[{$ai}]' value=''>\n\t\t\t\t<input type='hidden' name='vatcodess[{$ai}]' value=''>\n\t\t\t\t<input type='hidden' name='whidss[{$ai}]' value='{$filter_store}'>\n\t\t\t\t<input type='hidden' size='3' name='qtyss[{$ai}]' value='1'>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td></td>\n\t\t\t\t\t<td>{$cods}</td>\n\t\t\t\t\t<td> </td>\n\t\t\t\t\t<td></td>\n\t\t\t\t\t<td>{$descs}</td>\n\t\t\t\t\t<td>1</td>\n\t\t\t\t\t<td> </td>\n\t\t\t\t\t<td><input type='text' size='4' name=discs[{$ai}] value='0'> OR <input type='text' size='4' name=discps[{$ai}] value='0' maxlength='5'>%</td>\n\t\t\t\t\t<td nowrap>" . CUR . " 0.00</td>\n\t\t\t\t\t<td></td>\n\t\t\t\t</tr>";
            ++$ai;
        } elseif (isset($addnon)) {
            db_conn('core');
            $Sl = "SELECT accid,topacc,accnum,accname FROM accounts WHERE acctype='I' ORDER BY accname";
            $Ri = db_exec($Sl) or errDie("Unable to get accounts.");
            $Accounts = "\n\t\t\t\t<select name='accountss[{$ai}]'  onChange='javascript:document.form.submit();'>\n\t\t\t\t\t<option value='0'>Select Account</option>";
            while ($ad = pg_fetch_array($Ri)) {
                if (isb($ad['accid'])) {
                    continue;
                }
                $Accounts .= "<option value={$ad['accid']}>{$ad['accname']}</option>";
            }
            $Accounts .= "</select>";
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes ORDER BY code";
            $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
            $Vatcodes = "\n\t\t\t\t<select name='vatcodess[{$ai}]'>\n\t\t\t\t\t<option value='0'>Select</option>";
            while ($vd = pg_fetch_array($Ri)) {
                if ($vd['del'] == "Yes") {
                    $sel = "selected";
                } else {
                    $sel = "";
                }
                $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
            }
            $Vatcodes .= "</select>";
            $products .= "\n\t\t\t\t<input type='hidden' name=whidss[{$ai}] value='1'>\n\t\t\t\t<inpu type='hidden' name='stkidss[{$ai}]' value=''>\n\t\t\t\t<input type='hidden' name='discs[{$ai}]' value='0'>\n\t\t\t\t<input type='hidden' name='discps[{$ai}]' value='0' >\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='2'>{$Accounts}</td>\n\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t<td></td>\n\t\t\t\t\t<td><input type='text' size='20' name='descriptionss[{$ai}]'></td>\n\t\t\t\t\t<td><input type='text' size='3' name='qtyss[{$ai}]' value='1'></td>\n\t\t\t\t\t<td><input type='text' name='unitcosts[{$ai}]' size='7'></td>\n\t\t\t\t\t<td></td>\n\t\t\t\t\t<td nowrap>" . CUR . " 0.00</td>\n\t\t\t\t\t<td></td>\n\t\t\t\t</tr>";
            ++$ai;
        }
    }
    $products .= "</table>";
    /* --- End Products Display --- */
    /* --- Start Some calculations --- */
    # Calculate subtotal
    $SUBTOT = sprint($inv['subtot']);
    # Calculate tradediscm
    if ($inv['traddisc'] > 0) {
        $traddiscm = sprint($inv['traddisc'] / 100 * $inv['total']);
    } else {
        $traddiscm = "0.00";
    }
    $VATP = TAX_VAT;
    # Calculate subtotal
    $SUBTOT = sprint($inv['subtot']);
    $VAT = sprint($inv['vat']);
    $TOTAL = sprint($inv['total']);
    $inv['delchrg'] = sprint($inv['delchrg']);
    /* --- End Some calculations --- */
    /*--- Start checks --- */
    # check only if the customer is selected
    if (isset($cusnum) && $cusnum != "-S" && is_numeric($cusnum)) {
        db_connect();
        #check for any unpaid inv before term limit
        $check_date = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - $cust['credterm'], date("Y")));
        $get_check2 = "SELECT sum(amount) FROM stmnt WHERE cusnum = '{$cusnum}' AND date < '{$check_date}'";
        $run_check2 = db_exec($get_check2) or errDie("Unable to check credit term information.");
        if (pg_numrows($run_check2) < 1) {
            #no entries found ...
        } else {
            $sum_amount = sprint(pg_fetch_result($run_check2, 0, 0));
            if ($sum_amount > sprint(0)) {
                $error .= "<li class='err'>Warning : Customers Credit Term of <b>{$cust['credterm']} days</b> has been exceeded.";
                $get_check = "SELECT value FROM set WHERE label = 'CUST_INV_WARN' LIMIT 1";
                $run_check = db_exec($get_check) or errDie("Unable to get credit limit response setting");
                if (pg_numrows($run_check) < 1) {
                    #no setting ? do nothing ....
                } else {
                    $sarr = pg_fetch_array($run_check);
                    if ($sarr['value'] == "block") {
                        #block account ...
                        $done = "";
                    }
                }
            }
        }
        #check againg credit limit
        if ($TOTAL + $cust['balance'] > $cust['credlimit']) {
            $error .= "<li class='err'>Warning : Customers Credit limit of <b>" . CUR . " " . sprint($cust["credlimit"]) . "</b> has been exceeded.";
            #limit reached ... check for warn/block
            db_conn("cubit");
            $get_check = "SELECT value FROM set WHERE label = 'CUST_INV_WARN' LIMIT 1";
            $run_check = db_exec($get_check) or errDie("Unable to get credit limit response setting");
            if (pg_numrows($run_check) < 1) {
                #no setting ? do nothing ....
            } else {
                $sarr = pg_fetch_array($run_check);
                if ($sarr['value'] == "block") {
                    #block account ...
                    $done = "";
                }
            }
            # Check permissions
            if (!perm("invoice-limit-override.php")) {
                $done = "";
            }
        }
        $avcred = $cust['credlimit'] - $cust['balance'];
    } else {
        $avcred = "0.00";
    }
    /*--- Start checks --- */
    db_conn('cubit');
    $Sl = "SELECT * FROM settings WHERE constant='SALES'";
    $Ri = db_exec($Sl) or errDie("Unable to get settings.");
    $data = pg_fetch_array($Ri);
    if ($data['value'] == "Yes") {
        $sc = "checked";
    } else {
        $sc = "";
    }
    $sales = "\n\t\t<td>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<td>{$salesps}</td>\n\t\t\t\t\t<td>Print</td>\n\t\t\t\t\t<td><input type='checkbox' name='printsales' {$sc}></td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t</td>";
    $inv['delvat'] += 0;
    if ($inv['delvat'] == 0) {
        $Sl = "SELECT * FROM vatcodes WHERE del='Yes'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $vd = pg_fetch_array($Ri);
        $inv['delvat'] = $vd['id'];
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes ORDER BY code";
    $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
    $Vatcodes = "\n\t\t<select name='delvat'>\n\t\t\t<option value='0'>Select</option>";
    while ($vd = pg_fetch_array($Ri)) {
        if ($vd['id'] == $inv['delvat']) {
            $sel = "selected";
        } else {
            $sel = "";
        }
        $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
    }
    $Vatcodes .= "</select>";
    db_conn('cubit');
    $Sl = "SELECT * FROM settings WHERE constant='Delivery Note'";
    $Ri = db_exec($Sl) or errDie("Unable to get settings.");
    $data = pg_fetch_array($Ri);
    if ($data['value'] == "Yes") {
        $chp = "checked";
    } else {
        $chp = "";
    }
    if (empty($inv["comm"])) {
        db_conn("cubit");
        $sql = "SELECT value FROM settings WHERE constant='DEFAULT_COMMENTS'";
        $cmntRslt = db_exec($sql) or errDie("Unable to retrieve the default comment from Cubit.");
        $comm = base64_decode(pg_fetch_result($cmntRslt, 0));
    } else {
        $comm = $inv["comm"];
    }
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    // Which display method was selected
    if (isset($sel_frm) && $sel_frm == "stkdes") {
        $sel_frm_cod = "";
        $sel_frm_des = "checked";
    } else {
        $sel_frm_cod = "checked";
        $sel_frm_des = "";
    }
    // Delivery Date
    if (!empty($inv["deldate"])) {
        $deldate = explode("-", $inv["deldate"]);
    } else {
        $trans_date_setting = getCSetting("USE_TRANSACTION_DATE");
        if (isset($trans_date_setting) and $trans_date_setting == "yes") {
            $trans_date_value = getCSetting("TRANSACTION_DATE");
            $date_arr = explode("-", $trans_date_value);
            $deldate[0] = $date_arr[0];
            $deldate[1] = $date_arr[1];
            $deldate[2] = $date_arr[2];
        } else {
            $deldate[0] = date("Y");
            $deldate[1] = date("m");
            $deldate[2] = date("d");
        }
    }
    // Retrieve VAT Setting
    $sql = "SELECT value FROM cubit.settings WHERE constant='VAT_INC'";
    $vatinc_rslt = db_exec($sql) or errDie("Unable to retrieve vat setting.");
    $vatinc = pg_fetch_result($vatinc_rslt, 0);
    if ($vatinc != "yes" && $vatinc != "no") {
        $vatinc = "no";
    }
    if ($vatinc == 'yes') {
        $chrgvat = "inc";
    } else {
        $chrgvat = "exc";
    }
    /* -- Final Layout --  onkeyup='javasript:predict()'   Exempt From Vat<input type=radio size=7 name=chrgvat value='nov' $chno>       */
    $details_begin = "\n\t\t<center>\n\t\t<h3>New Invoice</h3>\n\t\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t\t<input type='hidden' name='SCROLL' value='yes'>\n\t\t\t<input type='hidden' name='key' value='update'>\n\t\t\t<input type='hidden' name='invid' value='{$invid}'>\n\t\t\t<input type='hidden' name='stkerr' value='{$stkerr}'>\n\t\t\t<input type='hidden' name='chrgvat' value='{$chrgvat}' />\n\t\t<table " . TMPL_tblDflts . " width='95%'>\n\t\t \t<tr>\n\t\t \t\t<td valign='top' width='50%'>\n\t\t \t\t\t<div id='cust_selection'>";
    if (empty($ajax_err) && (isset($cusnum) || AJAX)) {
        if (isset($cusnum)) {
            $OTS_OPT = onthespot_encode(SELF, "cust_selection", "deptid={$inv['deptid']}&letters={$letters}&cusnum={$cusnum}&invid={$invid}");
            //	<a href='javascript: popupSized(\"cust-edit.php?cusnum=$cusnum&onthespot=$OTS_OPT\", \"edit_cust\", 700, 630);'>
            $custedit = "<td nowrap><a href='javascript: popupSized(\"customers-new.php?cusnum={$cusnum}&onthespot={$OTS_OPT}\", \"edit_cust\", 700, 630);'>Edit Customer Details</a></td>";
        } else {
            $custedit = "";
        }
        $optional_filter_setting = getCSetting("OPTIONAL_STOCK_FILTERS");
        if (isset($optional_filter_setting) and $optional_filter_setting == "yes") {
            db_connect();
            $catsql = "SELECT catid, cat, catcod FROM stockcat WHERE div = '" . USER_DIV . "' ORDER BY cat ASC";
            $catRslt = db_exec($catsql);
            if (pg_numrows($catRslt) < 1) {
                $cat_drop = "<input type='hidden' name='filter_cat' value='0'>";
            } else {
                $cat_drop = "<select name='filter_cat'>";
                $cat_drop .= "<option value='0'>All Categories</option>";
                while ($cat = pg_fetch_array($catRslt)) {
                    if (isset($filter_cat) and $filter_cat == $cat['catid']) {
                        $cat_drop .= "<option value='{$cat['catid']}' selected>({$cat['catcod']}) {$cat['cat']}</option>";
                    } else {
                        $cat_drop .= "<option value='{$cat['catid']}'>({$cat['catcod']}) {$cat['cat']}</option>";
                    }
                }
                $cat_drop .= "</select>";
            }
            # Select classification
            $classsql = "SELECT * FROM stockclass WHERE div = '" . USER_DIV . "' ORDER BY classname ASC";
            $clasRslt = db_exec($classsql);
            if (pg_numrows($clasRslt) < 1) {
                $class_drop = "<input type='hidden' name='filter_class' value='0'>";
            } else {
                $class_drop = "<select name='filter_class' style='width: 167'>";
                $class_drop .= "<option value='0'>All Classifications</option>";
                while ($clas = pg_fetch_array($clasRslt)) {
                    if (isset($filter_class) and $filter_class == $clas['clasid']) {
                        $class_drop .= "<option value='{$clas['clasid']}' selected>{$clas['classname']}</option>";
                    } else {
                        $class_drop .= "<option value='{$clas['clasid']}'>{$clas['classname']}</option>";
                    }
                }
                $class_drop .= "</select>";
            }
            $display_optional_filters = "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Select Category</td>\n\t\t\t\t\t<td>{$cat_drop}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Select Classification</td>\n\t\t\t\t\t<td>{$class_drop}</td>\n\t\t\t\t</tr>";
        }
        db_conn("exten");
        $sql = "SELECT whid, whname, whno FROM warehouses WHERE div = '" . USER_DIV . "' ORDER BY whname ASC";
        $whRslt = db_exec($sql);
        if (pg_numrows($whRslt) < 1) {
            $store_drop = "<input type='hidden' name='filter_store' value='0'>";
        } else {
            if (!isset($filter_store)) {
                # check if setting exists
                db_connect();
                $sql = "SELECT value FROM set WHERE label = 'DEF_WH' AND div = '" . USER_DIV . "'";
                $Rslt = db_exec($sql) or errDie("Unable to check database for existing settings.");
                if (pg_numrows($Rslt) > 0) {
                    $set = pg_fetch_array($Rslt);
                    $filter_store = $set['value'];
                }
            }
            $store_drop = "<select name='filter_store'>";
            $store_drop .= "<option value='0'>All Stores</option>";
            while ($wh = pg_fetch_array($whRslt)) {
                if (isset($filter_store) and $filter_store == $wh['whid']) {
                    $store_drop .= "<option value='{$wh['whid']}' selected>({$wh['whno']}) {$wh['whname']}</option>";
                } else {
                    $store_drop .= "<option value='{$wh['whid']}'>({$wh['whno']}) {$wh['whname']}</option>";
                }
            }
            $store_drop .= "</select>";
        }
        $ajaxOut = "\n\t\t\t<input type='hidden' name='letters' value='{$letters}'>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th colspan='2'> Customer Details </th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Department</td>\n\t\t\t\t\t<td valign='center'>{$dept['deptname']}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Account No.</td>\n\t\t\t\t\t<td valign='center'>{$cust['accno']}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Customer</td>\n\t\t\t\t\t<td valign='center'>{$customers}</td>\n\t\t\t\t\t{$custedit}\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td valign='top'>Customer Branch</td>\n\t\t\t\t\t<td valign='center'>{$branchdrop}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td valign='top'>Customer Address</td>\n\t\t\t\t\t<td valign='center'>" . nl2br($cust['addr1']) . "</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td valign='top'>Current Delivery Address</td>\n\t\t\t\t\t<td valign='center'>" . nl2br($cust_del_addr) . "</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td valign='top'>Delivery Address</td>\n\t\t\t\t\t<td valign='center'>\n\t\t\t\t\t\t<input type='button' onClick=\"\n\t\t\t\t\t\t\tvar windowReference;\n\n\t\t\t\t\t\t\tfunction openPopup() {\n\t\t\t\t\t\t\t\twindowReference = window.open('cust-credit-stockinv-deladdr.php?invid={$invid}','windowName','width=500,height=400,status=1');\n\t\t\t\t\t\t\t\tif (!windowReference.opener)\n\t\t\t\t\t\t\t\t\twindowReference.opener = self;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\topenPopup();\" value='Change Delivery Address'>\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Customer Order number</td>\n\t\t\t\t\t<td valign='center'><input type='text' size='10' name='cordno' value='{$inv['cordno']}'></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Customer VAT Number</td>\n\t\t\t\t\t<td>{$cust['vatnum']}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<th colspan='2'>Point of Sale</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Barcode</td>\n\t\t\t\t\t<td><input type='text' size='13' name='bar' value=''></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Print Delivery Note</td>\n\t\t\t\t\t<td><input type='checkbox' name='printdel' {$chp}></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Select Using</td>\n\t\t\t\t\t<td>Stock Code<input type='radio' name='sel_frm' value='stkcod' onChange='javascript:document.form.submit();' {$sel_frm_cod}><br>Stock Description<input type='radio' name='sel_frm' value='stkdes' onChange='javascript:document.form.submit();' {$sel_frm_des}></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<th colspan='2'>Additional Filters</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Select Store</td>\n\t\t\t\t\t<td>{$store_drop}</td>\n\t\t\t\t</tr>\n\t\t\t\t{$display_optional_filters}\n\t\t\t\t<tr class='" . bg_class() . "' " . ass("Type the first letters of the stock code you are looking for.") . ">\n\t\t\t\t\t<td>Stock Filter</td>\n\t\t\t\t\t<td nowrap><input type='text' size='13' name='ria' value='{$ria}'> <input type='submit' value='Search'> <input type='submit' name='ria' value='Show All'></td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    } else {
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE div = '" . USER_DIV . "' ORDER BY deptname ASC";
        $deptRslt = db_exec($sql) or errDie("Unable to view customers");
        if (pg_numrows($deptRslt) < 1) {
            return "<li class='err'>There are no Departments found in Cubit.</li>";
        } else {
            $depts = "<select name='deptid' id='deptid'>";
            $depts .= "<option value='0'>All Departments</option>";
            while ($dept = pg_fetch_array($deptRslt)) {
                $depts .= "<option value='{$dept['deptid']}'>{$dept['deptname']}</option>";
            }
            $depts .= "</select>";
        }
        if (!isset($ajax_err)) {
            $ajax_err = "";
        }
        $ajaxOut = "\n\t\t\t<script>\n\t\t\tfunction updateCustSelection() {\n\t\t\t\tdeptid = getObject('deptid').value;\n\t\t\t\tletters = getObject('letters').value;\n\t\t\t\tctyp = getObject('ctypintl').checked;\n\n\t\t\t\tif (ctyp) {\n\t\t\t\t\tdocument.location.href='intinvoice-new.php?' + 'letters=' + letters + '&deptid=' + deptid + '&ctyp=' + ctyp + '&invid={$invid}';\n\t\t\t\t} else {\n\t\t\t\t\tajaxRequest('" . SELF . "', 'cust_selection', AJAX_SET, 'letters='+letters+'&deptid='+deptid+'&ctyp='+ctyp+'&invid={$invid}');\n\t\t\t\t}\n\t\t\t}\n\t\t\t</script>\n\t\t\t{$ajax_err}\n\t\t\t<form name='cusselfrm'>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th colspan='2'>Customer Selection</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Select Department</td>\n\t\t\t\t\t<td valign='center'>{$depts}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='bg-even'>\n\t\t\t\t\t<td>First Letters of customer</td>\n\t\t\t\t\t<td valign='center'><input type='text' size='5' id='letters' maxlength='5'></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Customer is International</td>\n\t\t\t\t\t<td valign='center'><input type='checkbox' id='ctypintl'></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td><br /></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td></td>\n\t\t\t\t\t<td valign='center'><input type='button' value='Update &raquo' onClick='updateCustSelection();'></td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t</form>";
    }
    $avcred = sprint($avcred);
    if (isset($addprodBtn) or isset($addnon) or isset($saveBtn) or isset($upBtn) or isset($ria)) {
        $jump_bot = "\n\t\t\t<script>\n\t\t\t\twindow.location.hash='bottom';\n\t\t\t</script>";
    } else {
        $jump_bot = "";
    }
    $details_end = "\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</td>\n\t\t\t\t\t<td valign='top' align='right' width='50%'>\n\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<th colspan='2'> Invoice Details </th>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Invoice No.</td>\n\t\t\t\t\t\t\t\t<td valign='center'>TI {$inv['invid']}</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Proforma Inv No.</td>\n\t\t\t\t\t\t\t\t<td valign='center'><input type='text' size='5' name='docref' value='{$inv['docref']}'></td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Sales Order No.</td>\n\t\t\t\t\t\t\t\t<td valign='center'><input type='text' size='5' name='ordno' value='{$inv['ordno']}'></td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Terms</td>\n\t\t\t\t\t\t\t\t<td valign='center'>{$termssel} Days</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Sales Person</td>\n\t\t\t\t\t\t\t\t{$sales}\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Invoice Date</td>\n\t\t\t\t\t\t\t\t<td valign='center'>" . mkDateSelect("inv_date", $inv_date_year, $inv_date_month, $inv_date_day) . "</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>VAT Inclusive</td>\n\t\t\t\t\t\t\t\t<td>Yes <input type='radio' size='7' name='chrgvat' value='inc' {$chin}> No<input type='radio' size='7' name='chrgvat' value='exc' {$chex}></td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Available Credit</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$avcred}</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Trade Discount</td>\n\t\t\t\t\t\t\t\t<td valign='center'><input type='text' size='5' name='traddisc' value='{$inv['traddisc']}'>%</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Delivery Charge</td>\n\t\t\t\t\t\t\t\t<td valign='center'><input type='text' size='7' name='delchrg' value='{$inv['delchrg']}'>{$Vatcodes}</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Delivery Date</td>\n\t\t\t\t\t\t\t\t<td valign='center'>" . mkDateSelect("del_date", $deldate[0], $deldate[1], $deldate[2]) . "</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='2'>{$products}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td>\n\t\t\t\t\t\t<p>\n\t\t\t\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<th width='25%'>Quick Links</th>\n\t\t\t\t\t\t\t\t<th width='25%'>Comments</th>\n\t\t\t\t\t\t\t\t<td rowspan='5' valign='top' width='50%'>{$error}</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<td class='" . bg_class() . "'><a href='customers-new.php?re={$inv['invid']}'>New Customer</a></td>\n\t\t\t\t\t\t\t\t<td class='" . bg_class() . "' rowspan='5' align='center' valign='top'><textarea name='comm' rows='4' cols='20'>{$comm}</textarea></td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<td class='" . bg_class() . "'><a href='cust-credit-stockinv-no-neg.php'>New Invoice</a></td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td><a href='invoice-view.php'>View Invoices</a></td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t</td>\n\t\t\t\t\t<td align='right' valign='top'>\n\t\t\t\t\t\t<table " . TMPL_tblDflts . " width='50%'>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>SUBTOTAL</td>\n\t\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " <input type='hidden' name='SUBTOT' value='{$SUBTOT}'>{$SUBTOT}</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Trade Discount</td>\n\t\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$inv['discount']}</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Delivery Charge</td>\n\t\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$inv['delivery']}</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td><b>VAT {$vat14}</b></td>\n\t\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$VAT}</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<th>GRAND TOTAL</th>\n\t\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$TOTAL}</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td align='right'><input name='addprodBtn' type='submit' value='Add Product'>| <input name='addnon' type='submit' value='Add Non stock Product'> | <input type='submit' name='saveBtn' value='Save'> </td>\n\t\t\t\t\t<td>| <input type='submit' name='upBtn' value='Update'>{$done}</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t<a name='bottom'>\n\t\t\t</form>\n\t\t\t</center>\n\t\t\t{$jump_bot}";
    if (AJAX) {
        return $ajaxOut;
    } else {
        return "{$details_begin}{$ajaxOut}{$details_end}";
    }
}