
<%@  page pageEncoding="utf-8" contentType="text/html;charset=utf-8" import="
                                                                             com.novell.emframe.dev.config.SystemConfig,
                                                                             com.novell.emframe.dev.MUtils,
                                                                             com.novell.emframe.fw.LookAndFeelDefaults,
                                                                             com.novell.emframe.fw.authenticator.DirAuthenticator,
                                                                             java.util.*" %>
<%@ page import="com.novell.emframe.dev.eMFrameUtils" %>

<%@ taglib uri="/WEB-INF/c.tld" prefix="c" %>
<%@ taglib uri="/WEB-INF/iman.tld" prefix="iman" %>

<iman:stringtable bundle="DevResources"/>
<iman:stringtable bundle="FwResources"/>

<%!
  
   /**
    * This method is used to make a user friendly display name for the authentication
    * broker key.  The original form is 'TreeName:FullContextUser:Protocol:Rank'.  
    * The user friendly form is FullContextUser@Tree_Name  
    * @param authBrokerKey
    * @return
    */
   private static String getFriendlyAuthBrokerName(String authBrokerKey)   {
      StringTokenizer stok = new StringTokenizer(authBrokerKey,":");
      String retVal = new String();
      if(stok.hasMoreElements())
      {
         String treeName = (String)stok.nextElement();
         String userName = (String)stok.nextElement();
         retVal = userName+"@"+treeName;
      }
      return retVal;
   }

%>
<%
  /* ********************************************************************************************************************* */
  /* The formatting part of this template is duplicated in AuthFormDisconn.  If changes are made, change that file as well */
  /* ********************************************************************************************************************* */
  //@todo-- this should be moved to DirAuthenticator.showLoginDlg()
   SystemConfig configuration = new SystemConfig();
	String showNonSecureWarning = configuration.getSetting("Security.Warn.nonSecure");
	request.setAttribute("Security_Warn_nonSecure", showNonSecureWarning);

	DirAuthenticator dirAuth = DirAuthenticator.getDirAuth(request);
   Hashtable authBrokers = dirAuth.getAuthenticationBrokers();
   Vector keys = new Vector(authBrokers.size());   
   Enumeration authBrokerEnum = authBrokers.keys();
   while(authBrokerEnum.hasMoreElements())
   {
      String keyName = (String)authBrokerEnum.nextElement();
      String friendlyName = getFriendlyAuthBrokerName(keyName);
      String callBackFunctionName = (String)pageContext.getRequest().getAttribute("callback");
      String html = "<a href=\"javascript:"+callBackFunctionName+"('"+keyName+"');\" >"+friendlyName+"</a>";
      keys.add(html);
   }
   
   pageContext.setAttribute("authBrokerKeys", keys);
%>
      <script>
         function pageInit()
         {
            <c:if test="${rank == 'primary'}" >
	            if(top.name != "eMFrame")
	            {
	               if(this.top.opener)
	               {
	                  this.top.opener.top.location = "frameservice?taskId=fw.Startup";
	                  this.top.close();
	               }
	            }
	            else if(this != top)
	            {
	               top.location = "frameservice?taskId=fw.Startup";
	            }
         </c:if>
        <c:if test="${!requestScope['Security.Https.required']}">
            top.name="eMFrame";
            if(document.AuthenticateForm != null)
            {
               if(document.AuthenticateForm.username.value.length > 0)
               {
                   document.AuthenticateForm.password.focus();
               }
               else
               {
                    document.AuthenticateForm.username.focus();
               }
            }
        </c:if>
            onChangeProtocol();
        }
        
        nvdsUsernameExample = "<iman:string key="AuthenticateForm.NVDSUserNameExample" />";
        eDirUsernameExample = "<iman:string key="AuthenticateForm.eDirUserNameExample" />";
        function onChangeProtocol()
        {
            // change the example string to match the protocal selected
            var usernameExample = document.getElementById("usernameExample");
            <c:if test="${ShowProtocol}">
               if(document.AuthenticateForm.protocol.value == "<%= DirAuthenticator.VALUE_DEFAULT_PROTOCOL_NDAP %>")
               {
                  usernameExample.innerHTML = eDirUsernameExample;
               }
               else
               {
                  usernameExample.innerHTML = nvdsUsernameExample;
               }
            </c:if>
        }
        
        var req;
      function webacc(){

	      var username = document.AuthenticateForm.username;
	      var password = document.AuthenticateForm.password;
	      var rank = document.AuthenticateForm.rank;
         var protocol = "";
         if(document.AuthenticateForm.protocol)
         {
            protocol = "&protocol="+escape(document.AuthenticateForm.protocol.value); 
         }
        
          
         var tree = document.AuthenticateForm.tree;
          
	      var url = "webacc?taskId=fw.Empty&username=" + escape(username.value)+"&password="+escape(password.value)+"&tree="+escape(tree.value)+"&rank="+escape(rank.value)+protocol;
	          
	      if (window.XMLHttpRequest) 
         {
	        req = new XMLHttpRequest();
	      } 
         else if (window.ActiveXObject) 
         {
	        req = new ActiveXObject("Microsoft.XMLHTTP");
	      }
          
	      req.open("POST", url);
	      req.onreadystatechange = callback;
	      req.send(url);
      }

      function callback() {
         if (req.readyState == 4) 
         {
            if (req.status == 200) 
            {
               parseMessage(req);
            }
         }
      }

      function parseMessage(req) 
      {
         var message = req.responseXML.getElementsByTagName("authentications")[0];
	      var error = req.responseXML.getElementsByTagName("error")[0];
          
	      if(error)
	      {
            var errorText = '<iman:string key="Icon.Error.alt" />';
		      var html = "<img style='float:left;' class='margin8' src='/nps/portal/modules/dev/images/error32.gif' alt='"+errorText+"' title='"+errorText+"'  align='absmiddle'/><FONT FACE='Arial,Helvetica'>"+error.firstChild.firstChild.nodeValue+"</FONT>";
		      var errorMsgDiv = document.getElementById("errorpane");
		      errorMsgDiv.innerHTML = html;
	      }
	      else
	      {
		      var errorMsgDiv = document.getElementById("errorpane");
		      errorMsgDiv.innerHTML = "";
		      //deactivateImanDialog('authenticate');
		      if(document.getElementById("authenticationDataTable"))
		      {
			      var authenticationDataTableDiv = document.getElementById("authenticationDataTable");
			      authenticationDataTableDiv.innerHTML = req.responseText;
		      }
            
            if(document.getElementById("loginList"))
            {
               var loginListDiv = document.getElementById("loginList");
               
               var callBackFunctionName = '<%= pageContext.getRequest().getAttribute("callback") != null ? pageContext.getRequest().getAttribute("callback") : "noCallbackDefined" %>';
               
               var i = 0;
               var html = "";
               while(message.childNodes[i]){
                  var friendlyName = message.childNodes[i].attributes[0].value;
                  var keyName = message.childNodes[i].childNodes[0].nodeValue;
                  html = html+"<div class=\"task3\"><a href=\"javascript:"+callBackFunctionName+"('"+keyName+"')\" >"+friendlyName+"</a></div>"
                  i++;
               }
               loginListDiv.innerHTML = html;
            
               <c:if test='${initCallbackOnSuccess}' >
                  eval(callBackFunctionName+'('+'\''+message.attributes[0].nodeValue+'\''+')');
               </c:if>
            }
	      }
      }
      
	  function checkDefaultKey(evt)
      {
         var form = document.forms[0];
         var keyCode = evt.which ? evt.which : evt.keyCode;
         // 13 is the Enter key code
         if (keyCode == 13)
         {
              document.forms[0].submit();
              return false;
         }
         return true;
      }
      
      function clearError() {
	      var errorMsgDiv = document.getElementById("errorpane");
	      errorMsgDiv.innerHTML = "";
      }

      </script>
      <form name="AuthenticateForm" method=post action="webacc" >
      <c:choose>
         <c:when test="${rank == 'secondary'}" >
            <input type=hidden name="rank" value="secondary"/>
         </c:when>
         <c:otherwise>
            <input type=hidden name="rank" value="primary"/>
         </c:otherwise>
      </c:choose>
      <input type=hidden name="DoLogin" value="true">
      <input type=hidden name="forceMaster" value="<c:out value="${forceMaster}" />"/>
      <input type=hidden name="Login_Key" value="<c:out value="${Login_Key}" />">
      <table border="0" cellpadding="2" cellspacing="0" >
         <tr bgcolor="#458ab9">
            <td valign=middle colspan="2">    
               <c:if test="${closeButton}" >         
                  <a href="javascript:deactivateImanDialog('authenticate')"><IMG class="floatright" src="<%= MUtils.getModulesUrl((HttpServletRequest) pageContext.getRequest()) %>/dev/images/nl_close_16.gif" alt="<iman:string key="Icon.Close.alt" />" title="<iman:string key="Icon.Close.alt" />" border=0 align=right></a>
               </c:if>
               <div class="emframeformhead1"><a href="#" onClick="javascript:window.open('<iman:string key="AuthenticateForm.HelpURL" />', '<iman:string key="Help.WindowName" />', 'toolbar=no,location=no,directories=no,menubar=no,scrollbars=yes,resizable=yes,width=700,height=<iman:string key="Help.WindowHeight" />');"><IMG class="floatright" id=help src='<%= MUtils.getModulesUrl(request) %>/dev/images/help_16.gif' border=0 width=16 height=16 alt="<iman:string key="Button.Help.alt" />" title="<iman:string key="Button.Help.alt" />"></a><iman:string key="AuthenticateForm.LoginTitle" /></div>               
            </td>
            
         </tr>
         
         <c:if test="${requestScope['Url.relogin']}">
            <tr>
               <td colspan="3"><br><b><span class="mediumtext"><iman:string key="AuthenticateForm.Browser.TimeoutMsg" /></span></b><br><br></td>               
            </tr>
         </c:if>
         <c:if test="${!empty unsupportedBrowserMsg}">
            <tr>
              <td colspan="2" style="background-color: #efeeec;">
              <br><b><span class="mediumtext"><iman:string key="AuthenticateForm.Browser.Warn.notSupported" /></span></b><br><br></td>
            </tr>
         </c:if>
         <c:if test="${!empty Error}">
            <c:if test="${Error == 'OldLogin'}">
               <c:set var="Error"><iman:string key="AuthenticateForm.Browser.OldLoginScreenMsg" /></c:set>
            </c:if>
            <tr>     
            <c:choose>
	            <c:when test="${rank == 'secondary'}" >         
	               <td colspan="2" style="background-color: #efeeec;">
	            </c:when>
	            <c:otherwise>
	               <td style="padding: 5px;">
	            </c:otherwise>
            </c:choose>            
               <img height="32" width="32"
                    src="<%= MUtils.getModulesUrl(request)%>/dev/images/error32.gif"
                    alt="<c:out value="${requestScope['GeneralMsg.Alt']}" />"
                    title="<c:out value="${requestScope['GeneralMsg.Alt']}" />"
                    align="absmiddle"/><FONT FACE="Arial,Helvetica"><c:out value="${requestScope['GeneralMsg.MsgBody']}" /></FONT>
            </td>
            </tr>
         </c:if>
         <tr>
         <c:choose>
	         <c:when test="${rank == 'secondary'}" >
	            <td colspan="2" style="background-color: #efeeec; padding: 5px;" >
	         </c:when>
	         <c:otherwise>
	            <td colspan="2" style="padding: 5px;" >
	         </c:otherwise>
         </c:choose>
               <div id="errorpane" ></div>
            </td>
         </tr>
      

        <tr>
           <td height="50" nowrap valign="bottom" class="mediumtext">
                  <iman:string key="AuthenticateForm.UserNameEditBoxHeader" />
              <br>
              <input TABINDEX=1 type="text" name="username" maxLength="256" width="200" style="width: 200px" value="<c:out value='${username}' />" size="40" <c:if test='${Browser_name=="MSIE"}'>onkeypress="return checkDefaultKey(event)"</c:if> />
                  <div id="usernameExample" class="instructions">
                     <c:choose>
                        <c:when test="${DefaultProtocol == 'NDAP'}">
                           <iman:string key="AuthenticateForm.eDirUserNameExample" />
                        </c:when>
                        <c:otherwise>
                           <iman:string key="AuthenticateForm.NVDSUserNameExample" />
                        </c:otherwise>
                     </c:choose>
                  </div>
           </td>
           <c:if test="${rank == 'secondary'}" >
           <td rowspan="5" valign="top" style="background-color: #efeeec; border-bottom: 2px solid #458ab9;  background-color: #efeee9; padding:5px" >
           
	           <div style="height: 200px; background-color: #efeeec; overflow:auto; width=270px;" >
                 <div class="tablesubhead1">Current Authentications</div>
                 <div id="loginList">
	              <c:forEach items="${authBrokerKeys}" var="authBrokerKey">
	                 <div class="task3">
		                 <c:url value="${authBrokerKey}" />
	                 </div>                    
	              </c:forEach>
                 </div>
	           </div>
          </c:if>            
         </td>
        </tr>
        <tr>
           <td valign="bottom" class="mediumtext">
              <iman:string key="AuthenticateForm.PasswordEditBoxHeader" />
              <br>
              <input TABINDEX=2 type="password" name="password" maxLength="256" width="200" style="width: 200px" value="" size="40" <c:if test='${Browser_name=="MSIE"}'>onkeypress="return checkDefaultKey(event)"</c:if> >
           </td>
           <c:if test="${rank == 'secondary'}" >
                      <td>&nbsp;</td>
           </c:if>
        </tr>
        <tr>
            <td valign="bottom" class="mediumtext">
               <c:if test="${ShowTree}">
                  <!-- Tree text -->
                  <iman:string key="AuthenticateForm.TreeEditBoxHeader" />
                  <br>
                  <input TABINDEX=3 type="text" name="tree" width="200" maxLength="256" style="width: 200px" value="<c:out value="${DefaultTree}" />" size="40" <c:if test='${Browser_name=="MSIE"}'>onkeypress="return checkDefaultKey(event)"</c:if>>
                  <div class="instructions">(192.168.14.199, mytree, myserver.company.com)</div>
               </c:if>
            </td>
            <c:if test="${rank == 'secondary'}" >
               <td>&nbsp;</td>
            </c:if>
         </tr>
         <tr>
            <td valign="bottom" class="mediumtext">
               <c:if test="${ShowProtocol}">
                  <!-- Show Protocol prompt -->
                  <iman:string key="AuthenticateForm.ProtocolEditBoxHeader" />
                  <br/>
                  <select TABINDEX=4 onchange="onChangeProtocol();" name="protocol" size=1  style="WIDTH: 200px">
                        <option <c:if test="${DefaultProtocol =='NDAP'}">selected </c:if>value="<%= DirAuthenticator.VALUE_DEFAULT_PROTOCOL_NDAP %>"><iman:string key="AuthenticateForm.ProtocolSelect.NDAP" /></option>
                        <option <c:if test="${DefaultProtocol =='LDAP'}">selected </c:if>value="<%= DirAuthenticator.VALUE_DEFAULT_PROTOCOL_LDAP %>"><iman:string key="AuthenticateForm.ProtocolSelect.LDAP" /></option>
                        <option <c:if test="${DefaultProtocol =='LDAPS'}">selected </c:if>value="<%= DirAuthenticator.VALUE_DEFAULT_PROTOCOL_LDAPS %>"><iman:string key="AuthenticateForm.ProtocolSelect.LDAPS" /></option>
                  </select>
               </c:if>
            </td>
            <c:if test="${rank == 'secondary'}" >
            <td>&nbsp;</td>
            </c:if>
         </tr>
         <tr>
            <td valign="bottom" height="34" class="emframerulebelow" style="padding-top: 10px;">
            <c:choose>
               <c:when test="${rank == 'secondary'}" >
                  <A TABINDEX=5 href="#"  onClick="javascript:webacc();"><img name="<iman:string key="Button.Login.alt" />" alt="<iman:string key="Button.Login.alt" />" title="<iman:string key="Button.Login.alt" />" src="<%= MUtils.getModulesUrl((HttpServletRequest) pageContext.getRequest())%>/dev/images/<iman:string key="Button.Login.image" />" border="0" /></a>&nbsp;
               </c:when>
               <c:otherwise>
                  <INPUT TABINDEX=5 type=image name="<iman:string key="Button.Login.alt" />" alt="<iman:string key="Button.Login.alt" />" title="<iman:string key="Button.Login.alt" />" src="<%= MUtils.getModulesUrl((HttpServletRequest) pageContext.getRequest())%>/dev/images/<iman:string key="Button.Login.image" />" border="0" />&nbsp;
               </c:otherwise>
            </c:choose>
           
            <c:if test="${closeButton}">
               <A TABINDEX=6 href="#" onClick="javascript:deactivateImanDialog('authenticate');clearError();return false"><img class="margin5r" name="Cancel" alt="<iman:string key="Button.Cancel.alt" />" src="<%=MUtils.getModulesUrl((HttpServletRequest) pageContext.getRequest())%>/dev/images/<iman:string key="Button.Cancel.image" />" border=0 ></A>
            </c:if>
            </td>
            <c:if test="${rank == 'secondary'}" >
            <td>&nbsp;</td>
            </c:if>
         </tr>
         <c:if test="${rank == 'primary'}" >
         <tr>
            <td colspan="2" class="smalltext" width="100%"><p><iman:string key="Application.htmlCopyright" /></p></td>
         </tr>
         <c:if test="${(pageContext.request.scheme eq 'http') and Security_Warn_nonSecure}">
             <tr><td colspan="2"  class="smalltext" >
                <b><iman:string key="AuthenticateForm.Warn.nonSecure" /></b>
             <td></tr>
         </c:if>
        </c:if>
      </table>
      </form>               
                  
