public class CheckDatabaseActivity extends Activity {

	public final static int DOWNLOAD_SUCCESS_DIALOG = 0;
	public final static int DOWNLOAD_ERROR_DIALOG = 1;
	public final static int MD5_ERROR_DIALOG = 2;
	public final static int NO_NETWORK_CONNECTION = 3;
	public final static int NO_DB_UPDATE_AVAILABLE = 4;
	public final static int NO_SD_CARD = 5;
	public final static int DB_OK = 6;
	public final static int DOWNLOAD_RETRY = 7;
	
	public final static int FR_OSM = 0;
	public final static int FR_DB = 1;
	

	
	
	/** Called with the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.splash);
		check_db();
	}
	
	public void check_db()
	{
		Resources res = this.getResources();
		String db_filename = res.getString(R.string.app_name_db) + ".db";
		try {
			new FileRetriever(this, db_filename, res.getString(R.string.downloading_db), res.getString(R.string.unzipping_db)).execute();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	public void check_osm()
	{
		Resources res = this.getResources();
		String osm_filename = res.getString(R.string.app_name_osm) + ".map";
		try {
			new FileRetriever(this, osm_filename, res.getString(R.string.downloading_map), res.getString(R.string.unzipping_map)).execute();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	public void showDialog(int id, int res)
	{
		Dialog dia = onCreateDialog(id, res);
		dia.show();
	}

	public final Dialog createAlertDialog(int msg, String placeholder, final int res) 
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		// builder.setTitle(R.string.a_given_string);
		builder.setIcon(R.drawable.icon);
		//builder.setMessage(msg);
		builder.setMessage(String.format(getString(msg),placeholder));
		builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int id) {
				if(res == FR_DB)
				{
					check_osm();
				}
				else
				{
					startActivity();
				}
				
			}
		});
		return builder.create();
	}
	

	/**
	 * this method is creating an allert message
	 * @param msg is the message to be shown in the alert dialog
	 * @return an Dialog to show
	 */
	private final Dialog createErrorAlertDialog(int msg) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		// builder.setTitle(R.string.a_given_string);
		builder.setIcon(R.drawable.icon);
		builder.setMessage(msg);
		builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int id) {
				System.exit(0);
			}
		});
		return builder.create();
	}
	
	/**
	 * this method is creating an allert message
	 * @param msg is the message to be shown in the alert dialog
	 * @return an Dialog to show
	 */
	private final Dialog createRetryDialog(int msg) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		// builder.setTitle(R.string.a_given_string);
		builder.setIcon(R.drawable.icon);
		builder.setMessage(msg);
		builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int id) {
				finish();
				Intent intent = new Intent(getContext(), CheckDatabaseActivity.class);
				startActivity(intent);
			}
		});
		builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int id) {
				finish();
				System.exit(-1);
			}
		});
		return builder.create();
	}

	
	private Context getContext()
	{
		return super.getApplicationContext();
	}
	
	
	/**
	 * Called when all downloads were successful and we have to start the
	 * first user activity called SelectModeActivity
	 */
	public void startActivity() {
		finish();
	}

	protected Dialog onCreateDialog(int id, int res) {
		switch (id) {
		case NO_NETWORK_CONNECTION:
			return createErrorAlertDialog(R.string.no_network_connection);
		case NO_DB_UPDATE_AVAILABLE:
			return createErrorAlertDialog(R.string.no_db_update_available);
		case DOWNLOAD_SUCCESS_DIALOG:
			String filename = getString(R.string.app_name_db)+ ".db";
			if(res == FR_OSM)
				filename = getString(R.string.app_name_osm)+ ".map";
			return createAlertDialog(R.string.db_ok,  filename, res);
		case DB_OK:
			String filename_ok = getString(R.string.app_name_db)+ ".db";
			if(res == FR_OSM)
				filename_ok = getString(R.string.app_name_osm)+ ".map";
			return createAlertDialog(R.string.db_ok,  filename_ok, res);
		case DOWNLOAD_ERROR_DIALOG:
			return createErrorAlertDialog(R.string.db_download_error);
		case MD5_ERROR_DIALOG:
			return createErrorAlertDialog(R.string.md5_error);
		case NO_SD_CARD:
			return createErrorAlertDialog(R.string.sd_card_not_mounted);
		case DOWNLOAD_RETRY:
			Log.v("CheckDatabaseActivity", "Habe retry Dialog erstellt!");
			return createRetryDialog(R.string.retry_download);
		default:
			return null;
		}
	}


	
} public class InfoActivity extends ListActivity {

	private Vector<DBObject> list = null;
	private ProgressDialog progdial = null;

	public InfoActivity() {
		// TODO Auto-generated constructor stub
	}

	/** Called with the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.standard_listview_layout);
        TextView titel = (TextView)findViewById(R.id.untertitel);
		titel.setText(R.string.menu_infos);
	}

	/**
	 * Called when the activity is about to start interacting with the user.
	 */
	@Override
	protected void onResume() {
		super.onResume();
		if(haveNetworkConnection())
			fillData();
		else
		{
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setCancelable(true);
			builder.setMessage(R.string.no_network_connection);
			builder.setTitle(R.string.error_title);
			builder.setNeutralButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
					dialog.dismiss();
				}
			});
			builder.create().show();
		}
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setPositiveButton(android.R.string.ok,
				new Dialog.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialogInterface, int i) {
						dialogInterface.dismiss();
					}
				});
		Information information = (Information) list.get(position);
		builder.setTitle(Html.fromHtml(information.getTitel()));
		builder.setMessage(Html.fromHtml("<pre>" + information.getNachricht() + "</pre>"));
		builder.create().show();
	}

	/**
	 * fills the list_view with the modes which are offered to the user
	 */
	public void fillData() {
		SharedPreferences shared = PreferenceManager
				.getDefaultSharedPreferences(this);
		int infocity = Integer.parseInt(shared.getString("infos", "0"));
		
		progdial = new ProgressDialog(this);
		
		progdial.setMessage(getResources().getText(R.string.waiting));
		progdial.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progdial.setCancelable(false);
		progdial.show();
		
		InformationList info = new InformationList(this);
		info.execute(Integer.valueOf(infocity));
	}

	public void fillList(Vector<DBObject> list)
	{
		this.list = list;
		MyListAdapter infos = new MyListAdapter(SASAbus.getContext(),
				R.id.text, R.layout.news_row, list);
		setListAdapter(infos);
		progdial.dismiss();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.optionmenu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_about: {
			new About(this).show();
			return true;
		}
		case R.id.menu_credits: {
			new Credits(this).show();
			return true;
		}
		}
		return false;
	}
	
	
	 /**
	 * this method checks if a networkconnection is active or not
	 * @return boolean if the network is reachable or not
	 */
	private boolean haveNetworkConnection() 
	{
		boolean haveConnectedWifi = false;
		boolean haveConnectedMobile = false;

		ConnectivityManager cm = (ConnectivityManager) (this.getSystemService(Context.CONNECTIVITY_SERVICE));
		NetworkInfo[] netInfo = cm.getAllNetworkInfo();
		for (NetworkInfo ni : netInfo) {
			//testing WIFI connection
			if (ni.getTypeName().equalsIgnoreCase("WIFI"))
				if (ni.isConnected())
					haveConnectedWifi = true;
			//testing GPRS/EDGE/UMTS/HDSPA/HUSPA/LTE connection
			if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
				if (ni.isConnected())
					haveConnectedMobile = true;
		}
		return haveConnectedWifi || haveConnectedMobile;
	}
} public class MapSelectActivity extends MapActivity {
	
	private String from = "";
	
	private String to = "";
	
	/**
	 * sets the text from the textview from to the string from
	 * @param from is the string to set
	 */
	public void setFrom(String from)
	{
		this.from = from;
	}
	
	/**
	 * sets the text from textview to to the string to
	 * @param to is the string to set
	 */
	public void setTo(String to)
	{
		this.to = to;
	}
	
	
	/** Called with the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.mapview_select_layout);
		TextView titel = (TextView) findViewById(R.id.titel);
		titel.setText(R.string.map);

		Resources res = getResources();
		
		MapView mapView = (MapView) findViewById(R.id.mapView);
		mapView.setClickable(true);
		mapView.setBuiltInZoomControls(true);
		mapView.setMapFile(new File(Environment.getExternalStorageDirectory(),
				res.getString(R.string.db_dir) + "/"
						+ res.getString(R.string.app_name_osm) + ".map"));
		mapView.setRenderTheme(InternalRenderTheme.OSMARENDER);

		Vector<DBObject> pallist = PalinaList.getMapList();
		
		Iterator<DBObject> iter = pallist.iterator();

		Drawable stop = getResources().getDrawable(
				R.drawable.glyphicons_238_pin);

		MyArrayItemizedSelectOverlay intermediate = new MyArrayItemizedSelectOverlay(stop);

		GeoPoint partPoint = null;
		
		while (iter.hasNext())
		{
			Palina pal = (Palina)iter.next();
			GeoPoint point = new GeoPoint(pal.getLatitude(),
					pal.getLongitude());
			if(partPoint == null)
			{
				partPoint = point;
			}
			MyOverlaySelectItem overlay = new MyOverlaySelectItem(point, stop, this, pal);
			intermediate.addItem(overlay);
		}

		mapView.getOverlays().add(intermediate);

		LocationManager locman = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        Location lastloc = locman.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if(MySQLiteDBAdapter.exists(this))
        {
	        if(lastloc == null)
	        {
	        	lastloc = locman.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
	        }
	        if(lastloc != null)
	        {
	        	try
	        	{
	        		Palina palina = PalinaList.getPalinaGPS(lastloc);
	        		if(palina != null)
	        		{
	        			partPoint = new GeoPoint(palina.getLatitude(), palina.getLongitude());
	        		}
	        	}
	        	catch(Exception e)
	        	{
	        		Log.e("HomeActivity", "Fehler bei der Location", e);
	        	}
	        }
	        else
	        {
	        	Log.v("HomeActivity", "No location found!!");
	        }
        }
		
		if(partPoint != null)
			mapView.setCenter(partPoint);

		mapView.getController().setZoom(15);

	}

	/**
	 * Called when the activity is about to start interacting with the user.
	 */
	@Override
	protected void onResume() {
		super.onResume();
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
        	setResult();
           return true;
        }
        return false;
    }

	
	private void setResult()
	{
		Intent returnIntent = new Intent();
		returnIntent.putExtra("from", from);
		returnIntent.putExtra("to", to);
		setResult(Activity.RESULT_OK,returnIntent);
		finish();
	}
	
	@Override
	protected void onDestroy ()
	{
		super.onDestroy();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.optionmenu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId())
		{
		case R.id.menu_about:
		{
			new About(this).show();
			return true;
		}
		case R.id.menu_credits:
		{
			new Credits(this).show();
			return true;
		}
		}
		return false;
	}
	
	

} public class DateTimePicker extends RelativeLayout implements View.OnClickListener, OnDateChangedListener, OnTimeChangedListener{
    // DatePicker reference
    private DatePicker datePicker;
    // TimePicker reference
    private TimePicker timePicker;
    // ViewSwitcher reference
    private ViewSwitcher viewSwitcher;
    // Calendar reference
    private Calendar mCalendar;

    // Constructor start
    public DateTimePicker(Context context) {
            this(context, null);
    }

    public DateTimePicker(Context context, AttributeSet attrs) {
            this(context, attrs, 0);
    }

    public DateTimePicker(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            
            // Get LayoutInflater instance
            final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            // Inflate myself
            inflater.inflate(R.layout.datetimepicker, this, true);

            // Inflate the date and time picker views
            final LinearLayout datePickerView = (LinearLayout) inflater.inflate(R.layout.datepicker, null);
            final LinearLayout timePickerView = (LinearLayout) inflater.inflate(R.layout.timepicker, null);
            
            // Grab a Calendar instance
            mCalendar = Calendar.getInstance();
            // Grab the ViewSwitcher so we can attach our picker views to it
            viewSwitcher = (ViewSwitcher) this.findViewById(R.id.DateTimePickerVS);

            // Init date picker
            datePicker = (DatePicker) datePickerView.findViewById(R.id.DatePicker);
            datePicker.init(mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH), this);

            
            // Init time picker
            timePicker = (TimePicker) timePickerView.findViewById(R.id.TimePicker);
            timePicker.setIs24HourView(true);
            timePicker.setOnTimeChangedListener(this);

            // Handle button clicks
            ((Button) findViewById(R.id.SwitchToTime)).setOnClickListener(this); // shows the time picker
            ((Button) findViewById(R.id.SwitchToDate)).setOnClickListener(this); // shows the date picker

            // Populate ViewSwitcher
            viewSwitcher.addView(datePickerView, 0);
            viewSwitcher.addView(timePickerView, 1);
    }
    // Constructor end

    // Called every time the user changes DatePicker values
    public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            // Update the internal Calendar instance
            mCalendar.set(year, monthOfYear, dayOfMonth, mCalendar.get(Calendar.HOUR_OF_DAY), mCalendar.get(Calendar.MINUTE));
    }

    // Called every time the user changes TimePicker values
    public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
            // Update the internal Calendar instance
    		mCalendar.set(mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH), hourOfDay, minute);
    }	

    // Handle button clicks
    public void onClick(View v) {
            switch (v.getId()) {
                    case R.id.SwitchToDate:
                            v.setEnabled(false);
                            findViewById(R.id.SwitchToTime).setEnabled(true);
                            viewSwitcher.showPrevious();
                            break;

                    case R.id.SwitchToTime:
                            v.setEnabled(false);
                            findViewById(R.id.SwitchToDate).setEnabled(true);
                            viewSwitcher.showNext();
                            break;
            }
    }

    // Convenience wrapper for internal Calendar instance
    public int get(final int field) {
        return mCalendar.get(field);
    }

    // Reset DatePicker, TimePicker and internal Calendar instance
    public void reset() {
            final Calendar c = Calendar.getInstance();
            updateDate(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
            updateTime(c.get(Calendar.HOUR_OF_DAY),c.get(Calendar.MINUTE));
    }

    // Convenience wrapper for internal Calendar instance
    public long getDateTimeMillis() {
            return mCalendar.getTimeInMillis();
    }

    // Convenience wrapper for internal TimePicker instance
    public void setIs24HourView(boolean is24HourView) {
            timePicker.setIs24HourView(is24HourView);
    }
   
    // Convenience wrapper for internal TimePicker instance
    public boolean is24HourView() {
            return timePicker.is24HourView();
    }

    // Convenience wrapper for internal DatePicker instance
    public void updateDate(int year, int monthOfYear, int dayOfMonth) {
            datePicker.updateDate(year, monthOfYear, dayOfMonth);
    }

    // Convenience wrapper for internal TimePicker instance
    public void updateTime(int currentHour, int currentMinute) {
            timePicker.setCurrentHour(currentHour);
            timePicker.setCurrentMinute(currentMinute);
    }

}
 public class MyAutocompleteAdapter extends BaseAdapter implements Filterable{
	private final Context context;
	private final Vector<DBObject> origlist;
	private Vector<DBObject> datalist = new Vector<DBObject>();
	private final int layoutId;

	
	/**
	 * This constructor creates an object with the following parameters
	 * @param context is the context to work with
	 * @param whereId is the resource id where to place the string
	 * @param layoutId is the layout id of the list_view
	 * @param list is the list of dbobject's which are to putting in the list_view
	 */
	public MyAutocompleteAdapter(Context context, int layoutId, Vector<DBObject> list) {
		this.context = context;
		this.origlist = list;
		this.layoutId = layoutId;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;  
		if (v == null) {
              LayoutInflater vi = LayoutInflater.from(context);
              v = vi.inflate(layoutId, null);
          }
		TextView textView = (TextView) v.findViewById(R.id.text1);
		textView.setTextColor(context.getResources().getColor(R.color.black));
		if (datalist != null)
		{
			DBObject listItem = datalist.get(position);
			if(listItem != null)
			{
				textView.setText(datalist.get(position).toString());
			}
		}
		return v;
	}

	@Override
	public int getCount() {
		if(datalist == null)
			return 0;
		return datalist.size();
	}

	@Override
	public Object getItem(int position) {
		if(datalist == null || position >= datalist.size())
			return null;
		return datalist.get(position);
	}
	
	@Override
	public long getItemId(int position) {
		if (datalist == null)
			return -1;
		return datalist.get(position).getId();
	}

	 @Override
	 public Filter getFilter() 
	 {
		Filter myFilter = null;
		myFilter = new Filter() {
			@Override
			protected FilterResults performFiltering(CharSequence constraint) {
				FilterResults filterResults = new FilterResults();
				Vector<DBObject> temp_datalist = new Vector<DBObject>();
				if (constraint != null)
				{
					Iterator<DBObject> iter = origlist.iterator();
					String[] constraints = constraint.toString().split(" ");
					while (iter.hasNext())
					{
						DBObject object = iter.next();
						String s = object.toString();
						boolean match = false;
						for (int i = 0; i < constraints.length
								&& (match || i == 0); ++i)
						{
							if (s.toLowerCase()
									.contains(
											constraints[i].toString()
													.toLowerCase()))
							{
								match = true;
							} else
							{
								match = false;
							}
						}
						if (match)
						{
							temp_datalist.add(object);							}
					}
				}
				filterResults.values = temp_datalist;
				filterResults.count = temp_datalist.size();
				return filterResults;
			}

			@Override
			protected void publishResults(CharSequence contraint,
					FilterResults results) {
				try
				{
					if(results.values instanceof Vector<?>)
						datalist = (Vector<DBObject>)results.values;
					notifyDataSetChanged();
				} catch (Exception e)
				{
					Log.v("MyAutocompleteAdapter", "Error", e);
				}
			}
		};
		return myFilter;
	}
} public class MySQLiteDBAdapter {
	
	private static SQLiteDatabase sqlite= null;
	private static DatabaseHelper helper = null;
	private static int counteropen = 0;
	private static int transactioncounter = 0;
	
	public static boolean exists(Context context)
	{
		String appName = context.getResources().getString(R.string.app_name_db);
		String dbFileName = appName + ".db";
		if(helper == null)
		{
			helper = new DatabaseHelper(dbFileName, null);
		}
		if(!helper.databaseFileExists())
			return false;
		return true;
	}
	
	/**
	 * This static method allows you tu getting an instance of the current database
	 * @param context is the actual context
	 * @return an opened and read only sqlite database
	 */
	public static MySQLiteDBAdapter getInstance(Context context)
	{
		if(counteropen == 0)
		{
			Resources res = context.getResources();
			String appName = res.getString(R.string.app_name_db);
			String dbFileName = appName + ".db";
			if(helper == null)
				helper = new DatabaseHelper(dbFileName,null);
			sqlite = helper.getReadableDatabase();
			if(sqlite == null)
			{
				System.err.println("Die Datenbank konnte nicht geoeffnet werden");
				System.exit(-2);
			}
		}
		++counteropen;
		return new MySQLiteDBAdapter();
	}
	
	/**
	 * makes the constructor private and so the only way to obtain an instance 
	 * of the object is the static method getInstance
	 */
	private MySQLiteDBAdapter()
	{
		//do nothing
	}
	
	/**
	 * This method closes all open MySQLiteDBAdapter
	 */
	public static void closeAll() 
	{
			helper.close();
			sqlite.close();
	}
	
	/**
	 * This method "closes" the database. There is a counter, because when there are more then one
	 * instance, then the db will not be closed, it will be decrementet only the counter.
	 * when the counter is 0, then the database will be closed
	 */
	public void close() 
	{
		--counteropen;
		if(counteropen == 0)
		{
			helper.close();
			sqlite.close();
		}
	}
	
	/**
	 * This method allows you to query the database
	 * @param query is the query to send
	 * @param args are the arguments for the query
	 * @return a cursor to the result set of the query
	 */
	public Cursor rawQuery(String query, String[] args)
	{
		Cursor ret = null;
		ret = sqlite.rawQuery(query, args);
		return ret;
	}
	
	/**
	 * to work with transaction management, and to provide it with the idea
	 * of the singleton pattern, there is a counter that counts the transactions open
	 * because the database can handle only one transaction open per dbfile
	 */
	public void beginTransaction()
	{
		if(transactioncounter == 0)
		{
			sqlite.beginTransaction();
		}
		transactioncounter++;
		
	}
	
	/**
	 * to work with transaction management, and to provide it with the idea
	 * of the singleton pattern, there is a counter that counts the transactions closed
	 * because the database can handle only one transaction open per dbfile
	 */
	public void endTransaction()
	{
		transactioncounter--;
		if(transactioncounter == 0)
		{
			sqlite.endTransaction();
		}
	}
	
	/**
	 * This classes helps to open the database read only and close it correctly after using
	 * @author Markus Windegger (markus@mowiso.com)
	 *
	 */
	private static class DatabaseHelper extends DBFileManager {

        DatabaseHelper(String dbFileName, SQLiteDatabase.CursorFactory factory) {
            super(dbFileName, factory);
        }
    }
	
} public class DBObject {
	
	/*
	 * The id is the integer which identifies the object in the database
	 */
	private int id = 0;

	/**
	 * This constructor creates an dbobject
	 */
	public DBObject()
	{
		super();
		//Nothing to do
	}
	
	/**
	 * this creates a dbobject with an identifier, which is the id
	 * provided in the database 
	 * @param identifier is the identifier from the database
	 */
	public DBObject(int identifier)
	{
		super();
		setId(identifier);
	}
	
	/**
	 * 
	 * @return the integer which identifies the object in the database
	 */
	public int getId() {
		return id;
	}

	/**
	 * 
	 * @param id is the integer which identifies the object in the database
	 */
	public void setId(int id) {
		this.id = id;
	}
	
	
	
} public class Palina extends DBObject{
	
	
	private String name_de = null;
	
	private String name_it = null;
	
	private double longitude = 0;
	
	private double latitude = 0;
	
	
	/**
	 * Standardconstructor
	 */
	public Palina()
	{
		super();
	}
	
	

	/**
	 * This is the constructor to fill the object entirely with id, name in it an de
	 * @param identifier is the id from the database
	 * @param name_it is the italian name of the busstop
	 * @param name_de is the german name of the busstop
	 */
	public Palina(int identifier, String name_it, String name_de)
	{
		super(identifier);
		this.setName_de(name_de);
		this.setName_it(name_it);
	}
	
	
	/**
	 * This is the constructor to fill the object with the names in it and de, an to add the coordinates to the bus stop
	 * @param identifier is the id from th db
	 * @param name_it is the italian name of the busstop
	 * @param name_de is the german name of the busstop
	 * @param longitude is the longitude of the busstop
	 * @param latitude is the latitude of the busstop
	 */
	public Palina(int identifier, String name_it, String name_de, double longitude, double latitude)
	{
		super(identifier);
		this.setName_de(name_de);
		this.setName_it(name_it);
		this.setLongitude(longitude);
		this.setLatitude(latitude);
	}

	
	/**
	 * This constructer fills the palina-object with information from a cursor
	 * if the position flag is set, then it fills the position variables longitude and latitude
	 * @param c is the cursor with the information from the db
	 */
	public Palina(Cursor c)
	{
		if (c.getColumnIndex("id") != -1)
			this.setId(c.getInt(c.getColumnIndex("id")));
		this.setName_de(c.getString(c.getColumnIndex("nome_de")));
		this.setName_it(c.getString(c.getColumnIndex("nome_it")));
		if(c.getColumnIndex("longitudine") != -1)
			this.setLongitude(c.getDouble(c.getColumnIndex("longitudine")));
		if (c.getColumnIndex("latitudine") != -1)
			this.setLatitude(c.getDouble(c.getColumnIndex("latitudine")));
	}

	public String getHaltestelle()
	{
		return this.name_it.trim() + " - " + this.name_de.trim(); 
	}
	
	/**
	 * @return the name_de
	 */
	public String getName_de() {
		return name_de;
	}

	/**
	 * @param name_de the name_de to set
	 */
	public void setName_de(String name_de) {
		this.name_de = name_de;
	}

	/**
	 * @return the name_it
	 */
	public String getName_it() {
		return name_it;
	}

	/**
	 * @param name_it the name_it to set
	 */
	public void setName_it(String name_it) {
		this.name_it = name_it;
	}
	
	/**
	 * @return the longitude
	 */
	public double getLongitude() {
		return longitude;
	}

	/**
	 * @param longitude the longitude to set
	 */
	public void setLongitude(double longitude) {
		this.longitude = longitude;
	}

	/**
	 * @return the latitude
	 */
	public double getLatitude() {
		return latitude;
	}

	/**
	 * @param latitude the latitude to set
	 */
	public void setLatitude(double latitude) {
		this.latitude = latitude;
	}
	
	@Override
	public String toString()
	{
		String ret = "";
		if((Locale.getDefault().getLanguage()).indexOf(Locale.GERMAN.toString()) != -1)
		{
			ret = this.getName_de().trim();
		}
		else
		{
			ret = this.getName_it().trim();
		}
		if(ret.indexOf(")") != -1 && ret.indexOf("(") != -1)
			ret = ret.substring(1, ret.indexOf(")")) + " -" + ret.substring(ret.indexOf(")") + 1);
		return ret;
	}
	
} public class PalinaList {
	
	
	
	/**
	 * Returns a list of all bus-stops avaiable in the database
	 * @return a vector of all bus-stops in the database
	 */
	public static Vector <DBObject> getList()
	{
		MySQLiteDBAdapter sqlite = MySQLiteDBAdapter.getInstance(SASAbus.getContext());
		Cursor cursor = sqlite.rawQuery("select *  from paline", null);
		Vector <DBObject> list = null;
		if(cursor.moveToFirst())
		{
			list = new Vector<DBObject>();
			do {
				Palina element = new Palina(cursor);
				list.add(element);
			} while(cursor.moveToNext());
		}
		cursor.close();
		sqlite.close();
		return list;
	}
	
	/**
	 * Returns a list of all bus-stops avaiable in the database
	 * @return a vector of all bus-stops in the database
	 */
	public static Vector <DBObject> getMapList()
	{
		MySQLiteDBAdapter sqlite = MySQLiteDBAdapter.getInstance(SASAbus.getContext());
		Cursor cursor = sqlite.rawQuery("select *  from paline order by nome_de", null);
		Vector <DBObject> list = null;
		if(cursor.moveToFirst())
		{
			list = new Vector<DBObject>();
			do {
				Palina element = new Palina(cursor);
				if(list.size() > 0 && !list.lastElement().toString().trim().equals(element.toString().trim()))
					list.add(element);
				else if(list.size() == 0)
					list.add(element);
			} while(cursor.moveToNext());
		}
		cursor.close();
		sqlite.close();
		return list;
	}
	
	/**
	 * Returns a list of all bus-stops avaiable in the database
	 * @return a vector of all bus-stops in the database
	 */
	public static Vector <DBObject> getNameList()
	{
		MySQLiteDBAdapter sqlite = MySQLiteDBAdapter.getInstance(SASAbus.getContext());
		Cursor cursor = sqlite.rawQuery("select distinct nome_de, nome_it from paline", null);
		Vector <DBObject> list = null;
		if(cursor.moveToFirst())
		{
			list = new Vector<DBObject>();
			do {
				Palina element = new Palina(cursor);
				list.add(element);
			} while(cursor.moveToNext());
		}
		cursor.close();
		sqlite.close();
		return list;
	}
	
	/**
	 * Returns a list of all bus-stops avaiable in the database
	 * @return a vector of all bus-stops in the database
	 */
	public static Vector <DBObject> getListLinea(int linea)
	{
		MySQLiteDBAdapter sqlite = MySQLiteDBAdapter.getInstance(SASAbus.getContext());
		String [] args = {Integer.toString(linea)};
		Cursor cursor = null;
		if((Locale.getDefault().getLanguage()).indexOf(Locale.GERMAN.toString()) != -1)
		{
			cursor = sqlite.rawQuery("select distinct paline.nome_de as nome_de, paline.nome_it as nome_it " +
					"from paline, " +
					"(select id from corse where lineaId = ?) as corse, " +
					"orarii " +
					"where orarii.corsaId = corse.id " +
					"AND orarii.palinaId = paline.id " +
					"order by paline.nome_de", args);
		}
		else
		{
				cursor = sqlite.rawQuery("select distinct paline.nome_de as nome_de, paline.nome_it as nome_it " +
				"from paline, " +
				"(select id from corse where lineaId = ?) as corse, " +
				"orarii " +
				"where orarii.corsaId = corse.id " +
				"AND orarii.palinaId = paline.id " +
				"order by paline.nome_it", args);
		}
		Vector <DBObject> list = null;
		if(cursor.moveToFirst())
		{
			list = new Vector<DBObject>();
			do {
				Palina element = new Palina(cursor);
				list.add(element);
			} while(cursor.moveToNext());
		}
		cursor.close();
		sqlite.close();
		return list;
	}
	
	/**
	 * Returns a list of all bus-stops avaiable in the database
	 * @return a vector of all bus-stops in the database
	 */
	public static Vector <DBObject> getListLinea(int linea, String table_prefix)
	{
		MySQLiteDBAdapter sqlite = MySQLiteDBAdapter.getInstance(SASAbus.getContext());
		String [] args = {Integer.toString(linea)};
		Cursor cursor = null;
		if((Locale.getDefault().getLanguage()).indexOf(Locale.GERMAN.toString()) != -1)
		{
			cursor = sqlite.rawQuery("select distinct paline.nome_de as nome_de, paline.nome_it as nome_it " +
					"from paline, " +
					"(select id from " + table_prefix + "corse where lineaId = ?) as corse, " + table_prefix +
					"orarii as orarii " +
					"where orarii.corsaId = corse.id " +
					"AND orarii.palinaId = paline.id " +
					"order by paline.nome_de", args);
		}
		else
		{
				cursor = sqlite.rawQuery("select distinct paline.nome_de as nome_de, paline.nome_it as nome_it " +
				"from paline, " +
				"(select id from " + table_prefix + "corse where lineaId = ?) as corse, " + table_prefix +
				"orarii as orarii " +
				"where orarii.corsaId = corse.id " +
				"AND orarii.palinaId = paline.id " +
				"order by paline.nome_it", args);
		}
		Vector <DBObject> list = null;
		if(cursor.moveToFirst())
		{
			list = new Vector<DBObject>();
			do {
				Palina element = new Palina(cursor);
				list.add(element);
			} while(cursor.moveToNext());
		}
		cursor.close();
		sqlite.close();
		return list;
	}
	
	
	/**
	 * Returns a list of all bus-stops avaiable in the database which were connected via linea to
	 * the destination destinazione
	 * @param destinazione is the name of the destination busstop
	 * @param linea is the number of the line tho connect 
	 * @return a vector of all bus-stops in the database which were connected via linea to the destination
	 */
	public static Vector <DBObject> getListDestinazione(String destinazione, int linea, String table_prefix)
	{	
		MySQLiteDBAdapter sqlite = MySQLiteDBAdapter.getInstance(SASAbus.getContext());
		String [] args = {Integer.toString(linea),destinazione};
		String query = "select distinct p.nome_de as nome_de, p.nome_it as nome_it " +
				"from " +
				"(select id, lineaId " +
				"from " + table_prefix + "corse as corse " +
				"where  " +
				"lineaId = ? " +
				"and substr(corse.effettuazione,round(strftime('%J','now','localtime')) - round(strftime('%J', '" + Config.getStartDate() + "')) + 1,1)='1' " + 
				") as c, " +
				"(select progressivo, orario, corsaId " +
				"from " + table_prefix + "orarii " +
				"where palinaId IN ( " +
				"select id from paline where nome_de = ? " +		
				")) as o1, " +
				"" + table_prefix + "orarii as o2, " +
				"paline p " +
				"where " +
				"o1.corsaId = c.id " +
				"and o2.corsaId = o1.corsaId " +
				"and o2.palinaId = p.id " +
				"and o1.progressivo < o2.progressivo " +
				"order by p.nome_it";
		if((Locale.getDefault().getLanguage()).indexOf(Locale.GERMAN.toString()) != -1)
		{
			query = "select distinct p.nome_de as nome_de, p.nome_it as nome_it " +
					"from " +
					"(select id, lineaId " +
					"from " + table_prefix + "corse as corse " +
					"where  " +
					"lineaId = ? " +
					"and substr(corse.effettuazione,round(strftime('%J','now','localtime')) - round(strftime('%J', '" + Config.getStartDate() + "')) + 1,1)='1' " + 
					") as c, " +
					"(select progressivo, orario, corsaId " +
					"from " + table_prefix + "orarii " +
					"where palinaId IN ( " +
					"select id from paline where nome_de = ? " +		
					")) as o1, " +
					"" + table_prefix + "orarii as o2, " +
					"paline p " +
					"where " +
					"o1.corsaId = c.id " +
					"and o2.corsaId = o1.corsaId " +
					"and o2.palinaId = p.id " +
					"and o1.progressivo < o2.progressivo " +
					"order by p.nome_de";
		}
		Cursor cursor = sqlite.rawQuery(query, args);
		Vector <DBObject> list = null;
		if(cursor.moveToFirst())
		{
			list = new Vector<DBObject>();
			do {
				Palina element = new Palina(cursor);
				list.add(element);
			} while(cursor.moveToNext());
		}
		cursor.close();
		sqlite.close();
		return list;
	}
	
	
	/**
	 * Gets a lists of palinas which are in a certain radius of a location fix
	 */
	public static Vector<DBObject> getListGPS (Location loc) throws Exception
	{
		MySQLiteDBAdapter sqlite = MySQLiteDBAdapter.getInstance(SASAbus.getContext());
		/*
		 * The following values are calculated with the formula 40045km : deltakm = 360deg : deltadeg
		 * (40045 is an estimation of the ratio of Earth)
		 */
		
		Context con = SASAbus.getContext();
		
		SharedPreferences shared = PreferenceManager.getDefaultSharedPreferences(con);
		
		double deltadegrees = Double.parseDouble(shared.getString("radius_gps", "0.0018"));
		
		Log.v("preferences", "delta: " + deltadegrees);
		
		String latitudemin = Double.toString(loc.getLatitude() - deltadegrees);
		String longitudemin = Double.toString(loc.getLongitude() - deltadegrees);
		String latitudemax = Double.toString(loc.getLatitude() + deltadegrees);
		String longitudemax = Double.toString(loc.getLongitude() + deltadegrees);
		String [] args = {longitudemin, longitudemax, latitudemin, latitudemax, 
				Double.toString(deltadegrees), Double.toString(deltadegrees), longitudemin, 
				longitudemax, latitudemin, latitudemax};
		Cursor cursor = sqlite.rawQuery("select distinct nome_de, nome_it from paline where " +
				" (longitudine - ?) * (longitudine - ?) + (latitudine - ? ) * (latitudine - ?) <= ? * ?" +
				" order by (longitudine - ?) * (longitudine - ?) + (latitudine - ? ) * (latitudine - ?)", args);
		Vector <DBObject> list = null;
		if(cursor.moveToFirst())
		{
			list = new Vector<DBObject>();
			do {
				Palina element = new Palina(cursor);
				list.add(element);
			} while(cursor.moveToNext());
		}
		cursor.close();
		sqlite.close();
		return list;
	}
	
	
	/**
	 * Get the nearest palina of a locationfix
	 * @param loc is the location of the last fix
	 * @return a palina
	 * @throws Exception
	 */
	public static Palina getPalinaGPS (Location loc) throws Exception
	{
		MySQLiteDBAdapter sqlite = MySQLiteDBAdapter.getInstance(SASAbus.getContext());			
		String latitude = Double.toString(loc.getLatitude());
		String longitude = Double.toString(loc.getLongitude());
		String [] args = {longitude, longitude, latitude, latitude};
		Cursor cursor = sqlite.rawQuery("select distinct nome_de, nome_it, longitudine, latitudine from paline order by " +
				" (longitudine - ?) * (longitudine - ?) + (latitudine - ? ) * (latitudine - ?)", args);
		Palina palina = null;
		if(cursor.moveToFirst())
		{
			palina = new Palina(cursor);
		}
		cursor.close();
		sqlite.close();
		return palina;
	}

	
	
	/**
	 * Returns a Palina identified by the given id
	 * @param id is the id of the Palina in the database
	 * @return the palina with the id id from the database, NULL if the query was empty
	 */
	public static Palina getById(int id)
	{	
		MySQLiteDBAdapter sqlite = MySQLiteDBAdapter.getInstance(SASAbus.getContext());
		String [] args = {Integer.toString(id)};
		String query = "select distinct p.nome_de as nome_de, p.nome_it as nome_it, p.latitudine as latitudine, p.longitudine as longitudine " +
				"from paline p " +
				"where id = ? " +
				"LIMIT 1";
		Cursor cursor = sqlite.rawQuery(query, args);
		Palina element = null;
		if(cursor.moveToFirst())
		{
			element = new Palina(cursor);
			element.setId(id);
		}
		cursor.close();
		sqlite.close();
		return element;
	}
	
	/**
	 * Returns a Palina filled with all the information, excluded the coordinates, becaus one name can have 2 coordinates
	 * @param name is the name of the palina to search
	 * @param lang is the language of the name
	 * @return the palina with the name name, otherwise NULL if the plaina was not found
	 */
	public static Palina getTranslation(String name, String lang)
	{	
		MySQLiteDBAdapter sqlite = MySQLiteDBAdapter.getInstance(SASAbus.getContext());
		String [] args = {name};
		String query = "select distinct p.nome_de as nome_de, p.nome_it as nome_it " +
				"from paline p " +
				"where nome_de = ? " +
				"LIMIT 1";
		if (lang.equals("it"))
		{
			query = "select distinct p.nome_de as nome_de, p.nome_it as nome_it " +
					"from paline p " +
					"where nome_it = ? " +
					"LIMIT 1";
		}
		Cursor cursor = sqlite.rawQuery(query, args);
		Palina element = null;
		if(cursor.moveToFirst())
		{
			element = new Palina(cursor);
		}
		cursor.close();
		sqlite.close();
		return element;
	}
	
}
 public class About {

	private Activity mActivity;

	public About(Activity context) {
		mActivity = context;
	}

	private PackageInfo getPackageInfo() {
		PackageInfo pi = null;
		try {
			pi = mActivity.getPackageManager().getPackageInfo(
					mActivity.getPackageName(), PackageManager.GET_ACTIVITIES);
		} catch (PackageManager.NameNotFoundException e) {
			e.printStackTrace();
		}
		return pi;
	}

	public void show() {
		PackageInfo versionInfo = getPackageInfo();

		// Show the About Dialog
		String title = mActivity.getString(R.string.app_name) + " v"
				+ versionInfo.versionName;

		String currentYear = Integer.toString(Calendar.getInstance().get(Calendar.YEAR));
		String firstCopyrightYear = mActivity.getString(R.string.copyright_first_year);
		String copyrightYearInterval = firstCopyrightYear;
		if (currentYear.compareTo(firstCopyrightYear) > 0) {
			copyrightYearInterval = firstCopyrightYear + "-" + currentYear;
		}
		// Includes the updates as well so users know what changed.
		String message =
		// mActivity.getString(R.string.updates) +
		String.format(mActivity.getString(R.string.copyright),copyrightYearInterval) + "\n\n"
				+ mActivity.getString(R.string.supp_email) + "\n\n"
				+ mActivity.getString(R.string.license) + "\n\n"
				+ mActivity.getString(R.string.disclaimer) + "\n\n"
				+ mActivity.getString(R.string.gpl);

		AlertDialog.Builder builder = new AlertDialog.Builder(mActivity)
				.setTitle(title).setMessage(message).setPositiveButton(
						android.R.string.ok, new Dialog.OnClickListener() {

							@Override
							public void onClick(
									DialogInterface dialogInterface, int i) {
								dialogInterface.dismiss();
							}
						});
		builder.create().show();
	}

} public class Credits {

	private Activity mActivity;

	public Credits(Activity context) {
		mActivity = context;
	}

	private PackageInfo getPackageInfo() {
		PackageInfo pi = null;
		try {
			pi = mActivity.getPackageManager().getPackageInfo(
					mActivity.getPackageName(), PackageManager.GET_ACTIVITIES);
		} catch (PackageManager.NameNotFoundException e) {
			e.printStackTrace();
		}
		return pi;
	}

	public void show() {
		PackageInfo versionInfo = getPackageInfo();

		// Show the About Dialog
		String title = mActivity.getString(R.string.menu_credits);

		String message = mActivity.getString(R.string.credits_text);

		AlertDialog.Builder builder = new AlertDialog.Builder(mActivity)
				.setTitle(title).setMessage(message).setPositiveButton(
						android.R.string.ok, new Dialog.OnClickListener() {

							@Override
							public void onClick(
									DialogInterface dialogInterface, int i) {
								dialogInterface.dismiss();
							}
						});
		builder.create().show();
	}

} public class SelectFavoritenDialog extends Dialog implements OnItemClickListener {

    
    private Vector<Favorit> list = null;
    
    private OnlineSearchFragment fragment = null;
    
    public SelectFavoritenDialog(OnlineSearchFragment fragment) {
    	super(fragment.getActivity());
    	this.fragment = fragment;
    }

    /** Called with the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.favoriten_listview);
        
        this.setTitle(R.string.mode_favoriten);
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
    	lp.copyFrom(getWindow().getAttributes());
    	lp.width = WindowManager.LayoutParams.FILL_PARENT;
    	lp.height = WindowManager.LayoutParams.FILL_PARENT;
    	getWindow().setAttributes(lp);
    	Display dm = getWindow().getWindowManager().getDefaultDisplay();
        int width = dm.getWidth();
        int height = dm.getHeight();
        getWindow().setLayout(width/5*4, height/2);
        fillData();
    }

    
    @Override
    public void onItemClick(AdapterView<?> av, View l, int position, long id) {
        Favorit fav = list.get(position);
        String namefrom = fav.getPartenza();
        String nameto = fav.getDestinazione();
        
        String namefromloc = "";
        String nametoloc = "";
        
        if((Locale.getDefault().getLanguage()).indexOf(Locale.GERMAN.toString()) != -1)
		{
			String italienischfrom = namefrom.substring(0, namefrom.indexOf("-")).trim();
			Palina stationfrom = PalinaList.getTranslation(italienischfrom, "it");
			if(stationfrom != null)
			{
				namefromloc = stationfrom.getName_de();
				namefromloc =  namefromloc.substring(1, namefromloc.indexOf(")"))+ " - " +
						namefromloc.substring(namefromloc.indexOf(")") + 1).trim();
			}
			else
			{
				String geteilt = namefrom.substring(namefrom.indexOf("-") + 1).trim();
				namefromloc =  geteilt.substring(1, geteilt.indexOf(")"))+ " - " +
						geteilt.substring(geteilt.indexOf(")") + 1).trim();
			}
			String italienischto = nameto.substring(0, nameto.indexOf("-")).trim();
			Palina stationto = PalinaList.getTranslation(italienischto, "it");
			if(stationto != null)
			{
				nametoloc = stationto.getName_de();
				nametoloc =  nametoloc.substring(1, nametoloc.indexOf(")"))+ " - " +
						nametoloc.substring(nametoloc.indexOf(")") + 1).trim();
			}
			else
			{
				String geteilt = nameto.substring(nameto.indexOf("-") + 1).trim();
				nametoloc =  geteilt.substring(1, geteilt.indexOf(")"))+ " - " +
						geteilt.substring(geteilt.indexOf(")") + 1).trim();
			}
		}
		else
		{
			String geteiltfrom = namefrom.substring(0, namefrom.indexOf("-")).trim();
			namefromloc = geteiltfrom.substring(1, geteiltfrom.indexOf(")")) + " - " + 
					geteiltfrom.substring(geteiltfrom.indexOf(")") + 1).trim();
			String geteiltto = nameto.substring(0, namefrom.indexOf("-")).trim();
			nametoloc = geteiltto.substring(1, geteiltto.indexOf(")")) + " - " + 
					geteiltto.substring(geteiltto.indexOf(")") + 1).trim();
		}
        
        View result = fragment.getResult();
        AutoCompleteTextView from = (AutoCompleteTextView)result.findViewById(R.id.from_text);
        AutoCompleteTextView to = (AutoCompleteTextView)result.findViewById(R.id.to_text);
        
        from.setText(namefromloc);
        to.setText(nametoloc);
        
        
    	this.dismiss();
    }
    
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {
      if (v.getId() == android.R.id.list) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
        menu.setHeaderTitle(list.get(info.position).toString());
        menu.add(Menu.NONE, 0, 0, R.string.delete);
      }
    }
    
    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
    	AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
        int menuItemIndex = item.getItemId();
        if(menuItemIndex == 0)
        {
      	  Favorit fav = list.get(info.position);
      	  SQLiteDatabase db = new FavoritenDB(getContext()).getWritableDatabase();
      	  if(fav.delete(db))
      		  Log.v("FAVORITENLOESCHEN", "OK");
      	  else 
      		  Log.v("FAVORITENLOESCHEN", "FEHLER");
      	  db.close();
      	  list.remove(info.position);
      	  MyFavoritenListAdapter favoriten = new MyFavoritenListAdapter(SASAbus.getContext(), list);
      	  ListView liste = (ListView)findViewById(android.R.id.list);
      	  liste.setAdapter(favoriten);
        }
        return false;
    }
    
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
      AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
      int menuItemIndex = item.getItemId();
      if(menuItemIndex == 0)
      {
    	  Favorit fav = list.get(info.position);
    	  SQLiteDatabase db = new FavoritenDB(getContext()).getWritableDatabase();
    	  if(fav.delete(db))
    		  Log.v("FAVORITENLOESCHEN", "OK");
    	  else 
    		  Log.v("FAVORITENLOESCHEN", "FEHLER");
    	  db.close();
    	  list.remove(info.position);
    	  MyFavoritenListAdapter favoriten = new MyFavoritenListAdapter(SASAbus.getContext(), list);
    	  ListView liste = (ListView)findViewById(android.R.id.list);
    	  liste.setAdapter(favoriten);
      }
      return false;
    }
    
    
    /**
     * fills the list_view with the modes which are offered to the user
     */
    public void fillData()
    {
    	 list = FavoritenList.getList();
    	 MyFavoritenListAdapter favoriten = new MyFavoritenListAdapter(SASAbus.getContext(), list);
    	 ListView liste = (ListView)findViewById(android.R.id.list);
         liste.setAdapter(favoriten); 
         registerForContextMenu(liste);
         liste.setOnItemClickListener(this);
         liste.setOnCreateContextMenuListener(this);
    }
    


	
}
 public class CheckUpdate extends AsyncTask<Void, String, Long> {

	private final OnlineSearchFragment activity;
	
	private final String TAG = "CheckUpdate";

	public CheckUpdate(OnlineSearchFragment activity) {
		super();
		this.activity = activity;
	}

	@Override
	protected Long doInBackground(Void... params) {
		SASAbus config = (SASAbus) activity.getActivity().getApplicationContext();
		Resources res = activity.getResources();
		String dbDirName = res.getString(R.string.db_dir);
		String dbFileName = res.getString(R.string.app_name_db) + ".db";
		String md5dbFileName = dbFileName + ".md5";
		// Check if the sd-card is mounted
		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			return Long.valueOf(OnlineSearchFragment.NO_SD_CARD);
		}
		File dbDir = new File(Environment.getExternalStorageDirectory(),
				dbDirName);
		// check if dbDir exists; if not create it
		if (!dbDir.exists()) {
			dbDir.mkdirs();
			return Long.valueOf(OnlineSearchFragment.DOWNLOAD_FILES);
		}
		// creates all files (zip, md5 and db)
		File dbFile = new File(dbDir, dbFileName);
		File md5dbFile = new File(dbDir, md5dbFileName);
		boolean download = false;
		if (dbFile.exists() && md5dbFile.exists()) {
			/*
			 * checks if the md5-sum are equal if not, directly download is
			 * true, whe have to do an update else we are checking other
			 * properties to download new database or not
			 */
			if (!MD5Utils.checksumOK(dbFile, md5dbFile)) {
				download = true;
			} else {
				String end = null;
				try {
					end = Config.getEndDate();
				} catch (Exception e) {
					e.printStackTrace();
				}
				SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd");
				Calendar cal = Calendar.getInstance();
				try {
					Date endDate = timeFormat.parse(end);
					Date currentDate = timeFormat.parse(timeFormat.format(cal
							.getTime()));
					Log.v("CheckDatabaseActivity",
							"endDate: " + endDate.toString()
									+ "; currentDate: "
									+ currentDate.toString());
					if (currentDate.after(endDate)) {
						download = true;
						config.setDbDownloadAttempts(config
								.getDbDownloadAttempts() + 1);
					}
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (!download && fileUpdateAvailable(md5dbFileName, dbDir)) {
					download = true;
				}
			}
		} else {
			download = true;
			return Long.valueOf(OnlineSearchFragment.DOWNLOAD_FILES);
		}
		if(download)
			return Long.valueOf(OnlineSearchFragment.DOWNLOAD_AVAILABLE);
		
		
		dbDirName = res.getString(R.string.db_dir);
		dbFileName = res.getString(R.string.app_name_osm) + ".map";
		md5dbFileName = dbFileName + ".md5";

		// Check if the sd-card is mounted
		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			return Long.valueOf(CheckDatabaseActivity.NO_SD_CARD);
		}

		// creates all files (zip, md5 and db)
		dbFile = new File(dbDir, dbFileName);
		md5dbFile = new File(dbDir, md5dbFileName);

		download = false;
		if (dbFile.exists() && md5dbFile.exists()) {
			/*
			 * checks if the md5-sum are equal if not, directly download is
			 * true, whe have to do an update else we are checking other
			 * properties to download new database or not
			 */
			if (!MD5Utils.checksumOK(dbFile, md5dbFile)) {
				download = true;
			} else {
				String end = null;
				try {
					end = Config.getEndDate();
				} catch (Exception e) {
					e.printStackTrace();
				}
				SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd");
				Calendar cal = Calendar.getInstance();
				try {
					Date endDate = timeFormat.parse(end);
					Date currentDate = timeFormat.parse(timeFormat.format(cal
							.getTime()));
					Log.v("CheckDatabaseActivity",
							"endDate: " + endDate.toString()
									+ "; currentDate: "
									+ currentDate.toString());
					if (currentDate.after(endDate)) {
						download = true;
						config.setDbDownloadAttempts(config
								.getDbDownloadAttempts() + 1);
					}
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (!download && fileUpdateAvailable(md5dbFileName, dbDir)) {
					download = true;
				}
			}
		} else {
			download = true;
			return Long.valueOf(OnlineSearchFragment.DOWNLOAD_FILES);
		}
		if(download)
			return Long.valueOf(OnlineSearchFragment.DOWNLOAD_AVAILABLE);
		return Long.valueOf(OnlineSearchFragment.DB_OK);
		
	}
	
	@Override
	protected void onPostExecute(Long result) {
		super.onPostExecute(result);
		activity.showDialog(result.intValue(), OnlineSearchFragment.DB_UP);

	}

	/**
	 * this method controlls if a db-update is available. downloads the md5-file
	 * of the server and checks if the md5 is a new md5. when it is, then
	 * returns true, else false
	 * 
	 * @param md5FileName
	 *            is the filename of the md5-file on the server
	 * @param dbDir
	 *            is the local dirname to put into the downloaded md5
	 * @return a boolean to determinate if an update is necessary or not
	 */
	public boolean fileUpdateAvailable(String md5FileName, File dbDir) {
		boolean update = false;
		File md5File = new File(dbDir, md5FileName);
		long lastLocalMod = md5File.lastModified();
		Date lastLocalModDate = new Date(lastLocalMod);
		String lastRemoteMod;
		Date lastRemoteModDate;
		Resources res = activity.getResources();

		// verify we have a network connection, otherwise act as no update is
		// available
		// and update remains false
		if (haveNetworkConnection()) {
			try {
				/*
				 * istanziate an object of the SasabusFTP, which provides the
				 * most important methods for connecting and getting files from
				 * an FTP server
				 */
				SasabusFTP ftp = new SasabusFTP();
				// SasabusHTTP http = new
				// SasabusHTTP(res.getString(R.string.http_repository_url));

				// connecting and login to the server
				ftp.connect(res.getString(R.string.repository_url), Integer
						.parseInt(res.getString(R.string.repository_port)));
				ftp.login(res.getString(R.string.ftp_user),
						res.getString(R.string.ftp_passwd));

				//
				lastRemoteMod = ftp.getModificationTime(md5FileName);
				ftp.disconnect();
				SimpleDateFormat simple = new SimpleDateFormat("yyyyMMddhhmmss");
				TimeZone utcZone = TimeZone.getTimeZone("UTC");
				simple.setTimeZone(utcZone);
				lastRemoteModDate = simple.parse(lastRemoteMod);
				// lastRemoteModDate = http.getModificationTime(md5FileName);
				// check if date of remote file is after date of local file
				update = lastRemoteModDate.after(lastLocalModDate);

				Log.v("CheckDatabaseActivity", "Date of local md5: "
						+ lastLocalModDate.toString());
				Log.v("CheckDatabaseActivity", "Date of remote md5: "
						+ lastRemoteModDate.toString());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return update;
	}

	/**
	 * this method checks if a networkconnection is active or not
	 * 
	 * @return boolean if the network is reachable or not
	 */
	private boolean haveNetworkConnection() {
		boolean haveConnectedWifi = false;
		boolean haveConnectedMobile = false;

		ConnectivityManager cm = (ConnectivityManager) (activity
				.getActivity().getSystemService(Context.CONNECTIVITY_SERVICE));
		NetworkInfo[] netInfo = cm.getAllNetworkInfo();
		for (NetworkInfo ni : netInfo) {
			// testing WIFI connection
			if (ni.getTypeName().equalsIgnoreCase("WIFI"))
				if (ni.isConnected())
					haveConnectedWifi = true;
			// testing GPRS/EDGE/UMTS/HDSPA/HUSPA/LTE connection
			if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
				if (ni.isConnected())
					haveConnectedMobile = true;
		}
		return haveConnectedWifi || haveConnectedMobile;
	}
} public class FileRetriever  extends AsyncTask<Void, String, Long>{
	
	private static final int MAX_DOWNLOAD = 5;
	
	private static final String TAG = "FileRetriever";
	
	private ProgressDialog progressDialog;

	private File dbZIPFile;
	private File md5File;
	private Resources res;

	private String filename;
	private CheckDatabaseActivity activity;
	
	private String download = null;
	private String unzipping = null;
	
	private int downloadcounter = 0;

	/**
	 * This constructor takes an activity, a dbZipFile to store the 
	 * downloaded Zip file, a dbFile to store the unzipped database and at least
	 * a md5File to save the downloaded md5File
	 * @param activity is the actual activity
	 * @param dbZIPFile is the file to save the downloaded zip file
	 * @param dbFile is the file to save the unzipped db file
	 * @param md5File is the file to save the downloaded md5 file
	 */
	public FileRetriever(CheckDatabaseActivity activity, String filename) {
		super();
		this.filename = filename;
		this.activity = activity;
		this.res = activity.getResources();

	}
	
	public FileRetriever(CheckDatabaseActivity activity, String filename, String download, String unzipping) {
		super();
		this.activity = activity;
		this.res = activity.getResources();
		this.filename = filename;
		this.download = download;
		this.unzipping = unzipping;

		
	}

	

	
	/**
	 * @return the progressDialog
	 */
	public ProgressDialog getProgressDialog() {
		return progressDialog;
	}

	/**
	 * @param progressDialog the progressDialog to set
	 */
	public void setProgressDialog(ProgressDialog progressDialog) {
		this.progressDialog = progressDialog;
	}

	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
	}

	@Override
	protected Long doInBackground(Void...params) {	
		Log.v("FileRetriever", "Bin beim Download, " + this.filename + "!");
		SASAbus config = (SASAbus) activity.getApplicationContext();
		// Check if db exists
		Resources res = activity.getResources();
		String dbDirName = res.getString(R.string.db_dir);
		String dbFileName = this.filename;
		String dbZIPFileName = dbFileName + ".zip";
		String md5FileName = dbFileName + ".md5";

		//Check if the sd-card is mounted
		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			return Long.valueOf(CheckDatabaseActivity.NO_SD_CARD);
		}
		File dbDir = new File(Environment.getExternalStorageDirectory(),
				dbDirName);
		// check if dbDir exists; if not create it
		if (!dbDir.exists()) {
			dbDir.mkdirs();
		}

		//creates all files (zip, md5 and db)
		Log.v("FR", "Open db file");
		File dbFile = new File(dbDir, dbFileName);
		Log.v("FR", "Open db file");
		dbZIPFile = new File(dbDir, dbZIPFileName);
		Log.v("FR", "Open db file");
		md5File = new File(dbDir, md5FileName);

		
		boolean download = false;
		if (dbFile.exists() && md5File.exists())
		{
			/*
			 * checks if the md5-sum are equal
			 * if not, directly download is true, whe have to do an update
			 * else we are checking other properties to download new database or not
			 */
			if (!MD5Utils.checksumOK(dbFile, md5File))
			{
				download = true;
			}
			else 
			{
				String end = null;
				try
				{
					end = Config.getEndDate();
				}
				catch(Exception e)
				{
					e.printStackTrace();
				}
				SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd");
				Calendar cal = Calendar.getInstance();
				try 
				{
					Date endDate = timeFormat.parse(end);
					Date currentDate = timeFormat.parse(timeFormat.format(cal
							.getTime()));
					Log.v("CheckDatabaseActivity", "endDate: " + endDate.toString() + "; currentDate: " + currentDate.toString());
					if (currentDate.after(endDate)) 
					{
						download = true;
						config.setDbDownloadAttempts(config.getDbDownloadAttempts() + 1);
					}
				} 
				catch (ParseException e) 
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (!download && fileUpdateAvailable(md5FileName, dbDir)) 
				{
					download = true;
				}
			}
		} 
		else 
		{
			download = true;
		}

		if (download) 
		{
			// verify we have a network connection
			if (haveNetworkConnection()) 
			{
				
				if(config.getDbDownloadAttempts() < 2) 
				{
					//download the new Database and the new md5-file with the FileRetriver
					int result = download(dbZIPFileName, md5FileName);
					Log.v("FR", "Nach herausschmeissen bin ich hier mit wert: " + result + "!");
					return Long.valueOf(result);
				}
				else 
				{
					//if no db-update is available will be shown a message
					return Long.valueOf(CheckDatabaseActivity.NO_DB_UPDATE_AVAILABLE);
				}
			} 
			else 
			{
				//shows dialog for no network connection
				return Long.valueOf(CheckDatabaseActivity.NO_NETWORK_CONNECTION);
			}
		}
		else 
		{
			// verify files
			if (!MD5Utils.checksumOK(dbFile, md5File)) 
			{
				//shows dialog that occours a md5-error
				return Long.valueOf(CheckDatabaseActivity.MD5_ERROR_DIALOG);
			}
			else 
			{
				//shows dialog that download success
				return Long.valueOf(CheckDatabaseActivity.DOWNLOAD_SUCCESS_DIALOG);
			}
		}
	}
		
		
		
	/**
	 * this method controlls if a db-update is available.
	 * downloads the md5-file of the server and checks if the md5 is a 
	 * new md5. when it is, then returns true, else false
	 * @param md5FileName is the filename of the md5-file on the server
	 * @param dbDir is the local dirname to put into the downloaded md5 
	 * @return a boolean to determinate if an update is necessary or not
	 */
	public boolean fileUpdateAvailable(String md5FileName, File dbDir) {
		boolean update = false;
		File md5File = new File(dbDir, md5FileName);
		long lastLocalMod = md5File.lastModified();
		Date lastLocalModDate = new Date(lastLocalMod);
		String lastRemoteMod;
		Date lastRemoteModDate;
		Resources res = activity.getResources();

		// verify we have a network connection, otherwise act as no update is available
		// and update remains false
		if (haveNetworkConnection()) 
		{
			try 
			{
				/*
				 * istanziate an object of the SasabusFTP, which provides the most
				 * important methods for connecting and getting files from an FTP 
				 * server
				 */
				SasabusFTP ftp = new SasabusFTP();
				//SasabusHTTP http = new SasabusHTTP(res.getString(R.string.http_repository_url));
				
				
				//connecting and login to the server
				ftp.connect(res.getString(R.string.repository_url), Integer.parseInt(res.getString(R.string.repository_port)));
				ftp.login(res.getString(R.string.ftp_user), res.getString(R.string.ftp_passwd));
				
				//
				lastRemoteMod = ftp.getModificationTime(md5FileName);
				ftp.disconnect();
				SimpleDateFormat simple = new SimpleDateFormat("yyyyMMddhhmmss");
				TimeZone utcZone = TimeZone.getTimeZone("UTC");
				simple.setTimeZone(utcZone);
				lastRemoteModDate = simple.parse(lastRemoteMod);
//				lastRemoteModDate = http.getModificationTime(md5FileName);
				// check if date of remote file is after date of local file
				update = lastRemoteModDate.after(lastLocalModDate);

				Log.v("CheckDatabaseActivity", "Date of local md5: " + lastLocalModDate.toString());
				Log.v("CheckDatabaseActivity", "Date of remote md5: " + lastRemoteModDate.toString());
			}
			catch (Exception e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return update;
	}
	
	
	/**
	 * this method checks if a networkconnection is active or not
	 * @return boolean if the network is reachable or not
	 */
	private boolean haveNetworkConnection() 
	{
		boolean haveConnectedWifi = false;
		boolean haveConnectedMobile = false;

		ConnectivityManager cm = (ConnectivityManager) (activity.getSystemService(Context.CONNECTIVITY_SERVICE));
		NetworkInfo[] netInfo = cm.getAllNetworkInfo();
		for (NetworkInfo ni : netInfo) {
			//testing WIFI connection
			if (ni.getTypeName().equalsIgnoreCase("WIFI"))
				if (ni.isConnected())
					haveConnectedWifi = true;
			//testing GPRS/EDGE/UMTS/HDSPA/HUSPA/LTE connection
			if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
				if (ni.isConnected())
					haveConnectedMobile = true;
		}
		return haveConnectedWifi || haveConnectedMobile;
	}
		
		
	private int downloadFile(SasabusFTP ftp, String dbZIPFileName, String md5FileName) throws FileNotFoundException
	{
		progressDialog = new ProgressDialog(this.activity);
		
		progressDialog = new ProgressDialog(this.activity);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		if(download == null)
			progressDialog.setMessage(res.getString(R.string.downloading_db));
		else
			progressDialog.setMessage(download);
		progressDialog.setCancelable(false);
		
		// download the file
		FileOutputStream output = new FileOutputStream(dbZIPFile);
		
		try 
		{
			ftp.bin();
			ftp.get(output, dbZIPFileName, this);
//			http.get(output, dbZIPFileName, this);
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
			progressDialog.dismiss();
			try
			{
				ftp.disconnect();
				output.flush();
				output.close();
			}
			catch(Exception ex)
			{
				ex.printStackTrace();
			}
			
			return CheckDatabaseActivity.DOWNLOAD_RETRY;
		}
		try
		{
			output.flush();
			output.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		progressDialog.dismiss();
		return CheckDatabaseActivity.DB_OK;
	}
		
	
	private int downloadMD5File(SasabusFTP ftp, String dbZIPFileName, String md5FileName) throws FileNotFoundException
	{
		progressDialog = new ProgressDialog(this.activity);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progressDialog.setMessage(res.getString(R.string.downloading_md5));
		progressDialog.setCancelable(false);
		
		FileOutputStream output = new FileOutputStream(this.md5File);
		
		
		try {
			ftp.bin();
			ftp.get(output, md5FileName, this);
//			http.get(output, md5FileName, this);
		} catch (Exception e) {
			e.printStackTrace();
			progressDialog.dismiss();
			try
			{
				ftp.disconnect();
				output.flush();
				output.close();
			}
			catch(Exception ex)
			{
				ex.printStackTrace();
			}
			return CheckDatabaseActivity.DOWNLOAD_RETRY;
		}
		try
		{
			output.flush();
			output.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		progressDialog.dismiss();
		return CheckDatabaseActivity.DB_OK;
	}
	
	private int unzip()
	{
		progressDialog = new ProgressDialog(this.activity);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		if(unzipping == null)
			progressDialog.setMessage(res.getString(R.string.unzipping_db));
		else
			progressDialog.setMessage(unzipping);
		progressDialog.setCancelable(false);
		progressDialog.setProgress(0);
		Decompress d = new Decompress(dbZIPFile.getAbsolutePath(),
				dbZIPFile.getParent());
		d.unzip();
		dbZIPFile.delete();
		
		File dbFile = new File(dbZIPFile.getParentFile().getAbsolutePath(), this.filename);
		if(!MD5Utils.checksumOK(dbFile, md5File))
		{
			progressDialog.dismiss();
			return CheckDatabaseActivity.MD5_ERROR_DIALOG;
		}
		
		progressDialog.dismiss();
		return CheckDatabaseActivity.DB_OK;
	}
	
	private int download(String dbZIPFileName, String md5FileName)
	{
		//creating a new ftp connection
//		SasabusHTTP http = new SasabusHTTP(activity.getResources().getString(R.string.http_repository_url));
		SasabusFTP ftp = new SasabusFTP();
		
		Looper.prepare();
//		SasabusHTTP http = null;
		try {
			try
			{
				ftp.connect(res.getString(R.string.repository_url), Integer.parseInt(res.getString(R.string.repository_port)));
				ftp.login(res.getString(R.string.ftp_user), res.getString(R.string.ftp_passwd));
			}
			catch (Exception e)
			{
				e.printStackTrace();
				return CheckDatabaseActivity.DOWNLOAD_RETRY;
			}
			
			// download dbZIPFile
			while(downloadFile(ftp, dbZIPFileName, md5FileName) != CheckDatabaseActivity.DB_OK 
					&& downloadcounter < MAX_DOWNLOAD)
			{
				++downloadcounter;
			}
			
			
	
			// download md5sum
			while(downloadMD5File(ftp, dbZIPFileName, md5FileName) != CheckDatabaseActivity.DB_OK 
					&& downloadcounter < MAX_DOWNLOAD)
			{
				++downloadcounter;
			}
			try
			{
				ftp.disconnect();
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			if(downloadcounter >= MAX_DOWNLOAD)
			{
				return CheckDatabaseActivity.DOWNLOAD_RETRY;
			}
			
			// unzip dbZIPFile
			unzip();

		} catch (Exception e) {
			e.printStackTrace();
			if(downloadcounter < MAX_DOWNLOAD)
			{
				++downloadcounter;
				return download(dbZIPFileName, md5FileName);
			}
			return CheckDatabaseActivity.DOWNLOAD_ERROR_DIALOG;
		}
		return CheckDatabaseActivity.DB_OK;
	}

	/**
	 * publishes the updated progress to the progressbar
	 * @param proc is the updated progress
	 */
	public void publishProgress(String proc) {
		super.publishProgress(proc);
	}
	
	@Override
	public void onProgressUpdate(String... args) {
		this.progressDialog.setProgress(Integer.parseInt(args[0]));
		progressDialog.show();
	}

	@Override
	protected void onPostExecute(Long result) {
		super.onPostExecute(result);

		Log.v("FileRetriever", "this result has been arrived in the onPostExecute-method: " + result);
		
		if(this.filename.equals(activity.getResources().getString(R.string.app_name_db) + ".db"))
		{
			activity.showDialog(result.intValue(), CheckDatabaseActivity.FR_DB);
		}
		else
		{
			activity.showDialog(result.intValue(), CheckDatabaseActivity.FR_OSM);
		}
		
		

	}
	
	
}
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.Vector;
import it.sasabz.android.sasabus.CheckDatabaseActivity;
import it.sasabz.android.sasabus.InfoActivity;
import it.sasabz.android.sasabus.MapSelectActivity;
import it.sasabz.android.sasabus.R;
import it.sasabz.android.sasabus.R.drawable;
import it.sasabz.android.sasabus.R.id;
import it.sasabz.android.sasabus.R.layout;
import it.sasabz.android.sasabus.R.menu;
import it.sasabz.android.sasabus.R.string;
import it.sasabz.android.sasabus.classes.DateTimePicker;
import it.sasabz.android.sasabus.classes.adapter.MyAutocompleteAdapter;
import it.sasabz.android.sasabus.classes.adapter.MySQLiteDBAdapter;
import it.sasabz.android.sasabus.classes.dbobjects.DBObject;
import it.sasabz.android.sasabus.classes.dbobjects.Palina;
import it.sasabz.android.sasabus.classes.dbobjects.PalinaList;
import it.sasabz.android.sasabus.classes.dialogs.About;
import it.sasabz.android.sasabus.classes.dialogs.Credits;
import it.sasabz.android.sasabus.classes.dialogs.SelectFavoritenDialog;
import it.sasabz.android.sasabus.classes.services.CheckUpdate;
import it.sasabz.android.sasabus.classes.services.FileRetriever;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

							datetimestring += (month + "." + year + " ");
							if(hour < 10)
							{
								datetimestring += "0";
							}
							datetimestring += (hour + ":");
							if(min < 10)
							{
								datetimestring += "0";
							}
							datetimestring += min;
							
							switch(append)
							{
							case 1:
								datetimestring += " AM";
								break;
							case 2:
								datetimestring += " PM";
								break;
							}
							
							TextView time = (TextView)result.findViewById(R.id.time);
							time.setText(datetimestring);
							mDateTimeDialog.dismiss();
						}
					});
				// Cancel the dialog when the "Cancel" button is clicked
				((Button) mDateTimeDialogView.findViewById(R.id.CancelDialog))
						.setOnClickListener(new View.OnClickListener() {

							public void onClick(View v) {
								// TODO Auto-generated method stub
								mDateTimeDialog.cancel();
							}
						});

				// Reset Date and Time pickers when the "Reset" button is
				// clicked
				((Button) mDateTimeDialogView.findViewById(R.id.ResetDateTime))
						.setOnClickListener(new View.OnClickListener() {

							public void onClick(View v) {
								// TODO Auto-generated method stub
								mDateTimePicker.reset();
							}
						});

				// Setup TimePicker
				mDateTimePicker.setIs24HourView(is24h);
				// No title on the dialog window
				mDateTimeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
				// Set the dialog content view
				mDateTimeDialog.setContentView(mDateTimeDialogView);
				// Display the dialog
				mDateTimeDialog.show();
			}

		});
        from = (AutoCompleteTextView)result.findViewById(R.id.from_text);
        to = (AutoCompleteTextView)result.findViewById(R.id.to_text);

        from.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            	InputMethodManager mgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    			mgr.hideSoftInputFromWindow(from.getWindowToken(), 0);
            }
        });
        
        to.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            	InputMethodManager mgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    			mgr.hideSoftInputFromWindow(to.getWindowToken(), 0);
            }
        });
        
        LocationManager locman = (LocationManager)this.getActivity().getSystemService(Context.LOCATION_SERVICE);
        Location lastloc = locman.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if(MySQLiteDBAdapter.exists(this.getActivity()))
        {
	        if(lastloc == null)
	        {
	        	lastloc = locman.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
	        }
	        if(lastloc != null)
	        {
	        	try
	        	{
	        		Palina palina = PalinaList.getPalinaGPS(lastloc);
	        		if(palina != null)
	        		{
	        			from.setHint(palina.toString());
	        		}
	        	}
	        	catch(Exception e)
	        	{
	        		Log.e("HomeActivity", "Fehler bei der Location", e);
	        	}
	        }
	        else
	        {
	        	Log.v("HomeActivity", "No location found!!");
	        }
	        Vector<DBObject> palinalist = PalinaList.getNameList(); 
	        MyAutocompleteAdapter adapterfrom = new MyAutocompleteAdapter(this.getActivity(), android.R.layout.simple_list_item_1, palinalist);
	        MyAutocompleteAdapter adapterto = new MyAutocompleteAdapter(this.getActivity(), android.R.layout.simple_list_item_1, palinalist);
	        
	        from.setAdapter(adapterfrom);
	        to.setAdapter(adapterto);
	        InputMethodManager mgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
			mgr.hideSoftInputFromWindow(from.getWindowToken(), 0);
			mgr.hideSoftInputFromWindow(to.getWindowToken(), 0);
        }
        Button favorites = (Button)result.findViewById(R.id.favorites);
        favorites.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {

				SelectFavoritenDialog dialog = new SelectFavoritenDialog(getThis());
