// file webqcode.js: WebQ main code
// Based on a script originally written by Rick Watson 
// (rwatson@uga.cc.uga.edu) Department of Management, University of Georgia
// January, 1997,
// and adapted by Peter.Schmolck@unibw-muenchen.de Dec-08-1997 
// and by Eshref Januzaj <januzaj@informatik.tu-muenchen.de>
//     http://www.informatik.tu-muenchen.de/~januzaj/  Dec-1998
// and Peter.Schmolck@unibw-muenchen.de again, July, August 1999
//
// global variables that should not be changed

//help_url: page opened by clicking the help_button button 
var help_url;
if (! help_url) help_url="webqhelp.htm";
var help_button;
if (! help_button) help_button="Help";

var item;

cf=parent.controlframe.document;
rf=parent.rankingframe.document;

study_title = '<FONT  FACE="verdana, arial, helvetica"  SIZE=2 color = "##0000ff"><em>' + study_title + '</em></FONT>'; // Title
anchor_font = '<FONT  FACE="arial black, haettenschweiler, times, arial"  SIZE=2 color = "#AF0000">'; 
//anchor_font = '<FONT  FACE="verdana, arial, helvetica"  SIZE=2 color = "#AF0000">'; 
item_font = '<FONT FACE="verdana, arial, helvetica"  SIZE=1 COLOR="#666666">';

leftanchor =  ' (' + (1-categories)/2 + ') ' + leftanchor
rightanchor = rightanchor + ' (+'+(categories-1)/2 + ') '
catnumber = new Array(categories);
pileindx = new Array(numstatements);
stmntid = new Array(numstatements);
boxfilld = '<IMG SRC="boxfilld.gif" ALIGN=middle  HEIGHT=20>';
box2many= '<IMG SRC="box2many.gif" ALIGN=middle HEIGHT=20>';
boxempty = '<IMG SRC="boxempty.gif"  ALIGN=middle HEIGHT=20>';

// Newline-Character within mailbody 
//var nl = "<br>%0D%0A";  //or: "\n" -- Windows: "\r\n" (??)
var nl = "\n"
if (navigator.appVersion.lastIndexOf('Win') !=-1) nl="\r\n"

//Aug-05-99 (SMK): variable browser4 not needed any more
// browser4: is Browser at least NN / IE version 4.0?
//var browser4 = new Boolean(false);
//if ( navigator.userAgent.charAt(8) >= 4 ) browser4 = true;
//alternatively: (navigator.userAgent.lastIndexOf('Mozilla/4') !=-1) ;

chkcode = new makearray2(numstatements,categories);
first = true;
catcode = new Array(categories);
for (count=categories; count > 0; count+=-1) {
	catcode[count] = count - (categories + 1)/2; 
	if (catcode[count] > 0) catcode[count]= '+' + catcode[count]; 
	}

// 27.11.1998 - Eshref Januzaj
cathead = '<TD></TD>';
for (count=1; count <= categories; count++) {
	cathead += '<td bgcolor=#CCFFFF align=center><FONT size = -2 color = "black">' + catcode[count] + '</font></td>';
	}


// end of global variables

// the main control function

function prepare() {
sum = 0;
for (count = 1; count <= categories; count++) {
sum = sum + cat[count];
}
if (sum != numstatements) alert('sum of categories not equal number of statements');

if (categories % 2 == 0) alert('number of categories is not uneven!');

sortstatements();
setTimeout('review()',100);

}

// 
function sortstatements() { 

var checker = new Array(numstatements);
mid = (categories+1)/2;
for (count1 = 1; count1 <= numstatements; count1++) {
	for (count2 = 1; count2 <= categories; count2++) { 
	checker[count1] = 0;
	if (count2 == mid)
		chkcode[count1][count2] = ' checked';
	else chkcode[count1][count2] = '';
	}
}

for (count=1; count<=numstatements; count++) {
	stmntid[count] = count;
	}
if (randomsort == true) {
	for (count=1; count<=numstatements; count++) {
		rnum=Math.floor(Math.random()*numstatements) + 1;
		hold=stmntid[count];
		stmntid[count]=stmntid[rnum];
		stmntid[rnum]=hold;
		}
	}
} 


function help(help_url) {
  if(help_url.indexOf('javascript:') != -1){
    parent.location.href=help_url;
    return;
  }
  helpwin = window.open(help_url,'helpwindow','menubar=yes, toolbar=no, location=no, directories=no,status=no,scrollbars=yes,resizable=yes,copyhistory=no,width=800,height=730');
  setTimeout('helpwin.focus()',100); //a simple helpwin.focus() does not work properly in IE
  return;
}


// Functions for displaying statements

function review() {
if (first == false) btnchk();
catcount();


// write the statements
// rf.clear(); //seems not to be required!
rf.writeln('<html><BODY BGCOLOR="#FFFFFF">');

rf.writeln('<p align=right>', anchor_font, rightanchor, '</font></p>');
rf.writeln('<form><center><table border=1 CELLSPACING=0 CELLPADDING=2>'); 

for (count1=categories; count1 > 0; count1+=-1) {
               symbol = '';

// match (green)
	if (cat[count1] == catnumber[count1]) 
		for (catcnt = 1; catcnt <= cat[count1]; catcnt++)
		  symbol = symbol  +  boxfilld;

// too many (red)
	if (cat[count1] < catnumber[count1]) {
		for (catcnt = 1; catcnt <= 2*cat[count1]-catnumber[count1]; catcnt++)
		  symbol = symbol  + boxfilld;
		for (catcnt_ = catcnt; catcnt_ <= cat[count1]; catcnt_++)
		  symbol = symbol  + box2many;
	} // IF

//	if (cat[count1] < catnumber[count1]) {
//		for (catcnt = 1; catcnt <= cat[count1]; catcnt++)
//		  symbol = symbol  + box2many;
//	} // IF

//too few (blue)
	if (cat[count1] > catnumber[count1]){
	  for (catcnt = 1; catcnt <= catnumber[count1]; catcnt++)
	  symbol = symbol  + boxfilld;

	  for (catcnt_ = catcnt; catcnt_ <= cat[count1]; catcnt_++){
	     symbol = symbol  + boxempty;
	  } // FOR
	} // IF
//add empty space before pile
	rf.writeln('<tr><td height=5></td></tr>');
    	
//	rf.writeln('<tr valign=middle><td bgcolor=#ff7f50 align=center><font color="#AF0000">',catcode[count1],'</font><td colspan=2 bgcolor=#ff7f50 valign=bottom>' + symbol + '</td></td>');
	rf.writeln('<tr valign=middle><td bgcolor=#CCFFFF align=center>', anchor_font, catcode[count1],'</font><td colspan=2 bgcolor=#CCFFFF valign=bottom>', symbol, '</td>');
	rf.writeln(cathead + '</tr>'); 
	
	for (count2 = 1; count2 <= numstatements; count2++) {
		item = stmntid[count2];
		
		for (count3 = 1; count3<= categories; count3++) {
		if ((chkcode[item][count3] == ' checked') && (count1 == count3)) {
			txt = '';
			for (catcnt = 1; catcnt<= categories; catcnt++) {
				if (catcnt==(categories+1)/2) 
					txt += '<td bgcolor=#CCFFFF ><input type=radio name="st'+item+'"'+chkcode[item][catcnt]  + '></td>';
				else txt +=  '<td><input type=radio name="st'+item+'"'+chkcode[item][catcnt]  + '></td>';
			}
		
			
			rf.writeln('<tr valign=top><td></td><td align=right>',item_font ,item, '.</font></td><td >', item_font ,statement[item], '</font></td><td></td>', txt, '<td></td></tr>');


		}
	}
  }  // end of pile

}
rf.writeln('</table></center></form>'); 
rf.writeln('<p align=left>', anchor_font, leftanchor, '</font></p>');
rf.writeln("</body></html>");
rf.close();

first = false;
return false;
}


function send() {
review();
var complete = new Boolean(true);
var respcat = new Array(numstatements);

for (i in cat) if (cat[i] != catnumber[i]) complete=false; 
if (complete == false) {
  if (forcedchoice == true) {
    alert('Q-sort is incomplete. Some categories have too few or too many statements')
    return false;
  }
  else {
    if (confirm('Q-sort is incomplete. Some categories have too few or too many statements' +
       '\nOK to send anyway --  CANCEL to continue with sorting') == false) return false;
  }
}

mailbody = 'Browser: '+navigator.userAgent+nl+'Q-Sort response array (DO NOT CHANGE!!):'+nl;

var sortid = prompt (
  "Please provide a code word which will be used for processing " +
  "your data anonymously (up to 8 characters): "," ")

if (! sortid) return false;   //if 'Cancel': don't send (now)

sortid=sortid+"        ";
mailbody += ">" + sortid.substring(0,8)+ "  ";

for (count1 = 1; count1 <= numstatements; count1++) {
	item = stmntid[count1];
	for (count2 = 1; count2 <= categories; count2++) {
		if ((chkcode[item][count2] == ' checked')) {
			respcat[item] = count2 - (categories + 1)/2 
			if (respcat[item] >= 0) 
				respcat[item] = ' ' + respcat[item] ;
			break;
		}	
	}
}

for (count1 = 1; count1 <= numstatements; count1++) {
	mailbody += respcat[count1]; 
	}

mailbody += '<' + nl +nl;

/* New since Aug-05-99 (SMK):
   Write a copy of the email to the ranking frame, which the
   respondent could manually cut&paste into email-software
   in case mailto: cannot be used. 
   Boolean variable 'first' is set true because function 
   review would otherwise start function btnchek
*/
first=true;
rf.writeln('<html><BODY BGCOLOR="#FFFFFF">');
rf.writeln('<p>Click on the <b>Update</b> button if you wish to restore the previous ranking frame. <br><br>');
rf.writeln('<p>This is an exact copy of what should be sent off by email (without your comments added!). <br>');
rf.writeln('If your email program has <b><em>not</b></em> opened already or if the `mailbody` with your data is not in place, please cut&paste the following and send it to');
rf.writeln('<a href="mailto:'+addressee+'?subject='+subject+'">' +addressee+'</a>');
rf.writeln('-- Please don`t forget the <b><em>Subject</em></b> line!<hr>');
rf.writeln('<p><pre><b>     To: </b>'+addressee+'<br><b>Subject: </b>'+subject+'<br><br>');
rf.writeln(mailbody+commentprompt+'<br></pre>');
rf.writeln("</body></html>");
rf.close();

/* Browser versions < 4 do not fully support the extended mailto:-
   protocol which allows to pass through the email-message body.
   In previous versions of WebQ (before 05-Aug-99), the solution
   for older browsers was to send data via form submit _in 
   addition_ to the mailto:-method which would open the email 
   window -- without the data pasted but for having the repondent
   add comments. Different to that approach, the new 'cut&paste'-
   solution also allows participation of users with non-standard
   email-client-browser configurations or those using web-based 
   email services of remailing providers.
   The essential part of the old code (without the specific alert
   messages) is preserved here within comments, because it might
   be helpful in case the code should be changed to cgi-script 
   based form-handling (the 'return true' triggers sending the
   form with mailto:). 

	if (browser4 == false) {
  document.mailform.my_sort.value = mailbody + "Posted by form submit";
	  document.mailform.action = "mailto:" + addressee + '?subject=' + subject;
	  document.mailform.method= "POST";
	  return true;
	}
*/

parent.location.href= "mailto:" + addressee + '?subject=' + subject
   + '&body=' + escape (mailbody + commentprompt +nl);
return false;
}

/* Checking the radio buttons -- using onClick does not work  :(
   smk: function btnchk greatly simplified (13-Jul-99)
*/
function btnchk() {
  for (i=1; i <= numstatements; i++) {
    radioI=eval("rf.forms[0].st"+i)
    for (j=0; j < categories; j++) {
      if (radioI[j].checked == true)  chkcode[i][j+1] = ' checked';
      else chkcode[i][j+1] = '';
    }
  }
return false;
}

function catcount() {

for (count = 1; count <= categories; count++) 
	catnumber[count] = 0;
	
for (count2 = 1; count2 <= numstatements; count2++) {
	item = stmntid[count2];
		
	for (count3 = 1; count3<= categories; count3++) {
	if (chkcode[item][count3] == ' checked')  {
		catnumber[count3]++;		
		}
	}
}
}

// functions to create arrays
function makearray2 (x,y) {
var count;
this.length = x;
for (var count = 1; count <= x; count++)
	this[count] = new makearray(y);
}
function makearray(numelements) {
var count;
this.length = numelements;
for (count = 1; count <= numelements; count++)
	this[count] = 0;
return (this);
}
/* Aug-05-99 (SMK):
   The following contains a 'mailform' that actually isn't
   executed anymore; function send always returns false now.
   (In previous versions of WebQ it returned true if 
   browser version < 4)
*/
cf.writeln("<BODY BGCOLOR='#FFFFFF' onload='prepare()'>");
cf.writeln("<FORM method='POST' name='mailform' enctype='text/plain'>");
cf.writeln("<center><TABLE border=0 cellspacing=2>"); 
cf.writeln("<TR><TD valign=top width=15%><TABLE  BORDER='0' CELLSPACING='2' CELLPADDING='0'>");
cf.writeln("<TR><TD >" + boxempty + "</TD>");
cf.writeln("<TD>&nbsp;</TD>");
cf.writeln("<TD><B><FONT SIZE=1 FONT FACE='Arial Narrow, helvetica'>Empty slot</FONT></B></TD></tr>");
cf.writeln("<TR><TD >" + boxfilld + "</TD>");
cf.writeln("<TD>&nbsp;</TD>");
cf.writeln("<TD><B><FONT SIZE=1 FONT FACE='Arial Narrow, helvetica'>Occupied slot</FONT></B></TD></tr>");
cf.writeln("<tr><TD >" + box2many + "</TD>");
cf.writeln("<TD>&nbsp;</TD>");
cf.writeln("<TD><B><FONT SIZE=1 FONT FACE='Arial Narrow, helvetica'>Too many in slot</FONT></B></TD></tr>");
cf.writeln("</TABLE></TD>");

cf.writeln("<TD valign=center width=70%><CENTER><FONT COLOR=\"#AF0000\" SIZE=+2>WebQ<hr noshade></FONT>" + study_title + "</CENTER>");
cf.writeln("</TD>");

cf.writeln("<TD valign=top align=right width=15%>");

//cf.writeln("<blink>==&gt;</blink>") //uncomment line to get a blinking arrow
                                    //besides the Help button

cf.writeln("<INPUT TYPE='button' NAME='Help' VALUE='"+help_button+"' onclick='help(help_url)'><br>");
cf.writeln("<INPUT TYPE='button' NAME='Review' VALUE='Update' onclick='review()'><br>");
cf.writeln("<INPUT TYPE='hidden' NAME='my_sort' VALUE=''>");
cf.writeln("<INPUT TYPE='submit' VALUE='Send' onclick='return send(this.form)'><br>");
cf.writeln("</TD></TR></TABLE></center></FORM></BODY>");
cf.close();

