package com.qiyou.mb.android.ui;

 
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Instrumentation;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.Typeface;
import android.location.Location;
import android.media.AudioManager;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ShareActionProvider;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult.AddressComponent;
import com.qiyou.mb.android.Activity_qiyouBase;
import com.qiyou.mb.android.QiYouApplication;
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.Activity_bean;
import com.qiyou.mb.android.beans.basic.GEOaddress;
import com.qiyou.mb.android.beans.basic.Group_bean;
import com.qiyou.mb.android.beans.basic.Note;
import com.qiyou.mb.android.beans.basic.NoteMessage;
import com.qiyou.mb.android.beans.basic.StatTrack;
import com.qiyou.mb.android.beans.basic.User_bean;
import com.qiyou.mb.android.service.LocationService;
import com.qiyou.mb.android.service.QNaviSvc;
import com.qiyou.mb.android.ui.charts.DistanceChart;
import com.qiyou.mb.android.ui.fragments.ActivityDetail;
import com.qiyou.mb.android.ui.fragments.ActivityHome;
import com.qiyou.mb.android.ui.fragments.GpxDetail_fragment;
import com.qiyou.mb.android.ui.fragments.GroupDetail;
import com.qiyou.mb.android.ui.fragments.GroupHome;
import com.qiyou.mb.android.ui.fragments.ImageDetailFragment;
import com.qiyou.mb.android.ui.fragments.ImagePager_fragment;
import com.qiyou.mb.android.ui.fragments.LocationPickerFragment;
import com.qiyou.mb.android.ui.fragments.LoginFragment;
import com.qiyou.mb.android.ui.fragments.NoteDetail;
import com.qiyou.mb.android.ui.fragments.NoteList;
import com.qiyou.mb.android.ui.fragments.NoteNew;
import com.qiyou.mb.android.ui.fragments.OfflineMaps_fragment;
import com.qiyou.mb.android.ui.fragments.Playback_fragment;
import com.qiyou.mb.android.ui.fragments.RegistFragment;
import com.qiyou.mb.android.ui.fragments.Route_fragment;
import com.qiyou.mb.android.ui.fragments.TrackDetail_fragment;
import com.qiyou.mb.android.ui.fragments.TrackList_fragment;
import com.qiyou.mb.android.ui.fragments.TrackStatics_fragment;
import com.qiyou.mb.android.ui.fragments.TrackTabs_fragment;
import com.qiyou.mb.android.ui.fragments.Track_fragment;
import com.qiyou.mb.android.ui.fragments.UserDetails;
import com.qiyou.mb.android.ui.fragments.UserHome;
import com.qiyou.mb.android.ui.fragments.WebList_fragment;
import com.qiyou.mb.android.utils.DummyTabContent;
import com.qiyou.mb.android.utils.Utils;
import com.qiyou.mb.android.utils.base.IlocationFragment;
import com.qiyou.mb.android.utils.enums.TrackStatus;
import com.qiyou.mb.android.utils.enums.TrackType;
import com.qiyou.mb.android.utils.log.QLog;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.umeng.analytics.MobclickAgent;
import com.umeng.analytics.MobclickAgent.UMAnalyticsConfig;
import com.umeng.socialize.bean.RequestType;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.QZoneShareContent;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.umeng.socialize.weixin.media.CircleShareContent;
import com.umeng.socialize.weixin.media.WeiXinShareContent;
import com.umeng.message.PushAgent;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
 

//@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
//@SuppressLint("NewApi")
@SuppressLint("NewApi")
public class MainActivity extends Activity_qiyouBase {
	public static final String TAG ="com.qiyou.MainActivity";
	public static final String dTAG ="com.qiyou";
	
    final UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.share",RequestType.SOCIAL);

	protected Handler handler = new Handler();
//	Nav_fragment  nav_fragment;
	public StatTrack statTrack;
	LocationSendBackReceiver receiver;
	IntentFilter filter; 
//	public boolean isShowingInput=false;
	public boolean isMapActive=false;
	public boolean is4Login=false;
//	final UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.share");
	//found address
	public  AddressComponent addressComponent;
	public String sharedAddressUrl;
	public GEOaddress geoAddress;
	public int addressTextId;
	public float latToshow;
	public float lngToshow;
	public Tencent  mTencent ;
	
	public boolean isNeedFresh = false;
//	public Activity_bean currentAcitiviy;
//	public Group_bean currentGroup;
//	public User_bean currentUser;
 
	@Override
	protected void onCreate(Bundle savedInstanceState) { 
//		startWelcome();
//		updateActionBar(false);
	 	   if (QiYouConstant.STRICT_MODE){
			    
	         StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
	         .detectLeakedSqlLiteObjects()
	         .detectLeakedClosableObjects()
	         .penaltyLog()
	         .penaltyDeath()
	         .build());
	    }    
	 	
//		app = (QiYouApplication) getApplication();
		super.onCreate(savedInstanceState); 
		 long startTime =System.currentTimeMillis();
		
//		Intent it = new Intent(MainActivity.this,Welcome.class);
//   		 startActivity(it);
		 
		 
		 
		// //			 QLog.getLogger().d(dTAG,TAG+" MainActivity.onCreate()  called.  time: " + startTime);
		setContentView(R.layout.activity_main_new);
	   this.initialTabs(); 
	 
	/*	app.restoreLastTracking();
		//			 QLog.getLogger().d(dTAG, TAG+"@@@@@@ activity.app.startTime  : " +app.startTime);		    
		app.getStaticsTracks();//异步获取track statistics 
		//TODO: review and to add waiting progress bar for the statistics,lasttrack,etc loading done. 
		app.initMapview(this);
		app.startNetworkLocationRequest(true);	
		*/
//		app.initialApplication();
	 
//		  app.initMapview(this);
		  filter = new IntentFilter(QiYouConstant.ACTION_NEW_LOCATION_GETBACK);  
	       filter.addCategory(Intent.CATEGORY_DEFAULT);  
	       receiver = new LocationSendBackReceiver();  
//	       registerReceiver(receiver, filter); 
	       
 
	    
		// //			 QLog.getLogger().d(dTAG,TAG+" MainActivity.onCreate(). cost time: " + (System.currentTimeMillis() - startTime));
		 
//	   onReceive(getIntent());
	 
		app.initialImageLoader();
		
		getScreenSize();
	 
		checkUpdate(true); 
		
		
		//-----umeng

		/*// 设置分享内容
		mController.setShareContent("友盟社会化组件（SDK）让移动应用快速整合社交分享功能，http://www.umeng.com/social"); 
		// 设置分享图片, 参数2为图片的url地址
		mController.setShareMedia(new UMImage(this, "http://www.umeng.com/images/pic/banner_module_social.png"));
		
		mController.getConfig().removePlatform( SHARE_MEDIA.RENREN, SHARE_MEDIA.DOUBAN);*/
		initialUMSocialService();
		setVolume();
		initialQQAuth20();
		
	}
		 
	 
//	@Override
//	public View  onCreateView(View parent,String name, Context context,AttributeSet attrs){
//		return parent;
//		 
//	  }
	
	private void initialQQAuth20(){
		mTencent = Tencent.createInstance(QiYouConstant.TENCENT_APP_ID, this.getApplicationContext());
		mTencent.setOpenId(QiYouConstant.PV_OPEN_ID);
		mTencent.setAccessToken(QiYouConstant.PV_ACCESS_TOKEN, String.valueOf(app.getTokenExpiresIn()));
	}
	
//	 String TENCENT_APPID="1104563148";
 
	private void initialUMSocialService(){
	    com.umeng.socialize.utils.Log.LOG = QiYouConstant.DEVELOPER_MODE; 
        String key ="550aa4e4fd98c5a25c000284" ; //old "4eaee02c527015373b000003"
	   if (!QiYouConstant.DEVELOPER_MODE){
		   UMAnalyticsConfig config = new  UMAnalyticsConfig(this,key , "i7lv");
		   MobclickAgent. startWithConfigure(config);
		   MobclickAgent.openActivityDurationTrack(false);
	   }

		PushAgent.getInstance(this).onAppStart(); //push start

        mController.getConfig().removePlatform(SHARE_MEDIA.DOUBAN, SHARE_MEDIA.RENREN);
        //分享给QQ好友
        UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(this, QiYouConstant.TENCENT_APP_ID, "bB5QKjxU4MpHoCq0");
        qqSsoHandler.addToSocialSDK();  
        
        //分享到QQ空间
        QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(this,  QiYouConstant.TENCENT_APP_ID, "bB5QKjxU4MpHoCq0");
        qZoneSsoHandler.addToSocialSDK();
 
        String appID = "wxd929b04a9846a889";
        String appSecret = "8730a983fb9f0962b2f6610ddd2bf0b6";
	     // 添加微信平台
	     UMWXHandler wxHandler = new UMWXHandler(this,appID,appSecret);
	     wxHandler.addToSocialSDK();
	     
	     // 支持微信朋友圈
	     UMWXHandler wxCircleHandler = new UMWXHandler(this,appID,appSecret);
	     wxCircleHandler.setToCircle(true);
	     wxCircleHandler.addToSocialSDK(); 
	      
	      mController.getConfig().setPlatformOrder(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE,
	                SHARE_MEDIA.QZONE, SHARE_MEDIA.QQ, SHARE_MEDIA.SINA, SHARE_MEDIA.SMS);
	}
	
	public   UMSocialService defaultShare() {
		return doShare("我在用爱骑驴记录运动数据","","",null,QiYouConstant.BASE_URL );
//		return shareImage("我在用爱骑驴记录运动数据","",getViewImage(),QiYouConstant.BASE_URL );
	}
	
	private   UMSocialService shareImage( String title,String content, Bitmap bit, String targetUrl) {
	
//		  mController.setShareMedia( new UMImage(this,  getViewImage()));
	        mController.setShareImage( new UMImage(this,  bit));
//	        mController.setAppWebSite(targetUrl);  
//	        content ="绿色出行，快乐运动，爱骑驴\n" +content;
//	        mController.setShareContent(content);
	       
	        
	       mController.openShare(this, true); 
	     return mController;
	}
	
public   UMSocialService doShareTrack( String title,String content, String imageUrl,Bitmap bit, String targetUrl) {
		 		
 /*       
        mController.getConfig().removePlatform(SHARE_MEDIA.DOUBAN, SHARE_MEDIA.RENREN);
        //分享给QQ好友
        UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(ctx, "1104563148", "bB5QKjxU4MpHoCq0");
        qqSsoHandler.addToSocialSDK();  
       

        mController.getConfig().setPlatformOrder(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE,
                SHARE_MEDIA.QZONE, SHARE_MEDIA.QQ, SHARE_MEDIA.SINA, SHARE_MEDIA.SMS);
*/
        // 设置分享图片, 参数2为图片的url地址
//         mController.setShareMedia( new UMImage(this,  getViewImage()));
	
//        content ="绿色出行，快乐运动，爱骑驴\n" +content;
      
	   content =TextUtils.isEmpty(content)?"绿色出行，快乐运动，爱骑驴\n" :content;
          
//    	//			 QLog.getLogger().d(dTAG,"shared imgage url is:"+ imageUrl);
    	// //			 QLog.getLogger().d(dTAG,"shared targetUrl url is:"+ targetUrl);
   	 	
        UMImage img;
        if(bit!=null)
        	img = new UMImage(this, bit);
        else
        	if(!TextUtils.isEmpty(imageUrl)){
        		img = new UMImage(this, imageUrl);
		}else{
//			if( isMapActive)
//				img = new UMImage(this, R.drawable.ic_launcher);
//			else
				img = new UMImage(this,  getViewImage());
		}
	 
         mController.setShareMedia(img);
//         mController.setShareContent(content);
       
       
         QQShareContent qqShareContent = new QQShareContent();
	      //设置分享文字
  	      qqShareContent.setShareContent(content);
	      //设置分享title
  	      qqShareContent.setTitle(title);
	      //设置分享图片
	      qqShareContent.setShareImage(img);
	      //设置点击分享内容的跳转链接
 	      qqShareContent.setTargetUrl(targetUrl);  
	      mController.setShareMedia(qqShareContent); 
	      
	        QZoneShareContent   qqzoneShareContent = new QZoneShareContent ();
			qqzoneShareContent.setShareContent(content);
			//设置qq title
			qqzoneShareContent.setTitle(title); 
			qqzoneShareContent.setShareImage(img);
			qqzoneShareContent.setTargetUrl(targetUrl);
			mController.setShareMedia(qqzoneShareContent); 
			 
			
			WeiXinShareContent weixinContent = new WeiXinShareContent();
			//设置分享文字
//			weixinContent.setShareContent(content);
			//设置title
			weixinContent.setTitle(title);
			//设置分享内容跳转URL
//			weixinContent.setTargetUrl(targetUrl);  
 			weixinContent.setShareImage(img);
			mController.setShareMedia(weixinContent);
 
          
			//CircleShareContent是和分享到微信好友不同的地方
			CircleShareContent circleMedia = new CircleShareContent();
//			circleMedia.setShareContent(content);
			//设置朋友圈title
			circleMedia.setTitle(title+"\n"+content);  
			circleMedia.setShareImage(img);
//			circleMedia.setTargetUrl(targetUrl);
			mController.setShareMedia(circleMedia);    
			
      /*  //分享到QQ空间
        QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(ctx,  "1104563148", "bB5QKjxU4MpHoCq0");
        qZoneSsoHandler.addToSocialSDK();

        mController.getConfig().setSsoHandler(new SinaSsoHandler());
        
        mController.getConfig().setSsoHandler(new TencentWBSsoHandler());
        
        String appID = "wxd929b04a9846a889";
        String appSecret = "8730a983fb9f0962b2f6610ddd2bf0b6";
	     // 添加微信平台
	     UMWXHandler wxHandler = new UMWXHandler(ctx,appID,appSecret);
	     wxHandler.addToSocialSDK();
	     
	     // 支持微信朋友圈
	     UMWXHandler wxCircleHandler = new UMWXHandler(ctx,appID,appSecret);
	     wxCircleHandler.setToCircle(true);
	     wxCircleHandler.addToSocialSDK();*/
     
        mController.openShare(this, false);

        return mController;
    }
public   UMSocialService doShare( String title,String content, String imageUrl,Bitmap bit, String targetUrl) {
		
	 /*       
	        mController.getConfig().removePlatform(SHARE_MEDIA.DOUBAN, SHARE_MEDIA.RENREN);
	        //分享给QQ好友
	        UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(ctx, "1104563148", "bB5QKjxU4MpHoCq0");
	        qqSsoHandler.addToSocialSDK();  
	       

	        mController.getConfig().setPlatformOrder(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE,
	                SHARE_MEDIA.QZONE, SHARE_MEDIA.QQ, SHARE_MEDIA.SINA, SHARE_MEDIA.SMS);
	*/
	        // 设置分享图片, 参数2为图片的url地址
//	         mController.setShareMedia( new UMImage(this,  getViewImage()));
		
//	        content ="绿色出行，快乐运动，爱骑驴\n" +content;
	      
		   content =TextUtils.isEmpty(content)?"绿色出行，快乐运动，爱骑驴\n" :content;
	          
//	    	//			 QLog.getLogger().d(dTAG,"shared imgage url is:"+ imageUrl);
	    	// //			 QLog.getLogger().d(dTAG,"shared targetUrl url is:"+ targetUrl);
	   	 	
	        UMImage img;
	        if(bit!=null)
	        	img = new UMImage(this, bit);
	        else
	        	if(!TextUtils.isEmpty(imageUrl)){
	        		img = new UMImage(this, imageUrl);
			}else{
//				if( isMapActive)
//					img = new UMImage(this, R.drawable.ic_launcher);
//				else
					img = new UMImage(this,  getViewImage());
			}
		 
	         mController.setShareMedia(img);
//	         mController.setShareContent(content);
	       
	       
	         QQShareContent qqShareContent = new QQShareContent();
		      //设置分享文字
	  	      qqShareContent.setShareContent(content);
		      //设置分享title
	  	      qqShareContent.setTitle(title);
		      //设置分享图片
		      qqShareContent.setShareImage(img);
		      //设置点击分享内容的跳转链接
	 	      qqShareContent.setTargetUrl(targetUrl);  
		      mController.setShareMedia(qqShareContent); 
		      
		        QZoneShareContent   qqzoneShareContent = new QZoneShareContent ();
				qqzoneShareContent.setShareContent(content);
				//设置qq title
				qqzoneShareContent.setTitle(title); 
				qqzoneShareContent.setShareImage(img);
				qqzoneShareContent.setTargetUrl(targetUrl);
				mController.setShareMedia(qqzoneShareContent); 
				 
				
				WeiXinShareContent weixinContent = new WeiXinShareContent();
				//设置分享文字
 				weixinContent.setShareContent(content);
				//设置title
				weixinContent.setTitle(title);
				//设置分享内容跳转URL
 				weixinContent.setTargetUrl(targetUrl);  
	 			weixinContent.setShareImage(img);
				mController.setShareMedia(weixinContent);
	 
	          
				//CircleShareContent是和分享到微信好友不同的地方
				CircleShareContent circleMedia = new CircleShareContent();
 				circleMedia.setShareContent(content);
				//设置朋友圈title
				circleMedia.setTitle(title+"\n"+content);  
				circleMedia.setShareImage(img);
 				circleMedia.setTargetUrl(targetUrl);
				mController.setShareMedia(circleMedia);    
				
	      /*  //分享到QQ空间
	        QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(ctx,  "1104563148", "bB5QKjxU4MpHoCq0");
	        qZoneSsoHandler.addToSocialSDK();

	        mController.getConfig().setSsoHandler(new SinaSsoHandler());
	        
	        mController.getConfig().setSsoHandler(new TencentWBSsoHandler());
	        
	        String appID = "wxd929b04a9846a889";
	        String appSecret = "8730a983fb9f0962b2f6610ddd2bf0b6";
		     // 添加微信平台
		     UMWXHandler wxHandler = new UMWXHandler(ctx,appID,appSecret);
		     wxHandler.addToSocialSDK();
		     
		     // 支持微信朋友圈
		     UMWXHandler wxCircleHandler = new UMWXHandler(ctx,appID,appSecret);
		     wxCircleHandler.setToCircle(true);
		     wxCircleHandler.addToSocialSDK();*/
	     
	        mController.openShare(this, false);

	        return mController;
	    }
	private Bitmap getViewImage(){
		View view =findViewById(R.id.realtabcontent);
//		 view =	getWindow().getDecorView(); //截屏
//		return Utils.getBitmapFromView(view,QiYouConstant.SUBNAIL_PIC_SIZE,QiYouConstant.SUBNAIL_PIC_SIZE);
//		return Utils.getBitmapFromView(view,QiYouConstant.PV_INT_SCREEN_WIDTH,QiYouConstant.PV_INT_SCREEN_HEIGHT-400 );
		
//		if(this.isMapActive)
//		 return	Utils.convertViewToBitmap(view);
		return Utils.getBitmapFromView(view);
		
//		return Utils.convertViewToBitmap(view  );
		
		
		
	} 
	 
	
	 void ToastMsg(String msg,int length){
		 Toast.makeText(MainActivity.this, msg, length).show();  
	}
	 public void startNaviService(final int trackId,final boolean isSimulation,final boolean isContinue){
		 MobclickAgent.onEvent(this,"startNavi");
		 final Intent serviceIntent = new Intent(this, QNaviSvc.class); 
			serviceIntent.putExtra(QiYouConstant.EXTRA_KEY_START_NAVI, 0);
		    stopService(serviceIntent);
		   
//		    lastStartDialog=!isContinue; //start new navi should not show dialog
			
			  handler = new Handler(){ 
					@Override
					public void handleMessage(Message msg) {  
						if (msg.what==10) {  
							 app.naviTrackId=trackId; //TODO:this need current navi stopped.
								startService(serviceIntent);
								if(isSimulation){
									startTrackPlayBack(trackId);		
								}else if(!isContinue){ 
									tabTrackClicked();//start new track
								}	  
						}
					}};
					
			    new Thread(){
					
					@Override
					public void run() {
						int totalWaiting=0;
//				    	if(app.naviTrackId>0){
						while(app.naviTrackId>0 && totalWaiting<10000){
				    		 try {
								Thread.sleep(500);
								totalWaiting+=500;
								//			 QLog.getLogger().dLog(dTAG,TAG + " to exit navigation totalWaiting "+totalWaiting);
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
				    	}  
				    	 handler.sendEmptyMessage(10);
				    	
				    		
					}}.start(); 
	 }
	
	
	public void startNaviService(final int trackId,final boolean isSimulation){
		
		startNaviService(trackId,isSimulation,false);
		  
		 
	}
		
public void stopNaviService(){
	 	app.naviTrackId =-1;
	    app.isNaving=false;
		Intent serviceIntent = new Intent(this, QNaviSvc.class); 
	    stopService(serviceIntent); 
	    app.clearLastNavId();
	   
	}
	
	
	
	public void showGpxTrackDetail(int typeId,int id,boolean isWebQuery) {
		 
		showFragment(GpxDetail_fragment.newInstance(typeId,id,isWebQuery),GpxDetail_fragment.getFTag());
	 
}
	public void showTrackDetail(int typeId,int id) {
		
	/*	if(id>0   &&  app.getRecordingTrack().getTrackBean().getTrackId()==id){
    			showRecordingTrack(false);
    			return;
    	}*/
 
			showFragment(TrackDetail_fragment.newInstance(typeId,id),TrackDetail_fragment.getFTag());
		
	}
	 
	/*
	 * check and confirm with user to start new track or continue the tracking one 
	 */
	protected void newNaviDialog(final boolean isContinue) {
		   AlertDialog.Builder builder = new Builder(this);
		   builder.setMessage("是否继续上次导航？");
		   builder.setTitle("提示");
		   builder.setCancelable(false);
		   builder.setPositiveButton("确认", new OnClickListener() {
		   @Override
		   public void onClick(DialogInterface dialog, int which) {
			   dialog.dismiss();		 
			   int navId=app.getExistNaviID();  
			   app.clearLastNavId();
			  
			   if(
//					   navId!=app.getCurrentTrack().getTrackBean().getTrackId()&& 
		    		   navId!=app.getRecordingTrack().getTrackBean().getTrackId() )
			   {
				   startNaviService(navId, false,isContinue);
			   }
				lastStartDialog=true;
				 new Thread(){ 
						@Override
						public void run() {
						  if(isContinue)
							while(!app.isNaving) 
					    		 try { 
					    				 Thread.sleep(500);
									
								} catch (InterruptedException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
					    	 
					    	  startNewTrack(isContinue);
					    	
					    		
						}}.start(); 
			  
			}
			});
		  builder.setNegativeButton("取消", new OnClickListener() {
		 @Override
		 public void onClick(DialogInterface dialog, int which) {
			 dialog.dismiss();
			 app.clearLastNavId();
			 startNewTrack(isContinue); 
			 }
			 });
		  	builder.create().show();
		 	}
	
    public void startNewTrackMap() { 
    	//TODO: is to check the preference for exist recording track?
      // //			 QLog.getLogger().dLog(TAG," Here , Start a New Track.................@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
    	
     
      app.setRecordingTrack(new Track());    	
      startNewTrack(false);
	}
    /*
     * continue the current track for recording.
     */
    public void continueTrack() { 
    	if(app.currentTrack==null 
//    			||app.currentTrack.getTrackBean().getTrackId()==app.getRecordingTrack().getTrackBean().getTrackId()
    			)return;
    	startNewTrack(true);
    	
    }
    private boolean lastStartDialog=false;
    void startNewTrack(final boolean isContinue){

    	// //			 QLog.getLogger().d(dTAG,TAG+" "+"Start a new track...");
    	 if(!lastStartDialog 
    			 &&app.isLastNaviExist() 
//    			 && app.getExistNaviID()!=app.getCurrentTrack().getTrackBean().getTrackId()
    			 && app.getExistNaviID()!=app.getRecordingTrack().getTrackBean().getTrackId()
    			 && app.naviTrackId<=0){
       	  newNaviDialog(isContinue) ;
   		}else{  
   			
    	 if(isContinue)
    		 app.setRecordingTrack(app.getCurrentTrack());
    	 
    	 if(isContinue)
	    		app.continueTrack(app.currentTrack.getTrackBean().getType());				    	
	    	else
	    		app.initialNewTrack(TrackType.BIKE);	
    	 
			 
		 app.playBack=false;
		 if(!lastStartDialog||isContinue)
			 showRecordingTrack(false);
		 
		 app.forceDbUpdate(false); 
		 
		 lastStartDialog=false;
   		}
//		 startNaviService();//TODO:remove
    }
    
     
    public void showRecordingTrack( boolean isContinue){
 
    	app.playBack=false;
    	
 
   		
   		Track_fragment fragment;
   		String tag =Track_fragment.getFTag();
   		if(isContinue){
   			fragment  = Track_fragment.newInstance(app.getCurrentTrack().getTrackBean().getTrackId());
   		}else{
   			fragment = (Track_fragment) getSupportFragmentManager().findFragmentByTag(tag);
   			if(fragment==null || fragment.trackId!=app.getRecordingTrack().getTrackBean().getTrackId()){
   				fragment = Track_fragment.newInstance(app.getRecordingTrack().getTrackBean().getTrackId());;
//   				fragment = new Track_fragment();
//   				Bundle args = new Bundle(); 
//   			    args.putInt(QiYouConstant.EXTRA_KEY_ID, app.getRecordingTrack().getTrackBean().getTrackId());
//   			    fragment.setArguments(args);
   			}
   		}
   		
   		showFragment(fragment,tag); 
   		
   		updateTabTitle();
    }
    
    
	/*
	 * play back
	 */
	public void startTrackPlayBack(Integer trackId) { 
	 
		 MobclickAgent.onEvent(this,"playback");
//		LocationChangedCnt=0;		
		// //			 QLog.getLogger().d(dTAG,TAG+" "+" Start  playback track "+ trackId );
		app.initialPlayBack(trackId);
		// //			 QLog.getLogger().d(dTAG,TAG+" "+ "startTrackPlayBack, isPlayback: " + app.playBack  ); 
//		if(app.isCanRecord()||app.playBack)
 		 if(QiYouConstant.PLAYBACK_CAN_RECORD){
		
			// //			 QLog.getLogger().d(dTAG,TAG+" "+"Start recording a playback...");
			if(app.recordingTrack!=null 
//					&& app.recordingTrack.getTrackBean().getType() != QiYouConstant.TRACK_TYPE_COPY
					&& app.recordingTrack.getTrackBean().getType()!=TrackType.COPY
					&& app.recordingTrack.getTrackBean().getStatus()==TrackStatus.RECORDING  
			  ){
				 finishRecording(); 
//				newTrackDialog();
		     } 
			  
		    		 // //			 QLog.getLogger().d(dTAG,TAG+"start new track for playback recording.");
		    		
//		    		 app.setRecordingTrack(new Track());
//		    		 app.getRecordingTrack().startNewTrack();
//		    		 app.initialNewTrack(QiYouConstant.TRACK_TYPE_COPY); 
		    		 app.initialNewTrack(TrackType.COPY);
		    		 app.playBack=true;
		    		 app.getRecordingTrack().getTrackBean().setComment("拷贝自"+trackId); 
		    		 // //			 QLog.getLogger().d(dTAG,TAG+"new track distance:" + app.getRecordingTrack().getTrackBean().getDistance());
		    		 // //			 QLog.getLogger().d(dTAG,TAG+"new track start time:" + Utils.getFormatedTime(app.getRecordingTrack().getTrackBean().getStartTime())); 
		  
		} 
       if(app.currentActiveFragment!=Playback_fragment.getFTag())	
	    showFragment(Playback_fragment.newInstance(trackId),Playback_fragment.getFTag());
       app.forceDbUpdate(false); 
       // //			 QLog.getLogger().d(dTAG,TAG+" "+ "startTrackPlayBack, isPlayback: " + app.playBack  ); 
	
		 
	}
	 
	
	public void showTrackChart(ArrayList<Track> trs) {  
		 
		DistanceChart dc = new DistanceChart();
		dc.setTrs(trs);
		Intent achartIntent =dc.execute(this);  
		startActivity(achartIntent);
	}
	
	
	public void showTrackStatics() { 
		 
//		showFragment(new testFragment(),testFragment.getFTag());
	    // //			 QLog.getLogger().d(dTAG," TrackStatics starting   show trackstatics...  " );
//		if(app.currentActiveFragment ==TrackStatics_fragment.getFTag())return;
		
		TrackStatics_fragment fragment = (TrackStatics_fragment) getSupportFragmentManager().findFragmentByTag(TrackStatics_fragment.getFTag());
	    if(fragment==null) fragment =new TrackStatics_fragment();
	    
			showFragment(fragment,TrackStatics_fragment.getFTag());
		// //			 QLog.getLogger().d(dTAG," TrackStatics starting   show trackstatics... end" );
		 
	}
	/*
	 * let user download offline maps
	 */
	public void showOffline() { 
		 
		showFragment(new OfflineMaps_fragment(),OfflineMaps_fragment.getFTag());
		 
	}
	 
	
	public void showWebList() { 
//		if(app.currentActiveFragment==WebList_fragment.getFTag()) return;
		
		WebList_fragment webList_fragment = (WebList_fragment) getSupportFragmentManager().findFragmentByTag(WebList_fragment.getFTag());
	    if(webList_fragment==null) webList_fragment =new WebList_fragment();
		showFragment(webList_fragment,WebList_fragment.getFTag());
		 
	}
	
	public void showNoteList(int cate,int subCate) { 
 		
		NoteList notelist = (NoteList) getSupportFragmentManager().findFragmentByTag(NoteList.getFTag());
	    if(notelist==null) notelist = NoteList.newInstance(cate,subCate);
		showFragment(notelist,NoteList.getFTag());
		 
	}
	

	public void showNewNote(Note note) { 
 		
		NoteNew noteNew = (NoteNew) getSupportFragmentManager().findFragmentByTag(NoteNew.getFTag());
	    if(noteNew==null) {
	    	noteNew = NoteNew.newInstance(note);
	    }else{
	    	 // update the currentNote
	    	noteNew.setCurrentNote(note);
	    }
		showFragment(noteNew,NoteNew.getFTag());
		 
	}
	
	

	public void showEditNote(Note note,NoteMessage noteMsg) { 
 		
		NoteNew noteNew = (NoteNew) getSupportFragmentManager().findFragmentByTag(NoteNew.getFTag());
	    if(noteNew==null) {
	    	noteNew = NoteNew.newInstance(note,noteMsg);
	    }else{
	    	 // update the currentNote,msg
	    	noteNew.setCurrentNote(note);
	    	noteNew.setCurrentMsg(noteMsg);
	    }
		showFragment(noteNew,NoteNew.getFTag());
		 
	}
	
	
	
public void showNoteDetail(Note note,NoteMessage noteMsg) { 
 		
 		NoteDetail noteDetail = (NoteDetail) getSupportFragmentManager().findFragmentByTag(NoteDetail.getFTag());
 		
 		if(noteDetail==null) {
 			noteDetail = NoteDetail.newInstance(note,noteMsg);
 	    }else{
 	    	 // update the currentNote,msg
 	    	noteDetail.setCurrentNote(note);
 	    	noteDetail.setCurrentMsg(noteMsg);
 	    } 
		 
		showFragment(noteDetail,NoteDetail.getFTag());
		 
	}
	
	public void showLocalTrackList() { 
//		if(app.currentActiveFragment==WebList_fragment.getFTag()) return;
		
		TrackList_fragment trackList_fragment = (TrackList_fragment) getSupportFragmentManager()
				.findFragmentByTag(TrackList_fragment.getFTag());
	    if(trackList_fragment==null) trackList_fragment =new TrackList_fragment();
		showFragment(trackList_fragment,TrackList_fragment.getFTag());
		 
	}
	
	/*
	 * show footmark's image in a pager photoviewer.
	 */
	public void showImagePagerFragment(int position,String[] urls){

		if(app.currentActiveFragment!=ImagePager_fragment.getFTag()){
				
				showFragment(ImagePager_fragment.newInstance(position,urls),ImagePager_fragment.getFTag());
		 				
			} 
	}
	 
	public void showLogin(){
		if(app.currentActiveFragment!=LoginFragment.getFTag()){
//			LoginFragment loginFragment = (LoginFragment) getSupportFragmentManager().findFragmentByTag(LoginFragment.getFTag());
//			if(loginFragment==null) loginFragment =LoginFragment.newInstance();
			LoginFragment loginFragment  =LoginFragment.newInstance();
			showFragment(loginFragment,LoginFragment.getFTag());
//			showFragment(LoginFragment.newInstance(),LoginFragment.getFTag());
	 				
		} 
	}
	
	public void showRegist(){
		if(app.currentActiveFragment!=RegistFragment.getFTag()){
			
//			RegistFragment registFragment = (RegistFragment) getSupportFragmentManager().findFragmentByTag(RegistFragment.getFTag());
//			if(registFragment==null) registFragment =RegistFragment.newInstance();
			RegistFragment registFragment  =RegistFragment.newInstance();
			showFragment(registFragment,LoginFragment.getFTag());
			
//			showFragment(RegistFragment.newInstance(),RegistFragment.getFTag());
	 				
		} 
	}
	public void showActvityHome( Activity_bean activity){
		if(app.currentActiveFragment!=ActivityHome.getFTag()){
			
	/*		ActivityDetail actFragment = (ActivityDetail) getSupportFragmentManager().findFragmentByTag(ActivityDetail.getFTag());
 			if(actFragment==null) actFragment =ActivityDetail.newInstance();
 			actFragment.setCurrentAct(activity); 
			*/
 
			ActivityHome actFragment  =ActivityHome.newInstance(activity); 	
			
			showFragment(actFragment,ActivityHome.getFTag());
		} 
	}
	
	public void showActvity( Activity_bean activity){
		if(app.currentActiveFragment!=ActivityDetail.getFTag()){
			
	/*		ActivityDetail actFragment = (ActivityDetail) getSupportFragmentManager().findFragmentByTag(ActivityDetail.getFTag());
 			if(actFragment==null) actFragment =ActivityDetail.newInstance();
 			actFragment.setCurrentAct(activity); 
			*/
 
	 		 ActivityDetail actFragment  =ActivityDetail.newInstance(activity); 	
			
			showFragment(actFragment,ActivityDetail.getFTag());
		} 
	}
	
	public void showGroup(Group_bean  group){
		if(app.currentActiveFragment!=GroupDetail.getFTag()){
			
		 /*	GroupDetail fragment = (GroupDetail) getSupportFragmentManager()
													.findFragmentByTag(GroupDetail.getFTag());
 			if(fragment==null) fragment =GroupDetail.newInstance(); 
 			fragment.setCurrentGroup(group);*/
 			
 			GroupDetail fragment  =GroupDetail.newInstance(group);
			showFragment(fragment,GroupDetail.getFTag());
 
	 				
		} 
	}
	public void showGroupHome(Group_bean  group){
		if(app.currentActiveFragment!=GroupHome.getFTag()){
			
 
 			
 			GroupHome fragment  =GroupHome.newInstance(group);
			showFragment(fragment,GroupHome.getFTag());
 
	 				
		} 
	}
	public void showLocationFinder() { 
 		
		 LocationPickerFragment lpfFragment = (LocationPickerFragment) getSupportFragmentManager().findFragmentByTag(LocationPickerFragment.getFTag());
	    if(lpfFragment==null) lpfFragment =new LocationPickerFragment();
		showFragment(lpfFragment,LocationPickerFragment.getFTag()); 
		 
	}

	public void showUserDetails(User_bean user/*,int userId*/) { 
//		if(app.currentActiveFragment==WebList_fragment.getFTag()) return;
		
 		/*UserDetails fragment = (UserDetails) getSupportFragmentManager().findFragmentByTag(UserDetails.getFTag());
 	    if(fragment==null) fragment = UserDetails.newInstance();  
		fragment.setCurrentUser(user);*/
		
		//TODO to use above reuse fragment mechnism
		
 		UserDetails fragment = UserDetails.newInstance(user);
		showFragment(fragment,UserDetails.getFTag());
		 
	}
	
	public void showUserHome(User_bean user/*,int userId*/) { 
 	 
		UserHome fragment = (UserHome) getSupportFragmentManager().findFragmentByTag(UserHome.getFTag());
 	    if(fragment==null) fragment = UserHome.newInstance();  
		fragment.setCurrentUser(user); 
		
		//TODO to use above reuse fragment mechnism
		
// 		UserHome fragment = UserHome.newInstance(user);
		showFragment(fragment,UserHome.getFTag());
		 
	}
	
	
	
	public void showRoute(int trackId){
	
		 Route_fragment route_fragment = (Route_fragment) getSupportFragmentManager().findFragmentByTag(Route_fragment.getFTag());
		if(route_fragment==null) route_fragment = Route_fragment.newInstance(trackId);
		route_fragment.trackId=trackId;
		if(app.currentActiveFragment!=Route_fragment.getFTag()){
			
			showFragment(route_fragment,Route_fragment.getFTag());
	 				
		} 
		
//		 route_fragment = (Route_fragment) getSupportFragmentManager().findFragmentByTag(Route_fragment.getFTag());
//		 route_fragment = (Route_fragment) getSupportFragmentManager().findFragmentByTag(Route_fragment.getFTag());
	}
	
	private void showFragment(Fragment fragment,String fragmentTag)
	{
		 	 
		FragmentManager fm = getSupportFragmentManager();
		FragmentTransaction ft = fm.beginTransaction();
		 
		if (findViewById(R.id.realtabcontent) != null) { //realtabcontent
		      
			  ft.replace(R.id.realtabcontent, fragment,fragmentTag);
		    // //			 QLog.getLogger().d(dTAG, " before commit,getSupportFragmentManager().findFragmentByTag： "+fragmentTag 		    		+", result is:"+getSupportFragmentManager().findFragmentByTag(fragmentTag));
			  Fragment lastFragmeng =  getSupportFragmentManager().findFragmentByTag(app.currentActiveFragment);
			  if(!   (lastFragmeng instanceof IlocationFragment     //see last fragment is track_fragment
   	    			    && fragmentTag.equalsIgnoreCase(TrackDetail_fragment.getFTag())   
					  )) {   //1.前一个fragment为 track_fragment 2.当前新fragment为detail_fragment， 则不放入回退栈
//				  if(!(fragment  instanceof RegistFragment))
  		    	   ft.addToBackStack(null); //add to backstack.   
		      } 
			 
		    }
		
		else
		{
			try{
			ft.add(R.id.realtabcontent, fragment,fragmentTag);
			}catch(Exception e){
				Utils.logStackTrace(e, dTAG);
			}
		}
		//  ft.show(bmapview_fragment);
		app.currentActiveFragment =fragmentTag;
// 		ft.setTransition(2500);//TRANSIT_FRAGMENT_OPEN
		ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
//		ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
//					ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
//			ft.setTransition(FragmentTransaction.TRANSIT_EXIT_MASK);
//			ft.setTransition(FragmentTransaction.TRANSIT_ENTER_MASK);
//			ft.setTransition(FragmentTransaction.TRANSIT_UNSET);
//							ft.setTransition(FragmentTransaction.TRANSIT_EXIT_MASK);
//		ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
//		ft.setTransition(FragmentTransaction.TRANSIT_NONE);
		
//		 ft.commit();
		 ft.commitAllowingStateLoss(); 
//		 fm.executePendingTransactions();
		 
		 
		 // //			 QLog.getLogger().d(dTAG, " after commit,getSupportFragmentManager().findFragmentByTag： "+fragmentTag +", result is:"+getSupportFragmentManager().findFragmentByTag(fragmentTag));
//		 Fragment frgmnt =  getSupportFragmentManager().findFragmentByTag(fragmentTag);
//		 int i=0;
//		 i++;
//		 i++;
		 
	}
	 
	
 
	
	public void startPrefActivity()
	{
		Intent intent = new Intent(this,SettingsActivity.class);
    	this.startActivity(intent);
	}
	/*public void startSpeech()
	{
		Intent intent = new Intent(this,TtsDemo.class);
    	this.startActivity(intent);
	}
	*/
	 
	 
	public void showAbout()
	{
		Intent intent = new Intent(this,About.class);
    	this.startActivity(intent);
	}

	public void showWeb()
	{
		Intent intent = new Intent(this,Website.class);
    	this.startActivity(intent);
	}
	 
	long lastNetworkLocationRequest=0;
	  class LocationSendBackReceiver extends BroadcastReceiver {  
		       
		        @Override  
		        public void onReceive(Context context, Intent intent) {   
		      
			       try{ 
			    	   
				            if (System.currentTimeMillis() - firstTime < 800) {  //back key hit
				            	return;				       
				            }
				            
//			        	if(app.canStopNetworkRequest() ||app.getRecordingTrack().getTrackBean().getStatus()!= TrackStatus.RECORDING &&!app.playBack &&!app.isRouting &&!app.isLocationFinding)
		        	if(app.getRecordingTrack().getTrackBean().getStatus()!= TrackStatus.RECORDING &&!app.playBack &&!app.isRouting &&!app.isLocationFinding)	{			        		
			        		Log.d(dTAG,TAG+" track id:"+app.getRecordingTrack().getTrackBean().getTrackId() +",status: "+app.getRecordingTrack().getTrackBean().getStatus()
			        				+",start time: "+ app.getRecordingTrack().getTrackBean().getStartTime());
			        		Log.d(dTAG,TAG+"  No active tracking activity,stoping the gps request..."); 
//			        		if(Utils.isLocOfGPS(loc))
			        		app.stopAndroidGPSRequest();
			        		return;
			        	} 
			        	 
			       	 final  Location navLoc  =intent.hasExtra( QiYouConstant.NEW_NAVIFO_MSG)? (Location)intent.getExtras().get(QiYouConstant.NEW_NAVIFO_MSG):null; 
			       	 
		        	/*if(navLoc!=null){
		        		//			 QLog.getLogger().d(dTAG,TAG+" get navi msg of" + navLoc.getExtras().getString( QiYouConstant.NEW_NAVIFO_MSG));
		        	}*/
			       	 
			        	 final Location location;
			        	 location=  intent.hasExtra( QiYouConstant.NEW_LOCATION)? (Location)intent.getExtras().get(QiYouConstant.NEW_LOCATION) :null;
		        		
			        

			        	/* if(location ==null){
			        		 //			 QLog.getLogger().d(dTAG, String.format("%s, app.isNetworkLocationRequestStarted :%s,location == null? %s", TAG, app.isNetworkLocationRequestStarted,location == null));
			        		
			        	 }*/
			        	 if(!app.isNetworkLocationRequestStarted && Utils.isLocOfMonitor(location)
			        			 &&System.currentTimeMillis() -lastNetworkLocationRequest> QiYouConstant.MAX_GPS_SPAN*4
			        			 ){
//			        	 if(location == null){
			        		  //			 QLog.getLogger().d(dTAG, String.format("%s,   app.startNetworkLocationRequest()", TAG ));			        		 
			        		 app.startNetworkLocationRequest(false);
			        		 lastNetworkLocationRequest =System.currentTimeMillis(); 
			        	 }else 
			        		 if(app.isNetworkLocationRequestStarted
			        			&& Utils.isLocOfGPS(location)	 
//			        		     && !intent.hasExtra(QiYouConstant.ACTION_NEW_COARSE_LOCATION)
//			        			 && location!=null
			        				 
			        			 )
			        		 {
				    		   app.stopNetworkLocationRequest();
				    		  
				    	     }	 
	        			 final boolean isPause = location==null?false:(Utils.isLocOfGPS(location)?location.getSpeed()==0:false);
	        			 
	//		        	 final boolean isNoSigNal =intent.getBooleanExtra(QiYouConstant.EXTRA_KEY_NO_LOCCATION_SIGNAL, false);
	//		        	 if(isNoSigNal)Log.d(dTAG,TAG+" Lost the gps signal..."); 
	//		             //			 QLog.getLogger().d(dTAG,TAG+" CurrentActiveFragment... "+app.currentActiveFragment); 
	        			 
	        			 
			        	 if(!TextUtils.isEmpty(app.currentActiveFragment))
			    	     {
			    	    	  final Fragment frgmnt =  getSupportFragmentManager().findFragmentByTag(app.currentActiveFragment); 
			    	    	  if(frgmnt instanceof IlocationFragment && !app.currentActiveFragment.equalsIgnoreCase(TrackDetail_fragment.getFTag())){ 
//			    	    		  //			 QLog.getLogger().d(dTAG, String.format(" app.currentActiveFragment: %s", app.currentActiveFragment ));
				    	    	   handler.post(new Runnable(){
				    	    		   @Override
									public void run() {
//				    	    			   ((IlocationFragment)frgmnt).updateUI(location, Pausingtime>0);
				    	    			   ((IlocationFragment)frgmnt).updateUI(location,isPause);
				    	    			   if(navLoc!=null)
				    	    					   ((IlocationFragment)frgmnt).navInfo(navLoc);  
				    	    		   }
				    	    	   }); 
			    	    	  }
			    	     }
			        	 
			        	// Log.d(TAG,"get Pausing time from location service:"+ Pausingtime.toString()); 
			      }catch (Exception e)
		        	{
		        		Log.d(dTAG, TAG + " " +e.getMessage());
		        		Log.d(dTAG,TAG +" Error while handling location changes information.");
		        	}
		        }  
		          
		    }  
	 
		 
		long firstTime =0;
		@Override 
	    public boolean onKeyUp(int keyCode, KeyEvent event) { 
	        if (keyCode == KeyEvent.KEYCODE_BACK) { 
	        	
//	        	tabHost.getTabWidget().setVisibility(View.VISIBLE);
	        	
	        	if(!app.currentActiveFragment.equalsIgnoreCase(ImageDetailFragment.getFTag())
	        			&& !app.currentActiveFragment.equalsIgnoreCase(LoginFragment.getFTag())
	        			&& !app.currentActiveFragment.equalsIgnoreCase(RegistFragment.getFTag())
	        			&& !app.currentActiveFragment.equalsIgnoreCase(OfflineMaps_fragment.getFTag()) 
	        			&& !app.currentActiveFragment.equalsIgnoreCase(UserDetails.getFTag())
	        			&& !app.currentActiveFragment.equalsIgnoreCase(UserHome.getFTag())
 	        			&& !app.currentActiveFragment.equalsIgnoreCase(tabList)
 	        			&& !app.currentActiveFragment.equalsIgnoreCase(Route_fragment.getFTag()))
	        			 {	        	
	        		
	        				updateTabVisibility(true);
	        	 
	        			 }
	        	
	        	
	        	
//	        	  getSupportFragmentManager().findFragmentByTag(app.currentActiveFragment).onHiddenChanged(true);
	        	 
	       /*   Fragment frgmnt =  getSupportFragmentManager().findFragmentByTag(app.currentActiveFragment);
   	    	  if(frgmnt instanceof IlocationFragment ) {
   	    		 this.showFragment(new Nav_fragment(), Nav_fragment.getFTag());return true;
   	    	  }*/
	        	int cnt=0;
//	        	Utils.hideSoftKeyboard(this);
//	        	if( ((InputMethodManager)  this.getSystemService(Activity.INPUT_METHOD_SERVICE)).isActive())
//	        	if(isShowingInput)
//	        		return true;
	        	
	        	
	        	if(app.currentActiveFragment.equalsIgnoreCase(TrackDetail_fragment.getFTag())){
//	        		 showWebList();
	        			showLocalTrackList();
	        		 return true;
	        	 }
	        	 
	        	 
	       /* 	 
	         if(app.currentActiveFragment.equalsIgnoreCase(TrackDetail_fragment.getFTag())
//	        	||app.currentActiveFragment.equalsIgnoreCase(GpxDetail_fragment.getFTag()) // why
	        	)
	        	while(true){
	        		{
	        			cnt++;
	        			if(cnt>3)showWebList()  ; 
	        			// //			 QLog.getLogger().d(dTAG, TAG +" back count is:" + cnt);
	        			
	        			// //			 QLog.getLogger().d(dTAG, TAG +" app.currentActiveFragment is:" + app.currentActiveFragment);
	        			
	        			if( app.currentActiveFragment==WebList_fragment.getFTag()
	        				||	app.currentActiveFragment==TrackStatics_fragment.getFTag()
	        				
	        			)
		        			return true;
	        			
	        			
//	        			if(  app.currentActiveFragment == Nav_fragment.getFTag())
//		        			break;
//	        			if(  app.currentActiveFragment == TrackDetail_fragment.getFTag())
//	        			break;
		        		Fragment frgmnt =  getSupportFragmentManager().findFragmentByTag(app.currentActiveFragment);
		        		if(frgmnt ==null  )break;
		        		
		        		FragmentTransaction fragmentTransaction =   getSupportFragmentManager().beginTransaction();
		        		fragmentTransaction.remove(frgmnt).commit();
		        		 super.onKeyUp(keyCode, event); 
//		        		frgmnt.onDestroy();
	        		}
	        		
	        	} */
	         
	          
	          
//	          if(!app.currentActiveFragment.equalsIgnoreCase(Nav_fragment.getFTag()))
//	         if(tabHost.getTabWidget().getVisibility()==View.GONE)
//	          if(!app.currentActiveFragment.equalsIgnoreCase(tabHome))
	         
	         if(app.currentActiveFragment.equalsIgnoreCase(RegistFragment.getFTag())){
	        	 this.isTabHome();
	        	 return true;
	         }
	         if(app.currentActiveFragment.equalsIgnoreCase(LoginFragment.getFTag())){
	        	 this.isTabHome();
	        	 return true;
	         }
	         
	         if(app.currentActiveFragment.equalsIgnoreCase(tabList)){
	        	 this.isTabHome();
 	        	 return true;
//	        	 firstTime = System.currentTimeMillis();
	        	 
//	        	 return super.onKeyUp(keyCode, event);
	         }
	         
//	         if(app.currentActiveFragment.equalsIgnoreCase(TrackList_fragment.getFTag())){
//	        	 this.isTabHome();
//	        	 return true;
//	         }
	         if( app.currentActiveFragment.equalsIgnoreCase(Route_fragment.getFTag())){
	        	 long secondTime = System.currentTimeMillis(); 
		            if (secondTime - firstTime > 800) {//如果两次按键时间间隔大于800毫秒，则不退出 
		            	String msg= "再按一次将退出路书编辑" ;
		                Toast.makeText(MainActivity.this, msg, 
		                        Toast.LENGTH_SHORT).show(); 
		                firstTime = secondTime;//更新firstTime 
		              
//		                if( app.currentActiveFragment.equalsIgnoreCase(tabTrack))
//		                	tabHost.getTabWidget().setVisibility(View.GONE);
		                
		                return true; 
		            }    
	         }
	         
	         if(!app.currentActiveFragment.equalsIgnoreCase(tabHome)
	        	&& !app.currentActiveFragment.equalsIgnoreCase(tabTrack)
	        		 )
	        	return super.onKeyUp(keyCode, event);	         
	         	
	            long secondTime = System.currentTimeMillis(); 
	            if (secondTime - firstTime > 800) {//如果两次按键时间间隔大于800毫秒，则不退出 
	            	String msg=app.canExit()?"再按一次将退出":"再按一次将在后台继续记录";
	                Toast.makeText(MainActivity.this, msg, 
	                        Toast.LENGTH_SHORT).show(); 
	                firstTime = secondTime;//更新firstTime 
	              
//	                if( app.currentActiveFragment.equalsIgnoreCase(tabTrack))
//	                	tabHost.getTabWidget().setVisibility(View.GONE);
	                
	                return true; 
	            } else { 
	            	//if(app.isCanRecord() && app.recordingTrack!=null && app.recordingTrack.getTrackBean().getStatus()==QiYouConstant.TRACK_STATUS_TRACKING ) 
//	            	if(app.isCanRecord() && !QiYouConstant.DEVELOPER_MODE)
	            	return  exit();
	            } 
	        } 
	        try{
	        	return super.onKeyUp(keyCode, event);
	        }
	        catch(Exception e){
	        	Utils.logStackTrace(e, TAG);
	        	return true;
	        }
	    } 
		
		void saveExit(){
			 if(!app.canExit())
				 Toast.makeText(this,  "系统将结束当前运动并退出", Toast.LENGTH_LONG ).show();
			 cancelRecording();
			 finishRecording();	
   		     app.ExitApp();	
   		    
		}
		
		boolean exit(){ 
   		     
			if(app.canExit()){ 
//       		 Toast toast=	Toast.makeText(this,  "谢谢使用，再见！", Toast.LENGTH_LONG );
//   		 	 toast.show(); 
				this.finish();
				 QLog.getLogger().d(dTAG,TAG+" activity finished." );
   		     app.ExitApp();	
   		     return false;
	       	}
	       	else{  
	   		 	 Toast toast=	Toast.makeText(this,  "结束运动之前，系统将在后台继续为您记录", Toast.LENGTH_LONG );
	   		 	 toast.show();
//	   		     toast=	Toast.makeText(this,  " ", Toast.LENGTH_LONG );
//	   		 	 toast.show();
	   		 	 Intent intent = new Intent(Intent.ACTION_MAIN);
	                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addCategory(Intent.CATEGORY_HOME);
                startActivity(intent);
//       		return super.onKeyUp(keyCode, event);
                return true;
       		}
		}
		public void cancelRecording(){
			 Log.i(dTAG,TAG + " cancelRecording  ");
			if(app.recordingTrack!=null && app.recordingTrack.getTrackBean().getTrackId()<=0){
				app.recordingTrack =null;
//				app.setLastRecordingIdStartTime();
				app.clearLastRecordingIdStartTime();
				// //			 QLog.getLogger().d(dTAG,TAG+" setLastRecordingIdStartTime 2" );
//				 Log.i(dTAG,TAG + " to stop gps request  ");	
//				app.forceDbUpdate(true);
				app.stopAndroidGPSRequest();
				app.stopNetworkLocationRequest();
				app.unregTimeTick();
				stopNaviService();
			}
//			showFragment(new Nav_fragment(),Nav_fragment.getFTag());
			
			 
		}
		
		public void pausingTrack(boolean is2Pause){			
			
			if(is2Pause){		 
				app.updateTrackStatus(QiYouConstant.TRACK_STATUS_PAUSED);	
				app.stopAndroidGPSRequest();
				app.updatePauseParameters();
			}
			else{
				app.updateTrackStatus(QiYouConstant.TRACK_STATUS_TRACKING);
				app.getPausedTime(true);//update manual paused time
			}
	 		
			
			
			
			
		}
		
		public void clearRecordingCache(){
			 Intent serviceIntent = new Intent(this, LocationService.class); 
		     serviceIntent.putExtra(QiYouConstant.EXTRA_KEY_FINISH_RECORDING, 1);
		     startService(serviceIntent);  
		     // //			 QLog.getLogger().d(dTAG,TAG+" cleaning requested." );
		}
		
		
		public void finishRecording(){
		 app.forceDbUpdate(true); 
		 
//			long st=System.currentTimeMillis();
		 app.clearLastRecordingIdStartTime();
    		 // //			 QLog.getLogger().dLog(TAG,  "activity.finishRecording() cost time:" +(System.currentTimeMillis()-st)); 
		 
		 if(null != app.currentTrack && app.currentTrack.getTrackBean().getTrackId()>0){
			 app.getTrackCache().put( app.currentTrack.getTrackBean().getTrackId(), app.currentTrack);
		 }
//			app.clearLastRecordingIdStartTime();

 
			if( app.recordingTrack!=null && TrackStatus.FINISHED != app.recordingTrack.getTrackBean().getStatus()){
			 
				try{
					
					
					if( app.recordingTrack.getTrackBean().getLastWp().getWb().getSumDist()<app.sumDist){
						app.recordingTrack.getTrackBean().getLastWp().getWb().setSumDist((float) app.sumDist);
						app.recordingTrack.getTrackBean().setDistance((float) app.sumDist);
					}
					 
					if( app.recordingTrack.getTrackBean().getLastWp().getWb().getSportTime()>
							app.recordingTrack.getTrackBean().getSportTime()){
						app.recordingTrack.getTrackBean().setSportTime(app.recordingTrack.getTrackBean().getLastWp().getWb().getSportTime());					
					}
					
					app.recordingTrack.getTrackBean().setDistance(app.recordingTrack.getTrackBean().getLastWp().getWb().getSumDist());
					app.recordingTrack.getTrackBean().setSportTime(app.recordingTrack.getTrackBean().getLastWp().getWb().getSportTime());
					 
//					st=System.currentTimeMillis();
				   app.updateStatistics();
	//			  app.writeStatiscs();	 
		    	    // //			 QLog.getLogger().dLog(TAG,  "   app.updateStatistics() cost time:" +(System.currentTimeMillis()-st)); 
				  app.recordingTrack.finishRecording();
				  
				  app.recordingTrack.getTrackBean().setStatus(TrackStatus.FINISHED);
				}catch(NullPointerException e){
					app.clearLastRecordingIdStartTime();
					Utils.logStackTrace(e, TAG);
				}
//			  app.setLastRecordingIdStartTime(); 
//			  app.clearLastRecordingIdStartTime();
			  
			/*  if(app.mStatistics!=null){
				  app.mStatistics.mergeTrack( app.recordingTrack);
				  app.writeStatiscs(); 
			  }*/
				 
//				st=System.currentTimeMillis();
			  app.setCurrentTrack( app.getRecordingTrack());
			  app.recordingTrack=null;
			  app.updateTrackStatus(app.getCurrentTrack().getTrackBean().getTrackId(),QiYouConstant.TRACK_STATUS_FINISHED);
	    	  // //			 QLog.getLogger().dLog(TAG,  "   updateTrackStatus cost time:" +(System.currentTimeMillis()-st)); 

			}
			app.clearLastRecordingIdStartTime();
		    app.initialTrackParameters();
		    app.stopNetworkLocationRequest();
		    
		    stopNaviService();
		    //			 QLog.getLogger().dLog(TAG,  "  navi stopped"); 
//			st=System.currentTimeMillis();

		    app.syncStatistics();
		    
		    // //			 QLog.getLogger().dLog(TAG,  "   app.syncStatistics() cost time:" +(System.currentTimeMillis()-st)); 
		    
//		    updateTabTitle();
		}
		
		boolean blDialog;
		/*
		 * check and confirm with user to start new track or continue the tracking one 
		 */
		protected void newTrackDialog(final boolean isContinue) {
			   AlertDialog.Builder builder = new Builder(this);
			   builder.setMessage("是否终止当前记录，并开始新的记录？");
			   builder.setTitle("提示");
			   builder.setCancelable(false);
			   builder.setPositiveButton("确认", new OnClickListener() {
				   @Override
				   public void onClick(DialogInterface dialog, int which) {
				   dialog.dismiss();	
				   finishRecording();
				 				  
	//				app.forceDbUpdate(true); 
	//			    app.setPreferences(false,false);
	//			    app.playbackPaused=false;
				    if(app.playBack)
				    	startTrackPlayBack(app.currentTrackId);
				    else{
				    	if(isContinue)
	//			    			continueTrack();
				    		 showRecordingTrack(isContinue);
				    		else			    		
				    			startNewTrackMap();
				    }
				    //notice the UI
	
				    
				    dialog.dismiss();			   
					}
				});
			   
			  builder.setNegativeButton("取消", new OnClickListener() {
				 @Override
				 public void onClick(DialogInterface dialog, int which) {
					 dialog.dismiss();
					 
					 }
				 });
			  	builder.create().show();
			 	}
		
		

//		 public StatisticsTrack statisticsTrack;

		 
		private ShareActionProvider mShareActionProvider;
		
		@Override
		public boolean onCreateOptionsMenu(Menu menu) {
			// Inflate the menu; this adds items to the action bar if it is present.
			getMenuInflater().inflate(R.menu.main, menu);
		  /*  
			MenuItem item = menu.findItem(R.id.menu_item_share); 
			    // Fetch and store ShareActionProvider
		     mShareActionProvider = (ShareActionProvider) item.getActionProvider();*/

			return true;
		}
		// Call to update the share intent
		private void setShareIntent(Intent shareIntent) {
		    if (mShareActionProvider != null) {
		        mShareActionProvider.setShareIntent(shareIntent);
		    }
		}
		@Override
		public boolean onMenuItemSelected(int featureId, MenuItem item) {
			switch (item.getItemId()) {
				case android.R.id.home:
//					KeyEvent kv = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK);
//					this.onKeyUp(KeyEvent.KEYCODE_BACK, kv);
//					 ActionBar ab =getActionBar();
//					  if(ab!=null){						  
					 if( tabHost.getTabWidget().getVisibility() ==View.GONE)
						new Thread(){
							   @Override
							public void run() {
							    try{
							     Instrumentation inst = new Instrumentation();
							     inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
							    }
							    catch (Exception e) {
							                 Log.e("Exception when onBack", e.toString());
							             }
							   }
							  }.start();
//					  }			  
							  return true;
			/*	case R.id.action_settings:
					startPrefActivity();
					return true;
				case R.id.action_offline:
					showOffline();
					return true;*/
				case R.id.action_about:
 					showAbout();
					return true;
				case R.id.action_exit:
					saveExit();
//					exit();
					return true;
				case R.id.action_route:
 					 showRoute(0);
 					 return true;
				/*case R.id.action_login:
					showLogin();
					 return true;*/
					 
				 case R.id.menu_item_share:
					doShare();
					 return true; 
				 case R.id.action_main:
					 isTabHome();
			     return true; 
 				 /* case R.id.action_history:
 					this.showLocalTrackList(); 
 			     return true;   */
			     
				/*case R.id.action_regist:
					showRegist();
					 return true;	*/ 
					 
 					
 					 
//				case R.id.action_navi:
//					 startNaviService();
// 					 return true;
 					 
//				case R.id.action_speech:
//					 startSpeech(); 
//					 return true;
					

			/*	case R.id.action_listview:
					  Intent intent = new Intent(this,CursorDSLV.class);
					  
 					 this.startActivity(intent);
					return true;*/
						
					
				default:
					 
					   Fragment frgmnt =  getSupportFragmentManager().findFragmentByTag(app.currentActiveFragment); 
	    	    	  if(frgmnt instanceof TrackTabs_fragment ){
	    	    		  ((TrackTabs_fragment)frgmnt).onContextItemSelected(item);
	    	    	  }
			}
			return false;
		}
		
	 	@SuppressLint("NewApi")
		@Override
	    public boolean onPrepareOptionsMenu(Menu menu){
//	     final int notShow=0;
//	     final int alwaysShow =2;
	     super.onPrepareOptionsMenu(menu);
//	     MenuItem mainItem=menu.findItem( R.id.action_main); 
//	     mainItem.setShowAsAction(app.currentActiveFragment.equalsIgnoreCase(tabHome)?notShow:alwaysShow);
	     
	     /*MenuItem loginItem=menu.findItem( R.id.action_login);
	     String loginTitle ="登录";//loginItem.getTitle().toString();
	     String loginUser =*//* app.user.getUserbean().getAccount();*//*app.user.getUserbean().getUserName();
	     if(TextUtils.isEmpty(loginUser))return true;
	     loginUser=loginUser.length()>20?loginUser.substring(0, 20):loginUser;
	     loginTitle += ( app.user.getUserbean().getId()<=0?"":" ( " + loginUser +" )");
	     loginItem.setTitle(loginTitle);*/
	     
	     return true;
	     
	    } 
		 
	
		public void doShare(){
		/*	Intent shareIntent=getShareIntent();
		    mShareActionProvider.setShareIntent(shareIntent);*/ 
			
			if(isMapActive){  
				ToastMsg("对不起，暂不支持分享地图",Toast.LENGTH_SHORT); 
			}else
				defaultShare();
			
		}
		
		public void doShare(Intent shareIntent){
			 
		    mShareActionProvider.setShareIntent(shareIntent);
		}
		
		/*public Intent getShareIntent() {
		  Intent intent = new Intent(Intent.ACTION_SEND);
		    intent.putExtra(Intent.EXTRA_TEXT, "这里是要分享的文字");
		    intent.setType("text/plain");
//		    intent.setType("image/*");  
		    Intent.createChooser(intent, "Share"); 
		    
		    if(app.getCurrentTrack().getTrackBean().getTrackId()>0){
			    Intent shareIntent = new Intent(Intent.ACTION_SEND);
	//		    Uri uri = Uri.parse("file:///sdcard/image.jpg");
			    FileCache fc= new FileCache(app);
			    Uri uri =fc.getCachedUri(app.getCurrentTrack().getStaticMap()); 
			    shareIntent.setType("* / * ");
			    shareIntent.putExtra(Intent.EXTRA_TEXT, "Body text of the new status");
			    shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
			    shareIntent.putExtra(Intent.EXTRA_SUBJECT, "  EXTRA_SUBJECT text of the new status");
			    shareIntent.putExtra(Intent.EXTRA_TITLE, "  TITLE text of the new status");
			    return shareIntent;
		    }
		    
		    
		    return  intent;
		  }
		*/
		
		
		/*
		 * bottom tabs
		 */
		
		TabHost tabHost;
		TabWidget tabWidget; 
		LinearLayout bottom_layout;
		int CURRENT_TAB = -1;	//设置常量
	
		final int TRACK_STATISTICS=0;
		final int TRACK_TAB=1;
		final int TRACK_WEB=2;
//		final int TRACK_HISTORY =1;
//		final int TRACK_TAB=2;
//		final int TRACK_NOTE=3;
//		final int TRACK_WEB=4;
		
		Track_fragment track_fragment;
		WebList_fragment webList_fragment;
		TrackStatics_fragment trackStatics_fragment;
//		Me_Fragment meFragment;
//		android.support.v4.app.FragmentTransaction ft;
		
		final String tabHome =TrackStatics_fragment.getFTag() ;
		final String tabList=TrackList_fragment.getFTag();
		final String tabWeb=WebList_fragment.getFTag();
		final String tabTrack=Track_fragment.getFTag();
		final String tabNote=NoteList.getFTag();

		final String tabLongway="tabLongway";
		final String tabSetup="setup";
		ColorStateList  colorSelected ;
		ColorStateList  colorUnselected ;
		
		RelativeLayout tabIndicator_home,tabIndicator_history,tabIndicator_track,tabIndicator_web,tabIndicator_note;//,tabIndicator4,tabIndicator5;
		
		 void initialTabs(){
			// //			 QLog.getLogger().d(dTAG, TAG+" app.currentActiveFragment:"+app.currentActiveFragment +",initialTabs() called.");
	        findTabView();
	        tabHost.setup();
	        colorUnselected = getResources().getColorStateList(R.color.white/*darkgrey*/);
	        colorSelected = getResources().getColorStateList(R.color.white);
	       
	        /** 监听*/
	        TabHost.OnTabChangeListener tabChangeListener = new TabHost.OnTabChangeListener(){
				@Override
				public void onTabChanged(String tabId) {
					
					 
					
					// //			 QLog.getLogger().d(dTAG, TAG+" onTabChanged:   app.currentActiveFragment,tabId is:"+ tabId +",CURRENT_TAB is: " +CURRENT_TAB);
					 
					((TextView)tabIndicator_track.getChildAt(1)).setTextColor(colorSelected);
					/** 如果当前选项卡是home */
					if(tabId.equalsIgnoreCase(tabHome) /*&&CURRENT_TAB!=TRACK_STATISTICS*/){
						 // //			 QLog.getLogger().d(dTAG," TrackStatics starting  tab clicked to show trackstatics...  " );
						isTabHome();
					 
					/** 如果当前选项卡是Me */
					}
				 	else if(tabId.equalsIgnoreCase(tabList) /* &&CURRENT_TAB!=TRACK_HISTORY*/){	
// 						CURRENT_TAB = 2;
 						
 						showLocalTrackList();
					 /** 如果当前选项卡是history list */ 
					}  
					else if(tabId.equalsIgnoreCase(tabTrack) /* &&CURRENT_TAB!=TRACK_TAB*/){	
						tabTrackClicked();
					 
						
					/** 如果当前选项卡是track */
					}  else if(tabId.equalsIgnoreCase(tabNote)  /*&&CURRENT_TAB!=3*/){	
//							showNoteList();
							
					 /** 如果当前选项卡是list */ 
					} else if(tabId.equalsIgnoreCase(tabWeb)  /*&&CURRENT_TAB!=TRACK_HISTORY*/){	
						isTabList();
					 
					}
				
					setSelectedTabhostStyle(tabHost);
				}
	        	
	        };
	        //设置初始选项卡  
//	        tabHost.setCurrentTab(0);
	        tabHost.setOnTabChangedListener(tabChangeListener);
	        initTab();
	         /**  设置初始化界面  */
//	        tabHost.setCurrentTab(TRACK_STATISTICS);

	        if(app.isLastTrackExist()){
	        	 tabHost.setCurrentTab(TRACK_TAB);
//	        	tabTrackClicked();
	        }
	        
	        setSelectedTabhostStyle(tabHost);
	    }
			
/*		 public   void setSelectedTabhostStyle(){ 
				TabWidget  tabWidget = tabHost.getTabWidget();
				for (int i =0; i < tabWidget.getChildCount(); i++) {  
				  
				    TextView tv = (TextView) tabWidget.getChildAt(i).findViewById(android.R.id.title);
				//    tv.setTextSize(15);
				    if(i!=tabHost.getCurrentTab()){ 
//				    	tabWidget.getChildAt(i).setBackgroundResource(R.color.lightgray);
				    	tv.setTextColor( getResources().getColorStateList(R.color.lightslategrey));		
//				    	 tv.setTextSize(unSelectedSize);
				    }else{
//				    	 tabWidget.getChildAt(tabhost.getCurrentTab()).setBackgroundResource(R.color.ivory);
		            	 tv.setTextColor( getResources().getColorStateList(R.color.darkslategrey));
//		            	 tv.setTextSize(selectedSize);
				    }
				    
				   }
//				tabhost.getTabWidget().setStripEnabled(true);
			}
		 */
		 
		 
		 
	    //判断当前
	    public void isTabHome(){   //show recording track_fragment
	    	
	    	showTrackStatics();
//	    	
	    	// //			 QLog.getLogger().d(dTAG,TAG+" app.currentActiveFragment: "+ app.currentActiveFragment +", isTabHome called");
 
	    }
	    
	 
	    public void isTabList(){ //show tracklist
	    	// //			 QLog.getLogger().d(dTAG,TAG+" app.currentActiveFragment: "+ app.currentActiveFragment +", isTabList called");
//	    	
	    	showWebList();
//	    	showLocalTrackList();
	    }
	    
	    public void tabTrackClicked(){
	    	// //			 QLog.getLogger().d(dTAG,TAG+" app.currentActiveFragment: "+ app.currentActiveFragment +", isTabTrack called");
//	    	
	    	if(app.isLastTrackExist())
	    		showRecordingTrack(false);
	    	else
	    		 startNewTrackMap();
	    	
	    	 updateTabTitle();
//	    	 tabHost.setCurrentTab(3);
	    }
	    
	    public void selectTabTrack(){ 
	    	CURRENT_TAB =TRACK_TAB;
	    	tabHost.setCurrentTab(CURRENT_TAB);
	    	CURRENT_TAB=-1;
	    	
	    }
	    
	    
	    public   void setSelectedTabhostStyle(TabHost tabhost){ 
			TabWidget  tabWidget = tabhost.getTabWidget();
			for (int i =0; i < tabWidget.getChildCount(); i++) {  
			  
			    TextView tv = (TextView)  ((RelativeLayout)tabWidget.getChildAt(i)).getChildAt(1)/*.findViewById(android.R.id.title)*/;
//			    TextView tv = (TextView) ((RelativeLayout)tabWidget.getChildAt(i)).findViewById(android.R.id.title);
			   
			    ImageView iv = (ImageView) ((RelativeLayout)tabWidget.getChildAt(i)).getChildAt(0);
			    
			    
			    if( tv==null){ 
			    	continue;
			    }
			//    tv.setTextSize(15);
			    if(i!=tabhost.getCurrentTab()){ 
//				    	tabWidget.getChildAt(i).setBackgroundResource(R.color.lightgray);
			    	tv.setTextColor( colorUnselected);	
//			    	tv.setPadding(0, 2, 0, -2);
			    	 tv.setTypeface(null, Typeface.NORMAL); 
			    	 tv.getPaint().setFlags(0);
			    	 
			    	 if (i== TRACK_TAB){
			    		 iv.setImageResource(R.drawable.icon_go_in);
			    	 }else if (i ==TRACK_STATISTICS ){
			    		 iv.setImageResource(R.drawable.icon_award_in);
			    	 }else if (i == TRACK_WEB){
			    		 iv.setImageResource(R.drawable.icon_web_32_in);
			    	 }
			    	 
//			    	 tv.setTextSize(unSelectedSize);
			    }else{
//				    	 tabWidget.getChildAt(tabhost.getCurrentTab()).setBackgroundResource(R.color.ivory);
	            	 tv.setTextColor( colorSelected);
// 	            	 tv.setTextSize(selectedSize);
	            	 tv.setTypeface(null, Typeface.BOLD); 
//	            	 tv.setPadding(0, 2, 0, -2);
	            	 tv.getPaint().setFlags(0);//Paint.UNDERLINE_TEXT_FLAG);
	            	 
	            	 if (i== TRACK_TAB){
			    		 iv.setImageResource(R.drawable.icon_go);
			    	 }else if (i ==TRACK_STATISTICS ){
			    		 iv.setImageResource(R.drawable.icon_award);
			    	 }else if (i == TRACK_WEB){
			    		 iv.setImageResource(R.drawable.icon_web_32);
			    	 }
			    	 
			    }
			    
			    
			    if(i==TRACK_TAB){
			    	updateTabTitle();
			    	 
			    	continue;
			    }
			    
			   
			    
			   }
//			tabhost.getTabWidget().setStripEnabled(true);
		}
	 
	    
	    
	    /**
	     * 找到Tabhost布局
	     */
	    public void findTabView(){
	    	
	    	 tabHost = (TabHost) findViewById(android.R.id.tabhost);
	         tabWidget = (TabWidget) findViewById(android.R.id.tabs);
	         LinearLayout layout = (LinearLayout)tabHost.getChildAt(0);
	         TabWidget tw = (TabWidget)layout.getChildAt(1);
	         
	        
	         
	         tabIndicator_home = (RelativeLayout) LayoutInflater.from(this)
		         		.inflate(R.layout.tab_indicator, tw, false);
		         TextView tvTab1 = (TextView)tabIndicator_home.getChildAt(1);
  		         ImageView ivTab1 = (ImageView)tabIndicator_home.getChildAt(0);
     	         ivTab1.setBackgroundResource(R.drawable.icon_award);
 		         tvTab1.setText(R.string.bottom_me);
		         
 
 		   /*      
 		    tabIndicator_history = (RelativeLayout) LayoutInflater.from(this)
	         		.inflate(R.layout.tab_indicator, tw, false);
 	         TextView tvTab2 = (TextView)tabIndicator_history.getChildAt(1);
//	         ImageView ivTab2= (ImageView)tabIndicator_home.getChildAt(0);
//	         ivTab2.setBackgroundResource(R.drawable.main_history);
 		         tvTab2.setText(R.string.bottom_list);
		         */
 		         
 		         
	         
		    int trackingTitle= R.string.bottom_new_track ; 
		   
		    tabIndicator_track = (RelativeLayout) LayoutInflater.from(this)
	         		.inflate(R.layout.tab_indicator/*_camera*/, tw, false);
	         TextView tvTab3 = (TextView)tabIndicator_track.getChildAt(1);
  	         ImageView ivTab3 = (ImageView)tabIndicator_track.getChildAt(0);
   	         ivTab3.setBackgroundResource(R.drawable.icon_go);
   	         
	         tvTab3.setTypeface(null, Typeface.NORMAL); 
	         tvTab3.setTextColor(getResources().getColorStateList(R.color.white));
	         if(app.isLastTrackExist()){
			    	trackingTitle =R.string.bottom_tracking ;
			    	tvTab3.setTypeface(null, Typeface.BOLD); 
			    	tvTab3.setTextColor(getResources().getColorStateList(R.color.wheat));
			    }
	         tvTab3.setText(trackingTitle); 
	          
	 
	         tabIndicator_web = (RelativeLayout) LayoutInflater.from(this)
	         		.inflate(R.layout.tab_indicator, tw, false);
	         TextView tvTab4 = (TextView)tabIndicator_web.getChildAt(1);
	         ImageView ivTab4 = (ImageView)tabIndicator_web.getChildAt(0);
	         ivTab4.setBackgroundResource(R.drawable.icon_web_32);
	         tvTab4.setText(R.string.bottom_web);
	         
	          /*
	         tabIndicator_note = (RelativeLayout) LayoutInflater.from(this)
		         		.inflate(R.layout.tab_indicator, tw, false);
		         TextView tvTab5 = (TextView)tabIndicator_note.getChildAt(1);
//		         ImageView ivTab5 = (ImageView)tabIndicator_web.getChildAt(0);
//		         ivTab5.setBackgroundResource(R.drawable.mian_note);
		         tvTab5.setText(R.string.bottom_note);
	         */
	         
	    }
	    
		  /** 
	     * 初始化选项卡
	     * 
	     * */
	    public void initTab(){
	    	
	        TabHost.TabSpec tSpecHome = tabHost.newTabSpec(tabHome);
	        tSpecHome.setIndicator(tabIndicator_home);        
	        tSpecHome.setContent(new DummyTabContent(getBaseContext()));
	        tabHost.addTab(tSpecHome);
	        
	        
//	        TabHost.TabSpec tSpecHistory = tabHost.newTabSpec(tabList);
//	        tSpecHistory.setIndicator(tabIndicator_history);        
//	        tSpecHistory.setContent(new DummyTabContent(getBaseContext()));
//	        tabHost.addTab(tSpecHistory);
	        
	         
	       TabHost.TabSpec tSpecTrack = tabHost.newTabSpec(tabTrack);
	        tSpecTrack.setIndicator(tabIndicator_track);        
	        tSpecTrack.setContent(new DummyTabContent(getBaseContext()));
	        tabHost.addTab(tSpecTrack);
	        
	        tabIndicator_track.setOnClickListener(new android.view.View.OnClickListener() {
				@Override
				public void onClick(View v) {
					tabTrackClicked();
				}

			 
			});
	        
	        
//	        TabHost.TabSpec sSpecNotes = tabHost.newTabSpec(tabNote);
//	        sSpecNotes.setIndicator(tabIndicator_note);      
//	        sSpecNotes.setContent(new DummyTabContent(getBaseContext()));
//	        tabHost.addTab(sSpecNotes);
	        
	        
	        TabHost.TabSpec tSpecList = tabHost.newTabSpec(tabWeb);
	        tSpecList.setIndicator(tabIndicator_web);      
	        tSpecList.setContent(new DummyTabContent(getBaseContext()));
	        tabHost.addTab(tSpecList);
	        
	        /*TabHost.TabSpec tSpecLongway = tabHost.newTabSpec(tabLongway);
	        tSpecLongway.setIndicator(tabIndicator_longway);      
	        tSpecLongway.setContent(new DummyTabContent(getBaseContext()));
	        tabHost.addTab(tSpecLongway);*/
	    }
	    
	   public void updateTabTitle(){ 
			if(tabHost==null)return;
			 
			boolean isSporting =app.isNaving||app.isLastTrackExist();
//			String title=isVisible?tabData:app.isLastTrackExist()?"数据加载中。。。":tabData; 
			int  title=app.isNaving?(app.isLastTrackExist()?R.string.bottom_navi:R.string.bottom_new_track ): (app.isLastTrackExist()?R.string.bottom_tracking:R.string.bottom_new_track ); 
			
			TextView textview =   (TextView)tabIndicator_track.getChildAt(1);//(TextView)tabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.title);	
 			
			  if(textview==null){
				  return;
			  }
 			
 			textview.setTypeface(null, Typeface.NORMAL); 
 			textview.setTextColor(getResources().getColorStateList(R.color.white));
	         if(isSporting){
	        	  
			    	textview.setTypeface(null, Typeface.BOLD); 
			    	textview.setTextColor(getResources().getColorStateList(R.color.gold));
			    }
	         
	       textview.setText(title);  
 			
		  
		} 
	   
	   public void updateTabVisibility(boolean visible ){
		   
//		   int visibility =visible?View.VISIBLE:View.GONE;
		   updateActionBar(!visible);
//		   if( tabHost.getTabWidget().getVisibility() ==visibility)return;
		    
		   
		   if(visible){
//			   tabHost.setCurrentTab(0);
//			   isTabHome();
			   
			   // //			 QLog.getLogger().d(dTAG,TAG+" updateTabVisibility, app.currentActiveFragment: "+app.currentActiveFragment);
			   
			   if(app.currentActiveFragment.equalsIgnoreCase(tabHome)){
				   tabHost.setCurrentTab(TRACK_STATISTICS);
//			   }
				   // //			 QLog.getLogger().d(dTAG,TAG+" setCurrentTab(0) " );
//				   isTabHome();
			   }else if(app.currentActiveFragment.equalsIgnoreCase(tabList)){
//				   tabHost.setCurrentTab(TRACK_HISTORY);
				   // //			 QLog.getLogger().d(dTAG,TAG+" setCurrentTab(TRACK_HISTORY) " );
//				   isTabList();
//				   isTabHome() ;
			   }
	 
			   else if(app.currentActiveFragment.equalsIgnoreCase(TrackDetail_fragment.getFTag()) ){				   
//					   updateTabVisibility(false);
					   // //			 QLog.getLogger().d(dTAG,TAG+" setCurrentTab(track detail) " );
			   }
			   else if(app.currentActiveFragment.equalsIgnoreCase(GpxDetail_fragment.getFTag()) ){				   
//				   updateTabVisibility(false);
				   // //			 QLog.getLogger().d(dTAG,TAG+" setCurrentTab(gpx detail) " );
			   }
			   else if(app.currentActiveFragment.equalsIgnoreCase(WebList_fragment.getFTag()) ){	
				   tabHost.setCurrentTab(TRACK_WEB);
//				   updateTabVisibility(false);
				   // //			 QLog.getLogger().d(dTAG,TAG+" setCurrentTab(gpx detail) " );
			   }
			    else if(app.currentActiveFragment.equalsIgnoreCase(Route_fragment.getFTag()) ){				   
 				 
			   }   else if(app.currentActiveFragment.equalsIgnoreCase(ActivityDetail.getFTag()) ){				   
//				   updateTabVisibility(false);
				   // //			 QLog.getLogger().d(dTAG,TAG+" setCurrentTab(Route detail) " );
			     
			   
		   		}   else if(app.currentActiveFragment.equalsIgnoreCase(ActivityHome.getFTag()) ){				   
//			   updateTabVisibility(false);
			  		 QLog.getLogger().d(dTAG,TAG+" setCurrentTab(ActivityHome detail) " );
		   		}  
		   	 else if(app.currentActiveFragment.equalsIgnoreCase(GroupHome.getFTag()) ){				   
//				   updateTabVisibility(false);
				  		 QLog.getLogger().d(dTAG,TAG+" setCurrentTab(GroupHome detail) " );
			   		}  
			   else if(app.currentActiveFragment.equalsIgnoreCase(UserDetails.getFTag()) ){				   
 
			   } else if(app.currentActiveFragment.equalsIgnoreCase(UserHome.getFTag()) ){				   
 
			   }else if(app.currentActiveFragment.equalsIgnoreCase(GroupDetail.getFTag()) ){				   
 
			   } else if(app.currentActiveFragment.equalsIgnoreCase(NoteList.getFTag()) ){				   
 
			   } else if(app.currentActiveFragment.equalsIgnoreCase(NoteDetail.getFTag()) ){				   
 
			   }    else if(app.currentActiveFragment.equalsIgnoreCase(NoteNew.getFTag()) ){				   
 
			   } 
			   
			   
			   else if(app.currentActiveFragment.equalsIgnoreCase(Playback_fragment.getFTag()) ){				   
				   updateTabVisibility(false);
				   // //			 QLog.getLogger().d(dTAG,TAG+" setCurrentTab(playback) " );
			   }
			   else if(app.currentActiveFragment.equalsIgnoreCase(LocationPickerFragment.getFTag()) ){				   
 
			   } 
			   
			   else if(app.isLastTrackExist() && app.currentActiveFragment.equalsIgnoreCase(Track_fragment.getFTag()) ){	//cancel recording goes here now 
					   tabHost.setCurrentTab(TRACK_TAB);
				   // //			 QLog.getLogger().d(dTAG,TAG+" setCurrentTab(TRACK_TAB) " );
			   }	
			   else{
				  
				   if(tabHost.getCurrentTab() ==TRACK_STATISTICS)
					   isTabHome() ;
				   else
					   tabHost.setCurrentTab(TRACK_STATISTICS);
				   // //			 QLog.getLogger().d(dTAG,TAG+" setCurrentTab(TRACK_STATISTICS) " );
			   }
			     
		   }
		 
		   
		   updateTabTitle();
		   tabHost.getTabWidget().setVisibility(visible?View.VISIBLE:View.GONE);	
	   }
	   
		

		@TargetApi(Build.VERSION_CODES.HONEYCOMB)
		 public void updateActionBar(boolean enable ){
		
		if(Utils.getAndroidSDKVersion()<Build.VERSION_CODES.HONEYCOMB)return;
	  
		ActionBar ab =getActionBar();
		  if(ab!=null){
//			  ab.setDisplayShowHomeEnabled(enable);
			  ab.setDisplayHomeAsUpEnabled(enable) ;
			  ab.setLogo(R.drawable.icon_ablogo);
//		   if(Utils.getAndroidSDKVersion()>Build.VERSION_CODES.JELLY_BEAN_MR2){
//			  ab.setHomeAsUpIndicator(R.drawable.icon_back);  
//		   }
//			  ab.setSubtitle(enable?" can be back ":"can not back"); 
			  if(!enable)
				  ab.setTitle(R.string.title_activity_main);
		  }
		} 
		
		@TargetApi(Build.VERSION_CODES.HONEYCOMB)
		 public void updateActionBarTitle(int title ){
			if(Utils.getAndroidSDKVersion()<Build.VERSION_CODES.HONEYCOMB)return;
		  ActionBar ab =getActionBar();
		  if(ab!=null){ 
			  ab.setTitle(title);
			 
 
		  }
		}  
		@TargetApi(Build.VERSION_CODES.HONEYCOMB)
		 public void updateActionBarTitle(String title ){
			if(Utils.getAndroidSDKVersion()<Build.VERSION_CODES.HONEYCOMB)return;
		  ActionBar ab =getActionBar();
		  if(ab!=null){ 
			  ab.setTitle(title);

		  }
		}  
		
		/*
		 * onFiling
		 */
		 public GestureDetector gestureDetector;	 
		 @Override
			public boolean dispatchTouchEvent(MotionEvent ev) {
				if (gestureDetector!=null && gestureDetector.onTouchEvent(ev)) {
					ev.setAction(MotionEvent.ACTION_CANCEL);
				}
				return super.dispatchTouchEvent(ev);
			}
		 
		 
		 public float getMiddleSizeFont(){ 
			 return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 24, this.getResources().getDisplayMetrics());
		 }
		 
		 
			public  int getFontSize( ) {
//				 Point outSize = new Point();
//				 getWindowManager().getDefaultDisplay().getSize(outSize);
//				 
//			    int screenWidth=outSize.x>outSize.y?outSize.x:outSize.y;  
				 int screenWidth =getWindowManager().getDefaultDisplay().getWidth();
				 int screenHeight =getWindowManager().getDefaultDisplay().getHeight();
				screenWidth=screenWidth>screenHeight?screenWidth:screenHeight;   
			    int rate = (int)(5*(float) screenWidth/320);
			    return rate<14?14:rate;   
			} 
			
			@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
			private  void getScreenSize( ) {
//				 Point outSize = new Point();
//				 getWindowManager().getDefaultDisplay().getSize(outSize);
//				 
//			    int screenWidth=outSize.x>outSize.y?outSize.x:outSize.y;
				if(QiYouConstant.PV_INT_SCREEN_WIDTH>0)return;
				Point outSize= new Point();
				outSize.set(480, 800);
				try{
					if(Utils.getAndroidSDKVersion()>=Build.VERSION_CODES.JELLY_BEAN_MR1)
						getWindowManager().getDefaultDisplay().getRealSize(outSize);
				}catch(Exception e){
					Utils.logStackTrace(e, TAG);
				}
				app.setScreenInfo(outSize); 
			} 
			
			
			
			
			
			
			@Override
			public void onPause() { 
				super.onPause(); 
	 			unregisterReceiver(receiver);
	 			app.isUIactive=false;
	 			MobclickAgent.onPause(this);

			}

			@Override
			public void onResume() {
			 
				super.onResume(); 
				registerReceiver(receiver, filter);
//				Toast toast=	Toast.makeText(this, TAG+" current recording track status:" +app.getRecordingTrack().getTrackBean().getStatus(), Toast.LENGTH_LONG );
//			    toast.show(); 
				if(app.canRecord() )//|| app.getRecordingTrack().getTrackBean().getStatus()==QiYouConstant.TRACK_STATUS_TRACKING)
				{				
					//app.stopAndroidGPSRequest();
					if(app.isLostGps())
						app.startAndroidGPSRequest(); //if duplicated called lm.requestLocationUpdates, will request more or no impact?
//				    toast=	Toast.makeText(this, TAG+" start GPS　requeest once more.", Toast.LENGTH_LONG );
//				    toast.show(); 
				}
				app.isUIactive=true;
				app.updateStatistics();
				app.getPreferences();
				MobclickAgent.onResume(this);

			}

			@Override
			public void onDestroy() {
//				Log.d(TAG,TAG+" The MainActivity is going to be destroied.");
//				 Toast toast=	Toast.makeText(this, TAG+" The MainActivity is going to be destroied.", Toast.LENGTH_LONG );
//			 	 toast.show(); 
//				app.stopAndroidGPSRequest();
			 	 app.setPreferences(false,false);
//			 	 mTts.stopSpeaking(mTtsListener);
//			        // 閫?嚭鏃堕噴鏀捐繛鎺?
//			     mTts.destory();
				super.onDestroy();		
			}
		
			public final MediaScannerConnection msc = new MediaScannerConnection((QiYouApplication) getApplication(), new MediaScannerConnectionClient() {   
				  @Override
				   public void onMediaScannerConnected() {   
//				    msc.scanFile("/sdcard/image.jpg", "image/jpeg");   
				   }  
				  @Override 
				   public void onScanCompleted(String path, Uri uri) {   
				   
//				    msc.disconnect();   
				   }   
				  });  
			
			void startWelcome(){
				Intent it = new Intent(MainActivity.this,Welcome.class);
				startActivity(it);
//				overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
//				Welcome.this.finish();
				
			}
			
			void setVolume(){
				/*<uses-permission Android:name="android.permission.MODIFY_AUDIO_SETTINGS" />*/
				 setVolumeControlStream(AudioManager.STREAM_MUSIC);
				/* MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.gogo);
				 mediaPlayer.setVolume(1.0f, 1.0f);
				 mediaPlayer.start();*/
			}
			
			
			String SCOPE = "get_simple_userinfo,add_topic";//所有权限用“all”
			public void doQQLogin() {
				IUiListener listener = new BaseUiListener() {
					@Override
					protected void doComplete(/*JSONObject*/Object values) {
						onAuth20LoginComplete(values);
					}
				};
				mTencent.login(this, SCOPE, listener);
			}

			private void onAuth20LoginComplete(Object values){
				JSONObject json =(JSONObject)values;
				
				try {
					QiYouConstant.PV_OPEN_ID =json.getString("openid");
					QiYouConstant.PV_ACCESS_TOKEN =json.getString("access_token");
					QiYouConstant.PV_EXPIRES_IN =System.currentTimeMillis()+Long.parseLong(json.getString("expires_in"))*1000;
				    app.saveAuth20Token(); 
					 
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				
				
				
				
				
				
			}
			
			private class BaseUiListener implements IUiListener {
				@Override
				public void onComplete(Object response) {
				     //V2.0版本，参数类型由JSONObject 改成了Object,具体类型参考api文档
//				mBaseMessageText.setText("onComplete:");
					//			 QLog.getLogger().d(dTAG, "Tencent Auth2.0 on Complete.");
				doComplete(response);
				}
				protected void doComplete(/*JSONObject*/Object values) {

				}
				@Override
				public void onError(UiError e) {
					//			 QLog.getLogger().e("onError:", "code:" + e.errorCode + ", msg:"0	+ e.errorMessage + ", detail:" + e.errorDetail);
				}
				@Override
				public void onCancel() {
//				showResult("onCancel", "");
				}
				 
				}
			
}

