com.guardtrax.ui.screens.HomeScreen.java Source code

Java tutorial

Introduction

Here is the source code for com.guardtrax.ui.screens.HomeScreen.java

Source

/**
'*********************************************************************************************************************
'* Project Name             : GuardTrax
'* File Name                : HomeScreen.java
'* Description              : HomeScreen Activity of Application
'* Package Name             : com.guardtrax.ui.screens
'* Version Number           : 1.0
'* Original Author          : Prasanna Vignesh R
'* Start Date               : 10 August 2011
'* Last Modified Date       : 21 September 2011
'* Modified By              : Hall B
'* GuardTrax, 2011, Confidential and proprietary.
'**********************************************************************************************************************
 */
package com.guardtrax.ui.screens;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.http.util.ByteArrayBuffer;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Looper;
import android.os.SystemClock;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.guardtrax.R;
import com.guardtrax.bgservices.MainService;
import com.guardtrax.db.GTParams;
import com.guardtrax.db.GuardTraxDB;
import com.guardtrax.db.PreferenceDB;
import com.guardtrax.db.accountsDB;
import com.guardtrax.db.ftpDataBase;
import com.guardtrax.db.tourDataBase;
import com.guardtrax.db.trafficDataBase;
import com.guardtrax.util.GTConstants;
import com.guardtrax.util.Utility;

public class HomeScreen extends Activity {

    //boolean test = false;
    private long mLastClickTime = 0;

    //Variable Declaration
    static String CRLF = "\r\n";
    static TextView textWarning;
    TextView textuserName;
    static boolean debug = false;
    Spinner spinner;
    Spinner report_spinner;
    public static Context ctx;
    String eventCode = "";
    String selectedCode;
    static String incidentDescription = "";
    boolean chekUpdate = true;

    //time and attendance parameters
    static String lunchTime = "00:00:00:00";
    static String breakTime = "00:00:00:00";
    static int lunchoutLocation;
    static int breakoutLocation;
    String signaturefileName = "";

    static boolean new_document = false;
    boolean firstUpdateCheck = true;
    boolean start_shift_wait = true;
    String show_alert_title = "";
    String show_alert_message = "";
    boolean incidentcodeSent = false;
    Dialog pdialog;
    boolean trafficIncident = false;
    static short taa = 0; //keeps track of what to do when returning to HomeScreen during time and attendance (see code in OnResume)
    static boolean newRegistration = false;
    boolean restartsyncTimer = false;
    static String lasttagScanned = "";

    //A button with two states, checked and unchecked.
    Button btn_send;
    Button btn_sendreport;
    Button btn_navigate_left;
    Date date;
    long id;
    int serverPort;
    String currentDate;

    //A concrete class for formatting and parsing dates in a locale-sensitive manner.
    SimpleDateFormat dateFormat;
    Cursor cursor;
    LayoutInflater inflater;
    PreferenceDB preferenceDB;
    GuardTraxDB myDatabase;
    ftpDataBase ftpdatabase;
    GTParams gtDB;
    accountsDB aDB;
    static trafficDataBase trafficDB;
    static tourDataBase tourDB;

    final Animation animation = new AlphaAnimation(1, 0);
    final Animation buttonClick = new AlphaAnimation(1, 0);

    //Mic, camera and video buttons
    Button btn_mic;
    Button btn_camera;
    Button btn_video;

    //tab buttons
    Button btn_report_screen;
    Button btn_scan_screen;
    Button btn_dial_screen;

    //swipe variables
    //static float x1 = 0,x2 = 0;

    private static final int CAMERA_PIC_REQUEST = 1337;
    private static final int ACTION_TAKE_VIDEO = 100;
    private static final int REQUEST_CODE_RECORD = 110;
    private static final int ACTIVITY_SELECT_IMAGE = 120;
    private static final int ACTIVITY_SELECT_VIDEO = 130;

    public static Uri Uri_image;

    //the name of the most recent audio, picture or video file
    public String file_name = "";

    Download_FTP ftpDownload = null;
    Intent cameraIntent = null;
    Intent galleryIntent = null;

    //tour parameters
    static int touritemNumber = -1;
    static String tourTime = "";
    static Long tourEnd = (long) 0;
    //static List<Boolean> tourtagsScanned = new ArrayList<Boolean>();

    static SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yy HH:mm:ss");

    //called when first activity starts
    public void onCreate(Bundle savedInstanceState) {
        ctx = this.getApplicationContext();

        super.onCreate(savedInstanceState);

        //restore saved instances if necessary
        if (savedInstanceState != null) {
            Toast.makeText(HomeScreen.this, savedInstanceState.getString("message"), Toast.LENGTH_LONG).show();

            GTConstants.darfileName = savedInstanceState.getString("darfileName");
            GTConstants.tarfileName = savedInstanceState.getString("tarfileName");
            GTConstants.trpfilename = savedInstanceState.getString("trpfilename");
            GTConstants.srpfileName = savedInstanceState.getString("srpfileName");
            Utility.setcurrentState(savedInstanceState.getString("currentState"));
            Utility.setsessionStart(savedInstanceState.getString("getsessionStart"));
            selectedCode = savedInstanceState.getString("selectedCode");
            lunchTime = savedInstanceState.getString("lunchTime");
            breakTime = savedInstanceState.getString("breakTime");
            signaturefileName = savedInstanceState.getString("signaturefileName");
            GTConstants.tourName = savedInstanceState.getString("tourName");
            tourTime = savedInstanceState.getString("tourTime");
            tourEnd = savedInstanceState.getLong("tourEnd");
            lunchoutLocation = savedInstanceState.getInt("lunchoutLocation");
            breakoutLocation = savedInstanceState.getInt("breakoutLocation");
            touritemNumber = savedInstanceState.getInt("touritemNumber");
            chekUpdate = savedInstanceState.getBoolean("chekUpdate");
            GTConstants.sendData = savedInstanceState.getBoolean("send_data");
            GTConstants.isTour = savedInstanceState.getBoolean("isTour");
            GTConstants.isGeoFence = savedInstanceState.getBoolean("isGeoFence");
        } else {
            //set the current state
            Utility.setcurrentState(GTConstants.offShift);

            //set the default startup code to start shift
            selectedCode = "start_shift";
        }

        /*
        //Determine screen size
         if ((getResources().getConfiguration().screenLayout &      Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) {     
             Toast.makeText(this, "Large screen",Toast.LENGTH_LONG).show();
         }
         else if ((getResources().getConfiguration().screenLayout &      Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {     
             Toast.makeText(this, "Normal sized screen" , Toast.LENGTH_LONG).show();
         } 
         else if ((getResources().getConfiguration().screenLayout &      Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_SMALL) {     
             Toast.makeText(this, "Small sized screen" , Toast.LENGTH_LONG).show();
         }
         else {
             Toast.makeText(this, "Screen size is neither large, normal or small" , Toast.LENGTH_LONG).show();
         }
             
          //initialize receiver to monitor for screen on / off
        /*
          IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
          filter.addAction(Intent.ACTION_SCREEN_OFF);
          BroadcastReceiver mReceiver = new ScreenReceiver();
          registerReceiver(mReceiver, filter);
          */

        setContentView(R.layout.homescreen);

        //Create object to call the Database class
        myDatabase = new GuardTraxDB(this);
        preferenceDB = new PreferenceDB(this);
        ftpdatabase = new ftpDataBase(this);
        gtDB = new GTParams(this);
        aDB = new accountsDB(this);
        trafficDB = new trafficDataBase(this);
        tourDB = new tourDataBase(this);

        //check for updates
        if (chekUpdate) {
            //reset the preference value
            chekUpdate = false;

            //check for application updates
            checkUpdate();
        }

        //initialize the message timer
        //initializeOnModeTimerEvent();

        //get the version number and set it in constants
        String version_num = "";

        PackageManager manager = this.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            version_num = info.versionName.toString();

        } catch (NameNotFoundException e) {
            version_num = "0.00.00";
        }
        GTConstants.version = version_num;

        //final TextView version = (TextView) findViewById(R.id.textVersion);
        //version.setText(version_num);

        //set up the animation
        animation.setDuration(500); // duration - half a second
        animation.setInterpolator(new LinearInterpolator()); // do not alter animation rate
        animation.setRepeatCount(Animation.INFINITE); // Repeat animation infinitely
        animation.setRepeatMode(Animation.REVERSE); // Reverse animation at the end so the button will fade back in

        buttonClick.setDuration(50); // duration - half a second
        buttonClick.setInterpolator(new LinearInterpolator()); // do not alter animation rate
        buttonClick.setRepeatCount(1); // Repeat animation once
        buttonClick.setRepeatMode(Animation.REVERSE); // Reverse animation at the end so the button will fade back in

        textWarning = (TextView) findViewById(R.id.txtWarning);
        textWarning.setWidth(500);
        textWarning.setGravity(Gravity.CENTER);

        //allow the text to be clicked if necessary 
        textWarning.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (GTConstants.isTour && GTConstants.tourName.length() > 1)
                    displaytourInfo();
            }
        });

        //goto scan page button
        btn_scan_screen = (Button) findViewById(R.id.btn_goto_scan);

        btn_scan_screen.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                btn_scan_screen.startAnimation(buttonClick);

                //Utility.showScan(HomeScreen.this);
                scan_click(false);
            }
        });

        //goto report page button
        btn_report_screen = (Button) findViewById(R.id.btn_goto_report);
        btn_report_screen.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                btn_report_screen.startAnimation(buttonClick);

                report_click();
            }
        });

        //goto dial page button
        btn_dial_screen = (Button) findViewById(R.id.btn_goto_dial);
        btn_dial_screen.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                btn_dial_screen.startAnimation(buttonClick);

                dial_click();
            }
        });

        //microphone button
        btn_mic = (Button) findViewById(R.id.btn_mic);
        btn_mic.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                btn_mic.startAnimation(buttonClick);

                voice_click();
            }

        });

        //camera button
        btn_camera = (Button) findViewById(R.id.btn_camera);
        btn_camera.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                btn_camera.startAnimation(buttonClick);

                camera_click();
            }
        });

        //video button
        btn_video = (Button) findViewById(R.id.btn_video);
        btn_video.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                btn_video.startAnimation(buttonClick);

                video_click();
            }

        });

        // Register a callback to be invoked when this view is clicked. If this view is not clickable, it becomes clickable.
        btn_send = (Button) findViewById(R.id.btn_Send);
        btn_send.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //prevent multiple fast clicking
                if (SystemClock.elapsedRealtime() - mLastClickTime < 2000)
                    return;

                mLastClickTime = SystemClock.elapsedRealtime();

                incidentcodeSent = true;

                btn_send.startAnimation(buttonClick);

                //if start shift has not been sent then the device is in do not send data mode.  Warn the user 
                if (Utility.getcurrentState().equals(GTConstants.offShift) && !selectedCode.equals("start_shift")) {
                    show_alert_title = "Error";
                    show_alert_message = "You must start your shift!";
                    showAlert(show_alert_title, show_alert_message, true);

                    //set spinner back to start shift
                    spinner.setSelection(0);
                } else {
                    if (Utility.deviceRegistered()) {
                        show_alert_title = "Success";
                        show_alert_message = "Action success";
                    } else {
                        show_alert_title = "Warning";
                        show_alert_message = "You are NOT registered!";

                        showAlert(show_alert_title, show_alert_message, true);
                    }

                    if (selectedCode.equals("start_shift")) {
                        //if shift already started
                        if (Utility.getcurrentState().equals(GTConstants.onShift)) {
                            show_alert_title = "Warning";
                            show_alert_message = "You must end shift!";

                            showAlert(show_alert_title, show_alert_message, true);

                            //set spinner back to all clear
                            spinner.setSelection(2);
                        } else {
                            ToastMessage.displayToastFromResource(HomeScreen.this, 5, Gravity.CENTER,
                                    (ViewGroup) findViewById(R.id.toast_layout_root));

                            pdialog = ProgressDialog.show(HomeScreen.this, "Please wait", "Starting shift ...",
                                    true);

                            //set the current state
                            Utility.setcurrentState(GTConstants.onShift);
                            setuserBanner();

                            //wait for start shift actions to complete (or timeout occurs) before dismissing wait dialog
                            new CountDownTimer(5000, 1000) {
                                @Override
                                public void onTick(long millisUntilFinished) {
                                    if (start_shift_wait)
                                        pdialog.dismiss();
                                }

                                @Override
                                public void onFinish() {
                                    if (!(pdialog == null))
                                        pdialog.dismiss();
                                }
                            }.start();

                            //create dar file
                            try {
                                //create the dar file name
                                GTConstants.darfileName = GTConstants.LICENSE_ID.substring(7) + "_"
                                        + Utility.getUTCDate() + "_" + Utility.getUTCTime() + ".dar";

                                //write the version to the dar file
                                Utility.write_to_file(HomeScreen.this,
                                        GTConstants.dardestinationFolder + GTConstants.darfileName,
                                        "Version;" + GTConstants.version + "\r\n", false);

                                //write the start shift event to the dar file
                                Utility.write_to_file(HomeScreen.this,
                                        GTConstants.dardestinationFolder + GTConstants.darfileName,
                                        "Start shift;" + GTConstants.currentBatteryPercent + ";"
                                                + Utility.getLocalTime() + ";" + Utility.getLocalDate() + "\r\n",
                                        true);

                                //create the tar file name if module installed
                                if (GTConstants.isTimeandAttendance) {
                                    GTConstants.tarfileName = GTConstants.LICENSE_ID.substring(7) + "_"
                                            + Utility.getUTCDate() + "_" + Utility.getUTCTime() + ".tar";

                                    //write the start shift event to the tar file
                                    Utility.write_to_file(HomeScreen.this,
                                            GTConstants.dardestinationFolder + GTConstants.tarfileName,
                                            "Name;" + GTConstants.report_name + "\r\n" + "Start shift;"
                                                    + Utility.getLocalTime() + ";" + Utility.getLocalDate()
                                                    + "\r\n",
                                            false);
                                }

                            } catch (Exception e) {
                                Toast.makeText(HomeScreen.this, "error = " + e, Toast.LENGTH_LONG).show();
                            }

                            GTConstants.sendData = true;

                            //if not time and attendance then send start shift event now, otherwise wait till after location scan
                            send_event("11");

                            //set the session start time
                            SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yy HH:mm:ss");
                            Utility.setsessionStart(sdf.format(new Date()));

                            //reset the server connection flag
                            Utility.resetisConnecting();

                            //start the GPS location service
                            MainService.openLocationListener();

                            //set spinner back to all clear
                            spinner.setSelection(2);

                            setwarningText("");

                            if (GTConstants.isTimeandAttendance) {
                                show_taa_scan(true, false);
                            }
                        }

                    } else if (selectedCode.equals("end_shift")) {
                        if (!Utility.getcurrentState().equals(GTConstants.onShift)
                                && GTConstants.isTimeandAttendance) {
                            show_alert_title = "Error";
                            show_alert_message = "You must end your Lunch / Break!";
                            showAlert(show_alert_title, show_alert_message, true);

                            //set spinner back to start shift
                            spinner.setSelection(2);
                        } else {
                            btn_send.setEnabled(false);
                            if (GTConstants.isTimeandAttendance) {
                                show_taa_scan(false, true);
                            } else
                                endshiftCode();
                        }
                    } else {
                        if (Utility.isselectionValid(HomeScreen.this, selectedCode)) {
                            //if time and attendance then write to file
                            if (selectedCode.equalsIgnoreCase(GTConstants.lunchin)
                                    || selectedCode.equalsIgnoreCase(GTConstants.lunchout)
                                    || selectedCode.equalsIgnoreCase(GTConstants.startbreak)
                                    || selectedCode.equalsIgnoreCase(GTConstants.endbreak)) {
                                if (GTConstants.isTimeandAttendance)
                                    Utility.write_to_file(HomeScreen.this,
                                            GTConstants.dardestinationFolder + GTConstants.tarfileName,
                                            spinner.getSelectedItem().toString() + ";" + Utility.getLocalTime()
                                                    + ";" + Utility.getLocalDate() + "\r\n",
                                            true);

                                if (selectedCode.equalsIgnoreCase(GTConstants.lunchin)) {
                                    Utility.setcurrentState(GTConstants.onLunch);
                                    Utility.setlunchStart(true);
                                    setuserBanner();
                                }

                                if (selectedCode.equalsIgnoreCase(GTConstants.startbreak)) {
                                    Utility.setcurrentState(GTConstants.onBreak);
                                    Utility.setbreakStart(true);
                                    setuserBanner();
                                }

                                if (selectedCode.equalsIgnoreCase(GTConstants.lunchout)) {
                                    Utility.setcurrentState(GTConstants.onShift);
                                    lunchTime = Utility.gettimeDiff(Utility.getlunchStart(),
                                            Utility.getLocalDateTime());
                                    setuserBanner();
                                }

                                if (selectedCode.equalsIgnoreCase(GTConstants.endbreak)) {
                                    Utility.setcurrentState(GTConstants.onShift);
                                    breakTime = Utility.gettimeDiff(Utility.getbreakStart(),
                                            Utility.getLocalDateTime());
                                    setuserBanner();
                                }
                            }

                            ToastMessage.displayToastFromResource(HomeScreen.this, 5, Gravity.CENTER,
                                    (ViewGroup) findViewById(R.id.toast_layout_root));

                            //save the event description as may be needed for incident report
                            incidentDescription = spinner.getSelectedItem().toString();

                            //write to dar
                            Utility.write_to_file(HomeScreen.this,
                                    GTConstants.dardestinationFolder + GTConstants.darfileName,
                                    "Event; " + incidentDescription + ";" + Utility.getLocalTime() + ";"
                                            + Utility.getLocalDate() + "\r\n",
                                    true);

                            //write to srp
                            if (GTConstants.srpfileName.length() > 1)
                                Utility.write_to_file(HomeScreen.this,
                                        GTConstants.dardestinationFolder + GTConstants.srpfileName,
                                        "Event; " + incidentDescription + ";" + Utility.getLocalTime() + ";"
                                                + Utility.getLocalDate() + "\r\n",
                                        true);

                            //send the data
                            send_event(selectedCode);

                            //ask if user wants to create an incident report.  If the last character is a space, that indicates not to ask for report
                            if (!(incidentDescription.charAt(incidentDescription.length() - 1) == ' ')
                                    && !trafficIncident)
                                showYesNoAlert("Report", "Create an Incident Report?", incidentreportScreen);
                            if (!(incidentDescription.charAt(incidentDescription.length() - 1) == ' ')
                                    && trafficIncident)
                                showYesNoAlert("Report", "Create a Traffic Violation?", incidentreportScreen);

                            //if last two characters are spaces then ask to write a note
                            if (incidentDescription.charAt(incidentDescription.length() - 1) == ' '
                                    && incidentDescription.charAt(incidentDescription.length() - 2) == ' ')
                                showYesNoAlert("Report", "Create a Note?", createNote);

                        }

                        //set spinner back to required state
                        if (selectedCode.equalsIgnoreCase(GTConstants.lunchin))
                            spinner.setSelection(lunchoutLocation);
                        else if (selectedCode.equalsIgnoreCase(GTConstants.startbreak))
                            spinner.setSelection(breakoutLocation);
                        else
                            spinner.setSelection(2);

                    }
                }
            }

        });

        //Finds a view that was identified by the id attribute from the XML that was processed in onCreate(Bundle).
        spinner = (Spinner) findViewById(R.id.spinner_list);

        //method initialize the spinner action
        initializeSpinnerControl();

        if (GTConstants.service_intent == null) {
            //Condition to check whether the Database exist and if so load data into constants
            try {
                if (preferenceDB.checkDataBase()) {
                    preferenceDB.open();

                    Cursor cursor = preferenceDB.getRecordByRowID("1");

                    preferenceDB.close();

                    if (cursor == null)
                        loadPreferenceDataBase();
                    else {
                        saveInConstants(cursor);
                        cursor.close();
                    }
                    syncDB();
                    syncFTP();
                    syncftpUpload();
                } else {
                    preferenceDB.open();
                    preferenceDB.close();
                    //Toast.makeText(HomeScreen.this, "Path = " + preferenceDB.get_path(), Toast.LENGTH_LONG).show();
                    //Toast.makeText(HomeScreen.this, "No database found", Toast.LENGTH_LONG).show();

                    loadPreferenceDataBase();

                    syncDB();
                    syncFTP();
                    syncftpUpload();
                }
            } catch (Exception e) {
                preferenceDB.createDataBase();
                loadPreferenceDataBase();
                Toast.makeText(HomeScreen.this, "Creating database", Toast.LENGTH_LONG).show();
            }

            //setup the auxiliary databases
            if (!aDB.checkDataBase()) {
                aDB.open();
                aDB.close();
            }

            if (!ftpdatabase.checkDataBase()) {
                ftpdatabase.open();
                ftpdatabase.close();
            }

            if (!gtDB.checkDataBase()) {
                gtDB.open();
                gtDB.close();
            }

            if (!trafficDB.checkDataBase()) {
                trafficDB.open();
                trafficDB.close();
            }

            if (!tourDB.checkDataBase()) {
                tourDB.open();
                tourDB.close();
            }

            //get the parameters from the parameter database
            loadGTParams();

            //this code starts the main service running which contains all the event timers
            if (Utility.deviceRegistered()) {
                //this is the application started event - sent once when application starts up
                if (savedInstanceState == null)
                    send_event("PU");

                initService();
            }
        }

        //if device not registered than go straight to scan screen
        if (!Utility.deviceRegistered()) {
            newRegistration = true;
            //send_data = true;
            scan_click(false);
        }

        //setup the user banner
        setuserBanner();

        //set the warning text
        setwarningText("");

    }

    //trap the back button
    @Override
    public void onBackPressed() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);

        if (GTConstants.sendData) {
            dialog.setTitle("Warning");
            dialog.setMessage("You must end shift before exit!");
            dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    return;
                }
            });
            dialog.show();
        } else {
            dialog.setTitle("Exit?");
            dialog.setMessage("Are you sure you want to exit?");
            dialog.setNegativeButton(android.R.string.no, null);
            dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();

                    // Create a Dialog to let the User know that we're waiting for a GPS Fix
                    pdialog = ProgressDialog.show(HomeScreen.this, "Please wait", "Exiting GT Android ...", true);

                    Runnable showWaitDialog = new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Looper.prepare();
                                MainService.closeLocationListener(); //close out GPS

                                //only send 92 if online
                                if (Utility.isOnline(HomeScreen.this)) {
                                    GTConstants.sendData = true; //allow the exit event to be sent
                                    send_event("92"); //send the event
                                    Utility.Sleep(4000); //give time for the event to be sent before exiting
                                }

                                stopService();

                                Utility.Sleep(1000);
                                pdialog.dismiss();
                                Utility.Sleep(1000);

                                //terminating the running threads and finishing program must be run on the main thread
                                HomeScreen.this.runOnUiThread(new Runnable() {
                                    public void run() {
                                        if (pdialog.isShowing())
                                            pdialog.dismiss();
                                        HomeScreen.super.onBackPressed();
                                        android.os.Process.killProcess(android.os.Process.myPid());
                                        finish();
                                    }
                                });
                            } catch (Exception e) {

                                //terminating the running threads and finishing program must be run on the main thread
                                HomeScreen.this.runOnUiThread(new Runnable() {
                                    public void run() {
                                        if (pdialog.isShowing())
                                            pdialog.dismiss();
                                        HomeScreen.super.onBackPressed();
                                        android.os.Process.killProcess(android.os.Process.myPid());
                                        finish();
                                    }
                                });

                            }
                        }
                    };

                    Thread t = new Thread(showWaitDialog);
                    t.start();
                }
            });

            dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (!Utility.deviceRegistered()) {
                        //send_data = true;
                        scan_click(false);
                    }
                }
            });

            dialog.show();
        }
    }

    @Override
    public void onResume() {
        //if exiting from the scan screen with an unregistered app
        if (GTConstants.exitingScanScreen && !Utility.deviceRegistered())
            onBackPressed();

        //if this is a newly registered app then reboot
        if (newRegistration && Utility.deviceRegistered()) {
            try {
                Intent restartIntent = getPackageManager().getLaunchIntentForPackage(getPackageName());
                PendingIntent intent = PendingIntent.getActivity(HomeScreen.this, 0, restartIntent,
                        Intent.FLAG_ACTIVITY_CLEAR_TOP);
                AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                manager.set(AlarmManager.RTC, System.currentTimeMillis() + 500, intent);
                System.exit(2);
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), "ON RESUME ERROR: " + e, Toast.LENGTH_LONG).show();
            }
        } else {
            if (!ScreenReceiver.wasScreenOn) {
                //Toast.makeText(getApplicationContext(), "ON RESUME", Toast.LENGTH_LONG).show();
                //if(ftpDownload.getStatus() != AsyncTask.Status.RUNNING)syncFTP();
                //syncFTP();
            }

            syncFTP();

            setuserBanner();

            //if returning from tag scan for time and attendance after an end shift then taa was set to 1
            //set taa to 2 and then launch dialog to display the time and attendance record and then signature page
            if (taa == 1) {
                taa = 0;
            }

            if (taa == 2) {
                //write to tar, transfer file to send directory
                Utility.write_to_file(HomeScreen.this, GTConstants.dardestinationFolder + GTConstants.tarfileName,
                        "End shift;" + Utility.getLocalTime() + ";" + Utility.getLocalDate() + "\r\n", true);

                //write additional info to tar file
                Utility.write_to_file(HomeScreen.this, GTConstants.dardestinationFolder + GTConstants.tarfileName,
                        "Total Time;" + Utility.gettimeDiff(Utility.getsessionStart(), Utility.getLocalDateTime())
                                + "\r\n" + "Time on Lunch;" + lunchTime + "\r\n" + "Time on Break;" + breakTime
                                + "\r\n",
                        true);

                //give time for file write
                Utility.initializeGeneralTimer(2000);
                do {
                    Utility.Sleep(100);
                } while (!Utility.fileAccessComplete() && !Utility.getgeneraltimerFlag());

                lunchTime = "00:00:00:00";
                breakTime = "00:00:00:00";

                taa = 5;
                show_taaSignature_dialog(); //returning from end shift location scan
            }

            if (taa == 3) {
                //write the event 25 information to the file
                String GM = "";
                if (GTConstants.isSignature) {
                    GM = Utility.getHeaderMessage("$GM") + ",25," + getCellID() + CRLF + "***SIGNATURE***" + CRLF
                            + Utility.getsharedPreference(HomeScreen.this, "signaturefileName");
                    GTConstants.isSignature = false;
                    signaturefileName = "";
                } else
                    GM = Utility.getHeaderMessage("$GM") + ",25," + getCellID();

                Utility.write_to_file(HomeScreen.this, GTConstants.dardestinationFolder + GTConstants.tarfileName,
                        GM + "\r\n", true);

                //give time for file write
                Utility.initializeGeneralTimer(2000);
                do {
                    Utility.Sleep(100);
                } while (!Utility.fileAccessComplete() && !Utility.getgeneraltimerFlag());

                //move the tar file to the send file folder 
                File from = new File(GTConstants.dardestinationFolder, GTConstants.tarfileName);

                //change the file name to match the $GM time and date
                String[] parse = GM.split(",");
                String newFile = GTConstants.LICENSE_ID.substring(7) + "_" + parse[10] + "_" + parse[2]
                        + "_tar.tar";

                File to = new File(GTConstants.sendfileFolder, newFile);
                from.renameTo(to);

                endshiftCode();

                taa = 0;
            }

            //check if the tag is in a tour
            if (GTConstants.exitingScanScreen) {
                if (GTConstants.isTour) {
                    if (GTConstants.tourName.length() == 1) {
                        if (getlasttagScanned().length() == 16)
                            show_tours_dialog(true);
                    } else {
                        updateTour(getlasttagScanned());
                    }
                }

                //check if this is an account setup tag, designated by an "@&" as the first two characters
                if (getlasttagScanned().length() == 16) {
                    String temp = Utility.get_from_GTParamsDataBase(HomeScreen.this, getlasttagScanned());
                    if (temp.contains("@&")) {
                        temp = temp.substring(2);
                        setupAccounts("0", temp);
                        //Toast.makeText(getApplicationContext(), temp, Toast.LENGTH_LONG).show();
                    }
                }

                GTConstants.exitingScanScreen = false;
            }

        }

        super.onResume();
    }

    @Override
    public void onPause() {
        if (ScreenReceiver.wasScreenOn) {
            //Toast.makeText(getApplicationContext(), "ON PAUSE", Toast.LENGTH_LONG).show();
        }

        super.onPause();
        //setVisible(true);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putString("message", "Restoring GuardTrax");
        outState.putString("darfileName", GTConstants.darfileName);
        outState.putString("tarfileName", GTConstants.tarfileName);
        outState.putString("trpfilename", GTConstants.trpfilename);
        outState.putString("srpfileName", GTConstants.srpfileName);
        outState.putString("currentState", Utility.getcurrentState());
        outState.putString("getsessionStart", Utility.getsessionStart());
        outState.putString("selectedCode", selectedCode);
        outState.putString("lunchTime", lunchTime);
        outState.putString("breakTime", breakTime);
        outState.putString("signaturefileName", signaturefileName);
        outState.putString("tourName", GTConstants.tourName);
        outState.putString("tourTime", tourTime);
        outState.putLong("tourEnd", tourEnd);
        outState.putInt("lunchoutLocation", lunchoutLocation);
        outState.putInt("breakoutLocation", breakoutLocation);
        outState.putInt("touritemNumber", touritemNumber);
        outState.putBoolean("chekUpdate", chekUpdate);
        outState.putBoolean("send_data", GTConstants.sendData);
        outState.putBoolean("isTour", GTConstants.isTour);
        outState.putBoolean("isGeoFence", GTConstants.isGeoFence);

        //Save data for main service
        String value = String.valueOf(GTConstants.sendData) + "," + GTConstants.darfileName + ","
                + GTConstants.tarfileName + "," + GTConstants.trpfilename + "," + GTConstants.srpfileName + ","
                + GTConstants.tourName;
        Utility.storesharedPreference(HomeScreen.this, "serviceString", value);

        // Save away the original text, so we still have it if the activity
        // needs to be killed while paused.
        //outState.putString("my_text", sMyText);
        //outState.putInt("my_int", nMyInt);
        //Toast.makeText(this, "onSaveInstanceState()", Toast.LENGTH_LONG).show();
    }

    /*
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) 
    {
        super.onRestoreInstanceState(savedInstanceState);
        // restore saved values
        //sNewMyText = savedInstanceState.getString("my_text");
        //nNewMyInt = savedInstanceState.getInt("my_int");
        //Toast.makeText(this, "onRestoreInstanceState()", Toast.LENGTH_LONG).show();
    }
    */

    @Override
    public void onDestroy() {

    }

    //this sets the warning text
    private static void setwarningText(String display) {

        String warningString = "";

        //add start shift warning
        if (Utility.getcurrentState().equals(GTConstants.offShift))
            warningString = "Warning: Start Shift!" + CRLF;

        //add account info if accounts module activated and account selected
        if (GTConstants.accountName.length() > 1)
            warningString = warningString + "Account: " + GTConstants.accountName + CRLF;

        //add tour info if tour module activated and tour is selected
        if (GTConstants.isTour && GTConstants.tourName.length() > 1)
            warningString = warningString + GTConstants.tourName + CRLF;

        //add any additional custom display
        warningString = warningString + display;

        textWarning.setText(warningString);
        textWarning.setVisibility(View.VISIBLE);

        /*
        if(_case == 1) //standard warning
        {
           //tour length = 1 indicates no tour has been selected
           if(GTConstants.isTour && GTConstants.tourName.length() == 1)
              textWarning.setText("Warning: Start Shift!" + CRLF + "No tour selected");
           else if(GTConstants.isTour && GTConstants.tourName.length() > 1 && !GTConstants.sendData)
              textWarning.setText("Warning: Start Shift!" + CRLF + GTConstants.tourName);
           else if(GTConstants.isTour && GTConstants.tourName.length() > 1 && GTConstants.sendData)
              textWarning.setText(GTConstants.tourName);
           else
              textWarning.setText("Warning: Start Shift!");
           textWarning.setVisibility(View.VISIBLE);
        }
            
        if(_case == 2) //start shift
        {
           textWarning.setVisibility(View.VISIBLE);
           if(GTConstants.accountName.length() > 1)                  
              textWarning.setText("Account: " + GTConstants.accountName);
           else if(GTConstants.isTour && GTConstants.tourName.length()>1)
              textWarning.setText(GTConstants.tourName);
           else if(GTConstants.isTour && GTConstants.tourName.length()==1)
              textWarning.setText("No tour selected");
           else
              textWarning.setVisibility(View.INVISIBLE);
        }
            
        if(_case == 3) //end shift
        {
           if(GTConstants.accountName.length() > 1)                  
              textWarning.setText("Warning: Start Shift!" + "\n" + "Account: " + GTConstants.accountName);
           else if(GTConstants.isTour && GTConstants.tourName.length() == 1)
              textWarning.setText("Warning: Start Shift!" + CRLF + "No tour selected");
           else if(GTConstants.isTour && GTConstants.tourName.length() > 1 )
              textWarning.setText("Warning: Start Shift!" + CRLF + GTConstants.tourName);
           else
              textWarning.setText("Warning: Start Shift!");
            
           textWarning.setVisibility(View.VISIBLE);
        }
            
        if(_case == 4) // display custom
        {
           textWarning.setText(display);
           textWarning.setVisibility(View.VISIBLE);
        }
        */
    }

    //this code is executed when an end shift is initiated
    private void endshiftCode() {
        pdialog = ProgressDialog.show(HomeScreen.this, "Please wait", "Ending shift ...", true);

        //send end shift code
        send_event("93");

        ToastMessage.displayToastFromResource(HomeScreen.this, 5, Gravity.CENTER,
                (ViewGroup) findViewById(R.id.toast_layout_root));

        //if tour module installed then clear out any current tour
        if (GTConstants.isTour) {
            //if tour started but not completed write to the trp file
            //touritemNumber > 0 indicates that at least one tag has been scanned
            if (GTConstants.trpfilename.length() > 1 && touritemNumber >= 0)
                endtrpFile(false);
            else
                cleantourInfo();
        }

        //write to dar, transfer file to send directory
        Utility.write_to_file(HomeScreen.this, GTConstants.dardestinationFolder + GTConstants.darfileName,
                "End shift;" + GTConstants.currentBatteryPercent + ";" + Utility.getLocalTime() + ";"
                        + Utility.getLocalDate() + "\r\n",
                true);

        //write the event 19 information to the file
        String GM = Utility.getHeaderMessage("$GM") + ",19," + getCellID();
        Utility.write_to_file(HomeScreen.this, GTConstants.dardestinationFolder + GTConstants.darfileName,
                GM + "\r\n", true);

        //give time for file write before moving file
        Utility.initializeGeneralTimer(2000);
        do {
            Utility.Sleep(1000);
        } while (!Utility.fileAccessComplete() && !Utility.getgeneraltimerFlag());

        //move the dar file to the send file folder 
        File from = new File(GTConstants.dardestinationFolder, GTConstants.darfileName);

        //change the file name to match the $GM time and date
        String parse[] = GM.split(",");
        String newFile = GTConstants.LICENSE_ID.substring(7) + "_" + parse[10] + "_" + parse[2] + ".dar";

        File to = new File(GTConstants.sendfileFolder, newFile);
        from.renameTo(to);

        //write to srp file
        if (GTConstants.srpfileName.length() > 1) {
            Utility.write_to_file(HomeScreen.this, GTConstants.dardestinationFolder + GTConstants.srpfileName,
                    "End account;" + GTConstants.accountName + ";" + Utility.getLocalTime() + ";"
                            + Utility.getLocalDate() + "\r\n",
                    true);

            //write the event 19 information to the file
            GM = Utility.getHeaderMessage("$GM") + ",19," + getCellID();
            Utility.write_to_file(HomeScreen.this, GTConstants.dardestinationFolder + GTConstants.srpfileName,
                    GM + "\r\n", true);

            //give time for file write before moving file
            Utility.initializeGeneralTimer(2000);
            do {
                Utility.Sleep(100);
            } while (!Utility.fileAccessComplete() && !Utility.getgeneraltimerFlag());

            //move the srp file to the send file folder 
            from = new File(GTConstants.dardestinationFolder, GTConstants.srpfileName);

            //change the file name to match the $GM time and date
            String _parse[] = GM.split(",");
            newFile = GTConstants.LICENSE_ID.substring(7) + "_" + _parse[10] + "_" + _parse[2] + "_srp.srp";

            to = new File(GTConstants.sendfileFolder, newFile);
            from.renameTo(to);

            //end account
            GTConstants.srpfileName = " ";
            GTConstants.accountID = "";
            GTConstants.accountName = "";
        }
        //set flag for sending
        Utility.setUploadAvailable();

        //pause the GPS location service after ending a shift
        MainService.pauseLocationListener();

        //wait for end shift string to reach server (or timeout occurs) before dismissing wait dialog
        new CountDownTimer(5000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                if (!GTConstants.sendData) {
                    //pdialog.dismiss();
                }
            }

            @Override
            public void onFinish() {
                if (!(pdialog == null)) {
                    pdialog.dismiss();

                    //set spinner back to start shift
                    spinner.setSelection(0);

                    //clear the warning text window
                    setwarningText("");

                    //set the current state
                    Utility.setcurrentState(GTConstants.offShift);
                    setuserBanner();

                    btn_send.setEnabled(true);

                    if (Utility.getpostorderAvailable()) {
                        restartsyncTimer = true;
                        showAlert("Sync Update", "Update of sync file required", true);
                    }
                }
            }
        }.start();
    }

    //set up the user banner
    private void setuserBanner() {
        String state = "";

        if (Utility.getcurrentState().equals(GTConstants.offShift))
            state = "Off Shift";
        if (Utility.getcurrentState().equals(GTConstants.onShift))
            state = "On Shift";
        if (Utility.getcurrentState().equals(GTConstants.onLunch))
            state = "On Lunch";
        if (Utility.getcurrentState().equals(GTConstants.onBreak))
            state = "On Break";

        textuserName = (TextView) findViewById(R.id.textUsername);
        textuserName.setText(GTConstants.report_name + " - " + state);
        textuserName.setVisibility(View.VISIBLE);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(1, 0, 0, "User name");
        if (GTConstants.isAccount)
            menu.add(1, 1, 1, "Accounts");
        if (GTConstants.isTour)
            menu.add(1, 2, 2, "Select Tour");
        if (GTConstants.isTraffic)
            menu.add(1, 3, 3, "License Plate Check");
        menu.add(1, 4, 4, "Help");
        menu.add(1, 5, 5, "About");
        menu.add(1, 6, 6, "Diagnostics");
        menu.add(1, 7, 7, "GPS Settings");

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case 0:
            show_username_dialog();
            return true;

        case 1:
            /*
            if(GTConstants.sendData)
            {
              show_alert_title = "Warning";
              show_alert_message = "You must end shift before changing accounts!";
                  
              showAlert(show_alert_title, show_alert_message, true);
            }
            else
              show_accounts_dialog();
              */
            show_accounts_dialog();
            return true;

        case 2:
            show_tours_dialog(false);
            return true;

        case 3:
            show_license_dialog();
            return true;

        case 4:
            //navigate to help URL
            Intent browse = new Intent(Intent.ACTION_VIEW, Uri.parse(
                    "http://www.manula.com/manuals/guardtrax/guardtrax-android-users-guide/1/en/topic/introduction-to-android"));
            startActivity(browse);
            return true;

        case 5:
            show_about_dialog();
            return true;

        case 6:
            show_diagnostics_dialog();
            return true;

        case 7:
            confirmgpsSettings();
            return true;
        }

        return super.onOptionsItemSelected(item);

    }

    @Override
    protected void onNewIntent(Intent intent) {
        /*
        Intent diagIntent = new Intent();
        diagIntent.setClass(HomeScreen.this, diagnostics.class);
              
        startActivity(diagIntent);
        //Toast.makeText(HomeScreen.this, "onNewIntent", Toast.LENGTH_SHORT).show();
        /*
         Bundle extras = getIntent().getExtras();
         if(extras != null)
         {
            Toast.makeText(HomeScreen.this, "newIntent extras", Toast.LENGTH_SHORT).show();
             if(extras.containsKey("NotificationMessage"))
             {
                String msg = extras.getString("NotificationMessage");
                Toast.makeText(HomeScreen.this, msg, Toast.LENGTH_SHORT).show();
             }
         }
         */
    }

    private void video_click() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(HomeScreen.this);
        dialog.setTitle("Video");
        dialog.setMessage("Record a video?");

        dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                if (GTConstants.videoFeed.equalsIgnoreCase("dvtel")) {
                    //Launch the DVTel program - TruWitness
                    Intent intent = getPackageManager().getLaunchIntentForPackage("com.dvtel.mobilecam");
                    if (intent != null) {
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }
                } else if (GTConstants.videoFeed.equalsIgnoreCase("milestone")) {
                    //Launch the DVTel program - TruWitness
                    Intent intent = getPackageManager().getLaunchIntentForPackage("com.milestonesys.mobile");
                    if (intent != null) {
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }
                } else {
                    // Launch an intent to capture video from MediaStore
                    Intent takeVideoIntent = new Intent(android.provider.MediaStore.ACTION_VIDEO_CAPTURE);

                    String path = GTConstants.sendfileFolder + Utility.createFileName() + ".mpeg";
                    file_name = path;

                    File file = new File(path);
                    Uri outputFileUri = Uri.fromFile(file);
                    takeVideoIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, outputFileUri);
                    startActivityForResult(takeVideoIntent, ACTION_TAKE_VIDEO);
                }
            }
        });

        dialog.setNeutralButton("View", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                galleryIntent = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(galleryIntent, ACTIVITY_SELECT_VIDEO);
            }
        });

        dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        dialog.show();
    }

    private void camera_click() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(HomeScreen.this);
        dialog.setTitle("Camera");
        dialog.setMessage("Snap a Picture?");

        dialog.setPositiveButton("Snap", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    //Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
                    cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    String path = GTConstants.sendfileFolder + Utility.createFileName() + ".jpg";
                    file_name = path;

                    File file = new File(path);
                    Uri outputFileUri = Uri.fromFile(file);
                    cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, outputFileUri);
                    startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
                } catch (Exception e) {

                }
            }
        });

        dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });

        dialog.setNeutralButton("View", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                galleryIntent = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(galleryIntent, ACTIVITY_SELECT_IMAGE);
            }
        });
        dialog.show();
    }

    private void voice_click() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(HomeScreen.this);
        dialog.setTitle("Microphone");
        dialog.setMessage("Record a voice note?");

        dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                try {
                    //open the voice recorder
                    Intent recordIntent = new Intent(android.provider.MediaStore.Audio.Media.RECORD_SOUND_ACTION);

                    /*
                    String path = GTConstants.sendfileFolder + Utility.createFileName() + ".3ga";
                    file_name = path;
                    File file = new File(path);
                       Uri outputFileUri = Uri.fromFile(file);
                           
                       recordIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, outputFileUri);
                       */
                    startActivityForResult(recordIntent, REQUEST_CODE_RECORD);
                } catch (Exception e) {
                    Toast.makeText(HomeScreen.this, "Voice Recorder not found: ", Toast.LENGTH_LONG).show();
                }

            }
        });

        dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                /*
                boolean temp = Utility.isInsideGeofence(HomeScreen.this, "42.76823265", "-74.236642");
                Toast.makeText(HomeScreen.this,String.valueOf(temp), Toast.LENGTH_SHORT).show();
                    
                Double d = Utility.getDistance("42.76823265","-74.236642","42.66823265","-74.2466428");
                    
                Toast.makeText(HomeScreen.this,"Distance: " + String.valueOf(d), Toast.LENGTH_SHORT).show();
                    
                boolean temp = Utility.isInsideGeofence(HomeScreen.this, "42.76823265", "-74.236642");
                Toast.makeText(HomeScreen.this,String.valueOf(temp), Toast.LENGTH_SHORT).show();
                    
                    
                     
                 List<String> temp = new ArrayList<String>();
                    
                temp = Utility.getGpsGeoFence(HomeScreen.this,1);
                Toast.makeText(HomeScreen.this,"size: " + String.valueOf(temp.size()), Toast.LENGTH_SHORT).show();
                for(int i=0;i<temp.size();i++)Toast.makeText(HomeScreen.this,temp.get(i), Toast.LENGTH_SHORT).show();
                    
                     
                Double d = Utility.getDistance("40.6680185","-74.2452543","40.6671548","-74.2375617");
                    
                Toast.makeText(HomeScreen.this,"Distance: " + String.valueOf(d), Toast.LENGTH_SHORT).show();
                    
                boolean temp = Utility.isInsideGeofence(HomeScreen.this, "40.68", "-74.25");
                Toast.makeText(HomeScreen.this,String.valueOf(temp), Toast.LENGTH_SHORT).show();
                    
                temp = Utility.isInsideGeofence(HomeScreen.this, "40.65", "-74.25");
                Toast.makeText(HomeScreen.this,String.valueOf(temp), Toast.LENGTH_SHORT).show();
                    
                    
                List<String> temp = new ArrayList<String>();
                    
                temp = Utility.getGpsGeoFence(HomeScreen.this);
                for(int i=0;i<temp.size();i++)Toast.makeText(HomeScreen.this,temp.get(i), Toast.LENGTH_SHORT).show();
                    
                    
                String temp = Utility.get_from_GTParamsDataBase(HomeScreen.this, "gps_call");
                    
                Toast.makeText(HomeScreen.this,temp, Toast.LENGTH_SHORT).show();
                    
                GTParams gtDB;
                gtDB = new GTParams(ctx);
                        
                //open the Database to insert the values
                gtDB.open();
                    
                Cursor c = gtDB.getRecordByParam("gps_loc");
                    
                Toast.makeText(HomeScreen.this,"Num records = " + String.valueOf(c.getCount()), Toast.LENGTH_SHORT).show();
                    
                String [] parse;
                if(c != null && c.moveToFirst())
                {
                   for(int i = 0;i<c.getCount();i++)
                   {
                      parse = c.getString(2).split("&");
                      //Toast.makeText(HomeScreen.this,c.getString(2), Toast.LENGTH_LONG).show();
                      for(int j=0;j<4;j++)Toast.makeText(HomeScreen.this,parse[j], Toast.LENGTH_SHORT).show();
                      c.moveToNext();
                   }
                }
                    
                gtDB.close();
                    
                Toast.makeText(HomeScreen.this, "reminder: " + String.valueOf(Utility.istourOntime(tourEnd)), Toast.LENGTH_SHORT).show();
                    
                String value = String.valueOf(GTConstants.sendData) + "," + GTConstants.darfileName + "," + GTConstants.tarfileName + "," + GTConstants.trpfilename + "," +  GTConstants.tourName;
                Utility.storesharedPreference(HomeScreen.this, "serviceString", value);
                    
                //get the parameters that were saved when HomeScreen was shut down
                String serviceString = Utility.getsharedPreference(HomeScreen.this, "serviceString");
                Toast.makeText(HomeScreen.this, "serviceString: " + serviceString, Toast.LENGTH_SHORT).show();
                    
                try
                {
                  String [] parse = serviceString.split(",");
                  GTConstants.sendData = Boolean.valueOf(parse[0]);
                  GTConstants.darfileName = parse[1];
                  GTConstants.tarfileName = parse[2];
                  GTConstants.trpfilename = parse[3];
                  GTConstants.tourName    = parse[4];
                }catch(Exception e)
                {
                  Toast.makeText(HomeScreen.this, "error: " + e, Toast.LENGTH_SHORT).show();
                }
                    
                    
                //get the parameters from the data base
                preferenceDB.open();
                Cursor c = preferenceDB.getRecordByRowID("1");
                    
                GTConstants.LOCATIONUPDATESINTERVAL       = c.getString(1);
                GTConstants.LOCATIONUPDATEDISTANCEINTERVAL    = c.getString(2);
                GTConstants.SERVERIP                   = c.getString(3);
                GTConstants.SERVERPORT                   = Integer.parseInt(c.getString(4));
                GTConstants.PANIC_NUMBER                = c.getString(5);
                GTConstants.UNIQUE_ID                   = c.getString(6);
                GTConstants.ACCELEROMETER_SPEED          = Integer.parseInt(c.getString(7));
                GTConstants.LICENSE_ID                   = c.getString(8);
                GTConstants.PHONE_TYPE                  = c.getString(9);
                GTConstants.REGISTRATION               = c.getString(10);
                c.close();
                    
                //Retrieve last saved user name from preferences 
                GTConstants.report_name = Utility.getsharedPreference(HomeScreen.this, "userName");
                      
                c.close();
                preferenceDB.close();
                      
                    
                    
                if(!test)
                {
                   Intent service_intent = new Intent(HomeScreen.this,StandAloneMainService.class);
                   startService(service_intent);
                   test = true;
                }
                else
                {
                   Toast.makeText(HomeScreen.this,"Stopping...", Toast.LENGTH_SHORT).show();
                   stopService(new Intent(HomeScreen.this, StandAloneMainService.class));
                       
                }
                    
                //Intent service_intent = new Intent(HomeScreen.this, MainService.class);
                //startService(service_intent);
                    
                //List<Boolean> returnList = new ArrayList<Boolean>();
                    
                //refreshtourtagList(5, true,false,false,false);
                    
                //refreshtourtagList(3, false,false,false,true);
                    
                //returnList = refreshtourtagList(5, false,false,true,false);
                    
                    
                //for(int i =0;i<returnList.size();i++)Toast.makeText(HomeScreen.this,String.valueOf(i) + " " + String.valueOf(returnList.get(i)), Toast.LENGTH_SHORT).show();
                    
                /*    
                    
                //Toast.makeText(HomeScreen.this,String.valueOf(GTConstants.locationInfoDTO.getLastAcquire(System.currentTimeMillis() / 1000)), Toast.LENGTH_LONG).show();
                    
                if(MainService.isgpsActivated())
                   Toast.makeText(HomeScreen.this,"Active", Toast.LENGTH_SHORT).show();
                else
                   Toast.makeText(HomeScreen.this,"Not Active", Toast.LENGTH_SHORT).show();
                    
                    
                tourDB.open();
                    
                Cursor c = tourDB.getRecordByTag("0E401005317A9CED");
                    
                if(c != null && c.moveToFirst())
                {
                   Toast.makeText(HomeScreen.this,"Num records = " + String.valueOf(c.getCount()), Toast.LENGTH_SHORT).show();
                   for(int i = 0;i<c.getCount();i++)
                   {
                      Toast.makeText(HomeScreen.this,"Tour " + c.getString(1), Toast.LENGTH_SHORT).show();
                      c.moveToNext();
                   }
                }
                    
                //Toast.makeText(HomeScreen.this,String.valueOf(tourDB.getNumRecords()), Toast.LENGTH_SHORT).show();
                tourDB.close();
                    
                    
                String temp = String.valueOf(MainService.istourReminder());
                Toast.makeText(HomeScreen.this,temp , Toast.LENGTH_SHORT).show();
                    
                try
                {
                   String setTime = "11:11:11+5";
                   long offset = 0;
                 if(setTime.contains("+") || setTime.contains("-"))
                 {
                    String[] parse = null;
                    if(setTime.contains("+"))parse = setTime.split("\\+");
                    if(setTime.contains("-"))parse = setTime.split("\\-");
                    setTime = parse[0];
                    offset = Long.valueOf(parse[1])*60000;
                 }
                     
                 Toast.makeText(HomeScreen.this,setTime , Toast.LENGTH_SHORT).show();
                 Toast.makeText(HomeScreen.this,String.valueOf(offset) , Toast.LENGTH_SHORT).show();
                }catch(Exception e)
                {
                   Toast.makeText(HomeScreen.this,"Error: " +e, Toast.LENGTH_LONG).show();
                }
                    
                    
                    
                Toast.makeText(HomeScreen.this,String.valueOf(tourtagsScanned.size()) , Toast.LENGTH_SHORT).show();
                    
                for(int i = 0;i<tourtagsScanned.size();i++)
                {
                   Toast.makeText(HomeScreen.this,String.valueOf(tourtagsScanned.get(i)) , Toast.LENGTH_SHORT).show();
                }
                    
                tourtagsScanned.set(1, true);
                Toast.makeText(HomeScreen.this,String.valueOf(tourtagsScanned.get(1)) , Toast.LENGTH_SHORT).show();
                    
                tourtagsScanned.clear();
                tourtagsScanned.add(true);
                tourtagsScanned.add(false);
                tourtagsScanned.add(true);
                Toast.makeText(HomeScreen.this,String.valueOf(tourtagsScanned.size()) , Toast.LENGTH_LONG).show();
                    
                for(int i = 0;i<tourtagsScanned.size();i++)
                {
                   Toast.makeText(HomeScreen.this,String.valueOf(tourtagsScanned.get(i)) , Toast.LENGTH_LONG).show();
                }
                    
                //String temp = Utility.offsetTime(Utility.getLocalDate() + " " + "01:00:00",86400000);
                //Toast.makeText(HomeScreen.this,temp , Toast.LENGTH_LONG).show();
                    
                String temp = Utility.gettimeDiff("10-26-14 23:00:00",Utility.getLocalDate() + " " + "01:00:00");
                Toast.makeText(HomeScreen.this,temp, Toast.LENGTH_LONG).show();
                    
                if(temp.charAt(0) == '-' && Integer.valueOf(temp.substring(4, 6)) >= 12)
                {
                   Toast.makeText(HomeScreen.this,temp.substring(4, 6), Toast.LENGTH_LONG).show();
                    
                   //add one day
                   temp = Utility.offsetTime(Utility.getLocalDate() + " " + "01:00:00",86400000);
                       
                   Toast.makeText(HomeScreen.this,temp , Toast.LENGTH_LONG).show();
                }
                    
                    
                //String temp = Utility.parsetarFile(HomeScreen.this);
                //Toast.makeText(HomeScreen.this,temp, Toast.LENGTH_LONG).show();
                    
                //Utility.parsetarFile(HomeScreen.this);
                    
                //show_taaSignature_dialog();
                    
                    
                try
                {
                   String[] test = {"1","2"};
                   Toast.makeText(HomeScreen.this,test[0] + " " + test[1], Toast.LENGTH_LONG).show();
                       
                }catch(Exception e)
                {
                   Toast.makeText(HomeScreen.this,"Error: " +e, Toast.LENGTH_LONG).show();
                }
                //test = test + "3";
                    
                try
                {
                   String temp = Utility.offsetTime(Utility.getLocalDateTime(),10000);
                   //Toast.makeText(HomeScreen.this,temp + " " + temp1, Toast.LENGTH_LONG).show();
                   MainService.initializetourReminder(temp,"Hello");
                }catch(Exception e)
                {
                   Toast.makeText(HomeScreen.this,"Error: " +e, Toast.LENGTH_LONG).show();
                }
                //Toast.makeText(HomeScreen.this,"MB = " + Utility.gettotalmegaBytes(HomeScreen.this), Toast.LENGTH_LONG).show();
                //long tx=TrafficStats.getTotalTxBytes();
                    
                    
                try
                {
                   if(tourDB.checkDataBase())
                   {
                      tourDB.open();
                          
                      Toast.makeText(HomeScreen.this,"Num records = " + String.valueOf(tourDB.getNumRecords()), Toast.LENGTH_SHORT).show();
                          
                      //tourDB.deleteDB();
                          
                      //tourDB.insertRecord("Tour 1","2nd Floor Bathroom" ," "," ");
                      //tourDB.insertRecord("Tour 1","3rd Floor Bathroom" ," "," ");
                      //tourDB.insertRecord("Tour 1","4rth Floor Bathroom" ," "," ");
                      //tourDB.insertRecord("Tour 2","1st Floor Bathroom" ," "," ");
                      //tourDB.insertRecord("Tour 2","1st Floor lobby" ," "," ");
                          
                      //Cursor c = tourDB.getRecordByParameter("Tour 1");
                      //Cursor c = tourDB.getallRecords();
                      Cursor c = tourDB.getDistinctRecordByColumn("1");
                          
                      Toast.makeText(HomeScreen.this,"Num records = " + String.valueOf(c.getCount()), Toast.LENGTH_SHORT).show();
                          
                      if(c != null && c.moveToFirst())
                      {
                for(int i = 0;i<c.getCount();i++)
                {
                   Toast.makeText(HomeScreen.this,c.getString(0), Toast.LENGTH_SHORT).show();
                   //Toast.makeText(HomeScreen.this,c.getString(1) + " " +  c.getString(2), Toast.LENGTH_SHORT).show();
                   c.moveToNext();
                }
                      }
                          
                      //Toast.makeText(HomeScreen.this,String.valueOf(tourDB.getNumRecords()), Toast.LENGTH_SHORT).show();
                      tourDB.close();
                   }
                   else
                   {
                      tourDB.open();
                      tourDB.close();
                   }
                       
                      
                }catch(Exception e)
                {
                   Toast.makeText(HomeScreen.this,"error: " + e, Toast.LENGTH_SHORT).show();
                }
                    
                    
                //MainService.mainserviceDialog("Test","Test");
                    
                //Toast.makeText(HomeScreen.this,"Time:  " + Utility.getLocalTime(), Toast.LENGTH_LONG).show();
                //Toast.makeText(HomeScreen.this,"Time:  " + Utility.getLocalDate(), Toast.LENGTH_LONG).show();
                    
                //Toast.makeText(HomeScreen.this,"Server:  " + Utility.getServerResponse(), Toast.LENGTH_LONG).show();
                //Toast.makeText(HomeScreen.this,"Lunch Out =  " + String.valueOf(lunchoutLocation), Toast.LENGTH_SHORT).show();
                //Toast.makeText(HomeScreen.this,"Break Out =  " + String.valueOf(breakoutLocation), Toast.LENGTH_SHORT).show();
                    
                    
                    
                trafficDB.open();
                Cursor c = trafficDB.getallRecords();
                    
                if(c != null && c.moveToFirst())
                {
                  for(int i=0;i<trafficDB.getNumRecords();i++)
                  {
                     Toast.makeText(HomeScreen.this,"License: " + c.getString(1) + " " + c.getString(2), Toast.LENGTH_SHORT).show();
                     c.moveToNext();
                  }
                }
                    
                trafficDB.close();
                    
                //Toast.makeText(HomeScreen.this,"Current time =  " + Utility.getLocalDateTime(), Toast.LENGTH_SHORT).show();
                //Toast.makeText(HomeScreen.this,"Lunch start =  " + Utility.getlunchStart(), Toast.LENGTH_SHORT).show();
                    
                //Toast.makeText(HomeScreen.this,"Diff =  " + Utility.gettimeDiff(Utility.getlunchStart(), Utility.getLocalDateTime()), Toast.LENGTH_SHORT).show();
                    
                //Toast.makeText(HomeScreen.this,"Diff =  " + Utility.gettimeDiff(Utility.getsessionStart(), new SimpleDateFormat("MM-dd-yy HH:mm:ss")), Toast.LENGTH_SHORT).show();
                /*
                trafficDB.open();
                    
                String license = "AAA123";
                String fields [] ={"NJ","AAA123","01-01-12","01-02-14","2"};
                    
                int i = 0;
                //check if license already in data base, if not just insert
                Cursor c = trafficDB.getRecordByParameter(fields[i+1]);
                    
                if(c != null && c.moveToFirst())
                {
                       
                   //choose which parameters to update data base with
                   String temp [] = new String[5];
                       
                   //test State
                   if(fields[i].equalsIgnoreCase("--"))
                      temp[0] = c.getString(1);
                   else
                      temp[0] = fields[i];
                       
                   //set license from incoming data
                   temp[1] = fields[i+1];
                       
                   //test first date of violation.  Keep the earlier one.
                   if(Integer.parseInt(Utility.getdiffDays(c.getString(3), fields[i+2])) >= 0)
                      temp[2] = c.getString(3);
                   else
                      temp[2] =fields[i+2];
                       
                   //test last date of violation.  Keep the later one.
                   Toast.makeText(HomeScreen.this,"Days =  " + Utility.getdiffDays(c.getString(4), fields[i+3]), Toast.LENGTH_SHORT).show();
                   if(Integer.parseInt(Utility.getdiffDays(c.getString(4), fields[i+3])) >= 0)
                      temp[3] = fields[i+3];
                   else
                      temp[3] = c.getString(4);
                       
                   //test the number of violations.  Put in the greater of the two
                   if(Integer.parseInt( fields[i+4]) >= Integer.parseInt(c.getString(5)))
                      temp[4] = fields[i+4];
                   else
                      temp[4] = c.getString(5);
                       
                   //update the data base
                   trafficDB.UpdateRecord(Long.parseLong(c.getString(0)), temp[0], temp[1], temp[2], temp[3], temp[4]);
                       
                }
                else
                   trafficDB.insertRecord(fields[i], fields[i+1], fields[i+2], fields[i+3], fields[i+4]);
                    
                trafficDB.close();
                    
                c = Utility.getTrafficViolations(HomeScreen.this,license);
                    
                if(c != null && c.moveToFirst())
                {
                   Toast.makeText(HomeScreen.this,"Data:  " + c.getString(1) + " " + c.getString(2)+ " " + c.getString(3) + " "+ c.getString(4) + " " + c.getString(5), Toast.LENGTH_SHORT).show();
                }
                else
                   Toast.makeText(HomeScreen.this,"No violations", Toast.LENGTH_LONG).show();
                    
                /*
                Toast.makeText(HomeScreen.this,"Days =  " + Utility.getdiffDays("01-01-14", "01-01-13"), Toast.LENGTH_SHORT).show();
                    
                String license = "NJ,SHX73Y";
                Cursor c = Utility.getTrafficViolations(HomeScreen.this,license);
                    
                if(c != null && c.moveToFirst())
                {
                   Toast.makeText(HomeScreen.this,"Data:  " + c.getString(1) + " " + c.getString(2)+ " " + c.getString(3) + " "+ c.getString(4) + " " + c.getString(5), Toast.LENGTH_SHORT).show();
                }
                else
                   Toast.makeText(HomeScreen.this,"No violations", Toast.LENGTH_SHORT).show();
                    
                license = "SHX73Y";
                c = Utility.getTrafficViolations(HomeScreen.this,license);
                    
                if(c != null && c.moveToFirst())
                {
                   Toast.makeText(HomeScreen.this,"Data 2:  " + c.getString(1) + " " + c.getString(2)+ " " + c.getString(3) + " "+ c.getString(4) + " " + c.getString(5), Toast.LENGTH_SHORT).show();
                }
                else
                   Toast.makeText(HomeScreen.this,"No violations", Toast.LENGTH_SHORT).show();
                    
                String test = "trafficModule";
                if(test.contains("traffic"))
                   Toast.makeText(HomeScreen.this,"True", Toast.LENGTH_SHORT).show();
                else
                   Toast.makeText(HomeScreen.this,"False ", Toast.LENGTH_SHORT).show();
                       
                try
                {
                   trafficDB.open();
                   trafficDB.deleteDB();
                   trafficDB.insertRecord("NJ","SHX75Y" ,"09-14-13","09-14-14","1");
                   trafficDB.insertRecord("NJ","ABCDEF" ,"09-14-13","09-14-14","2");
                   trafficDB.insertRecord("NJ","HIJKLM" ,"09-14-13","09-14-14","3");
                   trafficDB.insertRecord("NJ","234567" ,"09-14-13","09-14-14","4");
                   trafficDB.insertRecord("NJ","AAA111" ,"09-14-13","09-14-13","4");
                  trafficDB.close();
                       
                  Toast.makeText(HomeScreen.this,"Days =  " + Utility.getdayssincelastViolation(HomeScreen.this, "AAA 111"), Toast.LENGTH_SHORT).show();
                }catch(Exception e)
                {
                   Toast.makeText(HomeScreen.this,"error: " + e, Toast.LENGTH_SHORT).show();
                }
                    
                try
                {
                   String license = "ABC 123";
                   Cursor c = Utility.getTrafficViolations(HomeScreen.this,license);
                   //Cursor c = Utility.getTrafficViolations(HomeScreen.this,"234 567");
                      
                   if(!(c == null))
                   {
                      c.moveToFirst();
                      Toast.makeText(HomeScreen.this,"Last violation =  " + c.getString(4), Toast.LENGTH_SHORT).show();
                     Toast.makeText(HomeScreen.this,"num violations =  " + c.getString(5), Toast.LENGTH_SHORT).show();
                   }
                   else
                      Toast.makeText(HomeScreen.this,"No violations", Toast.LENGTH_SHORT).show();
                       
                   Utility.updatetrafficViolations(HomeScreen.this, "NJ", license);
                }catch(Exception e)
                {
                   Toast.makeText(HomeScreen.this,"error: " + e, Toast.LENGTH_SHORT).show();
                }
                    
                    
                    
                    
                try
                {
                   if(trafficDB.checkDataBase())
                   {
                      trafficDB.open();
                          
                      Cursor c = trafficDB.getRecordByParameter("234567");
                          
                      if(!(c == null))
                      {
                c.moveToFirst();
                Toast.makeText(HomeScreen.this,"num violations =  " + c.getString(5), Toast.LENGTH_SHORT).show();
                      }
                          
                          
                      for(int i=1;i<trafficDB.getNumRecords()+1;i++)
                      {
                Toast.makeText(HomeScreen.this,"num: " + String.valueOf(i), Toast.LENGTH_SHORT).show();
                //Cursor c = trafficDB.getRecordByRowID(String.valueOf(i));
                Cursor c = trafficDB.getallRecords();
                    
                c.moveToFirst();
                Toast.makeText(HomeScreen.this,"c " + c.getString(1) + c.getString(2), Toast.LENGTH_SHORT).show();
                      }
                          
                          
                      //trafficDB.deleteDB();
                      //trafficDB.insertRecord("NJ","SHX75Y" ,"091413","091414","1");
                      //trafficDB.insertRecord("NJ","ABCDEF" ,"091413","091414","2");
                      //trafficDB.insertRecord("NJ","HIJKLM" ,"091413","091414","3");
                      //trafficDB.insertRecord("NJ","234567" ,"091413","091414","4");
                      //int i = trafficDB.getNumRecords();
                          
                      trafficDB.close();
                      //Toast.makeText(HomeScreen.this,"num: " + String.valueOf(i), Toast.LENGTH_SHORT).show();
                   }
                   else
                   {
                      Toast.makeText(HomeScreen.this,"Creating trafficDB", Toast.LENGTH_SHORT).show();
                      trafficDB.open();
                      trafficDB.close();
                   }
                }catch(Exception e)
                {
                   Toast.makeText(HomeScreen.this,"error: " + e, Toast.LENGTH_SHORT).show();
                }
                    
                     
                  myDatabase.open();
                 myDatabase.deleteDB();
                 myDatabase.close();
                     
                 myDatabase.open();
                {
                 cursor = myDatabase.getRecordByStatus("0");
                 if (cursor.moveToFirst()) 
                 {
                    do 
                    {
                       //get the data
                       String dMessage = cursor.getString(1).toString();
                           
                       Toast.makeText(HomeScreen.this,dMessage, Toast.LENGTH_SHORT).show();
                        
                    } while (cursor.moveToNext());
                 }
                 cursor.close();
                }
                myDatabase.close();
                     
                myDatabase.open();
                Toast.makeText(HomeScreen.this,"Num records = " + String.valueOf(myDatabase.getnumRecords()), Toast.LENGTH_SHORT).show();
                myDatabase.close();
                    
                File wFile =  new File(GTConstants.sendfileFolder);
                Toast.makeText(HomeScreen.this,"Num files = " + String.valueOf(Utility.getnumFiles(wFile)), Toast.LENGTH_SHORT).show();
                    
                     
                Utility.checkboxDialog(HomeScreen.this,"email","reportEmailPref");
                    
                    
                accountsDB aDB;
                aDB  = new accountsDB(HomeScreen.this);
                    
                aDB.open();
                    
                for(int i=1;i<aDB.getNumRecords()+1;i++)
                {
                  Cursor c = aDB.getRecordByRowID(String.valueOf(i));
                  Toast.makeText(HomeScreen.this,c.getString(1) + " " + c.getString(2), Toast.LENGTH_SHORT).show();
                }
                    
                aDB.close();
                */

                /*
                 * 
                 * ActivityManager activityManager = (ActivityManager) getSystemService( ACTIVITY_SERVICE );
                 List<RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses();
                 for(int i = 0; i < procInfos.size(); i++)
                 {
                     
                     if(procInfos.get(i).processName.equals("com.guardtrax")) 
                     {
                Toast.makeText(getApplicationContext(), "GuardTrax is running", Toast.LENGTH_LONG).show();
                     }
                 }
                     
                 incidentCodeDataBase icdatabase;
                icdatabase  = new incidentCodeDataBase(HomeScreen.this);
                    
                icdatabase.open();
                    
                for(int i=1;i<icdatabase.getNumRecords()+1;i++)
                {
                  Cursor c = icdatabase.getRecordByRowID(String.valueOf(i));
                  Toast.makeText(HomeScreen.this, "Code: " + c.getString(1), Toast.LENGTH_SHORT).show();
                }
                    
                icdatabase.close();
                    
                String test;
                for(int i=0;i<4;i++)
                {
                  test  = Utility.getkeyCode(HomeScreen.this,i);
                  Toast.makeText(HomeScreen.this, "Code: " + test, Toast.LENGTH_SHORT).show();
                }
                    
                    
                    
                    
                if( Utility.isfilewithexExists("/GT/temp/", "dar"))
                {
                   Toast.makeText(HomeScreen.this, "Exists", Toast.LENGTH_SHORT).show();
                   List<String> temp = Utility.get_saved_file_names("/GT/temp", false, true, "dar");
                   for(int i = 0; i < temp.size();i++)
                 {
                      Toast.makeText(HomeScreen.this, temp.get(i).toString() , Toast.LENGTH_SHORT).show();
                 }
                   }else
                   {
                      Toast.makeText(HomeScreen.this, "not exists" , Toast.LENGTH_SHORT).show();
                   }
                    
                    
                if(Utility.isOnline(HomeScreen.this))
                   Toast.makeText(HomeScreen.this, "Data connection", Toast.LENGTH_LONG).show();
                else
                {
                   Toast.makeText(HomeScreen.this, "No Data connection - " + GTConstants.nodataSMS, Toast.LENGTH_LONG).show();
                   Utility.send_nodata_message(HomeScreen.this);
                }
                    
                Intent intent = new Intent();
                intent.setClass(HomeScreen.this, SignatureScreen.class);
                startActivity(intent);   
                    
                    
                if(GTConstants.test == 0)
                {
                   Thread newThread = new Thread()
                    {
                       public void run() 
                       {
                 String fileUrl = "http://myguardtrax.com/Common/SiteData/b0468944-04cf-425b-91d9-4caf822ce74eGuardTraxResponsetoCSCRFP-COPS.docx";
                 //String fileUrl = "http://android.guardtrax.info/update/update.txt";
                     
                   String destinationFile = Environment.getExternalStorageDirectory() + "/GT/r/" + "test.docx";
                 try 
                 {
                 Utility.savefileatURL(HomeScreen.this, fileUrl, destinationFile);
                       } catch (IOException e) 
                       {
                     
                       }
                       }
                    };
                    newThread.start();
                }
                else
                   Toast.makeText(HomeScreen.this, "error = " + GTConstants.error, Toast.LENGTH_SHORT).show();
                    
                    
                    
                    
                String test = Utility.get_from_GTParamsDataBase(HomeScreen.this, "1234567890987654");            
                Toast.makeText(HomeScreen.this, "record = " + test, Toast.LENGTH_SHORT).show();
                    
                test = Utility.get_from_GTParamsDataBase(HomeScreen.this, "type");            
                Toast.makeText(HomeScreen.this, "type = " + test, Toast.LENGTH_SHORT).show();
                    
                test = Utility.get_from_GTParamsDataBase(HomeScreen.this, "delay");            
                Toast.makeText(HomeScreen.this, "record = " + test, Toast.LENGTH_SHORT).show();
                */

                //Utility.add_to_PreferenceDataBase(HomeScreen.this, 2, "test");

                //Cursor c = Utility.get_from_PreferenceDataBase(HomeScreen.this, "2");
                //Toast.makeText(HomeScreen.this, c.getString(0), Toast.LENGTH_SHORT).show();

                /*
                incidentCodeDataBase icdatabase;
                icdatabase  = new incidentCodeDataBase(HomeScreen.this);
                    
                    
                icdatabase.open();
                icdatabase.deleteDB();
                    
                for(int i=1;i<icdatabase.getNumRecords()+1;i++)
                {
                  Cursor c = icdatabase.getRecordByRowID(String.valueOf(i));
                  Toast.makeText(HomeScreen.this, "Code: " + c.getString(1), Toast.LENGTH_SHORT).show();
                }
                    
                icdatabase.close();
                */

                //btn_report_screen.startAnimation(animation);
                /*
                Toast.makeText(HomeScreen.this, "Name: " + GTConstants.report_name, Toast.LENGTH_SHORT).show();
                    
                String wFile = Environment.getExternalStorageDirectory() + "/GT/r/" + "test";
                String wString = "this is a test ";
                for(int i=0;i<10;i++)
                {
                  wFile = wFile + String.valueOf(i) + ".txt";
                 wString = wString + String.valueOf(i);
                  Utility.write_to_file(HomeScreen.this,wFile,wString);
                  wFile = wFile.substring(0, wFile.length()-4);
                      
                }
                */
                //String test = Utility.read_from_file(HomeScreen.this,wFile);

                //Toast.makeText(HomeScreen.this, "data: " + test, Toast.LENGTH_SHORT).show();
                /*
                 * Utility.delete_ftpdatabase(HomeScreen.this);
                 * 
                Utility.add_mediafile_to_ftpDatabase(HomeScreen.this,"test 1");
                Utility.add_mediafile_to_ftpDatabase(HomeScreen.this,"test 2");
                Utility.add_mediafile_to_ftpDatabase(HomeScreen.this,"test 3");
                Utility.add_mediafile_to_ftpDatabase(HomeScreen.this,"test 4");
                ArrayList<String> list = Utility.get_all_media_from_ftpdatabase(HomeScreen.this);
                int i = Utility.get_ftpdatabase_count(HomeScreen.this);
                Toast.makeText(HomeScreen.this, "ftp database count = " + String.valueOf(i), Toast.LENGTH_SHORT).show();
                    
                for(int j=0;j<i+1;j++)
                {
                   Toast.makeText(HomeScreen.this, "file: " + Utility.get_mediafile_from_ftpDatabase(HomeScreen.this, j), Toast.LENGTH_SHORT).show();
                }
                try
                {
                   if(list != null)
                   {
                      Toast.makeText(HomeScreen.this, "list size = " + String.valueOf(list.size()), Toast.LENGTH_SHORT).show();
                      for(int j = 0;j < list.size();j++)Toast.makeText(HomeScreen.this, list.get(j), Toast.LENGTH_SHORT).show();
                   }
                       
                }catch(Exception e)
                {
                   Toast.makeText(HomeScreen.this, e.toString(), Toast.LENGTH_SHORT).show();
                }
                //Utility.delete_ftpdatabase(HomeScreen.this);
                    
                */
                //Toast.makeText(HomeScreen.this, Utility.getimageIMEIString(), Toast.LENGTH_SHORT).show();
                /*
                String fname = Utility.getLocalDate() +"_" + Utility.getLocalTime() + ".jpg";
                Utility.add_mediafile_to_ftpDatabase(HomeScreen.this, fname);
                    
                int i = Utility.get_ftpdatabase_count(HomeScreen.this);
                Toast.makeText(HomeScreen.this, "count = " + String.valueOf(i), Toast.LENGTH_SHORT).show();
                    
                ArrayList<String> list = Utility.get_all_media_from_ftpdatabase(HomeScreen.this);
                    
                try
                {
                   if(list != null)Toast.makeText(HomeScreen.this, String.valueOf(list.size()), Toast.LENGTH_SHORT).show();
                       
                   for(int j = 0;j < list.size();j++)Toast.makeText(HomeScreen.this, list.get(j), Toast.LENGTH_SHORT).show();
                   if(i==2)Utility.remove_mediafile_from_ftpDatabase(HomeScreen.this, "", i);
                }catch(Exception e)
                {
                   Toast.makeText(HomeScreen.this, e.toString(), Toast.LENGTH_SHORT).show();
                }
                       
                //Utility.delete_ftpdatabase(HomeScreen.this);
                */

                /*
                String QR_day_code = "GTXDA031";
                String substr = QR_day_code.substring(5, 8);
                Calendar calendar = Calendar.getInstance();
                int day = calendar.get(Calendar.DAY_OF_WEEK); 
                int day_code = Integer.valueOf(substr);
                    
                Toast.makeText(HomeScreen.this, "day = " + String.valueOf(day), Toast.LENGTH_LONG).show();
                day = 1 << (day-1);
                Toast.makeText(HomeScreen.this, "day shif ted = " + String.valueOf(day), Toast.LENGTH_LONG).show();
                Toast.makeText(HomeScreen.this, "AND = " + String.valueOf(day & day_code), Toast.LENGTH_LONG).show();
                */
            }
        });
        dialog.show();
    }

    //sends device to location settings to allow user to select correct GPS settings
    private void confirmgpsSettings() {
        Intent i = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivity(i);
    }

    private void dial_click() {
        Intent intent = new Intent();
        intent.setClass(HomeScreen.this, PanicScreen.class);
        startActivity(intent);
    }

    private void scan_click(boolean taaScan) {
        Intent intent = new Intent();
        intent.setClass(HomeScreen.this, ScanBarCodeScreen.class);
        if (taaScan) {
            intent.putExtra("taaScan", "yes");
            intent.putExtra("tagScan", "no");
        } else {
            intent.putExtra("taaScan", "no");
            intent.putExtra("tagScan", "yes");
        }

        //clear the last tag scanned
        setlasttagScanned("");

        startActivity(intent);
    }

    private void report_click() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(HomeScreen.this);
        dialog.setTitle("Reports - Documents");
        dialog.setMessage("Create Notes or review a Document?");

        dialog.setPositiveButton("Notes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent();
                intent.setClass(HomeScreen.this, ReportScreen.class);
                intent.putExtra("type", "Activity Report");
                intent.putExtra("incident", "");
                intent.putExtra("fromFile", "no");
                intent.putExtra("fileName", "");
                intent.putExtra("traffic", "no");
                startActivity(intent);
            }
        });

        dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });

        dialog.setNeutralButton("Documents", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent();
                intent.setClass(HomeScreen.this, PostOrderScreen.class);

                if (new_document) {
                    animation.cancel();
                    new_document = false;
                    intent.putExtra("new_document", Utility.getlastDocument());
                }

                startActivity(intent);
            }
        });
        dialog.show();
    }

    /*
    @Override
    public boolean onTouchEvent(MotionEvent touchevent)
    {
       switch (touchevent.getAction())
        {
           //when user first touches the screen we get x and y coordinate
    case MotionEvent.ACTION_DOWN:
    {
       x1 = touchevent.getX();
        break;
    }
    case MotionEvent.ACTION_UP:
    {
        x2 = touchevent.getX();
                       
        // if right to left sweep event on screen
        if (x1 > x2)
        {
           Intent intent = new Intent();
           intent.setClass(HomeScreen.this, ScanBarCodeScreen.class);
           startActivity(intent);
        }       
        break;
    }
        }
        return false;
    }
    */

    //a method to write the last entries to a trp file
    private static void endtrpFile(boolean completed) {
        //write the tour tag to the trp file
        String message = "";
        int notScanned = 0;
        int total = 0;

        if (completed)
            message = "Tour Completed;";
        else
            message = "Tour Not Completed;";

        Utility.write_to_file(ctx, GTConstants.dardestinationFolder + GTConstants.trpfilename,
                message + Utility.getLocalTime() + ";" + Utility.getLocalDate() + "\r\n", true);

        //get the number of items in the tour and those not scanned if needed
        tourDB.open();

        Cursor c = tourDB.getRecordByTour(GTConstants.tourName);

        //get the tour tag scan list
        List<Boolean> tourtagsScanned = new ArrayList<Boolean>();
        List<Boolean> tourtagIncluded = new ArrayList<Boolean>();
        tourtagsScanned = refreshtourtagList(c.getCount(), false, true, false, false);
        tourtagIncluded = refreshtourtagList(c.getCount(), false, false, true, false);

        //get the number of items in the tour
        for (int i = 0; i < c.getCount(); i++) {
            if (tourtagIncluded.get(i))
                total++;
        }

        //if tour not completed then write the tags that were not scanned
        if (!completed) {
            if (c != null && c.moveToFirst()) {
                for (int i = 0; i < c.getCount(); i++) {
                    if (!tourtagsScanned.get(i) && tourtagIncluded.get(i)) {
                        notScanned++;
                        Utility.write_to_file(ctx, GTConstants.dardestinationFolder + GTConstants.trpfilename,
                                "Missed Tag;" + c.getString(3) + "\r\n", true);
                    }

                    c.moveToNext();
                }
            }
        }
        tourDB.close();

        //write  stats to file
        Utility.write_to_file(ctx, GTConstants.dardestinationFolder + GTConstants.trpfilename,
                "Stats;" + String.valueOf(total - notScanned) + ";" + String.valueOf(total) + "\r\n", true);

        //write the event 19 information to the file
        String GM = Utility.getHeaderMessage("$GM") + ",19," + getCellID();
        Utility.write_to_file(ctx, GTConstants.dardestinationFolder + GTConstants.trpfilename, GM + "\r\n", true);

        //give time for file write
        Utility.initializeGeneralTimer(2000);
        do {
            Utility.Sleep(100);
        } while (!Utility.fileAccessComplete() && !Utility.getgeneraltimerFlag());

        //move the dar file to the send file folder 
        File from = new File(GTConstants.dardestinationFolder, GTConstants.trpfilename);

        //change the file name to match the $GM time and date
        String parse[] = GM.split(",");
        String newFile = GTConstants.LICENSE_ID.substring(7) + "_" + parse[10] + "_" + parse[2] + "_trp.trp";

        File to = new File(GTConstants.sendfileFolder, newFile);
        from.renameTo(to);

        GTConstants.trpfilename = " ";

        //clean up the tour info
        cleantourInfo();

        Utility.setUploadAvailable();

    }

    //cleaqn up tour info
    private static void cleantourInfo() {
        GTConstants.trpfilename = " ";
        MainService.canceltourReminder();
        GTConstants.tourName = " ";
        touritemNumber = -1;
        refreshtourtagList(0, true, false, false, false);
        tourTime = "";
        tourEnd = (long) 0;
    }

    //Checks to see if the current tour is a randomized tour
    private static boolean isRandomTour() {
        if (GTConstants.tourName.length() > 1) {
            if (GTConstants.tourName.charAt(GTConstants.tourName.length() - 1) == ' ')
                return true;
            else
                return false;
        }
        return false;
    }

    //Checks to see if the current tour is a single display randomized tour
    private static boolean isSingleRandomTour() {
        if (GTConstants.tourName.length() > 1) {
            if (GTConstants.tourName.charAt(GTConstants.tourName.length() - 2) == ' '
                    && GTConstants.tourName.charAt(GTConstants.tourName.length() - 1) == ' ')
                return true;
            else
                return false;
        }
        return false;
    }

    //updates the tour list when a tag has been scanned
    public static void updateTour(String tagNumber) {
        if (GTConstants.tourName.length() == 0)
            return;

        boolean tourComplete = true;
        int i = 0; //this will be the position of the first item in the list that has not been scanned
        String temp = "";
        List<Boolean> tourtagsScanned = new ArrayList<Boolean>();
        List<Boolean> tourtagsIncluded = new ArrayList<Boolean>();
        List<Integer> tourOrder = new ArrayList<Integer>();

        tourDB.open();

        Cursor c = tourDB.getRecordByTour(GTConstants.tourName);

        if (c != null && c.moveToFirst()) {
            //get the included tags from the tour list
            tourtagsIncluded = refreshtourtagList(c.getCount(), false, false, true, false);
            tourtagsScanned = refreshtourtagList(c.getCount(), false, true, false, false);
            tourOrder = gettourOrder(c.getCount());

            //first update tag scanned information
            if (tagNumber.length() > 0) {
                //String setTime = c.getString(4);   //this is the time set for the tour

                for (i = 0; i < c.getCount(); i++) {
                    //check if tag matches a tag in the tour list that has not yet been scanned
                    if (tourtagsIncluded.get(i) && !tourtagsScanned.get(i)) {
                        //move to the database location of this item
                        c.moveToPosition(tourOrder.get(i));

                        if (c.getString(3).equals(tagNumber)) {
                            //Toast.makeText(ctx, "Tag: " + c.getString(3), Toast.LENGTH_SHORT).show();

                            //Toast.makeText(ctx, "item # / i: " + String.valueOf(touritemNumber) + " / " + tourOrder.get(i), Toast.LENGTH_SHORT).show();

                            //first check if this is a single display random tour and that this is the correct tag.  If not exit!
                            if (tourOrder.get(i) != touritemNumber && isSingleRandomTour()) {
                                tourDB.close();
                                return;
                            }

                            //write to the tour tag list
                            refreshtourtagList(i, false, false, false, true);

                            //if trp file not yet created, then create it
                            if (GTConstants.trpfilename.length() < 2) {
                                //create the tour report file name
                                GTConstants.trpfilename = GTConstants.LICENSE_ID.substring(7) + "_"
                                        + Utility.getUTCDate() + "_" + Utility.getUTCTime() + ".trp";

                                //write the version to the trp file
                                Utility.write_to_file(ctx,
                                        GTConstants.dardestinationFolder + GTConstants.trpfilename,
                                        "Version;" + GTConstants.version + "\r\n", false);

                                //write the tour name to the trp file
                                Utility.write_to_file(ctx,
                                        GTConstants.dardestinationFolder + GTConstants.trpfilename,
                                        "Tour;" + GTConstants.tourName + ";" + Utility.getLocalTime() + ";"
                                                + Utility.getLocalDate() + "\r\n",
                                        true);

                                //write the user name to the trp file
                                Utility.write_to_file(ctx,
                                        GTConstants.dardestinationFolder + GTConstants.trpfilename,
                                        "Name;" + GTConstants.report_name + "\r\n", true);

                            }

                            //check if scan is late
                            temp = String.valueOf(Utility.istourOntime(tourEnd));

                            Utility.write_to_file(ctx, GTConstants.dardestinationFolder + GTConstants.trpfilename,
                                    "Tag Scan;" + tagNumber + ";" + temp + ";" + Utility.getLocalTime() + ";"
                                            + Utility.getLocalDate() + "\r\n",
                                    true);

                            break;
                        }
                    }
                }

            }

            //get the list of scannedtags from file
            tourtagsScanned = refreshtourtagList(c.getCount(), false, true, false, false);

            //check the tourtagsScanned list to see if all tags have been scanned and set the touritemNumber (touritemNumber is the location in the database list)
            for (i = 0; i < c.getCount(); i++) {
                if (!tourtagsScanned.get(i) && tourtagsIncluded.get(i)) {
                    //go to the position of the next tag to scan which is the next one in the tour order list
                    touritemNumber = tourOrder.get(i);

                    //Toast.makeText(ctx, "Tour item #: " + String.valueOf(touritemNumber), Toast.LENGTH_SHORT).show();
                    //get the location name from the database 
                    c.moveToPosition(touritemNumber);
                    temp = c.getString(2);

                    tourComplete = false;
                    break;
                }
            }

            //if tour is done then reset and display message
            if (tourComplete) {
                tourDB.close();

                //write to the trp file 
                endtrpFile(true);

                setwarningText("Tour complete");
                return;
            } else {
                //check if single display randomized tour.  If so, get the next tag info and display in popup
                if (isSingleRandomTour()) {
                    MainService.mainserviceDialog("Tour Info", "Next Tag: " + CRLF + temp);
                }

                tourDB.close();

                setwarningText("");

                return;
            }
        }

        tourDB.close();
    }

    private void show_about_dialog() {
        show_alert_title = "About";
        show_alert_message = "Android Version: " + android.os.Build.VERSION.RELEASE + "  SDK: "
                + String.valueOf(android.os.Build.VERSION.SDK_INT) + "\n" + "GT Version: " + GTConstants.version
                + "\n" + "License #: " + GTConstants.LICENSE_ID + "\n" + "IMEI    #: " + GTConstants.UNIQUE_ID
                + "\n" + "Phone type: " + GTConstants.PHONE_TYPE + "\n" + "Sim #:      " + get_sim() + "\n"
                + "Registered: " + GTConstants.REGISTRATION + "\n" + "Panic #: " + GTConstants.PANIC_NUMBER + "\n"
                + "Time Event: " + GTConstants.LOCATIONUPDATESINTERVAL + "\n" + "NM Time: "
                + GTConstants.LOCATIONUPDATEDISTANCEINTERVAL + "\n" + "Motion S: "
                + String.valueOf(GTConstants.ACCELEROMETER_SPEED) + "\n";

        showAlert(show_alert_title, show_alert_message, true);
    }

    //this dialog displays time and attendance information
    private void show_taaSignature_dialog() {
        //taa = 5 tells the alert dialog that this was a request from the time and attendance module
        taa = 5;
        try {
            showAlert("Time-Attendance - Signature?", Utility.parsetarFile(HomeScreen.this), false);
        } catch (Exception e) {
            Toast.makeText(HomeScreen.this, "Error: " + e, Toast.LENGTH_SHORT).show();
        }
    }

    //this dialog displays diagnostics information
    private void show_diagnostics_dialog() {

        Intent diagIntent = new Intent();
        diagIntent.setClass(HomeScreen.this, diagnostics.class);

        startActivity(diagIntent);

        /*
        show_alert_title = "Diagnostics";
        //if(sendData())
        {
           myDatabase.open();
             String logged = String.valueOf(myDatabase.getnumRecords());
           myDatabase.close();
               
           show_alert_message = "Session started at: " + Utility.getsessionStart().substring(9,14) + "\n" + 
               "on: " + Utility.getsessionStart().substring(0,5) + "\n" + 
               "Connected to server: " + Utility.isConnecting() + "\n" + 
               "Valid GPS: " + Utility.isvalidGps() + "  (" +  String.valueOf(GTConstants.locationInfoDTO.getNumSats()) + ")\n" +
               "Pending files: " + String.valueOf(Utility.getnumFiles( new File(GTConstants.sendfileFolder)))+ "\n" +
               "Logged events: " + logged;
        }
        //else
           //show_alert_message = "Start shift to run diagnostics";
                    
        showAlert(show_alert_title, show_alert_message, true);
            
        /*
         show_alert_message = "Session started" + "\n" + "  at: " + Utility.getsessionStart().format(new Date()).substring(9) + "\n" +
               "  on: " + Utility.getsessionStart().format(new Date()).substring(0,9) + "\n" + 
               "Connected to server: " + Utility.isConnecting() + "\n" + 
               "Valid GPS: " + Utility.isvalidGps() + "\n" +
               "Pending files: " + String.valueOf(Utility.getnumFiles( new File(GTConstants.sendfileFolder)));
         */
    }

    //this pops up a selector for which account is to be used
    private void show_accounts_dialog() {
        final List<String> listNames = new ArrayList<String>();
        final List<String> listGroupID = new ArrayList<String>();

        aDB.open();

        for (int i = 1; i < aDB.getNumRecords() + 1; i++) {
            Cursor c = aDB.getRecordByRowID(String.valueOf(i));
            listNames.add(c.getString(1));
            listGroupID.add(c.getString(2));
            //Toast.makeText(HomeScreen.this,c.getString(1) + " " + c.getString(2), Toast.LENGTH_SHORT).show();
        }

        aDB.close();

        //add cancel
        listNames.add("Cancel");
        listGroupID.add(" ");

        //CharSequence accounts[] = new CharSequence[] {"red", "green", "blue", "black"};
        final CharSequence[] accounts = listNames.toArray(new CharSequence[listNames.size()]);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Select an Account");
        builder.setItems(accounts, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int location) {
                setupAccounts(listGroupID.get(location), listNames.get(location));
            }
        });
        builder.show();
    }

    private void setupAccounts(String ID, String accountName) {
        //write to srp file if needed
        if (GTConstants.srpfileName.length() > 1) {
            //write to dar report
            Utility.write_to_file(HomeScreen.this, GTConstants.dardestinationFolder + GTConstants.darfileName,
                    "End account;" + GTConstants.accountName + ";" + Utility.getLocalTime() + ";"
                            + Utility.getLocalDate() + "\r\n",
                    true);

            //write to srp report
            Utility.write_to_file(HomeScreen.this, GTConstants.dardestinationFolder + GTConstants.srpfileName,
                    "End account;" + GTConstants.accountName + ";" + Utility.getLocalTime() + ";"
                            + Utility.getLocalDate() + "\r\n",
                    true);

            //write the event 19 information to the file
            String GM = Utility.getHeaderMessage("$GM") + ",19," + getCellID();
            Utility.write_to_file(HomeScreen.this, GTConstants.dardestinationFolder + GTConstants.srpfileName,
                    GM + "\r\n", true);

            //give time for file write before moving file
            Utility.initializeGeneralTimer(2000);
            do {
                Utility.Sleep(100);
            } while (!Utility.fileAccessComplete() && !Utility.getgeneraltimerFlag());

            //move the srp file to the send file folder 
            File from = new File(GTConstants.dardestinationFolder, GTConstants.srpfileName);

            //change the file name to match the $GM time and date
            String _parse[] = GM.split(",");
            String newFile = GTConstants.LICENSE_ID.substring(7) + "_" + _parse[10] + "_" + _parse[2] + "_srp.srp";

            File to = new File(GTConstants.sendfileFolder, newFile);
            from.renameTo(to);

            //set flag for sending
            Utility.setUploadAvailable();

            //if account name is asame as current then end account by changing accountName to Cancel
            if (GTConstants.accountName.equals(accountName))
                accountName = "Cancel";
        }

        if (!accountName.equalsIgnoreCase("Cancel")) {
            GTConstants.accountID = ID;
            GTConstants.accountName = accountName;
            setwarningText("");

            //create srp file
            Utility.createsrpFile(HomeScreen.this);

            /*
            Thread newThread = new Thread()
            {
               public void run() 
               {
                  //String accountMessage = Utility.getHeaderMessage("$GT") + ","+ GTConstants.accountID + "," + getCellID();
                  //sendCodeToDatabase(accountMessage, true);
               }
            };
            newThread.start();
            */

        } else //cancel selected
        {
            GTConstants.srpfileName = " ";
            GTConstants.accountID = "";
            GTConstants.accountName = "";

            setwarningText("");
            //textWarning.setText("Warning: Start Shift!");
        }

    }

    //this pops up a selector for which tour to be selected.  The tour list can be filtered by tag.
    private void show_tours_dialog(final boolean byTag) {
        final List<String> listTours = new ArrayList<String>();

        tourDB.open();

        if (byTag) //only select tours from data basethat have this tag
        {
            Cursor c = tourDB.getRecordByTag(getlasttagScanned());

            if (c != null && c.moveToFirst()) {
                for (int i = 0; i < c.getCount(); i++) {
                    listTours.add(c.getString(1));
                    c.moveToNext();
                }
            }
        } else //select all tours from data base
        {
            Cursor c = tourDB.getDistinctRecordByColumn("1");

            if (c != null && c.moveToFirst()) {
                for (int i = 0; i < c.getCount(); i++) {
                    listTours.add(c.getString(0));
                    c.moveToNext();
                }
            }
        }

        tourDB.close();

        if (listTours.size() > 0) {
            //add cancel
            listTours.add("Cancel");

            final CharSequence[] tours = listTours.toArray(new CharSequence[listTours.size()]);

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Select a Tour");
            builder.setItems(tours, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int location) {
                    if (location != listTours.size() - 1) //tour selected
                    {
                        //if tour started but not completed write to the trp file 
                        //touritemNumber > 0 indicates that at least one tag has been scanned
                        if (GTConstants.trpfilename.length() > 1 && touritemNumber >= 0)
                            endtrpFile(false);
                        else
                            cleantourInfo();

                        //set the new tour name
                        GTConstants.tourName = listTours.get(location);

                        //set up the tag scan list to false by getting the total number of items in the tour and then calling refreshtourtagList
                        tourDB.open();
                        Cursor c = tourDB.getRecordByTour(GTConstants.tourName);
                        c.moveToFirst();
                        tourDB.close();
                        refreshtourtagList(c.getCount(), true, false, false, false);

                        //update the warning text
                        setwarningText("");

                        //set the tour reminder
                        //parse the time info to see if a reminder message offset was included
                        //the offset will be in minutes and be preceded by either a + or - sign
                        Long offset = (long) 0;
                        c.moveToFirst();

                        String setTime = c.getString(4);

                        if (setTime.contains("+") || setTime.contains("-")) {
                            String[] parse = null;
                            if (setTime.contains("+"))
                                parse = setTime.split("\\+");
                            if (setTime.contains("-"))
                                parse = setTime.split("\\-");
                            setTime = parse[0];
                            offset = Long.valueOf(parse[1]) * 60000;

                            Date now = null;
                            try {
                                now = sdf.parse(Utility.getLocalDate() + " " + parse[0]);
                                tourEnd = now.getTime() + offset;
                            } catch (ParseException e) {
                                tourEnd = (long) 0;
                            }

                            tourTime = parse[0].substring(0, parse[0].length() - 3) + " hrs for " + parse[1]
                                    + " mins";
                        } else {
                            Date now = null;
                            try {
                                now = sdf.parse(Utility.getLocalDate() + " " + setTime);
                                tourEnd = now.getTime();
                            } catch (ParseException e) {
                                tourEnd = (long) 0;
                            }

                            tourTime = setTime.substring(0, setTime.length() - 3);
                        }

                        //set reminder 
                        Utility.settourReminder(ctx, setTime, offset,
                                "Tour " + GTConstants.tourName + " not completed!");

                        //write to dar file
                        Utility.write_to_file(HomeScreen.this,
                                GTConstants.dardestinationFolder + GTConstants.darfileName,
                                "Event; Tour " + GTConstants.tourName + " selected;" + Utility.getLocalTime() + ";"
                                        + Utility.getLocalDate() + "\r\n",
                                true);

                        //write to srp file
                        if (GTConstants.srpfileName.length() > 1)
                            Utility.write_to_file(HomeScreen.this,
                                    GTConstants.dardestinationFolder + GTConstants.srpfileName,
                                    "Event; Tour " + GTConstants.tourName + " selected;" + Utility.getLocalTime()
                                            + ";" + Utility.getLocalDate() + "\r\n",
                                    true);

                        //if the tour was established by a tag scan then update the list
                        if (byTag)
                            updateTour(getlasttagScanned());
                        else
                            updateTour("");

                        //Utility.settourReminder(ctx, setTime, offset,"Reminder: " + c.getString(2));
                        //Toast.makeText(HomeScreen.this,"Set time: " + setTime, Toast.LENGTH_SHORT).show();                   
                    } else //this is the cancel selection
                    {
                        //previous tour not completed
                        //touritemNumber > 0 indicates that at least one tag has been scanned
                        if (GTConstants.trpfilename.length() > 1 && touritemNumber >= 0)
                            endtrpFile(false);
                        else
                            cleantourInfo();

                        //update the warning text
                        setwarningText("");
                    }

                }
            });
            builder.show();
        }
    }

    //displays tour information
    private void displaytourInfo() {
        String message = "";
        int i = 0;
        int tagCount = 0;
        boolean singleDisplay = false; //indicates that only 1 item is to be displayed in the tour list
        List<Boolean> tourtagsIncluded = new ArrayList<Boolean>();
        List<Boolean> tourtagsScanned = new ArrayList<Boolean>();
        List<Integer> tourOrder = new ArrayList<Integer>();
        List<String> messageList = new ArrayList<String>();

        //check if this is a single display (second last character of tour name is a space)
        singleDisplay = isSingleRandomTour();
        tourDB.open();

        Cursor c = tourDB.getRecordByTour(GTConstants.tourName);

        if (c != null && c.moveToFirst()) {
            tourtagsScanned = refreshtourtagList(c.getCount(), false, true, false, false);
            tourtagsIncluded = refreshtourtagList(c.getCount(), false, false, true, false);
            tourOrder = gettourOrder(c.getCount());

            //initialize the message array which wil be used to display the messages in the random order
            while (messageList.size() < c.getCount())
                messageList.add("");

            for (i = 0; i < c.getCount(); i++) {
                if (tourtagsScanned.get(i) && tourtagsIncluded.get(i) && !singleDisplay)
                    messageList.add(tourOrder.get(i),
                            "<br><font color='#00FF00'>" + c.getString(2) + "</font><br/>");
                else if (!tourtagsScanned.get(i) && !Utility.istourOntime(tourEnd)
                        && Utility.getcurrentState().equals(GTConstants.onShift) && tourtagsIncluded.get(i)
                        && !singleDisplay)
                    messageList.add(tourOrder.get(i),
                            "<br><font color='#FF0000'>" + c.getString(2) + "</font><br/>");
                else if (!tourtagsScanned.get(i) && tourtagsIncluded.get(i) && !singleDisplay)
                    messageList.add(tourOrder.get(i),
                            "<br><font color='#FFFFFF'>" + c.getString(2) + "</font><br/>");
                else if (singleDisplay && i == touritemNumber)
                    messageList.add(tourOrder.get(i),
                            "<br><font color='#FFFFFF'>" + c.getString(2) + "</font><br/>");

                //get the number of tags included
                if (tourtagsIncluded.get(i))
                    tagCount++;
                c.moveToNext();
            }
        }

        tourDB.close();

        //create the message string
        for (i = 0; i < messageList.size(); i++)
            if (messageList.get(i).length() > 1)
                message = message + messageList.get(i);

        LayoutInflater inflater = LayoutInflater.from(HomeScreen.this);
        View view = inflater.inflate(R.layout.scroll_dialog, null);

        TextView textview = (TextView) view.findViewById(R.id.dialogtext);
        textview.setText(Html.fromHtml(message));
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(HomeScreen.this);

        //create custom title
        TextView title = new TextView(HomeScreen.this);

        //if this is a single display tour then do not indicate how many tags are in the tour
        if (isSingleRandomTour()) //this is a single display tour
            title.setText(GTConstants.tourName + CRLF + tourTime + CRLF);
        else
            title.setText(GTConstants.tourName + CRLF + tourTime + CRLF + String.valueOf(tagCount) + " Tags");
        title.setPadding(10, 10, 10, 10);
        title.setGravity(Gravity.CENTER);
        title.setTextColor(Color.parseColor("#79ABFF"));
        title.setTextSize(20);
        alertDialog.setCustomTitle(title);

        //alertDialog.setTitle(tourName + CRLF + String.valueOf(i-1) + " Tags"); 
        alertDialog.setView(view);
        alertDialog.setPositiveButton("OK", null);
        AlertDialog alert = alertDialog.create();
        alert.show();
    }

    //a dialog for scanning time and attendance location
    private void show_taa_scan(final boolean startShift, final boolean endShift) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(HomeScreen.this);
        dialog.setTitle("Time-Attendance");
        dialog.setMessage("Scan Location Tag?");

        dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (startShift)
                    taa = 1;
                if (endShift)
                    taa = 2;
                scan_click(true);
            }
        });

        //if no email to be sent then exit
        dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Utility.write_to_file(HomeScreen.this, GTConstants.dardestinationFolder + GTConstants.tarfileName,
                        "Tag Scan;No Location Scan" + "\r\n", true);

                //if starting a shift
                if (startShift) {
                    taa = 0;
                }

                //if ending a shift
                if (endShift) {
                    taa = 2; //this tells the onResume to execute the end shift code
                    onResume();
                }

            }
        });
        dialog.show();
    }

    //a dialog for the user to enter their name
    private void show_username_dialog() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(HomeScreen.this);
        dialog.setTitle("User name: " + GTConstants.report_name);
        dialog.setMessage("Enter your name");
        final EditText input = new EditText(this);
        dialog.setView(input);

        dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //store in GTConstants for current use
                GTConstants.report_name = input.getText().toString().trim();

                //store in preferences for later use
                SharedPreferences settings = getSharedPreferences("GTPrefs", 0);
                SharedPreferences.Editor editor = settings.edit();
                editor.putString("userName", GTConstants.report_name);
                editor.commit();

                setuserBanner();
            }
        });

        //if no email to be sent then exit
        dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        dialog.show();
    }

    //a dialog for checking traffic data base
    private void show_license_dialog() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(HomeScreen.this);
        dialog.setTitle("Traffic Violation Database");
        dialog.setMessage("Enter Plate #");
        final EditText input = new EditText(this);
        dialog.setView(input);

        dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Cursor c = Utility.getTrafficViolations(HomeScreen.this, input.getText().toString().trim());

                show_alert_title = "License Plate: " + input.getText().toString().trim().toUpperCase();
                if (c != null && c.moveToFirst()) {
                    show_alert_message = "State: " + c.getString(1) + CRLF;
                    show_alert_message = show_alert_message + "Number of Violations: " + c.getString(5) + CRLF;
                    show_alert_message = show_alert_message + "Last Violation: " + c.getString(4) + CRLF;
                    show_alert_message = show_alert_message + "Days since last violation: "
                            + Utility.getdayssincelastViolation(HomeScreen.this, input.getText().toString().trim());
                } else
                    show_alert_message = "No Recorded Violations";

                showAlert(show_alert_title, show_alert_message, true);
            }
        });

        //if no email to be sent then exit
        dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        dialog.show();
    }

    //this routine refreshes the tour list from file
    //count is either the total number of elements in the list or the position in the list that is being updated to true.
    private static List<Boolean> refreshtourtagList(int count, boolean create, boolean readScanned,
            boolean readIncluded, boolean write) {
        try {
            List<Boolean> returnList = new ArrayList<Boolean>();
            List<Boolean> tempList = new ArrayList<Boolean>();
            List<Integer> orderList = new ArrayList<Integer>();
            String outString = "";
            int listMin = 0;
            int listMax = count;

            //if we need to create a new file
            if (create) {
                //if count = 0 then cleaning up so delete the file
                if (count == 0) {
                    Utility.delete_file(ctx, GTConstants.dardestinationFolder, "toursScanned.txt");
                } else {
                    //create an order list.  This list will be shuffled if it is a randomized tour
                    for (int i = 0; i < count; i++)
                        orderList.add(i, i);

                    //check if it is a tour that needs to be randomized
                    //Make sure tour name is long enough so as no to cause acrash when tryimng to look at the last two characters
                    //a space as the last character indicates randomize the tour
                    if (isRandomTour()) {
                        listMin = (int) (0.4 * count);
                        listMax = (int) (0.6 * count);
                        listMin = Utility.randInt(0, listMin);
                        listMax = Utility.randInt(listMax, count);
                        Collections.shuffle(orderList);
                    }

                    for (int i = 0; i < count; i++) {
                        //if bracketed by listMin and listMax then include, else exclude
                        if (i >= listMin && i <= listMax)
                            outString = outString + "false,true," + String.valueOf(orderList.get(i)) + ",";
                        else
                            outString = outString + "false,false," + String.valueOf(orderList.get(i)) + ",";
                    }

                    //remove the last comma
                    outString = outString.substring(0, outString.length() - 1);

                    Utility.write_to_file(ctx, GTConstants.dardestinationFolder + "toursScanned.txt", outString,
                            false);
                }

                return null;
            }

            //read the file and put into a list the items that have been scanned
            if (readScanned) {
                String inFile = Utility.read_from_file(ctx, GTConstants.dardestinationFolder + "toursScanned.txt");
                String[] parse = inFile.split(",");

                for (int i = 0; i < 3 * count; i += 3)
                    returnList.add(Boolean.valueOf(parse[i]));
                return returnList;

            }

            //read the file and put into a list the items that are included in the tour
            if (readIncluded) {
                String inFile = Utility.read_from_file(ctx, GTConstants.dardestinationFolder + "toursScanned.txt");
                String[] parse = inFile.split(",");

                for (int i = 1; i < 3 * count; i += 3)
                    returnList.add(Boolean.valueOf(parse[i]));

                return returnList;
            }

            //write to the file 
            if (write) {
                //read the current file into a list
                String inFile = Utility.read_from_file(ctx, GTConstants.dardestinationFolder + "toursScanned.txt");
                String[] parse = inFile.split(",");
                int size = parse.length / 3;

                //parse the file into the three lists (scanned, included and order)
                for (int i = 0; i < 3 * size; i += 3)
                    returnList.add(Boolean.valueOf(parse[i]));
                for (int i = 1; i < 3 * size; i += 3)
                    tempList.add(Boolean.valueOf(parse[i]));
                for (int i = 2; i < 3 * size; i += 3)
                    orderList.add(Integer.parseInt(parse[i]));

                //replace the specified location
                returnList.set(count, true);

                //write the new file
                for (int i = 0; i < size; i++)
                    outString = outString + String.valueOf(returnList.get(i)) + ","
                            + String.valueOf(tempList.get(i)) + "," + String.valueOf(orderList.get(i)) + ",";
                outString = outString.substring(0, outString.length() - 1);
                Utility.write_to_file(ctx, GTConstants.dardestinationFolder + "toursScanned.txt", outString, false);

                return null;
            }

            return returnList;
        } catch (Exception e) {
            Toast.makeText(ctx, "Error " + e, Toast.LENGTH_LONG).show();
            return null;
        }
    }

    //gets the tour order
    private static List<Integer> gettourOrder(int count) {
        List<Integer> orderList = new ArrayList<Integer>();
        //read the file and put into a list the items that are included in the tour

        String inFile = Utility.read_from_file(ctx, GTConstants.dardestinationFolder + "toursScanned.txt");
        String[] parse = inFile.split(",");

        for (int i = 2; i < 3 * count; i += 3)
            orderList.add(Integer.parseInt(parse[i]));

        return orderList;

    }

    //returns the sim card number
    private String get_sim() {
        TelephonyManager telemamanger = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        String getSimSerialNumber = telemamanger.getSimSerialNumber();
        //String getSimNumber = telemamanger.getLine1Number();
        return getSimSerialNumber;
    }

    //sets the last tag scanned
    public static void setlasttagScanned(String tagNum) {
        lasttagScanned = tagNum;
    }

    //gets that last tag scanned
    private String getlasttagScanned() {
        return lasttagScanned;
    }

    /*
    private void view_database()
    {
       String dMessage;
       myDatabase.open();
       {
          cursor = myDatabase.getRecordByStatus("0");
          if (cursor.moveToFirst()) 
          {
     do 
     {
        dMessage = cursor.getString(1).toString();
        Toast.makeText(HomeScreen.this, dMessage, Toast.LENGTH_LONG).show();
            
     } while (cursor.moveToNext());
          }
          cursor.close();
       }
       myDatabase.close();
    }
    */

    //load values into the preference database and also put values into constants
    private void loadPreferenceDataBase() {
        //get the default values
        //List<String> defaults = OptionsScreen.loadDefaults();

        String uniqueID = "";

        //get the IMEI number
        try {
            TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
            if (tm != null)
                uniqueID = tm.getDeviceId();
            if (uniqueID == null || uniqueID.length() == 0) {
                WifiManager wifimanager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                if (wifimanager != null)
                    uniqueID = wifimanager.getConnectionInfo().getMacAddress();
            }
            if (uniqueID == null)
                uniqueID = BluetoothAdapter.getDefaultAdapter().getAddress();
            if (uniqueID == null)
                uniqueID = "123456789";
        } catch (Exception e) {
            uniqueID = "987654321";
        }

        String uniqueIdDB = Utility.getUniqueNumber(uniqueID);

        //get the type of phone  (GSM,CDMA) and put into constants
        GTConstants.PHONE_TYPE = getPhoneType();

        //Load into new database 
        preferenceDB.open();

        id = preferenceDB.insertRecord(GTConstants.LOCATIONUPDATESINTERVAL,
                GTConstants.LOCATIONUPDATEDISTANCEINTERVAL, GTConstants.SERVERIP,
                String.valueOf(GTConstants.SERVERPORT), GTConstants.PANIC_NUMBER, uniqueIdDB,
                String.valueOf(GTConstants.ACCELEROMETER_SPEED), GTConstants.LICENSE_ID, GTConstants.PHONE_TYPE,
                GTConstants.REGISTRATION);

        preferenceDB.close();

        //load into constants
        preferenceDB.open();
        cursor = preferenceDB.getRecordByRowID("1");

        saveInConstants(cursor);

        cursor.close();
        preferenceDB.close();

    }

    //load parameters from GTParams data base
    private void loadGTParams() {
        if (gtDB.checkDataBase()) {
            String temp;
            temp = Utility.get_from_GTParamsDataBase(HomeScreen.this, "type");
            if (!temp.equals(""))
                GTConstants.APP_TYPE = temp;
            temp = Utility.get_from_GTParamsDataBase(HomeScreen.this, "postorderURL");
            if (!temp.equals(""))
                GTConstants.postorderURL = temp;
            temp = Utility.get_from_GTParamsDataBase(HomeScreen.this, "videoFeed");
            if (!temp.equals(""))
                GTConstants.videoFeed = temp;
            temp = Utility.get_from_GTParamsDataBase(HomeScreen.this, "nodataSMS");
            if (!temp.equals(""))
                GTConstants.nodataSMS = temp;
            temp = Utility.get_from_GTParamsDataBase(HomeScreen.this, "accounts");
            if (!temp.equals(""))
                GTConstants.isAccount = Boolean.valueOf(temp);
            temp = Utility.get_from_GTParamsDataBase(HomeScreen.this, "trfc");
            if (!temp.equals(""))
                GTConstants.isTraffic = Boolean.valueOf(temp);
            temp = Utility.get_from_GTParamsDataBase(HomeScreen.this, "taaModule");
            if (!temp.equals(""))
                GTConstants.isTimeandAttendance = Boolean.valueOf(temp);
            temp = Utility.get_from_GTParamsDataBase(HomeScreen.this, "tourModule");
            if (!temp.equals(""))
                GTConstants.isTour = Boolean.valueOf(temp);
            temp = Utility.get_from_GTParamsDataBase(HomeScreen.this, "gps_call");
            if (!temp.equals(""))
                GTConstants.isGeoFence = Boolean.valueOf(temp);
        }

        //if necessary, find the location in the spinner for the end lunch and end break codes
        if (GTConstants.isTimeandAttendance) {
            lunchoutLocation = Utility.getlunchendPosition();
            breakoutLocation = Utility.getbreakendPosition();
        }
    }

    public static Uri get_Uri_image() {
        return Uri_image;
    }

    protected void onActivityResult(final int requestCode, int resultCode, final Intent data) {
        if (resultCode == RESULT_CANCELED)
            return;

        //After running Media Gallery Program
        if (requestCode == ACTIVITY_SELECT_IMAGE) {
            Uri_image = data.getData();

            Intent i = new Intent(HomeScreen.this, SingleImageView.class);
            startActivity(i);

            return;
        }

        if (requestCode == ACTIVITY_SELECT_VIDEO) {
            Uri_image = data.getData();

            Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
            intent.setDataAndType(Uri_image, "video/mpeg");
            startActivity(intent);
            return;
        }

        //after running audio program
        if (requestCode == REQUEST_CODE_RECORD) {
            //move file into GT/s directory
            Uri savedUri = data.getData();
            Cursor cursor = getContentResolver().query(savedUri, null, null, null, null);
            if (cursor.moveToFirst()) {
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);//Instead of "MediaStore.Images.Media.DATA" can be used "_data"
                Uri filePathUri = Uri.parse(cursor.getString(column_index));
                String file_path = filePathUri.getPath();

                //rename the file
                String path = GTConstants.sendfileFolder + Utility.createFileName() + ".3ga";

                //put the file name into the global
                file_name = path;

                File file_to = new File(path);
                File file_from = new File(file_path);
                file_from.renameTo(file_to);

                //Toast.makeText(HomeScreen.this, file_name, Toast.LENGTH_LONG).show();
            }
        }

        //after running camera, audio or video program
        if (requestCode == REQUEST_CODE_RECORD || requestCode == CAMERA_PIC_REQUEST
                || requestCode == ACTION_TAKE_VIDEO) {

            //this section was pulled from the "Cancel" option of the the tagging code - it replaces tagging (i.e. as if cancel is always being selected

            try {
                //copy file to /GT/r directory so that local user can view the image
                File file = new File(file_name);
                copyFile(GTConstants.sendfileFolder, file.getName(), GTConstants.receivefileFolder);

                //this needs to be sent to clear the deleted image from the gallery memory - otherwise would have to wait for reboot of phone
                //sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri .parse("file://" + Environment.getExternalStorageDirectory())));
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                        Uri.parse("file://" + Environment.getExternalStorageDirectory())));

                //new Upload_FTP().execute(file_name);
                Utility.setUploadAvailable();
            } catch (Exception e) {
                Toast.makeText(HomeScreen.this, "File copy Error: " + e, Toast.LENGTH_LONG).show();
            }

            //create filename info for dar
            String darFile[] = null;
            String newFile;
            try {
                darFile = file_name.split("_");
                newFile = GTConstants.LICENSE_ID.substring(7) + "_" + darFile[1] + "_" + darFile[2];
                //Toast.makeText(HomeScreen.this, "File: " + newFile, Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                Toast.makeText(HomeScreen.this, "File Naming Error: " + e, Toast.LENGTH_LONG).show();
                newFile = "unknown";
            }

            //email option
            if (requestCode == REQUEST_CODE_RECORD) {
                //add event to dar and srp
                if (GTConstants.sendData) {
                    Utility.write_to_file(HomeScreen.this,
                            GTConstants.dardestinationFolder + GTConstants.darfileName, "Voice;" + newFile + ".3ga"
                                    + ";" + Utility.getLocalTime() + ";" + Utility.getLocalDate() + "\r\n",
                            true);

                    if (GTConstants.srpfileName.length() > 1)
                        Utility.write_to_file(HomeScreen.this,
                                GTConstants.dardestinationFolder + GTConstants.srpfileName,
                                "Voice;" + newFile + ".3ga" + ";" + Utility.getLocalTime() + ";"
                                        + Utility.getLocalDate() + "\r\n",
                                true);

                }
                send_media_via_email("audio");
            }

            if (requestCode == CAMERA_PIC_REQUEST) {
                //add event to dar and srp
                if (GTConstants.sendData) {
                    Utility.write_to_file(HomeScreen.this,
                            GTConstants.dardestinationFolder + GTConstants.darfileName, "Photo;" + newFile + ".jpg"
                                    + ";" + Utility.getLocalTime() + ";" + Utility.getLocalDate() + "\r\n",
                            true);

                    if (GTConstants.srpfileName.length() > 1)
                        Utility.write_to_file(HomeScreen.this,
                                GTConstants.dardestinationFolder + GTConstants.srpfileName,
                                "Photo;" + newFile + ".jpg" + ";" + Utility.getLocalTime() + ";"
                                        + Utility.getLocalDate() + "\r\n",
                                true);

                }
                send_media_via_email("photo");
            }

            if (requestCode == ACTION_TAKE_VIDEO) {
                //add event to dar
                if (GTConstants.sendData) {
                    Utility.write_to_file(HomeScreen.this,
                            GTConstants.dardestinationFolder + GTConstants.darfileName, "Video;" + newFile + ".mpeg"
                                    + ";" + Utility.getLocalTime() + ";" + Utility.getLocalDate() + "\r\n",
                            true);

                    if (GTConstants.srpfileName.length() > 1)
                        Utility.write_to_file(HomeScreen.this,
                                GTConstants.dardestinationFolder + GTConstants.srpfileName,
                                "Video;" + newFile + ".mpeg" + ";" + Utility.getLocalTime() + ";"
                                        + Utility.getLocalDate() + "\r\n",
                                true);

                }
                send_media_via_email("video");
            }

            //end cancel section

            /*  Allowing fore tagging of media files removed 7/1/14 - B. Hall
            //after taking audio, camera or video this routine fires.  file_name is a common variable file name that is assigned when an audio, camera or video is taken
            AlertDialog.Builder dialog = new AlertDialog.Builder(HomeScreen.this);
            dialog.setTitle("Tag");
            dialog.setMessage("Add a tag?");
            final EditText input = new EditText(this);
            dialog.setView(input);
                
            dialog.setPositiveButton("OK",new DialogInterface.OnClickListener() 
            {
               @Override
               public void onClick(DialogInterface dialog,int which) 
               {
                  String tagText = input.getText().toString().trim();
                      
                  //rename the file
                  File currentFile = new File(file_name);
                  String path = GTConstants.sendfileFolder;
                      
                  String oldFile = currentFile.getName();
                  String newFile = oldFile.substring(0, oldFile.lastIndexOf('.')) + "_" + tagText + "_";
                      
                  if (requestCode == CAMERA_PIC_REQUEST) 
                     { 
                     //rename the file to include tag
                     newFile = newFile + ".jpg";
                     file_name = path + newFile;
                         
                     File from = new File(path,oldFile);
                     File to = new File(path,newFile);
                     from.renameTo(to);
                         
                     //now upload the file to the ftp server
              //new Upload_FTP().execute(file_name);
              Utility.setUploadAvailable();
                  
              //email option
              send_media_via_email("photo");
                  
              //this needs to be sent to clear the deleted image from the gallery memory - otherwise would have to wait for reboot of phone
             sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri .parse("file://" + Environment.getExternalStorageDirectory())));
                 
              //Toast.makeText(HomeScreen.this, "Picture saved", Toast.LENGTH_LONG).show();
                     }  
                         
                     if (requestCode == ACTION_TAKE_VIDEO) 
                     {
              newFile = newFile + ".mpeg";
                     file_name = path + newFile;
                         
                     File from = new File(path,oldFile);
                     File to = new File(path,newFile);
                     from.renameTo(to);
              //new Upload_FTP().execute(file_name);
                         
                     Utility.setUploadAvailable();
                  
              //email option
              send_media_via_email("video");
                  
              //this needs to be sent to clear the deleted image from the gallery memory - otherwise would have to wait for reboot of phone
             sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
                 
              //Toast.makeText(HomeScreen.this, "Video saved", Toast.LENGTH_LONG).show();
                     }
                         
                     if (requestCode == REQUEST_CODE_RECORD) 
                     {
              newFile = newFile + ".3ga";
                     file_name = path + newFile;
                         
                     File from = new File(path,oldFile);
                     File to = new File(path,newFile);
                     from.renameTo(to);
              //new Upload_FTP().execute(file_name);
                     Utility.setUploadAvailable();
                  
              //email option
              send_media_via_email("audio");
                  
              //Toast.makeText(HomeScreen.this, "Audio saved", Toast.LENGTH_LONG).show();
                     }
                         
                   //copy file to /GT/r directory so that local user can view the image
                 copyFile(GTConstants.sendfileFolder, newFile, GTConstants.receivefileFolder);
                     
                 //this needs to be sent to clear the deleted image from the gallery memory - otherwise would have to wait for reboot of phone
                 sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri .parse("file://" + Environment.getExternalStorageDirectory())));
               }
            });
                
            //if no tag is added then leave the filename alone, it was set during initial save (although issue still exists with audio filename!!!).
            dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
            {
                 public void onClick(DialogInterface dialog, int which) 
                 {
                    //copy file to /GT/r directory so that local user can view the image
                    File file = new File(file_name);
                  copyFile(GTConstants.sendfileFolder, file.getName(), GTConstants.receivefileFolder);
                      
                  //this needs to be sent to clear the deleted image from the gallery memory - otherwise would have to wait for reboot of phone
                  sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri .parse("file://" + Environment.getExternalStorageDirectory())));
                      
                    //new Upload_FTP().execute(file_name);
                  Utility.setUploadAvailable();
                        
                    //email option
                    if (requestCode == REQUEST_CODE_RECORD)send_media_via_email("audio");
                    if (requestCode == CAMERA_PIC_REQUEST) send_media_via_email("photo");
                    if (requestCode == ACTION_TAKE_VIDEO)  send_media_via_email("video"); 
                 } 
             });
            dialog.show();
            */
        }

    }

    //send an email
    private void send_media_via_email(final String type) {
        //only send email if "allowed"
        if (Utility.allowSend(HomeScreen.this)) {
            AlertDialog.Builder dialog = new AlertDialog.Builder(HomeScreen.this);
            dialog.setTitle("email the media?");
            dialog.setMessage("Enter Email address");
            final EditText input = new EditText(this);
            dialog.setView(input);

            dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String emailAddress = input.getText().toString().trim();
                    File current_file = new File(file_name);
                    //String attachment = GTConstants.receivefileFolder + current_file.getName();
                    ArrayList<String> mediaList = new ArrayList<String>();
                    mediaList.add(GTConstants.receivefileFolder + current_file.getName());

                    if (type.equalsIgnoreCase("audio"))
                        Utility.send_email(HomeScreen.this, emailAddress, mediaList, "audio",
                                "email from GT android App",
                                "This email is being sent directly from the GuardTrax - Android App");
                    if (type.equalsIgnoreCase("photo"))
                        Utility.send_email(HomeScreen.this, emailAddress, mediaList, "photo",
                                "email from GT android App",
                                "This email is being sent directly from the GuardTrax - Android App");
                    if (type.equalsIgnoreCase("video"))
                        Utility.send_email(HomeScreen.this, emailAddress, mediaList, "video",
                                "email from GT android App",
                                "This email is being sent directly from the GuardTrax - Android App");
                }
            });

            //if no email to be sent then exit
            dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            dialog.show();
        }
    }

    //Method to save the data from PreferenceDB to GTConstants 
    private void saveInConstants(Cursor c) {
        //PreferenceClass.setValue(c.getString(1),c.getString(2),c.getString(3),c.getString(4), c.getString(5), c.getString(6),Integer.parseInt(c.getString(7)));

        GTConstants.LOCATIONUPDATESINTERVAL = c.getString(1);
        GTConstants.LOCATIONUPDATEDISTANCEINTERVAL = c.getString(2);
        GTConstants.SERVERIP = c.getString(3);
        GTConstants.SERVERPORT = Integer.parseInt(c.getString(4));
        GTConstants.PANIC_NUMBER = c.getString(5);
        GTConstants.UNIQUE_ID = c.getString(6);
        GTConstants.ACCELEROMETER_SPEED = Integer.parseInt(c.getString(7));
        GTConstants.LICENSE_ID = c.getString(8);
        GTConstants.PHONE_TYPE = c.getString(9);
        GTConstants.REGISTRATION = c.getString(10);
        c.close();

        //Retrieve last saved user name from preferences 
        SharedPreferences settings = getSharedPreferences("GTPrefs", 0);
        GTConstants.report_name = settings.getString("userName", "Guard");

        //Toast.makeText(HomeScreen.this, GTConstants.PHONE_TYPE, Toast.LENGTH_LONG).show();
        //Toast.makeText(HomeScreen.this, GTConstants.REGISTRATION, Toast.LENGTH_LONG).show();

    }

    //Method to show alert
    private void showAlert(final String title, final String message, boolean OKOnly) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(HomeScreen.this);
        dialog.setCancelable(false);
        dialog.setTitle(title);
        dialog.setMessage(message);
        dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int place) {
                //if device not registered go straight to scan screen
                if (!Utility.deviceRegistered())
                    scan_click(false);

                //if OK entered from updateSync then reboot
                if (restartsyncTimer) {
                    Intent restartIntent = getPackageManager().getLaunchIntentForPackage(getPackageName());
                    PendingIntent intent = PendingIntent.getActivity(HomeScreen.this, 0, restartIntent,
                            Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                    manager.set(AlarmManager.RTC, System.currentTimeMillis() + 500, intent);
                    System.exit(2);
                }

                if (taa == 5) {
                    taa = 3; //when returning to onResume from signature screen this will execute specific code inside onResume
                    signaturefileName = Utility.createSignatureFileName();
                    Intent intent = new Intent();
                    intent.setClass(HomeScreen.this, SignatureScreen.class);
                    intent.putExtra("file_name", Utility.getsharedPreference(HomeScreen.this, "signaturefileName"));
                    startActivity(intent);
                }
            }
        });

        if (!OKOnly) {
            dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int place) {
                    if (taa == 5) {
                        taa = 3; //tells onResume to execute end shift code
                        onResume();
                    }
                }
            });
        }
        dialog.show();
    }

    //this runs the incident report screen
    Runnable incidentreportScreen = new Runnable() {
        public void run() {

            Intent intent = new Intent();
            intent.setClass(HomeScreen.this, ReportScreen.class);
            intent.putExtra("type", "Incident Report");
            intent.putExtra("incident", incidentDescription);
            intent.putExtra("fromFile", "no");

            if (trafficIncident) {
                intent.putExtra("traffic", "yes");
                trafficIncident = false;
            } else
                intent.putExtra("traffic", "no");

            startActivity(intent);
        }
    };

    Runnable createNote = new Runnable() {
        public void run() {
            Intent intent = new Intent();
            intent.setClass(HomeScreen.this, ReportScreen.class);
            intent.putExtra("type", "Activity Report");
            intent.putExtra("incident", "");
            intent.putExtra("fromFile", "no");
            intent.putExtra("fileName", "");
            intent.putExtra("traffic", "no");
            startActivity(intent);
        }
    };

    //method to create Yes No dialog
    private void showYesNoAlert(String title, String message, final Runnable func) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(HomeScreen.this);

        dialog.setTitle(title);
        dialog.setMessage(message);
        dialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int place) {
                func.run();
            }
        });

        dialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int place) {
                trafficIncident = false;
            }
        });
        dialog.show();
    }

    //Method to show images in dialog box
    public void showImage() {

    }

    /*
    //method to navigate from current screen to Option screen
    private void switchTabSpecial(int index) 
    {
          TabScreen ParentActivity = (TabScreen) this.getParent();
          ParentActivity.switchTabSpecial(index);
              
    }
    */

    //method to shut down service
    private void stopService() {
        if (GTConstants.service_intent != null) {
            //first stop the main service from running - this kills all of the timers
            stopService(new Intent(HomeScreen.this, MainService.class));
        }
    }

    //method called to start the service in background
    private void initService() {

        if (GTConstants.service_intent != null) {
            //first stop the main service from running - this kills all of the timers
            stopService(new Intent(HomeScreen.this, MainService.class));
        }

        //now restart the main service with the new values this code starts the main service running which contains all the event timers
        GTConstants.service_intent = new Intent(HomeScreen.this, MainService.class);
        startService(GTConstants.service_intent);

        /*
        Intent service_intent = new Intent(HomeScreen.this, MainService.class);
        startService(service_intent);
        */

    }

    //To Synchronize the Undelivered data and update it to Database
    private void syncDB() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
            new SyncDataFromDB().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        else
            new SyncDataFromDB().execute();

    }

    //Check for new files to download from FTP site
    private void syncFTP() {
        //new Download_FTP().execute();
        //do not sync if dummy registration is in place
        if (Utility.deviceRegistered()) {
            if (ftpDownload == null) {
                ftpDownload = new Download_FTP(HomeScreen.this);

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                    ftpDownload.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                else
                    ftpDownload.execute();
            }
        }
    }

    //To Synchronize the Undelivered data and update it to Database
    private void syncftpUpload() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
            new Upload_FTP(HomeScreen.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        else
            new Upload_FTP(HomeScreen.this).execute();
    }

    private void send_event(final String eventCode) {
        //this is the application started event - sent once when application starts up
        Thread newThread = new Thread() {
            public void run() {
                String udpMessage = "";

                //Looper.prepare();
                //Utility.Sleep(3000);

                //treat power up message separately 
                if (eventCode.equalsIgnoreCase("PU")) {
                    boolean fileTransfer = false;

                    //transfer any leftover dar files to send directory
                    //if(Utility.isfilewithexExists("/GT/temp", "dar") || Utility.isfilewithexExists("/GT/temp", "tar"))
                    //{
                    List<String> temp = Utility.get_saved_file_names("/GT/temp", false, true, "*");
                    if (!temp.isEmpty()) {
                        for (int i = 0; i < temp.size(); i++) {
                            if (!temp.get(i).toString().equalsIgnoreCase(GTConstants.darfileName)
                                    || !temp.get(i).toString().equalsIgnoreCase(GTConstants.srpfileName)) //do not send the current dar or srp
                            {
                                //write the event 19 information to the file
                                String GM = Utility.getHeaderMessage("$GM") + ",19," + getCellID();
                                Utility.write_to_file(HomeScreen.this,
                                        GTConstants.dardestinationFolder + temp.get(i), GM + "\r\n", true);

                                //give time for file write
                                Utility.initializeGeneralTimer(2000);
                                do {
                                    Utility.Sleep(100);
                                } while (!Utility.fileAccessComplete() && !Utility.getgeneraltimerFlag());

                                //move the file to the send folder
                                File from = new File(GTConstants.dardestinationFolder, temp.get(i).toString());

                                //change the file name to match the $GM time and date
                                String parse[] = GM.split(",");
                                String newFile = GTConstants.LICENSE_ID.substring(7) + "_" + parse[10] + "_"
                                        + parse[2];
                                if (temp.get(i).contains(".srp"))
                                    newFile = newFile + "_srp.srp";
                                if (temp.get(i).contains(".dar"))
                                    newFile = newFile + ".dar";

                                File to = new File(GTConstants.sendfileFolder, newFile);
                                from.renameTo(to);

                                fileTransfer = true;
                            }
                        }
                    }

                    if (fileTransfer)
                        Utility.setUploadAvailable();
                    //}

                    udpMessage = Utility.getPowerUpMessage();
                } else
                    udpMessage = Utility.getHeaderMessage("$GM") + "," + eventCode + "," + getCellID();

                sendCodeToDatabase(udpMessage, false);

                //prevent data from being sent until a start shift code is entered
                //if(eventCode.equals("93") || eventCode.equalsIgnoreCase("PU"))send_data = false;
                if (eventCode.equals("93")) {
                    GTConstants.sendData = false;
                }
            }

        };
        newThread.start();
    }

    //method to send the Message code to Server and Update in Database with status - THIS METHOD MUST BE CALLED FROM A THREAD!!!!!!
    private void sendCodeToDatabase(String messageUDP, boolean sync) {
        //send the data - first make sure that no current transmissions are taking place
        int i = 0;
        boolean flag = false;

        do {
            if (!Utility.isTransmitBusy())
                flag = Utility.sendUDPDataToServer(HomeScreen.this, messageUDP, true, sync);

            Utility.Sleep(500);
        } while (Utility.isTransmitBusy() && i++ < 10);

        //if a start shift was entered, this dismisses the dialog box
        start_shift_wait = false;

        //if a parameter was changed then restart services
        if (Utility.getparamChange()) {
            Utility.resetparamChange();
            stopService();
            initService();
        }

        if (Utility.getmessageString().length() > 0) {
            HomeScreen.this.runOnUiThread(new Runnable() {
                public void run() {
                    MainService.mainserviceDialog("Message", Utility.getmessageString());
                    Utility.resetmessageString();
                }
            });
        }

        //if no response from server AND the device is registered then save the data for future send
        if (!flag && Utility.deviceRegistered()) {
            try {
                date = new Date();
                dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ");
                currentDate = dateFormat.format(date);

                //open the Database to insert the values
                myDatabase.open();

                // insert into Database where status=0
                id = myDatabase.insertRecord(messageUDP, "0", currentDate);

                //close the database
                myDatabase.close();

                HomeScreen.this.runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(HomeScreen.this, "Data stored", Toast.LENGTH_LONG).show();
                    }
                });

            } catch (Exception e) {
                final String eMessage = e.getMessage();
                HomeScreen.this.runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(HomeScreen.this, eMessage, Toast.LENGTH_LONG).show();
                    }
                });

            }
        }
    }

    //method to get the description of the code when the item is selected in the Spinnerbox
    private void initializeSpinnerControl() {
        List<String> SpinnerArray = Utility.getincidentcodeList(HomeScreen.this);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_text, SpinnerArray);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        spinner.setAdapter(adapter);

        //default the spinner to the start shift code set to position 0
        spinner.setSelection(0);

        // Register a callback to be invoked when an item in this AdapterView has been selected
        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedCode = Utility.getkeyCode(HomeScreen.this, position);

                //if traffic violation module then set flag
                if (selectedCode.equalsIgnoreCase(GTConstants.trafficCode))
                    trafficIncident = true;
                //else
                //trafficIncident = false;

                /*
                //start the send code timer, except the first item (start shift) and the default item (usually All Clear)
                if( spinner.getSelectedItemPosition() != 0 && spinner.getSelectedItemPosition() != 2)
                {
                   incidentcodeSent = false;
                   initializenoclickTimer();
                }
                */
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                Toast.makeText(HomeScreen.this, "Please select an Item ", Toast.LENGTH_LONG).show();
            }

        });
    }

    /*
    private void initializeReportSpinnerControl() 
    {
          // Register a callback to be invoked when an item in this AdapterView
          // has been selected
           report_spinner.setOnItemSelectedListener(new OnItemSelectedListener()
          {
     @Override
     public void onItemSelected(AdapterView<?> parent, View view,
           int position, long id) 
     {
        if(position != 0)
        {
           //grab the report type and then set the spinner back to default position before leaving page
           reportType = getResources().getStringArray(R.array.Report_array)[position];
           report_spinner.setSelection(0);
               
           Intent i = new Intent(HomeScreen.this, ReportScreen.class);
             startActivity(i);
        }
     }
        
     @Override
     public void onNothingSelected(AdapterView<?> arg0) 
     {
        Toast.makeText(HomeScreen.this, "Please select an Item ",Toast.LENGTH_LONG).show();
     }
        
          });
    }
    */

    /*
    //moves files from one folder to another - fileName must contain path information
    private void moveFile(String fileName, String oldPath, String newPath)
    {
       //fileName contains path information, so need to remove it 
       //File currentFile = new File(fileName);
       //fileName = currentFile.getName();
           
       //rename the paths
       oldPath = Environment.getExternalStorageDirectory() + oldPath;
       newPath = Environment.getExternalStorageDirectory() + newPath;
           
       //Toast.makeText(HomeScreen.this, oldPath + fileName,Toast.LENGTH_SHORT).show();
       //Toast.makeText(HomeScreen.this, newPath + fileName,Toast.LENGTH_SHORT).show();
           
       File from = new File(oldPath,fileName);
       File to = new File(newPath,fileName);
       from.renameTo(to);
    }
    */

    private void home_screen_toast(final String message, final boolean bshort) {
        HomeScreen.this.runOnUiThread(new Runnable() {
            public void run() {

                if (bshort)
                    Toast.makeText(HomeScreen.this, message, Toast.LENGTH_SHORT).show();
                else
                    Toast.makeText(HomeScreen.this, message, Toast.LENGTH_LONG).show();
            }
        });
    }

    //copy files
    private void copyFile(String inputPath, String inputFile, String outputPath) {
        InputStream in = null;
        OutputStream out = null;

        //get the full name for the paths
        //inputPath = Environment.getExternalStorageDirectory() + inputPath;
        //outputPath = Environment.getExternalStorageDirectory() + outputPath;

        //fileName contains path information, so need to remove it 
        File currentFile = new File(inputFile);
        inputFile = currentFile.getName();

        try {
            in = new FileInputStream(inputPath + inputFile);
            out = new FileOutputStream(outputPath + inputFile);

            byte[] buffer = new byte[1024];
            int read;
            while ((read = in.read(buffer)) != -1) {
                out.write(buffer, 0, read);
            }
            in.close();
            in = null;

            // write the output file (You have now copied the file)
            out.flush();
            out.close();
            out = null;

        } catch (FileNotFoundException fnfe1) {
            Toast.makeText(HomeScreen.this, "File not found", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(HomeScreen.this, "Exception: " + e.toString(), Toast.LENGTH_SHORT).show();
        }

    }

    //get list of all files in the files sub directory GT that contains files that need to be transferred to server
    private List<String> get_saved_file_names(String path) {
        //String file_name = "";
        //String directory_name = Environment.getExternalStorageDirectory() + "/GT/s";
        String directory_name = Environment.getExternalStorageDirectory() + path;

        List<String> sendFiles = new ArrayList<String>();
        File dir = new File(directory_name);
        for (File file : dir.listFiles()) {
            //if (file.getName().endsWith((".jpg")) || file.getName().endsWith((".mpeg")) || file.getName().endsWith((".3ga")))
            sendFiles.add(directory_name + "/" + file.getName());
        }

        return sendFiles;
    }

    //get list of previously downloaded files from ftpfiles data base
    private List<String> get_downloaded_file_names() {
        //create a list
        List<String> downloadedFiles = new ArrayList<String>();

        //open the Database to insert the values
        ftpdatabase.open();

        //put all files into cursor
        Cursor filenames = ftpdatabase.getallRecords();

        //add all file names to list
        filenames.moveToFirst();
        do {
            downloadedFiles.add(filenames.getString(1));

        } while (filenames.moveToNext());

        //close the database
        ftpdatabase.close();

        return downloadedFiles;
    }

    /*
    //check if file exists in data base
    private boolean ftpfileExists(String filename)
    {
       //open the Database to insert the values
       ftpdatabase.open();
            
       //insert records
       boolean exists = ftpdatabase.exists(filename);
              
       //close the database
       ftpdatabase.close();
           
       return exists;
           
    }
    */

    //Store file names downloaded from ftp site in database
    protected void saveInftpDataBase(String filename) {

        //open the Database to insert the values
        ftpdatabase.open();

        // insert records
        ftpdatabase.insertRecord(filename);

        //close the database
        ftpdatabase.close();

    }

    //delete file names downloaded from ftp site in database
    protected void deleteInftpDataBase(String filename) {

        //open the Database to insert the values
        ftpdatabase.open();

        // insert records
        ftpdatabase.deleteRecord_value(filename);

        //close the database
        ftpdatabase.close();

    }

    //Store all file names downloaded from ftp site in database
    protected void replaceftpDataBase(List<String> ftpfileNames) {
        boolean match = false;

        //get all file names from data base
        List<String> dbfileNames = get_downloaded_file_names();

        ftpdatabase.open();
        for (int i = 0; i < dbfileNames.size(); i++) {
            match = false;
            for (int j = 0; j < ftpfileNames.size(); j++) {
                if (dbfileNames.get(i).equalsIgnoreCase(ftpfileNames.get(j))) {
                    match = true;
                    break;
                }
            }
            try {
                if (!match)
                    ftpdatabase.deleteRecord_value(dbfileNames.get(i));
            } catch (Exception e) {
                Toast.makeText(HomeScreen.this, "NM = " + e.toString(), Toast.LENGTH_LONG).show();
            }
        }
        ftpdatabase.close();

    }

    //check whether file exists on server
    private boolean existsftpServer(FTPFile[] ftpFiles, String testFile) {
        for (FTPFile ftpFile : ftpFiles) {
            if (ftpFile.getName().equalsIgnoreCase(testFile))
                return true;
        }
        return false;
    }

    // This Thread checks for Updates in the Background 
    private void checkUpdate() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
            new checkForUpdates().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        else
            new checkForUpdates().execute();
    }

    private class checkForUpdates extends AsyncTask<String, Object, Boolean> {
        @Override
        protected void onPreExecute() {
            //Toast.makeText(HomeScreen.this, "Checking for updates", Toast.LENGTH_SHORT).show();
        }

        @Override
        protected void onPostExecute(Boolean return_value) {
            if (return_value) {
                //String message = "To install update, go to downloads and launch GuardTrax.";
                //showAlert("Update Message", message);
                //Toast.makeText(HomeScreen.this, "Updates downloading", Toast.LENGTH_LONG).show();
            } else
                Toast.makeText(HomeScreen.this, "Update error", Toast.LENGTH_LONG).show();

            firstUpdateCheck = false;

            //checkUpdate();
        }

        @Override
        protected Boolean doInBackground(String... params) {
            try {
                //after initial check, check for updates every day
                //if(!firstUpdateCheck)Utility.Sleep(86400000);

                URL updateURL = new URL("http://android.guardtrax.info/update/update.txt");
                URLConnection conn = updateURL.openConnection();
                InputStream is = conn.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);
                ByteArrayBuffer baf = new ByteArrayBuffer(50);
                int curVersion = 0;
                int current = 0;
                final String currentVersion;
                final String downloadVersion;

                while ((current = bis.read()) != -1) {
                    baf.append((byte) current);
                }

                // Convert the Bytes read to a String.
                final String s = new String(baf.toByteArray());
                final int newVersion = Integer.valueOf(s);

                downloadVersion = s.substring(0, 1) + "." + s.substring(1, 3) + "." + s.substring(3, 5);

                //Get current Version Number 
                curVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
                PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0);
                currentVersion = info.versionName.toString();

                //Check if a newer version is available
                if (newVersion > curVersion) {
                    HomeScreen.this.runOnUiThread(new Runnable() {
                        public void run() {
                            AlertDialog.Builder updateDialog = new AlertDialog.Builder(HomeScreen.this);
                            updateDialog.setTitle("Info");
                            updateDialog.setMessage("Update to version " + downloadVersion + " now?");
                            updateDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            });

                            updateDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Toast.makeText(HomeScreen.this, "Update downloading", Toast.LENGTH_LONG).show();

                                    Intent promptInstall = new Intent("android.intent.action.VIEW",
                                            Uri.parse("http://android.guardtrax.info/GT.apk"));
                                    promptInstall.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    startActivity(promptInstall);
                                }
                            });
                            updateDialog.show();
                        }
                    });
                } else {
                    if (firstUpdateCheck) {
                        HomeScreen.this.runOnUiThread(new Runnable() {
                            public void run() {
                                AlertDialog.Builder updateDialog = new AlertDialog.Builder(HomeScreen.this);
                                updateDialog.setTitle("Info");
                                updateDialog.setMessage("Version " + currentVersion + " is up to date!");
                                updateDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                });
                                updateDialog.show();
                            }
                        });
                    }
                }
            } catch (final Exception e) {
                return false;
            }
            return true;
        }
    }

    private class SyncDataFromDB extends AsyncTask<String, Object, Boolean> {
        //ProgressDialog dialog = new ProgressDialog(HomeScreen.this);

        @Override
        //Runs on the UI thread before doInBackground(Params...).
        protected void onPreExecute() {
            //dialog.setMessage("DataBase is Synchronising");
            //dialog.show();
        }

        @Override
        protected void onPostExecute(Boolean unused) {
            //Toast.makeText(HomeScreen.this, "syncDB done", Toast.LENGTH_SHORT).show();
            //dialog.setMessage("Synchronising Done");
            //dialog.show();
            syncDB();

        }

        //this function syncs the data base and deletes stored data if it syncs
        @Override
        protected Boolean doInBackground(String... params) {
            boolean dataSent = false;
            String dMessage = "";

            //Delay syncing for 30 seconds.  Effectively, this allows for Syncing every minute
            Utility.Sleep(30000);

            try {
                myDatabase.open();
                {
                    cursor = myDatabase.getRecordByStatus("0");
                    if (cursor.moveToFirst()) {
                        do {
                            //get the data
                            dMessage = cursor.getString(1).toString();

                            //if $GG is in the logs then delete it (this is a legacy issue, it should not occur in versions going forward)
                            if (dMessage.contains("$GG,")) {
                                myDatabase.deleteRecord(Long.parseLong(cursor.getString(0)));
                                Utility.Sleep(500);
                            } else {
                                //send the data
                                int i = 0;
                                do {
                                    if (!Utility.isTransmitBusy())
                                        dataSent = Utility.sendUDPDataToServer(HomeScreen.this, dMessage, false,
                                                true);
                                    Utility.Sleep(500);
                                } while (Utility.isTransmitBusy() && i++ < 10);

                                //give time for data to be sent
                                Utility.Sleep(3500);

                                //if data was sent then get the next record to send.  If not stop the process
                                if (dataSent) {
                                    myDatabase.deleteRecord(Long.parseLong(cursor.getString(0)));
                                    Utility.Sleep(500);
                                } else {
                                    cursor.close();
                                    myDatabase.close();

                                    return false;
                                }
                            }
                        } while (cursor.moveToNext());
                    }
                    cursor.close();
                }
                myDatabase.close();

                return true;
            } catch (Exception e) {
                try {
                    cursor.close();
                    myDatabase.close();
                    return false;
                } catch (Exception ex) {
                    return false;
                }
            }
        }
    }

    //upload a file via FTP using background AsyncTask
    private class Upload_FTP extends AsyncTask<String, Object, Boolean> {
        Context cx;

        public Upload_FTP(Context ctx) {
            this.cx = ctx;
        }

        @Override
        protected void onPreExecute() {
            String message = "ftp upload sync";
            if (debug)
                Toast.makeText(HomeScreen.this, message, Toast.LENGTH_SHORT).show();
        }

        @Override
        protected void onPostExecute(Boolean return_value) {
            if (return_value)
                Toast.makeText(HomeScreen.this, "File transferred", Toast.LENGTH_LONG).show();

            //else
            //Toast.makeText(HomeScreen.this, "File transfer delayed", Toast.LENGTH_LONG).show();

            //restart ftp upload syncing
            syncftpUpload();
        }

        @Override
        protected Boolean doInBackground(String... params) {
            Boolean post_success = false;
            //final String file_type = params[0];
            //File file = new File(send_file);
            String send_file = "";
            String ext = "";
            String data = "";
            String event_num = "";
            boolean result = false;
            File file = null;
            FileInputStream in = null;

            //home_screen_toast(file_type);

            //home_screen_toast("ftp async", true);

            try {
                //Wait 1 minute before trying again if not success from last try
                if (Utility.getUploadAvailable())
                    Utility.Sleep(60000);

                //test for unsent files OR wait for a media file to be available and allowSend to be true
                if (Utility.get_saved_file_names("/GT/s", false, false, "*").size() == 0) {
                    do {
                        Utility.Sleep(1000);
                    } while (!Utility.getUploadAvailable() || !Utility.allowSend(cx));
                }

                //home_screen_toast("After wait", true);
                //reset the flag - Moved to below after successful upload
                //Utility.resetUploadAvailable();

                FTPClient ftp = new FTPClient();

                //ftp.connect("96.240.101.7");
                ftp.setConnectTimeout(600);

                ftp.connect(GTConstants.ftpURL);

                if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                    if (ftp.login("ftpconnect", "Renova11")) {
                        if (debug)
                            home_screen_toast("Connected to ftp", true);

                        ftp.enterLocalPassiveMode();

                        //get list of files names at the given location
                        List<String> send_file_list = get_saved_file_names("/GT/s");

                        //get list of all files on server
                        FTPFile[] ftpFiles = ftp.listFiles();

                        for (int i = 0; i < send_file_list.size(); i++) {
                            send_file = send_file_list.get(i);

                            if (!existsftpServer(ftpFiles, send_file)) {
                                //create directory for device to device exchange
                                String directoryName = "/Android/send/" + GTConstants.LICENSE_ID.substring(7);
                                ftp.changeWorkingDirectory(directoryName);

                                //check if directory exists.  If not create it
                                if (ftp.getReplyCode() == 550) {
                                    if (!ftp.makeDirectory(directoryName)) {
                                        //if failed to make directory logout and return
                                        ftp.logout();
                                        ftp.disconnect();
                                        return false;
                                    }
                                }

                                file = new File(send_file);

                                ext = send_file.substring((send_file.lastIndexOf(".") + 1), send_file.length());

                                if (ext.equals("jpg"))
                                    event_num = "16";
                                else if (ext.equals("3ga"))
                                    event_num = "17";
                                else if (ext.equals("mpeg"))
                                    event_num = "18";
                                else if (ext.equals("txt"))
                                    event_num = "19";
                                else if (ext.equals("dar"))
                                    event_num = "20";
                                else
                                    event_num = "21";

                                //now upload the file
                                //ftp.enterLocalPassiveMode();
                                ftp.setFileType(FTP.BINARY_FILE_TYPE);

                                final String send_file_name = send_file.substring(send_file.lastIndexOf("/") + 1);
                                final String parsed[] = send_file_name.split("_");

                                //set up an ftp stream to save the file on the ftp server
                                data = send_file;
                                in = new FileInputStream(new File(data));

                                String ftpfileName = "";

                                if (debug)
                                    home_screen_toast("file = " + send_file_name, true);

                                //if necessary change the filename.  In case of error just send file name as is
                                try {
                                    if (!send_file_name.contains(GTConstants.UNIQUE_ID) || ext.equals("dar")) //if not a "GT" file or a daily activity report file then store it with its given filename
                                        ftpfileName = send_file_name; //result = ftp.storeFile(send_file_name, in);
                                    else if (parsed[parsed.length - 2].contains(".")) //if file does not contain a tag
                                        ftpfileName = GTConstants.LICENSE_ID.substring(7) + "_" + parsed[1] + "_"
                                                + parsed[2] + "." + ext; //result = ftp.storeFile(parsed[0] + "_" + parsed[1] + "_" + parsed[2] + "." + ext, in);   
                                    else //if file does contain a tag
                                        ftpfileName = GTConstants.LICENSE_ID.substring(7) + "_" + parsed[1] + "_"
                                                + parsed[2] + "_" + parsed[parsed.length - 2] + "." + ext; //result = ftp.storeFile(parsed[0] + "_" + parsed[1] + "_" + parsed[2] + "_" + parsed[parsed.length-2] + "." + ext, in);
                                } catch (Exception e) {
                                    ftpfileName = send_file_name;
                                }

                                if (debug)
                                    home_screen_toast("ftp file = " + ftpfileName, true);

                                //save the ftp file onto the ftp server
                                result = ftp.storeFile(ftpfileName, in);

                                if (debug)
                                    if (!result)
                                        home_screen_toast("File not stored", true);

                                //close the ftp file stream
                                in.close();

                                if (result) {
                                    post_success = true;

                                    //reset the flag
                                    Utility.resetUploadAvailable();

                                    //create an event 16, 17 or 18 to let server know media is ready************************************************
                                    if (!event_num.equals("19") && send_file_name.contains(GTConstants.UNIQUE_ID)) {
                                        //get the file IMEI_DATE_TIME
                                        final String messageUDP = Utility.getPhotoHeader(parsed) + "," + event_num
                                                + "," + getCellID();

                                        int ii = 0;
                                        boolean dataSent = false;
                                        do {
                                            if (!Utility.isTransmitBusy())
                                                dataSent = Utility.sendUDPDataToServer(HomeScreen.this, messageUDP,
                                                        false, false);
                                            Utility.Sleep(1000);
                                        } while (Utility.isTransmitBusy() && ii++ < 10);

                                        //if no response from server AND the device is registered then save the data for future send
                                        if (!dataSent && Utility.deviceRegistered()) {
                                            try {
                                                date = new Date();
                                                dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ");
                                                currentDate = dateFormat.format(date);

                                                myDatabase.open();
                                                id = myDatabase.insertRecord(messageUDP, "0", currentDate);
                                                myDatabase.close();

                                            } catch (Exception e) {
                                                if (debug)
                                                    home_screen_toast("error: " + e.toString(), false);
                                            }
                                        }
                                    }
                                    //end of sending event**********************************************************************************************

                                    //now delete copy from local /GT/s directory
                                    file.delete();
                                    file = null;
                                    in = null;
                                } else {
                                    post_success = false;
                                    //break;
                                }
                            }
                        }

                        ftp.logout();
                    }
                    ftp.disconnect();
                }

            } catch (Exception e) {
                //home_screen_toast("error: " + e.toString(), false);
                if (debug)
                    home_screen_toast("error: " + e.toString(), false);
                post_success = false;
            }

            return post_success;
        }

    }

    //download a file via FTP using background AsyncTask
    private class Download_FTP extends AsyncTask<String, Object, Boolean> {
        Context cx;

        public Download_FTP(Context ctx) {
            this.cx = ctx;
        }

        @Override
        protected void onPreExecute() {
            if (debug)
                Toast.makeText(HomeScreen.this, "Starting ftp sync", Toast.LENGTH_SHORT).show();
        }

        @Override
        protected void onPostExecute(Boolean return_value) {
            if (return_value) {
                if (debug)
                    Toast.makeText(HomeScreen.this, "FTP download success", Toast.LENGTH_SHORT).show();
                long[] pattern = { 1000, 500 };
                Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                vibrator.vibrate(pattern, -1);

                final ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 500);
                tg.startTone(ToneGenerator.TONE_PROP_ACK);
                Utility.Sleep(500);
                tg.startTone(ToneGenerator.TONE_PROP_ACK);

                /*
                if(Utility.getpostorderAvailable())
                {
                   Utility.resetpostorderAvailable();
                   new_document = true;
                   btn_report_screen.startAnimation(animation);
                }
                */
                //showImage();
            } else
                Toast.makeText(HomeScreen.this, "FTP download error", Toast.LENGTH_SHORT).show();

            //Continuously run syncFTP to look for new images
            ftpDownload = null;
            syncFTP();
        }

        @Override
        protected Boolean doInBackground(String... params) {
            boolean result = false;
            boolean fileMatch = false;
            Boolean receive_success = false;
            BufferedOutputStream fos = null;
            String get_file_name = "";
            String downloadFile = "";
            int rowID = 0;

            try {
                //wait for a media file to be available
                do {
                    Utility.Sleep(1000);
                } while (!Utility.getimageAvailable() || !Utility.allowSend(cx));

                /*
                //get the list of files that need to be down loaded
                  fileArray = Utility.get_all_media_from_ftpdatabase(getApplicationContext());
                      
                  if(fileArray.size() == 0)
                  {
                     Utility.resetimageAvailable();
                     return false;
                  }
                  */

                //get the number of records inside the ftpdatabase
                int dbCount = Utility.get_ftpdatabase_count(getApplicationContext());

                //if per chance database is empty then return - this should never happen but who knows
                if (dbCount == 0) {
                    Utility.resetimageAvailable();
                    return false;
                }

                FTPClient ftp = new FTPClient();

                ftp.connect(GTConstants.ftpURL);

                if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                    if (ftp.login("ftpconnect", "Renova11")) {
                        try {
                            if (debug)
                                home_screen_toast("db size: " + String.valueOf(dbCount), true);

                            //run through all rows in db - remember some rows can be blank due to auto increment feature in data base!!!
                            for (rowID = dbCount; rowID > 0; rowID--) {
                                //get the file name to be down loaded from the list
                                downloadFile = Utility.get_mediafile_from_ftpDatabase(getApplicationContext(),
                                        rowID);

                                //check if file name is not blank
                                if (downloadFile.length() > 0) {
                                    //the FTP directory path for each device is set by the devices IMEI number
                                    final String strFTPDirectory = "/Android/send/"
                                            + Utility.getimageIMEIString(downloadFile) + "/";

                                    if (debug)
                                        home_screen_toast("directory: " + strFTPDirectory, true);
                                    if (debug)
                                        home_screen_toast("download: " + downloadFile.substring(10), true);
                                    if (ftp.changeWorkingDirectory(strFTPDirectory)) {
                                        ftp.setFileType(FTP.BINARY_FILE_TYPE);
                                        ftp.enterLocalPassiveMode();

                                        //get list of all files in ftp directory
                                        FTPFile[] getFiles = ftp.listFiles();

                                        for (FTPFile ftpFile : getFiles) {
                                            get_file_name = ftpFile.getName();

                                            fileMatch = false;

                                            //check if file was already down loaded by looking at internal database          
                                            if (get_file_name.contains(downloadFile.substring(10))) {
                                                fileMatch = true;
                                                if (debug)
                                                    home_screen_toast("match file: " + downloadFile, true);

                                                File fileDownload = new File(
                                                        GTConstants.receivefileFolder + get_file_name);
                                                fileDownload.createNewFile();

                                                fos = new BufferedOutputStream(new FileOutputStream(fileDownload));

                                                result = ftp.retrieveFile(get_file_name, fos);

                                                if (result) {
                                                    receive_success = true;
                                                    if (fos != null)
                                                        fos.close();

                                                    //delete the file at the ftp site
                                                    //ftp.deleteFile(get_file_name);
                                                } else {
                                                    receive_success = false;
                                                }

                                                if (debug)
                                                    home_screen_toast("removing matched file: " + downloadFile,
                                                            true);
                                                Utility.remove_mediafile_from_ftpDatabase(getApplicationContext(),
                                                        "", rowID);
                                            }
                                            if (fileMatch)
                                                break;
                                        }
                                        if (!fileMatch) {
                                            if (debug)
                                                home_screen_toast("removing unmatched file: " + downloadFile, true);
                                            Utility.remove_mediafile_from_ftpDatabase(getApplicationContext(), "",
                                                    rowID);
                                        }
                                    } else {
                                        receive_success = false;
                                    }
                                }
                            }
                        } catch (Exception e) {
                            home_screen_toast("ftp error: " + e.toString(), true);
                            receive_success = false;
                        }
                        ftp.logout();
                    }
                    ftp.disconnect();
                }
            } catch (Exception e) {
                receive_success = false;
            }

            if (rowID == 0 && fileMatch) {
                if (debug)
                    home_screen_toast("reseting database", true);

                //reset the data base
                Utility.delete_ftpdatabase(getApplicationContext());

                //reset the image flag
                Utility.resetimageAvailable();
            } else
                Utility.Sleep(6000); //wait 1 minute before trying again
            return receive_success;
        }
    }

    public static class ScreenReceiver extends BroadcastReceiver {
        public static boolean wasScreenOn = true;

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
                // do whatever you need to do here
                wasScreenOn = false;
            } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
                // and do whatever you need to do here
                wasScreenOn = true;
            }
        }
    }

    /*
    private void display_dialog(String message)
    {
       AlertDialog.Builder dialog = new AlertDialog.Builder(HomeScreen.this);
       dialog.setTitle("Message");
       dialog.setMessage(message);
           
       dialog.setPositiveButton("OK",new DialogInterface.OnClickListener() 
       {
          @Override
          public void onClick(DialogInterface dialog,int which) 
          {
     //do nothing
          }
       });
           
       dialog.show();
           
    }
    */

    String getPhoneType() {
        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

        int phoneType = telephonyManager.getPhoneType();
        switch (phoneType) {
        case TelephonyManager.PHONE_TYPE_NONE:
            return "NONE";

        case TelephonyManager.PHONE_TYPE_GSM:
            return "GSM";

        case TelephonyManager.PHONE_TYPE_CDMA:
            return "CDMA";

        /*
         *  for API Level 11 or above
         *  case TelephonyManager.PHONE_TYPE_SIP:
         *   return "SIP";
         */

        default:
            return "UNKNOWN";
        }
    }

    //Method to return the CellID
    public static String getCellID() {
        return GTConstants.cellID;
    }

}

/*
 * private class Upload_Post extends AsyncTask<String, Object, Boolean>  
{
   @Override
protected void onPreExecute() 
{
  String message = "Sending file: " + file_name;
  Toast.makeText(HomeScreen.this, message, Toast.LENGTH_LONG).show();
}
       
   @Override
   protected void onPostExecute(Boolean return_value) 
   {
  if(return_value)
     Toast.makeText(HomeScreen.this, "File Transferred", Toast.LENGTH_LONG).show();
  else
     Toast.makeText(HomeScreen.this, "File error", Toast.LENGTH_LONG).show();
   }
     
@SuppressWarnings("deprecation")
   @Override
protected Boolean doInBackground(String... params) 
{
   Boolean post_success = false;
       
   //upload Server SCRIPT
   //String urlString = "http://www.guardtrax.info/FileTransferAndroid/FileTransfer.aspx";
   //String urlString = "http://filetransfer.guardtrax.com/FileTransferAndroid/FileTransfer.aspx";
   String urlString = "http://filetransfer.guardtrax.com/default.aspx";
       
   //file information
   final String send_file = params[0];
   File file = new File(send_file);
    
   HttpClient httpclient = new DefaultHttpClient();
   HttpPost httppost = new HttpPost(urlString);
    
  MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    
   //Set up the file body
  String ext = send_file.substring((send_file.lastIndexOf(".") + 1), send_file.length());
      
  FileBody fb = new FileBody(file, "unknown");
  if(ext.equals("3ga")) 
     fb = new FileBody(file, "audio/3gpp");
  else if(ext.equals("jpg")) 
     fb = new FileBody(file, "image/jpeg");
  else if(ext.equals("mpeg")) 
     fb = new FileBody(file, "video/mpeg");
  else
     return false;
      
   FormBodyPart bodyPart = new FormBodyPart("uploadedfile",fb);
   reqEntity.addPart(bodyPart);
   httppost.setEntity(reqEntity);
       
   //SERVER RESPONSE
   try 
   {
      final HttpResponse response = httpclient.execute(httppost);
      if(response.getStatusLine().getStatusCode() == 200)post_success = true;
          
      HomeScreen.this.runOnUiThread(new Runnable() {
         public void run() {
            Toast.makeText(HomeScreen.this, String.valueOf(response.getStatusLine().getStatusCode()), Toast.LENGTH_SHORT).show();
            Toast.makeText(HomeScreen.this, String.valueOf(response.getStatusLine().getReasonPhrase()), Toast.LENGTH_LONG).show();
         }
     });
          
   } catch (ClientProtocolException e) 
   {
       return false;
   } catch (IOException e) 
   {
       return false;
   }
    return post_success;
}
     
}*/

/*
 * //method to register the receiver to send code to server when SMS is received
private void registerReceiverForTextReceived() 
{
  textReceivedService = new BroadcastReceiver() 
  {
     //This method is called when the BroadcastReceiver is receiving an Intent broadcast.
     public void onReceive(Context context, Intent intent) 
     {
        if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) 
        {
           Bundle bundle = intent.getExtras();
            if (bundle != null) 
            {
                Object[] pdus = (Object[])bundle.get("pdus");
                final SmsMessage[] messages = new SmsMessage[pdus.length];
                for (int i = 0; i < pdus.length; i++)  messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                    
                if (messages.length > -1) 
                {
                    //Toast.makeText(HomeScreen.this, "Message from: " + messages[0].getOriginatingAddress(), Toast.LENGTH_LONG).show();
                        
                        
                    //showAlert("SMS from: " + messages[0].getOriginatingAddress(),messages[0].getMessageBody());
                    String temp = messages[0].getOriginatingAddress();
                    if(temp.contains("908") && temp.contains("279") && temp.contains("0847"))
                    {
                       //broadcast toast
                       Toast.makeText(HomeScreen.this, "GuardTrax Message: " + messages[0].getMessageBody(), Toast.LENGTH_LONG).show();
                           
                       //show home screen dialog
                       showAlert(gtsmsMessage,messages[0].getMessageBody());
                       send_event("70");
                    }
                       
                }
            }
        }
     }
  };
      
  //An IntentFilter can match against actions, categories, and data(either via its type, scheme, and/or path) in an Intent.
  IntentFilter textReceivedFilter = new IntentFilter();
  textReceivedFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
  registerReceiver(textReceivedService, textReceivedFilter);
}
*/