private static String buildAttachment(
      ThreadRowInfo row, boolean showImage, int imageQuality, HashSet<String> imageURLSet) {

    if (row == null || row.getAttachs() == null || row.getAttachs().size() == 0) {
      return "";
    }
    StringBuilder ret = new StringBuilder();
    ThemeManager theme = ThemeManager.getInstance();
    ret.append("<br/><br/>").append(attachment).append("<hr/><br/>");
    // ret.append("<table style='background:#e1c8a7;border:1px solid #b9986e;margin:0px 0px 10px
    // 30px;padding:10px;color:#6b2d25;max-width:100%;'>");
    if (theme.mode == theme.MODE_NIGHT) {
      ret.append(
          "<table style='background:#000000;border:1px solid #b9986e;padding:10px;color:#6b2d25;font-size:2'>");
    } else {
      ret.append(
          "<table style='background:#e1c8a7;border:1px solid #b9986e;padding:10px;color:#6b2d25;font-size:2'>");
    }
    ret.append("<tbody>");
    Iterator<Entry<String, Attachment>> it = row.getAttachs().entrySet().iterator();
    int attachmentCount = 0;
    while (it.hasNext()) {
      Entry<String, Attachment> entry = it.next();
      if (imageURLSet != null
          && imageURLSet.size() > 0
          && imageURLSet.contains(entry.getValue().getAttachurl())) {
        continue;
      }
      // String url = "http://img.nga.178.com/attachments/" +
      // entry.getValue().getAttachurl();
      ret.append("<tr><td><a href='http://" + HttpUtil.NGA_ATTACHMENT_HOST + "/attachments/");
      ret.append(entry.getValue().getAttachurl());
      ret.append("'>");
      if (showImage) {
        String attachURL =
            "http://"
                + HttpUtil.NGA_ATTACHMENT_HOST
                + "/attachments/"
                + entry.getValue().getAttachurl();
        if ("1".equals(entry.getValue().getThumb())) {
          attachURL = attachURL + ".thumb.jpg";
          // ret.append(entry.getValue().getExt());
        } else {
          attachURL = StringUtil.buildOptimizedImageURL(attachURL, imageQuality);
        }
        ret.append("<img src='");
        ret.append(attachURL);
      } else {
        ret.append("<img src='file:///android_asset/ic_offline_image.png");
      }

      ret.append("' style= 'max-width:70%;'></a>");

      ret.append("</td></tr>");
      attachmentCount++;
    }
    ret.append("</tbody></table>");
    if (attachmentCount == 0) return "";
    else return ret.toString();
  }
  private void handleAvatar(ImageView avatarIV, ThreadRowInfo row) {

    final int lou = row.getLou();
    final String avatarUrl = FunctionUtil.parseAvatarUrl(row.getJs_escap_avatar()); //
    final String userId = String.valueOf(row.getAuthorid());
    if (PhoneConfiguration.getInstance().nikeWidth < 3) {
      avatarIV.setImageBitmap(null);
      return;
    }
    if (defaultAvatar == null
        || defaultAvatar.getWidth() != PhoneConfiguration.getInstance().nikeWidth) {
      Resources res = avatarIV.getContext().getResources();
      InputStream is = res.openRawResource(R.drawable.default_avatar);
      InputStream is2 = res.openRawResource(R.drawable.default_avatar);
      this.defaultAvatar = ImageUtil.loadAvatarFromStream(is, is2);
    }

    Object tagObj = avatarIV.getTag();
    if (tagObj instanceof AvatarTag) {
      AvatarTag origTag = (AvatarTag) tagObj;
      if (origTag.isDefault == false) {
        ImageUtil.recycleImageView(avatarIV);
        // Log.d(TAG, "recycle avatar:" + origTag.lou);
      } else {
        // Log.d(TAG, "default avatar, skip recycle");
      }
    }

    AvatarTag tag = new AvatarTag(lou, true);
    avatarIV.setImageBitmap(defaultAvatar);
    avatarIV.setTag(tag);
    if (!StringUtil.isEmpty(avatarUrl)) {
      final String avatarPath = ImageUtil.newImage(avatarUrl, userId);
      if (avatarPath != null) {
        File f = new File(avatarPath);
        if (f.exists() && !isPending(avatarUrl)) {

          Bitmap bitmap = ImageUtil.loadAvatarFromSdcard(avatarPath);
          if (bitmap != null) {
            avatarIV.setImageBitmap(bitmap);
            tag.isDefault = false;
          } else f.delete();
          long date = f.lastModified();
          if ((System.currentTimeMillis() - date) / 1000 > 30 * 24 * 3600) {
            f.delete();
          }

        } else {
          final boolean downImg =
              isInWifi() || PhoneConfiguration.getInstance().isDownAvatarNoWifi();

          new AvatarLoadTask(avatarIV, null, downImg, lou, this)
              .execute(avatarUrl, avatarPath, userId);
        }
      }
    }
  }
 private static String buildHeader(ThreadRowInfo row, String fgColorStr) {
   if (row == null || (StringUtil.isEmpty(row.getSubject()) && !row.getISANONYMOUS())) return "";
   StringBuilder sb = new StringBuilder();
   sb.append("<h4 style='color:").append(fgColorStr).append("' >");
   if (!StringUtil.isEmpty(row.getSubject())) sb.append(row.getSubject());
   if (row.getISANONYMOUS())
     sb.append("<font style='color:#D00;font-weight: bold;'>").append("[匿名]").append("</font>");
   sb.append("</h4>");
   return sb.toString();
 }
 private static String buildSignature(ThreadRowInfo row, boolean showImage, int imageQuality) {
   if (row == null
       || row.getSignature() == null
       || row.getSignature().length() == 0
       || !PhoneConfiguration.getInstance().showSignature) {
     return "";
   }
   return "<br/></br>"
       + sig
       + "<hr/><br/>"
       + StringUtil.decodeForumTag(row.getSignature(), showImage, imageQuality, null);
 }
  public static String convertToHtmlText(
      final ThreadRowInfo row,
      boolean showImage,
      int imageQuality,
      final String fgColorStr,
      final String bgcolorStr) {
    HashSet<String> imageURLSet = new HashSet<String>();
    String ngaHtml =
        StringUtil.decodeForumTag(row.getContent(), showImage, imageQuality, imageURLSet);
    if (row.get_isInBlackList()) {
      ngaHtml =
          "<HTML> <HEAD><META http-equiv=Content-Type content= \"text/html; charset=utf-8 \">"
              + "<body bgcolor= '#"
              + bgcolorStr
              + "'>"
              + "<font color='red' size='2'>["
              + blacklistban
              + "]</font>"
              + "</font></body>";
    } else {
      if (imageURLSet.size() == 0) {
        imageURLSet = null;
      }
      if (StringUtil.isEmpty(ngaHtml)) {
        ngaHtml = row.getAlterinfo();
      }
      if (StringUtil.isEmpty(ngaHtml)) {

        ngaHtml = "<font color='red'>[" + hide + "]</font>";
      }
      ngaHtml =
          ngaHtml
              + buildComment(row, fgColorStr, showImage, imageQuality)
              + buildAttachment(row, showImage, imageQuality, imageURLSet)
              + buildSignature(row, showImage, imageQuality)
              + buildVote(row);
      ngaHtml =
          "<HTML> <HEAD><META http-equiv=Content-Type content= \"text/html; charset=utf-8 \">"
              + buildHeader(row, fgColorStr)
              + "<body bgcolor= '#"
              + bgcolorStr
              + "'>"
              + "<font color='#"
              + fgColorStr
              + "' size='2'>"
              + ngaHtml
              + "</font></body>";
    }
    return ngaHtml;
  }
  private static String buildComment(
      ThreadRowInfo row, String fgColor, boolean showImage, int imageQuality) {
    if (row == null || row.getComments() == null || row.getComments().size() == 0) {
      return "";
    }

    StringBuilder ret = new StringBuilder();
    ret.append("<br/></br>").append(comment).append("<hr/><br/>");
    ret.append("<table border='1px' cellspacing='0px' style='border-collapse:collapse;");
    ret.append("color:");
    ret.append(fgColor);
    ret.append("'>");

    ret.append("<tbody>");

    Iterator<ThreadRowInfo> it = row.getComments().iterator();
    while (it.hasNext()) {
      ThreadRowInfo comment = it.next();
      ret.append("<tr><td>");
      ret.append("<span style='font-weight:bold' >");
      ret.append(comment.getAuthor());
      ret.append("</span><br/>");
      ret.append("<img src='");
      String avatarUrl = FunctionUtil.parseAvatarUrl(comment.getJs_escap_avatar());
      ret.append(avatarUrl);
      ret.append("' style= 'max-width:32;'>");

      ret.append("</td><td>");
      ret.append(StringUtil.decodeForumTag(comment.getContent(), showImage, imageQuality, null));
      ret.append("</td></tr>");
    }
    ret.append("</tbody></table>");
    return ret.toString();
  }
  private boolean isComment(ThreadRowInfo row) {

    return row.getAlterinfo() == null
        && row.getAttachs() == null
        && row.getComments() == null
        && row.getJs_escap_avatar() == null
        && row.getLevel() == null
        && row.getSignature() == null;
  }
 private void handleReport(ThreadRowInfo row) {
   /*String url="http://bbs.ngacn.cc/nuke.php?func=logpost&tid="
   		+ tid + "&pid="+ row.getPid()
   		+"&log";
   ReportTask task= new ReportTask(getActivity());
   if(ActivityUtil.isGreaterThan_2_3_3())
   	RunParallen(task, url);
   else
   	task.execute(url);*/
   DialogFragment df = new ReportDialogFragment();
   Bundle args = new Bundle();
   args.putInt("tid", tid);
   args.putInt("pid", row.getPid());
   df.setArguments(args);
   df.show(getFragmentManager(), null);
 }
  @Override
  public boolean onContextItemSelected(MenuItem item) {

    Log.d(TAG, "onContextItemSelected,tid=" + tid + ",page=" + page);
    PagerOwnner father = null;
    try {
      father = (PagerOwnner) getActivity();
    } catch (ClassCastException e) {
      Log.e(TAG, "father activity does not implements interface " + PagerOwnner.class.getName());
      return true;
    }

    if (father == null) return false;

    if (father.getCurrentPage() != page) {
      return false;
    }

    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    int position = this.listview.getCheckedItemPosition();
    if (info != null) {
      position = info.position;
    }
    if (position < 0 || position >= listview.getAdapter().getCount()) {
      Toast.makeText(getActivity(), R.string.floor_error, Toast.LENGTH_LONG).show();
      position = 0;
    }
    StringBuffer postPrefix = new StringBuffer();
    String tidStr = String.valueOf(this.tid);

    ThreadRowInfo row = (ThreadRowInfo) listview.getItemAtPosition(position);
    if (row == null) {
      Toast.makeText(getActivity(), R.string.unknow_error, Toast.LENGTH_LONG).show();
      return true;
    }
    String content = row.getContent();
    final String name = row.getAuthor();
    String mention = null;
    Intent intent = new Intent();
    switch (item.getItemId())
    // if( REPLY_POST_ORDER ==item.getItemId())
    {
      case R.id.quote_subject:
        final String quote_regex = "\\[quote\\]([\\s\\S])*\\[/quote\\]";
        final String replay_regex =
            "\\[b\\]Reply to \\[pid=\\d+,\\d+,\\d+\\]Reply\\[/pid\\] Post by .+?\\[/b\\]";
        content = content.replaceAll(quote_regex, "");
        content = content.replaceAll(replay_regex, "");
        final String postTime = row.getPostdate();

        if (!content.trim().endsWith("[/url]")) {
          if (content.length() > 100) content = content.substring(0, 99) + ".......";
        }
        content = StringUtil.unEscapeHtml(content);

        if (row.getPid() != 0) {
          mention = name;
          postPrefix.append("[quote][pid=");
          postPrefix.append(row.getPid());
          postPrefix.append(',').append(tidStr).append(",").append(page);
          postPrefix.append("]"); // Topic
          postPrefix.append("Reply");
          postPrefix.append("[/pid] [b]Post by ");
          postPrefix.append(name);
          postPrefix.append(" (");
          postPrefix.append(postTime);
          postPrefix.append("):[/b]\n");
          postPrefix.append(content);
          postPrefix.append("[/quote]\n");
        }

        // case R.id.r:

        if (!StringUtil.isEmpty(mention)) intent.putExtra("mention", mention);
        intent.putExtra("prefix", StringUtil.removeBrTag(postPrefix.toString()));
        intent.putExtra("tid", tidStr);
        intent.putExtra("action", "reply");
        intent.setClass(getActivity(), PostActivity.class);
        startActivity(intent);
        if (PhoneConfiguration.getInstance().showAnimation)
          getActivity().overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
        break;
      case R.id.edit:
        if (isComment(row)) {
          Toast.makeText(getActivity(), R.string.cannot_eidt_comment, Toast.LENGTH_SHORT).show();
          break;
        }
        Intent intentModify = new Intent();
        intentModify.putExtra("prefix", StringUtil.unEscapeHtml(StringUtil.removeBrTag(content)));
        intentModify.putExtra("tid", tidStr);
        String pid = String.valueOf(row.getPid()); // getPid(map.get("url"));
        intentModify.putExtra("pid", pid);
        intentModify.putExtra("title", StringUtil.unEscapeHtml(row.getSubject()));
        intentModify.putExtra("action", "modify");
        intentModify.setClass(getActivity(), PostActivity.class);
        startActivity(intentModify);
        if (PhoneConfiguration.getInstance().showAnimation)
          getActivity().overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
        break;
      case R.id.copy_to_clipboard:
        // if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB )
        // {
        android.text.ClipboardManager cbm =
            (android.text.ClipboardManager)
                getActivity().getSystemService(Activity.CLIPBOARD_SERVICE);
        cbm.setText(StringUtil.removeBrTag(content));
        // }else{
        // android.content.ClipboardManager  cbm = (android.content.ClipboardManager)
        // getSystemService(CLIPBOARD_SERVICE);
        // cbm.setPrimaryClip(ClipData.newPlainText("content", content));
        // }

        Toast.makeText(getActivity(), R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show();
        break;
      case R.id.show_this_person_only:
        Intent intentThis = new Intent();
        intentThis.putExtra("tab", "1");
        intentThis.putExtra("tid", tid);
        intentThis.putExtra("authorid", row.getAuthorid());

        intentThis.setClass(getActivity(), PhoneConfiguration.getInstance().articleActivityClass);
        startActivity(intentThis);
        if (PhoneConfiguration.getInstance().showAnimation)
          getActivity().overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);

        // restNotifier.reset(0, row.getAuthorid());
        // ActivityUtil.getInstance().noticeSaying(getActivity());

        break;
      case R.id.show_whole_thread:
        ResetableArticle restNotifier = null;
        try {
          restNotifier = (ResetableArticle) getActivity();
        } catch (ClassCastException e) {
          Log.e(
              TAG,
              "father activity does not implements interface " + ResetableArticle.class.getName());
          return true;
        }
        restNotifier.reset(0, 0, row.getLou());
        ActivityUtil.getInstance().noticeSaying(getActivity());
        break;
      case R.id.post_comment:
        final String dialog_tag = "post comment";
        FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
        Fragment prev = getActivity().getSupportFragmentManager().findFragmentByTag(dialog_tag);
        if (prev != null) {
          ft.remove(prev);
        }
        DialogFragment df = new PostCommentDialogFragment();
        Bundle b = new Bundle();
        b.putInt("pid", row.getPid());
        b.putInt("tid", this.tid);
        df.setArguments(b);
        df.show(ft, dialog_tag);

        break;
      case R.id.report:
        handleReport(row);
        break;
      case R.id.search_post:
        intent.putExtra("searchpost", 1);
      case R.id.search_subject:
        intent.putExtra("authorid", row.getAuthorid());
        intent.setClass(getActivity(), PhoneConfiguration.getInstance().topicActivityClass);
        startActivity(intent);
        if (PhoneConfiguration.getInstance().showAnimation)
          getActivity().overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);

        break;
      case R.id.item_share:
        intent.setAction(Intent.ACTION_SEND);
        intent.setType("text/plain");
        String shareUrl = "http://bbs.ngacn.cc/read.php?";
        if (row.getPid() != 0) {
          shareUrl = shareUrl + "pid=" + row.getPid();
        } else {
          shareUrl = shareUrl + "tid=" + tid;
        }
        intent.putExtra(Intent.EXTRA_TEXT, shareUrl);
        String text = getResources().getString(R.string.share);
        getActivity().startActivity(Intent.createChooser(intent, text));
        break;
    }
    return true;
  }
 private static String buildVote(ThreadRowInfo row) {
   if (row == null || StringUtil.isEmpty(row.getVote())) {
     return "";
   }
   return "<br/><hr/>" + "本楼有投票/投注内容,长按本楼在菜单中点击投票/投注按钮";
 }
  public View getView(int position, View view, ViewGroup parent) {
    final ThreadRowInfo row = data.getRowList().get(position);

    int lou = -1;
    if (row != null) lou = row.getLou();
    ViewHolder holder = null;
    boolean needin = false;
    SoftReference<View> ref = viewCache.get(position);
    View cachedView = null;
    if (ref != null) {
      cachedView = ref.get();
    }
    if (cachedView != null) {
      if (((ViewHolder) cachedView.getTag()).position == position) {
        Log.d(TAG, "get view from cache ,floor " + lou);
        return cachedView;
      } else {
        view = LayoutInflater.from(activity).inflate(R.layout.relative_aritclelist, parent, false);
        holder = initHolder(view);
        holder.position = position;
        view.setTag(holder);
        viewCache.put(position, new SoftReference<View>(view));
      }
    } else {
      view = LayoutInflater.from(activity).inflate(R.layout.relative_aritclelist, parent, false);
      holder = initHolder(view);
      holder.position = position;
      view.setTag(holder);
      viewCache.put(position, new SoftReference<View>(view));
    }
    if (!PhoneConfiguration.getInstance().showReplyButton) {
      holder.viewBtn.setVisibility(View.GONE);
    } else {
      MyListenerForReply myListenerForReply = new MyListenerForReply(position, data, activity);
      holder.viewBtn.setOnClickListener(myListenerForReply);
    }
    ThemeManager theme = ThemeManager.getInstance();
    int colorId = theme.getBackgroundColor(position);
    view.setBackgroundResource(colorId);

    // colorId = theme.getBackgroundColor(2);

    if (row == null) {
      return view;
    }

    handleAvatar(holder.avatarIV, row);

    int fgColorId = ThemeManager.getInstance().getForegroundColor();
    final int fgColor = parent.getContext().getResources().getColor(fgColorId);

    FunctionUtil.handleNickName(row, fgColor, holder.nickNameTV, activity);

    final int bgColor = parent.getContext().getResources().getColor(colorId);

    final WebView contentTV = holder.contentTV;

    final String floor = String.valueOf(lou);
    TextView floorTV = holder.floorTV;
    floorTV.setText("[" + floor + " 楼]");
    floorTV.setTextColor(fgColor);

    if (!StringUtil.isEmpty(row.getFromClientModel())) {
      MyListenerForClient myListenerForClient =
          new MyListenerForClient(position, data, activity, parent);
      String from_client_model = row.getFromClientModel();
      if (from_client_model.equals("ios")) {
        holder.clientBtn.setImageResource(R.drawable.ios); // IOS
      } else if (from_client_model.equals("wp")) {
        holder.clientBtn.setImageResource(R.drawable.wp); // WP
      } else if (from_client_model.equals("unknown")) {
        holder.clientBtn.setImageResource(R.drawable.unkonwn); // 未知orBB
      }
      holder.clientBtn.setVisibility(View.VISIBLE);
      holder.clientBtn.setOnClickListener(myListenerForClient);
    }
    if (ActivityUtil.isLessThan_4_3()) {
      new Thread(
              new Runnable() {
                public void run() {
                  FunctionUtil.handleContentTV(
                      contentTV, row, bgColor, fgColor, activity, null, client);
                }
              })
          .start();
    } else if (ActivityUtil.isLessThan_4_4()) {
      ((Activity) parent.getContext())
          .runOnUiThread(
              new Runnable() {
                public void run() {
                  FunctionUtil.handleContentTV(
                      contentTV, row, bgColor, fgColor, activity, null, client);
                }
              });
    } else {
      FunctionUtil.handleContentTV(contentTV, row, bgColor, fgColor, activity, null, client);
    }
    TextView postTimeTV = holder.postTimeTV;
    postTimeTV.setText(row.getPostdate());
    postTimeTV.setTextColor(fgColor);
    if (needin) {
      view.invalidate();
    }
    return view;
  }