<%@  page pageEncoding="utf-8" contentType="text/html;charset=utf-8" import="com.novell.webaccess.common.JSPConduit2,
                                                                             com.novell.nps.utils.Utils,
                                                                             com.novell.emframe.dev.*,
                                                                             java.io.*,
                                                                             com.novell.admin.ns.nds.NDSNamespace,
                                                                             com.novell.application.console.snapin.ObjectEntry,
                                                                             com.novell.admin.ns.ClassDefinition,
                                                                             com.novell.admin.ns.AttributeDefinition,
                                                                             java.util.*,
                                                                             com.novell.emframe.fw.*,
                                                                             com.novell.emframe.dev.config.SystemConfig" %>
<%@ taglib uri="/WEB-INF/iman.tld" prefix="iman" %>
<%@ taglib uri="/WEB-INF/c.tld" prefix="c" %>
<iman:stringtable bundle="DevResources"/>
<iman:stringtable bundle="FwResources"/>
<%--
   Consumer Paramaters:
     Required: 
     TC.controlName                                this key in HttpRequest will contain the target; (default=eDir$target)
     objectTypeNames                               String[] of unlocalized type names
     
     Parameters from setupTargetChooser:
       -TC.defaultPrompt                           if no title parameter, default title to display above control
       -TC.packedObjectTypeNames                   packed string of localized class names
       -TC.packedRealObjectClassNames              packed string of unlocalized class names
       -TC.osTypeFilter                            string of comma-delimited type names
     
     Optional:
     TC.advancedSelectionEnabled                   allows user to choose filter (instead of selecting specific objects) (default false)
     TC.initialValues                              a packed array representing the initial contents of
     TC.initialSelections                          a packed array of array indexes (zero-based)
     TC.mode                                       which tab to be enabled on startup
     TC.multipleObjectEnabled                      allows user to choose multiple objects (default false)
     
     TC.showObjectTypeSelectionInAdvancedSelect    allows user to pick a type and only select objects of that type in advanced selection mode
     TC.singleSelectionEnabled                     allows user to choose one object (default true)
     TC.title                                      title to display by control

     Future:
     TC.showObjectTypeSelectionInMultiSelect       allows user to pick a type and only select objects of that type in multiple selection mode
     
     Question:
     targetNames                                   is the the way initial values are passed in from EDAS?
     
   Consumer must call c.setupTargetChooser(context, resultStrings, String[] objectTypeNames)
   Consumer should call MContext.addToHistory() from the Java code after a valid object is chosen
   Consumer template must import DevResources
   Consumer template must call validateTargetChooser() in javascript onExit
--%>
<!-- Begin TC_inc.jsp (Browser) -->
<%   JSPConduit2 c = JSPConduit2.getJSPConduit(request);

   /*=== Used by PropertyBook and EDAS ==== */
   c.stringTable("DevResources");
   c.stringTable("FwResources");
   
   //------------------- Handle Deprecations ------------------------------
   //TC.objectTypeName and TC.objectTypeNames deprecated... replaced with TC.osTypeFilter
   if (c.var("TC.osTypeFilter").equals(""))
   {
      if (!c.var("TC.objectTypeNames").equals(""))
      {
         //use value from deprecated parameter TC.objectTypeNames
         c.set("TC.osTypeFilter",c.var("TC.objectTypeNames"));
      }
      else if (!c.var("TC.objectTypeName").equals(""))
      {
         //use value from deprecated parameter TC.objectTypeNames
         c.set("TC.osTypeFilter",c.var("TC.objectTypeName"));
      }
   }
   
   //TC.initialValue deprecated.... replaced with TC.initialValues
   if (c.var("TC.initialValues").equals(""))
   {
      c.set("TC.initialValues", c.var("TC.initialValue"));   
   }
   
   //TC.prompt deprecated.... replaced with TC.title
   if (c.var("TC.title").equals(""))
   {
      c.set("TC.title", c.var("TC.prompt"));   
   }
   
   //-------------------- Validate Parameters -----------------------------
   if (c.var("TC.title").equals(""))
   {
      c.set("TC.title", c.var("TC.defaultPrompt"));
   }

   //if no osTypeFilter, assume "*"   
   if (c.var("TC.osTypeFilter").equals(""))
   {
      c.set("TC.osTypeFilter", "*");
   }
   
   // get array of unlocalized object type names from request
   String[] objectTypeNames = (String[])request.getAttribute("objectTypeNames");

   // determine which options to display (single select, multiple select, simple selection (quick fine) and advanced selection
   boolean singleEnabled =    !(c.var("TC.singleObjectEnabled").equals("false"));         //true if anything but "false"
   boolean mooEnabled =       c.var("TC.multipleObjectEnabled").equals("true");
   boolean advancedEnabled =  c.var("TC.advancedSelectionEnabled").equals("true");
   boolean simpleEnabled =    ( !(c.var("TC.quickFindEnabled").equals("false")) );        // May be disabled by xml.  Multiple classes now allowed.
   
   // determine the first tab that is enabled.
   String firstEnabled = null;  //assume single
   if (singleEnabled)            firstEnabled="single";
   else if (mooEnabled)          firstEnabled="multiple";
   else if (simpleEnabled)       firstEnabled="simple";
   else if (advancedEnabled)     firstEnabled="advanced";
   else                          { singleEnabled = true;  firstEnabled = "single"; }   //default to single selection mode
   c.set("TC.firstEnabled",firstEnabled);
   
   //setup the initial values array (from targetNames or TC.initialValues)
   String[] initialValues = null;
   String targetNames = request.getParameter("targetNames");   //from EDAS
   if (targetNames==null) targetNames = c.var("TC.initialValues"); else c.set("TC.initialSelections","PP");
   if (targetNames!=null && targetNames.length()!=0) initialValues = eMFrameUtils.unpack(targetNames, eMFrameFactory.getMContext(request));
   int ivLen = ((initialValues==null)?0:initialValues.length);
   
   //make sure initial mode parameter and enabled panes are consistent
   c.set("TC.mode", c.toLower(c.var("TC.mode")));
   String mode = c.var("TC.mode");
   if (mode.equals(""))
   {
      //no mode specified, pick a pane that makes sense
      if (ivLen<2 && singleEnabled) c.set("TC.mode", "single");   
      else if (mooEnabled)          c.set("TC.mode", "multiple");
      else if (advancedEnabled)     c.set("TC.mode", "advanced");
      else if (simpleEnabled)       c.set("TC.mode", "simple");
      else                          c.set("TC.mode", firstEnabled);  //default to first enabled tab
   }
   else
   {
      //make sure specified mode has been enabled, otherwise use first enabled 
      if (mode.equals("single") && !singleEnabled)          c.set("TC.mode", firstEnabled);
      else if (mode.equals("multiple") && !mooEnabled)      c.set("TC.mode", firstEnabled);
      else if (mode.equals("advanced") && !advancedEnabled) c.set("TC.mode", firstEnabled);
      else if (mode.equals("simple") && !simpleEnabled)     c.set("TC.mode", firstEnabled);
   }

   //build the menu structure
   ArrayList list = new ArrayList();
   if (singleEnabled)      list.add(new TCMenuBuilder.TCMenuItem("singleSelect", c.string("General.selectSingle"), "safeFocus(document.forms[0].single)"));
   if (mooEnabled)         list.add(new TCMenuBuilder.TCMenuItem("multiSelect", c.string("General.selectMultiple"), "safeFocus(document.forms[0].multipleListTB)"));
   if (simpleEnabled)      list.add(new TCMenuBuilder.TCMenuItem("quickFind", c.string("General.quickFind"), "safeFocus(document.getElementById('quickFindFilter'))"));
   if (advancedEnabled)    list.add(new TCMenuBuilder.TCMenuItem("advancedSelection", c.string("General.advancedSelection"), ""));
   TCMenuBuilder menuBuilder = new TCMenuBuilder(list);
   
   String pack = c.var("TC.packedObjectTypeNames");
   if (pack==null)
   {
      pack = "";
   }
%>

<SCRIPT>
   window.finishedLoading        = false;
   window.controlName            = "<%= c.var("TC.controlName") %>";
   window.singleObjectName       = "<%= c.var("TC.osTypeFilter") %>";
   window.packedObjectTypeNames  = "<%= pack %>";
   
<%    if (singleEnabled)      out.println("panels[panels.length] = \"singleSelect\";");
      if (advancedEnabled)    out.println("panels[panels.length] = \"advancedSelection\";");
      if (mooEnabled)         out.println("panels[panels.length] = \"multiSelect\";");
      if (simpleEnabled)      out.println("panels[panels.length] = \"quickFind\";"); %>

   //when user clicks on a menu tab, this function is called to make it visible.
   function setDisplay(vis)
   {
      try
      {
         //make sure page has completed loading before processing user's tab selection
         if ( (document.readyState && document.readyState!="complete") || window.finishedLoading==false )
         {
            alert("<%= c.string("Book.pageLoading") %>"); 
            return;
         }

         //walk through all panes making on the selected tab visible and the rest invisible
         for (i in panels) document.getElementById(panels[i]).style.display = ( (panels[i]==vis)?"block":"none" );
      }
      catch(e) {} 
   }
   
   function tcLoadQuery(queryObject)
   {
      //dumpQueryObject("tcLoadQuery", queryObject);
      
      document.getElementById("tc_container").value = queryObject.container;
      document.getElementById("tc_subContainerSearch").checked = queryObject.subcontainerSearch == "true";
      document.getElementById("tc_subClasses").checked = queryObject.subClasses == "true";
   
      var crit = queryObject.criteria;
      var objectTypes = null;
      if (crit!=null && crit[0]!=null && crit[0].length>0)
      {
         //load advanced selection criteria into target chooser gui
         saveXML("advancedSelectionXML", null, crit[0]);
         
         //find type in list and select it
         objectTypes = getCriteriaTypes(crit[0]);
         if (objectTypes!=null)
         {
            var sel = document.getElementById("tc_asTargetType");
            var opts = sel.options;
            for (var i=0; i < opts.length; i++)
            {
               if (opts[i].value==objectTypes[0])
               {
                  sel.selectedIndex = i;   //found it; select it
                  break;
               }
            }
         }
      }
      else
      {
         //no criteria to load; clear existing criteria in gui
         clearAdvancedFilter();
      }
      
   }
</SCRIPT>

<INPUT type=hidden name="<%= c.var("TC.controlName") %>" value="<%= c.var("TC.initialValues") %>">
<INPUT type=hidden name="TC.packRealObjectClassNames" value="<%= c.var("TC.packRealObjectClassNames") %>">  <%-- for edas validation --%>
<INPUT type=hidden name="targetType" value="">  <%-- send a single type to propertybook (DirPropertybook.java --%>

<!-- ========== Single Select ============== -->

<% if (singleEnabled) { %>

<DIV id=singleSelect style="display:<% if (c.var("TC.mode").equals("single")) out.print("block"); else out.print("none"); %>">
<% menuBuilder.buildMenu(out, "singleSelect"); %>
   <NOBR><%= c.toDisplay(c.var("TC.title")) %>: <% if (!c.var("TC.packedObjectTypeNames").equals("")) { %>(<A href="Javascript: showList();"><%= c.string("TC.seeList") %></A>)<% } %></NOBR><BR>
   <TABLE cellpadding="0" cellspacing="0">
   <TR>
      <TD>
         <INPUT type=text name="single" value="<% if (initialValues!=null && initialValues.length>0){ out.println(Utils.toTag(initialValues[0])); } %>" 
                size=<%= c.string("UI.textboxSize") %> style="width:<%= c.string("UI.textboxPixel") %>">
         <iman:os typeFilter="${requestScope['TC.osTypeFilter']}" control="single" history="true" />
      </TD>
   </TR>
   </TABLE>
</DIV>
<% } else { %>
<!-- Single Select not enabled -->
<% } %>

<!-- ========== Multiple Select ============ -->

<% if (mooEnabled) { %>

<DIV id=multiSelect style="display:<% if (c.var("TC.mode").equals("multiple")) out.print("block"); else out.print("none"); %>">
<% menuBuilder.buildMenu(out, "multiSelect"); %>

   <INPUT type="hidden" name="mooTargetType" value="<%= objectTypeNames[0] %>">
   <NOBR><%= c.toDisplay(c.var("TC.title")) %>: <% if (!c.var("TC.packedObjectTypeNames").equals("")) { %>(<A href="Javascript: showList();"><%= c.string("TC.seeList") %></A>)<% } %></NOBR><BR>   
<%    if (initialValues != null && initialValues.length>1)
      {
         MContext taskContext=eMFrameFactory.getMContext(request);
         c.set("MVStringEditor_pack",eMFrameUtils.pack(initialValues,taskContext));
      }
      c.set("MVStringEditor_selections", c.var("TC.initialSelections"));
      c.set("MVStringEditor_name", "multipleList");
      c.set("MVStringEditor_size", "10");
      c.set("MVStringEditor_objectTypeName", c.var("TC.osTypeFilter"));
      c.set("MVStringEditor_enforceUnique", "true");
      c.set("MVStringEditor_history", "true");
      c.set("MVStringEditor_mode", "mvsel");
   %>
   <iman:include page="dev/MVStringEditor_inc.jsp" />
</DIV>
<% } else { %>
<!-- Multiple Select not enabled -->
<% } %>

<!-- ==== Simple Select (Quick Find) ======= -->
<% if (simpleEnabled) { 
	  MContext qfContext = eMFrameFactory.getMContext(request);
     SystemConfig configuration = SystemConfig.getSystemConfig(qfContext);
     String ldapSSLSetting = configuration.getSetting("Authenticate.LDAP.useSSL");
%>

<DIV id="quickFind" style="display:<% if (c.var("TC.mode").equals("simple")) out.print("block"); else out.print("none"); %>">
<% menuBuilder.buildMenu(out, "quickFind"); %>

   <SPAN class="smalltext2d"><%= c.string("QuickSearch.warning") %></SPAN><BR><BR>
<% if (configuration.getSetting("Authenticate.LDAP.useSSL") != null && ldapSSLSetting.equalsIgnoreCase("false")) { %>
   <SPAN class="smalltext2d"><%= c.string("QuickSearch.SecureLDAPDisabled") %></SPAN><BR><BR>
   <%}%>
   <TABLE >
   <TR>
      <td>
         <SELECT name="quickFindAttribute" id="quickFindAttribute">
<%
   MContext context = eMFrameFactory.getMContext(request);
   String objectTypeName = objectTypeNames[0];
   DirUtils dirUtils = context.getDirUtils();
   boolean haveFavorites = false;

   // ouput favorite attributes
   if (objectTypeNames.length==1)
   {
      List favoriteAttrs = TargetChooserUtils.getTCQuickFindAttributes(objectTypeName,  context);
      if (!favoriteAttrs.isEmpty())
      {
         for (Iterator iter = favoriteAttrs.iterator(); iter.hasNext();)
         {
            String ldapName = (String) iter.next();
            String ndapName = null;
            String attributeDisplayName = ldapName;
            try
            {
               MappingObject mo = dirUtils.getMappingObject();
               ndapName = ((mo==null) ? ldapName : mo.LDAPAttributeToNDS(ldapName));
               attributeDisplayName=dirUtils.getAttributeDisplayName(ndapName, context);
               out.println("<OPTION value=\"" + ldapName  +"\" >" + attributeDisplayName);
               haveFavorites = true;
            }
            catch(Throwable e)
            {
               D.log("Skipping favorite attribute...\n   LDAP name: "+ldapName+"\n   NDAP name: "+ndapName);
               D.log(e);
            }
         }
         if (haveFavorites) out.println("<OPTION value=\"\">---------------------------------------------");
      }
   }

   // output all attributes
   String[] attributesDisplayNames = (String[])FwAttr.getFwRequestAttribute("QuickFind_AttributesDisplayNames", request);
   String[] attributesNames = (String[])FwAttr.getFwRequestAttribute("QuickFind_AttributesNames", request);

   for (int i=0; i<attributesNames.length; i++)
   {
      if (attributesNames[i].equalsIgnoreCase("cn") && !haveFavorites)  
         out.println("<OPTION value=\"" + attributesNames[i]  +"\" selected>" + attributesDisplayNames[i]);
      else
         out.println("<OPTION value=\"" + attributesNames[i]  +"\" >" + attributesDisplayNames[i]);
   }
%>
         </SELECT>
      </td>
      <td>
         <SELECT name="quickFindOp" id="quickFindOp">
            <OPTION value="startsWith"><iman:string key="QuickSearch.StartsWith"/>
            <OPTION value="equals"><iman:string key="QuickSearch.Equals"/>
            <OPTION value="isPresent"><iman:string key="AS.Op.isPresent"/>
            <OPTION value="isNotPresent"><iman:string key="AS.Op.isNotPresent"/>
         </SELECT>
      </td>
      <td>
         <%--
            MOZILLA-HACK: crapy mozilla broke event cancel bubbling;  It worked in NN4, but not in 6 or 7
            <INPUT type="text" id="quickFindFilter" onKeyPress="if(event.keyCode==13) {doQuickFind(); return false;}" >
         --%>
         <INPUT size=25 type="text" id="quickFindFilter" onKeyPress="return quickFindKeyPressed(event)">
      </td>
      <td>
         <IMG align=absmiddle src="<c:out value='${ModulesPath}'/>/dev/images/<iman:string key="Button.Search.image"/>" title="<iman:string key="OS.Browser.SearchMode"/>" onClick="doQuickFind()">
      </td>
   </TR>
   </TABLE>

   <IFRAME name="quickFindResults" id="quickFindResults" src="/nps/Empty.html" style="width: 390px; height: 165px; border:0" border="0" frameBorder="0"></IFRAME>
</DIV>
<% } else { %>
<!-- Simple Selection (Quick Find) not enabled -->
<% } %>

<!-- ========== Advanced Selection ========= -->

<% if (advancedEnabled) { %>

<DIV id=advancedSelection style="display:<% if (c.var("TC.mode").equals("advanced")) out.print("block"); else out.print("none"); %>">
   <% menuBuilder.buildMenu(out, "advancedSelection"); %>
   <INPUT type="hidden" name="advancedSelectionXML">
   <DIV class="instructions"><%= c.string("TC.AdvancedSelectionDescription") %><BR><BR></DIV>
   <TABLE cellpadding=0 cellspacing=0>
      <!-- type selection UI -->
      <% String showTypeSelection = ((c.var("TC.showObjectTypeSelectionInAdvancedSelect").equals("true") && objectTypeNames!=null && objectTypeNames.length>0)?"block":"none");%>
      <TR style="display:<%= showTypeSelection %>"><TD class=mediumtext><%= c.toDisplay(c.string("TC.objectClass")) %></TD></TR>
      <TR style="display:<%= showTypeSelection %>">
         <TD>
            <SELECT id="tc_asTargetType" name="asTargetType" style="width:<%= c.string("UI.textboxPixel") %>" onChange="clearFilter();">
            <%
               int size = objectTypeNames.length;
               for (int i=0; i<size; i++)
               {
                  if (objectTypeNames[i].equals("User")) out.print("<OPTION value=\"" + c.toTag(objectTypeNames[i]) + "\" selected >" + c.toTag(objectTypeNames[i]));
                  else                                   out.print("<OPTION value=\"" + c.toTag(objectTypeNames[i]) + "\">" + c.toTag(objectTypeNames[i]));
               }
            %>
            </SELECT>
         </TD>
      </TR>
      <TR style="display:<%= showTypeSelection %>">
      	<TD class=mediumtext>&nbsp;&nbsp;&nbsp;&nbsp;<INPUT type="checkbox" id="tc_subClasses"  name="subClasses" ><%= c.toDisplay(c.string("TC.subClasses")) %></TD>
      </TR>
      <TR style="display:<%= showTypeSelection %>"><TD height=8px></TD></TR>

      <!-- container UI -->
      <TR><TD class=mediumtext><%= c.toDisplay(c.string("TC.container")) %></TD></TR>
      <TR>
         <TD><INPUT id="tc_container" name="container" type="text" value="" size=<%= c.string("PocketUI.textboxSize") %> style="width:<%= c.string("UI.textboxPixel") %>" onKeyPress="if(event.keyCode==13) return false"></TD>
         <TD>&nbsp;<iman:os typeFilter="[containers],[Root]" control="container" history="true" /></TD>
      </TR>
      <TR><TD height=2px></TD></TR>
      <TR><TD class=mediumtext>&nbsp;&nbsp;&nbsp;&nbsp;<INPUT type="checkbox" id="tc_subContainerSearch"  name="subContainerSearch" ><%= c.toDisplay(c.string("TC.searchSubContainer")) %></TD></TR>
      <TR><TD height=8px></TD></TR>
  
      <!-- filter UI -->
      <TR>
         <TD class=mediumtext><%= c.toDisplay(c.string("TC.filter")) %>&nbsp;&nbsp;<span id="filterNo" style="display:inline"><%= c.toTag(c.string("TC.noFilter")) %></span><span id="filterYes" style="display:none"><%= c.toTag(c.string("TC.advancedFilterSet")) %></span></TD>
         <TD>&nbsp;<iman:as control = "advancedSelectionXML" 
                            controlCallBack = "saveXML" 
                            typesCallBack = "myASTypeFilterCallBack" 
                            initialCriterionCallBack = "tcGetFilterXML" />
            <A href="javascript:clearAdvancedFilter();"><IMG alt="<%= c.string("Button.Remove.alt") %>" src="<%= c.getModulesUrl() %>/dev/images/iconremove.gif" border="0" align="absmiddle"></A><IMG src="<%= c.getModulesUrl() + "/fw/images/1px_spacer.gif" %>" width=2 border="0"></TD>
      </TR>
      <TR><TD height="12px"></TD></TR>
   
      <!-- Preview, Save, Load UI -->
     <TR>
         <TD class="mediumtext">
            <iman:button key="Preview" onClick="preview()"/>
            <iman:button key="LoadDots" onClick="doLoadQuery('tcLoadQuery')" />
            <iman:button key="SaveDots" onClick="doSaveQuery(tcBuildSaveQuery())"/>
         </TD>
      </TR>
   </TABLE><BR>

   <iman:bar/><BR>
   <TABLE cellpadding="0" cellspacing="1">
      <TR><TD><%= c.toDisplay(c.string("TC.preview")) %></TD><TD align="right"><SPAN id="countBox"></SPAN></TD></TR>
      <TR><TD colspan="2"><IFRAME src="/nps/Empty.html" name="previewFrame" id="previewFrame" style="width:393px"></IFRAME></TD></TR>
      <tr height=10><td></td></tr>
      <TR><TD>
         <IMG id=backButton onClick="movePreview('previewPrevious', this)" src="<%= c.getModulesUrl() + "/dev/images/"+c.string("Button.PreviousDisabled.image") %>" border=0 alt="<%= c.string("Button.Back.alt") %>" title="<%= c.string("Button.Back.alt") %>">
         <IMG id=nextButton onClick="movePreview( 'previewNext', this)" src="<%= c.getModulesUrl() + "/dev/images/"+c.string("Button.NextDisabled.image") %>" border=0 alt="<%= c.string("Button.Next.alt") %>" title="<%= c.string("Button.Next.alt") %>"></TD></TR>
   </TABLE>
</DIV>
<% } else { %>
<!-- Advanced Selection not enabled -->
<% } %>

<SCRIPT>window.finishedLoading = true;</SCRIPT>

<!-- remove parameters from request -->
<c:remove var="TC.controlName"/>
<c:remove var="TC.advancedSelectionEnabled"/>
<c:remove var="TC.multipleObjectEnabled"/>
<c:remove var="TC.singleSelectionEnabled"/>
<c:remove var="TC.quickFindEnabled"/>
<c:remove var="TC.osTypeFilter"/>
<c:remove var="TC.defaultPrompt"/>
<c:remove var="TC.title"/>
<c:remove var="TC.packRealObjectClassNames"/>
<c:remove var="TC.packedObjectTypeNames"/>
<c:remove var="TC.mode"/>
<c:remove var="TC.initialValues"/>
<c:remove var="TC.initialSelections"/>
<c:remove var="TC.showObjectTypeSelectionInAdvancedSelect"/>
<c:remove var="TC.showObjectTypeSelectionInMultiSelect"/>

<!-- remove deprecated parameters from request -->
<c:remove var="TC.prompt"/>
<c:remove var="TC.initialValue"/>
<c:remove var="TC.objectTypeName"/>
<c:remove var="TC.objectTypeNames"/>
<!-- End TC_inc.jsp (Browser) -->
