public class MainActivity extends ActionBarActivity implements
		NavigationDrawerFragment.NavigationDrawerCallbacks {

	/**
	 * Fragment managing the behaviors, interactions and presentation of the
	 * navigation drawer.
	 */
	private NavigationDrawerFragment mNavigationDrawerFragment;
	
	/**
	 * Used to store information during application restart due to configuration
	 * changes
	 */
	private RetainedFragment dataFragment;

	/**
	 * Simulator object
	 */
	private Simulator simulator;
	
	/**
	 * Returns the simulator object
	 * @return
	 */
	public Simulator getSimulator(){
		return simulator;
	}
	
	/**
	 * Browser object
	 */
	private XWalkView mXwalkView;
	private XWalkView mXwalkViewOrbit;
	private boolean loadBrowser;
	private boolean loadBrowserOrbit;
	/**
	 * Returns the simulator object
	 * @return
	 */
	public XWalkView getBrowser(){
		return mXwalkView;
	}
	public XWalkView getBrowserOrbit(){
		return mXwalkViewOrbit;
	}
	public boolean getLoadBrowserFlag(){
		return loadBrowser;
	}
	public void resetLoadBrowserFlag(){
		loadBrowser = false;
	}
	public void raiseLoadBrowserFlag(){
		loadBrowser = true;
	}
	public boolean getLoadBrowserFlagOrbit(){
		return loadBrowserOrbit;
	}
	public void resetLoadBrowserFlagOrbit(){
		loadBrowserOrbit = false;
	}
	public void raiseLoadBrowserFlagOrbit(){
		loadBrowserOrbit = true;
	}
	
    public boolean flag_show_welcome = false;
    
    private ProgressBar browserProgressBar = null;
    private FrameLayout browserProgressLayout = null;
    public void setBrowserProgressBar(ProgressBar bar, FrameLayout fr){
    	browserProgressLayout = fr;
    	browserProgressBar = bar;
    }
    public void resetBrowserProgressBar(){
    	browserProgressLayout = null;
    	browserProgressBar = null;
    }
    public void setBrowserProgressValue(int progr){
    	if(browserProgressLayout!=null && browserProgressBar!=null){
	    	browserProgressBar.setProgress(progr);
	    	if(progr<10000){
	    		browserProgressLayout.setVisibility(View.VISIBLE);
	    	}else{
	    		Animation fadeOut = new AlphaAnimation(1.00f, 0.00f);
                fadeOut.setDuration(1500);
                fadeOut.setAnimationListener(new AnimationListener() {
                    public void onAnimationStart(Animation animation) {}
                    public void onAnimationRepeat(Animation animation) {}
                    public void onAnimationEnd(Animation animation) {
                    	browserProgressLayout.setVisibility(View.GONE);
                    }
                });

                browserProgressLayout.startAnimation(fadeOut);
	    		
	    	}
    	}
    }
    
    
    private ProgressBar browserProgressBarOrbit = null;
    private FrameLayout browserProgressLayoutOrbit = null;
    public void setBrowserProgressBarOrbit(ProgressBar bar, FrameLayout fr){
    	browserProgressLayoutOrbit = fr;
    	browserProgressBarOrbit = bar;
    }
    public void resetBrowserProgressBarOrbit(){
    	browserProgressLayoutOrbit = null;
    	browserProgressBarOrbit = null;
    }
    public void setBrowserProgressValueOrbit(int progr){
    	if(browserProgressLayoutOrbit!=null && browserProgressBarOrbit!=null){
	    	browserProgressBarOrbit.setProgress(progr);
	    	if(progr<10000){
	    		browserProgressLayoutOrbit.setVisibility(View.VISIBLE);
	    	}else{
	    		Animation fadeOut = new AlphaAnimation(1.00f, 0.00f);
                fadeOut.setDuration(1500);
                fadeOut.setAnimationListener(new AnimationListener() {
                    public void onAnimationStart(Animation animation) {}
                    public void onAnimationRepeat(Animation animation) {}
                    public void onAnimationEnd(Animation animation) {
                    	browserProgressLayoutOrbit.setVisibility(View.GONE);
                    }
                });

                browserProgressLayoutOrbit.startAnimation(fadeOut);
	    		
	    	}
    	}
    }

    private ProgressBar browserProgressBarMap = null;
    private FrameLayout browserProgressLayoutMap = null;
    public void setBrowserProgressBarMap(ProgressBar bar, FrameLayout fr){
    	browserProgressLayoutMap = fr;
    	browserProgressBarMap = bar;
    }
    public void resetBrowserProgressBarMap(){
    	browserProgressLayoutMap = null;
    	browserProgressBarMap = null;
    }
    public void setBrowserProgressValueMap(int progr){
    	if(browserProgressLayoutMap!=null && browserProgressBarMap!=null){
	    	browserProgressBarMap.setProgress(progr);
	    	if(progr<10000){
	    		browserProgressLayoutMap.setVisibility(View.VISIBLE);
	    	}else{
	    		Animation fadeOut = new AlphaAnimation(1.00f, 0.00f);
                fadeOut.setDuration(1500);
                fadeOut.setAnimationListener(new AnimationListener() {
                    public void onAnimationStart(Animation animation) {}
                    public void onAnimationRepeat(Animation animation) {}
                    public void onAnimationEnd(Animation animation) {
                    	browserProgressLayoutMap.setVisibility(View.GONE);
                    }
                });

                browserProgressLayoutMap.startAnimation(fadeOut);
	    		
	    	}
    	}
    }
    
    //Temporal storing of the user missions for the upgrading of the database
    public ArrayList<UserMission> userMissions;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//start_time = System.nanoTime(); 
		
		//Install Orekit default files if not installed yet
		userMissions = new ArrayList<UserMission>();
		Installer.installApkData(this);
		
		//Initialize Orekit with the data files
		OrekitInit.init(Installer.getOrekitDataRoot(this));
		
		//Configure application window
		//requestWindowFeature(Window.FEATURE_PROGRESS);
		setContentView(R.layout.activity_main);
		//setProgressBarVisibility(true);
		
		// find the retained fragment on activity restarts
        FragmentManager fm = getFragmentManager();
        dataFragment = (RetainedFragment) fm.findFragmentByTag("data");

        // create the fragment and data the first time
        if (dataFragment == null) {
        	((StavorApplication)getApplication()).modelViewId = R.id.menu_views_ref_frame_xyz;
        	((StavorApplication)getApplication()).modelOrbitViewId = R.id.menu_orbviews_free;
			((StavorApplication)getApplication()).follow_sc = R.id.menu_mapviews_free;
        	((StavorApplication)getApplication()).zoom = 1;
        	((StavorApplication)getApplication()).lon = (float)0.0;
        	((StavorApplication)getApplication()).lat = (float)0.0;
            // add the fragment
            dataFragment = new RetainedFragment();
            fm.beginTransaction().add(dataFragment, "data").commit();
            
            Simulator simu = new Simulator(this);
	    	
            ReaderDbHelper db_help_tmp;
            SQLiteDatabase db_tmp;
            db_help_tmp = Installer.installApkDatabase(this);
            db_tmp = db_help_tmp.getWritableDatabase();
            
            ((StavorApplication)getApplication()).jsInterface = new WebAppInterface(this, simu.getSimulationResults());
            
            dataFragment.setData(
            		simu,
            		db_help_tmp,
            		db_tmp,
            		Parameters.Hud.start_panel_open
            		);
            
            RatingSystem.verify(this);
        }
        
        // the data is available in dataFragment.getData()
        this.simulator = dataFragment.getSim();
        //this.simulator.reconstruct(this);
        
        //Update javascriptInterface
        ((StavorApplication)getApplication()).jsInterface.reconstruct(this, simulator.getSimulationResults());
        //XGGDEBUG: NullPointer dans cette ligne au dessus quand on ferme l'application
        
        mXwalkView = new XWalkView(this.getApplicationContext(), this);
		//mXwalkView.setBackgroundResource(R.color.black);
        mXwalkView.setBackgroundColor(0x00000000);
        mXwalkView.setResourceClient(new MyResourceClient(mXwalkView));
        mXwalkView.setUIClient(new MyUIClient(mXwalkView));
        mXwalkView.clearCache(true);
    	
    	//Orbit browser
        mXwalkViewOrbit = new XWalkView(this.getApplicationContext(), this);
		//mXwalkView.setBackgroundResource(R.color.black);
        mXwalkViewOrbit.setBackgroundColor(0x00000000);
        mXwalkViewOrbit.setResourceClient(new MyResourceClient(mXwalkViewOrbit));
        mXwalkViewOrbit.setUIClient(new MyUIClient(mXwalkViewOrbit));
        mXwalkViewOrbit.clearCache(true);
    	
    	((StavorApplication)getApplication()).jsInterface = new WebAppInterface(this, simulator.getSimulationResults());
    	mXwalkView.addJavascriptInterface(((StavorApplication)getApplication()).jsInterface, "Android");
    	mXwalkViewOrbit.addJavascriptInterface(((StavorApplication)getApplication()).jsInterface, "Android");
    	
    	mXwalkView.load(Parameters.Web.STARTING_PAGE,null);
    	mXwalkViewOrbit.load(Parameters.Web.STARTING_PAGE_ORBIT,null);
    	
    	resetLoadBrowserFlag();
    	resetLoadBrowserFlagOrbit();
        
		//Install the Missions database if not installed yet and store database objects
		((StavorApplication)getApplication()).db_help = dataFragment.getDbHelp();
		((StavorApplication)getApplication()).db = dataFragment.getDb();

		hud_panel_open = dataFragment.getHudPanelOpen();
        
        // NAVIGATION
		mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
				.findFragmentById(R.id.navigation_drawer);
		
		//((StavorApplication)getApplication()).mTitle = getTitle();

		// Set up the drawer.
		mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
				(DrawerLayout) findViewById(R.id.drawer_layout));
		
		restoreActionBar();
	}

	@Override
	public void onNavigationDrawerItemSelected(int position) {
		//Reset flag to not start playing when the browser has to reload.
		if(simulator!=null)
			simulator.resetTemporaryPause();
		// update the main content by replacing fragments
		FragmentManager fragmentManager = getFragmentManager();
		if(position==0){// selection of tabs content
			fragmentManager
			.beginTransaction()
			.replace(R.id.container,
					SimulatorFragment.newInstance(position + 1)).commit();
		}else if(position==1){
			fragmentManager
			.beginTransaction()
			.replace(R.id.container,
					HudFragment.newInstance(position + 1)).commit();
		}else if(position==2){
			// Display the fragment as the main content.
	        fragmentManager
	        .beginTransaction()
	        .replace(R.id.container, 
	        		SettingsBasicFragment.newInstance(position +1)).commit();
		}else if(position==3){
			// Display the fragment as the main content.
	        fragmentManager
	        .beginTransaction()
	        .replace(R.id.container, 
	        		SettingsExtraFragment.newInstance(position +1)).commit();
		}else if(position==4){
			// Display the fragment as the main content.
	        fragmentManager
	        .beginTransaction()
	        .replace(R.id.container, 
	        		SettingsMeasuresFragment.newInstance(position +1)).commit();
		}else if(position==5){
			// Display the fragment as the main content.
	        fragmentManager
	        .beginTransaction()
	        .replace(R.id.container, 
	        		SettingsModelsFragment.newInstance(position +1)).commit();
		}else if(position==6){
			// Display the fragment as the main content.
	        fragmentManager
	        .beginTransaction()
	        .replace(R.id.container, 
	        		OrbitFragment.newInstance(position +1)).commit();
		}else if(position==7){
			// Display the fragment as the main content.
	        fragmentManager
	        .beginTransaction()
	        .replace(R.id.container, 
	        		SettingsOrbitFragment.newInstance(position +1)).commit();
		}else if(position==8){
			fragmentManager
			.beginTransaction()
			.replace(R.id.container,
					MapFragment.newInstance(position + 1)).commit();
		}else if(position==9){
			// Display the fragment as the main content.
	        fragmentManager
	        .beginTransaction()
	        .replace(R.id.container, 
	        		SettingsCoverageFragment.newInstance(position +1)).commit();
		}else if(position==10){
			// Display the fragment as the main content.
	        fragmentManager
	        .beginTransaction()
	        .replace(R.id.container, 
	        		StationsFragment.newInstance(position +1)).commit();
		}else if(position==11){
			// Display the fragment as the main content.
	        fragmentManager    
	        .beginTransaction()
	        .replace(R.id.container, 
	        		SettingsGeneralMapFragment.newInstance(position +1)).commit();
		}else if(position==12){
			// Display the fragment as the main content.
	        fragmentManager    
	        .beginTransaction()
	        .replace(R.id.container, 
	        		SettingsGeneralFragment.newInstance(position +1)).commit();
		}else if(position==13){
			// Display the fragment as the main content.
	        fragmentManager
	        .beginTransaction()
	        .replace(R.id.container, TestFragment.newInstance(position + 1)).commit();
		}else{
			
		}
	}

	/**
	 * Updates the title of the section
	 */
	public void onSectionAttached(int number) {
		((StavorApplication)getApplication()).currentSection = number;
		switch (number) {
		case 1:
			((StavorApplication)getApplication()).mTitle = getString(R.string.title_section1);
			break;
		case 2:
			((StavorApplication)getApplication()).mTitle = getString(R.string.title_section2);
			break;
		case 3:
			((StavorApplication)getApplication()).mTitle = getString(R.string.title_section3);
			break;
		case 4:
			((StavorApplication)getApplication()).mTitle = getString(R.string.title_section4);
			break;
		case 5:
			((StavorApplication)getApplication()).mTitle = getString(R.string.title_section5);
			break;
		case 6:
			((StavorApplication)getApplication()).mTitle = getString(R.string.title_section6);
			break;
		case 7:
			((StavorApplication)getApplication()).mTitle = getString(R.string.title_section7);
			break;
		case 8:
			((StavorApplication)getApplication()).mTitle = getString(R.string.title_section8);
			break;
		case 9:
			((StavorApplication)getApplication()).mTitle = getString(R.string.title_section9);
			break;
		case 10:
			((StavorApplication)getApplication()).mTitle = getString(R.string.title_section10);
			break;
		case 11:
			((StavorApplication)getApplication()).mTitle = getString(R.string.title_section11);
			break;
		case 12:
			((StavorApplication)getApplication()).mTitle = getString(R.string.title_section12);
			break;
		case 13:
			((StavorApplication)getApplication()).mTitle = getString(R.string.title_section13);
			break;
		case 14:
			((StavorApplication)getApplication()).mTitle = getString(R.string.title_section14);
			break;
		}
	}
    
	public void restoreActionBar() {
		ActionBar actionBar = getSupportActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setTitle(((StavorApplication)getApplication()).mTitle);
		//actionBar.setIcon(R.drawable.simulator_s);
		//getSupportActionBar().setDisplayShowHomeEnabled(true);
	}
	
	private ShareActionProvider mShareActionProvider;
	
	private void launchMarket() {

        
	    Uri uri = Uri.parse("market://details?id=" + getPackageName());
	    Intent myAppLinkToMarket = new Intent(Intent.ACTION_VIEW, uri);
	    try {
	        startActivity(myAppLinkToMarket);
	    } catch (ActivityNotFoundException e) {
	        Toast.makeText(this, " unable to find market app", Toast.LENGTH_LONG).show();
	    }
	}


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		//actionBarMenu = menu;
		//currentSection = currentSection;
		if (!mNavigationDrawerFragment.isDrawerOpen()) {
			// Only show items in the action bar relevant to this screen
			// if the drawer is not showing. Otherwise, let the drawer
			// decide what to show in the action bar.
			getMenuInflater().inflate(R.menu.main, menu);
			
			// Locate MenuItem with ShareActionProvider
		    MenuItem item = menu.findItem(R.id.menu_item_share);
		    //mShareActionProvider = (ShareActionProvider) item.getActionProvider(); 
		    mShareActionProvider = (ShareActionProvider)
		            MenuItemCompat.getActionProvider(item);
		    
		    Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setAction(Intent.ACTION_SEND);
            shareIntent.putExtra(Intent.EXTRA_TEXT,"https://play.google.com/store/apps/details?id=cs.si.stavor");
            shareIntent.setType("text/plain");
            mShareActionProvider.setShareIntent(shareIntent); 
		    
			restoreActionBar();
			return true;
		}
		
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		if (!mNavigationDrawerFragment.isDrawerOpen()) {
			// Only show items in the action bar relevant to this screen
			// if the drawer is not showing. Otherwise, let the drawer
			// decide what to show in the action bar.
			if(((StavorApplication)getApplication()).currentSection==1){
				MenuItem item = menu.findItem(R.id.action_simulator);
				//item.setVisible(false);
				item.setIcon(R.drawable.ab_simulator);
			}else if(((StavorApplication)getApplication()).currentSection==2){
				MenuItem item = menu.findItem(R.id.action_attitude);
				//item.setVisible(false);
				item.setIcon(R.drawable.ab_attitude);
			}else if(((StavorApplication)getApplication()).currentSection==7){
				MenuItem item = menu.findItem(R.id.action_orbit);
				//item.setVisible(false);
				item.setIcon(R.drawable.ab_orbit);
			}else if(((StavorApplication)getApplication()).currentSection==9){
				MenuItem item = menu.findItem(R.id.action_map);
				//item.setVisible(false);
				item.setIcon(R.drawable.ab_map);
			}
			supportInvalidateOptionsMenu();
			return true;
		}
		return super.onCreateOptionsMenu(menu);
	}
	
	public void refreshActionBarIcons(){
		supportInvalidateOptionsMenu();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_about) {
			showAbout();
			return true;
		}else if (id == R.id.action_simulator && ((StavorApplication)getApplication()).currentSection!=1) {
			showSection(0);
			return true;
		}else if (id == R.id.action_attitude && ((StavorApplication)getApplication()).currentSection!=2) {
			showSection(1);
			return true;
		}else if (id == R.id.action_orbit && ((StavorApplication)getApplication()).currentSection!=7) {
			showSection(6);
			return true;
		}else if (id == R.id.action_map && ((StavorApplication)getApplication()).currentSection!=9) {
			showSection(8);
			return true;
		}else if (id == R.id.menu_item_rate) {
			launchMarket();
		}else if (id == R.id.menu_item_tutorial) {
			String key1 = getString(R.string.pref_key_guide_visualization);
			String key2 = getString(R.string.pref_key_guide_simulator);
			SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
			sharedPref.edit()
					.putBoolean(key1, true)
					.putBoolean(key2, true).commit();
		}
		/*if (id == R.id.action_reset_conf) {
			resetUserConfigShowDialog();
			return true;
		}
		if (id == R.id.action_reset_db) {
			resetMissionsDbShowDialog();
			return true;
		}*/
		return super.onOptionsItemSelected(item);
	}

	/**
	 * Start the About activity
	 */
	public void showAbout() {
		Intent myIntent = new Intent(MainActivity.this, AboutActivity.class);
		MainActivity.this.startActivity(myIntent);
	}
	
	/**
	 * Starts the Mission editor activity in create mode
	 */
	public void showMissionCreator() {
		Intent myIntent = new Intent(MainActivity.this, MissionActivity.class);
		MainActivity.this.startActivity(myIntent);
	}
	
	/**
	 * Starts the Mission editor activity in edit mode
	 */
	public void showMissionEditor(MissionAndId mission){
		Intent myIntent = new Intent(MainActivity.this, MissionActivity.class);
		Bundle b = new Bundle();
		b.putSerializable("MISSION",mission);
		myIntent.putExtras(b);
		MainActivity.this.startActivity(myIntent);
	}
	
	/**
	 * Starts the Station editor activity in create mode
	 */
	public void showStationCreator() {
		Intent myIntent = new Intent(MainActivity.this, StationActivity.class);
		MainActivity.this.startActivity(myIntent);
	}
	
	/**
	 * Starts the Station editor activity in edit mode
	 */
	public void showStationEditor(StationAndId station){
		Intent myIntent = new Intent(MainActivity.this, StationActivity.class);
		Bundle b = new Bundle();
		b.putSerializable("STATION",station);
		myIntent.putExtras(b);
		MainActivity.this.startActivity(myIntent);
	}

	/**
	 * GoTo specified section of the navigation menu
	 * @param sel
	 */
	public void showSection(final int sel) {
		runOnUiThread( new Runnable() {
			public void run() {    
				mNavigationDrawerFragment.select(sel);
				onSectionAttached(sel+1);
				restoreActionBar();
	        }
		});
	}
	
	/**
	 * GoTo previously selected section of the navigation menu
	 */
	public void showSection() {
		showSection(mNavigationDrawerFragment.getSelectedPosition());
	}
	
    private Toast toast;
    private long lastBackPressTime = 0;


    @Override
    public void onBackPressed() {
    	if (!mNavigationDrawerFragment.isDrawerOpen()) {//If the navigation menu is not opened
	    	int sel = mNavigationDrawerFragment.getSelectedPosition();
	    	if(sel==7){//If it is currently in a configuration section, goto Hud
	    		showSection(6);
	    	}else if (sel>1 && sel<6){//If it is in Hud, goto simulator screen
	    		showSection(1);
	    	}else if (sel>8 && sel<12){//If it is in Hud, goto simulator screen
	    		showSection(8);
	    	}else if (sel==1 || sel==6 || sel==8 || sel==12){//If it is in Hud, goto simulator screen
	    		showSection(0);
	    	}else if (sel==0){//If it is in Simulator, warn user before exit
		    	if (this.lastBackPressTime < System.currentTimeMillis() - 4000) {//Wait some time for confirmation
		    		toast = Toast.makeText(this, getString(R.string.app_exit_prevent_message), 4000);
		    		toast.show();
		    		this.lastBackPressTime = System.currentTimeMillis();
		    	} else {//Exit application
		    		if (toast != null) {
		    			toast.cancel();
		    		}
		    		super.onBackPressed();
		    	}
	    	}
    	}else{//If the navigation menu is open, close it
    		showSection();	
	    }
    }
    
    /**
     * Displays the Welcome dialog
     */
    public void showWelcomeMessage() {
		if(Parameters.App.show_orekit_data_installation_message){
	        DialogFragment newFragment = new WelcomeDialogFragment();
	        newFragment.show(getFragmentManager(), "welcome");
		}
    }
    
    /**
     * Displays an error dialog
     * @param message
     * @param canIgnore
     */
    public void showErrorDialog(String message, boolean canIgnore) {
    	DialogFragment newFragment = ErrorDialogFragment.newInstance(message, canIgnore);
    	newFragment.setCancelable(false);
    	newFragment.show(getFragmentManager(), "error");
    }
    
    
    /*public void showTutorialSimulator(){
    	String key = getString(R.string.pref_key_tutorial_simulator);
    	SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    	if(sharedPref.getBoolean(key, Parameters.App.show_tutorial)){
	    	String title = getString(R.string.tutorial_title_simulator);
	    	String message = getString(R.string.tutorial_message_simulator);
	    	showTutorialDialog(key, title, message);
    	}
    	if(flag_show_welcome){
    		flag_show_welcome=false;
			showWelcomeMessage();
    	}
    }*/
    /*
    public void showTutorialDisplay(){
    	String key = getString(R.string.pref_key_tutorial_display);
    	SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    	if(sharedPref.getBoolean(key, Parameters.App.show_tutorial)){
	    	String title = getString(R.string.tutorial_title_display);
	    	String message = getString(R.string.tutorial_message_display);
	    	showTutorialDialog(key, title, message);
    	}
    }
    public void showTutorialOrbit(){
    	String key = getString(R.string.pref_key_tutorial_orbit);
    	SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    	if(sharedPref.getBoolean(key, Parameters.App.show_tutorial)){
	    	String title = getString(R.string.tutorial_title_orbit);
	    	String message = getString(R.string.tutorial_message_orbit);
	    	showTutorialDialog(key, title, message);
    	}
    }
    public void showTutorialConfig(){
    	String key = getString(R.string.pref_key_tutorial_config);
    	SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    	if(sharedPref.getBoolean(key, Parameters.App.show_tutorial)){
	    	String title = getString(R.string.tutorial_title_config);
	    	String message = getString(R.string.tutorial_message_config);
	    	showTutorialDialog(key, title, message);
    	}
    }
	public void showTutorialMap(){
    	String key = getString(R.string.pref_key_tutorial_map);
    	SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    	if(sharedPref.getBoolean(key, Parameters.App.show_tutorial)){
	    	String title = getString(R.string.tutorial_title_map);
	    	String message = getString(R.string.tutorial_message_map);
	    	showTutorialDialog(key, title, message);
    	}
    }
    public void showTutorialStations(){
    	String key = getString(R.string.pref_key_tutorial_stations);
    	SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    	if(sharedPref.getBoolean(key, Parameters.App.show_tutorial)){
	    	String title = getString(R.string.tutorial_title_stations);
	    	String message = getString(R.string.tutorial_message_stations);
	    	showTutorialDialog(key, title, message);
    	}
    }
    public void showTutorialCoverage(){
    	String key = getString(R.string.pref_key_tutorial_coverage);
    	SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    	if(sharedPref.getBoolean(key, Parameters.App.show_tutorial)){
	    	String title = getString(R.string.tutorial_title_coverage);
	    	String message = getString(R.string.tutorial_message_coverage);
	    	showTutorialDialog(key, title, message);
    	}
    }
    public void showTutorialConfigMap(){
    	String key = getString(R.string.pref_key_tutorial_config_map);
    	SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    	if(sharedPref.getBoolean(key, Parameters.App.show_tutorial)){
	    	String title = getString(R.string.tutorial_title_config_map);
	    	String message = getString(R.string.tutorial_message_config_map);
	    	showTutorialDialog(key, title, message);
    	}
    }
    private void showTutorialDialog(String key, String title, String message) {
    	DialogFragment newFragment = TutorialDialogFragment.newInstance(key, title, message);
    	newFragment.setCancelable(true);
    	newFragment.show(getFragmentManager(), "tutorial-"+title);
    }*/
    
    /**
     * Displays a confirmation dialog for reseting application configuration
     */
    /*private void resetUserConfigShowDialog() {
    	DialogFragment newFragment = ResetAppDialogFragment.newInstance();
    	newFragment.setCancelable(true);
    	newFragment.show(getFragmentManager(), "reset");
	}*/
    
    /**
     * Displays a confirmation dialog for reseting Missions database
     */
    /*private void resetMissionsDbShowDialog() {
    	DialogFragment newFragment = ResetDbDialogFragment.newInstance();
    	newFragment.setCancelable(true);
    	newFragment.show(getFragmentManager(), "reset_db");
	}*/
    
    Dialog rate_dialog;
    public void setRateDialog(Dialog dialog){
    	rate_dialog = dialog;
    }
    
    @Override
    protected void onPause() {//Pause simulator and browser
        super.onPause();
        if(rate_dialog!=null){
        	rate_dialog.dismiss();
        }
        /*if(simulator!=null){
        	simulator.pause();
        }*/
    }

    @Override
    protected void onResume() {//Resume browser
        super.onResume();
        this.simulator.reconstruct(this);
    }

    @Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
    	super.onActivityResult(requestCode, resultCode, data);
        if (mXwalkView != null) {
            mXwalkView.onActivityResult(requestCode, resultCode, data);
        }
        if (mXwalkViewOrbit != null) {
            mXwalkViewOrbit.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        if (mXwalkView != null) {
            mXwalkView.onNewIntent(intent);
        }
        if (mXwalkViewOrbit != null) {
            mXwalkViewOrbit.onNewIntent(intent);
        }
    	super.onNewIntent(intent);
    }
	
	@Override
    public void onDestroy() {//Disconnect simulator, close database and browser
        super.onDestroy();
        // store the data in the fragment
        if(isFinishing()){
        	simulator.disconnect();
            //((StavorApplication)getApplication()).db_help.close();
        }else{
        	dataFragment.setData(
        			this.simulator,
        			((StavorApplication)getApplication()).db_help,
        			((StavorApplication)getApplication()).db,
        			hud_panel_open
        			);
        	//Recycle background [NOT USED SINCE NEW ACTIVITY SPLASH SCREEN BUT SAVE FOR FUTURE IMPLEMENTATIONS]
            /*BitmapDrawable bd = (BitmapDrawable)getWindow().getDecorView().getBackground();
            Bitmap mBitmap = bd.getBitmap();
            if (mBitmap != null && !mBitmap.isRecycled()) {
            	getWindow().getDecorView().setBackgroundResource(0);
                bd.setCallback(null);
                mBitmap.recycle();
                mBitmap = null; 
            }*/
        }
      //Prevent onDestroy to avoid exception of illegalArgument: receiver not registered
    	try{
            mXwalkView.onDestroy();
    	}catch(Exception e){
    	}
    	try{
            mXwalkViewOrbit.onDestroy();
    	}catch(Exception e){
    	}
    }

	private boolean hud_panel_open;
	public boolean getHudPanelOpen(){
		return hud_panel_open;
	}
	public void setHudPanelOpen(boolean open){
		hud_panel_open = open;
	}
} public class StavorApplication extends MultiDexApplication {
	private String searchTerm = "";
	
	/**
	 * Used to store the last screen title. For use in restoreActionBar()
	 */
	public CharSequence mTitle;
	public int currentSection;
	
	//Global database objects (for multi-activity access)
	public ReaderDbHelper db_help;
    public SQLiteCursorLoader loader = null;
    public SQLiteDatabase db;
    
    public int modelViewId = R.id.menu_views_ref_frame_xyz;
    public int modelOrbitViewId = R.id.menu_orbviews_free;
    
    WebAppInterface jsInterface;

    public int follow_sc = R.id.menu_mapviews_free;
    public int zoom = 1;
    public float lon = (float) 0.0;
    public float lat = (float) 0.0;
	
	public void setSearchTerm(String searchTerm) {
		this.searchTerm = searchTerm;
	}
	
	public String getSearchTerm() {
		return this.searchTerm;
	}

} public final class MissionReaderContract {
	public MissionReaderContract(){}
	
	/* Inner class that defines the table contents */
    public static abstract class MissionEntry implements BaseColumns {
        public static final String TABLE_NAME = "mission";
        public static final String COLUMN_NAME_NAME = "name";
        public static final String COLUMN_NAME_DESCRIPTION = "description";
        public static final String COLUMN_NAME_CLASS = "class";
    }

    private static final String TEXT_TYPE = " TEXT";
    private static final String SERIALIZED_TYPE = " BLOB";
    private static final String COMMA_SEP = ",";
    static final String SQL_CREATE_ENTRIES =
        "CREATE TABLE " + MissionEntry.TABLE_NAME + " (" +
        		MissionEntry._ID + " INTEGER PRIMARY KEY," +
        		MissionEntry.COLUMN_NAME_NAME + TEXT_TYPE + COMMA_SEP +
        		MissionEntry.COLUMN_NAME_DESCRIPTION + TEXT_TYPE + COMMA_SEP +
        		MissionEntry.COLUMN_NAME_CLASS + SERIALIZED_TYPE + 
        " )";

    static final String SQL_DELETE_ENTRIES =
        "DROP TABLE IF EXISTS " + MissionEntry.TABLE_NAME;

} public class ReaderDbHelper extends SQLiteOpenHelper {
	// If you change the database schema, you must increment the database version.
    public static final int DATABASE_VERSION = 3;
    public static final String DATABASE_NAME = "Missions.db";
    private MainActivity activity;
    
    public ReaderDbHelper(Context context, MainActivity activity) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.activity = activity;
    }
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(MissionReaderContract.SQL_CREATE_ENTRIES);
        db.execSQL(StationsReaderContract.SQL_CREATE_ENTRIES);
        
        //Reset install database flag
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity.getApplicationContext());
        prefs.edit().putBoolean(activity.getString(R.string.pref_key_database_installed), false).commit();
    }
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // This database is only a cache for online data, so its upgrade policy is
        // to simply to discard the data and start over
    	
    	//Check if the user has introduced new entries
    		//Get all entries
    	
    	if(oldVersion==1){
	    	
			Cursor result =
				    db.rawQuery("select * from "+MissionReaderContract.MissionEntry.TABLE_NAME+" order by "+MissionReaderContract.MissionEntry._ID+" asc",null);
			
			activity.userMissions.clear();
			if(result.getCount()>3){
				for(int i = 3; i < result.getCount(); i++){
					result.moveToPosition(i);
					String name = result.getString(result.getColumnIndex(MissionReaderContract.MissionEntry.COLUMN_NAME_NAME));
					String description = result.getString(result.getColumnIndex(MissionReaderContract.MissionEntry.COLUMN_NAME_DESCRIPTION));
					byte[] serialclass = result.getBlob(result.getColumnIndex(MissionReaderContract.MissionEntry.COLUMN_NAME_CLASS));
					activity.userMissions.add(new UserMission(name, description, serialclass));
				}
			}
	    	
	        db.execSQL(MissionReaderContract.SQL_DELETE_ENTRIES);
    	}else if(oldVersion==2){
	    	
			Cursor result =
				    db.rawQuery("select * from "+MissionReaderContract.MissionEntry.TABLE_NAME+" order by "+MissionReaderContract.MissionEntry._ID+" asc",null);
			
			activity.userMissions.clear();
			if(result.getCount()>6){
				for(int i = 6; i < result.getCount(); i++){
					result.moveToPosition(i);
					String name = result.getString(result.getColumnIndex(MissionReaderContract.MissionEntry.COLUMN_NAME_NAME));
					String description = result.getString(result.getColumnIndex(MissionReaderContract.MissionEntry.COLUMN_NAME_DESCRIPTION));
					byte[] serialclass = result.getBlob(result.getColumnIndex(MissionReaderContract.MissionEntry.COLUMN_NAME_CLASS));
					activity.userMissions.add(new UserMission(name, description, serialclass));
				}
			}
	    	
	        db.execSQL(MissionReaderContract.SQL_DELETE_ENTRIES);
    	}
    	
        onCreate(db);
    }
    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        onUpgrade(db, oldVersion, newVersion);
    }

} public class StationsCursorAdapter extends CursorAdapter {
    private SQLiteCursorLoader loader;
    private int mSelectedPosition;
    LayoutInflater mInflater;

    public StationsCursorAdapter(Context context, Cursor c, SQLiteCursorLoader cloader) {
        // that constructor should be used with loaders.
        super(context, c, 0);
        mInflater = LayoutInflater.from(context);
        loader = cloader;
    }

    public void setSelectedPosition(int position) {
        mSelectedPosition = position;
        // something has changed.
        notifyDataSetChanged();
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        final TextView list_item_id = (TextView)view.findViewById(R.id.textViewStationId);
        TextView list_item_name = (TextView)view.findViewById(R.id.textViewStationName);
        CheckBox list_item_enabled = (CheckBox)view.findViewById(R.id.checkBoxStationEnabled);
        
        list_item_enabled.setOnCheckedChangeListener(new OnCheckedChangeListener(){

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				String entry = "0";
				if(arg1){
					entry = "1";
				}
				String db_id = list_item_id.getText().toString();
				updateStationEnabled(db_id, entry);
			}
        });
        
        list_item_id.setText(cursor.getString(cursor.getColumnIndex(StationEntry._ID)));
        list_item_name.setText(cursor.getString(cursor.getColumnIndex(StationEntry.COLUMN_NAME_NAME)));
        String boolean_str = cursor.getString(cursor.getColumnIndex(StationEntry.COLUMN_NAME_ENABLED));
        boolean boolean_val = false;
        if(boolean_str.equals("1"))
        	boolean_val=true;
        list_item_enabled.setChecked(boolean_val);
        
        int position = cursor.getPosition(); // that should be the same position
        if (mSelectedPosition == position) {
        	//view.setBackgroundColor(Color.RED);
        	view.setBackgroundResource(R.drawable.mission_item_sel);
        } else {
        	//view.setBackgroundColor(Color.WHITE);
        	view.setBackgroundResource(R.drawable.mission_item);
        }
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        View v = mInflater.inflate(R.layout.station_list_item, parent, false);
        // edit: no need to call bindView here. That's done automatically
        return v;
    }
    
    private void updateStationEnabled(String db_id, String entry) {
    	ContentValues values = new ContentValues();
		values.put(StationEntry.COLUMN_NAME_ENABLED, entry);
		
		// Edit the row
		loader.update(
				StationEntry.TABLE_NAME,
				values,
				"_id "+"="+db_id, 
				null);
		
	}

} public final class StationsReaderContract {
	public StationsReaderContract(){}
	
	/* Inner class that defines the table contents */
    public static abstract class StationEntry implements BaseColumns {
        public static final String TABLE_NAME = "station";
        public static final String COLUMN_NAME_ENABLED = "enabled";
        public static final String COLUMN_NAME_NAME = "name";
        public static final String COLUMN_NAME_LATITUDE = "latitude";
        public static final String COLUMN_NAME_LONGITUDE = "longitude";
        public static final String COLUMN_NAME_ALTITUDE = "altitude";
        public static final String COLUMN_NAME_ELEVATION = "elevation";
    }

    private static final String DOUBLE_TYPE = " DOUBLE";
    //private static final String BOOLEAN_TYPE = " BOOLEAN";
    private static final String TEXT_TYPE = " TEXT";
    //private static final String SERIALIZED_TYPE = " BLOB";
    private static final String COMMA_SEP = ",";
    
    static final String SQL_CREATE_ENTRIES =
        "CREATE TABLE " + StationEntry.TABLE_NAME + " (" +
        		StationEntry._ID + " INTEGER PRIMARY KEY," +
        		StationEntry.COLUMN_NAME_ENABLED + TEXT_TYPE + COMMA_SEP +
        		StationEntry.COLUMN_NAME_NAME + TEXT_TYPE + COMMA_SEP +
        		StationEntry.COLUMN_NAME_LATITUDE + DOUBLE_TYPE + COMMA_SEP +
        		StationEntry.COLUMN_NAME_LONGITUDE + DOUBLE_TYPE + COMMA_SEP +
        		StationEntry.COLUMN_NAME_ALTITUDE + DOUBLE_TYPE + COMMA_SEP +
        		StationEntry.COLUMN_NAME_ELEVATION + DOUBLE_TYPE + 
        " )";

    static final String SQL_DELETE_ENTRIES =
        "DROP TABLE IF EXISTS " + StationEntry.TABLE_NAME;

} public static abstract class StationEntry implements BaseColumns {
    public static final String TABLE_NAME = "station";
    public static final String COLUMN_NAME_ENABLED = "enabled";
    public static final String COLUMN_NAME_NAME = "name";
    public static final String COLUMN_NAME_LATITUDE = "latitude";
    public static final String COLUMN_NAME_LONGITUDE = "longitude";
    public static final String COLUMN_NAME_ALTITUDE = "altitude";
    public static final String COLUMN_NAME_ELEVATION = "elevation";
} public class DeleteStationDialogFragment extends DialogFragment {
	private static final String ARG_NAME = "station_name";
	private static final String ARG_ID = "station_id";
	
	public static DeleteStationDialogFragment newInstance(int id, String name) {	
		DeleteStationDialogFragment fragment = new DeleteStationDialogFragment();
		Bundle args = new Bundle();
		args.putString(ARG_NAME, name);
		args.putInt(ARG_ID, id);
		fragment.setArguments(args);
		return fragment;
	}
	int station_id;
	
	@Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the Builder class for convenient dialog construction
		String gs_name = getArguments().getString(ARG_NAME);
		int gs_id = getArguments().getInt(ARG_ID);
		station_id = gs_id;
		
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(getString(R.string.dialog_delete_title_station))
        		.setMessage(getString(R.string.dialog_delete_message_station)+" "+gs_name)
        		.setCancelable(true)
               .setPositiveButton(getString(R.string.dialog_delete_confirm), new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       // Dummy
                	   deleteStation(station_id);
                   }

               });
               builder.setNegativeButton(getString(R.string.dialog_delete_cancel), new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       // User cancelled the dialog
                   }
               });
        // Create the AlertDialog object and return it
        return builder.create();
    }
	
	/**
	 * Delete Mission from database
	 * @param station_id
	 */
	private void deleteStation(int station_id) {
		MainActivity act = ((MainActivity)getActivity());
		((StavorApplication)act.getApplication()).loader.delete(StationEntry.TABLE_NAME, StationEntry._ID+"="+station_id, null);
	}

} public class GroundStation  implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 7297608100756290938L;
	public GroundStation(boolean station_enabled, String station_name,
			double station_lat, double station_lon, double station_alt, double station_elev) {
		enabled = station_enabled;
		name = station_name;
		latitude = station_lat;
		longitude = station_lon;
		altitude = station_alt;
		elevation = station_elev;
		
	}
	public GroundStation() {
	}
	public boolean enabled = false;
	public String name = "";
	public double latitude = 0.0;
	public double longitude = 0.0;
	public double altitude = 0.0;//m
	public double elevation = 5.0;
} public class StationAndId implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public GroundStation station;
	public int id;
	
	public StationAndId(GroundStation gs, int identif){
		station=gs;
		id=identif;
	}
}
import cs.si.stavor.MainActivity;
import cs.si.stavor.R;
import cs.si.stavor.StavorApplication;
import cs.si.stavor.database.MissionReaderContract;
import cs.si.stavor.database.ReaderDbHelper;
import cs.si.stavor.database.StationsCursorAdapter;
import cs.si.stavor.database.StationsReaderContract;
import cs.si.stavor.database.StationsReaderContract.StationEntry;
import cs.si.stavor.dialogs.DeleteStationDialogFragment;
import cs.si.stavor.station.GroundStation;
import cs.si.stavor.station.StationAndId;
import android.app.Activity;
import android.app.DialogFragment;
import android.app.LoaderManager.LoaderCallbacks;
import android.os.Bundle;
import android.app.Fragment;
import android.content.Loader;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.TextView;
import com.commonsware.cwac.loaderex.SQLiteCursorLoader;
		    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		    	updateListSelection();
		    }
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				//if(scrollState == 0){
					updateListSelection();
				//}
		    }
		});
		
		adapter = new StationsCursorAdapter(
	    		this.getActivity().getApplicationContext(), null, ((StavorApplication)getActivity().getApplication()).loader);

		
		stationsList.setAdapter(adapter);
	    registerForContextMenu(stationsList);
		getLoaderManager().initLoader(R.id.listView1, null, this);
    	
    	//Delete
    	Button button_delete = (Button)rootView.findViewById(R.id.buttonMissionDelete);
    	button_delete.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				//if(simulator.getSimulatorStatus().equals(SimulatorStatus.Connected)){
					//Toast.makeText(getActivity().getApplicationContext(), getString(R.string.sim_stop_simulator_first), Toast.LENGTH_LONG).show();
				//}else{
					if(activeStationId==-1){
						Toast.makeText(getActivity().getApplicationContext(), getString(R.string.select_first_a_station), Toast.LENGTH_LONG).show();
					}else{
						showDeleteStationDialog(activeStationId, activeStationName);
					}
				//}
			}
    		
    	});
    	
    	//New
    	Button button_new = (Button)rootView.findViewById(R.id.buttonMissionNew);
    	button_new.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				//if(simulator.getSimulatorStatus().equals(SimulatorStatus.Connected)){
					//Toast.makeText(getActivity().getApplicationContext(), getString(R.string.sim_stop_simulator_first), Toast.LENGTH_LONG).show();
				//}else{
					((MainActivity)getActivity()).showStationCreator();
				//}
			}
    		
    	});
    	
    	//Edit
    	Button button_edit = (Button)rootView.findViewById(R.id.buttonMissionEdit);
    	button_edit.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				//if(simulator.getSimulatorStatus().equals(SimulatorStatus.Connected)){
					//Toast.makeText(getActivity().getApplicationContext(), getString(R.string.sim_stop_simulator_first), Toast.LENGTH_LONG).show();
				//}else{
					if(activeStationId==-1){
						Toast.makeText(getActivity().getApplicationContext(), getString(R.string.select_first_a_station), Toast.LENGTH_LONG).show();
					}else{
						StationAndId gs = getSelectedStation();
		    			if(gs!=null){
		    				((MainActivity)getActivity()).showStationEditor(gs);
		    			}else{
		    				System.err.println("Error loading station");
		    			}
					}
				//}
			}
    		
    	});
    	
		return rootView;
	}
	
	/**
	 * Returns the selected Mission from the database
	 * @return
	 */
	private StationAndId getSelectedStation(){
		String[] projection = {
				StationEntry._ID,
				StationEntry.COLUMN_NAME_NAME,
				StationEntry.COLUMN_NAME_LATITUDE,
				StationEntry.COLUMN_NAME_LONGITUDE,
				StationEntry.COLUMN_NAME_ALTITUDE,
				StationEntry.COLUMN_NAME_ELEVATION,
				StationEntry.COLUMN_NAME_ENABLED
			    };

		Cursor c = ((StavorApplication)((MainActivity)getActivity()).getApplication()).db
			.query(
					StationEntry.TABLE_NAME,  // The table to query
				    projection,                               // The columns to return
				    StationEntry._ID+" = ?",                                // The columns for the WHERE clause
				    new String[]{Integer.toString(activeStationId)},                            // The values for the WHERE clause
				    "",                                     // don't group the rows
				    "",                                     // don't filter by row groups
				    null                                 // The sort order
				    );
		if (c != null && c.getCount() > 0) {
			c.moveToFirst();
			int idIndex = c.getColumnIndex(StationEntry._ID);
			int nameIndex = c.getColumnIndex(StationEntry.COLUMN_NAME_NAME);
			int latIndex = c.getColumnIndex(StationEntry.COLUMN_NAME_LATITUDE);
			int lonIndex = c.getColumnIndex(StationEntry.COLUMN_NAME_LONGITUDE);
			int altIndex = c.getColumnIndex(StationEntry.COLUMN_NAME_ALTITUDE);
			int elevIndex = c.getColumnIndex(StationEntry.COLUMN_NAME_ELEVATION);
			int enabledIndex = c.getColumnIndex(StationEntry.COLUMN_NAME_ENABLED);
			
			//this.itemId = cursor.getLong(idIndex);
			int station_id = c.getInt(idIndex);
			String station_name = c.getString(nameIndex);
			double station_lat = c.getDouble(latIndex);
			double station_lon = c.getDouble(lonIndex);
			double station_alt = c.getDouble(altIndex);
			double station_elev = c.getDouble(elevIndex);
			boolean station_enabled = c.getString(enabledIndex).equals("1");
			
			GroundStation gs = new GroundStation(