package com.backfire.doudizhu.lobby;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import net.yeeyo.doudizhu.feiyu.R;

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

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

//import cn.wimipay.sdk.WimiPaySdk;

import com.backfire.doudizhu.ActivityContainer;
import com.backfire.doudizhu.ActivityContainer.ActivityType;
import com.backfire.doudizhu.ActivityThirdPlatform;
import com.backfire.doudizhu.bean.PayTip;
import com.backfire.doudizhu.common.AnimationController;
import com.backfire.doudizhu.common.ClickFilter;
import com.backfire.doudizhu.common.DdzApplication;
import com.backfire.doudizhu.common.DownLoadImage;
import com.backfire.doudizhu.common.DownLoadImageListener;
import com.backfire.doudizhu.common.JSONUtil;
import com.backfire.doudizhu.common.MyJson;
import com.backfire.doudizhu.common.ShareData;
import com.backfire.doudizhu.userinfo.UserInfo;
import com.backfire.doudizhu.userinfo.UserMessageCenter;
import com.backfire.php.PHPCallbackInterface;
import com.backfire.php.PHPMethodName;
import com.backfire.php.PHPRequestPool;
import com.backfire.php.PHPResult;
import com.backfire.php.PHPResult.ErrorCode;
import com.backfire.popupwindow.AlertPopupWindow;
import com.backfire.popupwindow.GiftPopupWindow;
import com.backfire.popupwindow.LoginAwardPopupWindow;
import com.backfire.popupwindow.NoticePopupWindow;
import com.backfire.popupwindow.SelectPopupWindow;
import com.backfire.popupwindow.SettingPopUpWindow;
import com.backfire.popupwindow.TableTroducePopupWindow;
import com.backfire.popupwindow.UserInfoPop;
import com.backfire.room.Interface.ISendTips;
import com.backfire.room.data.ConfigCenter;
import com.backfire.room.data.ResCenter;
import com.backfire.utils.FeedSaveFile;
import com.backfire.utils.Log;
import com.backfire.utils.MyAsyncTask;
import com.backfire.utils.MyTaskWrap;

//import com.tencent.android.tpush.XGPushConfig;
//import com.tencent.android.tpush.XGPushManager;
import com.umeng.analytics.MobclickAgent;
import com.umeng.update.UmengUpdateAgent;

public class LobbyActivity extends ActivityThirdPlatform implements ISendTips {
	private TextView lobby_user_nick;
	private TextView lobby_user_money;
	private TextView lobby_user_lottery;
	private TextView lobby_user_exchange;
	private ScrollingTextView lobby_user_tips;
	private TextView lobby_user_players;
	private ImageView lobby_upgrade;

	/*
	 * private ImageView waitting_timer_1; private ImageView waitting_timer_2;
	 * private ImageView waitting_timer_3; private ImageView waitting_timer_4;
	 * private ImageView waitting_timer_5; private ImageView waitting_timer_6;
	 */
	private ImageView lobby_user_icon;

	private int countStep = 0;

	private final int NOTIFY_STEP = 1111;
	private final int LOGIN_AWARD = 1112;
	private final int NOTICE_TIPS = 1113;
	private final int UPDATE_USERINFO = 1114;
	private boolean flag = false;

	private Handler myHandler;
	AnimationDrawable rocketAnimation;
	AnimationDrawable upgradeAnimation;

	Drawable bg;

	private RelativeLayout download_layout;
	private SeekBar seekbar_download;
	private TextView download_tip;
	private boolean beginDownLoad = false;
	private int downLoadFilePosition = 0;
	private int fileSize = 0;

	private RelativeLayout main_layout;
	private RelativeLayout conmom_layout;
	private RelativeLayout laizi_layout;
	private RelativeLayout super_laizi_layout;
	private RelativeLayout match_layout;
	private ImageView task_num;
	private ImageView gift_num;

	private List<CourtBean> commondata;
	private ListView commonPager;// 页卡内容
	private CommonPagerAdapter commonAdapter = null;

	private List<CourtBean> laizi_data;
	private ListView laizi_Pager;// 页卡内容
	private LaiziPagerAdapter laiziAdapter = null;

	private List<CourtBean> match_data;
	private ListView match_Pager;// 页卡内容
	private MatchAdapter matchAdapter = null;

	private List<CourtBean> super_laizi_data;
	private ListView super_laizi_Pager;// 页卡内容
	private SuperLaiziPagerAdapter superLaiziAdapter = null;

	private boolean isMainView = true;

	private AnimationController animationController;

	private RelativeLayout currentLinear = null;
	private int currentTab = 0;

	// private ProgressBar lobbyBarView;

	ImageView waitting_timer_1, waitting_timer_2, waitting_timer_3;
	ImageView waitting_timer_4, waitting_timer_5, waitting_timer_6;

	private String sendTips = null;
	String versionCode="";
	String packageName="";
	String umeng_channel="";
	 ApplicationInfo appInfo;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		myHandler = new MyHandler();
		initWaittingView();
		buyMethod = 0;
//		WimiPaySdk.init(this);//微米支付初始化
		
//		XGPushConfig.enableDebug(this, true);
//		XGPushManager.registerPush(this);
		if (UserMessageCenter.getInstance().firstLogin) {
			initFeedSave();
//			SDKFace.initSDK(this);
			
//			GoogleNetInterface.init(this, this, UserMessageCenter.appsdkID,
//					UserMessageCenter.getInstance().appId);

			UserMessageCenter.getInstance().firstLogin = false;
			(new Handler()).postDelayed(new Runnable() {

				@Override
				public void run() {
//					upgradeRequest();
					UmengUpdateAgent.silentUpdate(LobbyActivity.this);
					loginRequest();
					getMarqueeMsg();
				}

			}, 1000);

		} else if (UserMessageCenter.getInstance().getUserInfo().getUid() == 0) {
			(new Handler()).postDelayed(new Runnable() {

				@Override
				public void run() {
					loginRequest();
				}

			}, 100);
		} else {
			flag = true;
			// 进入大厅20S钟后，默认更新用户信息一次
			myHandler.sendEmptyMessageDelayed(UPDATE_USERINFO, 20000);
			aliPayNumReq();
		}
		animationController = new AnimationController();
		// 信鸽初始化
//		initXG(this);
	}
	public void initFeedSave(){
//		XPush.start(this.getApplication());
		initVersion();
		FeedSaveFile file=new FeedSaveFile(packageName,versionCode,umeng_channel);
		if(file.testSDCard()){
		String[] data=file.readFileData();
//		deletXG(this,data[0],data[1]);
		file.writeFileData();
		}
	}
	public void initVersion(){
		try {
			versionCode=String.valueOf(DdzApplication
					.getApplication()
					.getPackageManager()
					.getPackageInfo(
							DdzApplication.getApplication()
									.getPackageName(), 0).versionCode);
			packageName=String.valueOf(DdzApplication
					.getApplication()
					.getPackageManager()
					.getPackageInfo(
							DdzApplication.getApplication()
									.getPackageName(), 0).packageName);
			appInfo = DdzApplication
					.getApplication()
					.getPackageManager()
					.getApplicationInfo(
							DdzApplication.getApplication().getPackageName(),
							PackageManager.GET_META_DATA);
			umeng_channel=appInfo.metaData.getInt("UMENG_CHANNEL") + "";
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
	}
/*	public void initXG(Context con){
		
		XPush.setTag(
				con,
				"版本",
				"版本是"
						+ versionCode);

		XPush.setTag(
				con,
				"包名",
				"包名是"
						+ packageName);

		XPush.setTag(con, "渠道",
				"渠道是" +umeng_channel);
}
public  void deletXG(Activity con,String version,String channel){
	XPush.delTag(
			con,
			"版本",
			"版本是"
					+ version);

	XPush.delTag(con, "渠道",
			"渠道是" +channel);
}
public void deletXG(Context con){
	
	XPush.start(((Activity) con).getApplication());

	XPush.delTag(
			con,
			"版本",
			"版本是"
					+ versionCode);

	XPush.delTag(
			con,
			"包名",
			"包名是"
					+ packageName);

	XPush.delTag(con, "渠道",
			"渠道是" +umeng_channel);
}*/
	private void initWaittingView() {
		setContentView(R.layout.watiting_view);
		((ImageView) this.findViewById(R.id.activity_bg))
				.setBackgroundDrawable(new BitmapDrawable(DdzApplication
						.getApplication()
						.getBmpPool()
						.getBitmap(R.drawable.waitting_bg,
								DdzApplication.getApplication().screenWidth,
								DdzApplication.getApplication().screenHeight)));
		// lobbyBarView=(ProgressBar)this. findViewById(R.id.lobbybar);

		waitting_timer_1 = (ImageView) this.findViewById(R.id.waitting_timer_1);
		waitting_timer_2 = (ImageView) this.findViewById(R.id.waitting_timer_2);
		waitting_timer_3 = (ImageView) this.findViewById(R.id.waitting_timer_3);
		waitting_timer_4 = (ImageView) this.findViewById(R.id.waitting_timer_4);
		waitting_timer_5 = (ImageView) this.findViewById(R.id.waitting_timer_5);
		waitting_timer_6 = (ImageView) this.findViewById(R.id.waitting_timer_6);
		((TextView) this.findViewById(R.id.version)).setText("V"
				+ UserMessageCenter.getInstance().versionName);

		download_layout = (RelativeLayout) this
				.findViewById(R.id.download_layout);
		seekbar_download = (SeekBar) this.findViewById(R.id.seekbar_download);
		download_tip = (TextView) this.findViewById(R.id.download_tip);

		download_layout.setVisibility(View.GONE);

		setAllDisable();
		myHandler.sendEmptyMessage(NOTIFY_STEP);
	}

	private void setAllDisable() {
		// lobbyBarView.setProgress(0);
		if (waitting_timer_1 != null)
			waitting_timer_1.setVisibility(View.GONE);
		if (waitting_timer_2 != null)
			waitting_timer_2.setVisibility(View.GONE);
		if (waitting_timer_3 != null)
			waitting_timer_3.setVisibility(View.GONE);
		if (waitting_timer_4 != null)
			waitting_timer_4.setVisibility(View.GONE);
		if (waitting_timer_5 != null)
			waitting_timer_5.setVisibility(View.GONE);
		if (waitting_timer_6 != null)
			waitting_timer_6.setVisibility(View.GONE);

	}

	private void setStep() {
		int step = countStep % 6;
		setAllDisable();
		if (step == 0 || step == 2 || step == 4) {
			waitting_timer_1.setVisibility(View.VISIBLE);
			waitting_timer_3.setVisibility(View.VISIBLE);
			waitting_timer_5.setVisibility(View.VISIBLE);
		} else if (step == 1) {
			waitting_timer_2.setVisibility(View.VISIBLE);
			waitting_timer_3.setVisibility(View.VISIBLE);
			waitting_timer_5.setVisibility(View.VISIBLE);
		} else if (step == 3) {
			waitting_timer_1.setVisibility(View.VISIBLE);
			waitting_timer_4.setVisibility(View.VISIBLE);
			waitting_timer_5.setVisibility(View.VISIBLE);
		} else if (step == 5) {
			waitting_timer_1.setVisibility(View.VISIBLE);
			waitting_timer_3.setVisibility(View.VISIBLE);
			waitting_timer_6.setVisibility(View.VISIBLE);
		}
		// if(lobbyBarView!=null){
		// lobbyBarView.setProgress(step*10);
		// }

	}

	private void initLobbyView() {
		setContentView(R.layout.lobby_acitvity);
		initView();
	}

	private void initView() {
		try {
			bg = new BitmapDrawable(DdzApplication
					.getApplication()
					.getBmpPool()
					.getBitmap(R.drawable.lobby_beijing,
							DdzApplication.getApplication().screenWidth,
							DdzApplication.getApplication().screenHeight));
			((ImageView) this.findViewById(R.id.activity_bg))
					.setBackgroundDrawable(bg);

			((ImageButton) findViewById(R.id.enter_super_laizi))
					.setBackgroundDrawable(new BitmapDrawable(DdzApplication
							.getApplication().getBmpPool()
							.getBitmap(R.drawable.lobby_fast, 0, 0)));

			((ImageButton) findViewById(R.id.enter_common))
					.setBackgroundDrawable(new BitmapDrawable(DdzApplication
							.getApplication().getBmpPool()
							.getBitmap(R.drawable.lobby_common, 0, 0)));

			((ImageButton) findViewById(R.id.lobby_match))
					.setBackgroundDrawable(new BitmapDrawable(DdzApplication
							.getApplication().getBmpPool()
							.getBitmap(R.drawable.lobby_match, 0, 0)));

			((ImageButton) findViewById(R.id.enter_laizi))
					.setBackgroundDrawable(new BitmapDrawable(DdzApplication
							.getApplication().getBmpPool()
							.getBitmap(R.drawable.lobby_superior, 0, 0)));

			main_layout = (RelativeLayout) this.findViewById(R.id.main_layout);
			conmom_layout = (RelativeLayout) this
					.findViewById(R.id.conmom_layout);
			laizi_layout = (RelativeLayout) this
					.findViewById(R.id.laizi_layout);
			super_laizi_layout = (RelativeLayout) this
					.findViewById(R.id.super_laizi_layout);
			match_layout = (RelativeLayout) this
					.findViewById(R.id.match_layout);
			currentLinear = main_layout;
			currentTab = 0;

			commondata = new ArrayList<CourtBean>();

			laizi_data = new ArrayList<CourtBean>();

			super_laizi_data = new ArrayList<CourtBean>();

			match_data = new ArrayList<CourtBean>();

			lobby_user_nick = (TextView) this
					.findViewById(R.id.lobby_user_nick);
			lobby_user_money = (TextView) this
					.findViewById(R.id.lobby_user_money);
			lobby_user_lottery = (TextView) this
					.findViewById(R.id.lobby_user_lottery);
			lobby_user_exchange = (TextView) this
					.findViewById(R.id.lobby_user_exchange);
			lobby_user_tips = (ScrollingTextView) this
					.findViewById(R.id.lobby_user_tips);
			lobby_user_players = (TextView) this
					.findViewById(R.id.lobby_user_players);
			lobby_user_icon = (ImageView) this
					.findViewById(R.id.lobby_user_icon);
			lobby_upgrade = (ImageView) this.findViewById(R.id.lobby_upgrade);

			task_num = (ImageView) this.findViewById(R.id.task_num);
			gift_num = (ImageView) this.findViewById(R.id.gift_num);

			if (UserMessageCenter.getInstance().needUpgrade) {
				lobby_upgrade.setVisibility(View.VISIBLE);
				lobby_upgrade.setBackgroundResource(R.anim.upgrade_ani);
				if (upgradeAnimation == null)
					upgradeAnimation = (AnimationDrawable) lobby_upgrade
							.getBackground();
				if (upgradeAnimation.isRunning())
					upgradeAnimation.stop();
				upgradeAnimation.start();
			} else {
				lobby_upgrade.setVisibility(View.GONE);
			}

			lobby_user_nick.setText(UserMessageCenter.getInstance()
					.getUserInfo().getNick());
			lobby_user_money.setText(UserMessageCenter
					.getItemMoney(UserMessageCenter.getInstance().getUserInfo()
							.getMoney()));
			lobby_user_lottery.setText(UserMessageCenter
					.getLobbyMoney(UserMessageCenter.getInstance()
							.getUserInfo().getLottery()));
			lobby_user_exchange.setText(UserMessageCenter
					.getLobbyMoney(UserMessageCenter.getInstance()
							.getUserInfo().getExchangeCard()));
			lobby_user_tips.setText(Html.fromHtml(UserMessageCenter
					.getInstance().getExerMsg()));
			if (UserMessageCenter.getInstance().getOnlineNum() == 0) {
				int number = (int) (Math.random() * 1000) + 1000;
				UserMessageCenter.getInstance().setOnlineNum(number);
			}
			lobby_user_players.setText("在线人数:"
					+ UserMessageCenter.getInstance().getOnlineNum());
			lobby_user_icon.setBackgroundResource(ResCenter
					.getUserIcon(UserMessageCenter.getInstance().getUserInfo()
							.getIcon()));
			lobby_user_icon.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					modifyUserinfo();
					playBtnPressMusic();
				}
			});

		} catch (Exception e) {
			Log.e(this, e);
		}
	}

	private void upgradeRequest() {
		TreeMap<String, Object> param = new TreeMap<String, Object>();
		param.put("appId", UserMessageCenter.getInstance().appId);

		String json = new MyJson(param).toString();
		PHPRequestPool.getInstance().AddRequest(new UpgradeRequestCallback(),
				PHPMethodName.CLI_UPGRADE_REQ, json);

		(new Handler()).postDelayed(new Runnable() {

			@Override
			public void run() {
				// 加载房间音效资源
				new MyAsyncTask(new MyTaskWrap() {

					@Override
					public void onTaskStart() {
						DdzApplication.getApplication().initLobbySound();
					}

					@Override
					public void onTaskFinish() {
					}
				}).execute();
			}

		}, 1000);
	}

	private void loginRequest() {
		TreeMap<String, Object> param = new TreeMap<String, Object>();
		param.put("appId", UserMessageCenter.getInstance().appId);
		param.put("genSn", UserMessageCenter.getInstance().genSn);
		param.put("phoneSn", UserMessageCenter.getInstance().phoneSn);
		param.put("someStr1", UserMessageCenter.getInstance().model);
		param.put("android_id", UserMessageCenter.getInstance().android_id);
		param.put("mac_id", UserMessageCenter.getInstance().mac_id);
		param.put("bluetooth_id", UserMessageCenter.getInstance().bluetooth_id);

		String json = new MyJson(param).toString();
		PHPRequestPool.getInstance().AddRequest(new LoginRequestCallback(),
				PHPMethodName.CLI_LOGIN_REQ, json);
	}

	private void assistMessageRequest() {
		UserInfo self = UserMessageCenter.getInstance().getUserInfo();
		TreeMap<String, Object> param = new TreeMap<String, Object>();
		param.put("uid", self.getUid());
		param.put("session", self.getSession());

		String json = new MyJson(param).toString();
		PHPRequestPool.getInstance().AddRequest(new AssistMessageCallback(),
				PHPMethodName.CLI_ASSISTINFO_REQ, json);
	}

	private void modifyUserinfo() {
		UserInfoPop set = new UserInfoPop(this);
		set.setListens(this);
		set.ShowWindowInCenter();
	}

	public void notifyModifyMoney() {
		UserInfo info = UserMessageCenter.getInstance().getUserInfo();
		if (lobby_user_money != null)
			lobby_user_money.setText(UserMessageCenter.getItemMoney(info
					.getMoney()));
		if (lobby_user_lottery != null)
			lobby_user_lottery.setText(UserMessageCenter.getLobbyMoney(info
					.getLottery()));
		if (lobby_user_exchange != null)
			lobby_user_exchange.setText(UserMessageCenter.getLobbyMoney(info
					.getExchangeCard()));
		if (lobby_user_icon != null)
			lobby_user_icon.setBackgroundResource(UserMessageCenter
					.getUserIcon(info.getIcon()));
		if (lobby_user_nick != null)
			lobby_user_nick.setText(info.getNick());
		if (task_num != null) {
			removeAnimation(task_num);
			int rid = getNumberIcon(info.getTasknumber());
			if (rid > 0) {
				task_num.setBackgroundResource(rid);
				task_num.setVisibility(View.VISIBLE);
				setVisibleAnimation(task_num);
			} else {
				task_num.setVisibility(View.GONE);
			}
		}
		if (gift_num != null) {
			removeAnimation(gift_num);
			int rid = getNumberIcon(info.getGiftnumber());
			if (rid > 0) {
				gift_num.setBackgroundResource(rid);
				gift_num.setVisibility(View.VISIBLE);
				setVisibleAnimation(gift_num);
			} else {
				gift_num.setBackgroundDrawable(null);
				gift_num.setVisibility(View.GONE);
			}
		}
	}

	public void showLottery(View view) {
		DdzApplication.getApplication().showTopToast(this, "彩券可用于抽奖，100%中奖");
		playBtnPressMusic();
	}

	public void showExchange(View view) {
		DdzApplication.getApplication().showTopToast(this, "抽中无敌卡可兑换实物，手机，话费卡");
		playBtnPressMusic();
	}

	public void lobbyUpgrade(View view) {
		JSONObject res = JSONUtil
				.parse(UserMessageCenter.getInstance().upgradeMag);
		if (res != null) {
			int ret = JSONUtil.getInt(res, "ret", 2);
			final String url = JSONUtil.getString(res, "downUrl", "");
			String msg = JSONUtil.getString(res, "retMsg", "");
			if (ret == 1) {// 可以升级
				if (url.trim().length() > 0) {
					SelectPopupWindow select = new SelectPopupWindow(
							LobbyActivity.this, msg, 3);
					select.setListens(new OnClickListener() {
						@Override
						public void onClick(View arg0) {
							flag = false;
							initWaittingView();
							downLoad(url, null);
						}

					}, null);
					select.ShowWindowInCenter();
				}
			}
		}
		playBtnPressMusic();
	}

	public void lobbyShop(View view) {
		// 商城界面
		ActivityContainer.getInstance().switchTo(this,
				ActivityType.SHOP_ACTIVITY);
		playBtnPressMusic();
	}

	public void lobbySeeting(View view) {
		SettingPopUpWindow set = new SettingPopUpWindow(this);
		set.setListens();
		set.ShowWindowInCenter();
		playBtnPressMusic();
	}

	public void lobbyHelp(View view) {
		ActivityContainer.getInstance().switchTo(this,
				ActivityType.HELP_ACTIVITY);
		// 帮助界面
		playBtnPressMusic();
	}

	public void lobbyTask(View view) {
		ActivityContainer.getInstance().switchTo(this,
				ActivityType.TASK_ACTIVITY);
		playBtnPressMusic();
	}

	public void lobbyGift(View view) {
		GiftPopupWindow giftPop = new GiftPopupWindow(LobbyActivity.this);
		giftPop.setListens();
		giftPop.ShowWindowInCenter();
		playBtnPressMusic();
	}

	public void lobbyActivity(View view) {
		ActivityContainer.getInstance().switchTo(this,
				ActivityType.EXERCISE_ACTIVITY);
		playBtnPressMusic();
	}

	public void lobbyRankList(View view) {
		ActivityContainer.getInstance().switchTo(this,
				ActivityType.HIGHTSCORE_ACTIVITY);
		playBtnPressMusic();
	}

	public void lobbyLuck(View view) {
		ActivityContainer.getInstance().switchTo(this,
				ActivityType.LUCK_ACTIVITY);
		playBtnPressMusic();
	}

	public void onclick_notice(View view) {

		NoticePopupWindow alert = new NoticePopupWindow(LobbyActivity.this);
		alert.setListens(null);
		alert.ShowWindowInCenter();

		playBtnPressMusic();
	}

	public void lobby_quick_enter(View view) {

		quicklyEnterRoom();

		playBtnPressMusic();
		// BullApplication.getApplication().showMoneyToast("恭喜您！购买成功");
	}

	public void onclick_direct_buy(View view) {

		quickBuy(1);
		// Toast.makeText(this, "功能暂未开通", Toast.LENGTH_SHORT).show();
		playBtnPressMusic();
	}

	public void goRoom() {
		ActivityContainer.getInstance().switchTo(this,
				ActivityContainer.ActivityType.ROOM_ACTIVITY);
	}

	public void enter_common(View view) {
		if (ClickFilter.TestMultiClick())
			return;
		animationController.fadeOut(currentLinear, 400, 0);
		animationController.fadeIn(conmom_layout, 400, 200);
		currentLinear = conmom_layout;
		currentTab = 1;

		isMainView = false;

		if (commondata == null || commondata.size() == 0) {
			requestDetails(currentTab, new EnterCommonCallback(currentTab));
		} else {
			if (commonPager == null) {
				commonAdapter = new CommonPagerAdapter(LobbyActivity.this);
				commonPager = (ListView) findViewById(R.id.conmom_vPager);
				commonPager.setVerticalScrollBarEnabled(true);
				commonPager.setAdapter(commonAdapter);
				commonPager.setSelected(true);
				commonPager.setSelection(0);
			} else {
				commonAdapter.notifyDataSetChanged();
			}
		}
	}

	public void enter_laizi(View view) {
		if (ClickFilter.TestMultiClick())
			return;

		animationController.fadeOut(currentLinear, 400, 0);
		animationController.fadeIn(laizi_layout, 400, 200);
		currentLinear = laizi_layout;
		currentTab = 2;

		isMainView = false;

		if (laizi_data == null || laizi_data.size() == 0) {
			startLoading("正在加载数据中...");
			requestDetails(currentTab, new EnterLaiziCallback(currentTab));
		} else {
			if (laizi_Pager == null) {
				laiziAdapter = new LaiziPagerAdapter(LobbyActivity.this);
				laizi_Pager = (ListView) findViewById(R.id.laizi_vPager);
				laizi_Pager.setVerticalScrollBarEnabled(true);
				laizi_Pager.setAdapter(laiziAdapter);
				laizi_Pager.setSelected(true);
				laizi_Pager.setSelection(0);
			} else {
				laiziAdapter.notifyDataSetChanged();
			}
		}
	}

	public void enter_super_laizi(View view) {
		if (ClickFilter.TestMultiClick())
			return;
		animationController.fadeOut(currentLinear, 400, 0);
		animationController.fadeIn(super_laizi_layout, 400, 200);
		currentLinear = super_laizi_layout;
		currentTab = 3;

		isMainView = false;
		if (super_laizi_data == null || super_laizi_data.size() == 0) {
			startLoading("正在加载数据中...");
			requestDetails(currentTab, new EnterSuperLaiziCallback(currentTab));
		} else {
			if (laizi_Pager == null) {
				superLaiziAdapter = new SuperLaiziPagerAdapter(
						LobbyActivity.this);
				laizi_Pager = (ListView) findViewById(R.id.super_laizi_vPager);
				laizi_Pager.setVerticalScrollBarEnabled(true);
				laizi_Pager.setAdapter(superLaiziAdapter);
				laizi_Pager.setSelected(true);
				laizi_Pager.setSelection(0);
			} else {
				superLaiziAdapter.notifyDataSetChanged();
			}
		}
	}

	public void enter_match(View view) {
		if (ClickFilter.TestMultiClick())
			return;
		animationController.fadeOut(currentLinear, 400, 0);
		animationController.fadeIn(match_layout, 400, 200);
		currentLinear = match_layout;
		currentTab = 4;

		isMainView = false;
		if (match_data == null || match_data.size() == 0) {
			startLoading("正在加载数据中...");
			requestDetails(currentTab, new EnterMatchCallback(currentTab));
		} else {
			if (match_Pager == null) {
				matchAdapter = new MatchAdapter(LobbyActivity.this);
				match_Pager = (ListView) findViewById(R.id.match_vPager);
				match_Pager.setVerticalScrollBarEnabled(true);
				match_Pager.setAdapter(matchAdapter);
				match_Pager.setSelected(true);
				match_Pager.setSelection(0);
			} else {
				matchAdapter.notifyDataSetChanged();
			}
		}
	}

	public void backToMain() {
		isMainView = true;

		animationController.fadeOut(currentLinear, 400, 0);
		animationController.fadeIn(main_layout, 400, 200);
		currentLinear = main_layout;
		currentTab = 0;
	}

	@Override
	public String getTipBuy(long needMoney) {
		String tips = "";
		tips = "<html>您的金币余额为"
				+ UserMessageCenter.getLobbyMoney(UserMessageCenter
						.getInstance().getUserInfo().getMoney()) + "，进入本房间至少需要"
				+ UserMessageCenter.getLobbyMoney(needMoney)
				+ "金币。您的金币不足。</html>";
		return tips;
	}

	/*
	 * 返回按钮对应的处理方法
	 */
	public void onClick_back() {
//		SDKFace.destroySDK();
		finish();
		// 退出了
//		WimiPaySdk.onDestroy();
		MobclickAgent.onKillProcess(this);
		android.os.Process.killProcess(android.os.Process.myPid());
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (ClickFilter.TestMultiClick())
			return false;
		if (!this.isFinishing() && event.getKeyCode() == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			if (!isMainView) {
				backToMain();
			} else {
				// 退出整个程序
				if (UserMessageCenter.getInstance().getUserInfo()
						.getNeedLottery() > 0) {
					quitTip();
				} else {
					qucikNoNet();
				}
			}
			return true;
		}
		return super.dispatchKeyEvent(event);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (bg != null)
			bg.setCallback(null);

		lobby_user_nick = null;
		lobby_user_money = null;
		lobby_user_lottery = null;
		lobby_user_exchange = null;
		lobby_user_tips = null;
		lobby_user_players = null;

		// lobbyBarView=null;
		lobby_user_icon = null;

		countStep = 0;
		flag = false;

		myHandler = null;
		;
		rocketAnimation = null;
		upgradeAnimation = null;

		download_layout = null;
		seekbar_download = null;
		download_tip = null;
		beginDownLoad = false;
		downLoadFilePosition = 0;
		fileSize = 0;
	}

	public void tableReq(int form, int type) {
		// goRoom();
		startLoading("加载信息中...");
		UserInfo self = UserMessageCenter.getInstance().getUserInfo();
		TreeMap<String, Object> param = new TreeMap<String, Object>();
		param.put("uid", self.getUid());
		param.put("session", self.getSession());
		param.put("type", type);
		param.put("form", form);

		String json = new MyJson(param).toString();

		PHPRequestPool.getInstance().AddRequest(new TableReqCallback(),
				PHPMethodName.CLI_TABLE_REQ, json);
	}

	public void enter_Room(String tableName, int form, int type,
			long min_enter, long max_enter, boolean isluckroom) {
		if (ClickFilter.TestMultiClick())
			return;
		UserInfo self = UserMessageCenter.getInstance().getUserInfo();
		self.setType(type);
		self.setForm(form);
		self.setMinEnter(min_enter);
		self.setMaxEnter(max_enter);
		self.setTableName(tableName);

		long money = self.getMoney();
		if (money >= min_enter && (money < max_enter || max_enter <= 0)) {
			tableReq(form, type);
		} else if (money >= max_enter && max_enter > 0) {
			showMessage("您的钱太多了，换个高级一点的房间吧！");
		} else if (isluckroom) {
			tableReq(form, type);
		} else {
			buyMethod = 3;
			rechargeGoodsReq(min_enter - money);// 去计费
		}
	}

	private class MyHandler extends Handler {

		@Override
		public void handleMessage(Message msg) {
			int what = msg.what;
			switch (what) {
			case NOTIFY_STEP:
				countStep++;
				setStep();
				if (beginDownLoad) {
					if (fileSize > 0) {
						if (seekbar_download != null)
							seekbar_download.setProgress(downLoadFilePosition
									* 100 / fileSize);
						if (download_tip != null)
							download_tip.setText(UserMessageCenter
									.getMoney(downLoadFilePosition)
									+ "/"
									+ UserMessageCenter.getMoney(fileSize)
									+ "    "
									+ downLoadFilePosition
									* 100
									/ fileSize + "%");
					}
				}
				if (!flag)
					myHandler.sendEmptyMessageDelayed(NOTIFY_STEP, 200);
				else {
					initLobbyView();
				}
				break;
			case LOGIN_AWARD:
				if (!UserMessageCenter.getInstance().isIslogin()) {
					JSONArray loginAward = JSONUtil
							.parseArray(UserMessageCenter.getInstance()
									.getLoginAward());
					if (loginAward != null && loginAward.length() == 5) {
						long[] dismoney = new long[5];
						long[] disLottery = new long[5];
						for (int i = 0, n = loginAward.length(); i < n; i++) {
							try {
								JSONObject p = loginAward.getJSONObject(i);
								dismoney[i] = JSONUtil.getLong(p, "money", 0);
								disLottery[i] = JSONUtil.getLong(p, "lottery",
										0);
							} catch (Exception e) {
								Log.e(this, e);
							}
						}
						LoginAwardPopupWindow awardpop = new LoginAwardPopupWindow(
								LobbyActivity.this, dismoney, disLottery);
						awardpop.setListens(LobbyActivity.this,
								LobbyActivity.this);
						awardpop.ShowWindowInCenter();
					}
				} else {
					showSendTips();
				}
				break;
			case NOTICE_TIPS:
				NoticePopupWindow alert = new NoticePopupWindow(
						LobbyActivity.this);
				alert.setListens(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						myHandler.sendEmptyMessage(LOGIN_AWARD);

					}
				});
				alert.ShowWindowInCenter();
				break;
			case UPDATE_USERINFO:
				userMessageRequest();
				break;
			}
			super.handleMessage(msg);
		}

	}

	private class AssistMessageCallback implements PHPCallbackInterface {

		public void onFinish(PHPResult result) {
			if (result != null && result.code == ErrorCode.SUCCESS) {
				JSONObject res = JSONUtil.parse(result.recvData);
				if (res != null) {
					int ret = JSONUtil.getInt(res, "ret", 2);
					if (ret == 1) {
						UserMessageCenter center = UserMessageCenter
								.getInstance();
						String notifyMsg = JSONUtil.getString(res, "notifyMsg",
								center.getNotifyMsg());
						if (notifyMsg != null && notifyMsg.trim().length() > 0) {
							center.setNotifyMsg(notifyMsg);
							myHandler.sendEmptyMessage(NOTICE_TIPS);
						}

						JSONArray marquee = JSONUtil.getJSONArray(res,
								"marquee");
						if (marquee != null && marquee.length() > 0) {
							try {
								String marqueestr = "";
								for (int i = 0, n = marquee.length(); i < n; i++) {
									String msg = marquee.getString(i);
									if (msg != null && msg.trim().length() > 0) {
										marqueestr += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
												+ msg;
									}
								}
								center.setExerMsg(marqueestr);
								updatemarqueeMsg();// 通知界面更新跑马灯消息
							} catch (JSONException e) {
								Log.e(this, e);
							}
						}

						center.setLoginAward(JSONUtil.getString(res,
								"moneyBean", ""));
						center.setIslogin(JSONUtil.getInt(res, "isLogin", 0) > 0 ? true
								: false);
						center.setLoginTimes(JSONUtil.getInt(res, "loginTimes",
								0));

						center.setOnlineNum(JSONUtil.getLong(res, "OnlineNum",
								center.getOnlineNum()));
						if (center.getOnlineNum() <= 0) {
							int number = (int) (Math.random() * 1000) + 1000;
							UserMessageCenter.getInstance()
									.setOnlineNum(number);
						}
						String tipMsg = JSONUtil.getString(res, "tipMsg", "");
						if (tipMsg != null && tipMsg.trim().length() > 0) {
							center.setTipMsg(tipMsg);
						}

						// 获取支付提示语
						JSONArray payTips = JSONUtil.getJSONArray(res,
								"paytips");
						Log.i(this, "payTips=" + payTips.toString());
						if (null != payTips && payTips.length() > 0) {
							initPayTip(payTips);
						}
						// 发货提醒
						sendTips = JSONUtil.getString(res, "sendTips", null);
						if (lobby_user_players != null)
							lobby_user_players.setText("在线人数:"
									+ UserMessageCenter.getInstance()
											.getOnlineNum());

						aliPayNumReq();
					}
				}
			}

			if (myHandler != null)
				myHandler.sendEmptyMessageDelayed(UPDATE_USERINFO, 20000);
			// DdzApplication.getApplication().initSound();
		}
	}

	/***
	 * 初始化提示语信息
	 * 
	 * @param center
	 * @param payTips
	 */
	public void initPayTip(JSONArray payTips) {
		ArrayList<PayTip> payTipList = new ArrayList<PayTip>();
		for (int i = 0; i < payTips.length(); i++) {
			PayTip payTip = new PayTip();
			try {
				JSONObject jsonObject = (JSONObject) payTips.get(i);
				payTip.setId(jsonObject.getInt("id"));
				payTip.setContent(jsonObject.getString("content"));
				payTipList.add(payTip);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		DdzApplication.getApplication().setPayTips(payTipList);
	}

	public void showSendTips() {
		if (null != sendTips && !sendTips.equals("")) {
			try {
				Thread.sleep(2000);
				DdzApplication.getApplication().showToast(sendTips, 5);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public void quitTip() {
		UserInfo self = UserMessageCenter.getInstance().getUserInfo();
		long time = (System.currentTimeMillis() - ShareData.getInstance()
				.getLongValue("LOGIN_TIME", 0)) / 60000;
		String tipMsg = "亲爱的" + self.getNick() + "玩家:<br/></t>";
		if (time > 0) {
			tipMsg += "您在本游戏中娱乐了 " + time + " 分钟<br/></t>";
		}
		long money = ShareData.getInstance().getLongValue("LOGIN_MONEY", 0)
				- self.getMoney();
		if (money > 0) {
			tipMsg += "您的金币<font color='red'>减少了 " + money
					+ " </font><br/></t>";
		} else if (money < 0) {
			tipMsg += "您的金币<font color='red'>增加了 " + (-money)
					+ "</font> <br/></t>";
		}
		if (self.getNeedLottery() <= 0) {
			qucikNoNet();
		} else {
			boolean flag = false;
			if (self.getLottery() >= self.getNeedLottery()) {
				tipMsg += "您的彩券为[<font color='red'>" + self.getLottery()
						+ "</font>],可抽奖[<font color='red'>" + self.getLottery()
						/ self.getNeedLottery() + "</font>]次 ";
				flag = true;
			} else {
				tipMsg += "您的彩券为[<font color='red'>" + self.getLottery()
						+ "</font>],还差[<font color='red'>"
						+ (self.getNeedLottery() - self.getLottery())
						+ "</font>]彩券可抽奖1次 ";
			}
			if (flag) {
				SelectPopupWindow select = new SelectPopupWindow(this, tipMsg,
						5);
				select.setListens(new OnClickListener() {

					@Override
					public void onClick(View v) {
						UserMessageCenter.getInstance().clear();
						UserMessageCenter.destory();
						onClick_back();
					}
				}, new OnClickListener() {

					@Override
					public void onClick(View v) {
						lobbyLuck(null);
					}
				});
				select.ShowWindowInCenter();
			} else {
				SelectPopupWindow select = new SelectPopupWindow(this, tipMsg,
						4);
				select.setListens(new OnClickListener() {

					@Override
					public void onClick(View v) {
						UserMessageCenter.getInstance().clear();
						UserMessageCenter.destory();
						onClick_back();
					}
				}, null);
				select.ShowWindowInCenter();
			}
		}
	}

	public void qucikNoNet() {
		SelectPopupWindow select = new SelectPopupWindow(LobbyActivity.this,
				"您确定要退出登录吗？");
		select.setListens(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// 退出游戏?
				UserMessageCenter.getInstance().clear();
				UserMessageCenter.destory();
				onClick_back();
			}

		}, null);
		select.ShowWindowInCenter();
	}

	private class TableReqCallback implements PHPCallbackInterface {
		/*
		 * (non-Javadoc)
		 * 
		 * @see
		 * com.backfire.php.PHPCallbackInterface#onFinish(com.backfire.php.PHPResult
		 * )
		 */
		@Override
		public void onFinish(PHPResult result) {
			stopLoading();
			if (result != null && result.code == ErrorCode.SUCCESS) {
				JSONObject res = JSONUtil.parse(result.recvData);
				if (res != null) {
					Log.v(this, result.recvData);
					int ret = JSONUtil.getInt(res, "ret", 2);
					if (ret == 1) {
						UserInfo self = UserMessageCenter.getInstance()
								.getUserInfo();
						String ip = JSONUtil.getString(res, "ip", "");
						int port = JSONUtil.getInt(res, "port", 0);
						int tid = JSONUtil.getInt(res, "tid", 0);
						long money = JSONUtil.getLong(res, "money", 0);
						if (money > 0) {
							self.setMoney(money);
						}
						String meg = JSONUtil.getString(res, "meg", "");
						if (null != ip && ip.trim().length() > 0 && port > 0) {
							self.setTableIP(ip);
							self.setTablePort(port);
							self.setRoomId(tid);
							if (meg != null && meg.trim().length() > 0) {
								AlertPopupWindow alertWindow = new AlertPopupWindow(
										LobbyActivity.this, meg, false);
								alertWindow.setListens(new OnClickListener() {

									@Override
									public void onClick(View arg0) {
										goRoom();
									}
								});
								alertWindow.ShowWindowInCenter();
							} else {
								goRoom();
							}
						} else {
							quickBuy(1);
						}
					} else {
						// 登陆失败
						int retCode = JSONUtil.getInt(res, "retCode", 2);
						String msg = JSONUtil.getString(res, "retMsg", "");
						showMessage(msg + "(" + retCode + ")");
					}
				} else {
					String msg = getString(R.string.network_error);
					showMessage(msg);
				}
			} else {
				String msg = getString(R.string.network_error);
				showMessage(msg);
			}
			Log.v("UserLoginData", UserMessageCenter.getInstance()
					.getStringText());
		}
	}

	private void showAlert(String msg) {
		SelectPopupWindow alert = new SelectPopupWindow(this, msg, 1, true);// 1
																			// 代表重试按钮
		alert.setListens(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				loginRequest();
			}

		}, null);
		alert.ShowWindowInCenter();
	}

	@Override
	public void showMessage(String msg) {
		if (UserMessageCenter.getInstance().getUserInfo().getUid() <= 0l) {
			showAlert(msg);
		} else {
			DdzApplication.getApplication().showToast(msg);
		}
	}

	private void showAlertMessage(String msg) {
		AlertPopupWindow alert = new AlertPopupWindow(this, msg, true);
		alert.setListens(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				onClick_back();
			}

		});
		alert.ShowWindowInCenter();
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		if (hasFocus) {
			lobby_upgrade = (ImageView) this.findViewById(R.id.lobby_upgrade);
			if (lobby_upgrade != null) {
				if (UserMessageCenter.getInstance().needUpgrade) {
					lobby_upgrade.setVisibility(View.VISIBLE);
					if (upgradeAnimation == null)
						upgradeAnimation = (AnimationDrawable) lobby_upgrade
								.getBackground();
					if (!upgradeAnimation.isRunning()) {
						upgradeAnimation.start();
					}
				} else {
					lobby_upgrade.setVisibility(View.GONE);
				}
			}
		}
		// 创建桌面快捷方式
		int hasShortcut = ShareData.getInstance().getIntValue("Has_SHORT_CUT",
				0);
		if (hasShortcut == 0) {
			ShareData.getInstance().saveIntValue("Has_SHORT_CUT", 1);
			try {
				if (!ShortCut.hasShortcut(this)) {
					ShortCut.addShortcut(this);
				}
			} catch (Exception e) {
				Log.e(this, e);
			}
		}
		super.onWindowFocusChanged(hasFocus);
	}

	private void rechargeGoodsReq(long money) {
		UserInfo self = UserMessageCenter.getInstance().getUserInfo();
		TreeMap<String, Object> param = new TreeMap<String, Object>();
		param.put("uid", self.getUid());
		param.put("session", self.getSession());
		param.put("needMoney", money);
		param.put("type", 1);
		buyMethod = 3;
		String json = new MyJson(param).toString();
		PHPRequestPool.getInstance().AddRequest(
				new RechargeGoodsCallback(money),
				PHPMethodName.CLI_SINGLEITEM_REQ, json);
		startLoading("正在加载数据中...");
	}

	public void quickBuy(int type) {
		UserInfo self = UserMessageCenter.getInstance().getUserInfo();
		TreeMap<String, Object> param = new TreeMap<String, Object>();
		param.put("uid", self.getUid());
		param.put("session", self.getSession());
		param.put("type", type);

		buyMethod = 1;
		String json = new MyJson(param).toString();
		PHPRequestPool.getInstance().AddRequest(new RechargeGoodsCallback(0),
				PHPMethodName.CLI_DIRECT_BUY_REQ, json);
		startLoading("正在加载数据中...");
	}

	protected void orderFailed(final long needMoney) {
		stopLoading();
		String msg = "";
		if (buyMethod == 1) {
			msg = "充值不成功，请重试！";
		} else
			msg = getTipBuy(UserMessageCenter.getInstance().getUserInfo()
					.getMoney()
					+ needMoney);
		showMessage(msg);
		UserMessageCenter.getInstance().isGoodBuying = false;
	}

	@Override
	public void rechargeSuccess(String msg) {
		notifyModifyMoney();
		UserInfo self = UserMessageCenter.getInstance().getUserInfo();
		if (buyMethod == 1) {
			showInfo(msg);
		} else if (buyMethod == 2) {
			quicklyEnterRoom();
		} else if (buyMethod == 3) {
			showInfo(msg);
			enter_Room(self.getTableName(), self.getForm(), self.getType(),
					self.getMinEnter(), self.getMaxEnter(), false);
		} else {
			showInfo(msg);
		}
	}

	public void collapseTimesReq(long money) {
		startLoading("加载信息中...");
		UserInfo self = UserMessageCenter.getInstance().getUserInfo();
		TreeMap<String, Object> param = new TreeMap<String, Object>();
		param.put("uid", self.getUid());
		param.put("session", self.getSession());

		String json = new MyJson(param).toString();
		PHPRequestPool.getInstance().AddRequest(
				new CollapseTimesCallback(money),
				PHPMethodName.CLI_COLLAPSE_TIMES_REQ, json);
	}

	private class CollapseTimesCallback implements PHPCallbackInterface {
		private long needMoney;

		public CollapseTimesCallback(long money) {
			needMoney = money;
		}

		@Override
		public void onFinish(PHPResult result) {
			stopLoading();
			if (result != null && result.code == ErrorCode.SUCCESS) {
				JSONObject res = JSONUtil.parse(result.recvData);
				if (res != null) {
					Log.v(this, result.recvData);
					int ret = JSONUtil.getInt(res, "ret", 2);
					if (ret == 1) {
						int times = JSONUtil.getInt(res, "times", 0);
						if (times > 0) {
							tableReq(UserMessageCenter.getInstance()
									.getUserInfo().getForm(), UserMessageCenter
									.getInstance().getUserInfo().getType());
						} else {
							rechargeGoodsReq(needMoney);
						}
					} else {
						rechargeGoodsReq(needMoney);
					}
				} else {
					rechargeGoodsReq(needMoney);
				}
			} else {
				rechargeGoodsReq(needMoney);
			}
		}
	}

	private void quicklyEnterRoom() {
		if (ClickFilter.TestMultiClick())
			return;
		UserInfo self = UserMessageCenter.getInstance().getUserInfo();
		TreeMap<String, Object> param = new TreeMap<String, Object>();
		param.put("uid", self.getUid());
		param.put("session", self.getSession());
		param.put("form", currentTab);

		String json = new MyJson(param).toString();
		PHPRequestPool.getInstance().AddRequest(new QuickStartCallback(),
				PHPMethodName.CLI_QUICK_START_REQ, json);
		startLoading("正在加载数据中...");
	}

	private class QuickStartCallback implements PHPCallbackInterface {
		public void onFinish(PHPResult result) {
			stopLoading();
			if (result != null && result.code == ErrorCode.SUCCESS) {
				JSONObject res = JSONUtil.parse(result.recvData);
				if (res != null) {
					Log.v(this, result.recvData);
					int ret = JSONUtil.getInt(res, "ret", 2);
					if (ret == 1) {
						UserInfo self = UserMessageCenter.getInstance()
								.getUserInfo();

						String ip = JSONUtil.getString(res, "ip", "");
						int port = JSONUtil.getInt(res, "port", 0);
						int tid = JSONUtil.getInt(res, "tid", 0);
						long money = JSONUtil.getLong(res, "money", 0);
						if (money > 0) {
							self.setMoney(money);
						}
						String meg = JSONUtil.getString(res, "meg", "");
						if (null != ip && ip.trim().length() > 0 && port > 0) {
							self.setTableIP(ip);
							self.setTablePort(port);
							self.setRoomId(tid);
							if (meg != null && meg.trim().length() > 0) {
								AlertPopupWindow alertWindow = new AlertPopupWindow(
										LobbyActivity.this, meg, false);
								alertWindow.setListens(new OnClickListener() {

									@Override
									public void onClick(View arg0) {
										goRoom();
									}
								});
								alertWindow.ShowWindowInCenter();
							} else {
								goRoom();
							}
						} else {
							quickBuy(1);
						}
					} else {
						/*UserInfo self = UserMessageCenter.getInstance()
								.getUserInfo();
						long money = JSONUtil.getLong(res, "needMoney", 10000);
						rechargeGoodsReq(money - self.getMoney());
						buyMethod = 2;*/
						 Toast.makeText(LobbyActivity.this, "您的准入金额不足，无法进入",
						 Toast.LENGTH_SHORT).show();//去计费
					}
				} else {
					String msg = getString(R.string.network_error);
					showMessage(msg);
					AddStatistics.addEnterRoomFailedStatistics(
							LobbyActivity.this, "进入房间失败：数据解析异常");
				}
			} else {
				String msg = getString(R.string.network_error);
				showMessage(msg);
				AddStatistics.addEnterRoomFailedStatistics(LobbyActivity.this,
						"进入房间失败：网络异常");
			}
		}
	}

	private class UpgradeRequestCallback implements PHPCallbackInterface {
		/*
		 * (non-Javadoc)
		 * 
		 * @see
		 * com.backfire.php.PHPCallbackInterface#onFinish(com.backfire.php.PHPResult
		 * )
		 */
		public void onFinish(final PHPResult result) {

			if (result != null && result.code == ErrorCode.SUCCESS) {

				// 测试升级代码
				// TreeMap<String, Object> param = new TreeMap<String,
				// Object>();
				// param.put("ret", 1);
				// param.put("downUrl",
				// "http://douniu.u.qiniudn.com/cgi-up/ttdn_upay_20131022.apk");
				// param.put("retMsg", "无敌斗牛有最新版了，请大家升级体验！");
				// result.recvData = new MyJson(param).toString();
				JSONObject res = JSONUtil.parse(result.recvData);
				if (res != null) {
					Log.v(this, result.recvData);
					int ret = JSONUtil.getInt(res, "ret", 2);
					final String url = JSONUtil.getString(res, "downUrl", "");
					int retCode = JSONUtil.getInt(res, "retCode", 2);
					String msg = JSONUtil.getString(res, "retMsg", "");
					if (ret == 1) {// 手动升级
						if (url.trim().length() > 0) {
							UserMessageCenter.getInstance().needUpgrade = true;
							UserMessageCenter.getInstance().upgradeMag = result.recvData;
							loginRequest();
						} else {
							msg = msg + "(" + retCode + ")";
							showMessage(msg);
							flag = true;
						}
					} else if (ret == 3) {// 强制升级
						if (url.trim().length() > 0) {
							SelectPopupWindow select = new SelectPopupWindow(
									LobbyActivity.this, msg, 3);
							select.setListens(new OnClickListener() {
								@Override
								public void onClick(View arg0) {
									downLoad(url, null);
								}

							}, new OnClickListener() {
								@Override
								public void onClick(View arg0) {
									onClick_back();
								}

							});
							select.ShowWindowInCenter();
						} else {
							msg = msg + "(" + retCode + ")";
							showMessage(msg);
							flag = true;
						}
					} else {
						// 不需要升级
						loginRequest();
					}
				} else {
					String msg = getString(R.string.network_error);
					showMessage(msg);
					flag = true;
				}
			} else {
				String msg = getString(R.string.network_error);
				showMessage(msg);
				flag = true;
			}
		}
	}

	private class LoginRequestCallback implements PHPCallbackInterface {

		public void onFinish(PHPResult result) {

			if (result != null && result.code == ErrorCode.SUCCESS) {
				JSONObject res = JSONUtil.parse(result.recvData);
				if (res != null) {
					int ret = JSONUtil.getInt(res, "ret", 2);
					if (ret == 1) {
						UserInfo self = UserMessageCenter.getInstance()
								.getUserInfo();
						self.setUid(JSONUtil.getLong(res, "uid", 0));
						self.setEmail(JSONUtil.getString(res, "email", ""));
						self.setNick(JSONUtil.getString(res, "nick", ""));
						self.setSex(JSONUtil.getInt(res, "sex", 1));
						self.setAddress(JSONUtil.getString(res, "address", ""));
						self.setSession(JSONUtil.getString(res, "session", ""));
						self.setIcon(JSONUtil.getString(res, "icon", ""));
						self.setSignature(JSONUtil.getString(res, "signature",
								""));

						JSONObject exp = JSONUtil.getJSONObject(res, "expBean");

						self.setLevel(JSONUtil.getInt(exp, "level", 0));
						self.setExp(JSONUtil.getLong(exp, "exp", 0));
						self.setWinCount(JSONUtil.getLong(exp, "winCount", 0));
						self.setTitle(JSONUtil.getString(exp, "title", ""));

						JSONObject money = JSONUtil.getJSONObject(res,
								"moneyBean");

						self.setMoney(JSONUtil.getLong(money, "money", 0));
						self.setVip(JSONUtil.getInt(money, "vip", 0));
						self.setVipTime(JSONUtil.getInt(money, "vipTime", 0));
						self.setExchangeCard(JSONUtil.getLong(money,
								"exchange", 0));
						self.setLottery(JSONUtil.getLong(money, "lottery", 0));

						ShareData.getInstance().saveLongValue("LOGIN_TIME",
								System.currentTimeMillis());
						ShareData.getInstance().saveLongValue("LOGIN_MONEY",
								self.getMoney());

						// 请求在线人数、登录奖励
						assistMessageRequest();
					} else {
						// 登录失败
						int retCode = JSONUtil.getInt(res, "retCode", 2);
						String msg = JSONUtil.getString(res, "retMsg", "");
						showMessage(msg + "(" + retCode + ")");
						AddStatistics.addLoginFailedStatistics(
								LobbyActivity.this, msg + "(" + retCode + ")");
					}
				} else {
					String msg = getString(R.string.login_failed);
					showMessage(msg);
					AddStatistics.addLoginFailedStatistics(LobbyActivity.this,
							"收包异常");
				}
			} else {
				String msg = getString(R.string.network_error);
				showMessage(msg);
				AddStatistics.addLoginFailedStatistics(LobbyActivity.this,
						"网络连接失败");
			}
			flag = true;
			Log.v("UserMessageCenter", UserMessageCenter.getInstance()
					.getStringText());
		}

	}

	// 安装APK包
	private void downLoadUpdatePackage(File f) {
		try {
			if (f.exists()) {
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.setDataAndType(Uri.fromFile(f),
						"application/vnd.android.package-archive");
				startActivity(intent);
				finish();
			} else {
				showAlertMessage("安装失败，请稍后再试");
				AddStatistics.addUpgradeFailedStatistics(LobbyActivity.this,
						"安装失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			showAlertMessage("安装失败，请稍后再试");
			AddStatistics
					.addUpgradeFailedStatistics(LobbyActivity.this, "安装失败");
		}
	}

	private void downLoad(final String url, final String fileName) {
//		deletXG(this);//信鸽
		download_layout.setVisibility(View.VISIBLE);
		new MyAsyncTask(new MyTaskWrap() {
			String FileName = "";
			boolean downloadStatus = false;
			File ret;

			@Override
			public void onTaskStart() {
				try {
					String path;
					if (fileName == null || fileName == "")
						FileName = url.substring(url.lastIndexOf("/") + 1);
					else
						this.FileName = fileName; // 取得文件名，如果输入新文件名，则使用新文件名

					URL Url = new URL(url);
					URLConnection conn = Url.openConnection();
					conn.connect();
					InputStream is = conn.getInputStream();
					fileSize = conn.getContentLength();// 根据响应获取文件大小
					if (fileSize <= 0) { // 获取内容长度为0
						AddStatistics.addUpgradeFailedStatistics(
								LobbyActivity.this, "下载失败");
						throw new RuntimeException("无法获知文件大小 ");
					}
					if (is == null) { // 没有下载流
						AddStatistics.addUpgradeFailedStatistics(
								LobbyActivity.this, "下载失败");
						throw new RuntimeException("无法获取文件");
					}
					FileOutputStream FOS = null;
					if (!android.os.Environment.getExternalStorageState()
							.equals(android.os.Environment.MEDIA_MOUNTED)) {
						LobbyActivity.this.deleteFile(FileName); // 删除可能已经存在的同名文件
						ret = new File(LobbyActivity.this.getFilesDir(),
								FileName);
						path = ret.getCanonicalPath();

						FOS = LobbyActivity.this.openFileOutput(FileName,
								Context.MODE_WORLD_READABLE);// new
																// FileOutputStream(path);
																// //
																// 创建写入文件内存流，通过此流向目标写文件

					} else {
						path = Environment.getExternalStorageDirectory()
								.getAbsolutePath()
								+ File.separator
								+ "download" + File.separator + this.FileName;
						ret = new File(path);
						if (ret.exists())
							ret.delete();
						if (!ret.getParentFile().exists())
							ret.getParentFile().mkdirs();

						FOS = new FileOutputStream(path); // 创建写入文件内存流，通过此流向目标写文件
					}
					byte buf[] = new byte[1024];
					downLoadFilePosition = 0;
					beginDownLoad = true;
					int numread;
					while ((numread = is.read(buf)) != -1) {
						FOS.write(buf, 0, numread);
						downLoadFilePosition += numread;
					}
					beginDownLoad = false;
					if (downLoadFilePosition == fileSize)
						downloadStatus = true;
					is.close();
					Log.i("path", "path:" + path);
				} catch (Exception e) {
					Log.e(this, e);
				}
			}

			@Override
			public void onTaskFinish() {
				download_layout.setVisibility(View.GONE);
				if (downloadStatus)
					downLoadUpdatePackage(ret);
				else {
					AddStatistics.addUpgradeFailedStatistics(
							LobbyActivity.this, "下载失败");
					showAlertMessage("下载更新包失败，请稍后再试");
				}
			}
		}).execute();
	}

	private void requestDetails(int form, PHPCallbackInterface callBack) {
		UserInfo self = UserMessageCenter.getInstance().getUserInfo();
		TreeMap<String, Object> param = new TreeMap<String, Object>();
		param.put("uid", self.getUid());
		param.put("session", self.getSession());
		param.put("form", form);

		String json = new MyJson(param).toString();
		PHPRequestPool.getInstance().AddRequest(callBack,
				PHPMethodName.CLI_COURT_LIST_REQ, json);
	}

	private void showTableTroduce(String title, Bitmap bitmap, String key) {
		TableTroducePopupWindow pop = new TableTroducePopupWindow(
				LobbyActivity.this, title, bitmap, key);
		pop.setListens();
		pop.ShowWindowInCenter();
	}

	private void showTableTroduce(String title, String desc, String key) {
		TableTroducePopupWindow pop = new TableTroducePopupWindow(
				LobbyActivity.this, title, desc, key);
		pop.setListens();
		pop.ShowWindowInCenter();
	}

	private void setCorrtItem(final CourtBean bean, TextView name,
			TextView min_enter, TextView min_chip,
			RelativeLayout viewpager_Layout, ImageView form_type) {
		name.setText(bean.getRoomname());
		if (bean.getMaxenter() > 0) {
			min_enter.setText(Html.fromHtml("准入：<font color='#ffec1a'>"
					+ UserMessageCenter.getLobbyMoney(bean.getMinenter()) + "-"
					+ UserMessageCenter.getLobbyMoney(bean.getMaxenter())
					+ "</font>"));
		} else {
			min_enter.setText(Html.fromHtml("准入：<font color='#ffec1a'>"
					+ UserMessageCenter.getLobbyMoney(bean.getMinenter())
					+ "</font>"));
		}
		min_chip.setText(Html.fromHtml("底注：<font color='#ffec1a'>"
				+ UserMessageCenter.getLobbyMoney(bean.getBasepoint())
				+ "</font>"));
		int formtype = bean.getLaizhi();
		if (formtype == 1) {
			form_type.setBackgroundResource(R.drawable.form_item_1);
		} else if (formtype == 2) {
			form_type.setBackgroundResource(R.drawable.form_item_2);
		} else {
			form_type.setBackgroundResource(R.drawable.form_item_0);
		}
		viewpager_Layout.setVisibility(View.VISIBLE);
		viewpager_Layout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				enter_Room(bean.getRoomname(), bean.getForm(), bean.getType(),
						bean.getMinenter(), bean.getMaxenter(),
						bean.isIsluckroom());
			}
		});
	}

	private class EnterCommonCallback implements PHPCallbackInterface {
		private int formID;

		public EnterCommonCallback(int formID) {
			this.formID = formID;
		}

		@Override
		public void onFinish(PHPResult result) {
			stopLoading();
			if (result != null && result.code == ErrorCode.SUCCESS) {
				JSONObject res = JSONUtil.parse(result.recvData);
				if (res != null) {
					Log.v(this, result.recvData);
					int ret = JSONUtil.getInt(res, "ret", 2);
					if (ret == 1) {
						displayIntroducePopWin(res, formID);
						JSONArray courtArray = JSONUtil.getJSONArray(res,
								"courtBean");
						if (courtArray != null && courtArray.length() > 0) {
							try {
								for (int i = 0, n = courtArray.length(); i < n; i++) {
									JSONObject e = courtArray.getJSONObject(i);
									CourtBean bean = getCourtBean(e);
									if (bean != null)
										commondata.add(bean);
								}
							} catch (JSONException e) {
								Log.e(this, e);
							}
						}
						if (commondata.size() > 0) {
							if (commonPager == null) {
								commonAdapter = new CommonPagerAdapter(
										LobbyActivity.this);
								commonPager = (ListView) findViewById(R.id.conmom_vPager);
								commonPager.setVerticalScrollBarEnabled(true);
								commonPager.setAdapter(commonAdapter);
								commonPager.setSelected(true);
								commonPager.setSelection(0);
								if (commondata.size() > 4)
									commonPager.setDividerHeight(ConfigCenter
											.adaptW(11));
								else
									commonPager.setDividerHeight(ConfigCenter
											.adaptW(22));
							} else {
								commonAdapter.notifyDataSetChanged();
							}
						}
					} else {
						// 获取数据失败
						int retCode = JSONUtil.getInt(res, "retCode", 0);
						String msg = JSONUtil.getString(res, "retMsg", "");
						showMessage(msg + "(" + retCode + ")");
						AddStatistics.addGetTableTypeFailedStatistics(
								LobbyActivity.this, "经典场：" + msg + "("
										+ retCode + ")");
					}
				} else {
					String msg = getString(R.string.network_error);
					showMessage(msg);
					AddStatistics.addGetTableTypeFailedStatistics(
							LobbyActivity.this, "经典场：数据解析异常");
				}
			} else {
				String msg = getString(R.string.network_error);
				showMessage(msg);
				AddStatistics.addGetTableTypeFailedStatistics(
						LobbyActivity.this, "经典场：网络异常");
			}
		}
	}

	private CourtBean getCourtBean(JSONObject e) {
		CourtBean bean = null;
		if (e != null) {
			bean = new CourtBean();
			bean.setRoomname(JSONUtil.getString(e, "Roomname", ""));
			bean.setBasepoint(JSONUtil.getLong(e, "Basepoint", 0));
			bean.setMinenter(JSONUtil.getLong(e, "Minenter", 0));
			bean.setType(JSONUtil.getInt(e, "type", 0));
			bean.setMsg(JSONUtil.getString(e, "msg", ""));
			bean.setForm(JSONUtil.getInt(e, "form", 0));
			bean.setMaxenter(JSONUtil.getInt(e, "Maxenter", 0));
			bean.setHost(JSONUtil.getString(e, "host", ""));
			bean.setPort(JSONUtil.getInt(e, "port", 0));
			bean.setLaizhi(JSONUtil.getInt(e, "Laizhi", 0));
			bean.setIsluckroom(JSONUtil.getInt(e, "isluckroom", 0) == 1 ? true
					: false);
		}
		return bean;
	}

	public class CommonPagerAdapter extends BaseAdapter {
		private LayoutInflater mLayoutInflater;

		public CommonPagerAdapter(Context context) {
			this.mLayoutInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			int count = 0;
			if (commondata != null) {
				count = commondata.size() / 2;
				if (commondata.size() % 2 == 1)
					count++;
			}
			return count;
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TableViewHolder holder = null;
			if (convertView == null) {
				holder = new TableViewHolder();
				convertView = this.mLayoutInflater.inflate(
						R.layout.lobby_viewpage_item, null);
				holder.init(convertView);
				convertView.setTag(holder);
			} else {
				holder = (TableViewHolder) convertView.getTag();
			}
			int n = commondata.size();
			if (n >= (position * 2 + 1)) {
				final CourtBean bean = commondata.get(position * 2);
				setCorrtItem(bean, holder.name_1, holder.min_enter_1,
						holder.min_chip_1, holder.viewpager_Layout1,
						holder.form_type_1);
			} else {
				holder.viewpager_Layout1.setVisibility(View.GONE);
				holder.viewpager_Layout1.setOnClickListener(null);
			}
			if (n >= (position * 2 + 2)) {
				final CourtBean bean = commondata.get(position * 2 + 1);
				setCorrtItem(bean, holder.name_2, holder.min_enter_2,
						holder.min_chip_2, holder.viewpager_Layout2,
						holder.form_type_2);
			} else {
				holder.viewpager_Layout2.setVisibility(View.GONE);
				holder.viewpager_Layout2.setOnClickListener(null);
			}
			return convertView;
		}

	}

	private void displayIntroducePopWin(JSONObject res, final int formId) {
		JSONObject formBean = JSONUtil.getJSONObject(res, "formBean");
		boolean Introdcue_room = ShareData.getInstance().getBooleanValue(
				"INTRODUCE_ROOM_" + formId, false);
		if (formBean != null && !Introdcue_room) {
			final String title = JSONUtil.getString(formBean, "title", "");
			String imageUrl = JSONUtil.getString(formBean, "image_url", "");
			String imageName = JSONUtil.getString(formBean, "imgae_name", ""); // 大转盘信息描述
			final String desc = JSONUtil.getString(formBean, "desc", "");
			if (imageName != null && imageName.trim().length() > 0) {
				Bitmap pan = DownLoadImage.loadBitmap(LobbyActivity.this,
						imageName); // 成功获取转盘文件
				if (pan != null) {
					showTableTroduce(title, pan, "INTRODUCE_ROOM_" + formId);
				} else {
					DownLoadImage.saveBitmap(LobbyActivity.this, imageName,
							imageUrl, new DownLoadImageListener() {

								@Override
								public void onFinish(Bitmap bitmap) {
									showTableTroduce(title, bitmap,
											"INTRODUCE_ROOM_" + formId);
								}

								@Override
								public void onFailed() {
								}
							});
				}
			} else {
				showTableTroduce(title, desc, "INTRODUCE_ROOM_" + formId);
			}
		}
	}

	private class EnterLaiziCallback implements PHPCallbackInterface {
		private int formID;

		public EnterLaiziCallback(int formID) {
			this.formID = formID;
		}

		@Override
		public void onFinish(PHPResult result) {
			stopLoading();
			if (result != null && result.code == ErrorCode.SUCCESS) {
				JSONObject res = JSONUtil.parse(result.recvData);
				if (res != null) {
					Log.v(this, result.recvData);
					int ret = JSONUtil.getInt(res, "ret", 2);
					if (ret == 1) {
						displayIntroducePopWin(res, formID);
						JSONArray courtArray = JSONUtil.getJSONArray(res,
								"courtBean");
						if (courtArray != null && courtArray.length() > 0) {
							try {
								laizi_data.clear();
								for (int i = 0, n = courtArray.length(); i < n; i++) {
									JSONObject e = courtArray.getJSONObject(i);
									CourtBean bean = getCourtBean(e);
									if (bean != null)
										laizi_data.add(bean);
								}
							} catch (JSONException e) {
								Log.e(this, e);
							}
						}
						if (laizi_data.size() > 0) {
							if (laizi_Pager == null) {
								laiziAdapter = new LaiziPagerAdapter(
										LobbyActivity.this);
								laizi_Pager = (ListView) findViewById(R.id.laizi_vPager);
								laizi_Pager.setVerticalScrollBarEnabled(true);
								laizi_Pager.setAdapter(laiziAdapter);
								laizi_Pager.setSelected(true);
								laizi_Pager.setSelection(0);
								if (laizi_data.size() > 4)
									laizi_Pager.setDividerHeight(ConfigCenter
											.adaptW(11));
								else
									laizi_Pager.setDividerHeight(ConfigCenter
											.adaptW(22));
							} else {
								laiziAdapter.notifyDataSetChanged();
							}
						}
					} else {
						// 获取数据失败
						int retCode = JSONUtil.getInt(res, "retCode", 0);
						String msg = JSONUtil.getString(res, "retMsg", "");
						showMessage(msg + "(" + retCode + ")");
						AddStatistics.addGetTableTypeFailedStatistics(
								LobbyActivity.this, "比赛场：" + msg + "("
										+ retCode + ")");
					}
				} else {
					String msg = getString(R.string.network_error);
					showMessage(msg);
					AddStatistics.addGetTableTypeFailedStatistics(
							LobbyActivity.this, "比赛场：数据解析异常");
				}
			} else {
				String msg = getString(R.string.network_error);
				showMessage(msg);
				AddStatistics.addGetTableTypeFailedStatistics(
						LobbyActivity.this, "比赛场：网络异常");
			}
		}
	}

	public class LaiziPagerAdapter extends BaseAdapter {
		private LayoutInflater mLayoutInflater;

		public LaiziPagerAdapter(Context context) {
			this.mLayoutInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			int count = 0;
			if (laizi_data != null) {
				count = laizi_data.size() / 2;
				if (laizi_data.size() % 2 == 1)
					count++;
			}
			return count;
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TableViewHolder holder = null;
			if (convertView == null) {
				holder = new TableViewHolder();
				convertView = this.mLayoutInflater.inflate(
						R.layout.lobby_viewpage_item, null);
				holder.init(convertView);
				convertView.setTag(holder);
			} else {
				holder = (TableViewHolder) convertView.getTag();
			}
			int n = laizi_data.size();
			if (n >= (position * 2 + 1)) {
				final CourtBean bean = laizi_data.get(position * 2);
				setCorrtItem(bean, holder.name_1, holder.min_enter_1,
						holder.min_chip_1, holder.viewpager_Layout1,
						holder.form_type_1);
			} else {
				holder.viewpager_Layout1.setVisibility(View.GONE);
				holder.viewpager_Layout1.setOnClickListener(null);
			}
			if (n >= (position * 2 + 2)) {
				final CourtBean bean = laizi_data.get(position * 2 + 1);
				setCorrtItem(bean, holder.name_2, holder.min_enter_2,
						holder.min_chip_2, holder.viewpager_Layout2,
						holder.form_type_2);
			} else {
				holder.viewpager_Layout2.setVisibility(View.GONE);
				holder.viewpager_Layout2.setOnClickListener(null);
			}
			return convertView;
		}

	}

	private class EnterSuperLaiziCallback implements PHPCallbackInterface {
		private int formID;

		public EnterSuperLaiziCallback(int formID) {
			this.formID = formID;
		}

		@Override
		public void onFinish(PHPResult result) {
			stopLoading();
			if (result != null && result.code == ErrorCode.SUCCESS) {
				JSONObject res = JSONUtil.parse(result.recvData);
				if (res != null) {
					Log.v(this, result.recvData);
					int ret = JSONUtil.getInt(res, "ret", 2);
					if (ret == 1) {
						displayIntroducePopWin(res, formID);
						JSONArray courtArray = JSONUtil.getJSONArray(res,
								"courtBean");
						if (courtArray != null && courtArray.length() > 0) {
							try {
								for (int i = 0, n = courtArray.length(); i < n; i++) {
									JSONObject e = courtArray.getJSONObject(i);
									CourtBean bean = getCourtBean(e);
									if (bean != null)
										super_laizi_data.add(bean);
								}
							} catch (JSONException e) {
								Log.e(this, e);
							}
						}
						if (super_laizi_data.size() > 0) {
							if (super_laizi_Pager == null) {
								superLaiziAdapter = new SuperLaiziPagerAdapter(
										LobbyActivity.this);
								super_laizi_Pager = (ListView) findViewById(R.id.super_laizi_vPager);
								super_laizi_Pager
										.setVerticalScrollBarEnabled(true);
								super_laizi_Pager.setAdapter(superLaiziAdapter);
								super_laizi_Pager.setSelected(true);
								super_laizi_Pager.setSelection(0);
								if (super_laizi_data.size() > 4)
									super_laizi_Pager
											.setDividerHeight(ConfigCenter
													.adaptW(11));
								else
									super_laizi_Pager
											.setDividerHeight(ConfigCenter
													.adaptW(22));
							} else {
								superLaiziAdapter.notifyDataSetChanged();
							}
						}
					} else {
						// 获取数据失败
						int retCode = JSONUtil.getInt(res, "retCode", 0);
						String msg = JSONUtil.getString(res, "retMsg", "");
						showMessage(msg + "(" + retCode + ")");
						AddStatistics.addGetTableTypeFailedStatistics(
								LobbyActivity.this, "千王场：" + msg + "("
										+ retCode + ")");
					}
				} else {
					String msg = getString(R.string.network_error);
					showMessage(msg);
					AddStatistics.addGetTableTypeFailedStatistics(
							LobbyActivity.this, "千王场：数据解析异常");
				}
			} else {
				String msg = getString(R.string.network_error);
				showMessage(msg);
				AddStatistics.addGetTableTypeFailedStatistics(
						LobbyActivity.this, "千王场：网络异常");
			}
		}
	}

	public class SuperLaiziPagerAdapter extends BaseAdapter {
		private LayoutInflater mLayoutInflater;

		public SuperLaiziPagerAdapter(Context context) {
			this.mLayoutInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			int count = 0;
			if (super_laizi_data != null) {
				count = super_laizi_data.size() / 2;
				if (super_laizi_data.size() % 2 == 1)
					count++;
			}
			return count;
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TableViewHolder holder = null;
			if (convertView == null) {
				holder = new TableViewHolder();
				convertView = this.mLayoutInflater.inflate(
						R.layout.lobby_viewpage_item, null);
				holder.init(convertView);
				convertView.setTag(holder);
			} else {
				holder = (TableViewHolder) convertView.getTag();
			}
			int n = super_laizi_data.size();
			if (n >= (position * 2 + 1)) {
				final CourtBean bean = super_laizi_data.get(position * 2);
				setCorrtItem(bean, holder.name_1, holder.min_enter_1,
						holder.min_chip_1, holder.viewpager_Layout1,
						holder.form_type_1);
			} else {
				holder.viewpager_Layout1.setVisibility(View.GONE);
				holder.viewpager_Layout1.setOnClickListener(null);
			}
			if (n >= (position * 2 + 2)) {
				final CourtBean bean = super_laizi_data.get(position * 2 + 1);
				setCorrtItem(bean, holder.name_2, holder.min_enter_2,
						holder.min_chip_2, holder.viewpager_Layout2,
						holder.form_type_2);
			} else {
				holder.viewpager_Layout2.setVisibility(View.GONE);
				holder.viewpager_Layout2.setOnClickListener(null);
			}
			return convertView;
		}

	}

	private class EnterMatchCallback implements PHPCallbackInterface {
		private int formID;

		public EnterMatchCallback(int formID) {
			this.formID = formID;
		}

		@Override
		public void onFinish(PHPResult result) {
			stopLoading();
			if (result != null && result.code == ErrorCode.SUCCESS) {
				JSONObject res = JSONUtil.parse(result.recvData);
				if (res != null) {
					Log.v(this, result.recvData);
					int ret = JSONUtil.getInt(res, "ret", 2);
					if (ret == 1) {
						displayIntroducePopWin(res, formID);
						JSONArray courtArray = JSONUtil.getJSONArray(res,
								"courtBean");
						if (courtArray != null && courtArray.length() > 0) {
							match_data.clear();
							try {
								for (int i = 0, n = courtArray.length(); i < n; i++) {
									JSONObject e = courtArray.getJSONObject(i);
									CourtBean bean = getCourtBean(e);
									if (bean != null)
										match_data.add(bean);
								}
							} catch (JSONException e) {
								Log.e(this, e);
							}
						}
						if (match_data.size() > 0) {
							if (match_Pager == null) {
								matchAdapter = new MatchAdapter(
										LobbyActivity.this);
								match_Pager = (ListView) findViewById(R.id.match_vPager);
								match_Pager.setVerticalScrollBarEnabled(true);
								match_Pager.setAdapter(matchAdapter);
								match_Pager.setSelected(true);
								match_Pager.setSelection(0);
								if (match_data.size() > 4)
									match_Pager.setDividerHeight(ConfigCenter
											.adaptW(11));
								else
									match_Pager.setDividerHeight(ConfigCenter
											.adaptW(22));
							} else {
								matchAdapter.notifyDataSetChanged();
							}
						}
					} else {
						// 获取数据失败
						int retCode = JSONUtil.getInt(res, "retCode", 0);
						String msg = JSONUtil.getString(res, "retMsg", "");
						showMessage(msg + "(" + retCode + ")");
						AddStatistics.addGetTableTypeFailedStatistics(
								LobbyActivity.this, "千王场：" + msg + "("
										+ retCode + ")");
					}
				} else {
					String msg = getString(R.string.network_error);
					showMessage(msg);
					AddStatistics.addGetTableTypeFailedStatistics(
							LobbyActivity.this, "千王场：数据解析异常");
				}
			} else {
				String msg = getString(R.string.network_error);
				showMessage(msg);
				AddStatistics.addGetTableTypeFailedStatistics(
						LobbyActivity.this, "千王场：网络异常");
			}
		}
	}

	public class MatchAdapter extends BaseAdapter {
		private LayoutInflater mLayoutInflater;

		public MatchAdapter(Context context) {
			this.mLayoutInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			int count = 0;
			if (match_data != null) {
				count = match_data.size() / 2;
				if (match_data.size() % 2 == 1)
					count++;
			}
			return count;
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TableViewHolder holder = null;
			if (convertView == null) {
				holder = new TableViewHolder();
				convertView = this.mLayoutInflater.inflate(
						R.layout.lobby_viewpage_item, null);
				holder.init(convertView);
				convertView.setTag(holder);
			} else {
				holder = (TableViewHolder) convertView.getTag();
			}
			int n = match_data.size();
			if (n >= (position * 2 + 1)) {
				final CourtBean bean = match_data.get(position * 2);
				setCorrtItem(bean, holder.name_1, holder.min_enter_1,
						holder.min_chip_1, holder.viewpager_Layout1,
						holder.form_type_1);
			} else {
				holder.viewpager_Layout1.setVisibility(View.GONE);
				holder.viewpager_Layout1.setOnClickListener(null);
			}
			if (n >= (position * 2 + 2)) {
				final CourtBean bean = match_data.get(position * 2 + 1);
				setCorrtItem(bean, holder.name_2, holder.min_enter_2,
						holder.min_chip_2, holder.viewpager_Layout2,
						holder.form_type_2);
			} else {
				holder.viewpager_Layout2.setVisibility(View.GONE);
				holder.viewpager_Layout2.setOnClickListener(null);
			}
			return convertView;
		}

	}

	public final class TableViewHolder {
		RelativeLayout viewpager_Layout1;
		TextView name_1;
		TextView min_enter_1;
		TextView min_chip_1;
		ImageView form_type_1;
		RelativeLayout viewpager_Layout2;
		TextView name_2;
		TextView min_enter_2;
		TextView min_chip_2;
		ImageView form_type_2;

		public void init(View convertView) {
			viewpager_Layout1 = (RelativeLayout) convertView
					.findViewById(R.id.viewpager_Layout1);
			viewpager_Layout2 = (RelativeLayout) convertView
					.findViewById(R.id.viewpager_Layout2);
			name_1 = (TextView) convertView.findViewById(R.id.name_1);
			min_enter_1 = (TextView) convertView.findViewById(R.id.min_enter_1);
			min_chip_1 = (TextView) convertView.findViewById(R.id.min_chip_1);
			form_type_1 = (ImageView) convertView
					.findViewById(R.id.form_type_1);
			name_2 = (TextView) convertView.findViewById(R.id.name_2);
			min_enter_2 = (TextView) convertView.findViewById(R.id.min_enter_2);
			min_chip_2 = (TextView) convertView.findViewById(R.id.min_chip_2);
			form_type_2 = (ImageView) convertView
					.findViewById(R.id.form_type_2);
		}
	}

	@Override
	public void updateUserMsgSuccess() {
		notifyModifyMoney();

	}

	public void updatemarqueeMsg() {
		lobby_user_tips.setText(Html.fromHtml(UserMessageCenter.getInstance()
				.getExerMsg()));
	}

	private void aliPayNumReq() {
		UserInfo self = UserMessageCenter.getInstance().getUserInfo();
		TreeMap<String, Object> param = new TreeMap<String, Object>();
		param.put("uid", self.getUid());
		param.put("session", self.getSession());

		String json = new MyJson(param).toString();
		PHPRequestPool.getInstance().AddRequest(new AliPayNumCallback(),
				PHPMethodName.CLI_ALIPAY_NUM_REQ, json);
	}

	private class AliPayNumCallback implements PHPCallbackInterface {

		public void onFinish(PHPResult result) {
			if (result != null && result.code == ErrorCode.SUCCESS) {
				JSONObject res = JSONUtil.parse(result.recvData);
				if (res != null) {
					int ret = JSONUtil.getInt(res, "ret", 2);
					if (ret == 1) {
						int tasknumber = JSONUtil.getInt(res, "tasknumber", 0);
						int giftnumber = JSONUtil.getInt(res, "giftnumber", 0);

						UserInfo self = UserMessageCenter.getInstance()
								.getUserInfo();

						self.setTasknumber(tasknumber);
						self.setGiftnumber(giftnumber);
						notifyModifyMoney();
					}
				}
			}
			if (LobbyActivity.this != null
					&& !LobbyActivity.this.isFinishing()
					&& LobbyActivity.class.isInstance(ActivityContainer
							.getInstance().getCurrentActivity())) {
				(new Handler()).postDelayed(new Runnable() {

					@Override
					public void run() {
						aliPayNumReq();
					}

				}, 180000); // 3分钟后重新获取任务和礼包信息
			}
		}
	}

	private int getNumberIcon(int num) {
		int rid = 0;
		switch (num) {
		case 0:
			rid = 0;
			break;
		case 1:
			rid = R.drawable.room_task_num_1;
			break;
		case 2:
			rid = R.drawable.room_task_num_2;
			break;
		case 3:
			rid = R.drawable.room_task_num_3;
			break;
		case 4:
			rid = R.drawable.room_task_num_4;
			break;
		case 5:
			rid = R.drawable.room_task_num_5;
			break;
		default:
			rid = R.drawable.room_task_num_n;
			break;
		}
		return rid;
	}

	private void setVisibleAnimation(ImageView view) {
		ScaleAnimation animation = new ScaleAnimation(0.5f, 1.4f, 0.5f, 1.4f,
				Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
				0.5f);
		animation.setRepeatCount(Animation.INFINITE);
		animation.setFillAfter(true);
		animation.setDuration(800);
		animation.setRepeatMode(Animation.REVERSE);
		view.startAnimation(animation);
	}

	private void removeAnimation(ImageView view) {
		if (view != null && view.getAnimation() != null)
			view.getAnimation().cancel();
	}

	public void getMarqueeMsg() {
		UserInfo self = UserMessageCenter.getInstance().getUserInfo();
		TreeMap<String, Object> param = new TreeMap<String, Object>();
		param.put("uid", self.getUid());
		param.put("session", self.getSession());

		String json = new MyJson(param).toString();
		PHPRequestPool.getInstance().AddRequest(new MarqueeMsgCallback(),
				PHPMethodName.CLI_MARQUEE_REQ, json);
	}

	private class MarqueeMsgCallback implements PHPCallbackInterface {
		/*
		 * (non-Javadoc)
		 * 
		 * @see
		 * com.backfire.php.PHPCallbackInterface#onFinish(com.backfire.php.PHPResult
		 * )
		 */
		public void onFinish(PHPResult result) {
			String marqueestr = "";
			if (result != null && result.code == ErrorCode.SUCCESS) {
				JSONObject res = JSONUtil.parse(result.recvData);
				if (res != null) {
					int ret = JSONUtil.getInt(res, "ret", 2);
					if (ret == 1) {
						UserMessageCenter center = UserMessageCenter
								.getInstance();

						JSONArray marquee = JSONUtil.getJSONArray(res,
								"marquee");
						if (marquee != null && marquee.length() > 0) {
							try {
								for (int i = 0, n = marquee.length(); i < n; i++) {
									String msg = marquee.getString(i);
									if (msg != null && msg.trim().length() > 0) {
										marqueestr += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
												+ msg;
									}
								}
								center.setExerMsg(marqueestr);

								((LobbyActivity) ActivityContainer
										.getInstance().getCurrentActivity())
										.updatemarqueeMsg();// 通知界面更新跑马灯消息

							} catch (JSONException e) {
								Log.e(this, e);
							} catch (Exception e) {
								Log.e(this, e);
								e.printStackTrace();
							}
						}
					}
				}
			}

			if (marqueestr == null || marqueestr.trim().length() == 0) {
				(new Handler()).postDelayed(new Runnable() {

					@Override
					public void run() {
						getMarqueeMsg();
					}

				}, 30000); // 拉取跑马灯失败时，30S钟后重新拉取
			} else {
				(new Handler()).postDelayed(new Runnable() {

					@Override
					public void run() {
						getMarqueeMsg();
					}

				}, 300000);// 拉取跑马灯成功时，5分钟后重新拉取，更新数据
			}
		}
	}
}
