<%@  page pageEncoding="utf-8" contentType="text/html;charset=utf-8" import="com.novell.webaccess.common.JSPConduit, com.novell.emframe.dev.D, com.novell.emframe.dev.eMFrameUtils, com.novell.emframe.dev.GlobalRegistry, com.novell.emframe.dev.utils.LocUtils" %>
<%   JSPConduit c = JSPConduit.getJSPConduit(request);
   c.stringTable("DevResources");
   c.stringTable("FwResources"); %>
<%@page import="java.util.Locale"%>
<HTML>
<HEAD>
<TITLE><%= c.toHTML(c.string("RBSManagement.BookPageTitle")) %></TITLE>
<LINK   href="<%= c.getModulesUrl() + "/dev/css/hf_style.css" %>"
        rel="styleSheet"
        type="text/css">

<jsp:include page='<%= c.getPath("dev/MoveListItems_inc.jsp") %>' flush="true" />
<jsp:include page='<%= c.getPath("dev/eMFrameScripts_inc.jsp") %>' flush="true" />
<%
	c.stringTable("FwResources");
	int myButtonWidth = c.string("Book.MovePageDown").length();
	if (c.string("Book.MovePageUp").length() > myButtonWidth)
		myButtonWidth = c.string("Book.MovePageUp").length();
%>
<%
	int fontSize = 16;
	int padding = 5;
	double wFactor = .55;
	String theLocale = (String) session.getAttribute("ClientLocale");
	if (theLocale.startsWith("zh") || theLocale.equalsIgnoreCase("ja")
			|| theLocale.equalsIgnoreCase("ru")) {
		wFactor = 1.0;
	}
	double w = myButtonWidth;
	w = ((w > 0) ? w : 10);
	w = w * fontSize * wFactor + padding * 2 + 2;
%>
<style>
      .myButton { font-size: .8em; cursor: pointer; width: <%= w%>px; background-color: #c9c6bf; color: #; border-bottom-width:1; border-right-width:1; border-bottom-color:gray; border-right-color:gray }
   </style>
   
<SCRIPT language="JavaScript">


    function detectBrowser()
    {
        var appVer = navigator.appVersion;
        var iePos = appVer.indexOf('MSIE');
        if (iePos != -1)
        {
            document.BookPageForm.AvailablePages.attachEvent('ondblclick',addSelectedItems);
            document.BookPageForm.AssignedPages.attachEvent('ondblclick',removeSelectedItems);
        }

        sortAvailList(document.BookPageForm.AvailablePages.options);
//      sortAssignedList(document.BookPageForm.AssignedPages.options);
    }

   /*******************
    * FUNCTION HEADER *
    *******************/
    function onPageLoad()
    {
        var form = document.BookPageForm;

        if (form.AvailablePages.length > 0)
        {
            form.AvailablePages.focus();
            form.AvailablePages[0].selected = true;
            form.Description.value = parseDescription(form.AvailablePages.options[0].value);
        }
    }


   /*******************
    * FUNCTION HEADER *
    *******************/
    function setListFocus(list)
    {
        if (list.name == "AssignedPages")
        {
            document.BookPageForm.AvailablePages.selectedIndex=-1;
        }
        else
        {
            document.BookPageForm.AssignedPages.selectedIndex=-1;
        }

        return;
    }

   /*******************
    * FUNCTION HEADER *
    *******************/
   function addSelectedItems(event)
   {
	   var availOpt      = document.BookPageForm.AvailablePages.options;
	   var optOpt        = document.BookPageForm.AssignedPages.options;
      var selectedNum   = 0;

      if (document.BookPageForm.AvailablePages.selectedIndex == -1)
      {
         // Nothing is selected in the Available Pages list when the user clicked on the add button. Just return.
         return;
      }

	   for (var i=(availOpt.length-1); i>=0; i--)
	   {
		   if(availOpt[i].selected)
		   {
		   		var value = availOpt[i].value;
  		    	var valueChapter = value.split("$$$");	
	   		   if(!ifDuplicateChapterAdd(valueChapter[1],availOpt[i].text,valueChapter[0],false,availOpt[i].selected))
	   		   {	
	   		   		var optgroup = document.createElement('optgroup');
					optgroup.label = valueChapter[1];
					var option = new Option(availOpt[i].text, valueChapter[0], false, availOpt[i].selected);
					option.innerHTML = availOpt[i].text;
					optgroup.appendChild(option);
					var select = document.getElementById("AssignedPages");
					select.appendChild(optgroup);		  
	   		   }			   
	   		   availOpt[i] = null;
			   selectedNum = i;
		   }
	   }

      document.BookPageForm.elements["BookPageFormChanged"].value = "true";
//    sortAssignedList(optOpt);
      setAvailableListFocus(availOpt,selectedNum);
    }

   /*******************
    * FUNCTION HEADER *
    *******************/
   function removeSelectedItems(event)
   {
       var availAttrOpt = document.BookPageForm.AvailablePages.options;
       var optAttrOpt   = document.BookPageForm.AssignedPages.options;
       var selectedNum  = 0;

       if (document.BookPageForm.AssignedPages.selectedIndex == -1)
       {
         // Nothing is selected in the Assigned Pages list when the user clicked on the remove button. Just return.
         return;
       }

       for (var i=(optAttrOpt.length-1); i>=0; i--)
       {
       		
          if(optAttrOpt[i].selected)
          {
          	 var opValue = optAttrOpt[i].value;
          	 var opText = optAttrOpt[i].text;
          	 var chapName = getChapterName(optAttrOpt[i].value);
          	 if(chapName == null)
          	 	chapName = "Other";	//Bad , Should never come here
          	 var value = opValue+"$$$"+chapName[0];
             availAttrOpt[availAttrOpt.length] = new Option(opText, value, false, false);
             if(chapName[1])
	             optAttrOpt[i] = null;
             selectedNum = i;                        	
          }
       }

       document.BookPageForm.elements["BookPageFormChanged"].value = "true";
       sortAvailList(availAttrOpt);
       setAssignedListFocus(optAttrOpt,selectedNum);
    }

   /*******************
    * FUNCTION HEADER *
    *******************/
   function setAssignedListFocus(list,num)
   {
      if(list.length > 0)
      {
         if(list[num] == null)
         {
           document.BookPageForm.AssignedPages.selectedIndex = num - 1;
         }
         else
         {
           document.BookPageForm.AssignedPages.selectedIndex = num;
         }
         getDescription(document.BookPageForm.AssignedPages);
      }
      else
      {
         document.BookPageForm.AvailablePages.selectedIndex = 0;
         getDescription(document.BookPageForm.AvailablePages);
      }
   }

   /*******************
    * FUNCTION HEADER *
    *******************/
    function setAvailableListFocus(list,num)
    {
       if(list.length > 0)
       {
          if(list[num] == null)
          {
            document.BookPageForm.AvailablePages.selectedIndex = num - 1;
          }
          else
          {
            document.BookPageForm.AvailablePages.selectedIndex = num;
          }
          getDescription(document.BookPageForm.AvailablePages);
       }
       else
       {
         document.BookPageForm.AssignedPages.selectedIndex = 0;
         getDescription(document.BookPageForm.AssignedPages);
       }
    }

    function sortAssignedList(x)
    {
        var iePos = navigator.appVersion.indexOf('MSIE');
        sortedArray = new Array();

        for (var i=0; i<x.length; i++) {
            sortedArray[i] = new Array(x[i].text, x[i].value, false, false);
        }

        sortedArray.sort(sortBYtext);

        for (var i=0; i<x.length; i++) {
            x[i] = new Option(sortedArray[i][0], sortedArray[i][1], sortedArray[i][2], sortedArray[i][3]);
            if (iePos == -1)
                x[i].addEventListener("dblclick",removeSelectedItems, false);
            x[i].selected = sortedArray[i][3];
        }

        return;
    }


   function sortAvailList(x)
   {
      var iePos = navigator.appVersion.indexOf('MSIE');
      sortedArray = new Array();

      for (var i=0; i<x.length; i++)
      {
          sortedArray[i] = new Array(x[i].text, x[i].value, false, x[i].selected);
      }

      sortedArray.sort(sortBYtext);

      for (var i=0; i<x.length; i++)
      {
         x[i] = new Option(sortedArray[i][0], sortedArray[i][1], sortedArray[i][2], sortedArray[i][3]);
         if (iePos == -1)
         {
              x[i].addEventListener("dblclick",addSelectedItems, false);
         }

         x[i].selected = sortedArray[i][3];

         if (iePos == -1)
         {
            if (x[i].selected == true)
            {
               x.selectedIndex = i;
            }
         }
      }

      return;
   }


    function sortBYtext(a,b)
    {
        if(a[0].toLowerCase() < b[0].toLowerCase())
        {
            return -1;
        }

        if(a[0].toLowerCase() > b[0].toLowerCase())
        {
            return 1;
        }

        return 0;
    }


   /*******************
    * FUNCTION HEADER *
    *******************/
    function onPageSubmit()
    {
        if(document.BookPageForm.elements["BookPageFormChanged"].value == "true")
        {
           var assignedBoxLength = document.BookPageForm.AssignedPages.length;
           if(assignedBoxLength == 1)
           {
               if (document.BookPageForm.AssignedPages.options[0].text == emptyListBracket)
               {
                   var message = "<%= c.toScript(c.string("BookSummary.NoPageAssignment")) %>";
                   message += "\n";
                   message += "<%= c.toScript(c.string("BookSummary.Continue")) %>";

                   if (!confirm(message))
                   {
                       return false;
                   }
               }
           }
           formatAssignedPageData();
        }

        document.BookPageForm.submit();
    }


   /*******************
    * FUNCTION HEADER *
    *******************/
    function formatAssignedPageData()
    {
        var boxLength = document.BookPageForm.AssignedPages.length;

        // Get everything in the AssignedPages list
        AssignedPages = new Array(boxLength);

        for (i = 0; i < boxLength; i++)
        {
            if (document.BookPageForm.AssignedPages.options[i].text != emptyListBracket)
            {
                // This needs to be the full name
                 AssignedPages[i] = urlEncode(parseName(document.BookPageForm.AssignedPages.options[i].value));
            }
        }

        // Convert array into delimited string to be passed into the java file
        var strAssignedPages = AssignedPages.join(";");
        document.BookPageForm.elements["AssignedPagesString"].value = strAssignedPages;

        return;
    }


   /*******************
    * FUNCTION HEADER *
    *******************/
    function getDescription(list)
    {
        if ((list != null) && (list.selectedIndex != -1))
        {
            var desc = parseDescription(list.options[list.selectedIndex].value);
            document.BookPageForm.Description.value = desc;
        }
    }


   /*******************
    * FUNCTION HEADER *
    *******************/
    function parseDescription(nameAndDescription)
    {
        var nameDescArray = nameAndDescription.split("$");
        var desc = nameDescArray[1];
        if(desc == null)
        {
            return "";
        }

        return urlDecode(desc);
    }


   /*******************
    * FUNCTION HEADER *
    *******************/
    function parseName(nameAndDescription)
    {
        var nameDescArray = nameAndDescription.split("$");
        return urlDecode(nameDescArray[0]);
    }
    
    function ifDuplicateChapterAdd(chapName,text,value,state,selected)
    {
    	var optgroups = document.BookPageForm.AssignedPages.getElementsByTagName("optgroup");
    	for(var i=0; i<optgroups.length; i++)
    	{
    		if(optgroups[i].label == chapName)
    		{
    			var option = new Option(text,value,state,selected);
    			option.innerHTML = text;	//For ie browser explicitly set
    			optgroups[i].appendChild(option);
    			return true;
    		}
    	}
    	return false;
    }
    
    function getChapterName(optionValue)
    {
    	var optgroups = document.BookPageForm.AssignedPages.getElementsByTagName("optgroup");
    	for(var i=0; i<optgroups.length; i++)
    	{
    		var optGrp = optgroups[i];
    		var options = optGrp.getElementsByTagName("option");
    		var arr = new Array(2);
    		for(var j=0; j< options.length; j++)
    		{
    			if(options[j].value == optionValue)
    			{
					if(options.length == 1)
		            {
        		     	var select = document.getElementById("AssignedPages");
						select.removeChild(optgroups[i]);	
						arr[0] = optGrp.label;
						arr[1] = false;	
	    				return arr;
		            }
		            arr[0] = optGrp.label;
					arr[1] = true;
    				return arr;
    			}    				
    		}	
    	}
    	return null;
    }
        
    function swapOptGroups(optGrp1, optGrp2)
    {
    	var i = 0;
    	var j = 0;
    	var options1 = optGrp1.getElementsByTagName("option");
    	var options2 = optGrp2.getElementsByTagName("option");

    	var tmpLabel = optGrp1.label;
    	optGrp1.label = optGrp2.label;
    	optGrp2.label = tmpLabel;

    	while(i < options1.length && j < options2.length)
    	{
    		//Swap options
    		var tmpVal = options1[i].value;
			var tmpText = options1[i].text;
			options1[i].value = options2[j].value;
			options1[i].text = options2[j].text;
			options2[j].value = tmpVal;
			options2[j].text = tmpText;
    		i++;
    		j++;
    	}
		if(options1.length == options2.length)
			return;	//done
		if(options1.length < options2.length)
		{
			var len = options2.length;
			var firstCase = true;
			while(j < len)
			{			
				var newOption = document.createElement("option");
				if(firstCase)
				{
					newOption.setAttribute("value",options2[j].value);
					newOption.innerHTML = options2[j].text;
					optGrp1.appendChild(newOption);
					optGrp2.removeChild(options2[j]);
					firstCase = false;
				}
				else
				{
					newOption.setAttribute("value",options2[j-1].value);
					newOption.innerHTML = options2[j-1].text;
					optGrp1.appendChild(newOption);
					optGrp2.removeChild(options2[j-1]);	
				}
				j++;
			}	
		}   	
		else
		{
			var len = options1.length;
			var firstCase = true;
			while(i < len)
			{				
				var newOption = document.createElement("option");
				if(firstCase)
				{
					newOption.setAttribute("value",options1[i].value);
					newOption.innerHTML = options1[i].text;
					optGrp2.appendChild(newOption);
					optGrp1.removeChild(options1[i]);
					firstCase = false;
				}
				else
				{
					newOption.setAttribute("value",options1[i-1].value);
					newOption.innerHTML = options1[i-1].text;
					optGrp2.appendChild(newOption);
					optGrp1.removeChild(options1[i-1]);
				}
				i++;
			}	
		}
    }
    
    function swapOptions(sel, i1, i2, dir)
      {
      	var optgroups = sel.getElementsByTagName("optgroup");
      	var o = sel.options;
      	
  		for(var i = 0; i < optgroups.length; i++)
		  {
		    var done = false;
		    var optgroup = optgroups[i];
		    var label = optgroup.label;
		    
		    // collect the options into an array
		    var options = optgroup.getElementsByTagName("option");
		    
		    for (var j = 0; j < options.length; j++)
		    {
		        var option = options[j];
		        if(option.value == o[i2].value)
		        {
		        	done=true;
		        	if(i1>=0 && i2>=0 && i1<o.length && i2<o.length)
		       		{
		       			//Move the optgroup up
		       			if(j == 0 && dir == "up")
		       			{
		       				swapOptGroups(optgroup,optgroups[i-1]);
		       				break;	
		       			}
		       			//Move the optgroup down	
		       			if(j == options.length-1 && dir == "down")
		       			{
		       				swapOptGroups(optgroup,optgroups[i+1]);
		       				break;	
		       			}
					      var tmpVal = o[i1].value;
			           	  var tmpText = o[i1].text;
				          o[i1].value = o[i2].value;
				          o[i1].text = o[i2].text;
				          o[i2].value = tmpVal;
				          o[i2].text = tmpText;
				          o.selectedIndex = i1;
				          break;
				    }	
		        }
		        else
		          continue;
		    }
		    if(done)
		      break;
		  }         
		  document.BookPageForm.elements["BookPageFormChanged"].value = "true";
      }

      function moveUp(sel)
      {
         swapOptions(sel, sel.selectedIndex-1, sel.selectedIndex, "up");
      }

      function moveDown(sel)
      {
         swapOptions(sel, sel.selectedIndex+1, sel.selectedIndex, "down");
      }

</SCRIPT>
</HEAD>
<BODY   TEXT="#000000" LINK="#000000" VLINK="#000000" ALINK="#000000" bgcolor="#FFFFFF"
        onload="onPageLoad(),detectBrowser()">

<FORM   name="BookPageForm"
        method=post
        action="webacc">

   <input   type=hidden
            name="taskId"
            value="<%= c.var("taskId") %>">

   <input   type=hidden
            name="merge"
            value="dev.GenConf">

   <input   type=hidden
            name="error"
            value="dev.GenErr">

   <input   type=hidden
            name="User.context"
            value="<%= c.var("User.context") %>">

   <input   type=hidden
            name="nextState"
            value="saveBookPageList">

   <input   type=hidden
            name="AssignedPagesString"
            value="">

   <input   type=hidden
            name="BookPageFormChanged"
            value="false">

   <!-- End of hidden tags -->

    <% c.set("TaskHeader.title", c.toHTML(c.string("ModifyBookPageList")));
       c.set("TaskHeader.iconUrl", "dir/rbsBook.gif");
       c.set("TaskHeader.helpFile", "base/modifypagelist.html"); %>
    <jsp:include page='<%= c.getPath("dev/TaskHeader_inc.jsp") %>' flush="true" /><BR>

    <TABLE width="100%" border="0" cellspacing="0" cellpadding="3">
        <TR>
            <TD class="mediumtext">
                <B><%= c.toHTML(c.string("BookPage.BookName")) %></B>&nbsp;<%= c.toHTML(c.var("BookName_Value")) %>
            </td>
        </tr>
        <TR>
            <TD class="mediumtext">
                &nbsp;
            </td>
        </TR>
        <TR>
            <TD class="formdescriptext">
                <%= c.toHTML(c.string("BookPage.Instruction")) %>
            </td>
        </tr>
            <TD class="mediumtext">
                &nbsp;
            </td>
    </table>
    <TABLE>
        <TR>
            <TD align="left" class="mediumtext" valign="bottom">
                <%= c.toHTML(c.string("BookPage.AvailablePages")) %>
            </TD>
            <TD align="left"></TD>
            <TD align="left" class="mediumtext" valign="bottom">
                <%= c.toHTML(c.string("BookPage.AssignedPages")) %>
            </TD>
        </TR>
        <TR>
            <TD>
                <SELECT name="AvailablePages" size=10 WIDTH="250" style="WIDTH: 250px"
                        multiple
                        onchange="getDescription(this);setListFocus(this)">
                    <% c.set("j", "0");
                       if (c.var("AvailablePage.Count").equals("0")) { %>
                        <OPTION value="urlEncode("NoName")$"><%= c.toHTML(c.string("Generic.EmptyListBracket")) %>
                    <% }
                       while (c.lt(c.var("j"), c.var("AvailablePage.Count"))) { %>
                        <OPTION value="<%= c.urlEncode(c.var("AvailablePage.Element."+c.var("j"))) %>$<%= c.urlEncode(c.var("AvailablePage.Description."+c.var("j"))) %>$$$<%= c.var("AvailablePage.Chapter."+c.var("j")) %>" ><%= c.toHTML(c.var("AvailablePage.TranslatedElement."+c.var("j"))) %> </OPTION>
                        </optgroup>
                        <% c.inc("j");
                       } %>
                </SELECT>
            </TD>
            <TD>
                <a href="#" onClick="javascript:addSelectedItems();return false"><IMG src="<%= c.getModulesUrl() + "/dev/images/" + c.string("Button.ArrowRight.image") %>" alt="<%= c.toHTML(c.string("Button.ArrowRight.alt")) %>" title="<%= c.toHTML(c.string("Button.ArrowRight.alt")) %>" border=0></a>
                <BR>
                <a href="#" onClick="javascript:removeSelectedItems();return false"><IMG src="<%= c.getModulesUrl() + "/dev/images/" + c.string("Button.ArrowLeft.image") %>" alt="<%= c.toHTML(c.string("Button.ArrowLeft.alt")) %>"  title="<%= c.toHTML(c.string("Button.ArrowLeft.alt")) %>" border=0></a>
                <BR>
            </TD>
            <TD>
                <SELECT name="AssignedPages" id="AssignedPages" size=10 WIDTH="250" style="WIDTH: 250px"
                        multiple
                        onchange="getDescription(this);setListFocus(this)">
                    <% c.set("i", "0");
                       if (c.var("AssignedPage.Count").equals("0")) { %>
                        <OPTION value="urlEncode("NoName")$"><%= c.toHTML(c.string("Generic.EmptyListBracket")) %>
                    <% }
                       while (c.lt(c.var("i"), c.var("ChapterCount"))) { 
                    	   c.set("j", "0"); %>
                    	   <optgroup label="<%= c.var("ChapterName."+c.var("i")) %>"> <%
                    	   while(c.lt(c.var("j"), c.var("ChapterName."+c.var("i")+"PageCount"))) { %>
                    		   <OPTION value="<%= c.urlEncode(c.var("ChapterName."+c.var("i")+"AssignedPage.Element."+c.var("j"))) %>$<%= c.urlEncode(c.var("ChapterName."+c.var("i")+"AssignedPage.Description."+c.var("j"))) %>"><%= c.toHTML(c.var("ChapterName."+c.var("i")+"AssignedPage.TranslatedElement."+c.var("j"))) %> </OPTION>               		   
                    		   <% c.inc("j"); 
                    	 }  %>
							</optgroup>         
             		   <% c.inc("i");   	   
                 	 } %>
                </SELECT>
            </TD>
            <TD valign="top"><INPUT type="button" name="moveUpButton" class="myButton"
			onClick="javascript:moveUp(document.BookPageForm.AssignedPages)" 
			value="<%= c.toHTML(c.string("Book.MovePageUp")) %>"><BR>
 		    <INPUT type="button" name="moveDownButton" class="myButton"
			onClick="javascript:moveDown(document.BookPageForm.AssignedPages)" 
			value="<%= c.toHTML(c.string("Book.MovePageDown")) %>"><BR>
			</TD>
        </TR>
        <TR>
            <TD colspan="3" class="mediumtext" valign="bottom">
                <BR><%= c.toHTML(c.string("GetBookName.Description")) %><BR>
                <TEXTAREA name="Description" rows="3" cols="32" readonly></TEXTAREA>
            </TD>
        </TR>
        <TR>
            <TD>&nbsp;</TD>
        </TR>
    </TABLE>
    <jsp:include page='<%= c.getPath("dev/Bar_inc.jsp") %>' flush="true" />
    <a href="#" onClick="javascript:onPageSubmit();return false">
    <IMG src="<%= c.getModulesUrl() + "/dev/images/" + c.string("Button.OK.image") %>" alt="<%= c.string("Button.OK.alt") %>" title="<%= c.string("Button.OK.alt") %>" border=0></a>
    <jsp:include page='<%= c.getPath("dev/Cancel_inc.jsp") %>' flush="true" />
</FORM>
</BODY></HTML>
