@Override
 public boolean onOptionsItemSelected(MenuItem item) {
   switch (item.getItemId()) {
     case android.R.id.home:
       onBackPressed();
       return true;
     case R.id.action_reply:
       Intent i =
           new Intent(getApplicationContext(), "voice".equals(type) ? call.class : sms.class);
       i.putExtra("from", original_called);
       i.putExtra("to", original_caller);
       i.putExtra("message_id", message_id);
       startActivity(i);
       return true;
     case R.id.action_delete:
       OpenVBX.status(context, "Deleting...");
       AsyncHttpClient client = new AsyncHttpClient();
       client.addHeader("Accept", "application/json");
       client.setBasicAuth(OpenVBX.getEmail(), OpenVBX.getPassword());
       RequestParams params = new RequestParams();
       params.put("archived", "true");
       client.post(
           OpenVBX.getServer() + "/messages/details/" + message_id,
           params,
           new JsonHttpResponseHandler() {
             @Override
             public void onSuccess(int statusCode, Header[] headers, JSONObject res) {
               Intent i = new Intent();
               i.putExtra("message_id", message_id);
               setResult(RESULT_OK, i);
               finish();
             }
           });
       return true;
   }
   return super.onOptionsItemSelected(item);
 }
 /**
  * Sets basic authentication for the request. Uses AuthScope.ANY. This is the same as
  * setBasicAuth('username','password',AuthScope.ANY)
  *
  * @param username
  * @param password
  */
 public void setBasicAuth(String user, String pass) {
   AuthScope scope = AuthScope.ANY;
   setBasicAuth(user, pass, scope);
 }
 /**
  * Sets basic authentication for the request. Uses AuthScope.ANY. This is the same as
  * setBasicAuth('username','password',AuthScope.ANY)
  *
  * @param username Basic Auth username
  * @param password Basic Auth password
  */
 public void setBasicAuth(String username, String password) {
   AuthScope scope = AuthScope.ANY;
   setBasicAuth(username, password, scope);
 }
  public void sendAllData() {
    String Url = "https://liborgs-1139.appspot.com/admin/upload_books";
    String username = "******";
    String password = "******";

    Cursor cursor =
        mContext
            .getContentResolver()
            .query(
                Media.EXTERNAL_CONTENT_URI,
                new String[] {
                  Media.DATA, Media.DATE_ADDED, MediaStore.Images.ImageColumns.ORIENTATION
                },
                Media.DATE_ADDED,
                null,
                "date_added ASC");
    if (cursor != null && cursor.moveToLast()) {
      Uri fileURI = Uri.parse(cursor.getString(cursor.getColumnIndex(Media.DATA)));
      fileSrc = fileURI.toString();
      cursor.close();
    }

    // Bitmap compressedImage = BitmapFactory.decodeStream(new
    // ByteArrayInputStream(out.toByteArray()));
    AsyncHttpClient client = new AsyncHttpClient();
    client.setBasicAuth(username, password);
    RequestParams params = new RequestParams();
    params.put("title", bookName);
    params.put("author", authorName);
    params.put("isbn", isbn);
    try {
      params.put("pic", storeImage());
    } catch (FileNotFoundException e) {
      Log.d("MyApp", "File not found!!!" + fileSrc);
    }
    client.post(
        Url,
        params,
        new JsonHttpResponseHandler() {
          @Override
          public void onSuccess(int statusCode, Header[] headers, JSONObject responseBody) {
            String message = "";
            try {
              message = responseBody.getString("message");
            } catch (JSONException e) {
              e.printStackTrace();
            }
            new AlertDialog.Builder(mContext)
                .setTitle("Sending")
                .setMessage(message)
                .setPositiveButton(
                    android.R.string.yes,
                    new DialogInterface.OnClickListener() {
                      public void onClick(DialogInterface dialog, int which) {}
                    })
                .show();
          }

          @Override
          public void onFailure(
              int statusCode, Header[] headers, String errorResponse, Throwable error) {
            JSONObject responseBody = null;
            try {
              responseBody = new JSONObject(errorResponse);
            } catch (JSONException e) {
              e.printStackTrace();
            }
            String message = "";
            try {
              message = responseBody.getString("message");
            } catch (JSONException e) {
              e.printStackTrace();
            }
            new AlertDialog.Builder(mContext)
                .setTitle("Sending")
                .setMessage(message)
                .setPositiveButton(
                    android.R.string.yes,
                    new DialogInterface.OnClickListener() {
                      public void onClick(DialogInterface dialog, int which) {}
                    })
                .show();
          }
        });
  }
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    try {
      getActionBar().setDisplayHomeAsUpEnabled(true);
    } catch (final NullPointerException e) {
      e.printStackTrace();
    }
    setContentView(R.layout.message);
    OpenVBX = (OpenVBXApplication) getApplication();
    progress = (LinearLayout) findViewById(R.id.progress);
    Bundle extras = getIntent().getExtras();
    message_id = extras.getInt("id");
    users = new ArrayList<User>();
    add = (Button) findViewById(R.id.add);
    annotationList = (ListView) findViewById(R.id.annotations);
    annotations = new ArrayList<Annotation>();
    annotationAdapter = new AnnotationAdapter(this, R.layout.annotation, annotations);
    annotationList.setAdapter(annotationAdapter);
    status = (Spinner) findViewById(R.id.status);
    ArrayAdapter<String> statusAdapter =
        new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, statuses);
    statusAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    status.setAdapter(statusAdapter);
    status.setOnItemSelectedListener(
        new OnItemSelectedListener() {
          public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            AsyncHttpClient client = new AsyncHttpClient();
            client.addHeader("Accept", "application/json");
            client.setBasicAuth(OpenVBX.getEmail(), OpenVBX.getPassword());
            RequestParams params = new RequestParams();
            params.put("ticket_status", statuses[pos].toLowerCase());
            client.post(
                OpenVBX.getServer() + "/messages/details/" + message_id,
                params,
                new JsonHttpResponseHandler() {
                  @Override
                  public void onSuccess(int statusCode, Header[] headers, JSONObject res) {}
                });
          }

          public void onNothingSelected(AdapterView<?> parent) {}
        });
    assigned = (Spinner) findViewById(R.id.assigned);
    userAdapter = new UserAdapter(this, users);
    assigned.setAdapter(userAdapter);
    assigned.setOnItemSelectedListener(
        new OnItemSelectedListener() {
          public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            AsyncHttpClient client = new AsyncHttpClient();
            client.addHeader("Accept", "application/json");
            client.setBasicAuth(OpenVBX.getEmail(), OpenVBX.getPassword());
            RequestParams params = new RequestParams();
            params.put("assigned", "" + users.get(pos).getId());
            client.post(
                OpenVBX.getServer() + "/messages/details/" + message_id,
                params,
                new JsonHttpResponseHandler() {
                  @Override
                  public void onSuccess(int statusCode, Header[] headers, JSONObject res) {}
                });
          }

          public void onNothingSelected(AdapterView<?> parent) {}
        });
    progress.setVisibility(View.VISIBLE);
    AsyncHttpClient client = new AsyncHttpClient();
    client.addHeader("Accept", "application/json");
    client.setBasicAuth(OpenVBX.getEmail(), OpenVBX.getPassword());
    client.get(
        OpenVBX.getServer() + "/messages/details/" + message_id,
        new JsonHttpResponseHandler() {
          @Override
          public void onSuccess(int statusCode, Header[] headers, JSONObject res) {
            try {
              original_called = res.getString("original_called");
              original_caller = res.getString("original_caller");
              ((TextView) findViewById(R.id.caller)).setText(res.getString("caller"));
              ((TextView) findViewById(R.id.received_time))
                  .setText(
                      DateFormat.format(
                              "M/d/yy h:mm AA",
                              new SimpleDateFormat("yyyy-MMM-dd'T'HH:mm:ssZ")
                                  .parse(res.getString("received_time")))
                          .toString());
              TextView folder = (TextView) findViewById(R.id.folder);
              folder.setText(res.getString("folder"));
              if ("".equals(res.getString("folder"))) folder.setVisibility(View.GONE);
              ((TextView) findViewById(R.id.summary)).setText(res.getString("summary"));
              type = res.getString("type");
              if ("voice".equals(type)) {
                for (int i = 0; i < statuses.length; i++)
                  if (statuses[i].toLowerCase().equals(res.getString("ticket_status")))
                    status.setSelection(i);
                status.setVisibility(View.VISIBLE);
                if (!"".equals(res.getString("folder"))) {
                  JSONArray active_users = res.getJSONArray("active_users");
                  users.add(new User(0, "Select a", "user"));
                  for (int i = 0; i < active_users.length(); i++)
                    users.add(
                        new User(
                            active_users.getJSONObject(i).getInt("id"),
                            active_users.getJSONObject(i).getString("first_name"),
                            active_users.getJSONObject(i).getString("last_name")));
                  userAdapter.notifyDataSetChanged();
                  if (!"null".equals(res.getString("assigned")))
                    assigned.setSelection(userAdapter.indexOf(res.getInt("assigned")));
                  assigned.setVisibility(View.VISIBLE);
                }
                add.setVisibility(View.VISIBLE);
                JSONArray annotation_items = res.getJSONObject("annotations").getJSONArray("items");
                for (int i = 0; i < annotation_items.length(); i++)
                  annotations.add(
                      new Annotation(
                          annotation_items.getJSONObject(i).getInt("id"),
                          annotation_items.getJSONObject(i).getString("first_name"),
                          annotation_items.getJSONObject(i).getString("last_name"),
                          annotation_items.getJSONObject(i).getString("description")));
                if (annotations.size() > 0) {
                  annotationAdapter.notifyDataSetChanged();
                  annotationList.setVisibility(View.VISIBLE);
                }
                status.setVisibility(View.VISIBLE);
                play = (ImageView) findViewById(R.id.play);
                seekBar = (SeekBar) findViewById(R.id.seekbar);
                seekBar.setOnTouchListener(
                    new OnTouchListener() {
                      public boolean onTouch(View v, MotionEvent event) {
                        if (mediaPlayer.isPlaying()) {
                          SeekBar sb = (SeekBar) v;
                          mediaPlayer.seekTo(sb.getProgress());
                        }
                        return false;
                      }
                    });
                play.setOnTouchListener(
                    new OnTouchListener() {
                      public boolean onTouch(View v, MotionEvent event) {
                        mediaPlayer.start();
                        updateProgress =
                            new Thread(
                                new Runnable() {
                                  public void run() {
                                    Thread currentThread = Thread.currentThread();
                                    int curr = mediaPlayer.getCurrentPosition();
                                    int total = mediaPlayer.getDuration();
                                    seekBar.setProgress(curr);
                                    seekBar.setMax(total);
                                    while (currentThread == updateProgress
                                        && mediaPlayer != null
                                        && mediaPlayer.isPlaying()) {
                                      try {
                                        curr = mediaPlayer.getCurrentPosition();
                                        seekBar.setProgress(curr);
                                        Thread.sleep(100);
                                      } catch (InterruptedException e) {
                                        e.printStackTrace();
                                      }
                                    }
                                    seekBar.setProgress(total);
                                  }
                                });
                        updateProgress.start();
                        return false;
                      }
                    });
                mediaPlayer = new MediaPlayer();
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                // TODO - Import Twilio SSL certificate for older versions of Android
                mediaPlayer.setDataSource(res.getString("recording_url").replace("https", "http"));
                mediaPlayer.setOnPreparedListener(
                    new MediaPlayer.OnPreparedListener() {
                      @Override
                      public void onPrepared(MediaPlayer mp) {
                        ((RelativeLayout) findViewById(R.id.audio)).setVisibility(View.VISIBLE);
                      }
                    });
                mediaPlayer.prepareAsync();
              }
              progress.setVisibility(View.GONE);
            } catch (JSONException e) {
              e.printStackTrace();
            } catch (ParseException e) {
              e.printStackTrace();
            } catch (IllegalArgumentException e) {
              e.printStackTrace();
            } catch (IllegalStateException e) {
              e.printStackTrace();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        });
    add.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View view) {
            Intent i = new Intent(getApplicationContext(), annotate.class);
            i.putExtra("id", message_id);
            startActivityForResult(i, 0);
          }
        });
  }
 public void setBasicAuth(String str, String str2) {
   setBasicAuth(str, str2, AuthScope.ANY);
 }