/*

    SCID Calculates scores for a personality test based on an array of
    questions and associated weighted values.
    Copyright (C) 2007	Jordan Wiens

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

questionList = new Array();
questionList[0] = new Array ("fearless in conquering a challenge","always enjoys having fun","free to express true feelings","usually at rest with circumstances","NNNN","NNNN");
questionList[1] = new Array ("tries to avoid mistakes","securely fixed in place","convinces others ","goes along with the flow","CDIS","CDIN");
questionList[2] = new Array ("liked by others","systematically thinks through issues","clearly conveys thoughts","untroubled by stress","ICDN","NCDS");
questionList[3] = new Array ("enjoys talking","able to control his/her impulses","actions can be foreseen by others","quickly makes decisions","ICSD","ICSD");
questionList[4] = new Array ("willing to take risks","easily distinguishes differences","people person","avoides extremes","DCIS","DCIS");
questionList[5] = new Array ("sensitive to the needs of others","guides the thinking or behavior of others","humbly acknowledges his/her abilities","capable of producing a desired result","SINN","SNCD");
questionList[6] = new Array ("full of energy","trys to avoid mistakes","takes control of situations","readily accessible to others","ICDN","ICDS");
questionList[7] = new Array ("has high-spirited energy","easily focuses his/her attention","tends not to speak frequently","fully committed to achieving a goal","ICSD","INSD");
questionList[8] = new Array ("has an extreme care for details","people person","captivates people's attention","able to give direction","CSID","CSID");
questionList[9] = new Array ("fearless in conquering a challenge","has the ability to encourage others","readily follows someone else's lead","minutely exact","DISN","DISC");
questionList[10] = new Array ("humbly acknowledges abilities","pays attention to the needs of others","driven by goals","sees the glass as half-full","CSDI","CSDI");
questionList[11] = new Array ("drives others forward","concerned about other's needs above own","concerned with correct information","able to take care of yourself","ISCD","ISCD");
questionList[12] = new Array ("forcefully pursues a goal","shares the feelings of others","other people love being around him/her","trys to avoid danger","DSIC","DSIC");
questionList[13] = new Array ("likes to have things a certain way","readily follows someone else's lead","establishes new endeavors","joyfully enjoys life","CSDI","CSDI");
questionList[14] = new Array ("liked by others","full of thought","perseveres despite opposition","does things the traditional way","ICDS","INDS");
questionList[15] = new Array ("thinks through problems analytically","willing to take risks","loyal to others","possesses a magnetic charm ","CDSI","CDSI");
questionList[16] = new Array ("enjoys the company of others","unmovable in opposition","able to take care of oneself","listens more than he/she talks","ISDC","ISDC");
questionList[17] = new Array ("goes along with the flow","has a one-track mind","works systematically","full of energy","SDCI","SNCI");
questionList[18] = new Array ("continues despite difficulties","shows love freely","mindful of the needs of others","prone to worrying","DISN","DISC");
questionList[19] = new Array ("seeks the company of others","cares deeply about the needs of others","free from bias","secure in his/her own abilities","ISND","ISCD");
questionList[20] = new Array ("capable of producing a desired result","gives freely to other's","clearly conveys meaningful thoughts","fully committed to achieving a goal","CSID","CSID");
questionList[21] = new Array ("instantly acts without thought","sees things as they are","readily accepts leadership roles","usually at rest with circumstances","ICDS","ICDS");
questionList[22] = new Array ("enjoys time spent with others","systematically thinks through issues","does not show weakness or uncertainty","gives grace when it is undeserved","ICDS","ICDS");
questionList[23] = new Array ("enjoys the company of others","satisfied with life","securely fixed in place","follows directions","ISDC","ISCD");
questionList[24] = new Array ("pushes others to do their best","thinks through problems analytically","collaborative team player","upbeat about life","DCSI","DCSI");
questionList[25] = new Array ("always enjoys having fun","conforms exactly to a standard","free to express true feelings","can be depended on consistently","ICDS","ICDS");
questionList[26] = new Array ("forcefully pursues a goal","welcoming to others","holds the attention of others","carefully assesses risks","DISC","DISC");
questionList[27] = new Array ("courteous of others","requires others to accomplish tasks correctly","sees the glass half-full","concerned with the feelings of others","CDIS","CDIS");
questionList[28] = new Array ("readily follows someone else's lead","trys to avoid mistakes","does not show weakness or uncertainty","minutely exact","NNNN","NNNN");
questionList[29] = new Array ("capable of expressing strong feelings","prominently stands out","minutely exact","satisfied with life","IDCS","IDCS");

questionRoot = document.getElementById('questionform');
resultRoot = document.getElementById('resultroot');

results=new Array();

function hilite(qNum) {
	var qid="q"+qNum;
	var qspan = document.getElementById(qid);
	qspan.firstChild.nextSibling.style.border="dashed #f00 2px";
	qspan.firstChild.scrollIntoView();
}

function removeChildren(idname) {
	var element=document.getElementById(idname);
	while (element.hasChildNodes()) {
		element.removeChild(element.lastChild);
	}
}

function resetQ() {
        var forminput=document.getElementsByTagName('input');
        for (var x=0; x<forminput.length; x++) {
                try { forminput[x].checked=false } catch (err)  {}
        }
	menuSelect("questions");
}

function resetResults() {
	removeChildren("graph1");
	removeChildren("graph2");
	//removeChildren("graph3");
	removeChildren("detailsmarker");
        document.getElementById("graph1").style.display='none';
	document.getElementById("graph2").style.display='none';
	//document.getElementById("graph3").style.display='none';
}

function URLEncode (clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}

function emailResults() {
      window.location = "mailto:?subject=SCID online assessment results&body="+
	"Graph1 - Adaptive Behavior - (SCID): "+
	results["S"][5]+
	","+results["C"][5]+
	","+results["I"][5]+
	","+results["D"][5]+
	" | "+
	"Graph2: - Natural Behavior - (SCID)"+
	results["S"][6]+
	","+results["C"][6]+
	","+results["I"][6]+
	","+results["D"][6]+
	" | ";
/*
	"Graph3: "+
	","+results["S"][4]+
	","+results["C"][4]+
	","+results["I"][4]+
	","+results["D"][4]+
	" | ";
*/
}

function printContent(section) {
        var docbody = document.getElementById(section).cloneNode(1)
        var printWindow = window.open("","printWindow","width=640,height=480,scrollbars=1")
	var printDoc = printWindow.document
	var newRules = printDoc.getElementsByTagName('head')[0].appendChild(printDoc.createElement('style'))

	if (document.styleSheets[0].rules) {  //IE Probably not working
		printWindow.document.styleSheets[0].cssText=document.styleSheets[0].cssText
	} else if (document.styleSheets[0].cssRules) { //Firefox
		myRules = document.styleSheets[0].cssRules
		for (var x=0; x<myRules.length; x++)
			printDoc.styleSheets[0].insertRule(myRules[x].cssText,0)
	}	
	
	//Could use appendChild for firefox, but the IE broken way works too.
	//IE can't handle appendChild from the parent to the new window, and it also
	//can't handle the DOM 2.0 importNODE that would help too.  Oh well.
	if (document.all) printDoc.body.innerHTML=docbody.innerHTML
	else printDoc.getElementsByTagName("body")[0].appendChild(docbody)

	if (printWindow.print())
		 {printWindow.close();}
}

function scoreMe() {
	resetResults();

	results["S"]=new Array(0,0,0,0,0);
	results["C"]=new Array(0,0,0,0,0);
	results["I"]=new Array(0,0,0,0,0);
	results["N"]=new Array(0,0,0,0,0);
	results["D"]=new Array(0,0,0,0,0);

	function calcResults(results,mode) {
		var idx=0;
		if (mode=="l") { idx=1; }

		for(var x=0; x<questionList.length; x++) {
			var y=scoreQ(x,mode)
			if (y == "S" || y=="C" || y=="I" || y=="N" || y=="D") {
				results[y][idx]++;
			} else {
				x++;
				hilite(x);
				return "err";
			}
		}
	return results
	}

	var mode="m";
	testresults=calcResults(results,mode)
	if (testresults == "err") { 
		logger("missing question, halting");
		return 0
	} else {
		results=testresults;
	}

	var mode="l";
	testresults=calcResults(results,mode)
	if (testresults == "err") { 
		logger("missing question");
		return 0
	} else {
		results=testresults;
	}

	results["S"][2]=results["S"][0]-results["S"][1];
	results["C"][2]=results["C"][0]-results["C"][1];
	results["I"][2]=results["I"][0]-results["I"][1];
	results["D"][2]=results["D"][0]-results["D"][1];

	results["S"][4]=results["S"][2]+27;
	results["C"][4]=results["C"][2]+26;
	results["I"][4]=results["I"][2]+26;
	results["D"][4]=results["D"][2]+27;

	results["S"][3]=27-results["S"][1];
	results["C"][3]=26-results["C"][1];
	results["I"][3]=26-results["I"][1];
	results["D"][3]=27-results["D"][1];

	var x,y = 0;
	x = results["S"][0] + results["C"][0] + results["I"][0] + results["D"][0];
	y = results["S"][3] + results["C"][3] + results["I"][3] + results["D"][3];

	results["S"][5]=(results["S"][0]/x*100).toFixed(0);
	results["C"][5]=(results["C"][0]/x*100).toFixed(0);
	results["I"][5]=(results["I"][0]/x*100).toFixed(0);
	results["D"][5]=(results["D"][0]/x*100).toFixed(0);

	results["S"][6]=(results["S"][3]/y*100).toFixed(0);
	results["C"][6]=(results["C"][3]/y*100).toFixed(0);
	results["I"][6]=(results["I"][3]/y*100).toFixed(0);
	results["D"][6]=(results["D"][3]/y*100).toFixed(0);


	logger("scoring done");

	var g = new graph();
	g.setScale(100);
	g.add("S",results["S"][5]);
	g.add("C",results["C"][5]);
	g.add("I",results["I"][5]);
	g.add("D",results["D"][5]);
	g.render("graph1","Adaptive Behavior");
	document.getElementById("graph1").style.display='block';

	g = new graph();
	g.setScale(100);
	g.add("S",results["S"][6]);
	g.add("C",results["C"][6]);
	g.add("I",results["I"][6]);
	g.add("D",results["D"][6]);
	g.render("graph2","Natural Behavior");
	document.getElementById("graph2").style.display='block';

	/*
	g = new graph();
	g.setScale(100);
	g.add("S",results["S"][4]);
	g.add("C",results["C"][4]);
	g.add("I",results["I"][4]);
	g.add("D",results["D"][4]);
	g.render("graph3","Graph3");
	document.getElementById("graph3").style.display='block';
	*/

	var detail1=document.createElement("p");
	detail1.innerHTML="Adaptive Behavior: "+results["S"][5]+", "+results["C"][5]+", "+results["I"][5]+", "+results["D"][5];

	var detail2=document.createElement("p");
	detail2.innerHTML="Natural Behavior: "+results["S"][6]+", "+results["C"][6]+", "+results["I"][6]+", "+results["D"][6];

	/*
	var detail3=document.createElement("p");
	detail3.innerHTML="Graph3: "+results["S"][4]+", "+results["C"][4]+", "+results["I"][4]+", "+results["D"][4];
	*/

	//detailtable.innerHTML="<tr><td>&nbsp;</td><th>S</th><th>C</th><th>I</th><th>D</th></tr>\n<tr><th>Graph1</th><td>"+results["S"][0]+"</td><td>"+results["C"][0]+"</td><td>"+results["I"][0]+"</td><td>"+results["D"][0]+"</td></tr>\n<tr><th>Graph2</th><td>"+results["S"][3]+"</td><td>"+results["C"][3]+"</td><td>"+results["I"][3]+"</td><td>"+results["D"][3]+"</td></tr>\n<tr><th>Graph3</th><td>"+results["S"][4]+"</td><td>"+results["C"][4]+"</td><td>"+results["I"][4]+"</td><td>"+results["D"][4]+"</td></tr>";
	
	var detailtext=document.getElementById("detailsmarker");
	var newthing=document.createElement("h3");

	detailtext.appendChild(newthing);
	detailtext.appendChild(detail1);
	detailtext.appendChild(detail2);
	//detailtext.appendChild(detail3);

	menuSelect("details");

	detailtext.style.display='block';

}

function scoreQ(qIdx,mode) {
	var qNum=qIdx+1;
	//logger("qNum: "+qNum+"\nqIdx: "+qIdx+"\nmode: "+mode);
	var curQ = eval("document.questionform.q"+qNum+mode); 
	if (mode == "m") { 
		var x=4
	} else { 
		var x=5;
	}
	var answerArray=questionList[qIdx][x].split("");

	//return questionList[qIdx][x][radioValue(curQ)];
	return answerArray[radioValue(curQ)];
}

function moveOn(curQ) {
	logger("question move: "+curQ);
	var qm = eval("document.questionform.q"+curQ+"m"); 
	var ql = eval("document.questionform.q"+curQ+"l"); 

	var mDone=0;
	var lDone=0;

	for (var x=0; x<qm.length; x++) {
		if (qm[x].checked) { mDone=1; }
	}
	
	for (var x=0; x<ql.length; x++) {
		if (ql[x].checked) { lDone=1; }
	}

	if (mDone && lDone)  {
		logger("should be moving");
		curQ++;
		document.getElementById("q"+curQ).scrollIntoView()
	}
	return true;
}

function createRadio(qnum,qmode,qvalue) {
	elementname='q'+qnum+qmode;
	try{
		/* IE is terrible */
		rdo = document.createElement('<input type="radio" value="'+qvalue+'" name="'+elementname+'" id="'+elementname+qnum+'" onClick="moveOn('+qnum+');" />');
	}catch(err){
		rdo = document.createElement('input');
		rdo.setAttribute('type','radio');
		rdo.setAttribute('name',elementname+qnum);
		rdo.setAttribute('id',elementname);
                rdo.setAttribute('onClick','moveOn('+qnum+');');
		rdo.setAttribute('value',qvalue);
	}
	return rdo;
}

function createQ(qIdx) {

	var questionRoot = document.getElementById('questionform');
	curQ=questionList[qIdx];

	qNum=qIdx+1;

	var spanQ=document.createElement('span');
	spanQ.id="q"+qNum;
	spanQ.className="question";
	//spanQ.setAttribute("class","question");

	var QTable=document.createElement('table');
	QTable.align="center";

	for (var x=0; x<=3; x++) {
		var y=QTable.insertRow(-1);
		y.insertCell(0).innerHTML=curQ[x];
		var radio1 = createRadio(qNum,'m',x);
		var radio2 = createRadio(qNum,'l',x);
		//var radio1 = document.createElement('input');
		//var radio2 = document.createElement('input');
		//radio1.type='radio';
		//radio1.name='q'+qNum+'m';
		//radio1.id='q'+qNum+'m';
		//radio1.setAttribute('onChange','moveOn('+qNum+');');
		//radio1.value=x;
		//radio2.type='radio';
		//radio2.name='q'+qNum+'l';
		//radio2.id='q'+qNum+'l';
		//radio2.setAttribute('onChange','moveOn('+qNum+');');
		//radio2.value=x;
	
		y.insertCell(1).appendChild(radio1);
		y.insertCell(2).appendChild(radio2);
	}

	var QTHead=QTable.createTHead();
	var QTHRow=QTHead.insertRow(0);
	QTHRow.insertCell(0).innerHTML="";
	QTHRow.insertCell(-1).innerHTML="Most";
	QTHRow.insertCell(-1).innerHTML="Least";

	var pNode = document.createElement('p');
	pNode.className='questionheader';
	pNode.innerHTML=qNum+':';

	spanQ.appendChild(pNode);
	spanQ.appendChild(QTable);
	questionRoot.appendChild(spanQ);
}

function radioValue(radio) {
	for(var x=0;x<radio.length;x++)
		{
		if(radio[x].checked==true)
			{
			return radio[x].value;
			}
		}
	return 'null';
}

function writeQuestions() {
	for(var x=0; x<questionList.length; x++) {
		createQ(x)
	}
	return true;
}

function r() {
	for(var x=1; x<=questionList.length; x++) {
		var choice1=Math.round(3*Math.random());
		var choice2=Math.round(3*Math.random());
    	var Q1 = eval("document.questionform.q"+x+"m"); 
    	var Q2 = eval("document.questionform.q"+x+"l"); 
		//logger(" setting document.questionform.q"+x+"m "+choice1+" to true");
		Q1[choice1].setAttribute('checked',true);
		Q2[choice2].setAttribute('checked',true);
	}
	logger("random answers populated");
}

function logger(message) {
	if (typeof console == "undefined") {
	//	alert(message);
		return;
	} else console.log(message);
}

function getElementsByClass(className) {
	var classArray = new Array();
	var x = document.getElementsByTagName("*");
	var pattern = new RegExp("(^|\\s)"+className+"(\\s|$)");
	for (i = 0, j = 0; i < x.length; i++) {
		if ( pattern.test(x[i].className) ) {
			classArray[j] = x[i];
			j++;
		}
	}
	return classArray;
}

function menuSelect(boxname) {
	var curTab=document.getElementById(boxname+"tab");
	var curText=document.getElementById(boxname+"text");
	
	var tabbar=document.getElementById("tabbar");
	var tchildren=tabbar.childNodes;

	//Why would these behave differently?!
	//for (var x; x < tchildren.length; x++) {
	for (var x in tchildren) {
		try {tchildren[x].childNodes[0].className=""; }
		catch(err) { }
	}

	var boxtexts=getElementsByClass("boxtext");

	//for (var x; x<boxtexts.length; x++) {
	for (var x in boxtexts) {
		boxtexts[x].style.display='none';
	}

	curTab.className="here";
	curText.style.display='block';
}

function toggle(idname) {
	elementstyle=document.getElementById(idname).style;
	if (elementstyle.display == "none") {
		elementstyle.display = "block";
	} else {
		elementstyl.display = "none";
  }
}
