text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package erp.mtrn.form;

import erp.data.SDataConstants;
import erp.data.SDataConstantsSys;
import erp.data.SDataUtilities;
import erp.gui.session.SSessionCustom;
import erp.lib.SLibConstants;
import erp.lib.SLibTimeUtilities;
import erp.lib.SLibUtilities;
import erp.lib.form.SFormUtilities;
import erp.lib.form.SFormValidation;
import erp.lib.table.STableColumnForm;
import erp.lib.table.STableConstants;
import erp.lib.table.STablePane;
import erp.lib.table.STableRow;
import erp.mbps.data.SDataBizPartnerBranch;
import erp.mcfg.data.SDataCompanyBranchEntity;
import erp.mtrn.data.SDataDiog;
import erp.mtrn.data.SDataDiogEntry;
import erp.mtrn.data.SDataDps;
import erp.mtrn.data.STrnDpsStockSupplyRow;
import erp.mtrn.data.STrnStock;
import erp.mtrn.data.STrnStockMove;
import erp.mtrn.data.STrnStockSegregationUtils;
import erp.mtrn.data.STrnUtilities;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.sql.ResultSet;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import sa.lib.SLibUtils;

/**
 *
 * @author Sergio Flores, Uriel Castañeda, Edwin Carmona
 * 2017-03-08 (sflores): Fix to form validation when previous supplies exceeds base quantity.
 *  Addition of column surplus percentage into supply rows grid.
 */
public class SDialogDpsStockSupply extends javax.swing.JDialog implements ActionListener, ListSelectionListener {

    private static final int COL_QTY = 5;

    private int mnFormResult;
    private int mnFormStatus;
    private boolean mbFirstTime;
    private erp.client.SClientInterface miClient;
    private erp.lib.table.STablePane moPaneDpsEntries;
    private erp.mtrn.form.SPanelDps moPanelDps;
    private erp.mtrn.form.SDialogPickerStockLots moPickerStockLots;

    private int mnYear;
    private int[] manWarehouseKey;
    private erp.mbps.data.SDataBizPartnerBranch moParamCompanyBranch;
    private erp.mcfg.data.SDataCompanyBranchEntity moParamWarehouse;
    private erp.mtrn.data.SDataDps moParamDps;
    private erp.mtrn.data.SDataDiog moParamDiog;

    /** Creates new form SDialogDpsStockSupply */
    public SDialogDpsStockSupply(erp.client.SClientInterface client) {
        super(client.getFrame(), true);

        miClient = client;

        initComponents();
        initComponentsExtra();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jlPanelDps = new javax.swing.JLabel();
        jpDpsEntries = new javax.swing.JPanel();
        jpDpsEntriesControls = new javax.swing.JPanel();
        jpDpsEntriesControls1 = new javax.swing.JPanel();
        jlWarehouse = new javax.swing.JLabel();
        jtfCompanyBranch = new javax.swing.JTextField();
        jtfCompanyBranchCode = new javax.swing.JTextField();
        jtfWarehouse = new javax.swing.JTextField();
        jtfWarehouseCode = new javax.swing.JTextField();
        jpDpsEntriesControls2 = new javax.swing.JPanel();
        jbSupplyAll = new javax.swing.JButton();
        jbCleanAll = new javax.swing.JButton();
        jpDpsEntriesInfo = new javax.swing.JPanel();
        jpDpsEntriesInfo1 = new javax.swing.JPanel();
        jpDpsEntriesInfo11 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        jlQuantity = new javax.swing.JLabel();
        jtfQuantity = new javax.swing.JTextField();
        jtfQuantityUnit = new javax.swing.JTextField();
        jPanel5 = new javax.swing.JPanel();
        jlQuantityAdjusted = new javax.swing.JLabel();
        jtfQuantityAdjusted = new javax.swing.JTextField();
        jtfQuantityAdjustedUnit = new javax.swing.JTextField();
        jPanel6 = new javax.swing.JPanel();
        jlQuantityNet = new javax.swing.JLabel();
        jtfQuantityNet = new javax.swing.JTextField();
        jtfQuantityNetUnit = new javax.swing.JTextField();
        jPanel10 = new javax.swing.JPanel();
        label = new javax.swing.JLabel();
        jpDpsEntriesInfo12 = new javax.swing.JPanel();
        jPanel7 = new javax.swing.JPanel();
        jlQuantityNetAux = new javax.swing.JLabel();
        jtfQuantityNetAux = new javax.swing.JTextField();
        jtfQuantityNetAuxUnit = new javax.swing.JTextField();
        jPanel8 = new javax.swing.JPanel();
        jlQuantitySupplied = new javax.swing.JLabel();
        jtfQuantitySupplied = new javax.swing.JTextField();
        jtfQuantitySuppliedUnit = new javax.swing.JTextField();
        jPanel9 = new javax.swing.JPanel();
        jlQuantityPend = new javax.swing.JLabel();
        jtfQuantityPend = new javax.swing.JTextField();
        jtfQuantityPendUnit = new javax.swing.JTextField();
        jPanel11 = new javax.swing.JPanel();
        label1 = new javax.swing.JLabel();
        jpDpsEntriesInfo2 = new javax.swing.JPanel();
        jpDpsEntriesInfo21 = new javax.swing.JPanel();
        jlStock = new javax.swing.JLabel();
        jtfStock = new javax.swing.JTextField();
        jtfStockUnit = new javax.swing.JTextField();
        jbViewLots = new javax.swing.JButton();
        jpDiogEntriesInfo24 = new javax.swing.JPanel();
        jlSegregated = new javax.swing.JLabel();
        jtfSegregated = new javax.swing.JTextField();
        jtfSegregatedUnit = new javax.swing.JTextField();
        jpDpsEntriesInfo22 = new javax.swing.JPanel();
        jlCurrentlyUsed = new javax.swing.JLabel();
        jtfCurrentlyUsed = new javax.swing.JTextField();
        jtfCurrentlyUsedUnit = new javax.swing.JTextField();
        jpDpsEntriesInfo23 = new javax.swing.JPanel();
        jlAvailable = new javax.swing.JLabel();
        jtfAvailable = new javax.swing.JTextField();
        jtfAvailableUnit = new javax.swing.JTextField();
        jlYear = new javax.swing.JLabel();
        jtfYear = new javax.swing.JTextField();
        jpControls = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jbOk = new javax.swing.JButton();
        jbCancel = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Surtido de documento");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
        });

        jlPanelDps.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jlPanelDps.setText("[Panel de documento de compras-ventas]");
        jlPanelDps.setPreferredSize(new java.awt.Dimension(100, 200));
        getContentPane().add(jlPanelDps, java.awt.BorderLayout.NORTH);

        jpDpsEntries.setBorder(javax.swing.BorderFactory.createTitledBorder("Partidas pendientes del documento:"));
        jpDpsEntries.setLayout(new java.awt.BorderLayout(0, 5));

        jpDpsEntriesControls.setLayout(new java.awt.BorderLayout());

        jpDpsEntriesControls1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT, 5, 0));

        jlWarehouse.setText("Almacén:");
        jlWarehouse.setPreferredSize(new java.awt.Dimension(65, 23));
        jpDpsEntriesControls1.add(jlWarehouse);

        jtfCompanyBranch.setBackground(java.awt.Color.lightGray);
        jtfCompanyBranch.setEditable(false);
        jtfCompanyBranch.setText("TEXT");
        jtfCompanyBranch.setFocusable(false);
        jtfCompanyBranch.setPreferredSize(new java.awt.Dimension(100, 23));
        jpDpsEntriesControls1.add(jtfCompanyBranch);

        jtfCompanyBranchCode.setBackground(java.awt.Color.lightGray);
        jtfCompanyBranchCode.setEditable(false);
        jtfCompanyBranchCode.setText("CODE");
        jtfCompanyBranchCode.setFocusable(false);
        jtfCompanyBranchCode.setPreferredSize(new java.awt.Dimension(55, 23));
        jpDpsEntriesControls1.add(jtfCompanyBranchCode);

        jtfWarehouse.setBackground(java.awt.Color.lightGray);
        jtfWarehouse.setEditable(false);
        jtfWarehouse.setText("TEXT");
        jtfWarehouse.setFocusable(false);
        jtfWarehouse.setPreferredSize(new java.awt.Dimension(155, 23));
        jpDpsEntriesControls1.add(jtfWarehouse);

        jtfWarehouseCode.setBackground(java.awt.Color.lightGray);
        jtfWarehouseCode.setEditable(false);
        jtfWarehouseCode.setText("CODE");
        jtfWarehouseCode.setFocusable(false);
        jtfWarehouseCode.setPreferredSize(new java.awt.Dimension(55, 23));
        jpDpsEntriesControls1.add(jtfWarehouseCode);

        jpDpsEntriesControls.add(jpDpsEntriesControls1, java.awt.BorderLayout.WEST);

        jpDpsEntriesControls2.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT, 5, 0));

        jbSupplyAll.setText("Surtir todo");
        jbSupplyAll.setMargin(new java.awt.Insets(2, 0, 2, 0));
        jbSupplyAll.setPreferredSize(new java.awt.Dimension(100, 23));
        jpDpsEntriesControls2.add(jbSupplyAll);

        jbCleanAll.setText("Limpiar todo");
        jbCleanAll.setMargin(new java.awt.Insets(2, 0, 2, 0));
        jbCleanAll.setPreferredSize(new java.awt.Dimension(100, 23));
        jpDpsEntriesControls2.add(jbCleanAll);

        jpDpsEntriesControls.add(jpDpsEntriesControls2, java.awt.BorderLayout.CENTER);

        jpDpsEntries.add(jpDpsEntriesControls, java.awt.BorderLayout.NORTH);

        jpDpsEntriesInfo.setLayout(new java.awt.BorderLayout());

        jpDpsEntriesInfo1.setLayout(new java.awt.GridLayout(1, 2));

        jpDpsEntriesInfo11.setLayout(new java.awt.GridLayout(4, 1, 0, 5));

        jPanel4.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));

        jlQuantity.setText("+ Cant. original:");
        jlQuantity.setPreferredSize(new java.awt.Dimension(100, 23));
        jPanel4.add(jlQuantity);

        jtfQuantity.setEditable(false);
        jtfQuantity.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
        jtfQuantity.setText("0.00");
        jtfQuantity.setFocusable(false);
        jtfQuantity.setPreferredSize(new java.awt.Dimension(120, 23));
        jPanel4.add(jtfQuantity);

        jtfQuantityUnit.setEditable(false);
        jtfQuantityUnit.setText("UNIT");
        jtfQuantityUnit.setFocusable(false);
        jtfQuantityUnit.setPreferredSize(new java.awt.Dimension(40, 23));
        jPanel4.add(jtfQuantityUnit);

        jpDpsEntriesInfo11.add(jPanel4);

        jPanel5.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));

        jlQuantityAdjusted.setText("– Cant. ajustada:");
        jlQuantityAdjusted.setPreferredSize(new java.awt.Dimension(100, 23));
        jPanel5.add(jlQuantityAdjusted);

        jtfQuantityAdjusted.setEditable(false);
        jtfQuantityAdjusted.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
        jtfQuantityAdjusted.setText("0.00");
        jtfQuantityAdjusted.setFocusable(false);
        jtfQuantityAdjusted.setPreferredSize(new java.awt.Dimension(120, 23));
        jPanel5.add(jtfQuantityAdjusted);

        jtfQuantityAdjustedUnit.setEditable(false);
        jtfQuantityAdjustedUnit.setText("UNIT");
        jtfQuantityAdjustedUnit.setFocusable(false);
        jtfQuantityAdjustedUnit.setPreferredSize(new java.awt.Dimension(40, 23));
        jPanel5.add(jtfQuantityAdjustedUnit);

        jpDpsEntriesInfo11.add(jPanel5);

        jPanel6.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));

        jlQuantityNet.setText("= Cantidad neta:");
        jlQuantityNet.setPreferredSize(new java.awt.Dimension(100, 23));
        jPanel6.add(jlQuantityNet);

        jtfQuantityNet.setBackground(java.awt.Color.pink);
        jtfQuantityNet.setEditable(false);
        jtfQuantityNet.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
        jtfQuantityNet.setText("0.00");
        jtfQuantityNet.setFocusable(false);
        jtfQuantityNet.setPreferredSize(new java.awt.Dimension(120, 23));
        jPanel6.add(jtfQuantityNet);

        jtfQuantityNetUnit.setBackground(java.awt.Color.pink);
        jtfQuantityNetUnit.setEditable(false);
        jtfQuantityNetUnit.setText("UNIT");
        jtfQuantityNetUnit.setFocusable(false);
        jtfQuantityNetUnit.setPreferredSize(new java.awt.Dimension(40, 23));
        jPanel6.add(jtfQuantityNetUnit);

        jpDpsEntriesInfo11.add(jPanel6);

        jPanel10.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));

        label.setPreferredSize(new java.awt.Dimension(100, 23));
        jPanel10.add(label);

        jpDpsEntriesInfo11.add(jPanel10);

        jpDpsEntriesInfo1.add(jpDpsEntriesInfo11);

        jpDpsEntriesInfo12.setLayout(new java.awt.GridLayout(4, 1, 0, 5));

        jPanel7.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));

        jlQuantityNetAux.setText("+ Cant. neta:");
        jlQuantityNetAux.setPreferredSize(new java.awt.Dimension(100, 23));
        jPanel7.add(jlQuantityNetAux);

        jtfQuantityNetAux.setEditable(false);
        jtfQuantityNetAux.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
        jtfQuantityNetAux.setText("0.00");
        jtfQuantityNetAux.setFocusable(false);
        jtfQuantityNetAux.setPreferredSize(new java.awt.Dimension(120, 23));
        jPanel7.add(jtfQuantityNetAux);

        jtfQuantityNetAuxUnit.setEditable(false);
        jtfQuantityNetAuxUnit.setText("UNIT");
        jtfQuantityNetAuxUnit.setFocusable(false);
        jtfQuantityNetAuxUnit.setPreferredSize(new java.awt.Dimension(40, 23));
        jPanel7.add(jtfQuantityNetAuxUnit);

        jpDpsEntriesInfo12.add(jPanel7);

        jPanel8.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));

        jlQuantitySupplied.setText("– Cant. surtida:");
        jlQuantitySupplied.setPreferredSize(new java.awt.Dimension(100, 23));
        jPanel8.add(jlQuantitySupplied);

        jtfQuantitySupplied.setEditable(false);
        jtfQuantitySupplied.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
        jtfQuantitySupplied.setText("0.00");
        jtfQuantitySupplied.setFocusable(false);
        jtfQuantitySupplied.setPreferredSize(new java.awt.Dimension(120, 23));
        jPanel8.add(jtfQuantitySupplied);

        jtfQuantitySuppliedUnit.setEditable(false);
        jtfQuantitySuppliedUnit.setText("UNIT");
        jtfQuantitySuppliedUnit.setFocusable(false);
        jtfQuantitySuppliedUnit.setPreferredSize(new java.awt.Dimension(40, 23));
        jPanel8.add(jtfQuantitySuppliedUnit);

        jpDpsEntriesInfo12.add(jPanel8);

        jPanel9.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));

        jlQuantityPend.setText("= Cant. pendiente:");
        jlQuantityPend.setPreferredSize(new java.awt.Dimension(100, 23));
        jPanel9.add(jlQuantityPend);

        jtfQuantityPend.setEditable(false);
        jtfQuantityPend.setBackground(java.awt.Color.pink);
        jtfQuantityPend.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
        jtfQuantityPend.setText("0.00");
        jtfQuantityPend.setFocusable(false);
        jtfQuantityPend.setPreferredSize(new java.awt.Dimension(120, 23));
        jPanel9.add(jtfQuantityPend);

        jtfQuantityPendUnit.setEditable(false);
        jtfQuantityPendUnit.setBackground(java.awt.Color.pink);
        jtfQuantityPendUnit.setText("UNIT");
        jtfQuantityPendUnit.setFocusable(false);
        jtfQuantityPendUnit.setPreferredSize(new java.awt.Dimension(40, 23));
        jPanel9.add(jtfQuantityPendUnit);

        jpDpsEntriesInfo12.add(jPanel9);

        jPanel11.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));

        label1.setPreferredSize(new java.awt.Dimension(100, 23));
        jPanel11.add(label1);

        jpDpsEntriesInfo12.add(jPanel11);

        jpDpsEntriesInfo1.add(jpDpsEntriesInfo12);

        jpDpsEntriesInfo.add(jpDpsEntriesInfo1, java.awt.BorderLayout.WEST);

        jpDpsEntriesInfo2.setLayout(new java.awt.GridLayout(4, 1, 0, 5));

        jpDpsEntriesInfo21.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));

        jlStock.setText("+ Existencias:");
        jlStock.setPreferredSize(new java.awt.Dimension(75, 23));
        jpDpsEntriesInfo21.add(jlStock);

        jtfStock.setEditable(false);
        jtfStock.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
        jtfStock.setText("0.00");
        jtfStock.setFocusable(false);
        jtfStock.setPreferredSize(new java.awt.Dimension(120, 23));
        jpDpsEntriesInfo21.add(jtfStock);

        jtfStockUnit.setEditable(false);
        jtfStockUnit.setText("UNIT");
        jtfStockUnit.setFocusable(false);
        jtfStockUnit.setPreferredSize(new java.awt.Dimension(40, 23));
        jpDpsEntriesInfo21.add(jtfStockUnit);

        jbViewLots.setText("Ver lotes");
        jbViewLots.setMargin(new java.awt.Insets(2, 0, 2, 0));
        jbViewLots.setPreferredSize(new java.awt.Dimension(75, 23));
        jpDpsEntriesInfo21.add(jbViewLots);

        jpDpsEntriesInfo2.add(jpDpsEntriesInfo21);

        jpDiogEntriesInfo24.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));

        jlSegregated.setText("– Segregadas:");
        jlSegregated.setPreferredSize(new java.awt.Dimension(75, 23));
        jpDiogEntriesInfo24.add(jlSegregated);

        jtfSegregated.setEditable(false);
        jtfSegregated.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
        jtfSegregated.setText("0.00");
        jtfSegregated.setFocusable(false);
        jtfSegregated.setPreferredSize(new java.awt.Dimension(120, 23));
        jpDiogEntriesInfo24.add(jtfSegregated);

        jtfSegregatedUnit.setEditable(false);
        jtfSegregatedUnit.setText("UNIT");
        jtfSegregatedUnit.setFocusable(false);
        jtfSegregatedUnit.setPreferredSize(new java.awt.Dimension(40, 23));
        jpDiogEntriesInfo24.add(jtfSegregatedUnit);

        jpDpsEntriesInfo2.add(jpDiogEntriesInfo24);

        jpDpsEntriesInfo22.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));

        jlCurrentlyUsed.setText("– Uso actual:");
        jlCurrentlyUsed.setPreferredSize(new java.awt.Dimension(75, 23));
        jpDpsEntriesInfo22.add(jlCurrentlyUsed);

        jtfCurrentlyUsed.setEditable(false);
        jtfCurrentlyUsed.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
        jtfCurrentlyUsed.setText("0.00");
        jtfCurrentlyUsed.setFocusable(false);
        jtfCurrentlyUsed.setPreferredSize(new java.awt.Dimension(120, 23));
        jpDpsEntriesInfo22.add(jtfCurrentlyUsed);

        jtfCurrentlyUsedUnit.setEditable(false);
        jtfCurrentlyUsedUnit.setText("UNIT");
        jtfCurrentlyUsedUnit.setFocusable(false);
        jtfCurrentlyUsedUnit.setPreferredSize(new java.awt.Dimension(40, 23));
        jpDpsEntriesInfo22.add(jtfCurrentlyUsedUnit);

        jpDpsEntriesInfo2.add(jpDpsEntriesInfo22);

        jpDpsEntriesInfo23.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));

        jlAvailable.setText("= Disponible:");
        jlAvailable.setPreferredSize(new java.awt.Dimension(75, 23));
        jpDpsEntriesInfo23.add(jlAvailable);

        jtfAvailable.setEditable(false);
        jtfAvailable.setBackground(new java.awt.Color(153, 204, 255));
        jtfAvailable.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
        jtfAvailable.setText("0.00");
        jtfAvailable.setFocusable(false);
        jtfAvailable.setPreferredSize(new java.awt.Dimension(120, 23));
        jpDpsEntriesInfo23.add(jtfAvailable);

        jtfAvailableUnit.setBackground(new java.awt.Color(153, 204, 255));
        jtfAvailableUnit.setEditable(false);
        jtfAvailableUnit.setText("UNIT");
        jtfAvailableUnit.setFocusable(false);
        jtfAvailableUnit.setPreferredSize(new java.awt.Dimension(40, 23));
        jpDpsEntriesInfo23.add(jtfAvailableUnit);

        jlYear.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jlYear.setText("Año:");
        jlYear.setPreferredSize(new java.awt.Dimension(35, 23));
        jpDpsEntriesInfo23.add(jlYear);

        jtfYear.setBackground(new java.awt.Color(153, 204, 255));
        jtfYear.setEditable(false);
        jtfYear.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jtfYear.setText("2000");
        jtfYear.setFocusable(false);
        jtfYear.setPreferredSize(new java.awt.Dimension(40, 23));
        jpDpsEntriesInfo23.add(jtfYear);

        jpDpsEntriesInfo2.add(jpDpsEntriesInfo23);

        jpDpsEntriesInfo.add(jpDpsEntriesInfo2, java.awt.BorderLayout.CENTER);

        jpDpsEntries.add(jpDpsEntriesInfo, java.awt.BorderLayout.SOUTH);

        getContentPane().add(jpDpsEntries, java.awt.BorderLayout.CENTER);

        jpControls.setLayout(new java.awt.BorderLayout());

        jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));

        jbOk.setText("Aceptar");
        jbOk.setToolTipText("[Ctrl + Enter]");
        jbOk.setPreferredSize(new java.awt.Dimension(75, 23));
        jPanel1.add(jbOk);

        jbCancel.setText("Cancelar");
        jbCancel.setToolTipText("[Escape]");
        jPanel1.add(jbCancel);

        jpControls.add(jPanel1, java.awt.BorderLayout.EAST);

        jPanel2.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));
        jpControls.add(jPanel2, java.awt.BorderLayout.CENTER);

        getContentPane().add(jpControls, java.awt.BorderLayout.SOUTH);

        setSize(new java.awt.Dimension(928, 609));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
        windowActivated();
    }//GEN-LAST:event_formWindowActivated

    private void initComponentsExtra() {
        int col = 0;
        STableColumnForm[] columns = null;

        moPanelDps = new SPanelDps(miClient, "a surtir");
        remove(jlPanelDps);
        add(moPanelDps, BorderLayout.NORTH);

        col = 0;
        columns = new STableColumnForm[8];
        columns[col++] = new STableColumnForm(SLibConstants.DATA_TYPE_INTEGER, "#", STableConstants.WIDTH_NUM_TINYINT);
        columns[col++] = new STableColumnForm(SLibConstants.DATA_TYPE_STRING, "Clave", STableConstants.WIDTH_ITEM_KEY);
        columns[col++] = new STableColumnForm(SLibConstants.DATA_TYPE_STRING, "Concepto", STableConstants.WIDTH_ITEM_3X);
        columns[col] = new STableColumnForm(SLibConstants.DATA_TYPE_DOUBLE, "Cant. neta", STableConstants.WIDTH_QUANTITY_2X);
        columns[col++].setCellRenderer(miClient.getSessionXXX().getFormatters().getTableCellRendererQuantity());
        columns[col] = new STableColumnForm(SLibConstants.DATA_TYPE_DOUBLE, "Cant. pendiente", STableConstants.WIDTH_QUANTITY_2X);
        columns[col++].setCellRenderer(miClient.getSessionXXX().getFormatters().getTableCellRendererQuantity());
        columns[col] = new STableColumnForm(SLibConstants.DATA_TYPE_DOUBLE, "Cant. a surtir", STableConstants.WIDTH_QUANTITY_2X);
        columns[col].setEditable(true);
        columns[col++].setCellRenderer(miClient.getSessionXXX().getFormatters().getTableCellRendererQuantity());
        columns[col++] = new STableColumnForm(SLibConstants.DATA_TYPE_STRING, "Unidad", STableConstants.WIDTH_UNIT_SYMBOL);
        columns[col] = new STableColumnForm(SLibConstants.DATA_TYPE_DOUBLE, "Excedente", STableConstants.WIDTH_PERCENTAGE);
        columns[col++].setCellRenderer(miClient.getSessionXXX().getFormatters().getTableCellRendererPercentage());

        moPaneDpsEntries = new STablePane(miClient);
        jpDpsEntries.add(moPaneDpsEntries, BorderLayout.CENTER);

        for (STableColumnForm column : columns) {
            moPaneDpsEntries.addTableColumn(column);
        }

        moPaneDpsEntries.createTable();
        moPaneDpsEntries.getTable().getSelectionModel().addListSelectionListener(this);
        moPaneDpsEntries.getTable().getTableHeader().setReorderingAllowed(false);
        moPaneDpsEntries.getTable().getTableHeader().setResizingAllowed(false);

        moPickerStockLots = new SDialogPickerStockLots(miClient, false);

        jbOk.addActionListener(this);
        jbCancel.addActionListener(this);
        jbSupplyAll.addActionListener(this);
        jbCleanAll.addActionListener(this);
        jbViewLots.addActionListener(this);

        SFormUtilities.createActionMap(rootPane, this, "actionOk", "ok", KeyEvent.VK_ENTER, KeyEvent.CTRL_DOWN_MASK);
        SFormUtilities.createActionMap(rootPane, this, "actionCancel", "cancel", KeyEvent.VK_ESCAPE, SLibConstants.UNDEFINED);
    }

    private void windowActivated() {
        if (mbFirstTime) {
            mbFirstTime = false;
            moPaneDpsEntries.getTable().requestFocus();
        }
    }

    private void computePaneEdition() {
        int decs = miClient.getSessionXXX().getParamsErp().getDecimalsQuantity();
        double factor = 0;
        STrnDpsStockSupplyRow stockSupplyRow = null;

        for (STableRow row : moPaneDpsEntries.getTableModel().getTableRows()) {
            stockSupplyRow = (STrnDpsStockSupplyRow) row;

            factor = ((SSessionCustom) miClient.getSession().getSessionCustom()).getUnitsFactorForQuantity(stockSupplyRow.getFkItemId(), stockSupplyRow.getFkOriginalUnitId(), stockSupplyRow.getFkUnitId());

            stockSupplyRow.setOriginalQuantityAboutToSupply((Double) row.getValues().get(COL_QTY));
            stockSupplyRow.setQuantityAboutToSupply(SLibUtilities.round(factor * stockSupplyRow.getOriginalQuantityAboutToSupply(), decs));
        }
    }

    private void computeClose() {
        if (moPaneDpsEntries.getTable().isEditing()) {
            moPaneDpsEntries.getTable().getCellEditor().cancelCellEditing();
        }
    }

    private void valueChangedPaneDpsEntries() {
        double stock = 0;
        double used = 0;
        double segregated = 0;

        STrnStockMove stockMoveParams = null;
        STrnStock objStock = null;
        STrnDpsStockSupplyRow stockSupplyRow = (STrnDpsStockSupplyRow) moPaneDpsEntries.getSelectedTableRow();

        if (stockSupplyRow == null) {
            jtfQuantity.setText("");
            jtfQuantityUnit.setText("");
            jtfQuantityAdjusted.setText("");
            jtfQuantityAdjustedUnit.setText("");
            jtfQuantityNet.setText("");
            jtfQuantityNetUnit.setText("");
            jtfQuantityNetAux.setText("");
            jtfQuantityNetAuxUnit.setText("");
            jtfQuantitySupplied.setText("");
            jtfQuantitySuppliedUnit.setText("");
            jtfQuantityPend.setText("");
            jtfQuantityPendUnit.setText("");

            jtfStock.setText("");
            jtfStockUnit.setText("");
            jtfCurrentlyUsed.setText("");
            jtfCurrentlyUsedUnit.setText("");
            jtfAvailable.setText("");
            jtfAvailableUnit.setText("");

            jbViewLots.setEnabled(false);
        }
        else {
            // Document stock supply is processed in original units:

            jtfQuantity.setText(SLibUtils.getDecimalFormatQuantity().format(stockSupplyRow.getOriginalQuantity()));
            jtfQuantityUnit.setText(stockSupplyRow.getAuxOriginalUnitSymbol());
            jtfQuantityAdjusted.setText(SLibUtils.getDecimalFormatQuantity().format(stockSupplyRow.getOriginalQuantityAdjusted()));
            jtfQuantityAdjustedUnit.setText(stockSupplyRow.getAuxOriginalUnitSymbol());
            jtfQuantityNet.setText(SLibUtils.getDecimalFormatQuantity().format(stockSupplyRow.getOriginalQuantityNet()));
            jtfQuantityNetUnit.setText(stockSupplyRow.getAuxOriginalUnitSymbol());
            jtfQuantityNetAux.setText(SLibUtils.getDecimalFormatQuantity().format(stockSupplyRow.getOriginalQuantityNet()));
            jtfQuantityNetAuxUnit.setText(stockSupplyRow.getAuxOriginalUnitSymbol());
            jtfQuantitySupplied.setText(SLibUtils.getDecimalFormatQuantity().format(stockSupplyRow.getOriginalQuantitySupplied()));
            jtfQuantitySuppliedUnit.setText(stockSupplyRow.getAuxOriginalUnitSymbol());
            jtfQuantityPend.setText(SLibUtils.getDecimalFormatQuantity().format(stockSupplyRow.getOriginalQuantityPend()));
            jtfQuantityPendUnit.setText(stockSupplyRow.getAuxOriginalUnitSymbol());

            // Available stock is processed in inventory units:

            try {
                stock = STrnUtilities.obtainStock(miClient, mnYear,
                        stockSupplyRow.getFkItemId(), stockSupplyRow.getFkUnitId(), SLibConstants.UNDEFINED,
                        manWarehouseKey[0], manWarehouseKey[1], SLibConstants.UNDEFINED, null,
                        (int[]) moParamDiog.getPrimaryKey());

                stockMoveParams = new STrnStockMove();
                stockMoveParams.setPkCompanyBranchId(manWarehouseKey[0]);
                stockMoveParams.setPkWarehouseId(manWarehouseKey[1]);
                stockMoveParams.setPkYearId(mnYear); // year of document
                stockMoveParams.setPkItemId(stockSupplyRow.getFkItemId());
                stockMoveParams.setPkUnitId(stockSupplyRow.getFkUnitId());

                objStock = STrnStockSegregationUtils.getStockSegregated(miClient, stockMoveParams);
                segregated = objStock.getSegregatedStock();
            }
            catch (Exception e) {
                SLibUtilities.printOutException(this, e);
            }

            for (SDataDiogEntry entry : moParamDiog.getDbmsEntries()) {
                for (STrnStockMove move : entry.getAuxStockMoves()) {
                    if (move.getPkItemId() == stockSupplyRow.getFkItemId() && move.getPkUnitId() == stockSupplyRow.getFkUnitId()) {
                        if (entry.getIsDeleted()) {
                            stock += move.getQuantity();
                        }
                        else {
                            used += move.getQuantity();
                        }
                    }
                }
            }

            jtfStock.setText(SLibUtils.getDecimalFormatQuantity().format(stock));
            jtfStockUnit.setText(stockSupplyRow.getAuxUnitSymbol());
            jtfSegregated.setText(SLibUtils.getDecimalFormatQuantity().format(segregated));
            jtfSegregatedUnit.setText(stockSupplyRow.getAuxUnitSymbol());
            jtfCurrentlyUsed.setText(SLibUtils.getDecimalFormatQuantity().format(used));
            jtfCurrentlyUsedUnit.setText(stockSupplyRow.getAuxUnitSymbol());
            jtfAvailable.setText(SLibUtils.getDecimalFormatQuantity().format(stock - used));
            jtfAvailableUnit.setText(stockSupplyRow.getAuxUnitSymbol());

            jbViewLots.setEnabled(true);
        }
    }

    public void actionSupplyAll() {
        STrnDpsStockSupplyRow stockSupplyRow = null;

        if (jbCleanAll.isEnabled()) {
            computeClose();

            for (STableRow row : moPaneDpsEntries.getTableModel().getTableRows()) {
                stockSupplyRow = (STrnDpsStockSupplyRow) row;
                stockSupplyRow.setOriginalQuantityAboutToSupply(stockSupplyRow.getOriginalQuantityPend() <= 0d ? 0d : stockSupplyRow.getOriginalQuantityPend());
                stockSupplyRow.setQuantityAboutToSupply(stockSupplyRow.getQuantityPend() <= 0d ? 0d : stockSupplyRow.getQuantityPend());
                stockSupplyRow.prepareTableRow();
            }

            moPaneDpsEntries.renderTableRows();
            moPaneDpsEntries.setTableRowSelection(0);
        }
    }

    public void actionCleanAll() {
        STrnDpsStockSupplyRow stockSupplyRow = null;

        if (jbCleanAll.isEnabled()) {
            computeClose();

            for (STableRow row : moPaneDpsEntries.getTableModel().getTableRows()) {
                stockSupplyRow = (STrnDpsStockSupplyRow) row;
                stockSupplyRow.setOriginalQuantityAboutToSupply(0d);
                stockSupplyRow.setQuantityAboutToSupply(0d);
                stockSupplyRow.prepareTableRow();
            }

            moPaneDpsEntries.renderTableRows();
            moPaneDpsEntries.setTableRowSelection(0);
        }
    }

    public void actionViewLots() {
        STrnDpsStockSupplyRow stockSupplyRow = (STrnDpsStockSupplyRow) moPaneDpsEntries.getSelectedTableRow();

        if (stockSupplyRow == null) {
            miClient.showMsgBoxWarning(SLibConstants.MSG_ERR_GUI_ROW_UNDEF);
        }
        else {
            moPickerStockLots.formReset();
            moPickerStockLots.setFormParams(mnYear, stockSupplyRow.getFkItemId(), stockSupplyRow.getFkUnitId(), moParamDiog.getWarehouseKey(), (int[]) moParamDiog.getPrimaryKey());
            moPickerStockLots.setVisible(true);
        }
    }

    public void actionOk() {
        SFormValidation validation = formValidate();

        if (validation.getIsError()) {
            if (validation.getComponent() != null) {
                validation.getComponent().requestFocus();
            }
            miClient.showMsgBoxWarning(validation.getMessage());
        }
        else {
            computeClose();
            mnFormResult = SLibConstants.FORM_RESULT_OK;
            setVisible(false);
        }
    }

    public void actionCancel() {
        computeClose();
        mnFormResult = SLibConstants.FORM_RESULT_CANCEL;
        setVisible(false);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel10;
    private javax.swing.JPanel jPanel11;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JButton jbCancel;
    private javax.swing.JButton jbCleanAll;
    private javax.swing.JButton jbOk;
    private javax.swing.JButton jbSupplyAll;
    private javax.swing.JButton jbViewLots;
    private javax.swing.JLabel jlAvailable;
    private javax.swing.JLabel jlCurrentlyUsed;
    private javax.swing.JLabel jlPanelDps;
    private javax.swing.JLabel jlQuantity;
    private javax.swing.JLabel jlQuantityAdjusted;
    private javax.swing.JLabel jlQuantityNet;
    private javax.swing.JLabel jlQuantityNetAux;
    private javax.swing.JLabel jlQuantityPend;
    private javax.swing.JLabel jlQuantitySupplied;
    private javax.swing.JLabel jlSegregated;
    private javax.swing.JLabel jlStock;
    private javax.swing.JLabel jlWarehouse;
    private javax.swing.JLabel jlYear;
    private javax.swing.JPanel jpControls;
    private javax.swing.JPanel jpDiogEntriesInfo24;
    private javax.swing.JPanel jpDpsEntries;
    private javax.swing.JPanel jpDpsEntriesControls;
    private javax.swing.JPanel jpDpsEntriesControls1;
    private javax.swing.JPanel jpDpsEntriesControls2;
    private javax.swing.JPanel jpDpsEntriesInfo;
    private javax.swing.JPanel jpDpsEntriesInfo1;
    private javax.swing.JPanel jpDpsEntriesInfo11;
    private javax.swing.JPanel jpDpsEntriesInfo12;
    private javax.swing.JPanel jpDpsEntriesInfo2;
    private javax.swing.JPanel jpDpsEntriesInfo21;
    private javax.swing.JPanel jpDpsEntriesInfo22;
    private javax.swing.JPanel jpDpsEntriesInfo23;
    private javax.swing.JTextField jtfAvailable;
    private javax.swing.JTextField jtfAvailableUnit;
    private javax.swing.JTextField jtfCompanyBranch;
    private javax.swing.JTextField jtfCompanyBranchCode;
    private javax.swing.JTextField jtfCurrentlyUsed;
    private javax.swing.JTextField jtfCurrentlyUsedUnit;
    private javax.swing.JTextField jtfQuantity;
    private javax.swing.JTextField jtfQuantityAdjusted;
    private javax.swing.JTextField jtfQuantityAdjustedUnit;
    private javax.swing.JTextField jtfQuantityNet;
    private javax.swing.JTextField jtfQuantityNetAux;
    private javax.swing.JTextField jtfQuantityNetAuxUnit;
    private javax.swing.JTextField jtfQuantityNetUnit;
    private javax.swing.JTextField jtfQuantityPend;
    private javax.swing.JTextField jtfQuantityPendUnit;
    private javax.swing.JTextField jtfQuantitySupplied;
    private javax.swing.JTextField jtfQuantitySuppliedUnit;
    private javax.swing.JTextField jtfQuantityUnit;
    private javax.swing.JTextField jtfSegregated;
    private javax.swing.JTextField jtfSegregatedUnit;
    private javax.swing.JTextField jtfStock;
    private javax.swing.JTextField jtfStockUnit;
    private javax.swing.JTextField jtfWarehouse;
    private javax.swing.JTextField jtfWarehouseCode;
    private javax.swing.JTextField jtfYear;
    private javax.swing.JLabel label;
    private javax.swing.JLabel label1;
    // End of variables declaration//GEN-END:variables

    @SuppressWarnings("unchecked")
    public void setFormParams(final SDataDps dps, final SDataDiog diog) {
        String sql = "";
        ResultSet resulSet = null;

        moPaneDpsEntries.clearTableRows();

        try {
            if (dps == null || diog == null) {
                moParamDps = null;
                moParamDiog = null;
                moPanelDps.setDps(null, null);

                mnYear = 0;
                manWarehouseKey = null;
                moParamCompanyBranch = null;
                moParamWarehouse = null;

                jtfCompanyBranch.setText("");
                jtfCompanyBranchCode.setText("");
                jtfWarehouse.setText("");
                jtfWarehouseCode.setText("");
                jtfYear.setText("");
            }
            else {
                moParamDps = dps;
                moParamDiog = diog;
                moPanelDps.setDps(moParamDps, moParamDiog.getDate());

                mnYear = SLibTimeUtilities.digestYear(moParamDiog.getDate())[0];
                manWarehouseKey = moParamDiog.getWarehouseKey();
                moParamCompanyBranch = (SDataBizPartnerBranch) SDataUtilities.readRegistry(miClient, SDataConstants.BPSU_BPB, new int[] { manWarehouseKey[0] }, SLibConstants.EXEC_MODE_VERBOSE);
                moParamWarehouse = (SDataCompanyBranchEntity) SDataUtilities.readRegistry(miClient, SDataConstants.CFGU_COB_ENT, manWarehouseKey, SLibConstants.EXEC_MODE_VERBOSE);

                jtfCompanyBranch.setText(moParamCompanyBranch.getBizPartnerBranch());
                jtfCompanyBranchCode.setText(moParamCompanyBranch.getCode());
                jtfWarehouse.setText(moParamWarehouse.getEntity());
                jtfWarehouseCode.setText(moParamWarehouse.getCode());
                jtfYear.setText(miClient.getSessionXXX().getFormatters().getYearFormat().format(mnYear));

                jtfCompanyBranch.setCaretPosition(0);
                jtfCompanyBranchCode.setCaretPosition(0);
                jtfWarehouse.setCaretPosition(0);
                jtfWarehouseCode.setCaretPosition(0);
                jtfYear.setCaretPosition(0);

                sql = "SELECT de.id_year, de.id_doc, de.id_ety, de.sort_pos, de.fid_item, de.fid_unit, de.fid_orig_unit, d.b_close, " +
                        "i.item_key, i.item, u.symbol AS f_unit, uo.symbol AS f_orig_unit, " +
                        "de.qty AS f_qty, " +
                        "de.orig_qty AS f_orig_qty, " +
                        "COALESCE((SELECT SUM(ddd.qty) FROM trn_dps_dps_adj AS ddd, trn_dps_ety AS dae, trn_dps AS da WHERE " +
                        "ddd.id_dps_year = de.id_year AND ddd.id_dps_doc = de.id_doc AND ddd.id_dps_ety = de.id_ety AND " +
                        "ddd.id_adj_year = dae.id_year AND ddd.id_adj_doc = dae.id_doc AND ddd.id_adj_ety = dae.id_ety AND " +
                        "dae.id_year = da.id_year AND dae.id_doc = da.id_doc AND " +
                        "dae.b_del = 0 AND dae.fid_tp_dps_adj = " + SDataConstantsSys.TRNS_TP_DPS_ADJ_RET + " AND " +
                        "da.b_del = 0 AND da.fid_st_dps = " + SDataConstantsSys.TRNS_ST_DPS_EMITED + "), 0) AS f_adj_qty, " +
                        "COALESCE((SELECT SUM(ddd.orig_qty) FROM trn_dps_dps_adj AS ddd, trn_dps_ety AS dae, trn_dps AS da WHERE " +
                        "ddd.id_dps_year = de.id_year AND ddd.id_dps_doc = de.id_doc AND ddd.id_dps_ety = de.id_ety AND " +
                        "ddd.id_adj_year = dae.id_year AND ddd.id_adj_doc = dae.id_doc AND ddd.id_adj_ety = dae.id_ety AND " +
                        "dae.id_year = da.id_year AND dae.id_doc = da.id_doc AND " +
                        "dae.b_del = 0 AND dae.fid_tp_dps_adj = " + SDataConstantsSys.TRNS_TP_DPS_ADJ_RET + " AND " +
                        "da.b_del = 0 AND da.fid_st_dps = " + SDataConstantsSys.TRNS_ST_DPS_EMITED + "), 0) AS f_adj_orig_qty, " +
                        "COALESCE((SELECT SUM(ge.qty * CASE WHEN ge.fid_dps_adj_year_n IS NULL THEN 1 ELSE -1 END) FROM trn_diog_ety AS ge, trn_diog AS g WHERE " +
                        "ge.fid_dps_year_n = de.id_year AND ge.fid_dps_doc_n = de.id_doc AND ge.fid_dps_ety_n = de.id_ety AND " +
                        "ge.id_year = g.id_year AND ge.id_doc = g.id_doc AND " +
                        "ge.b_del = 0 AND g.b_del = 0 AND " +
                        "NOT (g.id_year = " + moParamDiog.getPkYearId() + " AND g.id_doc = " + moParamDiog.getPkDocId() + ")), 0) AS f_sup_qty, " +
                        "COALESCE((SELECT SUM(ge.orig_qty * CASE WHEN ge.fid_dps_adj_year_n IS NULL THEN 1 ELSE -1 END) FROM trn_diog_ety AS ge, trn_diog AS g WHERE " +
                        "ge.fid_dps_year_n = de.id_year AND ge.fid_dps_doc_n = de.id_doc AND ge.fid_dps_ety_n = de.id_ety AND " +
                        "ge.id_year = g.id_year AND ge.id_doc = g.id_doc AND " +
                        "ge.b_del = 0 AND g.b_del = 0 AND " +
                        "NOT (g.id_year = " + moParamDiog.getPkYearId() + " AND g.id_doc = " + moParamDiog.getPkDocId() + ")), 0) AS f_sup_orig_qty, " +
                        "COALESCE((SELECT SUM(dds.qty) FROM trn_dps_dps_supply AS dds " +
                        "INNER JOIN trn_dps AS dd ON dds.id_des_year = dd.id_year AND dds.id_des_doc = dd.id_doc AND dd.b_del = false AND dd.fid_st_dps = " + SDataConstantsSys.TRNS_ST_DPS_EMITED + " " +
                        "INNER JOIN trn_dps_ety AS dde ON dds.id_des_year = dde.id_year AND dds.id_des_doc = dde.id_doc AND dds.id_des_ety = dde.id_ety AND dde.b_del = false " +
                        "WHERE de.id_year = dds.id_src_year AND de.id_doc = dds.id_src_doc AND de.id_ety = dds.id_src_ety), 0) AS f_link_qty, " +
                        "COALESCE((SELECT SUM(dds.orig_qty) FROM trn_dps_dps_supply AS dds " +
                        "INNER JOIN trn_dps AS dd ON dds.id_des_year = dd.id_year AND dds.id_des_doc = dd.id_doc AND dd.b_del = false AND dd.fid_st_dps = " + SDataConstantsSys.TRNS_ST_DPS_EMITED + " " +
                        "INNER JOIN trn_dps_ety AS dde ON dds.id_des_year = dde.id_year AND dds.id_des_doc = dde.id_doc AND dds.id_des_ety = dde.id_ety AND dde.b_del = false " +
                        "WHERE de.id_year = dds.id_src_year AND de.id_doc = dds.id_src_doc AND de.id_ety = dds.id_src_ety), 0)  AS f_orig_link_qty, " +
                        "de.surplus_per " +
                        "FROM trn_dps AS d " +
                        "INNER JOIN trn_dps_ety AS de ON d.id_year = de.id_year AND d.id_doc = de.id_doc AND " +
                        "de.b_del = 0 AND de.b_inv = 1 AND de.qty > 0 AND de.orig_qty > 0 AND " +
                        "d.id_year = " + moParamDps.getPkYearId() + " AND d.id_doc = " + moParamDps.getPkDocId() + " " +
                        "INNER JOIN erp.itmu_item AS i ON de.fid_item = i.id_item " +
                        "INNER JOIN erp.itmu_unit AS u ON de.fid_unit = u.id_unit " +
                        "INNER JOIN erp.itmu_unit AS uo ON de.fid_orig_unit = uo.id_unit " +
                        "GROUP BY de.id_year, de.id_doc, de.id_ety, de.sort_pos, de.fid_item, de.fid_unit, de.fid_orig_unit, d.b_close, " +
                        "i.item_key, i.item, u.symbol, uo.symbol, de.qty, de.orig_qty " +
                        "HAVING (f_orig_qty - f_adj_orig_qty - f_sup_orig_qty) <> 0 AND d.b_close = 0 " +
                        "ORDER BY de.sort_pos; ";

                resulSet = miClient.getSession().getStatement().executeQuery(sql);
                while (resulSet.next()) {
                    STrnDpsStockSupplyRow stockSupplyRow = new STrnDpsStockSupplyRow(new int[] { resulSet.getInt("id_year"), resulSet.getInt("id_doc"), resulSet.getInt("id_ety") });

                    stockSupplyRow.setSortingPosition(resulSet.getInt("sort_pos"));
                    stockSupplyRow.setQuantity(resulSet.getDouble("f_qty"));
                    stockSupplyRow.setOriginalQuantity(resulSet.getDouble("f_orig_qty"));

                    if (dps.isOrder()) {
                        stockSupplyRow.setQuantityAdjusted(resulSet.getDouble("f_adj_qty") + resulSet.getDouble("f_link_qty"));
                        stockSupplyRow.setOriginalQuantityAdjusted(resulSet.getDouble("f_adj_orig_qty") + resulSet.getDouble("f_orig_link_qty"));
                    }
                    else {
                        stockSupplyRow.setQuantityAdjusted(resulSet.getDouble("f_adj_qty"));
                        stockSupplyRow.setOriginalQuantityAdjusted(resulSet.getDouble("f_adj_orig_qty"));
                    }

                    stockSupplyRow.setQuantitySupplied(resulSet.getDouble("f_sup_qty"));
                    stockSupplyRow.setOriginalQuantitySupplied(resulSet.getDouble("f_sup_orig_qty"));
                    stockSupplyRow.setQuantityAboutToSupply(0d);
                    stockSupplyRow.setOriginalQuantityAboutToSupply(0d);
                    stockSupplyRow.setSurplusPercentage(resulSet.getDouble("surplus_per"));
                    stockSupplyRow.setFkItemId(resulSet.getInt("fid_item"));
                    stockSupplyRow.setFkUnitId(resulSet.getInt("fid_unit"));
                    stockSupplyRow.setFkOriginalUnitId(resulSet.getInt("fid_orig_unit"));
                    stockSupplyRow.setAuxItem(resulSet.getString("item"));
                    stockSupplyRow.setAuxItemKey(resulSet.getString("item_key"));
                    stockSupplyRow.setAuxUnitSymbol(resulSet.getString("f_unit"));
                    stockSupplyRow.setAuxOriginalUnitSymbol(resulSet.getString("f_orig_unit"));

                    for (SDataDiogEntry diogEntry : moParamDiog.getDbmsEntries()) {
                        if (!diogEntry.getIsDeleted()) {
                            if (SLibUtilities.compareKeys(stockSupplyRow.getDpsEntryKey(), diogEntry.getLinkedDpsEntryKey_n())) {
                                stockSupplyRow.setQuantitySupplied(stockSupplyRow.getQuantitySupplied() + diogEntry.getQuantity());
                                stockSupplyRow.setOriginalQuantitySupplied(stockSupplyRow.getOriginalQuantitySupplied() + diogEntry.getOriginalQuantity());
                            }
                        }
                    }

                    stockSupplyRow.prepareTableRow();
                    moPaneDpsEntries.addTableRow(stockSupplyRow);
                }

                if (moPaneDpsEntries.getTableGuiRowCount() > 0) {
                    moPaneDpsEntries.renderTableRows();
                    moPaneDpsEntries.setTableRowSelection(0);
                    moPaneDpsEntries.setTableColumnSelection(COL_QTY);
                }
            }
        }
        catch (Exception e) {
           SLibUtilities.renderException(this, e);
       }
    }

    public java.util.Vector<erp.mtrn.data.STrnDpsStockSupplyRow> obtainDpsStockSupplyRows() {
        Vector<STrnDpsStockSupplyRow> stockSupplyRows = new Vector<STrnDpsStockSupplyRow>();

        computePaneEdition();   // updates user edition into internal pane data objects

        for (STableRow row : moPaneDpsEntries.getTableModel().getTableRows()) {
            if (((STrnDpsStockSupplyRow) row).getOriginalQuantityAboutToSupply() > 0d) {
                stockSupplyRows.add((STrnDpsStockSupplyRow) row);
            }
        }

        return stockSupplyRows;
    }

    public int getFormResult() {
        return mnFormResult;
    }

    public int getFormStatus() {
        return mnFormStatus;
    }

    public void formReset() {
        mnFormResult = SLibConstants.UNDEFINED;
        mnFormStatus = SLibConstants.UNDEFINED;
        mbFirstTime = true;
    }

    public erp.lib.form.SFormValidation formValidate() {
        int supplies = 0;
        STrnDpsStockSupplyRow stockSupplyRow = null;
        SFormValidation validation = new SFormValidation();

        computePaneEdition();   // updates user edition into internal pane data objects

        for (int row = 0; row < moPaneDpsEntries.getTableModel().getTableRows().size(); row++) {
            stockSupplyRow = (STrnDpsStockSupplyRow) moPaneDpsEntries.getTableRow(row);

            if (stockSupplyRow.getOriginalQuantityAboutToSupply() < 0d) {
                validation.setMessage(SLibConstants.MSG_ERR_GUI_FIELD_VALUE_DIF + "'" + moPaneDpsEntries.getTableColumn(COL_QTY).getColumnTitle() + "' en la fila " + (row + 1) + ":\n" +
                        "el valor no puede ser negativo.");
                validation.setComponent(moPaneDpsEntries.getTable());
                break;
            }
            else if (stockSupplyRow.getOriginalQuantityAboutToSupply() > 0d) {
                if (stockSupplyRow.getOriginalQuantityAboutToSupply() > stockSupplyRow.getOriginalQuantityPendWithSurplus()) {
                    validation.setMessage(SLibConstants.MSG_ERR_GUI_FIELD_VALUE_DIF + "'" + moPaneDpsEntries.getTableColumn(COL_QTY).getColumnTitle() + "' en la fila " + (row + 1) + ":\n" +
                            "el valor no puede ser mayor a " + SLibUtils.getDecimalFormatQuantity().format(stockSupplyRow.getOriginalQuantityPendWithSurplus()) + " " + stockSupplyRow.getAuxOriginalUnitSymbol() + ".");
                    validation.setComponent(moPaneDpsEntries.getTable());
                    break;
                }
                else if (stockSupplyRow.getQuantityAboutToSupply() <= 0d) {
                    validation.setMessage("Error al calcular las unidades equivalentes del movimiento en la fila " + (row + 1) + ":\n" +
                            "el valor calculado es " + SLibUtils.getDecimalFormatQuantity().format(stockSupplyRow.getQuantityAboutToSupply()) + " " + stockSupplyRow.getAuxUnitSymbol() + ".");
                    validation.setComponent(moPaneDpsEntries.getTable());
                    break;
                }
                else {
                    supplies++;
                }
            }
        }

        if (!validation.getIsError()) {
            if (supplies == 0) {
                validation.setMessage("Se debe capturar al menos una partida.");
                validation.setComponent(moPaneDpsEntries.getTable());
            }
        }

        return validation;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() instanceof JButton) {
            JButton button = (JButton) e.getSource();

            if (button == jbOk) {
                actionOk();
            }
            else if (button == jbCancel) {
                actionCancel();
            }
            else if (button == jbSupplyAll) {
                actionSupplyAll();
            }
            else if (button == jbCleanAll) {
                actionCleanAll();
            }
            else if (button == jbViewLots) {
                actionViewLots();
            }
        }
    }

    @Override
    public void valueChanged(ListSelectionEvent e) {
        if (!e.getValueIsAdjusting()) {
            valueChangedPaneDpsEntries();
        }
    }
}


If you haven't finished up your passport for the 2018 Wicked Brew Tour, Saturday, Sept. 29 could be the perfect day to do so. Many local shops are offering deals and discounts on coffee in honor of National Coffee Day.
Wichita is definitely a coffee city, with Food Network royalty Alton Brown naming Reverie Coffee Roasters as a favorite coffee shop.
Experience the super cold chill of Churn & Burn's ice cream-coffee cooled with liquid nitrogen. For National Coffee Day, customers can get an extra shot of espresso or grab a small $2 latte or $2.50 vanilla latte.
College Hill Creamery & Coffee Bar has been celebrating National Coffee Day all week long, showcasing a different brew each day. Check their Instagram for a list of drinks to try. Saturday, customers can get a $1 house drip coffee and $2 12-oz. Nitro Joe's cold brew. Feeling hungry? Grab some pumpkin coffee cake and cinnamon coffee cake to pair with your drink.
Don't forget to try the affogato or affogato shake. It's a single scoop of ice cream with a double shot of espresso on top. Any flavor works, but the most popular are the Mackinac Island fudge and vanilla.
Grab a Wicked Brew Tour stamp at Ecclesia Coffee in west Wichita, which will be offering discounts on some of their items in honor of National Coffee Day. Don't forget to try the Snickers latte, Chemex coffee or Spice Brown Sugar Latte, or mix your own flavors for a unique brew.
Take advantage of a BOGO 50 percent off deal on drip coffee and cold brew at Fairmount Coffee Co., located near Wichita State University. To celebration National Coffee Day, the coffee shop will also offer live jazz music from 11 a.m.-1 p.m.
With many familiar flavors from drip coffee, espresso or Americano to tantalizing candy mixtures like Almond Joy, Funky Monkey or Banana Split, R Coffee House knows coffee. Try something new and get 25 percent off specialty drinks in honor of National Coffee Day.
Reverie Coffee Roasters is offering a free 8 oz. specialty batch brew coffee to the first 50 guests who mention "National Coffee Day." Limit one free beverage per person. No substitutes.
You may also find a deal and score a Wicked Brew Tour stamp at The Donut Whole or Cocoa Dolce. Sente; Games & Refreshments will be open, but not offering a special deal or discount.
Explore other restaurants and hangouts in Wichita and other things to do this weekend in our calendar of events.


text:
Mixx Facebook Twitter Digg delicious reddit MySpace StumbleUpon LinkedIn Viadeo
Police, protesters battle in Bahrain's streets after boy's death
NEW: Clashes extend into Thursday following boy's death
NEW: Street battles reported around and outside Manama
The dead boy's father calls for human rights groups to act
Protests demanding political reform and greater freedoms began in February
Civil Unrest
Sitra, Bahrain (CNN) -- Clashes between police and Shiite Muslims in Bahrain stretched into Thursday morning, fueled by the killing of a 14-year-old boy by riot police in earlier demonstrations.
The government of the Persian Gulf island state said it would "await a full investigation" by the Interior Ministry before drawing any conclusions about the death early Wednesday of Ali Jawad al-Sheikh. Several witnesses said they saw the boy collapse after a tear-gas round was fired directly at him by riot police who were chasing al-Sheikh and other protesters in Sitra, southwest of the capital Manama.
But the Interior Ministry said no clashes were taking place at the time when the boy was injured, saying that the last reported incident of unrest in the area was around 1:15 a.m. Wednesday.
Public prosecutors have already begun examining the incident, according to a statement from Bahrain's Information Affairs Authority, and it would also fall under the authority of the Independent Commission of Inquiry set up by Bahrain's King Hamad in June to investigate reports of human rights abuses.
Clashes broke out on the first day of the Eid al-Fitr festival for many Shiites in Bahrain, one of several countries embroiled in anti-government protests across the Middle East and North Africa this year. By the early hours of Thursday, they had spread to most Shiite villages and parts of Manama.
Police responded heavily to street fights in three districts near the Pearl Roundabout, the epicenter of anti-government protests that began in February, witnesses said. Bahrain demolished the landmark Pearl Monument at the center of the plaza in March after it became a symbol of the demonstrations.
Protests have lingered for months despite a crackdown by Bahrain's Sunni monarchy, backed by troops from Saudi Arabia and the United Arab Emirates. More than 30 people have been killed the crackdown, in which activists say Bahraini security forces used live ammunition. Opposition groups say more than 1,000 people -- mainly Shiites -- have been detained and more than 2,000 have lost their jobs for allegedly taking part in the protests.
Bahrain is a close ally of the United States and houses the headquarters of the U.S. Navy's 5th Fleet. Its rulers blame Shiite-ruled Iran for stirring up trouble among its Shiite majority, but opposition leaders and Iranian officials deny the allegation and many Western powers have dismissed it.
The funeral for the boy killed in Wednesday's protests is scheduled for Thursday morning. Riot police surrounded the hospital where he was taken and took custody of his body amid rising tension with relatives and area residents, witnesses said. The body was transported to the country's main hospital morgue.
The boy's father, Jawad al-Sheikh, told CNN that when he went to the hospital, his son was "hard to recognize because he was covered with blood." He appealed for human rights groups to take steps against Bahrain's leaders, saying, "I lost my child. ... He does not deserve this destiny."
Tuesday, Rupert Colville, a spokesman for the U.N. High Commissioner for Human Rights, said the situation in Bahrain remains "tense and unpredictable," with small protests still being repressed. The United Nations has demanded that Bahrain release prisoners detained for exercising freedom of speech.
Today's five most popular stories
Fine art from an iPhone? The best Instagram photos from 2014
After IVF shock, mom gives birth to two sets of identical twins
Inside North Korea: Water park, sacred birth site and some minders
10 top destinations to visit in 2015
What really scares terrorists

redpajama_set_name: RedPajamaCommonCrawl


In 1854, the 4th, 5th and the 6th Dragoon Guards rode together in the charge of the Heavy Brigade at Balaclava, Crimea. In this action, eight hundred men utterly routed nearly three thousand five hundred of the Tsar's finest Cavalry, with minimal loss to themselves, and so demoralised the Russian horseman that they did not dare to follow up the subsequent disaster to the Light Brigade later that same day.
Rather interesting tent in the foreground.


They're Back! The Periodical Cicadas Have Arrived!
Yay! Right on time! The adults of Brood III of the periodical cicada have emerged.
On Thursday, May 29 I received my first reported observation of periodical cicadas in 2014. A caller from northern Des Moines County phoned to ask about 1-inch long, red-eyed, black insects in his garden. Periodical cicadas at last. I have waited 17 years for this call.
Since the initial report we have heard from others where "a few" cicadas have emerged. With temperatures in the 80s this week, more will be coming and reports will come from more locations. At the moment we have had reports from Warren, Decatur, Wapello and Madison Counties. We are anxious to hear from the rest of you!
For more about the periodical cicadas see the HHPN from April 11, 2014 and the ISU News Service release from May 30, 2014.
See below for photos of "new" cicadas from this year!
An emerging periodical cicada. Note the empty shells nearby on the tree trunk. At the peak of emergence, some trees will be a solid mass of "shells."
Strawberry Root Weevils-- They're Back!
Periodical Cicada Flagging- The End is Near!


In late 2008 I did some scouting of locations near Denver International Airport, and in December headed out to one of those locations with a photographer friend. Parked on the side of the road we watched the aircraft depart after dusk on a mild evening. As the aircraft took off we photographed trying to catch the lights of the plane go through the night. One of the issues is that after sunset most of the aircraft depart to the west. Where we were located if the aircraft would take off on the south runway, it would usually turn to the west prior to reaching our location.
After some time, I was getting ready to give up when an aircraft started a turn to what it looked like could be to the southeast and near our position. Quickly adjusting the camera, I open the shutter and started counting the number of seconds. I wasn't sure when the aircraft would be out of the frame, but once it was even with me I knew that was more than enough. With the 45 second exposure the light from the airport illuminates the bottom of the clouds which were present in the distance. Also at that length of exposure you start to get slight movement from the visible stars. The amount of movement of the stars depends on their distance from the north star. I wasn't sure at that time if this image would be the one I was hoping to obtain, but once I got home I knew this would be a keeper of an Aircraft Departing.
Be a safe distance from the airport as there are many security concerns these days. A safe distance may help with some of those matters, but do be smart about your location.
Respect private property. If there is a fence don't jump it or sneak through an opening. If you would really like to access some property in order to photograph especially in a farm area inquire ahead of time and be honest with what you are looking to do.
Be a safe distance off the road. For this photograph we were not near a busy road, but one with a high speed limit. Make sure that you are well off the road with your car and self. Additionally don't position yourself just over a hill as drivers will not see you until they are close. If you can, use the car to also protect you from oncoming traffic as well as light pollution. Normally I will be parked on the shoulder and photographing further down so I am not next to the car, however in a location where it can help shield me if needed. Also know the law for area and if a reflective vest is needed where you are photographing.
Dress for the time of year. After a while it may start to get chilly being in one location. Have additional layers of clothes available to add if needed or be ready to call it an evening if you are not prepared for the weather.
Have you photographed anything with paints a line in the night, or know of anything else to try with a long exposure?


text:
Australian Pictorial
Dieback : Death of an Australian Landscape by H. Heatwale; M. Lowman
Category: SECONDHAND BOOKS
Illustrated Guide To Australian Places by Readers Digest
A NEW HISTORY OF WESTERN AUSTRALIA by C T STANNAGE
Category: AUSTRALIANA
Underbelly: The Golden Mile by John Silvester
It's 1989 and the cops are on the take and the crims are on the make. They are kings of the Cross. They run the street that put the sin in Sin City. The Golden Mile. Strippers, gamblers, gunmen, dealers, bouncers, bagmen they all come to where the action is. Kim Hollingsworth is a policeman's daughter w ho wants to follow daddy's footsteps. She's a stripper and a hooker but that's no problem until she blows the whistle on bent cops who think they can stand over her. They are wrong. Then there's 'Teflon John' Ibrahim, the rising star who made his name looking after the Bayeh brothers. And there are Trevor Haken, Chook Fowler and the other Kings Cross cops who treat the street as their playground - and play as if there's no tomorrow. ...Show more
Ten Thousand Acres: A Love Story by Patrice Newell
This unique and beautiful book pleads for a more personal knowledge of Australia's ancient, fragile landscape, a re-evaluation of one of the oldest relationships of all.
Full Steam Ahead : Bunbury Port Authority 1909-1995 by J WILLINGE
The Australian Pub by Diane Kirkby
The pub is one of Australia's most-loved institutions. The Australian Pub takes us on an intoxicating journey through the colourful history of this Australian icon: from its colonial origins along the waterfronts and roadways used by travellers, through to the mid-twentieth century six o'clock swill, an d on to the boutique bars of contemporary cosmopolitanism. The authors trace the essential role of the pub as an enduring provider of drink, food, entertainment, accommodation and illegal betting, as well as its relationship to sport, and its battles with licensing laws. The hubbub of the public bar, patrons' loyalty to the local, the friendship of the lounge, the work of kitchen staff and barmaids, the local standing of publicans, and classic pub architecture and heritage - all are explored in this comprehensive history. This beautiful book celebrates our pubs, proving that they are, and always have been, more than just a place to drink. ...Show more
A GEOGRAPHICAL DICTIONARY OR GAZETTEER OF THE AUSTRALIAN COLONIES 1848 by WILLIAM HENRY WELLS
Whose ABC?: The Australian Broadcasting Commission 1983-2006 by K. S. Inglis
Whose ABC?is Ken Inglis's long-awaited political and cultural history of one of Australia's best-loved institutions. Combining in-depth research, interviews with the key players and a gift for story-telling, it is social history of the highest order.Since 1983, the ABC has seen controversial managing di rectors - David Hill, Jonathan Shier - come and go. There have been fights over funding - "eight cents a day" - and charges of bias. There have been both programming triumphs - from Bananas in Pyjamas to Kath & Kim - and accusations of cowardice and dumbing down.Whose ABC?deals with all these events and more. It seeks out the truth of events and breaks new ground. The result is an unfailingly readable narrative that will be seen as a classic of Australian historical writing. ...Show more
Key Guide to Australia's National Parks by Leonard Cronin
Category: SECONDHAND BOOKS | Series: Key Guides Ser.
Providing everything needed to discover the great network of national parks around Australia, this is a comprehensive guide to scenic wonders, including the rainforests and rugged wilderness areas to the east, the amazing wildflower parks of the west, sun-drenched tropical islands, and the stunning land scapes and mountain ranges at the heart of the continent. facilities are available, the climate, walking tracks, fauna and flora, boat ramps, and Aboriginal heritage. The most significant areas are specially featured, each with a colour relief map showing the landform, roads and walking tracks, the camping and picnic areas, and the park's major attractions. edition. ...Show more
Reader's Digest Book of the Great Barrier Reef by Reader's Digest Editors
A complete picture of life on Australia's phenomenal Great Barrier Reef. Over 800 full colour photographs are included.
Environmental Planning and Management in Australia - SIGNED by Arthur Conacher
Category: RARE AND COLLECTIBLE
This is the first comprehensive text on environmental planning and management in Australia


Living with five 6 and 7 year olds. The man sat nearby. He suffers from a hormone disorder which causes proportionate dwarfism, rendering him 4 feet tall but otherwise remarkably normal. I'm watching the 42 year old climb out of the van. The break between 6th period and dinner is the best time for midgets to shower. She says the most fun thing about being a midget counselor is that they bring you back down to earth; you get to play their silly games and really enjoy the innocence of life. Siesta is always great fun in a midget cabin.


23 Mar 84: Did You See God This Week?
DID YOU SEE GOD THIS WEEK?
Probably the most revolutionary thing that Jesus said in this church service was not the reading he made.
After all, many preachers and teachers before him must have read these verses from Isaiah. The new dimension which Jesus brought was in his statement "These Scriptures came true today!"
It was not so much that Jesus was claiming that these verses referred to him. Rather, the revolutionary idea came in the concept that God was acting right in the very middle of this church service.
The church of Jesus' time had lost its relevance as a centre for worshipping God. It had become a place in which people taught and debated. Many of our churches today are much the same. We come together to improve ourselves, to learn, to grow, to think. There is nothing wrong with that, unless that is the total of what we should be doing in church.
Jesus stood up in the church and talked about God here and now, and that was uncomfortable. Somehow it is much safer to talk about Jesus as if he were a historical figure. It is easy to debate what the gospel writers meant, or to study the Old Testament prophets, or to think about the God who will come at the end of time.
But if we only have a God of yesterday, or a God of tomorrow, we have no God. Jesus said TODAY this Scripture comes true. This is the day that the Lord has made. Let us rejoice, be glad in it, and look for His actions. Our God is alive - right now!


For other uses, see Heraclius (disambiguation).
Not to be confused with Heraclitus.
"Heraclius I" redirects here. For the Georgian king, see Heraclius I of Kakheti. For the patriarch, see Patriarch Heraclius of Jerusalem.
He was responsible for introducing Greek as the Eastern Roman Empire's official language. His rise to power began in 608, when he and his father, Heraclius the Elder, the exarch of Africa, led a revolt against the unpopular usurper Phocas.
Heraclius's reign was marked by several military campaigns. The year Heraclius came to power, the empire was threatened on multiple frontiers. Heraclius immediately took charge of the Byzantine–Sassanid War of 602–628. The first battles of the campaign ended in defeat for the Byzantines; the Persian army fought their way to the Bosphorus but Constantinople was protected by impenetrable walls and a strong navy and Heraclius was able to avoid total defeat. Soon after, he initiated reforms to rebuild and strengthen the military. Heraclius drove the Persians out of Asia Minor and pushed deep into their territory, defeating them decisively in 627 at the Battle of Nineveh. The Persian king Khosrau II was overthrown and executed by his son Kavadh II, who soon sued for a peace treaty, agreeing to withdraw from all occupied territory. This way peaceful relations were restored to the two deeply strained empires.
Heraclius soon experienced a new event, the Muslim conquests. Emerging from the Arabian Peninsula, the Muslims quickly conquered the Sassanid empire. In 634 the Muslims marched into Roman Syria, defeating Heraclius' brother Theodore. Within a short period of time, the Arabs conquered Mesopotamia, Armenia and Egypt.
Heraclius entered diplomatic relations with the Croats and Serbs in the Balkans. He tried to repair the schism in the Christian church in regard to the Monophysites, by promoting a compromise doctrine called Monothelitism. The Church of the East (commonly called Nestorian) was also involved in the process. Eventually, however, this project of unity was rejected by all sides of the dispute.
Heraclius was the eldest son of Heraclius the Elder and Epiphania, of an Armenian family from Cappadocia,[A 2] probably of Arsacid descent. Beyond that, there is little specific information known about his ancestry. His father was a key general during Emperor Maurice's war with Bahrām Chobin, usurper of the Sassanid Empire, during 590. After the war, Maurice appointed Heraclius the Elder to the position of Exarch of Africa.
In 608, Heraclius the Elder renounced his loyalty to the Emperor Phocas, who had overthrown Maurice six years earlier. The rebels issued coins showing both Heraclii dressed as consuls, though neither of them explicitly claimed the imperial title at this time. Heraclius' younger cousin Nicetas launched an overland invasion of Egypt; by 609, he had defeated Phocas' general Bonosus and secured the province. Meanwhile, the younger Heraclius sailed eastward with another force via Sicily and Cyprus.
As he approached Constantinople, he made contact with prominent leaders and planned an attack to overthrow aristocrats in the city, and soon arranged a ceremony where he was crowned and acclaimed as Emperor. When he reached the capital, the Excubitors, an elite Imperial Guard unit led by Phocas' son-in-law Priscus, deserted to Heraclius, and he entered the city without serious resistance. When Heraclius captured Phocas, he asked him "Is this how you have ruled, wretch?" Phocas' reply—"And will you rule better?"—so enraged Heraclius that he beheaded Phocas on the spot. He later had the genitalia removed from the body because Phocas had raped the wife of Photius, a powerful politician in the city.
On October 5, 610, Heraclius was crowned for a second time, this time in the Chapel of St. Stephen within the Great Palace; at the same time he married Fabia, who took the name Eudokia. After her death in 612, he married his niece Martina in 613; this second marriage was considered incestuous and was very unpopular. In the reign of Heraclius' two sons, the divisive Martina was to become the center of power and political intrigue. Despite widespread hatred for Martina in Constantinople, Heraclius took her on campaigns with him and refused attempts by Patriarch Sergius to prevent and later dissolve the marriage.
During his Balkan Campaigns, Emperor Maurice and his family were murdered by Phocas in November 602 after a mutiny. Khosrau II (Chosroes) of the Sassanid Empire had been restored to his throne by Maurice, and they had remained allies.[A 3] Thus, the Persian King Khosrau II seized the pretext to attack the Byzantine Empire and reconquer the Byzantine province of Mesopotamia. Khosrau had at his court a man who claimed to be Maurice's son Theodosius, and Khosrau demanded that the Byzantines accept this Theodosius as Emperor.
The war initially went the Persians' way, partly because of Phocas' brutal repression and the succession crisis that ensued as the general Heraclius sent his nephew Nicetas to attack Egypt, enabling his son Heraclius the younger to claim the throne in 610. Phocas, an unpopular ruler who is invariably described in historical sources as a "tyrant" (in its original meaning of the word, i.e. illegitimate king by the rules of succession), was eventually deposed by Heraclius, who sailed to Constantinople from Carthage with an icon affixed to the prow of his ship.
By this time, the Persians had conquered Mesopotamia and the Caucasus, and in 611 they overran Syria and entered Anatolia. A major counter-attack led by Heraclius two years later was decisively defeated outside Antioch by Shahrbaraz and Shahin, and the Roman position collapsed; the Persians devastated parts of Asia Minor and captured Chalcedon across from Constantinople on the Bosporus. Over the following decade the Persians were able to conquer Palestine and Egypt (by mid-621 the whole province was in their hands) and to devastate Anatolia,[A 4] while the Avars and Slavs took advantage of the situation to overrun the Balkans, bringing the Empire to the brink of destruction. In 613, the Persian army took Damascus with the help of the Jews, seized Jerusalem in 614, damaging the Church of the Holy Sepulchre and capturing the True Cross, and afterwards capturing Egypt in 617 or 618.
With the Persians at the very gate of Constantinople, Heraclius thought of abandoning the city and moving the capital to Carthage, but the powerful church figure Patriarch Sergius convinced him to stay. Safe behind the walls of Constantinople, Heraclius was able to sue for peace in exchange for an annual tribute of a thousand talents of gold, a thousand talents of silver, a thousand silk robes, a thousand horses, and a thousand virgins to the Persian King. The peace allowed him to rebuild the Empire's army by slashing non-military expenditure, devaluing the currency, and melting down, with the backing of Patriarch Sergius, Church treasures to raise the necessary funds to continue the war.
On April 5, 622, Heraclius left Constantinople, entrusting the city to Sergius and general Bonus as regents of his son. He assembled his forces in Asia Minor, probably in Bithynia, and, after he revived their broken morale, he launched a new counter-offensive, which took on the character of a holy war; an acheiropoietos image of Christ was carried as a military standard.
Cherub and Heraclius receiving the submission of Khosrau II; plaque from a cross (Champlevé enamel over gilt copper, 1160–1170, Paris, Louvre).
The Roman army proceeded to Armenia, inflicted a defeat on an army led by a Persian-allied Arab chief, and then won a victory over the Persians under Shahrbaraz. Heraclius would stay on campaign for several years. On March 25, 624 he again left Constantinople with his wife, Martina, and his two children; after he celebrated Easter in Nicomedia on April 15, he campaigned in the Caucasus, winning a series of victories in Armenia against Khosrau and his generals Shahrbaraz, Shahin, and Shahraplakan. However, in the same year the Visigoths succeeded in recapturing Cartagena, capital of the western Byzantine province of Spania, resulting in the loss of one of the few minor provinces that had been conquered by the armies of Justinian I. In 626 the Avars and Slavs supported by a Persian army commanded by Shahrbaraz, besieged Constantinople, but the siege ended in failure (the victory was attributed to the icons of the Virgin which were led in procession by Sergius about the walls of the city), while a second Persian army under Shahin suffered another crushing defeat at the hands of Heraclius' brother Theodore.
With the Persian war effort disintegrating, Heraclius was able to bring the Gokturks of the Western Turkic Khaganate, Ziebel, who invaded Persian Transcaucasia. Heraclius exploited divisions within the Persian Empire, keeping the Persian general Shahrbaraz neutral by convincing him that Khosrau had grown jealous of him and had ordered his execution. Late in 627 he launched a winter offensive into Mesopotamia, where, despite the desertion of his Turkish allies, he defeated the Persians under Rhahzadh at the Battle of Nineveh. Continuing south along the Tigris he sacked Khosrau's great palace at Dastagird and was only prevented from attacking Ctesiphon by the destruction of the bridges on the Nahrawan Canal. Discredited by this series of disasters, Khosrau was overthrown and killed in a coup led by his son Kavadh II, who at once sued for peace, agreeing to withdraw from all occupied territories. In 629 Heraclius restored the True Cross to Jerusalem in a majestic ceremony.
Heraclius took for himself the ancient Persian title of "King of Kings" after his victory over Persia. Later on, starting in 629, he styled himself as Basileus, the Greek word for "sovereign", and that title was used by the Roman Emperors for the next 800 years. The reason Heraclius chose this title over previous Roman terms such as Augustus has been attributed by some scholars as relating to his Armenian origins.
Heraclius' defeat of the Persians ended a war that had been going on intermittently for almost 400 years and led to instability in the Persian Empire. Kavadh II died only months after assuming the throne, plunging Persia into several years of dynastic turmoil and civil war. Ardashir III, Heraclius' ally Shahrbaraz, and Khosrau's daughters Purandokht and Azarmidokht all succeeded to the throne within months of each other. Only when Yazdgerd III, a grandson of Khosrau II, succeeded to the throne in 632 was there stability. But by then the Sasanid Empire was severely disorganised and had been severely weakened by years of war and civil strife over the succession to the throne.
However, the Byzantine victory was ultimately a pyrrhic one, as the devastating impact of the war left the Byzantines in much weakened state. Within a few years both empires were overwhelmed by the onslaught of the Arabs who had become newly united by Islam, ultimately leading to the Muslim conquest of Persia in 644 and the fall of the Sassanid dynasty in 651.
In 629, the Islamic Prophet Muhammad had recently succeeded in unifying all of the nomadic tribes of the Arabian Peninsula. Those tribes had previously been too divided to pose a serious military challenge to the Byzantines or the Persians. Now unified and animated by their new conversion to Islam, they comprised one of the most powerful states in the region. The first conflict between the Byzantines and Muslims was the Battle of Mu'tah in September 629. A small Muslim skirmishing force attacked the province of Arabia in response to their ambassador's murder at the hands of the Ghassanid Roman governor, but were repulsed. Because the engagement was a Byzantine victory, there was no apparent reason to make changes to the military configuration of the region. Also, the Byzantines had little preceding battlefield experience with the Arabs, and even less with zealous soldiers united by a prophet. Even the Strategicon of Maurice, a manual of war praised for the variety of enemies it covers, does not mention warfare against Arabs at any length.
The following year the Muslims launched an offensive into the Arabah south of Lake Tiberias, taking Al Karak. Other raids penetrated into the Negev reaching as far as Gaza. The Battle of Yarmouk in 636 resulted in a crushing defeat for the larger Byzantine army; within three years, the Levant had been lost again. By the time of Heraclius' death in Constantinople, on February 11, 641, most of Egypt had fallen as well.
Looking back at the reign of Heraclius, scholars have credited him with many accomplishments. He enlarged the Empire, and his reorganization of the government and military were great successes. His attempts at religious harmony failed, but he succeeded in returning the True Cross, one of the holiest Christian relics, to Jerusalem.
Although the territorial gains produced by his defeat of the Persians were lost to the advance of the Muslims, Heraclius still ranks among the great Roman Emperors. His reforms of the government reduced the corruption which had taken hold in Phocas' reign, and he reorganized the military with great success. Ultimately, the reformed Imperial army halted the Muslims in Asia Minor and held on to Carthage for another 60 years, saving a core from which the empire's strength could be rebuilt.
The recovery of the eastern areas of the Roman Empire from the Persians once again raised the problem of religious unity centering on the understanding of the true nature of Christ. Most of the inhabitants of these provinces were Monophysites who rejected the Council of Chalcedon. Heraclius tried to promote a compromise doctrine called Monothelitism; however, this philosophy was rejected as heretical by both sides of the dispute. For this reason, Heraclius was viewed as a heretic and bad ruler by some later religious writers. After the Monophysite provinces were finally lost to the Muslims, Monotheletism rather lost its raison d'être and was eventually abandoned.
One of the most important legacies of Heraclius was changing the official language of the Empire from Latin to Greek in 620. The Croats and Serbs of Byzantine Dalmatia initiated diplomatic relations and dependencies with Heraclius. The Serbs, who briefly lived in Macedonia, became foederati and were baptized at the request of Heraclius (before 626). At his request, Pope John IV (640–642) sent Christian teachers and missionaries to Duke Porga and his Croats, who practiced Slavic paganism. He also created the office of sakellarios, a comptroller of the treasury.
Up to the 20th century he was credited with establishing the Thematic system but modern scholarship now points more to the 660s, under Constans II.
Of the characters conspicuous in history, that of Heraclius is one of the most extraordinary and inconsistent. In the first and last years of a long reign, the emperor appears to be the slave of sloth, of pleasure, or of superstition, the careless and impotent spectator of the public calamities. But the languid mists of the morning and evening are separated by the brightness of the meridian sun; the Arcadius of the palace arose the Caesar of the camp; and the honor of Rome and Heraclius was gloriously retrieved by the exploits and trophies of six adventurous campaigns. [...] Since the days of Scipio and Hannibal, no bolder enterprise has been attempted than that which Heraclius achieved for the deliverance of the empire.
Heraclius was long remembered favourably in the Western church for his reputed feat in recovering the True Cross, which had been captured by the Persians. As Heraclius approached the capital, Khosrau fled from his favourite residence, Dastagird near Baghdad, without offering resistance. Meanwhile, some of the Persian grandees freed his eldest son Kavadh II, whom Khosrau II had imprisoned, and proclaimed him King on the night of 23–24 February, 628. Kavadh however was mortally ill and was anxious that Heraclius should protect his infant son Ardeshir. So, as a goodwill gesture, he sent the True Cross with a peace negotiator to sue for peace in 628.
After a tour of the Empire Heraclius returned the cross on March 21, 629 or 630. For Christians of the Western Medieval Europe, Heraclius was the "first crusader". The iconography of the emperor appeared in the sanctuary at Mont Saint-Michel (ca. 1060), and then it became popular especially in France, Italian Peninsula and Holy Roman Empire. The story was included in the Golden Legend, the famous 13th century compendium of hagiography, and he is sometimes shown in art, as in The History of the True Cross sequence of frescoes painted by Piero della Francesca in Arezzo, and a similar sequence on a small altarpiece by Adam Elsheimer (Städel, Frankfurt). Both of these show scenes of Heraclius and Constantine I's mother Saint Helena, traditionally responsible for the excavation of the cross. The scene usually shown is Heraclius carrying the cross; according to the Golden Legend he insisted on doing this as he entered Jerusalem, against the advice of the Patriarch. At first, when he was on horseback (shown above), the burden was too heavy, but after he dismounted and removed his crown it became miraculously light, and the barred city gate opened of its own accord.
Probably because he was one of the few Eastern Roman Emperors widely known in the West, the Late Antique Colossus of Barletta was considered to depict Heraclius.
Some scholars disagree with this narrative, Professor Constantin Zuckerman going as far as to suggest that the True Cross was actually lost, and that the wood contained in the allegedly still sealed reliquary brought to Jerusalem by Heraclius in 629 was a fake. In his analysis, the hoax was designed to serve the political purposes of both Heraclius and his former foe, recently turned ally and co-father-in-law, Persian general and soon-to-become king, Shahrvaraz.
30:2 The Romans have been defeated 3 In the nearest land. But they, after their defeat, will overcome. 4 Within several years. To Allah belongs the command before and after. And that day the believers will rejoice 5 In the victory of Allah . He gives victory to whom He wills, and He is the Exalted in Might, the Merciful.
In Islamic and Arab histories Heraclius is the only Roman Emperor who is discussed at any length. Owing to his role as the Roman Emperor at the time Islam emerged, he was remembered in Arabic literature, such as the Islamic hadith and sira.
The Swahili Utendi wa Tambuka, an epic poem composed in 1728 at Pate Island (off the shore of present-day Kenya) and depicting the wars between the Muslims and Byzantines from the former's point of view, is also known as Kyuo kya Hereḳali ("The book of Heraclius"). In that work, Heraclius is portrayed as declining the Prophet's command to renounce his false belief in Christianity; he is therefore defeated by the Muslim forces.
In Muslim tradition he is seen as a just ruler of great piety, who had direct contact with the emerging Islamic forces. The 14th century scholar Ibn Kathir (d. 1373) went even further stating that "Heraclius was one of the wisest men and among the most resolute, shrewd, deep and opinionated of kings. He ruled the Romans with great leadership and splendor." Historians such as Nadia Maria El-Cheikh and Lawrence Conrad note that Islamic histories even go so far as claiming that Heraclius recognized Islam as the true faith and Muhammad as its prophet, by comparing Islam to Christianity.
Islamic historians often cite a letter that they claim Heraclius wrote to Muhammad: "I have received your letter with your ambassador and I testify that you are the messenger of God found in our New Testament. Jesus, son of Mary, announced you." According to the Muslim sources reported by El-Cheikh, he tried to convert the ruling class of the Empire, but they resisted so strongly that he reversed his course and claimed that he was just testing their faith in Christianity. El-Cheikh notes that these accounts of Heraclius add "little to our historical knowledge" of the emperor; rather, they are an important part of "Islamic kerygma," attempting to legitimate Muhammad's status as a prophet.
However, most scholarly historians view such traditions as "profoundly kerygmatic" and that "enormous difficulties" exist in using these sources for actual history. Furthermore, any messengers sent by Muhammad to Heraclius would not have received an imperial audience or recognition. Outside of Islamic sources there is no evidence to suggest Heraclius ever heard of Islam, and it is possible that he and his advisors actually viewed the Muslims as some special sect of Jews.
Heraclius was married twice: first to Fabia Eudokia, a daughter of Rogatus, and then to his niece Martina. He had two children with Fabia and at least nine with Martina, most of whom were sickly children.[A 5] Of Martina's children at least two were disabled, which was seen as punishment for the illegality of the marriage: Fabius (Flavius) had a paralyzed neck and Theodosios, who was a deaf-mute, married Nike, daughter of Persian general Shahrbaraz or daughter of Niketas, cousin of Heraclius.
Two of Heraclius' children would become Emperor: Heraclius Constantine (Constantine III), his son from Eudokia, from 613 – 641, and Martina's son Constantine Heraclius (Heraklonas), from 638 – 641.
Heraclius had at least one illegitimate son, John Athalarichos, who conspired a plot against Heraclius with his cousin, the magister Theodorus, and the Armenian noble David Saharuni.[A 6] When Heraclius discovered the plot, he had Athalarichos' nose and hands cut off, and he was exiled to Prinkipo, one of the Princes' Islands. Theodorus had the same treatment but was sent to Gaudomelete (possibly modern day Gozo Island) with additional instructions to cut off one leg.
During the last years of Heraclius' life, it became evident that a struggle was taking place between Heraclius Constantine and Martina, who was trying to position her son Heraklonas in line for the throne. When Heraclius died, he willed the empire to both Heraclius Constantine and Heraklonas to rule jointly with Martina as Empress.
↑ Byzantine Empire is a relatively modern term for what in Heraclius' time was referred to the Roman Empire or Eastern Roman Empire. The earliest use of the term, "Byzantine" was 900 years after Heraclius' death. It first appeared in 1557, when German historian Hieronymus Wolf coined the term when he published his work Corpus Historiæ Byzantinæ. Later French historians popularized the term. Other civilizations of the time referred to Byzantine Empire as the Eastern Roman Empire or just the Roman Empire. In the Persian, Islamic, and Slavic worlds, the Empire's Roman identity was generally accepted. In the Islamic world it was known primarily as روم (Rûm "Rome"). For more information see Nomenclature of the Byzantine Empire.
↑ His father referred to retrospectively as Heraclius the Elder.
↑ Also referred to as Khosrow II, Chosroes II, or Xosrov II in classical sources, sometimes called Parvez, "the Ever Victorious" (in Persian: خسرو پرویز).
↑ The mint of Nicomedia ceased operating in 613, and Rhodes fell to the invaders in 622/623.
↑ The number and order of Heraclius' children by Martina is unsure. Some sources say nine children and others saying ten.
↑ The illegitimate son is recorded by a number of different spellings including: Atalarichos, Athalaric, At'alarik, etc.
1 2 Fox, Clifton R. (March 29, 1996). "What, if anything, is a Byzantine?". Lone Star College–Tomball. Retrieved October 21, 2009.
↑ Seleznyov N.N. "Heraclius and Ishoʿyahb II", Simvol 61: Syriaca-Arabica-Iranica. (Paris-Moscow, 2012), pp. 280–300.
↑ Treadgold 1997, p. 287.
↑ "Sasanian Dynasty". Encyclopædia Iranica. 20 July 2005. Retrieved 17 August 2013.
1 2 Kaegi 2003, pp. 24–25.
1 2 Mitchell 2007, p. 411.
↑ Charles 2007, p. 177.
1 2 Kaegi 2003, p. 106.
1 2 3 Gibbon 1998, p. 777.
1 2 Speck 1984, p. 178.
↑ Greatrex-Lieu 2002, pp. II, 194–195.
↑ Greatrex-Lieu 2002, p. II, 196.
↑ Greatrex-Lieu 2002, p. II, 197.
1 2 Greatrex-Lieu 2002, p. II, 198.
↑ Theophanes 1997, pp. 303.12–304.13.
↑ Treadgold 1997, p. 294.
↑ Theophanes 1997, pp. 304.25–306.7.
↑ Greatrex-Lieu 2002, p. II, 199.
↑ Theophanes 1997, pp. 307.19–308.25.
↑ Greatrex-Lieu 2002, pp. II, 202–205.
↑ The Oxford Dictionary of Byzantium, article Cartagena, p. 384.
↑ Cameron 1979, pp. 5–6, 20–22.
↑ Treadgold 1997, p. 298.
1 2 Baynes 1912, p. 288.
↑ Kouymjian 1983, pp. 635–642.
↑ Kaegi 2003, p. 227.
↑ Beckwith 2009, p. 121.
↑ Foss 1975, pp. 746–747.
↑ Milani 2004, p. 15.
↑ Lewis 2002, pp. 43–44.
↑ Kaegi 2003, p. 231.
1 2 3 Kaegi 2003, p. 230.
↑ Kaegi 2003, p. 233.
↑ Collins 2004, p. 128.
1 2 Bury 2005, p. 251.
↑ Davis 1990, p. 260.
1 2 Kaegi, p. 319.
↑ De Administrando Imperio, ch. 32 [Of the Serbs and of the country they now dwell in.]: "the emperor brought elders from Rome and baptized them and taught them fairly to perform the works of piety and expounded to them the faith of the Christians."
↑ Deanesly 1969, p. 491.
↑ Haldon 1997, pp. 208ff.
↑ Milman-Guizot 1862, p. 398.
↑ Thomson 1999, p. 221.
↑ Frolow 1953, pp. 88–105.
1 2 Zuckerman, Constantin (2013). Heraclius and the return of the Holy Cross. Constructing the Seventh Century. Travaux et mémoires. Paris: Association des amis du Centre d'histoire et civilisation de Byzance. pp. 197–218. ISBN 978-2-916716-45-9. Retrieved 8 January 2016.
↑ Baert 2008, pp. 03–20.
↑ Souza 2015, pp. 27–38.
1 2 El-Cheikh 1999, p. 7.
↑ Summary of the plot of the poem at the Swahili Manuscripts Project at the School of Oriental and African Studies of London.
1 2 El-Cheikh 1999, p. 9.
↑ El-Cheikh 1999, p. 12.
↑ Conrad 2002, p. 120.
↑ Haykal 1994, p. 402.
↑ El-Cheikh 1999, p. 14.
↑ El-Cheikh 1999, p. 54.
↑ Walter Emil Kaegi (27 March 2003). Heraclius, Emperor of Byzantium. Cambridge University Press. p. 236. ISBN 978-0-521-81459-1. Retrieved 23 March 2013.
↑ Kaegi 2003, p. 229.
↑ Alexander 1977, p. 230.
↑ Spatharakis 1976, p. 19.
1 2 3 Bellinger-Grierson 1992, p. 385.
↑ Kaegi 2003, p. 120.
↑ Charanis 1959, p. 34.
↑ Sebeos; Translated from Old Armenian by Robert Bedrosian. "Chapter 29". Sebeos History: A History of Heraclius. History Workshop. Retrieved October 22, 2009.
1 2 Nicephorus 1990, p. 73.
Alexander, Suzanne Spain (April 1977). "Heraclius, Byzantine Imperial Ideology, and the David Plates". Medieval Academy of America. 52 (2): 217–237. JSTOR 2850511.
Baert, Barbara (2008). "Héraclius, l'Exaltation de la Croix et le Mont-Saint-Michel au XIe siècle: une lecture attentive du ms. 641 de la Pierpont Morgan Library à New York". Cahiers de Civilisation médiévale (51): 03–20.
Bellinger, Alfred Raymond; Grierson, Philip. Catalogue of the Byzantine coins in the Dumbarton Oaks Collection and in the Whittemore Collection, Volume 2, Parts 1–2 (1992 ed.). Dumbarton Oaks. ISBN 0-88402-024-X.
El-Cheikh, Nadia Maria (1999). "Muḥammad and Heraclius: A Study in Legitimacy". Studia Islamica. Maisonneuve & Larose. 62 (89): 5–21. doi:10.2307/1596083. ISSN 0585-5292.
Frolow, Anatole (1953). La Vraie Croix et les expéditions d'Héraclius en Perse. Revue des études byzantines. pp. 88–105.
Kouymjian, Dickran. "Ethnic Origins and the 'Armenian' Policy of Emperor Heraclius". Revue des Études Arméniennes (vol. XVII, 1983 ed.).
Souza, Guilherme Queiroz de (2015). "Heraclius, emperor of Byzantium" (PDF). Revista Digital de Iconografía Medieval. 7 (14): 27–38.
Speck, Paul (1984). "Ikonoklasmus und die Anfänge der Makedonischen Renaissance". Varia 1 (Poikila Byzantina 4). Rudolf Halbelt. pp. 175–210.
Wikisource has the text of the 1911 Encyclopædia Britannica article Heraclius.