<%@page contentType="text/html;charset=UTF-8" pageEncoding="ISO-8859-1" session="true"%>
<%@page errorPage="Exception.jsp"
%><%@page import="com.fujitsu.iflow.dbadapter.dataobjects.SearchStruct"
%><%@page import="com.fujitsu.iflow.dbadapter.dataobjects.SearchUdaStruct"
%><%@page import="com.fujitsu.iflow.model.bpm.BPMSession"
%><%@page import="com.fujitsu.iflow.model.bpmcore.BPMSessionImpl"
%><%@page import="com.fujitsu.iflow.model.util.QuickForm"
%><%@page import="com.fujitsu.iflow.model.util.URLEncoder"
%><%@page import="com.fujitsu.iflow.model.workflow.DataItem"
%><%@page import="com.fujitsu.iflow.model.workflow.DataItemRef"
%><%@page import="com.fujitsu.iflow.model.workflow.Filter"
%><%@page import="com.fujitsu.iflow.model.workflow.WFObjectFactory"
%><%@page import="com.fujitsu.iflow.model.workflow.WFObjectList"
%><%@page import="com.fujitsu.iflow.model.workflow.WorkItem"
%><%@page import="com.fujitsu.iflow.server.dataobjects.FilterEnum"
%><%@page import="com.fujitsu.iflow.server.dataobjects.WorkItemStatesEnum"
%><%@page import="java.io.Writer"
%><%@page import="java.text.SimpleDateFormat"
%><%@page import="java.util.Date"
%><%@page import="java.util.Enumeration"
%><%@page import="java.util.StringTokenizer"
%><%@page import="javax.servlet.http.Cookie"
%><%@page import="java.text.DateFormat"
%><%
    request.setCharacterEncoding("UTF-8");request.getParameterNames(); //Need dummy call for WL9.1
    bps = (BPMSession) session.getAttribute("BPMSession");
    if (bps == null) {
        %><jsp:include page="PasswordPanel.jsp" flush="true"/><%
        return;
    }
    transportType = (String) session.getAttribute("TransportType");
%>
<html>
<head>
<title>Interstage Business Process Manager | Work List</title>
<jsp:include page="StyleSheet.jsp" flush="true"/>
<script language="javascript" src="styles/clockscripts.js"></script>
<script>
function setSelection(wiForm, selPage)
{
    wiForm.pgNum.value = selPage;
    wiForm.submit();
}
function sort(field, order)
{
    if (document.wiForm.filterId.value == 13) { // MyCompleted
        if (field != "Activity Name") {
            alert("For My Completed Activities, sorting is only supported on Activity Name");
            return;
        }
    }
    document.wiForm.sort.value = field;
    document.wiForm.asc.value = order;
    document.wiForm.pgNum.value = 1;
    document.wiForm.submit();

}
function trimString (str) {
  str = this != window? this : str;
  return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}
function save()
{
    document.saveForm.srchnm.value = trimString(document.saveForm.srchnm.value);
    if (document.saveForm.srchnm.value == null || document.saveForm.srchnm.value == "" ) {
        alert("Please specify a search name");
        document.saveForm.srchnm.focus();
        return;
    }
    if (document.saveForm.srchnm.value.indexOf(",") >= 0 ) {
        alert("Illegal character: ',' not allowed in search name");
        document.saveForm.srchnm.focus();
        return;
    }
    var savedSearches = document.saveForm.searchesStr.value.split(",");
    for (i=0; i < savedSearches.length; i++) {
        if (savedSearches[i].toLowerCase() == document.saveForm.srchnm.value.toLowerCase()) {
            alert("Could not save this search, since a search with the same name exists already");
            document.saveForm.srchnm.focus();
            return;
        }
    }
    document.wiForm.srchnm.value = document.saveForm.srchnm.value;
    document.cookie = "SaveCookie=true";
    document.wiForm.submit();
}
function bodyLoaded()
{
    // remove SaveCookie
    var date = new Date();
    date.setTime(date.getTime()-(24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
    document.cookie = "SaveCookie=false"+expires;
}
</script>
</head>

<body class="bodyClass" onload="bodyLoaded()">
<center>
<%!
    BPMSession bps = null;
    String transportType = null;
    String srchnm = null;
    int filterId = Filter.MyActiveWorkItems;
    int pageNumber = 1;
    int pageSize = 20;
    WorkItem[] tasks = new WorkItem[0];
    String tableTitle = "My Active Activities";
    String sortField = "Id";
    String sortAsc = "true";
    String filterName = "";
    String planName = "";
    String piName = "";
    String piopStr = "";
    String wiName = "";
    String wiopStr = "";
    String assigneeName = "";
    String asnopStr = "";
    String udaFilters = "";
    SearchUdaStruct[] searchUdaStruct = null;
    String displayUdasStr = "";
    String displayUdas[] = null;
    String displayFieldsStr = "";
    String displayFields[] = null;
    final String defaultFields = "Id,Activity Name,Process Instance Name,Created,Status,Due Date,Assignee";
    String hFrmCrt = "";
    String hToCrt = "";
    String hFrmDue = "";
    String hToDue = "";
    boolean trace=false;
%>
<%
    session.removeAttribute("Forms");
    session.removeAttribute("completedTasks");

    // SETUP GLOBALS
    String pageNumberStr = request.getParameter("pgNum");
    if (pageNumberStr == null || pageNumberStr.trim().length() == 0) {
        // no pageNumber : Entry from "Worklist" tab. Look for default search.
        srchnm = getDefaultSearch();
        if(srchnm == null){
            // Default search not found. Use default values.
            setDefaultValues();
        }
    }
    else {
        readParams(request);
    }

    cleanupGlobals();

    // Save search if the cookie is set
    Cookie cookies[] = request.getCookies();
    String doSave="false";
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
           if (cookies[i].getName().equals("SaveCookie")) {
               doSave = cookies[i].getValue();
           }
        }
    }
    if (doSave.equals("true")) {
        SearchStruct s = new SearchStruct();
        s.userId = bps.getUserName();
        s.queryName = srchnm;
        s.queryType = SearchStruct.TYPE_WI;
        s.preDefFilter = Integer.toString(filterId);
        s.pdNames = planName;
        s.piNames = piName;
        s.wiNames = wiName;
        s.assignees = assigneeName;
        s.piOp = piopStr;
        s.wiOp = wiopStr;
        s.asnOp = asnopStr;
        s.sortBy = sortField;
        s.sortOrder = sortAsc;
        s.pageSize = pageSize;
        s.udaFilter = searchUdaStruct;
        s.disUdas = displayUdasStr;
        s.disColums = displayFieldsStr;
        s.createdStartDate = hFrmCrt;
        s.createdEndDate = hToCrt;
        s.dueDateStarts = hFrmDue;
        s.dueDateEnds = hToDue;
        bps.createSearch(s);
    }

    // Now get the workitems
    tasks = getWorkItems(filterId, pageNumber, pageSize, sortField, sortAsc, trace, out);
    if (filterId ==  Filter.MyCompletedWorkItems) {
        //setting a variable in a session does not work if the user has two browsers open!
        session.setAttribute("completedTasks", tasks);
    }

    // Now display
    String[] bcolor = {"evenrow","oddrow"};
    int nextColor = 0;
    String rowColor = bcolor[nextColor];
    session.setAttribute("TabIndex","0");

%>
    <jsp:include page="Header.jsp" flush="true"/><br>
    <jsp:include page="WorkListHeader.jsp" flush="true"/>


  <table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0">
    <td valign="top">
      <table width="90%" border="0" cellpadding="2" cellspacing="2" align="center" class="tableclass">
        <tr>
          <form name="wiForm" method="post" action="WorkList.jsp">
            <input type="hidden" name="pgNum" value="<%= pageNumber %>">
            <input type="hidden" name="filterId" value="<%= filterId %>">
            <input type="hidden" name="sort" value="<%= sortField %>">
            <input type="hidden" name="asc" value="<%= sortAsc %>">
            <input type="hidden" name="pd" value="<%= planName %>">
            <input type="hidden" name="pin" value="<%= piName %>">
            <input type="hidden" name="piop" value="<%= piopStr %>">
            <input type="hidden" name="win" value="<%= wiName %>">
            <input type="hidden" name="wiop" value="<%= wiopStr %>">
            <input type="hidden" name="asn" value="<%= assigneeName %>">
            <input type="hidden" name="asnop" value="<%= asnopStr %>">
            <input type="hidden" name="pg" value="<%= pageSize %>">
            <input type="hidden" name="srchnm" value="<%= srchnm %>">
            <input type="hidden" name="dspUda" value="<%= displayUdasStr %>">
            <input type="hidden" name="dspFields" value="<%= displayFieldsStr %>">
            <input type="hidden" name="filterUdas" value="<%=udaFilters%>">
            <input type="hidden" name="hFrmCrt" value="<%=hFrmCrt%>">
            <input type="hidden" name="hToCrt" value="<%=hToCrt%>">
            <input type="hidden" name="hFrmDue" value="<%=hFrmDue%>">
            <input type="hidden" name="hToDue" value="<%=hToDue%>">

            <td align="left">
<%
    String btnOption = "";
    if (pageNumber > 1) {
        btnOption = "onClick=\"setSelection(this.form, " + (pageNumber-1) +")\"";
    }
    else {
        btnOption = "disabled";
    }
%>
              <input value="Prev Page" <%= btnOption %> type="button" class="core-button">
              &nbsp;&nbsp;
<%
    if (tasks.length != pageSize)
        btnOption = "disabled";
    else
        btnOption = "onClick=\"setSelection(this.form, " + (pageNumber+1) +")\"";
%>
                <input value="Next Page" <%= btnOption %> type="button" class="core-button">
                &nbsp;&nbsp;
              </td>
            </form>
            <td align="right">
              <form name="main" method="GET" action="AdvSearch.jsp">
                <input type="hidden" name="qtype" value="WI"/>
                <input value="Advanced Search..." type="submit" class="core-button">
              </form>
            </td>
        </tr>
        <tr>
          <td colspan="2">
            <TABLE bgcolor="#CCCCCC" border="0" cellpadding="4" cellspacing="1" class="tableClass" width="100%" align="center">
              <tr align="center" class="headrow">
                <td bgcolor="#EEEEEE" style="filter:progid:DXImageTransform.Microsoft.Gradient(startColorStr='#FFFFFF', endColorStr='#6699CC', gradientType='1')"><font color="#000000" size="2"><%=tableTitle%></font></td>
              </tr>
            </table>
            <TABLE bgcolor="#CCCCCC" border="0" cellpadding="4" cellspacing="1" class="tableClass" width="100%" align="center">
              <tr align="center" class="headrow" bgcolor="#0066CC">
<%
    for (int i = 0; i < displayFields.length; i++)
    {
        String fieldName = displayFields[i].trim();
%>
                <th>
                    <TABLE bgcolor="#0066CC" border="0" cellpadding="0" cellspacing="0">
                        <tr align="center" class="headrow" bgcolor="#0066CC">
                            <td rowspan="2"><%=fieldName%>&nbsp;</td>
                            <td><input type="image" src="images/asc.gif" onclick="sort('<%=fieldName%>', true)"></td>
                        </tr>
                        <tr>
                            <td><input type="image" src="images/desc.gif" onclick="sort('<%=fieldName%>', false)"></td>
                        </tr>
                    </TABLE>
                </th>
<%
    }

    for (int i = 0; i < displayUdas.length; i++)
    {
        int pos = displayUdas[i].indexOf("(");
        String udaName = displayUdas[i].substring(0, pos).trim();
        String udaType = displayUdas[i].substring(pos+1, displayUdas[i].indexOf(")")).trim();
%>
                <th>
                    <TABLE bgcolor="#0066CC" border="0" cellpadding="0" cellspacing="0">
                        <tr align="center" class="headrow" bgcolor="#0066CC">
                            <td><%=udaName%>&nbsp;</td>
                            <td><input type="image" src="images/asc.gif" onclick="sort('<%=displayUdas[i]%>', true)"></td>
                        </tr>
                        <tr align="center" class="headrowsmall" bgcolor="#0066CC">
                            <td>&nbsp;(<%=udaType%>)&nbsp;</td>
                            <td><input type="image" src="images/desc.gif" onclick="sort('<%=displayUdas[i]%>', false)"></td>
                        </tr>
                    </TABLE>
                </th>
<%
    }
%>
              </tr>
              <%
   for (int i = 0; i < tasks.length; i++)
   {
        rowColor = bcolor[nextColor];
        nextColor = (nextColor + 1)%2;

        WorkItem wi = tasks[i];
        DataItem[] dataItems = wi.getWorklistDataItems();

        String processName = wi.getProcessInstanceName();
        String taskName = wi.getName();
        String wiId = String.valueOf(wi.getId());
        String wiState = null;
        if (wi.getState() == -1)
            wiState = "Completed";
        else
            wiState = WorkItemStatesEnum.from_int(wi.getState()).toString();
        String wiAssignee = wi.getAssignee();
        String taskURL = "WorkItem.jsp?wid="+String.valueOf(wi.getId());
        if (filterId == Filter.MyCompletedWorkItems) {
            taskURL = taskURL + "&isCompleted=" + i;
            processName = wi.getProcessInstance().getName();
        }
        taskURL = response.encodeURL(taskURL);
%>
              <tr class="<%=rowColor%>">
<%
       for (int k = 0; k < displayFields.length; k++)
       {
            String displayField = displayFields[k];
            debug(" K = : " + k + " displayFields : " + displayField);

            if (displayField.equals("Id")) {
%>
                <td> <a href="<% QuickForm.writeHtml(out, taskURL );%>">
                  <% QuickForm.writeHtmlWithNBSPs(out, wiId); %>
                  </a>
                </td>
<%
            }
            if (displayField.equals("Activity Name")) {
%>
                <td> <a href="<% QuickForm.writeHtml(out, taskURL );%>">
                  <% QuickForm.writeHtmlWithNBSPs(out, taskName); %>
                  </a>
                </td>
<%
            }
            if (displayField.equals("Process Instance Name")) {
%>
                <td>
                  <% QuickForm.writeHtmlWithNBSPs(out, processName); %>
                </td>
<%
            }
            if (displayField.equals("Created")) {
%>
                <td nowrap> <script> showDate('<%=wi.getCreationTime()%>'); </script> </td>
<%
            }
            if (displayField.equals("Status")) {
%>
                <td> <%= wiState %> </td>
<%
            }
            if (displayField.equals("Due Date")) {
%>
                <td nowrap>
                    <%
                    Date dueDate = wi.getDueDate();
                    if (dueDate != null) { %>
                        <script> showDate('<%=dueDate.getTime()%>'); </script>
                    <% } %>
                </td>
<%
            }
            if (displayField.equals("Assignee")) {
%>
                <td> <% QuickForm.writeHtml(out, wiAssignee); %> </td>
<%
            }
        }
        for (int k = 0; k < displayUdas.length; k++)
        {
            int pos = displayUdas[k].indexOf("(");
            String udaName = displayUdas[k].substring(0, pos).trim();
            String udaType = displayUdas[k].substring(pos+1, displayUdas[k].indexOf(")")).trim();

            boolean foundUda = false;
            for (int m=0; m < dataItems.length; m++) {
                if (udaName.equals(dataItems[m].getName().trim()) &&
                    udaType.equalsIgnoreCase(dataItems[m].getType()) )
                {
                    String udaValue = dataItems[m].getValue();
                    if (udaValue == null)
                        udaValue = "";
                    if (dataItems[m].getType().equals(DataItemRef.TYPE_DATE)) {
%>
                <td nowrap> <script> showDate('<%=udaValue%>'); </script> </td>
<%
                    }
                    else {
%>
                <td><% QuickForm.writeHtml(out, udaValue); %></td>
<%
                    }
                    foundUda = true;
                    break;
                }
            }
            if (!foundUda) {
%>
                <td><% QuickForm.writeHtml(out, ""); %></td>
<%
            }
        }
    }
%>
              </tr>
            </TABLE>
          </td>
        </tr>
        <tr>
            <td align="left">
              <form name="saveForm">
<%
                SearchStruct[] searches = null;
                if(!("LE".equalsIgnoreCase(transportType)))
                {
                    searches = bps.getAllSearchs(bps.getUserName(), SearchStruct.TYPE_WI);
                }
                String searchesStr = "";
                if(searches != null)
                {
                   for(int kk=0; kk < searches.length; kk++)
                      searchesStr = searchesStr + searches[kk].queryName + ",";
                }
%>
                <input type="hidden" name="searchesStr" value="<%= searchesStr %>">
                <input name="srchnm" type="text" size="40" maxlength="64">
                <input value="Save this Search" type="button" class="core-button" onclick="save()">
              </form>
            </td>
        </tr>
      </table>
<%!
    public
    int
    getFieldIdFromFieldName(
        String fieldName)
    {
        int fieldId=WFObjectList.LISTFIELD_WORKITEM_NAME;
        if (fieldName.equals("Activity Name"))
            fieldId = WFObjectList.LISTFIELD_WORKITEM_NAME;
        if (fieldName.equals("Process Instance Name"))
            fieldId = WFObjectList.LISTFIELD_PROCESSINSTANCE_NAME;
        if (fieldName.equals("Created"))
            fieldId = WFObjectList.LISTFIELD_WORKITEM_CREATEDTIME;
        if (fieldName.equals("Status"))
            fieldId = WFObjectList.LISTFIELD_WORKITEM_STATE;
        if (fieldName.equals("Due Date"))
            fieldId = WFObjectList.LISTFIELD_WORKITEM_DUEDATE;
        if (fieldName.equals("Id"))
            fieldId = WFObjectList.LISTFIELD_WORKITEM_ID;
        if (fieldName.equals("Assignee"))
            fieldId = WFObjectList.LISTFIELD_WORKITEM_ASSIGNEE;
        return fieldId;
    }

    public
    String
    getFilterTitleFromId(
        int filterId)
    {
        String filterTitle = "My Active Activities";
        switch(filterId){
            case Filter.MyActiveWorkItems:
                filterTitle = "My Active Activities";
                break;
            case Filter.MyAcceptedWorkItems:
                filterTitle = "My Accepted Activities";
                break;
            case Filter.MyWorkItems:
                filterTitle = "My Activities";
                break;
            case Filter.MyDeclinedWorkItems:
                filterTitle = "My Declined Activities";
                break;
            case Filter.MyCompletedWorkItems:
                filterTitle = "My Completed Activities";
                break;
            case Filter.AllInactiveWorkItems:
                filterTitle = "All Inactive Activities";
                break;
            case Filter.AllWorkItems:
                filterTitle = "All Activities";
                break;
        }
        return filterTitle;
    }

    public
    int
    convertFilterNameToId(
        String filterName)
    {
        int filterId = Filter.MyActiveWorkItems;
        if (filterName.equals("My Active Activities")) {
            filterId = Filter.MyActiveWorkItems;
        }
        else if (filterName.equals("My Accepted Activities")) {
            filterId = Filter.MyAcceptedWorkItems;
        }
        else if (filterName.equals("My Activities")) {
            filterId = Filter.MyWorkItems;
        }
        else if (filterName.equals("My Declined Activities")) {
            filterId = Filter.MyDeclinedWorkItems;
        }
        else if (filterName.equals("All Inactive Activities")) {
            filterId = Filter.AllInactiveWorkItems;
        }
        else if (filterName.equals("All Activities")) {
            filterId = Filter.AllWorkItems;
        }
        return filterId;
    }

    public
    String
    convertUDAOperationString(
        String displayOperator)
    {
        String internalOperator = displayOperator;
        if (displayOperator.equals("In")) {
            internalOperator = WFObjectList.SQLOP_IN;
        }
        else if (displayOperator.equals("Like")) {
            internalOperator = WFObjectList.SQLOP_LIKE;
        }
        else if (displayOperator.equals("Not Like")) {
            internalOperator = WFObjectList.SQLOP_NOTLIKE;
        }
        return internalOperator;
    }

    public
    String
    convertOperationString(
        String displayOperator)
    {
        String internalOperator = WFObjectList.SQLOP_EQUALTO;
        if (displayOperator.equals("Equal To")) {
            internalOperator = WFObjectList.SQLOP_EQUALTO;
        }
        else if (displayOperator.equals("Greater Than")) {
            internalOperator = WFObjectList.SQLOP_GREATERTHAN;
        }
        else if (displayOperator.equals("Greater Than Or Equal To")) {
            internalOperator = WFObjectList.SQLOP_GREATERTHANOREQUALTO;
        }
        else if (displayOperator.equals("Less Than")) {
            internalOperator = WFObjectList.SQLOP_LESSTHAN;
        }
        else if (displayOperator.equals("Less Than Or Equal To")) {
            internalOperator = WFObjectList.SQLOP_LESSTHANOREQUALTO;
        }
        else if (displayOperator.equals("In")) {
            internalOperator = WFObjectList.SQLOP_IN;
        }
        else if (displayOperator.equals("Not Equal To")) {
            internalOperator = WFObjectList.SQLOP_NOTEQUALTO;
        }
        else if (displayOperator.equals("Like")) {
            internalOperator = WFObjectList.SQLOP_LIKE;
        }
        else if (displayOperator.equals("Not Like")) {
            internalOperator = WFObjectList.SQLOP_NOTLIKE;
        }
        return internalOperator;
    }

    public
    WorkItem[]
    getWorkItems(
        int filterId,
        int batchNumber,
        int batchSize,
        String sortField,
        String sortAsc,
        boolean trace,
        Writer out)
        throws Exception
    {
        debug("filterId="+filterId + " batchNumber="+batchNumber + " batchSize="+batchSize + " sortField="+sortField +
              " sortAsc="+sortAsc);

        WFObjectList list = WFObjectFactory.getWFObjectList(((BPMSessionImpl)bps)._wfs);
        addFilters(list);

        WorkItem[] wiList = new WorkItem[0];
        try {
            Object[] objList = null;
            boolean sortAscBool;
            if (sortAsc.equals("true")) {
              sortAscBool = true;
            }
            else if (sortAsc.equals("false")) {
              sortAscBool = false;
            }
            else {
              sortAscBool = true;
            }
            int sortFieldInt;
            if (sortField != null && sortField.trim().length() > 0) {
                int pos = sortField.indexOf("(");
                if(pos == -1){
                    sortFieldInt = getFieldIdFromFieldName(sortField.trim());
                    if (!(sortFieldInt == WFObjectList.LISTFIELD_WORKITEM_ID && sortAscBool == true)) {
                        debug("\n in getWorkItems, adding sort order field="+sortFieldInt + " order="+sortAscBool);
                        list.addSortOrder(sortFieldInt, sortAscBool);
                    }
                }else{
                    String udaName = sortField.substring(0, pos).trim();
                    String udaType = sortField.substring(pos+1, sortField.indexOf(")")).trim();
                    list.addSortOrder(udaName, udaType, sortAscBool);
                }
            }
            list.openBatchedList(filterId);
            objList = list.getNextBatch(batchSize);

            if (objList != null) {
                debug("\n in getWorkItems, got FIRST batch of "+objList.length + " workitems");
            }
            else {
                debug("\n in getWorkItems, for FIRST batch, objList is null");
            }
            if (batchNumber > 1) {
                for (int i=1; i<batchNumber; i++) {
                    objList = list.getNextBatch(batchSize);
                    if (objList != null) {
                        debug("\n in getWorkItems, for batch number ="+i+ ", got " + objList.length + " workitems");
                    }
                    else {
                        debug("\n in getWorkItems, for batch number ="+i+ ", objList is null");
                    }
                }
            }

            if (objList != null && objList.length > 0) {
                wiList = new WorkItem[objList.length];
                for (int i=0; i<objList.length; i++) {
                    wiList[i] = (WorkItem)objList[i];
                        debug("\n in getWorkItems, workitem id =" + wiList[i].getId());
                }
            }

        }
        finally {
            if (list != null)
                list.closeList();
        }
        return wiList;
    }

    public void debug (String msg) throws Exception
    {
        if (trace) {
            System.out.println(msg);
        }
    }

    public String getDefaultSearch() throws Exception
    {
        String srchName = null;
        SearchStruct defaultSearch = null;
        if(!("LE".equalsIgnoreCase(transportType)))
        {
            defaultSearch = bps.getDefaultSearchQuery(bps.getUserName(), SearchStruct.TYPE_WI);
        }
        if(defaultSearch != null){
            srchName = defaultSearch.queryName + " (Default)";
            String filterIdStr = defaultSearch.preDefFilter;
            filterId = new Integer(filterIdStr).intValue();
            planName = defaultSearch.pdNames;
            piName = defaultSearch.piNames;
            piopStr = defaultSearch.piOp;
            wiName = defaultSearch.wiNames;
            wiopStr = defaultSearch.wiOp;
            assigneeName = defaultSearch.assignees;
            asnopStr = defaultSearch.asnOp;
            sortField = defaultSearch.sortBy;
            sortAsc = defaultSearch.sortOrder;
            pageSize = defaultSearch.pageSize;
            searchUdaStruct = defaultSearch.udaFilter;
            udaFilters = "";
            if(searchUdaStruct != null ) {
                for(int i = 0; i < searchUdaStruct.length; i++) {
                    udaFilters += searchUdaStruct[i].name+" ("+
                                  searchUdaStruct[i].type+") "+
                                  searchUdaStruct[i].operation+" "+
                                  searchUdaStruct[i].value;
                    if(i != searchUdaStruct.length - 1){
                        udaFilters += ",";
                    }
                }
            }

            displayUdasStr = defaultSearch.disUdas;
            if ((displayUdasStr != null) && (displayUdasStr.trim().length() > 0)) {
                displayUdas = displayUdasStr.split(",");
            }
            else {
                displayUdas = new String[0];
                displayUdasStr = "";
            }

            displayFieldsStr = defaultSearch.disColums;
            if (displayFieldsStr == null) {
                displayFieldsStr = defaultFields;
            }
            displayFields = displayFieldsStr.split(",");

            hFrmCrt = defaultSearch.createdStartDate;
            hToCrt = defaultSearch.createdEndDate;
            hFrmDue = defaultSearch.dueDateStarts;
            hToDue = defaultSearch.dueDateEnds;

            tableTitle = "Advanced Search - " + srchName;
        }

        return srchName;
    }

    public void readParams(HttpServletRequest request) throws Exception
    {
        String filterIdStr = request.getParameter("filterId");
        filterId = new Integer(filterIdStr).intValue();

        srchnm = request.getParameter("srchnm");
        if (srchnm == null || srchnm.trim().length() == 0) {
            tableTitle = getFilterTitleFromId(filterId);
        }
        else if (srchnm.equals("--new--")) {
            tableTitle = "New Advanced Search";
        }
        else {
            tableTitle = "Advanced Search - " + srchnm;
        }

        sortField = request.getParameter("sort");
        sortAsc = request.getParameter("asc");
        planName = request.getParameter("pd");
        piName = request.getParameter("pin");
        piopStr = request.getParameter("piop");
        wiName = request.getParameter("win");
        wiopStr =  request.getParameter("wiop");
        assigneeName = request.getParameter("asn");
        asnopStr = request.getParameter("asnop");
        String pageSizeStr = request.getParameter("pg");
        if (pageSizeStr != null) {
            pageSize = Integer.parseInt(pageSizeStr);
        }
        udaFilters = request.getParameter("filterUdas");
        displayUdasStr = request.getParameter("dspUda");
        if ((displayUdasStr != null) && (displayUdasStr.trim().length() > 0)) {
            displayUdas = displayUdasStr.split(",");
        }
        else {
            displayUdas = new String[0];
            displayUdasStr = "";
        }
        displayFieldsStr = request.getParameter("dspFields");
        if (displayFieldsStr == null) {
            displayFieldsStr = defaultFields;
        }
        displayFields = displayFieldsStr.split(",");
        hFrmCrt = request.getParameter("hFrmCrt");
        hToCrt = request.getParameter("hToCrt");
        hFrmDue = request.getParameter("hFrmDue");
        hToDue = request.getParameter("hToDue");
        String pageNumberStr = request.getParameter("pgNum");
        if (pageNumberStr != null) {
            pageNumber = Integer.parseInt(pageNumberStr);
        }
    }

    public void setDefaultValues() throws Exception
    {
        filterId = Filter.MyActiveWorkItems;
        tableTitle = getFilterTitleFromId(filterId);
        pageSize = 20;
        tasks = new WorkItem[0];
        sortField = "Id";
        sortAsc = "true";
        filterName = "";
        planName = "";
        piName = "";
        piopStr = "";
        wiName = "";
        wiopStr =  "";
        assigneeName = "";
        asnopStr = "";
        udaFilters = "";
        searchUdaStruct = null;
        displayUdasStr = "";
        displayUdas = new String[0];
        displayFieldsStr = defaultFields;
        displayFields = displayFieldsStr.split(",");
        hFrmCrt = "";
        hToCrt = "";
        hFrmDue = "";
        hToDue = "";
    }

    public void cleanupGlobals() throws Exception
    {
        if(pageNumber == 0){
            pageNumber = 1;
        }
        if (sortField != null && !sortField.equals("-- Select --") ) {
            if (sortAsc == null) {
                sortAsc = "true";
            }
        }
        else {
            sortField = "Id";
            sortAsc = "true";
        }
        if(planName == null){
            planName = "";
        }
        if(piName == null){
            piName = "";
        }
        if(piopStr == null){
            piopStr = "";
        }
        if(wiName == null){
            wiName = "";
        }
        if(wiopStr == null){
            wiopStr = "";
        }
        if(assigneeName == null){
            assigneeName = "";
        }
        if(asnopStr == null){
            asnopStr = "";
        }
        if(pageSize == 0){
            pageSize = 20;
        }
        if(srchnm == null){
            srchnm = "";
        }
        if(displayUdasStr == null){
            displayUdasStr = "";
        }
        if(displayFieldsStr == null){
            displayFieldsStr = "";
        }
        if(udaFilters == null){
            udaFilters = "";
        }
        if(hFrmCrt == null){
            hFrmCrt = "";
        }
        if(hToCrt== null){
            hToCrt = "";
        }
        if(hFrmDue == null){
            hFrmDue = "";
        }
        if(hToDue == null){
            hToDue = "";
        }
    }

    public void addFilters(WFObjectList list) throws Exception {
        if (planName != null && planName.trim().length() > 0 && !planName.equals("-- Select --")) {
            debug("\n adding planName filter '"+planName+"'");
            list.addFilter(WFObjectList.LISTFIELD_PLAN_NAME, WFObjectList.SQLOP_EQUALTO, "'" + planName + "'");
        }
        if (piName != null && piName.trim().length() > 0) {
            String piop = convertOperationString(piopStr);
            debug("\n adding piName filter " + piop + "'"+piName+"'");
            if (piop.equals(WFObjectList.SQLOP_IN)) {
                list.addFilter(WFObjectList.LISTFIELD_PROCESSINSTANCE_NAME, piop, processOperandForIn(piName));
            }
            else {
                list.addFilter(WFObjectList.LISTFIELD_PROCESSINSTANCE_NAME, piop, "'" + piName + "'");
            }
        }
        if (wiName != null && wiName.trim().length() > 0) {
            String wiop = convertOperationString(wiopStr);
            debug("\n adding wiName filter " + wiop + "'"+wiName+"'");
            if (wiop.equals(WFObjectList.SQLOP_IN)) {
                list.addFilter(WFObjectList.LISTFIELD_WORKITEM_NAME, wiop, processOperandForIn(wiName));
            }
            else {
                list.addFilter(WFObjectList.LISTFIELD_WORKITEM_NAME, wiop, "'" + wiName + "'");
            }
        }
        if (assigneeName != null && assigneeName.trim().length() > 0) {
            String asnop = convertOperationString(asnopStr);
            debug("\n adding assigneeName filter " + asnop + "'"+assigneeName+"'");
            if (asnop.equals(WFObjectList.SQLOP_IN)) {
                list.addFilter(WFObjectList.LISTFIELD_WORKITEM_ASSIGNEE, asnop, processOperandForIn(assigneeName));
            }
            else {
                list.addFilter(WFObjectList.LISTFIELD_WORKITEM_ASSIGNEE, asnop, "'" + assigneeName + "'");
            }
        }
        if (hFrmCrt != null && hFrmCrt.trim().length() > 0) {
            debug("\n adding LISTFIELD_WORKITEM_CREATEDTIME filter 1");
            list.addFilter(WFObjectList.LISTFIELD_WORKITEM_CREATEDTIME, WFObjectList.SQLOP_GREATERTHANOREQUALTO , "'" + hFrmCrt + "'");
        }
        if (hToCrt != null && hToCrt.trim().length() > 0) {
            debug("\n adding LISTFIELD_WORKITEM_CREATEDTIME filter 2");
            list.addFilter(WFObjectList.LISTFIELD_WORKITEM_CREATEDTIME, WFObjectList.SQLOP_LESSTHANOREQUALTO , "'" + hToCrt + "'");
        }
        if (hFrmDue != null && hFrmDue.trim().length() > 0) {
            debug("\n adding LISTFIELD_WORKITEM_DUEDATE filter 1");
            list.addFilter(WFObjectList.LISTFIELD_WORKITEM_DUEDATE, WFObjectList.SQLOP_GREATERTHANOREQUALTO , "'" + hFrmDue + "'");
        }
        if (hToDue != null && hToDue.trim().length() > 0) {
            debug("\n adding LISTFIELD_WORKITEM_DUEDATE filter 2");
            list.addFilter(WFObjectList.LISTFIELD_WORKITEM_DUEDATE, WFObjectList.SQLOP_LESSTHANOREQUALTO , "'" + hToDue + "'");
        }
        if (udaFilters != null && udaFilters.trim().length() > 0) {
            debug("\n udaFilters="+udaFilters);

            String[] udaFilter = udaFilters.split(";");
            searchUdaStruct = new SearchUdaStruct[udaFilter.length];

            for (int i = 0; i < udaFilter.length; i++) {
                String oneUdaFilter = udaFilter[i];
                debug("\n worklist -- oneUdaFilter=" + oneUdaFilter);

                int posOpenParen = oneUdaFilter.indexOf("(");
                String udaName = oneUdaFilter.substring(0, posOpenParen).trim();
                int posCloseParen = oneUdaFilter.indexOf(")");
                String udaType = oneUdaFilter.substring(posOpenParen + 1, posCloseParen).trim();
                int posSpace = oneUdaFilter.lastIndexOf(" ");
                String udaOpStr = oneUdaFilter.substring(posCloseParen + 2, posSpace).trim();
                ;
                String udaOp = convertUDAOperationString(udaOpStr);
                String originalUdaValue = oneUdaFilter.substring(posSpace).trim();
                String udaValue = originalUdaValue;

                if (udaOp.equals(WFObjectList.SQLOP_IN)) {
                    udaValue = processOperandForIn(udaValue);
                } else {
                    udaValue = "'" + udaValue + "'";
                }

                debug("\n udaName=" + udaName);
                debug("\n udaType=" + udaType);
                debug("\n udaOp=" + udaOp);
                debug("\n udaValue=" + udaValue);
                debug("\n adding UDA filter #2");
                list.addFilter(udaName, udaType, udaOp, udaValue);

                SearchUdaStruct suda = new SearchUdaStruct();
                suda.name = udaName;
                suda.type = udaType;
                suda.operation = udaOpStr;
                suda.value = originalUdaValue;

                searchUdaStruct[i] = suda;
            }

        }
    }

    public String processOperandForIn(String operand) throws Exception {
        StringTokenizer st = new StringTokenizer(operand,",",true);
        StringBuffer sb = new StringBuffer();
        sb.append("(");
        while(st.hasMoreTokens()) {
            String token = st.nextToken();
            if (token.equals(",")) {
                sb.append(token);
            }
            else {
                sb.append("'");
                sb.append(token);
                sb.append("'");
            }
        }
        sb.append(")");
        return sb.toString();
    }

%>
    </td>
    </tr>
  </table>
</center>
</body>
</html>
