<%@ page contentType="text/html;charset=GBK" %>
<%
/**
 *	$RCSfile: search.jsp,v $
 *	$Revision: 1.3 $
 *	$Date: 2002/09/30 14:56:16 $
 */
%>

<%@ page import="java.util.*,
                 com.jivesoftware.forum.*,
                 com.jivesoftware.forum.util.*"
    errorPage="error.jsp"
%>

<%@ include file="global.jsp" %>

<%! // global variables, methods, etc

    static final int DEFAULT_RESULT_COUNT = 10;
    static final int[] RESULT_COUNTS = { 10, 15, 30 };

    static String printForumParams(long[] forumIDs) {
        StringBuffer buf = new StringBuffer(50);
        for (int i=0; i<forumIDs.length; i++) {
            buf.append("forums=").append(forumIDs[i]);
            if ((i+1) < forumIDs.length) {
                buf.append("&");
            }
        }
        return buf.toString();
    }
%>

<%  // Get parameters
    //long forumID = ParamUtils.getLongParameter(request,"forum",-1L);
    long[] forumIDs = ParamUtils.getLongParameters(request,"forums",-1L);
    long userID = ParamUtils.getLongParameter(request,"user",-1L);
    String username = ParamUtils.getParameter(request,"user");
    String queryText = ParamUtils.getParameter(request,"q");
    long dateLo = ParamUtils.getLongParameter(request,"dateLo",-1L);
    long dateHi = ParamUtils.getLongParameter(request,"dateHi",-1L);
    boolean search = ParamUtils.getBooleanParameter(request,"search");
    boolean options = ParamUtils.getBooleanParameter(request,"options");
    boolean advanced = ParamUtils.getBooleanParameter(request,"adv");
    int start = ParamUtils.getIntParameter(request,"start",0);
    int range = ParamUtils.getIntParameter(request,"range",DEFAULT_RESULT_COUNT);

    // null check
    if (forumIDs == null) {
        forumIDs = new long[0];
    }

    // Forum object. If it is null, that means we're either doing a global
    // search over all forums, or searching a set of forums.
    Forum forum = null;

    // Create the query object
    Query query = null;
    if (forumIDs.length == 0) {
        // No forum specified so we search all.
        query = myEnv.getForumFactory().createQuery();
    }
    else if (forumIDs.length == 1) {
        // All forums
        if (forumIDs[0] == -1L) {
            query = myEnv.getForumFactory().createQuery();
        }
        // A specific forum
        else if (forumIDs[0] > -1) {
            forum = myEnv.getForumFactory().getForum(forumIDs[0]);
            query = forum.createQuery();
        }
        else {
            throw new ForumNotFoundException("论坛 " + forumIDs[0] + "不能加载");
        }
    }
    // A list of forums
    else {
        // See if any of the forumIDs is -1. If it is, do a global search
        boolean doGlobal = false;
        for (int i=0; i<forumIDs.length; i++) {
            if (forumIDs[i] == -1L) {
                doGlobal = true;
                break;
            }
        }
        if (doGlobal) {
            query = myEnv.getForumFactory().createQuery();
        }
        // otherwise, we're searching multiple forums:
        else {
            Forum[] forums = new Forum[forumIDs.length];
            for (int i=0; i<forumIDs.length; i++) {
                try {
                    forums[i] = myEnv.getForumFactory().getForum(forumIDs[i]);
                } catch (Exception e) {}
            }
            query = myEnv.getForumFactory().createQuery(forums);
        }
    }

    // Try to load a user (try by userID first, then try username). If the user
    // is loaded successfully, we'll add it to the query object so the results
    // returned are messages posted by this user.
    User user = null;
    UserManager userManager = myEnv.getForumFactory().getUserManager();
    try {
        user = userManager.getUser(userID);
    }
    catch (UserNotFoundException unfe) {
        try {
            user = userManager.getUser(username);
        }
        catch (UserNotFoundException ignored) {}
    }
    if (user != null) {
        userID = user.getID();
        username = user.getUsername();
        query.filterOnUser(user);
    }
%>

<%  String title = "论坛 - 搜索"; %>
<%@ include file="header.jsp" %>

<table cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
    <td valign="top" width="98%">

    <font face="<%= JiveGlobals.getJiveProperty("skin.default.fontFace") %>" color="<%= JiveGlobals.getJiveProperty("skin.default.linkColor") %>">
    <b>搜索</b>
    </font>
    <br>

    <font size="-1" face="<%= JiveGlobals.getJiveProperty("skin.default.fontFace") %>" color="<%= JiveGlobals.getJiveProperty("skin.default.linkColor") %>">
    <b>
    <a href="<%= JiveGlobals.getJiveProperty("skin.default.homeURL") %>"
     >首页</a>
    &raquo;
    <a href="index.jsp" class="header" title="返回论坛列表"
    >论坛</a>
<%  if (forum != null) { %>
    &raquo;
    <a href="forum.jsp?forum=<%= forum.getID() %>" class="header" title="返回论坛主题列表"
    ><%= forum.getName() %></a>
<%  } else { %>
    &raquo;
    <a href="search.jsp?forums=-1" class="header"
    >搜索所有论坛</a>
<%  } %>
    </b>
    </font>
    </td>
    <td width="1%"><img src="images/blank.gif" width="10" height="1" border="0"></td>
    <td valign="top" width="1%" align="center">
    <%@ include file="loginbox.jsp" %>
    </td>
</tr>
</table>

<center>

<form action="search.jsp" name="searchForm" method="post">
<%  if (forum != null) { %>
<input type="hidden" name="forums" value="<%= forum.getID() %>">
<%  } %>
<input type="hidden" name="search" value="true">
<input type="hidden" name="range" value="<%= range %>">

<table bgcolor="<%= JiveGlobals.getJiveProperty("skin.default.tableBorderColor") %>"
 cellpadding="0" cellspacing="0" border="0">
<tr><td>
    <table bgcolor="<%= JiveGlobals.getJiveProperty("skin.default.tableBorderColor") %>"
     cellpadding="5" cellspacing="1" border="0">
    <tr bgcolor="<%= JiveGlobals.getJiveProperty("skin.default.prefsBgColor") %>">
        <td>
        <input type="text" name="q" size="40" maxlength="60"
         value="<%= ((queryText!=null)?queryText:"") %>">
        <input type="submit" value="Search">
        </td>
    </tr>
    <tr bgcolor="<%= JiveGlobals.getJiveProperty("skin.default.prefsHeaderBgColor") %>">
        <td>
        <font class=p2 face="<%= JiveGlobals.getJiveProperty("skin.default.fontFace") %>">
        <a href="search.jsp?<%= printForumParams(forumIDs) %>&q=<%= (queryText!=null)?java.net.URLEncoder.encode(queryText):"" %>&options=<%= (options?false:true) %>&range=<%= range %>"
        ><%= (options?"&laquo; Hide":"&raquo; Show") %> 选 项</a>
        </font>
        </td>
    </tr>
    <%  if (options) { %>
    <tr bgcolor="<%= JiveGlobals.getJiveProperty("skin.default.prefsHeaderBgColor") %>">
        <td>
        <font class=p2 face="<%= JiveGlobals.getJiveProperty("skin.default.fontFace") %>">
        每页显示
        <select class=p2 name="range">
<%      for (int i=0; i<RESULT_COUNTS.length; i++) {
            String selected = "";
            if (range == RESULT_COUNTS[i]) {
                selected = " selected";
            }
%>
        <option value="<%= RESULT_COUNTS[i] %>"<%= selected %>><%= RESULT_COUNTS[i] %>
        <%  } %>
        </select>
        个结果。
        </font>
        </td>
    </tr>
    <%  } %>
    </table>
</td></tr>
</table>

</form>

</center>

<font size="-1">

<%  if (search) { %>

    <p>

<%      // Set the query text, do a search:
        query.setQueryString(queryText);
        // execute the query
        Iterator results = query.results(start,range);

        // display results
        if (!results.hasNext()) {
%>
        <font class=p2 face="<%= JiveGlobals.getJiveProperty("skin.default.fontFace") %>">
        <center><i>没有匹配结果</i></center>
        </font>
        <p>
<%      }
        else {
            int numResults = query.resultCount();
%>
        <font class=p2 face="<%= JiveGlobals.getJiveProperty("skin.default.fontFace") %>">
        对于 "<b><%= queryText %></b>"搜索到 <%= numResults %> 个结果.
        每页显示 <%= range %> 个结果.
        </font>
        <p>

<%      int count = start + 1;
        String[] queryWords = StringUtils.toLowerCaseWordArray(queryText);
        int messageRange = myEnv.du.getMessageRange(request, response, pageUser);
        while (results.hasNext()) {
            ForumMessage message = (ForumMessage)results.next();
            String body = StringUtils.escapeHTMLTags(message.getUnfilteredBody());
	    body = StringUtils.chopAtWord(body, 150) + " ...";
	    body = StringUtils.highlightWords(body, queryWords, "<font style='background-color:#ffff00'><b>", "</b></font>");
            long mID = message.getID();
            long tID = message.getForumThread().getID();
            long fID = message.getForumThread().getForum().getID();
            Forum f = myEnv.getForumFactory().getForum(fID);
            ForumThread t = f.getThread(tID);
            int messageCount = t.getMessageCount();
            int numPages = (int)Math.ceil((double)messageCount/(double)messageRange);
            int msgStart = (numPages-1) * messageRange;
            User author = message.getUser();
            String authorUsername = "<i>客人</i>";
            if (author != null) {
                authorUsername = author.getUsername();
            }
%>
        <table cellpadding="2" cellspacing="0" border="0">
        <tr>
        <td valign="top">
            <font class=p2 face="<%= JiveGlobals.getJiveProperty("skin.default.fontFace") %>">
            <%= count++ %>)
            </font>
        </td>
        <td>
            <font class=p2 face="<%= JiveGlobals.getJiveProperty("skin.default.fontFace") %>">
            <a href="thread.jsp?forum=<%= fID %>&thread=<%= tID %>&message=<%= mID %>&redirect=true&hilite=true&q=<%= java.net.URLEncoder.encode(queryText) %>"
            ><%= message.getSubject() %></a>
            <br>
            <font color="#666666" face="<%= JiveGlobals.getJiveProperty("skin.default.fontFace") %>">
            发表时间: <%= SkinUtils.formatDate(request,response,pageUser,message.getCreationDate()) %>
            发表人: <%= authorUsername %>
            </font>
            </font>
        </td>
        </tr>
        </table>
        <ul>
        <font class=p2 face="<%= JiveGlobals.getJiveProperty("skin.default.fontFace") %>">
        <%= body %>
        </font>
        </ul>
<%      } // end while loop
%>

</font>

<%  // Code for displaying the correct search result page links
	int totalPages = 1;
    if (start > 0 && start%range == 0) {
        totalPages = (start/range);
    }
    else {
        totalPages = (start/range) + 1;
    }
    int i = totalPages;

	int lTotal = i-1;
	int rTotal = totalPages-i;
	int lCount, rCount;

	if (i < 5) {
        lCount = lTotal;
    }
	else {
        lCount = 5;
    }

	if (i+5 > totalPages) {
		rCount = totalPages-i;
		//now, add as much as we can to other side
		lCount += 5-(totalPages-i) > lTotal-lCount? lTotal-lCount: 5-(totalPages-i);
	}
	else {
		rCount = 5;
		//Add in more to right if possible;
		if (lCount < 5) {
			rCount += 5-lCount > rTotal-rCount? rTotal-rCount: 5-lCount;
		}
	}
    String href = "search.jsp?" + printForumParams(forumIDs)
            + "&q=" + java.net.URLEncoder.encode(queryText) + "&range=" + range
            + "&search=true";
%>
<center>
<table cellpadding="4" cellspacing="2" border="0">
<tr>
    <td>
    <font class=p2 face="<%= JiveGlobals.getJiveProperty("skin.default.fontFace") %>">
    <%	if ((start-range) >= 0) { %>
    <a href="<%= href %>&start=<%= (start-range) %>" title="上一页搜索结果"><img src="images/prev.gif" width="10" height="10" alt="上一页搜索结果" border="0"></a>
    <a href="<%= href %>&start=<%= (start-range) %>">上一页</a>
    <%	} %>
    &nbsp;
    </font>
    </td>
<%      for (int idx=(i-lCount); idx<=(i+rCount); idx++) {
            boolean onCurrent = !((range*(idx-1))!=start);
            String color = (onCurrent)?"blue":"red";
%>
    <td align="center">
    <font class=p2 face="<%= JiveGlobals.getJiveProperty("skin.default.fontFace") %>">
    <%  if (onCurrent) { %>
    <a href="<%= href %>&start=<%= range*(idx-1) %>"
     style="color:#000000;background-color:#cccccc;"><%= idx %></a>
    <%  } else { %>
    <a href="<%= href %>&start=<%= range*(idx-1) %>"
     ><%= idx %></a>
    <%  } %>
    </font>
    </td>
    <%	} %>
    <td>
    <font class=p2 face="<%= JiveGlobals.getJiveProperty("skin.default.fontFace") %>">
    &nbsp;
    <%	if( (start+range) < numResults) { %>
    <a href="<%= href %>&start=<%= (start+range) %>" title="下一页搜索结果">下一页</a>
    <a href="<%= href %>&start=<%= (start+range) %>"><img src="images/next.gif" width="10" height="10" alt="下一页搜索结果" border="0"></a>
    <%	} %>
    </font>
    </td>
</tr>
</table>
</center>

<%      } // end else there are results
%>

<%  } // end search block %>

<!--
<ul>
    <li>Ability to search by all forums
    <li>Ability to search one forum
    <li>Ability to search a set of forums
    <li>Ability to search within a given thread
    <li>Search within date range
    <li>Search by a user
</ul>
-->

<script language="JavaScript" type="text/javascript">
<!--
document.searchForm.q.focus();
//-->
</script>

<br>

<%@ include file="footer.jsp" %>