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

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.client.CookieStore;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnTouchListener;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.MySSLSocketFactory;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.qiyou.mb.android.QiYouApplication;
import com.qiyou.mb.android.QiYouConstant;
import com.qiyou.mb.android.R;
import com.qiyou.mb.android.R.color;
import com.qiyou.mb.android.beans.Track;
import com.qiyou.mb.android.beans.basic.Activity_bean;
import com.qiyou.mb.android.beans.basic.Group_bean;
import com.qiyou.mb.android.beans.basic.Media;
import com.qiyou.mb.android.beans.basic.Track_bean;
import com.qiyou.mb.android.beans.basic.User_bean;
import com.qiyou.mb.android.beans.basic.Waypoint;
import com.qiyou.mb.android.beans.basic.Waypoint_bean;
import com.qiyou.mb.android.ui.MainActivity;
import com.qiyou.mb.android.utils.FileUtil;
import com.qiyou.mb.android.utils.GoogleEleResult;
import com.qiyou.mb.android.utils.LocationEle;
import com.qiyou.mb.android.utils.QSimpleAdapter;
import com.qiyou.mb.android.utils.Utils;
import com.qiyou.mb.android.utils.enums.TrackAvStatus;
import com.qiyou.mb.android.utils.enums.mediaStatus;
import com.qiyou.mb.android.utils.enums.mediaType;
import com.qiyou.mb.android.utils.exception.NoWebObjectException;
import com.qiyou.mb.android.utils.image.ImageUtil;
import com.qiyou.mb.android.utils.log.QLog;
import com.qiyou.mb.android.utils.server.RestMethods;
import com.umeng.analytics.MobclickAgent;

public abstract class QiyouFragment extends Fragment {
	 
	public static String TAG ="need to be replaced";
	public static final String dTAG ="com.qiyou";
	public int trackId;
	protected MainActivity activity; 
	protected View vContainer;
//	protected float mediumFontSize;
	protected boolean isCateQuery=false; // the fragment is to query cates or not.
	protected TextView mNoteText;
	protected LinearLayout ll_note;
	protected com.qiyou.mb.android.ui.fragments.InnerGridView cateLv  ;
	protected Track mTrack =null;
	protected Track_bean mTrack_bean =null; 
	protected boolean isLoginForShare=false;
	protected boolean isWebRequest =false;
	protected SwipeRefreshLayout mSwipeLayout;
	// Progress Dialog Object
	 Dialog prgDialog;
	 ProgressBar mProgress ;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		activity =(MainActivity)getActivity(); 
		setFTag();
		if(activity!=null &&activity.app!=null)
			activity.app.currentActiveFragment =TAG;
		//			 QLog.getLogger().e(dTAG,TAG+" "+ "onCreate");
//		mediumFontSize = activity.getMiddleSizeFont();
	}
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		if (vContainer!=null){
		this.vContainer. setOnTouchListener(new OnTouchListener() {
			    @Override
			    public boolean onTouch(View v, MotionEvent event) {
	 		        Utils.hideSoftKeyboard(activity);
			        return false;
			    }
			});
		}
		initialGestureDetector();
//		  selectedSize =(int) getResources().getDimensionPixelOffset(R.dimen.text_size);
//		  unSelectedSize =(int) getResources().getDimensionPixelOffset(R.dimen.text_m_size);
		
	}	 
	@Override
	public void onResume() {
		/**
		 * MapView的生命周期与Activity同步，当activity恢复时需调用MapView.onResume()
		 */ 
	   	activity.app.currentActiveFragment = getCurrentTag();

 		//			 QLog.getLogger().e(dTAG,TAG+" onResume(), app.currentActiveFragment: "+activity.app.currentActiveFragment);
		
	   	activity.updateTabVisibility(isShowBottomTabs());
	   	setSelectedTab();
	   	setFTag();
	   	super.onResume();
	   	MobclickAgent.onPageStart(TAG);      //统计页面，

	}
	
	@Override
	public void onPause(){
		super.onPause();
		MobclickAgent.onPageEnd(TAG);      //统计页面，
	}
	
	
	protected void setSelectedTab(){
//		//			 QLog.getLogger().d(dTAG,TAG+" tabhost.getCurrentTab() "+tabhost.getCurrentTab());
//		//			 QLog.getLogger().d(dTAG,TAG+" currentTab "+currentTab);
	 	if(tabhost!=null&& tabhost.getCurrentTab()!=currentTab){
	   		tabhost.setCurrentTab(currentTab);
	   	}
	}
	
	public abstract boolean isShowBottomTabs() ;
	public User_bean getUser(){
		return activity==null?new User_bean():activity.app.user.getUserbean();
	}
	
	public boolean isAdmin(){
		return activity==null?false:activity.app.isAdmin();
	}
//	public  abstract static String getFTag();
//	{
//		return TAG;
//	}
	
//	public abstract String getCurrentTag()
	 
	public String getCurrentTag() { 
		setFTag();
		return TAG;
	}
//	{
//		return TAG;
//	}
	
	public   abstract void setFTag();
//	{
//		TAG="need to be replaced";
//		
//	}
	
	public abstract void setTabOnFiling();
	
	
	 protected  int MAPVIEW_INDEX=-1;
	 protected   int maxTabIndex = -1;
	 protected TabHost tabhost; 
	 protected int currentTab = 0;
		
		// *********************************
		private  final int SWIPE_MIN_DISTANCE = 120;
		private  final int SWIPE_MAX_OFF_PATH = 150;
		private    int SWIPE_THRESHOLD_VELOCITY =20 ;
	    private    int MAPVIEW_THRESHOLD_VELOCITY ;
		View.OnTouchListener gestureListener;
	
		@SuppressWarnings("deprecation")
		void initialGestureDetector(){
	     setTabOnFiling();
		 activity.gestureDetector = new GestureDetector(new MyGestureDetector());		 
		 int maxV =ViewConfiguration.get(activity).getScaledMaximumFlingVelocity();
//		 SWIPE_THRESHOLD_VELOCITY =maxV/50;
		 MAPVIEW_THRESHOLD_VELOCITY =(int) (maxV*0.332);
		 // //			 QLog.getLogger().d(dTAG, TAG+" onFiling: SWIPE_THRESHOLD_VELOCITY " +SWIPE_THRESHOLD_VELOCITY+",MAPVIEW_THRESHOLD_VELOCITY is "+MAPVIEW_THRESHOLD_VELOCITY);
			
			gestureListener = new View.OnTouchListener() {
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					if ( activity.gestureDetector.onTouchEvent(event)) {
						return true;
					}
					return false;
				}
			};
		 }

		// 左右<strong>滑动</strong>刚好页面也有<strong>滑动</strong><strong>效果</strong>
		class MyGestureDetector extends SimpleOnGestureListener {
			@Override
			public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
					float velocityY) { 
				
				if(tabhost==null)return false;
				
				maxTabIndex = tabhost.getTabWidget().getChildCount();
				
				if(currentTab ==MAPVIEW_INDEX){
					return false; //mapview not effect
				}
				
				if(maxTabIndex==-1)return false;
				try {
					
                QLog.getLogger().d(dTAG, String.format("%s onFiling: currentTab is %s,currentTab ==MAPVIEW_INDEX? %s" +
                		" ,velocityX is  %s" ,TAG,currentTab,currentTab ==MAPVIEW_INDEX,velocityX));

					int swip_threshold_v =currentTab ==MAPVIEW_INDEX?MAPVIEW_THRESHOLD_VELOCITY:SWIPE_THRESHOLD_VELOCITY;
//					//			 QLog.getLogger().d(dTAG, TAG+" onFiling: currentTab is " +currentTab+",velocityX is "+velocityX);
//					//			 QLog.getLogger().d(dTAG, TAG+" Math.abs(e1.getY() - e2.getY()) "+Math.abs(e1.getY() - e2.getY()));
					if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
						return false;
					// right to left swipe
					activity.app.updateSlidTabs();
					if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
							&& Math.abs(velocityX) > swip_threshold_v) {
						Log.i("test", "right");
						if (currentTab == maxTabIndex) {
							currentTab = 0;
						} else {
							currentTab++;
						}
						tabhost.setCurrentTab(currentTab);
					} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
							&& Math.abs(velocityX) > swip_threshold_v) {
						Log.i("test", "left");
						if (currentTab == 0) {
							currentTab = maxTabIndex;
						} else {
							currentTab--;
						}
						tabhost.setCurrentTab(currentTab);
					}
				} catch (Exception e) {
				}
				return false;
			}
		}
		
		 protected void onMyTabChanged(String tabId){
			 if(tabhost==null)return;
//			 initialTabhostStyle(tabhost);
			 setSelectedTabhostStyle(tabhost);
			 currentTab= tabhost.getCurrentTab();
			 hideNotes();
			 
		 }
		
//			private int selectedSize ;
//			private int unSelectedSize  ;
		 
	
// 		 int FirstTabBackGround ;
 	 
//		 ColorStateList FirstTabTextColor;
		 
		@TargetApi(Build.VERSION_CODES.FROYO)
		    void initialTabhostStyle(TabHost tabhost){ 
			int height= getResources().getDimensionPixelSize(R.dimen.tab_top_height);
			
			int width=-1;
				TabWidget  tabWidget = tabhost.getTabWidget();
				for (int i =0; i < tabWidget.getChildCount(); i++) {  
//					if( tabWidget.getChildAt(i).getId() == R.id.tab_toolbar)continue;
				    tabWidget.getChildAt(i).getLayoutParams().height = height; 
				    tabWidget.getChildAt(i).getLayoutParams().width = width;
				    TextView tv = (TextView) tabWidget.getChildAt(i).findViewById(android.R.id.title);
				    if(tv==null){
				    	continue;
				    }
				    
				    tv.setPadding(5, 0, 0, 0);
				    
				    if(i>0){
//				    	tv.setTextColor( getResources().getColorStateList(R.color.lightslategrey));
				    	tv.setTextColor( getResources().getColorStateList(R.color.darkgray));
//				        tv.setTextSize(unSelectedSize);
// 				    	tabWidget.getChildAt(i).setBackgroundResource(R.color.lightgray);
				    }else{
				    	
				    	

//				    	tv.setTextSize(selectedSize);
				        tv.setTextColor( getResources().getColorStateList(R.color.darkslategrey));
				       /* tv.setLayoutParams(new  LayoutParams(    LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
// 				        tv.setBackgroundColor(color.darkslategrey) ;
 				        tv.setGravity(Gravity.CENTER_VERTICAL);*/
 				          
				        
//				        if(FirstTabTextColor!=null){
//				        	tv.setTextColor(FirstTabTextColor);
//
//				        	 
//				        }
//				        tv.setBackgroundResource(color.darkslategrey); 
				    }
				    
//				    addPic((LinearLayout)tabWidget.getChildAt(i),i,tabWidget.getChildCount());
				     
				    
				   }
// 				tabhost.getTabWidget().setStripEnabled(true);
			}
		
		 
		/*
		void addPic(LinearLayout ll,int currentTab,int  tabsCnt){
			  if(FirstTabBackGround==0  ){
			    	 return;
			    }
			     ImageView	iv = new ImageView(activity); 
		 		 iv.setBackgroundResource(FirstTabBackGround);
		 		 
		 		 try{
		 			 ll.setGravity(Gravity.CENTER_VERTICAL);
		 			 ll.addView(iv,0);
//		 			ll.setLayoutParams(new  LayoutParams(    LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
//		 			ll.setBackgroundColor(color.darkslategrey) ;
		 			 if(tabsCnt>4){
		 				 ll.setPadding(10, 0, 0, 0);
		 			 }
		 		 }catch(ClassCastException e){
		 			 
		 		 }
		        
		}*/
		
		
		/*TabHost.TabSpec getTab(String label, int drawableId, int content) {
 			TabHost.TabSpec spec = tabhost.newTabSpec(label);
			 
			View tabIndicator = LayoutInflater.from(activity).inflate(R.layout.tab_indicator, tabhost.getTabWidget(), false);
			TextView title = (TextView) tabIndicator.findViewById(R.id.title);
			title.setText(label);
			ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
			icon.setImageResource(drawableId); 
			spec.setIndicator(tabIndicator);
			spec.setContent(content);
 			return spec;
		 }
		*/
		
		
		
		
		
		
		 public   void setSelectedTabhostStyle(TabHost tabhost){ 
				TabWidget  tabWidget = tabhost.getTabWidget();
				for (int i =0; i < tabWidget.getChildCount(); i++) {  
				  
				    TextView tv = (TextView)  tabWidget.getChildAt(i).findViewById(android.R.id.title);
//				    TextView tv = (TextView) ((RelativeLayout)tabWidget.getChildAt(i)).findViewById(android.R.id.title);
				   
				    if(tv==null){
				    	continue;
				    }
				//    tv.setTextSize(15);
				    if(i!=tabhost.getCurrentTab()){ 
// 				    	tabWidget.getChildAt(i).setBackgroundResource(R.color.lightgray);
				    	tv.setTextColor( getResources().getColorStateList(R.color.darkgray));		
//				    	 tv.setTextSize(unSelectedSize);
				    }else{
// 				    	 tabWidget.getChildAt(tabhost.getCurrentTab()).setBackgroundResource(R.color.ivory);
		            	 tv.setTextColor( getResources().getColorStateList(R.color.darkslategrey));
//		            	 tv.setTextSize(selectedSize);
				    }
//				    if(i==0 )
//				    	  if(FirstTabTextColor!=null){
//					        	tv.setTextColor(FirstTabTextColor);
////					        	 tabWidget.getChildAt(0).setBackgroundColor(color.darkslategrey) ;
//					        }
				    
				   }
//				tabhost.getTabWidget().setStripEnabled(true);
			}
		 
		 protected void showCategoryList(com.qiyou.mb.android.ui.fragments.InnerGridView cateLv , ScrollView textContainer ){
				if(activity.app.mStatistics==null)return; 
				 HashMap<String,ArrayList<Integer>> cates= activity.app.mStatistics.getCategoryList();
				 
				 List<Map<String, String>> cateList = new ArrayList<Map<String, String>>();
				 HashMap<String, String> map;
				 final String FLAG=",.*&";
				 final String ID_FLAG=FLAG+trackId; 
				 for(String cate:cates.keySet()){
					 map =new HashMap<String, String>();
					 map.put("cate", cate);
					 map.put("chk", cate);
					 if(trackId>0)
					 for(int id:cates.get(cate)){
						 if(id==trackId){
							 map.put("chk", cate+ID_FLAG);
						 
						 }
					 }
					 cateList.add(map);
				 }
				  
				 
				  QSimpleAdapter   adapter = new QSimpleAdapter(activity,cateList,R.layout.category_list_detail,
							new String[]{"cate","chk"},
							new int[]{R.id.txt_cate,R.id.chk_cate}); 
//				  ArrayList<String> srcs = activity.app.getImportedGpxFileList();	
			      adapter.setViewBinder( new ViewBinder(){
				  	@Override
				    public boolean setViewValue(View view, Object data,String textRepresentation) {    		
//			  		 
			  		if(view.getId()==R.id.chk_cate){
						CheckBox cb = (CheckBox) view;
						String value= (String)data;
						String tmp="";
						if(isCateQuery){ 
								cb.setChecked(activity.app.getQueryCategoryList().contains(value) );  
						}
						else
						if(value.indexOf(FLAG)>0){
							cb.setChecked(true ); 
							tmp=value.substring(0,value.indexOf(FLAG));
						}
						final String CATE=TextUtils.isEmpty(tmp)?value:tmp; 
						 // //			 QLog.getLogger().d(dTAG, "trackId is" + trackId +",CATE is" +CATE  ); 
						cb.setOnCheckedChangeListener(new  CheckBox.OnCheckedChangeListener(){
						    @Override
							public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
						    	
//						    	//			 QLog.getLogger().d(dTAG, "trackId is" + trackId +",CATE is" +CATE +", isDel "+!isChecked);
						    	//			 QLog.getLogger().d(dTAG, " isCateQuery? " +isCateQuery+", CATE is " +CATE );
								if(isChecked){
									if(isCateQuery){
										if(!activity.app.getQueryCategoryList().contains(CATE))
											activity.app.getQueryCategoryList().add(CATE);
									}else{
									
										if(activity.app.getNewCategoryList().get(trackId) ==null){
											activity.app.getNewCategoryList().put(trackId, new ArrayList<String>());
										}
										if(!activity.app.getNewCategoryList().get(trackId).contains(CATE))
											activity.app.getNewCategoryList().get(trackId).add(CATE);
									}
								}else{
									if(isCateQuery){
										if(activity.app.getQueryCategoryList().contains(CATE))
											activity.app.getQueryCategoryList().remove(CATE);
									}else{
										
										//			 QLog.getLogger().d(dTAG, " isCateQuery? " +isCateQuery+", CATE is " +CATE );
										
											if(activity.app.getNewCategoryList().get(trackId) !=null 
												&&activity.app.getNewCategoryList().get(trackId).contains(CATE)){
												activity.app.getNewCategoryList().get(trackId).remove(CATE); 
											}else{							
												
												if(activity.app.getDelCategoryList().get(trackId) ==null ){
													activity.app.getDelCategoryList().put(trackId, new ArrayList<String>());								
												}
												if(!activity.app.getDelCategoryList().get(trackId).contains(CATE)){
													activity.app.getDelCategoryList().get(trackId).add(CATE);
												}								
												
											} 
									}
								}
								 
						  }

							 
					   }); 
			  	 
			   		 return true;
			  		}else if(view.getId()==R.id.txt_cate){  
						 ((TextView)view).setText(((String)data));
						 return true;
					} 
			          return false;    
			      }    
			  });   
			  

			  cateLv.setAdapter(adapter);  
			  cateLv.setParentScrollView(textContainer);
			  cateLv.setMaxHeight(140);
			  
			//  adapter.setSelectItem(selectedFoodmarkItem);
			//  filelv.setSelection(selectedFoodmarkItem);
			}
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 
//		 ---------------------------------------------------------async http process---------------------
		 
		 
		
		 
		 
		 
		 
		 
		 
		 
		 
		  void showWebDialog(){
			 try{
			 if(this.isAdded()) 
				 prgDialog.show();
			 }catch(Exception er){
				 
			 }
		 }
		  
		 
		 AsyncHttpResponseHandler asyncHttpResponseHandler = new AsyncHttpResponseHandler(){
		      
					public void onFailure(int paramAnonymousInt, Header[] paramAnonymousArrayOfHeader, byte[] paramAnonymousArrayOfByte, Throwable paramAnonymousThrowable)
					{
						//			 QLog.getLogger().d(dTAG,  TAG + ", onFailure(int, Header[],byte[], Throwable ) was received");
//						//			 QLog.getLogger().d(dTAG,  TAG + ", response is  " + new String(paramAnonymousArrayOfByte));
						
						 paramAnonymousThrowable.printStackTrace();
						 
						 asynClientOnFailure(paramAnonymousInt, paramAnonymousThrowable.getMessage(), paramAnonymousArrayOfHeader);
					}
					
					public void onSuccess(int statusCode, Header[] header, byte[] paramAnonymousArrayOfByte)
					{
						 if(prgDialog!=null)prgDialog.hide();
						//			 QLog.getLogger().d(dTAG,  TAG + ", response is  " + new String(paramAnonymousArrayOfByte));
						if (paramAnonymousArrayOfByte != null) {
						    processTxtOnSuccess(paramAnonymousArrayOfByte);
						}
				 
					}
				} ;
		
		 void httpsGet(RequestParams params, String strUrl){
			 URL url;
			 URI uri = null ;
			try {
				url = new URL(strUrl); 
			    uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null);
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (URISyntaxException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(uri==null)return;
			 // //			 QLog.getLogger().dLog(dTAG, TAG, "httpsGet url:" +strUrl);
			 // //			 QLog.getLogger().dLog(dTAG, TAG, "uri.getRawPath():" + uri.getRawPath());
			 // //			 QLog.getLogger().dLog(dTAG, TAG, "uri:" + uri.toString());
			
			 /*   if (this.prgDialog == null) {
			      initPrgDialog();
			    }
			    if (isAdded()) {
//			      this.prgDialog.show();
			    }*/
			 
			 try{
				/// We initialize a default Keystore
				 KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());			 
				 // We load the KeyStore
				 trustStore.load(null, null);
				 // We initialize a new SSLSocketFacrory
				 MySSLSocketFactory socketFactory = new MySSLSocketFactory(trustStore);
				 // We set that all host names are allowed in the socket factory
				 socketFactory.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
				 // We initialize the Async Client
				 AsyncHttpClient client = new AsyncHttpClient(true, 80, 443);
				 // We set the timeout to 30 seconds
				 client.setTimeout(30*1000);
				 // We set the SSL Factory
				 client.setSSLSocketFactory(socketFactory);
				 client.get( uri.toString(), params, asyncHttpResponseHandler);
				 
//				 AsyncHttpClient asycnHttpClient = new AsyncHttpClient(true, 80, 443);
//				 asycnHttpClient.get( uri.toString(), params, asyncHttpResponseHandler);
			 }catch(NoSuchAlgorithmException e){
				 e.printStackTrace();
			 } catch (CertificateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (KeyStoreException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (KeyManagementException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (UnrecoverableKeyException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			 
			 /*
			 asycnHttpClient.get(uri.getRawPath(), params, new AsyncHttpResponseHandler(){
				 				      String msg = "";
				      
				      public void onFailure(int paramAnonymousInt, Header[] paramAnonymousArrayOfHeader, byte[] paramAnonymousArrayOfByte, Throwable paramAnonymousThrowable)
				      {
				        //			 QLog.getLogger().d(dTAG,  TAG + ", onFailure(int, Header[],byte[], Throwable ) was received");
				        QiyouFragment.this.asynClientOnFailure(paramAnonymousInt, this.msg, paramAnonymousArrayOfHeader);
				      }
				      
				      public void onSuccess(int statusCode, Header[] header, byte[] paramAnonymousArrayOfByte)
				      {
				        QiyouFragment.this.prgDialog.hide();
				        //			 QLog.getLogger().d(dTAG,  TAG + ", response is  " + new String(paramAnonymousArrayOfByte));
				        if (paramAnonymousArrayOfByte != null) {
				             processTxtOnSuccess(paramAnonymousArrayOfByte);
				        }
				      }
				      });*/
			  } 
			 
		  void getTextW(RequestParams params, String url){
			  if(!Utils.isNetworkConnected(activity)){
//					 this.showNotes("没有可用的网络连接");
					 asynClientOnFailure(0,"",null);
					 return;
				 }
			  hideNotes();  
		  if (this.prgDialog == null) {
		      initPrgDialog();
		    }
		    if (isAdded()) {
		      this.prgDialog.show();
		    } 
		    QiYouApplication.getEle(url, params, new AsyncHttpResponseHandler(){
		    
			      String msg = "";
			      
			      public void onFailure(int paramAnonymousInt, Header[] paramAnonymousArrayOfHeader, byte[] paramAnonymousArrayOfByte, Throwable paramAnonymousThrowable)
			      {
			        // //			 QLog.getLogger().d(dTAG,  TAG + ", onFailure(int, Header[],byte[], Throwable ) was received");
			        QiyouFragment.this.asynClientOnFailure(paramAnonymousInt, this.msg, paramAnonymousArrayOfHeader);
			      }
			      
			      public void onSuccess(int paramAnonymousInt, Header[] paramAnonymousArrayOfHeader, byte[] paramAnonymousArrayOfByte)
			      {
			        QiyouFragment.this.prgDialog.hide();
			        // //			 QLog.getLogger().d(dTAG,  TAG + ", response is  " + new String(paramAnonymousArrayOfByte));
			        if (paramAnonymousArrayOfByte != null) {
			             processTxtOnSuccess(paramAnonymousArrayOfByte);
			        }
			      }
			      });
		  } 
		  
		  
		  JsonHttpResponseHandler getJsonResponseHandler = new JsonHttpResponseHandler() {
	            @Override
	            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
	            	prgDialog.hide();
	            	//			 QLog.getLogger().d(dTAG,  TAG+", onSuccess(int statusCode, Header[] headers, JSONObject response) was received");
	            	 String method ="";
//					 if (response != null) { 
	            	JSONObject jsonObject=	null; 
	            	
						 try { 
							 
							   try { 
								      jsonObject=	response.getJSONObject(QiYouConstant.JSONOBJECT_KEY); 
									 
							    	} catch (JSONException e) { 
							    		Utils.logStackTrace(e, TAG);;
								   }
							 
							   method =response.has(QiYouConstant.SIGN_KEY)?response.getString(QiYouConstant.SIGN_KEY):"";
							 String msg=response.getString(QiYouConstant.MSG_KEY); 
							
							processGetJsonObject( method,  jsonObject,msg );
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							
							Utils.logStackTrace(e, TAG);
							showNotes("出错了",false);
						}catch (NullPointerException e) {
							// TODO Auto-generated catch block
							
							Utils.logStackTrace(e, TAG);
							showNotes("出错了",false);
						} catch (NoWebObjectException e) {
							// TODO Auto-generated catch block
						 
							if(method.equalsIgnoreCase(RestMethods.SECURITY_INVALIDE))
								showNotes("身份验证错误，请登录",true);
							else
								showNotes("没找到记录,请检查您的输入",true);
						} 
						 
//					 }
	            }
	            
	            @Override
	            public void onSuccess(int statusCode, Header[] headers, JSONArray response) { 
	            	prgDialog.hide();
	            	//			 QLog.getLogger().d(dTAG,  TAG+", onSuccess(int statusCode, Header[] headers, JSONArray response) was received");
	            	 
//		            	if (response != null) { 
						 
				      processJsonArray(response);
					 
						 
//					 }
	            }
	            String msg = "";
	            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
			        // //			 QLog.getLogger().d(dTAG,  TAG+", onFailure(int, Header[], Throwable, JSONObject) was received");
			       
					try {
						msg = errorResponse==null?null:errorResponse.getString(QiYouConstant.MSG_KEY);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						Utils.logStackTrace(e, dTAG);
					}
			        asynClientOnFailure(statusCode,msg,headers);
			    }
	            
	        	@Override
				public void onFailure(int statusCode, org.apache.http.Header[] headers,  String errorResponse, java.lang.Throwable throwable  ) {
					//			 QLog.getLogger().d(dTAG,  TAG+", onFailure(int, Header[], String, Throwable)  was received" );
					//			 QLog.getLogger().d(dTAG,  TAG+"errorResponse: "+errorResponse);
					asynClientOnFailure(statusCode,msg,headers);
					
					 
					 
					 
				}
	        	
	        	@Override
				public void onProgress(int bytesWritten, int totalSize) {
					// TODO Auto-generated method stub
					super.onProgress(bytesWritten, totalSize);
					int count = (int) ((bytesWritten * 1.0 / totalSize) * 100);
					// 上传进度显示
					mProgress.setProgress(count);
					//			 QLog.getLogger().d(dTAG,"上传 Progress>>>>>"+ bytesWritten + " / " + totalSize);
				}
					
	        };
		  
		  
		 void getJsonWs(RequestParams params,String url,boolean isInsilence){

			 if(!Utils.isNetworkConnected(activity)){
//				 this.showNotes("没有可用的网络连接");
				 asynClientOnFailure(0,"",null);
				 return;
			 }
			 if(prgDialog==null)initPrgDialog();
//			if(this.isAdded()) prgDialog.show();
			 if(!isInsilence)
				 showWebDialog();
			 
			 hideNotes();  
			 
		        		 QLog.getLogger().d(dTAG,  TAG + "requesting----> " +url +"?"+params.toString());

			 
//		     setCookie();
			 QiYouApplication.get(url, params, getJsonResponseHandler);
			   
		 
		 }
		 
		 //other url than i7lv
		 void get3dJsonWs(RequestParams params,String url,boolean isInsilence){

			 if(!Utils.isNetworkConnected(activity)){
//				 this.showNotes("没有可用的网络连接");
				 asynClientOnFailure(0,"",null);
				 return;
			 }
			 if(prgDialog==null)initPrgDialog();
//			if(this.isAdded()) prgDialog.show();
			 if(!isInsilence)
				 showWebDialog();
			 
			 hideNotes();  
			 
		        //			 QLog.getLogger().d(dTAG,  TAG + "requesting----> " +url +"?"+params.toString()); 
			 
			 QiYouApplication.get3dpart(url, params, new JsonHttpResponseHandler() {
				 
				 @Override
		            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
		            	prgDialog.hide();
		            	//			 QLog.getLogger().d(dTAG,  TAG+", onSuccess(int statusCode, Header[] headers, JSONObject response) was received");
		            	//			 QLog.getLogger().d(dTAG,  TAG+", response from qq:" +response.toString());
		            	try {
							process3dpartJson(response);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							showNotes("认证出错了。。。",true);
						}
 
		            }
				 @Override
					public void onFailure(int statusCode, org.apache.http.Header[] headers,  String errorResponse, java.lang.Throwable throwable  ) {
						//			 QLog.getLogger().d(dTAG,  TAG+", onFailure(int, Header[], String, Throwable)  was received" );
						//			 QLog.getLogger().d(dTAG,  TAG+"errorResponse: "+errorResponse);
						asynClientOnFailure(statusCode,"QQ 用户信息同步错误",headers);
					}
				 
			 } );  
			   
		 
		 }
		 
		 void 	process3dpartJson(JSONObject response) throws JSONException{
			 
		 }
		 
		 
		 void getJsonWs(RequestParams params,String url){
			 	getJsonWs(params,url,false);
			}
		
		 void processGetJsonObject(String method,JSONObject jsonObject,String msg)throws JSONException,NullPointerException, NoWebObjectException {
			 if(TextUtils.isEmpty(method) /*|| jsonObject==null*/)return;
			 
			 //			 QLog.getLogger().d(dTAG, " get method is: " +method);	
			 
			 if(method.equalsIgnoreCase(RestMethods.SECURITY_INVALIDE)){ //to login
				 this.showNotes(msg,true);
				 activity.showLogin();
			 }
			 
			 

		 }
		 
		  /*
		   * post json string to server
		   */
		     void postJsonWS(String json,String url) {
		    	 if(!Utils.isNetworkConnected(activity)){
//					 this.showNotes("没有可用的网络连接");
					 asynClientOnFailure(0,"",null);
					 return;
				 }   
// 		    	 setCookie();
		    	 showCookies();
		    	 hideNotes();  
		    	 //			 QLog.getLogger().d(dTAG, TAG+" post json is "+json); 
				// Show Progress Dialog
			   if(prgDialog==null)initPrgDialog();
			   showWebDialog();//if(this.isAdded())prgDialog.show();
				// Make RESTful webservice call using AsyncHttpClient object
//				testCookies();
				 StringEntity entity =null;
				try {
					entity = new StringEntity(json,HTTP.UTF_8);
				} catch (UnsupportedEncodingException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} 
				if(entity==null)return;
				
				entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
				
//				QiyouRestClient.post(activity,url, entity,"application/json",
				QiYouApplication.post(activity.app,url, entity,"application/json",
						new JsonHttpResponseHandler(){ 
							@Override
							public void onSuccess(int statusCode, org.apache.http.Header[] headers,   JSONObject response){
								prgDialog.hide();
								 if (response != null) { 
									 try {
//										 JSONObject jsonObject=	 response.getJSONObject(QiYouConstant.JSONOBJECT_KEY) ;
										 JSONObject jsonObject=	null;  
											try { 
											      jsonObject=	response.getJSONObject(QiYouConstant.JSONOBJECT_KEY);
												 
											} catch (JSONException e) { 
											 
											}
										 String method =response.has(QiYouConstant.SIGN_KEY)?response.getString(QiYouConstant.SIGN_KEY):"";
										 String msg=response.getString(QiYouConstant.MSG_KEY);
										 //			 QLog.getLogger().d(dTAG, " post sucess,method is: " +method +" msg is " +msg);
										processJsonObject(method,  jsonObject,msg);
									} catch (JSONException e) {
										// TODO Auto-generated catch block
										Utils.logStackTrace(e, dTAG);
									}
									 
								 }
							}
							
							@Override
							 public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
								 // //			 QLog.getLogger().d(dTAG, TAG+", onSuccess(int, Header[], JSONArray) was  received");
								 
								 
							    } 

							 
							
						        String msg = "";
							 /**
							     * Returns when request failed
							     *
							     * @param statusCode    http response status line
							     * @param headers       response headers if any
							     * @param throwable     throwable describing the way request failed
							     * @param errorResponse parsed response if any
							     */
							    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
							        // //			 QLog.getLogger().d(dTAG,  TAG+", onFailure(int, Header[], Throwable, JSONObject) was received");
							       
									try {
//										 JSONObject jsonObject=	 errorResponse.getJSONObject(QiYouConstant.JSONOBJECT_KEY) ;
//										 String method =jsonObject.has(QiYouConstant.SIGN_KEY)?jsonObject.getString(QiYouConstant.SIGN_KEY):"";
//										 String msg=errorResponse.getString(QiYouConstant.MSG_KEY);
										msg = errorResponse==null?null:errorResponse.getString(QiYouConstant.MSG_KEY);
									} catch (JSONException e) {
										// TODO Auto-generated catch block
										Utils.logStackTrace(e, dTAG);
									}
							        asynClientOnFailure(statusCode,msg,headers);
							    }

							    /**
							     * Returns when request failed
							     *
							     * @param statusCode    http response status line
							     * @param headers       response headers if any
							     * @param throwable     throwable describing the way request failed
							     * @param errorResponse parsed response if any
							     */
							    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
							    	 // //			 QLog.getLogger().d(dTAG, TAG+", onFailure(int, Header[], Throwable, JSONArray) was received" );
							    	 asynClientOnFailure(statusCode,msg,headers);
							    }

							    

							@Override
							public void onFailure(int statusCode, org.apache.http.Header[] headers,  String errorResponse, java.lang.Throwable throwable  ) {
								//			 QLog.getLogger().d(dTAG,  TAG+", onFailure(int, Header[], String, Throwable)  was received" );
								//			 QLog.getLogger().d(dTAG,  TAG+"errorResponse: "+errorResponse);
								asynClientOnFailure(statusCode,msg,headers);
							}
							@Override
							public void onProgress(int bytesWritten, int totalSize) {
								// TODO Auto-generated method stub
								super.onProgress(bytesWritten, totalSize);
								int count = (int) ((bytesWritten * 1.0 / totalSize) * 100);
								// 上传进度显示
								if(mProgress!=null)
										mProgress.setProgress(count);
								//			 QLog.getLogger().d(dTAG,"上传 Progress>>>>>"+ bytesWritten + " / " + totalSize);
							}
						});
				
				
				
			}
			
//		     void postBinaryWS(JSONObject mdJson,String svrUrl) throws FileNotFoundException, JSONException {
		     void postBinaryWS(Media md,String svrUrl) throws FileNotFoundException, JSONException {
		    	 if(!Utils.isNetworkConnected(activity)){
//					 this.showNotes("没有可用的网络连接");
		    		 asynClientOnFailure(0,"",null);
					 return;
				 }
//		    	 showCookies();
					// Show Progress Dialog
				   if(prgDialog==null)initPrgDialog();
				   prgDialog.setTitle("正在上传图片");
					// Make RESTful webservice call using AsyncHttpClient object
//					testCookies();
			 
				   hideNotes();  
					String path=md.getUri();//mdJson.getString("Uri"); 
					String smallPicPath =getSmallPicName(path);
					
					
					File file = new File(smallPicPath);
					if (!file.exists()){
						this.createSmallPic(path, QiYouConstant.WEB_PIC_SIZE,null);//QiYouConstant.MAP_PIC_WATER_MARK_WORDS);
					}
					
					if (file.exists() && file.length() > 0) {
						showWebDialog();//if(this.isAdded()) prgDialog.show();
						RequestParams params = new RequestParams();  
					    params.put("file", file);  
	//				    params.put("name", mdJson.getString("name"));
	//				    params.put("mdJson", mdJson);
					    params.put("md", Utils.getGsonString(md));
//						QiyouRestClient.post(svrUrl, params, 
						QiYouApplication.post(svrUrl, params, 
						 
						 new JsonHttpResponseHandler(){
							String msg="《无》";
							@Override
							public void onSuccess(int statusCode, org.apache.http.Header[] headers,   JSONObject response){
								prgDialog.hide();
								mdUploaded=true;
								 // //			 QLog.getLogger().dLog(dTAG,  TAG+" mdUploading   return result  ,uploading success,start next... "); 
								 if (response != null) { 
									 try {
									// 上传成功后要做的工作
	//									Toast.makeText(activity, "上传成功", Toast.LENGTH_LONG).show();
										 mProgress.setProgress(100);
										/* String jsonString =  response.getString(QiYouConstant.JSONOBJECT_KEY);
										 JSONObject json = new JSONObject(jsonString); 
										processJsonObject4MdUpload(  json);*/
										//			 QLog.getLogger().d(dTAG, TAG+" 上传成功");
										JSONObject jo=response.getJSONObject(QiYouConstant.JSONOBJECT_KEY);
										//			 QLog.getLogger().d(dTAG,  TAG+" onSuccess JSONObject: "+response.toString());
										
										uploadMediasOnReturn(jo);
									/*	if(jo!=null){											
											processJsonObject4MdUpload(jo  );
											uploadMedias(mTrack);
										}*/
	//									response.getString(QiYouConstant.JSONOBJECT_KEY);
									} catch (JSONException e) {
										// TODO Auto-generated catch block
										Utils.logStackTrace(e, dTAG);
									}
									 
								 }
							}
							
						/*	@Override
							public void onFailure(int statusCode, Header[] headers,
									byte[] responseBody, Throwable error) {
								// 上传失败后要做到工作
								Toast.makeText(activity, "上传失败", Toast.LENGTH_LONG).show();
								String msg="";
								asynClientOnFailure(statusCode,msg,headers);
							}*/
							@Override
							 public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
							        // //			 QLog.getLogger().d(dTAG,  TAG+", onFailure(int, Header[], Throwable, JSONObject) was received");
							        prgDialog.hide();
							        mdUploaded=true;
									 // //			 QLog.getLogger().dLog(dTAG,  TAG+" mdUploading   return result  ,uploading failure,start next... "); 

									try {
										msg = errorResponse==null?null:errorResponse.getString(QiYouConstant.MSG_KEY);
									} catch (JSONException e) {
										// TODO Auto-generated catch block
										Utils.logStackTrace(e, dTAG);
									}
							        asynClientOnFailure(statusCode,msg,headers);
							    }
							
								    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
								    	 // //			 QLog.getLogger().d(dTAG, TAG+", onFailure(int, Header[], Throwable, JSONArray) was received" );
								    	 asynClientOnFailure(statusCode,msg,headers);
								    	 uploadMediasOnReturn(null);
								    	 
								    }
			
								    
			
								@Override
								public void onFailure(int statusCode, org.apache.http.Header[] headers,  String errorResponse, java.lang.Throwable throwable  ) {
									//			 QLog.getLogger().d(dTAG,  TAG+", onFailure(int, Header[], String, Throwable)  was received" );
									//			 QLog.getLogger().dLog(dTAG,  TAG+"errorResponse: "+errorResponse);
									mdUploaded=true;
									asynClientOnFailure(statusCode,msg,headers);									
									uploadMediasOnReturn(null);
								}
	
						
							@Override
							public void onProgress(int bytesWritten, int totalSize) {
								// TODO Auto-generated method stub
								super.onProgress(bytesWritten, totalSize);
								int count = (int) ((bytesWritten * 1.0 / totalSize) * 100);
								// 上传进度显示
								mProgress.setProgress(count);
								//			 QLog.getLogger().d(dTAG,"上传 Progress>>>>>"+ bytesWritten + " / " + totalSize);
							}
	
							@Override
							public void onRetry(int retryNo) {
								// TODO Auto-generated method stub
								super.onRetry(retryNo);
								// 返回重试次数
							}
	
						});
					} else {
//					Toast.makeText(activity, "文件不存在", Toast.LENGTH_LONG).show();
					showNotes("出错了，文件不存在："+path);
				}
					
					
					
				}
		     
		     void updateUIOnRequestResonsed(String method){
		    	 
		     }
		     
			void asynClientOnFailure(int statusCode,String msg, org.apache.http.Header[] headers){
				// Response failed :(
				
				/*if(headers!=null)
				 for (Header h : headers) {
					 //			 QLog.getLogger().d(dTAG,  TAG+"    "+ h.getName() + " " + " " + h.getValue() + "");
				    }*/
				
				updateUIOnRequestResonsed("");
				
				if (mSwipeLayout!=null){
					mSwipeLayout.setRefreshing(false);
				}
				
				  			 QLog.getLogger().d(dTAG,  TAG+"   failure msg: "+ msg);
				  			 QLog.getLogger().d(dTAG,  TAG+"   failure statusCode: "+ statusCode);
				// Hide Progress Dialog
				 if(prgDialog!=null)
					 prgDialog.hide();
				// When Http response code is '404'
				if (statusCode == 401) {
//					Toast.makeText(activity,
//							"Requested resource not found" +msg,
//							Toast.LENGTH_LONG).show();
					activity.app.user.getUserbean().setExprires(0);
					activity.showLogin();
					showNotes("服务器需要验证您的身份， 请登录 ",true);
				}if (statusCode == 404) {
//					Toast.makeText(activity,
//					"Requested resource not found" +msg,
//					Toast.LENGTH_LONG).show();
					showNotes("出错了，错误信息："+msg,false);
				}
				// When Http response code is '500'
				else if (statusCode == 500) {
//					Toast.makeText(activity,
//							"Something went wrong at server end" +msg,
//							Toast.LENGTH_LONG).show();
					showNotes("出错了，错误信息："+msg,false);
				}
				// When Http response code is '500'
				else if (statusCode == 417) {
					 
					showNotes("出错了，错误信息："+msg,true);
				}
				// When Http response code other than 404, 500
				else {
//					Toast.makeText(
//							activity,
//							"Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]" +msg,
//							Toast.LENGTH_LONG).show();
					showNotes("出错了，无法连接服务器，请检查网络连接.",false);
				}
			}
		 
		 /*
		  * upload track success,then update mobile info
		  * upload medias
		  */
		 void processJsonObject(String method,JSONObject jsonObject,String msg)throws JSONException{
			 pirntCookies();
			 updateUIOnRequestResonsed(method);
			 if(jsonObject==null)return;
			 
			 if(method.equalsIgnoreCase(RestMethods.TRACK_P_IMPORT)){
				 onImportTrackSuccess(  method,  jsonObject,  msg);
			 } 
			
		 }
		 void processJsonArray(JSONArray jsonArrary){}
		 
		 boolean isForShare=false;
		 void shareTrack(Track track){
			 isForShare=!isForShare;
			 if(track.getTrackBean().getSvrNumber()==0){
				 if(!isWebRequest)
					 uploadTrack(track);
				if(isForShare) return; 
			 }
			  
		 }
		 /*
		  * start upload 
		  */
		 void uploadTrack(Track track){
			  
//			 if(QiYouConstant.PV_USER_ID==-1){
			 if(activity.app.user.getUserbean().getId()<=0){
//				 Toast.makeText(activity,
//							"请先登录",
//							Toast.LENGTH_LONG).show();
				 showNotes("请先登录"); 
				 isLoginForShare=true;
				 activity.showLogin();
				 return;
			 }
			 if(track.getTrackBean().getDistance()<=10){
				 showNotes("运动的距离太短了。。。上传失败"); 
				 return;
			 }
			 if(QiYouConstant.DEVELOPER_MODE)
				 track.getTrackBean().setUserid(activity.app.user.getUserbean().getId());//TODO:to remove
			 
			 if(track.getTrackBean().getUserid()<=0){
				 track.getTrackBean().setUserid(activity.app.user.getUserbean().getId());
			 }
			 else if(!QiYouConstant.DEVELOPER_MODE && track.getTrackBean().getUserid()>0 && track.getTrackBean().getUserid()!=activity.app.user.getUserbean().getId()){
				 Toast.makeText(activity,
							"只能上传本人的记录，上传取消",
							Toast.LENGTH_LONG).show();
				 return;
			 } 
			  
			 if( track.getTrackBean().getSvrNumber()<=0){
				 track.getTrackBean().setAvStatus(TrackAvStatus.PUBLIC);
			 }
			 
			 track.getTrackBean().setSummary(track.getSummary());
			 ArrayList<Waypoint_bean> wps =track.getTrackBean().getTrkseg().size() > QiYouConstant.MAX_UPLOAD_WPS_SIZE_PER_KM ?  track.getTrackBean().getTrkseg() : null;
			 track.getTrackBean().setTrksegs(Utils.zipPathPoints(track.getTrackBean(), QiYouConstant.MAX_UPLOAD_WPS_SIZE_PER_KM)); //zip to target size
			 this.postJsonWS(track.toString(),RestMethods.TRACK_P_IMPORT /*"mb/track/"*/);  
			 if(wps!= null){
				 track.getTrackBean().setTrksegs(wps);//set back original
			 }
			 
//			  track.getTrackBean().setUserid(QiYouConstant.PV_USER_ID);
//			  track.getTrackBean().setTrksegs(null);
//			  track.getTrackBean().setRoadWps(null) ;
//			  track.getTrackBean().setStartWp(null);
//			  track.getTrackBean().setLastWp(null);
//			  track.getTrackBean().setMaxDistWp(null);
			 
//			  track.getTrackBean().setDistance(track.getTrackBean().getDistance()+10000);
//			  String trackString=track.toString();
			  // //			 QLog.getLogger().dLog(dTAG, trackString);
//			  //			 QLog.getLogger().dLog(dTAG, "upload track user id is:" +track.getTrackBean().getUserid());
//			  //			 QLog.getLogger().dLog(dTAG, "upload track distance is:" +track.getTrackBean().getDistance());
//			  //			 QLog.getLogger().dLog(dTAG, track.getTrackBean().getStartWp().toJsonWp());
			  
			  
		 }
		  
		 
		 void onImportTrackSuccess(String method,JSONObject jsonObject,String msg) throws JSONException{
			 int svrNo= jsonObject.getInt("svrNumber"); 
			 if(svrNo<=0)return;
			 activity.app.user.getUserbean().setScore(jsonObject.getInt("userScore"));
			 activity.app.updateUserPref();
			if( mTrack.getTrackBean().getSvrNumber()!=svrNo){
				 mTrack.getTrackBean().setSvrNumber(svrNo);
				 HashMap<Integer,Integer> ids = new HashMap<Integer,Integer>();
//				 ids.put(jsonObject.getInt("trackId"), jsonObject.getInt("svrNumber"));
				 ids.put(mTrack.getTrackBean().getTrackId(), jsonObject.getInt("svrNumber"));
				 activity.app.updateTrackSvrNos(ids);
			 }
//			 Toast.makeText(activity,
//						"Success",
//						Toast.LENGTH_LONG).show();
			 showNotes("上传成功！云编号："+svrNo);  
			 try{
				 activity.app.mStatistics.getStatisticsTracks().get(Integer.valueOf(mTrack.getTrackBean().getType().toInt()))
			 		.getSbs().get(Integer.valueOf(mTrack_bean.getTrackId())).setSvrNo(svrNo);
			 }catch(Exception e){
				 Utils.logStackTrace(e, TAG);
			 }
			 
		     activity.app.mStatistics.getExistedSvrNos().add(Integer.valueOf(svrNo));
		     activity.app.writeStatiscs();
			 
//			 if(txtNote!=null)txtNote.setVisibility(View.VISIBLE);
			 //begin to upload medias
			 uploadedmds = new ArrayList<Waypoint_bean>();
			 uploadedmdsSuccessed = new ArrayList<JSONObject>();
			 uploadMedias(mTrack); //TODO: mTrack 是不是合适
			 //TODO: update the track's medias,防止重复上载 
			 
			 if(isForShare)
				 shareTrack(mTrack);
		 }
		 
		 
		 boolean mdUploaded=true;
		 ArrayList<Waypoint_bean> uploadedmds; 
		 void uploadMedias(  Track track) throws JSONException{
			 // //			 QLog.getLogger().dLog(dTAG,  TAG+" start to upload medias");
			 
			 for(Waypoint_bean wb:track.getTrackBean().getMdWps()){
				 if(wb==null ||uploadedmds.contains(wb))continue;
				 for(Media md:wb.getMedias()){
					 if(md==null)continue;
						//			 QLog.getLogger().dLog(dTAG,  TAG+" md.getStatus(): "+md.getStatus());
						//			 QLog.getLogger().dLog(dTAG,  TAG+" mediaStatus.UPLOADED: "+mediaStatus.UPLOADED); 
					 if(md.getStatus()!=mediaStatus.UPLOADED && md.getStatus()!=mediaStatus.DELETED && md.getStatus()!=mediaStatus.HIDED){
						 md.setTrackId(track.getTrackBean().getTrackId());
						 md.setTrackSvrNumber(track.getTrackBean().getSvrNumber());
						 
						 try { 
							/* while(!mdUploaded){
								 //			 QLog.getLogger().dLog(dTAG,  TAG+" mdUploading not return result yet, sleeping... "); 
								 Thread.sleep(200);
							 }  */
							    postBinaryWS(md,RestMethods.TRACK_P_UPLOAD_FILE/*"mb/track/file"*/);
							    uploadedmds.add(wb);							    
							 	mdUploaded=false;
							 	return;
						} catch (FileNotFoundException e) {
							// TODO Auto-generated catch block
							Utils.logStackTrace(e, dTAG);  
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							Utils.logStackTrace(e, dTAG);  
						} /*catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} */
					 }
				 }
			 }	
//			 //			 QLog.getLogger().dLog(dTAG,  TAG+" start to building mdstring for update ---------------");
			 //to update local database for media changes
			 boolean isToUpdate=false;
			 for(JSONObject jo:uploadedmdsSuccessed){
				 if(jo==null)continue;
				 for(Waypoint_bean wb:track.getTrackBean().getMdWps()){
					 if(wb==null)continue; 
						 for(Media md:wb.getMedias()){
							 if(md==null)continue; 
								 try {
									if( md.getTime()==jo.getLong("time")){
//										//			 QLog.getLogger().dLog(dTAG,  TAG+" md.getUri(): "+md.getUri());
										 md.setTrackId(jo.getInt("trackId"));
										 md.setTrackSvrNumber(jo.getInt("trackSvrNumber"));
										 md.setSvrUri(jo.getString("svrUri"));
										 md.setStatus(mediaStatus.UPLOADED);
										 isToUpdate=true;
//											//			 QLog.getLogger().dLog(dTAG,  TAG+" md.getSvrUri(): "+md.getSvrUri());
									 }
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
						 }
				 	}	
			 }
			if(isToUpdate){
				 processJsonObject4MdUpload(track.getTrackBean().getTrackId(),  Utils.getGsonString(track.getTrackBean().getMdWps())  );
				 uploadedmdsSuccessed.clear();
				 uploadedmds.clear();
			}
			 
			/*	new Thread(){
					@Override
					public void run() { 
				 
			 }}.run();*/
			 
			 
		 }
		 
		 /*
		  * upload medias success
		  * to update local medias by the server info
		  */
		 void processJsonObject4MdUpload(int trackId,String mdsString)throws JSONException{ 
			 // //			 QLog.getLogger().dLog(dTAG,  TAG+" mdsString to update is: "+mdsString);
			 activity.app.updateTrackMds(trackId,mdsString); 
		 }
		 
		 ArrayList<JSONObject> uploadedmdsSuccessed;
		 void uploadMediasOnReturn(JSONObject jo)  {
			 if(jo!=null){
				 uploadedmdsSuccessed.add(jo);
			 }
			 
			 try {
				uploadMedias(mTrack);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				Utils.logStackTrace(e, TAG);
			}
		 }
		 
		 
		 
		/*
		 * to update track status
		 *  
		 */
		 
		 protected void updateTrackStatus(int svrNumber,TrackAvStatus status){ 
			 Track tr =new Track();
			 tr.getTrackBean().setSvrNumber(svrNumber);
			 tr.getTrackBean().setAvStatus(status);
			 // //			 QLog.getLogger().d(dTAG, "Track to update is:"+tr.toString());
			 postJsonWS(tr.toString(),RestMethods.TRACK_P_UPDATE_STATUS/*"/mb/track/status"*/);
		 }
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 

		 protected String buildPicWaterMarkTitle(float dist,long time){
			 String title =""; 
			 String format ="%s     %s  avs %.1f ";
			 title=String.format(format,
					 Utils.getFormatedTime(time),
					 Utils.getFormatedDistance(dist),
					 mTrack_bean.getAvs() 
					
					 );
			 
			 return title;
		 }
	  
	  
		
		  void createSmallPic(final String picName,final int SMALLSIZE,final String title){
			  // //			 QLog.getLogger().d(dTAG, TAG+" start to create small pic for "+picName);
//			 new Thread(new Runnable(){
//			    @Override
//			    public void run() {?
//			    	  com.qiyou.mb.android.utils.ImageLoader IL = new com.qiyou.mb.android.utils.ImageLoader(activity);
			    	  
//			    	 Bitmap b= IL.getBitmap(picName, SMALLSIZE);
			    	 Bitmap b=ImageUtil.getSmallBitmap(picName, SMALLSIZE);
//			    	  b= watermarkBitmap(b,null,QiYouConstant.MAP_PIC_WATER_MARK_WORDS);
			    	 b= watermarkBitmap(b,null,title); 
			    	  String smallPicName=getSmallPicName(picName);//picName.substring(0,picName.lastIndexOf(".jpg"))+"_"+SMALLSIZE+".jpg";
					  File file = new File(smallPicName);
			         FileOutputStream out;
			         try{
			             out = new FileOutputStream(file);
			             if(b.compress(Bitmap.CompressFormat.JPEG, QiYouConstant.SMALLPIC_SIZE_COMPRESS_REATE, out)) 
			             {
			                 out.flush();
			                 out.close();
			             }  
			           // //			 QLog.getLogger().d(dTAG, TAG+"small pic created as: " +smallPicName);
			         } 
			         catch (FileNotFoundException e) 
			         {
			             e.printStackTrace();
			         } 
			         catch (IOException e) 
			         {
			             e.printStackTrace(); 
			         }
			    	  
//			    }
//			 	}).start();
		} 
		 
		   Bitmap watermarkBitmap(Bitmap src, Bitmap watermark,  String title) {
		        if (src == null) {
		            return null;
		        }
		        if (TextUtils.isEmpty(title)){
		        	return src;
		        }
		        int w = src.getWidth();
		        int h = src.getHeight(); 
		        //需要处理图片太大造成的内存超过的问题,这里我的图片很小所以不写相应代码了        
		        Bitmap newb= Bitmap.createBitmap(w, h, Config.ARGB_8888);// 创建一个新的和SRC长度宽度一样的位图
		        Canvas cv = new Canvas(newb);
		        cv.drawBitmap(src, 0, 0, null);// 在 0，0坐标开始画入src    
		      
		        //加入图片
		        if (watermark != null) {
		        	Paint paint=new Paint();
		            int ww = watermark.getWidth();
		            int wh = watermark.getHeight();
		            paint.setAlpha(50);
		            cv.drawBitmap(watermark, w - ww + 5, h - wh + 5, paint);// 在src的右下角画入水印            
		        }
		        //加入文字
		        if(title!=null)
		        {
		            String familyName ="宋体";
		            Typeface font = Typeface.create(familyName,Typeface.NORMAL);            
		            TextPaint textPaint=new TextPaint();
		            textPaint.setColor(Color.LTGRAY);
		            textPaint.setTypeface(font);
		            textPaint.setTextSize(20);
		            //这里是自动换行的
//		            StaticLayout layout = new StaticLayout(title,textPaint,w,Alignment.ALIGN_NORMAL,1.0F,0.0F,true);
//		            layout.draw(cv);
		            //文字就加左上角算了
//		            cv.drawText(title,w/2-10,h-20,textPaint);
		            cv.drawText(title,w/4,h-40,textPaint);
//		            if(!TextUtils.isEmpty(title))
//		            	cv.drawText(title,w-title.length()*20,h-40,textPaint);
		            String sign ="by "+QiYouConstant.PV_USER_NAME +" " +QiYouConstant.WATER_MARKER_SIGN;
		            cv.drawText( sign,w/4,h-10,textPaint); 
		        }
		        cv.save(Canvas.ALL_SAVE_FLAG);// 保存
		        cv.restore();// 存储
		        return newb;
		    }
		 
		 String getSmallPicName(String picName){
			 String smallName="";
			 try{
				 String sufix=picName.substring(picName.lastIndexOf("."),picName.length());
				 smallName= picName.substring(0,picName.lastIndexOf(sufix))+"_small"+sufix;
			 }catch(Exception e){
				 Utils.logStackTrace(e, TAG);
			 }
			 return smallName;
		 }
		 
		 
		 void initPrgDialog(){
		/*	 	prgDialog. = new ProgressDialog(activity);
				// Set Progress Dialog Text
				prgDialog.setMessage("正在请求云端数据...请稍候");
				// Set Cancelable as False
				prgDialog.setCancelable(false);*/
				
				
				
			 
				AlertDialog.Builder builder = new Builder(activity);
				builder.setTitle(R.string.web_request);
				 
				final LayoutInflater inflater = LayoutInflater.from(activity);
				View v = inflater.inflate(R.layout.softupgrade_progress, null);
			    mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
				builder.setView(v);
		 
				/*builder.setNegativeButton(R.string.soft_update_cancel, new OnClickListener()
				{
					@Override
					public void onClick(DialogInterface dialog, int which)
					{
						dialog.dismiss();
						 
//						cancelUpdate = true;
					}
				});*/
				
				prgDialog =  builder.create();
				prgDialog.setCancelable(false);
//				prgDialog.show();
		 }
		 
		 
		 public void onBack(){
			 getFragmentManager().popBackStack();
	/*		  new Thread(){
			   public void run() {
			    try{
			     Instrumentation inst = new Instrumentation();
			     inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
			    }
			    catch (Exception e) {
			                 Log.e("Exception when onBack", e.toString());
			             }
			   }
			  }.start();
*/
			 }
		 
		 void showNotes(String notes){
			 showNotes(notes,true);
		 }
		public void showNotes(String notes,Boolean showToast){
			 if(TextUtils.isEmpty(notes) || notes.equalsIgnoreCase("null"))return;
			 if(showToast)
 			   Toast.makeText(activity,notes,Toast.LENGTH_SHORT ).show();
			   if(vContainer==null)return;
			   TextView txtNote=(TextView)vContainer.findViewById(R.id.txtNotice);
			   if(txtNote!=null){				   
				   txtNote.setText(notes);
				   txtNote.setVisibility(View.VISIBLE);
			   }
		   }
		 void hideNotes(){
			  TextView txtNote=(TextView)vContainer.findViewById(R.id.txtNotice);
			   if(txtNote!=null){				   
				   txtNote.setText("");
				   txtNote.setVisibility(View.GONE);
			   }
		 }
		 
		 
		/* void setCookie(){
				PersistentCookieStore myCookieStore = new PersistentCookieStore(activity.app);
				
				String name = "uk";  
		        String value = QiYouConstant.PV_ACCESS_TOKEN +"-c-d-x-"+QiYouConstant.PV_USER_ID;  
		        BasicClientCookie clientCookie = new BasicClientCookie(name, value);  
		        clientCookie.setComment("");  
		        clientCookie.setDomain("i7lv.com");  
//		        clientCookie.setExpiryDate("");  
		        clientCookie.setPath("//");
		        myCookieStore.clear();
				myCookieStore.addCookie(clientCookie);
			 
//				myCookieStore.clear();
				//			 QLog.getLogger().d(dTAG," begin to print cookies myCookieStore befor set...............................");
				for(Cookie c:myCookieStore.getCookies()){
					//			 QLog.getLogger().d(dTAG,TAG+ " print cookies ~~ name:"+c.getName()+",value:"+c.getValue());
					//			 QLog.getLogger().d(dTAG,TAG+ " print cookies ~~ domain:"+c.getDomain()+",path:"+c.getPath());
					//			 QLog.getLogger().d(dTAG,TAG+ " print cookies ~~ ExpiryDate():"+c.getExpiryDate()+",ports:"+c.getPorts());
					//			 QLog.getLogger().d(dTAG,TAG+ " print cookies ~~ version():"+c.getVersion() );
				}
//				QiyouRestClient.setCookieStore(myCookieStore);
				QiYouApplication.setCookieStore(myCookieStore);
				//			 QLog.getLogger().d(dTAG," begin to print cookies myCookieStore after set...............................");
				for(Cookie c:myCookieStore.getCookies()){
					//			 QLog.getLogger().d(dTAG,TAG+ " print cookies ~~ name:"+c.getName()+",value:"+c.getValue());
					//			 QLog.getLogger().d(dTAG,TAG+ " print cookies ~~ domain:"+c.getDomain()+",path:"+c.getPath());
					//			 QLog.getLogger().d(dTAG,TAG+ " print cookies ~~ ExpiryDate():"+c.getExpiryDate()+",ports:"+c.getPorts());
					//			 QLog.getLogger().d(dTAG,TAG+ " print cookies ~~ version():"+c.getVersion() );
				}
				 
		 }*/
		 
		  void showCookies() {
			/*    PersistentCookieStore mCookieStore = new PersistentCookieStore(
			            activity);
			    List<Cookie> cookies = mCookieStore.getCookies();
			    for (Cookie c : cookies) {
			         //			 QLog.getLogger().d(dTAG, TAG+" cookies:" + c.getName() +"....."+ c.getPath()+"....."+ c.getValue());
			    }*/
//			  pirntCookies();
			}
		 
		 void pirntCookies(){
//			  AsyncHttpClient client = new AsyncHttpClient(); 
				HttpContext httpContext =QiYouApplication.getHttpContext();// QiyouRestClient.getHttpContext();
				
				CookieStore cookies = (CookieStore) httpContext.getAttribute(ClientContext.COOKIE_STORE);//获取AsyncHttpClient中的CookieStore
				//			 QLog.getLogger().d(dTAG," begin to print cookies...............................");
				if(cookies!=null){
					for(Cookie c:cookies.getCookies()){
						//			 QLog.getLogger().d(dTAG,TAG+ " print cookies ~~ name:"+c.getName()+",value:"+c.getValue());
						//			 QLog.getLogger().d(dTAG,TAG+ " print cookies ~~ domain:"+c.getDomain()+",path:"+c.getPath());
						//			 QLog.getLogger().d(dTAG,TAG+ " print cookies ~~ ExpiryDate():"+c.getExpiryDate()+",ports:"+c.getPorts());
						//			 QLog.getLogger().d(dTAG,TAG+ " print cookies ~~ version():"+c.getVersion() );
					}
				}else{
					//			 QLog.getLogger().d(dTAG,"main  before~~,cookies is null");
				}
				//			 QLog.getLogger().d(dTAG," print cookies end   ...............................");
	/*			//save cookie
				 PersistentCookieStore myCookieStore = new PersistentCookieStore(context);
				 QiyouRestClient.setCookieStore(myCookieStore);
		        
				httpContext = QiyouRestClient.getHttpContext();
				cookies = (CookieStore) httpContext.getAttribute(ClientContext.COOKIE_STORE);
				if(cookies!=null){
					//			 QLog.getLogger().d(dTAG, "main  after~~,cookies is not null");
					for(Cookie c:cookies.getCookies()){
						//			 QLog.getLogger().d(dTAG,"main after ~~"+c.getName()+","+c.getValue());
					}
				}else{
					//			 QLog.getLogger().d(dTAG, "main  after~~,cookies is null");
				}
				*/
		}
		 
		 
		 
		
		  

		  void processTxtOnSuccess(byte[] paramArrayOfByte) {
			  
				 // //			 QLog.getLogger().dLog(dTAG, TAG, " not get result from googleapi for ele.");
			 
//				  try {
//					String strResult = EntityUtils.toString(response.getEntity());
					  String strResult=new String(paramArrayOfByte) ;
					
					
					 // //			 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++;
						}
					}
			  
		  }
		  
		  void writeWebTrackCache(String fileName, JSONObject paramJSONObject){
			  
			    try
			    {
			      // //			 QLog.getLogger().d(dTAG, TAG +" writing gpx cache into local sdcard," +getCacheFileName(fileName));
			      //TODO: check if the file exits already or not
			      String tmpFile =getCacheFileName(QiYouConstant.GPX_CACHE_PATH,"tmp");
			      Utils.writeSDFile(tmpFile, paramJSONObject.toString());
			      FileUtil.encodeFile(getCacheFileName(QiYouConstant.GPX_CACHE_PATH,fileName), tmpFile, activity.app.crypto, activity.app.entity);
			   
			      return;
			    }
			    catch (IOException localIOException)
			    { 
			       
			        localIOException.printStackTrace();
			       
			    }
			  }
		  
		  void writeActivitiesCache(String fileName, String act){
			  try
			    {
			      //			 QLog.getLogger().d(dTAG, TAG +" writing gpx cache into local sdcard," +getCacheFileName(QiYouConstant.ACT_CACHE_PATH,fileName));
			      //			 QLog.getLogger().d(dTAG, TAG +" writing gpx cache into local sdcard," +act);
			      //TODO: check if the file exits already or not
			      String tmpFile =getCacheFileName(QiYouConstant.ACT_CACHE_PATH,"tmp");
			      Utils.writeSDFile(tmpFile, act);
			      FileUtil.encodeFile(getCacheFileName(QiYouConstant.ACT_CACHE_PATH,fileName), tmpFile, activity.app.crypto, activity.app.entity);
			   
			      return;
			    }
			    catch (IOException localIOException)
			    { 
			       
			        localIOException.printStackTrace();
			       
			    }
		  }
		  
		  void writeActivitiesCache(Activity_bean act){
			  writeActivitiesCache(act.getSvrNumber()+""+act.getLastupdated(),Utils.getGsonString(act));
			   
			  }
		  
		  void writeGroupCache(Group_bean grp){
			  writeActivitiesCache(grp.getId()+"grp"+grp.getLastupdated(),Utils.getGsonString(grp));
			   
			  }
		  
		  void writeActivitiesCache(String fileName, JSONObject paramJSONObject){
			  writeActivitiesCache(fileName,paramJSONObject.toString());
			   
			  }
		  
		  String getCacheFileName(String path,String fileName){
		  
		    File localFile = new File(path);
		    if (!localFile.exists()) {
		      localFile.mkdirs();
		    }
		    return localFile.getAbsolutePath() + File.separator + fileName + ".txt";
		  }
		 

		  Track getTrackFromWebCache(int svrNo,long lastupdated)  throws IOException,JsonSyntaxException{ 
			  
			  
			  int id =Integer.MAX_VALUE-svrNo;
			  Track tr =activity.app.getTrackCache().get(Integer.valueOf(id));
			  if(tr!=null)return tr;
			  String fileName=getCacheFileName(QiYouConstant.GPX_CACHE_PATH,String.valueOf(svrNo) + lastupdated);
			/*  String tmpFileName=fileName+"tmp";
			  
			  FileUtil.decodeFile(fileName, tmpFileName,  activity.app.crypto, activity.app.entity);
			  
		       String str = Utils.readSDFile(tmpFileName);*/
			  // //			 QLog.getLogger().d(dTAG, TAG +" begin reading track from gpx cache ..........." );
			  
		    String str =FileUtil.readEncodedFile(fileName, activity.app.crypto, activity.app.entity);
		    
		    
//		    //			 QLog.getLogger().d(dTAG, TAG +"reading track from gpx cache" +getCacheFileName(paramString));
		    if (TextUtils.isEmpty(str)) {
		    	return null;
		    } 
		    // //			 QLog.getLogger().d(dTAG, TAG +"reading track from gpx cache ... success " +str);
		   
		    tr= new Track((Track_bean)Utils.getGsonObject(str, Track_bean.class));		     
		    activity.app.getTrackCache().put(id, tr);
		    return  tr;  
		    
		  }
		  
	       Activity_bean getActFromWebCache(int svrNo,long lastupdated)  throws IOException,JsonSyntaxException{ 
			  
			  
//			  int id =Integer.MAX_VALUE-svrNo;
//			  Activity_bean act =activity.app.getTrackCache().get(Integer.valueOf(id));
//			  if(tr!=null)return tr;
			  String fileName=getCacheFileName(QiYouConstant.ACT_CACHE_PATH,String.valueOf(svrNo) + lastupdated);
			/*  String tmpFileName=fileName+"tmp";
			  
			  FileUtil.decodeFile(fileName, tmpFileName,  activity.app.crypto, activity.app.entity);
			  
		       String str = Utils.readSDFile(tmpFileName);*/
			  // //			 QLog.getLogger().d(dTAG, TAG +" begin reading track from gpx cache ..........." );
			  
		    String str =FileUtil.readEncodedFile(fileName, activity.app.crypto, activity.app.entity);
		    
		    
 		    //			 QLog.getLogger().d(dTAG, TAG +" reading track from gpx cache " +fileName);
		    if (TextUtils.isEmpty(str)) {
		    	return null;
		    } 
		    // //			 QLog.getLogger().d(dTAG, TAG +"reading track from gpx cache ... success " +str);
		   
		    Activity_bean act= (Activity_bean)Utils.getGsonObject(str, Activity_bean.class) ;		     
//		    activity.app.getTrackCache().put(id, tr);
		    return  act;  
		    
		  }
		  
	       void delCachedGroup(int svrNo,long lastupdated){
	    	   String fileName=getCacheFileName(QiYouConstant.GPX_CACHE_PATH,String.valueOf(svrNo) + lastupdated);  
			    try {
					FileUtil.del(fileName);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
	       }
		 
	       Group_bean getGroupFromWebCache(int svrNo,long lastupdated)  throws IOException,JsonSyntaxException{ 
				  
				  
//				  int id =Integer.MAX_VALUE-svrNo;
//				  Activity_bean act =activity.app.getTrackCache().get(Integer.valueOf(id));
//				  if(tr!=null)return tr;
				  String fileName=getCacheFileName(QiYouConstant.ACT_CACHE_PATH,String.valueOf(svrNo) +"grp"+ lastupdated);
				/*  String tmpFileName=fileName+"tmp";
				  
				  FileUtil.decodeFile(fileName, tmpFileName,  activity.app.crypto, activity.app.entity);
				  
			       String str = Utils.readSDFile(tmpFileName);*/
				  // //			 QLog.getLogger().d(dTAG, TAG +" begin reading track from gpx cache ..........." );
				  
			    String str =FileUtil.readEncodedFile(fileName, activity.app.crypto, activity.app.entity);
			    
			    
	 		    //			 QLog.getLogger().d(dTAG, TAG +" reading track from gpx cache " +fileName);
			    if (TextUtils.isEmpty(str)) {
			    	return null;
			    } 
			    // //			 QLog.getLogger().d(dTAG, TAG +"reading track from gpx cache ... success " +str);
			   
			    Group_bean act= (Group_bean)Utils.getGsonObject(str, Group_bean.class) ;		     
//			    activity.app.getTrackCache().put(id, tr);
			    return  act;  
			    
			  }
		  
		  
		  
		 void mergeTrack(final int trackId){
			 
			 Track newTrack =new Track();
			 
			 
			 if(activity.app.getTrackCache().get(Integer.valueOf(trackId))==null)
				 activity.app.getTrackById(trackId);	 
			 
			 final   Handler	 handler	= new Handler(){
					
					@Override
					public void handleMessage(Message msg) {
						
						if (msg.what==1 ) {  
						
							Track to =  activity.app.getTrackCache().get(Integer.valueOf(trackId));
							mTrack.mergeTrack(to); //merge track segs, distance,time, bears...
							
							Waypoint wp ;
							for(Waypoint_bean wb :to.getTrackBean().getMdWps()){
								wp=new Waypoint();
								wp.setWb(wb);
								mTrack.newMdWpsJson.append(wp.toJsonWp()+",");							 
								mTrack.getTrackBean().getMdWps().add(wb);
							}
							
						}
						 
					 
//						progressDialog.dismiss(); 
 
							  showNotes("数据导出出现错误，导出失败。");
					 		  
					}};
					
			 new Thread(new Runnable(){
				    @Override
				    public void run() {
				        try {
				        
				        	int totalWaiting = 0;
				        	//to get track to be merged
				        	while(activity.app.getTrackCache().get(Integer.valueOf(trackId))==null){
				        		Thread.sleep(200);
				        		totalWaiting+=200;
				        		if(totalWaiting>QiYouConstant.MAX_TRACK_RESTORE_TIME){
				        			handler.sendEmptyMessage(0);
				        			break;
				        		}
				        	}
				        	
				        	handler.sendEmptyMessage(1);
				         
								 
				        } catch (Exception e) {
				            e.printStackTrace();
				        }
				    }
				}).start();
			 
			  
		 }
		  
		  /**
		   * adjust the listview to show properly in the scrollview
		   * @param listView
		   */
		 void setListViewHeightBasedOnChildren(ListView listView) {
	          ListAdapter listAdapter = listView.getAdapter(); 
	          if (listAdapter == null) {
	              // pre-condition
	              return;
	          }

	          int totalHeight = 0;
	          for (int i = 0; i < listAdapter.getCount(); i++) {
	              View listItem = listAdapter.getView(i, null, listView);
	              listItem.measure(0, 0);
	              totalHeight += listItem.getMeasuredHeight();
	          }

	          ViewGroup.LayoutParams params = listView.getLayoutParams();
	          params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
	          listView.setLayoutParams(params);
	      }
		  
		 
		  protected Waypoint mdWp;
		  protected final int SELECT_PIC_KITKAT=2000;
		  protected final int SELECT_PIC=3000;  
		  
		  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);
						
					}
				}
			
			 protected void setMD(String picName,long time,Waypoint wp,mediaType mdType){
				 
			 }
			 
			 
			 
		protected void logout(){
			 AlertDialog.Builder builder = new AlertDialog.Builder(activity);
             builder.setTitle("确认要退出登录吗？") 
                     .setNegativeButton("取消", null);
             builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                 public void onClick(DialogInterface dialog, int which) { 

     			 	activity.app.logout();
     		    	Toast.makeText(activity, "您已登出",Toast.LENGTH_SHORT).show();
     		    	activity.isTabHome();
                	  
                 }
             });
             builder.show();
	    	
			 }
}




//StringEntity entity=null;
//try {
//	 String trackstring=track.toString();
//	 //			 QLog.getLogger().d(dTAG, TAG+"upload track: "+trackstring); 
//	  entity=new StringEntity(trackstring); 
//} catch (UnsupportedEncodingException e) {
//	// TODO Auto-generated catch block
//	//			 QLog.getLogger().d(dTAG, TAG+" "+e.getMessage());
//}
//if(entity!=null)
 
 
 
	 


	/*JSONObject json = new JSONObject();
   try {
		json.put("name", "android test");
		json.put("gpsSpan", "20000");
//		json.put("cmt", "this is a android test JSONOBJECT");
       json.put("userid", 1);
       //			 QLog.getLogger().d(dTAG, TAG+" test track for uploading1: "+json.toString());
       String jsonString=new JSONStringer().object()
       .key("name").value("android test").key("gpsSpan").value("20000").key("cmt").value("this is a android test JSONStringer").key("userid").value("1")
       .endObject()
       .toString();
       //			 QLog.getLogger().d(dTAG, TAG+" test track for uploading2: "+jsonString);
     
       entity = new StringEntity(json.toString() );
       entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));//Reason once you use some entity it will ignore content type given in post and use entity's content
//       
       if(entity!=null)
			 this.postJsonWS(entity, "mb/track/"); 
//       
       entity = new StringEntity(jsonString );
       entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));//Reason once you use some entity it will ignore content type given in post and use entity's content
       
       
	} catch (JSONException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (UnsupportedEncodingException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} */
     


 
	/*Thread thread = new Thread(new Runnable(){
	    @Override
	    public void run() {
	        try {
	        	 String url="http://home:8080/qiyouji/mb/track/";
				    HttpPost request = new HttpPost(url);
				    JSONObject param = new JSONObject();
				    try {
						param.put("name", "android test");
						param.put("gpsSpan", "123456");
						param.put("userid", 1);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						Utils.logStackTrace(e, dTAG);
					}
				    
				    JSONObject json = new JSONObject();
		          
						json.put("name", "android test");
						json.put("gpsSpan", "20000");
						json.put("cmt", "this is a android test HttpPost");
			            json.put("userid", 1);
				    
				    StringEntity se;
					try {
						 //			 QLog.getLogger().d(dTAG, TAG+" test track for uploading3: "+json.toString());
						se = new StringEntity(json.toString());
						  request.setEntity(se);
						  request.setHeader("Content-Type", "application/json");
						    HttpResponse httpResponse = activity.app.getHttpClient().execute(request);
						    String retSrc = EntityUtils.toString(httpResponse.getEntity());
						    System.out.println(httpResponse.getStatusLine().getReasonPhrase());
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						Utils.logStackTrace(e, dTAG);
					} catch (ClientProtocolException e) {
						// TODO Auto-generated catch block
						Utils.logStackTrace(e, dTAG);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						Utils.logStackTrace(e, dTAG);
					}
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }
	});

	thread.start();  

*/

