public class DropMenuAdapter extends BaseAdapter {
	private Context context;
	private List<WifiAccount> list;// 数据集合
	private LayoutInflater listContainer;// 视图容器
	private DropPopMenu dropPopMenu;

	static class DropItemViewHolder { // 自定义控件集合
		public TextView title;
		public TextView id;
		public ImageButton delete;
	}

	public DropMenuAdapter(Context context, List<WifiAccount> data,
			DropPopMenu dropPopMenu) {
		this.context = context;
		this.listContainer = MyApplication.getLayoutInflater(); // 创建视图容器并设置上下文
		this.list = data;
		this.dropPopMenu = dropPopMenu;
	}

	public List<WifiAccount> getList() {
		return list;
	}

	public void setList(List<WifiAccount> list) {
		this.list = list;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return list.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		// 自定义视图
		DropItemViewHolder listItemView = null;

		if (convertView == null) {
			// 获取list_item布局文件的视图
			convertView = listContainer.inflate(
					R.layout.droppopmenu_listview_item, null);

			listItemView = new DropItemViewHolder();
			// 获取控件对象
			listItemView.title = (TextView) convertView
					.findViewById(R.id.droppopmenu_listView_item_title);
			listItemView.id = (TextView) convertView
					.findViewById(R.id.droppopmenu_listView_item_id);
			listItemView.delete = (ImageButton) convertView
					.findViewById(R.id.droppopmenu_listView_item_delete);
			// 设置控件集到convertView
			convertView.setTag(listItemView);
		} else {
			listItemView = (DropItemViewHolder) convertView.getTag();
		}
		final WifiAccount item = list.get(position);
		listItemView.title.setText(item.getUsername());
		listItemView.id.setText(String.valueOf(item.getId()));
		listItemView.delete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dropPopMenu.dismiss();
				WifiDb.getInstance(context).deleteByName(item.getUsername());
			}
		});
		return convertView;
	}

} public class UmengSherlockFragmentActivity extends SherlockFragmentActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}
} public class WifiDb extends WifiDBUtil {

	private static final String TABLE_NAME = "wifi";

	private static WifiDb service = null;

	public static WifiDb getInstance(Context context) {
		if (service == null) {
			service = new WifiDb(context);
		}
		return service;
	}

	public WifiDb(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);
	}

	public WifiDb(Context context) {
		super(context);
	}

	/**
	 * 插入一条数据
	 * 
	 * @param WifiAccount
	 * @return
	 */
	public boolean insert(WifiAccount account) {
		try {
			ContentValues cv = new ContentValues();
			cv.put("username", account.getUsername());
			cv.put("password", account.getPassword());
			SQLiteDatabase db = this.getWritableDatabase();
			db.insert(TABLE_NAME, null, cv);
			db.close();
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 更新一条数据
	 * 
	 * @param lessons
	 */
	public void update(WifiAccount account) {
		SQLiteDatabase db = this.getWritableDatabase();
		ContentValues cv = new ContentValues();
		cv.put("id", account.getId());
		cv.put("username", account.getUsername());
		cv.put("password", account.getPassword());
		db.update(TABLE_NAME, cv, "id=?",
				new String[] { String.valueOf(account.getId()) });
		db.close();
	}

	/**
	 * 由ID获取课程
	 * 
	 * @param Id
	 * @return
	 */
	public WifiAccount getAccountById(String id) {
		SQLiteDatabase db = this.getReadableDatabase();
		Cursor cursor = db.query(TABLE_NAME, null, "id = ?",
				new String[] { String.valueOf(id) }, null, null, null);
		WifiAccount account = new WifiAccount();
		if (cursor.moveToFirst()) {
			account.setId(cursor.getInt(cursor.getColumnIndex("id")));
			account.setUsername(cursor.getString(cursor
					.getColumnIndex("username")));
			account.setPassword(cursor.getString(cursor
					.getColumnIndex("password")));
			cursor.close();
			db.close();
			return account;
		}
		if (cursor != null)
			cursor.close();
		cursor = null;
		db.close();
		return null;
	}

	/**
	 * 由username获取课程
	 * 
	 * @param username
	 * @return
	 */
	public WifiAccount getAccountByUsername(String username) {
		SQLiteDatabase db = this.getReadableDatabase();
		Cursor cursor = db.query(TABLE_NAME, null, "username = ?",
				new String[] { String.valueOf(username) }, null, null, null);
		WifiAccount account = new WifiAccount();
		if (cursor.moveToFirst()) {
			account.setId(cursor.getInt(cursor.getColumnIndex("id")));
			account.setUsername(cursor.getString(cursor
					.getColumnIndex("username")));
			account.setPassword(cursor.getString(cursor
					.getColumnIndex("password")));
			cursor.close();
			db.close();
			return account;
		}
		if (cursor != null)
			cursor.close();
		cursor = null;
		db.close();
		return null;
	}

	/**
	 * 
	 * @return 数据库中的所有WIFI账户信息
	 */
	public List<WifiAccount> getLocalAccountsList() {
		ArrayList<WifiAccount> list = new ArrayList<WifiAccount>();
		SQLiteDatabase db = this.getReadableDatabase();
		Cursor cursor = db.query(TABLE_NAME, //
				null, null, null, null, null, null);
		try {
			while (cursor.moveToNext()) {
				WifiAccount account = new WifiAccount();
				account.setId(cursor.getInt(cursor.getColumnIndex("id")));
				account.setUsername(cursor.getString(cursor
						.getColumnIndex("username")));
				account.setPassword(cursor.getString(cursor
						.getColumnIndex("password")));
				list.add(account);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cursor != null)
				cursor.close();
			cursor = null;
			db.close();
		}
		return list;
	}

	/**
	 * 根据用户名删除账户
	 * 
	 * @param name
	 * @return
	 */
	public boolean deleteByName(String name) {
		if (this.getWritableDatabase().delete(TABLE_NAME, "username=?",
				new String[] { name }) != 0) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 根据Id删除课程
	 * 
	 * @param id
	 * @return
	 */
	public boolean deleteById(String id) {
		if (this.getWritableDatabase().delete(TABLE_NAME, "id=?",
				new String[] { id }) != 0) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 删除所有的数据
	 */
	public void deleteAll() {
		this.getWritableDatabase().delete(TABLE_NAME, null, null);
	}

} public class WifiAccount {

	private int id;
	private String username;
	private String password;

	public WifiAccount(int id, String username, String password) {
		super();
		this.id = id;
		this.username = username;
		this.password = password;
	}

	public WifiAccount(String username, String password) {
		super();
		this.id = -1;
		this.username = username;
		this.password = password;
	}

	public WifiAccount() {
		super();
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
} public class BosCrypto {
	public static final String Excalibur = "WYY";// 无意义

	/**
	 * @param seed
	 *            密钥
	 * @param cleartext
	 *            正文
	 * @return 加密结果
	 */
	public static String encrypt(String seed, String cleartext)
			throws Exception {
		byte[] rawKey = getRawKey(seed.getBytes());
		byte[] result = encrypt(rawKey, cleartext.getBytes());
		return toHex(result);
	}

	/**
	 * @param seed
	 *            密钥
	 * @param cleartext
	 *            正文
	 * @return 解密结果
	 */
	public static String decrypt(String seed, String encrypted)
			throws Exception {
		byte[] rawKey = getRawKey(seed.getBytes());
		byte[] enc = toByte(encrypted);
		byte[] result = decrypt(rawKey, enc);
		return new String(result);
	}

	private static byte[] getRawKey(byte[] seed) throws Exception {
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		SecureRandom sr = null;
		if (android.os.Build.VERSION.SDK_INT >= 17) {
			sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
		} else {
			sr = SecureRandom.getInstance("SHA1PRNG");
		}
		sr.setSeed(seed);
		kgen.init(128, sr); // 192 and 256 bits may not be available
		SecretKey skey = kgen.generateKey();
		byte[] raw = skey.getEncoded();
		return raw;
	}

	private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
		byte[] encrypted = cipher.doFinal(clear);
		return encrypted;
	}

	private static byte[] decrypt(byte[] raw, byte[] encrypted)
			throws Exception {
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.DECRYPT_MODE, skeySpec);
		byte[] decrypted = cipher.doFinal(encrypted);
		return decrypted;
	}

	public static String toHex(String txt) {
		return toHex(txt.getBytes());
	}

	public static String fromHex(String hex) {
		return new String(toByte(hex));
	}

	public static byte[] toByte(String hexString) {
		int len = hexString.length() / 2;
		byte[] result = new byte[len];
		for (int i = 0; i < len; i++)
			result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2),
					16).byteValue();
		return result;
	}

	public static String toHex(byte[] buf) {
		if (buf == null)
			return "";
		StringBuffer result = new StringBuffer(2 * buf.length);
		for (int i = 0; i < buf.length; i++) {
			appendHex(result, buf[i]);
		}
		return result.toString();
	}

	private final static String HEX = "0123456789ABCDEF";

	private static void appendHex(StringBuffer sb, byte b) {
		sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
	}
} public final class Constants {
	public static final String PREFS_NAME_APP_SETTING = "zq.whu.zhangshangwuda.ui_preferences";
	public static final String PREFS_NAME_USER_DATA = "User_Data";
	public static final int DISPLAY_LDPI_WIDTH = 240; // ldpi屏幕的宽度
	public static final int DISPLAY_MDPI_WIDTH = 320; // mdpi屏幕的宽度
	public static final int DISPLAY_HDPI_WIDTH = 480; // hdpi屏幕的宽度
	public static final int DISPLAY_XHDPI_WIDTH = 640; // xhdpi屏幕的宽度
} public class LessonsTool {
	public static String thtml = "";

	public static List<Map<String, String>> sortLessonsByTime(
			List<Map<String, String>> list) {
		// 消除无法解析的错误课程信息
		int tsize = list.size();
		for (int i = 0; i < tsize; ++i) {
			Map<String, String> map = new HashMap<String, String>();
			map = list.get(i);
			if (!checkStr(map.get("ste")) || !checkStr(map.get("time"))
					|| !StringUtils.isNumeric(map.get("day"))) {
				list.remove(i);
				i--;
				tsize--;
			}
		}
		int size = list.size();
		Map<String, String> tmap = new HashMap<String, String>();
		for (int i = 0; i < size; ++i) {
			if (list.get(i).get("place").length() < 4) {
				list.get(i).put("place", list.get(i).get("other"));
			}
			// +",每"+list.get(i).get("mjz")+"周"
			list.get(i).put(
					"time",
					list.get(i).get("time") + "节," + list.get(i).get("ste")
							+ "周");
		}
		for (int i = 0; i < size - 1; ++i)
			for (int j = i + 1; j <= size - 1; ++j) {
				// 获取第i个元素是第几节课
				String tstring = list.get(i).get("time");
				int k = tstring.indexOf("-");
				tstring = tstring.substring(0, k);
				int a = StringUtils.toInt(tstring);
				// 获取第j个元素是第几节课
				tstring = list.get(j).get("time");
				k = tstring.indexOf("-");
				tstring = tstring.substring(0, k);
				int b = StringUtils.toInt(tstring);
				if (a > b) {
					tmap = list.get(i);
					list.set(i, list.get(j));
					list.set(j, tmap);
				}
			}
		return list;
	}

	public static List<Map<String, String>> getLessonsList(Context context,
			String html) {
		Document doc = null;
		thtml = html;
		if (StringUtils.isEmpty(html)) {
			return null;
		}
		doc = Jsoup.parse(thtml);
		if (doc == null) {
			return null;
		}

		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		Elements lessons = doc.select("tr[align=center]");
		for (Element lesson : lessons) {
			Elements times = lesson.select("td[width=113]");
			int weekday = 0;
			for (Element time : times) {
				String tinfo = time.text();
				if (tinfo.length() < 2) {
					++weekday;
					continue;
				} else {
					Map<String, String> map = new HashMap<String, String>();
					Integer tid = LessonsSharedPreferencesTool
							.getLessonsId(context);
					++tid;
					LessonsSharedPreferencesTool.setLessonsId(context, tid);
					// 设置课程ID
					map.put("id", String.valueOf(tid));
					// 提取课程名
					map.put("name", lesson.select("td[width=80]").text());
					// 提取教师名
					map.put("teacher", lesson.select("td[width=52]").text());
					// 提取第几星期上课
					++weekday;
					map.put("day", Integer.toString(weekday));
					// 提取起止周数
					int tpos = tinfo.indexOf("周");
					map.put("ste", tinfo.substring(0, tpos));
					// 提取每几周
					tinfo = tinfo.substring(tpos + 3);
					map.put("mjz", tinfo.substring(0, 1));
					// 提取第几节上课
					tinfo = tinfo.substring(4);
					tpos = tinfo.indexOf("节");
					map.put("time", tinfo.substring(0, tpos));
					// 提取上课地点
					if (tinfo.length() > tpos + 2) {
						tinfo = tinfo.substring(tpos + 2);
						map.put("place", tinfo.substring(0));
					} else {
						map.put("place", "");
					}
					// 提取备注信息
					map.put("other", lesson.select("td[width=100]").text());
					list.add(map);
				}
			}
		}
		return list;
	}

	public static List<Map<String, String>> washLessonsByWeek(
			List<Map<String, String>> list, int nowWeek) {
		int tsize = list.size();
		String tstring;
		boolean isDel;
		for (int i = 0; i < tsize; ++i) {
			isDel = false;
			Map<String, String> map = new HashMap<String, String>();
			map = list.get(i);
			tstring = map.get("time");
			// 提取上课起止周数
			String tsw = map.get("ste");
			int startweek = StringUtils
					.toInt(tsw.substring(0, tsw.indexOf("-")));
			int endweek = Integer.parseInt(tsw.substring(tsw.indexOf("-") + 1));
			if (startweek == 0 || endweek == 0)
				isDel = true;
			int mjz = StringUtils.toInt(map.get("mjz"));
			// 判断双周是否该上
			if (mjz == 2 && (nowWeek - startweek) % mjz == 1)
				isDel = true;
			// 判断是否已经停课
			if (!(startweek <= nowWeek && nowWeek <= endweek))
				isDel = true;
			if (isDel) {
				list.remove(i);
				i--;
				tsize--;
			}
		}
		return list;
	}

	public static int getWhichWeek(int fyear, int fmonth, int fday, int year,
			int month, int day) {
		Calendar a = Calendar.getInstance();
		a.set(fyear, fmonth - 1, fday, 0, 0, 0);
		a.set(Calendar.MILLISECOND, 0);
		while (a.get(Calendar.DAY_OF_WEEK) != 1)
			a.add(Calendar.DATE, +1);
		Calendar b = Calendar.getInstance();
		b.set(year, month - 1, day, 0, 0, 0);
		b.set(Calendar.MILLISECOND, 0);
		long diff = b.getTimeInMillis() - a.getTimeInMillis();
		if (diff < 0)
			return 0;
		long diffDays = diff / (24 * 60 * 60 * 1000);
		return (int) (diffDays / 7 + 1);
	}

	public static int getWeek(int fyear, int fmonth, int fday) {
		int week = 0;
		int year, month, day;
		Calendar a = Calendar.getInstance();
		year = a.get(Calendar.YEAR);
		month = a.get(Calendar.MONTH) + 1;
		day = a.get(Calendar.DATE);
		week = LessonsTool.getWhichWeek(fyear, fmonth, fday, year, month, day);
		if (week > 30)
			week = 0;
		return week;
	}

	public static int getNowWeek(Context context) {
		String TermFirstDay = LessonsSharedPreferencesTool
				.getTermFirstDay(context);
		String[] splitStr = TermFirstDay.split("-");
		int fyear = StringUtils.toInt(splitStr[0]);
		int fmonth = StringUtils.toInt(splitStr[1]);
		int fday = StringUtils.toInt(splitStr[2]);
		int nowWeek = LessonsTool.getWeek(fyear, fmonth, fday);
		return nowWeek;
	}

	// 检查字符串是否符合规范
	private static boolean checkStr(String str) {
		if (str.indexOf("-") < 0)
			return false;
		String a = str.substring(0, str.indexOf("-"));
		String b = str.substring(str.indexOf("-") + 1);
		return StringUtils.isNumeric(a) && StringUtils.isNumeric(b);
	}
} public class MainActivity extends BaseThemeFragmentActivityWithoutAnime {
	public static int mDrawerState = 0;
	private static final String STATE_CURRENT_FRAGMENT = "MainActivity_Tab";
	private final static String TAB_TAG_NEWS = "news";
	private final static String TAB_TAG_LESSONS = "lessons";
	private final static String TAB_TAG_WIFI = "wifi";
	private final static String TAB_TAG_SETTING = "setting";
	private final static String TAB_TAG_HELP = "help";
	private final static String TAB_TAG_FEED = "feed";
	private final static String TAB_TAG_ABOUT = "about";
	private String mCurrentFragmentTag;
	public MenuDrawer mMenuDrawer;
	private FeedbackAgent agent;
	public static ActionBar MainActivityActionbar;
	private FragmentManager mFragmentManager;
	private FragmentTransaction mFragmentTransaction;
	private Fragment mContent;

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			mMenuDrawer.toggleMenu();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// System.out.println("onCreate");
		super.onCreate(savedInstanceState);
		init();
		if (savedInstanceState != null) {
			mCurrentFragmentTag = savedInstanceState
					.getString(STATE_CURRENT_FRAGMENT);
			selectItem(mCurrentFragmentTag);
		} else {
			initStartTab();
		}
		getWindow().setBackgroundDrawable(null);
	}

	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		if (mCurrentFragmentTag != null)
			selectItem(mCurrentFragmentTag);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// System.out.println("onSaveInstanceState");
		super.onSaveInstanceState(outState);
		outState.putString(STATE_CURRENT_FRAGMENT, mCurrentFragmentTag);
	}

	private void init() {
		MainActivityActionbar = getSupportActionBar();
		mFragmentManager = getSupportFragmentManager();
		setDrawer();
		initWeekTitle();
		agent = new FeedbackAgent(this);
		agent.sync();
		// MobclickAgent.setDebugMode(true);
		MobclickAgent.openActivityDurationTrack(false);
		UmengUpdateAgent.setUpdateOnlyWifi(false);
		UmengUpdateAgent.update(this);
	}

	private void selectItem(String tab) {
		// System.out.println("selectItem");
		// System.out.println("tab " + tab);
		// System.out.println("mCurrentFragmentTag " + mCurrentFragmentTag);
		hideOtherFragment(tab);
		mCurrentFragmentTag = tab;
		attachFragment(mMenuDrawer.getContentContainer().getId(),
				getFragment(mCurrentFragmentTag), mCurrentFragmentTag);
		commitTransactions();
	}

	private void hideOtherFragment(String tab) {
		if (!tab.equals(TAB_TAG_NEWS))
			hideFragment(getFragment(TAB_TAG_NEWS));
		if (!tab.equals(TAB_TAG_LESSONS))
			hideFragment(getFragment(TAB_TAG_LESSONS));
		if (!tab.equals(TAB_TAG_WIFI))
			hideFragment(getFragment(TAB_TAG_WIFI));
	}

	protected FragmentTransaction ensureTransaction() {
		if (mFragmentTransaction == null) {
			mFragmentTransaction = mFragmentManager.beginTransaction();
			mFragmentTransaction
					.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
		}
		return mFragmentTransaction;
	}

	protected void attachFragment(int layout, Fragment f, String tag) {
		if (f != null) {
			if (!f.isAdded()) {
				ensureTransaction();
				mFragmentTransaction.add(layout, f, tag);
				mFragmentTransaction.show(f);
			} else {
				mFragmentTransaction.show(f);
			}
		}
	}

	protected void hideFragment(Fragment f) {
		if (f != null) {
			ensureTransaction();
			mFragmentTransaction.hide(f);
		}
	}

	protected void commitTransactions() {
		if (mFragmentTransaction != null && !mFragmentTransaction.isEmpty()) {
			mFragmentTransaction.commitAllowingStateLoss();
			mFragmentTransaction = null;
		}
	}

	private Fragment getFragment(String tag) {
		Fragment f = mFragmentManager.findFragmentByTag(tag);
		if (f == null) {
			if (tag.equals("news")) {
				f = new NewsFragmentSupport();
			}
			if (tag.equals("lessons")) {
				f = new LessonsFragmentSupport();
			}
			if (tag.equals("wifi")) {
				f = new WifiFragmentSupport();
			}
		}
		return f;
	}

	private void setDrawer() {
		mMenuDrawer = MenuDrawer.attach(this, MenuDrawer.Type.OVERLAY);
		mMenuDrawer.setContentView(R.layout.main);
		int mTheme = PreferenceHelper.getTheme(this);
		if (mTheme == R.style.MyLightTheme)
			mMenuDrawer.setMenuView(R.layout.left_menu_light);
		else
			mMenuDrawer.setMenuView(R.layout.left_menu);
		mMenuDrawer.setSlideDrawable(R.drawable.ic_drawer_black);
		// Whether the previous drawable should be shown
		mMenuDrawer.setDrawerIndicatorEnabled(true);
		initLeftMenu();
	}

	private void initStartTab() {
		// TODO Auto-generated method stub
		String StartTab = SettingSharedPreferencesTool
				.getStartTab(getApplication());
		int StartTabNo = 1;
		if (StartTab.equals("news"))
			StartTabNo = 1;
		if (StartTab.equals("lessons"))
			StartTabNo = 2;
		if (StartTab.equals("wifi"))
			StartTabNo = 3;
		switch (StartTabNo) {
		case 1:
			mMenuDrawer.setActiveView(findViewById(R.id.left_menu_news));
			selectItem(TAB_TAG_NEWS);
			getSupportActionBar().setTitle(R.string.News);
			break;
		case 2:
			mMenuDrawer.setActiveView(findViewById(R.id.left_menu_lessons));
			selectItem(TAB_TAG_LESSONS);
			getSupportActionBar().setTitle(R.string.Lessons);
			break;
		case 3:
			mMenuDrawer.setActiveView(findViewById(R.id.left_menu_wifi));
			selectItem(TAB_TAG_WIFI);
			getSupportActionBar().setTitle(R.string.Wifi);
			break;
		}
	}

	private void initWeekTitle() {
		// TODO Auto-generated method stub
		String TermFirstDay = LessonsSharedPreferencesTool
				.getTermFirstDay(this);
		String[] splitStr = TermFirstDay.split("-");
		int fyear = StringUtils.toInt(splitStr[0]);
		int fmonth = StringUtils.toInt(splitStr[1]);
		int fday = StringUtils.toInt(splitStr[2]);
		if (fyear != 0 && fmonth != 0 && fday != 0) {
			int nowWeek = LessonsTool.getWeek(fyear, fmonth, fday);
			String sWeekFormat = getResources().getString(R.string.Lessons_now_day); 
			String sWeekInfo=String.format(sWeekFormat,nowWeek); 
			getSupportActionBar().setSubtitle(sWeekInfo);
		}
	}

	private void initLeftMenu() {
		// TODO Auto-generated method stub
		MenuScrollView msv = (MenuScrollView) mMenuDrawer.getMenuView();
		msv.setOnScrollChangedListener(new MenuScrollView.OnScrollChangedListener() {
			@Override
			public void onScrollChanged() {
				mMenuDrawer.invalidate();
			}
		});
		findViewById(R.id.left_menu_news).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						mMenuDrawer.setActiveView(arg0);
						selectItem(TAB_TAG_NEWS);
						mMenuDrawer.closeMenu();
						getSupportActionBar().setTitle(R.string.News);
						int nowWeek = LessonsTool
								.getNowWeek(getApplicationContext());
						getSupportActionBar().setSubtitle(
								"第" + String.valueOf(nowWeek) + "周");
					}
				});
		findViewById(R.id.left_menu_lessons).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						mMenuDrawer.setActiveView(arg0);
						selectItem(TAB_TAG_LESSONS);
						mMenuDrawer.closeMenu();
						getSupportActionBar().setTitle(R.string.Lessons);
						int week = MyApplication.getInstance().getLessonsWeek();
						getSupportActionBar().setSubtitle(
								"第" + String.valueOf(week) + "周");
					}
				});
		findViewById(R.id.left_menu_wifi).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						mMenuDrawer.setActiveView(arg0);
						selectItem(TAB_TAG_WIFI);
						mMenuDrawer.closeMenu();
						getSupportActionBar().setTitle(R.string.Wifi);
						int nowWeek = LessonsTool
								.getNowWeek(getApplicationContext());
						getSupportActionBar().setSubtitle(
								"第" + String.valueOf(nowWeek) + "周");
					}
				});
		findViewById(R.id.left_menu_setting).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						Intent intent = new Intent();
						intent.setClass(getApplicationContext(),
								SettingActivity.class);
						startActivity(intent);
					}
				});
		findViewById(R.id.left_menu_help).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						Intent intent = new Intent();
						intent.setClass(getApplicationContext(),
								HelpActivity.class);
						startActivity(intent);
					}
				});
		findViewById(R.id.left_menu_feedback).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						agent.startFeedbackActivity();
					}
				});
		findViewById(R.id.left_menu_about).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						Intent intent = new Intent();
						intent.setClass(getApplicationContext(),
								AboutActivity.class);
						startActivity(intent);
					}
				});
	}

	// 截取按键动作
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		final int drawerState = mMenuDrawer.getDrawerState();
		if (drawerState == MenuDrawer.STATE_OPEN
				|| drawerState == MenuDrawer.STATE_OPENING) {
			mMenuDrawer.closeMenu();
			return true;
		}
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			MainActivityExit();
		}
		return super.dispatchKeyEvent(event);
	}

	private void MainActivityExit() {
		AlertDialog.Builder dialog = new Builder(this);
		dialog.setTitle(getResources().getString(R.string.exit_tip));
		dialog.setPositiveButton(getResources().getString(R.string.ok),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						android.os.Process.killProcess(android.os.Process
								.myPid());
					}
				});
		dialog.setNegativeButton(getResources().getString(R.string.cancel),
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		dialog.show();
	}
} public final class MyApplication extends Application {

	private static final String TAG = MyApplication.class.getSimpleName();
	private static MyApplication myapplication = null;
	private static Activity activity;
	private static LayoutInflater layoutInflater;
	private static String innerCachePath; // 手机内部存储缓存(由于手机内部存储有限，考虑废弃)
	private static String sdcardCachePath; // sdcard外部存储缓存;

	private static int smallAvatarSize;
	private static int normalAvatarSize;
	private static int displayWidth;
	private static int displayHeight;
	private static int densityDpi;
	private static float density;
	public ImageLoader mImageLoader = null;
	private int lessonsWeek;

	public int getLessonsWeek() {
		return lessonsWeek;
	}

	public void setLessonsWeek(int lessonsWeek) {
		this.lessonsWeek = lessonsWeek;
	}

	public static LayoutInflater getLayoutInflater() {
		if (layoutInflater == null) {
			layoutInflater = getActivity().getLayoutInflater();
		}
		return layoutInflater;
	}

	public static void setLayoutInflater(LayoutInflater layoutInflater) {
		MyApplication.layoutInflater = layoutInflater;
	}

	public static MyApplication getInstance() {
		return myapplication;
	}

	public static int getDisplayWidth() {
		return displayWidth;
	}

	public static int getDisplayHeight() {
		return displayHeight;
	}

	public static int getDensityDpi() {
		return densityDpi;
	}

	public static float getDensity() {
		return density;
	}

	public static String getSdcardCachePath() {
		return sdcardCachePath;
	}

	public static String getInnerCachePath() {
		return innerCachePath;
	}

	public static int getSmallAvatarSize() {
		return smallAvatarSize;
	}

	public static int getNormalAvatarSize() {
		return normalAvatarSize;
	}

	public static Activity getActivity() {
		return activity;
	}

	public static void setActivity(Activity activity) {
		MyApplication.activity = activity;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		myapplication = this;
		//prefs = getSharedPreferences(Constants.PREFS_NAME_APP_SETTING,
		//		MODE_PRIVATE);
		//lessonsWeek = LessonsTool.getNowWeek(this);
		initImageLoader();
		initAvatarSize();
	}

	private void initImageLoader() {
		DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
				.cacheInMemory(true).cacheOnDisc(true).build();
		File cacheDir = StorageUtils.getCacheDirectory(this);
		File cacheImg = new File(cacheDir, "IMG");
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				getApplicationContext())
				.defaultDisplayImageOptions(defaultOptions)
				.discCache(new UnlimitedDiscCache(cacheImg))
				.discCacheSize(30 * 1024 * 1024)
				// .writeDebugLogs()
				.build();
		mImageLoader = ImageLoader.getInstance();
		mImageLoader.init(config);
	}

	private void initAvatarSize() {
		WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		Display display = windowManager.getDefaultDisplay();
		// 要获取屏幕的宽和高等参数，首先需要声明一个DisplayMetrics对象，屏幕的宽高等属性存放在这个对象中
		DisplayMetrics DM = new DisplayMetrics();
		// 获取窗口管理器,获取当前的窗口,调用getDefaultDisplay()后，其将关于屏幕的一些信息写进DM对象中,最后通过getMetrics(DM)获取
		windowManager.getDefaultDisplay().getMetrics(DM);
		displayWidth = DM.widthPixels;
		displayHeight = DM.heightPixels;
		// 使用display.getOrientation() 判断横竖屏不准确
		if (displayWidth > displayHeight) {
			displayWidth = DM.heightPixels;
			displayHeight = DM.widthPixels;
		}
		DisplayMetrics metrics = new DisplayMetrics();
		display.getMetrics(metrics);
		density = metrics.density;
		densityDpi = metrics.densityDpi;
		if (densityDpi <= DisplayMetrics.DENSITY_LOW) {
		} else if (densityDpi <= DisplayMetrics.DENSITY_MEDIUM) {
		} else if (densityDpi <= DisplayMetrics.DENSITY_HIGH
				&& displayWidth <= Constants.DISPLAY_HDPI_WIDTH) {
		} else {
		}
		if (BuildConfig.DEBUG) {
			Log.v("Display Width: ", " " + displayWidth);
			Log.v("Display Height: ", " " + displayHeight);
			Log.v("Display Density: ", " " + densityDpi);
			Log.d(TAG, "initAvatarSize Finish : " + System.currentTimeMillis()
					/ 1000);
		}
	}

	private void initCachePath() {
		innerCachePath = getCacheDir().getAbsolutePath();
		File sdcardPath = android.os.Environment.getExternalStorageDirectory();
		final String cacheDir = "/Android/data/" + getPackageName() + "/cache/";
		sdcardCachePath = sdcardPath.getAbsolutePath() + File.separator
				+ cacheDir;
	}
} public class DropPopMenu {
	private ArrayList<String> itemList;
	private Context context;
	private PopupWindow popupWindow;
	private ListView listView;
	private BaseAdapter mAdapter;

	public DropPopMenu(Context context) {
		this.context = context;
		initList();
	}

	public void setWidth(int width) {
		popupWindow.setWidth(width);
	}

	public void setmAdapter(BaseAdapter mAdapter) {
		this.mAdapter = mAdapter;
		listView.setAdapter(mAdapter);
	}

	// 设置菜单项点击监听器
	public void setOnItemClickListener(
			android.widget.AdapterView.OnItemClickListener listener) {
		listView.setOnItemClickListener(listener);
	}

	// 下拉式 弹出 pop菜单 parent
	public void showAsDropDown(View parent) {
		// 保证尺寸是根据屏幕像素密度来的
		popupWindow.showAsDropDown(parent, 2, 0);
	}

	// 隐藏菜单
	public void dismiss() {
		popupWindow.dismiss();
	}

	public boolean isShowing() {
		return popupWindow.isShowing();
	}

	private void initList() {
		View popupWindow_view = LayoutInflater.from(context).inflate(
				R.layout.droppopmenu, null);
		popupWindow_view.setFocusableInTouchMode(true);
		// 设置popupWindow的布局
		popupWindow = new PopupWindow(popupWindow_view,
				WindowManager.LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.WRAP_CONTENT);
		popupWindow.setTouchable(true);
		popupWindow.setFocusable(true);
		// 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
		popupWindow.setBackgroundDrawable(new ColorDrawable(
				android.R.color.transparent));
		// 设置允许在外点击消失
		popupWindow.setOutsideTouchable(true);
		listView = (ListView) popupWindow_view
				.findViewById(R.id.droppopmenu_listView);
		popupWindow.update();
	}
} public class ToastUtil {

	private static AppMsg mToast;

	public static void showToast(Activity mContext, String text, int duration) {

		mToast = AppMsg.makeText(mContext, text, AppMsg.STYLE_INFO);
		mToast.setDuration(duration);
		mToast.show();
	}

	public static void showToast(Activity mContext, String text) {

		mToast = AppMsg.makeText(mContext, text, AppMsg.STYLE_INFO);
		mToast.setDuration(1000);
		mToast.show();
	}

	public static void showToast(Activity mContext, int resId, int duration) {
		showToast(mContext, mContext.getResources().getString(resId), duration);
	}

	public static void showToast(Activity mContext, int resId) {
		showToast(mContext, mContext.getResources().getString(resId), 1000);
	}
}
import java.io.IOException;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;
import com.umeng.analytics.MobclickAgent;
import zq.whu.zhangshangwuda.adapter.DropMenuAdapter;
import zq.whu.zhangshangwuda.base.UmengSherlockFragmentActivity;
import zq.whu.zhangshangwuda.db.WifiDb;
import zq.whu.zhangshangwuda.entity.WifiAccount;
import zq.whu.zhangshangwuda.tools.BosCrypto;
import zq.whu.zhangshangwuda.tools.Constants;
import zq.whu.zhangshangwuda.tools.LessonsTool;
import zq.whu.zhangshangwuda.ui.MainActivity;
import zq.whu.zhangshangwuda.ui.MyApplication;
import zq.whu.zhangshangwuda.ui.R;
import zq.whu.zhangshangwuda.views.DropPopMenu;
import zq.whu.zhangshangwuda.views.toast.ToastUtil;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.net.DhcpInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.text.format.Formatter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
			bottomImg.setVisibility(View.GONE);
		} else {
			bottomImg.setVisibility(View.VISIBLE);
		}
		if (dropMenu.isShowing()) {
			dropMenu.dismiss();
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rootView = MyApplication.getLayoutInflater().inflate(R.layout.wifi,
				container, false);
		return rootView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		int nowWeek = LessonsTool.getNowWeek(getActivity());
		MainActivity.MainActivityActionbar.setSubtitle("第"
				+ String.valueOf(nowWeek) + "周");
		if (isCheckNetwork()) {
			CheckNetwork();
		}
		findViews();
		InitConfig();
		Account = AccountView.getText().toString();
		Password = PasswordView.getText().toString();
		if (isAutoLogin() && !Account.equals("") && !Password.equals("")) {
			if (GetWifiStatus())
				new Thread(new OnlineThread()).start();
			else
				CheckNetwork();
		}
		initDropMenu();
	}

	public void findViews() {
		AccountView = (EditText) rootView
				.findViewById(R.id.wifi_txtAccount_EditText);
		PasswordView = (EditText) rootView
				.findViewById(R.id.wifi_txtPassword_EditText);
		LoginButton = (Button) rootView.findViewById(R.id.wifi_cmdLogin_Button);
		LoginButton.setOnClickListener(new LoginButtonListener());
		moreButton = (ImageButton) rootView
				.findViewById(R.id.wifi_txtAccount_more_Button);
		bottomImg = (ImageView) rootView.findViewById(R.id.wifi_bottom);
		Configuration cf = this.getResources().getConfiguration(); // 获取设置的配置信息
		int ori = cf.orientation; // 获取屏幕方向
		if (ori == Configuration.ORIENTATION_LANDSCAPE) {
			bottomImg.setVisibility(View.GONE);
			// 横屏
		} else if (ori == Configuration.ORIENTATION_PORTRAIT) {
			// 竖屏
			bottomImg.setVisibility(View.VISIBLE);
		}
		wifiManager = (WifiManager) getActivity().getSystemService(
				Context.WIFI_SERVICE);

	}

	private void initDropMenu() {
		// TODO Auto-generated method stub
		dropMenu = new DropPopMenu(getActivity());
		templist = WifiDb.getInstance(getActivity()).getLocalAccountsList();
		if (templist != null && templist.size() > 0) {
			list.clear();
			list.addAll(templist);
		}
		dropMenuAdapter = new DropMenuAdapter(getSherlockActivity(), list,
				dropMenu);
		dropMenu.setmAdapter(dropMenuAdapter);
		moreButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showMoreAccounts();
			}
		});
		dropMenu.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				WifiAccount account = dropMenuAdapter.getList().get(position);
				ToastUtil.showToast(getActivity(),
						String.valueOf(account.getUsername()));
				setUserAccount(account.getUsername(), account.getPassword());
				dropMenu.dismiss();
			}
		});
	}

	private void showMoreAccounts() {
		list.clear();
		list.addAll(WifiDb.getInstance(getActivity()).getLocalAccountsList());
		if (list == null || list.size() == 0)
			return;
		dropMenuAdapter.notifyDataSetChanged();
		dropMenu.setWidth(AccountView.getWidth());
		dropMenu.showAsDropDown(AccountView);
	}

	private void SaveConfig() {
		SharedPreferences.Editor localEditor = getActivity()
				.getSharedPreferences("User_Data", 0).edit();
		String str1 = AccountView.getText().toString();
		String str2 = PasswordView.getText().toString();
		try {
			str1 = BosCrypto.encrypt(BosCrypto.Excalibur, str1);