public class NavActivity extends SherlockFragmentActivity {

	String supportedWinGuiMissionFiles = "2.3 pre7";

	MapHelperClass mapHelperClass;
	Menu ActionBarMenu;
	ActionMode mMode;
	private DrawerLayout mDrawerLayout;
	private ActionBarDrawerToggle mDrawerToggle;
	private ListView mDrawerList;

	int defaultAltitude = 25;
	int defaultAction = 1;

	// float CircleRadius = 0;
	// int CirclePointsCount = 10;

	boolean ShowWaypointControls = true;

	boolean CenterMap = false;
	private long centerPeriod = 0;

	// int CurrentWaypointNumber = -1;
	final int CircleAroundWPinMeters = 5;

	boolean killme = false;
	boolean killed = false;

	Random random = new Random(); // for test

	App app;
	Handler mHandler = new Handler();

	TextView TVWPInfo;

	NumberFormat format = new DecimalFormat("0.00");

	private Runnable update = new Runnable() {
		@Override
		public void run() {

			app.mw.ProcessSerialData(app.loggingON);
			app.frskyProtocol.ProcessSerialData(false);

			// simulation
			if (app.D) {
				app.mw.GPS_latitude += random.nextInt(50) - 1;
				app.mw.GPS_longitude += random.nextInt(50) - 1;
				app.mw.GPS_fix = 1;
				app.mw.head++;
				if (app.mw.head > 360)
					app.mw.head = 0;
			}

			LatLng copterPositionLatLng = new LatLng(app.mw.GPS_latitude / Math.pow(10, 7), app.mw.GPS_longitude / Math.pow(10, 7));

			// Map centering
			if (CenterMap && centerPeriod < System.currentTimeMillis()) {
				if (app.mw.GPS_fix == 1) {
					mapHelperClass.map.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(copterPositionLatLng, app.MapZoomLevel, 0, app.mw.head)));
				} else {
					mapHelperClass.map.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(app.sensors.PhoneLatitude, app.sensors.PhoneLongitude), app.MapZoomLevel, 0, 0)));
				}
				centerPeriod = System.currentTimeMillis() + app.MapCenterPeriod * 1000;
			}

			mapHelperClass.SetCopterLocation(copterPositionLatLng, app.mw.head, app.mw.alt);
			// mapHelperClass.SetCopterLocation(app.sensors.MapCurrentPosition,
			// app.sensors.Heading, 0);
			mapHelperClass.DrawFlightPath(copterPositionLatLng);
			mapHelperClass.PositionHoldMarker.setPosition(app.mw.Waypoints[16].Lat_Lng());
			mapHelperClass.HomeMarker.setPosition(app.mw.Waypoints[0].Lat_Lng());

			// DisplayInfo();
			app.Frequentjobs();

			app.mw.SendRequest(app.MainRequestMethod);
			if (!killme) {
				mHandler.postDelayed(update, app.RefreshRate);
			} else {
				mHandler.removeCallbacksAndMessages(null);
				killed = true;
				Log.d("nav", "Killed");
			}

		}
	};

	void DisplayInfo() {
		TVWPInfo.setText("");
		TVWPInfo.setText(getString(R.string.MaxNumberOfWP) + String.valueOf(app.mw.NAVmaxWpNumber));

		mDrawerList.setAdapter(new ArrayAdapter<WaypointNav>(this, R.layout.nav_drawer_list_item, app.mw.WaypointsList) {
			//
			@Override
			public View getView(int position, View convertView, ViewGroup parent) {

				// 1. Create inflater
				LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

				// 2. Get rowView from inflater

				View rowView = null;

				// if(!modelsArrayList.get(position).isGroupHeader()){
				rowView = inflater.inflate(R.layout.nav_drawer_list_item, parent, false);

				// 3. Get icon,title & counter views from the rowView
				ImageView imgView = (ImageView) rowView.findViewById(R.id.item_icon);
				TextView titleView = (TextView) rowView.findViewById(R.id.item_title);

				// 4. Set the text for textView
				switch (app.mw.WaypointsList.get(position).Action) {

				case WaypointNav.WP_ACTION_LAND:
					imgView.setImageResource(R.drawable.land);
					break;

				case WaypointNav.WP_ACTION_SET_HEAD:
					imgView.setImageResource(R.drawable.set_heading);
					break;

				case WaypointNav.WP_ACTION_RTH:
					imgView.setImageResource(R.drawable.rth);
					break;

				case WaypointNav.WP_ACTION_POSHOLD_UNLIM:
					imgView.setImageResource(R.drawable.poshold_unlim);
					break;

				case WaypointNav.WP_ACTION_POSHOLD_TIME:
					imgView.setImageResource(R.drawable.poshold_time);
					break;

				case WaypointNav.WP_ACTION_JUMP:
					imgView.setImageResource(R.drawable.jump);
					break;

				case WaypointNav.WP_ACTION_WAYPOINT:
					imgView.setImageResource(R.drawable.waypoint);
					break;

				case WaypointNav.WP_ACTION_SET_POI:
					imgView.setImageResource(R.drawable.poi);
					break;

				default:
					imgView.setImageResource(R.drawable.green_light);
					break;
				}

				titleView.setText(app.mw.WaypointsList.get(position).toString());

				return rowView;
			}

		});
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext()) != ConnectionResult.SUCCESS) {
			Toast.makeText(this, getString(R.string.GooglePlayServiecesError), Toast.LENGTH_LONG).show();
			finish();
		}

		app = (App) getApplication();
		app.ForceLanguage();

		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		setContentView(R.layout.nav_layout);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		getSupportActionBar().setHomeButtonEnabled(true);
		getSupportActionBar().setTitle(getString(R.string.Navigation));

		TVWPInfo = (TextView) findViewById(R.id.TextViewWPinfo);

		mDrawerList = (ListView) findViewById(R.id.ListViewWPList);
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

		mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) {

			/** Called when a drawer has settled in a completely closed state. */
			public void onDrawerClosed(View view) {
				getSupportActionBar().setTitle(getString(R.string.Navigation));
			}

			/** Called when a drawer has settled in a completely open state. */
			public void onDrawerOpened(View drawerView) {
				getSupportActionBar().setTitle(getString(R.string.Options));
				DisplayInfo();
			}

			@Override
			public void onDrawerSlide(View drawerView, float slideOffset) {
				super.onDrawerSlide(drawerView, slideOffset);
				mDrawerLayout.bringChildToFront(drawerView);
				mDrawerLayout.requestLayout();
			}
		};

		mDrawerToggle.syncState();
		mDrawerLayout.setDrawerListener(mDrawerToggle);

		mDrawerList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				openMWEditor(app.mw.WaypointsList.get(position).MarkerId);

			}
		});

		// mapHelperClass////////////////////////////////////////////////
		mapHelperClass = new MapHelperClass(getApplicationContext(), ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap(), CircleAroundWPinMeters, app.mw.multiType);

		mapHelperClass.map.setOnCameraChangeListener(new OnCameraChangeListener() {
			@Override
			public void onCameraChange(CameraPosition position) {
				if (app.mw.GPS_fix == 1)
					app.MapZoomLevel = (int) position.zoom;
			}
		});

		mapHelperClass.map.setOnMarkerClickListener(new OnMarkerClickListener() {

			@Override
			public boolean onMarkerClick(Marker marker) {

				return false;
			}
		});

		mapHelperClass.map.setOnMarkerDragListener(new OnMarkerDragListener() {

			@Override
			public void onMarkerDragStart(Marker marker) {
				// Toast.makeText(getApplicationContext(), marker.getId(),
				// Toast.LENGTH_LONG).show();
			}

			@Override
			public void onMarkerDragEnd(Marker marker) {

				for (WaypointNav WP : app.mw.WaypointsList) {
					if (WP.MarkerId.equals(marker.getId())) {
						WP.setLatLng(marker.getPosition());
					}
				}
				mapHelperClass.RedrawLines();
			}

			@Override
			public void onMarkerDrag(Marker marker) {
				mapHelperClass.RedrawLines();
			}
		});

		mapHelperClass.map.setOnMapLongClickListener(new OnMapLongClickListener() {
			@Override
			public void onMapLongClick(LatLng point) {

				if (app.mw.NAVmaxWpNumber == 0 || app.mw.WaypointsList.size() <= app.mw.NAVmaxWpNumber) {
					AddNewWP(point);
					Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
					if (vibrator != null) {
						vibrator.vibrate(50);
					}
				} else {

					DisplayInfoDialog(getString(R.string.Info), getString(R.string.MaxNumberWPreached), getString(R.string.OK));

				}
			}
		});

		mapHelperClass.map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {

			@Override
			public void onInfoWindowClick(Marker marker) {
				openMWEditor(marker.getId());
			}
		});

		mapHelperClass.map.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(0, 0), mapHelperClass.map.getMinZoomLevel(), 0, 0)));
		// mapHelperClass///END/////////////////////////////////////////////

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == android.R.id.home) {

			if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
				mDrawerLayout.closeDrawer(GravityCompat.START);
			} else {
				mDrawerLayout.openDrawer(GravityCompat.START);
			}
		}
		// Handle your other action bar items...

		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onResume() {
		super.onResume();
		app.ForceLanguage();
		app.Say(getString(R.string.Navigation));
		killme = false;
		mHandler.removeCallbacksAndMessages(null);
	
		setVolumeControlStream(AudioManager.STREAM_MUSIC);

		LoadMarkersFromWPlist();
		DisplayInfo();

		if (Sec.VerifyDeveloperID(Sec.GetDeviceID(getApplicationContext()), Sec.TestersIDs) || Sec.Verify(getApplicationContext(), "D..3")) {
			mHandler.postDelayed(update, app.RefreshRate);
		} else {
			AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);

			dlgAlert.setTitle(getString(R.string.Locked));
			dlgAlert.setMessage(getString(R.string.DoYouWantToUnlock));

			// dlgAlert.setPositiveButton(getString(R.string.Yes), null);
			dlgAlert.setCancelable(false);
			dlgAlert.setPositiveButton(getString(R.string.Yes), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					try {
						Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.ezio.ez_gui_unlocker");
						startActivity(LaunchIntent);
					} catch (Exception e) {
						Intent goToMarket = null;
						goToMarket = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.ezio.ez_gui_unlocker"));
						startActivity(goToMarket);
					}
					finish();
				}
			});
			dlgAlert.setNegativeButton(getString(R.string.No), new OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});

			dlgAlert.create().show();
		}

		//app.sensors.startMagACC();

		if (app.Protocol != App.PROTOCOL_NAV) {
			DisplayInfoDialog("Protocol", "This requires selected NAV Protocol in Settings", getString(R.string.OK));
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		mHandler.removeCallbacks(null);
		killme = true;

		if (app.mw.GPS_fix == 1) {
			app.MapZoomLevel = mapHelperClass.map.getCameraPosition().zoom;
			app.SaveSettings(true);
		}

		//app.sensors.stopMagACC();
	}

	private WaypointNav getWPfromMarkerId(String markerId) {
		for (WaypointNav WP : app.mw.WaypointsList) {
			if (WP.MarkerId.equals(markerId)) {
				return WP;
			}
		}
		return null;
	}

	void AddNewWP(LatLng point) {
		app.mw.WaypointsList.add(new WaypointNav(app.mw.WaypointsList.size() + 1, point, defaultAction, 0, 0, 0, defaultAltitude, 0));
		LoadMarkersFromWPlist();
	}

	void ClearMap() {
		mapHelperClass.CleanMap();
		app.mw.WaypointsList.clear();
	}

	void ZoomToShawAllMarkers() {
		if (mapHelperClass.markers.size() > 0) {
			LatLngBounds.Builder builder = new LatLngBounds.Builder();
			for (Marker marker : mapHelperClass.markers) {
				builder.include(marker.getPosition());
			}
			LatLngBounds bounds = builder.build();
			int padding = 50; // offset from edges of the map in pixels
			CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, padding);
			mapHelperClass.map.animateCamera(cu);
		}
	}

	void SortAndPrepareWPs() {
		if (app.mw.WaypointsList.size() > 0) {
			Collections.sort(app.mw.WaypointsList);
			int i = 0;
			for (i = 0; i < app.mw.WaypointsList.size(); i++) {
				app.mw.WaypointsList.get(i).Number = i + 1;
				app.mw.WaypointsList.get(i).Flag = 0;
			}
			app.mw.WaypointsList.get(i - 1).Flag = WaypointNav.MISSION_FLAG_END;
		}
	}

	boolean IsWPLastToDownload(int WPNumber) {
		for (WaypointNav wp : app.mw.WaypointsList) {
			if (wp.Number == WPNumber && wp.Flag == WaypointNav.MISSION_FLAG_END)
				return true;
		}
		return false;
	}

	int isWPhasBeenDownloaded(int WPNumber) {
		for (int i = 0; i < app.mw.WaypointsList.size(); i++) {
			if (app.mw.WaypointsList.get(i).Number == WPNumber)
				return i;
		}
		return -1;
	}

	void CheckWPErrors() {
		for (int i = 0; i < app.mw.WaypointsList.size(); i++) {
			if (app.mw.WaypointsList.get(i).Flag == WaypointNav.ERROR_ERROR) {
				app.mw.WaypointsList.get(i).Error = WaypointNav.ERROR_ERROR;

				DisplayInfoDialog(getString(R.string.WPError), "WP" + String.valueOf(app.mw.WaypointsList.get(i).Number) + " " + getString(R.string.isNotCorrect), getString(R.string.OK));

			}
			if (app.mw.WaypointsList.get(i).Flag == WaypointNav.ERROR_CRC) {
				app.mw.WaypointsList.get(i).Error = WaypointNav.ERROR_CRC;
				DisplayInfoDialog(getString(R.string.WPError), "WP" + String.valueOf(app.mw.WaypointsList.get(i).Number) + " " + getString(R.string.CRCisNotCorrect), getString(R.string.OK));

			}
		}
	}

	void DownloadMission() {
		if (app.commMW.Connected) {
			Log.d("nav", "download mission");
			ClearMap();

			final ProgressDialog progress = ProgressDialog.show(this, getString(R.string.Downloading), getString(R.string.PleaseWait), true);

			new Thread(new Runnable() {
				@Override
				public void run() {
					boolean finished = false;
					int i = 1;
					boolean error = false;

					killme = true;
					killed = false;
					mHandler.removeCallbacks(null);
					while (!killed) {
						try {
							Thread.sleep(app.RefreshRate);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}

					while (!finished) {
						app.mw.SendRequestMSP_WP(i);
						Log.d("nav", "send request " + String.valueOf(i));

						int t = 0;
						int t1 = 0;

						while (isWPhasBeenDownloaded(i) < 0) {
							Log.d("nav", "waiting..." + String.valueOf(i));
							try {
								Thread.sleep(app.RefreshRate);
							} catch (InterruptedException e) {
								//
								e.printStackTrace();
							}

							app.mw.ProcessSerialData(false);

							t++;
							if (t > 20) {
								app.mw.SendRequestMSP_WP(i);
								Log.d("nav", "send request " + String.valueOf(i));
								t = 0;
								t1++;

								if (t1 > 5) {
									finished = true;
									error = true;
								}
							}

						}

						Log.d("nav", "2");
						if (IsWPLastToDownload(i))
							finished = true;

						i++;
						if (i > 255)
							finished = true;
					}

					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							CheckWPErrors();
							LoadMarkersFromWPlist();
							progress.dismiss();
							ZoomToShawAllMarkers();
							DisplayInfo();
							killme = false;
							killed = false;
							mHandler.postDelayed(update, app.RefreshRate);

						}
					});
				}
			}).start();
		}

	}

	void UploadMission() {
		Log.d("nav", "upload mission");

		final ProgressDialog progress = ProgressDialog.show(this, getString(R.string.Uploading), getString(R.string.PleaseWait), true);

		new Thread(new Runnable() {
			@Override
			public void run() {

				SortAndPrepareWPs();

				killme = true;
				killed = false;
				mHandler.removeCallbacks(null);

				while (!killed) {
					try {
						Thread.sleep(app.RefreshRate);
					} catch (InterruptedException e) {
						//
						e.printStackTrace();
					}
				}

				if (app.mw.WaypointsList.size() == 0) {
					app.mw.SendRequestMSP_SET_WP_NAV(new WaypointNav(1, 0, 0, WaypointNav.WP_ACTION_RTH, 0, 0, 0, defaultAltitude, WaypointNav.MISSION_FLAG_END));
					Log.d("nav", "RTH upladed");
					killme = false;
					mHandler.postDelayed(update, app.RefreshRate);
					progress.dismiss();

				} else {

					for (WaypointNav wp : app.mw.WaypointsList) {
						app.mw.SendRequestMSP_SET_WP_NAV(wp);
						Log.d("nav", "send request " + String.valueOf(wp.Number));
						try {
							Thread.sleep(app.RefreshRate);
						} catch (InterruptedException e) {
							//
							e.printStackTrace();
						}
					}
				}

				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						progress.dismiss();
						killme = false;
						killed = false;
						mHandler.postDelayed(update, app.RefreshRate);
					}
				});
			}
		}).start();
	}

	void LoadMarkersFromWPlist() {
		mapHelperClass.CleanMap();
		SortAndPrepareWPs();

		if (app.mw.WaypointsList.size() > 0) {
			for (WaypointNav WP : app.mw.WaypointsList) {

				if (WP.ShowMarkerForThisWP())
					WP.MarkerId = mapHelperClass.AddMarker(WP.getLatLng(), WP.getMarkerTitle(), WP.getMarkerSnippet(), WP.Action);

				if (WP.Action == WaypointNav.WP_ACTION_RTH || WP.Action == WaypointNav.WP_ACTION_POSHOLD_UNLIM || WP.Action == WaypointNav.WP_ACTION_LAND)
					return;
			}
		}
		DisplayInfo();

	}

	public void ClearMapOnClick(View v) {
		ClearMap();
		DisplayInfo();
	}

	public void DownloadMissionOnClick(View v) {
		DownloadMission();
	}

	public void UploadMissionOnClick(View v) {
		UploadMission();
	}

	public void ZoomInOnClick(View v) {
		ZoomToShawAllMarkers();
		mDrawerLayout.closeDrawers();
	}

	public void LoadMissionOnClick(View v) {
		Intent i = new Intent(this, FilePickerActivity.class);
		startActivityForResult(i, 1);
	}

	void openMWEditor(String markerId) {
		Intent i = new Intent(getApplicationContext(), WPEditorActivity.class);
		// i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		i.putExtra("MARKERID", markerId);
		startActivityForResult(i, 2);
	}

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

		Log.d("nav", "onActivityResult");
		if (requestCode == 1) {

			if (resultCode == RESULT_OK) {
				String result = data.getStringExtra("fileName");
				try {

					LoadMission(result);
				} catch (XmlPullParserException e) {
					//
					e.printStackTrace();
				} catch (IOException e) {
					//
					e.printStackTrace();
				}
			}
			if (resultCode == RESULT_CANCELED) {
				// Write your code if there's no result
			}
		}

		if (requestCode == 2) {

			if (resultCode == RESULT_OK) {
				createCircle(data.getStringExtra("MarkerId"), data.getStringExtra("RADIUS"), data.getStringExtra("NRPOINTS"), data.getStringExtra("DIRECTION"));
			}
			if (resultCode == RESULT_CANCELED) {
				// Write your code if there's no result
			}
		}
	}

	public void LoadMission(String filePath) throws XmlPullParserException, IOException {

		ClearMap();

		XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
		factory.setNamespaceAware(true);
		XmlPullParser xpp = factory.newPullParser();

		File file = new File(filePath);
		xpp.setInput(new FileReader(file));

		int eventType = xpp.getEventType();
		while (eventType != XmlPullParser.END_DOCUMENT) {
			if (eventType == XmlPullParser.START_DOCUMENT) {
				Log.d("xml", "Start document");
			} else if (eventType == XmlPullParser.END_DOCUMENT) {
				Log.d("xml", "End document");
			} else if (eventType == XmlPullParser.START_TAG) {

				if (xpp.getName().equals("MISSIONITEM")) {
					Log.d("xml", "Start tag " + xpp.getName());
					try {
						Map<String, String> attributes = getAttributes(xpp);

						int no = Integer.parseInt(attributes.get("no"));
						String action = attributes.get("action");
						int parameter1 = Integer.parseInt(attributes.get("parameter1"));
						int parameter2 = Integer.parseInt(attributes.get("parameter2"));
						int parameter3 = Integer.parseInt(attributes.get("parameter3"));
						double lat = Double.parseDouble(attributes.get("lat").replace(",", "."));
						double lon = Double.parseDouble(attributes.get("lon").replace(",", "."));
						int alt = Integer.parseInt(attributes.get("alt"));

						app.mw.WaypointsList.add(new WaypointNav(no, new LatLng(lat, lon), WaypointNav.getActionNumberFromString(action), parameter1, parameter2, parameter3, alt, 0));

					} catch (Exception e) {
						//
						e.printStackTrace();
					}
				}

				if (xpp.getName().equals("VERSION")) {
					Log.d("xml", "Start tag " + xpp.getName());
					try {
						Map<String, String> attributes = getAttributes(xpp);
						String version = attributes.get("value");
						Log.d("xml", "version= " + version);

						if (!version.equals(supportedWinGuiMissionFiles)) {
							DisplayInfoDialog(getString(R.string.Info), getString(R.string.FileVersionMismach), getString(R.string.OK));
							return;
						}

					} catch (Exception e) {
						//
						e.printStackTrace();
					}
				}

			} else if (eventType == XmlPullParser.END_TAG) {
				Log.d("xml", "End tag " + xpp.getName());
			} else if (eventType == XmlPullParser.TEXT) {
				Log.d("xml", "Text " + xpp.getText());
			}
			eventType = xpp.next();
		}

		LoadMarkersFromWPlist();
		ZoomToShawAllMarkers();
		mDrawerLayout.closeDrawers();
	}

	private Map<String, String> getAttributes(XmlPullParser parser) throws Exception {
		Map<String, String> attrs = null;
		int acount = parser.getAttributeCount();
		if (acount != -1) {
			Log.d("xml", "Attributes for [" + parser.getName() + "]");
			attrs = new HashMap<String, String>(acount);
			for (int x = 0; x < acount; x++) {
				Log.d("xml", "\t[" + parser.getAttributeName(x) + "]=" + "[" + parser.getAttributeValue(x) + "]");
				attrs.put(parser.getAttributeName(x), parser.getAttributeValue(x));
			}
		} else {
			throw new Exception("Required entity attributes missing");
		}
		return attrs;
	}

	void saveMission(String filePath) throws IllegalArgumentException, IllegalStateException, IOException {

		XmlSerializer s = Xml.newSerializer();
		FileWriter writer = new FileWriter(filePath, false);

		s.setOutput(writer);

		s.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
		s.startDocument("UTF-8", true);

		String app_ver = "";
		int app_ver_code = 0;
		try {
			app_ver = getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName;
			app_ver_code = getPackageManager().getPackageInfo(this.getPackageName(), 0).versionCode;
		} catch (NameNotFoundException e1) {
			e1.printStackTrace();
		}

		s.comment(getString(R.string.app_name) + ", Version " + app_ver + "." + String.valueOf(app_ver_code));
		s.comment("MultiWii mission");

		s.startTag("", "MISSION");

		s.startTag("", "VERSION");
		s.attribute("", "value", supportedWinGuiMissionFiles);
		s.endTag("", "VERSION");

		for (WaypointNav wp : app.mw.WaypointsList) {
			s.startTag("", "MISSIONITEM");
			s.attribute("", "no", String.valueOf(wp.Number));
			s.attribute("", "action", WaypointNav.WP_ACTION_NAMES[wp.Action]);
			s.attribute("", "parameter1", String.valueOf(wp.Parameter1));
			s.attribute("", "parameter2", String.valueOf(wp.Parameter2));
			s.attribute("", "parameter3", String.valueOf(wp.Parameter3));
			s.attribute("", "lat", String.valueOf(wp.getLatLng().latitude));
			s.attribute("", "lon", String.valueOf(wp.getLatLng().longitude));
			s.attribute("", "alt", String.valueOf(wp.Altitude));
			s.endTag("", "MISSIONITEM");
		}

		s.endTag("", "MISSION");
		s.endDocument();

		writer.close();
		// Log.d("xml", writer.toString());

	}

	public void SaveMissionOnClick(View v) {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle(getString(R.string.EnterFileName));

		final EditText input = new EditText(this);

		Calendar c = Calendar.getInstance();
		final String s = String.valueOf(c.get(Calendar.DAY_OF_MONTH)) + String.valueOf(c.get(Calendar.MONTH) + 1) + String.valueOf(c.get(Calendar.YEAR)) + "-" + String.valueOf(c.get(Calendar.HOUR)) + String.valueOf(c.get(Calendar.MINUTE));

		input.setText(s);

		alert.setView(input);

		alert.setPositiveButton(getString(R.string.Save), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {

				try {
					saveMission(Environment.getExternalStorageDirectory() + "/MultiWiiLogs/" + input.getText().toString() + ".mission");
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		});

		alert.setNegativeButton(getString(R.string.Cancel), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// Canceled.
			}
		});

		alert.show();

	}

	private final void DisplayInfoDialog(String title, String text, String buttonText) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(title).setMessage(text).setCancelable(false).setNegativeButton(buttonText, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.cancel();
			}
		});
		AlertDialog alert = builder.create();
		alert.show();
	}

	private void createCircle(String MarkerId, String RadiusIn, String Pointsin, String Directionin) {

		Log.d("nav", "create circle");
		LatLng center = getWPfromMarkerId(MarkerId).getLatLng();

		int Points = 0;
		int Radius = 0;
		int Direction = 1;

		Radius = Integer.parseInt(RadiusIn);

		if (Radius < 20) {
			DisplayInfoDialog(getString(R.string.Info), "Invalid Radius", getString(R.string.OK));
			return;
		}

		Points = Integer.parseInt(Pointsin);

		if (Points < 5 || Points > 30) {
			DisplayInfoDialog(getString(R.string.Info), "Invalid Number of points", getString(R.string.OK));
			return;
		}

		Direction = Integer.parseInt(Directionin);

		if (Direction != -1 && Direction != 1) {
			DisplayInfoDialog(getString(R.string.Info), "Invalid Direction value", getString(R.string.OK));
			return;
		}

		double a = 0;
		double step = 360.0f / Points;
		if (Direction == -1) {
			a = 360;
			step *= -1;
		}
		for (; a <= 360 && a >= 0; a += step) {

			float d = Radius;
			float R = 6371000;

			final float rad2deg = (float) (180 / Math.PI);
			final float deg2rad = (float) (1.0 / rad2deg);

			double lat2 = Math.asin(Math.sin(center.latitude * deg2rad) * Math.cos(d / R) + Math.cos(center.latitude * deg2rad) * Math.sin(d / R) * Math.cos(a * deg2rad));
			double lon2 = center.longitude * deg2rad + Math.atan2(Math.sin(a * deg2rad) * Math.sin(d / R) * Math.cos(center.latitude * deg2rad), Math.cos(d / R) - Math.sin(center.latitude * deg2rad) * Math.sin(lat2));

			LatLng pll = new LatLng(lat2 * rad2deg, lon2 * rad2deg);
			app.mw.WaypointsList.add(new WaypointNav(app.mw.WaypointsList.size() + 1, pll, defaultAction, 0, 0, 0, defaultAltitude, 0));

			// AddNewWP(pll);
		}

		LoadMarkersFromWPlist();
		ZoomToShawAllMarkers();
	}

} public class AboutActivity extends SherlockActivity {

	TextView TextViewCopyRights;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.about_layout);

		TextViewCopyRights = (TextView) findViewById(R.id.textViewCopyRights);
		String s = "<b>MultiWii EZ-GUI</b><br>" + "Copyright (C) <2012>  Bartosz Szczygiel (eziosoft)<br><br>" + " This program 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." + "<br>" + "This program is distributed in the hope that it will be useful,  but <b>WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE</b>." + "<br>See the GNU General Public License for more details.<br><br>" + "You should have received a copy of the GNU General Public License along with this program.  If not, see http://www.gnu.org/licenses/" + "<br><br><b>Libraries:</b><br>ActionBarSherlock,<br>ViewPagerIndicator,<br>Osmdroid,<br>slf4j,<br>GraphView by jjoe64,<br>FTDI Driver by @ksksue";

		TextViewCopyRights.setText(Html.fromHtml(s));

		try {
			TextViewCopyRights.append(GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(this));
		} catch (Exception e) {
			// TODO: handle exception
		}

	}
} public class PIDActivity extends SherlockActivity {

	App app;
	// ActionBarSherlock actionBar;

	EditText P1;
	EditText P2;
	EditText P3;
	EditText P4;
	EditText P5;
	EditText P6;
	EditText P7;
	EditText P8;
	EditText P9;

	EditText D1;
	EditText D2;
	EditText D3;
	EditText D4;
	EditText D5;
	EditText D6;
	EditText D7;
	EditText D8;
	EditText D9;

	EditText I1;
	EditText I2;
	EditText I3;
	EditText I4;
	EditText I5;
	EditText I6;
	EditText I7;
	EditText I8;
	EditText I9;

	EditText RollPitchRate;
	EditText RollPitchRate2;
	EditText YawRate;

	EditText ThrottleMid;
	EditText ThrottleExpo;

	EditText RcRate;
	EditText RcExpo;

	EditText ThrottleRate;

	Spinner spinnerProfile;

	// used for write to eeprom
	float[] P;
	float[] I;
	float[] D;

	float confRC_RATE = 0, confRC_EXPO = 0, rollPitchRate = 0, yawRate = 0, dynamic_THR_PID = 0, throttle_MID = 0, throttle_EXPO = 0;

	// ///

	public void OpenInfoOnClick(View v) {
		app.OpenInfoOnClick(v);
	}

	public void SetPIDNames() {
		((TextView) findViewById(R.id.PIDName0)).setText(app.mw.PIDNames[0]);
		((TextView) findViewById(R.id.PIDName1)).setText(app.mw.PIDNames[1]);
		((TextView) findViewById(R.id.PIDName2)).setText(app.mw.PIDNames[2]);
		((TextView) findViewById(R.id.PIDName3)).setText(app.mw.PIDNames[3]);
		((TextView) findViewById(R.id.PIDName4)).setText(app.mw.PIDNames[4]);
		((TextView) findViewById(R.id.PIDName5)).setText(app.mw.PIDNames[5]);
		((TextView) findViewById(R.id.PIDName6)).setText(app.mw.PIDNames[6]);
		((TextView) findViewById(R.id.PIDName7)).setText(app.mw.PIDNames[7]);
		((TextView) findViewById(R.id.PIDName8)).setText(app.mw.PIDNames[8]);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.pid_layout);

		getSupportActionBar().setTitle(getString(R.string.PID));

		app = (App) getApplication();
		// actionBar = getSherlock();

		P = new float[app.mw.PIDITEMS];
		I = new float[app.mw.PIDITEMS];
		D = new float[app.mw.PIDITEMS];

		P1 = (EditText) findViewById(R.id.P1);
		P2 = (EditText) findViewById(R.id.P2);
		P3 = (EditText) findViewById(R.id.P3);
		P4 = (EditText) findViewById(R.id.P4);
		P5 = (EditText) findViewById(R.id.P5);
		P6 = (EditText) findViewById(R.id.P6);
		P7 = (EditText) findViewById(R.id.P7);
		P8 = (EditText) findViewById(R.id.P8);
		P9 = (EditText) findViewById(R.id.P9);

		D1 = (EditText) findViewById(R.id.D1);
		D2 = (EditText) findViewById(R.id.D2);
		D3 = (EditText) findViewById(R.id.D3);
		D4 = (EditText) findViewById(R.id.D4);
		D5 = (EditText) findViewById(R.id.D5);
		D6 = (EditText) findViewById(R.id.D6);
		D7 = (EditText) findViewById(R.id.D7);
		D8 = (EditText) findViewById(R.id.D8);
		D9 = (EditText) findViewById(R.id.D9);

		I1 = (EditText) findViewById(R.id.I1);
		I2 = (EditText) findViewById(R.id.I2);
		I3 = (EditText) findViewById(R.id.I3);
		I4 = (EditText) findViewById(R.id.I4);
		I5 = (EditText) findViewById(R.id.I5);
		I6 = (EditText) findViewById(R.id.I6);
		I7 = (EditText) findViewById(R.id.I7);
		I8 = (EditText) findViewById(R.id.I8);
		I9 = (EditText) findViewById(R.id.I9);

		RollPitchRate = (EditText) findViewById(R.id.editTextRatePitchRoll1);
		RollPitchRate2 = (EditText) findViewById(R.id.editTextRatePitchRoll2);
		YawRate = (EditText) findViewById(R.id.editTextRateYaw);

		ThrottleMid = (EditText) findViewById(R.id.editTextMIDThrottle);
		ThrottleExpo = (EditText) findViewById(R.id.editTextEXPOThrottle);

		RcRate = (EditText) findViewById(R.id.editTextRate2PitchRoll);
		RcExpo = (EditText) findViewById(R.id.editTextEXPOPitchRoll);

		ThrottleRate = (EditText) findViewById(R.id.editTextTPA);

		loadProfileFiles();

		SetPIDNames();

	}

	private void loadProfileFiles() {
		File folder = new File(Environment.getExternalStorageDirectory() + "/MultiWiiLogs");
		boolean success = false;
		if (!folder.exists()) {
			success = folder.mkdir();
		} else {
			success = true;
		}

		if (success) {
			File sdCardRoot = Environment.getExternalStorageDirectory();
			File yourDir = new File(sdCardRoot, "MultiWiiLogs");
			ArrayList<String> l = new ArrayList<String>();

			if (yourDir.listFiles() != null) {
				for (File f : yourDir.listFiles()) {
					if (f.isFile())
						if (f.getName().contains("mwi"))
							l.add(f.getName().replace(".mwi", ""));
				}
			}
			spinnerProfile = (Spinner) findViewById(R.id.spinnerProfile);
			ArrayAdapter aa = new ArrayAdapter(this, android.R.layout.simple_spinner_item, l);

			spinnerProfile.setAdapter(aa);
		}
	}

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

	@Override
	protected void onResume() {
		super.onResume();
		app.ForceLanguage();
		app.Say(getString(R.string.PID));
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

		ReadOnClick(null);
	}

	public void ReadOnClick(View v) {
		app.mw.SendRequestMSP_PID_MSP_RC_TUNING();
		try {
			Thread.sleep(300);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		app.mw.ProcessSerialData(false);

		ShowData();

	}

	void ShareIt() {

		try {

			Log.d("aaa", "File to send:" + Environment.getExternalStorageDirectory() + "/MultiWiiLogs/" + spinnerProfile.getSelectedItem().toString());
			File myFile = new File(Environment.getExternalStorageDirectory() + "/MultiWiiLogs/" + spinnerProfile.getSelectedItem().toString());
			// MimeTypeMap mime = MimeTypeMap.getSingleton();
			// String ext =
			// myFile.getName().substring(myFile.getName().lastIndexOf(".") +
			// 1);
			// String type = mime.getMimeTypeFromExtension(ext);
			Intent sharingIntent = new Intent("android.intent.action.SEND");
			sharingIntent.setType("*/*");
			sharingIntent.putExtra("android.intent.extra.STREAM", Uri.fromFile(myFile));
			startActivity(Intent.createChooser(sharingIntent, "Share using"));
		} catch (Exception e) {
			Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
		}

	}

	public void SetOnClick(View v) {

		// Log.d("aaaaa",RATE2PitchRoll.getText().toString());
		confRC_RATE = Float.parseFloat(RcRate.getText().toString().replace(",", "."));
		confRC_EXPO = Float.parseFloat(RcExpo.getText().toString().replace(",", "."));
		rollPitchRate = Float.parseFloat(RollPitchRate.getText().toString().replace(",", "."));
		yawRate = Float.parseFloat(YawRate.getText().toString().replace(",", "."));
		dynamic_THR_PID = Float.parseFloat(ThrottleRate.getText().toString().replace(",", "."));
		throttle_MID = Float.parseFloat(ThrottleMid.getText().toString().replace(",", "."));
		throttle_EXPO = Float.parseFloat(ThrottleExpo.getText().toString().replace(",", "."));

		P[0] = Float.parseFloat(P1.getText().toString().replace(",", "."));
		P[1] = Float.parseFloat(P2.getText().toString().replace(",", "."));
		P[2] = Float.parseFloat(P3.getText().toString().replace(",", "."));
		P[3] = Float.parseFloat(P4.getText().toString().replace(",", "."));
		P[4] = Float.parseFloat(P5.getText().toString().replace(",", "."));
		P[5] = Float.parseFloat(P6.getText().toString().replace(",", "."));
		P[6] = Float.parseFloat(P7.getText().toString().replace(",", "."));
		P[7] = Float.parseFloat(P8.getText().toString().replace(",", "."));
		P[8] = Float.parseFloat(P9.getText().toString().replace(",", "."));

		I[0] = Float.parseFloat(I1.getText().toString().replace(",", "."));
		I[1] = Float.parseFloat(I2.getText().toString().replace(",", "."));
		I[2] = Float.parseFloat(I3.getText().toString().replace(",", "."));
		I[3] = Float.parseFloat(I4.getText().toString().replace(",", "."));
		I[4] = Float.parseFloat(I5.getText().toString().replace(",", "."));
		I[5] = Float.parseFloat(I6.getText().toString().replace(",", "."));
		I[6] = Float.parseFloat(I7.getText().toString().replace(",", "."));
		I[7] = Float.parseFloat(I8.getText().toString().replace(",", "."));
		I[8] = Float.parseFloat(I9.getText().toString().replace(",", "."));

		D[0] = Float.parseFloat(D1.getText().toString().replace(",", "."));
		D[1] = Float.parseFloat(D2.getText().toString().replace(",", "."));
		D[2] = Float.parseFloat(D3.getText().toString().replace(",", "."));
		D[3] = Float.parseFloat(D4.getText().toString().replace(",", "."));
		D[4] = Float.parseFloat(D5.getText().toString().replace(",", "."));
		D[5] = Float.parseFloat(D6.getText().toString().replace(",", "."));
		D[6] = Float.parseFloat(D7.getText().toString().replace(",", "."));
		D[7] = Float.parseFloat(D8.getText().toString().replace(",", "."));
		D[8] = Float.parseFloat(D9.getText().toString().replace(",", "."));

		if (v != null) {
			app.mw.SendRequestMSP_SET_PID(confRC_RATE, confRC_EXPO, rollPitchRate, yawRate, dynamic_THR_PID, throttle_MID, throttle_EXPO, P, I, D);
			app.mw.SendRequestMSP_EEPROM_WRITE();
			Toast.makeText(getApplicationContext(), getString(R.string.Done), Toast.LENGTH_SHORT).show();
		} else {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(getString(R.string.Continue)).setCancelable(false).setPositiveButton(getString(R.string.Yes), new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog, int id) {

					app.mw.SendRequestMSP_SET_PID(confRC_RATE, confRC_EXPO, rollPitchRate, yawRate, dynamic_THR_PID, throttle_MID, throttle_EXPO, P, I, D);
					app.mw.SendRequestMSP_EEPROM_WRITE();
					Toast.makeText(getApplicationContext(), getString(R.string.Done), Toast.LENGTH_SHORT).show();

				}
			}).setNegativeButton(getString(R.string.No), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
				}
			});
			AlertDialog alert = builder.create();
			alert.show();
		}

	}

	public void LoadProfilePIDOnClick(View v) {
		try {
			if (spinnerProfile.getCount() > 0)
				readFromXML("/MultiWiiLogs/" + spinnerProfile.getSelectedItem().toString() + ".mwi");
		} catch (InvalidPropertiesFormatException e) {

			e.printStackTrace();
		} catch (IOException e) {

			e.printStackTrace();
		}
	}

	private void readFromXML(String fileName) throws InvalidPropertiesFormatException, IOException {

		File sdcard = Environment.getExternalStorageDirectory();
		File file = new File(sdcard, fileName);
		Properties properties = new Properties();
		FileInputStream fis = new FileInputStream(file);
		properties.loadFromXML(fis);

		for (int i = 0; i < app.mw.PIDITEMS; i++) {
			P[i] = Float.parseFloat(properties.getProperty("pid." + i + ".p"));
			I[i] = Float.parseFloat(properties.getProperty("pid." + i + ".i"));
			D[i] = Float.parseFloat(properties.getProperty("pid." + i + ".d"));
		}

		P1.setText(String.format("%.1f", P[0]));
		P2.setText(String.format("%.1f", P[1]));
		P3.setText(String.format("%.1f", P[2]));
		P4.setText(String.format("%.1f", P[3]));
		P5.setText(String.format("%.2f", P[4]));
		P6.setText(String.format("%.1f", P[5]));
		P7.setText(String.format("%.1f", P[6]));
		P8.setText(String.format("%.1f", P[7]));
		P9.setText(String.format("%.1f", P[8]));

		I1.setText(String.format("%.3f", I[0]));
		I2.setText(String.format("%.3f", I[1]));
		I3.setText(String.format("%.3f", I[2]));
		I4.setText(String.format("%.3f", I[3]));
		I5.setText(String.format("%.1f", I[4]));
		I6.setText(String.format("%.2f", I[5]));
		I7.setText(String.format("%.2f", I[6]));
		I8.setText(String.format("%.3f", I[7]));
		I9.setText(String.format("%.3f", I[8]));

		D1.setText(String.format("%.0f", D[0]));
		D2.setText(String.format("%.0f", D[1]));
		D3.setText(String.format("%.0f", D[2]));
		D4.setText(String.format("%.0f", D[3]));
		D5.setText(String.format("%.0f", D[4]));
		D6.setText(String.format("%.3f", D[5]));
		D7.setText(String.format("%.3f", D[6]));
		D8.setText(String.format("%.0f", D[7]));
		D9.setText(String.format("%.3f", D[8]));

		RollPitchRate.setText(String.format("%.2f", Float.valueOf(properties.getProperty("rc.rollpitch.rate"))));
		RollPitchRate2.setText(String.format("%.2f", Float.valueOf(properties.getProperty("rc.rollpitch.rate"))));

		YawRate.setText(String.format("%.2f", Float.valueOf(properties.getProperty("rc.yaw.rate"))));

		ThrottleMid.setText(String.format("%.2f", Float.valueOf(properties.getProperty("rc.throttle.mid"))));
		ThrottleExpo.setText(String.format("%.2f", Float.valueOf(properties.getProperty("rc.throttle.expo"))));

		RcRate.setText(String.format("%.2f", Float.valueOf(properties.getProperty("rc.rate"))));
		RcExpo.setText(String.format("%.2f", Float.valueOf(properties.getProperty("rc.expo"))));

		ThrottleRate.setText(String.format("%.2f", Float.valueOf(properties.getProperty("rc.throttle.rate"))));

	}

	private void ShowData() {

		P1.setText(String.format("%.1f", (float) app.mw.byteP[0] / 10.0));
		P2.setText(String.format("%.1f", (float) app.mw.byteP[1] / 10.0));
		P3.setText(String.format("%.1f", (float) app.mw.byteP[2] / 10.0));
		P4.setText(String.format("%.1f", (float) app.mw.byteP[3] / 10.0));
		P5.setText(String.format("%.2f", (float) app.mw.byteP[4] / 100.0));
		P6.setText(String.format("%.1f", (float) app.mw.byteP[5] / 10.0));
		P7.setText(String.format("%.1f", (float) app.mw.byteP[6] / 10.0));
		P8.setText(String.format("%.1f", (float) app.mw.byteP[7] / 10.0));
		P9.setText(String.format("%.1f", (float) app.mw.byteP[8] / 10.0));

		I1.setText(String.format("%.3f", (float) app.mw.byteI[0] / 1000.0));
		I2.setText(String.format("%.3f", (float) app.mw.byteI[1] / 1000.0));
		I3.setText(String.format("%.3f", (float) app.mw.byteI[2] / 1000.0));
		I4.setText(String.format("%.3f", (float) app.mw.byteI[3] / 1000.0));
		I5.setText(String.format("%.1f", (float) app.mw.byteI[4] / 100.0));
		I6.setText(String.format("%.2f", (float) app.mw.byteI[5] / 100.0));
		I7.setText(String.format("%.2f", (float) app.mw.byteI[6] / 100.0));
		I8.setText(String.format("%.3f", (float) app.mw.byteI[7] / 1000.0));
		I9.setText(String.format("%.3f", (float) app.mw.byteI[8] / 1000.0));

		D1.setText(String.format("%.0f", (float) app.mw.byteD[0]));
		D2.setText(String.format("%.0f", (float) app.mw.byteD[1]));
		D3.setText(String.format("%.0f", (float) app.mw.byteD[2]));
		D4.setText(String.format("%.0f", (float) app.mw.byteD[3]));
		D5.setText(String.format("%.0f", (float) app.mw.byteD[4]));
		D6.setText(String.format("%.3f", (float) app.mw.byteD[5] / 1000.0));
		D7.setText(String.format("%.3f", (float) app.mw.byteD[6] / 1000.0));
		D8.setText(String.format("%.0f", (float) app.mw.byteD[7]));
		D9.setText(String.format("%.3f", (float) app.mw.byteD[8]));

		RollPitchRate.setText(String.format("%.2f", (float) app.mw.byteRollPitchRate / 100.0));
		RollPitchRate2.setText(String.format("%.2f", (float) app.mw.byteRollPitchRate / 100.0));

		YawRate.setText(String.format("%.2f", (float) app.mw.byteYawRate / 100.0));

		ThrottleMid.setText(String.format("%.2f", (float) app.mw.byteThrottle_MID / 100.0));
		ThrottleExpo.setText(String.format("%.2f", (float) app.mw.byteThrottle_EXPO / 100.0));

		RcRate.setText(String.format("%.2f", (float) app.mw.byteRC_RATE / 100.0));
		RcExpo.setText(String.format("%.2f", (float) app.mw.byteRC_EXPO / 100.0));

		ThrottleRate.setText(String.format("%.2f", (float) app.mw.byteDynThrPID / 100.0));
	}

	public void SaveProfileOnClick(View v) {

		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setTitle(getString(R.string.EnterFileName));
		// alert.setMessage(getString(R.string.Profile));

		// Set an EditText view to get user input
		final EditText input = new EditText(this);
		if (spinnerProfile.getCount() > 0) {
			input.setText(spinnerProfile.getSelectedItem().toString());
		}
		alert.setView(input);

		alert.setPositiveButton(getString(R.string.Save), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {

				try {
					SaveToXml(input.getText().toString());
				} catch (InvalidPropertiesFormatException e) {

					e.printStackTrace();
				} catch (IOException e) {

					e.printStackTrace();
				}

				loadProfileFiles();

			}
		});

		alert.setNegativeButton(getString(R.string.Cancel), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// Canceled.
			}
		});

		alert.show();

	}

	private void SaveToXml(String fileName) throws InvalidPropertiesFormatException, IOException {

		confRC_RATE = Float.parseFloat(RcRate.getText().toString().replace(",", "."));
		confRC_EXPO = Float.parseFloat(RcExpo.getText().toString().replace(",", "."));
		rollPitchRate = Float.parseFloat(RollPitchRate.getText().toString().replace(",", "."));
		yawRate = Float.parseFloat(YawRate.getText().toString().replace(",", "."));
		dynamic_THR_PID = Float.parseFloat(ThrottleRate.getText().toString().replace(",", "."));
		throttle_MID = Float.parseFloat(ThrottleMid.getText().toString().replace(",", "."));
		throttle_EXPO = Float.parseFloat(ThrottleExpo.getText().toString().replace(",", "."));

		P[0] = Float.parseFloat(P1.getText().toString().replace(",", "."));
		P[1] = Float.parseFloat(P2.getText().toString().replace(",", "."));
		P[2] = Float.parseFloat(P3.getText().toString().replace(",", "."));
		P[3] = Float.parseFloat(P4.getText().toString().replace(",", "."));
		P[4] = Float.parseFloat(P5.getText().toString().replace(",", "."));
		P[5] = Float.parseFloat(P6.getText().toString().replace(",", "."));
		P[6] = Float.parseFloat(P7.getText().toString().replace(",", "."));
		P[7] = Float.parseFloat(P8.getText().toString().replace(",", "."));
		P[8] = Float.parseFloat(P9.getText().toString().replace(",", "."));

		I[0] = Float.parseFloat(I1.getText().toString().replace(",", "."));
		I[1] = Float.parseFloat(I2.getText().toString().replace(",", "."));
		I[2] = Float.parseFloat(I3.getText().toString().replace(",", "."));
		I[3] = Float.parseFloat(I4.getText().toString().replace(",", "."));
		I[4] = Float.parseFloat(I5.getText().toString().replace(",", "."));
		I[5] = Float.parseFloat(I6.getText().toString().replace(",", "."));
		I[6] = Float.parseFloat(I7.getText().toString().replace(",", "."));
		I[7] = Float.parseFloat(I8.getText().toString().replace(",", "."));
		I[8] = Float.parseFloat(I9.getText().toString().replace(",", "."));

		D[0] = Float.parseFloat(D1.getText().toString().replace(",", "."));
		D[1] = Float.parseFloat(D2.getText().toString().replace(",", "."));
		D[2] = Float.parseFloat(D3.getText().toString().replace(",", "."));
		D[3] = Float.parseFloat(D4.getText().toString().replace(",", "."));
		D[4] = Float.parseFloat(D5.getText().toString().replace(",", "."));
		D[5] = Float.parseFloat(D6.getText().toString().replace(",", "."));
		D[6] = Float.parseFloat(D7.getText().toString().replace(",", "."));
		D[7] = Float.parseFloat(D8.getText().toString().replace(",", "."));
		D[8] = Float.parseFloat(D9.getText().toString().replace(",", "."));

		File sdcard = Environment.getExternalStorageDirectory();
		File file = new File(sdcard, "/MultiWiiLogs/" + fileName + ".mwi");
		Properties properties = new Properties();
		FileOutputStream fos = new FileOutputStream(file);

		for (int i = 0; i < app.mw.PIDITEMS; i++) {
			properties.setProperty("pid." + i + ".p", String.valueOf(P[i]).replace(",", "."));
			properties.setProperty("pid." + i + ".i", String.valueOf(I[i]).replace(",", "."));
			properties.setProperty("pid." + i + ".d", String.valueOf(D[i]).replace(",", "."));
		}

		properties.setProperty("rc.rollpitch.rate", RollPitchRate.getText().toString().replace(",", "."));
		properties.setProperty("rc.yaw.rate", YawRate.getText().toString().replace(",", "."));
		properties.setProperty("rc.throttle.mid", ThrottleMid.getText().toString().replace(",", "."));
		properties.setProperty("rc.throttle.expo", ThrottleExpo.getText().toString().replace(",", "."));
		properties.setProperty("rc.rate", RcRate.getText().toString().replace(",", "."));
		properties.setProperty("rc.expo", RcExpo.getText().toString().replace(",", "."));
		properties.setProperty("rc.throttle.rate", ThrottleRate.getText().toString().replace(",", "."));

		properties.storeToXML(fos, new Date().toString());

		Toast.makeText(getApplicationContext(), getString(R.string.Settingssaved), Toast.LENGTH_SHORT).show();

	}

	public void ShowCustomDialogOnClick(final View vv) {
		CustomInputDialog.ShowCustomDialogOnClick(vv, this);
	}

	// /////menu////////
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getSupportMenuInflater();
		inflater.inflate(R.menu.menu_pid, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.MenuReadPID) {
			ReadOnClick(null);
			return true;
		}

		if (item.getItemId() == R.id.MenuSavePID) {
			SetOnClick(null);
			return true;
		}

		if (item.getItemId() == R.id.MenuSharePID) {
			ShareIt();
			return true;
		}

		return false;
	}

	// ///menu end//////

} public class ServosActivity extends SherlockActivity {

	private boolean killme = false;
	final int ROWS = 8;
	final int COLS = 4;

	App app;
	Handler mHandler = new Handler();

	private Runnable update = new Runnable() {
		@Override
		public void run() {

			app.mw.ProcessSerialData(app.loggingON);

			app.frskyProtocol.ProcessSerialData(false);
			app.Frequentjobs();

			app.mw.SendRequest(app.MainRequestMethod);
			if (!killme)
				mHandler.postDelayed(update, app.RefreshRate);

		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		app = (App) getApplication();
		app.ForceLanguage();
		
		setContentView(R.layout.servo_conf_layout);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		getSupportActionBar().setTitle(getString(R.string.Servos));

	}

	@Override
	protected void onResume() {
		super.onResume();
		app.ForceLanguage();
		app.Say(getString(R.string.Servos));
		killme = false;
		// mHandler.postDelayed(update, app.RefreshRate);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

		ServoReadOnClick();

		if (Sec.VerifyDeveloperID(Sec.GetDeviceID(getApplicationContext()), Sec.TestersIDs) || Sec.Verify(getApplicationContext(), "D..3")) {
			mHandler.postDelayed(update, app.RefreshRate);
		} else {
			AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);

			dlgAlert.setTitle(getString(R.string.Locked));
			dlgAlert.setMessage(getString(R.string.DoYouWantToUnlock));

			// dlgAlert.setPositiveButton(getString(R.string.Yes), null);
			dlgAlert.setCancelable(false);
			dlgAlert.setPositiveButton(getString(R.string.Yes), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					try {
						Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.ezio.ez_gui_unlocker");
						startActivity(LaunchIntent);
					} catch (Exception e) {
						Intent goToMarket = null;
						goToMarket = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.ezio.ez_gui_unlocker"));
						startActivity(goToMarket);
					}
					finish();
				}
			});
			dlgAlert.setNegativeButton(getString(R.string.No), new OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});

			dlgAlert.create().show();
		}

	}

	@Override
	protected void onPause() {
		super.onPause();
		mHandler.removeCallbacks(null);
		killme = true;
	}

	public void ServoCheckBoxOnClick(View v) {
		String name = getResources().getResourceEntryName(v.getId());
		Log.d("aaa", name.substring(3, 5));

		int i = Integer.parseInt(name.substring(3, 5)) - 1;
		for (int j = 0; j < COLS; j++) {
			String a = String.format("%02d", i + 1);
			String b = String.format("%02d", j + 1);
			int editTextId = getResources().getIdentifier("box" + a + b, "id", getPackageName());
			EditText et = (EditText) findViewById(editTextId);
			switch (j) {
			case 3:
				int checkbox1Id = getResources().getIdentifier("box" + a + String.format("%02d", j + 2), "id", getPackageName());
				CheckBox cb1 = (CheckBox) findViewById(checkbox1Id);
				int checkbox2Id = getResources().getIdentifier("box" + a + String.format("%02d", j + 3), "id", getPackageName());
				CheckBox cb2 = (CheckBox) findViewById(checkbox2Id);

				if (i < 2) {
					if (cb1.isChecked() && Integer.parseInt(et.getText().toString()) != 0) {
						et.setText(String.valueOf((Math.abs(Integer.parseInt(et.getText().toString()))) * -1));
					} else {
						et.setText(String.valueOf((Math.abs(Integer.parseInt(et.getText().toString())))));
					}
				}

				if (i == 2) {
					if (cb1.isChecked()) {
						et.setText("1");
					} else {
						et.setText("0");
					}
				}

				if (i > 2) {
					int x = (cb1.isChecked()) ? 1 : 0;
					int y = (cb2.isChecked()) ? 2 : 0;
					et.setText(String.valueOf(x + y));
				}
				break;
			}
		}
	}

	private void ServoWriteOnClick() {

		for (int i = 0; i < ROWS; i++) {
			for (int j = 0; j < COLS; j++) {
				String a = String.format("%02d", i + 1);
				String b = String.format("%02d", j + 1);
				int editTextId = getResources().getIdentifier("box" + a + b, "id", getPackageName());
				EditText et = (EditText) findViewById(editTextId);
				switch (j) {
				case 0:

					app.mw.ServoConf[i].Min = Integer.parseInt(et.getText().toString());
					break;
				case 1:

					app.mw.ServoConf[i].Max = Integer.parseInt(et.getText().toString());
					break;
				case 2:
					app.mw.ServoConf[i].MidPoint = Integer.parseInt(et.getText().toString());
					break;
				case 3:

					if (Integer.parseInt(et.getText().toString()) < 0) {
						app.mw.ServoConf[i].Rate = Integer.parseInt(et.getText().toString()) + 256;
					} else {
						app.mw.ServoConf[i].Rate = Integer.parseInt(et.getText().toString());
					}
					break;
				}
			}
		}

		app.mw.SendRequestMSP_SET_SERVO_CONF();
	}

	public void ServoReadOnClick() {
		app.mw.SendRequestMSP_SERVO_CONF();

		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		app.mw.ProcessSerialData(app.loggingON);
		for (int i = 0; i < 8; i++) {

			// TODO
			// Check the boundaries, if no servos are defined in config.h then
			// the servo variables remain uninitailised in EEPROM so expect
			// gibberis

			if ((app.mw.ServoConf[i].Min < 400) || (app.mw.ServoConf[i].Min > 1500))
				app.mw.ServoConf[i].Min = 1000;

			if ((app.mw.ServoConf[i].Max < 1500) || (app.mw.ServoConf[i].Max > 2500))
				app.mw.ServoConf[i].Max = 2000;

			if ((app.mw.ServoConf[i].MidPoint < 0) || (app.mw.ServoConf[i].MidPoint > 2000))
				app.mw.ServoConf[i].MidPoint = 1500;

			// if (app.mw.ServoConf[i].Rate == 0)
			// app.mw.ServoConf[i].Rate = 100;

		}
		for (int i = 0; i < ROWS; i++) {
			for (int j = 0; j < COLS; j++) {
				String a = String.format("%02d", i + 1);
				String b = String.format("%02d", j + 1);
				int editTextId = getResources().getIdentifier("box" + a + b, "id", getPackageName());
				EditText et = (EditText) findViewById(editTextId);
				//
				et.setFocusable(false);
				//
				switch (j) {
				case 0:
					et.setText(String.valueOf(app.mw.ServoConf[i].Min));
					break;
				case 1:
					et.setText(String.valueOf(app.mw.ServoConf[i].Max));
					break;
				case 2:
					et.setText(String.valueOf(app.mw.ServoConf[i].MidPoint));
					break;
				case 3:
					int checkbox1Id = getResources().getIdentifier("box" + a + String.format("%02d", j + 2), "id", getPackageName());
					CheckBox cb1 = (CheckBox) findViewById(checkbox1Id);
					int checkbox2Id = getResources().getIdentifier("box" + a + String.format("%02d", j + 3), "id", getPackageName());
					CheckBox cb2 = (CheckBox) findViewById(checkbox2Id);

					if (app.mw.ServoConf[i].Rate > 127) {

						et.setText(String.valueOf(app.mw.ServoConf[i].Rate - 256));
					} else {
						et.setText(String.valueOf(app.mw.ServoConf[i].Rate));
					}

					if (i < 2) {
						cb2.setVisibility(View.INVISIBLE);
						if (app.mw.ServoConf[i].Rate > 127) {
							cb1.setChecked(true);
						} else {
							cb1.setChecked(false);
						}
					}

					if (i == 2) {
						cb2.setVisibility(View.INVISIBLE);
						if (app.mw.ServoConf[i].Rate == 1) {
							cb1.setChecked(true);
						} else {
							cb1.setChecked(false);
						}
					}

					if (i > 2) {
						if (app.mw.ServoConf[i].Rate == 1) {
							cb1.setChecked(true);
							cb2.setChecked(false);
						}

						if (app.mw.ServoConf[i].Rate == 2) {
							cb1.setChecked(false);
							cb2.setChecked(true);
						}

						if (app.mw.ServoConf[i].Rate == 3) {
							cb1.setChecked(true);
							cb2.setChecked(true);
						}

						if (app.mw.ServoConf[i].Rate > 3 || app.mw.ServoConf[i].Rate < 0) {
							cb1.setChecked(false);
							cb2.setChecked(false);
						}
					}

					break;
				}
			}
		}
	}

	public void OpenInfoOnClick(View v) {
		app.OpenInfoOnClick(v);
	}

	public void ShowCustomDialogOnClick(View vv) {
		CustomInputDialog.ShowCustomDialogOnClick(vv, this);
	}

	// /////menu////////
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getSupportMenuInflater();
		inflater.inflate(R.menu.menu_servoconf, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.MenuReadServo) {
			ServoReadOnClick();
			return true;
		}

		if (item.getItemId() == R.id.MenuSaveServo) {

			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(getString(R.string.Continue)).setCancelable(false).setPositiveButton(getString(R.string.Yes), new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog, int id) {

					ServoWriteOnClick();
					Toast.makeText(getApplicationContext(), getString(R.string.Done), Toast.LENGTH_SHORT).show();

				}
			}).setNegativeButton(getString(R.string.No), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
				}
			});
			AlertDialog alert = builder.create();
			alert.show();

			return true;
		}

		return false;
	}

	// ///menu end//////
} public class ConfigActivity extends SherlockActivity {

	ViewFlipper VF;

	App app;
	RadioButton Mode1;
	RadioButton Mode2;
	RadioButton Protocol220;
	RadioButton Protocol230;
	RadioButton Protocol231;
	RadioButton MagMode1;
	RadioButton MagMode2;
	RadioButton RadioFTDI;
	RadioButton RadioOtherChips;

	TextView MacAddressBTTV;
	TextView MacAddressBTFrskyTV;

	CheckBox CheckBoxTTS;

	CheckBox CheckBoxDisableBTonExit;
	CheckBox CheckBoxCopyFrskyToMW;
	CheckBox CheckBoxReverseRollDirection;
	CheckBox CheckBoxUseFTDISerial;
	CheckBox CheckBoxFrskySupport;
	CheckBox CheckBoxBT_New;
	CheckBox CheckBoxNoDataReceivedWarning;

	RadioButton RadioNotForce;
	RadioButton RadioForceEnglish;
	RadioButton RadioForceGerman;
	RadioButton RadioForceHungarian;
	RadioButton RadioForcePolish;
	RadioButton RadioForceCzech;

	EditText EditTextPeriodicSpeaking;
	EditText EditTextVoltageAlarm;
	EditText EditTextRefreshRate;
	EditText EditTextMapCenterPeriod;
	EditText EditTextSerialBaudRateMW;

	LinearLayout LayoutSerialFTDI;

	private static final int REQUEST_CONNECT_DEVICE_MULTIWII = 1;
	private static final int REQUEST_CONNECT_DEVICE_FRSKY = 2;

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_CONNECT_DEVICE_MULTIWII:
			if (resultCode == Activity.RESULT_OK) {
				String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
				app.MacAddress = address;
				MacAddressBTTV.setText("MAC:" + app.MacAddress);
			}
			break;

		case REQUEST_CONNECT_DEVICE_FRSKY:
			if (resultCode == Activity.RESULT_OK) {
				String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
				app.MacAddressFrsky = address;
				MacAddressBTFrskyTV.setText("MAC:" + app.MacAddressFrsky);
			}
			break;
		}
	}

	public void SelectBTdevice(View v) {
		Intent serverIntent = null;
		serverIntent = new Intent(this, DeviceListActivity.class);
		startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_MULTIWII);
	}

	public void SelectFrskyDevice(View v) {
		Intent serverIntent = null;
		serverIntent = new Intent(this, DeviceListActivity.class);
		startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_FRSKY);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.config_layout);

		app = (App) getApplication();

		VF = (ViewFlipper) findViewById(R.id.viewFlipperConfig);
		VF.setInAnimation(this, android.R.anim.slide_in_left);
		VF.setOutAnimation(this, android.R.anim.slide_out_right);

		Mode1 = (RadioButton) findViewById(R.id.radioButton1);
		Mode2 = (RadioButton) findViewById(R.id.radioButton2);
		Protocol220 = (RadioButton) findViewById(R.id.radioButtonProtocol220);
		Protocol230 = (RadioButton) findViewById(R.id.radioButtonProtocol230);
		Protocol231 = (RadioButton) findViewById(R.id.radioButtonProtocol231);
		MagMode1 = (RadioButton) findViewById(R.id.radioButtonMagMode1);
		MagMode2 = (RadioButton) findViewById(R.id.radioButtonMagMode2);
		CheckBoxTTS = (CheckBox) findViewById(R.id.checkBoxTTS);
		MacAddressBTTV = (TextView) findViewById(R.id.textViewMacAddress);
		MacAddressBTFrskyTV = (TextView) findViewById(R.id.textViewMacAddressFrsky);
		CheckBoxDisableBTonExit = (CheckBox) findViewById(R.id.checkBoxDisableBTonExit);
		RadioNotForce = (RadioButton) findViewById(R.id.RadioDontForce);
		RadioForceEnglish = (RadioButton) findViewById(R.id.radioForceEnglish);
		RadioForceGerman = (RadioButton) findViewById(R.id.radioForceGerman);
		RadioForceHungarian = (RadioButton) findViewById(R.id.radioForceHungarian);
		RadioForcePolish = (RadioButton) findViewById(R.id.radioForcePolish);
		RadioForceCzech = (RadioButton) findViewById(R.id.radioForceCzech);
		EditTextPeriodicSpeaking = (EditText) findViewById(R.id.editTextPeriodicSpeaking);
		EditTextVoltageAlarm = (EditText) findViewById(R.id.editTextVoltageAlarm);
		EditTextRefreshRate = (EditText) findViewById(R.id.editTextRefreshRate);
		CheckBoxCopyFrskyToMW = (CheckBox) findViewById(R.id.checkBoxCopyFrskyToMW);
		CheckBoxReverseRollDirection = (CheckBox) findViewById(R.id.checkBoxReverseRollDirection);
		EditTextMapCenterPeriod = (EditText) findViewById(R.id.EditTextMapCenterPeriod);
		CheckBoxUseFTDISerial = (CheckBox) findViewById(R.id.checkBoxUseFTDISerial);
		EditTextSerialBaudRateMW = (EditText) findViewById(R.id.editTextSerialPortBaudRate);
		LayoutSerialFTDI = (LinearLayout) findViewById(R.id.LinearLayoutSerialPort);
		RadioFTDI = (RadioButton) findViewById(R.id.radioFTDI);
		RadioOtherChips = (RadioButton) findViewById(R.id.radioOtherChips);
		CheckBoxBT_New = (CheckBox) findViewById(R.id.CheckBox_BT_New);
		CheckBoxNoDataReceivedWarning = (CheckBox) findViewById(R.id.checkBoxNoDataReceivedWarning);

		CheckBoxFrskySupport = (CheckBox) findViewById(R.id.checkBoxFrskySupport);
		CheckBoxFrskySupport.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				ShowFrskySupport(isChecked);
			}
		});

		CheckBoxUseFTDISerial.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (isChecked) {
					RadioFTDI.setChecked(true);
					RadioOtherChips.setChecked(false);
				}
			}
		});

	}

	void ShowFrskySupport(boolean visible) {
		if (visible) {
			findViewById(R.id.FrskySupportLayout).setVisibility(View.VISIBLE);
		} else {
			findViewById(R.id.FrskySupportLayout).setVisibility(View.GONE);
		}
	}

	@Override
	protected void onPause() {
		SaveSettingsOnClick(null);
		app.ConfigHasBeenChange_DisplayRestartInfo = true;

		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
		app.ForceLanguage();

		if (app.RadioMode == 1) {
			Mode1.setChecked(true);
		} else {
			Mode2.setChecked(true);
		}

		switch (app.Protocol) {
		case App.PROTOCOL_220:
			Protocol220.setChecked(true);
			break;
		case App.PROTOCOL_230:
			Protocol230.setChecked(true);
			break;
		case App.PROTOCOL_NAV:
			Protocol231.setChecked(true);
			break;

		default:
			break;
		}

		if (app.MagMode == 1) {
			MagMode1.setChecked(true);
		} else {
			MagMode2.setChecked(true);
		}

		CheckBoxTTS.setChecked(app.TextToSpeach);
		CheckBoxDisableBTonExit.setChecked(app.DisableBTonExit);
		CheckBoxCopyFrskyToMW.setChecked(app.CopyFrskyToMW);
		CheckBoxReverseRollDirection.setChecked(app.ReverseRoll);
		CheckBoxUseFTDISerial.setChecked(app.CommunicationTypeMW == App.COMMUNICATION_TYPE_SERIAL_FTDI || app.CommunicationTypeMW == App.COMMUNICATION_TYPE_SERIAL_OTHERCHIPS);
		if (CheckBoxUseFTDISerial.isChecked()) {
			RadioFTDI.setChecked(app.CommunicationTypeMW == App.COMMUNICATION_TYPE_SERIAL_FTDI || app.CommunicationTypeMW == App.COMMUNICATION_TYPE_BT);
			RadioOtherChips.setChecked(app.CommunicationTypeMW == App.COMMUNICATION_TYPE_SERIAL_OTHERCHIPS);
		}
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR1) {
			LayoutSerialFTDI.setVisibility(View.GONE);
		}

		MacAddressBTTV.setText("MAC:" + app.MacAddress);
		MacAddressBTFrskyTV.setText("MAC:" + app.MacAddressFrsky);

		RadioNotForce.setChecked(app.ForceLanguage.equals(""));
		RadioForceEnglish.setChecked(app.ForceLanguage.equals("en"));
		RadioForceGerman.setChecked(app.ForceLanguage.equals("de"));
		RadioForceHungarian.setChecked(app.ForceLanguage.equals("hu"));
		RadioForcePolish.setChecked(app.ForceLanguage.equals("pl"));
		RadioForcePolish.setChecked(app.ForceLanguage.equals("cz"));

		EditTextPeriodicSpeaking.setText(String.valueOf(app.PeriodicSpeaking / 1000));

		EditTextVoltageAlarm.setText(String.valueOf(app.VoltageAlarm));
		EditTextRefreshRate.setText(String.valueOf(app.RefreshRate));
		EditTextMapCenterPeriod.setText(String.valueOf(app.MapCenterPeriod));
		EditTextSerialBaudRateMW.setText(String.valueOf(app.SerialPortBaudRateMW));

		CheckBoxFrskySupport.setChecked(app.FrskySupport);
		ShowFrskySupport(app.FrskySupport);

		if (app.CommunicationTypeMW == App.COMMUNICATION_TYPE_BT_NEW) {
			CheckBoxBT_New.setChecked(true);
		} else {
			CheckBoxBT_New.setChecked(false);
		}

		CheckBoxNoDataReceivedWarning.setChecked(app.NoDataReceievedWarning);

		app.Say(getString(R.string.Config));

		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

	}

	public void SaveSettingsOnClick(View v) {

		if (Mode1.isChecked()) {
			app.RadioMode = 1;
		} else {
			app.RadioMode = 2;
		}

		if (Protocol220.isChecked()) {
			app.Protocol = App.PROTOCOL_220;
		}

		if (Protocol230.isChecked()) {
			app.Protocol = App.PROTOCOL_230;
		}

		if (Protocol231.isChecked()) {
			app.Protocol = App.PROTOCOL_NAV;
		}

		if (MagMode1.isChecked()) {
			app.MagMode = 1;
		} else {
			app.MagMode = 2;
		}

		app.TextToSpeach = CheckBoxTTS.isChecked();
		app.DisableBTonExit = CheckBoxDisableBTonExit.isChecked();
		app.CopyFrskyToMW = CheckBoxCopyFrskyToMW.isChecked();
		app.ReverseRoll = CheckBoxReverseRollDirection.isChecked();

		if (RadioNotForce.isChecked())
			app.ForceLanguage = "";
		if (RadioForceEnglish.isChecked())
			app.ForceLanguage = "en";
		if (RadioForceGerman.isChecked())
			app.ForceLanguage = "de";
		if (RadioForceHungarian.isChecked())
			app.ForceLanguage = "hu";
		if (RadioForcePolish.isChecked())
			app.ForceLanguage = "pl";
		if (RadioForceCzech.isChecked())
			app.ForceLanguage = "cs";

		app.PeriodicSpeaking = Integer.parseInt(EditTextPeriodicSpeaking.getText().toString()) * 1000;
		app.VoltageAlarm = Float.parseFloat(EditTextVoltageAlarm.getText().toString());
		app.RefreshRate = Integer.parseInt(EditTextRefreshRate.getText().toString());
		app.MapCenterPeriod = Integer.parseInt(EditTextMapCenterPeriod.getText().toString());

		if (CheckBoxUseFTDISerial.isChecked()) {
			if (RadioFTDI.isChecked())
				app.CommunicationTypeMW = App.COMMUNICATION_TYPE_SERIAL_FTDI;

			if (RadioOtherChips.isChecked())
				app.CommunicationTypeMW = App.COMMUNICATION_TYPE_SERIAL_OTHERCHIPS;

		} else {
			if (!CheckBoxBT_New.isChecked())
				app.CommunicationTypeMW = App.COMMUNICATION_TYPE_BT;

			if (CheckBoxBT_New.isChecked())
				app.CommunicationTypeMW = App.COMMUNICATION_TYPE_BT_NEW;
		}

		if (EditTextSerialBaudRateMW.getText().toString().equals(""))
			EditTextSerialBaudRateMW.setText("115200");
		app.SerialPortBaudRateMW = Integer.parseInt(EditTextSerialBaudRateMW.getText().toString());

		app.FrskySupport = CheckBoxFrskySupport.isChecked();

		app.NoDataReceievedWarning = CheckBoxNoDataReceivedWarning.isChecked();

		app.SaveSettings(false);

	}

	public void NextOnClick(View v) {

		if (VF.getDisplayedChild() == VF.getChildCount() - 1) {
			finish();
		} else {
			VF.showNext();
			((ScrollView) findViewById(R.id.scrollViewConfig)).fullScroll(ScrollView.FOCUS_UP);
		}
	}
} public class Dashboard11Activity extends SherlockActivity {

	private boolean killme = false;

	App app;
	PitchRollView PRVp;
	PitchRollView PRVr;
	HeadingView headingView;

	LinearLayout boxesLayout;

	TextView TVInfo;

	Handler mHandler = new Handler();

	float myAzimuth = 0;

	private Runnable update = new Runnable() {
		@Override
		public void run() {

			app.mw.ProcessSerialData(app.loggingON);
			app.frskyProtocol.ProcessSerialData(false);

			myAzimuth = (float) (app.sensors.Heading);
			if (app.D) {
				app.mw.angy = app.sensors.Pitch;
				app.mw.angx = app.sensors.Roll;
			}

			PRVp.Set(app.mw.angy);
			PRVr.Set(app.mw.angx);
			headingView.Set(app.mw.head);

			setActiveBoxes();

			String s = "";

			s += getString(R.string.Altitude) + ":" + String.valueOf(app.mw.alt) + "\n";
			s += getString(R.string.Battery) + ":" + String.valueOf((float) (app.mw.bytevbat / 10.0)) + "\n";
			s += getString(R.string.Satellites) + ":" + String.valueOf(app.mw.GPS_numSat) + "\n";
			s += getString(R.string.GPS_speed) + ":" + String.valueOf(app.mw.GPS_speed) + "\n";
			s += getString(R.string.CycleTime) + ":" + String.valueOf(app.mw.cycleTime) + "\n";
			TVInfo.setText(s);

			app.Frequentjobs();

			app.mw.SendRequest(app.MainRequestMethod);
			if (!killme)
				mHandler.postDelayed(update, app.RefreshRate);

			if (app.D)
				Log.d(app.TAG, "loop " + this.getClass().getName());

		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dashboard12);

		app = (App) getApplication();

		PRVp = (PitchRollView) findViewById(R.id.PitchView);
		PRVp.arrow = true;
		PRVp.init();

		PRVr = (PitchRollView) findViewById(R.id.RollView);

		TVInfo = (TextView) findViewById(R.id.textViewInfoD1);

		headingView = (HeadingView) findViewById(R.id.headingView1);

		setVolumeControlStream(AudioManager.STREAM_MUSIC);

		getSupportActionBar().setTitle(getString(R.string.Dashboard1));

		getSupportActionBar().hide();

	}

	Button boxes[];

	void createBoxes() {
		boxes = new Button[app.mw.BoxNames.length];

		boxesLayout = (LinearLayout) findViewById(R.id.LinearLayoutBoxes);

		for (int i = 0; i < app.mw.BoxNames.length; i++) {
			boxes[i] = new Button(getApplicationContext());
			boxes[i].setText(app.mw.BoxNames[i]);
			// boxes[i].setBackgroundResource(R.drawable.button_0);

		}

		for (int i = 0; i < app.mw.BoxNames.length; i++) {
			boxesLayout.addView(boxes[i]);
		}

	}

	void setActiveBoxes() {
		for (int i = 0; i < app.mw.BoxNames.length; i++) {
			if (app.mw.ActiveModes[i]) {
				boxes[i].setBackgroundResource(R.drawable.button_0);
			} else {
				boxes[i].setBackgroundResource(R.drawable.button_01);
			}

		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		killme = true;
		mHandler.removeCallbacks(update);
		// app.sensors.stopMagACC();
	}

	@Override
	protected void onResume() {
		super.onResume();
		app.ForceLanguage();
		killme = false;
		mHandler.postDelayed(update, app.RefreshRate);
		app.Say(getString(R.string.Dashboard1));
		// app.sensors.startMagACC();

		createBoxes();

	}

} public class Dashboard3Activity extends SherlockFragmentActivity {
	private boolean killme = false;

	MapHelperClass mapHelperClass;

	Random random = new Random(); // for test

	App app;
	Handler mHandler = new Handler();

	HorizonView horizonView;
	AltitudeView altitudeView;
	HeadingView headingView;
	VarioView varioView;

	TextView TextViewd31;
	TextView TextViewd32;
	TextView TextViewd33;
	TextView TextViewd34;
	TextView TextViewStatus;

	ProgressBar ProgressBarTx;
	ProgressBar ProgressBarRx;

	long timer1 = 0;
	boolean MoveMap = true;
	private long centerStep = 0;

	private Runnable update = new Runnable() {
		@Override
		public void run() {

			if (timer1 < System.currentTimeMillis()) {
				app.mw.ProcessSerialData(app.loggingON);
				app.frskyProtocol.ProcessSerialData(false);

				if (app.D) {
					app.mw.GPS_latitude += random.nextInt(200) - 50;// simulation
					app.mw.GPS_longitude += random.nextInt(100) - 50;// simulation
					app.mw.GPS_fix = 1;
					app.mw.head++;
				}

				String state = "";
				for (int i = 0; i < app.mw.CHECKBOXITEMS; i++) {
					if (app.mw.ActiveModes[i]) {
						state += " " + app.mw.BoxNames[i];
					}
				}

				TextViewd31.setText(String.valueOf(app.mw.GPS_numSat));
				if (app.mw.GPS_update % 2 == 0) {
					TextViewd31.append("*");
				}
				TextViewd32.setText(String.valueOf(app.mw.bytevbat / 10f) + "V");

				TextViewd33.setText(String.valueOf(app.mw.GPS_distanceToHome) + "m");
				TextViewd34.setText(String.valueOf(app.mw.pMeterSum) + "/" + String.valueOf(app.mw.intPowerTrigger) + "(" + String.valueOf(Functions.map(app.mw.pMeterSum, 1, app.mw.intPowerTrigger, 100, 0)) + "%)");
				TextViewStatus.setText(state);

				if (app.frskyProtocol.RxRSSI > 0 || app.frskyProtocol.TxRSSI > 0) {
					ProgressBarRx.setVisibility(View.VISIBLE);
					ProgressBarTx.setVisibility(View.VISIBLE);
					ProgressBarRx.setProgress(app.frskyProtocol.RxRSSI);
					ProgressBarTx.setProgress(app.frskyProtocol.TxRSSI);
				} else {
					ProgressBarRx.setVisibility(View.GONE);
					ProgressBarTx.setVisibility(View.GONE);
				}
				app.Frequentjobs();
				app.mw.SendRequest(app.MainRequestMethod);

				timer1 = System.currentTimeMillis() + app.RefreshRate;

			}

			// ///////////////////////

			LatLng copterPositionLatLng = new LatLng(app.mw.GPS_latitude / Math.pow(10, 7), app.mw.GPS_longitude / Math.pow(10, 7));
			mapHelperClass.SetCopterLocation(copterPositionLatLng, app.mw.head, app.mw.alt);
			mapHelperClass.DrawFlightPath(copterPositionLatLng);
			mapHelperClass.PositionHoldMarker.setPosition(new LatLng(app.mw.Waypoints[16].Lat / Math.pow(10, 7), app.mw.Waypoints[16].Lon / Math.pow(10, 7)));
			mapHelperClass.HomeMarker.setPosition(new LatLng(app.mw.Waypoints[0].Lat / Math.pow(10, 7), app.mw.Waypoints[0].Lon / Math.pow(10, 7)));

			// Map centering
			if (MoveMap && centerStep < System.currentTimeMillis()) {
				if (app.mw.GPS_fix == 1) {
					mapHelperClass.map.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(copterPositionLatLng, app.MapZoomLevel, 0, app.mw.head)));
				} else {
					mapHelperClass.map.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(app.sensors.PhoneLatitude, app.sensors.PhoneLongitude), app.MapZoomLevel, 0, 0)));
				}
				centerStep = System.currentTimeMillis() + app.MapCenterPeriod * 1000;
			}

			int a = 1; // used for reverce roll in artificial horyzon
			if (app.ReverseRoll) {
				a = -1;
			}
			horizonView.Set(-app.mw.angx * a, -app.mw.angy * 1.5f);
			altitudeView.Set(app.mw.alt * 10);
			headingView.Set(app.mw.head);
			varioView.Set(app.mw.vario * 0.6f);
			// ///////////////////////

			if (!killme)
				mHandler.postDelayed(update, 50);

		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		app = (App) getApplication();
		app.ForceLanguage();
	
		setContentView(R.layout.dashboard3_layout);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		getSupportActionBar().hide();

		mapHelperClass = new MapHelperClass(((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap(), 5);

		horizonView = (HorizonView) findViewById(R.id.horizonView1);
		varioView = (VarioView) findViewById(R.id.varioView1);
		headingView = (HeadingView) findViewById(R.id.headingView1);
		altitudeView = (AltitudeView) findViewById(R.id.altitudeView1);

		TextViewd31 = (TextView) findViewById(R.id.TextViewd31);
		TextViewd32 = (TextView) findViewById(R.id.TextViewd32);
		TextViewd33 = (TextView) findViewById(R.id.TextViewd33);
		TextViewd34 = (TextView) findViewById(R.id.TextViewd34);
		TextViewStatus = (TextView) findViewById(R.id.textViewStatus);

		ProgressBarTx = (ProgressBar) findViewById(R.id.progressBarTx);
		ProgressBarRx = (ProgressBar) findViewById(R.id.progressBarRx);

		ProgressBarRx.setMax(110);
		ProgressBarTx.setMax(110);

		mapHelperClass.map.setOnCameraChangeListener(new OnCameraChangeListener() {
			@Override
			public void onCameraChange(CameraPosition position) {
				if (app.mw.GPS_fix == 1)
					app.MapZoomLevel = (int) position.zoom;
			}
		});
		setVolumeControlStream(AudioManager.STREAM_MUSIC);
	}

	@Override
	protected void onResume() {
		super.onResume();
		app.ForceLanguage();
		app.Say(getString(R.string.Dashboard3));
		killme = false;

		if (Sec.VerifyDeveloperID(Sec.GetDeviceID(getApplicationContext()), Sec.TestersIDs) || Sec.Verify(getApplicationContext(), "D..3")) {
			mHandler.postDelayed(update, app.RefreshRate);
		} else {
			AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);

			dlgAlert.setTitle(getString(R.string.Locked));
			dlgAlert.setMessage(getString(R.string.DoYouWantToUnlock));

			// dlgAlert.setPositiveButton(getString(R.string.Yes), null);
			dlgAlert.setCancelable(false);
			dlgAlert.setPositiveButton(getString(R.string.Yes), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					try {
						Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.ezio.ez_gui_unlocker");
						startActivity(LaunchIntent);
					} catch (Exception e) {
						Intent goToMarket = null;
						goToMarket = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.ezio.ez_gui_unlocker"));
						startActivity(goToMarket);
					}
					finish();
				}
			});
			dlgAlert.setNegativeButton(getString(R.string.No), new OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});

			dlgAlert.create().show();
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		mHandler.removeCallbacks(null);
		killme = true;
		app.SaveSettings(true);
	}

} public class FrskyActivity extends SherlockActivity {

	private boolean killme = false;

	App app;
	Handler mHandler = new Handler();

	TextView TV;
	TextView TVSmall;

	ProgressBar pbTx;
	ProgressBar pbRx;
	TextView TxdBTV;
	TextView RxdBTV;

	private Runnable update = new Runnable() {
		@Override
		public void run() {

			app.mw.ProcessSerialData(app.loggingON);

			app.Frequentjobs();

			app.mw.SendRequest(app.MainRequestMethod);

			app.frskyProtocol.ProcessSerialData(false);

			pbRx.setProgress(app.frskyProtocol.RxRSSI);
			pbTx.setProgress(app.frskyProtocol.TxRSSI);

			RxdBTV.setText(String.valueOf(app.frskyProtocol.RxRSSI) + "dBc");
			TxdBTV.setText(String.valueOf(app.frskyProtocol.TxRSSI) + "dBc");

			TV.setText("A1=" + String.valueOf(app.frskyProtocol.Analog1) + " A2=" + String.valueOf(app.frskyProtocol.Analog2) + " RxRSSI=" + String.valueOf(app.frskyProtocol.RxRSSI) + " TxRSSI=" + String.valueOf(app.frskyProtocol.TxRSSI));

			TV.setText("");
			log("A1=" + String.valueOf((float) app.frskyProtocol.Analog1 * 0.052f) + " A2=" + String.valueOf(app.frskyProtocol.Analog2) + " " + "HubErr=" + String.valueOf(app.frskyProtocol.frskyHubProtocol.hubErrors));
			// log("Altitude="
			// + String.valueOf(app.frsky.frskyHubProtocol.Altitude));
			// log("Heading=" +
			// String.valueOf(app.frsky.frskyHubProtocol.Heading));
			// log("AccX=" + String.valueOf(app.frsky.frskyHubProtocol.Acc_X /
			// 10));
			// log("AccY=" + String.valueOf(app.frsky.frskyHubProtocol.Acc_Y /
			// 10));
			// log("AccZ=" + String.valueOf(app.frsky.frskyHubProtocol.Acc_Z /
			// 10));
			// log("Time=" + String.valueOf(app.frsky.FHour) + ":"
			// + String.valueOf(app.frsky.FMinute) + ":"
			// + String.valueOf(app.frsky.FSecond));

			TVSmall.setText(app.frskyProtocol.frskyHubProtocol.whatFramesToString());

			// log(app.frsky.lastHubFrameslog);

			if (!killme)
				mHandler.postDelayed(update, app.RefreshRate);

			Log.d(app.TAG, "loop " + this.getClass().getName());

		}
	};

	void log(String t) {
		TV.append(t + "\n");
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		app = (App) getApplication();
		setContentView(R.layout.frsky_layout);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

		// bt = new BT(getApplicationContext());
		// frsky = new FrskyProtocol(bt);

		TV = (TextView) findViewById(R.id.textViewFrsky);
		TVSmall = (TextView) findViewById(R.id.textViewFrskySmall);

		pbRx = (ProgressBar) findViewById(R.id.progressBarFrskyRxRSSI);
		pbTx = (ProgressBar) findViewById(R.id.progressBarFrskyTxRSSI);

		RxdBTV = (TextView) findViewById(R.id.textViewRxdB);
		TxdBTV = (TextView) findViewById(R.id.textViewTxdB);

		pbRx.setMax(110);
		pbTx.setMax(110);

	}

	@Override
	protected void onResume() {
		super.onResume();

		// app.BTFrsky.Connect(app.MacAddressFrsky);

		app.ForceLanguage();
		app.Say(getString(R.string.Frsky));
		killme = false;
		mHandler.postDelayed(update, app.RefreshRate);

	}

	@Override
	protected void onPause() {
		super.onPause();
		mHandler.removeCallbacks(null);
		killme = true;

		// bt.CloseSocket();
	}

} public class MOCK_GPS_Service extends Service {

	private boolean killme = false;
	Random random = new Random(); // for test

	App app;
	Handler mHandler = new Handler();

	private Runnable update = new Runnable() {
		@Override
		public void run() {

			Log.d("aaaService", "Service running...");
			if (app.D) {
				app.mw.GPS_latitude += random.nextInt(200) - 50;// for
				// simulation
				app.mw.GPS_longitude += random.nextInt(100) - 50;// for
				// simulation
				app.mw.GPS_fix = 1;
				// app.mw.alt++;

				app.mw.head++;
			}

			app.mw.ProcessSerialData(app.loggingON);
			app.frskyProtocol.ProcessSerialData(false);

			app.sensors.setMOCKLocation(app.mw.GPS_latitude / Math.pow(10, 7), app.mw.GPS_longitude / Math.pow(10, 7), app.mw.alt, app.mw.head, app.mw.GPS_speed);

			app.Frequentjobs();

			// app.mw.SendRequest();
			// app.mw.SendRequestMSP_RAW_GPS();
			app.mw.SendRequest(app.MainRequestMethod);
			if (!killme) {
				mHandler.postDelayed(update, 1000);
			} else {
				app.sensors.ClearMOCKLocation();
			}

		}
	};

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		app = (App) getApplication();
		if (app.sensors.isMockEnabled()) {
			app.sensors.initMOCKLocation();
			mHandler.postDelayed(update, app.RefreshRate);
		} else {
			stopSelf();
		}

	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		mHandler.removeCallbacks(null);
		killme = true;

		super.onDestroy();

	}

} public class Functions {

	
	public static long ConcatInt(int x, int y) {
		return (int) ((x * Math.pow(10, numberOfDigits(y))) + y);
	}

	public static float map(float x, float in_min, float in_max, float out_min, float out_max) {
		return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
	}

	public static int map(int x, int in_min, int in_max, int out_min, int out_max) {
		return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
	}

	public static int numberOfDigits(long n) {
		// Guessing 4 digit numbers will be more probable.
		// They are set in the first branch.
		if (n < 10000L) { // from 1 to 4
			if (n < 100L) { // 1 or 2
				if (n < 10L) {
					return 1;
				} else {
					return 2;
				}
			} else { // 3 or 4
				if (n < 1000L) {
					return 3;
				} else {
					return 4;
				}
			}
		} else { // from 5 a 20 (albeit longs can't have more than 18 or 19)
			if (n < 1000000000000L) { // from 5 to 12
				if (n < 100000000L) { // from 5 to 8
					if (n < 1000000L) { // 5 or 6
						if (n < 100000L) {
							return 5;
						} else {
							return 6;
						}
					} else { // 7 u 8
						if (n < 10000000L) {
							return 7;
						} else {
							return 8;
						}
					}
				} else { // from 9 to 12
					if (n < 10000000000L) { // 9 or 10
						if (n < 1000000000L) {
							return 9;
						} else {
							return 10;
						}
					} else { // 11 or 12
						if (n < 100000000000L) {
							return 11;
						} else {
							return 12;
						}
					}
				}
			} else { // from 13 to ... (18 or 20)
				if (n < 10000000000000000L) { // from 13 to 16
					if (n < 100000000000000L) { // 13 or 14
						if (n < 10000000000000L) {
							return 13;
						} else {
							return 14;
						}
					} else { // 15 or 16
						if (n < 1000000000000000L) {
							return 15;
						} else {
							return 16;
						}
					}
				} else { // from 17 to ...¿20?
					if (n < 1000000000000000000L) { // 17 or 18
						if (n < 100000000000000000L) {
							return 17;
						} else {
							return 18;
						}
					} else { // 19? Can it be?
						// 10000000000000000000L is'nt a valid long.
						return 19;
					}
				}
			}
		}
	}
} public class LogActivity extends SherlockActivity {

	App app;
	Handler mHandler = new Handler();

	private Runnable update = new Runnable() {
		@Override
		public void run() {

			app.mw.ProcessSerialData(app.loggingON);

			app.Frequentjobs();
			app.mw.SendRequest(app.MainRequestMethod);
			mHandler.postDelayed(update, app.RefreshRate);

			Log.d(app.TAG, "loop " + this.getClass().getName());

		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.logging_layout);

		app = (App) getApplication();
		app.Say(getString(R.string.Logging));

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		mHandler.removeCallbacks(update);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		app.ForceLanguage();
	}

	public void ConvertToKMLOnClick(View v) {
		try {
			Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.eziosoft.multiwii.kmlconverter");
			startActivity(LaunchIntent);
		} catch (Exception e) {
			Intent goToMarket = null;
			goToMarket = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.eziosoft.multiwii.kmlconverter"));
			startActivity(goToMarket);
		}
	}

	public void StartLoggingOnClick(View v) {
		app.mw.CreateNewLogFile();
		app.loggingON = true;
		mHandler.postDelayed(update, app.RefreshRate);

		Toast.makeText(getApplicationContext(), getString(R.string.Loggingstarted), Toast.LENGTH_LONG).show();

	}

	public void StopLoggingOnClick(View v) {
		app.loggingON = false;
		app.mw.CloseLoggingFile();

		Toast.makeText(getApplicationContext(), getString(R.string.Loggingstopedandsaved), Toast.LENGTH_LONG).show();

	}

} public class MotorsActivity extends SherlockActivity {
	
	private boolean		killme		= false;

	App					app;
	Handler				mHandler	= new Handler();

	final Random		myRandom	= new Random();

	ProgressBar			M1;
	ProgressBar			M2;
	ProgressBar			M3;
	ProgressBar			M4;
	ProgressBar			M5;
	ProgressBar			M6;
	ProgressBar			M7;
	ProgressBar			M8;

	ProgressBar			S1;
	ProgressBar			S2;
	ProgressBar			S3;
	ProgressBar			S4;
	ProgressBar			S5;
	ProgressBar			S6;
	ProgressBar			S7;
	ProgressBar			S8;

	TextView			TVM1;
	TextView			TVM2;
	TextView			TVM3;
	TextView			TVM4;
	TextView			TVM5;
	TextView			TVM6;
	TextView			TVM7;
	TextView			TVM8;

	private Runnable	update		= new Runnable() {
										@Override
										public void run() {

											app.mw.ProcessSerialData(app.loggingON);

											if (app.mw.mot[0] >= 1000)
												M1.setProgress((int) app.mw.mot[0] - 1000);
											if (app.mw.mot[1] >= 1000)
												M2.setProgress((int) app.mw.mot[1] - 1000);
											if (app.mw.mot[2] >= 1000)
												M3.setProgress((int) app.mw.mot[2] - 1000);
											if (app.mw.mot[3] >= 1000)
												M4.setProgress((int) app.mw.mot[3] - 1000);
											if (app.mw.mot[4] >= 1000)
												M5.setProgress((int) app.mw.mot[4] - 1000);
											if (app.mw.mot[5] >= 100)
												M6.setProgress((int) app.mw.mot[5] - 1000);
											if (app.mw.mot[6] >= 1000)
												M7.setProgress((int) app.mw.mot[6] - 1000);
											if (app.mw.mot[7] >= 1000)
												M8.setProgress((int) app.mw.mot[7] - 1000);

											TVM1.setText(Integer.toString((int) app.mw.mot[0]));
											TVM2.setText(Integer.toString((int) app.mw.mot[1]));
											TVM3.setText(Integer.toString((int) app.mw.mot[2]));
											TVM4.setText(Integer.toString((int) app.mw.mot[3]));
											TVM5.setText(Integer.toString((int) app.mw.mot[4]));
											TVM6.setText(Integer.toString((int) app.mw.mot[5]));
											TVM7.setText(Integer.toString((int) app.mw.mot[6]));
											TVM8.setText(Integer.toString((int) app.mw.mot[7]));

											if (app.mw.servo[0] >= 1000)
												S1.setProgress((int) app.mw.servo[0] - 1000);
											if (app.mw.servo[1] >= 1000)
												S2.setProgress((int) app.mw.servo[1] - 1000);
											if (app.mw.servo[2] >= 1000)
												S3.setProgress((int) app.mw.servo[2] - 1000);
											if (app.mw.servo[3] >= 1000)
												S4.setProgress((int) app.mw.servo[3] - 1000);
											if (app.mw.servo[4] >= 1000)
												S5.setProgress((int) app.mw.servo[4] - 1000);
											if (app.mw.servo[5] >= 1000)
												S6.setProgress((int) app.mw.servo[5] - 1000);
											if (app.mw.servo[6] >= 1000)
												S7.setProgress((int) app.mw.servo[6] - 1000);
											if (app.mw.servo[7] >= 1000)
												S8.setProgress((int) app.mw.servo[7] - 1000);

											app.Frequentjobs();

											app.mw.SendRequest(app.MainRequestMethod);
											if (!killme)mHandler.postDelayed(update, app.RefreshRate);

											if(app.D)		Log.d(app.TAG, "loop "+this.getClass().getName());
										}
									};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		app = (App) getApplication();
		setContentView(R.layout.motor_layout);
		getSupportActionBar().setTitle(getString(R.string.Motors));
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

		// motorsView = (MotorView) findViewById(R.id.motorView1);
		// motorsView.SetMotorsCount(4, true);

		M1 = (ProgressBar) findViewById(R.id.progressBar1);
		M2 = (ProgressBar) findViewById(R.id.progressBar2);
		M3 = (ProgressBar) findViewById(R.id.progressBar3);
		M4 = (ProgressBar) findViewById(R.id.progressBar4);
		M5 = (ProgressBar) findViewById(R.id.progressBar5);
		M6 = (ProgressBar) findViewById(R.id.progressBar6);
		M7 = (ProgressBar) findViewById(R.id.progressBar7);
		M8 = (ProgressBar) findViewById(R.id.progressBar8);

		TVM1 = (TextView) findViewById(R.id.textViewM1);
		TVM2 = (TextView) findViewById(R.id.textViewM2);
		TVM3 = (TextView) findViewById(R.id.textViewM3);
		TVM4 = (TextView) findViewById(R.id.textViewM4);
		TVM5 = (TextView) findViewById(R.id.textViewM5);
		TVM6 = (TextView) findViewById(R.id.textViewM6);
		TVM7 = (TextView) findViewById(R.id.textViewM7);
		TVM8 = (TextView) findViewById(R.id.textViewM8);

		S1 = (ProgressBar) findViewById(R.id.ProgressBar9);
		S2 = (ProgressBar) findViewById(R.id.ProgressBar10);
		S3 = (ProgressBar) findViewById(R.id.ProgressBar11);
		S4 = (ProgressBar) findViewById(R.id.ProgressBar12);
		S5 = (ProgressBar) findViewById(R.id.ProgressBar13);
		S6 = (ProgressBar) findViewById(R.id.ProgressBar14);
		S7 = (ProgressBar) findViewById(R.id.ProgressBar15);
		S8 = (ProgressBar) findViewById(R.id.ProgressBar16);

		M1.setMax(1000);
		M2.setMax(1000);
		M3.setMax(1000);
		M4.setMax(1000);
		M5.setMax(1000);
		M6.setMax(1000);
		M7.setMax(1000);
		M8.setMax(1000);

		S1.setMax(1000);
		S2.setMax(1000);
		S3.setMax(1000);
		S4.setMax(1000);
		S5.setMax(1000);
		S6.setMax(1000);
		S7.setMax(1000);
		S8.setMax(1000);

	}

	@Override
	protected void onPause() {
		super.onPause();
		mHandler.removeCallbacks(null);
		killme=true;
	}

	@Override
	protected void onResume() {
		super.onResume();
		app.ForceLanguage();
		app.Say(getString(R.string.Motors));
		killme=false;
		mHandler.postDelayed(update, app.RefreshRate);

	}

} public class CalibrationActivity extends SherlockActivity {
	App app;
	Handler mHandler = new Handler();
	private boolean killme = false;

	Button ButtonRxBIND;

	private Runnable update = new Runnable() {
		@Override
		public void run() {

			app.mw.ProcessSerialData(app.loggingON);

			app.frskyProtocol.ProcessSerialData(false);
			app.Frequentjobs();

			app.mw.SendRequest(app.MainRequestMethod);
			if (!killme)
				mHandler.postDelayed(update, app.RefreshRate);

		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.calibration_layout);

		app = (App) getApplication();

		getSupportActionBar().setTitle(getString(R.string.Calibration));

	}

	@Override
	protected void onPause() {
		super.onPause();
		mHandler.removeCallbacks(null);
		killme = true;

	}

	@Override
	protected void onResume() {
		super.onResume();
		app.ForceLanguage();
		killme = false;
		mHandler.postDelayed(update, app.RefreshRate);
		app.Say(getString(R.string.Calibration));
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		Read();

		if (!app.mw.multi_Capability.RXBind) {
			((Button) findViewById(R.id.buttonRXBIND)).setEnabled(false);
		}

		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
	}

	private void Read() {
		app.mw.SendRequestMSP_MISC();

		try {
			Thread.sleep(600);
		} catch (InterruptedException e) {

			e.printStackTrace();
		}

		app.mw.ProcessSerialData(false);

	}

	public void ResetOnClick(View v) {

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(getString(R.string.ResetALLnotonlyPIDparamstodefault)).setCancelable(false).setPositiveButton(getString(R.string.Yes), new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int id) {

				app.mw.SendRequestMSP_RESET_CONF();
				Toast.makeText(getApplicationContext(), getString(R.string.Done), Toast.LENGTH_LONG).show();

			}
		}).setNegativeButton(getString(R.string.No), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.cancel();
			}
		});
		AlertDialog alert = builder.create();
		alert.show();

	}

	public void MSP_MISC_CONFreadOnClick(View v) {
		Read();
	}

	public void MagCalibrationOnClick(View v) {

		if (app.mw.communication.Connected) {
			app.mw.SendRequestMSP_MAG_CALIBRATION();
			ShowCountDown(getString(R.string.MagCalibration), getString(R.string.MagCalibrationDialogInfo), 30);
		}

	}

	public void AccCalibrationOnClick(View v) {
		if (app.mw.communication.Connected) {
			app.mw.SendRequestMSP_ACC_CALIBRATION();
			ShowCountDown(getString(R.string.AccCalibration), getString(R.string.ACCcalibrationDialogInfo), 10);
		}

	}

	public void RXBINDOnClick(View v) {
		app.mw.SendRequestMSP_BIND();
	}

	public void SetSerialBoudRateOnClick(View v) {
		app.mw.SendRequestMSP_ENABLE_FRSKY();
		app.mw.SendRequestMSP_SET_SERIAL_BAUDRATE(9600);
		app.commMW.Close();
	}

	private void ShowCountDown(String title, final String message, int time_s) {
		final ProgressDialog alertDialog = new ProgressDialog(this);
		alertDialog.setTitle(title);
		alertDialog.setMessage(message + "(" + "30" + "s)");
		alertDialog.setMax(time_s);
		alertDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

		alertDialog.show(); //

		new CountDownTimer(time_s * 1000, 1000) {
			@Override
			public void onTick(long millisUntilFinished) {
				alertDialog.setMessage(message + "(" + String.valueOf((millisUntilFinished / 1000) + "s)"));
				alertDialog.setProgress((int) (millisUntilFinished / 1000));
			}

			@Override
			public void onFinish() {
				alertDialog.dismiss();
			}
		}.start();
	}

} public class MiscActivity extends SherlockActivity {

	private boolean killme = false;

	EditText ETPowerTrigger;
	EditText ETMinThrottle;
	EditText ETMaxThrottle;
	EditText ETMinCommand;
	EditText ETFailSafeThrottle;
	EditText ETArmCount;
	EditText ETLifeTime;
	EditText ETMagDeclination;
	EditText ETVBatScale;
	EditText ETLevelWarn1;
	EditText ETLevelWarn2;
	EditText ETLevelCrit;
	EditText ETBatteryVoltage;

	App app;
	Handler mHandler = new Handler();

	private Runnable update = new Runnable() {
		@Override
		public void run() {

			app.mw.ProcessSerialData(app.loggingON);

			app.frskyProtocol.ProcessSerialData(false);
			app.Frequentjobs();

			ETBatteryVoltage.setText(String.valueOf((float) (app.mw.bytevbat / 10.0)));

			app.mw.SendRequest(app.MainRequestMethod);
			if (!killme)
				mHandler.postDelayed(update, app.RefreshRate);

		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		app = (App) getApplication();
		app.ForceLanguage();
		
		setContentView(R.layout.misc_layout);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		setVolumeControlStream(AudioManager.STREAM_MUSIC);

		ETPowerTrigger = (EditText) findViewById(R.id.EditTextPowerTrigger);
		ETMinThrottle = (EditText) findViewById(R.id.EditTextMinThrottle);
		ETMaxThrottle = (EditText) findViewById(R.id.EditTextMaxThrottle);
		ETMinCommand = (EditText) findViewById(R.id.EditTextMinCommand);
		ETFailSafeThrottle = (EditText) findViewById(R.id.EditTextFailsafeThrottle);
		ETArmCount = (EditText) findViewById(R.id.EditTextArmedCount);
		ETLifeTime = (EditText) findViewById(R.id.EditTextLiveTime);
		ETMagDeclination = (EditText) findViewById(R.id.EditTextMagneticDeclination);
		ETVBatScale = (EditText) findViewById(R.id.EditTextVBatScale);
		ETLevelWarn1 = (EditText) findViewById(R.id.EditTextBatLevelWarn1);
		ETLevelWarn2 = (EditText) findViewById(R.id.EditTextBatLevelWarn2);
		ETLevelCrit = (EditText) findViewById(R.id.editTextBatLevelCrit);
		ETBatteryVoltage = (EditText) findViewById(R.id.EditTextBatteryVoltage);

		getSupportActionBar().setTitle(getString(R.string.Misc));

		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

	}

	@Override
	protected void onResume() {
		super.onResume();
		app.ForceLanguage();
		app.Say(getString(R.string.Misc));
		killme = false;
		mHandler.postDelayed(update, app.RefreshRate);

		if (app.mw.multi_Capability.ByMis) {
			((TextView) findViewById(R.id.TextViewMinCommand)).setText(getString(R.string.FSRTHaltitude));
			((EditText) findViewById(R.id.EditTextMinCommand)).setEnabled(true);
		}

		ReadAndDisplay();

		switch (app.mw.confSetting) {
		case 0:
			((RadioButton) findViewById(R.id.radioSelectSetting0)).setChecked(true);
			break;
		case 1:
			((RadioButton) findViewById(R.id.radioSelectSetting1)).setChecked(true);
			break;
		case 2:
			((RadioButton) findViewById(R.id.radioSelectSetting2)).setChecked(true);
			break;
		}

		if (Sec.VerifyDeveloperID(Sec.GetDeviceID(getApplicationContext()), Sec.TestersIDs) || Sec.Verify(getApplicationContext(), "D..3")) {
			mHandler.postDelayed(update, app.RefreshRate);
		} else {
			AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);

			dlgAlert.setTitle(getString(R.string.Locked));
			dlgAlert.setMessage(getString(R.string.DoYouWantToUnlock));

			// dlgAlert.setPositiveButton(getString(R.string.Yes), null);
			dlgAlert.setCancelable(false);
			dlgAlert.setPositiveButton(getString(R.string.Yes), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					try {
						Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.ezio.ez_gui_unlocker");
						startActivity(LaunchIntent);
					} catch (Exception e) {
						Intent goToMarket = null;
						goToMarket = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.ezio.ez_gui_unlocker"));
						startActivity(goToMarket);
					}
					finish();
				}
			});
			dlgAlert.setNegativeButton(getString(R.string.No), new OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});

			dlgAlert.create().show();
		}

	}

	@Override
	protected void onPause() {
		super.onPause();
		mHandler.removeCallbacks(null);
		killme = true;
	}

	private void ReadAndDisplay() {
		app.mw.SendRequestMSP_MISC();

		try {
			Thread.sleep(300);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		app.mw.ProcessSerialData(app.loggingON);

		ETPowerTrigger.setText(String.valueOf(app.mw.intPowerTrigger));
		ETMinThrottle.setText(String.valueOf(app.mw.minthrottle));
		ETMaxThrottle.setText(String.valueOf(app.mw.maxthrottle));
		ETMinCommand.setText(String.valueOf(app.mw.mincommand));
		ETFailSafeThrottle.setText(String.valueOf(app.mw.failsafe_throttle));
		ETArmCount.setText(String.valueOf(app.mw.ArmCount));
		ETLifeTime.setText(String.valueOf(app.mw.LifeTime));
		ETMagDeclination.setText(String.valueOf(app.mw.mag_decliniation));
		ETVBatScale.setText(String.valueOf(app.mw.vbatscale));
		ETLevelWarn1.setText(String.valueOf(app.mw.vbatlevel_warn1));
		ETLevelWarn2.setText(String.valueOf(app.mw.vbatlevel_warn2));
		ETLevelCrit.setText(String.valueOf(app.mw.vbatlevel_crit));

	}

	private void Save() {
		int powerTrigger = Integer.parseInt(ETPowerTrigger.getText().toString());
		int MinThrottle = Integer.parseInt(ETMinThrottle.getText().toString());
		int MaxThrottle = Integer.parseInt(ETMaxThrottle.getText().toString());
		int MinCommand = Integer.parseInt(ETMinCommand.getText().toString());
		int FailSafhrottle = Integer.parseInt(ETFailSafeThrottle.getText().toString());
		// int ArmCount = Integer.parseInt(ETArmCount.getText().toString());
		// int Lifime = Integer.parseInt(ETLifeTime.getText().toString());
		float MagDeclination = Float.parseFloat(ETMagDeclination.getText().toString());
		int VBatScale = Integer.parseInt(ETVBatScale.getText().toString());
		float LevelWarn1 = Float.parseFloat(ETLevelWarn1.getText().toString());
		float LevelWarn2 = Float.parseFloat(ETLevelWarn2.getText().toString());
		float LevelCrit = Float.parseFloat(ETLevelCrit.getText().toString());

		app.mw.SendRequestMSP_SET_MISC(powerTrigger, MinThrottle, MaxThrottle, MinCommand, FailSafhrottle, MagDeclination, VBatScale, LevelWarn1, LevelWarn2, LevelCrit);

		Toast.makeText(getApplicationContext(), getString(R.string.Done), Toast.LENGTH_SHORT).show();
	}

	public void SelectSettingSetOnClick(View v) {

		int a = 0;
		if (((RadioButton) findViewById(R.id.radioSelectSetting0)).isChecked())
			a = 0;
		if (((RadioButton) findViewById(R.id.radioSelectSetting1)).isChecked())
			a = 1;
		if (((RadioButton) findViewById(R.id.radioSelectSetting2)).isChecked())
			a = 2;

		app.mw.SendRequestMSP_SELECT_SETTING(a);
		Toast.makeText(getApplicationContext(), getString(R.string.Done), Toast.LENGTH_SHORT).show();

	}

	public void GetDeclinationOnClick(View v) {
		final NumberFormat format = NumberFormat.getNumberInstance();
		format.setMinimumFractionDigits(1);
		format.setMaximumFractionDigits(1);
		format.setGroupingUsed(false);
		ETMagDeclination.setText(format.format(app.sensors.Declination));
	}

	public void ShowCustomDialogOnClick(View vv) {
		CustomInputDialog.ShowCustomDialogOnClick(vv, this);
	}

	// /////menu////////
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getSupportMenuInflater();
		inflater.inflate(R.menu.menu_misc, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.MenuRead) {
			ReadAndDisplay();
			return true;
		}

		if (item.getItemId() == R.id.MenuSave) {

			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(getString(R.string.Continue)).setCancelable(false).setPositiveButton(getString(R.string.Yes), new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog, int id) {

					Save();
					Toast.makeText(getApplicationContext(), getString(R.string.Done), Toast.LENGTH_SHORT).show();

				}
			}).setNegativeButton(getString(R.string.No), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
				}
			});
			AlertDialog alert = builder.create();
			alert.show();

			return true;
		}

		if (item.getItemId() == R.id.MenuSharePID) {
			// ShareIt();
			return true;
		}

		return false;
	}

	// ///menu end//////

} public class RawDataActivity extends Activity {
	private boolean killme = false;

	App app;
	Handler mHandler = new Handler();

	TextView TVData;
	TextView TVMWInfo;
	View FlashUpdate;

	private Runnable update = new Runnable() {
		@Override
		public void run() {

			app.mw.ProcessSerialData(app.loggingON);

			app.frskyProtocol.ProcessSerialData(false);
			app.Frequentjobs();

			displayData();

			if (FlashUpdate.getVisibility() == View.VISIBLE) {
				FlashUpdate.setVisibility(View.INVISIBLE);
			} else {
				FlashUpdate.setVisibility(View.VISIBLE);
			}

			app.mw.SendRequest(app.MainRequestMethod);
			if (!killme)
				mHandler.postDelayed(update, app.RefreshRate);

			if (app.D)
				Log.d(app.TAG, "loop " + this.getClass().getName());
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		app = (App) getApplication();
		app.ForceLanguage();

		setContentView(R.layout.raw_data_layout);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		TVData = (TextView) findViewById(R.id.textViewData);
		TVMWInfo = (TextView) findViewById(R.id.textViewMWInfo);
		FlashUpdate = (View) findViewById(R.id.UpdateFlash);

	}

	@Override
	protected void onResume() {
		super.onResume();
		app.ForceLanguage();
		app.Say(getString(R.string.RawData));
		killme = false;
		mHandler.postDelayed(update, app.RefreshRate);

		if (app.MacAddress.equals("")) {
			TVData.setText(getString(R.string.MacNotSet));
		} else {
			TVData.setText("");
			if (!app.commMW.Connected)
				TVData.setText(getString(R.string.InfoNotConnected));
		}

	}

	@Override
	protected void onPause() {
		super.onPause();
		mHandler.removeCallbacks(null);
		killme = true;
	}

	private void displayData() {

		String t = new String();
		if (app.mw.BaroPresent == 1)
			t += "BARO ";
		if (app.mw.GPSPresent == 1)
			t += "GPS ";
		if (app.mw.SonarPresent == 1)
			t += "SONAR ";
		if (app.mw.MagPresent == 1)
			t += "MAG ";
		if (app.mw.AccPresent == 1)
			t += "ACC";
		TVMWInfo.setText("MW Version:" + String.valueOf(app.mw.version) + "\n" + "MultiType:" + app.mw.MultiTypeName[app.mw.multiType] + "\n" + "CycleTime:" + String.valueOf(app.mw.cycleTime) + "\n" + "i2cError:" + String.valueOf(app.mw.i2cError) + "\n" + t + "\n MSP_ver:" + String.valueOf(app.mw.MSPversion));

		TVData.setText("");

		log("DeviceID", Sec.GetDeviceID(getApplicationContext()));
		log("EZ-Gui Protocol", app.mw.EZGUIProtocol);
		log("BytesSent", app.mw.communication.BytesSent);
		log("BytesRecieved", app.mw.communication.BytesRecieved);

		log("gx", app.mw.gx);
		log("gy", app.mw.gy);
		log("gz", app.mw.gz);

		log("ax", app.mw.ax);
		log("ay", app.mw.ay);
		log("az", app.mw.az);

		log("magx", app.mw.magx);
		log("magy", app.mw.magy);
		log("magz", app.mw.magz);

		log("alt", app.mw.alt);
		log("vario", app.mw.vario);
		log("head", app.mw.head);

		log("angx", app.mw.angx);
		log("angy", app.mw.angy);
		log("bytevbat", app.mw.bytevbat);
		log("pMeterSum", app.mw.pMeterSum);
		log("amperage", app.mw.amperage);

		// log("nunchukPresent", app.mw.nunchukPresent);
		log("AccPresent", app.mw.AccPresent);
		log("BaroPresent", app.mw.BaroPresent);
		log("MagnetoPresent", app.mw.MagPresent);
		log("GPSPresent", app.mw.GPSPresent);
		log("SonarPresent", app.mw.SonarPresent);

		log("present", app.mw.SensorPresent);
		log("mode", app.mw.mode);
		// log("levelMode", app.mw.levelMode);

		log("byteThrottle_EXPO", app.mw.byteThrottle_EXPO);
		log("byteThrottle_MID", app.mw.byteThrottle_MID);

		log("GPS_fix", app.mw.GPS_fix);
		log("GPS_numSat", app.mw.GPS_numSat);
		log("GPS_update", app.mw.GPS_update);
		log("GPS_directionToHome", app.mw.GPS_directionToHome);
		log("GPS_distanceToHome", app.mw.GPS_distanceToHome);
		log("GPS_altitude", app.mw.GPS_altitude);
		log("GPS_speed", app.mw.GPS_speed);
		log("GPS_latitude", app.mw.GPS_latitude);
		log("GPS_longitude", app.mw.GPS_longitude);
		log("GPS_ground_course", app.mw.GPS_ground_course);

		log("rcThrottle", app.mw.rcThrottle);
		log("rcYaw", app.mw.rcYaw);
		log("rcPitch", app.mw.rcPitch);
		log("rcRoll", app.mw.rcRoll);
		log("rcAUX1", app.mw.rcAUX1);
		log("rcAUX2", app.mw.rcAUX2);
		log("rcAUX3", app.mw.rcAUX3);
		log("rcAUX4", app.mw.rcAUX4);

		log("debug1", app.mw.debug1);
		log("debug2", app.mw.debug2);
		log("debug3", app.mw.debug3);
		log("debug4", app.mw.debug4);

		log("MSP_DEBUGMSG", app.mw.DebugMSG);

		for (int i = 0; i < app.mw.mot.length; i++) {
			log("Motor" + String.valueOf(i + 1), app.mw.mot[i]);
		}

		for (int i = 0; i < app.mw.PIDITEMS; i++) {
			log("P=" + String.valueOf(app.mw.byteP[i]) + " I=" + String.valueOf(app.mw.byteI[i]) + " D", app.mw.byteD[i]);
		}

		log("confSetting", app.mw.confSetting);
		log("multiCapability", app.mw.multiCapability);

		log("rssi", app.mw.rssi);

		log("declination", app.mw.mag_decliniation);

		for (String s : app.mw.BoxNames) {
			log("buttonCheckboxLabel", s);

		}

		int Si = 0;
		for (ServoConfClass s : app.mw.ServoConf) {
			log("Servo" + String.valueOf(Si) + "MIN", s.Min);
			log("Servo" + String.valueOf(Si) + "MID", s.MidPoint);
			log("Servo" + String.valueOf(Si) + "MAX", s.Max);
			log("Servo" + String.valueOf(Si) + "Rate", s.Rate);
			Si++;
		}

		log("---", 0);

		String app_ver = "";
		int app_ver_code = 0;
		try {
			app_ver = getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName;
			app_ver_code = getPackageManager().getPackageInfo(this.getPackageName(), 0).versionCode;
		} catch (NameNotFoundException e1) {
			e1.printStackTrace();
		}

		log("App version", getString(R.string.app_name) + " " + app_ver + "." + String.valueOf(app_ver_code));

		log("versionMisMatch", app.mw.versionMisMatch);
		// log("1G", app.mw._1G);
		log("CHECKBOXITEMS", app.mw.CHECKBOXITEMS);
		log("PIDITEMS", app.mw.PIDITEMS);
		log("timer1", app.mw.timer1);
		log("timer2", app.mw.timer2);
		log("dataFlow", app.mw.DataFlow);

		log("AppStartCounter", String.valueOf(app.AppStartCounter));
		log("DonationButtonPressed", String.valueOf(app.DonateButtonPressed));
		log("Andorid version", String.valueOf(Build.VERSION.SDK_INT));
		log("CommunicationTypeMW", app.CommunicationTypeMW);
		log("comm Connected", String.valueOf(app.commMW.Connected));
		log("commFrsky Connected", String.valueOf(app.commFrsky.Connected));

	}

	private void log(String co, int wartosc) {
		TVData.append(co + "=" + String.valueOf(wartosc) + "\n");
	}

	private void log(String co, float wartosc) {
		TVData.append(co + "=" + String.valueOf(wartosc) + "\n");
	}

	private void log(String co, String wartosc) {
		TVData.append(co + "=" + (wartosc) + "\n");
	}

	void ShareIt() {
		Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
		sharingIntent.setType("text/plain");
		String shareBody = TVMWInfo.getText().toString() + "\n\n" + TVData.getText().toString();

		sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "MultiWii Raw Data");
		sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);

		startActivity(Intent.createChooser(sharingIntent, "Share via"));
	}

	public void SendOnClick(View v) {
		ShareIt();
	}

	public void EnableDebugOnClick(View v) {
		app.D = true;
		// for testing
		if (app.D) {
			Toast.makeText(getApplicationContext(), "Debug version", Toast.LENGTH_LONG).show();
			app.Say("Debug version");
			app.mw.GPS_longitude = 24414160;
			app.mw.GPS_latitude = 488300660;
			app.mw.Waypoints[0].Lat = 488300660;
			app.mw.Waypoints[0].Lon = 24414160;
			app.mw.GPS_fix = 1;
			app.mw.GPS_numSat = 4;
		}
	}

	public void SerialMonitorOnClick(View v) {
		killme = true;
		mHandler.removeCallbacksAndMessages(null);
		startActivity(new Intent(getApplicationContext(), vt100Activity.class));
	}

} public class MapWaypointsActivity extends SherlockFragmentActivity {

	MapHelperClass mapHelperClass;
	Menu ActionBarMenu;
	ActionMode mMode;

	float CircleRadius = 0;
	int CirclePointsCount = 10;

	boolean ShowWaypointControls = false;

	boolean MoveMap = true;
	private long centerStep = 0;

	int CurrentWaypointNumber = -1;
	final int distanceWhenWPReached = 5;
	float distanceToNextWaypoint = 9999;

	boolean killme = false;

	Random random = new Random(); // for test

	App app;
	Handler mHandler = new Handler();

	TextView TVInfoMap;

	NumberFormat format = new DecimalFormat("0.00");

	private Runnable update = new Runnable() {
		@Override
		public void run() {
			app.mw.ProcessSerialData(app.loggingON);
			app.frskyProtocol.ProcessSerialData(false);

			// simulation
			if (app.D) {
				app.mw.GPS_latitude += random.nextInt(50) - 1;
				app.mw.GPS_longitude += random.nextInt(50) - 1;
				app.mw.GPS_fix = 1;
				app.mw.head++;
				if (app.mw.head > 360)
					app.mw.head = 0;
			}

			LatLng copterPositionLatLng = new LatLng(app.mw.GPS_latitude / Math.pow(10, 7), app.mw.GPS_longitude / Math.pow(10, 7));

			// Map centering
			if (MoveMap && centerStep < System.currentTimeMillis()) {
				if (app.mw.GPS_fix == 1) {
					mapHelperClass.map.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(copterPositionLatLng, app.MapZoomLevel, 0, app.mw.head)));
				} else {
					mapHelperClass.map.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(app.sensors.PhoneLatitude, app.sensors.PhoneLongitude), app.MapZoomLevel, 0, 0)));
				}
				centerStep = System.currentTimeMillis() + app.MapCenterPeriod * 1000;
			}

			if (distanceToNextWaypoint < 5)
				SetNextWaypoint(false);

			mapHelperClass.SetCopterLocation(copterPositionLatLng, app.mw.head, app.mw.alt);
			mapHelperClass.DrawFlightPath(copterPositionLatLng);
			mapHelperClass.PositionHoldMarker.setPosition(app.mw.Waypoints[16].Lat_Lng());
			mapHelperClass.HomeMarker.setPosition(app.mw.Waypoints[0].Lat_Lng());

			if (CurrentWaypointNumber >= 0) {
				distanceToNextWaypoint = (float) MapHelperClass.gps2m(copterPositionLatLng.latitude, copterPositionLatLng.longitude, mapHelperClass.markers.get(CurrentWaypointNumber).getPosition().latitude, mapHelperClass.markers.get(CurrentWaypointNumber).getPosition().longitude);
			}

			DisplayInfo();
			app.Frequentjobs();

			app.mw.SendRequest(app.MainRequestMethod);
			if (!killme)
				mHandler.postDelayed(update, app.RefreshRate);

		}
	};

	void DisplayInfo() {
		TVInfoMap.setText("");
		if (CurrentWaypointNumber >= 0) {
			TVInfoMap.setText("WP#" + String.valueOf(CurrentWaypointNumber + 1) + "\n");
			TVInfoMap.append("To WP#" + String.valueOf(CurrentWaypointNumber + 1) + ":" + format.format(distanceToNextWaypoint) + "m" + "\n");
		}
		TVInfoMap.append("Alt:" + format.format(app.mw.alt) + "m" + "\n");
		TVInfoMap.append("Bat:" + format.format(app.mw.bytevbat / 10.0) + "V" + "\n");
		TVInfoMap.append("Power:" + String.valueOf(app.mw.pMeterSum) + "/" + String.valueOf(app.mw.intPowerTrigger) + "\n");
		TVInfoMap.append("Sat:" + String.valueOf(app.mw.GPS_numSat) + "\n");
		TVInfoMap.append("Head:" + String.valueOf((int) app.mw.head) + "°" + "\n");
		TVInfoMap.append("Speed:" + String.valueOf((int) app.mw.GPS_speed) + "m/s" + "\n");
		TVInfoMap.append("ToHome:" + format.format(app.mw.GPS_distanceToHome) + "m" + "\n");
		TVInfoMap.append("DirToHome:" + String.valueOf((int) app.mw.GPS_directionToHome + "°"));

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext()) != ConnectionResult.SUCCESS) {
			Toast.makeText(this, getString(R.string.GooglePlayServiecesError), Toast.LENGTH_LONG).show();
			finish();
		}

		app = (App) getApplication();
		app.ForceLanguage();
		

		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		setContentView(R.layout.waypoints_map_layout);
		getSupportActionBar().setDisplayShowTitleEnabled(false);
		getSupportActionBar().setDisplayShowHomeEnabled(false);

		TVInfoMap = (TextView) findViewById(R.id.textViewInfoMap);

		mapHelperClass = new MapHelperClass(((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap(), distanceWhenWPReached);

		mapHelperClass.map.setOnCameraChangeListener(new OnCameraChangeListener() {
			@Override
			public void onCameraChange(CameraPosition position) {
				if (app.mw.GPS_fix == 1)
					app.MapZoomLevel = (int) position.zoom;
			}
		});

		mapHelperClass.map.setOnMarkerDragListener(new OnMarkerDragListener() {
			@Override
			public void onMarkerDragStart(Marker marker) {
			}

			@Override
			public void onMarkerDragEnd(Marker marker) {
				mapHelperClass.RedrawLines();
			}

			@Override
			public void onMarkerDrag(Marker marker) {
				mapHelperClass.RedrawLines();
			}
		});

		mapHelperClass.map.setOnMapLongClickListener(new OnMapLongClickListener() {
			@Override
			public void onMapLongClick(LatLng point) {

				Toast.makeText(getApplicationContext(), String.valueOf(point.latitude * 1e6), Toast.LENGTH_SHORT).show();

				Intent i = new Intent(getApplicationContext(), WaypointActivity.class);
				i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				i.putExtra("LAT", (long) (point.latitude * 1e6));
				i.putExtra("LON", (long) (point.longitude * 1e6));
				startActivity(i);
			}
		});

		mapHelperClass.map.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(0, 0), mapHelperClass.map.getMinZoomLevel(), 0, 0)));

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			ShowWaypointControls = extras.getBoolean("WAYPOINT");
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		app.ForceLanguage();
		app.Say(getString(R.string.Map));
		killme = false;
		mHandler.postDelayed(update, app.RefreshRate);
		setVolumeControlStream(AudioManager.STREAM_MUSIC);

	}

	@Override
	protected void onPause() {
		super.onPause();
		mHandler.removeCallbacks(null);
		killme = true;

		if (app.mw.GPS_fix == 1) {
			app.MapZoomLevel = mapHelperClass.map.getCameraPosition().zoom;
			app.SaveSettings(true);
		}
	}

	void SetNextWaypoint(boolean previous) {

		if (previous) {
			CurrentWaypointNumber--;
		} else {
			CurrentWaypointNumber++;
		}

		if (CurrentWaypointNumber >= mapHelperClass.markers.size() || CurrentWaypointNumber <= -1) {
			CurrentWaypointNumber = -1;
			mapHelperClass.CurrentWPCircle.setCenter(new LatLng(0, 0));
			return;
		}

		int alt = 0;
		app.mw.SendRequestMSP_SET_WP(new Waypoint(16, (int) (mapHelperClass.markers.get(CurrentWaypointNumber).getPosition().latitude * 1e6 * 10), (int) (mapHelperClass.markers.get(CurrentWaypointNumber).getPosition().longitude * 1e6 * 10), alt, 0, 0, 0));
		app.soundManager.playSound(2);
		mapHelperClass.CurrentWPCircle.setCenter(mapHelperClass.markers.get(CurrentWaypointNumber).getPosition());

		for (Marker m : mapHelperClass.markers) {
			m.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
		}

		mapHelperClass.markers.get(CurrentWaypointNumber).setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));

		if (app.D) {
			app.mw.Waypoints[16].Lat = (int) (mapHelperClass.markers.get(CurrentWaypointNumber).getPosition().latitude * 1e6 * 10);
			app.mw.Waypoints[16].Lon = (int) (mapHelperClass.markers.get(CurrentWaypointNumber).getPosition().longitude * 1e6 * 10);
		}
	}

	void AddCircleDialogShow() {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setTitle(getString(R.string.Radius));
		alert.setMessage(getString(R.string.EnterRadius));

		// Set an EditText view to get user input
		final EditText input = new EditText(this);
		input.setText("10");
		alert.setView(input);

		alert.setPositiveButton(getString(R.string.OK), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				String value = input.getText().toString();
				CircleRadius = Float.parseFloat(value.replace(",", "."));
				AddCircle(CircleRadius, CirclePointsCount);
				mMode = startActionMode(new CircleOptionsActionModeMenu());
			}
		});

		alert.setNegativeButton(getString(R.string.Cancel), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// Canceled.
			}
		});

		alert.show();
	}

	void AddCircle(double diameterInMeters, int howManyPoints) {
		float x = 360 / howManyPoints;
		double azimuth = 0;
		for (int i = 0; i < howManyPoints; i++) {
			mapHelperClass.AddMarker((MapHelperClass.GetPointGivenRadialAndDistance(mapHelperClass.markers.get(0).getPosition(), diameterInMeters, azimuth)));
			azimuth += x;
		}

	}

	// /////menu////////
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getSupportMenuInflater();
		ActionBarMenu = menu;
		inflater.inflate(R.menu.menu_map_waypoints, menu);

		if (!ShowWaypointControls) {
			menu.findItem(R.id.MenuMapWaypointAddWP).setVisible(false);
			menu.findItem(R.id.MenuMapWaypointClean).setVisible(false);
			menu.findItem(R.id.MenuMapWaypointNextWP).setVisible(false);
			menu.findItem(R.id.MenuMapWaypointPrevWP).setVisible(false);
		}

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.MenuMapWaypointAddWP) {
			mapHelperClass.AddMarker();

			if (mapHelperClass.markers.size() == 1) {
				mMode = startActionMode(new AddPatternActionModeMenu());
			} else {
				if (mMode != null) {
					mMode.finish();
				}
			}
			return true;
		}

		if (item.getItemId() == R.id.MenuMapWaypointPrevWP) {
			SetNextWaypoint(true);
			return true;
		}

		if (item.getItemId() == R.id.MenuMapWaypointNextWP) {
			SetNextWaypoint(false);
			return true;
		}

		if (item.getItemId() == R.id.MenuMapWaypointClean) {
			mapHelperClass.CleanMap();
			CurrentWaypointNumber = -1;
			return true;
		}

		if (item.getItemId() == R.id.MenuMapWaypointMoveMap) {
			MoveMap = !MoveMap;
			item.setChecked(MoveMap);
			if (MoveMap)
				Toast.makeText(getApplicationContext(), getString(R.string.MoveMapEnable), Toast.LENGTH_SHORT).show();
			else
				Toast.makeText(getApplicationContext(), getString(R.string.MoveMapDissable), Toast.LENGTH_SHORT).show();
			return true;
		}

		return false;
	}

	// ///menu end//////

	private final class AddPatternActionModeMenu implements ActionMode.Callback {
		@Override
		public boolean onCreateActionMode(ActionMode mode, Menu menu) {

			menu.add(Menu.NONE, 1, Menu.NONE, getString(R.string.AddCirclePath))
			// .setIcon(isLight ? R.drawable.ic_compose_inverse :
			// R.drawable.ic_compose)
			.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

			return true;
		}

		@Override
		public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
			return false;
		}

		@Override
		public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
			if (item.getItemId() == 1) {
				AddCircleDialogShow();
				mode.finish();
			}
			return true;

		}

		@Override
		public void onDestroyActionMode(ActionMode mode) {

		}
	}

	private final class CircleOptionsActionModeMenu implements ActionMode.Callback {
		@Override
		public boolean onCreateActionMode(ActionMode mode, Menu menu) {

			menu.add(Menu.NONE, 1, Menu.NONE, getString(R.string.Bigger)).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
			menu.add(Menu.NONE, 2, Menu.NONE, getString(R.string.Smaller)).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
			menu.add(Menu.NONE, 3, Menu.NONE, getString(R.string.AddWP)).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
			menu.add(Menu.NONE, 4, Menu.NONE, getString(R.string.RemWP)).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

			return true;
		}

		@Override
		public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
			return false;
		}

		@Override
		public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
			if (item.getItemId() == 1) {
				CircleRadius += 1f;
				while (mapHelperClass.markers.size() > 1) {
					mapHelperClass.RemoveMarker(mapHelperClass.markers.size() - 1);
				}

				AddCircle(CircleRadius, CirclePointsCount);
				mapHelperClass.RedrawLines();
			}

			if (item.getItemId() == 2) {
				CircleRadius -= 1f;
				while (mapHelperClass.markers.size() > 1) {
					mapHelperClass.RemoveMarker(mapHelperClass.markers.size() - 1);
				}

				AddCircle(CircleRadius, CirclePointsCount);
				mapHelperClass.RedrawLines();
			}

			if (item.getItemId() == 3) {
				CirclePointsCount += 1;
				while (mapHelperClass.markers.size() > 1) {
					mapHelperClass.RemoveMarker(mapHelperClass.markers.size() - 1);
				}

				AddCircle(CircleRadius, CirclePointsCount);
				mapHelperClass.RedrawLines();
			}

			if (item.getItemId() == 4) {
				CirclePointsCount -= 1;
				while (mapHelperClass.markers.size() > 1) {
					mapHelperClass.RemoveMarker(mapHelperClass.markers.size() - 1);
				}

				AddCircle(CircleRadius, CirclePointsCount);
				mapHelperClass.RedrawLines();
			}

			return true;

		}

		@Override
		public void onDestroyActionMode(ActionMode mode) {
			mapHelperClass.RemoveMarker(0);
			mapHelperClass.RedrawLines();

		}
	}

}
import nav.NavActivity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.ActionBarSherlock;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;
import com.ezio.multiwii.R;
import com.ezio.multiwii.about.AboutActivity;
import com.ezio.multiwii.advanced.AdvancedActivity;
import com.ezio.multiwii.app.App;
import com.ezio.multiwii.aux_pid.AUXActivity;
import com.ezio.multiwii.aux_pid.PIDActivity;
import com.ezio.multiwii.aux_pid.ServosActivity;
import com.ezio.multiwii.config.ConfigActivity;
import com.ezio.multiwii.dashboard.Dashboard11Activity;
import com.ezio.multiwii.dashboard.Dashboard2Activity;
import com.ezio.multiwii.dashboard.dashboard3.Dashboard3Activity;
import com.ezio.multiwii.frsky.FrskyActivity;
import com.ezio.multiwii.gps.GPSActivity;
import com.ezio.multiwii.gps.MOCK_GPS_Service;
import com.ezio.multiwii.graph.GraphsActivity;
import com.ezio.multiwii.helpers.Functions;
import com.ezio.multiwii.log.LogActivity;
import com.ezio.multiwii.motors.MotorsActivity;
import com.ezio.multiwii.other.CalibrationActivity;
import com.ezio.multiwii.other.MiscActivity;
import com.ezio.multiwii.radio.RadioActivity;
import com.ezio.multiwii.raw.RawDataActivity;
import com.ezio.multiwii.waypoints.MapWaypointsActivity;
import com.ezio.sec.Sec;
import com.viewpagerindicator.TitlePageIndicator;
import communication.BT_New;
/*  MultiWii EZ-GUI
    Copyright (C) <2012>  Bartosz Szczygiel (eziosoft)

    This program 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.

    This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.ezio.multiwii.Main;



public class MainMultiWiiActivity extends SherlockActivity {
	private boolean killme = false;
	private App app;
	TextView TVInfo;
	ActionBarSherlock actionBar;
	MyPagerAdapter adapter;

	private final Handler mHandler = new Handler();
	private final Handler mHandler1 = new Handler() {
		// BinaryFileAccess file = new
		// BinaryFileAccess("/MultiWiiLogs/dump1.txt", true);

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case BT_New.MESSAGE_STATE_CHANGE:
				Log.i("ccc", "MESSAGE_STATE_CHANGE: " + msg.arg1);

				switch (msg.arg1) {
				case BT_New.STATE_CONNECTED:
					// setStatus("Connected");
					break;
				case BT_New.STATE_CONNECTING:
					setStatus(getString(R.string.Connecting));
					break;
				case BT_New.STATE_NONE:
					break;
				}

				break;
			case BT_New.MESSAGE_WRITE:
				break;
			case BT_New.MESSAGE_READ:
				// byte[] readBuf = (byte[]) msg.obj;
				// String readMessage = new String(readBuf, 0, msg.arg1);
				// //file.WriteBytes(readBuf);

				break;
			case BT_New.MESSAGE_DEVICE_NAME:
				String deviceName = msg.getData().getString(BT_New.DEVICE_NAME);
				setStatus(getString(R.string.Connected) + "->" + deviceName);
				Log.d("ccc", "Device Name=" + deviceName);
				break;
			case BT_New.MESSAGE_TOAST:
				Log.i("ccc", "MESSAGE_TOAST:" + msg.getData().getString(BT_New.TOAST));
				Toast.makeText(getApplicationContext(), msg.getData().getString(BT_New.TOAST), Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};

	private final void setStatus(String message) {
		Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();

	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		app = (App) getApplication();

		app.commMW.SetHandler(mHandler1);
		app.commFrsky.SetHandler(mHandler1);

		Log.d("aaa", "MAIN ON CREATE");
		requestWindowFeature(Window.FEATURE_PROGRESS);

		super.onCreate(savedInstanceState);
		setContentView(R.layout.multiwii_main_layout3);

		ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
		adapter = new MyPagerAdapter(this);

		adapter.SetTitles(new String[] { getString(R.string.page1), getString(R.string.page2), getString(R.string.page3) });
		final LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		adapter.AddView(inflater.inflate(R.layout.multiwii_main_layout3_1, (ViewGroup) null, false));
		adapter.AddView(inflater.inflate(R.layout.multiwii_main_layout3_2, (ViewGroup) null, false));
		adapter.AddView(inflater.inflate(R.layout.multiwii_main_layout3_3, (ViewGroup) null, false));

		TVInfo = (TextView) adapter.views.get(0).findViewById(R.id.textViewInfoFirstPage);

		if (!app.FrskySupport) {
			((Button) adapter.views.get(1).findViewById(R.id.buttonFrsky)).setVisibility(View.GONE);
		}

		viewPager.setAdapter(adapter);

		TitlePageIndicator titleIndicator = (TitlePageIndicator) findViewById(R.id.indicator);
		titleIndicator.setViewPager(viewPager);

		getSupportActionBar().setDisplayShowTitleEnabled(false);

		app.AppStartCounter++;
		app.SaveSettings(true);

		setVolumeControlStream(AudioManager.STREAM_MUSIC);

		if (app.AppStartCounter == 1)
			startActivity(new Intent(getApplicationContext(), ConfigActivity.class));

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

	}

	@Override
	public void onResume() {
		Log.d("aaa", "MAIN ON RESUME");
		app.ForceLanguage();
		super.onResume();

		killme = false;

		String app_ver = "";
		int app_ver_code = 0;
		try {
			app_ver = getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName;
			app_ver_code = getPackageManager().getPackageInfo(this.getPackageName(), 0).versionCode;
		} catch (NameNotFoundException e1) {
			e1.printStackTrace();
		}

		TVInfo.setText(getString(R.string.app_name) + " " + app_ver + "." + String.valueOf(app_ver_code));

		if (app.commMW.Connected || app.commFrsky.Connected) {

			try {
				mHandler.removeCallbacksAndMessages(null);
			} catch (Exception e) {

			}

			mHandler.postDelayed(update, 100);
			// Log.d(BT_old.TAG, "OnResume if connected");

		}

		if (app.ConfigHasBeenChange_DisplayRestartInfo) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(getString(R.string.PressOKToRestart)).setCancelable(false).setPositiveButton(getString(R.string.OK), new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog, int id) {
					EXIT(true);
				}
			});
			AlertDialog alert = builder.create();
			alert.show();
		}

	}

	@Override
	public void onPause() {
		killme = true;
		mHandler.removeCallbacksAndMessages(null);
		super.onPause();

	}

	public void Close() {
		try {
			mHandler.removeCallbacksAndMessages(null);
			if (app.commMW.Connected)
				app.commMW.Close();
			if (app.commFrsky.Connected)
				app.commFrsky.Close();
		}

		catch (Exception e) {

		}

	}

	public void Connect() {
		if (app.CommunicationTypeMW == App.COMMUNICATION_TYPE_BT || app.CommunicationTypeMW == App.COMMUNICATION_TYPE_BT_NEW) {
			if (!app.MacAddress.equals("")) {
				app.commMW.Connect(app.MacAddress, app.SerialPortBaudRateMW);
				app.Say(getString(R.string.menu_connect));
			} else {
				Toast.makeText(getApplicationContext(), "Wrong MAC address. Go to Config and select correct device", Toast.LENGTH_LONG).show();
			}
			try {
				mHandler.removeCallbacksAndMessages(null);
			} catch (Exception e) {
			}
		} else {
			app.commMW.Connect(app.MacAddress, app.SerialPortBaudRateMW);
			app.Say(getString(R.string.menu_connect));
		}
	}

	public void ConnectFrsky(String MacAddress) {
		// if (app.CommunicationTypeFrSky == App.COMMUNICATION_TYPE_SERIAL_FTDI)
		// {
		// app.commMW.Connect(app.MacAddressFrsky, app.SerialPortBaudRateFrSky);
		// }

		if (app.CommunicationTypeFrSky == App.COMMUNICATION_TYPE_BT || app.CommunicationTypeFrSky == App.COMMUNICATION_TYPE_BT_NEW) {
			if (!app.MacAddressFrsky.equals("")) {
				app.commFrsky.Connect(app.MacAddressFrsky, app.SerialPortBaudRateFrSky);
				app.Say(getString(R.string.Connect_frsky));
			} else {
				Toast.makeText(getApplicationContext(), "Wrong MAC address. Go to Config and select correct device", Toast.LENGTH_LONG).show();
			}
			try {
				mHandler.removeCallbacksAndMessages(null);
			} catch (Exception e) {

			}
		}
	}

	private Runnable update = new Runnable() {
		@Override
		public void run() {

			app.mw.ProcessSerialData(app.loggingON);

			app.frskyProtocol.ProcessSerialData(false);
			if (app.commFrsky.Connected)
				setSupportProgress((int) Functions.map(app.frskyProtocol.TxRSSI, 0, 110, 0, 10000));