// JavaScript Document

/*
quello che vogliamo è creare uno script per la valutazione di quiz
che non abbia javascript invasivo nella pagina
indipendente dalla struttura html
con varie tipologie di domande (iniziando con la scelta mnultipla)

sistema di scoring personalizzabile con risultati in pagine separate e caricati in ajax nella pagina resultati

THE SINGLE CHOICE RADIOS MUST BE INSIDE A <UL> TAG. MAYBE IN A FUTURE CAN BE CHANGED

*/
$(document).ready(function(){
						   
	counter();	
	cypher();
	
	$(sendbutt).click(function(){
		
		evalTest(); return false;
	});



});

/*### PREP SECTION #######################################################*/

function selectalltxt(elid){
	javascript:document.getElementById(elid).focus();
	document.getElementById(elid).select();
	
	}



 
function counter(){
	
	$(qstCount).each(function(){
		totCount = totQst+1;
		if (totCount < 10 ){
			$(this).html('0'+totCount)
		}
		else {		
			$(this).html(totCount)
		}
		totQst = totCount;
	});	
};//end counter


function cypher(){
		
/*	chars = new Array ('A','E','I','O','U','H','X','Y','G','Q','Z','R','T','S','N','M','C','1','2','3','4','5','6','7','8','9','0');
	charCount = chars.length;
	stringLength = 6;
	outputString ='';

	i = 0;
   do {
	  random = Math.floor(Math.random());
	  random *= charCount;
	  random = chars[random];
	  outputString += parseString(random);
	  i++;
   }
   while (i<stringLength)
 alert(outputString);*/
};







/*### EVALUATION SECTION #######################################################*/


function evalTest () {

	grossScore = 0;
	correctCount = 0; 
	wrongCount = 0; //reset all scores
	
	if ($(boxElem).is(fillgaps) == true ){
		
		evalFillgaps(); //eval the fill in the gaps type of questions
	}
	if ($(boxElem).is(singlechoice) == true ){
		evalSinglechoice(); //eval the single choice type of questions
	}
	if ($(boxElem).is(multichoice) == true ){
		//not ready yet. need to set up a function and a structure
	}
	cleanScore(); 
	
	showResults(); //display the results
};


function evalFillgaps(){/*eval fill in the gaps questions*/

	
	/*var qstElem = fillgaps+" select";*/
	
	$(fillgaps).each(function(){
		
		maxScore = maxScore+Number($(this).children(weightClassId).attr(weightAttr));
		
		multiplier = 1/($(this).find('select').length);
				
		$(this).find('select').each(function(){  
			if($(this).attr('value') == correctChar) {
				qstWeight = Number($(this).parents(fillgaps).children(weightClassId).attr(weightAttr))*multiplier;
				grossScore = grossScore+qstWeight;
				correctCount = correctCount+(1*multiplier)
				var selectedOpt = '<span class="'+questGeneral+' '+questCorrect+'">'+$(this).find('option').filter(':selected').text()+'</span>';
				
			}
			else if ($(this).attr('value') != 0){
			
				wrongCount = wrongCount+(1*multiplier);
				var selectedOpt = '<span class="'+questGeneral+' '+questWrong+'">'+$(this).find('option').filter(':selected').text()+'</span>';
			}
			else{ 
				var selectedOpt = '<span class="'+questGeneral+' '+questNA+'">'+$(this).find('option').filter(':selected').text()+'</span>';
			}
					
			$(this).after(selectedOpt)
			$(this).remove()
			
			
	
		});
	});	
	
	storeQuestion(fillgaps);
};/*end eval fillgaps*/


function evalSinglechoice(){ /*eval single choice questions*/
	

	
	$(singlechoice).each(function(){  
		var ansOk = false;
		maxScore = maxScore+Number($(singlechoice+' '+weightClassId ).attr(weightAttr));
		
		$(this).find('input[type=radio]').each(function(){					 
			if ( $(this).attr('checked') == true && $(this).attr('value') == correctChar )	{
				
				qstWeight = Number($(singlechoice+' '+weightClassId ).attr(weightAttr));
				grossScore = grossScore+qstWeight;
				
				correctCount = correctCount+1;
				
				ansOk = true;
				$(this).parent('li').addClass(questGeneral).addClass(questCorrect);
				$(this).remove();
			}			
			else if ( $(this).attr('checked') == true && $(this).attr('value') != correctChar ) { 
				wrongCount = wrongCount+1;
				$(this).parent('li').addClass(questGeneral).addClass(questWrong);
				ansOk = true;
				$(this).remove();
				
			}
			else {$(this).parent('li').remove();  }
		});

	
		if ( ansOk != true){ // if no option was selected we return a not answered text
			$(this).children('ul').append('<li class="'+questGeneral+' '+questNA+'">'+notAnsweredTxt+'</li>')
		}
		ansOk = false;
	});

	storeQuestion(singlechoice);						 
							 

};


function storeQuestion(elem){
	
		$(elem).each(function(){
		questionsArr[arraycounter] = '<'+qstResTag+' class="'+qstResClass+' '+elem.substr(1)+'">'+$(this).html()+'</'+qstResTag+'>';
		arraycounter = arraycounter+1;
	});
	
};

/*### SCORING SECTION #######################################################*/



function cleanScore(){  // clean the gross score
	correctPercent = Math.round((correctCount / totQst)*100) ;
	netScore = ((grossScore / maxScore)*10).toFixed(2);  

	ranger();
};

function ranger (){
	var rmax = rangeArr.length ;
	
	for(i=0;i<rmax;i++){
		var separator = rangeArr[i].indexOf(',');
		var rangenum = Number(rangeArr[i].substring(0,separator));
		if (rangenum >= netScore ){
			loadurl = rangeArr[i].substring(separator+1);
			break;
		}
	}	
};

/*### DISPLAY SECTION #######################################################*/




function showResults (){
	$(qzBox).fadeOut("fast",function(){
		$(qzBox).empty();
		
				 
		
		//append the score box
		createStruct();
		$(qzBox).html(resultStructure);


		//append the range result
		$(qzBox).prepend('<div class="'+rangeStrBox+'"></div>');
		$('.'+rangeStrBox).load(loadurl);			
		
		// start appending questions
		$(qzBox).append(qstBoxOpen);
		var qmax = questionsArr.length;
		var qstBoxId = '#'+questResClass;
		for(i=0;i<qmax;i++){
			  
			$(qstBoxId).append(questionsArr[i])
		}  
		$(qzBox).append(qstBoxClose); // stop appending questions
		
		//append the options bar
		$(optionbar).appendTo(qzBox);
		$(optionbar).prependTo(qzBox);
		$(qzBox).fadeIn("slow");
		scroll(0,0);
	});
};








