<%@ page pageEncoding="utf-8" contentType="text/html;charset=utf-8"%>
<%@ page import="com.novell.webaccess.common.JSPConduit" %>
<%@ page import="com.novell.emframe.fw.FwUtils" %>
<%@ page import="com.novell.nps.utils.Utils" %>
<%@ page import="java.util.Hashtable" %>
<%@ page import="java.util.Enumeration" %>
<%@ page import="java.util.Vector" %>
<%@ page import="com.novell.emframe.dev.*" %>
<%
   JSPConduit c = JSPConduit.getJSPConduit(request);
   c.stringTable("DevResources");
   c.stringTable("FwResources");
%>

<%@ taglib uri="/WEB-INF/iman.tld" prefix="iman" %>
<%@ taglib uri="/WEB-INF/c.tld" prefix="c" %>
<%@ taglib uri="/WEB-INF/x.tld" prefix="x" %>
<iman:stringtable bundle="DevResources"/>
<iman:stringtable bundle="FwResources"/> 

<%
   String agent = request.getHeader("User-Agent");
   boolean isIE = agent.indexOf("Microsoft Internet Explorer") != -1 || agent.indexOf("MSIE") != -1;
   request.setAttribute("isIE", "" + isIE);
%>

<c:choose>
   <c:when test="${isIE}" >
      <c:set var="mainTableAttributes" value='height="100%" width="100%"'/>
      <c:set var="topRightDivStyles" value="overflow:auto; height:100%; border:'1px black solid'"/>
    </c:when>
   <c:otherwise>
      <c:set var="mainTableAttributes" value='height="300px" width="730px"'/>
<%--      <c:set var="mainTableAttributes" value='height="${param.screenWidth}px" width="730px"'/>--%>
      <c:set var="topRightDivStyles" value="overflow:auto; height:250px; border:1px black solid"/>
   </c:otherwise>
</c:choose>



<HTML>
<HEAD>
   <iman:stylesheet/>
   <SCRIPT src="<c:out value="${ModulesPath}" />/fw/javascripts/Studio.js"></SCRIPT>
   <SCRIPT src="<c:out value="${ModulesPath}" />/fw/javascripts/Menu.js"></SCRIPT>
   <iman:eMFrameScripts/>
   <iman:osScripts/>
   <iman:mvedScripts />
   <iman:menubarScripts/>

   <iman:include page="dev/XmlScripts_inc.jsp" />


   <STYLE>
      .nitem {cursor:'pointer'}
      .nonclickable {background-color: #f5f5f5}
      .WINDOWDRAG{border-color:#000000;border-width:3;border-style:solid;position:absolute;}

      .paneContent {width: 100%; overflow:auto; border: 1px solid black}
      .pane {position:absolute; visibility: hidden}
      .paneTitle   {width:100%; margin-bottom: 2px; color: white; font-weight: bold; font-size: 1em; background-color: #6b8899; text-align: left; text-indent: 0.2em; letter-spacing: 0.05em; vertical-align: middle; padding: 0.2em }
   </STYLE>


   <SCRIPT>
      window.rc_mustEnterParams = "<iman:string key="Studio.mustEnterRequiredParams"/>";
      window.rc_requiredField = "<iman:string key="Studio.requiredField"/>";
      window.rc_enterRequiredParams = "<iman:string key="Studio.enterRequiredParams"/>";
      window.rc_modifyParams = "<iman:string key="Studio.modifyParams"/>";
      window.rc_changeControlTo = "<iman:string key="Studio.changeControlTo"/>";
      window.rc_removeField = "<iman:string key="TaskBuilder.RemoveField"/>";
      window.rc_changeControl = "<iman:string key="TaskBuilder.ChangeControl"/>";
	
	  var addedAttributes = 0;

      window.var_pluginType = "<%= c.var("pluginType")%>";
      window.var_taskId = "<%= c.var("taskId")%>";

      function whatsThis()
      {
         alert("<%= c.string("TaskBuilder.PublicPageDescription") %>");
      }

      // global vars
      var selectedAttribute = null;       // Keep index of last attribute clicked on
      var currentControlNames = null;     // String array of control names of selectedAttribute
      var currentControlIds = null;       // String array of control ids of selectedAttribute
      var selectedFields = new Array();   // Hashtable of selected fields (key=attribute name; value=PluginField object

      function AttributeInfo(displayName, controlXmls, controlNames, controlIds)
      {
         this.m_displayName = displayName;
         this.m_controlXmls = controlXmls;
         this.m_controlNames = controlNames;
         this.m_controlIds = controlIds;
      }

      var availableAttributes = [
      <% int count = Integer.parseInt(c.var("attributes.count"));
         for(int i=0; i<count; i++)
         {
            out.print("\"" + c.toScript(c.var("attributes."+i+ ".safeName")) + "\"");
            if(i+1<count)
            {
               out.print(",");
            }
         }
      %>];
      
      var filePathMap = new Array()
      <% 
      	 int attrCount = Integer.parseInt(c.var("attributes.count"));
      	 //We need to build a list of UIHandlers
      	 String packedHandlers = "";
      	 String[] unpackedHandlers = null;
      	 String tempHandler = null;
      	 Vector handlers = new Vector();
         for(int i=0; i<attrCount; i++)
         {
         	packedHandlers = c.var("attributes."+i+ ".controlIds");
         	unpackedHandlers = eMFrameUtils.unpack(packedHandlers, eMFrameFactory.getMContext(request));
         	for(int handlerCount = 0; handlerCount < unpackedHandlers.length; handlerCount++)
         	{
         		tempHandler = unpackedHandlers[handlerCount];
         		if(tempHandler.indexOf(".") != -1)
         		{
         			tempHandler = tempHandler.substring(tempHandler.indexOf(".")+1, tempHandler.length());
         			if(!handlers.contains(tempHandler))
         			{
         				handlers.add(tempHandler);
         			}
         		}
         	}
         }
         for(int i=0; i<handlers.size(); i++)
         {
            %>
            <c:set var="stringKey">Studio.UIHandlers.images.<%= (String) handlers.get(i) %></c:set>
            filePathMap["<%= c.toScript( (String) handlers.get(i))%>"] = "<iman:string key="${stringKey}"/>";
            <%
         }
            
      %>

      <%-- hashtable of attribute display names --%>
      var attrInfoMap = new Array();
      var mandatoryAttrs = new Array();
      <% count = Integer.parseInt(c.var("attributes.count"));
         for(int i=0; i<count; i++)
         {
            String safeName = c.var("attributes."+i+ ".safeName");
            out.println("attrInfoMap[\"" + c.toScript(safeName) + "\"] = new AttributeInfo(\"" + c.toScript(c.var("attributes."+i+ ".name")) + "\", \"" + c.toScript(c.var("attributes."+i+ ".controlXmls")) + "\", \"" + c.toScript(c.var("attributes."+i+ ".controlNames")) + "\", \"" + c.toScript(c.var("attributes."+i+ ".controlIds")) + "\");");

            if(c.var("attributes."+i+ ".required").equals("true"))
            {
               out.println("mandatoryAttrs[\"" + c.var("attributes."+i+ ".safeName") + "\"] = \"true\";");
            }
         }
      %>


      var initialAttrs = new Array();
      <%
         String[] initialFieldNames = (String[]) request.getAttribute("initialFieldNames");
         for(int i=0; i<initialFieldNames.length; i++)
         {
            out.println("initialAttrs[initialAttrs.length] = \"" + FwUtils.getSafeName(initialFieldNames[i]) + "\";");
         }
      %>


      var initialFieldsMap = new Array();
      <%
         Hashtable initialFields = (Hashtable)request.getAttribute("initialFields");
         if(initialFields!=null)
         {
            Enumeration enumer = initialFields.keys();
            while (enumer.hasMoreElements())
            {
               String key = (String) enumer.nextElement();
               String id = (String)initialFields.get(key);
               out.println("initialFieldsMap[\"" + FwUtils.getSafeName(key) + "\"] = \"" + id + "\";");
            }
         }
      %>


      function doInstall()
      {
         var ok = gatherData();
         if(ok)
         {
            if(document.pluginProperties.pluginName.value.length==0)
            {
               alert("<iman:string key="Studio.enterPluginName"/>");
               return;
            }

            if(document.pluginProperties.pluginName.value.indexOf(".") != -1)
            {
               alert("<iman:string key="Studio.noDotInPluginName"/>");
               return;
            }
            if(document.pluginProperties.pluginName.value.indexOf("&") != -1)
            {
            	alert("<iman:string key="Studio.noAmberInPluginName"/>");
            	return;
            }


            <c:if test="${pluginType=='task' || pluginType=='create'}">
               var collectionName = document.pluginProperties.rbsCollection.value.toUpperCase();
               if(collectionName.length==0)
               {
                  alert("<iman:string key="TaskBuilder.MustEnterRbsCollectionName"/>");
                  return;
               }

               var roles = mvGetValuesAsArray("roleName");
               for(var i=0; i < roles.length; i++)
               {
                  var roleName = roles[i].toUpperCase();
                  if(roleName!="" && roleName.indexOf(collectionName)==-1)
                  {
                     alert("<iman:string key="TemplateBuilder.roleMustbeInCollection"/>");
                     return;
                  }
               }
            </c:if>


            document.pluginProperties.merge.value = "dev.GenConf";
            document.pluginProperties.target = "_self";
            document.pluginProperties.nextState.value = "doInstall";
            document.pluginProperties.submit();
         }
      }

      function doMore()
      {
         var url = "frameservice?taskId=dev.Empty&merge=fw.Studio_more&pluginType=<c:out value="${pluginType}"/>";

         <c:if test="${pluginType=='create'}">
            url += "&modifyTask=" + document.pluginProperties.modifyTask.value;
            url += "&addToCreateObject=" + document.pluginProperties.addToCreateObject.value;
         </c:if>

         <c:if test="${pluginType=='page'}">
            url += "&pageOrder=" + document.pluginProperties.pageOrder.value;
         </c:if>

         url += "&labelAboveControl=" + document.pluginProperties.labelAboveControl.value;
         url += "&mooEnabled=" + document.pluginProperties.mooEnabled.value;
         url += "&objectTypeNameReg=" + document.pluginProperties.objectTypeNameReg.value;
         url += "&displayName=" + escape(document.pluginProperties.displayName.value);

         url += "&tcClassName=" + document.pluginProperties.tcClassName.value;
         url += "&tcListObjectName=" + document.pluginProperties.tcListObjectName.value;
         url += "&tcStaticList=" + document.pluginProperties.tcStaticList.value;

         window.open(url, "MoreParameters", "toolbar=no,location=no,directories=no,menubar=no,scrollbars=yes,resizable=yes,width=540,height=600");
      }

      function menuHandler(menuItemId)
      {
         if(menuItemId=="install")
         {
            doInstall();
         }
         else if(menuItemId=="preview")
         {
            if(addedAttributeCount > 0)
            {
            	preview();
            }
            else
            {
            	alert("<iman:string key="TaskBuilder.SelectAnAttribute"/>");
            }
         }
         else if(menuItemId=="exit")
         {
         	var ok = confirm("<iman:string key="Studio.confirmExit"/>");
			if(ok)
			{         	
            	window.location = "webacc?NPService=fw.LaunchService&NPAction=Return&return=cancel&returnID=<c:out value="${taskId}"/>";
            }
         }
         else if(menuItemId=="makeAllFieldsReadOnly")
         {
            makeAllReadOnly();
         }
         else if(menuItemId=="makeAllFieldsMandatory")
         {
            makeAllMandatory();
         }
      }
   </SCRIPT>

</HEAD>

<BODY onLoad="init()" rightmargin="0" bottommargin="0" onresize="doLayout()">

   <DIV id="title" >
      <TABLE width="100%" cellpadding="0" cellspacing="0">
         <TR><TD><iman:taskHeader titleKey="Studio.taskName" helpFile="fw/studio_main.html" /></TD></TR>
         <TR>
            <TD>
               <iman:menubar id="studioMenu" menuActionHandler="menuHandler">
                  <iman:menuItem textKey="Studio.install" id="install"/>
                  <iman:menuItem textKey="Studio.preview" id="preview"/>
                  <iman:menuItem textKey="Studio.exit" id="exit"/>
<%-- See Bug 249591  --%>
<%--                  <iman:menuItem textKey="Studio.actions" id="actions"> --%>
<%--                     <iman:menuItem textKey="Studio.makeAllFieldsReadOnly" id="makeAllFieldsReadOnly"/> --%>
<%--                     <iman:menuItem textKey="Studio.makeAllFieldsMandatory" id="makeAllFieldsMandatory"/> --%>
<%--                  </iman:menuItem> --%>
               </iman:menubar>
            </TD>
         </TR>
         <TR height="8px"><TD> </TD></TR>
      </TABLE>
   </DIV>



   <DIV id="topLeft" class="pane">
      <DIV id="topLeftTitle" class="paneTitle">
         <iman:string key="Studio.pluginFields"/>
      </DIV>

      <DIV id="topLeftContent" style="overflow:auto;width:100%">
         <TABLE width="100%" id="items" cellspacing="2" cellpadding="0">
            <c:if test="${isIE}"><TR id="firstRow" height="10"><TD></TD></TR></c:if>
            <TR id="drop_0" style="height:1px" ><TD colspan="3" height="1px" bgColor="#000000"></TD></TR>
            <TR height="100%"></TR>
         </TABLE>
      </DIV>
   </DIV>

   <DIV id="topRight" class="pane">
      <DIV id="topRightTitle" class="paneTitle">
         <iman:string key="Studio.Attributes"/>
      </DIV>

      <DIV id="topRightContent" class="paneContent">
         <FORM name="form">
         <TABLE id="availFields" border="0" bgColor="#f5f5f5" width="100%">

            <% int size = Integer.parseInt(c.var("attributes.count"));
               for(int i=0; i<size; i++) { %>

               <%
                  String imageName = c.var("attributes." + i + ".image");
                  String path = c.getModulesUrl() + "/dev/images/";
                  if(!imageName.equals("star.gif"))
                  {
                     path += "dir/";
                  }

                  String onClick = null;
                  if(c.var("attributes." + i + ".uihandler.count").equals("0"))
                  {
                     onClick = "alert('"+c.string("Studio.noControlForAttribute")+"')";
                  }
                  else
                  {
                     onClick = "if(event.altKey){addDefaultControl(" + i + ");}else{toggleRow(event);showControls('"+i+"');}return false;";
                  }
               %>

               <TR class="nitem" id="attr_<%= c.toTag(c.var("attributes."+i+ ".safeName")) %>" onmouseover="sel(event)" onmouseout="unsel(event)" onClick="<%= onClick %>" onDblClick="addDefaultControl(<%= i %>); return false;">
                  <TD><IMG src="<%= path + imageName %>" alt="<%= c.toDisplay(c.var("attributes."+i+ ".imageAlt")) %>" title="<%= c.toDisplay(c.var("attributes."+i+ ".imageAlt")) %>"></TD>
                  <TD><A href="#" style="text-decoration:none;color:#000000;font-size:13px"><%= c.toHTML(c.var("attributes."+i+ ".name")) %></A></TD>
               </TR>

            <% } %>

         </TABLE>
         </FORM>
      </DIV>
   </DIV>

   <DIV id="bottomLeft" class="pane">
      <DIV id="bottomLeftTitle" class="paneTitle">
         <iman:string key="Studio.pluginProperties"/>
      </DIV>

      <DIV id="bottomLeftContent" style="overflow:auto;width:100%">
         <FORM name="pluginProperties" method="POST" action="webacc">
            <TABLE width="130%" cellspacing="0" cellpadding="2">
               <TR><TD><nobr><iman:string key="Studio.pluginId"/>&nbsp;&nbsp;</nobr></TD><TD width="100%"><INPUT type="text" name="pluginName" maxlength="63" value="<c:out value="${pluginId}"/>" onBlur="copyName()" <c:if test="${modify=='true'}">readOnly="true" </c:if>style="width:<iman:string key="UI.textboxPixel"/>"></TD></TR>

               <c:choose>

                  <c:when test="${pluginType=='task' || pluginType=='create'}">
                     <TR><TD><nobr><iman:string key="Studio.rbsCollection"/>&nbsp;&nbsp;</nobr></TD><TD><INPUT type="text" name="rbsCollection" style="width:<iman:string key="UI.textboxPixel"/>" value="<c:out value="${rbsCollection}"/>"><iman:os typeFilter="rbsCollection2" control="rbsCollection" history="true" windowed="true" /></TD></TR>
                     <TR>
                        <TD><nobr><iman:string key="Studio.rbsRole"/>&nbsp;&nbsp;</nobr></TD>
                        <TD>
<%--                           <INPUT type="text" name="roleName" style="width:<iman:string key="UI.textboxPixel"/>" value="<c:out value="${rbsRole}"/>"><iman:os typeFilter="rbsRole2" control="roleName" history="true" windowed="true"/>--%>
                           <TABLE cellpadding="0" cellspacing="0">
                              <TR>
                                 <TD><iman:mved name="roleName" items="${rbsRole}" objectTypeName="rbsRole2" history="true" /></TD>
                                 <TD>&nbsp;<nobr><SPAN class="smalltext2d"><iman:string key="TaskBuilder.RoleIsOptional"/></SPAN></nobr></TD>
                              </TR>
                           </TABLE>
                        </TD>
                     </TR>
                  </c:when>

                  <c:when test="${pluginType=='page'}">
                     <TR><TD><%= Utils.replaceSubString(c.string("TaskBuilder.BookName"), " ", "&nbsp;") %></TD><TD><INPUT type="text" name="book" value="<c:out value="${book}"/>" style="width:<iman:string key="UI.textboxPixel"/>"><iman:os typeFilter="rbsBook2" control="book" history="true" windowed="true"/></TD></TR>
                     <TR>
                        <TD><iman:string key="TaskBuilder.Chapter"/></TD>
                        <TD>
                           <TABLE>
                              <TR>
                                 <TD><INPUT type="radio" name="chapterSrc" value="existing" <c:if test="${chapterSrc!='new'}">checked</c:if>>&nbsp;<%= c.string("TaskBuilder.Existing") %></TD>
                                 <TD>
                                    <SELECT name="chapterName1" style="width:159">
                                    <%
                                       int num = c.toInt("chapters.length");
                                       String chapterId = c.var("chapterId");

                                       for(int i=0; i<num; i++)
                                       {
                                          String id = c.var("chapters."+i+ ".id");
                                          boolean sel = (chapterId!=null && chapterId.equals(id));

                                          out.print("<OPTION value=\"" + i +"\"" );
                                          if(sel) out.println("selected");
                                          out.print(">" + c.toDisplay(c.var("chapters."+i+ ".name")));

                                       }
                                    %>
                                    </SELECT>
                                 </TD>
                              </TR>
                              <TR>
                                 <TD><INPUT type="radio" name="chapterSrc" value="new" <c:if test="${chapterSrc=='new'}">checked</c:if>>&nbsp;<%= c.string("TaskBuilder.New") %></TD>
                                 <TD><INPUT type="text" name="chapterName2" style="width:159" value="<c:if test="${chapterSrc=='new'}"><c:out value="${chapterId}"/></c:if>"></TD>
                              </TR>
                           </TABLE>
                        </TD>
                     </TR>
                     <TR><TD><%= c.string("TaskBuilder.Public") %></TD><TD><INPUT type="checkbox" name="public" <c:if test="${isPublic=='true'}" >checked</c:if>>&nbsp;<A href="#" onClick="whatsThis();"><%= c.string("TaskBuilder.WhatIsThis") %></A></TD></TR>
                  </c:when>
               </c:choose>






               <TR><TD colspan="2"><A href="#" onClick="doMore()"><iman:string key="Studio.advanced"/></A></TD></TR>

               <TR height="100%"></TR>
            </TABLE>


            <%-- hidden non-plugin specific --%>
            <INPUT type="hidden" name="taskId" value="<c:out value="${taskId}"/>">
            <INPUT type="hidden" name="merge" value="dev.GenConf">
            <INPUT type="hidden" name="modify" value="<c:out value="${modify}"/>">
            <INPUT type="hidden" name="error" value="dev.GenErr">
            <INPUT type="hidden" name="nextState">
            <INPUT type="hidden" name="attributeNames">
            <INPUT type="hidden" name="attributeHandlerIds">
            <INPUT type="hidden" name="attributeHandlerXmls">
            <INPUT type="hidden" name="objectTypeName" value="<c:out value="${objectTypeName}"/>">
            <INPUT type="hidden" name="client" value="<c:out value="${client}"/>">
            <INPUT type="hidden" name="pluginType" value="<c:out value="${pluginType}"/>">
            <INPUT type="hidden" name="auxPack" value="<c:out value="${auxPack}"/>">
            <INPUT type="hidden" name="nextUrl"><%-- Used only for preivew --%>


            <%-- hidden plug-in specific --%>
            <c:choose>
               <c:when test="${pluginType=='create'}">
                  <INPUT type="hidden" name="modifyTask" value="<c:out value="${modifyTask}"/>">
                  <INPUT type="hidden" name="addToCreateObject" value="false"><%-- MREMIND: load from xml --%>
                  <INPUT type="hidden" name="namingAttribute" value="true"><%-- MREMIND: load from xml --%>
               </c:when>
               <c:when test="${pluginType=='task'}">
               </c:when>
               <c:when test="${pluginType=='page'}">
                  <INPUT type="hidden" name="pageOrder" value="<c:out value="${pageOrder}"/>">
               </c:when>
               <c:otherwise>
               </c:otherwise>
            </c:choose>


            <%-- parameters shown on the "more" page --%>
            <c:if test="${empty mooEnabled}"><c:set var="mooEnabled" value="true"/></c:if>
            <INPUT type="hidden" name="mooEnabled" value="<c:out value="${mooEnabled}"/>">

            <c:if test="${empty labelAboveControl}"><c:set var="labelAboveControl" value="true"/></c:if>
            <INPUT type="hidden" name="labelAboveControl" value="<c:out value="${labelAboveControl}"/>">

            <INPUT type="hidden" name="objectTypeNameReg" value="<c:out value="${objectTypeNameReg}"/>">

            <INPUT type="hidden" name="displayName" value="<c:out value="${displayName}"/>">


            <INPUT type="hidden" name="tcClassName" value="<c:out value="${tcClassName}"/>">
            <INPUT type="hidden" name="tcListObjectName" value="<c:out value="${tcListObjectName}"/>">
            <INPUT type="hidden" name="tcStaticList" value="<c:out value="${tcStaticList}"/>">

         </FORM>
      </DIV>
   </DIV>

   <DIV id="bottomRight" class="pane">
      <DIV id="bottomRightTitle" class="paneTitle">
         <iman:string key="Studio.controls"/>
      </DIV>

      <DIV id="bottomRightContent" class="paneContent" style="overflow:auto;width:100%">
         <TABLE width="100%" height="100%" id="ControlsTable" bgColor="#f5f5f5">
            <TR width="100%" height="100%"><TD>&nbsp;</TD></TR>
         </TABLE>
      </DIV>
   </DIV>

   <DIV ID="winDrag" STYLE="display:none;" CLASS="WINDOWDRAG"></DIV>
   <DIV ID="changeControlBox" STYLE="display:none; border:1px black solid; height:125px; width:180px; position:absolute; background-color:white;" valign="top"></DIV>

   <form name="controlPropertiesForm" method="POST" action="frameservice" target="controlParams">
      <input type="hidden" name="taskId" value="fw.Create iManager Task"/>
      <input type="hidden" name="nextState" value="attributeDetails"/>
      <input type="hidden" name="merge" value="fw.Studio_params"/>
      <input type="hidden" name="attributeName"/>
      <input type="hidden" name="xml"/>
      <input type="hidden" name="objectTypeName"/>
   </form>

   <iman:osFooter/>


</BODY>
</HTML>
