public class SASAbus extends Application {
    private int dbDownloadAttempts;
    
    private static Context context = null;
 
    @Override
    public void onCreate() 
    {
        // Init values which could be loaded from files stored in res/raw
        setDbDownloadAttempts(0);
        super.onCreate();
        context = this.getApplicationContext();
    }

    @Override
    public void onTerminate()
    {
    	//do nothing
    	MySQLiteDBAdapter.closeAll();
    }
    
    /**
     * @return the Strings and Variables stored in the Context;
     */
    public static Context getContext()
    {
    	return context;
    }
    
	/**
	 * @param dbDownloadAttempts the dbDownloadAttempts to set
	 */
	public void setDbDownloadAttempts(int dbDownloadAttempts) {
		this.dbDownloadAttempts = dbDownloadAttempts;
	}

	/**
	 * @return the dbDownloadAttempts
	 */
	public int getDbDownloadAttempts() {
		return dbDownloadAttempts;
	}
 

} public class Favorit {
	
	private int id = 0;
	
	private String partenza = null;
	
	private String destinazione = null;
	
	public Favorit()
	{
		
	}
	
	public Favorit(String partenza_de, String destinazione_de)
	{
		this.partenza = partenza_de;
		this.destinazione = destinazione_de;
	}
	
	public Favorit(int id, String partenza_de, String destinazione_de)
	{
		this.id = id;
		this.partenza = partenza_de;
		this.destinazione = destinazione_de;
	}

	
	/**
	 * @return the id
	 */
	public int getId() {
		return id;
	}

	/**
	 * @param id the id to set
	 */
	public void setId(int id) {
		this.id = id;
	}
	

	/**
	 * @return the partenza_de
	 */
	public String getPartenza() {
		return partenza;
	}
	
	public String getPartenzaString() {
		String ret = "";
		String fromItalienisch = getPartenza().substring(0, getPartenza().indexOf("-")).trim();
		Palina fromStation = PalinaList.getTranslation(fromItalienisch, "it");
		if(fromStation != null)
		{
			ret = fromStation.toString(); 
		}
		return ret;
	}

	/**
	 * @param partenza_de the partenza_de to set
	 */
	public void setPartenza(String partenza) {
		this.partenza = partenza;
	}

	public String getDestinazioneString() {
		String ret = "";
		String toItalienisch = getDestinazione().substring(0, getDestinazione().indexOf("-")).trim();
		Palina toStation = PalinaList.getTranslation(toItalienisch, "it");
		if(toStation != null)
		{
			ret = toStation.toString(); 
		}
		return ret;
	}
	
	/**
	 * @return the destinazione_de
	 */
	public String getDestinazione() {
		return destinazione;
	}

	/**
	 * @param destinazione_de the destinazione_de to set
	 */
	public void setDestinazione(String destinazione) {
		this.destinazione = destinazione;
	}
	
	public String toString()
	{
		String ret = "";
		Resources res = SASAbus.getContext().getResources();
		String toItalienisch = getDestinazione().substring(0, getDestinazione().indexOf("-")).trim();
		String fromItalienisch = getPartenza().substring(0, getPartenza().indexOf("-")).trim();
		Palina toStation = PalinaList.getTranslation(toItalienisch, "it");
		Palina fromStation = PalinaList.getTranslation(fromItalienisch, "it");
		if(toStation != null && fromStation != null)
		{
			ret = res.getString(R.string.from) + " " + fromStation.toString() + " - " + 
					res.getString(R.string.to) + " " + toStation.toString(); 
		}
		return ret;
	}
	
	
	public boolean insert(SQLiteDatabase db)
	{
		if(this.partenza == null || this.destinazione == null)
			return false;
		if(db == null || !db.isOpen() || db.isReadOnly())
			return false;
		String query_select = "Select * from " + FavoritenDB.FAVORITEN_TABLE_NAME + " where " +
				"partenza=\"" + partenza + "\" and destinazione=\"" + destinazione + "\";";
		Cursor cursor = db.rawQuery(query_select,null);
		if(cursor.getCount() != 0)
			return false;
		String query = "Insert into " + FavoritenDB.FAVORITEN_TABLE_NAME + 
				" VALUES ((select count(*) from " + FavoritenDB.FAVORITEN_TABLE_NAME + "), " +
						"\"" + partenza + "\", \"" + destinazione + "\");";
		db.execSQL(query);
		return true;
	}
	
	public boolean delete(SQLiteDatabase db)
	{
		if(db == null || !db.isOpen() || db.isReadOnly())
		{
			Log.v("FAVORITENLOESCHEN", "DB");
			return false;	
		}
		String query_select = "delete from " + FavoritenDB.FAVORITEN_TABLE_NAME + " where id=" + this.id + ";";
		Log.v("SQL_QUERY", query_select);
		db.execSQL(query_select);
		return true;
	}
}
 public class FavoritenDB extends SQLiteOpenHelper{

	 public static final int DATABASE_VERSION = 1;
	
	 public static final String FAVORITEN_TABLE_NAME = "favoriten";
	 
	 private static final String FAVORITEN_TABLE_CREATE =
	                "CREATE TABLE " + FAVORITEN_TABLE_NAME + "(" +
	                		"id INT AUTO_INCREMENT, " +
	                		"partenza TEXT, " +
	                		"destinazione TEXT );";
	
	
	
	public FavoritenDB(Context context) {
		super(context, context.getResources().getString(R.string.favoriten_db_name), null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL(FAVORITEN_TABLE_CREATE);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		db.execSQL("delete from " + FAVORITEN_TABLE_NAME + ";");
		db.execSQL("drop table" + FAVORITEN_TABLE_NAME + ";");
	}

}
 public class FavoritenList {
	
	/**                                                                                                                                                                                                          
	 * This function returns a vector of all the objects momentanly avaiable in the database                                                                                                                     
	 * @return a vector of objects if all goes right, alternativ it returns a MyError                                                                                                                              
	 */
	public static  Vector <Favorit>getList()
	{
		SQLiteDatabase sqlite = new FavoritenDB(SASAbus.getContext()).getReadableDatabase();
		Cursor cursor = sqlite.rawQuery("select * from " + FavoritenDB.FAVORITEN_TABLE_NAME + " order by id DESC", null);
		Vector <Favorit> list = null;
		if(cursor.moveToFirst())
		{
			list = new Vector<Favorit>();
			do {
				Log.v("Listenerstellung", "ID: " + cursor.getInt(cursor.getColumnIndex("id")));
				Favorit element = new Favorit(cursor.getInt(cursor.getColumnIndex("id")),
						cursor.getString(cursor.getColumnIndex("partenza")),
						cursor.getString(cursor.getColumnIndex("destinazione")));
				list.add(element);
			} while(cursor.moveToNext());
		}
		cursor.close();
		sqlite.close();
		return list;
	}
	
	/**                                                                                                                                                                                                          
	 * This function returns a vector of all the objects momentanly avaiable in the database                                                                                                                     
	 * @return a vector of objects if all goes right, alternativ it returns a MyError                                                                                                                              
	 */
	public static Favorit getById(int ident)
	{
		SQLiteDatabase sqlite = new FavoritenDB(SASAbus.getContext()).getReadableDatabase();
		Cursor cursor = sqlite.rawQuery("select * from " + FavoritenDB.FAVORITEN_TABLE_NAME + " where id = " 
				+ ident, null);
		Favorit list = null;
		if(cursor.moveToFirst())
		{
			list =  new Favorit(cursor.getInt(cursor.getColumnIndex("id")),
						cursor.getString(cursor.getColumnIndex("partenza")),
						cursor.getString(cursor.getColumnIndex("destinazione")));
		}
		cursor.close();
		sqlite.close();
		return list;
	}
	
}
 public class Modus extends DBObject {

	private String string = null;
	
	

	/**
	 * @return the string
	 */
	public String getString() {
		return string;
	}



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



	@Override
	public String toString()
	{
		return this.getString().trim();
	}
} public class MyFavoritenListAdapter extends BaseAdapter {
	private final Context context;
	private final Vector<Favorit> list;

	
	/**
	 * 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 MyFavoritenListAdapter(Context context, Vector<Favorit> list) {
		this.context = context;
		this.list = list;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;  
		if (v == null) {
              LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
              v = vi.inflate(R.layout.favoriten_row, null);
          }
		TextView departure = (TextView) v.findViewById(R.id.departure);
		TextView arrival = (TextView) v.findViewById(R.id.arrival);
		if (list != null)
		{
			Favorit listItem = list.get(position);
			if(listItem != null)
			{
				String favtext_arrival = list.get(position).getDestinazioneString();
				String favtext_departure = list.get(position).getPartenzaString();
				departure.setText(favtext_departure);
				arrival.setText(favtext_arrival);
			}
		}
		return v;
	}

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

	@Override
	public Object getItem(int position) {
		if(list == null)
			return null;
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		if (list == null)
			return -1;
		return list.get(position).getId();
	}

}
 public class MyListAdapter extends BaseAdapter {
	private final Context context;
	private final Vector<DBObject> list;
	private final int layoutId;
	private final int whereId;

	
	/**
	 * 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 MyListAdapter(Context context, int whereId, int layoutId, Vector<DBObject> list) {
		this.context = context;
		this.list = list;
		this.layoutId = layoutId;
		this.whereId = whereId;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;  
		if (v == null) {
              LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
              v = vi.inflate(layoutId, null);
          }
		TextView textView = (TextView) v.findViewById(whereId);
		if (list != null)
		{
			DBObject listItem = list.get(position);
			if(listItem != null)
			{
				textView.setText(list.get(position).toString());
			}
		}
		return v;
	}

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

	@Override
	public Object getItem(int position) {
		if(list == null)
			return null;
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		if (list == null)
			return -1;
		return list.get(position).getId();
	}

} public class Bacino extends DBObject {
	
	/*
	 * Is the name of the current Bacino in italian and german
	 */
	private String bacino_de = null;
	
	private String bacino_it = null;
	
	private String table_prefix = null;
	
	
	
	
	/*
	 * The standard-constructor
	 */
	public Bacino() {
		super();
	}
	
	/**
	 * This constructor creates an object from the data id and the name of the bacino
	 * @param identifyer is the id from the database
	 * @param bacinoName is the name of the bacino
	 */
	public Bacino (int identifyer, String bacino_it, String bacino_de){
		super(identifyer);
		this.bacino_it = bacino_it;
		this.bacino_de = bacino_de;
	}
	
	/**
	 * This constructor creates an object from the database provinding directly the
	 * default cursor from the database
	 * @param c is the cursor on an object from the database
	 */
	public Bacino(Cursor c)
	{
		super(c.getInt(c.getColumnIndex("id")));
		this.setBacino_de(c.getString(c.getColumnIndex("nome_de")));
		this.setBacino_it(c.getString(c.getColumnIndex("nome_it")));
		this.setTable_prefix(c.getString(c.getColumnIndex("nome_table")));
	}
	
	/**
	 * @return the bacino_de
	 */
	public String getBacino_de() {
		return bacino_de;
	}

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

	/**
	 * @return the bacino_it
	 */
	public String getBacino_it() {
		return bacino_it;
	}

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

	public String getTable_prefix()
	{
		return this.table_prefix;
	}
	
	public void setTable_prefix(String table_prefix)
	{
		this.table_prefix = table_prefix;
	}
	
	/**
	 * This method returns the string related to the locale set on the smartphone 
	 */
	@Override
	public String toString()
	{
		if((Locale.getDefault().getLanguage()).indexOf(Locale.GERMAN.toString()) != -1)
		{
			return this.getBacino_de().trim();
		}
		
		return this.getBacino_it().trim();
	}
	
}
 public class BacinoList {
	
	 
	/**                                                                                                                                                                                                          
	 * This function returns a vector of all the objects momentanly avaiable in the database                                                                                                                     
	 * @return a vector of objects if all goes right, alternativ it returns a MyError                                                                                                                              
	 */
	public static  Vector <DBObject>  getList()
	{
		MySQLiteDBAdapter sqlite = MySQLiteDBAdapter.getInstance(SASAbus.getContext());
		Cursor cursor = sqlite.rawQuery("select * from  bacini", null);
		Vector <DBObject> list = null;
		if(cursor.moveToFirst())
		{
			int i = 0;
			list = new Vector<DBObject>();
			do {
				Bacino element = new Bacino(cursor);
				list.add(i, element);
				++i;
			} while(cursor.moveToNext());
		}
		cursor.close();
		sqlite.close();
		return list;
	}
	
	public static Bacino getBacino(String start, String stop, String linecode)
	{
		Bacino ret = null;
		MySQLiteDBAdapter sqlite = MySQLiteDBAdapter.getInstance(SASAbus.getContext());
		Vector<DBObject> list = getList();
		Iterator<DBObject> iter = list.iterator();
		boolean gefunden = false;
		while(iter.hasNext() && !gefunden)
		{
			Bacino bac = (Bacino)iter.next();
			String[] args = {linecode, start, stop};
			Cursor cursor = sqlite.rawQuery("select * " +
    				"from "+
    				"(select id, lineaId " +
    				"from " + bac.getTable_prefix() + "corse as corse "+
    				"where " +
    				"lineaId = (" +
    				"Select id from " + bac.getTable_prefix() + "linee where num_lin = ?) ) as c, " +
    				"(select progressivo, orario, corsaId "+
    				"from " + bac.getTable_prefix() + "orarii "+
    				"where palinaId IN (" +
    				"select id from paline where nome_de = ?" +
    				")) as o1, " +
    				"(select progressivo , corsaId "+
    				"from " + bac.getTable_prefix() + "orarii " +
    				"where palinaId IN (" +
    				"select id from paline where nome_de = ?" +
    				")) as o2 " +
    				"where o1.progressivo < o2.progressivo " +
    				"and c.id = o1.corsaId " +
    				"and c.id = o2.corsaId " +
    				"LIMIT 1 ", 
    				args);
			if(cursor.moveToFirst())
			{
				ret = bac;
				gefunden = true;
			}
			cursor.close();

		}
		sqlite.close();
		return ret;
	}
	
	public static  Bacino  getById(int id)
	{
		MySQLiteDBAdapter sqlite = MySQLiteDBAdapter.getInstance(SASAbus.getContext());
		String args[] = {Integer.toString(id)};
		Cursor cursor = sqlite.rawQuery("select * from  bacini where id = ?", args);
		Bacino bacino = null;
		if(cursor.moveToFirst())
		{
			bacino = new Bacino(cursor);
		}
		cursor.close();
		sqlite.close();
		return bacino;
	}

}
 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 LineaList {
	
	
	
	/**                                                                                                                                                                                                          
	 * This function returns a vector of all the objects momentanly avaiable in the database                                                                                                                     
	 * @return a vector of objects if all goes right, alternativ it returns a MyError                                                                                                                              
	 */
	public static  Vector <DBObject>  getList()
	{
		MySQLiteDBAdapter sqlite = MySQLiteDBAdapter.getInstance(SASAbus.getContext());
		Cursor cursor = sqlite.rawQuery("select * from linee", null);
		Vector <DBObject> list = null;
		if(cursor.moveToFirst())
		{
			list = new Vector<DBObject>();
			do {
				Linea element = new Linea(cursor);
				list.add(element);
			} while(cursor.moveToNext());
		}
		cursor.close();
		sqlite.close();
		return list;
	}
	
	/**
	 * This method returns a vector of linee which are located in the bacino 
	 * @param bacino is the bacino where we are searching the linee 
	 * @return a vector of DBObjects with the linee located in the bacino
	 */
	public static Vector <DBObject> getList(String table_prefix)
	{
		MySQLiteDBAdapter sqlite = MySQLiteDBAdapter.getInstance(SASAbus.getContext());
		String[] args = null;
		Cursor cursor = sqlite.rawQuery("select * from " + table_prefix + "linee order by num_lin", args);
		Vector <DBObject> list = null;
		if(cursor.moveToFirst())
		{
			list = new Vector<DBObject>();
			do {
				Linea element = new Linea(cursor);
				list.add(element);
			} while(cursor.moveToNext());
		}
		cursor.close();
		sqlite.close();
		return list;
	}
	
	/**
	 * This method returns a vector of linee which are connecting the departure with the destination 
	 * @param destinazione is the name of the destination busstop
	 * @param partenza is the name of the departure busstop
	 * @return a vector of DBObjects which are lines which connect the departure with the destination
	 */
	public static Vector <DBObject> getListDestPart(String destinazione, String partenza)
	{
		MySQLiteDBAdapter sqlite = MySQLiteDBAdapter.getInstance(SASAbus.getContext());
		String[] args = {destinazione, partenza};
		/*
		 * This is a special query to provide the cases which the departure is 
		 * yesterday near midnight and the destination is now, for showing non-negativ
		 * differences
		 */
		Cursor cursor = sqlite.rawQuery("select distinct l.id as id, l.num_lin as num_lin, l.abbrev as abbrev, " +
				"l.bacinoId as bacinoId, l.descr_it as descr_it, l.descr_de as descr_de " +
				" from linee l, " +
				"(select * from orarii where palinaId IN (" +
				"select id from paline where nome_de = ?" +
				")) as o1, " +
				"(select * from orarii where palinaId IN (" +
				"select id from paline where nome_de = ?" +
				")) as o2, " +
				"(select id, lineaId " +
				"from corse " +
				"where  " +
				"substr(corse.effettuazione,round(strftime('%J','now','localtime')) - round(strftime('%J', '" + Config.getStartDate() + "')) + 1,1)='1' " + 
				") as c " +
				"where c.lineaId = l.id " +
				"and o1.corsaId = o2.corsaId " +
				"and o2.corsaId = c.id " +
				"and o2.progressivo < o1.progressivo " +
				"order by l.abbrev", args);
		Vector <DBObject> list = null;
		if(cursor.moveToFirst())
		{
			list = new Vector<DBObject>();
			do {
				Linea element = new Linea(cursor);
				if(!list.contains(element))
					list.add(element);
			} while(cursor.moveToNext());
		}
		cursor.close();
		sqlite.close();
		return list;
	}
	
	
	public static Vector<DBObject> sort(Vector <DBObject> list)
	{
		int j, i;
		try {
			for (j=list.size(); j > 1;--j)
			{
				for(i=0;i < j-1;++i)
				{
					Linea current = (Linea)list.elementAt(i);
					Linea next = (Linea)list.elementAt(i+1);
					if(current.compareTo(next) > 0)
					{
						list.remove(i);
						list.add(i+1, current);
					}
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return list;
	}
	
	
	/**                                                                                                                                                                                                          
	 * This function returns a vector of all the objects momentanly avaiable in the database                                                                                                                     
	 * @return a vector of objects if all goes right, alternativ it returns a MyError                                                                                                                              
	 */
	public static  Linea  getById(int lineaId, String table_prefix)
	{
		MySQLiteDBAdapter sqlite = MySQLiteDBAdapter.getInstance(SASAbus.getContext());
		String[] args = {Integer.toString(lineaId)};
		Cursor cursor = sqlite.rawQuery("select * from " + table_prefix + "linee where id = ?", args);
		Linea line = null;
		if(cursor.moveToFirst())
		{
			line = new Linea(cursor);
		}
		cursor.close();
		sqlite.close();
		return line;
	}
	
	/**                                                                                                                                                                                                          
	 * This function returns a vector of all the objects momentanly avaiable in the database                                                                                                                     
	 * @return a vector of objects if all goes right, alternativ it returns a MyError                                                                                                                              
	 */
	public static  Linea  getByNumLin(String linecode, String table_prefix)
	{
		MySQLiteDBAdapter sqlite = MySQLiteDBAdapter.getInstance(SASAbus.getContext());
		String[] args = {linecode};
		Cursor cursor = sqlite.rawQuery("select * from " + table_prefix + "linee where num_lin = ?", args);
		Linea line = null;
		if(cursor.moveToFirst())
		{
			line = new Linea(cursor);
		}
		cursor.close();
		sqlite.close();
		return line;
	}
}
 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 OnlineSearchFragment extends Fragment {

	
	public final static int DOWNLOAD_AVAILABLE = 0;
	public final static int DOWNLOAD_FILES = 1;
	public final static int DB_OK = 2;
	public final static int NO_SD_CARD = 3;
	
	
	public final static int FR_OSM = 0;
	public final static int FR_DB = 1;
	public final static int DB_UP = 2;
	
	public final static int OFFLINE = 34;
	
	public final static int REQUESTCODE_ACTIVITY = 123;
	
	private AutoCompleteTextView from;
	private AutoCompleteTextView to;
	
	private CheckUpdate updatecheck = null;
    
	private View result = null;
	private LayoutInflater inflater_glob = null;
	
    public OnlineSearchFragment() {
    }

    private OnlineSearchFragment getThis()
    {
    	return this;
    }
    
    public View getResult()
    {
    	return result;
    }
    
    @Override
    public void onPause() {
    	super.onPause();
    	InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(result.getWindowToken(), 0);
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
    	this.inflater_glob = inflater;
    	result = inflater.inflate(R.layout.online_search_layout, container, false);
    	
    	Date datum = new Date();
        SimpleDateFormat simple = new SimpleDateFormat("dd.MM.yyyy HH:mm");
        
        
        TextView datetime = (TextView)result.findViewById(R.id.time);
        String datetimestring = "";
        
        datetimestring = simple.format(datum);
        
        datetime.setText(datetimestring);
        
        Button search = (Button)result.findViewById(R.id.search);
        
        search.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				AutoCompleteTextView from = (AutoCompleteTextView)result.findViewById(R.id.from_text);
				AutoCompleteTextView to = (AutoCompleteTextView)result.findViewById(R.id.to_text);
				TextView datetime = (TextView)result.findViewById(R.id.time);
				
				String from_txt = getThis().getResources().getString(R.string.from_txt);
				
				if((!from.getText().toString().trim().equals("") || !from.getHint().toString().trim().equals(from_txt)) && !to.getText().toString().trim().equals(""))
				{
					//Intent getSelect = new Intent(getThis().getActivity(), OnlineSelectStopActivity.class);
					String fromtext = "";
					if(from.getText().toString().trim().equals(""))
						fromtext = from.getHint().toString();
					else
						fromtext = from.getText().toString();
					String totext = to.getText().toString();
					fromtext = "(" + fromtext.replace(" -", ")");
					totext = "(" + totext.replace(" -", ")");
					Fragment fragment = new OnlineSelectFragment(fromtext, totext, datetime.getText().toString());
					FragmentManager fragmentManager = getFragmentManager();
					FragmentTransaction ft = fragmentManager.beginTransaction();
					
					Fragment old = fragmentManager.findFragmentById(R.id.onlinefragment);
					if(old != null)
					{
						ft.remove(old);
					}
					ft.add(R.id.onlinefragment, fragment);
					ft.addToBackStack(null);
					ft.commit();
					fragmentManager.executePendingTransactions();
				}
			}
		});
        
        datetime.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				// Create the dialog
				final Dialog mDateTimeDialog = new Dialog(getThis().getActivity());
				// Inflate the root layout
				final RelativeLayout mDateTimeDialogView = (RelativeLayout) inflater_glob.inflate(R.layout.date_time_dialog, null);
				// Grab widget instance
				final DateTimePicker mDateTimePicker = (DateTimePicker) mDateTimeDialogView
						.findViewById(R.id.DateTimePicker);
				TextView dt = (TextView)result.findViewById(R.id.time);
				String datetimestring = dt.getText().toString();
				
				SimpleDateFormat datetimeformat = new SimpleDateFormat("dd.MM.yyyy HH:mm");
				Date datetime = null;
				try
				{
					datetime = datetimeformat.parse(datetimestring);
				}
				catch(Exception e)
				{
					;
				}
				mDateTimePicker.updateTime(datetime.getHours(), datetime.getMinutes());
				mDateTimePicker.updateDate(datetime.getYear() + 1900, datetime.getMonth(), datetime.getDate());
				// Check is system is set to use 24h time (this doesn't seem to
				// work as expected though)
				final String timeS = android.provider.Settings.System
						.getString(getThis().getActivity().getContentResolver(),
								android.provider.Settings.System.TIME_12_24);
				final boolean is24h = !(timeS == null || timeS.equals("12"));
				
				
				
				((Button) mDateTimeDialogView.findViewById(R.id.SetDateTime)).setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
							mDateTimePicker.clearFocus();
							String datetimestring = "";
							int day = mDateTimePicker.get(Calendar.DAY_OF_MONTH);
							int month = mDateTimePicker.get(Calendar.MONTH) + 1;
							int year = mDateTimePicker.get(Calendar.YEAR);
							int hour = 0;
							int min = 0;
							int append = 0;
							if (mDateTimePicker.is24HourView()) {
								hour = mDateTimePicker.get(Calendar.HOUR_OF_DAY);
								min = mDateTimePicker.get(Calendar.MINUTE);
							} else {
								hour = mDateTimePicker.get(Calendar.HOUR);
								min = mDateTimePicker.get(Calendar.MINUTE);
								if(mDateTimePicker.get(Calendar.AM_PM) == Calendar.AM)
								{
									append = 1;
								}
								else
								{
									append = 2;
								}
							}
							if (day < 10)
							{
								datetimestring += "0";
							}
							datetimestring += (day + ".");
							if(month < 10)
							{
								datetimestring += "0";
							}
							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();
			}

		});
        
        ImageButton datepicker = (ImageButton)result.findViewById(R.id.datepicker);
        
        datepicker.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				// Create the dialog
				final Dialog mDateTimeDialog = new Dialog(getThis().getActivity());
				// Inflate the root layout
				final RelativeLayout mDateTimeDialogView = (RelativeLayout) inflater_glob
						.inflate(R.layout.date_time_dialog, null);
				// Grab widget instance
				final DateTimePicker mDateTimePicker = (DateTimePicker) mDateTimeDialogView
						.findViewById(R.id.DateTimePicker);
				TextView dt = (TextView)result.findViewById(R.id.time);
				String datetimestring = dt.getText().toString();
				SimpleDateFormat datetimeformat = new SimpleDateFormat("dd.MM.yyyy HH:mm");
				Date datetime = null;
				try
				{
					datetime = datetimeformat.parse(datetimestring);
				}
				catch(Exception e)
				{
					;
				}
				mDateTimePicker.updateTime(datetime.getHours(), datetime.getMinutes());
				mDateTimePicker.updateDate(datetime.getYear() + 1900, datetime.getMonth(), datetime.getDate());
				// Check is system is set to use 24h time (this doesn't seem to
				// work as expected though)
				final String timeS = android.provider.Settings.System
						.getString(getThis().getActivity().getContentResolver(),
								android.provider.Settings.System.TIME_12_24);
				final boolean is24h = !(timeS == null || timeS.equals("12"));

				// Update demo TextViews when the "OK" button is clicked
				((Button) mDateTimeDialogView.findViewById(R.id.SetDateTime)).setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
							mDateTimePicker.clearFocus();
							String datetimestring = "";
							int day = mDateTimePicker.get(Calendar.DAY_OF_MONTH);
							int month = mDateTimePicker.get(Calendar.MONTH) + 1;
							int year = mDateTimePicker.get(Calendar.YEAR);
							int hour = 0;
							int min = 0;
							int append = 0;
							if (mDateTimePicker.is24HourView()) {
								hour = mDateTimePicker.get(Calendar.HOUR_OF_DAY);
								min = mDateTimePicker.get(Calendar.MINUTE);
							} else {
								hour = mDateTimePicker.get(Calendar.HOUR);
								min = mDateTimePicker.get(Calendar.MINUTE);
								if(mDateTimePicker.get(Calendar.AM_PM) == Calendar.AM)
								{
									append = 1;
								}
								else
								{
									append = 2;
								}
							}
							if (day < 10)
							{
								datetimestring += "0";
							}
							datetimestring += (day + ".");
							if(month < 10)
							{
								datetimestring += "0";
							}
							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());
				dialog.show();
			}
		});
        
        Button mappicker = (Button)result.findViewById(R.id.map);
        mappicker.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getActivity(), MapSelectActivity.class);
				startActivityForResult(intent, REQUESTCODE_ACTIVITY);
			}
		});
    	return result;
    }
    
    /** Called with the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        
        
        if(MySQLiteDBAdapter.exists(this.getActivity()))
        {
	        updatecheck = new CheckUpdate(this);
	        updatecheck.execute();
	        
        }
        else if (haveNetworkConnection())
        {
        	Intent download = new Intent(this.getActivity(), CheckDatabaseActivity.class);
			startActivity(download);
        }
        else
        {
        	createErrorDialog(R.string.no_network_connection);
        }
	}

    
    @Override
    public void onResume()
    {
    	super.onResume();
    }
    
    public void showDialog(int id, int res)
	{
		Dialog dia = onCreateDialog(id, res);
		if(dia != null)
			dia.show();
	}
    
    protected Dialog onCreateDialog(int id, int res) {
		switch (id) {
		case DOWNLOAD_AVAILABLE:
			return createDownloadAlertDialog(R.string.download_available);
		case NO_SD_CARD:
			return createErrorDialog(R.string.sd_card_not_mounted);
		case DOWNLOAD_FILES:
			Intent down = new Intent(this.getActivity(), CheckDatabaseActivity.class);
			myStartActivity(down);
			return null;
		default:
			return null;
		}
	}
    
    public final Dialog createErrorDialog(int msg) 
   	{
   		AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
   		// builder.setTitle(R.string.a_given_string);
   		builder.setIcon(R.drawable.icon);
   		builder.setMessage(msg);
   		builder.setNeutralButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

   			@Override
   			public void onClick(DialogInterface dialog, int id) {
   				dialog.dismiss();
   				System.exit(-3);
   			}
   		});
   		
   		return builder.create();
   	}
    
    
    public void myStartActivity(Intent intent)
    {
    	if(!haveNetworkConnection())
    	{
    		createOfflineAlertDialog();
    		return;
    	}
    	if(updatecheck != null)
		{
			Log.v("HomeActivity", "AsynTask cancelled!");
			updatecheck.cancel(true);
		}
    	super.startActivity(intent);
    }
    
    /**
	 * 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) (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;
	}
    
	private void createOfflineAlertDialog()
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
		builder.setTitle(R.string.information);
		builder.setMessage(R.string.offline_info);
		
		builder.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener(){

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
			
		});
		
		builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener(){

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				Intent oldmode = new Intent(getThis().getActivity(), BacinoFragment.class);
				startActivity(oldmode);
			}
			
		});
		builder.create().show();
		
	}
	
    public final Dialog createDownloadAlertDialog(int msg) 
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
		// builder.setTitle(R.string.a_given_string);
		builder.setIcon(R.drawable.icon);
		//builder.setMessage(msg);
		builder.setMessage(msg);
		builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int id) {
				dialog.dismiss();
				Intent download = new Intent(getThis().getActivity(), CheckDatabaseActivity.class);
				myStartActivity(download);
			}
		});
		builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int id) {
				dialog.dismiss();
			}
		});
		
		return builder.create();
	}
    
    public void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
    	if (requestCode == REQUESTCODE_ACTIVITY)
    	{
    		if (resultCode == Activity.RESULT_OK)
    		{
    			Bundle extras = data.getExtras();
    			String from = extras.getString("from");
    			String to = extras.getString("to");
    			
    			if(from != null && from != "")
    			{
    				TextView from_text = (TextView)result.findViewById(R.id.from_text);
    				from_text.setText(from);
    			}
    			
    			if(to != null && to != "")
    			{
    				TextView to_text = (TextView)result.findViewById(R.id.to_text);
    				to_text.setText(to);
    			}
    			InputMethodManager mgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    			mgr.hideSoftInputFromWindow(this.from.getWindowToken(), 0);
    			mgr.hideSoftInputFromWindow(this.to.getWindowToken(), 0);
    		}
 
    	}
    }
    
}
 public class OrarioFragment extends Fragment implements OnItemClickListener {


	
	//provides the linea for this object
	private Linea linea;

	//provides the destination for this object
	private Palina departure;
		
	//provides the departure in this object
	private Palina  arrival;
	
	//provides the list for this object of all passages during the actual day
	private Vector<Passaggio> list = null;
	
	//is the next departure time of the bus
	private int pos;
	
	private Bacino bacino = null;

	private OrarioFragment() {
	}

	public OrarioFragment(Bacino bacino, Linea linea, Palina departure, Palina arrival)
	{
		this();
		this.bacino = bacino;
		this.linea = linea;
		this.departure = departure;
		this.arrival = arrival;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View result = inflater.inflate(R.layout.palina_listview_layout, container, false);
		TextView titel = (TextView)result.findViewById(R.id.untertitel);
		
		titel.setText(R.string.show_orari);
		
		Resources res = getResources();
		
		TextView lineat = (TextView)result.findViewById(R.id.line);
        TextView from = (TextView)result.findViewById(R.id.from);
        TextView to = (TextView)result.findViewById(R.id.to);
        
        lineat.setText(res.getString(R.string.line_txt) + " " + linea.toString());
        from.setText(res.getString(R.string.from) + " " + departure.toString());
        to.setText(res.getString(R.string.to) + " " + arrival.toString());
		
		fillData(result);
		if (pos != -1) {
			((ListView)result.findViewById(android.R.id.list)).setSelection(pos);
		}
		return result;
	}
	

	

	/**
	 * fills the listview with the timetable
	 * @return a cursor to the time table
	 */
	private void fillData(View result) {
		list = PassaggioList.getVector(linea.getId(), arrival.getName_de(), departure.getName_de(), bacino.getTable_prefix());
		pos = getNextTimePosition(list);
        MyPassaggioListAdapter orari = new MyPassaggioListAdapter(SASAbus.getContext(), R.id.text, R.layout.standard_row, list, pos);
        ListView listview = (ListView)result.findViewById(android.R.id.list);
        listview.setAdapter(orari);
        listview.setOnItemClickListener(this);
        listview.setDividerHeight(0);
        listview.setDivider(null);
	}

	/**
	 * This method gets the next departure time and returns the
	 * index of this element
	 * @param c is the cursor to the list_view
	 * @return the index of the next departure time
	 */
	private int getNextTimePosition(Vector<Passaggio> list) {
		int count = list.size();
		if (count == 0) {
			return -1;
		} else if (count == 1) {
			return 0;
		} else {
			int i = 0;
			boolean found = false;
			while (i <= count-2 && !found) {
				Time currentTime = new Time();
				Time sasaTime = new Time();
				Time sasaTimeNext = new Time();
				currentTime.setToNow();
				sasaTime = list.get(i).getOrario();
				sasaTimeNext = list.get(i + 1).getOrario();

				if (sasaTime.after(currentTime)
						|| sasaTime.equals(currentTime)
						|| sasaTime.before(currentTime)
						&& (sasaTimeNext.equals(currentTime) || sasaTimeNext
								.after(currentTime)))
				{
					found = true;
				}
				else
				{
					i++;
				}
			}
			return i;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> av, View v, int position, long id) {
		// TODO Auto-generated method stub
			Passaggio orario = list.get(position);
			FragmentManager fragmentManager = getFragmentManager();
			FragmentTransaction ft = fragmentManager.beginTransaction();
			
			Fragment fragment = fragmentManager.findFragmentById(R.id.onlinefragment);
			if(fragment != null)
			{
				ft.remove(fragment);
			}
			fragment = new WayFragment(bacino, linea, arrival, orario);
			ft.add(R.id.onlinefragment, fragment);
			ft.addToBackStack(null);
			ft.commit();
			fragmentManager.executePendingTransactions();
			/*
			Intent showWay = new Intent(this, ShowWayActivity.class);
			showWay.putExtra("orario", orario);
			showWay.putExtra("destinazione", destinazione);
			showWay.putExtra("linea", linea);
			showWay.putExtra("bacino", bacino.getId());
			startActivity(showWay);
			*/
	}

	
}

import java.util.Locale;
import java.util.Vector;
import it.sasabz.android.sasabus.R;
import it.sasabz.android.sasabus.SASAbus;
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.Favorit;
import it.sasabz.android.sasabus.classes.FavoritenDB;
import it.sasabz.android.sasabus.classes.FavoritenList;
import it.sasabz.android.sasabus.classes.Modus;
import it.sasabz.android.sasabus.classes.adapter.MyFavoritenListAdapter;
import it.sasabz.android.sasabus.classes.adapter.MyListAdapter;
import it.sasabz.android.sasabus.classes.dbobjects.Bacino;
import it.sasabz.android.sasabus.classes.dbobjects.BacinoList;
import it.sasabz.android.sasabus.classes.dbobjects.DBObject;
import it.sasabz.android.sasabus.classes.dbobjects.LineaList;
import it.sasabz.android.sasabus.classes.dbobjects.Palina;
import it.sasabz.android.sasabus.classes.dbobjects.PalinaList;
import it.sasabz.android.sasabus.fragments.OnlineSearchFragment;
import it.sasabz.android.sasabus.fragments.OrarioFragment;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Display;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

/**
 *
 * SelectFavoritenActivity.java
 * 
 * 
 * Copyright (C) 2012 Markus Windegger
 *
 * This file is part of SasaBus.

 * SasaBus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * SasaBus is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with SasaBus.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

package it.sasabz.android.sasabus.classes.dialogs;




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);
