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

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Editable;
import android.text.InputType;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;

import com.google.gson.JsonSyntaxException;
import com.loopj.android.http.RequestParams;
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.CItem;
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.Track_bean;
import com.qiyou.mb.android.beans.basic.User_bean;
import com.qiyou.mb.android.content_providers.TrackProvider;
import com.qiyou.mb.android.utils.ImageLoader;
import com.qiyou.mb.android.utils.NoScrollGridView;
import com.qiyou.mb.android.utils.QCursorAdapter;
import com.qiyou.mb.android.utils.QSimpleAdapter;
import com.qiyou.mb.android.utils.Utils;
import com.qiyou.mb.android.utils.enums.BBSCate;
import com.qiyou.mb.android.utils.enums.TrackAvStatus;
import com.qiyou.mb.android.utils.enums.TrackType;
import com.qiyou.mb.android.utils.exception.NoWebObjectException;
import com.qiyou.mb.android.utils.image.ImageGridAdapter;
import com.qiyou.mb.android.utils.image.QimageView;
import com.qiyou.mb.android.utils.log.QLog;
import com.qiyou.mb.android.utils.server.RestMethods;
import com.qiyou.mb.android.utils.server.SharedLocation;

public abstract class Querybase_fragment extends QiyouFragment implements SwipeRefreshLayout.OnRefreshListener, LoaderCallbacks<Cursor> { 
	
	public  abstract void doQuery();
	
		protected ImageLoader IL; 
	    Button btn_live_list;
	    ImageView btn_live_query;
		EditText edit_act_query;
		 Button btn_live_refresh;
		 
	    EditText etStartTime;   
	    EditText etEndTime;  
	    datePickerListener tl;  
	    long custStartDate=0;
	    long custEndDate=0;
	    long startDate=0;
	    long endDate=0;
	    boolean firstLoad=false;
	    boolean isSwitchWebInputOnly = false;
	    String strStartTime="开始时间";
	    String strEndTime="结束时间"; 
	    private Button 	btnQuery;
	    LinearLayout llDtRange ;
		LinearLayout ll_selection;
	    int trackType=0;
	    int webTrackType=0;
	    List<CItem > typeLst ;
//	    protected TabHost tabhost;
	    ImageView btn_queryCates;	    
	    RadioGroup cateQueryRdGroup;
	
	    
	 
	    protected List<Integer> trackIds;
	    protected int queryType=0;//0,1,2...normal/cates/inactive
	    protected String lastWebQueryPara="";
	    protected String lastActQueryPara="";	
	    protected String lastMemberQueryPara="";
	    protected String lastGrpQueryPara="";	
	    ScrollView textContainer ;
	    protected int visibleItemCnt;
	    protected int visibleLastIndex;
//		boolean isLoadMoreIndex=false;  //when localTracklist clicked set it to -1; when loadmore,set it to visibleLastIndex
		protected int lastIndexOnMore =-1; //when localTracklist clicked set it to -1; when loadmore,set it to visibleLastIndex
		protected int BBScate = 0;
		protected int BBSSubcate = 0; 
		protected int BBSSubcateOwner = 0;
		protected String BBSsubCateName = "";
		 protected ListView lvWeb = null;
		 protected ImageView imgWebPlus;
		   protected NoteMessage currentMsg;
		    protected Note currentNote;
		    Spinner spTrackType;
//		    Spinner spTrackTypeWeb;
		    Spinner spTrackDtRange;//St_SpinnerDateRange;
		    Spinner spWebInputType;
		    ArrayAdapter<?> spAdapterWeb;
		    EditText  txt_webinput;		  
//		    Map<Integer,Integer> tabSpIndex;
			Map<Integer,Map<Integer,String>> tabSpIndexValue;
		    private  ArrayAdapter<?> spAdapter;
		    private  ArrayAdapter<?> spDateAdapter;
//		    private  ArrayAdapter<?> spAdapterWeb;
		    @Override
			  public void onActivityCreated(Bundle savedInstanceState) {
			    super.onActivityCreated(savedInstanceState);
			    
			    initialCommonControlls();
		    }
		    
		    protected void initialCommonControlls(){
		    	 mSwipeLayout = (SwipeRefreshLayout)vContainer.findViewById(R.id.swipRefresh);
			     if (mSwipeLayout!=null){
			     
//			    	 txt_swip_refrsh = (TextView)vContainer.findViewById(R.id.txt_swip_refrsh); 
			        //设置刷新时动画的颜色，可以设置4个
			    	mSwipeLayout.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light);
			    	mSwipeLayout.setOnRefreshListener(this);
			     
			     }
			     
			     textContainer =(ScrollView)vContainer.findViewById(R.id.td_scrollView); 
			     
			     if(textContainer!=null)
				     textContainer.setOnTouchListener(new OnTouchListener() {
					    @Override
					    public boolean onTouch(View v, MotionEvent event) {
			 		        Utils.hideSoftKeyboard(activity);
					        return false;
					    }
					});
			   
			     initialWebListView(R.id.tr_listWeb);
//			     initialLoadingMore();
			     
			     imgWebPlus =(ImageView)vContainer.findViewById(R.id.img_webAdd);  
			     if (imgWebPlus!=null){
				  imgWebPlus.setOnClickListener(ButtonOnClickListener);
				  imgWebPlus.setVisibility(View.GONE);
			     } 
			     
				  
		    }

			  void initialWebListView(int viewId){
				 
			}
	  
		 
		 void webAdd(){
			if(this.isGroupQuery) {
				activity.showGroup(null);
			}else if(this.isActivityQuery){
				activity.showActvity(null);
			}else if(this.isBBSQuery){
				currentNote = new Note();
				currentNote.setUserId(activity.app.user.getUserbean().getId());
				currentNote.setCategory(this.BBScate);
				currentNote.setCateOwnerId(BBSSubcateOwner);
				currentNote.setSubCate(this.BBSSubcate);
				currentNote.setSubCateName(BBSsubCateName);
				 activity.showNewNote(currentNote);
			}
			  
		  }
				 
				 
	   protected void initialView(){ 
		   
		    isCateQuery =true;
		    firstLoad=true; 
		    btnQuery=(Button) vContainer.findViewById(R.id.st_btn_query);
		  
		    btn_queryCates=(ImageView) vContainer.findViewById(R.id.btn_CateQuery);
		    if(btn_queryCates!=null)
		    	btn_queryCates.setOnClickListener(ButtonOnClickListener);
		    btnQuery.setOnClickListener(ButtonOnClickListener); 
		    initTrackDateRangeSpin();  
		    etStartTime = (EditText)vContainer.findViewById(R.id.st_date_start);  
	        etEndTime = (EditText) vContainer.findViewById(R.id.st_date_end);   
	        tl = new datePickerListener();
	        etStartTime.setOnTouchListener(tl);  
	        etEndTime.setOnTouchListener(tl);  
	    	llDtRange =(LinearLayout)vContainer.findViewById(R.id.st_ll_custom);
			ll_selection =(LinearLayout)vContainer.findViewById(R.id.ll_selection);
			initQueryTrackTypeSpin();
//			initQueryTrackTypeSpinWeb();
			 initialTabhost();
			 cateLv = (com.qiyou.mb.android.ui.fragments.InnerGridView) vContainer.findViewById(R.id.cate_list); 
			if(cateLv!=null)
			 cateLv. setOnTouchListener(new OnTouchListener() {
				    @Override
				    public boolean onTouch(View v, MotionEvent event) {
		 		        Utils.hideSoftKeyboard(activity);
				        return false;
				    }
				});
			 cateQueryRdGroup = (RadioGroup)vContainer.findViewById(R.id.catesQuery_rdGroup);
			 if(cateQueryRdGroup!=null)
				 cateQueryRdGroup.setOnCheckedChangeListener(rdgChanged);
	        doQuery(); 
	       
		}
	   OnCheckedChangeListener rdgChanged = new OnCheckedChangeListener() {
           
           @Override
           public void onCheckedChanged(RadioGroup arg0, int arg1) {
               // TODO Auto-generated method stub
               //获取变更后的选中项的ID
               int radioButtonId = arg0.getCheckedRadioButtonId();
               //根据ID获取RadioButton的实例
//               RadioButton rb = (RadioButton)activity.findViewById(radioButtonId);
               
               if(radioButtonId ==R.id.catesQuery_b){
               
               cateQueryType=0;
               }else if(radioButtonId ==R.id.catesQuery_j){
               	   
            	   cateQueryType=1;               
               } 
                
           }
       }; 
		protected OnClickListener  ButtonOnClickListener = new OnClickListener() {
		    @Override
			public void onClick(View view) {
		    	switch (view.getId() ){
		    		case R.id.st_btn_query: {
		    			
		    			//			 QLog.getLogger().d(dTAG, TAG+  " -------------------OnClickListener Get StatTrack. -------------"  );
		    			doQuery() ;
		    			break;
		    			}
		    		case R.id.btn_CateQuery: {
		    	 
		    			doQuery();
		    			break;
		    			}
		    		case R.id.img_webAdd: {  webAdd(); break; }
		    		/*case R.id.btn_WebQuery: {  //move to baisc fragment
//		    			lastWebQueryPara="";
//		    			doQuery();
		    			initialWebQuery();
		    			break;
		    			}
		    		case R.id.btn_webpageup: {
		    		
		    			webPageup();
		    			break;
		    			}
		    		case R.id.btn_webpagedown: {
//		    			lastWebQueryPara="";
		    			webPagedown();
		    			break;
		    			}*/
		    		
		    	}
		    }
		};  
		
		
//		void webPageup(){}
//		void webPagedown(){}
		void loadingMore(){}
		void initialWebQuery(){}
		protected void doCatesQuery(){
			buildIds();
			doQuery() ;
			whereCates="";
			trackIds=null;
		}
		
		
/*		protected void	doInactiveQuery(){
//			whereCates  = " ifnull(" + TrackProvider.KEY_TRACK_AVSTATUS +","+TrackAvStatus.ACTIVE +")="+TrackAvStatus.INACTIVE;
			whereCates  =  TrackProvider.KEY_TRACK_AVSTATUS +"=="+TrackAvStatus.INACTIVE;
			 doQuery();
		}*/
		
		protected void	doRouteQuery(){
//			whereCates  = " ifnull(" + TrackProvider.KEY_TRACK_AVSTATUS +","+TrackAvStatus.ACTIVE +")="+TrackAvStatus.INACTIVE;
			whereCates  =  TrackProvider.KEY_TRACK_TYPE +"=="+TrackType.GPX;
			 doQuery();
		}

		
		
	    String whereCates="";
	    int cateQueryType=0;//0,1..并集，交集
		/*
		 * build trackIds from Cates selected.
		 */
		protected void buildIds(){
			ArrayList<Integer> ids =new ArrayList<Integer>();
			//			 QLog.getLogger().d(dTAG, " cateQueryType? " +cateQueryType  );
			whereCates="-1,";
			if(cateQueryType==0){
			   for(String cate:	activity.app.getQueryCategoryList()){
				   // //			 QLog.getLogger().d(dTAG, " cate? " +cate   );
					if(activity.app.mStatistics.getCategoryList().keySet().contains(cate)){					
						ids.addAll(activity.app.mStatistics.getCategoryList().get(cate));						
						 // //			 QLog.getLogger().d(dTAG, " exits in activity.app.getQueryCategoryList(), add all ids of "+cate     );
						 // //			 QLog.getLogger().d(dTAG, " added ids  is? "+activity.app.mStatistics.getCategoryList().get(cate)     );
					}
				}
				 
			}
			
			if(cateQueryType==1){
				String lastCate="";
				   for(String cate:	activity.app.getQueryCategoryList()){
					   if(!activity.app.mStatistics.getCategoryList().keySet().contains(cate)){//not exist at all.
						   // //			 QLog.getLogger().d(dTAG, cate +" not exits in activity.app.getQueryCategoryList(),break.. "     );
						   ids.clear();
						   break;
					   }
					    ArrayList<Integer> cates =(ArrayList<Integer>) activity.app.mStatistics.getCategoryList().get(cate).clone();//to avoid the retainAll removing the trackId ..
					    cates.remove(Integer.valueOf(0));
					    if(cates.size()==0){
					    	ids.clear();
					    	break;
					    }
					    // //			 QLog.getLogger().d(dTAG, "lastCate ?"+lastCate);
					    // //			 QLog.getLogger().d(dTAG, "Cate ?"+cate);
					    // //			 QLog.getLogger().d(dTAG, "Cates ?"+cates);
					   if(!TextUtils.isEmpty(lastCate))		{ 
						   
						  ArrayList<Integer> lastCates =activity.app.mStatistics.getCategoryList().get(lastCate);
						  cates.retainAll(lastCates);
						  if(cates.size()==0){
							ids.clear();
							break;
						  }
						 ids.retainAll(cates);  
					   }else
						   ids.addAll(cates);
					   
					   if(ids.size()==0) break;
					
//					 ids.addAll(cates);    
					 lastCate=cate;
						 
					}
					
				}
			
			for(Integer i:ids){
				  if(!getTrackIds().contains(i))getTrackIds().add(i);
			 }
			for(Integer i:getTrackIds()){
				
				whereCates+=i+"," ;
				 // //			 QLog.getLogger().d(dTAG, "whereCates ?"+whereCates);
			}
			if(  whereCates.lastIndexOf(",")>1){
				whereCates=whereCates.substring(0,whereCates.lastIndexOf(","));
			}
			whereCates =" _id in ("+whereCates+")";
			 // //			 QLog.getLogger().d(dTAG, "whereCates ?"+whereCates);
		}
		
		
		
	class datePickerListener implements View.OnTouchListener{

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			// TODO Auto-generated method stub
			if (event.getAction() == MotionEvent.ACTION_DOWN) {     
				 AlertDialog.Builder   albuilder = new AlertDialog.Builder(activity);
			   
//			       dtview.getParent()getView().
//			    if( dtview.getParent()!=null)
//			      ((ViewGroup) dtview.getParent()).removeView(dtview);   //java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
				
			   
			       
			       LayoutInflater inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);				       
			       View  dtview =   inflater.inflate(  R.layout.date_picker,null); 				       
			       albuilder.setView(dtview);  
			       
			       final DatePicker   datePicker = (DatePicker) dtview.findViewById(R.id.date_picker); 
			       
			       Calendar cal = Calendar.getInstance();  
		           cal.setTimeInMillis(System.currentTimeMillis());  
		           datePicker.init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), null);
		        	/*	   new OnDateChangedListener() {
                       
                        public void onDateChanged(DatePicker view, int year, int monthOfYear,
                                        int dayOfMonth) {
                                // TODO Auto-generated method stub
                                if (year>MAX) {
                                        view.updateDate(MAX, monthOfYear, dayOfMonth);
                                }else if (year<MIN) {
                                        view.updateDate(MIN, monthOfYear, dayOfMonth);
                                }
                        }
                });  */
				
//				   datePicker.setMaxDate(System.currentTimeMillis());
		           final TimePicker   timePicker = (TimePicker) dtview.findViewById(R.id.time_picker);    
		           
				
	            if (v.getId() == R.id.st_date_start) {  
	            	
	                final int inType = etStartTime.getInputType();  
	                etStartTime.setInputType(InputType.TYPE_NULL);  
	                etStartTime.onTouchEvent(event);  
	                etStartTime.setInputType(inType);  
	                etStartTime.setSelection(etStartTime.getText().length());  
	                  
	                albuilder.setTitle("选取起始时间");  
	                albuilder.setPositiveButton("确  定", new DialogInterface.OnClickListener() {  
	  
	                    @Override  
	                    public void onClick(DialogInterface dialog, int which) {   
	                    	
	                        Calendar cal = Calendar.getInstance(); 
	                    	cal.clear();
		                    cal.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth());
		                    int year =cal.get(Calendar.YEAR);
                        	int month =cal.get(Calendar.MONTH);
                        	int day =cal.get(Calendar.DAY_OF_MONTH);  
		                 
	                        dialog.cancel();
	                         
	                        if(cal.getTimeInMillis()>System.currentTimeMillis()){
	                        	cal = Calendar.getInstance();
	                            year =cal.get(Calendar.YEAR);
	                        	month =cal.get(Calendar.MONTH);
	                        	day =cal.get(Calendar.DAY_OF_MONTH);
	                        	cal.clear();
	                        	cal.set(year, month, day);		                        	
	                        }
	                        custStartDate = cal.getTimeInMillis(); 
	                        etStartTime.setText(String.format("%d-%02d-%02d",year,month+1,day)); 
	                        etStartTime.setText(Utils.getShortFormatedTime(custStartDate)); 
	                        cal=null; 
	                        isFilterChanged =true;
	                        if(custEndDate>0 && custEndDate < custStartDate){
	                        	custEndDate = custStartDate;
	                        	
	                        	etEndTime.setText(etStartTime.getText());
//	                        	etEndTime.setText( Utils.getShortFormatedTime(custStartDate));
	                        }
//	                        datePicker.setMinDate(custStartDate);
	                    }  
	                });  
	                  
	            } else if (v.getId() == R.id.st_date_end) {  
	                int inType = etEndTime.getInputType();  
	                etEndTime.setInputType(InputType.TYPE_NULL);      
	                etEndTime.onTouchEvent(event);  
	                etEndTime.setInputType(inType);  
	                etEndTime.setSelection(etEndTime.getText().length());  
	  
	                albuilder.setTitle("选取结束时间");  
	                albuilder.setPositiveButton("确  定", new DialogInterface.OnClickListener() {  
	  
	                    @Override  
	                    public void onClick(DialogInterface dialog, int which) {  

	                        Calendar cal = Calendar.getInstance(); 
	                    	cal.clear();
		                    cal.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth());
		                    int year =cal.get(Calendar.YEAR);
                        	int month =cal.get(Calendar.MONTH);
                        	int day =cal.get(Calendar.DAY_OF_MONTH);  
		                 
	                        dialog.cancel();
	                        
	                        if(cal.getTimeInMillis()>System.currentTimeMillis()){
	                        	cal = Calendar.getInstance();
	                            year =cal.get(Calendar.YEAR);
	                        	month =cal.get(Calendar.MONTH);
	                        	day =cal.get(Calendar.DAY_OF_MONTH);
	                        	cal.clear();
	                        	cal.set(year, month, day);		                        	
	                        }
	                         custEndDate = cal.getTimeInMillis(); 
//	                         etEndTime.setText(String.format("%d-%02d-%02d",year,month + 1,day)); 
	                         etEndTime.setText(Utils.getShortFormatedTime(custEndDate));
	                         cal=null;
	                         isFilterChanged =true;  
	                        if(custEndDate < custStartDate){
	                        	custStartDate=custEndDate;
                        		etStartTime.setText(etEndTime.getText());
//                        		etStartTime.setText( Utils.getShortFormatedTime(custEndDate));
	                        }
//	                        datePicker.setMaxDate(custEndDate);
	                    }  
	                });  
	            }else{
	            	
	            	 final TextView timeView =(TextView)vContainer.findViewById(v.getId());
	            	  final int inType = timeView.getInputType();  
		                timeView.setInputType(InputType.TYPE_NULL);  
		                timeView.onTouchEvent(event);  
		                timeView.setInputType(inType);  
	            	
		                albuilder.setTitle("选取日期");  
		                albuilder.setPositiveButton("确  定", new DialogInterface.OnClickListener() {  
		  
		                    @Override  
		                    public void onClick(DialogInterface dialog, int which) {  

		                        Calendar cal = Calendar.getInstance(); 
		                    	cal.clear();
			                    cal.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth());
//			                    int year =cal.get(Calendar.YEAR);
//	                        	int month =cal.get(Calendar.MONTH);
//	                        	int day =cal.get(Calendar.DAY_OF_MONTH);  
			                    timeView.setText(Utils.getShortFormatedTime(cal.getTimeInMillis()));
		                        dialog.cancel();
		                        
		                       /* if(cal.getTimeInMillis()>System.currentTimeMillis()){
		                        	cal = Calendar.getInstance();
		                            year =cal.get(Calendar.YEAR);
		                        	month =cal.get(Calendar.MONTH);
		                        	day =cal.get(Calendar.DAY_OF_MONTH);
		                        	cal.clear();
		                        	cal.set(year, month, day);		                        	
		                        }*/
		                        
		                      /*   custEndDate = cal.getTimeInMillis(); 
//		                         etEndTime.setText(String.format("%d-%02d-%02d",year,month + 1,day)); 
		                         etEndTime.setText(Utils.getShortFormatedTime(custEndDate));
		                         cal=null;
		                         isFilterChanged =true;  
		                        if(custEndDate < custStartDate){
		                        	custStartDate=custEndDate;
	                        		etStartTime.setText(etEndTime.getText());
//	                        		etStartTime.setText( Utils.getShortFormatedTime(custEndDate));
		                        }*/
//		                        datePicker.setMaxDate(custEndDate);
		                    }  
		                });  
	            	
	            	
	            	
	            }
	              
	            
	            Dialog dialog = albuilder.create();  
	            dialog.show();  
	        }  
	  
	        return true;  
		}
    	
    }
	
	int mHour;
	int mMinute;
//	long timePicked;
	
	class timePickerListener implements View.OnTouchListener{

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			// TODO Auto-generated method stub
			if (event.getAction() == MotionEvent.ACTION_DOWN) {     
				 AlertDialog.Builder   albuilder = new AlertDialog.Builder(activity);
			   
//			       dtview.getParent()getView().
//			    if( dtview.getParent()!=null)
//			      ((ViewGroup) dtview.getParent()).removeView(dtview);   //java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
				
			   
			       
			       LayoutInflater inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);				       
			       View  dtview =   inflater.inflate(  R.layout.time_picker,null); 				       
			       albuilder.setView(dtview);  
			       
			       Calendar cal = Calendar.getInstance();  
		           cal.setTimeInMillis(System.currentTimeMillis());  
			          
			       final TimePicker timePicker = (TimePicker) dtview.findViewById(R.id.time_picker);
	                //初始化时间 
	                timePicker.setIs24HourView(true); 
	                timePicker.setCurrentHour(cal.get(Calendar.HOUR_OF_DAY)); 
	                timePicker.setCurrentMinute(Calendar.MINUTE); 
	                  
	              final TextView timeView =(TextView)vContainer.findViewById(v.getId());
				 
//	            if (v.getId() == R.id.act_edit_starttime) {  
	            	
	                final int inType = timeView.getInputType();  
	                timeView.setInputType(InputType.TYPE_NULL);  
	                timeView.onTouchEvent(event);  
	                timeView.setInputType(inType);  
//	                timeView.setSelection(timeView.getText().length());  
	                  
	                albuilder.setTitle("选取时间");  
	                albuilder.setPositiveButton("确  定", new DialogInterface.OnClickListener() {  
	  
	                    @Override  
	                    public void onClick(DialogInterface dialog, int which) {   
	                    	
	                       
	                    	mHour = timePicker.getCurrentHour();
                            mMinute = timePicker.getCurrentMinute();
                            //时间小于10的数字 前面补0 如01:12:00
                            
                            timeView.setText(new StringBuilder().append(mHour < 10 ? 0 + mHour : mHour).append(":")
                            			.append(mMinute < 10 ? 0 + mMinute : mMinute).append(":00") ); 
                            
                         
                            dialog.cancel(); 
                            
	                    	
	                     
	                    }  
	                });  
	            
	            Dialog dialog = albuilder.create();  
	            dialog.show();  
	        }  
	  
	        return true;  
		}
    	
    }
	
	
	class dateTimePickerListener implements View.OnTouchListener{

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			// TODO Auto-generated method stub
			if (event.getAction() == MotionEvent.ACTION_DOWN) {     
				 AlertDialog.Builder   albuilder = new AlertDialog.Builder(activity);
			   
//			       dtview.getParent()getView().
//			    if( dtview.getParent()!=null)
//			      ((ViewGroup) dtview.getParent()).removeView(dtview);   //java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
				
			   
			       
			       LayoutInflater inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);				       
			       View  dtview =   inflater.inflate(  R.layout.time_picker,null); 				       
			       albuilder.setView(dtview);  
			       
			       
			       
			       
			       Calendar cal = Calendar.getInstance();  
		           cal.setTimeInMillis(System.currentTimeMillis());  
			       
		           final DatePicker   datePicker = (DatePicker) dtview.findViewById(R.id.date_picker);  
			       
		           datePicker.init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), null);
		           
		           
		           
			       final TimePicker timePicker = (TimePicker) dtview.findViewById(R.id.time_picker);
	                //初始化时间 
	                timePicker.setIs24HourView(true); 
	                timePicker.setCurrentHour(cal.get(Calendar.HOUR_OF_DAY)); 
	                timePicker.setCurrentMinute(Calendar.MINUTE); 
	                  
	              final TextView timeView =(TextView)vContainer.findViewById(v.getId());
				  final int viewId=v.getId() ;
//	            if (v.getId() == R.id.act_edit_starttime) {  
	            	
	                final int inType = timeView.getInputType();  
	                timeView.setInputType(InputType.TYPE_NULL);   
	                timeView.onTouchEvent(event);  
	                timeView.setInputType(inType);
	               /* timeView.getLayoutParams().width=LayoutParams.WRAP_CONTENT;
	                LayoutParams lp =  timeView.getLayoutParams();
	                lp.width=LayoutParams.WRAP_CONTENT;
	                timeView.setLayoutParams(lp);*/
//	                timeView.setSelection(timeView.getText().length());  
	                  
	                albuilder.setTitle("选取日期和时间");  
	                albuilder.setPositiveButton("确  定", new DialogInterface.OnClickListener() {  
	  
	                    @Override  
	                    public void onClick(DialogInterface dialog, int which) {    
	                    	
	                    	
	                    	Calendar cal = Calendar.getInstance(); 
		                    	cal.clear();
			                    cal.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth());
//			                    cal.set(year, month, day, hourOfDay, minute)
//			                    int year =cal.get(Calendar.YEAR);
//	                        	int month =cal.get(Calendar.MONTH);
//	                        	int day =cal.get(Calendar.DAY_OF_MONTH);  
//			                    timeView.setText(Utils.getShortFormatedTime(cal.getTimeInMillis()));
			                    
	                    	
//	                    	mHour = timePicker.getCurrentHour();
//                            mMinute = timePicker.getCurrentMinute();
                            //时间小于10的数字 前面补0 如01:12:00
                            cal.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth(),timePicker.getCurrentHour(), timePicker.getCurrentMinute());
                            
//                            timeView.setText(new StringBuilder().append(mHour < 10 ? 0 + mHour : mHour).append(":")
//                            			.append(mMinute < 10 ? 0 + mMinute : mMinute).append(":00") ); 
//                            timeView.setText(Utils.getFormatedTime("yy/mm/dd HH:mm",cal.getTimeInMillis()));
//                            timeView.setText(Utils.getShortFormatedTime(cal.getTimeInMillis()));
                            
                            timeView.setText(Utils.getFormatedTime(cal.getTimeInMillis()));
                            
                            onTimePicked(viewId ,cal.getTimeInMillis());
                            	 
                            dialog.cancel(); 
                            
	                    	
	                     
	                    }  
	                });  
	            
	            Dialog dialog = albuilder.create();  
	            dialog.show();  
	        }  
	  
	        return true;  
		}
    	
    }
	
	void onTimePicked(int viewId,long timePicked){
		
	}
	
	
 
    
    
    void initQueryTrackTypeSpin(){
    	
    	spTrackType = (Spinner)vContainer.findViewById(R.id.St_SpinnerTrackType); 
		//			 QLog.getLogger().d(dTAG,TAG+" 1 initTrackTypeSpin() lastTypeId,lastTypePos: "+ lastTypeId+","+lastTypePos);

    	if(activity.app.mStatistics!=null && activity.app.mStatistics.getTypeUsedLst().size()>0){ 
	    	ArrayAdapter<CItem > Adapter = new ArrayAdapter<CItem>(getActivity(),
	    						  R.layout.myspinner, activity.app.mStatistics.getTypeUsedLst()); 
			Adapter.setDropDownViewResource(R.layout.spinner_item);

	    	spTrackType.setAdapter(Adapter);
			//			 QLog.getLogger().d(dTAG,TAG+" 2 initTrackTypeSpin() lastTypeId,lastTypePos: "+ lastTypeId+","+lastTypePos);

	    	
	    	
	    	if(lastTypeId>0 && lastTypePos>0){ 
				spTrackType.setSelection(lastTypePos); 
				} else {
					int type = activity.app.getLastTracktype();
					String t = TrackType.values()[type].toCHString();
					int pos = 0;
					 for(int i=0;i< activity.app.mStatistics.getTypeUsedLst().size();i++){
						if( activity.app.mStatistics.getTypeUsedLst().get(i).getValue().equalsIgnoreCase(t)){
							pos = i;
							break;
						}
					 }
					 
					spTrackType.setSelection(pos);
					
					
				}
    	}
    	else{
			int type_array=Utils.getTrackType();// R.array.trackType;
//	    	if(QiYouConstant.DEVELOPER_MODE)
//	    		type_array =R.array.trackType_develop_use; 
		//将可选内容与ArrayAdapter连接起来
	     	spAdapter = ArrayAdapter.createFromResource( activity,type_array,  R.layout.myspinner);

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

			//将adapter2 添加到spinner中
	    	spTrackType.setAdapter(spAdapter);
		} 
    
//    	lastTypeId=-1;
//		lastTypePos=-1;
		//将可选内容与ArrayAdapter连接起来
/*         spAdapter = ArrayAdapter.createFromResource( getActivity(), R.array.trackType,  R.layout.myspinner);

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

		//将adapter2 添加到spinner中
    	spTrackType.setAdapter(spAdapter);
*/
		//添加事件Spinner事件监听  
    	spTrackType.setOnItemSelectedListener(new SpinnerXMLSelectedListener());

		//设置默认值
//    	spTrackType.setVisibility(View.VISIBLE);
/*    	if(activity.app.mStatisticsTracks!=null)	     
    	for(int i=0; i<activity.app.mStatisticsTracks.size();i++){
    		if(activity.app.mStatisticsTracks.get(i)==null)continue;
    		int type=activity.app.mStatisticsTracks.get(i).getType();
    		if(spTrackType.getChildAt(type)!=null){
	    		String txt=((TextView)spTrackType.getChildAt(type)).getText().toString();
	    		((TextView)spTrackType.getChildAt(type)).setText(txt +"..."+ activity.app.mStatisticsTracks.get(i).getStaticsTrackBeans().size());
    		}
    		
    	}*/
    	
//    	spTrackType.getChildAt(index);
//    	spTrackType.getItemAtPosition(position)
	}
    
    void initTrackDateRangeSpin(){
//    	if( spTrackDtRange!=null ||	lastTypeId>-1 ||	lastTypePos>-1 ) {
//    		doQuery();
//    		return;
//    	}
    	
    	spTrackDtRange = (Spinner)vContainer.findViewById(R.id.St_SpinnerDateRange);
		 
		//将可选内容与ArrayAdapter连接起来
    	spDateAdapter = ArrayAdapter.createFromResource( getActivity(), R.array.trackDateRanger,  R.layout.myspinner);

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

		//将adapter2 添加到spinner中
    	spTrackDtRange.setAdapter(spDateAdapter);
    	
    	if(lastDtRangeId>-1 ){ 
    		spTrackDtRange.setSelection(lastDtRangeId); 
			}
//    	lastDtRangeId =-1; 
		//添加事件Spinner事件监听  
    	spTrackDtRange.setOnItemSelectedListener(new SpinnerXMLSelectedListener());
    	
    	
		//设置默认值
//    	spTrackDtRange.setVisibility(View.VISIBLE);
		
	}
    
 /*void initQueryTrackTypeSpinWeb(){
    	
	 	spTrackTypeWeb = (Spinner)vContainer.findViewById(R.id.St_SpinnerTrackTypeWeb); 
	 	if(spTrackTypeWeb==null)return;
		//			 QLog.getLogger().d(dTAG,TAG+" 1 initTrackTypeSpin() lastTypeId,lastTypePos: "+ lastTypeId+","+lastTypePos); 
   
			int type_array=Utils.getTrackType();// R.array.trackType;
 
		//将可选内容与ArrayAdapter连接起来
			spAdapterWeb = ArrayAdapter.createFromResource( activity,type_array,  R.layout.myspinner);

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

			//将adapter2 添加到spinner中
	    	spTrackTypeWeb.setAdapter(spAdapterWeb);
	    	int type = activity.app.getLastTracktype(); //设置首选
	    	spTrackTypeWeb.setSelection(type);
	    	
	    	spTrackTypeWeb.setOnItemSelectedListener(new SpinnerXMLSelectedListener());
		 
 }*/
    
// 	void initWebQueryTypeSpinWeb(){
 	 
 		/*
 		  tabSpIndex = new HashMap<Integer,Integer>();		    
		    tabSpIndex.put(0, 0);
		    tabSpIndex.put(1, 4);
		    tabSpIndex.put(2, 4);
		    tabSpIndex.put(3, 4); 
 	
		    tabSpIndexValue = new HashMap<Integer,Map<Integer,String>>();
		    HashMap<Integer,String> tmp =new HashMap<Integer,String>();
		    tmp.put(0, "");
		    tabSpIndexValue.put(0, tmp);
		    
		    tmp =new HashMap<Integer,String>();
	 		tmp.put(4, "");
	 		tabSpIndexValue.put(1, tmp );
	 		
		    tmp =new HashMap<Integer,String>();
	 		tmp.put(4, "");
	 		tabSpIndexValue.put(2, tmp);
	 		
		    tmp =new HashMap<Integer,String>();
	 		tmp.put(4, "");
	 		tabSpIndexValue.put(3, tmp);
		  
		   */
 	 
	    	/*txt_webinput.setVisibility(View.VISIBLE);
			txt_webinput.setHint("例如："+QiYouConstant.PV_LAST_CITY); 
		    txt_webinput.setText(QiYouConstant.PV_LAST_CITY); 
			txt_webinput.setInputType(InputType.TYPE_CLASS_TEXT);*/
	     
		 
// 	}
 
    int lastDtRangeId=-1;
    int lastTypeId=-1;
   
    int lastTypePos=-1;
    int webLastTypePos=-1;
    int webLastTypeId=-1;
	boolean isFilterChanged=false;
	//使用XML形式操作
	class SpinnerXMLSelectedListener implements OnItemSelectedListener{
		@Override
		public void onItemSelected(AdapterView<?> spinner, View textView, int spID,
				long arg3) {
//			view2.setText("你使用什么样的手机："+adapter2.getItem(arg2));
			String cust ="自定义";
			  switch (spinner.getId() ){
	            case R.id.St_SpinnerDateRange: {
	            	buildDateFilter(spID);  
	            	if(cust.equalsIgnoreCase(spDateAdapter.getItem(spID).toString())){
	            		llDtRange.setVisibility(View.VISIBLE);
	            		custStartDate =0;
	            		custEndDate=0;	
	            		etStartTime.setText(strStartTime);
	            		etEndTime.setText(strEndTime);
	            		
	            	}else{
	            		llDtRange.setVisibility(View.GONE);
	            		custStartDate =0;
	            		custEndDate=0;	
	            		isFilterChanged =spID!=lastDtRangeId;
	            			
	            		if(isFilterChanged){
//	            			lastTypeId=spID;
	            			lastDtRangeId=spID;
	            			//			 QLog.getLogger().d(dTAG, TAG+  " -------------------R.id.St_SpinnerDateRange isFilterChanged  Get StatTrack. -------------"  );
	            			if(firstLoad){
	            				firstLoad=false;		            				
	            			}else	    
	            				doQuery();        				
//	            			if(!firstLoad)doQuery();
	            			
	            		}
	            	}		            		
	            			
	            break;	
	            }
				case R.id.St_SpinnerTrackType: {
//					trackType =spID; 
//					trackType =Integer.valueOf(((CItem)spTrackType.getSelectedItem()).GetID());
//					if(spTrackType.getSelectedItem() instanceof CItem && ((CItem)spTrackType.getSelectedItem()).GetID()!=null)
					if(spTrackType.getSelectedItem() instanceof CItem && !TextUtils.isEmpty(((CItem)spTrackType.getSelectedItem()).getId()) )
						trackType =Integer.valueOf(((CItem)spTrackType.getSelectedItem()).getId());
					else
						trackType=spID;
					lastTypePos =spID;
					isFilterChanged =trackType!=lastTypeId;
					//			 QLog.getLogger().d(dTAG, TAG+ " spID is: " +spID +", last");
					firstLoad=false;
					if(isFilterChanged){
//            			lastDtRangeId=spID;
            			lastTypeId=trackType;
            			//			 QLog.getLogger().d(dTAG, TAG+  " -------------------R.id.St_SpinnerTrackType isFilterChanged  Get StatTrack. -------------"  );
	            		
             			if(firstLoad){
             				firstLoad=false;
//            			 return;
            			} 
//            			if(!firstLoad)
             			doQuery();
            		}
				 
				break;		            	
				} 
				/*case R.id.St_SpinnerTrackTypeWeb:{
					webTrackType =spID; 
//					trackType =Integer.valueOf(((CItem)spTrackType.getSelectedItem()).GetID());
					if(spTrackTypeWeb.getSelectedItem() instanceof CItem && ((CItem)spTrackTypeWeb.getSelectedItem()).getId()!=null)
						webTrackType =Integer.valueOf(((CItem)spTrackTypeWeb.getSelectedItem()).getId());
					else
						webTrackType=spID;
					lastTypePos =spID;
					isFilterChanged =webTrackType!=webLastTypeId;
					//			 QLog.getLogger().d(dTAG, TAG+ " spID is: " +spID +", last");
					firstLoad=false;
					if(isFilterChanged){
//            			lastDtRangeId=spID;
						webLastTypeId=webTrackType;
            			//			 QLog.getLogger().d(dTAG, TAG+  " -------------------R.id.St_SpinnerTrackType isFilterChanged  Get StatTrack. -------------"  );
	            		
             			if(firstLoad){
             				firstLoad=false;
            			 return;
            			} 
//            			if(!firstLoad)
            				doQuery();
            		}
					break;
				}*/
				
			  }
			 
		}
		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			
		}		 
		
	}
	
	void webSpinnerSelected(int spID){
		 
		
	}
	
	/* int MAX=2014;
     int MIN=1990;
	class DateChangeListener implements  OnDateChangedListener{
			 
              public void onDateChanged(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
                      // TODO Auto-generated method stub
            	  if (year>MAX) { 
                      view.updateDate(MAX,  monthOfYear, dayOfMonth);
              }else if (year<MIN) {
                      view.updateDate(MIN,  monthOfYear, dayOfMonth);
              }
          }

		 
	}*/
	
	
	void buildDateFilter(int id){
		
		final int All=2;
		final int thisWeek=1;
		final int thisMonth=0;  
//		final long missPerday =24*3600*1000;
		startDate=0; 
    	//			 QLog.getLogger().d(dTAG, TAG+  " dateRange id is: " + id);
    	switch (id){
        	case All:{
        		break;
        	}
        	case thisWeek:{ 
        		startDate =Utils.getMondayOfTheWeek();        		
            	//			 QLog.getLogger().d(dTAG, TAG+  " startDate of the week is: " + Utils.getFormatedTime(startDate));
         		break;
        	}
        	case thisMonth:{ 
        		startDate =Utils.getFirstDayOfTheMonth();       		
            	//			 QLog.getLogger().d(dTAG, TAG+  " startDate of the month is: " + Utils.getFormatedTime(startDate));
            	break;
        	} 
    	
    	} 
    	 endDate =startDate>0?System.currentTimeMillis():0;
	}
	
	protected void initialTabhost(){
		
	}
	
	
	//-----------------------------------track list -------query------begin---------------------------------------------------------------
	
	  boolean isWebTrackQuery;  
	  boolean isByCatesQuery =false;  
//	  boolean isInactiveQuery =false;
	  boolean isRouteQuery =false;
      boolean isNormalQuery=false; 
      boolean isActivityQuery=false;
      boolean isMemberQuery=false;
      boolean isGroupQuery=false;
      boolean isBBSQuery=false;
      boolean isLiveQuery =false; 
       
     int trackSvrNumber;
 	 int svrTrackType;
 	 long lastupdated;
//	  int actPageNo=1;
//	  int memberPageNo=1; 
	  
	  int pageNo=1; 
	  int pageSize=10;	
	  
//	 int actSvrNumber;
	 int actType;
	 long actLastupdated;
	 
	 
//	  int grpSvrNumber;
//	  int grpPageNo=1;
	 

	 
	 List<Map<String, String>> liveData;
	 Map<Integer,Map<String, String>> liveDataMap;

	  void requestTrackFromWeb(int svrNumber){
			RequestParams params = new RequestParams();  
			params.add("id", String.valueOf( svrNumber));		
			params.add("swidth", String.valueOf(QiYouConstant.PV_INT_SCREEN_WIDTH));
			params.add("sheight", String.valueOf(QiYouConstant.PV_INT_SCREEN_HEIGHT));
			//			 QLog.getLogger().d(dTAG, TAG+" web query params: "+params);
	    getJsonWs(params, RestMethods.TRACK_G_FIND_BY_ID/*"mb/track/"*/);
//	    long l1 = System.currentTimeMillis();
//	    //			 QLog.getLogger().d("com.qiyou", TAG + " start Click item to show track detail, time is:" + l1);
//	    getJsonWs(null, "mb/track/" + this.svrNumber);
//	    /long l2 = System.currentTimeMillis() - l1;
//	    //			 QLog.getLogger().d("com.qiyou", TAG + " get data from web cost:" + l2);
	  }
	   
 
	  
	  boolean checkJsonArray(JSONObject jsonObject) throws JSONException{
		  
		  if(jsonObject==null || jsonObject.has("content") && jsonObject.has("first") 
				  					&&( jsonObject.getJSONArray("content") ==null ||jsonObject.getJSONArray("content").length()==0)){
//				 showNotes("没有数据");
//				 actData=null;
				 showNoRecText(true); 
//				 return false;
			 } 
		  
		  return true;
	  }
	  void showNoRecText(boolean isNoRec){
		  
	  }
	  
	  
	   @Override
		void processGetJsonObject(String method,JSONObject jsonObject,String msg) throws JSONException,NullPointerException, NoWebObjectException {
			 
		  super.processGetJsonObject(method, jsonObject, msg);
			 QLog.getLogger().d(dTAG, TAG+"------ge  web query data back --------- method is " + method); 
//		  if(this.isActivityQuery){
			  
			   if(jsonObject==null){
				   throw new NoWebObjectException();
			   }
				  
				
				if(method.equalsIgnoreCase(RestMethods.ACT_G_LIST) 
						/*||method.equalsIgnoreCase(RestMethods.ACT_G_NEARBY_LIST)*/ ){
					if(checkJsonArray(jsonObject)){
					   
						processActPageInfo(jsonObject ); 
						//			 QLog.getLogger().d(dTAG, TAG+"------get act web query data--------- "); 
    					//			 QLog.getLogger().d(dTAG, TAG+" activities : "+jsonObject.toString());

					}
 						 
				}   	//its a single act.
				else if(method.equalsIgnoreCase(RestMethods.ACT_G_FIND_BY_ID)){
					 Activity_bean localAct_bean = (Activity_bean)Utils.getGsonObject(jsonObject.toString(), Activity_bean.class);
					 writeActivitiesCache(localAct_bean );
 					 showActivity(localAct_bean);
			  
				 return;
				} 
				else  if(method.equalsIgnoreCase(RestMethods.USER_G_LIST)){  
//				if(jsonObject.has(QiYouConstant.JSONOBJECT_KEY)){// its a page<track>
					 
					   //			 QLog.getLogger().d(dTAG, TAG+"------get member web query data--------- ");
						if(checkJsonArray(jsonObject)){
//							//			 QLog.getLogger().d(dTAG, TAG+" members : "+jsonObject==null?null:jsonObject.toString());

						 processUserPageInfo(jsonObject );
						}
				 
				 }  
				//its a single  data.
				 else  if(method.equalsIgnoreCase(RestMethods.USER_G_FIND_BY_ID)){
//					if(jsonObject.has(QiYouConstant.JSONOBJECT_KEY)){ 
					 User_bean user = (User_bean)Utils.getGsonObject(jsonObject.toString(), User_bean.class);
	//				 writeActivitiesCache(String.valueOf(svrNumber) + this.actLastupdated, jsonObject);
	//				  showWebTrack(new Track(localTrack_bean));
					 showMember(user);
//					 activity.showUserDetails(user/*,0*/);
				  
				  
				  return;
				}
		   
				 else  if(method.equalsIgnoreCase(RestMethods.TRACK_G_LIST) 
						/* ||method.equalsIgnoreCase(RestMethods.TRACK_G_FIND_BY_ACT_GRP)*/  ){
  
    
					 //			 QLog.getLogger().d(dTAG, TAG+"------get web query data--------- ");
				 	if(checkJsonArray(jsonObject)){
 			   
				 		processTrackPageInfo(jsonObject );
				 	}
			  
			 }	 else  if(method.equalsIgnoreCase(RestMethods.TRACK_G_FIND_BY_ID)){	 
			//its a single track.
			 
				 Track_bean localTrack_bean = (Track_bean)Utils.getGsonObject(jsonObject.toString(), Track_bean.class);
				  writeWebTrackCache(String.valueOf(localTrack_bean.getSvrNumber()) + localTrack_bean.getLastdbTime(), jsonObject);
				  showWebTrack(new Track(localTrack_bean));
			  
			 }  else  if(method.equalsIgnoreCase(RestMethods.LIVE_G_SHARE_LIST)){	  
				 
				     //			 QLog.getLogger().d(dTAG, TAG+"------get live query data--------- ");
			 	 
 				     //			 QLog.getLogger().d(dTAG, TAG+" shared locations: "+jsonObject==null?"null":jsonObject.toString()); 
			 		 processLiveData(jsonObject.getJSONArray("list") );
			 		 /*if(  btn_live_refresh !=null){
						  btn_live_refresh .setEnabled(true);
						}*/
			 } else if(method.equalsIgnoreCase(RestMethods.GRP_G_LIST)){	
				 if(checkJsonArray(jsonObject)){
					    //			 QLog.getLogger().d(dTAG, TAG+"------get group web query data--------- "); 
 					//			 QLog.getLogger().d(dTAG, TAG+" groups : "+jsonObject.toString());

						processGrpPageInfo(jsonObject );
					}
			 }
			 else if(method.equalsIgnoreCase(RestMethods.GRP_G_FIND_BY_ID)){  //show a single group
				 
				 Group_bean grp_bean = (Group_bean)Utils.getGsonObject(jsonObject.toString(), Group_bean.class);
//				 writeActivitiesCache(String.valueOf(svrNumber) + this.actLastupdated, jsonObject);
//				  showWebTrack(new Track(localTrack_bean));
				 showGroup(grp_bean);
		  
			 return;
			}else if(method.equalsIgnoreCase(RestMethods.NOTE_G_LIST) ||method.equalsIgnoreCase(RestMethods.NOTEMSG_G_LIST)  ) {
				 
				 if(checkJsonArray(jsonObject)){
					   
					 
					 QLog.getLogger().d(dTAG, TAG+"------get notes web query data--------- "); 
				 	 QLog.getLogger().d(dTAG, TAG+" notes : "+jsonObject.toString());
				 	 
				 	 processNotesPageInfo(jsonObject ); 

					}
					
		      }else if(method.equalsIgnoreCase(RestMethods.NOTE_G_FIND_BY_ID)  ) {
		    	   
		    	  activity.showNoteDetail( (Note)Utils.getGsonObject(jsonObject.toString(), Note.class),null);
		    	  
			  }
				
		}

		boolean isBBSLastPage; 
		void processNotesPageInfo(JSONObject jo) throws JSONException{
				 if(jo==null){
					 
					 return;
				 }
				 isBBSLastPage =jo.getBoolean("last");
//			  isGrpFirstPage =jo.getBoolean("first"); 
				    QLog.getLogger().d(dTAG, TAG+"   isNoteLastPage--- " + isBBSLastPage); 

			  processNotesJsonArray(jo.getJSONArray("content"));
		  } 
		
		
//	     boolean isFirstPage;
		 boolean isTrackLastPage;
		  void processTrackPageInfo(JSONObject jo) throws JSONException{
			  if(jo==null){
				  processTrackJsonArray(null);
					 return;
			  }
//			  jo.getInt("totalPages");
			  isTrackLastPage =jo.getBoolean("last");
//			  isFirstPage =jo.getBoolean("first");		  		  
//			  jo.get("size");//pagesize
//			  jo.get("totalElements"); //总数
//			  jo.get("numberOfElements");//返回个数
//			  jo.get("number"); 
			  
//			  this.btn_pagedown.setEnabled(!isLastPage);
//			  this.btn_pageup.setEnabled(!isFirstPage);
			  processTrackJsonArray(jo.getJSONArray("content"));
		  }
//		  boolean isActFirstPage;
		  boolean isActLastPage; 
		  void processActPageInfo(JSONObject jo) throws JSONException{
				 if(jo==null){
					 processActJsonArray(null);
					 return;
				 }
//			  jo.getInt("totalPages");
//			  isActLastPage =jo.getBoolean("last");
				 isActLastPage =jo.getBoolean("last");
//			  isActFirstPage =jo.getBoolean("first");		  		  
//			  jo.get("size");//pagesize
//			  jo.get("totalElements"); //总数
//			  jo.get("numberOfElements");//返回个数
//			  jo.get("number"); 
			  
//			  this.btn_pagedown.setEnabled(!isLastPage);
//			  this.btn_pageup.setEnabled(!isFirstPage);
			  processActJsonArray(jo.getJSONArray("content"));
		  }
		  
//		  boolean isGrpFirstPage;
		  boolean isGrpLastPage; 
		  void processGrpPageInfo(JSONObject jo) throws JSONException{
				 if(jo==null){
					 processGrpJsonArray(null);
					 return;
				 }
 				 isGrpLastPage =jo.getBoolean("last");
//			  isGrpFirstPage =jo.getBoolean("first"); 
				    //			 QLog.getLogger().d(dTAG, TAG+"   isGrpLastPage--- " +isGrpLastPage); 

			  processGrpJsonArray(jo.getJSONArray("content"));
		  }
		  
		  boolean isMemberFirstPage;
		  boolean isMemberLastPage; 
		  void processUserPageInfo(JSONObject jo) throws JSONException{
			  if(jo==null){
				  processUserJsonArray(null);
					 return;
				 }
//			  jo.getInt("totalPages");
//			  isMemberFirstPage =jo.getBoolean("last");
			  isMemberLastPage =jo.getBoolean("last");
//			  isMemberLastPage =jo.getBoolean("first");		  		  
//			  jo.get("size");//pagesize
//			  jo.get("totalElements"); //总数
//			  jo.get("numberOfElements");//返回个数
//			  jo.get("number"); 
			  
//			  this.btn_pagedown.setEnabled(!isLastPage);
//			  this.btn_pageup.setEnabled(!isFirstPage);
			  processUserJsonArray(jo.getJSONArray("content"));
		  }  
		  
		  
		  
	  void processNotesJsonArray(JSONArray jsonArrary){
		  
	  } 
	  		  
	  void processTrackJsonArray(JSONArray jsonArrary){
		  
	  } 
	  
	  void processUserJsonArray(JSONArray jsonArrary){
		  
	  } 
		  
	  void processActJsonArray(JSONArray jsonArrary){
		  
	  }
	   
	  
	 
	  void showActivity(Activity_bean act) { 
		  	activity.showActvityHome(act);  
		 }
	  
  
	  void  showWebTrack(Track tr){ 
		  
	  }
	  void showGroup(Group_bean group) { 
		  	activity.showGroupHome(group);  
		  }
     
     void showMember(User_bean user){
    	 activity.showUserHome(user/*,0*/);
	  }
	  
	//--------------------end track act query list --------------------------
	  
	  
	  
	  
	  //-------------------------------live query begin--------------------- 
	  
	  long lastMaxLiveTime; // latest time stamp of received shared location
	  String lastLiveQueryPara="";
	  int selectedLiveItem=-1;
	  ListView liveLv;
		void  doLiveQuery(){
			
			Utils.hideSoftKeyboard(activity);
//			noRec.setVisibility(View.GONE);
//			this.isActShareQuery=true;
			liveLv.setVisibility(View.VISIBLE);
//			localTracklist.setVisibility(View.GONE);
			//			 QLog.getLogger().d(dTAG, TAG+"------begin live query--------- "); 
			
//			getJsonWs(buildQueryParames(),"mb/track/list/"+pageNo);
//			lastWebQueryPara
			
			/*if(this.firstLoad&&!TextUtils.isEmpty(lastLiveQueryPara)){
				//			 QLog.getLogger().d(dTAG, String.format("isfirstload%s last query para %s" , firstLoad,lastLiveQueryPara)); 
				return;
			}*/
			RequestParams param=buildLiveQueryParames();
			if(param!=null /*&& !lastLiveQueryPara.equalsIgnoreCase(param.toString())*/ ){
				
				//			 QLog.getLogger().d(dTAG, lastLiveQueryPara);
				//			 QLog.getLogger().d(dTAG, param.toString());
				
				getJsonWs(param,RestMethods.LIVE_G_SHARE_LIST/*"mb/sharelocation/list"*/);
				lastLiveQueryPara =param.toString();
				selectedLiveItem =-1;
				/*if(btn_live_refresh!=null){
					btn_live_refresh.setEnabled(false);
				}*/
				
			}
			
		}
	  
	  
		RequestParams buildLiveQueryParames(){
			return null;
		}
		 
		void processLiveData(JSONArray jsonArrary ) throws JSONException{
			if(jsonArrary==null){//no data
				return;
			}
			
//			JSONArray jsonArrary = jsonObject.getJSONArray(QiYouConstant.JSONOBJECT_KEY);
			
			 
			 liveDataMap =liveDataMap==null? new HashMap<Integer,Map<String, String>>():liveDataMap;
		
			 
			 
			 JSONObject jo = null;
			 SharedLocation sl;
			 ArrayList<SharedLocation> deltaList = new  ArrayList<SharedLocation>();
			 if(jsonArrary!=null)
			 for(int i=0;i<jsonArrary.length();i++){ 
				 try {
						jo=jsonArrary.getJSONObject(i); 
						if(jo==null)continue; 
						  			 QLog.getLogger().d(dTAG, "jsonarray:--> " +jo.toString());
						 sl=(SharedLocation) Utils.getGsonObject(jo.toString(), SharedLocation.class);
						 			 QLog.getLogger().d(dTAG, " sharedlocation data" +Utils.getGsonString(sl));
						 deltaList.add(sl);
					 }catch( JsonSyntaxException je){
						 Utils.logStackTrace(je, TAG);
						 continue;
					 } catch (JSONException e) {
						// TODO Auto-generated catch block
						 Utils.logStackTrace(e, TAG);
						 continue;
					}


				 if(sl!=null){
//					 tr= new Track(tb);
					 Map<String, String> t = new HashMap<String,String>();	
//					 t.put("abulm", sl.getName());
					 t.put("username", sl.getName());
					 t.put("userid", String.valueOf(sl.getId())); 
//					 t.put("dist",Utils.getFormatedDistance(sl.getDist())); 
//					 t.put("speed", String.format("%.0fkm/h",  sl.getSpeed()*3.6)); 
//					 t.put("time", Utils.getTimeCnt( java.lang.System.currentTimeMillis() - sl.getTime() ));
//					 t.put("time", Utils.getFormatedTime("hh:mm:ss", sl.getTime())); 
					 t.put("sort", String.valueOf(  sl.getTime())); 
					 t.put("msg",sl.getMsg());
					 t.put("lat", String.valueOf(sl.getLat())); 
					 t.put("lon", String.valueOf(sl.getLon())); 
					 
					 /* t.put("dist",     String.format("%s", Utils.getFormatedDistance(
							   (float) Utils.getDistanceFromXtoY(   sl.getLat(), sl.getLon(),
								QiYouConstant.PV_LAST_LAT, QiYouConstant.PV_LAST_LON)  )) );*/
					 t.put("dist",     sl.getLat()>0 &&QiYouConstant.PV_LAST_LAT>0? Utils.getFormatedDistance(
							   (float) Utils.getDistanceFromXtoY(   sl.getLat(), sl.getLon(),
								QiYouConstant.PV_LAST_LAT, QiYouConstant.PV_LAST_LON)  )
								:"--");

					 String sportData =String.format("d%.0f s%.0f  t%s", sl.getDist()/1000
							 											,sl.getSpeed()*3.6
							 											,Utils.getFormatedTime("HH:mm", sl.getTime())
							 											);
					 t.put("sportdata",sportData);
					 //			 QLog.getLogger().d(dTAG, " share sport data is " + sportData);
					 lastMaxLiveTime =lastMaxLiveTime>sl.getTime()?lastMaxLiveTime:sl.getTime();
					 liveDataMap.put(sl.getId(), t);
				 }
				 
				 
				  
			 }
//			 liveData = new ArrayList<Map<String, String>>() ;
			 if ( liveData != null ) {
				 liveData.clear();
			 } else {
				 liveData = new ArrayList<Map<String, String>>() ;
			 }
			 liveData.addAll( liveDataMap.values());

			 
//			 for( Map<String, String> map : liveData){
//				 //			 QLog.getLogger().d(dTAG, " print befor sort.." + map.get("sort"));
//			 }
			 
			 Collections.sort(liveData, new SortByTime(SortByTime.DESC,"sort"));
			 
//			 for( Map<String, String> map : liveData){
//				 //			 QLog.getLogger().d(dTAG, " print after sort.." + map.get("sort"));
//			 }
			 
		
			 showLiveData();
			  
			 showLiveMap(deltaList); 
//			 showLiveMap(liveDataMap.values()); 
			
		};
	  
	  
        void showLiveMap(ArrayList<SharedLocation> deltaList) { }//draw shared locations on map



		QSimpleAdapter    qsimpleAdapter; 
		 int currentActRow=0;
		protected void showLiveData( ){
			   
			  
			  qsimpleAdapter = new QSimpleAdapter(activity,liveData,R.layout.live_list_detail,
							new String[]{ 
					  				"abulm",
					  				"username",
					  				"dist",
					  				/*"avspeed",*/
					  				"sportdata",
					  				/*"time",*/
					  				/*"loc",*/
					  				"msg"
					  				
									},
							new int[]{ 
					  				 R.id.share_photo,
					  				 R.id.share_name,
					  				 R.id.share_dist,
					  				/* R.id.share_avspeed,*/
					  				 R.id.share_sportdata,
					  				/* R.id.share_time,*/
					  				/* R.id.share_loc,*/
					  				 R.id.share_msg 
					  				 
	        						}); 
		  
			  
			  
			    /* String toFind=  this.edit_act_query.getText().toString().trim();
				 if(!TextUtils.isEmpty(toFind)){
					 
					   qsimpleAdapter.getFilter().filter(toFind);
				 } */
		 		 
//			    qsimpleAdapter.getFilter().filter("a"); why filter not work....
			     liveLv.setAdapter(qsimpleAdapter);  
			    qsimpleAdapter.setSelectItem(selectedLiveItem);
			    liveLv.setSelection(selectedLiveItem); 
//			    bindListView(qsimpleAdapter,liveLv,selectedLiveItem,true);
  
//			    adapter.setSelectItem(selectedFoodmarkItem);
//			    localTracklist.setSelection(selectedFoodmarkItem);
			 
//			    localTracklist.smoothScrollToPosition(selectedFoodmarkItem);
//			    localTracklist.smoothScrollToPositionFromTop(selectedFoodmarkItem, 50);
		 }
	  
	  
	  
		  OnItemClickListener shareListItemListener = new OnItemClickListener() {  
		        @Override  
		        public void onItemClick(AdapterView<?> parent, View view, int position,  long id) {   

		        	selectedLiveItem =position;
		        
		        	 showSharePointOnMap(position);
		        	
		        }
		  };
		        
	  
	  void  showSharePointOnMap(int position){
		  
		     qsimpleAdapter.setSelectItem(position);
		     qsimpleAdapter.notifyDataSetInvalidated();
		     liveLv.setSelection(position);
		     if(position<0)return;
		    HashMap<String, String> localHashMap = (HashMap<String, String>)this.qsimpleAdapter.getItem(position); 
		 /*   this.svrNumber =  Integer.parseInt(localHashMap.get("userid")) ;
		    this.svrTrackType =    Integer.parseInt(localHashMap.get("type")) ;
		    this.lastupdated =   Long.parseLong(localHashMap.get("lastupdated")) ;
		    SharedLocation loc = new SharedLocation();*/
		    
		    
		    showSharePaoPao(this.liveDataMap.get(Integer.valueOf(  localHashMap.get("userid") )));
	  }
	  
	   protected  void showSharePaoPao(Map<String, String> sharedLocation){
		   
	   }
	  
	   
	   
	   void showShareListOnMap(){
		   LinearLayout   ll_list =(LinearLayout)vContainer.findViewById(R.id.share_ll_list);
		   if(ll_list==null) return;
		   
		   if(ll_list.getVisibility()==View.VISIBLE){
			   ll_list.setVisibility(View.GONE);
			   btn_live_list.setText(R.string.share_show_list);
		   }else{
			   ll_list.setVisibility(View.VISIBLE);
			   btn_live_list.setText(R.string.share_hide_list);
		   }
		   
	   }
	   void queryFromShareList(){
		   
		   this.hideNotes();
		   if(edit_act_query==null){
			   return;
		   }
		 showSharePointOnMap(-1);
		 String toFind=  this.edit_act_query.getText().toString().trim();
		 if(TextUtils.isEmpty(toFind)){
			 edit_act_query.setHintTextColor(Color.RED);
			 edit_act_query.setSelected(true);
			 this.showNotes("请输入查找的驴友名称");  
			 return;}
		  int position=0;
		   for(Map<String,String> map:liveData){
			   
			   if(map.get("username")!=null 
					   && (map.get("username").equalsIgnoreCase(toFind) || map.get("username").contains(toFind))){
				   
				   selectedLiveItem =position; 
		           showSharePointOnMap(position);
				   return;
//		           break;
				   
			   }
			   
			   position++;
			  
		   } 
		   this.showNotes("没找到 "+toFind);  
		   
// 		   qsimpleAdapter.getFilter().filter(toFind);
// 		    liveLv.setAdapter(qsimpleAdapter);  
//		    qsimpleAdapter.setSelectItem(-1);
//		    liveLv.setSelection(-1); 
//		     qsimpleAdapter.notifyDataSetInvalidated();

	   }
	   
	   void onNameFindChange(){
		 String  toFind=  this.edit_act_query.getText().toString().trim();
		 if(TextUtils.isEmpty(toFind)){
			 return;
		 }else{
//			 showLiveData();
			 try{
			  
				 qsimpleAdapter.getFilter().filter(toFind);
			 }catch (NullPointerException e){
				 
			 }
// 			    qsimpleAdapter.setSelectItem(-1);
//			    liveLv.setSelection(-1); 
//			     qsimpleAdapter.notifyDataSetInvalidated();
		 }
	   }
	   
	   
	   TextWatcher watcher = new TextWatcher() {
		     
		     @Override
		     public void onTextChanged(CharSequence s, int start, int before, int count) {
		         // TODO Auto-generated method stub
		         
		     }
		     
		     @Override
		     public void beforeTextChanged(CharSequence s, int start, int count,
		             int after) {
		         // TODO Auto-generated method stub
		         
		     }
		     
		 
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				onNameFindChange();
			}
		 };
	     
	    
	  //-----------------------------live list end ---------------------------
	  

		public List<Integer> getTrackIds() {
			if(trackIds==null)trackIds =new ArrayList<Integer>();
			return trackIds;
		}

		public void setTrackIds(List<Integer> trackIds) {
			this.trackIds = trackIds;
		}
	

		void requestUserFromWeb(int userId){
			if(userId<=0) return;
			RequestParams params = new RequestParams();  
//			params.add("id", String.valueOf( userId));	 
			 
//			//			 QLog.getLogger().d(dTAG, TAG+" web query params: "+params);
//	         getJsonWs(params, "mb/user/");
			getJsonWs(params, RestMethods.USER_G_FIND_BY_ID/*"mb/user/"*/+userId);
			
			
			
			
		}
		void processGrpJsonArray(JSONArray jsonArrary) {
			// TODO Auto-generated method stub
			
		} 
		
		
		//<!-----------------start  building loading ---------------------------------------->
	   
		boolean isLoadingMore=false;//more button in the view clicked
		protected TextView loadingMore;
		protected ImageView loadingImg;
	    boolean  canLoadingMore =false;
	    protected View ll_loadmore;
	    
	    
		   void initialLoadingMore(){
				 ll_loadmore = activity.getLayoutInflater().inflate(R.layout.load_more, null); 
//		 		 btn_loadMore=(Button)ll_loadmore.findViewById(R.id.loadMoreButton); 
//			     btn_loadMore.setOnClickListener(ButtonOnClickListener);
			     loadingMore =(TextView)ll_loadmore.findViewById(R.id.loadMoreLable); 
			     loadingImg =(ImageView)ll_loadmore.findViewById(R.id.img_loadMore); 
		   }
		private List<Map<String, String>> initialListData(List<Map<String, String>> listData 	){
			 if(listData==null ||/* !isLoadingMore ||*/ pageNo == 1){ //初始化，或者新查询
				 QLog.getLogger().d(TAG, "isLoadingMore? "+ isLoadingMore +" ,pageNo: "+ pageNo);
				 listData= new ArrayList<Map<String, String>>() ;
			   }
			 isLoadingMore =false;
			 return listData;
		}
		
		List<Map<String, String>> getListData(List<Map<String, String>> listData ,List<Map<String, String>> dataValue 	){
		 
			 
			 listData =initialListData(listData);
			 listData.addAll(dataValue);
			 
			 return listData;
		}
		
		
		
		void bindListView(QSimpleAdapter qsimpleAdapter,ListView listView,int selectItem,boolean isLastPage){
			 selectItem =lastIndexOnMore>0?
					 					visibleLastIndex<qsimpleAdapter.getCount()?
					 									qsimpleAdapter.getCount()-pageSize
					 									:qsimpleAdapter.getCount()
					 					 :selectItem;
					 									
			 isLastPage =isLastPage ||  qsimpleAdapter.getCount()<pageSize;					
			 
			if(loadingMore == null){initialLoadingMore() 	;}					
			loadingMore.setText(isLastPage?R.string.loadmore_complete:R.string.loadmore);
//			loadingMore.setEnabled(!isLastPage);
			loadingImg.setBackgroundResource(isLastPage?R.drawable.icon_stop:R.drawable.icon_busy);
			canLoadingMore = !isLastPage;
			 //			 QLog.getLogger().d(dTAG, "------ can loading more  1.. " + canLoadingMore);
			 QLog.getLogger().d(dTAG, "------ can loading more visibleItemCnt: " + visibleItemCnt +",selectItem :"+selectItem);
			 listView.removeFooterView(ll_loadmore);
//			 if(qsimpleAdapter.getCount()>=pageSize){
				 listView.addFooterView(ll_loadmore);
//			 }
			 listView.setAdapter( qsimpleAdapter);  
			 if (visibleItemCnt > 0){
				 selectItem -= visibleItemCnt -1 -1;
			 }
			 selectItem = selectItem <0 ? -1 : selectItem;
			 QLog.getLogger().d(dTAG, "------ can loading more visibleItemCnt: " + visibleItemCnt +",selectItem :"+selectItem);
			 
			 
		     if(lastIndexOnMore<=0){
		    	 qsimpleAdapter.setSelectItem(selectItem);
		     }
			 listView.setSelection(selectItem); 
			 listView.setDividerHeight(0);
			 listView.setVisibility(View.VISIBLE);
			 if (mSwipeLayout!=null){
				 mSwipeLayout.setRefreshing(false);
			 }
			 
			 setNote();
			 
		}
		
		void setNote() {}
		
		 class ListviewOnScroll implements OnScrollListener{

			  /** 
			     * 滑动时被调用 
			     */  
			    @Override  
			    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {  
			    	visibleItemCnt = visibleItemCount;  
			        visibleLastIndex = firstVisibleItem + visibleItemCount - 1;  
			    }  
			  
			    /** 
			     * 滑动状态改变时被调用 
			     */  
			    @Override  
			    public void onScrollStateChanged(AbsListView view, int scrollState) {  
			        int itemsLastIndex = view.getAdapter().getCount() - 1;    //数据集最后一项的索引  
   		        int lastIndex = itemsLastIndex;// + 1;             //加上底部的loadMoreView项  
			        //			 QLog.getLogger().d("com.qiyou",String.format("lastIndex is  %s，visiblelastIndex is  %s", lastIndex,visibleLastIndex));  
			        if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && visibleLastIndex == lastIndex) {  
			            //如果是自动加载,可以在这里放置异步加载数据的代码  
			        	if(!canLoadingMore){
			        		return;
			        	}
			        	loadingMore();
			           //			 QLog.getLogger().d("com.qiyou"," LOADMORE loading...");  
			        }  
			    }  
			      
			
		}
		 
		 
		 
		 @Override
			public void onRefresh() {
				// TODO Auto-generated method stub
				 QLog.getLogger().d(dTAG, "refreshing.....");
				 this.doQuery();
//				 this.initialWebQuery();
				 
				 
			}
		 
		 
		 
		 //------------ lcoal for track list
		 
		  protected Cursor cursor = null;
		  protected QCursorAdapter adapter;
	 
		  protected ProgressDialog progressDialog ;
	 
		  protected ListView localTracklist = null;
	 
		  protected  String whereClause=null;
		  protected int selectedTrackItem=-1;
		    protected CheckBox chk_show_map;
		     protected TextView txtNote;
		     protected CheckBox chk_show_pic;
		  /**
		   * {@inheritDoc}
		   * This loader will return the ID, Reference, Name, and Distance of all the venues
		   * currently stored in the {@link PlacesContentProvider}.
		   */
		  @Override
		public Loader<Cursor> onCreateLoader(int id, Bundle args) {
		    String[] projection = new String[] {TrackProvider.KEY_ID,TrackProvider.KEY_TRACK_START_TIME,
		    			 TrackProvider.KEY_TRACK_DISTANCE,TrackProvider.KEY_TRACK_SPORT_TIME,TrackProvider.KEY_TRACK_CAL_BURNING,
		    			 TrackProvider.KEY_TRACK_COMMENT,TrackProvider.KEY_TRACK_NAME,TrackProvider.KEY_TRACK_DESC,
		    			 TrackProvider.KEY_TRACK_MDWPS,TrackProvider.KEY_TRACK_CREATOR,TrackProvider.KEY_TRACK_END_TIME,
		    			 TrackProvider.KEY_TRACK_STATUS,TrackProvider.KEY_LAST_UPDATE_TIME,TrackProvider.KEY_SVR_NUMBER,
		    			 TrackProvider.KEY_TRACK_ROAD_BEARS};
		    
//		    String orderby =(lastTypeId==TrackType.GPX.toInt())?TrackProvider.KEY_TRACK_STATUS+","+TrackProvider.KEY_ID +" DESC":TrackProvider.KEY_ID +" DESC";
//		    String orderby =( TrackProvider.KEY_LAST_UPDATE_TIME +" DESC");
		    String orderby =( TrackProvider.KEY_ID +" DESC");
		    return new CursorLoader(activity, TrackProvider.TRACKS_URI, 
		        projection, whereClause, null,   orderby);
		  }
		  
		  /* Loader<Cursor> getCursor() {
			    String[] projection = new String[] {TrackProvider.KEY_ID,TrackProvider.KEY_TRACK_START_TIME,
		    			 TrackProvider.KEY_TRACK_DISTANCE,TrackProvider.KEY_TRACK_SPORT_TIME,
		    			 TrackProvider.KEY_TRACK_COMMENT,TrackProvider.KEY_TRACK_NAME,TrackProvider.KEY_TRACK_DESC,
		    			 TrackProvider.KEY_TRACK_MDWPS};
		    
		    return new CursorLoader(activity, TrackProvider.TRACKS_URI, 
		        projection, whereClause, null,  TrackProvider.KEY_ID +" DESC");
		  }*/
		  
		@Override
		public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
			// TODO Auto-generated method stub
			if(this.isWebTrackQuery)return;
			if(this.isActivityQuery)return;
			if(progressDialog!=null)
			 progressDialog.dismiss();	 
			if(adapter ==null) return;
			 adapter.swapCursor(arg1);
			 showNoRecText(adapter.getCount()==0);

			 if(!isFilterChanged){
				 adapter.setSelectItem(selectedTrackItem);
		         localTracklist.setSelection(selectedTrackItem);
				 QLog.getLogger().d(dTAG, TAG+" selectedTrackItem:"+selectedTrackItem);
			 }
			

		}
		
	 

		@Override
		public void onLoaderReset(Loader<Cursor> arg0) {
			// TODO Auto-generated method stub
			if(adapter==null)return; 
			adapter.swapCursor(null);
	  	 
		}
		 
		 
		 
	 
		public void doTrackQuery(){
		/* 
			isByCatesQuery =queryType ==2;
//			isInactiveQuery =queryType ==2;
			isRouteQuery =queryType ==1;
			isNormalQuery =queryType ==0;*/
			final boolean isGpx =(lastTypeId==TrackType.GPX.toInt()) ||isRouteQuery;
//		    final Track tr = new Track();
		    
			final ArrayList<Integer> showingGpxIds =activity.app.getGpxShowingTracks();
			if(isByCatesQuery || isRouteQuery /*||isInactiveQuery*/){//by cates
				whereClause = whereCates;
			}else/* if(isNormalQuery)*/{
				
				endDate=System.currentTimeMillis();
				
				if(custStartDate>0||custEndDate>0){
					startDate =custStartDate;
					endDate =custEndDate;
					endDate=endDate==0?System.currentTimeMillis():endDate;
				}			
//				 endDate=endDate==0?System.currentTimeMillis():endDate;
				
				
				 
//				String timeCol= trackType==TrackType.GPX.toInt()?  TrackProvider.KEY_TRACK_CREATE_TIME: TrackProvider.KEY_TRACK_START_TIME;
				String timeCol=  TrackProvider.KEY_TRACK_CREATE_TIME;
				String timeColOld=  TrackProvider.KEY_TRACK_START_TIME;
			   	
			  whereClause = String.format("(%s >=%s and %s <= %s or %s >=%s and %s <= %s )", timeCol,startDate,timeCol,endDate,
					  timeColOld,startDate,timeColOld,endDate);
			    
		     whereClause +=    " and ifnull(" + TrackProvider.KEY_TRACK_TYPE +",1)" + " = " + trackType; 
						    
//			   whereClause =  timeCol + " >= "+ startDate + " and " 
//						    + timeCol + " <= "+ endDate 
//					 		+ " and ifnull(" + TrackProvider.KEY_TRACK_TYPE +",1)" + " = " + trackType;
			}
			
			whereClause=TextUtils.isEmpty(whereClause)?"1=1 ":whereClause;
//			if(!isInactiveQuery)	
//				whereClause+= " and ifnull(" + TrackProvider.KEY_TRACK_AVSTATUS +","+TrackAvStatus.ACTIVE +")=="+TrackAvStatus.ACTIVE;
//			    whereClause+=" and ( ifnull(" + TrackProvider.KEY_TRACK_AVSTATUS +","+TrackAvStatus.ACTIVE +")!="  +TrackAvStatus.DELETED   +
//								" OR " + TrackProvider.KEY_TRACK_AVSTATUS+" != "+TrackAvStatus.DELETED +")";
			    
			    whereClause+=" and (  "  + TrackProvider.KEY_TRACK_AVSTATUS+" != "+TrackAvStatus.DELETED +")";
		     
		   
		   QLog.getLogger().d(dTAG, TAG+" query tracklist whereClause: "+whereClause);
		 
		    adapter = new QCursorAdapter(
		            activity,
//		            android.R.layout.two_line_list_item,
		            isGpx? R.layout.gpx_list_detail: R.layout.track_list_detail,
		            cursor,  //null,  //      什么时候初始化的?.......................... onLoadFinished    adapter.swapCursor(data);                                 
		            new String[] {TrackProvider.KEY_TRACK_START_TIME, TrackProvider.KEY_TRACK_DISTANCE,
		            		        TrackProvider.KEY_TRACK_SPORT_TIME, TrackProvider.KEY_TRACK_CAL_BURNING,
		            		        TrackProvider.KEY_TRACK_COMMENT,
		            		        TrackProvider.KEY_TRACK_DESC, TrackProvider.KEY_TRACK_NAME
		            		        ,TrackProvider.KEY_TRACK_MDWPS,TrackProvider.KEY_TRACK_CREATOR,
		            		        TrackProvider.KEY_TRACK_END_TIME, TrackProvider.KEY_TRACK_STATUS,
		            		        TrackProvider.KEY_TRACK_STATUS,TrackProvider.KEY_SVR_NUMBER,
		            		        TrackProvider.KEY_TRACK_ROAD_BEARS},           
//		            new int[] {android.R.id.text1, android.R.id.text2},
		            new int[] {R.id.trakList_tv_starttime, R.id.trakList_tv_dist,R.id.trakList_tv_avs,R.id.trakList_tv_burn,
		            		R.id.trakList_tv_comment,R.id.trakList_tv_sportTime,R.id.trakList_tv_desc,R.id.trakList_tv_name
		            		,R.id.trakList_gridView,R.id.trakList_tv_creator,  R.id.trakList_tv_svrNo,R.id.trakList_tv_showGpx,R.id.trakList_staticMap,R.id.trakList_staticMap},
		            0);
		    // Allocate the adapter to the List displayed within this fragment.
		   

		    adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
		    	 
		        @Override
				public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
		     
//		            if(columnIndex == 1) {
//		     
//		                    TextView text = (TextView) view;  // get your View
//		     
//		                    text.setText(Utils.getFormatedTime(cursor.getLong(1) ));  //set some data
//		     
//		                    return true;
//		     
//		            }
		        	
		        	TextView text ;  // get your View 
		        	String unvailable="--";
		            switch (view.getId() ){
		            case R.id.trakList_tv_name: {	
		            	String name =cursor.getString(6);
		            	if(TextUtils.isEmpty(name))
		            		name ="No."+cursor.getString(0);
		            	  text = (TextView) view; 
		                  text.setText( Utils.getShortString(name,10));  //set some data
		    			return true;
		    			}
		        	case R.id.trakList_tv_creator:  {
		    			text = (TextView) view;   
		    			String creator = Utils.getShortString(  cursor.getString(9),20 ) ; 
		    			if(!TextUtils.isEmpty(creator)){	    			
		    				text.setText( creator) ;  
		    				text.setVisibility(View.VISIBLE);
		    			}
		    			return true;
		    		}
		        	case R.id.trakList_tv_svrNo:  {
		    			text = (TextView) view;  
		    			
		    			int svrNumber =cursor.getInt(13)  ; 
		    			if(svrNumber>0){	    			
		    				text.setText( "云编号：" + svrNumber) ;  
//		    				text.setVisibility(View.VISIBLE);
		    			}else
		    				text.setText( "未上传") ; 
		    			return true;
		    		}
		        	
		        	
		    		case R.id.trakList_tv_starttime: {
		    			text = (TextView) view; 
		                  text.setText(" "+Utils.getFormatedTimeMonthDay(cursor.getLong(1) ));  //set some data
		    			return true;
		    			}
		    		case R.id.trakList_tv_dist: {
//		    			  TextView text = (TextView) view;  // get your View 
		    			text = (TextView) view; 
		    			text.setText( String.format("%.2f",cursor.getFloat(2)/1000.0 ) );  //set some data
		    			return true;
		    			}
		    		case R.id.trakList_tv_avs:  {
//		    			  TextView text = (TextView) view;  // get your View 
		    			text = (TextView) view; 
		    			/*float f=cursor.getLong(3)>0? 3600*cursor.getFloat(2)/cursor.getLong(3):0;
		    			if(isGpx){
		    				f=cursor.getLong(10)-cursor.getLong(1)>0? 3600*cursor.getFloat(2)/(cursor.getLong(10)-cursor.getLong(1)):0;
		    			}*/
		    			float f=cursor.getLong(10)-cursor.getLong(1)>0? 3600*cursor.getFloat(2)/(cursor.getLong(10)-cursor.getLong(1)):0; //tavs
		    			if(f>0)
		    				text.setText(String.format("%.2f",f) );  //set some data
		    			else
		    				text.setText(unvailable);  //set some data
		    			return true;
		    			}
		    		
		    		case R.id.trakList_tv_showGpx:  {
//		    			CheckBox cb = (CheckBox) view;  
//		    			((CheckBox) view).setChecked(cursor.getInt(11)==TrackStatus.ACTIVE.toInt());   
		    			
//		    			String v =(cursor.getInt(11)==TrackStatus.ACTIVE.toInt())?"是":"否";
		    			boolean isShowing=(showingGpxIds.contains(cursor.getInt(0)));
//		    			String v =(activity.app.getGpxShowingTracks().contains(cursor.getInt(0)))?"是":"否";
		    			text = (TextView) view; 
		    			text.setText(isShowing?"是":"否");
		    			if(isShowing)
		    				text.setTextColor(Color.RED);
		    			else
		    				text.setTextColor(Color.GRAY);
		    			return true;
		    		}
		    		case R.id.trakList_tv_burn:  {
//		    			  TextView text = (TextView) view;  // get your View 
		    			text = (TextView) view; 
		    			float b=cursor.getFloat(4);	    
		    			if(b>0)
		    				text.setText(String.format("%.0f",b) );  //set some data
		    			else
		    				text.setText(unvailable );  //set some data
		    			return true;
		    			} 
		      		
		    		case R.id.trakList_tv_comment:  {
//		    			  TextView text = (TextView) view;  // get your View 
		    			text = (TextView) view;   
		    			String str=Utils.getShortString(  cursor.getString(5),20 ) ; 
		    			if(TextUtils.isEmpty(str))
		    				text.setVisibility(View.GONE);
		    			else{
		    				text.setText(  str );  //set some data
		    				text.setVisibility(View.VISIBLE);
		    			}	    				
		    				
		    			return true;
		    			}
		    		case R.id.trakList_tv_sportTime:  {
//		    			  TextView text = (TextView) view;  // get your View 
		    			text = (TextView) view;   
		    			/*long b=cursor.getLong(3);
		    			if(isGpx){
		    				b=cursor.getLong(10)-cursor.getLong(1) ; 
		    			}*/
		    			long b=cursor.getLong(10)-cursor.getLong(1) ;  //total time
		    			if(b>0)
		    				text.setText( Utils.getTimeCnt(b));  //set some data
		    			else
		    				text.setText(unvailable );  //set some dat
		    			 
		    			return true;
		    			}
		    		case R.id.trakList_tv_desc:  {
//		    			  TextView text = (TextView) view;  // get your View
		    			text = (TextView) view;  
		                String str=Utils.getShortString(  cursor.getString(7),20 ) ; 
		    			if(TextUtils.isEmpty(str))
		    				text.setVisibility(View.GONE);
		    			else{
		    				text.setText(  str );  //set some data
		    				text.setVisibility(View.VISIBLE);
		    			}
		    			return true;
		    			}	 
		    		
		    		case R.id.trakList_staticMap:  {
		    			if(chk_show_map !=null && !chk_show_map.isChecked())
		    				return true;
//		    			  TextView text = (TextView) view;  // get your View
		    			QimageView imgv =  (QimageView)  view;  
//		                tr.getTrackBean().setTrackId( cursor.getInt(0));
		    			
		    			/*if(!Utils.isNetworkConnected(activity)){
		    				  if(tr.isStaticMapExist()){
//		 		   	    		 IL.DisplayImage(tr.getStaticMap(),imgv);  Utils.getBaiduStaticMapUrl(tr);
		 	                	  
		 		   	    		imgv.setVisibility(View.VISIBLE);
		 		   	    	 }
		 		   	    	 else
		 		   	    		imgv.setVisibility(View.GONE); 
		    				  
		    				  return true;
		    			}*/
		    			asyncImageLoad(imgv,cursor.getInt(0),cursor.getLong(10) );
		              /*  Track tr;//=new Track(cursor.getInt(0),null,null,cursor.getString(14),null);
//		                tr=new Track(cursor.getInt(0), true,null,null);
		                tr=new Track();
		                tr.getTrackBean().setTrackId(cursor.getInt(0));
		                tr.assemblyContent();
		                
//		                if(tr.getTrackBean().getRoadWps().size()>1){
		                if(tr.getTrackBean().getTrkseg().size()>1){
		                	tr.setStartWp(new Waypoint());
		                	tr.setLastWp(new Waypoint());	                	
		                	tr.setMaxDistWp(new Waypoint());
			                tr.getLastWp().setWb(tr.getTrackBean().getRoadWps().get(tr.getTrackBean().getRoadWps().size()-1));
			                tr.getStartWp().setWb(tr.getTrackBean().getRoadWps().get(0));
			                tr.getMaxDistWp().setWb(tr.getLastWp().getWb());
			                String staticUrl= Utils.getBaiduStaticMapUrl(tr);
			                if(TextUtils.isEmpty(staticUrl)){
			            	   imgv.setVisibility(View.GONE);
			                }else{
			                	imgv.setVisibility(View.VISIBLE);
			            	    IL.DisplayImage(staticUrl,imgv);  
			                }
		                }*/
		              
		    			return true;
		    		 }	 
		    		
		    		
		    		case R.id.trakList_gridView:  {
//		    			  TextView text = (TextView) view;  // get your View  
		    			if(chk_show_pic !=null && !chk_show_pic.isChecked())
		    				return true;
		    			int picCnt=4;
		    			String[] Urls=getImages(cursor.getString(8),picCnt,cursor.getInt(13)); //pic cnt = screen.width/80
		    			  NoScrollGridView gridView =(NoScrollGridView) view;
		    			if(Urls!=null && Urls.length>0){
		    				 
		    			/*	if(Urls.length<4){
		    					String[] newUrls =new String[4];
		    					for(int i=0;i<Urls.length;i++){
			    					newUrls[i]=Urls[i];
			    				}
		    					for(int i=Urls.length;i<4 ;i++){
		    						newUrls[i]=Urls[0]; 
			    				 }
		    					
		    					Urls =newUrls;
		    					
		    				}*/
		    				 
		    				
//		    				NoScrollGridView gridView =(NoScrollGridView) view;
		    				 
		    				 gridView.setVisibility(View.VISIBLE);
		    				 gridView.setAdapter(new ImageGridAdapter(Urls, activity));
		    				 gridView.setFocusable(false);
		    				 
//		    			     gridView.setOnItemClickListener(itemListener);
		    			     gridView.cursorPosition=cursor.getPosition();
		    			  
		    			   
		    			      gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

		    				@Override
		    					public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//		    						imageBrower(position,Urls);
//		    						localTracklist.callOnClick();
//		    					 picGridClickedPosition =adapter.getCursor().getPosition();
//		    					localTracklist.performItemClick(gridView, position, id)
		    					
		    					int mpos = ((NoScrollGridView)parent).cursorPosition;
//		    					localTracklist.requestFocusFromTouch();
//		    					localTracklist.setSelection(mpos);
//		    					adapter.setSelectItem(mpos);
		    					localTracklist.performItemClick(localTracklist.getAdapter().getView(mpos, null, null), mpos, mpos);
		    					
		    					}
		    				});  
		    			     
		    			} 
		    				 else{
		    				 gridView.setVisibility(View.GONE);
		    			}
		    			
		    			
//		    			NoScrollGridView gridView =(NoScrollGridView) view;
		    		 
		    			
		    			
		    			return true;
		    			}
		    	
		    	
		            }
		            
		     
		            return false;
		     
		        }
		     
		    });
		     
		    
		    
			localTracklist.setAdapter(adapter);
			getLoaderManager().restartLoader(0, null, this);
		    
			
			if(ll_loadmore==null){
				 initialLoadingMore();
				   loadingMore.setText( R.string.loadmore_complete );
			 	   loadingImg.setBackgroundResource( R.drawable.icon_stop ); 
			 }
	 		localTracklist.removeFooterView(ll_loadmore);
			localTracklist.addFooterView(ll_loadmore); 
	 	    
		  	    // Populate the adapter / list using a Cursor Loader. 
		    
		    
		  
		   
//		    progressDiaQLog.getLogger().dismiss();
//		    activity.app.playBack=false; //TODO: review if it can be here.
		  /*  if(adapter.getCount()>0)
//		    if(adapter.getCursor().getCount()>0)
//		    if(adapter.getCursor().getCount()>0)
		    	noRec.setVisibility(View.GONE);
		    else
		    	noRec.setVisibility(View.VISIBLE);*/
		    
		}
		 

		  void asyncImageLoad(QimageView imageView,int trackId,long endTime) {
			AsyncImageTask asyncImageTask = new AsyncImageTask(imageView,trackId,endTime);
			asyncImageTask.execute();

		}
		 
		 
		  
		   String[] getImages(String mdJson,int cnt,int svrNumber){
			   
			   Track tr = new Track(null,null,null,mdJson);
			   tr.getTrackBean().setSvrNumber(svrNumber);
			   return tr.getPicList(cnt);
			   
 
		   }

		/**
		 * 使用AsyncTask异步加载图片
		 * 
		 * @author Administrator
		 * 
		 */
		private final class AsyncImageTask extends AsyncTask<String,Integer,String > {
			private QimageView imageView;
			private int trackId=0;
			private long endTime=0;
			public AsyncImageTask(QimageView imageView,int trackId,long endTime) {
				this.imageView = imageView;
				this.trackId=trackId;
				this.endTime=endTime;
			}

			/*protected Uri doInBackground(String... params) {// 子线程中执行的
				try {
					return ContactService.getImage(params[0], cache);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}*/

		
			@Override
			protected void onPostExecute(String staticUrl) {// 运行在主线程
				if (!TextUtils.isEmpty(staticUrl)   && imageView != null)
					if(TextUtils.isEmpty(staticUrl)){
			        	imageView.setVisibility(View.GONE);
			        }else{
			        	imageView.setVisibility(View.VISIBLE);
//			        	QLog.getLogger().d(dTAG, "imageloader to DisplayImage url is:"+staticUrl);
			        	if(IL!=null)
			        		IL.DisplayImage(staticUrl,imageView);  
			        }
			}

			@Override
			protected String doInBackground(String... params) {
							
				  Track tr =new Track();
	              tr.getTrackBean().setTrackId(trackId);
	              tr.getTrackBean().setEndTime(endTime);
	              return tr.getStaticMap();
	            
			}

			 
		}
		 
		boolean canclick =true;
		 Handler handler;
		 
		    OnItemClickListener trackListItemListener = new OnItemClickListener() {  
		        @Override  
		        public void onItemClick(AdapterView<?> parent, View view, int position,  long id) {   

		        	if(!canclick)return;	        	
		        		canclick =false;
		        	
		        	selectedTrackItem =position;
		        	 
		        	 
		        	 if(adapter==null){
		        		 return;
		        	 }
		        	 Cursor c = adapter.getCursor();
		        	 if(c==null || c.getCount()==0 || c.getCount() == position ){
							QLog.getLogger().d(dTAG, TAG+ " No record, return........ " );
    				 
							return;
						}
		        	 
		        	adapter.setSelectItem(position);
	 				adapter.notifyDataSetInvalidated();
					selectedTrackItem =position;
				 
					
		        	final long startClicktime=System.currentTimeMillis();
		        	QLog.getLogger().d(dTAG, 
		        			TAG+" start Click item to show track detail, time is:"+startClicktime);
		        	
//		        	if(progressDialog==null)
		        		progressDialog = ProgressDialog.show(activity, "请稍等...", "正在读取记录数据...", true);
		        		progressDialog.setCancelable(true);
	 		    		progressDialog.setCanceledOnTouchOutside(true);
		        	
		        	final long afterDialog =System.currentTimeMillis()-startClicktime;
		        	
		        	QLog.getLogger().d(dTAG, 
		        			TAG+" show progressDialog cost:"+afterDialog);
				        	final int mPosition= position;  
		    			
		    			handler = new Handler(){

		    				@Override
		    				public void handleMessage(Message msg) {
		    					
		    					//关闭ProgressDialog
		    				
		    		 
		    						if(msg.what==1){
		    							Toast.makeText(activity, "查询超时...",Toast.LENGTH_SHORT).show();
		    					} 
		    						else if(msg.what==0){
		    							showDetailTrack(trackId);
		    					}
		    					
		    					progressDialog.dismiss(); 
		    					canclick =true;
		    					 
		    					QLog.getLogger().d(dTAG, 
		    							 TAG+  " progressdialog dismissed:"+(System.currentTimeMillis()-afterDialog-startClicktime));
		    				}};
		    		   
		    				new Thread(){

		    					@Override
		    					public void run() {
		    						//需要花时间计算的方法		 
		    						Cursor c = adapter.getCursor();
		    						if(c==null || c.getCount()==0 || c.getCount() == mPosition ){
		    							QLog.getLogger().d(dTAG, TAG+ " No record, return........ " );
		   	    				 
		    							return;
		    						}
		    			      	    c.moveToPosition(mPosition);	 
//		    			      	    final String trackId = c.getString(c.getColumnIndex(TrackProvider.KEY_ID));	
//		    			      	    int trackId = c.getInt(c.getColumnIndex(TrackProvider.KEY_ID));
		    			      	  trackId = c.getInt(c.getColumnIndex(TrackProvider.KEY_ID));
		    			      	    QLog.getLogger().d(dTAG, TAG+ "start request for track of id "+ trackId  ); 
						      	    
		    						int topWaiting=0;
//		    						  String[] ids = new String[]{String.valueOf(Integer.valueOf(trackId) -1),trackId};
//		    						  String[] ids = new String[]{ "-1" ,trackId};		
//			      	  					QLog.getLogger().d(dTAG, TAG+ "..................Start to get ids............. "+ System.currentTimeMillis()  );   
//			      	  					activity.app.getTracks(ids);	 
		    						if(activity.app.recordingTrack!=null 
		    								&&activity.app.recordingTrack.getTrackBean().getTrackId()==trackId	    								
		    								&&(activity.app.currentTrack==null ||activity.app.currentTrack.getTrackBean().getTrackId()!=trackId)
		    								){
		    							if(activity.app.mStatistics!=null){
		    								activity.app.mStatistics.mergeTrack( activity.app.recordingTrack);	
		    							}
		    							activity.app.currentTrack=activity.app.recordingTrack;
		    							QLog.getLogger().d(dTAG, TAG+" set currentTrack to recordingTrack ");
				      	  				
		    						}else{
		    							activity.app.getTrack( trackId);
				      	  				QLog.getLogger().d(dTAG, TAG+" start to load track from db: "+trackId);

		    						}	    						
			      	  				QLog.getLogger().d(dTAG, TAG+" app.getCurrentTrack().getTrackBean().getTrackId() is:" +activity.app.getCurrentTrack().getTrackBean().getTrackId()+" trackId is,"+trackId);
			      	  				
//			      	  				Statics_bean sb;
//			      	  				if(activity.app.mStatistics!=null 
//			      	  						&&activity.app.mStatistics.getStatisticsTracks().get(lastTypeId)!=null){
//			      	  				  sb=activity.app.mStatistics.getStatisticsTracks().get(lastTypeId).getSbs().get(trackId);	
//			      	  				}
			      	  						 	
			      	  			 
	  			        		    while(	 activity.app.mStatistics==null 
		  			        		    		||(
		  			        		    				 isNormalQuery && (
		  			        		    						activity.app.mStatistics.getStatisticsTracks().get(lastTypeId)==null
		  			        		    						|| activity.app.mStatistics.getStatisticsTracks().get(lastTypeId).getSbs().get(new Integer(trackId))==null
		  			        		    				  )
		  			        		    				  ||/*(isByCatesQuery || isRouteQuery ||isInactiveQuery) &&*/ activity.app.getCurrentTrack().getTrackBean().getTrackId() != Integer.valueOf(trackId)
		  			        		    		)
	  			        		    		)
	  			        		    		
//		    			        	while( activity.app.getCurrentTrack().getTrackBean().getTrackId() != Integer.valueOf(trackId)
////		    			        			||app.getStatTrack().getType()!=app.getCurrentTrack().getTrackBean().getType().toInt() 
//		    			        			)
		    			        	  {
		    			        		
			    			        	 try {
			    			 				Thread.sleep(50);
			    			 				topWaiting+=50;
			    			 				QLog.getLogger().d(dTAG, TAG+" topWaiting:"+topWaiting);
			    			 				 
			    			 				if(topWaiting>QiYouConstant.MAX_TIME_GET_TRACK_FROM_DB/2   )
			    			 				{ 
			    			 					QLog.getLogger().d(dTAG, TAG+" topWaiting:"+topWaiting+",limit is:"+QiYouConstant.MAX_TIME_GET_TRACK_FROM_DB );
			    			 					if(activity.app.getCurrentTrack().getTrackBean().getTrackId() != Integer.valueOf(trackId))
			    			 					{
			    				 					handler.sendEmptyMessage(1);
			    				 					
			    			 					} else
			    			 						handler.sendEmptyMessage(0);
			    			 					
//			    			 					showDetailTrack(trackId);
			    			 					return;
			    			 				}
			    			 			  } catch (InterruptedException e) {
			    			 				// TODO Auto-generated catch block
			    			 				Utils.logStackTrace(e, TAG);
			    			 				}
			    				    	}
			      	  				QLog.getLogger().d(dTAG, TAG+" to show track detail....");

//	  			        		  showDetailTrack(trackId);
		    						handler.sendEmptyMessage(0);
		    					}}.start();
		    		     	 
		    					 
		    					 
		        } 
		        
		       
		    };
		    
		    
		 
		    void showDetailTrack(int trackId){
		    	
		    }
		    
		    
		    protected void setUserLinkSpanTxt(TextView txt,final int userId,String name){
		    	txt.setText(getUserLinkSpanTxt(userId,name));
		    	txt.setMovementMethod(LinkMovementMethod.getInstance());
		    }
		    
		    
		   protected SpannableString getUserLinkSpanTxt(final int userId,String name){
			   SpannableString spannableString1 = new SpannableString(name);
				spannableString1.setSpan(new ClickableSpan() {
					@Override
					public void onClick(View view) {
		  
						final int cate = BBSCate.USER.toInt();
						String cacheKey = cate + "-" + userId;
						String restMethod = "";
						Boolean isCached = activity.app.getWebObjcache().containsKey(cacheKey);
		 			 
							if (isCached) {
								User_bean obj = (User_bean) activity.app.getWebObjcache()
										.get(cacheKey);
								showMember(obj);

							} else {
								restMethod = RestMethods.USER_G_FIND_BY_ID;
							}
						 

						 if (!TextUtils.isEmpty(restMethod)){
							 RequestParams params = new RequestParams();  
								params.add("id", String.valueOf( userId));		
							       QLog.getLogger().d(dTAG, TAG+" web query params: "+params);
						       getJsonWs(params,restMethod );
						 }
						
		 			}
					
				},
				0, name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
				
				return spannableString1;
		   }
		    
		    
		    
		    
		    
		    
		    
		    
		    
		    
		    
		    
		    
		 
		 
			
	}


class SortByTime implements Comparator<Map<String, String>> {
	
	  public static int ASC=1;
	  public static int DESC =-1;
		//  public static String sortByTime="time";
		//  public static String sortByDist="dist";
		//  public static String sortByRange=4;

	  private int direction;
	  private String column;
	public SortByTime(int sortDirection, String sortColumn){
		direction = sortDirection;
		column = sortColumn;
	}

	@Override
	public int compare(Map<String, String> map1, Map<String, String> map2) {
		// TODO Auto-generated method stub
		
			if(Long.valueOf(map1.get("sort"))>Long.valueOf(map2.get("sort"))){
				return -1;
			}
			
			return 1;
		}
	
	 
	
	}
	



	

