$(document).ready(function(){

	// Button click
	$('.tthquiz input:button').click(function(){
	
		var $parent = $(this).parents('.tthquiz');
	
		// create our output rankings object, init'd to an empty object
		var rankings = {};
		
		// loop through each radio button and checkbox selected
		//$('.tthquiz *:checked').each(function(i,e){
		$parent.find('*:checked').each(function(i,e){
			
			// get our rankings from the currently selected input box
			var rank = $(this).attr('personalities');
			
			// strip all spaces
			rank = rank.replace(/ /g, '');
			
			// convert the string to an object
			rank = StringToObject(rank);

			// loop through each entry in the rank object
			for (var key in rank) {
				if (rank.hasOwnProperty(key)) {
				
					// convert the value to a number -- I use float in case we want to use decimal specific values
					var rankNum = parseFloat(rank[key]);
				
					// the first time we create an entry in our rankings object, there won't be a number
					// to add to. To fix that we check to see if the object isNaN (is not a number). If
					// it isn't a number, then we create the key with a 0 value. That lets us do the 
					// addition below
					if(isNaN(rankings[key])) {
						rankings[key] = 0;
					}
					
					// add (or subtract) the ranknumber to the rankings object
					rankings[key] += rankNum;
				}
			}
			
		});
		
		// Now we have our output rankings object with the scores for each class, we need
		// to figure out which one is the greatest score.
		
		// create our new output object
		var recommended = GetRecommendedClass(rankings);
		
		var $messagebox = $parent.find('.message');
		
		$messagebox.text('The recommended class is: ');
		for(var i = 0; i < recommended.personality.split(',').length; i++) {
			if(i > 0) $messagebox.append(' or ');
			$messagebox.append(recommended.personality.split(',')[i]);
		}
	});
	
});

function GetRecommendedClass(rankings) {
	// create our new output object
	var recommended = {personality: '', score: 0};
	
	// loop through the values in the rankings object
	for (var key in rankings) {
		if (rankings.hasOwnProperty(key)) {
		
			// if the current value is greater than the previous score, replace the previous score
			if(rankings[key] > recommended.score) {
				recommended.personality = key;
				recommended.score = rankings[key];
			}
			
			// if the current value is the same as the previous, combine them
			// -- remember that I'm returning comma seperated values here...
			if(rankings[key] == recommended.score) {
				if(!recommended.personality.match(key)) recommended.personality += ',' + key;
				recommended.score = rankings[key];
			}
		
		}
	}
	
	return recommended;
}

function StringToObject(str){
	var V={};
	var A=str.split(',');
	var L=A.length,temp;
	for(var i=0; i<L; i++){
		temp= A[i].split(':');
		V[temp[0]]=temp[1];
	}
	return V;
}


