<%@page language="java" %>
<%@page import="java.util.*" %>
<%@page import="java.io.*" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html><head>
<meta http-equiv="expires" content="0">
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<meta http-equiv="imagetoolbar" content="no">
<title>Sort The Items</title>

<%

// Creating the Items
Vector items = new Vector();
//for (int i=0; i<9; i++)
//	items.add("Item "+(i+1));
items.add("Small talk");
items.add("Killing time");
items.add("Getting to know him/her");
items.add("Getting/giving advice");
items.add("Reminiscing");
items.add("Getting/giving support");
items.add("Disagreeing or arguing");
items.add("Joking around");
items.add("Catching up");
items.add("Sharing experiences");
items.add("Discussing work/school");
items.add("Persuading");
items.add("Romantic talk");
items.add("Complaining");
items.add("Gossip/talking about others");
items.add("Recapping the day");
items.add("Making plans & arrangements");
items.add("Discussing interests, hobbies");
items.add("Talking about your relationship");
items.add("Talking about problems");
items.add("Asking favors");
items.add("Exchanging information");

int maxUsers=100;
if (pageContext.getRequest().getParameter("textfield1")!=null) {

String dirToSaveIn="C:\\clusteringOutput\\";

File dir=new File(dirToSaveIn);
String[] done=dir.list();
boolean[] doneNums=new boolean[maxUsers];
for (int i=1; i<done.length; i++) {
  if (done[i].endsWith(".esd")) {
    try {
      int one = Integer.parseInt(done[i].substring(0, done[i].indexOf(".")));
      doneNums[one]=true;
      System.out.println("done: "+one);
    } catch (NumberFormatException e) { e.printStackTrace(); }
  }
}

String userID=null;
loop: for (int i=1; i<doneNums.length; i++) {
  if (!doneNums[i]) {
    userID=i+"";
    break loop;
  }
}
System.out.println("userID="+userID);


// Checking for the submitted data
// Output in a format readable by the programs at:
// http://www-3.ibm.com/ibm/easy/eou_ext.nsf/Publish/410

String output=">Cardnames\r\n";
for (int i=0; i<items.size(); i++) {
  output+=items.get(i)+"\r\n";
}

output+=">Person\r\n"+userID+"\r\n";
output+=">Groupnames\r\n===\r\n>Sortresult\r\n";
int groupNumber[]=new int[items.size()];
for (int i=0; i<items.size(); i++) {
  String textFieldData=(String)pageContext.getRequest().getParameter("textfield"+(i+1));
  
  if (textFieldData!=null && textFieldData.length()>4){
    StringTokenizer tokenizer = new StringTokenizer(textFieldData, "\n\r\f");
    while (tokenizer.hasMoreTokens()) {
      String token=(String)tokenizer.nextElement();
      if (token!=null && token.length()>=5)
         groupNumber[Integer.parseInt(token.substring(4))-1]=i;
    }
  }
}
for (int i=0; i<items.size(); i++) {
  output+=(groupNumber[i]+1)+",1\r\n";
}

System.out.println("Output: -----------------------");
System.out.println(output);
System.out.println("End Output -----------------------");

try {

  
  PrintStream outputStream = new PrintStream(new FileOutputStream(dirToSaveIn+userID+".esd", false));
  outputStream.println(output);
} catch (IOException e) {
  cmu.survey.Maintenance.sendBug(e);
}


  out.println("<body>Thank you!</body></html>");
  return;
}


int itemWidth=230;
int itemHeight=30;

int groupWidth=400;
int groupHeight=80;

String textfield="textfield";


out.print("<style type=\"text/css\">");
out.print("<!--\n");

	out.print("#dragWarning {"+
		"  position:relative;"+
		"  background-color:#ffffff;"+
		"  border:2px solid #FF2222;"+
		"}\n"
		);

Vector order = new Vector();
Vector vectorToDeplete = new Vector();
for (int i=0; i<items.size(); i++)
  vectorToDeplete.add(new Integer(i+1));
Random random = new Random();
while (vectorToDeplete.size()>0) {
  int toDeplete = (random.nextInt() % vectorToDeplete.size());
  if (toDeplete<0)
    toDeplete = -toDeplete;
  order.add(vectorToDeplete.get(toDeplete));
  //    System.out.println("Depleting: "+toDeplete);
  vectorToDeplete.remove(toDeplete);
}


for (int i=1; i<=items.size(); i++) {
	out.print("#item"+i+" {"+
		"  position:relative;"+
		"  background-color:#ffffff;"+
		"  border:2px solid #000099;"+
		"}\n"+
		"#group"+i+" {  position:relative;  background-color:#ffffff;  border:1px solid #000099;}\n"
		);
}
out.print("-->\n");
out.print("</style>");
out.print("</head>");



// Start of Body:

out.print("<body bgcolor=\"#ffffff\">");
out.print("<p>");
out.print("<form name=\"form1\" method=\"post\" action=\"\">");
out.print("  <script language=\"JavaScript\" type=\"text/javascript\" src=\"wz_dragdrop.js\"></script>");
out.print("<script language=\"JavaScript\" type=\"text/javascript\" src=\"libraryFunctions.js\"></script>");
out.print("</p>");
out.print("<p><b>To classify the items into groups:</b></p>");
out.print("<ol>");
out.print("  <li>Drag each item into one group below.  Put similar items into the same group.</li>");
// &quot;
out.print("  <li>If there aren't enough groups, click <a href=\"javascript:void(0);\" onClick=\";showANewGroup();return false;\">Add new Group</a> and a new ");
out.print("    box will appear.</li>");
out.print("  <li>Press <input type=\"button\" value=\"Submit\" onClick=\"javascript:submitASort();\"></li>");
out.print("</ol>");

out.print("<table>");
out.print("<tr><td valign=\"top\">");
out.print("<table border=\"0\">");

int[] orderOfItems = new int[items.size()];

for (int i=0; i<items.size(); i++) {
	out.print("<tr>");
        int thisItemNum=((Integer)order.get(i)).intValue();
	out.print("<td><div id=\"item"+(thisItemNum)+"\" style=\"cursor: move; z-index: 54;  width: "+itemWidth+"px; height: "+itemHeight+"px;\">&nbsp;<font face=\"Arial, Helvetica, sans-serif\" size=\"2\">"+items.get(thisItemNum-1)+"</font></div></td>");
	out.print("</tr>");
}

out.print("</table>");
out.print("</td><td>");
out.print("<table border=\"0\">");

for (int i=0; i<items.size(); i++) {
	out.print("<tr>");
	out.print("<td height=\""+groupHeight+"\"><div id=\"group"+(i+1)+"\" style=\"z-index: 50;  width: "+groupWidth+"px; height: "+groupHeight+"px;\"><font face=\"Arial, Helvetica, sans-serif\" size=\"2\">&nbsp;Group<br><br><br></font></div></td>");
	out.print("</tr>");
        if ((i+1) % 6 == 0 && i!=items.size()-1) {
          	out.print("<tr>");
        	out.print("<td><a href=\"javascript:void(0);\" onClick=\";showANewGroup();return false;\">Add new Group</a></td>");
	        out.print("</tr>");
        }
}

out.print("</table>");
out.print("</td></tr><table>\n");

out.print("<div id=\"dragWarning\" style=\"z-index: 600000;  width: 300px; height: 100px;\">&nbsp;<font face=\"Arial, Helvetica, sans-serif\" size=\"2\"><b>Please use the scrollbars on the right to scroll.  You can't drag the item and scroll at the same time.</b></font></div>");

out.print("<script language=\"JavaScript\" type=\"text/javascript\">\n");
out.print("<!--\n");

out.print("SET_DRAGGABLE(CURSOR_MOVE, NO_ALT, NO_SCROLL, RESET_Z, \"dragWarning\"+NO_DRAG");
for (int i=0; i<items.size(); i++) {
	out.print(", \"item"+(i+1)+"\", \"group"+(i+1)+"\"+NO_DRAG");
}
out.print(");\n");

out.print("dd.elements[\"dragWarning\"].hide();\n");

out.print("var numGroups="+items.size()+";\n");

out.print("var nextGroupToShow=7;\n");
out.print("for (var i=nextGroupToShow; i<=numGroups; i++) {\n");

out.print("	if(window.dd && dd.elements[\"group\"+i]){\n");
out.print("		dd.elements[\"group\"+i].hide();\n");

out.print("	}\n");
out.print("}\n");

//out.print("\n");


out.print("function showANewGroup() {");
out.print("	if (dd.elements[\"group\"+nextGroupToShow]) {");
out.print("		dd.elements[\"group\"+nextGroupToShow].show();");
out.print("		nextGroupToShow++;");
out.print("		for(var i=0; i<"+items.size()+"; i++)");
out.print("		  checkIfDroppedInAGroup(dd.elements[\"item\"+(i+1)]);");
out.print("	} else {");
out.print("		alert(\"Sorry, you've reached the max number of groups.  You cannot add more groups than number of items.\");");
out.print("	}");
out.print("}\n");

out.print("var isInMultipleGroups = new Array("+(items.size()+1)+");\n");
out.print("var hasBeenSorted = new Array("+(items.size()+1)+");\n");
out.print("for (var i=0; i<isInMultipleGroups.length; i++) {");
out.print("	isInMultipleGroups[i]=false;");
out.print("	hasBeenSorted[i]=false;");
out.print("}\n");


out.print("function checkIfDroppedInAGroup(draggedItem) {");
out.print("	var drHeight = "+itemHeight+";");
out.print("	var drWidth = "+itemWidth+";");
out.print("	var grWidth="+groupWidth+";");
out.print("	var grHeight="+groupHeight+";");
out.print("	var found=false;");
out.print("	var moveMessageSent=false;");
out.print("	for (var i=1; i<nextGroupToShow; i++) {");
out.print("		if(window.dd && dd.elements[\"group\"+i]) {");
out.print("			var groupItem = dd.elements[\"group\"+i];");
out.print("			if (groupItem.x<draggedItem.x+drWidth &&");
out.print("				 groupItem.y<draggedItem.y+drHeight &&");
out.print("				 groupItem.x+grWidth>draggedItem.x &&");
out.print("				 groupItem.y+grHeight>draggedItem.y) {");
//out.print("				//alert(\"in \"+i+\"  heightc=\"+drHeight);");
out.print("				if (found && !moveMessageSent) {");
out.print("					alert(\"That item is on the boundary of multiple groups!  Please move it so it is only in one group.\");");
out.print("					moveMessageSent=true;");
out.print("					isInMultipleGroups[draggedItem.name.substring(4)]=true;");
out.print("				} else ");
out.print("				   isInMultipleGroups[draggedItem.name.substring(4)]=false;");
out.print("				hasBeenSorted[draggedItem.name.substring(4)]=true;");
//out.print("				alert(\"Has been sorted: \"+draggedItem.name.substring(4));");
out.print("				addToAGroup(i, draggedItem.name);");
out.print("				found=true;");
out.print("			} else {");
//out.print("				//alert(\"groupItem.x=\"+groupItem.x+\"  draggedItem.x+drWidth=\");");
out.print("			}");
out.print("		} else {");
out.print("			alert(\"bug: not finding group #\"+i+\" in the length of \"+dd.elements.length);");
out.print("		}");
out.print("	}");
out.print("	if (!found) {");
out.print("		removeFromAllGroups(draggedItem.name);");
out.print("		isInMultipleGroups[draggedItem.name.substring(4)]=false;");
out.print("		hasBeenSorted[draggedItem.name.substring(4)]=false;");
out.print("	}");
out.print("}\n");
out.print("dump(\"dddddddump\");");

out.print("function addToAGroup(groupNum, itemName) {\n");
out.print("	removeFromAllGroups(itemName);");
out.print("	var field = getAnObject(\""+textfield+"\"+groupNum);");
out.print("	if (field.value.indexOf(itemName)>-1) {");
out.print("	} else {");
out.print("		field.value+=itemName+\"\\n\";");
out.print("	}");
out.print("}\n");

out.print("function removeFromAllGroups(itemName) {\n");
//out.print("	// Remove it from the group it's in");
out.print("	for (var i=1;i<=numGroups; i++) {");
out.print("		removeFromAGroup(i, itemName);");
out.print("	}");
out.print("}\n");

out.print("function removeFromAGroup(groupNum, itemName) {\n");
out.print("	if (groupNum<=numGroups) {");
out.print("		var field = getAnObject(\""+textfield+"\"+groupNum);");
out.print("		var index = field.value.indexOf(itemName);");
out.print("		if (index>-1) {");
out.print("			field.value=field.value.substring(0, index)+field.value.substring(index+itemName.length+1);");
out.print("		}");
out.print("	} else {");
out.print("		alert(\"removeFromAGroup called with a group that doesn't exist: \"+groupNum);");
out.print("	}");
out.print("}\n");

out.print("function submitASort(){");
//out.print("          alert(\"submitASort\");");
out.print("	var theForm = getAnObject('form1');");
out.print("	if (theForm==null) {");
out.print("		alert(\"You can only submit this in a newer browser.  JavaScript on this browser is implemented wrong.\");");
out.print("		return false;");
out.print("	}");
out.print("     for (var i=1; i<="+items.size()+"; i++) {");
out.print("       if (isInMultipleGroups[i]) {");
out.print("          alert(\"Some items are overlapping two separate groups.  You still need to sort them into just a single group.\");");
out.print("          return false;");
out.print("       }");
out.print("       if (!hasBeenSorted[i]) {");
out.print("          alert(\"Some items have not been sorted into a group. You still need to sort them into a group.\");");
out.print("          return false;");
out.print("       }");
out.print("     }");
out.print("     ");
out.print("	theForm.submit('submit');");
out.print("	return true;");
out.print("}");

out.print("//-->\n");
out.print("</script>\n");
out.print("</p>\n");


out.print("<input type=\"button\" value=\"Submit\" onClick=\"javascript:submitASort();\"><br>\n");
for (int i=0; i<items.size(); i++) {
	//out.print("<input type=\"text\" name=\""+textfield+(i+1)+"\">");
	out.print("<input type=\"hidden\" name=\""+textfield+(i+1)+"\">");
	//out.print("<textarea cols=\"40\" rows=\"4\" name=\""+textfield+(i+1)+"\"></textarea>");
}
out.print("</form>");

/* Current bugs:
Current Bugs:
- When you add a new group, it doesn't check to see if items are already in it, so they are unsorted
- it doesn't mark items as being in multiple groups (for feedback before submit -- it should do that)
- it should mark items as unsorted until they are sorted (for feedback before submit)
- Does not work in Netscape 4.  The boxes don't show at their full height there. :(
    - check current fixes
    - Possible fixish hack: show borders of tables
    - also show all groups -- users may not realize they're not all groups yet!
- dragWarning shows up under the dragged items
*/
%>
</body></html>
