<%-- 
  Copyright 2003 Sun Microsystems, Inc. All rights reserved 
  Use is subject to license terms.
 --%> 
<%-- contentedit.jsp --%>
<%@ page import="com.sun.portal.providers.containers.jsp.single.JSPSingleContainerProvider,
                 com.sun.portal.providers.containers.jsp.table.JSPTableContainerProvider,
                 com.sun.portal.providers.Provider,
                 com.sun.portal.providers.ProviderWidths,
                 com.sun.portal.providers.containers.jsp.tab.UnmodifiableTab,
                 java.util.Map,
                 java.util.Iterator,
                 java.util.Collections,
                 java.util.List,
                 java.util.ArrayList"
%>

<%@ page session="false" %>

<%@ taglib uri="/tld/desktop.tld" prefix="dt" %>
<%@ taglib uri="/tld/jx.tld" prefix="jx" %>
<%@ taglib uri="/tld/desktopProviderContext.tld" prefix="dtpc" %>
<%@ taglib uri="/tld/desktopContainerProviderContext.tld" prefix="dtcpc" %>
<%@ taglib uri="/tld/desktopTheme.tld" prefix="dttheme" %>

<%
   JSPSingleContainerProvider scp = (JSPSingleContainerProvider)pageContext.getAttribute("JSPProvider");
   String container = (String)request.getParameter("container");
	 pageContext.setAttribute( "container", container, PageContext.REQUEST_SCOPE );
   String parentContainer = scp.getProviderContext().getDefaultChannelName();
   String parentContainerProvider = scp.getProviderContext().getProviderName(parentContainer);
   String selectedTabName = request.getParameter("selected");
   JSPTableContainerProvider tcp = (JSPTableContainerProvider)scp.getContainerProviderContext().getProvider(request, scp.getName(), container);
   pageContext.setAttribute( "tableProvider", tcp );
   String fontFace1 = (String)pageContext.getAttribute("fontFace1", PageContext.REQUEST_SCOPE);
%>


<dt:obtainContainer container="$tableProvider">
  <dtcpc:containerProviderContext>
  <dt:getAvailableChannels id="availableChannels"/>
  <dt:getSelectedChannels id="selectedChannels"/>
  <jx:declare id="selectedChannels" type="List"/>
  <jx:declare id="availableChannels" type="List"/>
  
<%
if ( parentContainer.equals("FrameTabContainer") ) { 
%>
<jsp:include page="framePreferenceHeader.jsp" flush="true"/>
<%
} else if ( parentContainerProvider.equals("JSPTabContainerProvider") ) { 
%>
<jsp:include page="tabPreferenceHeader.jsp" flush="true"/>
<%
} else if (parentContainerProvider.equals("JSPTableContainerProvider") ){
%>
<jsp:include page="tablePreferenceHeader.jsp" flush="true"/>
<%
} else if (parentContainerProvider.equals("JSPSingleContainerProvider") ) {
%>
<jsp:include page="singlePreferenceHeader.jsp" flush="true"/>
<%
} else {
%>
<jsp:include page="defaultHeader.jsp" flush="true"/>
<%
}
%>

<script src="<dt:scontent/>/close-windows.jsp" language="JavaScript" type="text/javascript"></script>

<%@ include file="contentLayoutBar.jsp" %>

<jsp:include page="JSPCreateChannelContainer/createchannelcontent.jsp" flush="true"/>

<FORM ACTION="<dtpc:getDesktopURL/>" TARGET="_parent" METHOD="POST" NAME="contentForm" ENCTYPE="application/x-www-form-urlencoded" >
<INPUT TYPE=HIDDEN NAME="action" SIZE=-1 VALUE="process">
<INPUT TYPE=HIDDEN NAME="provider" SIZE=-1 VALUE="JSPContentContainer">
<INPUT TYPE=HIDDEN NAME="container" SIZE=-1 VALUE="<%=container%>">
    <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="0" WIDTH="100%">
      <TR>
        <TD ALIGN="CENTER">
          <CENTER>
        <P>
        <TABLE BORDER="0" CELLPADDING=2 CELLSPACING="0" WIDTH="100%">
          <TR>
            <TD COLSPAN="2" BGCOLOR="<dttheme:getAttribute name="tabColor" default="#CCCCCC"/>">
            <FONT COLOR="<dttheme:getAttribute name="tabFontColor" default="#000000"/>" SIZE="+0" FACE="Verdana"><b>
                Select the Channels you would like displayed on this Page.<BR> </b>
                </FONT>
            </TD>
          </TR>
          <TR><TD COLSPAN="2">
                <B><FONT SIZE="-1">Legend: T = thin column, W = wide column, FT = full top column, FB = full bottom column</FONT></B>
            </TD>
          </TR>
  <TR><td bgcolor="#FFFFFF"><img src="<dt:scontent/>/images/spacer.gif" width=
"100%" height="20" alt="Spacer Image"></td></TR>        
  
  <%-- Get the list of categories for this container --%>
  <dtpc:getLocalePropertiesFilters id="localeFilter"/>
  <dtpc:getCollectionProperty  key="categories" pfList="$localeFilter" id="categories"/>
  
  <%-- Declare categories, because it will be used in scriptlets --%>
  	<jx:declare id="categories" type="Map"/>

   	<jx:declare id="categEntry" type="String"/>   
  <%-- Create the arraylist --%>
  <% 
  	int channelTotal        = 0;                          // Total number of channels in the page
	int channelCount        = 0;                          // Channels in a caegory
	List leftList           = null;                       // Left column categories
	int leftChannelCount    = 0;                          // Total number of channels in the left column
	int categCount          = categories.size();          // Category Count
	List rightList          = new java.util.ArrayList();  // Right column categories
        List categsWithCount    = new java.util.ArrayList(categCount); // List with n:category format - n # of channels
        StringBuffer buf        = new  StringBuffer();
	//Get the iterator to get all the channels for each category
        Iterator itr = categories.keySet().iterator();
	String tempVar = null;
        String leftColumn  = "notEmpty";
	String rightColumn = "notEmpty";
	List   strayList   = null;
	
	// Get a copy of the available channels and remove the channels with category information
	// from the list, which will be the list of channels with no categories. 
	// Shallow copy will do the job here, hence clone.
	List missedList = new ArrayList(availableChannels);
        String [] missedChannels = null;
	
        // Build up a list with entry of the format n:categoryName where
        // n is the number of channels for the category. This is required to
	// build up a plan to effectively use the real estate on the page.
	// The mapping between the categories and the channel count has to be 
	// preserved but we need a sorted list, so build a string list like this.
	while(itr.hasNext()) {
	    // Get one category at a time
	    categEntry = (String)itr.next();
	    // Set the category in the pagecontext to be used by the tags
            pageContext.setAttribute("categEntry",categEntry);
    	    
  %>
	<%-- Get the list of channels for that category, which is a collection property in the container dp --%>
	   <dtpc:getCollectionProperty id="channelsInCategory" pfList="$localeFilter" key="$categEntry"/>   
	   <jx:declare id="channelsInCategory" type="Map"/> 
 	   
           <%-- Remove this channels from the missedList, the missedList should only have channels without category info --%>
	   <jx:forEach var="channelEntry" items="$channelsInCategory"> 
		<jx:set var="channel">
		    <jx:expr value="$channelEntry.key"/>
		</jx:set>
	        <jx:declare id="channel" type="String"/>
  <%
           missedList.remove(channel);
	   if(!availableChannels.contains(channel)) {
	       if(strayList == null) {
	           strayList = new ArrayList();
	       }
               strayList.add(channel);
	   } 
	   
  %>
	</jx:forEach>
  <%
	   // Clear stray channels
           if(strayList != null) {
	       for(Iterator i = strayList.iterator(); i.hasNext();) {
	           channelsInCategory.remove(i.next());
               }
	       strayList.clear();
           }
           // Number of channels in that category
	   channelCount = channelsInCategory.size();
           // Update the total count
	   channelTotal += channelCount;
           // clear the buff
	   buf.delete(0,buf.length());
	   // Add an entry to the categsWithCount list of the format n:category
	   if(channelCount<10) {
           	categsWithCount.add(buf.append(channelCount).append(":").append(categEntry).toString());
	   } else {
                categsWithCount.add(buf.append(":").append(channelCount).append(":").append(categEntry).toString());	
 	   } 
	
	}
	   // Get the total number of channels without any category information
	   int missedChannelsCount = missedList.size();
        
	   if(missedChannelsCount > 0) {
              	channelTotal += missedChannelsCount;
	   	buf.delete(0,buf.length());
	   	missedChannels = new String[missedChannelsCount];
            	// Create an entry of the format n:Uncategorized, hence all these channels can be grouped
		// under the category uncategorized
		if(missedChannelsCount < 10 ) {
		    categsWithCount.add(buf.append(missedChannelsCount).append(":").append("Uncategorized").toString());
		} else {
		    categsWithCount.add(buf.append(":").append(missedChannelsCount).append(":").append("Uncategorized").toString());
		}	
            	categCount++;
		for(int i = 0; i < missedChannelsCount; i++) {
                    missedChannels[i] = (String)missedList.get(i);
            	}
           	// Set this in page context
		pageContext.setAttribute("missedChannels",missedChannels);     		  
	   }
	   
	pageContext.setAttribute("categsWithCount",categsWithCount); 
  
	// Sort the list, to build the plan.
	Collections.sort(categsWithCount);
 	// The idea here is print the output in two columns so that both the
	// columns are aprroximately equal.

	tempVar = (String)categsWithCount.get(categCount-1);
	boolean singleDigit = true;
	if(tempVar.charAt(0) == ':') {
	    singleDigit = false;
	}
	int rightChannelCount = 0;
	if(singleDigit) {
	    rightChannelCount = Integer.parseInt(tempVar.substring(0,tempVar.indexOf(':')));
	    // Just add the category name not the n:category string
	    rightList.add(tempVar.substring(tempVar.indexOf(':')+1));
		
        } else {
	    rightChannelCount = Integer.parseInt(tempVar.substring(1,tempVar.lastIndexOf(':')));
	    // Just add the category name not the n:category string
	    rightList.add(tempVar.substring(tempVar.lastIndexOf(':')+1));
	
	}
  	// Remove the entry that has been added to the right list
	categsWithCount.remove(categCount-1);

	// If the biggest category is greater than half the channel count,
	// then that category alone goes to one column and the rest goes to the other.
	if(rightChannelCount >= channelTotal/2) {
	    int count = categsWithCount.size();
	    for(int i = 0; i < count; i++) {
		tempVar = (String)categsWithCount.get(i);
	        singleDigit = true;
		if(tempVar.charAt(0) == ':') {
	    	    singleDigit = false;
		}
		if(singleDigit) {
		    categsWithCount.set(i,tempVar.substring(tempVar.indexOf(':')+1));
		} else {
		    categsWithCount.set(i,tempVar.substring(tempVar.lastIndexOf(':')+1));
		}
	    }
	    leftList = categsWithCount;
        } else {
	    // Add the categories one by one to the rightlist, till rightList ~= leftList
	    int changingSize = categCount - 1;
	    while(changingSize > 0) {
	        tempVar = (String)categsWithCount.get(0);
		singleDigit = true;
		if(tempVar.charAt(0) == ':') {
	    	    singleDigit = false;
		}
		if(singleDigit) {
		    channelCount = Integer.parseInt(tempVar.substring(0,tempVar.indexOf(':')));
	            rightList.add(tempVar.substring(tempVar.indexOf(':')+1));
		} else {
		    channelCount = Integer.parseInt(tempVar.substring(1,tempVar.lastIndexOf(':')));
	            rightList.add(tempVar.substring(tempVar.lastIndexOf(':')+1));
		} 
		
		rightChannelCount += channelCount;
		changingSize--;
		categsWithCount.remove(0);
                if(rightChannelCount >= channelTotal/2)
		{
	    	    int count = categsWithCount.size();
	    	    for(int j = 0; j < count; j++) {
			tempVar = (String)categsWithCount.get(j);
			singleDigit = true;
			if(tempVar.charAt(0) == ':') {
	    	    	    singleDigit = false;
			}
			if(singleDigit) {
		            categsWithCount.set(j,tempVar.substring(tempVar.indexOf(':')+1));
			} else {
			    categsWithCount.set(j,tempVar.substring(tempVar.lastIndexOf(':')+1));
			}
	    	    }
	    	    leftList = categsWithCount;
		    break;
	        }
	    }
	}
	
	// Get the left height and right height. Adjust it, so that
        // left side is always taller or equal to the right side
        leftChannelCount = channelTotal - rightChannelCount;
             
	if( leftChannelCount == 0 && rightChannelCount ==0) {
	    //If there are no channels, handle that
	    leftColumn = "empty";
	    rightColumn = "empty";
	} else if(leftChannelCount == 0) {
            // only one coloumn
	    leftList = rightList;
	    rightColumn = "empty";
	} else if( leftChannelCount < rightChannelCount) {
            // Make the left side taller.
	    Object hold = leftList;
            leftList = rightList;
            rightList = (List)hold;
        }

	
	List [] lists = {leftList,rightList};
        String [] isEmpty = {leftColumn,rightColumn};
	pageContext.setAttribute("lists",lists);
  	pageContext.setAttribute("isEmpty",isEmpty);
  
 %>
   
 <% int i = 0; %>
 <TR>
    <jx:forEach var="listI" items="$lists">
    	<jx:declare id="listI" type="List"/>
        <jx:set var="emptyCheck">
            <%=isEmpty[i]%>
       	</jx:set>
       	<jx:declare id="emptyCheck" type="String"/>
        <jx:if test="$emptyCheck != 'empty'">
	    <% i++; %> 	
            <TD VALIGN="TOP">
	        <TABLE BORDER="0" CELLPADDING=2 CELLSPACING="0" WIDTH="100%">
                    <jx:forEach var="category" items="$listI">
	        	<jx:declare id="category" type="String"/>
	    		<jx:choose>
		            <jx:when test="$category == 'Uncategorized'">
			        <% pageContext.setAttribute("channels",missedChannels); 
				   Boolean empty = null;
				   if (missedChannels.length > 0) {
				       empty = Boolean.FALSE;
				   } else {
				       empty = Boolean.TRUE;
				   }
				pageContext.setAttribute("empty", empty); %>
			    </jx:when>
		            <jx:otherwise>
				<dtpc:getCollectionProperty id="channelsInCategory" pfList="$localeFilter" key="$category"/>   
	                	<jx:declare id="channelsInCategory" type="Map"/> 
				<% 
				   for(Iterator j = channelsInCategory.keySet().iterator(); j.hasNext(); ) {
					String chan = (String)j.next();
					if(!availableChannels.contains(chan)) {
					    j.remove();
					}
				   }
				   pageContext.setAttribute("channels", channelsInCategory.keySet()); 
				   Boolean empty = null;
				   if(channelsInCategory.size() > 0 ) {
				       empty = Boolean.FALSE;
				   } else {
				       empty = Boolean.TRUE;
				   }
				   pageContext.setAttribute("empty",empty);
				%>
		    	    </jx:otherwise>
		        </jx:choose>
			<jx:if test="$empty == false">
			<TR>
				<TD><B>
						<jx:choose>
							<jx:when test="$category == 'Uncategorized'">
								Uncategorized
							</jx:when>
							<jx:otherwise>
								<%=category%>
							</jx:otherwise>
						</jx:choose>
				</B></TD>
			</TR>
			</jx:if>
            	        
		        <%-- Retrieve channel removable properties  --%> 
		        <dtpc:getCollectionProperty id="channelsIsRemovable" key="channelsIsRemovable"/>  
		        <dtpc:getBooleanProperty id="defaultIsRemovable" key="defaultChannelIsRemovable"/>
		        <jx:declare id="channelsIsRemovable" type="Map"/> 
		        <jx:declare id="defaultIsRemovable" type="Boolean"/>
		        <jx:declare id="isRemovable" type="Boolean"/>

			<jx:forEach var="channelN" items="$channels">
		            <TR>
				<TD>
			    	    <jx:declare id="channelN" type="String"/>
				    <dtcpc:obtainChannelFromContainer channel="$channelN">
      			    	    <dt:isPresentable id="presentable"/>
      			            <jx:if test="$presentable">
				    
				    <dt:getTitle id="title" silentException="true"/>
                                    <dt:getDescription id="desc" silentException="true"/>
      			            <dt:getWidth id="width" silentException="true"/>
      			            <jx:declare id="title" type="String"/>
      			            <jx:declare id="desc" type="String"/>
      			            <jx:declare id="width" type="Integer"/>
      			            <jx:declare id="channel" type="String"/>
  		            <%
      			            String widthchar = "";
  		            %>
      			            <jx:choose>
            		                <jx:when test="$width == 1">
  		            <%
         			            widthchar = "T";
  		            %>
            		                </jx:when>
            		                <jx:when test="$width == 2">
  		            <%
         			            widthchar = "FT";
  		            %>
            		                </jx:when>
            		                <jx:when test="$width == 3">
  		            <%
         			            widthchar = "FB";
  		            %>
            		                </jx:when>
            		                <jx:otherwise>
  		            <%
         			            widthchar = "W";
 		             %>
            		    		</jx:otherwise>
        		    	    </jx:choose>

  		            <%-- Determine if the channel is removable and display accordingly --%> 
  		            <%
  		            Boolean rmapVal = (Boolean)channelsIsRemovable.get(channelN);
  		            isRemovable     = defaultIsRemovable;
  		            
  		            if (rmapVal != null) {
  		              isRemovable = rmapVal;
  		            }
  		            
  		            pageContext.setAttribute("isRemovable", isRemovable); 
  		            %>

      			            <jx:if test="$isRemovable">
                                      <jx:if test="$width != -1">
  		    	    <%
      			    	    String checked = "";
      			            if  (selectedChannels.contains(channelN)) {
           		        	checked = "CHECKED";
      			            }
			    %>      
                           <TR><TD><INPUT TYPE=CHECKBOX NAME="<%=channelN%>" VALUE="1" <%=checked%>>
      		    				<%=title%> ( <%=widthchar%> ) <BR>
      		    				<FONT SIZE=-1><%=desc%></FONT>
                                    </TD></TR>

                                      </jx:if>
      			            </jx:if>
				    
                                    </jx:if>	
    		    		    </dtcpc:obtainChannelFromContainer>			    	
				</TD>
		    	    </TR>
                   	</jx:forEach>
                    </jx:forEach>		
		</TABLE>
    	    </TD>
          </jx:if>
      </jx:forEach>
  </TR>

      
          </TABLE>
            </CENTER>
<BR>
<CENTER>
<FONT SIZE=+0 FACE="<%=fontFace1%>">
<INPUT TYPE=SUBMIT NAME="Submit" onClick="closeWindows('detached$'); return true;" VALUE="Finished" style='background-color:<dttheme:getAttribute name="titleBarColor" default="#333366"/>;color:<dttheme:getAttribute name="titleFontColor" default="#ffffff"/>'>
<INPUT TYPE=BUTTON ONCLICK="top.document.location.href='<dtpc:getDesktopURL/>'" VALUE="Cancel" style='background-color:<dttheme:getAttribute name="titleBarColor" default="#333366"/>;color:<dttheme:getAttribute name="titleFontColor" default="#ffffff"/>'>
</font>
</CENTER>
<BR>
        </TD>
    </TR>
</TABLE>
</FORM>
</CENTER>
<%
if ( parentContainer.equals("FrameTabContainer") ) { 
%>
<jsp:include page="framePreferenceMenubar.jsp" flush="true"/>
<%
} else if ( parentContainerProvider.equals("JSPTabContainerProvider") ) { 
%>
<jsp:include page="tabPreferenceMenubar.jsp" flush="true"/>
<%
} else if (parentContainerProvider.equals("JSPTableContainerProvider") ){
%>
<jsp:include page="tablePreferenceMenubar.jsp" flush="true"/>
<%
} else if (parentContainerProvider.equals("JSPSingleContainerProvider") ) {
%>
<jsp:include page="singlePreferenceMenubar.jsp" flush="true"/>
<% 
} else {
%>
<jsp:include page="defaultMenubar.jsp" flush="true"/>
<%
}
%>
<%@ include file="footer.html" %>

  </dtcpc:containerProviderContext>
</dt:obtainContainer>

