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

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
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.MyLocationData;
import com.baidu.mapapi.model.LatLng;
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.Media;
import com.qiyou.mb.android.beans.basic.Waypoint;
import com.qiyou.mb.android.beans.basic.Waypoint_bean;
import com.qiyou.mb.android.service.TrackDbServiceBackground;
import com.qiyou.mb.android.ui.charts.AbstractChart;
import com.qiyou.mb.android.ui.charts.DistEleChartNoDown;
import com.qiyou.mb.android.ui.charts.DistKmSpeedChart;
import com.qiyou.mb.android.ui.charts.DistSpeedChart;
import com.qiyou.mb.android.utils.ImageLoader;
import com.qiyou.mb.android.utils.QSimpleAdapter;
import com.qiyou.mb.android.utils.Utils;
import com.qiyou.mb.android.utils.enums.BBSCate;
import com.qiyou.mb.android.utils.enums.TrackStatus;
import com.qiyou.mb.android.utils.enums.TrackType;
import com.qiyou.mb.android.utils.enums.mediaStatus;
import com.qiyou.mb.android.utils.enums.mediaType;
import com.qiyou.mb.android.utils.log.QLog;

@TargetApi(Build.VERSION_CODES.FROYO)
public class TrackTabs_fragment extends WebList_fragment{// TrackMap_fragment  {
//	  public static final String TAG ="com.qiyou.TrackTabs_fragment";
//	  public static final String dTAG ="com.qiyou";
	@Override
	public void setFTag(){
		TAG="com.qiyou.TrackTabs_fragment";
	}
	public static String getFTag(){
		return "com.qiyou.TrackTabs_fragment";
	}
	@Override
	public String getCurrentTag(){
		return "com.qiyou.TrackTabs_fragment";
	}
//	  protected SimpleAdapter adapter;
	  QSimpleAdapter adapter;
//	  protected MainActivity activity;
	  ProgressDialog progressDialog ;	    
//	  MemorySoftCache picCache;
//	  ImageLoader IL;
//	  String trackId;
	  private List<Map<String, String>> mData;
	  private ListView lv = null;  
	  private CheckBox chk_pic;
	  protected CheckBox chk_showChats;
//	  View vContainer;
	   private static final int ITEM_LOC = 1;  
	   private static final int ITEM_LOC_SAVE_SCREEN = 2;
//	   private static final int ITEM_MODIFY = 2;
	   private static final int ITEM_ADDPIC = 5;
 	   private static final int ITEM_DELETE = 3;
 	  private static final int ITEM_COMMENT = 4;
 	  
	   
//	   RadioGroup rdGroup;
//	   int fmLevel =0;
	   boolean showPicOnly  ;  
	   boolean isShowCharts  ;
//	   ToggleButton tgShowPic;
//	   String[] imgUrls;
	  
//	   private Handler handler ;
//	   private ImageView fmMapImg;
	   protected boolean isShowEdit;
	   protected   String tabData="数据";
	   protected   String tabMap="地图";
	   protected   String tabFootmark="足迹";
//	   protected final String tabChart="图表"; 
	   protected final String tabEdit="编辑";
	   protected final String tabWaypoints="途经点";
	   
//	   com.qiyou.mb.android.ui.fragments.InnerGridView cateLv  ;
	   Button btnNewCate;
	   EditText editNewCate;
	   private TextView txtNotice;
	   
//	   Track mTrack;
	   protected LinearLayout llcharts ; 
	   protected CheckBox chk_showGpx; 
	 
	   
//	   Button btnExportFm;
	public TrackTabs_fragment() {
		// TODO Auto-generated constructor stub
	}
	
/*	public static TrackTabs_fragment newInstance(String trackId)
	{
		TrackTabs_fragment f = new TrackTabs_fragment();
		Bundle args = new Bundle(); 
	    args.putString(QiYouConstant.EXTRA_KEY_ID, trackId);
	    f.setArguments(args);
	    return f;
	}
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		  setFTag();
		  setWorkingTrack(); 
//		  vContainer = inflater.inflate(R.layout.track_fragment, container, false);
		  initialViews(); 
//		  initViewMap(); 
		  initialTabhost();
		  if(!activity.app.playBack) initialFootmark();
//		  initialGestureDetector();
		return vContainer;
		}
	
	 @Override
	  public void onActivityCreated(Bundle savedInstanceState) {
	    super.onActivityCreated(savedInstanceState);
//	    if(mTrack_bean.getTrackId()>0)  drawTrack(); 
//	    drawTrack();
//	    picCache = new MemorySoftCache();
//	    activity = (MainActivity)getActivity();	   
//	    activity.app.currentActiveFragment =TAG; 
	   
	    getExtrArgs();
	   
//		final  Activity activity =activity;
	
		
	    initalLvs();
	    
	    
	   
	 }
	 
	 void getExtrArgs(){
		 if (getArguments() != null) {	      
//		    	String  Id = getArguments().getString(QiYouConstant.EXTRA_KEY_ID);
//		        if(Id!=null)trackId =Integer.valueOf(Id);
		        trackId= getArguments().getInt(QiYouConstant.EXTRA_KEY_ID);
		      }
	 }
	 
	 
	 protected void initalLvs(){
		 if(activity.app.playBack)return;
		    
		    IL = new ImageLoader(activity); 
		    
	        // 设置在条目上单击监听器  
	        lv.setOnItemClickListener(itemListener);  
	        // 设置长按事件  
	        registerForContextMenu(lv);  
		    
//		    showData(true);
//		    if(!isPlayback)showFullMap();
//			setListAdapter(adapter);
	        
		    if(mTrack_bean==null)return;
		    
	        showTabs(mTrack_bean.getTrackId()>0 &&mTrack_bean.getTrackId() ==trackId);
	        setStaticMap();
	 }
	 
	 
	
	 void addNotes(List<Map<String, String>> mData,int level){
		 if(txtNotice==null)return;
			String notice="";
			if(mData==null || mData.size()==0 ){
				notice="还没有发现小脚印...";
				if(level ==1){
					notice ="没找到详细数据,连接WIFI后会自动生成详细地址数据...";
				}else if(level==2){
 				/*	if(activity.app.currentActiveFragment.equalsIgnoreCase(Route_fragment.getFTag()))
						notice ="没找到照片...长按路点数据可以插入照片" ;
					else*/
						notice ="没找到照片...快去拍些亮丽的片片吧" ;
 
				}
			}else{
				  notice ="提示: 长按可显示编辑项";
 				if(level ==1 
 						&&( mTrack_bean.getStatus()==TrackStatus.FINISHED && mData.size()<4 
 							||mTrack_bean.getStatus()!=TrackStatus.FINISHED && mData.size()<2	
 						  ) 
 						){
 				   notice ="没找到详细数据,连接WIFI后会自动生成详细地址数据...";;
 				}else 
					if(level==2){
						if(mTrack_bean.getTrackId()>0)
								notice ="提示: 点击图片可进入浏览模式,长按可显示编辑项" ;
						else
							notice ="提示: 长按可显示编辑项" ;
				}
			}
			setNotice(notice);
	 }
	 
	 void setNotice(String notice){
		 txtNotice.setText(notice);
	 }
	 
 	  @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 );
//			
	/*		LinearLayout trackDetail =(LinearLayout)vContainer.findViewById(R.id.ll_recording_data);
//			tm_ll_top_txt.setVisibility(ll.getVisibility()==View.GONE?View.VISIBLE:View.GONE);
			if(trackDetail!=null) trackDetail.setVisibility( View.GONE );
		    if(btnLocation!=null)
		    	btnLocation.setVisibility(View.GONE);
			if(this.btnSaveScreen!=null)
				btnSaveScreen.setVisibility(View.VISIBLE);  
			GridLayout grid_top_txt =(GridLayout)vContainer.findViewById(R.id.grid_top_txt);
			if(grid_top_txt!=null)grid_top_txt.setVisibility( View.VISIBLE );
			((TextView)this.vContainer.findViewById(R.id.tm_top_speed_title)).setText("均速");*/
//			takeMapScreenshot();
		
		} 
	  
	   CheckBox.OnCheckedChangeListener m_checkboxListener =new  CheckBox.OnCheckedChangeListener(){
		    @Override
			public void onCheckedChanged(CompoundButton buttonView,
						boolean isChecked) {
					// TODO Auto-generated method stub
					
					if(buttonView.getId()==R.id.fm_chk_pic)
					{
 						showPicOnly = chk_pic.isChecked();	  
 						switchFootmarkCharts(false);
		            	showFootmarkData(true);
					}else if(buttonView.getId()==R.id.fm_chk_charts && chk_showChats.isEnabled()){
						isShowCharts =chk_showChats.isChecked();
//						chk_pic.setEnabled(!isShowCharts);
						switchFootmarkCharts(isShowCharts);
						if(isShowCharts ){
							showCharts();
						}
						
					}
		  }

			 
	   };
		
	   void switchFootmarkCharts(boolean isShowCharts){
		 
		   if(chk_showChats.isChecked() && !isShowCharts){
			   chk_showChats.setEnabled(false);
			   chk_showChats.setChecked(isShowCharts);
		   	   chk_showChats.setEnabled(true);
		   }
		   
		   chk_pic.setVisibility(isShowCharts?View.GONE:View.VISIBLE);
			lv.setVisibility(isShowCharts?View.GONE:View.VISIBLE);
			txtNotice.setVisibility(isShowCharts?View.GONE:View.VISIBLE);
			((ScrollView)vContainer.findViewById(R.id.td_scrollViewCharts)).setVisibility(isShowCharts?View.VISIBLE:View.GONE);
			
	   }
	 void initialFootmark(){
		  chk_pic = (CheckBox)vContainer.findViewById(R.id.fm_chk_pic); 
		  chk_pic.setChecked(true);
		  chk_pic.setOnCheckedChangeListener(m_checkboxListener);
		 
		  showPicOnly =chk_pic.isChecked();
		  
		   
		  chk_showChats = (CheckBox)vContainer.findViewById(R.id.fm_chk_charts);  
		  chk_showChats.setOnCheckedChangeListener(m_checkboxListener);
//		  if(trackId==activity.app.getRecordingTrack().getTrackBean().getTrackId() &&
//				  activity.app.getRecordingTrack().getTrackBean().getStatus()== TrackStatus.RECORDING ){
		 /* if(mTrack_bean.getStatus()== TrackStatus.RECORDING ){
			  chk_showChats.setVisibility(View.VISIBLE);
		  }*/
		  lv = (ListView) vContainer.findViewById(R.id.fm_list);  
// 		  fmMapImg =(ImageView)vContainer.findViewById(R.id.fm_staticMap);
//		  rdGroup = (RadioGroup)vContainer.findViewById(R.id.fm_rdGroup);
//		  rdGroup.setOnCheckedChangeListener(rdgChanged);
		  /*tgShowPic = (ToggleButton) vContainer.findViewById(R.id.fm_tgShowPic); 
		  tgShowPic.setChecked(showPic);
		  tgShowPic.setOnClickListener(new Button.OnClickListener(){ 
	            @Override 
	            public void onClick(View v) { 
	                // ToggleButton.isChecked() – 双状态按钮的按钮状态，根据状态作出对于的事件响应 
	            	showPic = tgShowPic.isChecked();
	            	QLog.getLogger().d(dTAG, TAG+ " show pic? " +showPic);
	            	showFootmarkData(true);
	            } 
	        });*/
		  txtNotice =(TextView)vContainer.findViewById(R.id.fm_notice);
 		 /* textContainer =(ScrollView)vContainer.findViewById(R.id.td_scrollView); 		  
 		  if(textContainer!=null)
		     textContainer.setOnTouchListener(new OnTouchListener() {
			    @Override
			    public boolean onTouch(View v, MotionEvent event) {
	 		        Utils.hideSoftKeyboard(activity);
			        return false;
			    }
			});*/
		     
		     
		     
	 }
	 
	 
	 
	 protected void onTabClicked(String tabId){ 
		 // QLog.getLogger().d(dTAG, TAG+ "................onTabClicked............ :"+  tabId  ); 
			activity.isMapActive=false;
		 
		 onMyTabChanged(tabId);
//		 if(tabId.equalsIgnoreCase(tabData)){
//    		 LinearLayout trackDetail =(LinearLayout)vContainer.findViewById(R.id.tab_statistic); 
// 			if(trackDetail!=null) trackDetail.setVisibility( View.GONE ); 
// 			showFootmarkData(true);
// 		}else		
		 Utils.hideSoftKeyboard(activity); //hide the input soft keys
 		 if(tabId.equalsIgnoreCase(tabFootmark)){
//    		 LinearLayout trackDetail =(LinearLayout)vContainer.findViewById(R.id.tab_trackingdata); 
// 			if(trackDetail!=null) trackDetail.setVisibility( View.GONE );
// 			 tgShowPic.setEnabled(mTrack.getTrackBean().getStartWp()!=null);
 			 showFootmarkData(true);
 			if(isShowCharts ){
				showCharts();
			}
    	 }else
    		 if(tabId.equalsIgnoreCase(tabData)){
    			 // QLog.getLogger().d(dTAG, TAG+ "................onTabClicked............ :"+  "showMapViews()"  );
    			 if(isPlayback)return;
    			 
    			 showMapViews();
//        		 LinearLayout tabFootmark =(LinearLayout)vContainer.findViewById(R.id.tab_statistic); 
//    	 		 if(tabFootmark!=null) tabFootmark.setVisibility( View.GONE );    	 			
    	 		 showMapButtons();
//    	 		 showCharts();
    	 		 //    			 showBasicButtons();
    	 }/*else 
    		 if(tabId.equalsIgnoreCase(tabChart)){
    			 QLog.getLogger().d(dTAG, TAG+ "................onTabClicked............ :"+  "showCharts(2)"  ); 
//    			 showCharts(0);
    			 showCharts(1);
    			 showCharts(2);
//    			 showMapButtons();
//    			 showBasicButtons();
    	 }*/
    		 else
        	 if(tabId.equalsIgnoreCase(tabMap)){
        			activity.isMapActive=true;
        		 // QLog.getLogger().d(dTAG, TAG+ "................onTabClicked............ :"+  "drawTrack()"  ); 
//        		 showMapButtons(); 
        		/* if(mTrack_bean.getStatus()==TrackStatus.RECORDING && !canDrawTrack){
        			 canDrawTrack=true;
        			 isDrawingTrack=false;
//        			 updateUI(null, false);
        			 updateGraphics(null, false);
        		 }*/
        		 if(mTrack_bean.getStatus()==TrackStatus.RECORDING){
        			 redrawTrack();
        		 }
        		  updateMapMarkers();
//        		  updateUI(null, false);
        		  
//        		 new Thread(){
//
// 					@Override
// 					public void run() {
// 				 drawTrack();
// 					}}.start();
//	       		  
        	 }
        	 else
            	 if(tabId.equalsIgnoreCase(tabEdit)){
            		 // QLog.getLogger().d(dTAG, TAG+ "................onTabClicked............ :"+  "tabEdit"  ); 
            		 
            		 validEditButtons();
            		 setTrackDesc();
    	       		  
            	 }
 		 
//            	 else
//                	 if(tabId.equalsIgnoreCase(tabWaypoints)){
//                		 // QLog.getLogger().d(dTAG, TAG+ "................onTabClicked............ :"+  "tabWaypoints"  ); 
//                		if(mMapView!=null)
//                			mMapView.refresh();
//        	       		  
//                	 }
	 }
	 
	 protected void showCharts(){
		   if(mTrack.getTrackBean().getType()==TrackType.GPX && mTrack.getTrackBean().getSvrNumber()==0)
		    	  return;
		 showCharts(0);
		 showCharts(1);
		 showCharts(2);
	 }
 
    protected void updateMapMarkers(){
    	
    }
	  
    protected void redrawTrack(){
		 // QLog.getLogger().d(dTAG, TAG+ " canDrawTrack? "+ canDrawTrack  ); 

//    	 if(!canDrawTrack)
    	 {
			 canDrawTrack=true;
			 isDrawingTrack=false;
//			 updateUI(null, false); 
		 } 
    	 drawTrack();
//    	 drawGpx();
//    	 updateGraphics(null, false);
    }
	 
	protected void initialTabhost(){

//			TabHost host = (TabHost)vContainer.findViewById(R.id.tabhost);
//	        host.setup();
	        tabhost = (TabHost)vContainer.findViewById(R.id.tabhost);
			 tabhost.setup();  
            // be used as tabId.
			//homeSpec.setIndicator(null,     getResources().getDrawable(R.drawable.empty_photo));
		
			if(!activity.app.playBack){
				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);
			}else{
				 LinearLayout tabFootmark =(LinearLayout)vContainer.findViewById(R.id.tab_footmark); 
    	 		 if(tabFootmark!=null) tabFootmark.setVisibility( View.GONE );    
			}
			
		
//			if(!activity.app.playBack){
		    if(isShowEdit){ 
		      /*  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);*/
			}else{
//				 ((LinearLayout)vContainer.findViewById(R.id.tab_chart)).setVisibility( View.GONE ); 
//				 ((LinearLayout)vContainer.findViewById(R.id.tab_edit)).setVisibility( View.GONE ); 
    	 		 
			}
		    TabHost.TabSpec mapTab = tabhost.newTabSpec(tabMap); // This param will
			mapTab.setIndicator(tabMap);
			mapTab.setContent(R.id.tab_map);
			tabhost.addTab(mapTab);
			


			if ( !this.isPlayback && mTrack_bean!=null && mTrack_bean.getSvrNumber() > 0){
				 
			    bbsTab = getResources().getString(R.string.tab_bbs);//"云端"; 
				tabBbs = tabhost.newTabSpec(bbsTab);  
				tabBbs.setIndicator(bbsTab/*, getResources().getDrawable(R.drawable.icon_user,null)*/);
				tabBbs.setContent(R.id.tab_bbs);  
				tabhost.addTab(tabBbs);
				
				  BBScate =BBSCate.TRACK.toInt() ;
				  BBSSubcate = mTrack_bean.getSvrNumber(); 
				  BBSSubcateOwner = mTrack_bean.getUserid();
				  BBSsubCateName = mTrack_bean.getName();
			}
			
			 
		/*        TabWidget  tabWidget = tabhost.getTabWidget();
		        for (int i =0; i < tabWidget.getChildCount(); i++) {  
		            tabWidget.getChildAt(i).getLayoutParams().height = 55;  
		            tabWidget.getChildAt(i).getLayoutParams().width = 65;
//		            TextView tv = (TextView) tabWidget.getChildAt(i).findViewById(android.R.id.title);
//		            tv.setTextSize(15);
//		            tv.setTextColor(this.getResources().getColorStateList(android.R.color.white));
		           }*/
		        
			
				
		        initialTabhostStyle(tabhost);
		        
		         
		        tabhost.setOnTabChangedListener(new OnTabChangeListener() {
	            @Override
	            public void onTabChanged(String tabId) {
	            /*   if(tabId.equalsIgnoreCase(tabFootmark)){
	            	   tgShowPic.setEnabled(mTrack.getTrackBean().getStartWp()!=null);
	            	   
	            	 
	           	 }  */
	            	onTabClicked(tabId);   
	            }}
	        ); 

		}
	@Override
	void switchTabOptions(int queryType){ 
		 
		if (lvWeb == null) {
			return;
		}
		 lvWeb.setVisibility(View.GONE); 
		int tabcnt = tabhost.getTabWidget().getTabCount();
		 isBBSQuery = queryType == 3;
	}
	 
	protected void drawTrack(){
//		  mTrack_bean = activity.app.getCurrentTrack().getTrackBean();
		 // QLog.getLogger().d(dTAG, TAG+ " begin to draw track "+  "drawTrack()"  );
		 
		 
		/* mTrack.getTrackBean().setTrksegs(null);
		 mTrack.getTrackBean().setRoadWps(null) ;  
		  String trackString=mTrack.toString();
		  QLog.getLogger().dLog(dTAG, trackString); 
		  QLog.getLogger().dLog(dTAG, mTrack.getTrackBean().getStartWp().toJsonWp());
		  */
		 
		 
		 
		 
		  setWorkingTrack();
		  //TODO: check why release apk has no start/lastwp/maxwp
		  
	/*	  if(mTrack_bean.getStartWp().getWb().getLatitude()==0 &&mTrack_bean.getRoadWps().size()>0){
			  mTrack_bean.getStartWp().setWb(mTrack_bean.getRoadWps().get(0));
			  mTrack_bean.getLastWp().setWb(mTrack_bean.getRoadWps().get(mTrack_bean.getRoadWps().size()-1));
		  }*/
		  
		  updateGraphics(null,false);
		  
		  if(!activity.app.playBack)
		    	 drawGpx(); 
		  
		  locationToTrackEnd();
		 
	 }
	 
	protected void locationToTrackEnd(){
		 QLog.getLogger().d(dTAG, TAG+ "................drawTrack............ :"+  "locationToTrackEnd()"  ); 
		 if(mTrack_bean.getTrackId()<=0)return;
		  Waypoint_bean wb ;//=mTrack_bean.getMaxDistWp().getWb();
//		 wb =mTrack_bean.getMaxDistWp().getWb();
		 wb =mTrack_bean.getLastWp().getWb(); 
		 
			if(mTrack_bean.getStatus()==TrackStatus.RECORDING 
		   			&& activity.app.getRecordingTrack().getTrackBean().getTrackId() ==mTrack_bean.getTrackId()
		   			&& activity.app.getRecordingTrack().getTrackBean().getStartTime() ==mTrack_bean.getStartTime()
		   			&& activity.app.getLocationCached().size()>0
		   			){
		   		Location loc =activity.app.getLocationCached().get(Integer.valueOf(activity.app.getLocationCached().size()-1));//activity.app.lastLocation;
//		   		loc =loc==null?activity.app.getLocationCached().get(Integer.valueOf(activity.app.getLocationCached().size()-1)):loc;
		   		if(loc!=null &&loc.getLatitude()>0 && wb.getTime()<loc.getTime() ){
			   		wb =new Waypoint_bean();	   			
			   		wb.setLatitude((float) loc.getLatitude());
		   			wb.setLongitude((float) loc.getLongitude());
		   			wb.setSpeed(loc.getSpeed()* 3.6f);
		   			wb.setTime(loc.getTime());	 
		   		}
	   			 		
			}
		   	 
		 
//		     locData.latitude = Utils.getbdLat(wb.getLatitude(), wb.getLongitude());		     
//		     locData.longitude =Utils.getbdLon(wb.getLatitude(), wb.getLongitude()); 
//			locData.accuracy = wb.getAccuracy();
//			locData.direction = wb.getBearing();
//			myLocationOverlay.setData(locData); 
			
			 locData = new MyLocationData.Builder()  
		     .latitude(Utils.getbdLat(wb.getLatitude(), wb.getLongitude()))
		     .longitude(Utils.getbdLon(wb.getLatitude(), wb.getLongitude()))
		     .accuracy(wb.getAccuracy())
		     .direction(wb.getBearing())
		     .build();
			 
			  mBaiduMap.setMyLocationData(locData);
			 
			 // QLog.getLogger().d(dTAG, " calculate lat lon of track endIcon............................");
			 // QLog.getLogger().d(dTAG, "  lat is: "+wb.getLatitude() +", lon is: "+wb.getLongitude());
			
		    QLog.getLogger().dLog(dTAG, TAG+" locationToTrackEnd --> draw  track end icon");
		 	setEndIcon(getLatLng(wb));
				/*float nwLat = mTrack_bean.getStartWp().getWb().getLatitude(); 
				float seLat =mTrack_bean.getMaxDistWp().getWb().getLatitude();
				float seLng = mTrack_bean.getMaxDistWp().getWb().getLongitude();
				float nwLng = mTrack_bean.getStartWp().getWb().getLongitude(); 
				
				  final int spanLatDelta = (int) (Math.abs(nwLat - seLat) * 1.1);  
				  final int spanLngDelta = (int) (Math.abs(seLng - nwLng) * 1.1);  
			      
		     mMapController.zoomToSpan(spanLatDelta,    spanLngDelta);  
		     mMapController.zoomToSpan(spanLatDelta,    spanLngDelta);  
 				 */   
			zoomToSpan(null);
//			 mMapController.animateTo(new GeoPoint(	(int) (locData.latitude * 1e6),	(int) (locData.longitude * 1e6))); 
				 	
//			 mMapView.refresh();
				/*
				mMapController.animateTo(new GeoPoint(	(int) (locData.latitude * 1e6),	(int) (locData.longitude * 1e6))); 
 			   mMapView.refresh();
 			     */ 
 			   top_dist.setText( String.format("%.2f", mTrack_bean.getDistance()/1000.00)); 
 			   top_sptime.setText(Utils.getTimeCnt(mTrack_bean.getSportTime(), false)  );
// 			   top_speed.setText("_._");
 			   if(mSpeedText!=null){
 				  top_speed.setText(mSpeedText.getText());
 				  return;
 			   }
 			   float avs =isPlayback?activity.app.getCurrentTrack().getTrackBean().getAvs():mTrack_bean.getAvs();
// 			   top_speed.setText((avs>0?String.format("%.2f",avs)+"(均速)":"--") ); 			  
 			   top_speed.setText((avs>0?String.format("%.2f",avs):"--") );
 			   
		
	 }
	
	
	/**
	 * Fits the map with the passed in points so all points are visible.
	 * @param mapController MapView controller
	 * @param points list of points you want the map to contain
	 */
  	/*private Handler handler;
	 
	protected void zoomToSpa1n()  {
		 
		handler = new Handler(){

		@Override
		public void handleMessage(Message msg) { 

			if (msg.obj != null) {  
				  
				CenterGeoPointModel centerGeoPointModel = (CenterGeoPointModel) msg.obj;  
				  
				// fit map to points  
				  
				mMapView.getController().animateTo(  centerGeoPointModel.getCenterGeoPoint());  
				  
				mMapView.getController().zoomToSpan( centerGeoPointModel.getSpanLatDelta() ,  centerGeoPointModel.getSpanLngDelta() );  
// 				mMapView.getController().zoomToSpan( centerGeoPointModel.getSpanLatDelta() ,  centerGeoPointModel.getSpanLngDelta() );  
				mMapView.refresh();  
				float nwLat = mTrack_bean.getStartWp().getWb().getLatitude(); 
				float seLat =mTrack_bean.getMaxDistWp().getWb().getLatitude();
				float seLng = mTrack_bean.getMaxDistWp().getWb().getLongitude();
				float nwLng = mTrack_bean.getStartWp().getWb().getLongitude(); 
				
				  int spanLatDelta = (int) (Math.abs(nwLat - seLat)* 1e6 * 1.1);  
			      int spanLngDelta = (int) (Math.abs(seLng - nwLng)* 1e6 * 1.1);   	
			mMapView.getController().zoomToSpan(spanLatDelta,    spanLngDelta);  
			   GeoPoint center = new GeoPoint( (int)((nwLat + seLat)* 1e6  / 2),  (int)((nwLng + seLng)* 1e6  / 2));
			   mMapController.animateTo(center);
			mMapView.refresh();
			
				   // set min and max for two points
			  
		}

		 

		} };
		
	new Thread() {

		public void run() {

		try {

		Thread.sleep(1000);

		} catch (Exception e) {

		} 
		
		  int nwLat = -90 * 1000000;
		    int nwLng = 180 * 1000000;
		    int seLat = 90 * 1000000;
		    int seLng = -180 * 1000000;
		    // find bounding lats and lngs
		    GeoPoint point;
		    for(Waypoint_bean wb:mTrack_bean.getRoadWps()){
//		    for (GeoPoint point : points) {
		    	if(wb==null)continue;
		    	point=getGeoPoint(wb);
				nwLat = Math.max(nwLat, point.getLatitudeE6()); 
				nwLng = Math.min(nwLng, point.getLongitudeE6());
				seLat = Math.min(seLat, point.getLatitudeE6());
		        seLng = Math.max(seLng, point.getLongitudeE6());
		    }
		    GeoPoint center = new GeoPoint((nwLat + seLat) / 2, (nwLng + seLng) / 2);
		    // add padding in each direction
		    int spanLatDelta = (int) (Math.abs(nwLat - seLat)   );
		    int spanLngDelta = (int) (Math.abs(seLng - nwLng)  );
		    QLog.getLogger().d(dTAG, String.format(" spanLatDelta: %s ,spanLngDelta: %s " ,  spanLatDelta,spanLngDelta  ));
		    // fit map to points 
		
	 	  Message msg = handler.obtainMessage();  
	 	  
	 	  msg.obj = new CenterGeoPointModel(spanLatDelta, spanLngDelta,   center);  
	 	   
	 	  msg.what = 1;  
	 	   
	 	  handler.sendMessage(msg);    
	 	  
	 		try {

	 			Thread.sleep(1000);

	 			} catch (Exception e) {

	 			} 
	 		  handler.sendMessage(msg); 
//	 	  
		};

		}.start();


	} 
	
	class CenterGeoPointModel {

		GeoPoint centerGeoPoint;

		int spanLatDelta;

		int spanLngDelta;

		public CenterGeoPointModel() {

		// TODO Auto-generated constructor stub

		}

		public CenterGeoPointModel(int spanLatDelta, int spanLngDelta,

		GeoPoint centerGeoPoint) {

		this.spanLatDelta = spanLatDelta;

		this.spanLngDelta = spanLngDelta;

		this.centerGeoPoint = centerGeoPoint;

		}

		public GeoPoint getCenterGeoPoint() {

		return centerGeoPoint;

		}

		public void setCenterGeoPoint(GeoPoint centerGeoPoint) {

		this.centerGeoPoint = centerGeoPoint;

		}

		public int getSpanLatDelta() {

		return spanLatDelta;

		}

		public void setSpanLatDelta(int spanLatDelta) {

		this.spanLatDelta = spanLatDelta;

		}

		public int getSpanLngDelta() {

		return spanLngDelta;

		}

		public void setSpanLngDelta(int spanLngDelta) {

		this.spanLngDelta = spanLngDelta;

		}

		}
*/
 
	
	 /*
	  * get footmark with specified levels.
	  */
	 void getFootmark(){
//		 showPic = fmLevel!=1 && tgShowPic.isChecked();
//		 mData = activity.app.getCurrentTrack().getFootmark(fmLevel, showPic);	
		 int fmLevel =showPicOnly?2:0;
		 try{
			 mData = mTrack.getFootmark(fmLevel, true);
		 }catch (Exception e){
			 Utils.logStackTrace(e, TAG);
		 }
		 if(mData==null){
			  mData = new ArrayList<Map<String, String>>();
		 }
		 addNotes(mData,fmLevel);
	 }
	 
	 void getPicUrls(){
//		 if(imgUrls==null)
//			 imgUrls= activity.app.getCurrentTrack().getPicList(); 
//			 imgUrls= mTrack.getPicList(); 
//			 ValidUrls=mTrack. getWebPicList(0,true);//TODO: to remove.
		 
		 
			 ValidUrls=mTrack.getValidPicList(true); 
			 ValidThumbUrls=mTrack.getValidPicList(false); 
		 
	 }
	 
	 
	 
	 
	 
 
	protected void showFootmarkData(boolean reLoad){
//		 if(!activity.app.playBack &&mTrack.getTrackBean().getTrackId()<=0)return;
//		 showPic = fmLevel!=1 && tgShowPic.isChecked();
//		 if( mTrack.getTrackBean().getStartWp()==null &&(chk_pici !showPic || mTrack.getTrackBean().getMdWps().size()==0 )) return;
		 if(mTrack_bean.getType()!=TrackType.GPX && mTrack.getTrackBean().getStartWp()==null &&(  mTrack.getTrackBean().getMdWps().size()==0 )) return;
//				 (fmLevel!=2 || fmLevel ==2 && showPic && mTrack.getTrackBean().getMdWps().size()==0 ))return;
		
		  
		 
		 if(reLoad)getFootmark();
			

		
		 
		 
		/* if(fmLevel==2 && mData.size()>0){
			 
			 HashMap<String, String> data = new HashMap<String, String>();
			 data.put("title","点击图片可进入大图浏览模式" ) ;
			 data.put("picUrl",null);
			 data.put("picCmnt",null);
			 mData.add(0,data);
		 }*/
		 
		 
//			 adapter = new SimpleAdapter(activity,mData);
			 
		    adapter = new QSimpleAdapter(activity,mData,R.layout.footmark_list_detail,
						new String[]{"title","uri","cmnt","time"},
						new int[]{R.id.fm_wp,R.id.fm_img,R.id.fm_imgCmnt,R.id.fm_time}); 
		    
		    adapter.setViewBinder( new ViewBinder(){
		    	@Override
				public boolean setViewValue(View view, Object data,String textRepresentation) {    		
		    			    		
		    		view.setVisibility(View.VISIBLE);
		    		if(data ==null || TextUtils.isEmpty(data.toString())){
		    			view.setVisibility(View.GONE);
		    			return true;
		    		} 
		    		 else
		            if( view instanceof com.qiyou.mb.android.utils.image.QimageView  && data instanceof String){  
		            	com.qiyou.mb.android.utils.image.QimageView iv = (com.qiyou.mb.android.utils.image.QimageView) view;    
 
//		    			iv.getLayoutParams().width= QiYouConstant.SUBNAIL_PIC_SIZE;
//		    			iv.getLayoutParams().height=iv.getLayoutParams().width*QiYouConstant.PV_INT_SCREEN_HEIGHT/QiYouConstant.PV_INT_SCREEN_WIDTH;
		            	QLog.getLogger().dLog(dTAG, " binding footmark pic: "+ data.toString());
		            	/*if(chk_pic.isChecked()) 		            	
		            		IL.DisplayImage((String) data,iv);
		            	iv.setVisibility(chk_pic.isChecked()?View.VISIBLE:View.GONE);*/
		            	IL.DisplayImage((String) data,iv);
		            	
//		                iv.setImageBitmap((Bitmap) IL.);    
		                return true;    
		            } else if(view.getId()==R.id.fm_time){
		            	
		            	view.setVisibility(View.GONE);
		    			return false;  //if return true then will no value set to the view.
		            }
		            return false;    
		        }    
		    });    
		    
		  
		    lv.setAdapter(adapter);  
		    adapter.setSelectItem(selectedFoodmarkItem);
		    lv.setSelection(selectedFoodmarkItem);
		 
//		    lv.smoothScrollToPosition(selectedFoodmarkItem);
//		    lv.smoothScrollToPositionFromTop(selectedFoodmarkItem, 50);
	 }
	 
	 
	 
	/* @Override
	  public void onListItemClick(ListView l, View v, int position, long theid) {
	    super.onListItemClick(l, v, position, theid);
	   //  activity.app.setCurrentTrack(null);
	    // Find the ID and Reference of the selected track.

	    HashMap<String,String> a=(HashMap<String, String>) l.getItemAtPosition(position);
	   
	    l.getSelectedView().setBackgroundColor(Color.DKGRAY);
	    
	   
	    
	 
	 }*/
	 
	 
	 
	    // 条目上单击处理方法.  
	    OnItemClickListener itemListener = new OnItemClickListener() {  
	        @Override  
	        public void onItemClick(AdapterView<?> parent, View view, int position,  
	                long id) {  
	        	
	        	adapter.setSelectItem(position);
 				adapter.notifyDataSetInvalidated();
 				
//	        	if(fmLevel==2 && mTrack_bean.getTrackId()>0 ){
 				if(showPicOnly && mTrack_bean.getTrackId()>0 ){
	        		getPicUrls();
//	        		imageBrower(position,imgUrls);
	        		if(ValidUrls.length>0)
//	        			imageBrower(position,ValidUrls);ValidThumbUrls
	        			imageBrower(position,ValidThumbUrls); 
	        	}
	        	
	        	  
	        }

		 
	    };  
	  
	    private void imageBrower(int position, String[] urls) {

			activity.showImagePagerFragment(position,urls);
			
			
		}
	    
	    
	    // 长按时显示的菜单  
	    @Override  
	    public void onCreateContextMenu(ContextMenu menu, View v,  
	            ContextMenuInfo menuInfo) {  
/*	        menu.setHeaderTitle("请选择操作");  
	        menu.add(0, ITEM_LOC, 0, "地图定位");
	        menu.add(0, ITEM_LOC_SAVE_SCREEN, 1, "地图截屏");  
//	        menu.add(0, ITEM_MODIFY, 1, "编辑");  
 	        menu.add(0, ITEM_DELETE, 2, "删除图片");  
 	        menu.add(0, ITEM_COMMENT, 3, "添加说明");*/
	    
	        menu.setHeaderTitle("请选择操作");  
	        menu.add(0, ITEM_LOC, 0, "地图定位");
	    	if(isWebRequest)return;
	        menu.add(0, ITEM_LOC_SAVE_SCREEN, 1, "地图截屏");  
//	        menu.add(0, ITEM_MODIFY, 1, "编辑");  
	        menu.add(0, ITEM_ADDPIC, 2, "添加图片");  
 	        menu.add(0, ITEM_DELETE, 3, "删除图片");  
 	        menu.add(0, ITEM_COMMENT, 4, "添加说明");
	    }  
	    
	    
	    /*因为在一个Activity中都使用onMenuItemSelected和onContextItemSelected时会冲突， 
	    也就是说，当有长按弹出菜单的时候，点击菜单的选项响应的是onMenuItemSelected（），如果被 
	    点击的Item Id不在 onMenuItemSelected中，事件就不会响应，此时不会再调用onContextItemSelected。 
	    这样的话，我们再onContextItemSelected中定义的事件就不会执行，这就是很多人遇到的“onContextItemSelected失效”的原因. 
	    这个时候，需要在onContextItemSelected做相应的判断，如果执行的事件不在onMenuItemSelected中，就执行onContextItemSelected。
	    http://blog.csdn.net/kavensu/article/details/8045041 
	    */  
	 
	 
	 int selectedFoodmarkItem=-1;
	    @Override
		public boolean onContextItemSelected(MenuItem item) {  
	        final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item  
	                .getMenuInfo();  
	        // info.targetView得到list.xml中的LinearLayout对象.  
//	        String stuId = ((TextView) info.targetView.findViewById(R.id.fm_wp)).getText().toString();  
//	        if (!TextUtils.isEmpty(stuId)) {  
//	            int id = Integer.parseInt(stuId);  
	        boolean isSaveScreen=false;
	        
	         final boolean isMd =info.targetView.findViewById(R.id.fm_img).getVisibility() ==View.VISIBLE;
//               isMd =!TextUtils.isEmpty(stuId);
          	 final String time = ((TextView) info.targetView.findViewById(R.id.fm_time)).getText().toString();
          	 QLog.getLogger().d(dTAG, TAG+ " time: " +time);
             String comment = ((TextView) info.targetView.findViewById(R.id.fm_imgCmnt)).getText().toString();
          	 selectedFoodmarkItem= info.position;
          	 if(TextUtils.isEmpty(time))return false;
				 String[] times=time.split(",");
				 if(times==null ||times.length==0)return false;
				 
				 final long targetTime=Long.valueOf(times[times.length-1]);    
				 final long targetCmntTime=Long.valueOf(times[0]);   
//				 final long targetTime=Long.valueOf(times[1]);   
	            switch (item.getItemId()) {  
	            case ITEM_LOC:  
//	            	if(info.position==0)break;
	                // 编辑数据  
//	                 boolean isMd;// =((ImageView) info.targetView.findViewById(R.id.fm_img)).getVisibility() ==View.VISIBLE;//   .getDrawable()==null;
//	                 stuId = ((TextView) info.targetView.findViewById(R.id.fm_wp)).getText().toString();
	            	isSaveScreen=false;
	           	 if(!TextUtils.isEmpty(time)) {
	          		 locateInMap(time,isMd,isSaveScreen);
	          	 }
	                break;  
	            case  ITEM_LOC_SAVE_SCREEN:
	            	isSaveScreen=true;
	            	btnSaveScreen.setVisibility(View.VISIBLE);
//	            	this.btnSaveScreen.setWidth(btnSaveScreen.getWidth()*2);
//	            	this.btnSaveScreen.setHeight(btnSaveScreen.getHeight()*4);
	           	 if(!TextUtils.isEmpty(time)) {
	          		 locateInMap(time,isMd,isSaveScreen);
	          	 }
	            	break; 
//	            case ITEM_MODIFY:  
//	                // 编辑数据  
//	                toastShow("编辑" + stuId);  
//	              
//	                break;  
	            case ITEM_DELETE:  
	                // 删除数据  
	            if(!isMd) return false;	
//	           	 ArrayList<Waypoint_bean> wbs = (isMd? mTrack_bean.getMdWps(): mTrack_bean.getRoadWps());
	            /*CopyOnWriteArrayList<Waypoint_bean> wbs =   mTrack_bean.getMdWps() ; */
	               ArrayList<Waypoint_bean> wbs =   mTrack_bean.getMdWps() ; 
    				QLog.getLogger().d(dTAG, TAG+" udpate wps comment, is MD? "+ isMd); 
    				
    				 for(Waypoint_bean wb :wbs){
    					 if(wb==null)continue;
    					if(isMd){
    						for(Media md: wb.getMedias()){
    							if(md.getTime()==targetTime){
    								md.setStatus(mediaStatus.DELETED);
    								break;
    							}
    						}
    					 }
//    					 else if(wb.getTime()==targetTime){
//    						wb.setComment(  inputServer.getText().toString());	 
//    						QLog.getLogger().d(dTAG, TAG+" udpate wps comment, wb comment:? "+ wb.getComment());
//    						//TODO:persist the change.
//    						break;
//    					 }  
    					 
    				 }
    				 
    				 showFootmarkData(true);
//    				 if(isMd)
//    					 mTrack.setMdWps(wbs);
//    				 else
//    					 mTrack.setBearWps(wbs);
	       			
    				 updateWPS(isMd);   
	               
	                break;  
	                
	            case ITEM_COMMENT:  
	                // 删除数据  
	               
	            	
	            	 final EditText inputServer = new EditText(activity);
	            	 inputServer.setText(comment);
	                 AlertDialog.Builder builder = new AlertDialog.Builder(activity);
	                 builder.setTitle("输入说明").setIcon(android.R.drawable.ic_dialog_info).setView(inputServer)
	                         .setNegativeButton("取消", null);
	                 builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

	                     public void onClick(DialogInterface dialog, int which) {
	                    	 
//	                    	 ((TextView) info.targetView.findViewById(R.id.fm_imgCmnt)).setText(inputServer.getText().toString()); 
	                        
	                    
	       				 
	                    	 /*CopyOnWriteArrayList<Waypoint_bean> wbs = (isMd? mTrack_bean.getMdWps(): mTrack_bean.getRoadWps());*/
	                    	 ArrayList<Waypoint_bean> wbs = (isMd? mTrack_bean.getMdWps(): mTrack_bean.getRoadWps());
		       			 
	       				 // QLog.getLogger().d(dTAG, TAG+" udpate wps comment, is MD? "+ isMd); 
	       				
	       				 for(Waypoint_bean wb :wbs){
	       					 if(wb==null)continue;
	       					if(isMd){
	       						for(Media md: wb.getMedias()){
	       							if(md.getTime()==targetTime){
	       								md.setComment(  inputServer.getText().toString());
	       								break;
	       							}
	       						}
	       					 }
	       					 else if(wb.getTime()==targetCmntTime/*targetTime*/){
	       						wb.setComment(  inputServer.getText().toString());	 
	       						QLog.getLogger().d(dTAG, TAG+" udpate wps comment, wb comment:? "+ wb.getComment());
	       						//TODO:persist the change.
	       						break;
	       					 }  
	       					 
	       				 }
	       				 
	       				 showFootmarkData(true);
//	       				 if(isMd)
//	       					 mTrack.setMdWps(wbs);
//	       				 else
//	       					 mTrack.setBearWps(wbs);
		       			 updateWPS(isMd);   
	                        
	                     }
	                 });
	                 builder.show();
	                 
	                 
	                 return false;
	                 
	            case ITEM_ADDPIC:    
	            	
	            	getWbsInBetween(time); //get the mdWp
	            	/* if(mTrack_bean.getType()!=TrackType.GPX){
	            		 locateInMap(time,isMd,isSaveScreen);
	            	 }*/
	            	
	            	if(mdWp!=null){
	            		Waypoint	wp = new Waypoint();
	            		wp.getWb().setLatitude( mdWp.getWb().getLatitude());
	            		wp.getWb().setLongitude( mdWp.getWb().getLongitude());
	            		wp.getWb().setTime(mdWp.getWb().getTime());
	            		wp.getWb().setSumDist( mdWp.getWb().getSumDist());
	            		wp.getWb().setSpeed( mdWp.getWb().getSpeed());
	            		wp.getWb().setElevation( mdWp.getWb().getElevation());
	            		mdWp=wp;
	            	}
	            	
	            	showPicPicker();
	            	 
	                 return false;
	            default:  
	                break;  
	            }  
	            
	            
	            
	       /*  boolean isMd =info.targetView.findViewById(R.id.fm_img).getVisibility() ==View.VISIBLE;
//                isMd =!TextUtils.isEmpty(stuId);
           	 String time = ((TextView) info.targetView.findViewById(R.id.fm_time)).getText().toString();
           	 QLog.getLogger().d(dTAG, TAG+ " time: " +time);
           	 if(!TextUtils.isEmpty(time)) {
           		 locateInMap(time,isMd,isSaveScreen);
           	 }
           	 selectedFoodmarkItem= info.position;*/
	            
	            
//	        }
//	        showData(false);  
	        return false; 
	    }
	    
	    /*
	    protected void showPicPicker(){
	    	Intent intent=new Intent(Intent.ACTION_GET_CONTENT);//ACTION_OPEN_DOCUMENT
        	intent.addCategory(Intent.CATEGORY_OPENABLE);
        	intent.setType("image/jpeg");
        	if(android.os.Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.KITKAT){                
        	        startActivityForResult(intent, SELECT_PIC_KITKAT);  
        	}else{              
        	        startActivityForResult(intent, SELECT_PIC); 
        	} 
	    }
	    
		
		@Override
		public void onActivityResult(int requestCode, int resultCode, Intent data) {
			
				super.onActivityResult(requestCode, resultCode, data);  
				if(requestCode ==SELECT_PIC_KITKAT ||requestCode ==SELECT_PIC) 				 
				if (resultCode == Activity.RESULT_OK) {
//					picPath = data.getStringExtra(SelectPicActivity.KEY_PHOTO_PATH);
//					Log.i(TAG, "最终选择的图片="+picPath);
//					Bitmap bm = BitmapFactory.decodeFile(picPath);
//					imageView.setImageBitmap(bm);
					 
					Uri photoUri = data.getData();
					String path= Utils.getPath(activity,photoUri);
					setMD(path,System.currentTimeMillis(),mdWp,mediaType.PIC);
					
				}
			}
		*/
		
	    void updateWPS(boolean isMd){
	    	  Intent serviceIntent = new Intent(activity, TrackDbServiceBackground.class);	   
			  serviceIntent.putExtra(QiYouConstant.EXTRA_KEY_UPDATE_WAYPOINTS, mTrack_bean.getTrackId()); 
			  serviceIntent.putExtra(QiYouConstant.EXTRA_KEY_IS_MD, isMd); 
			  activity.startService(serviceIntent);
	    }
	    
//	    public void toastShow(String text) {  
//	        Toast.makeText( activity , text, 1000).show();  
//	    }  
//	    
	     
       /* //绑定一个匿名监听器
	    OnCheckedChangeListener rdgChanged = new OnCheckedChangeListener() {
            
            @Override
            public void onCheckedChanged(RadioGroup arg0, int arg1) {
                // TODO Auto-generated method stub
                //获取变更后的选中项的ID
                int radioButtonId = arg0.getCheckedRadioButtonId();
                //根据ID获取RadioButton的实例
//                RadioButton rb = (RadioButton)activity.findViewById(radioButtonId);
                
                if(radioButtonId ==R.id.fm_rdStandard){
//                	fmLevel=0;
//                	tgShowPic.setEnabled(mTrack.getTrackBean().getStartWp()!=null);
                }else if(radioButtonId ==R.id.fm_rdDetail){
//                	fmLevel=1;    
//                	tgShowPic.setEnabled(mTrack.getTrackBean().getStartWp()!=null);
                } 
                else if(radioButtonId ==R.id.fm_rdPic){
//                	fmLevel =2; 
//                	tgShowPic.setChecked(true);
//                	tgShowPic.setEnabled(false);
                	
                }
                else if(radioButtonId ==R.id.fm_rdPicOnly){
                	fmLevel =3;
                	showPic =true;
                } 
                
                showFootmarkData(true);
                
                //更新文本内容，以符合选中项
                 
            }
        }; 
	    */
	    @Override
    	public void updateUI(Location location, Boolean isOnPause){
	    	/*if(activity.app.currentActiveFragment.equalsIgnoreCase(TrackTabs_fragment.getFTag()) &&!activity.app.playBack)  {
//	    		   top_dist.setText( String.format("%.2f", mTrack_bean.getDistance()/1000.00)); 
//	 			   top_sptime.setText(Utils.getTimeCnt(mTrack_bean.getSportTime(), false)  );
				 return;
	    	}*/
	    		
	    	super.updateUI(location,isOnPause);
    	}
	    
	    
	  /*  class myadapter extends SimpleAdapter{

				public myadapter(Context context, List<? extends Map<String, ?>> data,
						int resource, String[] from, int[] to) {
					super(context, data, resource, from, to);
					// TODO Auto-generated constructor stub
				}
				int[] colors={Color.WHITE,Color.LTGRAY};
				int selectedColor=Color.GRAY;
				@Override 
				public View getView(int position, View convertView, ViewGroup parent){
					View v =super.getView(position, convertView, parent);  
		    	    v.setBackgroundColor(colors[position%2]); 
		    	    if (position == selectItem) {
						v.setBackgroundColor(selectedColor);
					} 
					return v; 
				}
				public  void setSelectItem(int selectItem) {
					 this.selectItem = selectItem;
				}
				private int  selectItem=-1;
				
			 }*/
		 
	 @Override
	   protected void setWorkingTrack(){
		   mTrack =activity.app.getCurrentTrack();
		   mTrack_bean = mTrack.getTrackBean();
		   // QLog.getLogger().d(dTAG, " TrackId id:" +trackId +",mTrack_bean id is "+ mTrack_bean.getTrackId());
	   }
			 
			 
	
	 private List<Waypoint_bean> getWbsInBetween(String time){
		 String[] times=time.split(","); 
		 long startTime=Long.valueOf(times[0]);
		 long endTime =times.length>1? Long.valueOf(times[1]):startTime;
	     // QLog.getLogger().d(dTAG, " startTime:" +Utils.getFormatedTime(startTime) +",endTime id is "+ Utils.getFormatedTime(endTime));

		 
		 List<Waypoint_bean> bwbs =new ArrayList<Waypoint_bean>();
		 for(Waypoint_bean wb:mTrack_bean.getTrkseg()){
			 if(wb==null)continue;
			 
			 if(startTime==endTime && wb.getTime()>= endTime){
				 bwbs.add(wb);
				 break;
			 }else
			 if(endTime>startTime && wb.getTime()<= endTime && wb.getTime()>=startTime){
				 bwbs.add(wb);
			     // QLog.getLogger().d(dTAG, " wb.getTime():" +Utils.getFormatedTime(wb.getTime()));
			 }
		 }
		 
		 if(bwbs.size()>0){
			 mdWp =new Waypoint();
			 mdWp.setWb(bwbs.get(bwbs.size()-1));
		 }
		 return bwbs;
	 }
	 
			 
	 protected void locateInMap(String time, boolean isMd,boolean isSaveScreen){
				 
				 if(mMapView==null)return;
				 
				 if(TextUtils.isEmpty(time))return;
				/* String[] times=time.split(","); 
				 long startTime=Long.valueOf(times[0]);
				 long endTime =times.length>1? Long.valueOf(times[1]):startTime;
				  QLog.getLogger().d(dTAG, " startTime:" +Utils.getFormatedTime(startTime) +",endTime id is "+ Utils.getFormatedTime(endTime));
*///				 int turnFlag=-100; 
				 Location loc = null;	
				  
//				 ArrayList<Waypoint_bean> wbs =isMd?mTrack_bean.getMdWps():mTrack_bean.getRoadWps();
 
				/*  List<Waypoint_bean> bwbs =new ArrayList<Waypoint_bean>();
				 for(Waypoint_bean wb:mTrack_bean.getTrkseg()){
					 if(wb==null)continue;
					 
					 if(startTime==endTime && wb.getTime()>= endTime){
						 bwbs.add(wb);
						 break;
					 }else
					 if(endTime>startTime && wb.getTime()<= endTime && wb.getTime()>=startTime){
						 bwbs.add(wb);
					     QLog.getLogger().d(dTAG, " wb.getTime():" +Utils.getFormatedTime(wb.getTime()));
					 }
				 }*/
				 
				 List<Waypoint_bean> bwbs =getWbsInBetween(time);
				 
				 Location endLoc = null;
				 if(bwbs.size()>=2){
					 
					 drawBearLine(bwbs);
					 
					 endLoc= new Location(QiYouConstant.LOCATION_RD_LOC);					 
					 endLoc.setLatitude(Utils.getbdLat(bwbs.get(bwbs.size()-1).getLatitude(),bwbs.get(bwbs.size()-1).getLongitude()));
					 endLoc.setLongitude(Utils.getbdLon(bwbs.get(bwbs.size()-1).getLatitude(),bwbs.get(bwbs.size()-1).getLongitude()));
					 endLoc.setBearing(bwbs.get(bwbs.size()-1).getBearing()); 
					 endLoc.setAccuracy(bwbs.get(bwbs.size()-1).getAccuracy());
					 endLoc.setSpeed(1);
				 }
				 else if(bwbs.size()==0) 
				 return;
//				 screenShotDist =(int) bwbs.get(bwbs.size()-1).getSumDist();
//				 mdWp =new Waypoint();
//				 mdWp.setWb(bwbs.get(bwbs.size()-1));
//				 QLog.getLogger().d(dTAG, TAG+String.format(" get start rd waypoint distanceis %s",screenShotDist));
				 loc = new Location(QiYouConstant.LOCATION_RD_LOC);
				 loc.setLatitude(Utils.getbdLat(bwbs.get(0).getLatitude(),bwbs.get(0).getLongitude()));
				 loc.setLongitude(Utils.getbdLon(bwbs.get(0).getLatitude(),bwbs.get(0).getLongitude()));
//				 loc.setBearing(bwbs.get(0).getBearing()); 
				 loc.setAccuracy(bwbs.get(0).getAccuracy());
				 loc.setSpeed(1);
				 
				 
 				 TabHost host = (TabHost)vContainer.findViewById(R.id.tabhost);
 				 host.setCurrentTabByTag(tabMap);				 
 				 canLocationMap=true; 
				
				    
				 
//				   	GeoPoint sgp =new GeoPoint((int) (loc.getLatitude()*1E6), (int) (loc.getLongitude()*1E6));
 			
 				    LatLng sgp =new LatLng(  loc.getLatitude() , loc.getLongitude() );
 				
				   	setGeoIcon(sgp,bearStartMarker,R.drawable.icon_bstart);
				
				   	String[] times=time.split(","); 
					 long startTime=Long.valueOf(times[0]);
					 long endTime =times.length>1? Long.valueOf(times[1]):startTime;
					 
				    if(startTime==endTime )
				   		 locationInMap(loc);
				    
					if(endLoc!=null){
//						GeoPoint egp =new GeoPoint((int) (endLoc.getLatitude()*1E6), (int) (endLoc.getLongitude()*1E6));
	 				    LatLng egp =new LatLng(  endLoc.getLatitude() , endLoc.getLongitude() );

						setGeoIcon(egp,bearEndMarker,R.drawable.icon_bend);
						
						locationInMap(endLoc);			
					}
				   	
		/*		  	if(gpFmPointsOverlay==null)
				  		gpFmPointsOverlay =new GraphicsOverlay(mMapView);				  	
				   	gpFmPointsOverlay.setData(drawRoadbookPoint(gp,turnFlag));				  
				  	if(!mMapView.getOverlays().contains(gpFmPointsOverlay))
						mMapView.getOverlays().add(gpFmPointsOverlay);*/ 
				  		 
				  	
				   
				    
//				    mMapView.getCurrentMap();	
				   if(isSaveScreen) {
					   Toast.makeText(activity, "提示：截图前，请先调整地图到所需比例、角度，点击'截屏'按钮。", Toast.LENGTH_LONG).show();
//					   saveScreen();
				   }
			 }
			 
	 	 
	 
	 private void drawBearLine(final  List<Waypoint_bean> al){
		 
		/* if(gpBearLinesOverlay==null){
			 gpBearLinesOverlay= new GraphicsOverlay(mMapView);
		 }else{
			 gpBearLinesOverlay.getAllGraphics().clear();
		 }
		  mMapView.getOverlays().remove(gpBearLinesOverlay);*/
		 new Thread(){
		        @Override
				public void run() { 
		        	
		        	boolean isAsist=!isPlayback && mTrack_bean.getType()!=TrackType.GPX;
			 		 if(al.size()<=2) return; 
					 ArrayList<LatLng> gpal= new ArrayList<LatLng>();	
					 long lastTime =0;
					 if(gpBearLinesOverlay ==null){
						 gpBearLinesOverlay = new LineOverlay(mBaiduMap);
					 }
					 gpBearLinesOverlay.removeFromMap();
					 gpBearLinesOverlay.getOverlayOptions().clear();
//			    	 synchronized(al)
					 {
				    	 for(Waypoint_bean wb:al){  //java.util.ConcurrentModificationException @Synchronized//	there is lock conflict with playback service.	use clone to resove.
				    		 
					       	if(wb ==null)continue;
//					       	if(wb.getRoadBear()==0)continue; //to only draw bearing points
//					       	QLog.getLogger().d(dTAG,TAG+" time between two waypoints:"+ (wb.getTime()-lastTime));
					       	    if(wb.getTime()<lastTime){
					       	    	Log.e(dTAG,TAG +" duplicated wp dropped in drawring track.");
					       	    	continue;
					       	    }
								double mLat =  Utils.getbdLat(wb.getLatitude(), wb.getLongitude());
								double mLon =  Utils.getbdLon(wb.getLatitude(), wb.getLongitude()); 
//								if(mTrack.isLushu()){
//									mLat=Utils.getggLat(mLat, mLon);
//									mLon=Utils.getggLon(mLat, mLon);
//							        mLat =  Utils.getbdLat(mLat, mLon);
//								    mLon =  Utils.getbdLon(mLat, mLon);  
//								}
							/*	int lat = (int) (mLat*1E6);
							   	int lon = (int) (mLon*1E6);   
							   	GeoPoint gp =new GeoPoint(lat, lon);*/
							   	LatLng gp = new LatLng(mLat,mLon);
					 		    if(lastTime >0 && wb.getTime() -lastTime > QiYouConstant.MAX_GPS_SPAN*60){	
//							    	  QLog.getLogger().d(dTAG,TAG + " QiYouConstant.MAX_GPS_SPAN:"+QiYouConstant.MAX_GPS_SPAN   
//							    									+ "QiYouConstant.MAX_GPS_SPAN*60:"+QiYouConstant.MAX_GPS_SPAN*60  
//							    			  						+ "QiYouConstant.MAX_GEO_TIME:"+QiYouConstant.MAX_GEO_TIME
//							    			  						+" time between two waypoints:"+ (wb.getTime()-lastTime));
//					 		    	gpBearLinesOverlay.setData(drawLine(getGPs(gpal),isAsist));
// 					 		    	mBaiduMap.addOverlay(drawLine( gpal,isAsist));
 					 		    	gpBearLinesOverlay.getOverlayOptions().add(drawLine( gpal,isAsist));
							    	gpal =  new ArrayList<LatLng>(); 
							    	gpal.add(gp);
	 
							    } else
							    	gpal.add(gp); 
							   	
							   lastTime =wb.getTime(); //to only draw bearing points
								
						} 
				    	 
//				    	 mBaiduMap.addOverlay(drawLine( gpal,isAsist));
				    	 gpBearLinesOverlay.getOverlayOptions().add(drawLine( gpal,isAsist));
			    	   }
					 gpBearLinesOverlay.addToMap();
//					 gpBearLinesOverlay.setData(drawLine(getGPs(gpal),isAsist));  

					 //			    	  QLog.getLogger().d(dTAG,TAG+" Draw track finished, it is playback track?  " + drawPlayBackTrack);
			    	  
//					  mMapView.getOverlays().add(gpBearLinesOverlay);
//			    	  mMapView.refresh(); 
			 	     //finished the track line, set the flag to true;
		    }}.start(); 
	 }
	 
			 
		@Override	 
		protected void showCharts( int chartType){
			    	if(mTrack ==null)return;
					 ArrayList<Track> trs = new ArrayList<Track>();	  
//			    	 String[] tmp =new String[]{};
//					if(TextUtils.isEmpty(mTrack.getTrackBean().getName()))mTrack.getTrackBean().setName("本次");
			    	 trs.add(mTrack );  
			    	 int llid=0;
				   	 if(chartType ==0){ 
				   		llid=isShowCharts?R.id.td_charts_speedkm:R.id.td_charts_1;
				   		llcharts = (LinearLayout)vContainer.findViewById(llid);
				   		getDistSpeedKmChart(trs);
//				   		return;
				   	 }
//			    	 geEleCharts(trs);
//			    	 geEledBarChart(trs);
//			    	 geEleDChart(trs);
				   	 else if(chartType ==1){
				    
			   			 llid=isShowCharts?R.id.td_charts_ele:R.id.td_charts_2;
				   	 
				   		llcharts = (LinearLayout)vContainer.findViewById(llid);
				   		getDistEleChart(trs);
//				   		return;
				   	}
				   	 else	if(chartType ==2){
				   		 
				   	     llid=isShowCharts?R.id.td_charts_speed:R.id.td_charts_3;
				   		
				   		llcharts = (LinearLayout)vContainer.findViewById(llid);
				   		getDistSpeedChart(trs);
//				   		return;
				   	}
				   	 
				   	 
				  /* 	 if(llcharts!=null){
//				   	case R.id.td_btnShowChartSpeed1:{  showSpeedKmChart(1)   ;break;}
//		    		case R.id.td_btnShowChartKm1:{  showSpeedKmChart(2)   ;break;}
//		    		case R.id.td_btnShowChartEle1:{  showSpeedKmChart(3)   ;break;}
				   		 final int chartToShow=chartType==0?2:chartType==1?3:2;
				   		llcharts.setOnClickListener(new View.OnClickListener() {

				            public void onClick(View v) { 
				            	 showSpeedKmChart(  chartToShow);  				            	
				            }
				        });
				   		
				   	 }*/

				   		 
				  
			    }
			    
			    void getDistSpeedChart(ArrayList<Track> trs){
			    	if(mTrack==null) return; 
		 	    	geChart(trs,new DistSpeedChart());
			    }
			    
			    void getDistSpeedKmChart(ArrayList<Track> trs){
			    	if(mTrack==null) return; 
		 	    	geChart(trs,new DistKmSpeedChart());
			    }
			    
			    void getDistEleChart(ArrayList<Track> trs)
			    {
			    	if(mTrack==null) return; 

//		 	    	geChart(trs,new  DistEleChart());
			    	geChart(trs,new  DistEleChartNoDown());//no ele down 
			    
		 		 	 
			    }
			    /*void geBarCharts(ArrayList<Track> trs)
			    { 
			    	if(mTrack==null) return; 
		 	    	geChart(trs,new DistanceSpeedBarChart());
			    }
			    
			    void getDistCharts(ArrayList<Track> trs)
			    {
			    	if(mTrack==null) return; 
			    	geChart(trs,new DistanceChart());
		 		 	 
			    }
			    
			    void geEleCharts(ArrayList<Track> trs)
			    {
			    	if(mTrack==null) return; 

		 	    	geChart(trs,new EleChart());
			    
		 		 	 
			    }
			   
			    void geEleDChart(ArrayList<Track> trs)
			    {
			    	if(mTrack==null) return; 
		 	    	geChart(trs,new EleDChart());
		 		 	 
			    }
			    void geEledBarChart(ArrayList<Track> trs)
			    {
			    	if(mTrack==null) return; 
		 	    	geChart(trs,new EledBarChart());
		 		 	 
			    }*/
			    void geChart(ArrayList<Track> trs,AbstractChart chart){
			    	
			    	if(mTrack==null) return;	 
			    	chart.setTrs(trs); 
			    	showCharts(chart.getChartView(activity));
		 		 	 
			    }
			    
			    
			    void showCharts(View v)
			    {  
			    	try{
			    		if(llcharts==null)return;
				    	if(llcharts.getChildCount()>0)
				    		llcharts.removeAllViews(); //this is must.
 		 			 int height=500;
 		 			 height =QiYouConstant.PV_INT_SCREEN_WIDTH/2;
//		 			int height=LayoutParams.MATCH_PARENT;
		 			 v.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,height)); //set the layout, or will not show out 
		 		     llcharts.addView(v);
		 			}catch (Exception e)
		 			{
		 				Utils.logStackTrace(e, TAG);
		 			}
			    	 
			    }
			
			  
		 
		@Override	 
		void showTabs(boolean isVisible ){ 
/*			
			if(trackId==0)return;
			if(tabhost==null)return;
			
			String title=isVisible?tabData:trackId>0?"数据加载中。。。":tabData;//"定位成功后将自动开始";
			
			TextView textview = (TextView)tabhost.getTabWidget().getChildAt(0).findViewById(android.R.id.title);			
// 			textview.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
			textview.setText(title); 
			int visible = isVisible?View.VISIBLE:View.GONE;
			for(int i=1;i<tabhost.getTabWidget().getChildCount();i++)
		    	 tabhost.getTabWidget().getChildAt(i).setVisibility(visible);
			
			if(isPlayback){ //hide the edit tab for playback
				tabhost.getTabWidget().getChildAt(tabhost.getTabWidget().getChildCount()-1).setVisibility(View.GONE);
			}
			
			if(trackId==0){ //show map while connecting to GPS.
				 tabhost.getTabWidget().getChildAt(2).setVisibility(View.VISIBLE);
//				 textview = (TextView)tabhost.getTabWidget().getChildAt(2).findViewById(android.R.id.title);			
//				 textview.setText(""); 
			}*/
			
		}
			  

		 @Override
		 protected  void playBack()
		    {
			 activity.app.playBack=true;
		    	
		     try{
		    	 
		    	boolean canNotPlay = activity.app.currentTrack!=null 
							&& activity.app.recordingTrack!=null
							&& activity.app.recordingTrack.getTrackBean().getTrackId() 
								== activity.app.currentTrack.getTrackBean().getTrackId()
							 &&	activity.app.recordingTrack.getTrackBean().getStatus()!=TrackStatus.FINISHED
						  ;
		       	 
		    	if(!canNotPlay) 

		        	new Thread(){
		    			
		    			@Override
		    			public void run() {
		    				activity.startTrackPlayBack(trackId);		
		    		    	 
		    			}}.start(); 
		    			
		    		
		     }catch(NumberFormatException  e)
		     {
		    	 Log.e(TAG,trackId + " is not a playback able track.Pls make sure it is a valid track.");
		     }
		     
		     
		    }		 
			 
			 
			 
			 
		 @Override
		 protected void setMD(String picName,long time,Waypoint wp,mediaType mdType){
			 super.setMD(picName,time,wp,mdType);
// 			 chk_pic.setEnabled(true);
			 
			 if(isShowCharts){
				 chk_showChats.setChecked(firstLoad);
			 }
			 if(mTrack_bean.getType()!=TrackType.GPX){
				 chk_pic.setChecked(true);
			 }
			 
			 showFootmarkData(true);
			 
			/* if(screenShotDist>0){
				 screenShotDist=0;
				 return;
			 }*/
			 
			 if(wp!=null &&wp.getWb().getMedias().size()==0){
				wp=null;
				 return;
			 }
			 if(mTrack_bean.getStatus()!=TrackStatus.RECORDING){
    			 redrawTrack();
    		 }
			 if(mTrack_bean.getType()==TrackType.GPX){ return;}
			 
			 //for camer a new pic
			  selectedFoodmarkItem =adapter.getCount()-1; 
			  adapter.setSelectItem(selectedFoodmarkItem);
			  lv.setSelection(selectedFoodmarkItem);
				 
			  
			 
			 
		 }
			 
		 protected void setStaticMap(){
			 /*if(fmMapImg==null)return;
			 IL.DisplayImage(mTrack.getStaticMap(),fmMapImg); 
			   if(mTrack.isStaticMapExist()){
		    		 IL.DisplayImage(mTrack.getStaticMap(),fmMapImg); 
		    	 }
		    	 else
		    		 fmMapImg.setVisibility(View.GONE);*/
	            
		   }
	 
		 protected  CheckBox.OnCheckedChangeListener gpxCheckboxListener =new  CheckBox.OnCheckedChangeListener(){
			    @Override
				public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
			    	QLog.getLogger().d(dTAG, "gpx_checkbox checked?" +chk_showGpx.isChecked());
					 if(mTrack_bean==null || mTrack_bean.getTrackId()<=0)return;
					 activity.app.setGpxShowingTracks(String.valueOf( mTrack_bean.getTrackId()), chk_showGpx.isChecked()); 
					 if(chk_showGpx.isChecked() &&mTrack!=null){
						 activity.app.getTrackCache().put(Integer.valueOf(mTrack_bean.getTrackId()), mTrack);
					 } 
			  }
	 
		   };
		
   @Override
	 protected void setTrackDesc(){	 
	 	super.setTrackDesc();
	 	
	 	      showCategoryList(cateLv,textContainer);
	 	     if(btnNewCate!=null)
	 	      this.btnNewCate.setEnabled(trackId>0);
	 	    if(btnSave!=null)
	 	      this.btnSave.setEnabled(trackId>0);
	 	      td_btn_export.setEnabled(trackId>0);
	 	      
	 	 }

	 @Override
		public void onResume() { 
		 	activity.app.isRouting=false;	 
			super.onResume();			 
			tabOnresume();
		}
	 
	 void tabOnresume(){
//		   	activity.app.currentActiveFragment =getFTag();   
		   	switchButtonStatus();
		   	showMapViews();
//		   	mTrack_bean = activity.app.getCurrentTrack().getTrackBean(); 
		    setWorkingTrack();
//		   	drawTrack=true;
//		   	drawTrack(); 
//		    mMapView.onResume();
//		    if(txtNotice!=null)
//		    	txtNotice.setVisibility((mTrack_bean==null||mTrack_bean.getTrackId()>0)?View.VISIBLE:View.GONE);
		   
//			   editNewCate.setSelection(0);
//		    redrawTrack();
		    
	 }
	 
	 @Override
		public void onPause() {
		 
			super.onPause();
		}
	 @Override
		public void onDestroy() {  
			super.onDestroy();
		}
	 
	 
	 
	 protected void updateGpxEle(){
		 
		 int minDist=200;
		 
		 int size =(int) ((mTrack_bean.getDistance())/minDist);
		 if(size>50)
			 size=50;
		 
		 String gpoints=Utils.buildPathPoints(mTrack_bean.getTrkseg(),mTrack,false,size);
		 
		 if(TextUtils.isEmpty(gpoints))return ;
			
			/*
			https://maps.googleapis.com/maps/api/elevation/json
			?locations=39.7391536,-104.9847034|36.455556,-116.866667&key=API_KEY
			 *  
			 */
		 
			 
			String eleUrl="https://maps.googleapis.com/maps/api/elevation/json?locations=";
			
			eleUrl+=gpoints+"&key="+QiYouConstant.GG_API_KEY+"&sensor=true";
			
//			eleUrl="https://maps.googleapis.com/maps/api/elevation/json?locations=39.7391536,-104.9847034|36.455556,-116.866667&key="+QiYouConstant.GG_API_KEY;
//			eleUrl="http://maps.googleapis.com/maps/api/elevation/json?key=AIzaSyBAey0WNbuvc2WeEbCOsGEpp2WW0iw77u0&sensor=true";
 			httpsGet(null,eleUrl);
			  /*
			HttpResponse response =activity.app.httpsExecute(eleUrl);
			
			
			if(response==null)return;
			
			if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){
				 QLog.getLogger().dLog(dTAG, TAG, " not get result from googleapi for ele.");
				return;
			}
			  try {
				String strResult = EntityUtils.toString(response.getEntity());
				 QLog.getLogger().dLog(dTAG, TAG, " get result from googleapi for ele:"+strResult);
				GoogleEleResult ger = null;
				
				Gson gson = new Gson();		
				try{
					if(!TextUtils.isEmpty(strResult)){
						ger = gson.fromJson(strResult, GoogleEleResult.class); 
					}
				}catch(Exception e){					
					Utils.logStackTrace(e, dTAG); 
					return;
				}
				int lasti=0;
				Waypoint_bean wb;
				for(LocationEle le:ger.getResults()){
					
					while(lasti<mTrack_bean.getTrkseg().size()){						
						wb =mTrack_bean.getTrkseg().get(lasti);
						if(wb.getLatitude()==le.getLocation().getLat() &&
								wb.getLongitude()==le.getLocation().getLon()){
							wb.setElevation((float) le.getElevation());
							
							 QLog.getLogger().dLog(dTAG, TAG," lasti, "+lasti+ "，set ele:"+le.getElevation());
						break;	
						}
						lasti++;
					}
				} 
				
			
				
			 	
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} */
		  
	 }
	 
	 
	 
	 
		/*
	 {
	  "status": "OK",
	  "results": [ {
	    "location": {
	      "lat": 39.7391536,
	      "lng": -104.9847034
	    },
	    "elevation": 1608.8402100
	  }, {
	    "location": {
	      "lat": 36.4555560,
	      "lng": -116.8666670
	    },
	    "elevation": -50.7890358
	  } ]
	}
	
	
	
	{ "location": { "lat": 39.7391536,"lng": -104.9847034  }, "elevation": 1608.8402100 }, */
/*	String status = allData.getString("status");
	if ("OK".equals(status)) {
	JSONArray jsonArr = allData.getJSONArray("results");
	for (int i = 0; i < jsonArr.length(); i++) {
	Map<String, String> map = new HashMap<String, String>();
	JSONObject jsonObj = jsonArr.getJSONObject(i);
	map.put("address", jsonObj.getString("formatted_address"));
	map.put("icon", jsonObj.getString("icon"));
	map.put("name", jsonObj.getString("name"));
	System.out.println("查询得到的数据address=" + jsonObj.getString("formatted_address"));
	JSONObject locationJsonObj = jsonObj.getJSONObject("geometry").getJSONObject("location");
	map.put("latitude", locationJsonObj.getString("lat"));
	map.put("longitude", locationJsonObj.getString("lng"));
	listMaps.add(map);
	}
	}*/
	 
	 
	  
/* 
 
@TargetApi(Build.VERSION_CODES.KITKAT)
public void genPDF(){
 
	int sysVersion = VERSION.SDK_INT;
	
	if(sysVersion<19)return;
	
		// create a new document
		 PdfDocument document = new PdfDocument();

		 // crate a page description
		 PageInfo pageInfo = new PageInfo.Builder(new Rect(0, 0, 100, 100), 1).create();

		 // start a page
		 Page page = document.startPage(pageInfo);

		 // draw something on the page
		 View content = getContentView();
		 content.draw(page.getCanvas());

		 // finish the page
		 document.finishPage(page);
//		 . . .
//		 // add more pages
//		 . . .
		 // write the document content
		 document.writeTo(getOutputStream());

		 //close the document
		 document.close();
	// Create a shiny new (but blank) PDF document in memory
				PdfDocument document = new PdfDocument();

				// crate a page description
				PageInfo pageInfo = new PageInfo.Builder(300, 300, 1).create();

				// create a new page from the PageInfo
				Page page = document.startPage(pageInfo);

				// repaint the user's text into the page
//				View content = findViewById(R.id.textArea);
				lv.draw(page.getCanvas());
				// do final processing of the page
				document.finishPage(page);
			 
		 
	 }
	 */
	 

public void createPDF()
{
 	/*Document doc = new Document();
    
	
	 try {
		 	String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/droidText";
		 	 
		 	File dir = new File(path);
		        if(!dir.exists())
		        	dir.mkdirs();

		    Log.d("PDFCreator", "PDF Path: " + path);
		    
		        
		    File file = new File(dir, "sample.pdf");
		    FileOutputStream fOut = new FileOutputStream(file);
 
    	 	PdfWriter.getInstance(doc, fOut);
             
            //open the document
            doc.open();
            
            
            Paragraph p1 = new Paragraph("Hi! I am generating my first PDF using DroidText");
            Font paraFont= new Font(Font.COURIER);
            p1.setAlignment(Paragraph.ALIGN_CENTER);
            p1.setFont(paraFont);
            
             //add paragraph to document    
             doc.add(p1);
            
             Paragraph p2 = new Paragraph("This is an example of a simple paragraph");
             Font paraFont2= new Font(Font.COURIER,14.0f,Color.GREEN);
             p2.setAlignment(Paragraph.ALIGN_CENTER);
             p2.setFont(paraFont2);
             
             doc.add(p2);
             
             ByteArrayOutputStream stream = new ByteArrayOutputStream();
             Bitmap bitmap = BitmapFactory.decodeResource(activity.getBaseContext().getResources(), R.drawable.ic_launcher);
             bitmap.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
             Image myImg = Image.getInstance(stream.toByteArray());
             myImg.setAlignment(Image.MIDDLE);
            
             //add image to document
             doc.add(myImg);
            
             //set footer
             Phrase footerText = new Phrase("This is an example of a footer");
             HeaderFooter pdfFooter = new HeaderFooter(footerText, false);
             doc.setFooter(pdfFooter);
            

            
     } catch (DocumentException de) {
             Log.e("PDFCreator", "DocumentException:" + de);
     } catch (IOException e) {
             Log.e("PDFCreator", "ioException:" + e);
     } 
	 finally
     {
             doc.close();
     }*/
   
}     





 
@Override	 
void processTabQuery(){
	switchTabOptions(currentTab);
	if (isBBSQuery){
		super.processTabQuery();
	}
	
}  //截断 weblist 

	 
	 
	 
	 
	 
	 
	 
}
