@Override
    public void run() {
      mState = RUNNING;
      total = 0;
      while (mState == RUNNING) {
        // The method Thread.sleep throws an InterruptedException if Thread.interrupt()
        // were to be issued while thread is sleeping; the exception must be caught.
        try {
          // Control speed of update (but precision of delay not guaranteed)
          Thread.sleep(delay);
        } catch (InterruptedException e) {
          LogWriter.writeException(TaxProgramsManageActivity.this, "Thread was Interrupted", e);
        }

        // Send message (with current value of  total as data) to Handler on UI thread
        // so that it can update the progress bar.
        // proceed one institution at a time
        work();

        Message msg = mHandler.obtainMessage();
        Bundle b = new Bundle();
        b.putInt("total", total);
        msg.setData(b);
        mHandler.sendMessage(msg);

        total++; // Count up
      }
    }
  protected void onResume() {
    super.onResume();

    try {
      storage = new SharedStorage(this);

      // populate data but only for the first time !
      if (firstRun) {
        // populate with the values
        loadInfo();

        firstRun = false;
      }

    } catch (Exception ex) {
      DKDialog.ShowMessage(
          this,
          Translate.translate("Error"),
          Translate.translate("Reading settings activitiy failed!"),
          Translate.translate("OK"),
          Translate.translate("Cancel"));

      LogWriter.writeException(this, ex.getMessage(), ex);
    }
  }
 public Object getItem(int position) {
   try {
     return array.get(position);
   } catch (JSONException ex) {
     LogWriter.writeException(_context, "Failed to get Item!", ex);
     return null;
   }
 }
  /** Loads detailed tax payer info */
  public void loadInfo() {
    // try to connect
    try {

      // Get TaxPayer Income first:
      HTTPConnection connection = new HTTPConnection(storage.getServerURL());

      JSONObject response = connection.connectJSON(Engine.getTaxPayerInfo(TaxPayerID));
      storage.setLastServerResponse(response.toString());

      if (!response.getString("result").equals("OK")) {
        throw new Exception("Invalid response from server = " + response.getString("data"));
      }

      // read results
      JSONObject data = response.getJSONArray("data").getJSONObject(0);

      // Fill the activity with results
      TaxIncome = data.getDouble("Income");
      tbTaxYearIncome.setText(String.valueOf(TaxIncome) + " \u20AC");
      // Get Tax stats:

      response = connection.connectJSON(Engine.TaxProgramGrid(TaxYearID, TaxPayerID));
      storage.setLastServerResponse(response.toString());

      // retrieve the array of items
      array = response.getJSONArray("data");

      recalculateTaxRate();

      // only after array is loaded - show the list
      adapter = new TaxYearProgramsAdapter(this);
      tableTaxProgramManage.setAdapter(adapter);

    } catch (Exception ex) {
      DKDialog.ShowMessage(
          this,
          Translate.translate("Error"),
          Translate.translate("Connection failed: " + ex.getMessage()),
          Translate.translate("OK"),
          Translate.translate("Cancel"));

      LogWriter.writeException(this, ex.getMessage(), ex);

      storage.setLastServerResponse(ex.toString());
    }
  }
  /** Called when activity is created */
  public void onCreated() {
    try {
      // find ui elements on the form:
      tbTaxYearIncome = (TextView) this.getElementById(R.id.tbTaxYearIncome);
      tbTaxYearStats = (TextView) this.getElementById(R.id.tbTaxYearStats);
      tbTaxYearTax = (TextView) this.getElementById(R.id.tbTaxYearTax);
      tableTaxProgramManage = (ListView) this.getElementById(R.id.listViewTaxPayerProgramManage);

      btnCancel = (Button) this.getElementById(R.id.btnCancel);
      btnSubmit = (Button) this.getElementById(R.id.btnSubmit);

      btnCancel.setVisibility(View.GONE); // only when it was submitted first time
      btnSubmit.setVisibility(View.GONE); // only when there is anything to submit

      btnSubmit.setOnClickListener(submitClicked);
      btnCancel.setOnClickListener(cancelClicked);

      // tbTaxYearIncome				= (ListView)this.getElementById(R.id.listViewTaxPayerYears);

      // lvTaxYearGrid.setOnItemClickListener( clickListener );

      TaxPayerID = getIntent().getExtras().getInt(TaxYearStatsActivity.EXTRA_INT_TAX_PAYER_ID);
      TaxYearID = getIntent().getExtras().getInt(TaxYearStatsActivity.EXTRA_INT_TAX_YEAR_ID);
      YearValue = getIntent().getExtras().getInt(TaxYearStatsActivity.EXTRA_INT_TAX_YEAR_VALUE);

      // specify changes
      // lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items ));

      tbTaxYearStats.setText("Manage year: " + YearValue);
    } catch (Exception e) {
      DKDialog.ShowMessage(
          this,
          Translate.translate("Error"),
          Translate.translate("Loading default activitiy failed!"),
          Translate.translate("OK"),
          Translate.translate("Cancel"));

      LogWriter.writeException(this, e.getMessage(), e);
    }
  }
    public void work() {
      // get the first institution
      if (total < _selected.size()) {
        int id = _selected.get(total);

        double firstPrice = 0;
        double currentPrice = 0;
        double avgPriceForProgram =
            (TaxIncome / _selected.size())
                * 0.2; // this is a price that is calculate for programs, average 20% of income

        // start negotiating
        try {
          // Get initial price of program
          LogWriter.writeInfo(
              "Agent -> Get program price: avgPerProgram = "
                  + avgPriceForProgram
                  + ", program ID = "
                  + id);

          HTTPConnection connection = new HTTPConnection(storage.getServerURL());

          JSONObject response =
              connection.connectJSON(Engine.AgentRequestProgramPrice(_taxYearID, _taxPayerID, id));
          storage.setLastServerResponse(response.toString());

          if (!response.getString("result").equals("OK")) {
            throw new Exception("Invalid response from server = " + response.getString("data"));
          }

          // read results
          JSONObject data = response.getJSONObject("data");

          int type = data.getInt("Type");
          currentPrice = data.getDouble("Price");
          firstPrice = currentPrice;
          double lowestPrice = firstPrice;
          double newPrice = 0;

          if (type == 1) {
            // this is final offer - we need to set the result - and offer to client
            LogWriter.writeInfo("Agent -> Final offer = " + currentPrice + " program ID = " + id);
            setProgramPrice(id, currentPrice);
          } else {
            double tries = 0.5;

            while (true) {
              if (type == 1) {
                // this is final offer - we need to set the result - and offer to client
                LogWriter.writeInfo(
                    "Agent -> Final offer = " + currentPrice + " program ID = " + id);
                setProgramPrice(id, currentPrice);
                break;
              }

              // we can try to continue more - to get a better deal if it is more than we want
              if (newPrice > firstPrice) {
                // obiously we cannot get betterp rice
                LogWriter.writeInfo(
                    "Agent -> Cannot go higher = " + lowestPrice + " program ID = " + id);
                setProgramPrice(id, lowestPrice);
                break;
              } else if (currentPrice > avgPriceForProgram) {

                // Get initial price of program
                connection = new HTTPConnection(storage.getServerURL());

                newPrice = avgPriceForProgram * 0.1 + avgPriceForProgram * (tries);

                LogWriter.writeInfo(
                    "Agent -> Askin better price = " + newPrice + " program ID = " + id);

                // lowe the price by 90%
                response =
                    connection.connectJSON(
                        Engine.AgentRequestProgramLowerPrice(
                            _taxYearID, _taxPayerID, id, newPrice));
                storage.setLastServerResponse(response.toString());

                if (!response.getString("result").equals("OK")) {
                  throw new Exception(
                      "Invalid response from server = " + response.getString("data"));
                }

                // read results
                data = response.getJSONObject("data");

                type = data.getInt("Type");
                currentPrice = data.getDouble("Price");

                LogWriter.writeInfo(
                    "Agent -> currentPrice = "
                        + currentPrice
                        + " lowestPrice = "
                        + lowestPrice
                        + " program ID = "
                        + id);

                if (currentPrice < lowestPrice) {
                  lowestPrice = currentPrice;
                }

                tries += 0.1;
              } else {
                // this is ok, we can accept that
                LogWriter.writeInfo(
                    "Agent -> Best offer = " + currentPrice + " program ID = " + id);
                setProgramPrice(id, currentPrice);
                break;
              }
            }
          }

        } catch (Exception ex) {
          // this will exit

          Message msg = mHandler.obtainMessage();
          Bundle b = new Bundle();
          b.putString("error", "Connection failed: " + ex.getMessage());
          msg.setData(b);
          mHandler.sendMessage(msg);

          LogWriter.writeException(TaxProgramsManageActivity.this, ex.getMessage(), ex);
        }
      }
    }
    public View getView(int position, View convertView, ViewGroup parent) {
      if ((array == null) || (array.length() == 0) || (position >= array.length())) {
        TextView tv = new TextView(_context);
        tv.setText("No items.");

        return tv;
      } else {

        final JSONObject currentObject = (JSONObject) getItem(position);

        View _inflatedView = _inflater.inflate(R.layout.managegridlayout, null);

        TextView tvID = (TextView) _inflatedView.findViewById(R.id.textview_stats_id_value);
        TextView tvInstitution =
            (TextView) _inflatedView.findViewById(R.id.textview_stats_institutionname);
        TextView tvProgram = (TextView) _inflatedView.findViewById(R.id.textview_stats_programname);
        TextView tvMinYears =
            (TextView) _inflatedView.findViewById(R.id.textview_stats_minimumyears_value);
        TextView tvYearsLeft =
            (TextView) _inflatedView.findViewById(R.id.textview_stats_yearsremaining_value);
        TextView tvYearsTaxRate =
            (TextView) _inflatedView.findViewById(R.id.textview_stats_taxrate_value);

        try {
          CheckBox cbSelect =
              (CheckBox) _inflatedView.findViewById(R.id.checkbox_taxprogram_select);

          tvID.setText(currentObject.getString("ID"));
          tvInstitution.setText(currentObject.getString("Institution"));
          tvProgram.setText(currentObject.getString("Name"));
          tvYearsLeft.setText(currentObject.getString("YearsLeft"));
          tvMinYears.setText(currentObject.getString("MinimumYears"));

          int isSelected = currentObject.getInt("IsSelected");

          if (btnCancel.getVisibility() == View.VISIBLE) {
            cbSelect.setEnabled(false);
          } else {
            cbSelect.setEnabled(true);
          }

          switch (isSelected) {
            case 0: // do nothing - it is not selected
              break;

            case 1: // it is selected and can be unselected
              cbSelect.setChecked(true);
              break;

            case 2: // it is selected and cannot be unselected
              cbSelect.setChecked(true);
              cbSelect.setEnabled(false);
              break;

            default:
              throw new Exception("Unknown IsSelected = " + String.valueOf(isSelected));
          }

          cbSelect.setOnCheckedChangeListener(
              new OnCheckedChangeListener() {
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                  try {
                    currentObject.put("IsSelected", isChecked == true ? 1 : 0);
                  } catch (JSONException ex) {
                    LogWriter.writeException(_context, "Failed to set checkbox!", ex);
                  }
                }
              });

          double taxAmount = currentObject.getDouble("TaxRate");
          double percent = (taxAmount / TaxIncome) * 100;

          DecimalFormat df = new DecimalFormat("#.##");

          tvYearsTaxRate.setText(df.format(percent) + " % (" + df.format(taxAmount) + " \u20AC )");
        } catch (Exception ex) {
          LogWriter.writeException(_context, "Failed to show Item!", ex);
        }

        return _inflatedView;
      }
    }
        public void onClick(View arg0) {

          if (btnCancel.getVisibility() == View.VISIBLE) {
            // Confirmation of existing programs

            try {

              for (int i = 0; i < array.length(); i++) {
                JSONObject object = (JSONObject) array.get(i);

                if (object.getInt("IsSelected") > 0) {
                  // Get TaxPayer Income first:
                  HTTPConnection connection = new HTTPConnection(storage.getServerURL());

                  JSONObject response =
                      connection.connectJSON(
                          Engine.ApproveProgramPrice(
                              TaxYearID,
                              TaxPayerID,
                              object.getInt("ID"),
                              object.getDouble("TaxRate")));
                  storage.setLastServerResponse(response.toString());

                  if (!response.getString("result").equals("OK")) {
                    throw new Exception(
                        "Invalid response from server = " + response.getString("data"));
                  }

                  // read results
                  int result = (Integer) response.getInt("data");
                }
              }

              Intent resultIntent = new Intent();
              setResult(Activity.RESULT_OK, resultIntent);
              TaxProgramsManageActivity.this.finish();
              /*
              	DKDialog.ShowMessage( TaxProgramsManageActivity.this,
              Translate.translate("Thank you") ,
              Translate.translate("All programs have been confirmed!"),
              Translate.translate("OK"),
              Translate.translate("Cancel"));
              	*/

            } catch (Exception ex) {
              DKDialog.ShowMessage(
                  TaxProgramsManageActivity.this,
                  Translate.translate("Error"),
                  Translate.translate("Connection failed: " + ex.getMessage()),
                  Translate.translate("OK"),
                  Translate.translate("Cancel"));

              LogWriter.writeException(TaxProgramsManageActivity.this, ex.getMessage(), ex);

              storage.setLastServerResponse(ex.toString());
            }
          } else {

            // 1-st submit

            selected = new ArrayList<Integer>();

            try {

              for (int i = 0; i < array.length(); i++) {

                JSONObject object = array.getJSONObject(i);

                if (object.getInt("IsSelected") > 0) {
                  selected.add(object.getInt("ID"));
                } else {
                  // clear the price
                  object.put("TaxRate", 0.0);
                }
              }

              if (selected.size() == 0) {
                DKDialog.ShowMessage(
                    TaxProgramsManageActivity.this,
                    Translate.translate("Error"),
                    Translate.translate("Nothing to submit, no programs selected!"),
                    Translate.translate("OK"),
                    Translate.translate("Cancel"));
              } else {
                typeBar = 1;
                showDialog(typeBar);
              }
            } catch (Exception ex) {
              DKDialog.ShowMessage(
                  TaxProgramsManageActivity.this,
                  Translate.translate("Error"),
                  Translate.translate("Failed to count selected values! " + ex.getMessage()),
                  Translate.translate("OK"),
                  Translate.translate("Cancel"));

              LogWriter.writeException(TaxProgramsManageActivity.this, ex.getMessage(), ex);
            }
          }
        }