me.ububble.speakall.fragment.ConversationChatFragment.java Source code

Java tutorial

Introduction

Here is the source code for me.ububble.speakall.fragment.ConversationChatFragment.java

Source

package me.ububble.speakall.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.drawable.GradientDrawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.PowerManager;
import android.os.Vibrator;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v8.renderscript.*;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.activeandroid.ActiveAndroid;
import com.activeandroid.query.Delete;
import com.activeandroid.query.Select;
import com.activeandroid.query.Update;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponseException;
import com.loopj.android.http.BinaryHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.netcompss.ffmpeg4android.CommandValidationException;
import com.netcompss.ffmpeg4android.GeneralUtils;
import com.netcompss.ffmpeg4android.Prefs;
import com.netcompss.loader.LoadJNI;
import com.nhaarman.supertooltips.ToolTip;
import com.nhaarman.supertooltips.ToolTipRelativeLayout;
import com.nhaarman.supertooltips.ToolTipView;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorSet;
import com.nineoldandroids.animation.ObjectAnimator;
import com.nineoldandroids.animation.ValueAnimator;
import com.nineoldandroids.view.ViewHelper;
import com.squareup.picasso.Picasso;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.provider.ContactsContract.Contacts.Data;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

import butterknife.ButterKnife;
import butterknife.InjectView;
import me.ububble.speakall.R;
import me.ububble.speakall.activity.MainActivity;
import me.ububble.speakall.util.*;
import me.ububble.speakall.util.model.Chats;
import me.ububble.speakall.util.model.Contact;
import me.ububble.speakall.util.model.Message;
import me.ububble.speakall.util.model.User;

public class ConversationChatFragment extends Fragment
        implements View.OnClickListener, View.OnTouchListener, LocationListener {

    private boolean setted = false;
    public Contact contact;
    private Activity activity;
    private Finder f;

    public int mensajesTotal;
    public int mensajesOffset = 20;
    public int mensajesLimit = 20;
    int prevSize = 0;
    int keyBoardHeight;
    public boolean isShowKeyboard = false;
    boolean scrollOnBottom = false;
    int scrollValue = 0;
    int messagesValuePrev = 0;
    int scrollHeight = 0;
    String messageSelected = null;
    boolean translate = true;
    public boolean isShowCustomKeyboard = false;
    boolean menuAdjunt = false;
    boolean tiempoMensaje;
    HashMap<String, ValueAnimator> animaciones = new HashMap<String, ValueAnimator>();
    String fechaAnterior = "";
    View itemAnterior = null;
    CountDownTimer writingCounter = null;
    public User u;
    private View dialogView;
    private AlertDialog finderDialog;
    boolean longclick = false;
    long millisToWriting = 0;
    Handler handlerContactStatus;
    Runnable runnableContactStatus;
    boolean dontClose = false;
    SeekBar activeAudioSeekBarr = null;
    TextView activeAudioTime = null;
    TextView activePlayer = null;
    LocationManager milocManager = null;
    LoadJNI vk;

    @InjectView(R.id.scroll)
    ScrollView sv;
    @InjectView(R.id.keyboard_layout)
    public LinearLayout keyboardLayout;
    @InjectView(R.id.messages_list_content_layout)
    public ScrollView messagesListScroll;
    @InjectView(R.id.messages_list_content)
    public LinearLayout messagesList;
    @InjectView(R.id.message_text)
    public CustomEdittext messageText;
    @InjectView(R.id.icn_message_send_divider)
    View messageSednDivider;
    @InjectView(R.id.icn_message_send)
    public TextView messageSend;
    @InjectView(R.id.icn_message_translate)
    TextView messageTranslate;
    @InjectView(R.id.icn_message_clock)
    TextView messageClock;
    @InjectView(R.id.message_menu)
    LinearLayout messageMenu;
    @InjectView(R.id.conversation_background)
    ImageView backgroundChat;

    @InjectView(R.id.temporizador_label)
    TextView temporLanel;
    @InjectView(R.id.custom_keyboard)
    public RelativeLayout customKeyboardLayout;
    @InjectView(R.id.temporizador_cancel)
    Button temporizadorCancel;
    @InjectView(R.id.temporizador_acept)
    Button temporizadorAcept;
    @InjectView(R.id.temporizador_seek)
    HoloCircleSeekBar temporizadorSeek;

    @InjectView(R.id.adjunt_layout)
    LinearLayout adjuntLayout;
    @InjectView(R.id.adjunt_contact)
    TextView adjuntContact;
    @InjectView(R.id.adjunt_photo)
    TextView adjuntPhoto;
    @InjectView(R.id.adjunt_audio)
    TextView adjuntAudio;
    @InjectView(R.id.adjunt_location)
    TextView adjuntLocation;
    @InjectView(R.id.adjunt_video)
    TextView adjuntVideo;
    @InjectView(R.id.adjunt_image)
    TextView adjuntImage;
    @InjectView(R.id.add_to_contacts)
    TextView addToContacts;

    @InjectView(R.id.seekbar_content)
    RelativeLayout seekBarContent;
    @InjectView(R.id.taps_content)
    RelativeLayout tapsContent;
    @InjectView(R.id._1)
    LinearLayout time1;
    @InjectView(R.id._2)
    LinearLayout time2;
    @InjectView(R.id._3)
    LinearLayout time3;
    @InjectView(R.id._4)
    LinearLayout time4;
    @InjectView(R.id._5)
    LinearLayout time5;
    @InjectView(R.id._6)
    LinearLayout time6;
    @InjectView(R.id._7)
    LinearLayout time7;
    @InjectView(R.id._8)
    LinearLayout time8;
    @InjectView(R.id._9)
    LinearLayout time9;
    @InjectView(R.id._10)
    LinearLayout time10;
    @InjectView(R.id._11)
    LinearLayout time11;
    @InjectView(R.id._12)
    LinearLayout time12;

    //AUDIO OPIONS
    @InjectView(R.id.record_audio)
    LinearLayout recordAudioButton;
    @InjectView(R.id.custom_keyboard_audio)
    RelativeLayout customKeyboardAudio;
    @InjectView(R.id.text_cancel_audio)
    TextView cancelAudio;
    @InjectView(R.id.text_timer_audio)
    TextView timerAudio;
    @InjectView(R.id.text_recording)
    TextView textRecording;
    @InjectView(R.id.audio_record_background)
    TextView audioRecordBackground;
    @InjectView(R.id.text_timer_press)
    TextView textRecordingPress;

    private MediaRecorder mediaRecorder;
    private MediaPlayer mediaPlayer = null;
    Rect rect;
    boolean saveAudio = false;
    long finalTime;
    String timeFinal;
    ValueAnimator scaleAnimX;
    ValueAnimator scaleAnimY;
    ValueAnimator scaleRedBackgroundX;
    ValueAnimator scaleRedBackgroundY;
    private float radius = 10f;
    boolean animatorBackground = false;
    DateFormat dateDay1;
    DateFormat dateDayText1;
    DateFormat dateMonth1;
    DateFormat dateYear1;
    DateFormat timeFormat1;
    String activeAudioDuration = "";
    long dateToCamera = 0;
    private static String ficheroAudio;
    long fechaAudioMillis;
    ArrayAdapter myAdapter;
    ArrayList venuesList;
    String latitude;
    String longitude;

    public static ConversationChatFragment newInstance(Contact contact) {
        ConversationChatFragment fragment = new ConversationChatFragment();
        Bundle args = new Bundle();
        args.putSerializable(C.contact, contact);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            this.contact = (Contact) getArguments().get(C.contact);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        System.gc();
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        if (!dontClose) {
            messageSelected = null;
            mediaPlayer = null;
            ((MainActivity) activity).changeBtnColor(R.id.ic_menu_chat);
            setIconBarContent();
            SpeakSocket.conversationChatFragment = this;
            initAdapter();
        }
        dontClose = false;
    }

    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable("contacto", this.contact);
    }

    public void onRetoreInstanceState(Bundle inState) {
        this.contact = (Contact) inState.get("contacto");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_conversation_chat, container, false);
        activity = getActivity();
        f = new Finder(activity);
        ButterKnife.inject(this, view);
        ((MainActivity) activity).actionBar.setVisibility(View.VISIBLE);
        ((MainActivity) activity).menuBottom.setVisibility(View.GONE);

        if (BackgroundFragment.getBackgroundChat(activity) != 0)
            backgroundChat.setImageDrawable(
                    activity.getResources().getDrawable(BackgroundFragment.getBackgroundChat(activity)));

        messageText.conversationChatFragment = this;
        TFCache.apply(activity, messageSend, TFCache.TF_SPEAKALL);
        TFCache.apply(activity, messageTranslate, TFCache.TF_SPEAKALL);
        TFCache.apply(activity, messageClock, TFCache.TF_SPEAKALL);
        TFCache.apply(activity, messageText, TFCache.TF_WHITNEY_LIGHT);
        TFCache.apply(activity, temporLanel, TFCache.TF_WHITNEY_BOLD);
        TFCache.apply(activity, addToContacts, TFCache.TF_WHITNEY_LIGHT);
        TFCache.apply(activity, temporizadorCancel, TFCache.TF_WHITNEY_LIGHT);
        TFCache.apply(activity, temporizadorAcept, TFCache.TF_WHITNEY_LIGHT);
        TFCache.apply(activity, textRecording, TFCache.TF_WHITNEY_LIGHT);
        TFCache.apply(activity, textRecordingPress, TFCache.TF_WHITNEY_LIGHT);
        TFCache.apply(activity, timerAudio, TFCache.TF_WHITNEY_LIGHT);
        TFCache.apply(activity, cancelAudio, TFCache.TF_WHITNEY_LIGHT);
        TFCache.apply(activity, audioRecordBackground, TFCache.TF_WHITNEY_LIGHT);
        temporizadorAcept.setVisibility(View.INVISIBLE);
        longclick = false;
        saveAudio = false;

        TFCache.apply(activity, adjuntContact, TFCache.TF_SPEAKALL);
        TFCache.apply(activity, adjuntPhoto, TFCache.TF_SPEAKALL);
        TFCache.apply(activity, adjuntAudio, TFCache.TF_SPEAKALL);
        TFCache.apply(activity, adjuntLocation, TFCache.TF_SPEAKALL);
        TFCache.apply(activity, adjuntVideo, TFCache.TF_SPEAKALL);
        TFCache.apply(activity, adjuntImage, TFCache.TF_SPEAKALL);

        messageText.setOnClickListener(this);
        messageTranslate.setOnClickListener(this);
        messageClock.setOnClickListener(this);
        temporizadorAcept.setOnClickListener(this);
        temporizadorCancel.setOnClickListener(this);
        adjuntContact.setOnClickListener(this);
        adjuntPhoto.setOnClickListener(this);
        adjuntAudio.setOnClickListener(this);
        adjuntLocation.setOnClickListener(this);
        adjuntVideo.setOnClickListener(this);
        adjuntImage.setOnClickListener(this);
        addToContacts.setOnClickListener(this);
        time1.setOnClickListener(this);
        time2.setOnClickListener(this);
        time3.setOnClickListener(this);
        time4.setOnClickListener(this);
        time5.setOnClickListener(this);
        time6.setOnClickListener(this);
        time7.setOnClickListener(this);
        time8.setOnClickListener(this);
        time9.setOnClickListener(this);
        time10.setOnClickListener(this);
        time11.setOnClickListener(this);
        time12.setOnClickListener(this);
        recordAudioButton.setOnTouchListener(this);
        messageText.requestFocus();

        dateDay1 = new SimpleDateFormat("d");
        dateDayText1 = new SimpleDateFormat("EEEE");
        dateMonth1 = new SimpleDateFormat("MMMM");
        dateYear1 = new SimpleDateFormat("yyyy");
        timeFormat1 = new SimpleDateFormat("h:mm a");

        messageSend.setText(Finder.STRING.ICN_SEND_MSJ.toString());
        messageTranslate.setText(Finder.STRING.ICN_TRANSLATE.toString());
        messageClock.setText(Finder.STRING.ICN_TEMPORIZER.toString());
        sv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        sv.setVerticalScrollBarEnabled(false);
        sv.setHorizontalScrollBarEnabled(false);

        final SharedPreferences settings = activity.getSharedPreferences(Finder.STRING.APP_PREF.toString(),
                Context.MODE_PRIVATE);
        keyBoardHeight = settings.getInt("INPUTKEY", 0);

        if (keyBoardHeight == 0) {
            getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
            messageText.postDelayed(new Runnable() {
                @Override
                public void run() {
                    InputMethodManager keyboard = (InputMethodManager) getActivity()
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    keyboard.showSoftInput(messageText, 0);

                }
            }, 50);
            isShowKeyboard = true;
            final Window mRootWindow = activity.getWindow();
            final View mRootView = mRootWindow.getDecorView().findViewById(android.R.id.content);
            mRootView.getViewTreeObserver()
                    .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                        public void onGlobalLayout() {

                            Rect r = new Rect();
                            View view = mRootWindow.getDecorView();
                            view.getWindowVisibleDisplayFrame(r);
                            if (prevSize == 0)
                                prevSize = r.bottom;
                            else if (prevSize != r.bottom) {
                                if (prevSize - r.bottom > 150) {
                                    keyBoardHeight = prevSize - r.bottom;
                                    SharedPreferences.Editor editor = settings.edit();
                                    editor.putInt("INPUTKEY", keyBoardHeight);
                                    editor.apply();
                                    keyboardLayout.setLayoutParams(new LinearLayout.LayoutParams(
                                            ViewGroup.LayoutParams.MATCH_PARENT, keyBoardHeight));
                                    isShowKeyboard = true;
                                    isShowCustomKeyboard = false;
                                    mRootView.getViewTreeObserver().removeGlobalOnLayoutListener(this);

                                }
                            }
                        }
                    });

        } else {
            isShowKeyboard = false;
            getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
            keyboardLayout.setLayoutParams(
                    new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, keyBoardHeight));
            if (keyBoardHeight > pxFromDp(activity, 240)) {
                ((LinearLayout.LayoutParams) seekBarContent.getLayoutParams()).width = (int) pxFromDp(activity,
                        180);
                ((LinearLayout.LayoutParams) seekBarContent.getLayoutParams()).height = (int) pxFromDp(activity,
                        180);

                ((RelativeLayout.LayoutParams) tapsContent.getLayoutParams()).width = (int) pxFromDp(activity, 180);
                ((RelativeLayout.LayoutParams) tapsContent.getLayoutParams()).height = (int) pxFromDp(activity,
                        180);

                ((RelativeLayout.LayoutParams) temporizadorSeek.getLayoutParams()).width = (int) pxFromDp(activity,
                        140);
                ((RelativeLayout.LayoutParams) temporizadorSeek.getLayoutParams()).height = (int) pxFromDp(activity,
                        140);
                temporizadorSeek.atributesCode(20, 16, 25);
                temporLanel.setTextSize(18);

                ((RelativeLayout.LayoutParams) time1.getLayoutParams()).height = (int) pxFromDp(activity, 30);
                ((RelativeLayout.LayoutParams) time1.getLayoutParams()).width = (int) pxFromDp(activity, 30);
                ((RelativeLayout.LayoutParams) time1.getLayoutParams()).topMargin = (int) pxFromDp(activity, 25);
                ((RelativeLayout.LayoutParams) time1.getLayoutParams()).leftMargin = (int) pxFromDp(activity, 90);

                ((RelativeLayout.LayoutParams) time2.getLayoutParams()).height = (int) pxFromDp(activity, 30);
                ((RelativeLayout.LayoutParams) time2.getLayoutParams()).width = (int) pxFromDp(activity, 30);
                ((RelativeLayout.LayoutParams) time2.getLayoutParams()).topMargin = (int) pxFromDp(activity, 35);
                ((RelativeLayout.LayoutParams) time2.getLayoutParams()).leftMargin = (int) pxFromDp(activity, 115);

                ((RelativeLayout.LayoutParams) time3.getLayoutParams()).height = (int) pxFromDp(activity, 30);
                ((RelativeLayout.LayoutParams) time3.getLayoutParams()).width = (int) pxFromDp(activity, 30);
                ((RelativeLayout.LayoutParams) time3.getLayoutParams()).topMargin = (int) pxFromDp(activity, 65);
                ((RelativeLayout.LayoutParams) time3.getLayoutParams()).leftMargin = (int) pxFromDp(activity, 128);

                ((RelativeLayout.LayoutParams) time4.getLayoutParams()).height = (int) pxFromDp(activity, 30);
                ((RelativeLayout.LayoutParams) time4.getLayoutParams()).width = (int) pxFromDp(activity, 30);
                ((RelativeLayout.LayoutParams) time4.getLayoutParams()).topMargin = (int) pxFromDp(activity, 92);
                ((RelativeLayout.LayoutParams) time4.getLayoutParams()).leftMargin = (int) pxFromDp(activity, 128);

                ((RelativeLayout.LayoutParams) time5.getLayoutParams()).height = (int) pxFromDp(activity, 30);
                ((RelativeLayout.LayoutParams) time5.getLayoutParams()).width = (int) pxFromDp(activity, 30);
                ((RelativeLayout.LayoutParams) time5.getLayoutParams()).topMargin = (int) pxFromDp(activity, 118);
                ((RelativeLayout.LayoutParams) time5.getLayoutParams()).leftMargin = (int) pxFromDp(activity, 115);

                ((RelativeLayout.LayoutParams) time6.getLayoutParams()).height = (int) pxFromDp(activity, 30);
                ((RelativeLayout.LayoutParams) time6.getLayoutParams()).width = (int) pxFromDp(activity, 30);
                ((RelativeLayout.LayoutParams) time6.getLayoutParams()).topMargin = (int) pxFromDp(activity, 130);
                ((RelativeLayout.LayoutParams) time6.getLayoutParams()).leftMargin = (int) pxFromDp(activity, 90);

                ((RelativeLayout.LayoutParams) time7.getLayoutParams()).height = (int) pxFromDp(activity, 30);
                ((RelativeLayout.LayoutParams) time7.getLayoutParams()).width = (int) pxFromDp(activity, 30);
                ((RelativeLayout.LayoutParams) time7.getLayoutParams()).topMargin = (int) pxFromDp(activity, 130);
                ((RelativeLayout.LayoutParams) time7.getLayoutParams()).leftMargin = (int) pxFromDp(activity, 60);

                ((RelativeLayout.LayoutParams) time8.getLayoutParams()).height = (int) pxFromDp(activity, 30);
                ((RelativeLayout.LayoutParams) time8.getLayoutParams()).width = (int) pxFromDp(activity, 30);
                ((RelativeLayout.LayoutParams) time8.getLayoutParams()).topMargin = (int) pxFromDp(activity, 118);
                ((RelativeLayout.LayoutParams) time8.getLayoutParams()).leftMargin = (int) pxFromDp(activity, 37);

                ((RelativeLayout.LayoutParams) time9.getLayoutParams()).height = (int) pxFromDp(activity, 30);
                ((RelativeLayout.LayoutParams) time9.getLayoutParams()).width = (int) pxFromDp(activity, 30);
                ((RelativeLayout.LayoutParams) time9.getLayoutParams()).topMargin = (int) pxFromDp(activity, 92);
                ((RelativeLayout.LayoutParams) time9.getLayoutParams()).leftMargin = (int) pxFromDp(activity, 24);

                ((RelativeLayout.LayoutParams) time10.getLayoutParams()).height = (int) pxFromDp(activity, 30);
                ((RelativeLayout.LayoutParams) time10.getLayoutParams()).width = (int) pxFromDp(activity, 30);
                ((RelativeLayout.LayoutParams) time10.getLayoutParams()).topMargin = (int) pxFromDp(activity, 65);
                ((RelativeLayout.LayoutParams) time10.getLayoutParams()).leftMargin = (int) pxFromDp(activity, 24);

                ((RelativeLayout.LayoutParams) time11.getLayoutParams()).height = (int) pxFromDp(activity, 30);
                ((RelativeLayout.LayoutParams) time11.getLayoutParams()).width = (int) pxFromDp(activity, 30);
                ((RelativeLayout.LayoutParams) time11.getLayoutParams()).topMargin = (int) pxFromDp(activity, 35);
                ((RelativeLayout.LayoutParams) time11.getLayoutParams()).leftMargin = (int) pxFromDp(activity, 37);

                ((RelativeLayout.LayoutParams) time12.getLayoutParams()).height = (int) pxFromDp(activity, 30);
                ((RelativeLayout.LayoutParams) time12.getLayoutParams()).width = (int) pxFromDp(activity, 30);
                ((RelativeLayout.LayoutParams) time12.getLayoutParams()).topMargin = (int) pxFromDp(activity, 25);
                ((RelativeLayout.LayoutParams) time12.getLayoutParams()).leftMargin = (int) pxFromDp(activity, 60);
            } else if (keyBoardHeight > pxFromDp(activity, 180)) {
                ((LinearLayout.LayoutParams) seekBarContent.getLayoutParams()).width = (int) pxFromDp(activity,
                        130);
                ((LinearLayout.LayoutParams) seekBarContent.getLayoutParams()).height = (int) pxFromDp(activity,
                        130);

                ((RelativeLayout.LayoutParams) tapsContent.getLayoutParams()).width = (int) pxFromDp(activity, 130);
                ((RelativeLayout.LayoutParams) tapsContent.getLayoutParams()).height = (int) pxFromDp(activity,
                        130);

                ((RelativeLayout.LayoutParams) temporizadorSeek.getLayoutParams()).width = (int) pxFromDp(activity,
                        110);
                ((RelativeLayout.LayoutParams) temporizadorSeek.getLayoutParams()).height = (int) pxFromDp(activity,
                        110);
                temporizadorSeek.atributesCode(15, 16, 9);
                temporLanel.setTextSize(14);

                ((RelativeLayout.LayoutParams) time1.getLayoutParams()).height = (int) pxFromDp(activity, 20);
                ((RelativeLayout.LayoutParams) time1.getLayoutParams()).width = (int) pxFromDp(activity, 20);
                ((RelativeLayout.LayoutParams) time1.getLayoutParams()).topMargin = (int) pxFromDp(activity, 19);
                ((RelativeLayout.LayoutParams) time1.getLayoutParams()).leftMargin = (int) pxFromDp(activity, 66);

                ((RelativeLayout.LayoutParams) time2.getLayoutParams()).height = (int) pxFromDp(activity, 20);
                ((RelativeLayout.LayoutParams) time2.getLayoutParams()).width = (int) pxFromDp(activity, 20);
                ((RelativeLayout.LayoutParams) time2.getLayoutParams()).topMargin = (int) pxFromDp(activity, 29);
                ((RelativeLayout.LayoutParams) time2.getLayoutParams()).leftMargin = (int) pxFromDp(activity, 85);

                ((RelativeLayout.LayoutParams) time3.getLayoutParams()).height = (int) pxFromDp(activity, 20);
                ((RelativeLayout.LayoutParams) time3.getLayoutParams()).width = (int) pxFromDp(activity, 20);
                ((RelativeLayout.LayoutParams) time3.getLayoutParams()).topMargin = (int) pxFromDp(activity, 47);
                ((RelativeLayout.LayoutParams) time3.getLayoutParams()).leftMargin = (int) pxFromDp(activity, 94);

                ((RelativeLayout.LayoutParams) time4.getLayoutParams()).height = (int) pxFromDp(activity, 20);
                ((RelativeLayout.LayoutParams) time4.getLayoutParams()).width = (int) pxFromDp(activity, 20);
                ((RelativeLayout.LayoutParams) time4.getLayoutParams()).topMargin = (int) pxFromDp(activity, 67);
                ((RelativeLayout.LayoutParams) time4.getLayoutParams()).leftMargin = (int) pxFromDp(activity, 94);

                ((RelativeLayout.LayoutParams) time5.getLayoutParams()).height = (int) pxFromDp(activity, 20);
                ((RelativeLayout.LayoutParams) time5.getLayoutParams()).width = (int) pxFromDp(activity, 20);
                ((RelativeLayout.LayoutParams) time5.getLayoutParams()).topMargin = (int) pxFromDp(activity, 85);
                ((RelativeLayout.LayoutParams) time5.getLayoutParams()).leftMargin = (int) pxFromDp(activity, 85);

                ((RelativeLayout.LayoutParams) time6.getLayoutParams()).height = (int) pxFromDp(activity, 20);
                ((RelativeLayout.LayoutParams) time6.getLayoutParams()).width = (int) pxFromDp(activity, 20);
                ((RelativeLayout.LayoutParams) time6.getLayoutParams()).topMargin = (int) pxFromDp(activity, 95);
                ((RelativeLayout.LayoutParams) time6.getLayoutParams()).leftMargin = (int) pxFromDp(activity, 66);

                ((RelativeLayout.LayoutParams) time7.getLayoutParams()).height = (int) pxFromDp(activity, 20);
                ((RelativeLayout.LayoutParams) time7.getLayoutParams()).width = (int) pxFromDp(activity, 20);
                ((RelativeLayout.LayoutParams) time7.getLayoutParams()).topMargin = (int) pxFromDp(activity, 95);
                ((RelativeLayout.LayoutParams) time7.getLayoutParams()).leftMargin = (int) pxFromDp(activity, 45);

                ((RelativeLayout.LayoutParams) time8.getLayoutParams()).height = (int) pxFromDp(activity, 20);
                ((RelativeLayout.LayoutParams) time8.getLayoutParams()).width = (int) pxFromDp(activity, 20);
                ((RelativeLayout.LayoutParams) time8.getLayoutParams()).topMargin = (int) pxFromDp(activity, 85);
                ((RelativeLayout.LayoutParams) time8.getLayoutParams()).leftMargin = (int) pxFromDp(activity, 28);

                ((RelativeLayout.LayoutParams) time9.getLayoutParams()).height = (int) pxFromDp(activity, 20);
                ((RelativeLayout.LayoutParams) time9.getLayoutParams()).width = (int) pxFromDp(activity, 20);
                ((RelativeLayout.LayoutParams) time9.getLayoutParams()).topMargin = (int) pxFromDp(activity, 67);
                ((RelativeLayout.LayoutParams) time9.getLayoutParams()).leftMargin = (int) pxFromDp(activity, 18);

                ((RelativeLayout.LayoutParams) time10.getLayoutParams()).height = (int) pxFromDp(activity, 20);
                ((RelativeLayout.LayoutParams) time10.getLayoutParams()).width = (int) pxFromDp(activity, 20);
                ((RelativeLayout.LayoutParams) time10.getLayoutParams()).topMargin = (int) pxFromDp(activity, 47);
                ((RelativeLayout.LayoutParams) time10.getLayoutParams()).leftMargin = (int) pxFromDp(activity, 18);

                ((RelativeLayout.LayoutParams) time11.getLayoutParams()).height = (int) pxFromDp(activity, 20);
                ((RelativeLayout.LayoutParams) time11.getLayoutParams()).width = (int) pxFromDp(activity, 20);
                ((RelativeLayout.LayoutParams) time11.getLayoutParams()).topMargin = (int) pxFromDp(activity, 29);
                ((RelativeLayout.LayoutParams) time11.getLayoutParams()).leftMargin = (int) pxFromDp(activity, 28);

                ((RelativeLayout.LayoutParams) time12.getLayoutParams()).height = (int) pxFromDp(activity, 20);
                ((RelativeLayout.LayoutParams) time12.getLayoutParams()).width = (int) pxFromDp(activity, 20);
                ((RelativeLayout.LayoutParams) time12.getLayoutParams()).topMargin = (int) pxFromDp(activity, 19);
                ((RelativeLayout.LayoutParams) time12.getLayoutParams()).leftMargin = (int) pxFromDp(activity, 45);

            }
        }
        messagesList.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (scrollOnBottom) {
                    messagesListScroll.scrollTo(0, messagesList.getBottom());
                } else {
                    messagesListScroll.scrollTo(0, ((messagesList.getHeight() - messagesValuePrev) + scrollValue)
                            + (scrollHeight - messagesListScroll.getHeight()));
                    messagesListScroll.setVerticalScrollBarEnabled(true);
                }

            }
        });
        messagesListScroll.getViewTreeObserver()
                .addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
                    @Override
                    public void onScrollChanged() {
                        if (messagesList.getHeight() - messagesListScroll.getScrollY() <= messagesListScroll
                                .getHeight()) {
                            scrollOnBottom = true;
                        } else {
                            scrollOnBottom = false;
                            messagesValuePrev = messagesList.getHeight();
                            scrollValue = messagesListScroll.getScrollY();
                            scrollHeight = messagesListScroll.getHeight();
                        }
                    }
                });

        messageSend.setOnClickListener(this);
        messageText.addTextChangedListener(new TextWatcher() {
            boolean delayed = false;

            @Override
            public void afterTextChanged(Editable arg0) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            private void sendWritingStatus() {
                if (SpeakSocket.isRunning()) {
                    try {
                        JSONObject data = new JSONObject();
                        data.put("source", u.id);
                        data.put("target", contact.idContacto);
                        data.put("type", 1);
                        if (SpeakSocket.mSocket != null)
                            if (SpeakSocket.mSocket.connected())
                                SpeakSocket.mSocket.emit("contact-status", data);
                        Log.e("STATUS WRITE", data.toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (messageText.getText().length() > 0) {
                    messageSend.setVisibility(View.VISIBLE);
                    messageSednDivider.setVisibility(View.VISIBLE);
                    if (!delayed) {
                        delayed = true;
                        sendWritingStatus();
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                delayed = false;
                            }
                        }, C.CONTACT_STATUS_DELAY_MS);
                    }
                } else {
                    messageSend.setVisibility(View.GONE);
                    messageSednDivider.setVisibility(View.GONE);
                }

            }
        });
        u = new Select().from(User.class).executeSingle();

        handlerContactStatus = new Handler();
        runnableContactStatus = new Runnable() {

            @Override
            public void run() {
                JSONObject dataLastSeen = new JSONObject();
                try {
                    dataLastSeen.put("source", u.id);
                    dataLastSeen.put("target", contact.idContacto);
                    if (SpeakSocket.mSocket != null)
                        if (SpeakSocket.mSocket.connected()) {
                            Log.e("Pidiendo lastseen", dataLastSeen.toString());
                            SpeakSocket.mSocket.emit("contact-lastseen", dataLastSeen);
                        }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                handlerContactStatus.postDelayed(runnableContactStatus, 5000);
            }
        };
        handlerContactStatus.postDelayed(runnableContactStatus, 500);
        Contact contAdd = new Select().from(Contact.class).where("id_contact = ?", contact.idContacto)
                .executeSingle();
        if (contAdd == null) {
            addToContacts.setVisibility(View.VISIBLE);
        } else {
            addToContacts.setVisibility(View.GONE);
        }

        return view;
    }

    public void setIconBarContent() {
        ((MainActivity) activity).actionBar
                .setBackgroundColor(getResources().getColor(R.color.speak_all_ligh_gray));
        ((MainActivity) activity).actionBarTitle.setTextColor(getResources().getColor(R.color.speak_all_gray));
        ((MainActivity) activity).actionBarDesc.setTextColor(getResources().getColor(R.color.speak_all_gray));
        ((MainActivity) activity).actionBarIconRight.setTextColor(getResources().getColor(R.color.speak_all_red));
        ((MainActivity) activity).actionBarIconLeft.setTextColor(getResources().getColor(R.color.speak_all_red));
        ((MainActivity) activity).actionBarTitle.setVisibility(View.VISIBLE);
        ((MainActivity) activity).actionBarTitle.setText(contact.fullName);
        ((MainActivity) activity).actionBarDesc.setVisibility(View.GONE);
        ((MainActivity) activity).actionBarIconLeft.setVisibility(View.VISIBLE);
        ((MainActivity) activity).actionBarIconLeft.setText(Finder.STRING.ICN_ARROW_LEFT.toString());
        ((MainActivity) activity).actionBarIconRight.setVisibility(View.VISIBLE);
        ((MainActivity) activity).actionBarLeftFavorites.setVisibility(View.GONE);
        ((MainActivity) activity).actionBarIconRight.setText(Finder.STRING.ICN_ADJUNT.toString());
        ((MainActivity) activity).actionBarIconRightBrowse.setVisibility(View.GONE);
        ((MainActivity) activity).actionBarRightAll.setVisibility(View.GONE);
        ((MainActivity) activity).actionBarIconRightDivider.setVisibility(View.GONE);
        ((MainActivity) activity).actionBarIconPic.setVisibility(View.GONE);
        ((MainActivity) activity).actionBarCenterLayout.setVisibility(View.VISIBLE);
        ((MainActivity) activity).actionBarSearchLayout.setVisibility(View.GONE);

        new Thread(new Runnable() {
            @Override
            public void run() {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (contact.photo != null) {
                            Bitmap bmp = BitmapFactory.decodeByteArray(contact.photo, 0, contact.photo.length);
                            ((MainActivity) activity).actionBarIconPicChat.setImageBitmap(bmp);
                            ((MainActivity) activity).actionBarIconPicChat.setVisibility(View.VISIBLE);
                            ((MainActivity) activity).actionBarIconPicEmpty.setVisibility(View.GONE);
                        } else {
                            ((MainActivity) activity).actionBarIconPicEmpty.setVisibility(View.VISIBLE);
                            ((MainActivity) activity).actionBarIconPicChat.setVisibility(View.GONE);
                        }
                    }
                });
            }
        }).start();

        ((MainActivity) activity).actionBarTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getFragmentManager().beginTransaction()
                        .replace(R.id.container2, ProfileContactFragment.newInstance(contact)).addToBackStack(null)
                        .commit();
                ((MainActivity) activity).setOnBackPressedListener(null);
            }
        });
        ((MainActivity) activity).actionBarIconLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.gc();
                if (messageSelected != null) {
                    View vista = messagesList.findViewWithTag(messageSelected);
                    Message mensaje = new Select().from(Message.class).where("mensajeId = ?", messageSelected)
                            .executeSingle();
                    if (mensaje.emisor.equals(u.id)) {
                        if (mensaje.status != 4) {
                            vista.findViewById(R.id.icn_message_tempo_divider).setVisibility(View.INVISIBLE);
                            vista.findViewById(R.id.icn_message_tempo).setVisibility(View.INVISIBLE);
                        } else {
                            vista.findViewById(R.id.icn_message_tempo_divider).setVisibility(View.GONE);
                            vista.findViewById(R.id.icn_message_tempo).setVisibility(View.GONE);
                        }
                        vista.findViewById(R.id.icn_message_back).setVisibility(View.INVISIBLE);
                        vista.findViewById(R.id.messages_menu_layout).setVisibility(View.INVISIBLE);
                        ((MainActivity) activity).setOnBackPressedListener(null);
                        messageSelected = null;
                    } else {
                        vista.findViewById(R.id.icn_message_tempo).setVisibility(View.GONE);
                        vista.findViewById(R.id.icn_message_copy).setVisibility(View.INVISIBLE);
                        vista.findViewById(R.id.icn_message_back).setVisibility(View.INVISIBLE);
                        vista.findViewById(R.id.messages_menu_layout).setVisibility(View.INVISIBLE);
                        ((MainActivity) activity).setOnBackPressedListener(null);
                        messageSelected = null;
                    }
                } else {
                    getFragmentManager().popBackStack();
                    ((MainActivity) activity).setOnBackPressedListener(null);
                }
            }
        });
        ((MainActivity) activity).actionBarIconRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                menuAdjunt = !menuAdjunt;
                if (menuAdjunt) {
                    adjuntLayout.setVisibility(View.VISIBLE);
                    AnimatorSet set = new AnimatorSet();
                    set.playTogether(ObjectAnimator.ofFloat(adjuntLayout, "alpha", 0, 1));
                    set.setDuration(200).start();
                } else {
                    adjuntLayout.setVisibility(View.GONE);
                    AnimatorSet set = new AnimatorSet();
                    set.playTogether(ObjectAnimator.ofFloat(adjuntLayout, "alpha", 1, 0));
                    set.setDuration(200).start();
                }
            }
        });
        setted = true;
    }

    public void showPreviousMessages(int mensajesOffset) {
        messagesListScroll.setVerticalScrollBarEnabled(false);
        mensajesTotal = new Select().all().from(Message.class).where("emisor = ?", contact.idContacto)
                .or("receptor = ?", contact.idContacto).count();
        List<Message> mensajes = new Select().from(Message.class).limit(mensajesLimit)
                .offset(mensajesTotal - mensajesOffset).where("emisor = ?", contact.idContacto)
                .or("receptor = ?", contact.idContacto).orderBy("emitedAt ASC").execute();
        Collections.reverse(mensajes);

        if (!mensajes.isEmpty()) {
            int position = mensajesLimit - 1;
            for (Message mensaje : mensajes) {
                final View v = addBoxMessage(position, getActivity(), mensaje, getActivity().getLayoutInflater());
                v.setTag(mensaje.mensajeId);
                messagesList.addView(v, 0);
                position = position - 1;
                if (!mensaje.emisor.equals(u.id) && mensaje.status == 0) {
                    Chats chats = new Select().from(Chats.class).where("idContacto = ?", mensaje.emisor)
                            .executeSingle();
                    if (chats.mensajeId.equals(mensaje.mensajeId)) {
                        chats.notRead = 0;
                        chats.save();
                    }
                    JSONObject notifyMessage = new JSONObject();
                    try {
                        notifyMessage.put("type", mensaje.tipo);
                        notifyMessage.put("message_id", mensaje.mensajeId);
                        notifyMessage.put("source", mensaje.emisor);
                        notifyMessage.put("status", 4);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (SpeakSocket.isRunning()) {
                        SpeakSocket.mSocket.emit("message-status", notifyMessage);
                        new Update(Message.class).set("status = ?", 4).where("mensajeId = ?", mensaje.mensajeId)
                                .execute();
                    }
                    if (mensaje.delay > 0) {
                        startCounterToDelete((mensaje.delay * 1000), mensaje);
                    }
                }
                if (mensaje.status == 4) {
                    if (mensaje.delay > 0) {
                        startCounterToDelete((mensaje.delay * 1000), mensaje);
                    }
                }
            }
            System.gc();
        }
    }

    public void initAdapter() {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                messagesList.removeAllViews();
                mensajesTotal = new Select().all().from(Message.class).where("emisor = ?", contact.idContacto)
                        .or("receptor = ?", contact.idContacto).count();
                List<Message> mensajes = new Select().from(Message.class).limit(mensajesLimit)
                        .offset(mensajesTotal - mensajesLimit).where("emisor = ?", contact.idContacto)
                        .or("receptor = ?", contact.idContacto).orderBy("emitedAt ASC").execute();
                Collections.reverse(mensajes);
                if (!mensajes.isEmpty()) {
                    int position = mensajesLimit - 1;
                    for (Message mensaje : mensajes) {
                        messagesListScroll.setVerticalScrollBarEnabled(false);
                        final View v = addBoxMessage(position, getActivity(), mensaje,
                                getActivity().getLayoutInflater());
                        v.setTag(mensaje.mensajeId);
                        messagesList.addView(v, 0);
                        position = position - 1;
                        if (!mensaje.emisor.equals(u.id) && mensaje.status == 0) {
                            Chats chats = new Select().from(Chats.class).where("idContacto = ?", mensaje.emisor)
                                    .executeSingle();
                            if (chats.mensajeId.equals(mensaje.mensajeId)) {
                                chats.notRead = 0;
                                chats.save();
                            }
                            JSONObject notifyMessage = new JSONObject();
                            try {
                                notifyMessage.put("type", mensaje.tipo);
                                notifyMessage.put("message_id", mensaje.mensajeId);
                                notifyMessage.put("source", mensaje.emisor);
                                notifyMessage.put("status", 4);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            if (SpeakSocket.isRunning()) {
                                if (SpeakSocket.mSocket.connected()) {
                                    SpeakSocket.mSocket.emit("message-status", notifyMessage);
                                    new Update(Message.class).set("status = ?", 4)
                                            .where("mensajeId = ?", mensaje.mensajeId).execute();
                                }
                            }

                            if (mensaje.delay > 0) {
                                startCounterToDelete((mensaje.delay * 1000), mensaje);
                            }
                        }

                        if (mensaje.status == 4) {

                            if (mensaje.delay > 0) {
                                startCounterToDelete((mensaje.delay * 1000), mensaje);
                            }
                        }
                    }
                    System.gc();
                    messagesList.setVisibility(View.VISIBLE);
                }
            }
        });

    }

    public void showNewMessage(final Message mensaje) {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (!messagesList.isShown()) {
                    messagesList.setVisibility(View.VISIBLE);
                }
                messagesListScroll.setVerticalScrollBarEnabled(false);
                mensajesTotal = mensajesTotal + 1;
                View v = addBoxMessage(-1, getActivity(), mensaje, getActivity().getLayoutInflater());
                v.setTag(mensaje.mensajeId);

                messagesList.addView(v);
                if (!mensaje.emisor.equals(u.id)) {
                    Chats chats = new Select().from(Chats.class).where("idContacto = ?", mensaje.emisor)
                            .executeSingle();
                    if (chats.mensajeId.equals(mensaje.mensajeId)) {
                        chats.notRead = 0;
                        chats.save();
                    }
                    JSONObject notifyMessage = new JSONObject();
                    try {
                        notifyMessage.put("type", mensaje.tipo);
                        notifyMessage.put("message_id", mensaje.mensajeId);
                        notifyMessage.put("source", mensaje.emisor);
                        notifyMessage.put("status", 4);
                        if (SpeakSocket.isRunning()) {
                            if (SpeakSocket.mSocket.connected()) {
                                SpeakSocket.mSocket.emit("message-status", notifyMessage);
                                new Update(Message.class).set("status = ?", 4)
                                        .where("mensajeId = ?", mensaje.mensajeId).execute();
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    if (mensaje.delay > 0) {
                        startCounterToDelete((mensaje.delay * 1000), mensaje);
                    }
                }
                if (mensaje.status == 4) {
                    if (mensaje.delay > 0) {
                        startCounterToDelete((mensaje.delay * 1000), mensaje);
                    }
                }
                messagesList.setVisibility(View.VISIBLE);
                System.gc();
            }
        }

        );
    }

    public void changeStatus(final String messageId, final int status) {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                View message = messagesList.findViewWithTag(messageId);
                if (message != null) {
                    TextView messageStatus = (TextView) message.findViewById(R.id.message_status);
                    LinearLayout mensajeLayout = (LinearLayout) message.findViewById(R.id.mensaje_layout);
                    TextView icnMessageArrow = (TextView) message.findViewById(R.id.icn_message_arrow);
                    if (status == 1) {
                        if (animaciones.get(messageId) != null)
                            if (animaciones.get(messageId).isRunning()) {
                                animaciones.get(messageId).cancel();
                                animaciones.remove(messageId);
                            }
                        messageStatus.setTextSize(16);
                        mensajeLayout.setBackgroundDrawable(
                                getResources().getDrawable(R.drawable.message_out_background));
                        icnMessageArrow.setTextColor(getResources().getColor(R.color.speak_all_red));
                        messageStatus.setTextColor(getResources().getColor(R.color.speak_all_ligh_gray));
                        messageStatus.setText(Finder.STRING.ICN_MSJ_SENDING.toString());
                        ValueAnimator colorAnim = ObjectAnimator.ofFloat(messageStatus, "alpha", 1, 0);
                        colorAnim.setRepeatCount(ValueAnimator.INFINITE);
                        colorAnim.setRepeatMode(ValueAnimator.REVERSE);
                        colorAnim.setDuration(1000).start();
                        animaciones.put(messageId, colorAnim);
                    }
                    if (status == 2) {
                        messageStatus.setTextSize(16);
                        if (animaciones.get(messageId) != null)
                            if (animaciones.get(messageId).isRunning()) {
                                animaciones.get(messageId).cancel();
                                animaciones.remove(messageId);
                            }
                        ViewHelper.setAlpha(messageStatus, 1);
                        messageStatus.setText(Finder.STRING.ICN_MSJ_SEND.toString());
                    }
                    if (status == 3) {
                        messageStatus.setTextSize(11);
                        if (animaciones.get(messageId) != null)
                            if (animaciones.get(messageId).isRunning()) {
                                animaciones.get(messageId).cancel();
                                animaciones.remove(messageId);
                            }
                        ViewHelper.setAlpha(messageStatus, 1);
                        messageStatus.setText(Finder.STRING.ICN_MSJ_CLOSED.toString());
                    }
                    if (status == 4) {
                        messageStatus.setTextSize(11);
                        if (animaciones.get(messageId) != null)
                            if (animaciones.get(messageId).isRunning()) {
                                animaciones.get(messageId).cancel();
                                animaciones.remove(messageId);
                            }
                        ViewHelper.setAlpha(messageStatus, 1);
                        messageStatus.setText(Finder.STRING.ICN_MSJ_OPENED.toString());
                        message.findViewById(R.id.icn_message_tempo_divider).setVisibility(View.GONE);
                        message.findViewById(R.id.icn_message_tempo).setVisibility(View.GONE);
                        Message mensaje = new Select().from(Message.class).where("mensajeId = ?", messageId)
                                .executeSingle();
                        if (mensaje.delay > 0) {
                            startCounterToDelete((mensaje.delay * 1000), mensaje);
                        }
                    }
                }
            }
        });
    }

    public void onPause() {
        super.onPause();
        System.gc();
        hideKeyBoard();
        if (!dontClose) {
            handlerContactStatus.removeCallbacks(runnableContactStatus);
            SpeakSocket.conversationChatFragment = null;
            if (isShowKeyboard) {
                final InputMethodManager imm = (InputMethodManager) activity
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
                keyboardLayout.setVisibility(View.GONE);
                isShowKeyboard = false;
            }
            if (animaciones.size() > 0) {
                for (String keys : animaciones.keySet()) {
                    if (animaciones.get(keys) != null)
                        if (animaciones.get(keys).isRunning()) {
                            animaciones.get(keys).cancel();
                        }
                }
                animaciones.clear();
            }

            if (mediaPlayer != null) {
                mediaPlayer.stop();
                mediaPlayer.release();
            }
            if (activeAudioSeekBarr != null) {
                activeAudioSeekBarr.setProgress(0);
                activeAudioSeekBarr.setOnSeekBarChangeListener(null);
            }
            if (activeAudioTime != null) {
                activeAudioTime.setText(activeAudioDuration);
            }
            if (!activeAudioDuration.equals("")) {
                activeAudioDuration = "";
            }
            seekHandler.removeCallbacks(runAudio);
        }
    }

    public static float dpFromPx(Context context, float px) {
        return px / context.getResources().getDisplayMetrics().density;
    }

    public static float pxFromDp(Context context, float dp) {
        return dp * context.getResources().getDisplayMetrics().density;
    }

    public View addBoxMessage(int position, Context context, final Message message, LayoutInflater miInflater) {
        Finder f = new Finder(context);
        View rowView = null;
        TextView icnMessageArrow = null;

        //Message message = getItem(position);
        if (message.tipo == Integer.parseInt(activity.getString(R.string.MSG_TYPE_TEXT))
                || message.tipo == Integer.parseInt(activity.getString(R.string.MSG_TYPE_BROADCAST_TEXT))
                || message.tipo == Integer.parseInt(activity.getString(R.string.MSG_TYPE_AUTORESPONSE))) {

            if (message.emisor.equals(u.id)) {
                rowView = miInflater.inflate(R.layout.message_out_adapter, null);
                icnMessageArrow = (TextView) rowView.findViewById(R.id.icn_message_arrow);
                TFCache.apply(context, icnMessageArrow, TFCache.TF_SPEAKALL);
                icnMessageArrow.setText(Finder.STRING.ICN_ARROW_GRAY.toString());
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
            } else {
                rowView = miInflater.inflate(R.layout.message_in_adapter, null);
                icnMessageArrow = (TextView) rowView.findViewById(R.id.icn_message_arrow);
                TFCache.apply(context, icnMessageArrow, TFCache.TF_SPEAKALL);
                icnMessageArrow.setText(Finder.STRING.ICN_ARROW_RED.toString());
                if (message.tipo == 21)
                    icnMessageArrow.setTextColor(getResources().getColor(R.color.speakall_autoresponse));
                else
                    icnMessageArrow.setTextColor(BalloonFragment.getFriendBalloon(activity));
            }
            showMensajeText(position, context, message, rowView, icnMessageArrow);
        } else if (message.tipo == Integer.parseInt(activity.getString(R.string.MSG_TYPE_AUDIO))) {
            if (message.emisor.equals(u.id)) {
                rowView = miInflater.inflate(R.layout.message_out_audio_adapter, null);
                icnMessageArrow = (TextView) rowView.findViewById(R.id.icn_message_arrow);
                TFCache.apply(context, icnMessageArrow, TFCache.TF_SPEAKALL);
                icnMessageArrow.setText(Finder.STRING.ICN_ARROW_GRAY.toString());
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
            } else {
                rowView = miInflater.inflate(R.layout.message_in_audio_adapter, null);
                icnMessageArrow = (TextView) rowView.findViewById(R.id.icn_message_arrow);
                TFCache.apply(context, icnMessageArrow, TFCache.TF_SPEAKALL);
                icnMessageArrow.setText(Finder.STRING.ICN_ARROW_RED.toString());
                icnMessageArrow.setTextColor(BalloonFragment.getFriendBalloon(activity));
            }
            showMensajeAudio(position, context, message, rowView, icnMessageArrow);
        } else if (message.tipo == Integer.parseInt(activity.getString(R.string.MSG_TYPE_PHOTO))
                || message.tipo == Integer.parseInt(activity.getString(R.string.MSG_TYPE_BROADCAST_PHOTO))) {
            if (message.emisor.equals(u.id)) {
                rowView = miInflater.inflate(R.layout.message_out_photo_adapter, null);
                icnMessageArrow = (TextView) rowView.findViewById(R.id.icn_message_arrow);
                TFCache.apply(context, icnMessageArrow, TFCache.TF_SPEAKALL);
                icnMessageArrow.setText(Finder.STRING.ICN_ARROW_GRAY.toString());
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
            } else {
                rowView = miInflater.inflate(R.layout.message_in_photo_adapter, null);
                icnMessageArrow = (TextView) rowView.findViewById(R.id.icn_message_arrow);
                TFCache.apply(context, icnMessageArrow, TFCache.TF_SPEAKALL);
                icnMessageArrow.setText(Finder.STRING.ICN_ARROW_RED.toString());
                icnMessageArrow.setTextColor(BalloonFragment.getFriendBalloon(activity));
            }
            showMensajePhoto(position, context, message, rowView, icnMessageArrow);
        } else if (message.tipo == Integer.parseInt(activity.getString(R.string.MSG_TYPE_LOCATION))) {
            if (message.emisor.equals(u.id)) {
                rowView = miInflater.inflate(R.layout.message_out_location_adapter, null);
                icnMessageArrow = (TextView) rowView.findViewById(R.id.icn_message_arrow);
                TFCache.apply(context, icnMessageArrow, TFCache.TF_SPEAKALL);
                icnMessageArrow.setText(Finder.STRING.ICN_ARROW_GRAY.toString());
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
            } else {
                rowView = miInflater.inflate(R.layout.message_in_location_adapter, null);
                icnMessageArrow = (TextView) rowView.findViewById(R.id.icn_message_arrow);
                TFCache.apply(context, icnMessageArrow, TFCache.TF_SPEAKALL);
                icnMessageArrow.setText(Finder.STRING.ICN_ARROW_RED.toString());
                icnMessageArrow.setTextColor(BalloonFragment.getFriendBalloon(activity));
            }
            showMensajeLocation(position, context, message, rowView, icnMessageArrow);
        } else if (message.tipo == Integer.parseInt(activity.getString(R.string.MSG_TYPE_VIDEO))) {
            if (message.emisor.equals(u.id)) {
                rowView = miInflater.inflate(R.layout.message_out_photo_adapter, null);
                icnMessageArrow = (TextView) rowView.findViewById(R.id.icn_message_arrow);
                TFCache.apply(context, icnMessageArrow, TFCache.TF_SPEAKALL);
                icnMessageArrow.setText(Finder.STRING.ICN_ARROW_GRAY.toString());
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
            } else {
                rowView = miInflater.inflate(R.layout.message_in_photo_adapter, null);
                icnMessageArrow = (TextView) rowView.findViewById(R.id.icn_message_arrow);
                TFCache.apply(context, icnMessageArrow, TFCache.TF_SPEAKALL);
                icnMessageArrow.setText(Finder.STRING.ICN_ARROW_RED.toString());
                icnMessageArrow.setTextColor(BalloonFragment.getFriendBalloon(activity));
            }
            showMensajeVideo(position, context, message, rowView, icnMessageArrow);
        } else if (message.tipo == Integer.parseInt(activity.getString(R.string.MSG_TYPE_CONTACT))) {
            if (message.emisor.equals(u.id)) {
                rowView = miInflater.inflate(R.layout.message_out_contact_adapter, null);
                icnMessageArrow = (TextView) rowView.findViewById(R.id.icn_message_arrow);
                TFCache.apply(context, icnMessageArrow, TFCache.TF_SPEAKALL);
                icnMessageArrow.setText(Finder.STRING.ICN_ARROW_GRAY.toString());
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
            } else {
                rowView = miInflater.inflate(R.layout.message_in_contact_adapter, null);
                icnMessageArrow = (TextView) rowView.findViewById(R.id.icn_message_arrow);
                TFCache.apply(context, icnMessageArrow, TFCache.TF_SPEAKALL);
                icnMessageArrow.setText(Finder.STRING.ICN_ARROW_RED.toString());
                icnMessageArrow.setTextColor(BalloonFragment.getFriendBalloon(activity));
            }
            showMensajeContact(position, context, message, rowView, icnMessageArrow);
        }

        return rowView;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.icn_message_send:
            temporizadorAcept.setVisibility(View.INVISIBLE);
            String message = messageText.getText().toString();
            Message msjNew = new Message();
            Calendar fecha = Calendar.getInstance();
            String id = u.id + contact.idContacto + fecha.getTimeInMillis()
                    + Settings.Secure.getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID);

            msjNew.mensajeId = id;
            msjNew.emisor = u.id;
            msjNew.receptor = contact.idContacto;
            msjNew.mensaje = message;
            msjNew.emisorEmail = u.email;
            msjNew.receptorEmail = contact.email;
            msjNew.emisorLang = u.lang;
            msjNew.receptorLang = contact.lang;
            msjNew.emitedAt = fecha.getTimeInMillis();
            msjNew.tipo = Integer.parseInt(getString(R.string.MSG_TYPE_TEXT));
            if (tiempoMensaje)
                msjNew.delay = temporizadorSeek.getValue();
            else
                msjNew.delay = 0;
            msjNew.translation = translate;
            if (SpeakSocket.mSocket != null)
                if (SpeakSocket.mSocket.connected()) {
                    msjNew.status = 1;
                } else {
                    msjNew.status = -1;
                }

            msjNew.save();
            Chats chat = new Select().from(Chats.class).where("idContacto = ?", msjNew.receptor).executeSingle();
            if (chat == null) {
                Contact contact = new Select().from(Contact.class).where("id_contact = ?", msjNew.receptor)
                        .executeSingle();
                Chats newChat = new Chats();
                newChat.mensajeId = msjNew.mensajeId;
                newChat.idContacto = msjNew.receptor;
                newChat.isLockedConversation = false;
                newChat.lastStatus = msjNew.status;
                newChat.email = msjNew.receptorEmail;
                if (contact != null) {
                    newChat.photo = contact.photo;
                    newChat.fullName = contact.fullName;
                    newChat.lang = contact.lang;
                    newChat.screenName = contact.screenName;
                    newChat.photoload = true;
                    newChat.phone = contact.phone;
                } else {
                    newChat.photo = null;
                    newChat.photoload = false;
                    newChat.fullName = msjNew.receptorEmail;
                    newChat.lang = msjNew.receptorLang;
                    newChat.screenName = msjNew.receptorEmail;
                    newChat.phone = null;
                }
                newChat.emitedAt = msjNew.emitedAt;
                newChat.notRead = 0;
                newChat.lastMessage = msjNew.mensaje;
                newChat.show = true;
                newChat.save();
            } else {
                if (!chat.photoload) {
                    Contact contact = new Select().from(Contact.class).where("id_contact = ?", msjNew.emisor)
                            .executeSingle();
                    if (contact != null) {
                        chat.photo = contact.photo;
                        chat.photoload = true;
                    } else {
                        chat.photo = null;
                        chat.photoload = false;
                    }
                }
                chat.mensajeId = msjNew.mensajeId;
                chat.lastStatus = msjNew.status;
                chat.emitedAt = msjNew.emitedAt;
                chat.notRead = 0;
                chat.lastMessage = msjNew.mensaje;
                chat.save();
            }
            messageText.setText("");
            showNewMessage(msjNew);
            messageClock.setTextColor(getResources().getColor(R.color.speak_all_gray));
            messageClock.setText(Finder.STRING.ICN_TEMPORIZER.toString());
            tiempoMensaje = false;
            break;
        case R.id.message_text:
            SharedPreferences settings = getActivity().getSharedPreferences(Finder.STRING.APP_PREF.toString(),
                    Context.MODE_PRIVATE);
            if (settings.getInt("INPUTKEY", 0) == 0) {
                customKeyboardLayout.setVisibility(View.GONE);
                customKeyboardAudio.setVisibility(View.GONE);
                keyboardLayout.setVisibility(View.GONE);
                isShowCustomKeyboard = false;
                if (tiempoMensaje) {
                    messageClock.setText(Finder.STRING.ICN_TEMPORIZER_FILL.toString());
                    messageClock.setTextColor(getResources().getColor(R.color.speak_all_red));
                } else {
                    messageClock.setText(Finder.STRING.ICN_TEMPORIZER.toString());
                    messageClock.setTextColor(getResources().getColor(R.color.speak_all_gray));
                }
                isShowKeyboard = true;
            } else {
                if (!isShowKeyboard) {
                    if (!isShowCustomKeyboard) {
                        messagesListScroll.setVerticalScrollBarEnabled(false);
                        final InputMethodManager imm = (InputMethodManager) activity
                                .getSystemService(Context.INPUT_METHOD_SERVICE);
                        if (tiempoMensaje) {
                            messageClock.setText(Finder.STRING.ICN_TEMPORIZER_FILL.toString());
                            messageClock.setTextColor(getResources().getColor(R.color.speak_all_red));
                        } else {
                            messageClock.setText(Finder.STRING.ICN_TEMPORIZER.toString());
                            messageClock.setTextColor(getResources().getColor(R.color.speak_all_gray));
                        }
                        imm.showSoftInput(messageText, 0);
                        keyboardLayout.setVisibility(View.GONE);
                        AnimatorSet set = new AnimatorSet();
                        set.playTogether(ObjectAnimator.ofFloat(keyboardLayout, "alpha", 0, 1));
                        set.setDuration(220).start();
                        set.addListener(new Animator.AnimatorListener() {
                            @Override
                            public void onAnimationStart(Animator animation) {

                            }

                            @Override
                            public void onAnimationEnd(Animator animation) {
                                keyboardLayout.setVisibility(View.VISIBLE);
                            }

                            @Override
                            public void onAnimationCancel(Animator animation) {

                            }

                            @Override
                            public void onAnimationRepeat(Animator animation) {

                            }
                        });
                        keyboardLayout
                                .setBackgroundColor(getResources().getColor(R.color.speak_all_ligh_gray_plus));
                        isShowKeyboard = true;
                        ((MainActivity) activity).setOnBackPressedListener(null);
                        customKeyboardLayout.setVisibility(View.GONE);
                        customKeyboardAudio.setVisibility(View.GONE);
                        isShowCustomKeyboard = false;
                    } else {
                        keyboardLayout.setVisibility(View.GONE);
                        AnimatorSet set = new AnimatorSet();
                        set.playTogether(ObjectAnimator.ofFloat(keyboardLayout, "alpha", 0, 1));
                        set.setDuration(220).start();
                        set.addListener(new Animator.AnimatorListener() {
                            @Override
                            public void onAnimationStart(Animator animation) {

                            }

                            @Override
                            public void onAnimationEnd(Animator animation) {
                                keyboardLayout.setVisibility(View.VISIBLE);
                            }

                            @Override
                            public void onAnimationCancel(Animator animation) {

                            }

                            @Override
                            public void onAnimationRepeat(Animator animation) {

                            }
                        });
                        ((MainActivity) activity).setOnBackPressedListener(null);
                        messagesListScroll.setVerticalScrollBarEnabled(false);
                        if (tiempoMensaje) {
                            messageClock.setText(Finder.STRING.ICN_TEMPORIZER_FILL.toString());
                            messageClock.setTextColor(getResources().getColor(R.color.speak_all_red));
                        } else {
                            messageClock.setText(Finder.STRING.ICN_TEMPORIZER.toString());
                            messageClock.setTextColor(getResources().getColor(R.color.speak_all_gray));
                        }
                        final InputMethodManager imm = (InputMethodManager) activity
                                .getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.showSoftInput(messageText, 0);
                        keyboardLayout
                                .setBackgroundColor(getResources().getColor(R.color.speak_all_ligh_gray_plus));
                        isShowKeyboard = true;
                        customKeyboardLayout.setVisibility(View.GONE);
                        customKeyboardAudio.setVisibility(View.GONE);
                        isShowCustomKeyboard = false;
                    }
                }
            }
            break;
        case R.id.icn_message_translate:
            translate = !translate;
            if (translate)
                messageTranslate.setTextColor(getResources().getColor(R.color.speak_all_red));
            else
                messageTranslate.setTextColor(getResources().getColor(R.color.speak_all_gray));
            break;
        case R.id.icn_message_clock:
            tiempoMensaje = false;
            temporizadorAcept.setVisibility(View.INVISIBLE);
            temporizadorSeek.setInitPosition(0);
            SharedPreferences settings1 = getActivity().getSharedPreferences(Finder.STRING.APP_PREF.toString(),
                    Context.MODE_PRIVATE);
            if (settings1.getInt("INPUTKEY", 0) != 0) {
                getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
            }
            if (!isShowCustomKeyboard) {
                if (!isShowKeyboard) {
                    keyboardLayout.setBackgroundColor(getResources().getColor(R.color.speak_all_ligh_gray_plus));
                    if (tiempoMensaje) {
                        messageClock.setText(Finder.STRING.ICN_TEMPORIZER_FILL.toString());
                        messageClock.setTextColor(getResources().getColor(R.color.speak_all_red));
                    } else {
                        messageClock.setTextColor(getResources().getColor(R.color.speak_all_gray));
                        messageClock.setText(Finder.STRING.ICN_TEMPORIZER_FILL.toString());
                    }
                    keyboardLayout.setVisibility(View.GONE);
                    AnimatorSet set = new AnimatorSet();
                    set.playTogether(ObjectAnimator.ofFloat(keyboardLayout, "alpha", 0, 1));
                    set.setDuration(220).start();
                    set.addListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            keyboardLayout.setVisibility(View.VISIBLE);
                        }

                        @Override
                        public void onAnimationCancel(Animator animation) {

                        }

                        @Override
                        public void onAnimationRepeat(Animator animation) {

                        }
                    });
                    customKeyboardLayout.setVisibility(View.VISIBLE);
                    customKeyboardAudio.setVisibility(View.GONE);
                    ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                        @Override
                        public void doBack() {
                            if (tiempoMensaje) {
                                messageClock.setText(Finder.STRING.ICN_TEMPORIZER_FILL.toString());
                                messageClock.setTextColor(getResources().getColor(R.color.speak_all_red));
                            } else {
                                messageClock.setText(Finder.STRING.ICN_TEMPORIZER.toString());
                                messageClock.setTextColor(getResources().getColor(R.color.speak_all_gray));
                            }
                            keyboardLayout.setVisibility(View.GONE);
                            customKeyboardLayout.setVisibility(View.GONE);
                            customKeyboardAudio.setVisibility(View.GONE);
                            isShowCustomKeyboard = false;
                            ((MainActivity) activity).setOnBackPressedListener(null);
                        }
                    });
                    isShowCustomKeyboard = true;
                    isShowKeyboard = false;
                } else {
                    keyboardLayout.setBackgroundColor(getResources().getColor(R.color.speak_all_ligh_gray_plus));
                    keyboardLayout.setVisibility(View.GONE);
                    AnimatorSet set = new AnimatorSet();
                    set.playTogether(ObjectAnimator.ofFloat(keyboardLayout, "alpha", 0, 1));
                    set.setDuration(220).start();
                    set.addListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            keyboardLayout.setVisibility(View.VISIBLE);
                        }

                        @Override
                        public void onAnimationCancel(Animator animation) {

                        }

                        @Override
                        public void onAnimationRepeat(Animator animation) {

                        }
                    });
                    hideKeyBoard();
                    ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                        @Override
                        public void doBack() {
                            if (tiempoMensaje) {
                                messageClock.setText(Finder.STRING.ICN_TEMPORIZER_FILL.toString());
                                messageClock.setTextColor(getResources().getColor(R.color.speak_all_red));
                            } else {
                                messageClock.setText(Finder.STRING.ICN_TEMPORIZER.toString());
                                messageClock.setTextColor(getResources().getColor(R.color.speak_all_gray));
                            }
                            keyboardLayout.setVisibility(View.GONE);
                            customKeyboardLayout.setVisibility(View.GONE);
                            customKeyboardAudio.setVisibility(View.GONE);
                            isShowCustomKeyboard = false;
                            ((MainActivity) activity).setOnBackPressedListener(null);
                        }
                    });
                    if (tiempoMensaje) {
                        messageClock.setText(Finder.STRING.ICN_TEMPORIZER_FILL.toString());
                        messageClock.setTextColor(getResources().getColor(R.color.speak_all_red));
                    } else {
                        messageClock.setTextColor(getResources().getColor(R.color.speak_all_gray));
                        messageClock.setText(Finder.STRING.ICN_TEMPORIZER_FILL.toString());
                    }
                    customKeyboardLayout.setVisibility(View.VISIBLE);
                    customKeyboardAudio.setVisibility(View.GONE);
                    isShowCustomKeyboard = true;
                    isShowKeyboard = false;
                }
            } else {
                customKeyboardAudio.setVisibility(View.GONE);
                if (!customKeyboardLayout.isShown()) {
                    customKeyboardLayout.setVisibility(View.VISIBLE);
                    if (tiempoMensaje) {
                        messageClock.setText(Finder.STRING.ICN_TEMPORIZER_FILL.toString());
                        messageClock.setTextColor(getResources().getColor(R.color.speak_all_red));
                    } else {
                        messageClock.setText(Finder.STRING.ICN_TEMPORIZER_FILL.toString());
                        messageClock.setTextColor(getResources().getColor(R.color.speak_all_gray));
                    }
                } else {
                    temporizadorAcept.setVisibility(View.INVISIBLE);
                    keyboardLayout.setVisibility(View.GONE);
                    customKeyboardLayout.setVisibility(View.GONE);
                    customKeyboardAudio.setVisibility(View.GONE);
                    isShowCustomKeyboard = false;
                    tiempoMensaje = false;
                    if (tiempoMensaje) {
                        messageClock.setTextColor(getResources().getColor(R.color.speak_all_red));
                        messageClock.setText(Finder.STRING.ICN_TEMPORIZER_FILL.toString());
                    } else {
                        messageClock.setTextColor(getResources().getColor(R.color.speak_all_gray));
                        messageClock.setText(Finder.STRING.ICN_TEMPORIZER.toString());
                    }
                }
            }
            break;
        case R.id.temporizador_cancel:
            temporizadorAcept.setVisibility(View.INVISIBLE);
            messageClock.setTextColor(getResources().getColor(R.color.speak_all_gray));
            messageClock.setText(Finder.STRING.ICN_TEMPORIZER.toString());
            keyboardLayout.setVisibility(View.GONE);
            customKeyboardLayout.setVisibility(View.GONE);
            customKeyboardAudio.setVisibility(View.GONE);
            temporizadorSeek.setInitPosition(0);
            isShowCustomKeyboard = false;
            tiempoMensaje = false;
            break;
        case R.id.temporizador_acept:
            temporizadorAcept.setVisibility(View.INVISIBLE);
            messageClock.setTextColor(getResources().getColor(R.color.speak_all_red));
            messageClock.setText(Finder.STRING.ICN_TEMPORIZER_FILL.toString());
            keyboardLayout.setVisibility(View.GONE);
            customKeyboardLayout.setVisibility(View.GONE);
            customKeyboardAudio.setVisibility(View.GONE);
            isShowCustomKeyboard = false;
            tiempoMensaje = true;
            if (!isShowKeyboard) {
                if (!isShowCustomKeyboard) {
                    messagesListScroll.setVerticalScrollBarEnabled(false);
                    final InputMethodManager imm = (InputMethodManager) activity
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (tiempoMensaje) {
                        messageClock.setText(Finder.STRING.ICN_TEMPORIZER_FILL.toString());
                        messageClock.setTextColor(getResources().getColor(R.color.speak_all_red));
                    } else {
                        messageClock.setText(Finder.STRING.ICN_TEMPORIZER.toString());
                        messageClock.setTextColor(getResources().getColor(R.color.speak_all_gray));
                    }
                    imm.showSoftInput(messageText, 0);
                    keyboardLayout.setVisibility(View.GONE);
                    AnimatorSet set = new AnimatorSet();
                    set.playTogether(ObjectAnimator.ofFloat(keyboardLayout, "alpha", 0, 1));
                    set.setDuration(220).start();
                    set.addListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            keyboardLayout.setVisibility(View.VISIBLE);
                        }

                        @Override
                        public void onAnimationCancel(Animator animation) {

                        }

                        @Override
                        public void onAnimationRepeat(Animator animation) {

                        }
                    });
                    keyboardLayout.setBackgroundColor(getResources().getColor(R.color.speak_all_ligh_gray_plus));
                    isShowKeyboard = true;
                    ((MainActivity) activity).setOnBackPressedListener(null);
                    customKeyboardLayout.setVisibility(View.GONE);
                    customKeyboardAudio.setVisibility(View.GONE);
                    isShowCustomKeyboard = false;
                } else {
                    keyboardLayout.setVisibility(View.GONE);
                    AnimatorSet set = new AnimatorSet();
                    set.playTogether(ObjectAnimator.ofFloat(keyboardLayout, "alpha", 0, 1));
                    set.setDuration(220).start();
                    set.addListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            keyboardLayout.setVisibility(View.VISIBLE);
                        }

                        @Override
                        public void onAnimationCancel(Animator animation) {

                        }

                        @Override
                        public void onAnimationRepeat(Animator animation) {

                        }
                    });
                    ((MainActivity) activity).setOnBackPressedListener(null);
                    messagesListScroll.setVerticalScrollBarEnabled(false);
                    if (tiempoMensaje) {
                        messageClock.setText(Finder.STRING.ICN_TEMPORIZER_FILL.toString());
                        messageClock.setTextColor(getResources().getColor(R.color.speak_all_red));
                    } else {
                        messageClock.setText(Finder.STRING.ICN_TEMPORIZER.toString());
                        messageClock.setTextColor(getResources().getColor(R.color.speak_all_gray));
                    }
                    final InputMethodManager imm = (InputMethodManager) activity
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(messageText, 0);
                    keyboardLayout.setBackgroundColor(getResources().getColor(R.color.speak_all_ligh_gray_plus));
                    isShowKeyboard = true;
                    customKeyboardLayout.setVisibility(View.GONE);
                    customKeyboardAudio.setVisibility(View.GONE);
                    isShowCustomKeyboard = false;
                }
            }
            break;
        case R.id._1:
            temporizadorSeek.setInitPosition(15);
            temporizadorAcept.setVisibility(View.VISIBLE);
            break;
        case R.id._2:
            temporizadorSeek.setInitPosition(30);
            temporizadorAcept.setVisibility(View.VISIBLE);
            break;
        case R.id._3:
            temporizadorSeek.setInitPosition(45);
            temporizadorAcept.setVisibility(View.VISIBLE);
            break;
        case R.id._4:
            temporizadorSeek.setInitPosition(60);
            temporizadorAcept.setVisibility(View.VISIBLE);
            break;
        case R.id._5:
            temporizadorSeek.setInitPosition(75);
            temporizadorAcept.setVisibility(View.VISIBLE);
            break;
        case R.id._6:
            temporizadorSeek.setInitPosition(90);
            temporizadorAcept.setVisibility(View.VISIBLE);
            break;
        case R.id._7:
            temporizadorSeek.setInitPosition(105);
            temporizadorAcept.setVisibility(View.VISIBLE);
            break;
        case R.id._8:
            temporizadorSeek.setInitPosition(120);
            temporizadorAcept.setVisibility(View.VISIBLE);
            break;
        case R.id._9:
            temporizadorSeek.setInitPosition(135);
            temporizadorAcept.setVisibility(View.VISIBLE);
            break;
        case R.id._10:
            temporizadorSeek.setInitPosition(150);
            temporizadorAcept.setVisibility(View.VISIBLE);
            break;
        case R.id._11:
            temporizadorSeek.setInitPosition(165);
            temporizadorAcept.setVisibility(View.VISIBLE);
            break;
        case R.id._12:
            temporizadorSeek.setInitPosition(180);
            temporizadorAcept.setVisibility(View.VISIBLE);
            break;
        case R.id.adjunt_image:
            System.gc();
            dontClose = true;
            ((MainActivity) activity).dontClose = true;
            hideKeyBoard();
            Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
            photoPickerIntent.setType("image/*");
            startActivityForResult(photoPickerIntent, 1);
            menuAdjunt = false;
            adjuntLayout.setVisibility(View.GONE);
            break;
        case R.id.adjunt_contact:
            System.gc();
            dontClose = true;
            ((MainActivity) activity).dontClose = true;
            hideKeyBoard();
            Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
            startActivityForResult(i, 34);
            menuAdjunt = false;
            adjuntLayout.setVisibility(View.GONE);
            break;
        case R.id.adjunt_audio:
            menuAdjunt = false;
            adjuntLayout.setVisibility(View.GONE);
            SharedPreferences settings2 = getActivity().getSharedPreferences(Finder.STRING.APP_PREF.toString(),
                    Context.MODE_PRIVATE);
            if (settings2.getInt("INPUTKEY", 0) != 0) {
                getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
            }
            if (!isShowCustomKeyboard) {
                if (!isShowKeyboard) {
                    keyboardLayout.setBackgroundColor(getResources().getColor(R.color.speak_all_ligh_gray_plus));
                    if (tiempoMensaje) {
                        messageClock.setText(Finder.STRING.ICN_TEMPORIZER_FILL.toString());
                        messageClock.setTextColor(getResources().getColor(R.color.speak_all_red));
                    } else {
                        messageClock.setTextColor(getResources().getColor(R.color.speak_all_gray));
                        messageClock.setText(Finder.STRING.ICN_TEMPORIZER.toString());
                    }
                    keyboardLayout.setVisibility(View.GONE);
                    AnimatorSet set4 = new AnimatorSet();
                    set4.playTogether(ObjectAnimator.ofFloat(keyboardLayout, "alpha", 0, 1));
                    set4.setDuration(220).start();
                    set4.addListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            keyboardLayout.setVisibility(View.VISIBLE);
                        }

                        @Override
                        public void onAnimationCancel(Animator animation) {

                        }

                        @Override
                        public void onAnimationRepeat(Animator animation) {

                        }
                    });
                    customKeyboardLayout.setVisibility(View.GONE);
                    customKeyboardAudio.setVisibility(View.VISIBLE);
                    ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                        @Override
                        public void doBack() {
                            if (tiempoMensaje) {
                                messageClock.setText(Finder.STRING.ICN_TEMPORIZER_FILL.toString());
                                messageClock.setTextColor(getResources().getColor(R.color.speak_all_red));
                            } else {
                                messageClock.setText(Finder.STRING.ICN_TEMPORIZER.toString());
                                messageClock.setTextColor(getResources().getColor(R.color.speak_all_gray));
                            }
                            keyboardLayout.setVisibility(View.GONE);
                            customKeyboardLayout.setVisibility(View.GONE);
                            customKeyboardAudio.setVisibility(View.GONE);
                            isShowCustomKeyboard = false;
                            ((MainActivity) activity).setOnBackPressedListener(null);
                        }
                    });
                    isShowCustomKeyboard = true;
                    isShowKeyboard = false;
                } else {
                    keyboardLayout.setBackgroundColor(getResources().getColor(R.color.speak_all_ligh_gray_plus));
                    keyboardLayout.setVisibility(View.GONE);
                    AnimatorSet set5 = new AnimatorSet();
                    set5.playTogether(ObjectAnimator.ofFloat(keyboardLayout, "alpha", 0, 1));
                    set5.setDuration(220).start();
                    set5.addListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            keyboardLayout.setVisibility(View.VISIBLE);
                        }

                        @Override
                        public void onAnimationCancel(Animator animation) {

                        }

                        @Override
                        public void onAnimationRepeat(Animator animation) {

                        }
                    });
                    hideKeyBoard();
                    ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                        @Override
                        public void doBack() {
                            if (tiempoMensaje) {
                                messageClock.setText(Finder.STRING.ICN_TEMPORIZER_FILL.toString());
                                messageClock.setTextColor(getResources().getColor(R.color.speak_all_red));
                            } else {
                                messageClock.setText(Finder.STRING.ICN_TEMPORIZER.toString());
                                messageClock.setTextColor(getResources().getColor(R.color.speak_all_gray));
                            }
                            keyboardLayout.setVisibility(View.GONE);
                            customKeyboardLayout.setVisibility(View.GONE);
                            customKeyboardAudio.setVisibility(View.GONE);
                            isShowCustomKeyboard = false;
                            ((MainActivity) activity).setOnBackPressedListener(null);
                        }
                    });
                    if (tiempoMensaje) {
                        messageClock.setText(Finder.STRING.ICN_TEMPORIZER_FILL.toString());
                        messageClock.setTextColor(getResources().getColor(R.color.speak_all_red));
                    } else {
                        messageClock.setTextColor(getResources().getColor(R.color.speak_all_gray));
                        messageClock.setText(Finder.STRING.ICN_TEMPORIZER.toString());
                    }
                    customKeyboardLayout.setVisibility(View.GONE);
                    customKeyboardAudio.setVisibility(View.VISIBLE);
                    isShowCustomKeyboard = true;
                    isShowKeyboard = false;
                }
            } else {
                customKeyboardLayout.setVisibility(View.GONE);
                if (!customKeyboardAudio.isShown()) {
                    customKeyboardAudio.setVisibility(View.VISIBLE);
                    if (tiempoMensaje) {
                        messageClock.setText(Finder.STRING.ICN_TEMPORIZER_FILL.toString());
                        messageClock.setTextColor(getResources().getColor(R.color.speak_all_red));
                    } else {
                        messageClock.setText(Finder.STRING.ICN_TEMPORIZER.toString());
                        messageClock.setTextColor(getResources().getColor(R.color.speak_all_gray));
                    }
                } else {
                    temporizadorAcept.setVisibility(View.INVISIBLE);
                    keyboardLayout.setVisibility(View.GONE);
                    customKeyboardLayout.setVisibility(View.GONE);
                    customKeyboardAudio.setVisibility(View.GONE);
                    isShowCustomKeyboard = false;
                }
            }
            break;
        case R.id.add_to_contacts:
            try {
                JSONArray jsonArr = new JSONArray();
                JSONObject jsonObj = new JSONObject();
                jsonObj.put(C.c_id_contact, contact.idContacto);
                RequestParams params = new RequestParams();
                params.put("contacts", jsonArr.put(jsonObj));
                addToContacts(params);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            break;
        case R.id.adjunt_photo:
            System.gc();
            dontClose = true;
            ((MainActivity) activity).dontClose = true;
            hideKeyBoard();
            File imagesFolder = new File(
                    Environment.getExternalStorageDirectory().getAbsolutePath() + "/SpeakOn/Image/Sent");
            imagesFolder.mkdirs();
            adjuntLayout.setVisibility(View.GONE);
            dateToCamera = Calendar.getInstance().getTimeInMillis();
            File image = new File(imagesFolder, dateToCamera + ".png");
            Uri uriSavedImage = Uri.fromFile(image);
            Intent pictureActionIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            pictureActionIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
            startActivityForResult(pictureActionIntent, 23);
            break;
        case R.id.adjunt_video:
            System.gc();
            dontClose = true;
            ((MainActivity) activity).dontClose = true;
            hideKeyBoard();
            Intent videoPickerIntent = new Intent(Intent.ACTION_PICK);
            videoPickerIntent.setType("video/*");
            startActivityForResult(videoPickerIntent, 18);
            menuAdjunt = false;
            adjuntLayout.setVisibility(View.GONE);
            break;
        case R.id.adjunt_location:
            adjuntLayout.setVisibility(View.GONE);
            hideKeyBoard();
            menuAdjunt = false;
            milocManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
            List<String> allProviders = milocManager.getAllProviders();
            boolean gpsProvider = false;
            boolean netProvider = false;
            for (String providerName : allProviders) {
                if (providerName.equals(LocationManager.GPS_PROVIDER)) {
                    gpsProvider = true;
                }
                if (providerName.equals(LocationManager.NETWORK_PROVIDER)) {
                    netProvider = true;
                }
            }
            checkCountryLocation(gpsProvider, netProvider);
            break;
        }
    }

    public void checkCountryLocation(final boolean gpsProvider, final boolean netProvider) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                boolean gpsEnabled = false;
                boolean networkEnabled = false;
                if (gpsProvider) {
                    gpsEnabled = milocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                }
                if (netProvider) {
                    networkEnabled = milocManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
                }
                if (gpsProvider && netProvider) {
                    if (!gpsEnabled && !networkEnabled) {
                        LayoutInflater dialogInflater = (LayoutInflater) activity
                                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                        dialogView = dialogInflater.inflate(R.layout.null_contact_dialog, null);
                        TextView mensaje = (TextView) dialogView.findViewById(R.id.dialog_add_contact);
                        mensaje.setText(getString(R.string.location_services));
                        final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity)
                                .setView(dialogView).setCancelable(true)
                                .setPositiveButton(R.string.add_contact_yes, null)
                                .setNegativeButton(R.string.add_contact_no, null);
                        finderDialog = dialogBuilder.show();
                        finderDialog.setCanceledOnTouchOutside(true);
                        finderDialog.getButton(DialogInterface.BUTTON_POSITIVE)
                                .setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        finderDialog.dismiss();
                                        System.gc();
                                        dontClose = true;
                                        ((MainActivity) activity).dontClose = true;
                                        hideKeyBoard();
                                        Intent intent = new Intent(
                                                android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                        startActivityForResult(intent, 45);
                                    }
                                });
                        finderDialog.getButton(DialogInterface.BUTTON_NEGATIVE)
                                .setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        finderDialog.dismiss();
                                    }
                                });
                    } else {
                        milocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
                                ConversationChatFragment.this);
                        milocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
                                ConversationChatFragment.this);
                    }
                }
            }
        });
    }

    public void addToContacts(RequestParams params) {
        SharedPreferences preferences = activity.getSharedPreferences(Finder.STRING.APP_PREF.toString(),
                Context.MODE_PRIVATE);
        SpeakHttp.turn(false);
        SpeakHttp.getS(
                "users/" + preferences.getString(Finder.STRING.SESSION_USER_ID.toString(), "") + "/contacts/find",
                params, new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        try {
                            JSONArray dataResponse = new JSONArray(response.getString("data_list"));
                            JSONObject contactdata = dataResponse.getJSONObject(0);
                            final Contact contacto = new Contact();
                            contacto.idContacto = contactdata.getString(C.c_id_contact);
                            contacto.fullName = contactdata.getString(C.c_full_name);
                            contacto.screenName = contactdata.getString(C.c_screen_name);
                            contacto.email = contactdata.getString(C.c_email);
                            contacto.phone = contactdata.getString(C.c_phone);
                            contacto.lang = contactdata.getString(C.c_language);
                            contacto.facebookId = contactdata.getString(C.c_facebook_id);
                            contacto.social = contactdata.getInt(C.c_social);
                            contacto.conected = contactdata.getBoolean(C.c_online);
                            contacto.isConversationOpen = contactdata.getInt(C.c_protected) == 1;
                            contacto.isLocked = contactdata.getBoolean(C.c_locked);
                            contacto.isFavourite = contactdata.getInt(C.c_favorite) == 1;
                            contacto.dateUpdated = ContactService.parserDate(contactdata.getString(C.c_updated_at));
                            contacto.photoLink = contactdata.getString(C.c_photo);
                            SpeakHttp.turn(false);
                            SpeakHttp.getS(
                                    "files/" + contactdata.getString(C.c_photo).replace(".png", "_thumb.png"), null,
                                    new BinaryHttpResponseHandler(C.photoTypes) {
                                        @Override
                                        public void onSuccess(int statusCode, Header[] headers, byte[] binaryData) {
                                            contacto.photo = binaryData;
                                            contact = contacto;
                                            setIconBarContent();
                                        }

                                        @Override
                                        public void onProgress(long bytesWritten, long totalSize) {
                                            System.gc();
                                        }

                                        @Override
                                        public void onFailure(int statusCode, Header[] headers, byte[] binaryData,
                                                Throwable error) {
                                        }

                                        @Override
                                        public void onFinish() {
                                            SpeakHttp.turn(true);
                                        }
                                    }, activity);
                            contacto.save();
                            Chats chat = new Select().from(Chats.class)
                                    .where("idContacto = ?", contactdata.getString(C.c_id_contact)).executeSingle();
                            if (chat != null) {
                                chat.photo = contacto.photo;
                                chat.photoload = true;
                                chat.fullName = contacto.fullName;
                                chat.lang = contacto.lang;
                                chat.screenName = contacto.screenName;
                                chat.phone = contacto.phone;
                                chat.save();
                            }
                            addToContacts.setVisibility(View.GONE);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onProgress(long bytesWritten, long totalSize) {
                        System.gc();
                    }

                    @Override
                    public void onFinish() {
                        SpeakHttp.turn(true);
                    }
                }, activity);
    }

    public void statuswriting() {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ((MainActivity) activity).actionBarDesc.setVisibility(View.VISIBLE);
                ((MainActivity) activity).actionBarDesc.setText(getString(R.string.status_writing));
                if (writingCounter == null) {
                    startCounterStatusWriting(3 * 1000);
                } else {
                    writingCounter.cancel();
                    startCounterStatusWriting(millisToWriting + 3000);
                }
            }
        });
    }

    public void contactLastSeen(JSONObject json) {
        try {
            boolean isOnline = json.getBoolean("connected");
            Log.e("Respuesta lastseen", json.toString());
            if (isOnline) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (ConversationChatFragment.this.isVisible()) {
                            ((MainActivity) activity).actionBarDesc.setVisibility(View.VISIBLE);
                            ((MainActivity) activity).actionBarDesc.setText(getString(R.string.online_status));
                        }
                    }
                });
            } else {
                String lastSeen = json.getString("last_seen");
                SimpleDateFormat formateador1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'.'SSS'Z'",
                        Locale.getDefault());
                formateador1.setTimeZone(TimeZone.getTimeZone("UTC"));
                String tiempo = lastSeen.substring(0, 23) + "Z";
                Calendar fecha = Calendar.getInstance();
                Date fecha1 = formateador1.parse(tiempo);
                fecha.setTimeZone(TimeZone.getDefault());
                fecha.setTimeInMillis(fecha1.getTime());
                String time = timeFormat1.format(fecha.getTime());
                String dayMessage = dateDay1.format(fecha.getTime());
                String monthMessage = dateMonth1.format(fecha.getTime());
                String yearMessage = dateYear1.format(fecha.getTime());
                String dayMessageText = dateDayText1.format(fecha.getTime());
                char[] caracteres = dayMessageText.toCharArray();
                caracteres[0] = Character.toUpperCase(caracteres[0]);
                dayMessageText = new String(caracteres);

                Calendar fechaActual = Calendar.getInstance();
                String dayActual = dateDay1.format(fechaActual.getTime());
                String monthActual = dateMonth1.format(fechaActual.getTime());
                String yearActual = dateYear1.format(fechaActual.getTime());

                String fechaMostrar = "";
                if (dayMessage.equals(dayActual) && monthMessage.equals(monthActual)
                        && yearMessage.equals(yearActual)) {
                    fechaMostrar = getString(R.string.messages_today);
                } else if (monthMessage.equals(monthActual) && yearMessage.equals(yearActual)) {
                    int days = Integer.parseInt(dayActual) - Integer.parseInt(dayMessage);
                    if (days < 7) {
                        switch (days) {
                        case 1:
                            fechaMostrar = getString(R.string.messages_yesterday);
                            break;
                        default:
                            fechaMostrar = dayMessageText;
                            break;
                        }
                    } else {
                        fechaMostrar = (dayMessage + " " + monthMessage + " " + yearMessage).toUpperCase();
                    }
                } else {
                    fechaMostrar = (dayMessage + " " + monthMessage + " " + yearMessage).toUpperCase();
                }

                final String finalFechaMostrar = fechaMostrar + " (" + time + ")";
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ((MainActivity) activity).actionBarDesc.setVisibility(View.VISIBLE);
                        ((MainActivity) activity).actionBarDesc.setText(finalFechaMostrar);
                    }
                });
            }
        } catch (JSONException e) {

        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    protected void hideKeyBoard() {
        isShowCustomKeyboard = false;
        isShowKeyboard = false;
        keyboardLayout.setVisibility(View.GONE);
        customKeyboardLayout.setVisibility(View.GONE);
        customKeyboardAudio.setVisibility(View.GONE);
        final InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
    }

    public void startCounterToDelete(long timer, final Message msj) {

        CountDownTimer aCounter = new CountDownTimer(timer, 1000) {

            public void onTick(long millisUntilFinished) {
                long days, hours, minutes, seconds;
                long secondsTotal = millisUntilFinished / 1000;
                days = (Math.round(secondsTotal) / 86400);
                hours = (Math.round(secondsTotal) / 3600) - (days * 24);
                minutes = (Math.round(secondsTotal) / 60) - (days * 1440) - (hours * 60);
                seconds = Math.round(secondsTotal) % 60;
            }

            public void onFinish() {
                if (ConversationChatFragment.this.isVisible()) {
                    new Delete().from(Message.class).where("mensajeId = ?", msj.mensajeId).execute();
                    View v = messagesList.findViewWithTag(msj.mensajeId);
                    if (v != null)
                        messagesList.removeView(v);

                } else {
                    ActiveAndroid.initialize(SpeakSocket.instance);
                    new Delete().from(Message.class).where("mensajeId = ?", msj.mensajeId).execute();

                }
                Message message = null;
                if (msj.emisor.equals(u.id)) {
                    message = new Select().from(Message.class)
                            .where("emisor = ? or receptor = ?", msj.receptor, msj.receptor)
                            .orderBy("emitedAt DESC").executeSingle();
                } else {
                    message = new Select().from(Message.class)
                            .where("emisor = ? or receptor = ?", msj.emisor, msj.emisor).orderBy("emitedAt DESC")
                            .executeSingle();
                }
                if (message != null) {
                    Chats chat = null;
                    if (msj.emisor.equals(u.id)) {
                        chat = new Select().from(Chats.class).where("idContacto = ?", msj.receptor).executeSingle();
                    } else {
                        chat = new Select().from(Chats.class).where("idContacto = ?", msj.emisor).executeSingle();
                    }
                    if (chat != null) {
                        chat.mensajeId = message.mensajeId;
                        chat.lastStatus = message.status;
                        chat.emitedAt = message.emitedAt;
                        chat.lang = message.emisorLang;
                        chat.notRead = 0;
                        if (chat.idContacto.equals(message.emisor))
                            chat.lastMessage = message.mensajeTrad;
                        else
                            chat.lastMessage = message.mensaje;
                        chat.save();
                    }
                } else {
                    if (msj.emisor.equals(u.id)) {
                        new Delete().from(Chats.class).where("idContacto = ?", msj.receptor).execute();
                    } else {
                        new Delete().from(Chats.class).where("idContacto = ?", msj.emisor).execute();
                    }
                }
            }
        };

        aCounter.start();
    }

    public void startCounterStatusWriting(long timer) {

        writingCounter = new CountDownTimer(timer, 1000) {

            public void onTick(long millisUntilFinished) {
                long days, hours, minutes, seconds;
                long secondsTotal = millisUntilFinished / 1000;
                days = (Math.round(secondsTotal) / 86400);
                hours = (Math.round(secondsTotal) / 3600) - (days * 24);
                minutes = (Math.round(secondsTotal) / 60) - (days * 1440) - (hours * 60);
                seconds = Math.round(secondsTotal) % 60;
                millisToWriting = millisUntilFinished;
            }

            public void onFinish() {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                    }
                });
                JSONObject dataLastSeen = new JSONObject();
                try {
                    dataLastSeen.put("source", u.id);
                    dataLastSeen.put("target", contact.idContacto);
                    if (SpeakSocket.mSocket != null)
                        if (SpeakSocket.mSocket.connected())
                            SpeakSocket.mSocket.emit("contact-lastseen", dataLastSeen);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                writingCounter = null;
            }
        };

        writingCounter.start();
    }

    public void messageDelete(final Message mensaje) {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.e("Borrando mensaje", "Borrando Mensaje");
                new Delete().from(Message.class).where("mensajeId = ?", mensaje.mensajeId).execute();
                Message message = new Select().from(Message.class)
                        .where("emisor = ? or receptor = ?", mensaje.receptor, mensaje.receptor)
                        .orderBy("emitedAt DESC").executeSingle();
                if (message != null) {
                    Chats chat = new Select().from(Chats.class).where("idContacto = ?", mensaje.receptor)
                            .executeSingle();
                    if (chat != null) {
                        chat.mensajeId = message.mensajeId;
                        chat.lastStatus = message.status;
                        chat.emitedAt = message.emitedAt;
                        chat.lang = message.emisorLang;
                        chat.notRead = 0;
                        if (chat.idContacto.equals(message.emisor))
                            chat.lastMessage = message.mensajeTrad;
                        else
                            chat.lastMessage = message.mensaje;
                        chat.save();
                    }
                } else {
                    new Delete().from(Chats.class).where("idContacto = ?", mensaje.receptor).execute();
                }
                View delete1 = messagesList.findViewWithTag(mensaje.mensajeId);
                if (delete1 != null)
                    messagesList.removeView(delete1);
                messageSelected = null;
                ((MainActivity) activity).setOnBackPressedListener(null);
            }
        });
    }

    public void showMensajeText(int position, Context context, final Message message, View rowView,
            TextView icnMessageArrow) {

        final TextView prevMessages = (TextView) rowView.findViewById(R.id.showprev_messages);
        TextView messageTime = (TextView) rowView.findViewById(R.id.message_time);
        final TextView icnMesajeTempo = (TextView) rowView.findViewById(R.id.icn_message_tempo);
        final View icnMensajeTempoDivider = (View) rowView.findViewById(R.id.icn_message_tempo_divider);
        final TextView icnMesajeCopy = (TextView) rowView.findViewById(R.id.icn_message_copy);
        final TextView icnMesajeBack = (TextView) rowView.findViewById(R.id.icn_message_back);
        final TextView messageContent = (TextView) rowView.findViewById(R.id.message_content);
        TextView messageStatus = (TextView) rowView.findViewById(R.id.message_status);
        final LinearLayout messageMenu = (LinearLayout) rowView.findViewById(R.id.messages_menu_layout);
        final LinearLayout mensajeLayout = (LinearLayout) rowView.findViewById(R.id.mensaje_layout);
        TextView messageDate = (TextView) rowView.findViewById(R.id.message_date);

        TFCache.apply(context, messageTime, TFCache.TF_WHITNEY_MEDIUM);
        TFCache.apply(context, messageContent, TFCache.TF_WHITNEY_MEDIUM);
        TFCache.apply(context, icnMesajeTempo, TFCache.TF_SPEAKALL);
        TFCache.apply(context, icnMesajeCopy, TFCache.TF_SPEAKALL);
        TFCache.apply(context, icnMesajeBack, TFCache.TF_SPEAKALL);
        TFCache.apply(context, messageStatus, TFCache.TF_SPEAKALL);
        TFCache.apply(context, prevMessages, TFCache.TF_WHITNEY_MEDIUM);
        TFCache.apply(context, messageDate, TFCache.TF_WHITNEY_MEDIUM);

        SharedPreferences pref = getActivity().getSharedPreferences(Finder.STRING.APP_PREF.toString(),
                Context.MODE_PRIVATE);

        if (position == 0) {
            if (mensajesTotal > mensajesOffset) {
                prevMessages.setVisibility(View.VISIBLE);
                prevMessages.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        prevMessages.setVisibility(View.GONE);
                        if (mensajesTotal - mensajesOffset >= 10) {
                            mensajesLimit = 10;
                            mensajesOffset += mensajesLimit;
                            showPreviousMessages(mensajesOffset);
                        } else {
                            mensajesLimit = mensajesTotal - mensajesOffset;
                            mensajesOffset += mensajesLimit;
                            showPreviousMessages(mensajesOffset);
                        }
                    }
                });
            }
        }

        DateFormat dateDay = new SimpleDateFormat("d");
        DateFormat dateDayText = new SimpleDateFormat("EEEE");
        DateFormat dateMonth = new SimpleDateFormat("MMMM");
        DateFormat dateYear = new SimpleDateFormat("yyyy");
        DateFormat timeFormat = new SimpleDateFormat("h:mm a");

        Calendar fechamsj = Calendar.getInstance();
        fechamsj.setTimeInMillis(message.emitedAt);
        String time = timeFormat.format(fechamsj.getTime());
        String dayMessage = dateDay.format(fechamsj.getTime());
        String monthMessage = dateMonth.format(fechamsj.getTime());
        String yearMessage = dateYear.format(fechamsj.getTime());
        String dayMessageText = dateDayText.format(fechamsj.getTime());
        char[] caracteres = dayMessageText.toCharArray();
        caracteres[0] = Character.toUpperCase(caracteres[0]);
        dayMessageText = new String(caracteres);

        Calendar fechaActual = Calendar.getInstance();
        String dayActual = dateDay.format(fechaActual.getTime());
        String monthActual = dateMonth.format(fechaActual.getTime());
        String yearActual = dateYear.format(fechaActual.getTime());

        String fechaMostrar = "";
        if (dayMessage.equals(dayActual) && monthMessage.equals(monthActual) && yearMessage.equals(yearActual)) {
            fechaMostrar = getString(R.string.messages_today);
        } else if (monthMessage.equals(monthActual) && yearMessage.equals(yearActual)) {
            int days = Integer.parseInt(dayActual) - Integer.parseInt(dayMessage);
            if (days < 7) {
                switch (days) {
                case 1:
                    fechaMostrar = getString(R.string.messages_yesterday);
                    break;
                default:
                    fechaMostrar = dayMessageText;
                    break;
                }
            } else {
                fechaMostrar = (dayMessage + " " + monthMessage + " " + yearMessage).toUpperCase();
            }
        } else {
            fechaMostrar = (dayMessage + " " + monthMessage + " " + yearMessage).toUpperCase();
        }

        messageDate.setText(fechaMostrar);
        if (position != -1) {

            if (itemAnterior != null) {
                if (!fechaMostrar.equals(fechaAnterior)) {
                    itemAnterior.findViewById(R.id.message_date).setVisibility(View.VISIBLE);
                } else {
                    itemAnterior.findViewById(R.id.message_date).setVisibility(View.GONE);
                }
            }
            itemAnterior = rowView;
            fechaAnterior = fechaMostrar;
        } else {
            View v = messagesList.getChildAt(messagesList.getChildCount() - 1);
            if (v != null) {
                TextView tv = (TextView) v.findViewById(R.id.message_date);
                if (tv.getText().toString().equals(fechaMostrar)) {
                    messageDate.setVisibility(View.GONE);
                } else {
                    messageDate.setVisibility(View.VISIBLE);
                }
            }
        }
        messageTime.setText(time);

        if (message.emisor.equals(u.id)) {

            messageContent.setText(message.mensaje);

            if (message.status != -1) {
                rowView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        if (messageSelected != null) {
                            View vista = messagesList.findViewWithTag(messageSelected);
                            vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                            messageSelected = message.mensajeId;
                            ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                                @Override
                                public void doBack() {
                                    View vista = messagesList.findViewWithTag(messageSelected);
                                    vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                                    ((MainActivity) activity).setOnBackPressedListener(null);
                                    messageSelected = null;
                                }
                            });
                        } else {
                            messageSelected = message.mensajeId;
                            ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                                @Override
                                public void doBack() {
                                    if (messageSelected != null) {
                                        View vista = messagesList.findViewWithTag(messageSelected);
                                        vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                                        ((MainActivity) activity).setOnBackPressedListener(null);
                                        messageSelected = null;
                                    }
                                }
                            });
                        }

                        Vibrator x = (Vibrator) activity.getApplicationContext()
                                .getSystemService(Context.VIBRATOR_SERVICE);
                        x.vibrate(30);
                        Message mensaje = new Select().from(Message.class).where("mensajeId = ?", message.mensajeId)
                                .executeSingle();
                        if (mensaje.status != 4) {
                            icnMesajeTempo.setVisibility(View.VISIBLE);
                            icnMensajeTempoDivider.setVisibility(View.VISIBLE);
                            icnMesajeCopy.setVisibility(View.VISIBLE);
                            icnMesajeBack.setVisibility(View.VISIBLE);
                            messageMenu.setVisibility(View.VISIBLE);
                            AnimatorSet set = new AnimatorSet();
                            set.playTogether(ObjectAnimator.ofFloat(icnMesajeTempo, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(icnMesajeTempo, "translationX", 150, 0),
                                    ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", 100, 0),
                                    ObjectAnimator.ofFloat(icnMesajeBack, "translationX", 50, 0));
                            set.setDuration(200).start();
                            set.addListener(new Animator.AnimatorListener() {
                                @Override
                                public void onAnimationStart(Animator animation) {

                                }

                                @Override
                                public void onAnimationEnd(Animator animation) {

                                }

                                @Override
                                public void onAnimationCancel(Animator animation) {

                                }

                                @Override
                                public void onAnimationRepeat(Animator animation) {

                                }
                            });
                        } else {
                            icnMesajeCopy.setVisibility(View.VISIBLE);
                            icnMesajeBack.setVisibility(View.VISIBLE);
                            messageMenu.setVisibility(View.VISIBLE);
                            AnimatorSet set = new AnimatorSet();
                            set.playTogether(ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", 100, 0),
                                    ObjectAnimator.ofFloat(icnMesajeBack, "translationX", 50, 0));
                            set.setDuration(200).start();
                            set.addListener(new Animator.AnimatorListener() {
                                @Override
                                public void onAnimationStart(Animator animation) {

                                }

                                @Override
                                public void onAnimationEnd(Animator animation) {

                                }

                                @Override
                                public void onAnimationCancel(Animator animation) {

                                }

                                @Override
                                public void onAnimationRepeat(Animator animation) {

                                }
                            });
                        }

                        return false;
                    }
                });
            }
            if (message.status == 1) {
                messageStatus.setTextSize(16);
                mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
                GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
                drawable.setCornerRadius(radius);
                drawable.setColor(BalloonFragment.getBackgroundColor(activity));
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
                messageStatus.setTextColor(getResources().getColor(R.color.speak_all_ligh_gray));
                messageStatus.setText(Finder.STRING.ICN_MSJ_SENDING.toString());
                ValueAnimator colorAnim = ObjectAnimator.ofFloat(messageStatus, "alpha", 1, 0);
                colorAnim.setRepeatCount(ValueAnimator.INFINITE);
                colorAnim.setRepeatMode(ValueAnimator.REVERSE);
                colorAnim.setDuration(1000).start();
                animaciones.put(message.mensajeId, colorAnim);
                JSONObject data = new JSONObject();
                try {
                    data.put("message_id", message.mensajeId);
                    data.put("source", message.emisor);
                    data.put("source_email", message.emisorEmail);
                    data.put("target_email", message.receptorEmail);
                    data.put("target", message.receptor);
                    data.put("message", message.mensaje);
                    data.put("source_lang", message.emisorLang);
                    data.put("delay", message.delay);
                    data.put("translation_required", message.translation);
                    data.put("target_lang", message.receptorLang);
                    data.put("type", message.tipo);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (SpeakSocket.mSocket != null)
                    if (SpeakSocket.mSocket.connected()) {
                        message.status = 1;
                        SpeakSocket.mSocket.emit("message", data);
                    } else {
                        message.status = -1;
                    }
            }
            if (message.status == -1) {
                messageStatus.setTextSize(11);
                mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
                GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
                drawable.setCornerRadius(radius);
                drawable.setColor(BalloonFragment.getBackgroundColor(activity));
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
                messageStatus.setText(Finder.STRING.ICN_MSJ_ERROR.toString());
            }
            if (message.status == 3) {
                messageStatus.setTextSize(11);
                mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
                GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
                drawable.setCornerRadius(radius);
                drawable.setColor(BalloonFragment.getBackgroundColor(activity));
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
                messageStatus.setText(Finder.STRING.ICN_MSJ_CLOSED.toString());
            }
            if (message.status == 2) {
                messageStatus.setTextSize(16);
                mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
                GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
                drawable.setCornerRadius(radius);
                drawable.setColor(BalloonFragment.getBackgroundColor(activity));
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
                messageStatus.setText(Finder.STRING.ICN_MSJ_SEND.toString());
            }
            if (message.status == 4) {
                messageStatus.setTextSize(11);
                mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
                GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
                drawable.setCornerRadius(radius);
                drawable.setColor(BalloonFragment.getBackgroundColor(activity));
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
                messageStatus.setText(Finder.STRING.ICN_MSJ_OPENED.toString());
                icnMensajeTempoDivider.setVisibility(View.GONE);
                icnMesajeTempo.setVisibility(View.GONE);
            } else {
                mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
                GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
                drawable.setCornerRadius(radius);
                drawable.setColor(BalloonFragment.getBackgroundColor(activity));
                icnMensajeTempoDivider.setVisibility(View.INVISIBLE);
                icnMesajeTempo.setVisibility(View.INVISIBLE);
            }

            icnMesajeTempo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    JSONObject notifyMessage = new JSONObject();
                    try {
                        Message mensaje = new Select().from(Message.class).where("mensajeId = ?", message.mensajeId)
                                .executeSingle();
                        Log.w("mensaje detail",
                                mensaje.status + " : " + mensaje.receptorEmail + " : " + mensaje.tipo);
                        if (mensaje.status != 4) {
                            notifyMessage.put("type", mensaje.tipo);
                            notifyMessage.put("message_id", mensaje.mensajeId);
                            notifyMessage.put("source", mensaje.emisor);
                            notifyMessage.put("target", mensaje.receptor);
                            notifyMessage.put("status", 5);
                            if (SpeakSocket.mSocket != null)
                                if (SpeakSocket.mSocket.connected())
                                    SpeakSocket.mSocket.emit("message-status", notifyMessage);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });

        } else {
            mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
            GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
            drawable.setCornerRadius(radius);
            if (message.tipo == 21)
                drawable.setColor(getResources().getColor(R.color.speakall_autoresponse));
            else
                drawable.setColor(BalloonFragment.getFriendBalloon(activity));

            if (message.tipo == Integer.parseInt(getString(R.string.MSG_TYPE_BROADCAST_TEXT))) {
                messageStatus.setTextSize(15);
                messageStatus.setText(Finder.STRING.ICN_BROADCAST_FILL.toString());
            }
            if (message.tipo == 21) {
                messageStatus.setTextSize(15);
                messageStatus.setTextColor(getResources().getColor(R.color.speak_all_white));
                TFCache.apply(activity, messageStatus, TFCache.TF_SPEAKON);
                messageStatus.setText(getResources().getString(R.string.icon_SpeakAll_rayo));
            }
            messageContent.setText(message.mensajeTrad);
            rowView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if (messageSelected != null) {
                        View vista = messagesList.findViewWithTag(messageSelected);
                        vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                        messageSelected = message.mensajeId;
                        ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                            @Override
                            public void doBack() {
                                View vista = messagesList.findViewWithTag(messageSelected);
                                vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                                ((MainActivity) activity).setOnBackPressedListener(null);
                                messageSelected = null;
                            }
                        });
                    } else {
                        messageSelected = message.mensajeId;
                        ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                            @Override
                            public void doBack() {
                                View vista = messagesList.findViewWithTag(messageSelected);
                                vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                                ((MainActivity) activity).setOnBackPressedListener(null);
                                messageSelected = null;
                            }
                        });
                    }

                    Vibrator x = (Vibrator) activity.getApplicationContext()
                            .getSystemService(Context.VIBRATOR_SERVICE);
                    x.vibrate(20);
                    if (!message.emisorLang.equals(message.receptorLang)) {
                        icnMesajeTempo.setVisibility(View.VISIBLE);
                        icnMesajeCopy.setVisibility(View.VISIBLE);
                        icnMesajeBack.setVisibility(View.VISIBLE);
                        messageMenu.setVisibility(View.VISIBLE);
                        AnimatorSet set = new AnimatorSet();
                        set.playTogether(ObjectAnimator.ofFloat(icnMesajeTempo, "alpha", 0, 1),
                                ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1),
                                ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1),
                                ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1),
                                ObjectAnimator.ofFloat(icnMesajeTempo, "translationX", -100, 0),
                                ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", -100, 0),
                                ObjectAnimator.ofFloat(icnMesajeBack, "translationX", -150, 0));
                        set.setDuration(200).start();
                        set.addListener(new Animator.AnimatorListener() {
                            @Override
                            public void onAnimationStart(Animator animation) {

                            }

                            @Override
                            public void onAnimationEnd(Animator animation) {

                            }

                            @Override
                            public void onAnimationCancel(Animator animation) {

                            }

                            @Override
                            public void onAnimationRepeat(Animator animation) {

                            }
                        });
                    } else {
                        icnMesajeTempo.setVisibility(View.GONE);
                        icnMensajeTempoDivider.setVisibility(View.GONE);
                        icnMesajeCopy.setVisibility(View.VISIBLE);
                        icnMesajeBack.setVisibility(View.VISIBLE);
                        messageMenu.setVisibility(View.VISIBLE);
                        AnimatorSet set = new AnimatorSet();
                        set.playTogether(ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1),
                                ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1),
                                ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1),
                                ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", -100, 0),
                                ObjectAnimator.ofFloat(icnMesajeBack, "translationX", -150, 0));
                        set.setDuration(200).start();
                        set.addListener(new Animator.AnimatorListener() {
                            @Override
                            public void onAnimationStart(Animator animation) {

                            }

                            @Override
                            public void onAnimationEnd(Animator animation) {

                            }

                            @Override
                            public void onAnimationCancel(Animator animation) {

                            }

                            @Override
                            public void onAnimationRepeat(Animator animation) {

                            }
                        });
                    }
                    return false;
                }
            });
            icnMesajeTempo.setOnClickListener(new View.OnClickListener() {
                boolean translation = true;

                @Override
                public void onClick(View v) {
                    translation = !translation;
                    if (translation) {
                        icnMesajeTempo.setTextColor(getResources().getColor(R.color.speak_all_red));
                        messageContent.setText(message.mensajeTrad);
                    } else {
                        icnMesajeTempo.setTextColor(getResources().getColor(R.color.speak_all_white));
                        messageContent.setText(message.mensaje);
                    }
                }
            });
        }

        if (message.orientation == 0) {
            messageContent.getViewTreeObserver()
                    .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                        @Override
                        public void onGlobalLayout() {
                            if (messageContent.getLineCount() > 1) {
                                mensajeLayout.setOrientation(LinearLayout.VERTICAL);
                                messageContent.setPadding(0, messageContent.getPaddingTop(), 0, 0);
                                new Update(Message.class).set("orientation = ?", 2)
                                        .where("mensajeId = ?", message.mensajeId).execute();
                                messageContent.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                            } else {
                                new Update(Message.class).set("orientation = ?", 1)
                                        .where("mensajeId = ?", message.mensajeId).execute();
                                messageContent.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                            }
                        }
                    });
        } else {
            if (message.orientation == 2) {
                mensajeLayout.setOrientation(LinearLayout.VERTICAL);
                messageContent.setPadding(0, messageContent.getPaddingTop(), 0, 0);
            }
        }

        icnMesajeCopy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ClipData clip = ClipData.newPlainText("text", messageContent.getText().toString());
                ClipboardManager clipboard = (ClipboardManager) getActivity()
                        .getSystemService(Context.CLIPBOARD_SERVICE);
                clipboard.setPrimaryClip(clip);
                Toast.makeText(activity, "Copiado", Toast.LENGTH_SHORT).show();
            }
        });

        icnMesajeBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (message.emisor.equals(u.id)) {
                    getFragmentManager().beginTransaction()
                            .replace(R.id.container2, ForwarForFragment.newInstance(message.mensaje))
                            .addToBackStack(null).commit();
                    ((MainActivity) activity).setOnBackPressedListener(null);
                } else {
                    getFragmentManager().beginTransaction()
                            .replace(R.id.container2, ForwarForFragment.newInstance(message.mensajeTrad))
                            .addToBackStack(null).commit();
                    ((MainActivity) activity).setOnBackPressedListener(null);
                }
            }
        });

        rowView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (messageSelected != null) {
                    View vista = messagesList.findViewWithTag(messageSelected);
                    if (!messageSelected.equals(message.mensajeId)) {
                        vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                        ((MainActivity) activity).setOnBackPressedListener(null);
                        messageSelected = null;
                    }
                }
                Message mensaje = new Select().from(Message.class).where("mensajeId = ?", message.mensajeId)
                        .executeSingle();
                if (mensaje.status == -1) {
                    String message = mensaje.mensaje;
                    JSONObject data = new JSONObject();
                    try {
                        data.put("message_id", mensaje.mensajeId);
                        data.put("source", mensaje.emisor);
                        data.put("source_email", mensaje.emisorEmail);
                        data.put("target_email", mensaje.receptorEmail);
                        data.put("target", mensaje.receptor);
                        data.put("message", message);
                        data.put("source_lang", mensaje.emisorLang);
                        data.put("delay", mensaje.delay);
                        data.put("translation_required", mensaje.translation);
                        data.put("target_lang", mensaje.receptorLang);
                        data.put("type", mensaje.tipo);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (SpeakSocket.mSocket != null)
                        if (SpeakSocket.mSocket.connected()) {
                            mensaje.status = 1;
                            SpeakSocket.mSocket.emit("message", data);
                        } else {
                            mensaje.status = -1;
                        }
                    changeStatus(mensaje.mensajeId, mensaje.status);
                }
            }
        });
    }

    public void showMensajePhoto(int position, Context context, final Message message, View rowView,
            TextView icnMessageArrow) {
        final TextView prevMessages = (TextView) rowView.findViewById(R.id.showprev_messages);
        TextView messageTime = (TextView) rowView.findViewById(R.id.message_time);
        final TextView icnMesajeTempo = (TextView) rowView.findViewById(R.id.icn_message_tempo);
        final View icnMensajeTempoDivider = (View) rowView.findViewById(R.id.icn_message_tempo_divider);
        final TextView icnMesajeCopy = (TextView) rowView.findViewById(R.id.icn_message_copy);
        final TextView icnMesajeBack = (TextView) rowView.findViewById(R.id.icn_message_back);
        final ImageView messageContent = (ImageView) rowView.findViewById(R.id.message_content);
        TextView messageStatus = (TextView) rowView.findViewById(R.id.message_status);
        final LinearLayout messageMenu = (LinearLayout) rowView.findViewById(R.id.messages_menu_layout);
        final LinearLayout mensajeLayout = (LinearLayout) rowView.findViewById(R.id.mensaje_layout);
        TextView messageDate = (TextView) rowView.findViewById(R.id.message_date);
        final ProgressBar progressBar = (ProgressBar) rowView.findViewById(R.id.progress_bar);
        final RelativeLayout progressLayout = (RelativeLayout) rowView.findViewById(R.id.progress_layout);
        final TextView progressText = (TextView) rowView.findViewById(R.id.progress_message);

        TFCache.apply(context, messageTime, TFCache.TF_WHITNEY_MEDIUM);
        TFCache.apply(context, icnMesajeTempo, TFCache.TF_SPEAKALL);
        TFCache.apply(context, icnMesajeCopy, TFCache.TF_SPEAKALL);
        TFCache.apply(context, icnMesajeBack, TFCache.TF_SPEAKALL);
        TFCache.apply(context, messageStatus, TFCache.TF_SPEAKALL);
        TFCache.apply(context, prevMessages, TFCache.TF_WHITNEY_MEDIUM);
        TFCache.apply(context, messageDate, TFCache.TF_WHITNEY_MEDIUM);

        if (position == 0) {
            if (mensajesTotal > mensajesOffset) {
                prevMessages.setVisibility(View.VISIBLE);
                prevMessages.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        prevMessages.setVisibility(View.GONE);
                        if (mensajesTotal - mensajesOffset >= 10) {
                            mensajesLimit = 10;
                            mensajesOffset += mensajesLimit;
                            showPreviousMessages(mensajesOffset);
                        } else {
                            mensajesLimit = mensajesTotal - mensajesOffset;
                            mensajesOffset += mensajesLimit;
                            showPreviousMessages(mensajesOffset);
                        }
                    }
                });
            }
        }

        DateFormat dateDay = new SimpleDateFormat("d");
        DateFormat dateDayText = new SimpleDateFormat("EEEE");
        DateFormat dateMonth = new SimpleDateFormat("MMMM");
        DateFormat dateYear = new SimpleDateFormat("yyyy");
        DateFormat timeFormat = new SimpleDateFormat("h:mm a");

        Calendar fechamsj = Calendar.getInstance();
        fechamsj.setTimeInMillis(message.emitedAt);
        String time = timeFormat.format(fechamsj.getTime());
        String dayMessage = dateDay.format(fechamsj.getTime());
        String monthMessage = dateMonth.format(fechamsj.getTime());
        String yearMessage = dateYear.format(fechamsj.getTime());
        String dayMessageText = dateDayText.format(fechamsj.getTime());
        char[] caracteres = dayMessageText.toCharArray();
        caracteres[0] = Character.toUpperCase(caracteres[0]);
        dayMessageText = new String(caracteres);

        Calendar fechaActual = Calendar.getInstance();
        String dayActual = dateDay.format(fechaActual.getTime());
        String monthActual = dateMonth.format(fechaActual.getTime());
        String yearActual = dateYear.format(fechaActual.getTime());

        String fechaMostrar = "";
        if (dayMessage.equals(dayActual) && monthMessage.equals(monthActual) && yearMessage.equals(yearActual)) {
            fechaMostrar = getString(R.string.messages_today);
        } else if (monthMessage.equals(monthActual) && yearMessage.equals(yearActual)) {
            int days = Integer.parseInt(dayActual) - Integer.parseInt(dayMessage);
            if (days < 7) {
                switch (days) {
                case 1:
                    fechaMostrar = getString(R.string.messages_yesterday);
                    break;
                default:
                    fechaMostrar = dayMessageText;
                    break;
                }
            } else {
                fechaMostrar = (dayMessage + " " + monthMessage + " " + yearMessage).toUpperCase();
            }
        } else {
            fechaMostrar = (dayMessage + " " + monthMessage + " " + yearMessage).toUpperCase();
        }

        messageDate.setText(fechaMostrar);
        if (position != -1) {
            if (itemAnterior != null) {
                if (!fechaMostrar.equals(fechaAnterior)) {
                    itemAnterior.findViewById(R.id.message_date).setVisibility(View.VISIBLE);
                } else {
                    itemAnterior.findViewById(R.id.message_date).setVisibility(View.GONE);
                }
            }
            itemAnterior = rowView;
            fechaAnterior = fechaMostrar;
        } else {
            View v = messagesList.getChildAt(messagesList.getChildCount() - 1);
            if (v != null) {
                TextView tv = (TextView) v.findViewById(R.id.message_date);
                if (tv.getText().toString().equals(fechaMostrar)) {
                    messageDate.setVisibility(View.GONE);
                } else {
                    messageDate.setVisibility(View.VISIBLE);
                }
            }
        }
        messageTime.setText(time);
        if (message.emisor.equals(u.id)) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (message.fileUploaded) {
                                if (message.photo != null) {
                                    Bitmap bmp = BitmapFactory.decodeByteArray(message.photo, 0,
                                            message.photo.length);
                                    messageContent.setImageBitmap(bmp);
                                    bmp = null;
                                }
                            } else {
                                if (message.photoBlur != null) {
                                    Bitmap bmp = BitmapFactory.decodeByteArray(message.photoBlur, 0,
                                            message.photoBlur.length);
                                    messageContent.setImageBitmap(bmp);
                                    bmp = null;
                                }
                            }
                        }
                    });
                }
            }).start();
            if (message.status != -1) {
                rowView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        if (messageSelected != null) {
                            View vista = messagesList.findViewWithTag(messageSelected);
                            vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                            messageSelected = message.mensajeId;
                            ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                                @Override
                                public void doBack() {
                                    View vista = messagesList.findViewWithTag(messageSelected);
                                    vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                                    ((MainActivity) activity).setOnBackPressedListener(null);
                                    messageSelected = null;
                                }
                            });
                        } else {
                            messageSelected = message.mensajeId;
                            ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                                @Override
                                public void doBack() {
                                    if (messageSelected != null) {
                                        View vista = messagesList.findViewWithTag(messageSelected);
                                        vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                                        ((MainActivity) activity).setOnBackPressedListener(null);
                                        messageSelected = null;
                                    }
                                }
                            });
                        }

                        Vibrator x = (Vibrator) activity.getApplicationContext()
                                .getSystemService(Context.VIBRATOR_SERVICE);
                        x.vibrate(30);
                        Message mensaje = new Select().from(Message.class).where("mensajeId = ?", message.mensajeId)
                                .executeSingle();
                        if (mensaje.status != 4) {
                            icnMesajeTempo.setVisibility(View.VISIBLE);
                            icnMensajeTempoDivider.setVisibility(View.VISIBLE);
                            icnMesajeCopy.setVisibility(View.VISIBLE);
                            icnMesajeBack.setVisibility(View.VISIBLE);
                            messageMenu.setVisibility(View.VISIBLE);
                            AnimatorSet set = new AnimatorSet();
                            set.playTogether(ObjectAnimator.ofFloat(icnMesajeTempo, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(icnMesajeTempo, "translationX", 150, 0),
                                    ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", 100, 0),
                                    ObjectAnimator.ofFloat(icnMesajeBack, "translationX", 50, 0));
                            set.setDuration(200).start();
                        } else {
                            icnMesajeCopy.setVisibility(View.VISIBLE);
                            icnMesajeBack.setVisibility(View.VISIBLE);
                            messageMenu.setVisibility(View.VISIBLE);
                            AnimatorSet set = new AnimatorSet();
                            set.playTogether(ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", 100, 0),
                                    ObjectAnimator.ofFloat(icnMesajeBack, "translationX", 50, 0));
                            set.setDuration(200).start();
                        }

                        return false;
                    }
                });
            }
            if (message.status == 1) {
                messageStatus.setTextSize(16);
                mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
                GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
                drawable.setCornerRadius(radius);
                drawable.setColor(BalloonFragment.getBackgroundColor(activity));
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
                messageStatus.setTextColor(getResources().getColor(R.color.speak_all_ligh_gray));
                messageStatus.setText(Finder.STRING.ICN_MSJ_SENDING.toString());
                ValueAnimator colorAnim = ObjectAnimator.ofFloat(messageStatus, "alpha", 1, 0);
                colorAnim.setRepeatCount(ValueAnimator.INFINITE);
                colorAnim.setRepeatMode(ValueAnimator.REVERSE);
                colorAnim.setDuration(1000).start();
                animaciones.put(message.mensajeId, colorAnim);
                try {
                    final JSONObject mensaje = new JSONObject();
                    mensaje.put("message_id", message.mensajeId);
                    mensaje.put("source", message.emisor);
                    mensaje.put("source_email", message.emisorEmail);
                    mensaje.put("target_email", message.receptorEmail);
                    mensaje.put("target", message.receptor);
                    mensaje.put("type", message.tipo);
                    mensaje.put("delay", message.delay);
                    if (!message.fileUploaded) {
                        progressLayout.setVisibility(View.VISIBLE);
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        uploadPhotoToServer(message.photoName, message, mensaje, progressBar,
                                                progressLayout, progressText, messageContent);
                                    }
                                });
                            }
                        }).start();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            if (message.status == -1) {
                messageStatus.setTextSize(11);
                mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
                GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
                drawable.setCornerRadius(radius);
                drawable.setColor(BalloonFragment.getBackgroundColor(activity));
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
                messageStatus.setText(Finder.STRING.ICN_MSJ_ERROR.toString());
            }
            if (message.status == 3) {
                messageStatus.setTextSize(11);
                mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
                GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
                drawable.setCornerRadius(radius);
                drawable.setColor(BalloonFragment.getBackgroundColor(activity));
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
                messageStatus.setText(Finder.STRING.ICN_MSJ_CLOSED.toString());
            }
            if (message.status == 2) {
                messageStatus.setTextSize(16);
                mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
                GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
                drawable.setCornerRadius(radius);
                drawable.setColor(BalloonFragment.getBackgroundColor(activity));
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
                messageStatus.setText(Finder.STRING.ICN_MSJ_SEND.toString());
            }
            if (message.status == 4) {
                messageStatus.setTextSize(11);
                mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
                GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
                drawable.setCornerRadius(radius);
                drawable.setColor(BalloonFragment.getBackgroundColor(activity));
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
                messageStatus.setText(Finder.STRING.ICN_MSJ_OPENED.toString());
                icnMensajeTempoDivider.setVisibility(View.GONE);
                icnMesajeTempo.setVisibility(View.GONE);
            } else {
                icnMensajeTempoDivider.setVisibility(View.INVISIBLE);
                icnMesajeTempo.setVisibility(View.INVISIBLE);
            }

        } else {
            mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
            GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
            drawable.setCornerRadius(radius);
            drawable.setColor(BalloonFragment.getFriendBalloon(activity));
            if (message.tipo == Integer.parseInt(getString(R.string.MSG_TYPE_BROADCAST_PHOTO))) {
                messageStatus.setTextSize(15);
                messageStatus.setText(Finder.STRING.ICN_BROADCAST_FILL.toString());
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            File archivo = new File(message.photoName);
                            if (archivo.exists()) {
                                if (message.photo != null) {
                                    Bitmap bmp = BitmapFactory.decodeByteArray(message.photo, 0,
                                            message.photo.length);
                                    messageContent.setImageBitmap(bmp);
                                    bmp = null;
                                }
                            } else {
                                if (message.photoBlur != null) {
                                    Bitmap bmp = BitmapFactory.decodeByteArray(message.photoBlur, 0,
                                            message.photoBlur.length);
                                    messageContent.setImageBitmap(bmp);
                                    bmp = null;
                                }
                            }
                        }
                    });
                }
            }).start();
            //messageContent.setText(message.mensajeTrad);
            icnMesajeTempo.setVisibility(View.GONE);
            rowView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if (messageSelected != null) {
                        View vista = messagesList.findViewWithTag(messageSelected);
                        vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                        messageSelected = message.mensajeId;
                        ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                            @Override
                            public void doBack() {
                                View vista = messagesList.findViewWithTag(messageSelected);
                                vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                                ((MainActivity) activity).setOnBackPressedListener(null);
                                messageSelected = null;
                            }
                        });
                    } else {
                        messageSelected = message.mensajeId;
                        ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                            @Override
                            public void doBack() {
                                View vista = messagesList.findViewWithTag(messageSelected);
                                vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                                ((MainActivity) activity).setOnBackPressedListener(null);
                                messageSelected = null;
                            }
                        });
                    }

                    Vibrator x = (Vibrator) activity.getApplicationContext()
                            .getSystemService(Context.VIBRATOR_SERVICE);
                    x.vibrate(20);
                    icnMesajeCopy.setVisibility(View.VISIBLE);
                    icnMesajeBack.setVisibility(View.VISIBLE);
                    messageMenu.setVisibility(View.VISIBLE);
                    AnimatorSet set = new AnimatorSet();
                    set.playTogether(ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1),
                            ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1),
                            ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1),
                            ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", -100, 0),
                            ObjectAnimator.ofFloat(icnMesajeBack, "translationX", -150, 0));
                    set.setDuration(200).start();
                    return false;
                }
            });
        }

        icnMesajeTempo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                JSONObject notifyMessage = new JSONObject();
                try {
                    Message mensaje = new Select().from(Message.class).where("mensajeId = ?", message.mensajeId)
                            .executeSingle();
                    if (mensaje.status != 4) {
                        notifyMessage.put("type", mensaje.tipo);
                        notifyMessage.put("message_id", mensaje.mensajeId);
                        notifyMessage.put("source", mensaje.receptor);
                        notifyMessage.put("status", 5);
                        SpeakSocket.mSocket.emit("message-status", notifyMessage);
                    }
                    new Delete().from(Message.class).where("mensajeId = ?", mensaje.mensajeId).execute();
                    Message message = null;
                    if (mensaje.emisor.equals(u.id)) {
                        message = new Select().from(Message.class)
                                .where("emisor = ? or receptor = ?", mensaje.receptor, mensaje.receptor)
                                .orderBy("emitedAt DESC").executeSingle();
                    } else {
                        message = new Select().from(Message.class)
                                .where("emisor = ? or receptor = ?", mensaje.emisor, mensaje.emisor)
                                .orderBy("emitedAt DESC").executeSingle();
                    }
                    if (message != null) {
                        Chats chat = null;
                        if (mensaje.emisor.equals(u.id)) {
                            chat = new Select().from(Chats.class).where("idContacto = ?", mensaje.receptor)
                                    .executeSingle();
                        } else {
                            chat = new Select().from(Chats.class).where("idContacto = ?", mensaje.emisor)
                                    .executeSingle();
                        }
                        if (chat != null) {
                            chat.mensajeId = message.mensajeId;
                            chat.lastStatus = message.status;
                            chat.emitedAt = message.emitedAt;
                            chat.lang = message.emisorLang;
                            chat.notRead = 0;
                            if (chat.idContacto.equals(message.emisor))
                                chat.lastMessage = message.mensajeTrad;
                            else
                                chat.lastMessage = message.mensaje;
                            chat.save();
                        }
                    } else {
                        if (mensaje.emisor.equals(u.id)) {
                            new Delete().from(Chats.class).where("idContacto = ?", mensaje.receptor).execute();
                        } else {
                            new Delete().from(Chats.class).where("idContacto = ?", mensaje.emisor).execute();
                        }
                    }

                    View delete = messagesList.findViewWithTag(mensaje.mensajeId);
                    if (delete != null)
                        messagesList.removeView(delete);
                    messageSelected = null;
                    ((MainActivity) activity).setOnBackPressedListener(null);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        );

        icnMesajeCopy.setOnClickListener(new View.OnClickListener()

        {
            @Override
            public void onClick(View v) {
                /*ClipData clip = ClipData.newPlainText("text", messageContent.getText().toString());
                ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                clipboard.setPrimaryClip(clip);
                Toast.makeText(activity, "Copiado", Toast.LENGTH_SHORT).show();*/
            }
        }

        );

        icnMesajeBack.setOnClickListener(new View.OnClickListener()

        {
            @Override
            public void onClick(View v) {
                if (message.emisor.equals(u.id)) {
                    getFragmentManager().beginTransaction()
                            .replace(R.id.container2, ForwarForFragment.newInstance(message.mensaje))
                            .addToBackStack(null).commit();
                    ((MainActivity) activity).setOnBackPressedListener(null);
                } else {
                    getFragmentManager().beginTransaction()
                            .replace(R.id.container2, ForwarForFragment.newInstance(message.mensajeTrad))
                            .addToBackStack(null).commit();
                    ((MainActivity) activity).setOnBackPressedListener(null);
                }
            }
        }

        );

        rowView.setOnClickListener(new View.OnClickListener()

        {
            @Override
            public void onClick(View v) {
                Message mensaje = new Select().from(Message.class).where("mensajeId = ?", message.mensajeId)
                        .executeSingle();
                if (messageSelected != null) {
                    View vista = messagesList.findViewWithTag(messageSelected);
                    if (!messageSelected.equals(message.mensajeId)) {
                        vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                        ((MainActivity) activity).setOnBackPressedListener(null);
                        messageSelected = null;
                    }
                } else {
                    if (mensaje.fileDownloaded || mensaje.fileUploaded) {
                        if (mensaje.status != -1) {
                            dontClose = true;
                            ((MainActivity) activity).dontClose = true;
                            hideKeyBoard();
                            Intent i = new Intent();
                            i.setAction(android.content.Intent.ACTION_VIEW);
                            File videoFile2Play2 = new File(message.photoName);
                            i.setDataAndType(Uri.fromFile(videoFile2Play2), "image/*");
                            startActivity(i);
                        }
                    }
                }
                if (mensaje.status == -1) {
                    String message = mensaje.mensaje;
                    JSONObject data = new JSONObject();
                    try {
                        data.put("message_id", mensaje.mensajeId);
                        data.put("source", mensaje.emisor);
                        data.put("source_email", mensaje.emisorEmail);
                        data.put("target_email", mensaje.receptorEmail);
                        data.put("target", mensaje.receptor);
                        data.put("message", message);
                        data.put("source_lang", mensaje.emisorLang);
                        data.put("delay", mensaje.delay);
                        data.put("type", mensaje.tipo);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (SpeakSocket.mSocket != null)
                        if (SpeakSocket.mSocket.connected()) {
                            mensaje.status = 1;
                            SpeakSocket.mSocket.emit("message", data);
                        } else {
                            mensaje.status = -1;
                        }
                    changeStatus(mensaje.mensajeId, mensaje.status);
                }
            }
        }

        );

    }

    public void showMensajeLocation(int position, Context context, final Message message, View rowView,
            TextView icnMessageArrow) {
        final TextView prevMessages = (TextView) rowView.findViewById(R.id.showprev_messages);
        TextView messageTime = (TextView) rowView.findViewById(R.id.message_time);
        final TextView icnMesajeTempo = (TextView) rowView.findViewById(R.id.icn_message_tempo);
        final View icnMensajeTempoDivider = (View) rowView.findViewById(R.id.icn_message_tempo_divider);
        final TextView icnMesajeCopy = (TextView) rowView.findViewById(R.id.icn_message_copy);
        final TextView icnMesajeBack = (TextView) rowView.findViewById(R.id.icn_message_back);
        final ImageView messageContent = (ImageView) rowView.findViewById(R.id.message_content);
        TextView messageStatus = (TextView) rowView.findViewById(R.id.message_status);
        final LinearLayout messageMenu = (LinearLayout) rowView.findViewById(R.id.messages_menu_layout);
        final LinearLayout mensajeLayout = (LinearLayout) rowView.findViewById(R.id.mensaje_layout);
        TextView messageDate = (TextView) rowView.findViewById(R.id.message_date);
        TextView messageLocationText = (TextView) rowView.findViewById(R.id.message_location_text);
        TextView messageLocationIcon = (TextView) rowView.findViewById(R.id.message_location_icon);

        TFCache.apply(context, messageTime, TFCache.TF_WHITNEY_MEDIUM);
        TFCache.apply(context, icnMesajeTempo, TFCache.TF_SPEAKALL);
        TFCache.apply(context, icnMesajeCopy, TFCache.TF_SPEAKALL);
        TFCache.apply(context, icnMesajeBack, TFCache.TF_SPEAKALL);
        TFCache.apply(context, messageStatus, TFCache.TF_SPEAKALL);
        TFCache.apply(context, messageStatus, TFCache.TF_SPEAKALL);
        TFCache.apply(context, messageLocationIcon, TFCache.TF_SPEAKALL);
        TFCache.apply(context, messageDate, TFCache.TF_WHITNEY_MEDIUM);
        TFCache.apply(context, messageLocationText, TFCache.TF_WHITNEY_MEDIUM);

        if (position == 0) {
            if (mensajesTotal > mensajesOffset) {
                prevMessages.setVisibility(View.VISIBLE);
                prevMessages.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        prevMessages.setVisibility(View.GONE);
                        if (mensajesTotal - mensajesOffset >= 10) {
                            mensajesLimit = 10;
                            mensajesOffset += mensajesLimit;
                            showPreviousMessages(mensajesOffset);
                        } else {
                            mensajesLimit = mensajesTotal - mensajesOffset;
                            mensajesOffset += mensajesLimit;
                            showPreviousMessages(mensajesOffset);
                        }
                    }
                });
            }
        }
        double latitud = 0;
        double longitud = 0;
        try {
            JSONObject locationData = new JSONObject(message.mensaje);
            messageLocationText.setText(locationData.getString("direccion"));
            latitud = Double.parseDouble(locationData.getString("latitud"));
            longitud = Double.parseDouble(locationData.getString("longitud"));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        DateFormat dateDay = new SimpleDateFormat("d");
        DateFormat dateDayText = new SimpleDateFormat("EEEE");
        DateFormat dateMonth = new SimpleDateFormat("MMMM");
        DateFormat dateYear = new SimpleDateFormat("yyyy");
        DateFormat timeFormat = new SimpleDateFormat("h:mm a");

        Calendar fechamsj = Calendar.getInstance();
        fechamsj.setTimeInMillis(message.emitedAt);
        String time = timeFormat.format(fechamsj.getTime());
        String dayMessage = dateDay.format(fechamsj.getTime());
        String monthMessage = dateMonth.format(fechamsj.getTime());
        String yearMessage = dateYear.format(fechamsj.getTime());
        String dayMessageText = dateDayText.format(fechamsj.getTime());
        char[] caracteres = dayMessageText.toCharArray();
        caracteres[0] = Character.toUpperCase(caracteres[0]);
        dayMessageText = new String(caracteres);

        Calendar fechaActual = Calendar.getInstance();
        String dayActual = dateDay.format(fechaActual.getTime());
        String monthActual = dateMonth.format(fechaActual.getTime());
        String yearActual = dateYear.format(fechaActual.getTime());

        String fechaMostrar = "";
        if (dayMessage.equals(dayActual) && monthMessage.equals(monthActual) && yearMessage.equals(yearActual)) {
            fechaMostrar = getString(R.string.messages_today);
        } else if (monthMessage.equals(monthActual) && yearMessage.equals(yearActual)) {
            int days = Integer.parseInt(dayActual) - Integer.parseInt(dayMessage);
            if (days < 7) {
                switch (days) {
                case 1:
                    fechaMostrar = getString(R.string.messages_yesterday);
                    break;
                default:
                    fechaMostrar = dayMessageText;
                    break;
                }
            } else {
                fechaMostrar = (dayMessage + " " + monthMessage + " " + yearMessage).toUpperCase();
            }
        } else {
            fechaMostrar = (dayMessage + " " + monthMessage + " " + yearMessage).toUpperCase();
        }

        messageDate.setText(fechaMostrar);
        if (position != -1) {
            if (itemAnterior != null) {
                if (!fechaMostrar.equals(fechaAnterior)) {
                    itemAnterior.findViewById(R.id.message_date).setVisibility(View.VISIBLE);
                } else {
                    itemAnterior.findViewById(R.id.message_date).setVisibility(View.GONE);
                }
            }
            itemAnterior = rowView;
            fechaAnterior = fechaMostrar;
        } else {
            View v = messagesList.getChildAt(messagesList.getChildCount() - 1);
            if (v != null) {
                TextView tv = (TextView) v.findViewById(R.id.message_date);
                if (tv.getText().toString().equals(fechaMostrar)) {
                    messageDate.setVisibility(View.GONE);
                } else {
                    messageDate.setVisibility(View.VISIBLE);
                }
            }
        }
        messageTime.setText(time);

        if (message.emisor.equals(u.id))

        {
            if (message.status != -1) {
                rowView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        if (messageSelected != null) {
                            View vista = messagesList.findViewWithTag(messageSelected);
                            vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                            messageSelected = message.mensajeId;
                            ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                                @Override
                                public void doBack() {
                                    View vista = messagesList.findViewWithTag(messageSelected);
                                    vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                                    ((MainActivity) activity).setOnBackPressedListener(null);
                                    messageSelected = null;
                                }
                            });
                        } else {
                            messageSelected = message.mensajeId;
                            ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                                @Override
                                public void doBack() {
                                    if (messageSelected != null) {
                                        View vista = messagesList.findViewWithTag(messageSelected);
                                        vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                                        ((MainActivity) activity).setOnBackPressedListener(null);
                                        messageSelected = null;
                                    }
                                }
                            });
                        }

                        Vibrator x = (Vibrator) activity.getApplicationContext()
                                .getSystemService(Context.VIBRATOR_SERVICE);
                        x.vibrate(30);
                        Message mensaje = new Select().from(Message.class).where("mensajeId = ?", message.mensajeId)
                                .executeSingle();
                        if (mensaje.status != 4) {
                            icnMesajeTempo.setVisibility(View.VISIBLE);
                            icnMensajeTempoDivider.setVisibility(View.VISIBLE);
                            icnMesajeCopy.setVisibility(View.VISIBLE);
                            icnMesajeBack.setVisibility(View.VISIBLE);
                            messageMenu.setVisibility(View.VISIBLE);
                            AnimatorSet set = new AnimatorSet();
                            set.playTogether(ObjectAnimator.ofFloat(icnMesajeTempo, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(icnMesajeTempo, "translationX", 150, 0),
                                    ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", 100, 0),
                                    ObjectAnimator.ofFloat(icnMesajeBack, "translationX", 50, 0));
                            set.setDuration(200).start();
                        } else {
                            icnMesajeCopy.setVisibility(View.VISIBLE);
                            icnMesajeBack.setVisibility(View.VISIBLE);
                            messageMenu.setVisibility(View.VISIBLE);
                            AnimatorSet set = new AnimatorSet();
                            set.playTogether(ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", 100, 0),
                                    ObjectAnimator.ofFloat(icnMesajeBack, "translationX", 50, 0));
                            set.setDuration(200).start();
                        }

                        return false;
                    }
                });
            }
            if (message.status == 1) {
                messageStatus.setTextSize(16);
                mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
                GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
                drawable.setCornerRadius(radius);
                drawable.setColor(BalloonFragment.getBackgroundColor(activity));
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
                messageStatus.setTextColor(getResources().getColor(R.color.speak_all_ligh_gray));
                messageStatus.setText(Finder.STRING.ICN_MSJ_SENDING.toString());
                ValueAnimator colorAnim = ObjectAnimator.ofFloat(messageStatus, "alpha", 1, 0);
                colorAnim.setRepeatCount(ValueAnimator.INFINITE);
                colorAnim.setRepeatMode(ValueAnimator.REVERSE);
                colorAnim.setDuration(1000).start();
                animaciones.put(message.mensajeId, colorAnim);
                JSONObject data = new JSONObject();
                try {
                    data.put("message_id", message.mensajeId);
                    data.put("source", message.emisor);
                    data.put("source_email", message.emisorEmail);
                    data.put("target_email", message.receptorEmail);
                    data.put("target", message.receptor);
                    data.put("message", message.mensaje);
                    data.put("source_lang", message.emisorLang);
                    data.put("delay", message.delay);
                    data.put("type", message.tipo);
                } catch (JSONException e) {
                    Log.w("--->", e.toString());
                    e.printStackTrace();
                }
                if (SpeakSocket.mSocket != null)
                    if (SpeakSocket.mSocket.connected()) {
                        message.status = 1;
                        SpeakSocket.mSocket.emit("message", data);
                    } else {
                        message.status = -1;
                    }
            }
            if (message.status == -1) {
                messageStatus.setTextSize(11);
                mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
                GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
                drawable.setCornerRadius(radius);
                drawable.setColor(BalloonFragment.getBackgroundColor(activity));
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
                messageStatus.setText(Finder.STRING.ICN_MSJ_ERROR.toString());
            }
            if (message.status == 3) {
                messageStatus.setTextSize(11);
                mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
                GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
                drawable.setCornerRadius(radius);
                drawable.setColor(BalloonFragment.getBackgroundColor(activity));
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
                messageStatus.setText(Finder.STRING.ICN_MSJ_CLOSED.toString());
            }
            if (message.status == 2) {
                messageStatus.setTextSize(16);
                mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
                GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
                drawable.setCornerRadius(radius);
                drawable.setColor(BalloonFragment.getBackgroundColor(activity));
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
                messageStatus.setText(Finder.STRING.ICN_MSJ_SEND.toString());
            }
            if (message.status == 4) {
                messageStatus.setTextSize(11);
                mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
                GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
                drawable.setCornerRadius(radius);
                drawable.setColor(BalloonFragment.getBackgroundColor(activity));
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
                messageStatus.setText(Finder.STRING.ICN_MSJ_OPENED.toString());
                icnMensajeTempoDivider.setVisibility(View.GONE);
                icnMesajeTempo.setVisibility(View.GONE);
            } else {
                icnMensajeTempoDivider.setVisibility(View.INVISIBLE);
                icnMesajeTempo.setVisibility(View.INVISIBLE);
            }

        } else

        {
            mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
            GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
            drawable.setCornerRadius(radius);
            drawable.setColor(BalloonFragment.getFriendBalloon(activity));
            if (message.tipo == Integer.parseInt(getString(R.string.MSG_TYPE_BROADCAST_PHOTO))) {
                messageStatus.setTextSize(15);
                messageStatus.setText(Finder.STRING.ICN_BROADCAST_FILL.toString());
            }
            //messageContent.setText(message.mensajeTrad);
            icnMesajeTempo.setVisibility(View.GONE);
            rowView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if (messageSelected != null) {
                        View vista = messagesList.findViewWithTag(messageSelected);
                        vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                        messageSelected = message.mensajeId;
                        ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                            @Override
                            public void doBack() {
                                View vista = messagesList.findViewWithTag(messageSelected);
                                vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                                ((MainActivity) activity).setOnBackPressedListener(null);
                                messageSelected = null;
                            }
                        });
                    } else {
                        messageSelected = message.mensajeId;
                        ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                            @Override
                            public void doBack() {
                                View vista = messagesList.findViewWithTag(messageSelected);
                                vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                                ((MainActivity) activity).setOnBackPressedListener(null);
                                messageSelected = null;
                            }
                        });
                    }

                    Vibrator x = (Vibrator) activity.getApplicationContext()
                            .getSystemService(Context.VIBRATOR_SERVICE);
                    x.vibrate(20);
                    icnMesajeCopy.setVisibility(View.VISIBLE);
                    icnMesajeBack.setVisibility(View.VISIBLE);
                    messageMenu.setVisibility(View.VISIBLE);
                    AnimatorSet set = new AnimatorSet();
                    set.playTogether(ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1),
                            ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1),
                            ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1),
                            ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", -100, 0),
                            ObjectAnimator.ofFloat(icnMesajeBack, "translationX", -150, 0));
                    set.setDuration(200).start();
                    return false;
                }
            });
        }

        icnMesajeTempo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                JSONObject notifyMessage = new JSONObject();
                try {
                    Message mensaje = new Select().from(Message.class).where("mensajeId = ?", message.mensajeId)
                            .executeSingle();
                    if (mensaje.status != 4) {
                        notifyMessage.put("type", mensaje.tipo);
                        notifyMessage.put("message_id", mensaje.mensajeId);
                        notifyMessage.put("source", mensaje.receptor);
                        notifyMessage.put("status", 5);
                        SpeakSocket.mSocket.emit("message-status", notifyMessage);
                    }
                    new Delete().from(Message.class).where("mensajeId = ?", mensaje.mensajeId).execute();
                    Message message = null;
                    if (mensaje.emisor.equals(u.id)) {
                        message = new Select().from(Message.class)
                                .where("emisor = ? or receptor = ?", mensaje.receptor, mensaje.receptor)
                                .orderBy("emitedAt DESC").executeSingle();
                    } else {
                        message = new Select().from(Message.class)
                                .where("emisor = ? or receptor = ?", mensaje.emisor, mensaje.emisor)
                                .orderBy("emitedAt DESC").executeSingle();
                    }
                    if (message != null) {
                        Chats chat = null;
                        if (mensaje.emisor.equals(u.id)) {
                            chat = new Select().from(Chats.class).where("idContacto = ?", mensaje.receptor)
                                    .executeSingle();
                        } else {
                            chat = new Select().from(Chats.class).where("idContacto = ?", mensaje.emisor)
                                    .executeSingle();
                        }
                        if (chat != null) {
                            chat.mensajeId = message.mensajeId;
                            chat.lastStatus = message.status;
                            chat.emitedAt = message.emitedAt;
                            chat.lang = message.emisorLang;
                            chat.notRead = 0;
                            if (chat.idContacto.equals(message.emisor))
                                chat.lastMessage = message.mensajeTrad;
                            else
                                chat.lastMessage = message.mensaje;
                            chat.save();
                        }
                    } else {
                        if (mensaje.emisor.equals(u.id)) {
                            new Delete().from(Chats.class).where("idContacto = ?", mensaje.receptor).execute();
                        } else {
                            new Delete().from(Chats.class).where("idContacto = ?", mensaje.emisor).execute();
                        }
                    }

                    View delete = messagesList.findViewWithTag(mensaje.mensajeId);
                    if (delete != null)
                        messagesList.removeView(delete);
                    messageSelected = null;
                    ((MainActivity) activity).setOnBackPressedListener(null);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        );

        icnMesajeCopy.setOnClickListener(new View.OnClickListener()

        {
            @Override
            public void onClick(View v) {
                /*ClipData clip = ClipData.newPlainText("text", messageContent.getText().toString());
                ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                clipboard.setPrimaryClip(clip);
                Toast.makeText(activity, "Copiado", Toast.LENGTH_SHORT).show();*/
            }
        }

        );

        icnMesajeBack.setOnClickListener(new View.OnClickListener()

        {
            @Override
            public void onClick(View v) {
                if (message.emisor.equals(u.id)) {
                    getFragmentManager().beginTransaction()
                            .replace(R.id.container2, ForwarForFragment.newInstance(message.mensaje))
                            .addToBackStack(null).commit();
                    ((MainActivity) activity).setOnBackPressedListener(null);
                } else {
                    getFragmentManager().beginTransaction()
                            .replace(R.id.container2, ForwarForFragment.newInstance(message.mensajeTrad))
                            .addToBackStack(null).commit();
                    ((MainActivity) activity).setOnBackPressedListener(null);
                }
            }
        }

        );

        final double finalLatitud = latitud;
        final double finalLongitud = longitud;
        rowView.setOnClickListener(new View.OnClickListener()

        {
            @Override
            public void onClick(View v) {
                Message mensaje = new Select().from(Message.class).where("mensajeId = ?", message.mensajeId)
                        .executeSingle();
                if (messageSelected != null) {
                    View vista = messagesList.findViewWithTag(messageSelected);
                    if (!messageSelected.equals(message.mensajeId)) {
                        vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                        ((MainActivity) activity).setOnBackPressedListener(null);
                        messageSelected = null;
                    }
                } else {
                    if (mensaje.status != -1) {
                        dontClose = true;
                        ((MainActivity) activity).dontClose = true;
                        hideKeyBoard();
                        Intent i = new Intent(Intent.ACTION_VIEW,
                                Uri.parse("geo:" + finalLatitud + "," + finalLongitud));
                        i.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
                        startActivity(i);
                    }
                }
                if (mensaje.status == -1) {
                    JSONObject data = new JSONObject();
                    try {
                        data.put("message_id", mensaje.mensajeId);
                        data.put("source", mensaje.emisor);
                        data.put("source_email", mensaje.emisorEmail);
                        data.put("target_email", mensaje.receptorEmail);
                        data.put("target", mensaje.receptor);
                        data.put("message", message.mensaje);
                        data.put("source_lang", mensaje.emisorLang);
                        data.put("delay", mensaje.delay);
                        data.put("type", mensaje.tipo);
                    } catch (JSONException e) {
                        Log.w("--->", e.toString());
                        e.printStackTrace();
                    }
                    if (SpeakSocket.mSocket != null)
                        if (SpeakSocket.mSocket.connected()) {
                            mensaje.status = 1;
                            SpeakSocket.mSocket.emit("message", data);
                        } else {
                            mensaje.status = -1;
                        }
                    changeStatus(mensaje.mensajeId, mensaje.status);
                }
            }
        }

        );

    }

    public void showMensajeContact(int position, final Context context, final Message message, View rowView,
            TextView icnMessageArrow) {

        final TextView prevMessages = (TextView) rowView.findViewById(R.id.showprev_messages);
        TextView messageTime = (TextView) rowView.findViewById(R.id.message_time);
        final TextView icnMesajeTempo = (TextView) rowView.findViewById(R.id.icn_message_tempo);
        final View icnMensajeTempoDivider = (View) rowView.findViewById(R.id.icn_message_tempo_divider);
        final TextView icnMesajeCopy = (TextView) rowView.findViewById(R.id.icn_message_copy);
        final TextView icnMesajeBack = (TextView) rowView.findViewById(R.id.icn_message_back);
        TextView messageStatus = (TextView) rowView.findViewById(R.id.message_status);
        final LinearLayout messageMenu = (LinearLayout) rowView.findViewById(R.id.messages_menu_layout);
        final LinearLayout mensajeLayout = (LinearLayout) rowView.findViewById(R.id.mensaje_layout);
        TextView messageDate = (TextView) rowView.findViewById(R.id.message_date);
        TextView contactPhoto = (TextView) rowView.findViewById(R.id.contact_photo);
        TextView contactName = (TextView) rowView.findViewById(R.id.contact_name);
        final TextView contactPhone = (TextView) rowView.findViewById(R.id.contact_phone);

        TFCache.apply(context, messageTime, TFCache.TF_WHITNEY_MEDIUM);
        TFCache.apply(context, icnMesajeTempo, TFCache.TF_SPEAKALL);
        TFCache.apply(context, icnMesajeCopy, TFCache.TF_SPEAKALL);
        TFCache.apply(context, icnMesajeBack, TFCache.TF_SPEAKALL);
        TFCache.apply(context, messageStatus, TFCache.TF_SPEAKALL);
        TFCache.apply(context, contactPhoto, TFCache.TF_SPEAKALL);
        TFCache.apply(context, prevMessages, TFCache.TF_WHITNEY_MEDIUM);
        TFCache.apply(context, messageDate, TFCache.TF_WHITNEY_MEDIUM);
        TFCache.apply(context, contactName, TFCache.TF_WHITNEY_MEDIUM);
        TFCache.apply(context, contactPhone, TFCache.TF_WHITNEY_MEDIUM);

        try {
            JSONObject contactData = new JSONObject(message.mensaje);
            contactName.setText(contactData.getString("nombre"));
            contactPhone.setText(Html.fromHtml("<u>" + contactData.getString("telefono") + "</u>"));
            if (contactPhone.length() > 0) {
                contactPhone.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dontClose = true;
                        ((MainActivity) activity).dontClose = true;
                        hideKeyBoard();
                        Intent intent = new Intent(Intent.ACTION_CALL,
                                Uri.parse("tel:" + contactPhone.getText().toString()));
                        context.startActivity(intent);
                    }
                });
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (position == 0) {
            if (mensajesTotal > mensajesOffset) {
                prevMessages.setVisibility(View.VISIBLE);
                prevMessages.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        prevMessages.setVisibility(View.GONE);
                        if (mensajesTotal - mensajesOffset >= 10) {
                            mensajesLimit = 10;
                            mensajesOffset += mensajesLimit;
                            showPreviousMessages(mensajesOffset);
                        } else {
                            mensajesLimit = mensajesTotal - mensajesOffset;
                            mensajesOffset += mensajesLimit;
                            showPreviousMessages(mensajesOffset);
                        }
                    }
                });
            }
        }

        DateFormat dateDay = new SimpleDateFormat("d");
        DateFormat dateDayText = new SimpleDateFormat("EEEE");
        DateFormat dateMonth = new SimpleDateFormat("MMMM");
        DateFormat dateYear = new SimpleDateFormat("yyyy");
        DateFormat timeFormat = new SimpleDateFormat("h:mm a");

        Calendar fechamsj = Calendar.getInstance();
        fechamsj.setTimeInMillis(message.emitedAt);
        String time = timeFormat.format(fechamsj.getTime());
        String dayMessage = dateDay.format(fechamsj.getTime());
        String monthMessage = dateMonth.format(fechamsj.getTime());
        String yearMessage = dateYear.format(fechamsj.getTime());
        String dayMessageText = dateDayText.format(fechamsj.getTime());
        char[] caracteres = dayMessageText.toCharArray();
        caracteres[0] = Character.toUpperCase(caracteres[0]);
        dayMessageText = new String(caracteres);

        Calendar fechaActual = Calendar.getInstance();
        String dayActual = dateDay.format(fechaActual.getTime());
        String monthActual = dateMonth.format(fechaActual.getTime());
        String yearActual = dateYear.format(fechaActual.getTime());

        String fechaMostrar = "";
        if (dayMessage.equals(dayActual) && monthMessage.equals(monthActual) && yearMessage.equals(yearActual)) {
            fechaMostrar = getString(R.string.messages_today);
        } else if (monthMessage.equals(monthActual) && yearMessage.equals(yearActual)) {
            int days = Integer.parseInt(dayActual) - Integer.parseInt(dayMessage);
            if (days < 7) {
                switch (days) {
                case 1:
                    fechaMostrar = getString(R.string.messages_yesterday);
                    break;
                default:
                    fechaMostrar = dayMessageText;
                    break;
                }
            } else {
                fechaMostrar = (dayMessage + " " + monthMessage + " " + yearMessage).toUpperCase();
            }
        } else {
            fechaMostrar = (dayMessage + " " + monthMessage + " " + yearMessage).toUpperCase();
        }

        messageDate.setText(fechaMostrar);
        if (position != -1) {
            if (itemAnterior != null) {
                if (!fechaMostrar.equals(fechaAnterior)) {
                    itemAnterior.findViewById(R.id.message_date).setVisibility(View.VISIBLE);
                } else {
                    itemAnterior.findViewById(R.id.message_date).setVisibility(View.GONE);
                }
            }
            itemAnterior = rowView;
            fechaAnterior = fechaMostrar;
        } else {
            View v = messagesList.getChildAt(messagesList.getChildCount() - 1);
            if (v != null) {
                TextView tv = (TextView) v.findViewById(R.id.message_date);
                if (tv.getText().toString().equals(fechaMostrar)) {
                    messageDate.setVisibility(View.GONE);
                } else {
                    messageDate.setVisibility(View.VISIBLE);
                }
            }
        }
        messageTime.setText(time);

        if (message.emisor.equals(u.id)) {
            if (message.status != -1) {
                rowView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        if (messageSelected != null) {
                            View vista = messagesList.findViewWithTag(messageSelected);
                            vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                            messageSelected = message.mensajeId;
                            ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                                @Override
                                public void doBack() {
                                    View vista = messagesList.findViewWithTag(messageSelected);
                                    vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                                    ((MainActivity) activity).setOnBackPressedListener(null);
                                    messageSelected = null;
                                }
                            });
                        } else {
                            messageSelected = message.mensajeId;
                            ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                                @Override
                                public void doBack() {
                                    if (messageSelected != null) {
                                        View vista = messagesList.findViewWithTag(messageSelected);
                                        vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                                        ((MainActivity) activity).setOnBackPressedListener(null);
                                        messageSelected = null;
                                    }
                                }
                            });
                        }

                        Vibrator x = (Vibrator) activity.getApplicationContext()
                                .getSystemService(Context.VIBRATOR_SERVICE);
                        x.vibrate(30);
                        Message mensaje = new Select().from(Message.class).where("mensajeId = ?", message.mensajeId)
                                .executeSingle();
                        if (mensaje.status != 4) {
                            icnMesajeTempo.setVisibility(View.VISIBLE);
                            icnMensajeTempoDivider.setVisibility(View.VISIBLE);
                            icnMesajeCopy.setVisibility(View.VISIBLE);
                            icnMesajeBack.setVisibility(View.VISIBLE);
                            messageMenu.setVisibility(View.VISIBLE);
                            AnimatorSet set = new AnimatorSet();
                            set.playTogether(ObjectAnimator.ofFloat(icnMesajeTempo, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(icnMesajeTempo, "translationX", 150, 0),
                                    ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", 100, 0),
                                    ObjectAnimator.ofFloat(icnMesajeBack, "translationX", 50, 0));
                            set.setDuration(200).start();
                        } else {
                            icnMesajeCopy.setVisibility(View.VISIBLE);
                            icnMesajeBack.setVisibility(View.VISIBLE);
                            messageMenu.setVisibility(View.VISIBLE);
                            AnimatorSet set = new AnimatorSet();
                            set.playTogether(ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", 100, 0),
                                    ObjectAnimator.ofFloat(icnMesajeBack, "translationX", 50, 0));
                            set.setDuration(200).start();
                        }

                        return false;
                    }
                });
            }
            if (message.status == 1) {
                messageStatus.setTextSize(16);
                mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
                GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
                drawable.setCornerRadius(radius);
                drawable.setColor(BalloonFragment.getBackgroundColor(activity));
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
                messageStatus.setTextColor(getResources().getColor(R.color.speak_all_ligh_gray));
                messageStatus.setText(Finder.STRING.ICN_MSJ_SENDING.toString());
                ValueAnimator colorAnim = ObjectAnimator.ofFloat(messageStatus, "alpha", 1, 0);
                colorAnim.setRepeatCount(ValueAnimator.INFINITE);
                colorAnim.setRepeatMode(ValueAnimator.REVERSE);
                colorAnim.setDuration(1000).start();
                animaciones.put(message.mensajeId, colorAnim);
                JSONObject data = new JSONObject();
                try {
                    data.put("message_id", message.mensajeId);
                    data.put("source", message.emisor);
                    data.put("source_email", message.emisorEmail);
                    data.put("target_email", message.receptorEmail);
                    data.put("target", message.receptor);
                    data.put("message", message.mensaje);
                    data.put("delay", message.delay);
                    data.put("translation_required", message.translation);
                    data.put("target_lang", message.receptorLang);
                    data.put("type", message.tipo);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (SpeakSocket.mSocket != null)
                    if (SpeakSocket.mSocket.connected()) {
                        message.status = 1;
                        SpeakSocket.mSocket.emit("message", data);
                    } else {
                        message.status = -1;
                    }
            }
            if (message.status == -1) {
                messageStatus.setTextSize(11);
                mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
                GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
                drawable.setCornerRadius(radius);
                drawable.setColor(BalloonFragment.getBackgroundColor(activity));
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
                messageStatus.setText(Finder.STRING.ICN_MSJ_ERROR.toString());
            }
            if (message.status == 3) {
                messageStatus.setTextSize(11);
                mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
                GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
                drawable.setCornerRadius(radius);
                drawable.setColor(BalloonFragment.getBackgroundColor(activity));
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
                messageStatus.setText(Finder.STRING.ICN_MSJ_CLOSED.toString());
            }
            if (message.status == 2) {
                messageStatus.setTextSize(16);
                mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
                GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
                drawable.setCornerRadius(radius);
                drawable.setColor(BalloonFragment.getBackgroundColor(activity));
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
                messageStatus.setText(Finder.STRING.ICN_MSJ_SEND.toString());
            }
            if (message.status == 4) {
                messageStatus.setTextSize(11);
                mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
                GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
                drawable.setCornerRadius(radius);
                drawable.setColor(BalloonFragment.getBackgroundColor(activity));
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
                messageStatus.setText(Finder.STRING.ICN_MSJ_OPENED.toString());
                icnMensajeTempoDivider.setVisibility(View.GONE);
                icnMesajeTempo.setVisibility(View.GONE);
            } else {
                icnMensajeTempoDivider.setVisibility(View.INVISIBLE);
                icnMesajeTempo.setVisibility(View.INVISIBLE);
            }

            icnMesajeTempo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    JSONObject notifyMessage = new JSONObject();
                    try {
                        Message mensaje = new Select().from(Message.class).where("mensajeId = ?", message.mensajeId)
                                .executeSingle();

                        if (mensaje.status != 4) {
                            notifyMessage.put("type", mensaje.tipo);
                            notifyMessage.put("message_id", mensaje.mensajeId);
                            notifyMessage.put("source", mensaje.receptor);
                            notifyMessage.put("target", mensaje.emisor);
                            notifyMessage.put("status", 5);
                            SpeakSocket.mSocket.emit("message-status", notifyMessage);
                        }
                        new Delete().from(Message.class).where("mensajeId = ?", mensaje.mensajeId).execute();
                        Message message = null;
                        if (mensaje.emisor.equals(u.id)) {
                            message = new Select().from(Message.class)
                                    .where("emisor = ? or receptor = ?", mensaje.receptor, mensaje.receptor)
                                    .orderBy("emitedAt DESC").executeSingle();
                        } else {
                            message = new Select().from(Message.class)
                                    .where("emisor = ? or receptor = ?", mensaje.emisor, mensaje.emisor)
                                    .orderBy("emitedAt DESC").executeSingle();
                        }
                        if (message != null) {
                            Chats chat = null;
                            if (mensaje.emisor.equals(u.id)) {
                                chat = new Select().from(Chats.class).where("idContacto = ?", mensaje.receptor)
                                        .executeSingle();
                            } else {
                                chat = new Select().from(Chats.class).where("idContacto = ?", mensaje.emisor)
                                        .executeSingle();
                            }
                            if (chat != null) {
                                chat.mensajeId = message.mensajeId;
                                chat.lastStatus = message.status;
                                chat.emitedAt = message.emitedAt;
                                chat.lang = message.emisorLang;
                                chat.notRead = 0;
                                if (chat.idContacto.equals(message.emisor))
                                    chat.lastMessage = message.mensajeTrad;
                                else
                                    chat.lastMessage = message.mensaje;
                                chat.save();
                            }
                        } else {
                            if (mensaje.emisor.equals(u.id)) {
                                new Delete().from(Chats.class).where("idContacto = ?", mensaje.receptor).execute();
                            } else {
                                new Delete().from(Chats.class).where("idContacto = ?", mensaje.emisor).execute();
                            }
                        }

                        View delete = messagesList.findViewWithTag(mensaje.mensajeId);
                        if (delete != null)
                            messagesList.removeView(delete);
                        messageSelected = null;
                        ((MainActivity) activity).setOnBackPressedListener(null);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });

        } else {
            mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
            GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
            drawable.setCornerRadius(radius);
            drawable.setColor(BalloonFragment.getFriendBalloon(activity));
            if (message.tipo == Integer.parseInt(getString(R.string.MSG_TYPE_BROADCAST_TEXT))) {
                messageStatus.setTextSize(15);
                messageStatus.setText(Finder.STRING.ICN_BROADCAST_FILL.toString());
            }
            rowView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if (messageSelected != null) {
                        longclick = true;
                        View vista = messagesList.findViewWithTag(messageSelected);
                        vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                        messageSelected = message.mensajeId;
                        ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                            @Override
                            public void doBack() {
                                View vista = messagesList.findViewWithTag(messageSelected);
                                vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                                ((MainActivity) activity).setOnBackPressedListener(null);
                                messageSelected = null;
                            }
                        });
                    } else {
                        messageSelected = message.mensajeId;
                        ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                            @Override
                            public void doBack() {
                                View vista = messagesList.findViewWithTag(messageSelected);
                                vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                                ((MainActivity) activity).setOnBackPressedListener(null);
                                messageSelected = null;
                            }
                        });
                    }

                    Vibrator x = (Vibrator) activity.getApplicationContext()
                            .getSystemService(Context.VIBRATOR_SERVICE);
                    x.vibrate(20);
                    icnMesajeTempo.setVisibility(View.GONE);
                    icnMensajeTempoDivider.setVisibility(View.GONE);
                    icnMesajeCopy.setVisibility(View.VISIBLE);
                    icnMesajeBack.setVisibility(View.VISIBLE);
                    messageMenu.setVisibility(View.VISIBLE);
                    AnimatorSet set = new AnimatorSet();
                    set.playTogether(ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1),
                            ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1),
                            ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1),
                            ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", -100, 0),
                            ObjectAnimator.ofFloat(icnMesajeBack, "translationX", -150, 0));
                    set.setDuration(200).start();
                    longclick = true;
                    return false;
                }
            });
            icnMesajeTempo.setOnClickListener(new View.OnClickListener() {
                boolean translation = true;

                @Override
                public void onClick(View v) {
                    translation = !translation;
                    if (translation) {
                        icnMesajeTempo.setTextColor(getResources().getColor(R.color.speak_all_red));
                    } else {
                        icnMesajeTempo.setTextColor(getResources().getColor(R.color.speak_all_white));
                    }
                }
            });
        }

        /*icnMesajeCopy.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              ClipData clip = ClipData.newPlainText("text", messageContent.getText().toString());
              ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
              clipboard.setPrimaryClip(clip);
              Toast.makeText(activity, "Copiado", Toast.LENGTH_SHORT).show();
          }
        });*/

        icnMesajeBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (message.emisor.equals(u.id)) {
                    getFragmentManager().beginTransaction()
                            .replace(R.id.container2, ForwarForFragment.newInstance(message.mensaje))
                            .addToBackStack(null).commit();
                    ((MainActivity) activity).setOnBackPressedListener(null);
                } else {
                    getFragmentManager().beginTransaction()
                            .replace(R.id.container2, ForwarForFragment.newInstance(message.mensajeTrad))
                            .addToBackStack(null).commit();
                    ((MainActivity) activity).setOnBackPressedListener(null);
                }
            }
        });

        rowView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (messageSelected != null) {
                    View vista = messagesList.findViewWithTag(messageSelected);
                    if (!messageSelected.equals(message.mensajeId)) {
                        longclick = true;
                        vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                        ((MainActivity) activity).setOnBackPressedListener(null);
                        messageSelected = null;
                    }
                }
                Message mensaje = new Select().from(Message.class).where("mensajeId = ?", message.mensajeId)
                        .executeSingle();
                if (mensaje.status == -1) {
                    String message = mensaje.mensaje;
                    JSONObject data = new JSONObject();
                    try {
                        data.put("message_id", mensaje.mensajeId);
                        data.put("source", mensaje.emisor);
                        data.put("source_email", mensaje.emisorEmail);
                        data.put("target_email", mensaje.receptorEmail);
                        data.put("target", mensaje.receptor);
                        data.put("message", mensaje.mensaje);
                        data.put("delay", mensaje.delay);
                        data.put("type", mensaje.tipo);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (SpeakSocket.mSocket != null)
                        if (SpeakSocket.mSocket.connected()) {
                            mensaje.status = 1;
                            SpeakSocket.mSocket.emit("message", data);
                        } else {
                            mensaje.status = -1;
                        }
                    mensaje.save();
                    changeStatus(mensaje.mensajeId, mensaje.status);
                }
                if (!mensaje.emisor.equals(u.id)) {
                    if (!longclick) {
                        showDialogAddContact(mensaje.mensaje);
                    }
                    longclick = false;
                }
            }
        });
    }

    public void showMensajeAudio(int position, Context context, final Message message, View rowView,
            TextView icnMessageArrow) {
        final TextView prevMessages = (TextView) rowView.findViewById(R.id.showprev_messages);
        TextView messageTime = (TextView) rowView.findViewById(R.id.message_time);
        final TextView icnMesajeTempo = (TextView) rowView.findViewById(R.id.icn_message_tempo);
        final View icnMensajeTempoDivider = (View) rowView.findViewById(R.id.icn_message_tempo_divider);
        final TextView icnMesajeCopy = (TextView) rowView.findViewById(R.id.icn_message_copy);
        final TextView icnMesajeBack = (TextView) rowView.findViewById(R.id.icn_message_back);
        TextView messageStatus = (TextView) rowView.findViewById(R.id.message_status);
        final LinearLayout messageMenu = (LinearLayout) rowView.findViewById(R.id.messages_menu_layout);
        final LinearLayout mensajeLayout = (LinearLayout) rowView.findViewById(R.id.mensaje_layout);
        TextView messageDate = (TextView) rowView.findViewById(R.id.message_date);
        final TextView audioTime = (TextView) rowView.findViewById(R.id.message_audio_time);
        final SeekBar audioSeekBar = (SeekBar) rowView.findViewById(R.id.audio_seekbar);
        final TextView playAudio = (TextView) rowView.findViewById(R.id.play_audio);
        final ProgressBar progressBar = (ProgressBar) rowView.findViewById(R.id.progress_bar);
        final RelativeLayout progressLayout = (RelativeLayout) rowView.findViewById(R.id.progress_layout);
        final TextView progressText = (TextView) rowView.findViewById(R.id.progress_message);

        TFCache.apply(context, messageTime, TFCache.TF_WHITNEY_MEDIUM);
        TFCache.apply(context, icnMesajeTempo, TFCache.TF_SPEAKALL);
        TFCache.apply(context, icnMesajeCopy, TFCache.TF_SPEAKALL);
        TFCache.apply(context, icnMesajeBack, TFCache.TF_SPEAKALL);
        TFCache.apply(context, messageStatus, TFCache.TF_SPEAKALL);
        TFCache.apply(context, prevMessages, TFCache.TF_WHITNEY_MEDIUM);
        TFCache.apply(context, messageDate, TFCache.TF_WHITNEY_MEDIUM);
        TFCache.apply(context, audioTime, TFCache.TF_WHITNEY_MEDIUM);
        TFCache.apply(context, playAudio, TFCache.TF_SPEAKON);

        if (position == 0) {
            if (mensajesTotal > mensajesOffset) {
                prevMessages.setVisibility(View.VISIBLE);
                prevMessages.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        prevMessages.setVisibility(View.GONE);
                        if (mensajesTotal - mensajesOffset >= 10) {
                            mensajesLimit = 10;
                            mensajesOffset += mensajesLimit;
                            showPreviousMessages(mensajesOffset);
                        } else {
                            mensajesLimit = mensajesTotal - mensajesOffset;
                            mensajesOffset += mensajesLimit;
                            showPreviousMessages(mensajesOffset);
                        }
                    }
                });
            }
        }

        DateFormat dateDay = new SimpleDateFormat("d");
        DateFormat dateDayText = new SimpleDateFormat("EEEE");
        DateFormat dateMonth = new SimpleDateFormat("MMMM");
        DateFormat dateYear = new SimpleDateFormat("yyyy");
        DateFormat timeFormat = new SimpleDateFormat("h:mm a");

        Calendar fechamsj = Calendar.getInstance();
        fechamsj.setTimeInMillis(message.emitedAt);
        String time = timeFormat.format(fechamsj.getTime());
        String dayMessage = dateDay.format(fechamsj.getTime());
        String monthMessage = dateMonth.format(fechamsj.getTime());
        String yearMessage = dateYear.format(fechamsj.getTime());
        String dayMessageText = dateDayText.format(fechamsj.getTime());
        char[] caracteres = dayMessageText.toCharArray();
        caracteres[0] = Character.toUpperCase(caracteres[0]);
        dayMessageText = new String(caracteres);

        Calendar fechaActual = Calendar.getInstance();
        String dayActual = dateDay.format(fechaActual.getTime());
        String monthActual = dateMonth.format(fechaActual.getTime());
        String yearActual = dateYear.format(fechaActual.getTime());

        String fechaMostrar = "";
        if (dayMessage.equals(dayActual) && monthMessage.equals(monthActual) && yearMessage.equals(yearActual)) {
            fechaMostrar = getString(R.string.messages_today);
        } else if (monthMessage.equals(monthActual) && yearMessage.equals(yearActual)) {
            int days = Integer.parseInt(dayActual) - Integer.parseInt(dayMessage);
            if (days < 7) {
                switch (days) {
                case 1:
                    fechaMostrar = getString(R.string.messages_yesterday);
                    break;
                default:
                    fechaMostrar = dayMessageText;
                    break;
                }
            } else {
                fechaMostrar = (dayMessage + " " + monthMessage + " " + yearMessage).toUpperCase();
            }
        } else {
            fechaMostrar = (dayMessage + " " + monthMessage + " " + yearMessage).toUpperCase();
        }

        messageDate.setText(fechaMostrar);
        if (position != -1) {

            if (itemAnterior != null) {
                if (!fechaMostrar.equals(fechaAnterior)) {
                    itemAnterior.findViewById(R.id.message_date).setVisibility(View.VISIBLE);
                } else {
                    itemAnterior.findViewById(R.id.message_date).setVisibility(View.GONE);
                }
            }
            itemAnterior = rowView;
            fechaAnterior = fechaMostrar;
        } else {
            View v = messagesList.getChildAt(messagesList.getChildCount() - 1);
            if (v != null) {
                TextView tv = (TextView) v.findViewById(R.id.message_date);
                if (tv.getText().toString().equals(fechaMostrar)) {
                    messageDate.setVisibility(View.GONE);
                } else {
                    messageDate.setVisibility(View.VISIBLE);
                }
            }
        }
        messageTime.setText(time);

        if (message.emisor.equals(u.id)) {
            mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
            GradientDrawable drawable1 = (GradientDrawable) mensajeLayout.getBackground();
            drawable1.setCornerRadius(radius);
            drawable1.setColor(BalloonFragment.getBackgroundColor(activity));
            progressBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.speak_all_red),
                    PorterDuff.Mode.SRC_IN);
            if (message.status != -1) {
                rowView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        if (messageSelected != null) {
                            View vista = messagesList.findViewWithTag(messageSelected);
                            vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                            messageSelected = message.mensajeId;
                            ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                                @Override
                                public void doBack() {
                                    View vista = messagesList.findViewWithTag(messageSelected);
                                    vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                                    ((MainActivity) activity).setOnBackPressedListener(null);
                                    messageSelected = null;
                                }
                            });
                        } else {
                            messageSelected = message.mensajeId;
                            ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                                @Override
                                public void doBack() {
                                    if (messageSelected != null) {
                                        View vista = messagesList.findViewWithTag(messageSelected);
                                        vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                                        ((MainActivity) activity).setOnBackPressedListener(null);
                                        messageSelected = null;
                                    }
                                }
                            });
                        }

                        Vibrator x = (Vibrator) activity.getApplicationContext()
                                .getSystemService(Context.VIBRATOR_SERVICE);
                        x.vibrate(30);
                        Message mensaje = new Select().from(Message.class).where("mensajeId = ?", message.mensajeId)
                                .executeSingle();
                        if (mensaje.status != 4) {
                            icnMesajeTempo.setVisibility(View.VISIBLE);
                            icnMensajeTempoDivider.setVisibility(View.VISIBLE);
                            icnMesajeCopy.setVisibility(View.VISIBLE);
                            icnMesajeBack.setVisibility(View.VISIBLE);
                            messageMenu.setVisibility(View.VISIBLE);
                            AnimatorSet set = new AnimatorSet();
                            set.playTogether(ObjectAnimator.ofFloat(icnMesajeTempo, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(icnMesajeTempo, "translationX", 150, 0),
                                    ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", 100, 0),
                                    ObjectAnimator.ofFloat(icnMesajeBack, "translationX", 50, 0));
                            set.setDuration(200).start();
                        } else {
                            icnMesajeCopy.setVisibility(View.VISIBLE);
                            icnMesajeBack.setVisibility(View.VISIBLE);
                            messageMenu.setVisibility(View.VISIBLE);
                            AnimatorSet set = new AnimatorSet();
                            set.playTogether(ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", 100, 0),
                                    ObjectAnimator.ofFloat(icnMesajeBack, "translationX", 50, 0));
                            set.setDuration(200).start();
                        }

                        return false;
                    }
                });
            }
            if (message.status == 1) {
                messageStatus.setTextSize(16);
                mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
                GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
                drawable.setCornerRadius(radius);
                drawable.setColor(BalloonFragment.getBackgroundColor(activity));
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
                messageStatus.setTextColor(getResources().getColor(R.color.speak_all_ligh_gray));
                messageStatus.setText(Finder.STRING.ICN_MSJ_SENDING.toString());
                ValueAnimator colorAnim = ObjectAnimator.ofFloat(messageStatus, "alpha", 1, 0);
                colorAnim.setRepeatCount(ValueAnimator.INFINITE);
                colorAnim.setRepeatMode(ValueAnimator.REVERSE);
                colorAnim.setDuration(1000).start();
                animaciones.put(message.mensajeId, colorAnim);
                final JSONObject data = new JSONObject();
                try {
                    data.put("message_id", message.mensajeId);
                    data.put("source", message.emisor);
                    data.put("source_email", message.emisorEmail);
                    data.put("target_email", message.receptorEmail);
                    data.put("target", message.receptor);
                    data.put("type", message.tipo);
                    if (!message.fileUploaded) {
                        progressLayout.setVisibility(View.VISIBLE);
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        uploadAudioToServer(message.audioName, message, data, progressBar,
                                                progressLayout, progressText);
                                    }
                                });
                            }
                        }).start();
                    } else {
                        data.put("videos", message.fileName);
                        if (SpeakSocket.mSocket != null)
                            if (SpeakSocket.mSocket.connected()) {
                                message.status = 1;
                                SpeakSocket.mSocket.emit("message", data);
                            } else {
                                message.status = -1;
                            }
                        message.save();
                        changeStatus(message.mensajeId, message.status);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            if (message.status == -1) {
                messageStatus.setTextSize(11);
                mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
                GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
                drawable.setCornerRadius(radius);
                drawable.setColor(BalloonFragment.getBackgroundColor(activity));
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
                messageStatus.setText(Finder.STRING.ICN_MSJ_ERROR.toString());
            }
            if (message.status == 3) {
                messageStatus.setTextSize(11);
                mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
                GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
                drawable.setCornerRadius(radius);
                drawable.setColor(BalloonFragment.getBackgroundColor(activity));
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
                messageStatus.setText(Finder.STRING.ICN_MSJ_CLOSED.toString());
            }
            if (message.status == 2) {
                messageStatus.setTextSize(16);
                mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
                GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
                drawable.setCornerRadius(radius);
                drawable.setColor(BalloonFragment.getBackgroundColor(activity));
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
                messageStatus.setText(Finder.STRING.ICN_MSJ_SEND.toString());
            }
            if (message.status == 4) {
                messageStatus.setTextSize(11);
                mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
                GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
                drawable.setCornerRadius(radius);
                drawable.setColor(BalloonFragment.getBackgroundColor(activity));
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
                messageStatus.setText(Finder.STRING.ICN_MSJ_OPENED.toString());
                icnMensajeTempoDivider.setVisibility(View.GONE);
                icnMesajeTempo.setVisibility(View.GONE);
            } else {
                icnMensajeTempoDivider.setVisibility(View.INVISIBLE);
                icnMesajeTempo.setVisibility(View.INVISIBLE);
            }

            icnMesajeTempo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    JSONObject notifyMessage = new JSONObject();
                    try {
                        Message mensaje = new Select().from(Message.class).where("mensajeId = ?", message.mensajeId)
                                .executeSingle();
                        Log.w("mensaje detail",
                                mensaje.status + " : " + mensaje.receptorEmail + " : " + mensaje.tipo);
                        if (mensaje.status != 4) {
                            notifyMessage.put("type", mensaje.tipo);
                            notifyMessage.put("message_id", mensaje.mensajeId);
                            notifyMessage.put("source", mensaje.emisor);
                            notifyMessage.put("target", mensaje.receptor);
                            notifyMessage.put("status", 5);
                            if (SpeakSocket.mSocket != null)
                                if (SpeakSocket.mSocket.connected())
                                    SpeakSocket.mSocket.emit("message-status", notifyMessage);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });

        } else {
            mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
            GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
            drawable.setCornerRadius(radius);
            drawable.setColor(BalloonFragment.getFriendBalloon(activity));
            if (message.tipo == Integer.parseInt(getString(R.string.MSG_TYPE_BROADCAST_AUDIO))) {
                messageStatus.setTextSize(15);
                messageStatus.setText(Finder.STRING.ICN_BROADCAST_FILL.toString());
            }
            rowView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if (messageSelected != null) {
                        View vista = messagesList.findViewWithTag(messageSelected);
                        vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                        messageSelected = message.mensajeId;
                        ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                            @Override
                            public void doBack() {
                                View vista = messagesList.findViewWithTag(messageSelected);
                                vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                                ((MainActivity) activity).setOnBackPressedListener(null);
                                messageSelected = null;
                            }
                        });
                    } else {
                        messageSelected = message.mensajeId;
                        ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                            @Override
                            public void doBack() {
                                View vista = messagesList.findViewWithTag(messageSelected);
                                vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                                ((MainActivity) activity).setOnBackPressedListener(null);
                                messageSelected = null;
                            }
                        });
                    }

                    Vibrator x = (Vibrator) activity.getApplicationContext()
                            .getSystemService(Context.VIBRATOR_SERVICE);
                    x.vibrate(20);
                    icnMesajeTempo.setVisibility(View.GONE);
                    icnMensajeTempoDivider.setVisibility(View.GONE);
                    icnMesajeCopy.setVisibility(View.VISIBLE);
                    icnMesajeBack.setVisibility(View.VISIBLE);
                    messageMenu.setVisibility(View.VISIBLE);
                    AnimatorSet set = new AnimatorSet();
                    set.playTogether(ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1),
                            ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1),
                            ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1),
                            ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", -100, 0),
                            ObjectAnimator.ofFloat(icnMesajeBack, "translationX", -150, 0));
                    set.setDuration(200).start();
                    return false;
                }
            });
        }

        /*icnMesajeCopy.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              ClipData clip = ClipData.newPlainText("text", messageContent.getText().toString());
              ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
              clipboard.setPrimaryClip(clip);
              Toast.makeText(activity, "Copiado", Toast.LENGTH_SHORT).show();
          }
        });*/

        icnMesajeBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (message.emisor.equals(u.id)) {
                    getFragmentManager().beginTransaction()
                            .replace(R.id.container2, ForwarForFragment.newInstance(message.mensaje))
                            .addToBackStack(null).commit();
                    ((MainActivity) activity).setOnBackPressedListener(null);
                } else {
                    getFragmentManager().beginTransaction()
                            .replace(R.id.container2, ForwarForFragment.newInstance(message.mensajeTrad))
                            .addToBackStack(null).commit();
                    ((MainActivity) activity).setOnBackPressedListener(null);
                }
            }
        });

        rowView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (messageSelected != null) {
                    View vista = messagesList.findViewWithTag(messageSelected);
                    if (!messageSelected.equals(message.mensajeId)) {
                        vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                        ((MainActivity) activity).setOnBackPressedListener(null);
                        messageSelected = null;
                    }
                }
                final Message mensaje = new Select().from(Message.class).where("mensajeId = ?", message.mensajeId)
                        .executeSingle();
                if (mensaje.status == -1) {
                    final JSONObject data = new JSONObject();
                    try {
                        data.put("message_id", mensaje.mensajeId);
                        data.put("source", mensaje.emisor);
                        data.put("source_email", mensaje.emisorEmail);
                        data.put("target_email", mensaje.receptorEmail);
                        data.put("target", mensaje.receptor);
                        data.put("type", mensaje.tipo);
                        if (!mensaje.fileUploaded) {
                            progressLayout.setVisibility(View.VISIBLE);
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    activity.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            uploadAudioToServer(mensaje.audioName, mensaje, data, progressBar,
                                                    progressLayout, progressText);
                                        }
                                    });
                                }
                            }).start();
                        } else {
                            data.put("audios", mensaje.fileName);
                            if (SpeakSocket.mSocket != null)
                                if (SpeakSocket.mSocket.connected()) {
                                    mensaje.status = 1;
                                    SpeakSocket.mSocket.emit("message", data);
                                } else {
                                    mensaje.status = -1;
                                }
                            mensaje.save();
                            changeStatus(mensaje.mensajeId, mensaje.status);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        File audioFile = null;
        final MediaPlayer mediaPlayer1 = new MediaPlayer();
        audioFile = new File(message.audioName);
        try {
            mediaPlayer1.setDataSource(audioFile.getAbsolutePath());
            mediaPlayer1.prepare();
            long timePlayer = mediaPlayer1.getDuration();
            long days, hours, minutes, seconds;
            long secondsTotal = timePlayer / 1000;
            days = (Math.round(secondsTotal) / 86400);
            hours = (Math.round(secondsTotal) / 3600) - (days * 24);
            minutes = (Math.round(secondsTotal) / 60) - (days * 1440) - (hours * 60);
            seconds = Math.round(secondsTotal) % 60;
            audioTime.setText(String.format("%02d", minutes) + " : " + String.format("%02d", seconds));
            audioSeekBar.setMax(mediaPlayer1.getDuration());
            audioSeekBar.setTag(message.mensajeId);
            mediaPlayer1.release();
        } catch (IOException e) {
            e.printStackTrace();
        }

        final File finalAudioFile = audioFile;
        playAudio.setOnClickListener(new View.OnClickListener() {
            boolean isplayAudio = false;

            @Override
            public void onClick(View v) {

                if (activeAudioSeekBarr != null) {
                    if (!activeAudioSeekBarr.getTag().equals(audioSeekBar.getTag())) {
                        isplayAudio = false;
                    }
                }
                if (!isplayAudio) {
                    try {
                        if (activeAudioSeekBarr != null) {
                            if (activeAudioSeekBarr.getTag().equals(audioSeekBar.getTag())) {
                                seekHandler.postDelayed(runAudio, 1000);
                                playAudio.setText(Finder.STRING.ICN_PAUSE.toString());
                                mediaPlayer.start();
                            } else {
                                if (mediaPlayer != null) {
                                    mediaPlayer.stop();
                                    mediaPlayer.release();
                                }
                                if (activeAudioSeekBarr != null) {
                                    activeAudioSeekBarr.setProgress(0);
                                    activeAudioSeekBarr.setOnSeekBarChangeListener(null);
                                }
                                if (activeAudioTime != null) {
                                    activeAudioTime.setText(activeAudioDuration);
                                }
                                if (!activeAudioDuration.equals("")) {
                                    activeAudioDuration = "";
                                }
                                if (activePlayer != null) {
                                    activePlayer.setText(Finder.STRING.ICN_PLAY.toString());
                                }
                                seekHandler.removeCallbacks(runAudio);
                                mediaPlayer = new MediaPlayer();
                                mediaPlayer.setDataSource(finalAudioFile.getAbsolutePath());
                                mediaPlayer.prepare();
                                activeAudioDuration = audioTime.getText().toString();
                                audioSeekBar.setProgress(mediaPlayer.getCurrentPosition());
                                audioSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                                    @Override
                                    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                                        if (fromUser) {
                                            mediaPlayer.seekTo(progress);
                                        }
                                    }

                                    @Override
                                    public void onStartTrackingTouch(SeekBar seekBar) {

                                    }

                                    @Override
                                    public void onStopTrackingTouch(SeekBar seekBar) {

                                    }
                                });
                                activeAudioSeekBarr = audioSeekBar;
                                activePlayer = playAudio;
                                activeAudioTime = audioTime;
                                seekHandler.postDelayed(runAudio, 1000);
                                mediaPlayer.start();
                                playAudio.setText(Finder.STRING.ICN_PAUSE.toString());
                            }
                        } else {
                            if (mediaPlayer != null) {
                                mediaPlayer.stop();
                                mediaPlayer.release();
                            }
                            if (activeAudioSeekBarr != null) {
                                activeAudioSeekBarr.setProgress(0);
                                activeAudioSeekBarr.setOnSeekBarChangeListener(null);
                            }
                            if (activeAudioTime != null) {
                                activeAudioTime.setText(activeAudioDuration);
                            }
                            if (!activeAudioDuration.equals("")) {
                                activeAudioDuration = "";
                            }
                            seekHandler.removeCallbacks(runAudio);
                            mediaPlayer = new MediaPlayer();
                            mediaPlayer.setDataSource(finalAudioFile.getAbsolutePath());
                            mediaPlayer.prepare();
                            activeAudioDuration = audioTime.getText().toString();
                            audioSeekBar.setProgress(mediaPlayer.getCurrentPosition());
                            audioSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                                @Override
                                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                                    if (fromUser) {
                                        mediaPlayer.seekTo(progress);
                                    }
                                }

                                @Override
                                public void onStartTrackingTouch(SeekBar seekBar) {

                                }

                                @Override
                                public void onStopTrackingTouch(SeekBar seekBar) {

                                }
                            });
                            activeAudioSeekBarr = audioSeekBar;
                            activePlayer = playAudio;
                            activeAudioTime = audioTime;
                            seekHandler.postDelayed(runAudio, 1000);
                            mediaPlayer.start();
                            playAudio.setText(Finder.STRING.ICN_PAUSE.toString());
                        }
                        //file2.delete();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    isplayAudio = true;
                } else {
                    playAudio.setText(Finder.STRING.ICN_PLAY.toString());
                    mediaPlayer.pause();
                    seekHandler.removeCallbacks(runAudio);
                    isplayAudio = false;
                }
            }
        });

    }

    public void showMensajeVideo(int position, Context context, final Message message, View rowView,
            TextView icnMessageArrow) {
        final TextView prevMessages = (TextView) rowView.findViewById(R.id.showprev_messages);
        TextView messageTime = (TextView) rowView.findViewById(R.id.message_time);
        final TextView icnMesajeTempo = (TextView) rowView.findViewById(R.id.icn_message_tempo);
        final View icnMensajeTempoDivider = (View) rowView.findViewById(R.id.icn_message_tempo_divider);
        final TextView icnMesajeCopy = (TextView) rowView.findViewById(R.id.icn_message_copy);
        final TextView icnMesajeBack = (TextView) rowView.findViewById(R.id.icn_message_back);
        final ImageView messageContent = (ImageView) rowView.findViewById(R.id.message_content);
        TextView messageStatus = (TextView) rowView.findViewById(R.id.message_status);
        final LinearLayout messageMenu = (LinearLayout) rowView.findViewById(R.id.messages_menu_layout);
        final LinearLayout mensajeLayout = (LinearLayout) rowView.findViewById(R.id.mensaje_layout);
        TextView messageDate = (TextView) rowView.findViewById(R.id.message_date);
        final ProgressBar progressBar = (ProgressBar) rowView.findViewById(R.id.progress_bar);
        final RelativeLayout progressLayout = (RelativeLayout) rowView.findViewById(R.id.progress_layout);
        final TextView progressText = (TextView) rowView.findViewById(R.id.progress_message);

        TFCache.apply(context, messageTime, TFCache.TF_WHITNEY_MEDIUM);
        TFCache.apply(context, icnMesajeTempo, TFCache.TF_SPEAKALL);
        TFCache.apply(context, icnMesajeCopy, TFCache.TF_SPEAKALL);
        TFCache.apply(context, icnMesajeBack, TFCache.TF_SPEAKALL);
        TFCache.apply(context, messageStatus, TFCache.TF_SPEAKALL);
        TFCache.apply(context, prevMessages, TFCache.TF_WHITNEY_MEDIUM);
        TFCache.apply(context, messageDate, TFCache.TF_WHITNEY_MEDIUM);

        if (position == 0) {
            if (mensajesTotal > mensajesOffset) {
                prevMessages.setVisibility(View.VISIBLE);
                prevMessages.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        prevMessages.setVisibility(View.GONE);
                        if (mensajesTotal - mensajesOffset >= 10) {
                            mensajesLimit = 10;
                            mensajesOffset += mensajesLimit;
                            showPreviousMessages(mensajesOffset);
                        } else {
                            mensajesLimit = mensajesTotal - mensajesOffset;
                            mensajesOffset += mensajesLimit;
                            showPreviousMessages(mensajesOffset);
                        }
                    }
                });
            }
        }

        DateFormat dateDay = new SimpleDateFormat("d");
        DateFormat dateDayText = new SimpleDateFormat("EEEE");
        DateFormat dateMonth = new SimpleDateFormat("MMMM");
        DateFormat dateYear = new SimpleDateFormat("yyyy");
        DateFormat timeFormat = new SimpleDateFormat("h:mm a");

        Calendar fechamsj = Calendar.getInstance();
        fechamsj.setTimeInMillis(message.emitedAt);
        String time = timeFormat.format(fechamsj.getTime());
        String dayMessage = dateDay.format(fechamsj.getTime());
        String monthMessage = dateMonth.format(fechamsj.getTime());
        String yearMessage = dateYear.format(fechamsj.getTime());
        String dayMessageText = dateDayText.format(fechamsj.getTime());
        char[] caracteres = dayMessageText.toCharArray();
        caracteres[0] = Character.toUpperCase(caracteres[0]);
        dayMessageText = new String(caracteres);

        Calendar fechaActual = Calendar.getInstance();
        String dayActual = dateDay.format(fechaActual.getTime());
        String monthActual = dateMonth.format(fechaActual.getTime());
        String yearActual = dateYear.format(fechaActual.getTime());

        String fechaMostrar = "";
        if (dayMessage.equals(dayActual) && monthMessage.equals(monthActual) && yearMessage.equals(yearActual)) {
            fechaMostrar = getString(R.string.messages_today);
        } else if (monthMessage.equals(monthActual) && yearMessage.equals(yearActual)) {
            int days = Integer.parseInt(dayActual) - Integer.parseInt(dayMessage);
            if (days < 7) {
                switch (days) {
                case 1:
                    fechaMostrar = getString(R.string.messages_yesterday);
                    break;
                default:
                    fechaMostrar = dayMessageText;
                    break;
                }
            } else {
                fechaMostrar = (dayMessage + " " + monthMessage + " " + yearMessage).toUpperCase();
            }
        } else {
            fechaMostrar = (dayMessage + " " + monthMessage + " " + yearMessage).toUpperCase();
        }

        messageDate.setText(fechaMostrar);
        if (position != -1) {

            if (itemAnterior != null) {
                if (!fechaMostrar.equals(fechaAnterior)) {
                    itemAnterior.findViewById(R.id.message_date).setVisibility(View.VISIBLE);
                } else {
                    itemAnterior.findViewById(R.id.message_date).setVisibility(View.GONE);
                }
            }
            itemAnterior = rowView;
            fechaAnterior = fechaMostrar;
        } else {
            View v = messagesList.getChildAt(messagesList.getChildCount() - 1);
            if (v != null) {
                TextView tv = (TextView) v.findViewById(R.id.message_date);
                if (tv.getText().toString().equals(fechaMostrar)) {
                    messageDate.setVisibility(View.GONE);
                } else {
                    messageDate.setVisibility(View.VISIBLE);
                }
            }
        }
        messageTime.setText(time);

        if (message.emisor.equals(u.id)) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (message.fileUploaded) {
                                if (new File(message.videoName).exists()) {
                                    if (message.photo != null) {
                                        Bitmap bmp = BitmapFactory.decodeByteArray(message.photo, 0,
                                                message.photo.length);
                                        messageContent.setImageBitmap(bmp);
                                        bmp = null;
                                    }
                                } else {
                                    if (message.photoBlur != null) {
                                        Bitmap bmp = BitmapFactory.decodeByteArray(message.photoBlur, 0,
                                                message.photoBlur.length);
                                        messageContent.setImageBitmap(bmp);
                                        bmp = null;
                                    }
                                }
                            } else {
                                if (message.photoBlur != null) {
                                    Bitmap bmp = BitmapFactory.decodeByteArray(message.photoBlur, 0,
                                            message.photoBlur.length);
                                    messageContent.setImageBitmap(bmp);
                                    bmp = null;
                                }
                            }
                        }
                    });
                }
            }).start();
            if (message.status != -1) {
                rowView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        if (messageSelected != null) {
                            View vista = messagesList.findViewWithTag(messageSelected);
                            vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                            messageSelected = message.mensajeId;
                            ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                                @Override
                                public void doBack() {
                                    View vista = messagesList.findViewWithTag(messageSelected);
                                    vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                                    ((MainActivity) activity).setOnBackPressedListener(null);
                                    messageSelected = null;
                                }
                            });
                        } else {
                            messageSelected = message.mensajeId;
                            ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                                @Override
                                public void doBack() {
                                    if (messageSelected != null) {
                                        View vista = messagesList.findViewWithTag(messageSelected);
                                        vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                                        ((MainActivity) activity).setOnBackPressedListener(null);
                                        messageSelected = null;
                                    }
                                }
                            });
                        }

                        Vibrator x = (Vibrator) activity.getApplicationContext()
                                .getSystemService(Context.VIBRATOR_SERVICE);
                        x.vibrate(30);
                        Message mensaje = new Select().from(Message.class).where("mensajeId = ?", message.mensajeId)
                                .executeSingle();
                        if (mensaje.status != 4) {
                            icnMesajeTempo.setVisibility(View.VISIBLE);
                            icnMensajeTempoDivider.setVisibility(View.VISIBLE);
                            icnMesajeCopy.setVisibility(View.VISIBLE);
                            icnMesajeBack.setVisibility(View.VISIBLE);
                            messageMenu.setVisibility(View.VISIBLE);
                            AnimatorSet set = new AnimatorSet();
                            set.playTogether(ObjectAnimator.ofFloat(icnMesajeTempo, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(icnMesajeTempo, "translationX", 150, 0),
                                    ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", 100, 0),
                                    ObjectAnimator.ofFloat(icnMesajeBack, "translationX", 50, 0));
                            set.setDuration(200).start();
                        } else {
                            icnMesajeCopy.setVisibility(View.VISIBLE);
                            icnMesajeBack.setVisibility(View.VISIBLE);
                            messageMenu.setVisibility(View.VISIBLE);
                            AnimatorSet set = new AnimatorSet();
                            set.playTogether(ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1),
                                    ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", 100, 0),
                                    ObjectAnimator.ofFloat(icnMesajeBack, "translationX", 50, 0));
                            set.setDuration(200).start();
                        }

                        return false;
                    }
                });
            }
            if (message.status == 1) {
                messageStatus.setTextSize(16);
                mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
                GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
                drawable.setCornerRadius(radius);
                drawable.setColor(BalloonFragment.getBackgroundColor(activity));
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
                messageStatus.setTextColor(getResources().getColor(R.color.speak_all_ligh_gray));
                messageStatus.setText(Finder.STRING.ICN_MSJ_SENDING.toString());
                ValueAnimator colorAnim = ObjectAnimator.ofFloat(messageStatus, "alpha", 1, 0);
                colorAnim.setRepeatCount(ValueAnimator.INFINITE);
                colorAnim.setRepeatMode(ValueAnimator.REVERSE);
                colorAnim.setDuration(1000).start();
                animaciones.put(message.mensajeId, colorAnim);
                try {
                    final JSONObject mensaje = new JSONObject();
                    mensaje.put("message_id", message.mensajeId);
                    mensaje.put("source", message.emisor);
                    mensaje.put("source_email", message.emisorEmail);
                    mensaje.put("target_email", message.receptorEmail);
                    mensaje.put("target", message.receptor);
                    mensaje.put("type", message.tipo);
                    mensaje.put("delay", message.delay);
                    if (!message.fileUploaded) {
                        progressLayout.setVisibility(View.VISIBLE);
                        System.gc();
                        File fileVideo = new File(message.videoName);
                        if (fileVideo.length() > 10000000) {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    runTranscodingUsingLoader(message.videoName, message, mensaje, progressBar,
                                            progressLayout, progressText, messageContent);
                                }
                            }).start();
                        } else {
                            uploadVideoToServer(message.videoName, message, mensaje, progressBar, progressLayout,
                                    progressText, messageContent);
                        }

                    } else {
                        mensaje.put("videos", message.fileName);
                        if (SpeakSocket.mSocket != null)
                            if (SpeakSocket.mSocket.connected()) {
                                message.status = 1;
                                SpeakSocket.mSocket.emit("message", mensaje);
                            } else {
                                message.status = -1;
                            }
                        message.save();
                        changeStatus(message.mensajeId, message.status);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            Log.e("SIGUIENTE TAREA", "SIGUIENTE TAREA");
            if (message.status == -1) {
                messageStatus.setTextSize(11);
                mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
                GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
                drawable.setCornerRadius(radius);
                drawable.setColor(BalloonFragment.getBackgroundColor(activity));
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
                messageStatus.setText(Finder.STRING.ICN_MSJ_ERROR.toString());
            }
            if (message.status == 3) {
                messageStatus.setTextSize(11);
                mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
                GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
                drawable.setCornerRadius(radius);
                drawable.setColor(BalloonFragment.getBackgroundColor(activity));
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
                messageStatus.setText(Finder.STRING.ICN_MSJ_CLOSED.toString());
            }
            if (message.status == 2) {
                messageStatus.setTextSize(16);
                mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
                GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
                drawable.setCornerRadius(radius);
                drawable.setColor(BalloonFragment.getBackgroundColor(activity));
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
                messageStatus.setText(Finder.STRING.ICN_MSJ_SEND.toString());
            }
            if (message.status == 4) {
                messageStatus.setTextSize(11);
                mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
                GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
                drawable.setCornerRadius(radius);
                drawable.setColor(BalloonFragment.getBackgroundColor(activity));
                icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
                messageStatus.setText(Finder.STRING.ICN_MSJ_OPENED.toString());
                icnMensajeTempoDivider.setVisibility(View.GONE);
                icnMesajeTempo.setVisibility(View.GONE);
            } else {
                icnMensajeTempoDivider.setVisibility(View.INVISIBLE);
                icnMesajeTempo.setVisibility(View.INVISIBLE);
            }

        } else {
            mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
            GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
            drawable.setCornerRadius(radius);
            drawable.setColor(BalloonFragment.getFriendBalloon(activity));
            if (message.tipo == Integer.parseInt(getString(R.string.MSG_TYPE_BROADCAST_PHOTO))) {
                messageStatus.setTextSize(15);
                messageStatus.setText(Finder.STRING.ICN_BROADCAST_FILL.toString());
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            File archivo = new File(message.videoName);
                            if (archivo.exists()) {
                                if (message.photo != null) {
                                    Bitmap bmp = BitmapFactory.decodeByteArray(message.photo, 0,
                                            message.photo.length);
                                    messageContent.setImageBitmap(bmp);
                                    bmp = null;
                                }
                            } else {
                                if (message.photoBlur != null) {
                                    Bitmap bmp = BitmapFactory.decodeByteArray(message.photoBlur, 0,
                                            message.photoBlur.length);
                                    messageContent.setImageBitmap(bmp);
                                    bmp = null;
                                }
                            }
                        }
                    });
                }
            }).start();
            //messageContent.setText(message.mensajeTrad);
            icnMesajeTempo.setVisibility(View.GONE);
            rowView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if (messageSelected != null) {
                        View vista = messagesList.findViewWithTag(messageSelected);
                        vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                        messageSelected = message.mensajeId;
                        ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                            @Override
                            public void doBack() {
                                View vista = messagesList.findViewWithTag(messageSelected);
                                vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                                ((MainActivity) activity).setOnBackPressedListener(null);
                                messageSelected = null;
                            }
                        });
                    } else {
                        messageSelected = message.mensajeId;
                        ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                            @Override
                            public void doBack() {
                                View vista = messagesList.findViewWithTag(messageSelected);
                                vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                                ((MainActivity) activity).setOnBackPressedListener(null);
                                messageSelected = null;
                            }
                        });
                    }

                    Vibrator x = (Vibrator) activity.getApplicationContext()
                            .getSystemService(Context.VIBRATOR_SERVICE);
                    x.vibrate(20);
                    icnMesajeCopy.setVisibility(View.VISIBLE);
                    icnMesajeBack.setVisibility(View.VISIBLE);
                    messageMenu.setVisibility(View.VISIBLE);
                    AnimatorSet set = new AnimatorSet();
                    set.playTogether(ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1),
                            ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1),
                            ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1),
                            ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", -100, 0),
                            ObjectAnimator.ofFloat(icnMesajeBack, "translationX", -150, 0));
                    set.setDuration(200).start();
                    return false;
                }
            });
        }

        icnMesajeTempo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                JSONObject notifyMessage = new JSONObject();
                try {
                    Message mensaje = new Select().from(Message.class).where("mensajeId = ?", message.mensajeId)
                            .executeSingle();
                    if (mensaje.status != 4) {
                        notifyMessage.put("type", mensaje.tipo);
                        notifyMessage.put("message_id", mensaje.mensajeId);
                        notifyMessage.put("source", mensaje.receptor);
                        notifyMessage.put("status", 5);
                        SpeakSocket.mSocket.emit("message-status", notifyMessage);
                    }
                    new Delete().from(Message.class).where("mensajeId = ?", mensaje.mensajeId).execute();
                    Message message = null;
                    if (mensaje.emisor.equals(u.id)) {
                        message = new Select().from(Message.class)
                                .where("emisor = ? or receptor = ?", mensaje.receptor, mensaje.receptor)
                                .orderBy("emitedAt DESC").executeSingle();
                    } else {
                        message = new Select().from(Message.class)
                                .where("emisor = ? or receptor = ?", mensaje.emisor, mensaje.emisor)
                                .orderBy("emitedAt DESC").executeSingle();
                    }
                    if (message != null) {
                        Chats chat = null;
                        if (mensaje.emisor.equals(u.id)) {
                            chat = new Select().from(Chats.class).where("idContacto = ?", mensaje.receptor)
                                    .executeSingle();
                        } else {
                            chat = new Select().from(Chats.class).where("idContacto = ?", mensaje.emisor)
                                    .executeSingle();
                        }
                        if (chat != null) {
                            chat.mensajeId = message.mensajeId;
                            chat.lastStatus = message.status;
                            chat.emitedAt = message.emitedAt;
                            chat.lang = message.emisorLang;
                            chat.notRead = 0;
                            if (chat.idContacto.equals(message.emisor))
                                chat.lastMessage = message.mensajeTrad;
                            else
                                chat.lastMessage = message.mensaje;
                            chat.save();
                        }
                    } else {
                        if (mensaje.emisor.equals(u.id)) {
                            new Delete().from(Chats.class).where("idContacto = ?", mensaje.receptor).execute();
                        } else {
                            new Delete().from(Chats.class).where("idContacto = ?", mensaje.emisor).execute();
                        }
                    }

                    View delete = messagesList.findViewWithTag(mensaje.mensajeId);
                    if (delete != null)
                        messagesList.removeView(delete);
                    messageSelected = null;
                    ((MainActivity) activity).setOnBackPressedListener(null);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        );

        icnMesajeCopy.setOnClickListener(new View.OnClickListener()

        {
            @Override
            public void onClick(View v) {
                /*ClipData clip = ClipData.newPlainText("text", messageContent.getText().toString());
                ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                clipboard.setPrimaryClip(clip);
                Toast.makeText(activity, "Copiado", Toast.LENGTH_SHORT).show();*/
            }
        }

        );

        icnMesajeBack.setOnClickListener(new View.OnClickListener()

        {
            @Override
            public void onClick(View v) {
                if (message.emisor.equals(u.id)) {
                    getFragmentManager().beginTransaction()
                            .replace(R.id.container2, ForwarForFragment.newInstance(message.mensaje))
                            .addToBackStack(null).commit();
                    ((MainActivity) activity).setOnBackPressedListener(null);
                } else {
                    getFragmentManager().beginTransaction()
                            .replace(R.id.container2, ForwarForFragment.newInstance(message.mensajeTrad))
                            .addToBackStack(null).commit();
                    ((MainActivity) activity).setOnBackPressedListener(null);
                }
            }
        }

        );

        rowView.setOnClickListener(new View.OnClickListener()

        {
            @Override
            public void onClick(View v) {
                final Message mensaje1 = new Select().from(Message.class).where("mensajeId = ?", message.mensajeId)
                        .executeSingle();
                if (messageSelected != null) {
                    View vista = messagesList.findViewWithTag(messageSelected);
                    if (!messageSelected.equals(message.mensajeId)) {
                        vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                        ((MainActivity) activity).setOnBackPressedListener(null);
                        messageSelected = null;
                    }
                } else {
                    if (mensaje1.status != -1) {
                        if (mensaje1.fileDownloaded || mensaje1.fileUploaded) {
                            dontClose = true;
                            ((MainActivity) activity).dontClose = true;
                            hideKeyBoard();
                            Intent i = new Intent();
                            i.setAction(android.content.Intent.ACTION_VIEW);
                            File videoFile2Play2 = new File(message.videoName);
                            i.setDataAndType(Uri.fromFile(videoFile2Play2), "video/*");
                            startActivity(i);
                        }
                    }
                }
                if (mensaje1.status == -1) {
                    final JSONObject data = new JSONObject();
                    try {
                        data.put("message_id", mensaje1.mensajeId);
                        data.put("source", mensaje1.emisor);
                        data.put("source_email", mensaje1.emisorEmail);
                        data.put("target_email", mensaje1.receptorEmail);
                        data.put("target", mensaje1.receptor);
                        data.put("type", mensaje1.tipo);
                        data.put("delay", mensaje1.delay);
                        if (!mensaje1.fileUploaded) {
                            Log.w("REENVIANDO VIDEO", "REENVIO VIDEO");
                            progressLayout.setVisibility(View.VISIBLE);
                            File fileVideo = new File(mensaje1.videoName);
                            if (fileVideo.length() > 10000000) {
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Log.w("COMPRESS VIDEO", "COMPRESS VIDEO");
                                        if (SpeakSocket.mSocket != null)
                                            if (SpeakSocket.mSocket.connected()) {
                                                mensaje1.status = 1;
                                            } else {
                                                mensaje1.status = -1;
                                                runTranscodingUsingLoader(mensaje1.videoName, mensaje1, data,
                                                        progressBar, progressLayout, progressText, messageContent);
                                            }
                                        mensaje1.save();
                                        changeStatus(mensaje1.mensajeId, mensaje1.status);
                                    }
                                }).start();

                            } else {
                                uploadVideoToServer(mensaje1.videoName, mensaje1, data, progressBar, progressLayout,
                                        progressText, messageContent);
                            }
                        } else {
                            data.put("videos", message.fileName);
                            if (SpeakSocket.mSocket != null)
                                if (SpeakSocket.mSocket.connected()) {
                                    mensaje1.status = 1;
                                    SpeakSocket.mSocket.emit("message", data);
                                } else {
                                    mensaje1.status = -1;
                                }
                            mensaje1.save();
                            changeStatus(mensaje1.mensajeId, mensaje1.status);
                        }
                    } catch (JSONException e) {
                        Log.w("--->", e.toString());
                        e.printStackTrace();
                    }
                }
            }
        }

        );

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        System.gc();
        if (requestCode == 18 && resultCode == Activity.RESULT_OK && null != data) {
            final ProgressDialog dialogLoader = ProgressDialog.show(activity, "",
                    Finder.STRING.CONTACT_PROGRESS.toString(), true);
            Uri selectedVideo = data.getData();
            String[] filePathColumn = { MediaStore.Video.Media.DATA };
            final Cursor cursor = activity.getContentResolver().query(selectedVideo, filePathColumn, null, null,
                    null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            final String videoPath = cursor.getString(columnIndex);
            cursor.close();
            System.gc();
            final File fileVideo = new File(videoPath);
            Calendar fecha = Calendar.getInstance();
            final long fechaInMillis = fecha.getTimeInMillis();
            File pathImage = new File(
                    Environment.getExternalStorageDirectory().getAbsolutePath() + "/SpeakOn/Video/Sent");
            pathImage.mkdirs();
            final File file = new File(pathImage, +fechaInMillis + ".mp4");
            cursor.close();
            //runTranscodingUsingLoader(fileVideo.getAbsolutePath(), file.getAbsolutePath());
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Bitmap thumbnailVideo = ThumbnailUtils.createVideoThumbnail(videoPath,
                            MediaStore.Video.Thumbnails.MICRO_KIND);
                    Bitmap toUpload = scaleDownLargeImageWithAspectRatio(thumbnailVideo, 1280);
                    Bitmap binaryData = toUpload;
                    Bitmap binaryData2 = BlurImage(toUpload);
                    try {
                        FileInputStream inStream = new FileInputStream(fileVideo);
                        FileOutputStream outStream = new FileOutputStream(file);

                        byte[] buffer = new byte[1024];

                        int length;
                        //copy the file content in bytes
                        while ((length = inStream.read(buffer)) > 0) {

                            outStream.write(buffer, 0, length);

                        }

                        inStream.close();
                        outStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    final Message msjVideo = new Message();
                    try {
                        String id = u.id + contact.idContacto + fechaInMillis + Settings.Secure
                                .getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID);

                        msjVideo.mensajeId = id;
                        msjVideo.emisor = u.id;
                        msjVideo.receptor = contact.idContacto;
                        msjVideo.emisorEmail = u.email;
                        msjVideo.receptorEmail = contact.email;
                        msjVideo.emisorLang = u.lang;
                        msjVideo.receptorLang = contact.lang;
                        msjVideo.emitedAt = fechaInMillis;
                        msjVideo.tipo = Integer.parseInt(getString(R.string.MSG_TYPE_VIDEO));
                        if (tiempoMensaje)
                            msjVideo.delay = temporizadorSeek.getValue();
                        else
                            msjVideo.delay = 0;
                        msjVideo.videoName = file.getAbsolutePath();

                        ByteArrayOutputStream stream = new ByteArrayOutputStream();
                        binaryData.compress(Bitmap.CompressFormat.JPEG, 60, stream);
                        byte[] byteArray = stream.toByteArray();
                        msjVideo.photo = byteArray;

                        ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
                        binaryData2.compress(Bitmap.CompressFormat.JPEG, 60, stream2);
                        byte[] byteArray2 = stream2.toByteArray();
                        msjVideo.photoBlur = byteArray2;
                        if (SpeakSocket.mSocket != null)
                            if (SpeakSocket.mSocket.connected()) {
                                msjVideo.status = 1;
                            } else {
                                msjVideo.status = -1;
                            }
                        msjVideo.fileUploaded = false;
                        msjVideo.save();

                        Chats chat = new Select().from(Chats.class).where("idContacto = ?", msjVideo.receptor)
                                .executeSingle();
                        if (chat == null) {
                            Contact contact = new Select().from(Contact.class)
                                    .where("id_contact = ?", msjVideo.receptor).executeSingle();
                            Chats newChat = new Chats();
                            newChat.mensajeId = msjVideo.mensajeId;
                            newChat.idContacto = msjVideo.receptor;
                            newChat.isLockedConversation = false;
                            newChat.lastStatus = msjVideo.status;
                            newChat.email = msjVideo.receptorEmail;
                            if (contact != null) {
                                newChat.photo = contact.photo;
                                newChat.fullName = contact.fullName;
                                newChat.lang = contact.lang;
                                newChat.screenName = contact.screenName;
                                newChat.photoload = true;
                                newChat.phone = contact.phone;
                            } else {
                                newChat.photo = null;
                                newChat.photoload = false;
                                newChat.fullName = msjVideo.receptorEmail;
                                newChat.lang = msjVideo.receptorLang;
                                newChat.screenName = msjVideo.receptorEmail;
                                newChat.phone = null;
                            }
                            newChat.emitedAt = msjVideo.emitedAt;
                            newChat.notRead = 0;
                            newChat.lastMessage = "send Video";
                            newChat.show = true;
                            newChat.save();
                        } else {
                            if (!chat.photoload) {
                                Contact contact = new Select().from(Contact.class)
                                        .where("id_contact = ?", msjVideo.emisor).executeSingle();
                                if (contact != null) {
                                    chat.photo = contact.photo;
                                    chat.photoload = true;
                                } else {
                                    chat.photo = null;
                                    chat.photoload = false;
                                }
                            }
                            chat.mensajeId = msjVideo.mensajeId;
                            chat.lastStatus = msjVideo.status;
                            chat.emitedAt = msjVideo.emitedAt;
                            chat.notRead = 0;
                            chat.lastMessage = "send Video";
                            chat.save();
                        }
                        showNewMessage(msjVideo);
                        dialogLoader.dismiss();
                    } catch (Exception e) {
                    }
                    System.gc();
                }
            }).start();

        }

        if (requestCode == 45) {
            milocManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
            List<String> allProviders = milocManager.getAllProviders();
            boolean gpsProvider = false;
            boolean netProvider = false;
            for (String providerName : allProviders) {
                if (providerName.equals(LocationManager.GPS_PROVIDER)) {
                    gpsProvider = true;
                }
                if (providerName.equals(LocationManager.NETWORK_PROVIDER)) {
                    netProvider = true;
                }
            }
            checkCountryLocation(gpsProvider, netProvider);
        }

        if (requestCode == 34) {
            if (resultCode == activity.RESULT_OK) {
                Uri contactUri = data.getData();
                try {
                    //contactPic.setImageBitmap(getPhoto(contactUri));
                    JSONObject contacto = new JSONObject();
                    contacto.put("nombre", getName(contactUri));
                    contacto.put("telefono", getPhone(contactUri));
                    Message msjNew = new Message();
                    Calendar fecha = Calendar.getInstance();
                    String id = u.id + contact.idContacto + fecha.getTimeInMillis()
                            + Settings.Secure.getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID);
                    msjNew.translation = true;
                    msjNew.mensajeId = id;
                    msjNew.emisor = u.id;
                    msjNew.receptor = contact.idContacto;
                    msjNew.mensaje = contacto.toString();
                    msjNew.emisorEmail = u.email;
                    msjNew.receptorEmail = contact.email;
                    msjNew.emisorLang = u.lang;
                    msjNew.receptorLang = contact.lang;
                    msjNew.emitedAt = fecha.getTimeInMillis();
                    msjNew.tipo = Integer.parseInt(getString(R.string.MSG_TYPE_CONTACT));
                    msjNew.delay = 0;
                    if (SpeakSocket.mSocket != null)
                        if (SpeakSocket.mSocket.connected()) {
                            msjNew.status = 1;
                        } else {
                            msjNew.status = -1;
                        }
                    msjNew.save();
                    Chats chat = new Select().from(Chats.class).where("idContacto = ?", msjNew.receptor)
                            .executeSingle();
                    if (chat == null) {
                        Contact contact = new Select().from(Contact.class).where("id_contact = ?", msjNew.receptor)
                                .executeSingle();
                        Chats newChat = new Chats();
                        newChat.mensajeId = msjNew.mensajeId;
                        newChat.idContacto = msjNew.receptor;
                        newChat.isLockedConversation = false;
                        newChat.lastStatus = msjNew.status;
                        newChat.email = msjNew.receptorEmail;
                        if (contact != null) {
                            newChat.photo = contact.photo;
                            newChat.fullName = contact.fullName;
                            newChat.lang = contact.lang;
                            newChat.screenName = contact.screenName;
                            newChat.photoload = true;
                            newChat.phone = contact.phone;
                        } else {
                            newChat.photo = null;
                            newChat.photoload = false;
                            newChat.fullName = msjNew.receptorEmail;
                            newChat.lang = msjNew.receptorLang;
                            newChat.screenName = msjNew.receptorEmail;
                            newChat.phone = null;
                        }
                        newChat.emitedAt = msjNew.emitedAt;
                        newChat.notRead = 0;
                        newChat.lastMessage = "send Contact";
                        newChat.show = true;
                        newChat.save();
                    } else {
                        if (!chat.photoload) {
                            Contact contact = new Select().from(Contact.class)
                                    .where("id_contact = ?", msjNew.emisor).executeSingle();
                            if (contact != null) {
                                chat.photo = contact.photo;
                                chat.photoload = true;
                            } else {
                                chat.photo = null;
                                chat.photoload = false;
                            }
                        }
                        chat.mensajeId = msjNew.mensajeId;
                        chat.lastStatus = msjNew.status;
                        chat.emitedAt = msjNew.emitedAt;
                        chat.notRead = 0;
                        chat.lastMessage = "send Contact";
                        chat.save();
                    }
                    showNewMessage(msjNew);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            System.gc();
        }
        if (requestCode == 1 && null != data) {
            Uri selectedImage = data.getData();
            InputStream imageStream = null;
            try {
                imageStream = activity.getContentResolver().openInputStream(selectedImage);
            } catch (FileNotFoundException e) {
            }
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = activity.getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            Bitmap bitmapRotate = C.rotateBitmapAndScale(picturePath);
            cursor.close();
            System.gc();
            Calendar fecha = Calendar.getInstance();
            long fechaInMillis = fecha.getTimeInMillis();
            File pathImage = new File(
                    Environment.getExternalStorageDirectory().getAbsolutePath() + "/SpeakOn/Image/Sent");
            pathImage.mkdirs();
            Bitmap toUpload = scaleDownLargeImageWithAspectRatio(bitmapRotate, 1280);
            System.gc();
            Bitmap binaryData = scaleDownLargeImageWithAspectRatio(toUpload, 500);
            System.gc();
            Bitmap binaryData2 = BlurImage(scaleDownLargeImageWithAspectRatio(toUpload, 400));
            System.gc();
            File file = new File(pathImage, +fechaInMillis + ".png");
            OutputStream outputStream = null;
            try {
                outputStream = new FileOutputStream(file);
                toUpload.compress(Bitmap.CompressFormat.JPEG, 60, outputStream);
                outputStream.flush();
                outputStream.close();
                System.gc();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                final Message msjPhoto = new Message();
                String id = u.id + contact.idContacto + fechaInMillis
                        + Settings.Secure.getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID);
                msjPhoto.mensajeId = id;
                msjPhoto.emisor = u.id;
                msjPhoto.receptor = contact.idContacto;
                msjPhoto.emisorEmail = u.email;
                msjPhoto.receptorEmail = contact.email;
                msjPhoto.emisorLang = u.lang;
                msjPhoto.receptorLang = contact.lang;
                msjPhoto.emitedAt = fechaInMillis;
                msjPhoto.tipo = Integer.parseInt(getString(R.string.MSG_TYPE_PHOTO));
                if (tiempoMensaje)
                    msjPhoto.delay = temporizadorSeek.getValue();
                else
                    msjPhoto.delay = 0;
                msjPhoto.photoName = file.getAbsolutePath();

                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                binaryData.compress(Bitmap.CompressFormat.JPEG, 60, stream);
                byte[] byteArray = stream.toByteArray();
                msjPhoto.photo = byteArray;

                ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
                binaryData2.compress(Bitmap.CompressFormat.JPEG, 40, stream2);
                byte[] byteArray2 = stream2.toByteArray();
                msjPhoto.photoBlur = byteArray2;
                if (SpeakSocket.mSocket != null)
                    if (SpeakSocket.mSocket.connected()) {
                        msjPhoto.status = 1;
                    } else {
                        msjPhoto.status = -1;
                    }
                msjPhoto.fileUploaded = false;
                msjPhoto.save();
                Chats chat = new Select().from(Chats.class).where("idContacto = ?", msjPhoto.receptor)
                        .executeSingle();
                if (chat == null) {
                    Contact contact = new Select().from(Contact.class).where("id_contact = ?", msjPhoto.receptor)
                            .executeSingle();
                    Chats newChat = new Chats();
                    newChat.mensajeId = msjPhoto.mensajeId;
                    newChat.idContacto = msjPhoto.receptor;
                    newChat.isLockedConversation = false;
                    newChat.lastStatus = msjPhoto.status;
                    newChat.email = msjPhoto.receptorEmail;
                    if (contact != null) {
                        newChat.photo = contact.photo;
                        newChat.fullName = contact.fullName;
                        newChat.lang = contact.lang;
                        newChat.screenName = contact.screenName;
                        newChat.photoload = true;
                        newChat.phone = contact.phone;
                    } else {
                        newChat.photo = null;
                        newChat.photoload = false;
                        newChat.fullName = msjPhoto.receptorEmail;
                        newChat.lang = msjPhoto.receptorLang;
                        newChat.screenName = msjPhoto.receptorEmail;
                        newChat.phone = null;
                    }
                    newChat.emitedAt = msjPhoto.emitedAt;
                    newChat.notRead = 0;
                    newChat.lastMessage = "send Image";
                    newChat.show = true;
                    newChat.save();
                } else {
                    if (!chat.photoload) {
                        Contact contact = new Select().from(Contact.class).where("id_contact = ?", msjPhoto.emisor)
                                .executeSingle();
                        if (contact != null) {
                            chat.photo = contact.photo;
                            chat.photoload = true;
                        } else {
                            chat.photo = null;
                            chat.photoload = false;
                        }
                    }
                    chat.mensajeId = msjPhoto.mensajeId;
                    chat.lastStatus = msjPhoto.status;
                    chat.emitedAt = msjPhoto.emitedAt;
                    chat.notRead = 0;
                    chat.lastMessage = "send Image";
                    chat.save();
                }
                showNewMessage(msjPhoto);

            } catch (Exception e) {
            }
            System.gc();
        }
        if (requestCode == 23) {
            if (resultCode == Activity.RESULT_OK) {
                Bitmap bitmapRotate = C
                        .rotateBitmapAndScale(Environment.getExternalStorageDirectory().getAbsolutePath()
                                + "/SpeakOn/Image/Sent/" + dateToCamera + ".png");
                System.gc();
                Bitmap toUpload = scaleDownLargeImageWithAspectRatio(bitmapRotate, 1280);
                System.gc();
                Bitmap binaryData = scaleDownLargeImageWithAspectRatio(toUpload, 500);
                System.gc();
                Bitmap binaryData2 = BlurImage(scaleDownLargeImageWithAspectRatio(toUpload, 400));
                System.gc();
                File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                        + "/SpeakOn/Image/Sent/" + dateToCamera + ".png");
                OutputStream outputStream = null;
                try {
                    outputStream = new FileOutputStream(file);
                    toUpload.compress(Bitmap.CompressFormat.JPEG, 60, outputStream);
                    outputStream.flush();
                    outputStream.close();
                    System.gc();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    final Message msjPhoto = new Message();
                    String id = u.id + contact.idContacto + dateToCamera
                            + Settings.Secure.getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID);
                    msjPhoto.mensajeId = id;
                    msjPhoto.emisor = u.id;
                    msjPhoto.receptor = contact.idContacto;
                    msjPhoto.emisorEmail = u.email;
                    msjPhoto.receptorEmail = contact.email;
                    msjPhoto.emisorLang = u.lang;
                    msjPhoto.receptorLang = contact.lang;
                    msjPhoto.emitedAt = dateToCamera;
                    msjPhoto.tipo = Integer.parseInt(getString(R.string.MSG_TYPE_PHOTO));
                    if (tiempoMensaje)
                        msjPhoto.delay = temporizadorSeek.getValue();
                    else
                        msjPhoto.delay = 0;
                    msjPhoto.photoName = file.getAbsolutePath();

                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    binaryData.compress(Bitmap.CompressFormat.JPEG, 60, stream);
                    byte[] byteArray = stream.toByteArray();
                    msjPhoto.photo = byteArray;

                    ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
                    binaryData2.compress(Bitmap.CompressFormat.JPEG, 40, stream2);
                    byte[] byteArray2 = stream2.toByteArray();
                    msjPhoto.photoBlur = byteArray2;
                    if (SpeakSocket.mSocket != null)
                        if (SpeakSocket.mSocket.connected()) {
                            msjPhoto.status = 1;
                        } else {
                            msjPhoto.status = -1;
                        }
                    msjPhoto.fileUploaded = false;
                    msjPhoto.save();
                    Chats chat = new Select().from(Chats.class).where("idContacto = ?", msjPhoto.receptor)
                            .executeSingle();
                    if (chat == null) {
                        Contact contact = new Select().from(Contact.class)
                                .where("id_contact = ?", msjPhoto.receptor).executeSingle();
                        Chats newChat = new Chats();
                        newChat.mensajeId = msjPhoto.mensajeId;
                        newChat.idContacto = msjPhoto.receptor;
                        newChat.isLockedConversation = false;
                        newChat.lastStatus = msjPhoto.status;
                        newChat.email = msjPhoto.receptorEmail;
                        if (contact != null) {
                            newChat.photo = contact.photo;
                            newChat.fullName = contact.fullName;
                            newChat.lang = contact.lang;
                            newChat.screenName = contact.screenName;
                            newChat.photoload = true;
                            newChat.phone = contact.phone;
                        } else {
                            newChat.photo = null;
                            newChat.photoload = false;
                            newChat.fullName = msjPhoto.receptorEmail;
                            newChat.lang = msjPhoto.receptorLang;
                            newChat.screenName = msjPhoto.receptorEmail;
                            newChat.phone = null;
                        }
                        newChat.emitedAt = msjPhoto.emitedAt;
                        newChat.notRead = 0;
                        newChat.lastMessage = "send Image";
                        newChat.show = true;
                        newChat.save();
                    } else {
                        if (!chat.photoload) {
                            Contact contact = new Select().from(Contact.class)
                                    .where("id_contact = ?", msjPhoto.emisor).executeSingle();
                            if (contact != null) {
                                chat.photo = contact.photo;
                                chat.photoload = true;
                            } else {
                                chat.photo = null;
                                chat.photoload = false;
                            }
                        }
                        chat.mensajeId = msjPhoto.mensajeId;
                        chat.lastStatus = msjPhoto.status;
                        chat.emitedAt = msjPhoto.emitedAt;
                        chat.notRead = 0;
                        chat.lastMessage = "send Image";
                        chat.save();
                    }
                    showNewMessage(msjPhoto);
                } catch (Exception e) {
                }
                System.gc();
            }
        }
    }

    private String getName(Uri uri) {
        String name = null;
        ContentResolver contentResolver = activity.getContentResolver();
        Cursor c = contentResolver.query(uri, new String[] { ContactsContract.Contacts.DISPLAY_NAME }, null, null,
                null);
        if (c.moveToFirst()) {
            name = c.getString(0);
        }
        c.close();
        return name;
    }

    private String getPhone(Uri uri) {
        String id = null;
        String phone = null;
        Cursor contactCursor = activity.getContentResolver().query(uri,
                new String[] { ContactsContract.Contacts._ID }, null, null, null);
        if (contactCursor.moveToFirst()) {
            id = contactCursor.getString(0);
        }
        contactCursor.close();
        String selectionArgs = ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND "
                + ContactsContract.CommonDataKinds.Phone.TYPE + "= "
                + ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE;

        Cursor phoneCursor = activity.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER }, selectionArgs, new String[] { id },
                null);
        if (phoneCursor.moveToFirst()) {
            phone = phoneCursor.getString(0);
        }
        phoneCursor.close();
        return phone;
    }

    private Bitmap getPhoto(Uri uri) {
        Bitmap photo = null;
        String id = null;
        Cursor contactCursor = activity.getContentResolver().query(uri,
                new String[] { ContactsContract.Contacts._ID }, null, null, null);

        if (contactCursor.moveToFirst()) {
            id = contactCursor.getString(0);
        }
        contactCursor.close();
        try {
            InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(activity.getContentResolver(),
                    ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(id)));
            if (input != null) {
                photo = BitmapFactory.decodeStream(input);
                input.close();
            }

        } catch (IOException iox) {
            Log.e("Error: ", iox.toString());
        }
        return photo;
    }

    public void showDialogAddContact(final String contacto) {
        final boolean[] agregar = { false };
        try {
            final ContentResolver contentResolver = activity.getContentResolver();
            final JSONObject contact = new JSONObject(contacto);
            String name = null;
            String phone = null;

            String selectionArgs = ContactsContract.Contacts.DISPLAY_NAME + " = ? AND "
                    + ContactsContract.CommonDataKinds.Phone.TYPE + "= "
                    + ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE;

            Cursor c = contentResolver.query(ContactsContract.Data.CONTENT_URI,
                    new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER }, selectionArgs,
                    new String[] { contact.getString("nombre") }, null);

            if (c.getCount() > 0) {
                if (c.moveToFirst()) {
                    phone = c.getString(0);
                }
                if (phone.equals(contact.getString("telefono"))) {
                    Toast.makeText(activity, "Ya tienes este contacto", Toast.LENGTH_SHORT).show();
                } else {
                    LayoutInflater dialogInflater = (LayoutInflater) activity
                            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    dialogView = dialogInflater.inflate(R.layout.add_contact_message, null);
                    final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity).setView(dialogView)
                            .setCancelable(true).setPositiveButton(R.string.add_contact_yes, null)
                            .setNegativeButton(R.string.add_contact_no, null);
                    finderDialog = dialogBuilder.show();
                    finderDialog.setCanceledOnTouchOutside(true);
                    finderDialog.getButton(DialogInterface.BUTTON_POSITIVE)
                            .setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    try {
                                        finderDialog.dismiss();
                                        agregar[0] = true;
                                        if (agregar[0]) {
                                            ContentValues values = new ContentValues();
                                            values.put(ContactsContract.Data.DISPLAY_NAME,
                                                    contact.getString("nombre"));
                                            Uri rawContactUri = contentResolver
                                                    .insert(ContactsContract.RawContacts.CONTENT_URI, values);

                                            long rawContactId = ContentUris.parseId(rawContactUri);
                                            long contactId = ContentUris.parseId(rawContactUri);

                                            values.clear();
                                            values.put(ContactsContract.CommonDataKinds.Phone.NUMBER,
                                                    contact.getString("telefono"));
                                            values.put(ContactsContract.CommonDataKinds.Phone.TYPE,
                                                    ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
                                            values.put(Data.RAW_CONTACT_ID, rawContactId);
                                            contentResolver.insert(ContactsContract.Data.CONTENT_URI, values);

                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                    finderDialog.getButton(DialogInterface.BUTTON_NEGATIVE)
                            .setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    finderDialog.dismiss();
                                    agregar[0] = false;
                                }
                            });
                }
            } else {
                LayoutInflater dialogInflater = (LayoutInflater) activity
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                dialogView = dialogInflater.inflate(R.layout.add_contact_message, null);
                final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity).setView(dialogView)
                        .setCancelable(true).setPositiveButton(R.string.add_contact_yes, null)
                        .setNegativeButton(R.string.add_contact_no, null);
                finderDialog = dialogBuilder.show();
                finderDialog.setCanceledOnTouchOutside(true);
                finderDialog.getButton(DialogInterface.BUTTON_POSITIVE)
                        .setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                try {
                                    finderDialog.dismiss();
                                    agregar[0] = true;
                                    if (agregar[0]) {
                                        ContentValues values = new ContentValues();
                                        values.put(ContactsContract.Data.DISPLAY_NAME, contact.getString("nombre"));
                                        Uri rawContactUri = contentResolver
                                                .insert(ContactsContract.RawContacts.CONTENT_URI, values);

                                        long rawContactId = ContentUris.parseId(rawContactUri);

                                        values.clear();
                                        values.put(android.provider.ContactsContract.Data.MIMETYPE,
                                                ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
                                        values.put(ContactsContract.CommonDataKinds.Phone.NUMBER,
                                                contact.getString("telefono"));
                                        values.put(ContactsContract.CommonDataKinds.Phone.TYPE,
                                                ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
                                        values.put(Data.RAW_CONTACT_ID, rawContactId);
                                        contentResolver.insert(ContactsContract.Data.CONTENT_URI, values);

                                        values.clear();
                                        values.put(Data.MIMETYPE, ContactsContract.Data.CONTENT_TYPE);
                                        values.put(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
                                                contact.getString("nombre"));
                                        values.put(Data.RAW_CONTACT_ID, rawContactId);
                                        contentResolver.insert(ContactsContract.Data.CONTENT_URI, values);

                                        values.clear();
                                        values.put(Data.MIMETYPE,
                                                ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
                                        values.put(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
                                                contact.getString("nombre"));
                                        values.put(Data.RAW_CONTACT_ID, rawContactId);
                                        contentResolver.insert(ContactsContract.Data.CONTENT_URI, values);

                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                finderDialog.getButton(DialogInterface.BUTTON_NEGATIVE)
                        .setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                finderDialog.dismiss();
                                agregar[0] = false;
                            }
                        });
            }
            c.close();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int action = event.getActionMasked();
        switch (v.getId()) {
        case R.id.record_audio:
            switch (action) {
            case MotionEvent.ACTION_DOWN:
                textRecordingPress.setVisibility(View.INVISIBLE);
                rect = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
                fechaAudioMillis = Calendar.getInstance().getTimeInMillis();
                File directory = new File(
                        Environment.getExternalStorageDirectory().getAbsolutePath() + "/SpeakOn/Audio/Sent");
                directory.mkdirs();
                ficheroAudio = Environment.getExternalStorageDirectory().getAbsolutePath() + "/SpeakOn/Audio/Sent/"
                        + fechaAudioMillis + ".mp4";
                mediaRecorder = new MediaRecorder();
                mediaRecorder.setOutputFile(ficheroAudio);
                mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
                mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
                try {
                    mediaRecorder.prepare();
                } catch (IOException e) {
                }
                mediaRecorder.start();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        finalTime += 1000;
                        int seconds = (int) (finalTime / 1000) % 60;
                        int minutes = (int) ((finalTime / (1000 * 60)) % 60);
                        int hours = (int) ((finalTime / (1000 * 60 * 60)) % 24);
                        timeFinal = String.format("%02d", minutes) + ":" + String.format("%02d", seconds);
                        timerAudio.setText(timeFinal);
                        if (!saveAudio) {
                            textRecording.setText(timeFinal);
                        }
                        handler.postDelayed(this, 1000);
                    }
                });
                scaleAnimX = ObjectAnimator.ofFloat(recordAudioButton, "scaleX", 1, 1.2f);
                scaleAnimX.setDuration(800);
                scaleAnimX.setRepeatCount(ValueAnimator.INFINITE);
                scaleAnimX.setRepeatMode(ValueAnimator.REVERSE);
                scaleAnimY = ObjectAnimator.ofFloat(recordAudioButton, "scaleY", 1, 1.2f);
                scaleAnimY.setDuration(800);
                scaleAnimY.setRepeatCount(ValueAnimator.INFINITE);
                scaleAnimY.setRepeatMode(ValueAnimator.REVERSE);
                scaleAnimY.start();
                scaleAnimX.start();

                scaleRedBackgroundX = ObjectAnimator.ofFloat(audioRecordBackground, "scaleX", 1, 100f);
                scaleRedBackgroundX.setDuration(200);
                scaleRedBackgroundY = ObjectAnimator.ofFloat(audioRecordBackground, "scaleY", 1, 100f);
                scaleRedBackgroundY.setDuration(200);
                saveAudio = true;
                break;

            case MotionEvent.ACTION_MOVE:
                if (!rect.contains(v.getLeft() + (int) event.getX(), v.getTop() + (int) event.getY())) {
                    recordAudioButton.setBackgroundResource(R.drawable.rounded_record_audio_white);
                    timerAudio.setVisibility(View.GONE);
                    textRecording.setTextColor(getResources().getColor(R.color.speak_all_red));
                    if (!animatorBackground) {
                        textRecording.setText(timeFinal);
                        if (scaleRedBackgroundX.isRunning())
                            scaleRedBackgroundX.end();
                        if (scaleRedBackgroundY.isRunning())
                            scaleRedBackgroundY.end();
                        scaleRedBackgroundY.start();
                        scaleRedBackgroundX.start();
                        animatorBackground = true;
                    }
                    saveAudio = false;
                } else {
                    recordAudioButton.setBackgroundResource(R.drawable.rounded_record_audio_red);
                    textRecording.setTextColor(getResources().getColor(R.color.speak_all_white));
                    textRecording.setText(getString(R.string.audio_record));
                    timerAudio.setVisibility(View.VISIBLE);
                    if (animatorBackground) {
                        if (scaleRedBackgroundX.isRunning())
                            scaleRedBackgroundX.end();
                        if (scaleRedBackgroundY.isRunning())
                            scaleRedBackgroundY.end();
                        ViewHelper.setScaleX(audioRecordBackground, 1);
                        ViewHelper.setScaleY(audioRecordBackground, 1);
                        animatorBackground = false;
                    }
                    saveAudio = true;
                }
                break;
            case MotionEvent.ACTION_UP:
                textRecordingPress.setVisibility(View.VISIBLE);
                animatorBackground = false;
                if (scaleAnimY.isRunning())
                    scaleAnimY.end();
                if (scaleAnimX.isRunning())
                    scaleAnimX.end();
                if (scaleRedBackgroundX.isRunning())
                    scaleRedBackgroundX.end();
                if (scaleRedBackgroundY.isRunning())
                    scaleRedBackgroundY.end();
                ViewHelper.setScaleX(audioRecordBackground, 1);
                ViewHelper.setScaleY(audioRecordBackground, 1);
                ViewHelper.setScaleX(recordAudioButton, 1);
                ViewHelper.setScaleY(recordAudioButton, 1);
                handler.removeCallbacksAndMessages(null);
                timerAudio.setText("00:00");
                timerAudio.setVisibility(View.VISIBLE);
                textRecording.setTextColor(getResources().getColor(R.color.speak_all_white));
                textRecording.setText(getString(R.string.audio_record));
                recordAudioButton.setBackgroundResource(R.drawable.rounded_record_audio_red);
                if (finalTime > 1000) {
                    mediaRecorder.stop();
                    mediaRecorder.release();
                } else {
                    saveAudio = false;
                    mediaRecorder.release();
                }
                finalTime = 0;
                timeFinal = "";
                if (saveAudio) {
                    try {
                        hideKeyBoard();
                        final Message msjAudio = new Message();
                        String id = u.id + contact.idContacto + fechaAudioMillis + Settings.Secure
                                .getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID);
                        msjAudio.mensajeId = id;
                        msjAudio.emisor = u.id;
                        msjAudio.receptor = contact.idContacto;
                        msjAudio.emisorEmail = u.email;
                        msjAudio.receptorEmail = contact.email;
                        msjAudio.emisorLang = u.lang;
                        msjAudio.receptorLang = contact.lang;
                        msjAudio.emitedAt = fechaAudioMillis;
                        msjAudio.tipo = Integer.parseInt(getString(R.string.MSG_TYPE_AUDIO));
                        if (SpeakSocket.mSocket != null)
                            if (SpeakSocket.mSocket.connected()) {
                                msjAudio.status = 1;
                            } else {
                                msjAudio.status = -1;
                            }
                        msjAudio.fileUploaded = false;
                        msjAudio.audioName = ficheroAudio;
                        msjAudio.save();
                        Chats chat = new Select().from(Chats.class).where("idContacto = ?", msjAudio.receptor)
                                .executeSingle();
                        if (chat == null) {
                            Contact contact = new Select().from(Contact.class)
                                    .where("id_contact = ?", msjAudio.receptor).executeSingle();
                            Chats newChat = new Chats();
                            newChat.mensajeId = msjAudio.mensajeId;
                            newChat.idContacto = msjAudio.receptor;
                            newChat.isLockedConversation = false;
                            newChat.lastStatus = msjAudio.status;
                            newChat.email = msjAudio.receptorEmail;
                            if (contact != null) {
                                newChat.photo = contact.photo;
                                newChat.fullName = contact.fullName;
                                newChat.lang = contact.lang;
                                newChat.screenName = contact.screenName;
                                newChat.photoload = true;
                                newChat.phone = contact.phone;
                            } else {
                                newChat.photo = null;
                                newChat.photoload = false;
                                newChat.fullName = msjAudio.receptorEmail;
                                newChat.lang = msjAudio.receptorLang;
                                newChat.screenName = msjAudio.receptorEmail;
                                newChat.phone = null;
                            }
                            newChat.emitedAt = msjAudio.emitedAt;
                            newChat.notRead = 0;
                            newChat.lastMessage = "send Audio";
                            newChat.show = true;
                            newChat.save();
                        } else {
                            if (!chat.photoload) {
                                Contact contact = new Select().from(Contact.class)
                                        .where("id_contact = ?", msjAudio.emisor).executeSingle();
                                if (contact != null) {
                                    chat.photo = contact.photo;
                                    chat.photoload = true;
                                } else {
                                    chat.photo = null;
                                    chat.photoload = false;
                                }
                            }
                            chat.mensajeId = msjAudio.mensajeId;
                            chat.lastStatus = msjAudio.status;
                            chat.emitedAt = msjAudio.emitedAt;
                            chat.notRead = 0;
                            chat.lastMessage = "send Audio";
                            chat.save();
                        }
                        showNewMessage(msjAudio);

                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                } else {
                    new File(ficheroAudio).delete();
                }
                break;
            }
            break;
        }

        return true;
    }

    final Handler handler = new Handler();

    final Handler seekHandler = new Handler();
    Runnable runAudio = new Runnable() {

        @Override
        public void run() {
            long timePlayer = mediaPlayer.getDuration() - mediaPlayer.getCurrentPosition();
            long days, hours, minutes, seconds;
            long secondsTotal = timePlayer / 1000;
            days = (Math.round(secondsTotal) / 86400);
            hours = (Math.round(secondsTotal) / 3600) - (days * 24);
            minutes = (Math.round(secondsTotal) / 60) - (days * 1440) - (hours * 60);
            seconds = Math.round(secondsTotal) % 60;
            activeAudioTime.setText(String.format("%02d", minutes) + " : " + String.format("%02d", seconds));
            activeAudioSeekBarr.setProgress(mediaPlayer.getCurrentPosition());
            seekHandler.postDelayed(this, 1000);
        }
    };

    Bitmap scaleDownLargeImageWithAspectRatio(Bitmap image, int scaleSize) {
        double imageHeight = image.getHeight();
        double imageWidth = image.getWidth();
        double newimageHeight = 0;
        double newimageWidth = 0;
        if (imageWidth > scaleSize || imageHeight > scaleSize) {
            if (imageHeight > imageWidth) {
                newimageHeight = scaleSize;
                newimageWidth = (imageWidth / imageHeight) * newimageHeight;
            } else {
                newimageWidth = scaleSize;
                newimageHeight = (imageHeight / imageWidth) * newimageWidth;
            }
        } else {
            newimageHeight = imageHeight;
            newimageWidth = imageWidth;
        }
        image = Bitmap.createScaledBitmap(image, (int) newimageWidth, (int) newimageHeight, true);
        return image;
    }

    Bitmap BlurImage(Bitmap input) {
        try {
            RenderScript rsScript = RenderScript.create(activity.getApplicationContext());
            Allocation alloc = Allocation.createFromBitmap(rsScript, input);

            ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(rsScript, Element.U8_4(rsScript));
            blur.setRadius(21);
            blur.setInput(alloc);

            Bitmap result = Bitmap.createBitmap(input.getWidth(), input.getHeight(), Bitmap.Config.ARGB_8888);
            Allocation outAlloc = Allocation.createFromBitmap(rsScript, result);

            blur.forEach(outAlloc);
            outAlloc.copyTo(result);

            rsScript.destroy();
            return result;
        } catch (Exception e) {
            // TODO: handle exception
            return input;
        }

    }

    @Override
    public void onLocationChanged(Location location) {
        muestraPosicion(location);
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    private void muestraPosicion(final Location location) {
        milocManager.removeUpdates(this);
        Geocoder geoCoder = new Geocoder(activity, Locale.getDefault());
        List<Address> addresses = null;
        StringBuilder sb = new StringBuilder();
        try {
            addresses = geoCoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
            if (addresses != null && addresses.size() > 0) {
                for (Address address : addresses) {
                    for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                        sb.append(address.getAddressLine(i)).append("\n");
                    }
                }
            }
            Log.w("UBICACION", sb.toString());
            Message msjNew = new Message();
            JSONObject locationSend = new JSONObject();
            locationSend.put("direccion", sb.toString());
            locationSend.put("latitud", location.getLatitude());
            locationSend.put("longitud", location.getLongitude());
            Calendar fecha = Calendar.getInstance();
            String id = u.id + contact.idContacto + fecha.getTimeInMillis()
                    + Settings.Secure.getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID);
            msjNew.translation = true;
            msjNew.mensajeId = id;
            msjNew.emisor = u.id;
            msjNew.receptor = contact.idContacto;
            msjNew.mensaje = locationSend.toString();
            msjNew.emisorEmail = u.email;
            msjNew.receptorEmail = contact.email;
            msjNew.emisorLang = u.lang;
            msjNew.receptorLang = contact.lang;
            msjNew.emitedAt = fecha.getTimeInMillis();
            msjNew.tipo = Integer.parseInt(getString(R.string.MSG_TYPE_LOCATION));
            msjNew.delay = 0;
            if (SpeakSocket.mSocket != null)
                if (SpeakSocket.mSocket.connected()) {
                    msjNew.status = 1;
                } else {
                    msjNew.status = -1;
                }
            msjNew.save();
            Chats chat = new Select().from(Chats.class).where("idContacto = ?", msjNew.receptor).executeSingle();
            if (chat == null) {
                Contact contact = new Select().from(Contact.class).where("id_contact = ?", msjNew.receptor)
                        .executeSingle();
                Chats newChat = new Chats();
                newChat.mensajeId = msjNew.mensajeId;
                newChat.idContacto = msjNew.receptor;
                newChat.isLockedConversation = false;
                newChat.lastStatus = msjNew.status;
                newChat.email = msjNew.receptorEmail;
                if (contact != null) {
                    newChat.photo = contact.photo;
                    newChat.fullName = contact.fullName;
                    newChat.lang = contact.lang;
                    newChat.screenName = contact.screenName;
                    newChat.photoload = true;
                    newChat.phone = contact.phone;
                } else {
                    newChat.photo = null;
                    newChat.photoload = false;
                    newChat.fullName = msjNew.receptorEmail;
                    newChat.lang = msjNew.receptorLang;
                    newChat.screenName = msjNew.receptorEmail;
                    newChat.phone = null;
                }
                newChat.emitedAt = msjNew.emitedAt;
                newChat.notRead = 0;
                newChat.lastMessage = "send Location";
                newChat.show = true;
                newChat.save();
            } else {
                if (!chat.photoload) {
                    Contact contact = new Select().from(Contact.class).where("id_contact = ?", msjNew.emisor)
                            .executeSingle();
                    if (contact != null) {
                        chat.photo = contact.photo;
                        chat.photoload = true;
                    } else {
                        chat.photo = null;
                        chat.photoload = false;
                    }
                }
                chat.mensajeId = msjNew.mensajeId;
                chat.lastStatus = msjNew.status;
                chat.emitedAt = msjNew.emitedAt;
                chat.notRead = 0;
                chat.lastMessage = "send Location";
                chat.save();
            }
            showNewMessage(msjNew);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void runTranscodingUsingLoader(String demoVideoPath, final Message menssage, final JSONObject dataSend,
            final ProgressBar progressBar, final RelativeLayout progressLayout, final TextView progressText,
            final ImageView messageContent) {
        String workFolder = activity.getApplicationContext().getFilesDir() + "/";

        int rc = GeneralUtils.isLicenseValid(activity.getApplicationContext(), workFolder);
        Log.i(Prefs.TAG, "License check RC: " + rc);
        PowerManager powerManager = (PowerManager) activity.getSystemService(Activity.POWER_SERVICE);
        PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "VK_LOCK");
        wakeLock.acquire();
        long fecha = Calendar.getInstance().getTimeInMillis();
        final String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/SpeakOn/Video/Sent/"
                + fecha + ".mp4";
        String commandStr = "ffmpeg -y -i " + demoVideoPath
                + " -strict experimental -s 640x352 -r 25 -vcodec mpeg4 -b 1500k -ab 48000 -ac 2 -ar 22050 "
                + filePath;

        vk = new LoadJNI();
        try {
            vk.run(GeneralUtils.utilConvertToComplex(commandStr), workFolder, activity.getApplicationContext());
        } catch (CommandValidationException e) {

        } catch (Throwable e) {
        } finally {
            if (wakeLock.isHeld()) {
                wakeLock.release();
                new File(demoVideoPath).delete();
                menssage.videoName = filePath;
                menssage.save();
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        uploadVideoToServer(filePath, menssage, dataSend, progressBar, progressLayout, progressText,
                                messageContent);
                    }
                });
            } else {
            }
        }
    }

    private void uploadPhotoToServer(String file, final Message menssage, final JSONObject dataSend,
            final ProgressBar progressBar, final RelativeLayout progressLayout, final TextView progressText,
            final ImageView messageContent) {
        try {
            RequestParams p = new RequestParams();
            final File archivo = new File(file);
            p.put("image", archivo);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    progressBar.setIndeterminate(false);
                    progressText.setText("0%");
                }
            });
            SpeakHttp.post("messages/" + SessionCustom.getUserId(activity) + "/upload/photo", p,
                    new JsonHttpResponseHandler() {
                        @Override
                        public void onSuccess(int statusCode, Header[] headers, final JSONObject response) {
                            super.onSuccess(statusCode, headers, response);
                            try {
                                JSONObject jsonObject = response.getJSONObject("data_response");
                                JSONArray photoArray = new JSONArray();
                                photoArray.put(0, jsonObject.getString("file_name"));
                                dataSend.put("photos", photoArray);
                                menssage.fileName = photoArray.toString();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            if (SpeakSocket.mSocket != null)
                                if (SpeakSocket.mSocket.connected()) {
                                    menssage.status = 1;
                                    SpeakSocket.mSocket.emit("message", dataSend);
                                } else {
                                    menssage.status = -1;
                                }
                            menssage.fileUploaded = true;
                            menssage.save();
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (menssage.photo != null) {
                                        Bitmap bmp = BitmapFactory.decodeByteArray(menssage.photo, 0,
                                                menssage.photo.length);
                                        messageContent.setImageBitmap(bmp);
                                        progressLayout.setVisibility(View.GONE);
                                        System.gc();
                                    }
                                }
                            });
                        }

                        @Override
                        public void onProgress(final long bytesWritten, final long totalSize) {
                            if (bytesWritten != totalSize) {
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        double prog = (100 / (double) totalSize) * (double) bytesWritten;
                                        progressBar.setProgress((int) Math.round(prog));
                                        progressText.setText((int) Math.round(prog) + "%");
                                        Log.e("PROGRESO", (int) Math.round(prog) + "");
                                    }
                                });
                            }
                        }

                        @Override
                        public void onFinish() {
                            System.gc();
                        }
                    }, activity);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void uploadVideoToServer(String file, final Message menssage, final JSONObject dataSend,
            final ProgressBar progressBar, final RelativeLayout progressLayout, final TextView progressText,
            final ImageView messageContent) {

        try {
            RequestParams p = new RequestParams();
            final File archivo = new File(file);
            p.put("video", archivo);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    progressBar.setIndeterminate(false);
                    progressText.setText("0%");
                }
            });

            SpeakHttp.client.setTimeout(70000);
            SpeakHttp.client.setResponseTimeout(70000);
            SpeakHttp.post("messages/" + SessionCustom.getUserId(activity) + "/upload/video", p,
                    new JsonHttpResponseHandler() {
                        @Override
                        public void onSuccess(int statusCode, Header[] headers, final JSONObject response) {
                            super.onSuccess(statusCode, headers, response);
                            try {
                                JSONObject jsonObject = response.getJSONObject("data_response");
                                JSONArray photoArray = new JSONArray();
                                photoArray.put(0, jsonObject.getString("file_name"));
                                dataSend.put("videos", photoArray);
                                menssage.fileName = photoArray.toString();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            if (SpeakSocket.mSocket != null)
                                if (SpeakSocket.mSocket.connected()) {
                                    menssage.status = 1;
                                    SpeakSocket.mSocket.emit("message", dataSend);
                                } else {
                                    menssage.status = -1;
                                }
                            menssage.fileUploaded = true;
                            menssage.save();
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (menssage.photo != null) {
                                        Bitmap bmp = BitmapFactory.decodeByteArray(menssage.photo, 0,
                                                menssage.photo.length);
                                        messageContent.setImageBitmap(bmp);
                                        progressLayout.setVisibility(View.GONE);
                                        System.gc();
                                    }
                                }
                            });

                        }

                        @Override
                        public void onProgress(final long bytesWritten, final long totalSize) {
                            if (bytesWritten != totalSize) {
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        double prog = (100 / (double) totalSize) * (double) bytesWritten;
                                        progressBar.setProgress((int) Math.round(prog));
                                        progressText.setText((int) Math.round(prog) + "%");
                                        Log.e("PROGRESO", (int) Math.round(prog) + "");
                                    }
                                });
                            }
                        }

                        @Override
                        public void onFinish() {
                            System.gc();
                        }
                    }, activity);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void onDestroy() {
        super.onDestroy();
        ((MainActivity) activity).dontClose = false;
        dontClose = false;
        System.gc();
    }

    private void uploadAudioToServer(String file, final Message menssage, final JSONObject dataSend,
            final ProgressBar progressBar, final RelativeLayout progressLayout, final TextView progressText) {
        try {
            RequestParams p = new RequestParams();
            File archivo = new File(file);
            p.put("audio", archivo);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    progressText.setText("0%");
                }
            });

            SpeakHttp.post("messages/" + SessionCustom.getUserId(activity) + "/upload/audio", p,
                    new JsonHttpResponseHandler() {
                        @Override
                        public void onSuccess(int statusCode, Header[] headers, final JSONObject response) {
                            super.onSuccess(statusCode, headers, response);
                            try {
                                final JSONObject dataResponse = response.getJSONObject("data_response");
                                Log.e("Respuesta", dataResponse.toString());
                                JSONArray photoArray = new JSONArray();
                                photoArray.put(0, dataResponse.getString("file_name"));
                                dataSend.put("audios", photoArray);
                                menssage.fileName = photoArray.toString();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            if (SpeakSocket.mSocket != null)
                                if (SpeakSocket.mSocket.connected()) {
                                    menssage.status = 1;
                                    SpeakSocket.mSocket.emit("message", dataSend);
                                } else {
                                    menssage.status = -1;
                                }
                            menssage.fileUploaded = true;
                            menssage.save();
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    progressLayout.setVisibility(View.GONE);
                                    System.gc();
                                }
                            });
                        }

                        @Override
                        public void onProgress(final long bytesWritten, final long totalSize) {
                            if (bytesWritten != totalSize) {
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        double prog = (100 / (double) totalSize) * (double) bytesWritten;
                                        progressBar.setProgress((int) Math.round(prog));
                                        progressText.setText((int) Math.round(prog) + "%");
                                        Log.e("PROGRESO", (int) Math.round(prog) + "");
                                    }
                                });
                            }
                        }

                        @Override
                        public void onFinish() {
                            System.gc();
                        }
                    }, activity);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

}