package fsenablers.android.activity;

import java.io.File;
import java.io.FileInputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.Manifest;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerFuture;
import android.app.Activity;
import android.app.DialogFragment;
import android.app.FragmentManager;
import android.app.NotificationManager;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.Uri;
import android.net.Uri.Builder;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;



import fsenablers.android.BuildConfig;
import fsenablers.android.R;

import fsenablers.android.http.HttpUploadRequest;
import fsenablers.android.http.HttpUploadTask;
import fsenablers.android.settings.EditSettingsDialogFragment;
import fsenablers.android.utilities.DeviceHelper;


public class WebAppActivity extends Activity implements SensorEventListener {
	public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
	public final static int PICK_CONTACT_REQUEST = 100;
	private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 101;
	private static final int SPEECH_RECOGNITION_REQUEST_CODE = 102;


    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;

    private static final String TAG = "WebAppActivity";

	private String currentScanTxId = null;
	private MyWebInterface mwf = null;
	private MyWebViewClient wvc = null;

	boolean bNewIntent = false;

	long lastSensorUpdate = System.currentTimeMillis();
	float sensorLastX = 0.0f;
	float sensorLastY = 0.0f;
	float sensorLastZ = 0.0f;

	private static final int SHAKE_THRESHOLD = 1500;

	SensorManager mSensorManager;
	Sensor mAccelerometer;

	private String mHost;


	private boolean checkIfAlreadyHavePermission() {
		int result = ContextCompat.checkSelfPermission(this, Manifest.permission.GET_ACCOUNTS);
		if (result == PackageManager.PERMISSION_GRANTED) {
			return true;
		} else {
			return false;
		}
	}

	private void requestForSpecificPermission() {
		//Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS, ,  Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE
		//Manifest.permission.GET_ACCOUNTS
		ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 101);
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
		switch (requestCode) {
			case 101:
				if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
					//granted
				} else {
					//not granted
				}
				break;
			default:
				super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		}
	}


	public List<String> getDocRootList() {


		return wvc.getDocRootList();

	}

	public String getDataFolderName() {
		return "FSEnablers";
	}

	// geo callback?
	public void invoke(String origin, boolean allow, boolean remember) {

	}

    @Override
	protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);


        if( BuildConfig.DEBUG ) { Log.d( TAG, "onCreate" );}


     // Get an instance of the SensorManager
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
		mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

        setContentView(R.layout.activity_webapp);

		if (!checkIfAlreadyHavePermission()) {
			requestForSpecificPermission();
		}

   	 	if( savedInstanceState == null ) {


   	 		WebView myWebView = getWebView();

	   	 	WebSettings webSettings = myWebView.getSettings();

	   	 	StringBuffer userAgentBuffer = new StringBuffer( webSettings.getUserAgentString());

	   	 	userAgentBuffer.append(  DeviceHelper.getUserAgentSuffix( this ));
	   	 	webSettings.setUserAgentString( userAgentBuffer.toString() );
	   	 	webSettings.setDatabaseEnabled( true );
	   	    webSettings.setGeolocationEnabled( true );
		    File databaseDBPath = new File(Environment.getDataDirectory(), getDataFolderName() + "/databases" );
		    // This location works best if you want the created images to be shared
		    // between applications and persist after your app has been uninstalled.

		    // Create the storage directory if it does not exist
		    if (! databaseDBPath.exists()){
		        if (! databaseDBPath.mkdirs()){
		            Log.e( TAG, "failed to create directory " + databaseDBPath );
		            // return null;
		        }
		    }
		    if( BuildConfig.DEBUG ) { Log.d(TAG, "DB Path is " + databaseDBPath );}
		    webSettings.setDatabasePath( databaseDBPath.toString() );
	   	    webSettings.setGeolocationDatabasePath( databaseDBPath.toString() + "/geo" );

	   	 	webSettings.setJavaScriptEnabled( true );
	   	 	webSettings.setSavePassword( false );
	   	 	WebChromeClient wcc = new MyChromeClient();
	   	 	myWebView.setWebChromeClient( wcc );

	   	 	wvc = new MyWebViewClient( this );
	   	 	myWebView.setWebViewClient( wvc );

	   	 	mwf = new MyWebInterface( this );
	   	 	myWebView.addJavascriptInterface( mwf, "FSEAndroid") ;

			myWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
			myWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

			if (Build.VERSION.SDK_INT >= 19) {
				// chromium, enable hardware acceleration
				myWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
			} else {
				// older android version, disable hardware acceleration
				myWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
			}

			myWebView.loadUrl( getBootStrapUrl() );

   	 	} else {

   	 		if( BuildConfig.DEBUG ) { Log.d( TAG, "Saved = " + savedInstanceState.getString( "saved"));}
   	 	}
   	 	// tts = new TextToSpeech(this, this);


    }

    WebView getWebView() {
    	MyWebViewFragment mwvf = (MyWebViewFragment) getFragmentManager().findFragmentById( R.id.webview_fragment );
   	 	return mwvf.getWebView();
    }

    public String getDocRootUrl() {

    	// Restore preferences
        SharedPreferences settings = getSharedPreferences( Constants.PREFERENCES_SETTINGS, 0);


        String sDocRootUrl = settings.getString( Constants.SETTINGS_DOCROOT_URI, getDefaultDocRootUrl() );

        return sDocRootUrl;

    }

    public String getDefaultDocRootUrl() {
    	return Constants.DEFAULT_DOCROOT_URI;
    }

    public String getHost() {
    	if( mHost == null ) {
    		Uri uri = Uri.parse( getDocRootUrl() );
    		mHost = uri.getHost();
    	}

    	return mHost;
    }

    private String getBootStrapUrl() {

    	Uri uri = Uri.parse( getDocRootUrl() );

    	Builder uriBuilder = uri.buildUpon();


    	if( ! "true".equalsIgnoreCase( uri.getQueryParameter( "native" )) ) {
    		uriBuilder.appendQueryParameter( "native", "true" );
    	}
    	uriBuilder.appendQueryParameter( "native_platform", DeviceHelper.getPlatform( this ) );
    	uriBuilder.appendQueryParameter( "native_format", DeviceHelper.getFormat( this ) );
    	uriBuilder.appendQueryParameter( "native_device", DeviceHelper.getName( this ) );




    	return  uriBuilder.build().toString();

    }

    public void reloadWebView() {

    	WebView myWebView = getWebView();

//    	String sUrl = getDocRootUrl() + "?native=true&platform=android";
//        
//    	Uri uri = Uri.parse( getDocRootUrl() );
//    	
//    	Builder uriBuilder = uri.buildUpon();
//    	
//    	
//    	if( ! "true".equalsIgnoreCase( uri.getQueryParameter( "native" )) ) {
//    		uriBuilder.appendQueryParameter( "native", "true" );
//    	}
//    	uriBuilder.appendQueryParameter( "platform", DeviceHelper.getPlatform( this ) );



    	String sUrl = getBootStrapUrl();

    	if( BuildConfig.DEBUG ) { Log.d( TAG, "Loading " + sUrl );}
    	myWebView.clearCache( true );
        myWebView.loadUrl(sUrl);

    }

    public void setDocRootUrl( String sUrl ) {

    	// We need an Editor object to make preference changes.
	    // All objects are from android.context.Context
	    SharedPreferences settings = getSharedPreferences( Constants.PREFERENCES_SETTINGS, 0);




	      try {


	    	  URL url = new URL ( sUrl );
	    	  SharedPreferences.Editor editor = settings.edit();
	    	  editor.clear();
	    	  editor.putString( Constants.SETTINGS_DOCROOT_URI, url.toString() );
	    	  // Commit the edits!
	          boolean bResult = editor.commit();

	          if( BuildConfig.DEBUG ) { Log.d( TAG, "setDocRootUrl(" + url + ") = " + bResult);}

	          mHost = Uri.parse( sUrl ).getHost();


	          this.runOnUiThread(
	        		new Runnable() {
	        			public void run() {
	        				reloadWebView();
	        			}
	        		}

	          );

	          // reloadWebView();


	      } catch ( MalformedURLException mux ) {
	    	  Log.e( TAG, "setDocRootUrl Failed: " + mux.getMessage());
	      }



    }



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

    	if( BuildConfig.DEBUG ) { Log.d( TAG, "onSaveInstanceState" );}


    	WebView wv = getWebView();
    	//wv.saveState(outState);

    	// getFragmentManager().findFragmentById( R.id.webview_fragment );

    	outState.putParcelable( "mwfState", mwf.getCurrentState());

    	outState.putString( "saved", "true" );

    }

    public void onRestoreInstanceState( Bundle savedInstanceState ) {

    	super.onRestoreInstanceState( savedInstanceState );

    	WebView wv = getWebView();
    	//wv.restoreState( savedInstanceState );

    	WebSettings webSettings = wv.getSettings();
   	 	webSettings.setJavaScriptEnabled(true);
   	 	WebChromeClient wcc = new WebChromeClient();
   	 	wv.setWebChromeClient( wcc );

   	 	MyWebViewClient wvc = new MyWebViewClient( this );
   	 	wv.setWebViewClient( wvc );



   	 	mwf = new MyWebInterface( this );



   	 	Bundle mwfState = savedInstanceState.getParcelable( "mwfState" );
   	 	mwf.setCurrentState( mwfState );

   	 	wv.addJavascriptInterface( mwf, "FSEAndroid") ;

   	 	if( BuildConfig.DEBUG ) { Log.d( TAG, "onRestoreInstanceState - " + savedInstanceState.getString( "saved" ));}



    }

    protected void onNewIntent( Intent intent ) {
    	if( BuildConfig.DEBUG ) { Log.d( TAG, "onNewIntent" );}
    	bNewIntent = true;
    	setIntent( intent );
    }
    @Override
    public void onStop() {
    	if( BuildConfig.DEBUG ) { Log.d( TAG, "onStop" );}
    	super.onStop();
    }

    @Override
    public void onStart() {

    	super.onStart();
    	if( BuildConfig.DEBUG ) { Log.d( TAG, "onStart" );}

    }

    @Override
    public void onDestroy() {

    	super.onDestroy();
    	if( BuildConfig.DEBUG ) { Log.d( TAG, "onDestroy" );  }
    	mwf.onDestroy();
    	mwf = null;
    }
    @Override

    public void onPause() {
    	super.onPause();
    	if( BuildConfig.DEBUG ) { Log.d( TAG, "onPause" );}
    	mSensorManager.unregisterListener(this);
    }
    @Override
    public void onResume(){

    	super.onResume();
    	if( BuildConfig.DEBUG ) { Log.d( TAG, "onResume" );}

    	mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL );

    	// cancel all notifications for this application
    	((NotificationManager)getSystemService( Context.NOTIFICATION_SERVICE )).cancelAll();


    	if( ! bNewIntent ) {
    		return;
    	}

    	bNewIntent = false;
    	Intent intent = getIntent();

    	if (Intent.ACTION_SEND.equals(intent.getAction())){
    		Uri uri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
    		if (uri != null) {
    			// fileset = new HashSet();
    			if( BuildConfig.DEBUG ) { Log.d( TAG, "SEND: " + uri ); }

    			int n = 0;
	    	    try {
	    	    	n = n + 1;

	    	    	FileInputStream strm;

//	    	    	String path = getPathfromUri( uri );
//	    	    	if( path != null ) {
//	    	    		strm = new FileInputStream( path );
//	    	    	} else {


	    	    		String mimeType = getContentResolver().getType( uri );
	    	    		if( BuildConfig.DEBUG ) { Log.d( TAG, "mimeType = " + mimeType );}
	    	    		AssetFileDescriptor afd = getContentResolver().openAssetFileDescriptor( uri, "r" );
	    	    		if( BuildConfig.DEBUG ) { Log.d("MyApp", "AFD: " + afd.toString());}
	    	    		strm = afd.createInputStream();
	    	    		if( BuildConfig.DEBUG ) { Log.d( TAG, "bytesAvailable 1: " + strm.available() );}
	    	    //	}

	    	    	//FileInputStream fstrm = new FileInputStream( getPathfromUri(uri) );

	    	    	HttpUploadRequest uploadRequest = new HttpUploadRequest( this, null, getDocRootUrl() + "/act_upload.cfm", null, null, strm, "upload-" + n + ".jpg", "my title", "my description");

	    	    	HttpUploadTask uploadTask = new HttpUploadTask( this );

	    	    	uploadTask.execute(uploadRequest);

	    	     } catch( Exception x ) {
	    	    	 x.printStackTrace();
	    	    	 // Log.e( "MyApp", x.getMessage() );
	    	     }
    		}
    	} else if (Intent.ACTION_SEND_MULTIPLE.equals(intent.getAction())) {
    		ArrayList<Uri> uris= intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
    		if (uris != null) {
		        //fileset = new HashSet();
    			if( BuildConfig.DEBUG ) {
			        for(Uri uri : uris) {
			        	Log.d( TAG, "SEND: " + getPathfromUri(uri));
			        }
    			}
    	    }
    	}



    }

    public void onFinishEditSettings( boolean bSaved, String sUrl ) {

    	mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL );
    	if( bSaved ) {
    		setDocRootUrl( sUrl );
    	}

    }

    private String getPathfromUri(Uri uri) {
    	 if(uri.toString().startsWith("file://"))
    	       return uri.getPath();
    	 String[] projection = { MediaStore.Images.Media.DATA };

    	 // Cursor cursor = managedQuery(uri, projection, null, null, null);
    	 // startManagingCursor(cursor);

    	 CursorLoader loader = new CursorLoader( this, uri, projection, null, null, null );
    	 Cursor cursor = loader.loadInBackground();


    	 int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    	 cursor.moveToFirst();
    	 String path= cursor.getString(column_index);
    	 //cursor.close();
    	 return path;
    	}



    @Override
    /* turned off for public publication - 07182013 - mwg */
    public boolean onCreateOptionsMenu(Menu menu) {

    	boolean bMenuEnabled = false;

    	if( bMenuEnabled ) {
	        // Inflate the menu; this adds items to the action bar if it is present.
	        getMenuInflater().inflate(R.menu.activity_webapp, menu);
	        if( BuildConfig.DEBUG ) { Log.d( TAG, "Menu Created" );}
	        return true;
    	} else {
    		return super.onCreateOptionsMenu( menu );
    	}

    }


    public boolean onOptionsItemSelected(MenuItem item) {

    	int iItemId = item.getItemId();

    	if( iItemId == R.id.menu_settings ) {

    		// app icon in action bar clicked; go home
            //Intent intent = new Intent(this, HomeActivity.class);
            //intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            //startActivity(intent);
    		if( BuildConfig.DEBUG ) { Log.d( TAG, "Settings..." );}

        	DialogFragment newFragment = new EditSettingsDialogFragment();
        	FragmentManager fm = getFragmentManager();
            newFragment.show( fm, "settings");

            return true;

        /*
    	} else if ( iItemId == R.id.menu_login ) { 
    		
        	Intent i = new Intent( this, AuthenticatorActivity.class );
        	startActivity( i );
        	
        	return true;      
        */

    	} else {

    		return super.onOptionsItemSelected(item);

    	}
    	
    	/* this was the original way but it doesn't work if this is a library project 
        switch (item.getItemId()) {
            case R.id.menu_settings:
                // app icon in action bar clicked; go home
                //Intent intent = new Intent(this, HomeActivity.class);
                //intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                //startActivity(intent);
            	Log.d( TAG, "Settings..." );
            	

            	
            	DialogFragment newFragment = new EditSettingsDialogFragment();
            	FragmentManager fm = getFragmentManager();
                newFragment.show( fm, "settings");
                
                return true;
     
            default:
                return super.onOptionsItemSelected(item);
        }
        */

    }





    void testFunction( String sMessage ) {

    	WebView aWebView = getWebView();


    	aWebView.loadUrl( "javascript:setMessage('" + sMessage + "')");

    }

    private void editSettings() {

    	if( BuildConfig.DEBUG ) { Log.d( TAG, "Settings..." );}
    	
    	/*
    	Intent i = new Intent( this, EditSettingsDialog.class );
    	startActivity( i );
    	*/

    	DialogFragment newFragment = new EditSettingsDialogFragment();
    	FragmentManager fm = getFragmentManager();
        newFragment.show( fm, "settings");

    }
    /*
    void startVoiceRecognitionActivity(){
    	 
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Voice recognition Demo...");
        startActivityForResult(intent, SPEECH_RECOGNITION_REQUEST_CODE );
    }
 	*/
    
    /*
    void takePicture( String sTxId ) {

    	
    	Intent intent = new Intent(this, CameraActivity.class);
    	intent.putExtra( "sTxId", sTxId );
    	startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE );
    	
    }*/



    public void login( View view ) {

    	AccountManager am = AccountManager.get( this );
    	Account accounts[] = am.getAccountsByType( fsenablers.android.login.Constants.ACCOUNT_TYPE  );
    	if( BuildConfig.DEBUG ) {
	    	for( int x = 0; x < accounts.length; x++ ) {
	    		Log.d( TAG, "Account: " + accounts[x].toString() );
	    	}
    	}


    	AccountManagerFuture<Bundle> amf = am.getAuthToken( accounts[0], fsenablers.android.login.Constants.AUTHTOKEN_TYPE, null, this, null, null );

    	try {
    		Bundle b = amf.getResult();
    		if( BuildConfig.DEBUG ) {
	    		Log.d( TAG, b.getString( AccountManager.KEY_ACCOUNT_NAME ));
	    		Log.d( TAG, b.getString( AccountManager.KEY_ACCOUNT_TYPE ));
	    		Log.d( TAG, b.getString( AccountManager.KEY_AUTHTOKEN ));
    		}
    	} catch( Exception x ) {
    		Log.e( TAG, "Exception: " + x.getMessage() );
    	}

    	//Intent intent = new Intent(this, AuthenticatorActivity.class);
    	//startActivity( intent );
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {



    	switch ( requestCode ) {

//    		case PICK_CONTACT_REQUEST :
//    			
//    			if (resultCode == Activity.RESULT_OK ) {
//    	            // Perform a query to the contact's content provider for the contact's name
//    	            Cursor cursor = getContentResolver().query(data.getData(),
//    	            new String[] {Contacts.DISPLAY_NAME}, null, null, null);
//    	            if (cursor.moveToFirst()) { // True if the cursor is not empty
//    	                int columnIndex = cursor.getColumnIndex(Contacts.DISPLAY_NAME);
//    	                String name = cursor.getString(columnIndex);
//    	                // Do something with the selected contact's name...
//    	                Intent intent = new Intent(this, DisplayMessageActivity.class);
//    	            	//EditText editText = (EditText) findViewById(R.id.edit_message);
//    	            	//String message = editText.getText().toString();
//    	            	intent.putExtra(EXTRA_MESSAGE, name);
//    	            	startActivity(intent);
//    	            	
//    	            }
//    	        }    			
//    			break;
//    			
    		
    		/*	
    		case SPEECH_RECOGNITION_REQUEST_CODE :
    			if ( resultCode == RESULT_OK) {
    	            // Populate the wordsList with the String values the recognition engine thought it heard
    	            ArrayList<String> matches = data.getStringArrayListExtra(
    	                    RecognizerIntent.EXTRA_RESULTS);
    	            Iterator<String> i = matches.iterator();
    	            while( i.hasNext() ) {
    	            	Log.d("MyApp", "Match: " + i.next().toString() );
    	            }
    	            Log.d( TAG, "Speech Ok" );
    	        } else if ( resultCode == RESULT_CANCELED ) {
    	        	
    	        	Log.d("MyApp", "Speech Cancelled" );
    	        } else {
    	        	
    	        	Log.d("MyApp", "resultCode = " + resultCode );
    	        }
    			break;
    			*/
    		default :


					  mwf.onActivityResult( requestCode, resultCode, data );

			  	break;

    	}

        super.onActivityResult(requestCode, resultCode, data );
    }


    public void sendResultToWebView( String sTxId, boolean bSuccess, String sResult ) {


    	if( mwf != null ) {
    		mwf.sendResultToWebView(sTxId, bSuccess, sResult);
    	}
//    	String sResultURL = "javascript:onAndroidResult('" + sTxId + "'," + bSuccess + ",'" + sResult + "')";
//    	
//    	Log.d("MyApp", sResultURL );
//    
//    	
//    	WebView aWebView = (WebView) findViewById(R.id.webview);
//		aWebView.loadUrl( sResultURL );

    }


    public void onSensorChanged(SensorEvent e) {


    	  if ( e.sensor.getType() == Sensor.TYPE_ACCELEROMETER ) {

    		  // Log.d( TAG, "onSensorChanged" );

    	    long curTime = System.currentTimeMillis();
    	    // only allow one update every 100ms.
    	    if ((curTime - lastSensorUpdate) > 100) {
    	      long diffTime = (curTime - lastSensorUpdate);
    	      lastSensorUpdate = curTime;

    	      float x = e.values[0];// x
    	      float y = e.values[1];// y
    	      float z = e.values[2];// z

    	      float speed = Math.abs(x+y+z-sensorLastX-sensorLastY-sensorLastZ) / diffTime * 10000;

    	      sensorLastX = x;
    	      sensorLastY = y;
    	      sensorLastZ = z;

    	      if (speed > SHAKE_THRESHOLD) {
    	        // Log.d("sensor", "shake detected w/ speed: " + speed);
    	        // Toast.makeText(this, "shake detected w/ speed: " + speed, Toast.LENGTH_SHORT).show();

    	    	mSensorManager.unregisterListener(this);

    	    	// this is commented out for production release - changing the settings is not allowed
    	    	// editSettings();

    	      }

    	    }
    	  }
    	}

    public void onAccuracyChanged( Sensor sensor, int accuracy ) {
    	// do nothing
    	if( BuildConfig.DEBUG ) { Log.d( TAG, "AccuracyChanged" ); }
    }


    @Override
    public void onBackPressed() {

    	WebView wv = getWebView();
    	wv.loadUrl( "javascript:{if(!Fse.popPage()){FSEAndroid.leave()}}" );

    }




}
