//jQuizzer Plug-in by Jeremiah Tolbert
(function(jQuery){

	//Attach this new method to jQuery
 	jQuery.fn.extend({ 
 		
 		//This is where you write your plugin's name
 		jquizzer: function(options) {
			//Set default values here
				var defaults = {
					numberofQuestions : 5,
					questionClass: ".question",
					questionIDPrefix : "#question-",
					answerValues : ["red","green","blue","yellow"]
				}			
			//Iterate over the current set of matched elements
    		return this.each(function() {
					var o = jQuery.extend(defaults, options);  
					var i = 1;
					var quiz = jQuery(this);
					var answers = jQuery(this).find('input');		
					//initialize the data stores for the answer types
					for (var a in o.answerValues){
						jQuery(this).data(o.answerValues[a], 0);
					}
					
				jQuery(this).children().not(o.questionIDPrefix+i).hide(); // hide all the questions except the first
					
				answers.bind('click',function(){//Here's what happens when we select an answer
						var value = jQuery(this).attr('value'); //get the values from the select
						var scorepairs = value.split(','); //split the value pairs by a comma
						 	for (z in scorepairs) {
								var score = scorepairs[z].split(':'); // split the score and its value by a : symbol
								var answer = score[0]; // set a variable with the name of the data store
								var scoreValue= parseInt(score[1]); //set a variable equal to integer of score value
								var currentValue = quiz.data(answer); // get the current value of the data store
								var newValue = currentValue + scoreValue; // add old value and new values
								quiz.data(answer, newValue); //write the new value to the datastore	
							}
						
						if (i < o.numberofQuestions) {  // make sure this isn't the last question
						i++;
						jQuery(this).parents('.questions').hide(function(){	
							quiz.children(o.questionIDPrefix+i).show();	
			
						});
													} else {
						//do something at the end of the quiz
							var answersArray = new Array();  //initalize an array 
							function findHi(A) {  //utility function to find the highest winner in an array
								hi = 0;
								for (i in A) {
									if (A[i] > hi) {
										hi = A[i];
										remember = i;
									}	
								}
								return remember;
							}
							
							for (var b in o.answerValues) {
								answername= o.answerValues[b];
							    ansvalue = quiz.data(o.answerValues[b]);
								answersArray[answername]=ansvalue;
								
							}
							var winner = findHi(answersArray);		
							jQuery(this).parents('.questions').hide(function(){	
							jQuery("#"+winner).show();
																});
																							
													}
					});
    		});
    	}
	});
	
//pass jQuery to the function
})(jQuery);
