package com.qiyou.mb.android.ui.fragments;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import android.widget.Toast; 
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.overlayutil.DrivingRouteOverlay;
import com.baidu.mapapi.overlayutil.OverlayManager;
import com.baidu.mapapi.overlayutil.PoiOverlay;
import com.baidu.mapapi.search.core.CityInfo;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.RouteLine;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.route.BikingRouteLine.BikingStep;
import com.baidu.mapapi.search.route.BikingRoutePlanOption;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRouteLine.DrivingStep;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteLine.WalkingStep;
import com.baidu.mapapi.search.route.WalkingRoutePlanOption;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.mobeta.android.dslv.DragSortListView;
import com.qiyou.mb.android.QiYouConstant;
import com.qiyou.mb.android.R;
import com.qiyou.mb.android.beans.Track;
import com.qiyou.mb.android.beans.basic.Waypoint;
import com.qiyou.mb.android.beans.basic.Waypoint_bean;
import com.qiyou.mb.android.service.QNaviSvc;
import com.qiyou.mb.android.ui.fragments.TrackingBasic_fragment.SpinnerXMLSelectedListener;
import com.qiyou.mb.android.utils.FileScan;
import com.qiyou.mb.android.utils.QSimpleAdapter;
import com.qiyou.mb.android.utils.Utils;
import com.qiyou.mb.android.utils.base.IlocationFragment;
import com.qiyou.mb.android.utils.enums.TrackType;
import com.qiyou.mb.android.utils.enums.WorkingTrackType;
import com.qiyou.mb.android.utils.enums.wpFlag;
import com.qiyou.mb.android.utils.log.QLog;

@SuppressLint("NewApi")
public class Route_fragment extends  TrackTabs_fragment  implements IlocationFragment 
   {
//	  public static final String TAG ="com.qiyou.track_fragment";
//	  public static final String dTAG ="com.qiyou";  
	@Override
	public void setFTag(){
		TAG="com.qiyou.Route_fragment";
	}
	public static String getFTag(){
		return "com.qiyou.Route_fragment";
	}
	@Override
	public String getCurrentTag(){
		
//		   //// QLog.getLogger().e(dTAG,TAG+" Track_fragment, app.currentActiveFragment: "+activity.app.currentActiveFragment);
		return "com.qiyou.Route_fragment";
		
	}
	
	public Route_fragment() {
		// TODO Auto-generated constructor stub
		workingTrackType= WorkingTrackType.ROUTE;
	}
	 
	
	 
	private ImageButton 	btnRouteStart; 
	private  ImageButton 	btnRouteWps;  
	private  ImageButton 	btnRouteTent;
	private  ImageButton    btnRouteCheck;
	private  ImageButton    btnRouteHand;
//	rt_btnTent
//	rt_btnRest
	private  ImageButton 	btnRouteRest;
	private  ImageButton 	btnRouteEnd; 
	private   Button 	btnRouteSearch; 
	private   Button 	btnRouteReset;  
	private   Button 	btnRouteSave;
    private HashMap<Integer,String> oldComments  ;   
	protected  ImageView rt_cross;
	private  TextView txtNote;
	private  EditText cityNameView ;
	private  ImageButton btnSearch;
	private EditText  rt_txt_target ;
 
		protected RoutePlanSearch mSearch = null;
		PoiSearch mPoiSearch = null; // 搜索模块，也可去掉地图模块独立使用
		
		
		private 	int geoType=-1; //0,1,2..start,wps,end
		private 	LatLng startPt=null;
		private 	LatLng endPt=null;
		private 	int custWpNumber=-1;
		private wpFlag currentWpFlag;
		private int custWpMarkNumber=0;
//		private int custTentMarkNumber=0;
		
		
//		List<LatLng> pts = new ArrayList<LatLng>();
//		private final String WAYPIONTS="路点";
		
		private TrackOverlay mGpOverlay = null;  //start,end,cust
		private RouteOverlay routeOverlay =null; // track route
//		private /*OverlayItem*/ MarkerOptions mCurItem = null;
		 
		private  MyPoiOverlay poiOverlay ;
	/*	private CopyOnWriteArrayList<Waypoint_bean> roadWbs = new CopyOnWriteArrayList<Waypoint_bean>();*/
		private ArrayList<Waypoint_bean> roadWbs = new  ArrayList<Waypoint_bean>();
//		private ArrayList<Waypoint_bean> mdWbs = new  ArrayList<Waypoint_bean>();
		private  float avSpeed=20f/3600f;//米/毫秒
		private Track gpxTrack=null; 
//		private ArrayAdapter<String> adapter;
//		private ArrayAdapter<Drawable> drableAdapter;
		private overLayItemListAdapter OverLayItemAdapter;
		private  DragSortListView lv;
//		private final String INPUT_TARGET="查询地址";
		
		private int icon_start=R.drawable.icon_st;
		private int icon_end=R.drawable.icon_en;
 
		private ListView filelv;
		private Button mbtn_import;
	    private Button mbtn_refresh; 
	    private TextView txt_importNote;
	    private List<Map<String, String>> gpxFileList ;
	    private final String exchangeTab ="导入";
	    private final String historyTab = "历史";
//		private CheckBox chck_mainRoad;
//		private boolean isAllowMainRoad=false;
		
		
 		protected  RoadOverlay gpxStartOverlay =null;
 		protected  RoadOverlay gpxEndOverlay =null;
 		
 		MarkerOptions startItem=null;
// 		Marker startMarker;
 		MarkerOptions endItem=null;
// 		Marker endMarker;
 		/*TrackOverlay*/ List<MarkerOptions> wpItems =null;
 		/*TrackOverlay*/ List<MarkerOptions> wpNumItems =null;
// 		 List<OverlayItem> wpItems =new ArrayList<OverlayItem>();
// 		 List<OverlayItem> wpNumItems =new ArrayList<OverlayItem>();
 		
	public static Route_fragment newInstance(int trackId)
	{
		
		Route_fragment f = new Route_fragment();
		Bundle args = new Bundle(); 
	    args.putInt(QiYouConstant.EXTRA_KEY_ID, trackId);
	    f.setArguments(args);
	    return f;
	}
	 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if(activity!=null &&activity.app!=null)
			activity.app.playBack=false;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) { 
		vContainer = inflater.inflate(R.layout.route_fragment, container, false);
		 activity.updateActionBarTitle(R.string.frg_route);	  
		  if (trackId<=0 && getArguments() != null) {	 
			  trackId =getArguments().getInt(QiYouConstant.EXTRA_KEY_ID); 
			 
		     } 
		   if(trackId<=0 && activity.app.isNaving && activity.app.naviTrackId>0){
					trackId=activity.app.naviTrackId; 
		   }
		   
		   initialGpxTrack();
		
		   super. onCreateView( inflater,  container, savedInstanceState);
		 
		
//		mTrack =activity.app.getRecordingTrack();
//		  vContainer = inflater.inflate(R.layout.track_fragment, container, false);
// 		  initialViews(); 
//		  initialTabhost();
//		  initialFootmark(); 
		
 	     if(chk_showChats!=null)
 			 chk_showChats.setVisibility(View.GONE);
		 if(btnCamera!=null)
			 btnCamera.setVisibility(View.GONE); 
		
//		   setWorkingTrack(); 	  
 		  
		return vContainer;
		}
	
	 @Override
	  public void onActivityCreated(Bundle savedInstanceState) {
	    super.onActivityCreated(savedInstanceState);
 
//	    myLocationOverlay.enableCompass();
//	    mMapController.setCompassMargin(100, 230);
 
	    routeInitial();
	 
	 }
	 
	 @Override
	 void getExtrArgs(){
		 
	 }
	 
	 protected void routeInitial(){
		 avSpeed=activity.app.getRAVS();
		  // QLog.getLogger().d(dTAG, " routeInitial to load track...loadFromTrack()"  );
	 		loadFromTrack( );
			getWaypointListData();
			isSilence=false;
			routeReset();
			if(!activity.app.playBack)
		    	 drawGpx();  
	 }
	 
	 @Override
		protected void initialViews(){		
			 super.initialViews();
			 initalFinderViews();
//			 chck_mainRoad=(CheckBox)vContainer.findViewById(R.id.chck_mainRoad); 
//			 chck_mainRoad.setOnCheckedChangeListener(CheckboxListener);
 		 
			 
			 
//			 GridLayout grid_top_txt =(GridLayout)vContainer.findViewById(R.id.grid_top_txt);
//			 grid_top_txt.setVisibility( View.GONE );	
			 vContainer.findViewById(R.id.grid_top_txt).setVisibility( View.GONE ); 
			 
			 localTracklist =(ListView)vContainer.findViewById(R.id.tr_list);  
			 localTracklist.setOnItemClickListener(trackListItemListener);
			 
			 LinearLayout topBtns =(LinearLayout)vContainer.findViewById(R.id.rt_ll_topButttons);
			 topBtns.setVisibility( View.VISIBLE );
			 
			 btnRouteStart=(ImageButton) vContainer.findViewById(R.id.rt_btnStart);	
			 btnRouteWps=(ImageButton) vContainer.findViewById(R.id.rt_btnWps);//
			 btnRouteEnd=(ImageButton) vContainer.findViewById(R.id.rt_btnEnd);// 
			 btnRouteTent   =(ImageButton) vContainer.findViewById(R.id.rt_btnTent);//
			 btnRouteRest   =(ImageButton) vContainer.findViewById(R.id.rt_btnRest);//
			 btnRouteCheck   =(ImageButton) vContainer.findViewById(R.id.rt_btnCheck);//
			 btnRouteHand   =(ImageButton) vContainer.findViewById(R.id.rt_btnHand);//
		 
			  
			 btnRouteSearch=(Button) vContainer.findViewById(R.id.rt_btnCalculate);	
			 btnRouteReset=(Button) vContainer.findViewById(R.id.rt_btnReset);//
			 btnRouteSave=(Button) vContainer.findViewById(R.id.rt_btnSave);//
			 btnNavi=(Button) vContainer.findViewById(R.id.rt_btnNav);//
			 
			 btnReverse=(Button) vContainer.findViewById(R.id.rt_btnReverse); 
			 btnReverse.setOnClickListener( ButtonOnClickListener);
			 btnNavi.setOnClickListener( ButtonOnClickListener);
			 btnNavi.setEnabled(trackId>0 &&!activity.app.isNaving); 
			 btnSNav=(Button) vContainer.findViewById(R.id.rt_btnSNav);//
			 btnSNav.setOnClickListener( ButtonOnClickListener);
			 btnSNav.setEnabled(trackId>0 &&!activity.app.isNaving); 
			 btnSaveScreen=(ImageButton) vContainer.findViewById(R.id.tm_btnSaveScreen); 
			 btnSearch=(ImageButton) vContainer.findViewById(R.id.rt_search);//
			 btnLocation  =(ImageButton) vContainer.findViewById(R.id.tm_btnLocaiton); 
				if(this.btnLocation!=null){ 
					btnLocation.setOnClickListener(ButtonOnClickListener);
					btnLocation.setVisibility(View.VISIBLE);
				}
				
			 btnRouteCheck.setVisibility(View.VISIBLE);
			 btnRouteHand.setVisibility(View.VISIBLE);
			 btnRouteStart.setVisibility(View.VISIBLE);
			 btnRouteWps.setVisibility(View.VISIBLE);
			 btnRouteEnd.setVisibility(View.VISIBLE);
			 btnRouteTent.setVisibility(View.VISIBLE);
			 btnRouteRest.setVisibility(View.VISIBLE);
			 
			 btnRouteStart.getBackground().setAlpha(alpha);
			 btnRouteWps.getBackground().setAlpha(alpha);
			 btnRouteEnd.getBackground().setAlpha(alpha);
			 btnRouteTent.getBackground().setAlpha(alpha);
			 btnRouteRest.getBackground().setAlpha(alpha);
			 btnRouteHand.getBackground().setAlpha(alpha);
			 btnRouteCheck.getBackground().setAlpha(alpha);
			 
			 
			 btnRouteCheck.setOnClickListener( ButtonOnClickListener);
			 btnRouteRest.setOnClickListener( ButtonOnClickListener);
			 btnRouteTent.setOnClickListener( ButtonOnClickListener);
			 btnRouteStart.setOnClickListener( ButtonOnClickListener);	
			 btnRouteWps.setOnClickListener( ButtonOnClickListener);
			 btnRouteEnd.setOnClickListener( ButtonOnClickListener);
			 btnRouteSearch.setOnClickListener( ButtonOnClickListener);	
			 btnRouteReset.setOnClickListener( ButtonOnClickListener);
			 btnRouteSave.setOnClickListener( ButtonOnClickListener);
			 btnSaveScreen.setOnClickListener( ButtonOnClickListener);	
			 btnRouteHand.setOnClickListener( ButtonOnClickListener);
			  btnSearch.setOnClickListener(  new OnClickListener() { 
					    @Override
						public void onClick(View view) {
					    	txtNote.setText(null);
					    	searchButtonProcess();
					    	}
					    }
					 ); 
			 btnNavi.setOnClickListener( new OnClickListener() { 
				    @Override
					public void onClick(View view) {
				    	startNavi(false);
				    	}
				    }
				 );
			 btnRouteSave.setEnabled(false);
//			 btnRouteSave.setVisibility(View.GONE);
//			 CrossIcon rt_cross =(CrossIcon) vContainer.findViewById(R.id.rt_cross);
//			 rt_cross.setVisibility(View.VISIBLE);
//			 
			  rt_cross =(ImageView) vContainer.findViewById(R.id.rt_cross);
			 rt_cross.setVisibility(View.VISIBLE);
//			  txtNote =(TextView) vContainer.findViewById(R.id.rt_notice);
			  
			 
			 txtNote.setVisibility(View.VISIBLE);
			 
//			 CrossIcon mi = new CrossIcon(activity);
//			 activity.getWindow().addContentView(mi,new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT)); 

			  if(!Utils.isNetworkConnected(activity)){
				  txtNote.setText(null);
					showMsg("制作路书需要链接互联网，请检查网络链接。");
			  }
			   
			  initialGpxViews();
//			  canLocationMap=true;
//			  updateUI(activity.app.lastLocation, false);
//			  locationInMap(null);
				
			 
			  
			/* wpItems =new TrackOverlay(mBaiduMap);
		 	 wpNumItems =new TrackOverlay(mBaiduMap);*/
			  
			  wpItems =new ArrayList<MarkerOptions>();
			  wpNumItems = new ArrayList<MarkerOptions>();
			  routeOverlay = new RouteOverlay(mBaiduMap);
		 }
	 
	 
	 void initalFinderViews(){
		  cityNameView  = (EditText)vContainer.findViewById(R.id.rt_txt_city);
		  cityNameView.setText(QiYouConstant.PV_LAST_CITY);
		 
		  rt_txt_target= (EditText)vContainer.findViewById(R.id.rt_txt_target);
 		  rt_txt_target.setSelectAllOnFocus(true); 
		 txtNote =(TextView) vContainer.findViewById(R.id.rt_notice);
 		 btnSearch=(ImageButton) vContainer.findViewById(R.id.rt_search);//
		 btnSearch.setOnClickListener(  new OnClickListener() { 
			    @Override
				public void onClick(View view) {
			    	txtNote.setText(null);
			    	searchButtonProcess();
			    	}
			    }
			 );
	    btnLocation  =(ImageButton) vContainer.findViewById(R.id.tm_btnLocaiton); 
		if(this.btnLocation!=null) btnLocation.setOnClickListener(ButtonOnClickListener);
	 }
	 
	/* protected  CheckBox.OnCheckedChangeListener CheckboxListener =new  CheckBox.OnCheckedChangeListener(){
		    @Override
			public void onCheckedChanged(CompoundButton buttonView,
						boolean isChecked) {
//		    	 // QLog.getLogger().d(dTAG, "gpx_checkbox checked?" +chck_mainRoad.isChecked());
		    	isAllowMainRoad =isChecked;
		        txtNote.setText(null);
		    	showMsg(isAllowMainRoad?"路线规划将优先采用机动车道，请注意避免逆行":"路线规划将优先采用非机动车道");
				 
		  }

	   };*/
	 @Override
	 protected void initViewMap(){
		   initialMapview();
			
//		   mMapView.getOverlays().clear(); 
//		   mGpOverlay = new MyOverlay(getResources().getDrawable(R.drawable.empty_photo),mMapView);	
		   mGpOverlay = new TrackOverlay(mBaiduMap);
//		   bearStartOverlay =getItemizedOverlay(R.drawable.icon_bstart);
//		   bearEndOverlay   =getItemizedOverlay(R.drawable.icon_bend);
		   
//		   mMapView.getOverlays().add(mGpOverlay); 
//		   gpxOverlay =new GraphicsOverlay(mMapView);
//		   mMapView.getOverlays().add(gpxOverlay);
//		   gpxStartOverlay =getItemizedOverlay(R.drawable.icon_bstart);
//		   gpxEndOverlay=getItemizedOverlay(R.drawable.icon_bend); 
		   //创建 弹出泡泡图层
//	        createPaopao();
	        
		   //地图点击事件处理
	        
	         initialMkSearch();
	         
	         initialPoiSearch();
	         
	         
	         
	 }
	 
	 void initialPoiSearch(){
		 
		 mPoiSearch = PoiSearch.newInstance();
	 
			mPoiSearch.setOnGetPoiSearchResultListener(
					
				new	OnGetPoiSearchResultListener(){
					
					
					public void onGetPoiResult(PoiResult result) {
						processAddress(result);
					}

					public void onGetPoiDetailResult(PoiDetailResult result) {
						if (result.error != SearchResult.ERRORNO.NO_ERROR) {
							
							showMsg("抱歉，未找到结果");
							 
						} else {
							Toast.makeText(activity, result.getName() + ": " + result.getAddress(), Toast.LENGTH_SHORT)
							.show();
							 
						}
					}
					 
				} 
					
		    ); 
		 
	 }
	 
	 void processAddress(PoiResult result ){
		 if (result == null
					|| result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
				
				showMsg( "未找到结果");
				 
				return;
			}
			if (result.error == SearchResult.ERRORNO.NO_ERROR) {
//				mBaiduMap.clear();
				if(poiOverlay==null){
					poiOverlay = new MyPoiOverlay(mBaiduMap);
				}
				mBaiduMap.setOnMarkerClickListener(poiOverlay);
				poiOverlay.setData(result);
				poiOverlay.addToMap();
				poiOverlay.zoomToSpan();
				
				showMsg( "找到 "+result.getTotalPoiNum() +"个 相关地点");
				
				return;
			}
			/*if (result.error == SearchResult.ERRORNO.AMBIGUOUS_KEYWORD) {

				// 当输入关键字在本市没有找到，但在其他城市找到时，返回包含该关键字信息的城市列表
				String strInfo = "在";
				for (CityInfo cityInfo : result.getSuggestCityList()) {
					strInfo += cityInfo.city;
					strInfo += ",";
				}
				strInfo += "找到结果";
				showMsg(strInfo);
				 
			}*/
	 }
	 
	private int directionRate = 1;
	 
	
	 void initialMkSearch(){
		 

		 // 初始化搜索模块，注册事件监听
         mSearch = RoutePlanSearch.newInstance();
        
         mSearch.setOnGetRoutePlanResultListener(

        		 new OnGetRoutePlanResultListener(){
        			 
        			 String instructions="";
		 				String exitInstruction="";
		 				String entranceInstruction;
		 				
		 				String lastDist=""; 
		 				String roadBook=""; 
		 				int index=-1; 
		 				 wpFlag flag;
		 				wpFlag lastflag = null;
		 				String lastRoadbook="";
		 				
		 				
		 				
		 				void onGetRouteResult(SearchResult result){
		 					
		 				}
		 				
		 				
		 				
		 				Boolean isCustPoint(int index){
		 					return  roadWbs.size() > 1 &&!TextUtils.isEmpty(instructions) &&( index==0 || instructions.indexOf("从起点")>0 || instructions.indexOf("方向出发")>0); 
		 				}
		 				
		 				
		 				
					@Override
					public void onGetBikingRouteResult(BikingRouteResult result) {

		 				setRouteGot(true);
							 // QLog.getLogger().d(dTAG, " Got biking result.......................................");

		 				//起点或终点有歧义，需要选择具体的城市列表或地址列表
						 if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
							 showMsg("抱歉，路径规划有点问题");
							 return;
					        }
						 if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
					            // 起终点或途经点地址有岐义，通过以下接口获取建议查询信息
					            // result.getSuggestAddrInfo()
					            return;
					        }
						 
						 if (result.error != SearchResult.ERRORNO.NO_ERROR) {
							 showMsg("很抱歉，路径规划有点问题");
							 return;
						 }
				 
		 				if(isSilence)return;
		 				
//		 				MKRoute singleRroute=res.getPlan(0).getRoute(0);
		 				RouteLine singleRroute = result.getRouteLines().get(0);
		 				 
//		 			    int sDistance=singleRroute.getDistance();
		 			    routeDistance+=singleRroute.getDistance();
		 				/*String lastDist=""; 
		 				String roadBook=""; 
		 				int index=-1; 
		 				 wpFlag flag;
		 				wpFlag lastflag = null;
		 				String lastRoadbook="";*/
		 				BikingStep step;
		 				for(int i=0;i<singleRroute.getAllStep().size()/*.getNumSteps()*/;i++){
//		 					Waypoint_bean wb = getWb(singleRroute.getAllStep().get(i)/*.getStep(i).getPoint()*/.getWayPoints());
//		 					Waypoint_bean wb = getWb()
//		 					 singleRroute.getAllStep().get(i).get
		 					 step = result.getRouteLines().get(0).getAllStep().get(i);
		 					Waypoint_bean wb = getWb(step.getWayPoints().get(0));
		 					
//		 					content= step.getInstructions()/*.getContent()*/ ;
		 					instructions =step.getInstructions();
		 					exitInstruction=step.getExitInstructions();
		 					entranceInstruction=step.getEntranceInstructions();
		 					wb.setBearing(step.getDirection()*directionRate);
//		 					 QLog.getLogger().d(dTAG, String.format(" instructions %s \n existinstruction %s | entranceInstruction %s"	, instructions,exitInstruction,entranceInstruction));
		 					
 		 					
 		 					
		 					index = exitInstruction.lastIndexOf("，");
		 					if(index==-1){
		 						index = exitInstruction.lastIndexOf(",");	
		 					}
		 					if(index>0){
		 						exitInstruction=exitInstruction.substring(index+1);
		 					}
		 					
		 					flag= exitInstruction.startsWith(wpFlag.TURNLEFT.toCHString())?wpFlag.TURNLEFT
		 							:exitInstruction.startsWith(wpFlag.TURNRIGHT.toCHString())?wpFlag.TURNRIGHT:wpFlag.NORMAL; 
		 					
		 					 // QLog.getLogger().d(dTAG, exitInstruction +", cust turn flag is:" +flag +", chinese words:" +flag.toCHString());
		 					
		 					if(lastflag!=null){
		 						wb.setTurnFlag(lastflag);
		 					}
//		 					wb.setTurnFlag(flag);
 		 					 
		 					if (isCustPoint(i)){
//		 					if(!roadWbs.isEmpty() &&!TextUtils.isEmpty(instructions) &&( i==0 || instructions.indexOf("从起点")>0) ){
		 						 
		 						 String addon =currentWpFlag==wpFlag.TENT?" 到达预设扎营住宿点"
		 								 		:currentWpFlag==wpFlag.REST?" 到达预设休息用餐点"
		 								 		:currentWpFlag==wpFlag.CHECK?" 到达打卡点"
		 								 				:"";
		 						 
		 						instructions=instructions.replace("从起点",String.format("到达【途经点%s】 \n",  custWpNumber+addon ));
//		 						wb.setTurnFlag(wpFlag.CUST);
		 						wb.setName(String.valueOf(custWpNumber));
		 						
		 						if(trackId>0 &&oldComments!=null)
		 							wb.setComment(oldComments.get(Integer.valueOf(custWpNumber)));
		 						
		 						 // QLog.getLogger().d(dTAG, TAG+ " oldComments.get(i): "+i+","+ wb.getComment());
		 						
		 						 // QLog.getLogger().d(dTAG, String.format("instructions: %s ", instructions));
		 						 // QLog.getLogger().d(dTAG, String.format("currentWpFlag: %s ", currentWpFlag));
//		 						wb.setTurnFlag(wpFlag.CUST);
		 						wb.setTurnFlag(currentWpFlag);
		 						  
		 						custGeos.add(step.getWayPoints().get(0));
		 					} 
		 					  
		 					if( instructions.indexOf(",到达终点")>0){
//		 						instructions=instructions.replace(",到达终点",String.format("到达【途经点%s】 \n",  custWpNumber+addon ));
		 						instructions=instructions.substring(0,instructions.indexOf(",到达终点"));
		 					}
		 					
		 					
 		 					index=instructions.lastIndexOf("，");	//沿星湖街骑行1.5公里,过人行道,到路口斜对面，左转进入崇文路
 		 					if(index==-1){
 		 						index=instructions.lastIndexOf(",") ;	
 		 					}
		 					
//		 					roadBook =index>1?existInstruction.substring(0,index):"";  
		 					roadBook =index>1?instructions.substring(0,index):""; 
		 					roadBook=roadBook.length()==2&&roadBook.startsWith("走")?"":roadBook;
		 					roadBook=roadBook.replace("出发", "");
		 					roadBook=roadBook.replace("行驶", "");
//		 					roadBook=roadBook.replace("靠左", "");
		 					
		 					index=exitInstruction.lastIndexOf("-");
		 				/*	String stepDist= index>1?exitInstruction.substring(index+2):""; 
		 					int dist =pareseDriveDist(stepDist); 
		 				    wb.setDistance(dist);
		 					wb.setBearDist(dist); */
		 					
		 					
 		 					 // QLog.getLogger().d(dTAG, "routeDistance is" + routeDistance);
//		 					wb.setSumDist(routeDistance);
		 					if(i>0 && index>0 &&index+1<exitInstruction.length()){
		 						lastDist=exitInstruction.substring(index+1);
		 						lastDist=String.format("前行%s",lastDist);
		 					}else{
		 						if(roadWbs.size()>0)
		 							lastDist="继续前行";
		 						else
		 							lastDist="出发";
		 					}
		 					
		 					
		 			 
		 					instructions = instructions.replaceAll(",", ",然后");//replaceFirst(",", ",然后");
		 				  
		 					lastRoadbook=routeDistance==0?"":/* roadBook*/  instructions /*String.format("\"%s%s"  ,roadBook ,lastDist )*/;
		 					
		 					wb.setRoadBook(lastRoadbook);	
//		 					wb.setComment(content);
		 					 // QLog.getLogger().d(dTAG, String.format(" roadbook is %s , turnflag is %s ",		 	 	lastRoadbook,wb.getTurnFlag().toCHString() ));
//		 					wb.setTurnFlag(wpFlag.CUST);
		 					roadWbs.add(wb);
//		 					starttime+=timestep;
		 					
//		 					custGeos.add(getLatLng(wb) ); 
		 					custGeos.addAll(step.getWayPoints());
		 					
		 					lastflag =flag!=wpFlag.NORMAL?flag:null;
		 				}
		 				 // QLog.getLogger().d(dTAG, "roadWbs。cnt "+ roadWbs.size());
					}

					@Override
					public void onGetDrivingRouteResult(DrivingRouteResult result) {  
						
		 				setRouteGot(true);
							 // QLog.getLogger().d(dTAG, " Got driving result.......................................");

		 				//起点或终点有歧义，需要选择具体的城市列表或地址列表
						 if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
							 showMsg("抱歉，路径规划有点问题");
							 return;
					        }
						 if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
					            // 起终点或途经点地址有岐义，通过以下接口获取建议查询信息
					            // result.getSuggestAddrInfo()
					            return;
					        }
						 
						 if (result.error != SearchResult.ERRORNO.NO_ERROR) {
							 showMsg("很抱歉，路径规划有点问题");
							 return;
						 }
				 
		 				if(isSilence)return;
		 				
 		 				RouteLine singleRroute = result.getRouteLines().get(0);
		 				 
 		 			    routeDistance+=singleRroute.getDistance();
		 			    
 		 				 wpFlag flag;
 		 				for(int i=0;i<singleRroute.getAllStep().size()/*.getNumSteps()*/;i++){
 
		 					DrivingStep step = result.getRouteLines().get(0).getAllStep().get(i);
		 					Waypoint_bean wb = getWb(step.getWayPoints().get(0));
		 					 
		 					instructions =step.getInstructions();
		 					exitInstruction=step.getExitInstructions();
		 					entranceInstruction=step.getEntranceInstructions();
		 					wb.setBearing(step.getDirection()*directionRate);
		 					
 		 					   QLog.getLogger().d(dTAG, String.format(" instructions %s \n existinstruction %s | entranceInstruction %s", instructions,exitInstruction,entranceInstruction));
		 					
		 					 
		 					flag= exitInstruction.startsWith(wpFlag.TURNLEFT.toCHString())?wpFlag.TURNLEFT
		 							:exitInstruction.startsWith(wpFlag.TURNRIGHT.toCHString())?wpFlag.TURNRIGHT:wpFlag.NORMAL; 
		 					if(lastflag!=null){
		 						wb.setTurnFlag(lastflag);
		 					} 
		 					if (isCustPoint(i)){
//		 					if(!roadWbs.isEmpty()&&( i==0 || /*instructions.indexOf("从起点")>0 ||*/ instructions.indexOf("方向出发")>0 ) ){
		 						
//		 						QLog.getLogger().d(dTAG, " get cust poiont...............");
 		 						
		 						 String addon =currentWpFlag==wpFlag.TENT?" 到达预设扎营住宿点"
	 								 		:currentWpFlag==wpFlag.REST?" 到达预设休息用餐点"
	 								 		:currentWpFlag==wpFlag.CHECK?" 到达打卡点"
	 								 				:"";
		 						 
	 		 					
		 						entranceInstruction/*lastRoadbook*/= String.format("到达【途经点%s】 \n",  custWpNumber+addon ) +instructions;//.substring(index+1) ;

		 						wb.setName(String.valueOf(custWpNumber));
		 						if(trackId>0 &&oldComments!=null)
		 							wb.setComment(oldComments.get(Integer.valueOf(custWpNumber)));
		 						 // QLog.getLogger().d(dTAG, TAG+ " oldComments.get(i): "+i+","+ wb.getComment());
		 						
		 						 // QLog.getLogger().d(dTAG, TAG+  instructions);
		 						 // QLog.getLogger().d(dTAG, TAG+  currentWpFlag);
		 						wb.setTurnFlag(currentWpFlag);
		 						  
		 						custGeos.add(step.getWayPoints().get(0));
		 					} 
		 					  
		 				/*	index=entranceInstruction.lastIndexOf("-");	
		 					
		 					if( instructions.indexOf(",到达终点")>0){
 		 						instructions=instructions.substring(0,instructions.indexOf(",到达终点"));
		 					}*/
		 					
		 					index =entranceInstruction.indexOf("-");
		 					if(index>0){
		 						entranceInstruction =entranceInstruction.substring(0,index); 
		 						roadBook =entranceInstruction +",然后前行" +Utils.getFormatedDistance(step.getDistance());
		 					}else
		 						roadBook =entranceInstruction;
// 		 					roadBook = entranceInstruction.replace("-", ",然后前行")/*.replaceAll(",", ",然后")*/;
 		 					
 		 					
 		 					if( roadBook.indexOf(",到达终点")>0){
//		 						instructions=instructions.replace(",到达终点",String.format("到达【途经点%s】 \n",  custWpNumber+addon ));
 		 						roadBook=roadBook.substring(0,roadBook.indexOf(",到达终点"));
		 					}
 		 					wb.setRoadBook(roadBook);
 		 					
		 					 // QLog.getLogger().d(dTAG, String.format(" roadbook is %s \n, turnflag is %s ",	roadBook,wb.getTurnFlag().toCHString() ));
  
		 					 roadWbs.add(wb);
 		 					 // QLog.getLogger().d(dTAG, "roadWbs。cnt "+ roadWbs.size());
 		 					
		 					
		 					custGeos.addAll(step.getWayPoints());
		 					lastflag =flag!=wpFlag.NORMAL?flag:null;
 		 				}
		 		/*	 
		 		 		for(Waypoint_bean wb:roadWbs){
		 					 // QLog.getLogger().d(dTAG, " road Wbs turn flag is: " +wb.getTurnFlag().toCHString() );
		 				}
		 				
		 				ArrayList<ArrayList<LatLng>> gps =singleRroute.get; 
		 				for(ArrayList<LatLng> gp:gps){
		 					custGeos.addAll(gp);
		 				}  
		 				*/
		 									
					}

					@Override
					public void onGetTransitRouteResult(TransitRouteResult arg0) {
						// TODO Auto-generated method stub
						
					}

					@Override
					public void onGetWalkingRouteResult(WalkingRouteResult result) {  //same logic with biking
						setRouteGot(true);
						 // QLog.getLogger().d(dTAG, " Got walking result.......................................");

	 				//起点或终点有歧义，需要选择具体的城市列表或地址列表
					 if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
						 showMsg("抱歉，路径规划有点问题");
						 return;
				        }
					 if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
				            // 起终点或途经点地址有岐义，通过以下接口获取建议查询信息
				            // result.getSuggestAddrInfo()
				            return;
				        }
					 
					 if (result.error != SearchResult.ERRORNO.NO_ERROR) {
						 showMsg("很抱歉，路径规划有点问题");
						 return;
					 }
			 
	 				if(isSilence)return;
	 				
//	 				MKRoute singleRroute=res.getPlan(0).getRoute(0);
	 				RouteLine singleRroute = result.getRouteLines().get(0);
	 				 
//	 			    int sDistance=singleRroute.getDistance();
	 			    routeDistance+=singleRroute.getDistance();
	 				/*String lastDist=""; 
	 				String roadBook=""; 
	 				int index=-1; 
	 				 wpFlag flag;
	 				wpFlag lastflag = null;
	 				String lastRoadbook="";*/
	 				WalkingStep step;
	 				for(int i=0;i<singleRroute.getAllStep().size()/*.getNumSteps()*/;i++){
//	 					Waypoint_bean wb = getWb(singleRroute.getAllStep().get(i)/*.getStep(i).getPoint()*/.getWayPoints());
//	 					Waypoint_bean wb = getWb()
//	 					 singleRroute.getAllStep().get(i).get
	 					 step = result.getRouteLines().get(0).getAllStep().get(i);
	 					Waypoint_bean wb = getWb(step.getWayPoints().get(0));
	 					
//	 					content= step.getInstructions()/*.getContent()*/ ;
	 					instructions =step.getInstructions();
	 					exitInstruction=step.getExitInstructions();
	 					entranceInstruction=step.getEntranceInstructions();
	 					wb.setBearing(step.getDirection()*directionRate);
	 					 // QLog.getLogger().d(dTAG, String.format(" instructions %s \n existinstruction %s | entranceInstruction %s", instructions,exitInstruction,entranceInstruction));
	 					
	 					 
	 					
//	 					 // QLog.getLogger().d(dTAG, " content is for step " + i+",  "+content);
	 					
	 					index = exitInstruction.lastIndexOf("，");
	 					if(index==-1){
	 						index = exitInstruction.lastIndexOf(",");	
	 					}
	 					if(index>0){
	 						exitInstruction=exitInstruction.substring(index+1);
	 					}
	 					
	 					flag= exitInstruction.startsWith(wpFlag.TURNLEFT.toCHString())?wpFlag.TURNLEFT
	 							:exitInstruction.startsWith(wpFlag.TURNRIGHT.toCHString())?wpFlag.TURNRIGHT:wpFlag.NORMAL; 
	 					
	 					 // QLog.getLogger().d(dTAG, exitInstruction +", cust turn flag is:" +flag +", chinese words:" +flag.toCHString());
	 					
	 					if(lastflag!=null){
	 						wb.setTurnFlag(lastflag);
	 					}
//	 					wb.setTurnFlag(flag);
//	 					 // QLog.getLogger().d(dTAG, String.format("routedistance is %s, road content is:%s",wb.getDistance(),content));
	 					if (isCustPoint(i)){
//	 					if(!roadWbs.isEmpty() &&!TextUtils.isEmpty(instructions) &&( i==0 || instructions.indexOf("从起点")>0) ){
	 						 
//	 						 String addon =currentWpFlag==wpFlag.TENT?" 到达预设扎营住宿点":currentWpFlag==wpFlag.REST?" 到达预设休息用餐点":"";
	 						
	 						 String addon =currentWpFlag==wpFlag.TENT?" 到达预设扎营住宿点"
								 		:currentWpFlag==wpFlag.REST?" 到达预设休息用餐点"
								 		:currentWpFlag==wpFlag.CHECK?" 到达打卡点"
								 				:"";
	 						 
	 						 
	 						instructions=instructions.replace("从起点",String.format("到达【途经点%s】 \n",  custWpNumber+addon ));
//	 						wb.setTurnFlag(wpFlag.CUST);
	 						wb.setName(String.valueOf(custWpNumber));
	 						
	 						if(trackId>0 &&oldComments!=null)
	 							wb.setComment(oldComments.get(Integer.valueOf(custWpNumber)));
	 						
	 						 // QLog.getLogger().d(dTAG, TAG+ " oldComments.get(i): "+i+","+ wb.getComment());
	 						
	 						 // QLog.getLogger().d(dTAG, String.format("instructions: %s ", instructions));
	 						 // QLog.getLogger().d(dTAG, String.format("currentWpFlag: %s ", currentWpFlag));
//	 						wb.setTurnFlag(wpFlag.CUST);
	 						wb.setTurnFlag(currentWpFlag);
	 						  
	 						custGeos.add(step.getWayPoints().get(0));
	 					} 
	 					  
	 					if( instructions.indexOf(",到达终点")>0){
//	 						instructions=instructions.replace(",到达终点",String.format("到达【途经点%s】 \n",  custWpNumber+addon ));
	 						instructions=instructions.substring(0,instructions.indexOf(",到达终点"));
	 					}
	 					
	 					
		 					index=instructions.lastIndexOf("，");	//沿星湖街骑行1.5公里,过人行道,到路口斜对面，左转进入崇文路
		 					if(index==-1){
		 						index=instructions.lastIndexOf(",") ;	
		 					}
	 					
//	 					roadBook =index>1?existInstruction.substring(0,index):"";  
	 					roadBook =index>1?instructions.substring(0,index):""; 
	 					roadBook=roadBook.length()==2&&roadBook.startsWith("走")?"":roadBook;
	 					roadBook=roadBook.replace("出发", "");
	 					roadBook=roadBook.replace("行驶", "");
//	 					roadBook=roadBook.replace("靠左", "");
	 					
	 					index=exitInstruction.lastIndexOf("-");
	 				/*	String stepDist= index>1?exitInstruction.substring(index+2):""; 
	 					int dist =pareseDriveDist(stepDist); 
	 				    wb.setDistance(dist);
	 					wb.setBearDist(dist); */
	 					
	 					
//	 					 // QLog.getLogger().d(dTAG, "routeDistance is" + routeDistance);
//	 					wb.setSumDist(routeDistance);
	 					if(i>0 && index>0 &&index+1<exitInstruction.length()){
	 						lastDist=exitInstruction.substring(index+1);
	 						lastDist=String.format("前行%s",lastDist);
	 					}else{
	 						if(roadWbs.size()>0)
	 							lastDist="继续前行";
	 						else
	 							lastDist="出发";
	 					}
	 					
	 					
	 			 
//	 					instructions = instructions.replaceFirst(",", ",然后");
	 					instructions = instructions.replaceAll(",", ",然后");
	 					lastRoadbook=routeDistance==0?"":/* roadBook*/  instructions /*String.format("\"%s%s"  ,roadBook ,lastDist )*/;
	 					
	 					wb.setRoadBook(lastRoadbook);	
//	 					wb.setComment(content);
	 					 // QLog.getLogger().d(dTAG, String.format(" roadbook is %s , turnflag is %s ",lastRoadbook,wb.getTurnFlag().toCHString() ));
//	 					wb.setTurnFlag(wpFlag.CUST);
	 					roadWbs.add(wb);
//	 					starttime+=timestep;
	 					
//	 					custGeos.add(getLatLng(wb) ); 
	 					custGeos.addAll(step.getWayPoints());
	 					
	 					lastflag =flag!=wpFlag.NORMAL?flag:null;
	 				}
	 				 // QLog.getLogger().d(dTAG, "roadWbs。cnt "+ roadWbs.size());
					}
        			 
        		 }  
        		 
        		 );
          
//		 poiOverlay = new MyPoiOverlay(activity, mMapView, mSearch);
	 }
	 
 
	 
	 
	  //按键点击事件
     OnClickListener clickListener = new OnClickListener(){
			public void onClick(View v) {
				//发起搜索
				SearchButtonProcess(v);
			}
     };
     
     
     int pareseDriveDist(String distStr){
    	 
    	 if(TextUtils.isEmpty(distStr))return 0;
    	 
    	 int mIndex =distStr.indexOf("米");
    	 if(mIndex>0){
    		 return Integer.parseInt(distStr.substring(0,mIndex));
    	 }
    	 int kmIndex =distStr.indexOf("公里");
    	 if(kmIndex>0){
    		 return (int) (Float.parseFloat(distStr.substring(0,kmIndex))*1000);
    	 }
    	 return 0;
    	 
    	   
     }
     
     
     void showMsg(String msg){
    	 if(isSilence)return;
    	 Toast.makeText(activity, msg, Toast.LENGTH_LONG).show();
//    	 txtNote.setText(msg);
    	 txtNote.setText(TextUtils.isEmpty(txtNote.getText())?msg:txtNote.getText()+"\n"+msg);
     }
     boolean canNavi(){
    	 return trackId>0 &&!activity.app.isNaving;
     }
     private boolean isRouteGot=false;
     private ArrayList<LatLng> custGeos =new ArrayList<LatLng>();
     private int routeDistance=0;
     private boolean isSilence=false;
     private int routeType =0;
     Handler	handler;
     
	 /**
		 * 发起路线规划搜索示例
		 * @param v
		 */
	 void SearchButtonProcess(View v) {
		 	 
			 custWpNumber=-1;
			 currentWpFlag=wpFlag.CUST;
//			 custWpMarkNumber=0;
			 isSilence=false;
			 txtNote.setText(null);
			 btnNavi.setEnabled(canNavi());
			 btnSNav.setEnabled(canNavi());
			if(!Utils.isNetworkConnected(activity)){
				showMsg("制作路书需要链接互联网，请检查网络链接。");
				return;
			}
			if(this.startPt==null || this.endPt==null ){
				showMsg("请设置路线的始起点和终点。");
				return;
			}
			 btnRouteReset.setEnabled(false);
			 btnRouteSave.setEnabled(false);
			 btnRouteSearch.setEnabled(false);
			 btnNavi.setEnabled(false);
			 btnSNav.setEnabled(false);
			 btnReverse.setEnabled(false);
//			showMsg("正努力计算路线，请稍等。。。");
			
			routeType =spRouteType.getSelectedItemPosition();
			spRouteType.setEnabled(false);
			 if(routeType==0){ //bike  							
 					showMsg( "正努力进行骑行路线规划，请稍等。。。");
				}else if(routeType==1) { //walk
 					showMsg( "正努力进行步行路线规划，请稍等。。。");
				}else if(routeType==2){//drive 							
 					showMsg( "正努力进行机动路线规划，请稍等。。。");
				} 
			custGeos.clear();
			
			routeDistance=0;
			geoType=-1;
			roadWbs.clear();
 
 			if(!wpItems/*.getOverlayOptions()*/.contains(startItem))
				wpItems/*.getOverlayOptions()*/.add(0, startItem);
			if(!wpItems/*.getOverlayOptions()*/.contains(endItem))
				wpItems/*.getOverlayOptions()*/.add(endItem);
			
			
			  handler = new Handler(){
				
				@Override
				public void handleMessage(Message msg) {
					
					//关闭ProgressDialog
//									progressDialog.dismiss(); 
					
					 //更新UI
//										 switchButtonStatus(); 
					
					  if(msg.what==0){ 
							 // QLog.getLogger().d(dTAG,"before assembly the track...............................");
						  showRoutes(false); 
						  isSilence=true;
						  btnRouteSave.setEnabled(false);
						   
//						  btnRouteSave.setVisibility(View.VISIBLE);
					}else if(msg.what==1){	
						 // QLog.getLogger().d(dTAG,"after assembly the track...............................");
						 showFootmarkData(true);
						/* for(Waypoint_bean wb1:gpxTrack.getTrackBean().getRoadWps()){
							 
							 //  // QLog.getLogger().d(dTAG,  "31 cust wp  turn flag" + wb1.getTurnFlag().toCHString());
						} */
 						 btnRouteSave.setEnabled(true);
						 btnRouteReset.setEnabled(true);
						
					}
					  spRouteType.setEnabled(true);
					  btnRouteSearch.setEnabled(true);   
					  btnReverse.setEnabled(true);
				}};
				
			
			new Thread(){ 
				@Override
				public void run() {
//					MKPlanNode stNode = new MKPlanNode();
//					MKPlanNode enNode = new MKPlanNode();
					
					 PlanNode stNode = null;
				     PlanNode enNode = null;
					
 				/*	if(isAllowMainRoad)
						mSearch.setDrivingPolicy(RoutePlanSearch.ECAR_FEE_FIRST);*/
				 
				     routeOverlay.removeFromMap();
				     Bundle bd=null;
 					 MarkerOptions mo ;
 					 	
					for(int i=0;i<wpItems/*.getOverlayOptions()*/.size()-1;i++){
						
						stNode=PlanNode.withLocation( ((MarkerOptions)wpItems/*.getOverlayOptions()*/.get(i)).getPosition());
						enNode =PlanNode.withLocation( ((MarkerOptions)wpItems/*.getOverlayOptions()*/.get(i+1)).getPosition());
						
						int j = -1;
						
 						if(i>0 && i-1<wpNumItems/*.getOverlayOptions()*/.size()) { 
								j = i -1;	
//						   mo =	(MarkerOptions)wpNumItems/*.getOverlayOptions()*/.get(i-1);
//						   bd = mo.getExtraInfo();
//							custWpNumber=Integer.valueOf(   bd.getInt(RoadOverlay.EXTR_KEY_INDEX)/*.getTitle()*/);
//							
//								if( bd.getInt(RoadOverlay.EXTR_KEY_FLAG,-10)!=-10/*wpNumItems.get(i-1).getSnippet()*/){
//									currentWpFlag = wpFlag.valueOf(bd.getInt(RoadOverlay.EXTR_KEY_FLAG));
// 							 
//									if (currentWpFlag == wpFlag.HAND){
//										Waypoint_bean wb = getWb(mo.getPosition());
//										wb.setTurnFlag(currentWpFlag);
//										wb.setName(String.valueOf(custWpNumber));
//										roadWbs.add(wb);
//										custGeos.add(mo.getPosition());
//										continue;
//									}
//								}
							
							
							} else if (i == 0 && wpNumItems.size() > 0){ //start point, to check the first cust num is hand or not
								j = i;
								
								Waypoint_bean wb = getWb(stNode.getLocation());
								wb.setTurnFlag(wpFlag.START); 
								roadWbs.add(wb);
								custGeos.add(stNode.getLocation());
								  
							} else if (i == wpItems.size()-2 && wpNumItems.size() > 0){ // check if the last 2 is the hand flag
								j = i;
								  
							}
 					
 						if (j > -1){
 							   mo =	(MarkerOptions)wpNumItems.get(j);
							   bd = mo.getExtraInfo();
								custWpNumber=Integer.valueOf(   bd.getInt(RoadOverlay.EXTR_KEY_INDEX)/*.getTitle()*/);
								
								if( bd.getInt(RoadOverlay.EXTR_KEY_FLAG,-10)!=-10/*wpNumItems.get(i-1).getSnippet()*/){
									currentWpFlag = wpFlag.valueOf(bd.getInt(RoadOverlay.EXTR_KEY_FLAG));
	 							 
									if (currentWpFlag == wpFlag.HAND){
										
										if (i == 0 && wpNumItems.size() > 0){ //start point, to check the first cust num is hand or not
										  
											Waypoint_bean wb = getWb(stNode.getLocation());
											wb.setTurnFlag(wpFlag.START); 
											roadWbs.add(wb);
											custGeos.add(stNode.getLocation());
											  
										}   
										
										
										
										Waypoint_bean wb = getWb(mo.getPosition());
										wb.setTurnFlag(currentWpFlag);
										wb.setName(String.valueOf(custWpNumber));
										wb.setRoadBook("手绘点 " +custWpNumber);
										roadWbs.add(wb);
										custGeos.add(mo.getPosition());
										
										custWpNumber=-1; 
										currentWpFlag=wpFlag.CUST;
										
										
										 if (i == wpItems.size()-2 && wpNumItems.size() > 0){ // check if the last 2 is the hand flag
											  
												Waypoint_bean wb1 = getWb(enNode.getLocation());
												wb1.setTurnFlag(wpFlag.END); 
												roadWbs.add(wb1);
												custGeos.add(enNode.getLocation());
											}
										 
										 
										continue;
									}
								}
 						}
	 						 
						
						
						
//						if(wpItems.get(i).getTitle().length()>0)continue;
				
						isRouteGot=false;
						 // QLog.getLogger().d(dTAG, String.format("from %s to %s, pt(%s,%s) to pt(%s,%s)", i,i+1,stNode.getLocation().latitude,stNode.getLocation().longitude,	enNode.getLocation().latitude,enNode.getLocation().longitude));
						
 						if(routeType==0){ //bike  							
 							mSearch.bikingSearch((new BikingRoutePlanOption()).from(stNode).to(enNode));
// 							showMsg( "正在进行骑行路线规划");
 						}else if(routeType==1) { //walk
  							mSearch.walkingSearch((new WalkingRoutePlanOption()) .from(stNode).to(enNode));
//  							showMsg( "正在进行步行路线规划");
 						}else if(routeType==2){//drive 							
 							mSearch.drivingSearch((new DrivingRoutePlanOption()) .from(stNode).to(enNode));
// 							showMsg( "正在进行机动路线规划");
 						}
 						
// 					 	Bundle bd=null;
//						if(i>0 && i-1<wpNumItems/*.getOverlayOptions()*/.size()){
//						   bd =((MarkerOptions)wpNumItems/*.getOverlayOptions()*/.get(i-1)).getExtraInfo();
//							custWpNumber=Integer.valueOf(   bd.getInt(RoadOverlay.EXTR_KEY_INDEX)/*.getTitle()*/);
//							
//							if( bd.getInt(RoadOverlay.EXTR_KEY_FLAG,-10)!=-10/*wpNumItems.get(i-1).getSnippet()*/)
//								currentWpFlag =wpFlag.valueOf(bd.getInt(RoadOverlay.EXTR_KEY_FLAG));
// 						}
						 
						
						
						int topWaiting=0;
						while(!isRouteGot){
						try {
 			 				Thread.sleep(100);
			 				topWaiting+=100;
			 				if(topWaiting>5000 ){  
			 					 break;
			 				 
			 				}
			 			  } catch (InterruptedException e) {
			 				// TODO Auto-generated catch block
			 				Utils.logStackTrace(e, TAG);
//			 				handler.sendEmptyMessage(0);
			 				
			 				}
						}
					}
				
					try {
			 				Thread.sleep(2000);
//						Thread.sleep(500); 
		 				 
		 				}
		 			  	catch (InterruptedException e) {
		 				// TODO Auto-generated catch block
		 				Utils.logStackTrace(e, TAG);
		 				 
		 				}
					assemblyTrack();
					handler.sendEmptyMessage(0);
//					assemblyTrack();
//					Message msg= Message.obtain(handler);// .obtain(handler, 1);
//					Bundle bd =new Bundle();
////					bd.putString("exportgpx", gpx);
//					msg.setData(bd);
//					handler.sendMessage(msg);
				
					handler.sendEmptyMessage(1);
			 }}.start();  
			
		
			
			/*
			stNode.pt=this.startPt;			
//			enNode.name = editEn.getText().toString();
			enNode.pt=this.endPt;
			// 实际使用中请对起点终点城市进行正确的设定
			mSearch.setDrivingPolicy(MKSearch.ECAR_DIS_FIRST);
			 
			mSearch.walkingSearch(null, stNode, null, enNode);*/
			 
			
			
			/*if (mBtnDrive.equals(v)) {
				mSearch.drivingSearch("北京", stNode, "北京", enNode);
			} else if (mBtnTransit.equals(v)) {
				mSearch.transitSearch("北京", stNode, enNode);
			} else if (mBtnWalk.equals(v)) {
				mSearch.walkingSearch("北京", stNode, "北京", enNode);
			} */
		}
		
		private void showRoutes(final boolean isLoadFromTrack){
//			searchType = 2;
//				int plans=res.getNumPlan();
//				for(int i=0;i<plans;i++){
//					int routes =res.getPlan(i).getNumRoutes();
//					for(int j=0;j<routes;j++){
//						
//					}
//				}
			
			
			if(custGeos.isEmpty() && !isLoadFromTrack){
				showMsg("无法从网络获得路线数据，请检查网络链接。");
				
				final double dist=routeDistance>0?routeDistance/1000:Utils.getDistanceFromXtoY(getWb(startItem.getPosition()).getLatitude(), getWb(startItem.getPosition()).getLongitude(),
						getWb(endItem.getPosition()).getLatitude(), getWb(endItem.getPosition()).getLongitude())/1000; 
				
				 //  // QLog.getLogger().d(dTAG," distance from start to end is:" +dist);
				if(dist>200 &&(  wpNumItems/*.getOverlayOptions()*/.size()==0 ||dist/wpNumItems/*.getOverlayOptions()*/.size()>100)						
						){
					showMsg("长途路书规划请适当增加加途经点数量");
				}
					
				return;
			}
				 
				 //remove the start,end point on the map
//				 mMapView.getOverlays().clear();
//				 mMapView.getOverlays().remove(this.mGpOverlay);
				 wpItems/*.getOverlayOptions()*/.remove(startItem);
				 wpItems/*.getOverlayOptions()*/.remove(this.endItem);				 
//				 mGpOverlay.removeAll();
//				 mGpOverlay.addItem(wpItems); 
//				 mGpOverlay.addItem(wpNumItems);  
//			     mMapView.getOverlays().add(mGpOverlay);
			       
				  
 		  
				 routeOverlay.removeFromMap();    /*mMapView.getOverlays().remove(routeOverlay);*/
				  
				
//				 final MKRoute custRoute = new MKRoute();
				 
				  
//				 LatLng[] GPS= (LatLng[]) custGeos.toArray(new LatLng[custGeos.size()]); 
//				 
//				 custRoute.customizeRoute(startPt, endPt, GPS);
				 
				 final Handler  handler2 = new Handler(){
						
						@Override
						public void handleMessage(Message msg) { 
							
							  if(msg.what==2){ 
								  //  // QLog.getLogger().d(dTAG,"after assembly the track...............................");
								  setRouteSuceedMsg();
							}
							 
							 
						}};
						
			    // 此处仅展示一个方案作为示例
				
				//清除其他图层
				/*int plans=res.getNumPlan();
				for(int i=0;i<plans;i++){
					int routes =res.getPlan(i).getNumRoutes();
					for(int j=0;j<routes;j++){
						
						routeOverlay = new RouteOverlay(activity, mMapView);
		 			    // 此处仅展示一个方案作为示例
		 				routeOverlay.setData(res.getPlan(i).getRoute(j));
						//添加路线图层
		 				mMapView.getOverlays().add(routeOverlay);
		 				 // QLog.getLogger().d(dTAG,"res.getPlan(i).getRoute(j).getDistance()"+ res.getPlan(i).getRoute(j).getDistance());
					}
				}
			  */
				 
				 
				/* 
				 try{
					 routeOverlay.setData(custRoute);
					 routeOverlay.setStMarker(getResources().getDrawable(icon_start));
			    	    routeOverlay.setEnMarker(getResources().getDrawable(icon_end));
			    	 mMapView.getOverlays().add(routeOverlay); 
			    	
				 }catch(NullPointerException er){
					 showMsg("路书需要链接互联网，请检查网络链接。");
					 return;
				 }*/
				 
			  //执行刷新使生效
			 
			    // 使用zoomToSpan()绽放地图，使路线能完全显示在地图上
				 
				 new Thread(){
					 @Override
						public void run() {
						 
					/*	 try {
							Thread.sleep(500);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}*/
						 
						/* try{
							 routeOverlay.setData(custRoute);
//							    routeOverlay.setStMarker(getResources().getDrawable(icon_start));
//					    	    routeOverlay.setEnMarker(getResources().getDrawable(icon_end));
					    	    mMapView.getOverlays().remove(routeOverlay);
					    	    mMapView.getOverlays().add(routeOverlay); 
					    	 
 					    	 Thread.sleep(100);
					         mMapView.getController().zoomToSpan(routeOverlay.getLatSpanE6(), routeOverlay.getLonSpanE6()); 
					    	 mMapView.getController().animateTo( startPt);  
						     mMapView.refresh();
						  
						 }catch(NullPointerException er){
							 showMsg("路书需要链接互联网，请检查网络链接。");
							 return;
						 } catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} */
						
						 routeOverlay.addToMap();
						 
						/* routeOverlay.zoomToSpan();*/
 						 
						 mGpOverlay.zoomToSpan();
						 
						 
						 handler2.sendEmptyMessage(2);
						 
					 }
				 }.start();
 			    
//			     // QLog.getLogger().d(dTAG, String.format("zoom spanzoom spanzoom spanzoom span zoom span: %s,%s", routeOverlay.getLatSpanE6(),routeOverlay.getLonSpanE6()));
			    
		/*	  //移动地图到起点
			    mMapView.getController().animateTo(this.startPt); 
			    
			    mMapView.refresh();
			    //将路线数据保存给全局变量
//			    route = res.getPlan(0).getRoute(0);
//			   MKRoute route = new MKRoute();
//			   route.customizeRoute(startPt, endPt, routeData);	
//			  
			    //重置路线节点索引，节点浏览时使用
//			    nodeIndex = -1;
			    txtNote.setText(null);
			    showMsg(String.format("路线%s完成，里程%.2f公里，预计骑行用时%s",
			    		trackId==0?"计算":"加载",
			    		routeDistance/1000.0,
			    		Utils.getTimeCnt4Read((long) (routeDistance/avSpeed),false)));
//			    mBtnPre.setVisibility(View.VISIBLE);
//				mBtnNext.setVisibility(View.VISIBLE);
*/		
		
			  
		
		}
		
		void setRouteSuceedMsg(){
			  isSilence=false;
			  txtNote.setText(null);   
				 showMsg(String.format("路线%s完成，里程%.2f公里，预计骑行用时%s",
				    		trackId==0?"计算":"加载",
				    		routeDistance/1000.0,
				    		Utils.getTimeCnt4Read((long) (routeDistance/avSpeed),false)));
		}
	 
		@Override
		protected void drawTrack(){}
		
	 @Override  
		protected void showMapViews(){
			 
// 		    super.showMapViews();
//			LinearLayout tm_ll_top_txt =(LinearLayout)vContainer.findViewById(R.id.tm_ll_top_txt); 
//			tm_ll_top_txt.setVisibility( View.VISIBLE );
		   /* GridLayout grid_top_txt =(GridLayout)vContainer.findViewById(R.id.grid_top_txt);
			grid_top_txt.setVisibility( View.GONE );*/
			vContainer.findViewById(R.id.grid_top_txt).setVisibility( View.GONE );
 		/*	if(tabhost!=null && tabhost.getCurrentTabTag().equalsIgnoreCase(tabData)){
				LinearLayout trackDetail =(LinearLayout)vContainer.findViewById(R.id.tab_Route);
	//			tm_ll_top_txt.setVisibility(ll.getVisibility()==View.GONE?View.VISIBLE:View.GONE);
				trackDetail.setVisibility( View.VISIBLE );
 			} */
		   
//		    if(btnLocation!=null)
//		    	btnLocation.setVisibility(View.GONE);
			if(this.btnSaveScreen!=null)
				btnSaveScreen.setVisibility(View.GONE);  
			if(this.btnSataliteMap!=null)
				btnSataliteMap.setVisibility(View.GONE);  
			if(this.btnKmpoints!=null)
				btnKmpoints.setVisibility(View.GONE);  
			

			
			
//			takeMapScreenshot();
		
		} 
	  
	
	 @Override
	protected void initialTabhost(){

		 tabhost = (TabHost)vContainer.findViewById(R.id.tabhost);
		 tabhost.setup();  
		 tabFootmark ="路点";
		 tabMap="编辑";
		 
	       TabHost.TabSpec mapTab = tabhost.newTabSpec(tabMap); // This param will
			mapTab.setIndicator(tabMap);
			mapTab.setContent(R.id.tab_map);
			tabhost.addTab(mapTab);
		 
	
			LinearLayout ll_waypoints =  (LinearLayout)vContainer.findViewById(R.id.tab_waypoints)  ; 
			ll_waypoints.setVisibility(View.VISIBLE); 
			 
			 TabHost.TabSpec waypointsTab = tabhost.newTabSpec(tabWaypoints); 
			 waypointsTab.setContent(R.id.tab_waypoints);
			 waypointsTab.setIndicator(tabWaypoints);
			 tabhost.addTab(waypointsTab); 
			 
			 
				TabHost.TabSpec footmarkTab = tabhost.newTabSpec(tabFootmark);
				//garbageSpec.setIndicator(null, getResources().getDrawable(R.drawable.empty_photo));
				footmarkTab.setContent(R.id.tab_footmark);
				footmarkTab.setIndicator(tabFootmark);
				tabhost.addTab(footmarkTab); 
		 
			      TabHost.TabSpec readmeTabSpec = tabhost.newTabSpec(exchangeTab);  // This param will be used as tabId.
			        readmeTabSpec.setIndicator(exchangeTab);
			        readmeTabSpec.setContent(R.id.ll_exchange);
			        tabhost.addTab(readmeTabSpec); 
			        
			        TabHost.TabSpec historyTabSpec = tabhost.newTabSpec(historyTab);  // This param will be used as tabId.
			        historyTabSpec.setIndicator(historyTab);
			        historyTabSpec.setContent(R.id.ll_trackList);
			        tabhost.addTab(historyTabSpec); 
				
			        
				
//	        TabHost.TabSpec editSpec = tabhost.newTabSpec(tabEdit);
////	        garbageSpec.setIndicator(null, getResources().getDrawable(R.drawable.empty_photo));
//	        editSpec.setContent(R.id.tab_edit);
//	        editSpec.setIndicator(tabEdit);
//	        tabhost.addTab(editSpec);
//			 ((LinearLayout)vContainer.findViewById(R.id.tab_edit)).setVisibility( View.GONE ); 
//			 ((LinearLayout)vContainer.findViewById(R.id.tab_chart)).setVisibility( View.GONE ); 
//			 ((LinearLayout)vContainer.findViewById(R.id.tab_Route)).setVisibility( View.GONE ); 
			 
	        
	        initialTabhostStyle(tabhost);
	        
	         
	        tabhost.setOnTabChangedListener(new OnTabChangeListener() {
            @Override
            public void onTabChanged(String tabId) {
            /*   if(tabId.equalsIgnoreCase(tabFootmark)){
            	   tgShowPic.setEnabled(mTrack.getTrackBean().getStartWp()!=null);
            	   
            	 
           	 }  */
            	onTabClicked(tabId);   
            }}
        ); 
	         
		} 
	 protected void onTabClicked(String tabId){  
		 
		 setSelectedTabhostStyle(tabhost);
	
		 currentTab= tabhost.getCurrentTab();
	
		 hideNotes();
		 
		 isRouteQuery = currentTab == 4;
		 
		 if(isRouteQuery){
			 getLoaderManager().initLoader(0, null, this);
			 this.localTracklist.setVisibility(View.VISIBLE);
			 doRouteQuery();			 
		 } 
		 
	 }
	    
	
	 @Override
	 protected void setWorkingTrack(){
		  if(gpxTrack==null)return;
		   gpxTrack.getTrackBean().setType(TrackType.GPX);
		   mTrack =gpxTrack;
		   mTrack_bean = mTrack.getTrackBean();
	   }
	   

	 
	 
	 private void setCurrentLatLng(LatLng gp,String msg){		 
		 if(geoType==-1)return;
		 Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();
		 
		 gp = /*mMapView*/mBaiduMap.getMapStatus().target;//.getProjection().fromPixels(mMapView.getCenterPixel().x,mMapView.getCenterPixel().y ); 
		 
 		  
	
		  if(geoType==0){ 
   
			 buildStart(gp,icon_start);
			 
		  }else if(geoType==1){
			/*  markerSrc=R.drawable.icon_pass;
			
			  OverlayItem  item  =new OverlayItem(gp,"","");
			  item.setMarker(getResources().getDrawable(markerSrc) ); 
			  wpItems.add(item); */
			  //LatLng gp,int number,wpFlag flag,int icon,boolean isLoadFromTrack
			  buildWpItem(gp,++custWpMarkNumber,wpFlag.CUST,R.drawable.icon_pass,false);
//			  wpNumItems.add( getCustWpNum(gp,++custWpMarkNumber));
			  getWaypointListData();
		  }else if(geoType==2){ 
			  
			  buildEnd(gp,icon_end);  
		  }	 else if(geoType==3){ 
			  
			  buildWpItem(gp,++custWpMarkNumber,wpFlag.TENT,R.drawable.icon_tent,false);
		  }	 else if(geoType==4){ 
			  
			  buildWpItem(gp,++custWpMarkNumber,wpFlag.REST,R.drawable.icon_rest,false);
		  }	 else if(geoType==5){ 
			  
			  buildWpItem(gp,++custWpMarkNumber,wpFlag.CHECK,R.drawable.icon_check,false);
		  }	  else if(geoType==6){ 
			  
			  buildWpItem(gp,++custWpMarkNumber,wpFlag.HAND,R.drawable.icon_edit,false);
		  }		
		  updateMapMarkers();
		 
	 }
	 
	 @Override
	 protected void updateMapMarkers(){
//		  mMapView.getOverlays().remove(mGpOverlay);
		 /* mGpOverlay.removeAll();
		  mGpOverlay.addItem(endItem);
		   mGpOverlay.addItem(startItem);		 
		   mGpOverlay.addItem(wpItems); 
		   mGpOverlay.addItem(wpNumItems); */
		   if(startItem!=null &&endItem!=null){//if the end==start, then give start point more 50 lat 
			   if(startItem.getPosition().latitude==endItem.getPosition().latitude
					   && startItem.getPosition().longitude==endItem.getPosition().longitude){
			   
				   startItem.position(new LatLng(startItem.getPosition().latitudeE6+100,startItem.getPosition().longitudeE6+100));
				/*   if(startMarker!=null){
					   startMarker.remove();
				   }
				   startMarker = (Marker) mBaiduMap.addOverlay(startItem);*/
			   }
		   }
 
	    }
	 
	 @Override
	  protected void  setRouteStart(){
		 geoType=0;
		 
		 
		 setCurrentLatLng(null,"设置起点");
	 }
	 @Override
	  protected void  setRouteWps(){
		 geoType=1;
		  
		 setCurrentLatLng(null,"设置途经点");
	 }
	 @Override
	  protected void  setRouteEnd(){
		 geoType=2;
		 
		 setCurrentLatLng(null,"设置终点");
	 }
	 @Override
	 protected void  setRouteTent(){
		 geoType=3; //tent
		 
		 setCurrentLatLng(null,"设置住宿点");
	 }
	 @Override
	 protected void  setRouteRest(){		 
		 geoType=4; //tent
		  
		 setCurrentLatLng(null,"设置休息点");
	 }
	 @Override
	 protected void  setRouteCheck(){
		 geoType=5; //tent
		  
		 setCurrentLatLng(null,"设置打卡点");
	 }
	 @Override
	 protected void  setRouteHand(){
		 geoType=6; //tent
		  
		 setCurrentLatLng(null,"设置手绘点");
	 }
	 
	 @Override
	 protected void  routeSearch(){

		 SearchButtonProcess(null);
	 }
	 @Override
	 protected void  routeReset(){
		 btnRouteSave.setEnabled(false);
		 btnReverse.setEnabled(false);
		 custWpNumber=-1;
		 custWpMarkNumber=0;
		 startPt=null;
		 endPt=null;
		 custGeos.clear();
		 startItem=null ;
		 endItem=null ;
	/*	 endMarker.remove();
		 startMarker.remove();*/
		 
		 mGpOverlay.removeFromMap();
		 mGpOverlay.getOverlayOptions().clear();
//		 try{
			 routeOverlay.removeFromMap();
			 routeOverlay.getOverlayOptions().clear();
		/* }catch(Exception e){
			 Utils.logStackTrace(e, TAG);
		 }*/
//		 wpItems.removeFromMap();
//		 wpItems.getOverlayOptions().clear();
		 wpItems.clear();
//		 wpNumItems.removeFromMap();
//		 wpNumItems.getOverlayOptions().clear();
		 wpNumItems.clear();
		 
//		 mMapView.getOverlays().clear(); 
//	     mMapView.getOverlays().remove(routeOverlay);
//	     mMapView.getOverlays().remove(mGpOverlay);
//		 mMapView.refresh();
		 txtNote.setText(R.string.note_start); 
		 initialGpxTrack(); 
		 setWorkingTrack(); 
		  // QLog.getLogger().d(dTAG, " road reset to load track...loadFromTrack()"  );
		 loadFromTrack(); 
		 btnNavi.setEnabled(canNavi());
		 btnSNav.setEnabled(canNavi());
		 reverseComment="";  
 		 reverseName="";
	 }
	 
	 private void initialGpxTrack(){
		  if(trackId>0){
			 
			  gpxTrack =activity.app.getTrackCache().get(Integer.valueOf(trackId));
			   
			  activity.updateActionBarTitle( getResources().getString(R.string.frg_route)+ "    编号"+trackId);  
		  }else{
			  gpxTrack=new Track();
//			  gpxTrack.getTrackBean().setUserid(QiYouConstant.PV_USER_ID);
			  
		  }
		  setWorkingTrack(); 	
	 }
	 @Override
	 protected void  routeSave(){
		
//		 txtNote.setText(null);
		 isSilence=false;
		 if(custGeos.isEmpty()){
			 showMsg("没有路书需要保存");
			 return;
		 }
		 
		 btnRouteSave.setEnabled(false);
		  
		 if(trackId<=0 || gpxTrack.getTrackBean().getUserid()!=activity.app.user.getUserbean().getId()){  //new route
			 
			 
			
			 
			 gpxTrack.getTrackBean().setUserid(activity.app.user.getUserbean().getId());
			 activity.app.initialImportedGpx();
			 activity.app.getImportedGpx().add(gpxTrack);		
			 activity.app.impGpx();		 
			 
			 
//			 for(Waypoint_bean wb1:gpxTrack.getTrackBean().getRoadWps()){
//					 // QLog.getLogger().d(dTAG, "  saved road Wbs turn flag is: " +wb1.getTurnFlag().toCHString() );
//				}
			 
			 
			 handler = new Handler(){
					
					@Override
					public void handleMessage(Message msg) {
						
						//关闭ProgressDialog
//										progressDialog.dismiss(); 
						
						 //更新UI
//											 switchButtonStatus(); 
						
						  if(msg.what==0){  
							  showMsg("已保存，新增路书编号：" +trackId+"，可以从菜单-->我的记录-->路书分类中找到该路书。");
							  activity.updateActionBarTitle( getResources().getString(R.string.frg_route)+ "    编号"+trackId); 
							  activity.app.getTrackCache().put(trackId, gpxTrack);
							  setWorkingTrack();
							  btnNavi.setEnabled(canNavi());
							  btnSNav.setEnabled(canNavi());
							  btnReverse.setEnabled(true);
							  activity.app.setCurrentTrack(gpxTrack);
 							  activity.app.worksOnLine(trackId);
							  
							  
							  
						}else if(msg.what==1){	
							 showMsg("保存过程遇到错误");
						}
						 
						   
						  
					}};
					
				new Thread(){ 
					@Override
					public void run() {
						 
							int topWaiting=0;
							while( gpxTrack.getTrackBean().getTrackId()==0){
							try {
	 			 				Thread.sleep(100);
				 				topWaiting+=100;
				 				if(topWaiting>5000 ){  
				 					handler.sendEmptyMessage(1);
				 					 break;
				 				 
				 				}
				 				 
				 			  } catch (InterruptedException e) {
				 				// TODO Auto-generated catch block
				 				Utils.logStackTrace(e, TAG);
//				 				handler.sendEmptyMessage(0);
				 				
				 				}
							} 
						  
						trackId=gpxTrack.getTrackBean().getTrackId();
						handler.sendEmptyMessage(0);
						isSilence=false;
				 }}.start();  
				
			 
			 
			 
			 
			 
			 
			 
			 
			 
		 }else{ //edit exist route
			 gpxTrack.getTrackBean().setTrackId(trackId);
			 gpxTrack.saveContent(false);
			 activity.app.getTrackCache().put(trackId, gpxTrack);
			if(activity.app.currentTrack==null||activity.app.currentTrack.getTrackBean().getTrackId()==trackId){
				activity.app.currentTrack=gpxTrack;
			}
			 doSave();
			  showMsg("已保存"+(trackId>0?"":"，你可以从菜单-->我的记录-->路书分类中找到该路书"));
			  btnNavi.setEnabled(true);
			  btnSNav.setEnabled(true);
		 }
		 
		 custGeos.clear();
		
		 isSilence=true;
		 
	 }
	 
	 void assemblyTrack(){
		 if(custGeos.isEmpty())return;
		
		  // QLog.getLogger().d(dTAG, "roadWbs。cnt "+ roadWbs.size());
		 if(QiYouConstant.DEVELOPER_MODE)
		 for(Waypoint_bean  wb:roadWbs){				
					 
					  // QLog.getLogger().d(dTAG,  " check cust wp  turn flag" + wb.getTurnFlag().toCHString());
					  // QLog.getLogger().d(dTAG,  " check road book " + wb.getRoadBook());
				
			 } 
		 
		 
		 if(gpxTrack==null){
			 gpxTrack = new Track();
			 String creator=activity.app.user.getUserbean().getUserName()/*.getAccount()*/;
			 creator=TextUtils.isEmpty(creator)?"爱骑驴路书":creator;
			 gpxTrack.getTrackBean().setCreatTime(System.currentTimeMillis()); 
			 gpxTrack.getTrackBean().setType(TrackType.GPX);
//			 gpxTrack.getTrackBean().setCreator("爱骑驴路书");
			 gpxTrack.getTrackBean().setCreator(creator);
			
		 }
		 else{
//			 gpxTrack.getTrackBean().getRoadWps().clear();
//			 gpxTrack.getTrackBean().getTrkseg().clear();
//			 gpxTrack.setRdWpsJson(new StringBuffer());//		
//			 gpxTrack.getTrackBean().setStartWp(null);
//			 gpxTrack.getTrackBean().setLastWp(null);
//			 gpxTrack.setStartWp(null);
//		 
			 Track tmp = new Track();
			 tmp.getTrackBean().setTrackId(gpxTrack.getTrackBean().getTrackId());
			 tmp.getTrackBean().setName(gpxTrack.getTrackBean().getName());
			 tmp.getTrackBean().setComment(gpxTrack.getTrackBean().getComment());
			 tmp.getTrackBean().setDescription(gpxTrack.getTrackBean().getDescription());
//			 tmp.getTrackBean().setCreatTime(gpxTrack.getTrackBean().getCreatTime()); 
//			 tmp.getTrackBean().setType(gpxTrack.getTrackBean().getType());
//			 tmp.getTrackBean().setCreator(gpxTrack.getTrackBean().getCreator());
			 tmp.getTrackBean().setCreatTime(System.currentTimeMillis()); 
			 tmp.getTrackBean().setType(TrackType.GPX);
			 tmp.getTrackBean().setCreator("爱骑驴路书");
			 tmp.getTrackBean().setUserid(gpxTrack.getTrackBean().getUserid());
			 tmp.getTrackBean().setMdWps(gpxTrack.getTrackBean().getMdWps());
			 tmp.getTrackBean().setSvrNumber(gpxTrack.getTrackBean().getSvrNumber());
			 gpxTrack=tmp;
			  if(!TextUtils.isEmpty(reverseComment))		 
		    		gpxTrack.getTrackBean().setDescription(reverseComment );
			  
			  if(!TextUtils.isEmpty(reverseName))		 
		    		gpxTrack.getTrackBean().setName(reverseName );
			  
			 
		 }
 
		 
	  
	    
//		 btnRouteSave.setEnabled(false);
//		 btnRouteSave.setVisibility(View.GONE);
		 
		 
//		long totalTime=(long) (routeDistance/avSpeed);
		long startTime=System.currentTimeMillis();
		long esp=0l;//(long)(routeDistance/avSpeed/custGeos.size());
		long sptime=0;;
		float speed=avSpeed*3600;
//		int sdist=routeDistance/custGeos.size();
		float sdist;
		int sumDist=0;
		gpxTrack.getTrackBean().setSportTime((long) (routeDistance/avSpeed));
		 //  // QLog.getLogger().d(dTAG,  String.format("routeDistance:%s,avSpeed %s,custGeos.size %s", routeDistance,avSpeed,custGeos.size()));
		 //  // QLog.getLogger().d(dTAG,  " esp: " + esp);
		
 //		Waypoint startWp = new Waypoint();
//		startWp.getWb().setTime(startTime);		
//		startWp.getWb().setLongitude((float)(startPt.getLongitudeE6()/1e6));
//		startWp.getWb().setLatitude((float)(startPt.getLatitudeE6()/1e6));
//		startWp.getWb().setSpeed(avSpeed);
//		track.setLastWp(startWp);
		
//		ArrayList<Waypoint_bean> wbs= track.getTrackBean().getTrkseg();
		 int num=0;
		 boolean isRoadBear;
		 Waypoint wp;
		 Waypoint lastwp = null;
		 Waypoint prewp =null;
		 Waypoint nextWp =null;
		 ArrayList<LatLng> tmpGeos =new ArrayList<LatLng>();
		 synchronized(custGeos) {
		  for(LatLng gp :custGeos){
//			 sptime+=esp;
			 wp = new Waypoint();
			 wp.setWb(getWb(gp));			
			 wp.getWb().setSpeed(speed);
			 wp.getWb().setTime(startTime);
			 
			
//			 wp.getWb().setDistance(sptime*avSpeed);
			 sdist =lastwp==null?0:  (float) Utils.getDistanceFromXtoY(lastwp.getWb().getLatitude(),lastwp.getWb().getLongitude(),wp.getWb().getLatitude(),wp.getWb().getLongitude());
			 sumDist+=sdist;
			 esp=(long)(sdist/avSpeed);
			 sptime+=esp;
			 wp.getWb().setDistance(sdist);
			 wp.getWb().setSumDist(sumDist);
			 wp.getWb().setSportTime(sptime);
			 int i=0;
			 prewp = lastwp;
			 nextWp =wp;
			if/* while*/(sdist>500){
				 i++;
				 prewp =lastwp;
				 sdist =sdist/2;
				 Waypoint	 mwp = new Waypoint();
				 Waypoint_bean wb  = new Waypoint_bean();
				 wb.setLatitude((prewp.getWb().getLatitude()+nextWp.getWb().getLatitude())/2);
				 wb.setLongitude( (prewp.getWb().getLongitude()+nextWp.getWb().getLongitude())/2);
				 mwp.setWb(wb);			
				 mwp.getWb().setSpeed(speed);
				 mwp.getWb().setTime(/*gpxTrack.getTrackBean().getLastWp().getWb().getTime()+1*/ startTime -(long)(sdist/avSpeed) );
				 mwp.getWb().setSumDist(sumDist-sdist);
				 mwp.getWb().setSportTime(sptime-100/*(long)(sdist/avSpeed)*/);
				 // QLog.getLogger().dLog(QNaviSvc.TAG, String.format(" gpxTrack wps size %s",gpxTrack.getTrackBean().getTrkseg().size()));
				 QLog.getLogger().d(dTAG,String.format(" to add new wp, current time %s - last time %s = %s ", mwp.getWb().getTime(),gpxTrack.getTrackBean().getLastWp().getWb().getTime(),  mwp.getWb().getTime() -gpxTrack.getTrackBean().getLastWp().getWb().getTime()));
				 gpxTrack.setLastWp(mwp);
				 // QLog.getLogger().dLog(QNaviSvc.TAG, String.format(" add middle waypoint, new sdist is %s",sdist));
				 // QLog.getLogger().dLog(QNaviSvc.TAG, String.format(" mwp.getWb().getSumDist  %s ,mwp.getWb().getTime  %s",mwp.getWb().getSumDist(),mwp.getWb().getTime()));
				 
				 // QLog.getLogger().dLog(QNaviSvc.TAG, String.format(" new gpxTrack wps size %s",gpxTrack.getTrackBean().getTrkseg().size()));
//				 tmpGeos.add(gp);
//				 prewp =;
//				 nextWp =mwp;
				 
				 wp.getWb().setDistance(sdist/2);
			 }
			 
			 
//			 wbs.add(wb);
//			 wp.getWb().setTurnFlag(wpFlag.TURNLEFT);
//			  // QLog.getLogger().d(dTAG,  "wp.getWb().getTurnFlag()" +wp.getWb().getTurnFlag()+"");
			
//			 startTime+=esp;
			 
			 isRoadBear=false;
			 for(Waypoint_bean  wb:roadWbs){
// 				  // QLog.getLogger().d(dTAG,  " 1 check time " + wb.getTime());
// 				  // QLog.getLogger().d(dTAG,  " 1 check road book " + wb.getRoadBook());
				if(wb.getTime()==0 && wp.getWb().getLatitude()==wb.getLatitude() && wp.getWb().getLongitude()==wb.getLongitude()) {
//					  // QLog.getLogger().d(dTAG,  "  wb.getTime()" +  wb.getTime());
//					 // QLog.getLogger().d(dTAG,  " cust wp set starttime" + startTime);
//					  // QLog.getLogger().d(dTAG,  " cust wp  turn flag" + wb.getTurnFlag().toCHString());
//					  // QLog.getLogger().d(dTAG,  " 2 check road book " + wb.getRoadBook());
					
					wb.setTime(startTime);
					wb.setSpeed(speed);
//					wb.setDistance(wp.getWb().getDistance()); 
					wb.setSumDist(sumDist);
					wb.setSportTime(sptime); 
					wp.getWb().setTurnFlag(wb.getTurnFlag()); 
				    isRoadBear=true;
					break;
				}
			 }
			 
//			 if(isRoadBear ||custGeos.size()<=2000 ||custGeos.size()>2000 && num % 2 == 0)
		     if(isRoadBear ||  sumDist< 50000 ||sumDist<100000 && num % 2 == 0 ||sumDist>100000 && sumDist<300000 &&  num % 5 == 0 ||num % 10 == 0 ){  
//				 QLog.getLogger().d(dTAG," to insert new wp" );

		    	 gpxTrack.setLastWp(wp);
				 tmpGeos.add(gp);
		     }
		     startTime+=esp+1;
			 num++;
//			 startTime+=esp;
			 lastwp=wp;
//			 sdist =lastwp==null?0:  (float) Utils.getDistanceFromXtoY(lastwp.getWb().getLatitude(),lastwp.getWb().getLongitude(),wp.getWb().getLatitude(),wp.getWb().getLongitude());
//			 sumDist+=sdist;
			 
		  }
		 }
		  
		 custGeos=tmpGeos; 
		  Waypoint_bean  wb;
		 Waypoint_bean  lastWb;
		 for(int i=roadWbs.size()-1;i>0;i--){
			 wb = roadWbs.get(i);
			 lastWb=roadWbs.get(i-1);
			 if(wb==null ||lastWb==null)continue;
//			 wb.setRoadBook(lastWb.getRoadBook()); 
//			 wb.setDistance(lastWb.getDistance());
// 			 wb.setBearDist(lastWb.getBearDist());
// 			 wb.setBearDist((float) Utils.getDistanceFromXtoY(wb.getLatitude(),wb.getLongitude(),lastWb.getLatitude(),lastWb.getLongitude()));
			 wb.setBearDist(wb.getSumDist() - lastWb.getSumDist());
			 wb.setDistance(wb.getBearDist());
 			 if(wb.getSumDist()==0 &&lastWb.getSumDist()>0){
				 wb.setSumDist(lastWb.getSumDist()+wb.getDistance() );
			 }
//			 wb.setTurnFlag(lastWb.getTurnFlag());
		 }	  
		 
		 
//		 Waypoint endWp = new Waypoint();
//		 endWp.getWb().setTime(startTime);		
//		 endWp.getWb().setLongitude((float)(endPt.getLongitudeE6()/1e6));
//		 endWp.getWb().setLatitude((float)(endPt.getLatitudeE6()/1e6));
//		 endWp.getWb().setSpeed(avSpeed);
//		 track.setLastWp(endWp);
		
		 if(gpxTrack.getTrackBean().getTrkseg().size()>5000){
			 /*CopyOnWriteArrayList<Waypoint_bean> wbs = new  CopyOnWriteArrayList<Waypoint_bean>();*/
			 ArrayList<Waypoint_bean> wbs = new   ArrayList<Waypoint_bean>();
//			 wbs.addAll(5000, gpxTrack.getTrackBean().getTrkseg());// gpxTrack.getTrackBean().getTrkseg().subList(0, 5000);
			 wbs.addAll(gpxTrack.getTrackBean().getTrkseg().subList(0, 5000));
			float dist=0;
			 for(int i=wbs.size()-1;i>0;i--){
				 if(wbs.get(i)!=null){
					 dist=wbs.get(i).getSumDist();
					 break;
				 }
			 }
			
			 
			 for(Waypoint_bean  wb1:roadWbs){
				 if(wb1==null)continue;
				 if(wb1.getSumDist()>dist)
					 wbs.add(wb1);
			 }
			 gpxTrack.getJsonWps().append(gpxTrack.wps2json(wbs)); 
			 gpxTrack.getTrackBean().setTrksegs(wbs);
		 }else			 
			 gpxTrack.getJsonWps().append(gpxTrack.wps2json(gpxTrack.getTrackBean().getTrkseg()));
		 
		 
		 gpxTrack.getTrackBean().setDistance(sumDist);
		 
	 
		 long lasttime=0;//=System.currentTimeMillis();
		 for(int i=0;i<roadWbs.size();i++){
			  if(roadWbs.get(i)==null)continue; 
			  if(lasttime==0){
				  lasttime =roadWbs.get(i).getTime();
				  continue;
			  }
			 if(roadWbs.get(i).getTime()<=lasttime){
				 roadWbs.get(i).setTime(lasttime+1);				 
			 }
			 
			 lasttime =roadWbs.get(i).getTime();
		 }
		 
		
		 gpxTrack.setBearWps(roadWbs); 
		 gpxTrack.getTrackBean().setIsCheckedIn(routeType);
		 setWorkingTrack();
		 
		  // QLog.getLogger().d(dTAG, "roadWbs。cnt "+ roadWbs.size());
//		  for(Waypoint_bean wb1:gpxTrack.getTrackBean().getRoadWps()){
				 // QLog.getLogger().d(dTAG, " to save road Wbs time: " +wb1.getTime() );
				  // QLog.getLogger().d(dTAG,  "2 cust wp  turn flag" + wb1.getTurnFlag().toCHString());
				  // QLog.getLogger().d(dTAG,  " check road book " + wb1.getRoadBook());
//			}  
//		 updateGpxEle();//TODO: need more validations, for its expensive ,Temply here.
 
	 }
	    
	 
	 
		private class MyPoiOverlay extends PoiOverlay {

			public MyPoiOverlay(BaiduMap baiduMap) {
				super(baiduMap);
			}

			@Override
			public boolean onPoiClick(int index) {
				super.onPoiClick(index);
				PoiInfo poi = getPoiResult().getAllPoi().get(index);
				// if (poi.hasCaterDetails) {
					mPoiSearch.searchPoiDetail((new PoiDetailSearchOption())
							.poiUid(poi.uid));
				// }
				return true;
			}
		}
		
	 
	  
		  protected void searchButtonProcess() {
			  isSilence=false;
			 String target=rt_txt_target.getText().toString();
			 String cityNm=cityNameView.getText().toString();
			 
			 if(TextUtils.isEmpty(cityNm)){
				 this.showMsg("请输入查询城市");
				 cityNameView.requestFocus();
				 return;
			 }
			 
//			 if(INPUT_TARGET.equalsIgnoreCase(target)){
			 if(TextUtils.isEmpty(target)){
				 this.showMsg("请输入查询地址");
				 rt_txt_target.requestFocus();
				 return;
			 }
			  
			  Utils.hideSoftKeyboard(activity);			  
// 	          mPoiSearch.poiSearchInCity(cityNm, target);
			 
 	         mPoiSearch.searchInCity((new PoiCitySearchOption())
 					.city(cityNm)
 					.keyword(target)
 					.pageNum(0));
 	         
	    }
	 
	 
		  
		  
		  
		 private void getWaypointListData(){ 
	 
			 

			    lv = (DragSortListView) vContainer.findViewById(android.R.id.list);

		        lv.setDropListener(onDrop);
		        lv.setRemoveListener(onRemove);
		        lv.setDragScrollProfile(ssProfile);
 
		
		        OverLayItemAdapter =new overLayItemListAdapter(activity, R.layout.list_item_click_remove, R.id.text_waypoint, wpNumItems);
		        lv.setAdapter(OverLayItemAdapter);
		        
		        
	    }

	   
		  private void restItems(){
 
				
				 mGpOverlay.removeFromMap();
				 mGpOverlay.getOverlayOptions().clear();
				    mGpOverlay.getOverlayOptions().add(endItem);
					mGpOverlay.getOverlayOptions().add(startItem);	
					mGpOverlay.getOverlayOptions().addAll(wpItems); 
					mGpOverlay.getOverlayOptions().addAll(wpNumItems);
					mGpOverlay.addToMap();
				
				if(routeOverlay!=null){
  					routeOverlay.removeFromMap();
  					routeOverlay.getOverlayOptions().clear();
				}
				
				 
		  }
		  
		  
		  
		  
		  
	    private DragSortListView.DropListener onDrop =
	            new DragSortListView.DropListener() {
	                @Override
	                public void drop(int from, int to) {

//	                	wpNumItems.indexOf(item);
 	                	
	          
	                	
//	                	//change the marker
//	                	Drawable df =wpNumItems.get(from).getMarker();
//	                	Drawable dt =wpNumItems.get(to).getMarker();
//	                	wpNumItems.get(to).setMarker(df);
//	                	wpNumItems.get(from).setMarker(dt);
	                	
	                    MarkerOptions item=OverLayItemAdapter.getItem(from);

	                	OverLayItemAdapter.notifyDataSetChanged();
	                	OverLayItemAdapter.remove(item);
	                	OverLayItemAdapter.insert(item, to); 
	                	
////	                	//exchange the gp of numberitem between 'from' and 'to'
//	                	 LatLng oldGp =new LatLng(item.getPoint().getLatitudeE6(),item.getPoint().getLongitudeE6());
//		                	wpNumItems.get(to).getPoint().setLatitudeE6(wpNumItems.get(from).getPoint().getLatitudeE6());
//		                	wpNumItems.get(to).getPoint().setLongitudeE6(wpNumItems.get(from).getPoint().getLongitudeE6());
//		                	wpNumItems.get(from).setLatLng(oldGp);
		                	
//	                	
	                	
	                	
	                	
	                	//reorder both the list,make them synchronize
	                	MarkerOptions i =wpItems.get(from);               	
	                    wpItems.remove(from);
	                	wpItems.add(to, i); 
	                	 
	                	
	                
	                	
//	                	  mGpOverlay.removeAll();
//	      			    mGpOverlay.addItem(endItem);
//	      				mGpOverlay.addItem(startItem);	
//	      				mGpOverlay.addItem(wpItems); 
//	      				mGpOverlay.addItem(wpNumItems); 
//	                	mMapView.refresh();
	                	restItems();
	                	//adapter will do below. 
//	                	wpNumItems.remove(item);
//	                	wpNumItems.add(to, i);
	                	
	                }
	            };

	        private DragSortListView.RemoveListener onRemove = 
	            new DragSortListView.RemoveListener() {
	                @Override
	                public void remove(int which) {
	                	MarkerOptions item =OverLayItemAdapter.getItem(which);
	                	OverLayItemAdapter.remove(item);// the adapter will do: wpNumItems.remove(item); 
	                	wpItems.remove(which);
	                	
	                	restItems();
	                }
	            };
		  
		  
	            private DragSortListView.DragScrollProfile ssProfile =
	                    new DragSortListView.DragScrollProfile() {
	                        @Override
	                        public float getSpeed(float w, long t) {
	                            if (w > 0.8f) {
	                                // Traverse all views in a millisecond
	                                return ((float) OverLayItemAdapter.getCount()) / 0.001f;
	                            } else {
	                                return 10.0f * w;
	                            }
	                        }
	                    };
		  
		  
		  
		  
	                    private class overLayItemListAdapter extends ArrayAdapter<MarkerOptions/*OverlayItem*/> {
	                    
	                    	public overLayItemListAdapter(Context context, int resource,int textViewResourceId,	List<MarkerOptions> objects) {
	                    		super(context,resource, textViewResourceId, objects);
	                    	 
	                    	}
	                    	
	                    	@Override
	                    	public View getView(int position, View convertView, ViewGroup parent){
	                    		MarkerOptions item = getItem(position);
	                    		 View v = super.getView(position, convertView, parent);
	                    	/*	 ImageView imgMarker = (ImageView)v.findViewById(R.id.route_marker);
	                    		 imgMarker.setBackground(item.getIcon() );*/
//	                    		 imgMarker.setImageDrawable(item.getMarker());  
	                    		 TextView tv =(TextView)v.findViewById(R.id.text_waypoint);
	                    		 tv.setText(String.format("途经点%s",item.getExtraInfo().getInt(RoadOverlay.EXTR_KEY_INDEX)/*item.getTitle()*/));
//	                    		 tv.setText("途经点");
	                    		 return v;
 
	                    	}
	                    }
		   
		  
	   
		public void loadFromTrack(){
			
			if(trackId<=0){
				 if( activity.app.isNaving && activity.app.naviTrackId>0){
						trackId=activity.app.naviTrackId; 
			   } else
					 return;
			}
			txtNote.setText(null);
			oldComments=new HashMap<Integer,String>();
//			custGeos
			for(Waypoint_bean wb:mTrack.getTrackBean().getTrkseg()){
			  if(wb==null)continue;
				custGeos.add(getLatLng(wb));
				
			}
			
			//build 途经点
			int i=0;
			custWpMarkNumber=0;
			for(Waypoint_bean wb:mTrack.getTrackBean().getRoadWps()){
				
//				 // QLog.getLogger().d(dTAG, TAG+ " road wb name is:"+wb.getName() + "  road wb roadbook is:"+wb.getRoadBook() );
//			     // QLog.getLogger().d(dTAG, " load from track: road Wbs turn flag is: " +wb.getTurnFlag().toCHString() );
// 				 // QLog.getLogger().d(dTAG, TAG +" road wb isCustWaypoint(wb)？" +isCustWaypoint(wb));
 				
//				 if(TextUtils.isEmpty(wb.getName())&&wb.getRoadBook().indexOf("到达【途经点")<0)continue; 
 			 
 				 // //  // QLog.getLogger().d(dTAG, " load from track: road Wbs turn flag is: " +wb.getTurnFlag().toCHString() );
 			 
				 if(!isCustWaypoint(wb))continue; //to check why not work here??
				
				   // QLog.getLogger().d(dTAG, TAG+ " got cust waypoint, road wb name is: "+wb.getName());
				 LatLng gp =getLatLng(wb);
				 
				  try{
					  	i=Integer.parseInt(wb.getName()) ;//custWpMarkNumber
//					    wpNumItems.add( getCustWpNum(gp,i,wpFlag.CUST));
//					  	 wpNumItems/*.getOverlayOptions()*/.add( getCustWpNum(gp,i,wb.getTurnFlag()));
				  }catch(NumberFormatException er){
//					    wpNumItems.add( getCustWpNum(getLatLng(wb),++i,wpFlag.CUST));
//					  wpNumItems/*.getOverlayOptions()*/.add( getCustWpNum(getLatLng(wb),++i,wb.getTurnFlag()));
					  ++i;
				  }
				  custWpMarkNumber=custWpMarkNumber<i?i:custWpMarkNumber;
				 if(!TextUtils.isEmpty(wb.getComment())){
						 oldComments.put(i, wb.getComment());	
						 //  // QLog.getLogger().d(dTAG, TAG+ " oldComments.put(i, wb.getComment()):"+ i+","+ wb.getComment());
					
				 }
					
//				  OverlayItem  item  =new OverlayItem(gp,"","");
//				  item.setMarker(getResources().getDrawable(R.drawable.icon_pass) ); 
//				  wpItems.add(item);   
				 
				 if(wb.getTurnFlag()==wpFlag.CUST)
					 buildWpItem(gp,/*++*/custWpMarkNumber,wpFlag.CUST,R.drawable.icon_pass,true);
				 else  if(wb.getTurnFlag()==wpFlag.TENT)
					 buildWpItem(gp,/*++*/custWpMarkNumber,wpFlag.TENT,R.drawable.icon_tent,true);
				 else  if(wb.getTurnFlag()==wpFlag.REST)
					 buildWpItem(gp,/*++*/custWpMarkNumber,wpFlag.REST,R.drawable.icon_rest,true);
				 else  if(wb.getTurnFlag()==wpFlag.CHECK)
					 buildWpItem(gp,/*++*/custWpMarkNumber,wpFlag.CHECK,R.drawable.icon_check,true);
			}
			  getWaypointListData();
			 
			//build start
			  if(mTrack.getStartWp()!=null){
				  buildStart(getLatLng(mTrack.getStartWp().getWb()),icon_start);
			  }
			  if(mTrack.getStartWp()!=null){
				  buildEnd(getLatLng(mTrack.getLastWp().getWb()),icon_end);
			  }
			  
			  
			  routeDistance=(int) mTrack.getTrackBean().getDistance();
			  showRoutes(true);
			  btnReverse.setEnabled(true); 
			  this.spRouteType.setSelection(mTrack.getTrackBean().getIsCheckedIn());
			  
		}
		
		private void buildStart(LatLng gp,int icon){
			     startPt=gp; 
			     if(startItem!=null && mGpOverlay.getOverlayOptions().contains(startItem))
					 mGpOverlay.getOverlayOptions().remove(startItem);
			     
				  startItem =  new MarkerOptions().position(gp)
						  		.anchor(0.5f, 0.5f)
						  		.icon(BitmapDescriptorFactory.fromResource(icon) );
				  mGpOverlay.getOverlayOptions().add(startItem);
				  mGpOverlay.addToMap();

		}
		
		private void buildWpItem(LatLng gp,int number,wpFlag flag,int icon,boolean isLoadFromTrack){ 
			  
 			 // QLog.getLogger().d(dTAG, String.format(" building cust road point--- flat %s, ", flag.toCHString()));

			 MarkerOptions o=  new MarkerOptions().position(gp)
//		  		.anchor(0.5f, 0.5f)
		  		.icon(BitmapDescriptorFactory.fromResource(icon) );
			 
			  wpItems.add(o);  
			  mGpOverlay.getOverlayOptions().add(o);//.addItem(item);
//			  if(!isLoadFromTrack)
			  	{
				  MarkerOptions oa =getCustWpNum(gp,number,flag);
			  	  wpNumItems.add( oa);
			      mGpOverlay.getOverlayOptions().add(oa);
			  }
			 
			  mGpOverlay.addToMap();
			  
			  
 		}
		  
		private void buildEnd(LatLng gp,int icon){
			if(endItem!=null && mGpOverlay.getOverlayOptions().contains(endItem))
			 mGpOverlay.getOverlayOptions().remove(endItem);
		 this.endPt=gp; 
		   
		  endItem =  new MarkerOptions().position(gp)
			  		.anchor(0.5f, 0.5f)
			  		.icon(BitmapDescriptorFactory.fromResource(icon) );
		  mGpOverlay.getOverlayOptions().add(endItem);
		  
		  mGpOverlay.addToMap();
		}
		
		
		
		
		
		
		@Override
		public void updateUI(Location location, Boolean isOnPause) {
			if(canLocationMap && locData!=null)
				updateMapView(location);
		}
		
		
		RadioGroup	 impRdGroup;
		Button btn_loadRoadbook;
		private void initialGpxViews(){
			filelv = (ListView) vContainer.findViewById(R.id.gpxfile_list);  
			txt_importNote =(TextView) vContainer.findViewById(R.id.imp_notice);
			mbtn_refresh =(Button)vContainer.findViewById(R.id.btn_refresh);
			mbtn_refresh.setOnClickListener( new OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					showGpxFileList();
				}
			});
			
			mbtn_import =(Button)vContainer.findViewById(R.id.btn_import);
			mbtn_import.setOnClickListener( new OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					pareseGPX();
				}
			});
			
			
			
			 
			 btn_loadRoadbook =(Button)vContainer.findViewById(R.id.map_btnLoadRoadbook); 
			btn_loadRoadbook.setOnClickListener(ButtonOnClickListener);		
			 

			 impRdGroup = (RadioGroup)vContainer.findViewById(R.id.rg_route_import); 
			 if(impRdGroup!=null){
				 impRdGroup.setOnCheckedChangeListener(rdgChanged);
			 } 
			
		}
		 
		
		
		 OnCheckedChangeListener rdgChanged = new OnCheckedChangeListener() {
	           
	           @Override
	           public void onCheckedChanged(RadioGroup arg0, int arg1) { 
	               //获取变更后的选中项的ID
	               int radioButtonId = arg0.getCheckedRadioButtonId();
	               //根据ID获取RadioButton的实例  
	               if(radioButtonId ==R.id.rd_import_web){
	            	 vContainer.findViewById(R.id.ll_import_gpxfile).setVisibility(View.GONE);   
	            	 vContainer.findViewById(R.id.ll_import_web).setVisibility(View.VISIBLE);  
	               }else if(radioButtonId ==R.id.rd_import_gpx){ 
	            	   vContainer.findViewById(R.id.ll_import_gpxfile).setVisibility(View.VISIBLE);   
		            	 vContainer.findViewById(R.id.ll_import_web).setVisibility(View.GONE);                 
	               } 
	                
	           }
	       }; 
		/*
		 * below is for import functions.
		 */
		
	   List<String> errorGpxfiles= new ArrayList<String>();
		private void pareseGPX(){
			
//			progressDialog = ProgressDialog.show(activity, "请稍等...", "正在导入GPX...", true);
			
			handler = new Handler(){

				@Override
				public void handleMessage(Message msg) {
					
					//关闭ProgressDialog
					if(progressDialog!=null)progressDialog.dismiss();
					if(msg.what==1){
						progressDialog = ProgressDialog.show(activity, "请稍等...", "正在导入 \n"+msg.getData().getString("file"), true);
						progressDialog.setCancelable(true);
	 		    		progressDialog.setCanceledOnTouchOutside(false);
						mbtn_import.setEnabled(false);
					}
					else
					if(msg.what==0){
					//更新UI 
						 mbtn_import.setEnabled(true);
						 progressDialog.dismiss();
						 showGpxFileList();
						
					}
				 
				}};
		   
				new Thread(){

					@Override
					public void run() {
		 	 
			 ArrayList<String> srcs = activity.app.getImportedGpxFileList();		 
			 
			 boolean succeed;
//			HashMap<String, String> gpxFiles =FileScan.getFiles(new File(QiYouConstant.IMP_PATH));
			 
			activity.app.initialImportedGpx();
			 
			for(Map<String,String> gpxFile:gpxFileList){
				 
//			 for(String fileName :gpxFile.keySet()) {
 				String gpxFullfileName= gpxFile.get("fileName");
 				 //  // QLog.getLogger().d(TAG," srcs.contains " + gpxFullfileName+"?" +srcs.contains(gpxFullfileName));
 
				 if(!gpxFullfileName.toUpperCase().endsWith(".GPX")||srcs.contains(gpxFullfileName))continue;
				 Message msg= Message.obtain();
				 Bundle bundle=new Bundle();  
                 bundle.putString("file", gpxFullfileName);  
                 msg.setData(bundle);//bundle传值，耗时，效率低   
                 msg.what=1;//标志是哪个线程传数据   
				 handler.sendMessage(msg);
				 succeed=false;
				  try{
//					  succeed= activity.app.impGpx( gpxFullfileName );
					  Track tr =Track.newInstance(gpxFullfileName);
					  succeed=tr!=null;
					    if(succeed)
					    	activity.app.getImportedGpx().add(tr);
					     
//						 importedGpx =new ArrayList<Track>();// initial the imported list for each import. so that the list contains the latest imported gpx tracks.
						  
				  }catch(Exception er){
					  Utils.logStackTrace(er, TAG);
					  
				  }
					if(!succeed){
						errorGpxfiles.add(gpxFullfileName);
						 // QLog.getLogger().d(TAG," import succeed?" +succeed +",file "+gpxFullfileName);
					}
//					if(succeed){
//						 // QLog.getLogger().d(TAG," import succeed?" +succeed);
//					}
					
					 // QLog.getLogger().d(TAG," import succeed?" +succeed);
				
              }
			  
			activity.app.impGpx();//persist the new gpx tracks.
			
			 try {
	 				Thread.sleep(5000); //waiting for syncronize completed
	 				 
	 			  } catch (InterruptedException e) {
	 				// TODO Auto-generated catch block
	 				Utils.logStackTrace(e, TAG);
	 				}
		    	 
			handler.sendEmptyMessage(0);
		  }}.start(); 
					
			
//			 String fileName="test_imp.gpx"; 
//			 String gpxfileName =QiYouConstant.IMP_PATH+fileName; 
			
//		
//			 if(srcs.contains(gpxfileName))return; 
//			 
//			 
//			boolean succeed= activity.app.impGpx( gpxfileName );
//			
//			if(succeed){
//				 // QLog.getLogger().d(TAG," import succeed?" +succeed);
//			}
//			
//			 // QLog.getLogger().d(TAG," import succeed?" +succeed);
			
		}
		
		
	  private void showGpxFileList(){
		  
//		  HashMap<String, String> gpxFiles =FileScan.getFiles(new File(QiYouConstant.IMP_PATH));
		  gpxFileList = FileScan.getFiles(new File(QiYouConstant.IMP_PATH));
//		  gpxFileList = new ArrayList<Map<String, String>>();
		  ArrayList<String> srcs = activity.app.getImportedGpxFileList();	
		  String importedOrNot;
		  final String WAIT_FOR_IMPORT="待导入";
		  final String ERROR_WHEN_IMPORT="导入失败";
			if(errorGpxfiles.size()==0)
				txt_importNote.setText("请将待导入的GPX文件（夹）放入下面目录： \n"
// 						+QiYouConstant.IMP_PATH
						+"/qiyou/imp/"
						+"\n导入的GPX轨迹可以在 菜单-->我的记录-->路书页面中找到。");   
			else
				txt_importNote.setText("GPX导入过程出现错误，请检查下列文件格式是否正确：");
		  mbtn_import.setEnabled(false);
			for(Map<String,String> gpxFile:gpxFileList){
				 
	 				String gpxFullfileName= gpxFile.get("fileName"); 
	 				 
	 				importedOrNot="已导入";
	 				 
	 				if(!srcs.contains(gpxFullfileName)){
	 					importedOrNot=WAIT_FOR_IMPORT;
	 					if(!mbtn_import.isEnabled()){
	 						mbtn_import.setEnabled(true);	 					
	 					}
//	 					if(errorGpxfiles.size()==0)
//	 						txt_importNote.setText(txt_importNote.getText()+"\n"+"发现待导入GPX");
	 					
	 				}
	 				if(errorGpxfiles.contains(gpxFullfileName)){
	 					if(!mbtn_import.isEnabled()){
	 						mbtn_import.setEnabled(true);	 					
	 					} 
	 					txt_importNote.setText(txt_importNote.getText()+"\n"+gpxFullfileName);
	 					importedOrNot =ERROR_WHEN_IMPORT;
	 				}
	 				   
	 				gpxFile.put("imported", importedOrNot);
	 				
//	 				  // QLog.getLogger().d(TAG," srcs.contains " + gpxFullfileName+"?" +srcs.contains(gpxFullfileName));
//	 				gpxFileList.add(gpxFile);
//					 if(srcs.contains(gpxFullfileName))continue;
				 }
	  
		  
		  QSimpleAdapter   adapter = new QSimpleAdapter(activity,gpxFileList,R.layout.import_gpx_detail,
					new String[]{"fileName","imported"},
					new int[]{R.id.txt_gpxfile,R.id.txt_gpxfileImported}); 
//		  ArrayList<String> srcs = activity.app.getImportedGpxFileList();	
	     adapter.setViewBinder( new ViewBinder(){
	    	@Override
			public boolean setViewValue(View view, Object data,String textRepresentation) {    		
//	    		 
	    		if(view.getId()==R.id.txt_gpxfileImported){
	    			 TextView tv =(TextView)view;
	    			 tv.setTextColor(Color.GRAY);
	    			 
//	    			  if(TextUtils.equals((String)data,ERROR_WHEN_IMPORT)) {
//    					 tv.setTextColor(Color.RED); 
//    			     } 
//    			 
	    			 
	    			 if(TextUtils.equals((String)data,WAIT_FOR_IMPORT)||TextUtils.equals((String)data,ERROR_WHEN_IMPORT)) {
	    					 tv.setTextColor(Color.RED); 
	    			 } 
	    			 tv.setText((String)data);
	    			 
	    			 
	    			 
	    			 /*if(Boolean.getBoolean((String)data))
	    				 tv.setText("已导入");
	    			 else{
	    				 tv.setText("未导入");
	    				 tv.setTextColor(Color.RED);
	    			 }*/
 	    		 return true;
	    		}
	    		else if(view.getId()==R.id.txt_gpxfile){
	    			 TextView tv =(TextView)view;
	    			 
	    			 String fileName = ((String)data);
//	    			 fileName =fileName.substring(fileName.lastIndexOf(QiYouConstant.IMP_PATH) + 1);
	    			 fileName =fileName.replace(QiYouConstant.IMP_PATH, "");
	    			 tv.setText(fileName);
	    			 return true;
	    		}
	            return false;    
	        }    
	    });    
	    
	  
	     filelv.setAdapter(adapter);  
//	    adapter.setSelectItem(selectedFoodmarkItem);
//	    filelv.setSelection(selectedFoodmarkItem);
	  }
	  	
		 
	String reverseComment;  
	String reverseName;
	  @Override
	   void reverseRoute(){ 
 		  reverseName ="";
		  reverseComment="";
		  if(trackId>0 && gpxTrack!=null){ 
			  reverseName = "【返程】";
			  reverseName =gpxTrack.getTrackBean().getName().replaceAll(reverseName, "")+reverseName;
			  reverseComment= "\n"+gpxTrack.getTrackBean().getName()+" 的返程路书.";
		  }
		  trackId=0;
		  	initialGpxTrack();
			LatLng tmpSt=startItem.getPosition();
			LatLng tmpEd=endItem.getPosition();
			buildEnd(tmpSt,icon_end); 
			buildStart(tmpEd,icon_start);
			
		    List<MarkerOptions> tmpWpItems= new ArrayList<MarkerOptions>();
			for(int i=wpItems.size();i>0;i--){
				tmpWpItems.add(wpItems.get(i-1));
			}
			 
			wpItems =tmpWpItems;
			
			 List<MarkerOptions> tmpWpNumItems= new ArrayList<MarkerOptions>();
				for(int i=wpNumItems.size();i>0;i--){
					tmpWpNumItems.add(wpNumItems.get(i-1));
				} 
			wpNumItems=tmpWpNumItems;  
			
	        OverLayItemAdapter =new overLayItemListAdapter(activity, R.layout.list_item_click_remove, R.id.text_waypoint, wpNumItems);
	        lv.setAdapter(OverLayItemAdapter);
	        
//	        mMapView.getOverlays().remove(routeOverlay);
	        routeOverlay.removeFromMap();
	        routeOverlay.getOverlayOptions().clear();
	        
		    restItems() ;
		    
		    routeSearch();
		    btnReverse.setEnabled(false);
		    
	    }
	  
	  
	   
	  
	  
	  
	  void routeResume(){ 
			  activity.app.isRouting=true;
			  canLocationMap=true;
			  updateUI(activity.app.lastLocation, false);
			  locationInMap(null);
			  showGpxFileList();
 
	  }
		
		
 
	  class RouteOverlay extends OverlayManager{

			public RouteOverlay(BaiduMap baiduMap) {
				super(baiduMap);
				// TODO Auto-generated constructor stub
			}

			@Override
			public boolean onMarkerClick(Marker arg0) {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public boolean onPolylineClick(Polyline arg0) {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public List<OverlayOptions> getOverlayOptions() {				 
				List<OverlayOptions> overlayList = new ArrayList<OverlayOptions>();
				ArrayList<LatLng> tmpGeos = new ArrayList<LatLng>();
				 synchronized(custGeos) {
					 for(LatLng ll : custGeos){
						 if (ll != null){
							 tmpGeos.add(ll);
						 }
					 }
					 custGeos = tmpGeos;
					 if(tmpGeos.size()>2){
						 overlayList.add(new PolylineOptions().points(custGeos).width(10)
		            		  .color(  Color.argb(178, 0, 78, 255)).zIndex(0));  
					 }
				 }
				return overlayList;
			}
			  
		  }
		   
		  
	  protected Spinner spRouteType;   
	   void initTrackTypeSpin(){
		    ArrayAdapter<?> spAdapter;
	    	spRouteType = (Spinner)vContainer.findViewById(R.id.SpinnerRouteType);
	    	if(spRouteType==null)return;
			 int spinner=R.layout.myspinner;
			//将可选内容与ArrayAdapter连接起来
//	    	spAdapter = ArrayAdapter.createFromResource( getActivity(), R.array.trackType, android.R.layout.simple_spinner_item);
	    	spAdapter = ArrayAdapter.createFromResource( getActivity(),  R.array.routeType , spinner/*R.layout.myspinner*/);

			//设置下拉列表的风格	
	    	spAdapter.setDropDownViewResource(R.layout.spinner_item);

			//将adapter2 添加到spinner中
	    	spRouteType.setAdapter(spAdapter);

			//添加事件Spinner事件监听  
	    	spRouteType.setOnItemSelectedListener(new SpinnerXMLSelectedListener());

			//设置默认值
//	    	spRouteType.setVisibility(View.VISIBLE);
			
		}
	     
	  
	 @Override
		public void onResume() {
			super.onResume();	
			   routeResume();
		}
	 
	 @Override
		public void onPause() { 
			super.onPause();  
			if(!activity.app.isLastTrackExist()){
				if(activity.app.lastGpsStartTime>0 &&!activity.app.isGPSstopped )
					activity.app.stopAndroidGPSRequest();
				activity.app.unregTimeTick();
				activity.app.stopNetworkLocationRequest();
			}
			
		}
	 @Override
		public void onDestroy() {  
			super.onDestroy();
		}
	@Override
	public void setTabOnFiling() {
		 MAPVIEW_INDEX=0;
//		 maxTabIndex = 3;
		
	}
	public boolean isRouteGot() {
		return isRouteGot;
	}
	public void setRouteGot(boolean isRouteGot) {
		this.isRouteGot = isRouteGot;
	} 
	 
	 @Override
	 protected void startNavi(boolean isSimulation){
		 //  // // QLog.getLogger().dLog(dTAG,TAG, "Start to Navigation,gpx trackId is "+trackId);
		 if(trackId<=0)return;		 
		 super.startNavi(isSimulation);
	 };
	 
@Override
	public boolean isShowBottomTabs() {
		// TODO Auto-generated method stub
		return false;
	}
	/* 
	 void buildWoGEO(Waypoint_bean wb){
		 
		 GEOaddress geo= new GEOaddress();
			if( wb.getGeo()==null && activity.app.getCityGEO(wb.getLatitude(),wb.getLongitude())){
				
				 geo.setProvince(activity.app.GEOadress.province);
				 geo.setCity(activity.app.GEOadress.city);
				 geo.setDistrict(activity.app.GEOadress.district);
				 geo.setStreet(activity.app.GEOadress.street);
				 geo.setStreetNo(activity.app.GEOadress.streetNumber);	
				 geo.setLat(wb.getLatitude());
				 geo.setLon(wb.getLongitude());
				 
				 wb.setGeo(geo);
				 
			}
			 
		}*/

	/**
	 * load track to edit
	 */
	@Override
	void  showWebTrack(Track tr){ 
	  if(tr==null)return;
	  this.activity.app.setCurrentTrack(tr,true);
//	  this.trackId = tr.getTrackBean().getTrackId();
//	  gpxTrack =activity.app.getTrackCache().get(Integer.valueOf(tr.getTrackBean().getSvrNumber())); 
//	  activity.updateActionBarTitle( getResources().getString(R.string.frg_route)+ "    编号"+trackId);  
	  showDetailTrack(tr.getTrackBean().getSvrNumber());
	    
	}
		@Override
		void showDetailTrack(int trackId){
		
		 
		    		this.trackId = trackId;
		    		initialGpxTrack();
		    		routeInitial();
		    		tabhost.setCurrentTab(0);
//		    		this.showRoutes(true);
			   
      }
	 
		@Override
		public void doQuery() {
			// TODO Auto-generated method stub
			doTrackQuery();
		}
}
