//----------------------------------------------------------------------------------
// Quiz
// Just an Object that holds lots of
// other objects relevant to the "Quiz"
Quiz = {};
//----------------------------------------------------------------------------------

   var clearMasteryLog = function(lpId) {
		 if (!confirm('Clear status and start again?')) return false;
		  var params = {
				method:'GET',
				parameters:'action=clear_mastery_log&lpId='+lpId,
				onComplete: function(responseObj) {
          updateOutline(lpId);
				}
			}
		  var clear = new Ajax.Request(jsconfig.ajax,params); 
	 }
	 
	 var updateOutline = function(lpId) {
		  var outline_id = 'lesson_plan_'+lpId+'_outline';
		  if (!$(outline_id)) return false;
			var get_outline = new Ajax.Request(jsconfig.ajax,
																				 {
																					 method:'get',
																				   parameters:'action=lesson_plan_outline&lpId='+lpId,
																					 onComplete: function(responseObj) {
																						 var response = JSON.parse(responseObj.responseText);
																						 if (response.outline && $(outline_id)) {
																							Element.update(outline_id,response.outline);
																						 }
																						 if (response.nextActivity && $('test_next')) {
																							 Element.update('test_next',response.nextActivity);
																						 }																						 
																					 }
																					});			
	 }
	 
	 var topic_display;



//----------------------------------------------------------------------------------
// Update the results tab
		
	 Quiz.PrintResults = [];
	 Quiz.view_print = function(missed) {
		 if (Quiz.PrintResults.length < 1) return false;
		 var last_result = Quiz.PrintResults[Quiz.PrintResults.length-1];
		 if (missed) var html = last_result.missed;
		 else var html = last_result.test;
  	 var print_window = window.open('','the_print_window','left=20,top=20,scrollbars=yes,menubar=yes,toolbar=yes,resizable=yes,');
		 var print_doc = print_window.document;																																		
		 print_doc.write(html);
		 print_doc.close();
	 }

//----------------------------------------------------------------------------------
// end Quiz.ResultsTab
//----------------------------------------------------------------------------------


//----------------------------------------------------------------------------------
// Update the results tab

	Quiz.ResultsTab = function(html,loadOnly) {
		if (!Quiz.tabset) return false;
		var tabset = Quiz.tabset;
		var tabset_id = tabset.get_tabset_id();
		var tab_id      = 'quizResults';	
		var full_tab_id = 'tabset_'+tabset_id+'_tab_'+tab_id;
		if (!$(full_tab_id)) {
			var params = {			
				name: 'Results',
				id: tab_id
			};
			tabset.new_temp_tab(params);
		}
		tabset.select_tab_by_id(tab_id);
		Element.update(full_tab_id+'_content',html);		
		if (loadOnly) {
			aParams = {message:' Loading Results...',container:'P',className:'center'};
			$(full_tab_id+'_content').appendChild(commonjs.ajax_loading(aParams));
		}
		Element.scrollTo(full_tab_id);					
	}
//----------------------------------------------------------------------------------
// end Quiz.ResultsTab
//----------------------------------------------------------------------------------


//----------------------------------------------------------------------------------
// Build Containers For Quiz
	 Quiz.ContainerBuilder = Class.create();
	 Quiz.ContainerBuilder.prototype = {	 
			
			initialize: function() {
				this.built = {};
				this.loading();
				this.tableContainer();
			},
			
			loading: function() {
				 if (this.built.loading) return this.built.loading;
				 var loadingText = " Loading...";
				 var loadingImg  = Builder.node('IMG',{src:jsconfig.loading_image,alt:loadingText});
				 var loading = Builder.node('DIV',{},[loadingImg,loadingText]);
				 this.built.loading = loading;
				 return this.built.loading;
			},
			
			show: function() {
				var main = this.main();
				document.body.appendChild(main);
				Element.hide('everythingContainer');
			},
			
			clear: function() {
				var main = this.main();
				Element.remove(main);
				this.built = {};
				Element.show('everythingContainer');
			},
			
			main: function() {
				 if (this.built.main) return this.built.main;
				 var main = Builder.node('DIV',{className:'quizMain quiz_container_back floatholder'});
				 this.built.main = main;
				 return this.built.main;
			},
			
			quizContainer: function() {
				return this.built.quizContainer;
			},
			
			outlinePlaceholder: function() {
				return this.built.outlinePlaceholder;
			},
			
			padding: function() {
				if (this.built.padding) return this.built.padding;
				var padding = Builder.node('DIV',{className:'window_container_border padding quiz_padding'});
				var main = this.main();
				main.appendChild(padding);
				this.built.padding = padding;
				return this.built.padding;
			},
			
			tableContainer: function() {
				 if (this.built.tableContainer) return this.built.tableContainer;
				 var outlinePlaceholderCell = Builder.node('TD',{className:'outline_placeholder aligntop',valign:'top'});
				 var quizContainer = Builder.node('DIV',{className:'quiz_container'});
				 var quizContainerCell = Builder.node('TD',{valign:'top'});
				 var row1 = Builder.node('TR',{},[outlinePlaceholderCell,quizContainerCell]);
				 var tbody = Builder.node('TBODY',{},[row1]);
				 var table = Builder.node('TABLE',{className:'quiz_table_container',width:"98%"},[tbody]);
				 var padding = this.padding();
				 padding.appendChild(table);
				 this.built.tableContainer = table;
				 this.built.quizContainer = quizContainerCell;	
				 this.built.outlinePlaceholder = outlinePlaceholderCell;
				 return this.built.tableContainer;
			}
//----------------------------------------------------------------------------------
// end Quiz.ContainerBuilder
	}
//----------------------------------------------------------------------------------
	 
	 
//----------------------------------------------------------------------------------
// Loads a new Quiz
	Quiz.Loader = function() 
	{		
	
			commonjs.preload_images(['http://www.studytag.com/images/site/3MA_loadingcontent.gif',
															 'http://www.studytag.com/images/site/studytag-small.gif']);
			//hide_start_screen();
			var content = [];
			var quiz = null;
			var mode = '';
			//commonjs.preload_images(response.preload_images);
			
		  this.Settings = new function() {
			 
			  this.info = {
				  settings: {},
					controller: {}
			  }
			  
				this.get = function() {
					return this.info;
				}
			 
			  this.add = function(obj) {
				  Object.extend(this.info, obj); 
			  }
			 
			  this.set = function(obj) {
				  this.info = obj;
			  }
			 
		  }();
						
			this.setContent = function(_content) {
				content = _content;
			}
			
			this.null_quiz = function() {
				quiz = null;
			}
			
			this.setMode = function(_mode) {
				mode = _mode;
			}
			
			this.handleAjaxResponse = function(responseObj) {
				var response = JSON.parse(responseObj.responseText);
				content = response.content;
				if (response.mode) mode = response.mode;
				if (response.settings) this.Settings.add(response.settings);
				if (response.cname)    this.Settings.add({cname:response.cname});
				if (response.ctype)    this.Settings.add({ctype:response.ctype});				
				if (response.styles)   this.Settings.add({style:response.styles});
				this.start();
			}
			
			this.loadWithAjax = function(controller) {
				// if (isMe('eric1')) alert(JSON.stringify(this.Settings));
				this.Settings.add({controller:controller});
				if (this.Settings.info.showLoading) {
					Element.hide('everythingContainer');
					var image = Builder.node('IMG',{src:'http://www.studytag.com/images/site/3MA_loadingcontent.gif'});
					var logo  = Builder.node('IMG',{src:'http://www.studytag.com/images/site/studytag-small.gif'});
					var loading = Builder.node('DIV',{className:'absolute loadingBox'},[logo,commonjs.br(),image]);
					document.body.appendChild(loading);
					document.body._previousBGColor = document.body.style.backgroundColor;
					document.body.style.backgroundColor = '#999999';
					Position.Center(loading);
				}
				var controllerStr = JSON.stringify(controller);
				    controllerStr = urlencode(controllerStr);
				var params = {
					method: 'POST',
					parameters:'action=quiz_load&controller='+controllerStr,
					onComplete: this.handleAjaxResponse.bind(this)
				}
				var get = new Ajax.Request(jsconfig.ajax,params);
				var cancel = Builder.node("BUTTON",{},['Cancel']);
				cancel.onclick = function() {
					get.options.onComplete = Prototype.emptyFunction;
					document.body.style.backgroundColor = document.body._previousBGColor;
					Element.remove(loading);
					Element.show('everythingContainer');					
				}
				var cancelP = Builder.node('P',{className:'center'},[cancel]);
				loading.appendChild(cancelP);
				this.loading = loading;
			}
			
			this.start = function() {
				if (this.loading) {
					document.body.style.backgroundColor = document.body._previousBGColor;
					Element.remove(this.loading);
				}
				if (mode == 'test') quiz = new Quiz.TestMode();
				else if (mode == 'reading' || mode == 'stepthrough' || mode == 'presentation' || mode == 'flashcard') quiz = new Quiz.StepThroughMode();
				else if (mode == 'tutor') quiz = new Quiz.TutorMode();
				else if (mode == 'introduction') quiz = new Quiz.IntroductionMode();					
				else { alert('what??'); return false; };
				 quiz.mode = mode;
				 if (mode == 'flashcard') quiz.show_as_flashcard = true;
				 if (mode == 'presentation' || mode == 'flashcard') quiz.mode = 'stepthrough';
				 quiz.set_content(content);
				 quiz.set_loader(this);
 				 quiz.set_settings(this.Settings.get());
				 quiz.points_hack();
				 quiz.apply_styles();
				 quiz.start();				 
				 Quiz.HotKeys.enable(quiz);
			}

//----------------------------------------------------------------------------------
// end Quiz.Loader
}
//----------------------------------------------------------------------------------

//----------------------------------------------------------------------------------
// Hot Keys for Quiz
	Quiz.HotKeys = new function() {

		var key_pressed  = false;
		var quizObj			 = false;
		
		this.enable = function(_quizObj) {
			 quizObj = _quizObj;
			 Event.observe(document,'keydown',keyPressed,false);				// add event listener for hot keys
			 Event.observe(document,'keyup',hotKeys,false);					 		// add event listener for hot keys					 			
		}
		
		this.disable = function() {
			 quizObj = false;
			 Event.stopObserving(document,'keydown',keyPressed,false);	// remove event listener for hot keys
			 Event.stopObserving(document,'keyup',hotKeys,false);				// remove event listener for hot keys				
		}		
				
		function keyPressed(evt)
		{
			var e = new xEvent(evt);
			var test = quizObj;
			if (Element.hasClassName(e.target,'nohotkey')) key_pressed = false;
			else if (TopicWindow.isVisible()) key_pressed = false;	// don't use hot keys if topic window is showing
			else if ($('report_abuse_window') && $('report_abuse_window').style.display == '') key_pressed = false;	// don't use hot keys if report abuse window is showing
			else if (test.current_format == 'fillintheblank' && test.first_key_pressed == false)
			{
				var input = $(test.fill_in_the_blank_input_id);
				Field.focus(input);
				test.first_key_pressed = true;
			}
			else key_pressed = true;
		}
	
		function hotKeys(evt)
		{
			var e = new xEvent(evt);	  
			var test = quizObj;
			if (key_pressed == false) return false;
			key_pressed = false;
	
			// if we aren't showing content - ignore
			if (test.current_format == 'none') return;
			// key that triggered event
			var key = e.keyCode;
			//if (jsconfig.me == 'eric1') alert(key);
			// fill in the blank
			if (test.current_format == 'fillintheblank')
			{
				if (key == 13 && e.target.id.indexOf('fillintheblank') == 0) test.process_answer(e.target.value,'fillintheblank'); // enter for fill in the blank
				return;
			}
			// other formats
			var buttons = test.answer_node.getElementsByTagName("button");		
			
			if (test.current_format == 'wronganswer')
			{
				if (key == 78) test.next();
			}		
			if ((test.mode == 'tutor' || test.mode == 'introduction') && buttons.length == 1)
			{
				if (key == 78 && (test.current_format == 'true' || test.current_format == 'reading')) { test.process_answer('Next'); return; }
				return;
			}
			if (test.mode != 'stepthrough' && test.mode != 'reading' && buttons.length == 1)
			{
				if (key == 32) test.next();
				return;
			}
			if (test.mode == 'stepthrough' || test.mode == 'reading')
			{
				if (key == 37 || key == 80) 			{ test.process_answer('Previous'); return; }
				else if (key == 39 || key == 78) { test.process_answer('Next'); return; }
				else if (key == 68) { test.cancel_out(); return }
			}
			if (test.current_format == 'truefalse')
			{
				if (key == 84) 			{ test.process_answer('True'); return; }
				else if (key == 70) { test.process_answer('False'); return; }
			}		
			for(i=0;i<buttons.length;i++)
			{
				if (key == (i+49) || key == (i+97) || buttons.length == 1 && key == 32)
				{
					test.process_answer(buttons[i].title);
					return;
				}
			}
		}
//----------------------------------------------------------------------------------
// end Quiz.HotKeys
	}();
//----------------------------------------------------------------------------------
		

//----------------------------------------------------------------------------------
// Quiz.Base
// All modes inherit these methods
// Though they can be locally overwritten
Quiz.Base = function(){};
Quiz.Base.prototype = {
//----------------------------------------------------------------------------------
	// points are awarded for correct answers
	// how many points is determined by the currect format
	points:{
	'true':0,
	'truefalse':20,
	'multiplechoice':50,
	'fillintheblank':100,
	'reading':0,
	'incorrect':0
	},

	points_earned:0,
	// for mark as correct
	if_correct_points:0,
  // time the last question was asked (for point calculation)	
	time_asked:0, 		
	// fill in the blank input id
	fill_in_the_blank_input_id:null,
	// first key pressed for ie focus hack
	first_key_pressed:false,
	// first question? for fill in the blank
	first_question_displayed:false,
	// for formats that replace variable with blank line
	blank_line:"_____________",

	// stats
	stats:{
		content:[],	// array containing objects specific to each content	  
		quiz:{}	// general quiz stats object		
	},	// stats object to send to server side

	// set by each rendering function so content can be displayed
	answer:null,																											// the current answer
	the_content:null,																									// the main content (fact,text)
	the_answer_input:null,																						// the answer input area (buttons,text input, etc...)
	the_title:null,																										// the title bar text
	the_style:null,																										// the style for the entire quiz
	current_format:null,																							// the current format in which the content is being displayed
	settings:null,																										// settings for the current content set
	
	// uncategorized variables
	time_elapsed:0,
	mode:null,						// mode we are running in - this is used for sending data back to server.

	// start
	start:function()	{
		Element.update(this.status_node,this.current_index+1 + ' of ' + this.content.length);
		this.display();
		this.timer.start();
	},

	initialize:function() {
		// stats
		this.stats = {
			content:[],	// array containing objects specific to each content	  
			quiz:{}	// general quiz stats object		
		};	// stats object to send to server side
	},

	// set settings
	set_settings:function(settings)	{
		this.settings = settings;
	},

	apply_styles:function() {
		// if (isMe('eric1')) alert(JSON.stringify(this.settings));
		if (this.settings.style) {
			//if (isMe('eric1')) alert(JSON.stringify(this.settings.style));
			Element.setStyle(this.content_node,this.settings.style);
		}
	},

	// set content
	set_content:function(content) {
		this.timer          = new Timer();
		this.content 				= content;																		// the content object
		this.remaining 			= content.length;															// content not yet answered correctly this session
		this.current_index 	= 0;																					// the index of the current content
		// page elements
		this.DOMNodes = new Quiz.ContainerBuilder();
		this.container_node = this.DOMNodes.quizContainer();		              	// the container for the quiz (on page);
		
		this.DOMNodes.show();
		
		// if ($('top_menu_container')) $('top_menu_container').parentNode.removeChild($('top_menu_container'));
		
		this.answer_node  			= Builder.node('DIV',{className:'answer_node floatholder'});		// the answer_node (on page)
		this.content_node 			= Builder.node('DIV',{className:'content_node'});		// the content_node (on page)
		this.title_node					= Builder.node('DIV',{className:'title_node'});			// the content title bar (on page);
		this.finished_node			= Builder.node('DIV',{className:'finished_node'});	// 
		this.top_menu_container	= Builder.node('DIV',{className:'top_menu_container window_info_bar'});	// 
		this.top_menu						= Builder.node('DIV',{className:'top_menu'});					// top menu bar
		this.status_node				= Builder.node('P',{className:'status_node inline indent5px'});			// the status for the quiz (on page);
		
		// create the mark_correct div
		this.mark_correct_link = commonjs.jslink('mark as correct',{className:'quiz_bottom_button',
																						 title:'Mark my answer as correct'});
		this.mark_correct_link.onclick = this.mark_as_correct.bind(this);
		this.mark_correct = Builder.node('DIV',{},[this.mark_correct_link]);
		
		var small_logo = Builder.node('IMG',{src:jsconfig.site_image+'studytag-small.gif',align:'text-top'});
		var small_logo_container = Builder.node('DIV',{className:'float_left'},[small_logo,this.status_node]);
		
		var spacer_div = Builder.node('DIV',{className:'spacer'},[' ']);
		var done_text	 = commonjs.new_element({element:'BUTTON',title:'Take me back to the start screen'});
		    done_text.onclick = this.cancel_out.bind(this);
		    // done_text.onclick = this.display_end_screen.bind(this);				
				done_text.innerHTML = '<img src="/images/site/stop.gif" align="top">';

		var comment_text = Builder.node('BUTTON',{title:'Comment on current content'});
		comment_text.innerHTML = '<img src="/images/site/comment.gif" align="top">';
		comment_text.onclick   = this.load_topic.bind(this);
		
		var flag	= commonjs.new_element({element:'BUTTON',id:'flag_link_1000',name: 'flag_link_1000',title: 'Flag as Inappropriate Content',
																												 onclick: function() {ShowReportAbuseWindow('where=2');}
																					 						 });
				flag.innerHTML = '<img src="/images/site/flag.gif" align="top">';
		
		var special_characters_button = Builder.node('BUTTON',{title:"Special Characters",onclick:"SpecialCharactersWindow()"},[Builder.node('IMG',{src:jsconfig.site_image+'text_letter_omega.gif',align:'top'})]);
		
		
		this.top_menu.appendChild(comment_text);
		this.top_menu.appendChild(special_characters_button);
		if (jsconfig.loggedIn) {
			this.top_menu.appendChild(flag);
		}
		this.top_menu.appendChild(done_text); 		
		this.top_menu_container.appendChild(small_logo_container);
		this.top_menu_container.appendChild(this.top_menu);
		this.top_menu_container.appendChild(spacer_div);
		this.DOMNodes.main().insertBefore(this.top_menu_container,this.DOMNodes.padding());		
		Nifty("div.top_menu_container","top");
		commonjs.append_children(this.container_node,[this.title_node,this.content_node,this.answer_node]);		
	},
	
	load_topic: function() {
		var c_id = this.content[this.current_index].id;
		var l_id = this.content[this.current_index].lesson_id;
		TopicWindow.get_topic(c_id,l_id);
	},
	
	set_loader: function(obj) {
		this.loader = obj;
	},
	
	cancel_out: function() {
		this.DOMNodes.clear();
		this.timer.stop();
		this.timer = null;
		this.loader.null_quiz();
	},
	
	// points hack to parse points from database as int
	points_hack:function() {
		for(var i=0;i<this.content.length;i++)
		{
			this.content[i].mastery_log.correct_in_a_row = parseInt(this.content[i].mastery_log.correct_in_a_row);			
		}
	},		
	
	calculate_content_stats:function()	{
		for(var i=0;i<this.content.length;i++)
		{
			var content 									  			= this.content[i];		
			this.stats.content[i] 								= new Object();
			this.stats.content[i].id 		 	  			= content.id;
			this.stats.content[i].correct 				= content.answered_correctly;
			this.stats.content[i].incorrect 			= content.incorrect_answers;
			this.stats.content[i].correct_answers = content.correct_answers;
			this.stats.content[i].mastery_log 		= content.mastery_log;
		}
	},

	calculate_quiz_stats:function()	{
		this.stats.quiz.flash_cards_remaining		= 0;
		this.stats.quiz.flash_cards_suppressed	= 0;
		this.stats.quiz.correct 								= 0;
		this.stats.quiz.incorrect  							= 0;
		this.stats.quiz.percent_correct_total 	= 0;
		this.stats.quiz.percent_correct_taken		= 0;
		this.stats.quiz.answers									= 0;
		this.stats.quiz.points									= 0;		
		this.stats.quiz.correct_answers					= 0;
		this.stats.quiz.content_length					= 0;
		
		this.calculate_content_stats();
		
		for(var i=0;i<this.stats.content.length;i++)
		{
			var content 										= this.stats.content[i];
			if (content.correct == true)		this.stats.quiz.correct +=1;
			this.stats.quiz.correct_answers += content.correct_answers;
			this.stats.quiz.incorrect 			+= content.incorrect;
		}
		this.stats.quiz.points									= this.points_earned;
		this.stats.quiz.content_length					= this.content.length;
		this.stats.quiz.answers 								= this.stats.quiz.correct_answers + this.stats.quiz.incorrect;
		this.stats.quiz.percent_correct_taken 	= this.stats.quiz.correct_answers > 0 ? Math.round(this.stats.quiz.correct_answers/this.stats.quiz.answers*100) : 0;
		this.stats.quiz.percent_correct_total 	= this.stats.quiz.correct > 0 ? Math.round(this.stats.quiz.correct/this.content.length*100) : 0;

		// this.stats.quiz.id 									= QuizSettings.info.id;
		// this.stats.quiz.name   							= QuizSettings.info.name;		
		this.stats.quiz.seconds 						= 0;
		this.stats.quiz.time_elapsed				= !this.timer.timeElapsed || this.timer.timeElapsed < 1000 ? 1000 : this.timer.timeElapsed;
		this.timer.reset();
	},

	// if outline present - do highlighting
	highlight_outline:function() {
		if ($('outline'))	{
			var thelinks = $('outline').getElementsByTagName('A');
			var trackBack = this.content[this.current_index].track_back;
			thelinks = $A(thelinks);
			thelinks.each(function(alink,i) {
				 alink.className = '';				 
				 if (alink.rel == trackBack) {
					  alink.className = 'outline_highlight'; 
				 }
			});
		}
	},

	// display selected content
	display:function(format)	{	
		this.timer.start();
		key_pressed = false;
		if (!format) var format = this.random_format();
		switch ( format )
		{
			case "truefalse":	     this.render_as_truefalse();      break;
			case "multiplechoice": this.render_as_multiplechoice(); break;
			case "fillintheblank": this.render_as_fillintheblank(); break;
			case "reading":				 this.render_as_reading();				break;
			case "true":					 this.render_as_true();						break;
			case "wronganswer":		 this.render_as_wronganswer();		break;			
			default:							 this.render_as_true();						break;
		}
		remove_children(this.answer_node);
		this.answer_node.appendChild(this.the_answer_input);
		Element.update(this.content_node,this.the_content);
		this.title_node.innerHTML			= this.the_title;
		this.container_node.className	= this.the_style;
		this.highlight_outline();
		this.time_asked = this.timer.timeElapsed > 0 ? this.timer.timeElapsed : 0;
	},
	
	random_format:function() {
		var formats  = this.content[this.current_index]['formats'];
		var	selected = Math.floor(Math.random()*formats.length);
		var format 	 = formats[selected];
		return format;
	},
	
	// render as true
	// works for question content type
	render_as_true:function() {	
					if (isMe('eric1')) alert('hi');
		var fact = this.content[this.current_index].fact;									// fact
		    fact = fact[0] + fact[1] + fact[2];														// display fact
		var answer_input = document.createElement('DIV');									// create answer input
				answer_input.appendChild(this.create_button('True',true));		// append button

		this.the_answer_input = answer_input;															// answer_input
		this.the_content 			= fact;																			// content
		this.the_title				= this.settings.fact_name ? this.settings.fact_name : 'Fact';																		// title
		this.the_style				= 'fact';																		// style
		this.current_format 	= 'true';																		// current format
						if (isMe('eric1')) alert('hi');
	},

	// render as wronganswer
	// works for question content type
	// display this when content is answered incorrectly
	render_as_wronganswer:function()	{
		this.timer.stop();
		var displayed 	 = this.the_content;																	// question displayed
		var wrong_answer = this.wrong_answer;
		var right_answer = this.answer;				

		var the_content  = '<strong>Displayed:</strong><div class="wronganswer">'+displayed+'</div>';
				if(this.current_format == 'truefalse' || (this.current_format == 'multiplechoice' && right_answer == 'none of the above')) the_content += '<strong>Correct Answer:</strong><div class="wronganswer">'+right_answer+' ( ' + this.content[this.current_index].fact[1] + ' )</div>';
				else the_content += '<strong>Correct Answer:</strong><div class="wronganswer">'+right_answer+'</div>';	
				the_content += '<strong>Your Answer:</strong><div class="wronganswer">'+wrong_answer+'</div>';
		var answer_input = document.createElement('DIV');													// create answer input
		answer_input.appendChild(this.create_smart_button('Next Question','<u>N</u>ext Question',true));							// append button			
		answer_input.appendChild(this.mark_correct);															// append mark correct link
				
		this.answer = 'mark_correct';

		this.the_answer_input = answer_input;															// answer_input
		this.the_content 			= the_content;															// content
		this.the_title				= 'Incorrect Answer';												// title
		this.the_style				= 'fact';																		// style
		this.current_format 	= 'wronganswer';	// current format				
	},

	// render as reading
	// works for reading content type	
	render_as_reading:function() {	
		var text = this.content[this.current_index]["text"];							// text

		this.answer = "Next"; // set correct answer
 		var answer_input = document.createElement('DIV');
		answer_input.appendChild(this.create_smart_button('Next','<u>N</u>ext'));	// create button
		this.the_answer_input = answer_input;
		this.the_content 			= text;																			// text
		this.the_title				= this.content[this.current_index]["name"]; // reading title
		this.the_style				= 'reading';
		this.current_format 	= 'reading';	// current format		
	},
	
	// render as true false
	// works for question content type	
	render_as_truefalse:function()	{
		var fact = this.content[this.current_index]["fact"];							// fact		
		var use_correct = Math.floor(Math.random()*2); 										// decide whether to use correct answer or foil
		if (use_correct == 1)
		{			
			var random_foil = this.content[this.current_index]["foils"][Math.floor(Math.random()*this.content[this.current_index]["foils"].length)]
			fact = fact[0] + random_foil + fact[2];
			this.answer = "False";
		}
		else 
		{
			var fact = fact[0] + fact[1] + fact[2];
			this.answer = "True";
		}
		var answer_input  = document.createElement('DIV');
		    answer_input.appendChild(this.create_smart_button('True','<u>T</u>rue'));
		    answer_input.appendChild(this.create_smart_button('False','<u>F</u>alse'));
		this.the_answer_input = answer_input;
		this.the_content			= fact;
		this.the_title				= 'Question';
		this.the_style				= 'question';
		this.current_format 	= 'truefalse';	// current format
	},

		// render as multiple choice
	// works for question content type	
	render_as_multiplechoice:function()	{
		var content = this.content[this.current_index];
		var fact    = content["fact"];
		var inorder = content.inorder === false ? false : true;
		var add_correct_answer = false;
		var noneoftheabove_display = this.settings.noneoftheabove;
		if (content.noneoftheabove != null) noneoftheabove_display = content.noneoftheabove;
		var show_none_of_the_above = false;		
		fact		    = fact[0]+this.blank_line+fact[2];																			// set correct answer
		var mc_max = content["mc_max"];

		if (inorder) mc_max = (content['foils'].length+1);
		
		var answers = [];																								// initalize answer array
		if (!inorder) content["foils"] = shuffleArray(content["foils"]);
		
		for ( var i=0;i<(mc_max-1);i++ ) {
		  if (content["foils"][i]) answers[i] = content["foils"][i];						// add foils		
		}
		if (noneoftheabove_display == 1 || (noneoftheabove_display == 2 && Math.floor(Math.random()*3) == 1))
		{		
			show_none_of_the_above = true;												
			if (Math.floor(Math.random()*mc_max) == 1){
			  this.answer	= 'none of the above';			  
			}
			else {
			  add_correct_answer = true;
			  answers.pop(); // remove one foil to make room for "none of the above" (FFNA)
			}		
		}
		else
		{
			add_correct_answer = true;
		}

		if (add_correct_answer == true)
		{
			this.answer	= content["fact"][1];
			if (inorder) 	answers = insert_into_array(answers,content.inorder,this.answer);
			else {			   
			   answers.push(this.answer);			  
			}
		}
		
		if (!inorder) answers = shuffleArray(answers);																											// shuffle answer array
		if (show_none_of_the_above == true) answers.push('none of the above');
		var answer_input = document.createElement('DIV');
		for ( var i=0;i<answers.length;i++)																										// build answer input
		{
			var new_div = document.createElement('div');
					new_div.className = 'quiz_button'; 
			var	number_div = document.createElement('div');
					number_div.className = 'number_button';
					number_div.innerHTML = i+1;
					new_div.appendChild(number_div);
					new_div.appendChild(this.create_button(answers[i]));
			answer_input.appendChild(new_div);			
		}
		var spacer_div = document.createElement('div');
				spacer_div.className = 'spacer';
		answer_input.appendChild(spacer_div);

		this.the_content 			= fact;
		this.the_answer_input = answer_input;
		this.the_title				= 'Question';
		this.the_style				= 'question';
		this.current_format 	= 'multiplechoice';	// current format		
	},
	// fill in the blank
	// works for question content type	
	render_as_fillintheblank:function() {
		var fact = this.content[this.current_index]["fact"];															// set fact
		this.answer = fact[1];																														// correct answer
		
		var random_id = "fillintheblank"+Math.floor(Math.random()*1000000);
		var blank = Builder.node('INPUT',																			// create text input field
				{
					id:random_id,								// set random id to trick autofill
				  type:'text',
				  size:'50',
				  value:"",
				  className:'iconPadRight'
				});

		var htmlcontainer = Builder.node('P',{},[blank]);
		
		specialCharacterDrop = blank.id;
		
		fact = fact[0] + htmlcontainer.innerHTML + fact[2]; 							// set fact to display (with blank line)
    
		var blank_submit = Builder.node('INPUT',{type:'button',value:'Fill in the Blank'});
		blank_submit.onclick = this.process_answer_value_from_id.bind(this,random_id);
		
		var answer_input = Builder.node('DIV',{},[blank_submit]);				
				
		this.fill_in_the_blank_input_id = blank.id;
		this.the_answer_input = answer_input;
		this.the_content			= fact;										
		this.the_title				= 'Question';
		this.the_style				= 'question';
		this.current_format 	= 'fillintheblank';	// current format
		this.first_key_pressed = false;
	},

	process_answer_value_from_id: function(id) {
		if (!$(id)) var value = '';
		else var value = $(id).value;		
		this.process_answer(value);
	},

	/*/ show topic window for current content
	this.show_topic_window = function()
	{		
		var id = 'topic_window';
		if (!$(id))
		{
			var topic_window 		= new Window();
					topic_window.id = id;
					topic_window.title = 'Comment Window';
					topic_window.loading = true;
					topic_window.create();
		}
		xGetElementById(id+'_inner').innerHTML = '';
		$(id).style.display = '';
		this.get_topic(id);
	}

	// load forum
	this.get_topic = function(window_id)
	{
		var c = this.content[this.current_index].id;
		var l = QuizSettings.info.id;
		var xmlhttp = new XMLHttpRequest();
		xmlhttp.open("GET", jsconfig.site.root+"library/quiz_actions.php?action=gettopic&content="+c+"&lesson="+l,true);
 		xmlhttp.onreadystatechange=function() {
  		if (xmlhttp.readyState==4) {
				var response = JSON.parse(xmlhttp.responseText);
				if (response == false) $(window_id+'_inner').appendChild(document.createTextNode(xmlhttp.responseText));
				else 
				{ 
					xGetElementById(window_id+'_inner').innerHTML = '';
					topic_display = new Topic(response.topic_id,xGetElementById(window_id+'_inner'),'topic_display');
				}
			}
 		}
 		xmlhttp.send(null)
	}*/

	// create button
	// value is the value of button
	// if second parameter is set, proceed to next question without processing answer
	// otherwise process answer with value
	// !depreciated
	create_button:function(value,skip) {
		var skippy = skip ? true : false;
		return this.create_smart_button(value,value,skippy);
	},

	// create a smart button
	// this will create a button with HTML inside
	create_smart_button:function(value,display,skip) {
		var button = Builder.node('button');									// create input
		button.className = 'quiz_button';
		button.title = value;																	// assign answer to title
		button.innerHTML = display;
		if (skip) button.onclick = this.next.bind(this);
		else button.onclick = this.process_answer.bind(this,value)
		return button;		
	},

	// checks answer against this.answer
	// if format == fillintheblank then check against content answers array (acceptable answers)
	// records common question stats
	answer_acceptable:function(answer) {
		var acceptable 			= this.check_answer(answer);
		var timer_penalty = this.timer.timeElapsed - this.time_asked;
				timer_penalty = timer_penalty > 0 ? Math.round(timer_penalty/1000) : 0;
		var current_points	= this.points[this.current_format] - timer_penalty;
				current_points  = current_points < 0 ? 0 : current_points;
		if (acceptable) 
		{
			this.content[this.current_index].correct_answers++;			
			this.content[this.current_index].answered_correctly = true;
			this.points_earned += current_points;
			this.content[this.current_index].mastery_log.correct_in_a_row++;
			this.content[this.current_index].mastery_log.correct_counter++;
		}
		else
		{
			this.if_correct_points = this.points_earned + current_points;
			this.content[this.current_index].incorrect_answers++;
			this.points_earned -= current_points;
			this.points_earned = this.points_earned < 0 ? 0 : this.points_earned;
			this.content[this.current_index].mastery_log.correct_in_a_row = 0;
			this.content[this.current_index].mastery_log.error_counter++;			
		}
		return acceptable;
	},

	check_answer:function(answer) {
		if (this.content[this.current_index].xsws != false)
		{
			answer 			= trim_xs_whitespace(answer);
			this.answer = trim_xs_whitespace(this.answer); 
		}
		if (Trim(answer.toLowerCase()) == Trim(this.answer.toLowerCase())) return true;
		if (this.current_format != 'fillintheblank') return false;
		for (var i = 0;i<this.content[this.current_index]["answers"].length;i++)
		{
			var aa = this.content[this.current_index]["answers"][i];
			if (Trim(answer.toLowerCase()) == Trim(aa.toLowerCase())) return true;
		}
		return false;
	},

	// mark correct
	mark_as_correct:function() {
		this.points_earned = this.if_correct_points;
		this.content[this.current_index].answered_correctly = true;
		this.content[this.current_index].correct_answers++;
		this.content[this.current_index].incorrect_answers--;
		this.content[this.current_index].mastery_log.correct_counter++;
		this.content[this.current_index].mastery_log.error_counter--;
		this.remaining--;
		this.next();
	},

	create_points_table:function() {
		QuizSettings.info.quiz_points += this.points_earned;
		QuizSettings.info.total_points += this.points_earned;
		if ($('initial_lesson_points')) $('initial_lesson_points').innerHTML = number_format(QuizSettings.info.points);
		update_total_points(QuizSettings.info.total_points);
		var table = document.createElement('TABLE');
		var	tbody = document.createElement('TBODY');
				table.appendChild(tbody);
				tbody.appendChild(create_row('Points Just Earned:',number_format(this.points_earned)));
				tbody.appendChild(create_row('Points This Lesson:',number_format(QuizSettings.info.points)));
				tbody.appendChild(create_row('Points All Lessons:',number_format(QuizSettings.info.total_points)));
		return table;	
	},

	// send data back to server
	save_data:function() {
	  this.calculate_quiz_stats();
		if (this.mode == 'test') {
			var view_test = this.build_test_results();
			var view_missed = this.build_test_results(true);
			Quiz.PrintResults.push({test:view_test,missed:view_missed});
		}
		Quiz.HotKeys.disable();
		var content_str = JSON.stringify(this.stats);
				content_str = urlencode(content_str);
		var controllerCopy = this.settings.controller;		
		var controller = JSON.stringify(this.settings.controller);
		    controller = urlencode(controller);
		var poststr = 'action=quiz_save&controller=' + controller + '&data=' + content_str;
		var params = {
			method: 'POST',
			parameters: poststr,
			onComplete: function(responseObj) {
			  var response = JSON.parse(responseObj.responseText);
				// Element.update('test_results','<pre>'+response.test_results+'</pre>');
				Element.update('test_next',response.next_activity);
				if (response.scripts) { response.scripts.evalScripts(); }
				if ($('lesson_plan_'+controllerCopy.lessonPlanId+'_outline')) {
					Element.update('lesson_plan_'+controllerCopy.lessonPlanId+'_outline',response.outline);
				}
				Quiz.ResultsTab(response.test_results);
			}
		};
		Quiz.ResultsTab('',true);
		var ajax_save_url = jsconfig.ajax_save ? jsconfig.ajax_save : jsconfig.ajax;
		var save = new Ajax.Request(ajax_save_url,params);
	}
	

//----------------------------------------------------------------------------------
// end Quiz.Base
}
//----------------------------------------------------------------------------------



//----------------------------------------------------------------------------------
// TestMode extends Quiz
Quiz.TestMode = Class.create();
Quiz.TestMode.prototype = Object.extend(new Quiz.Base(),{

	mode:'test',
	
	// display next
	next:function()	{	
		if 	(this.current_index+1 >= (this.content.length)) { this.display_end_screen(); return; }
		else this.current_index = this.current_index+1;
		this.status_node.innerHTML = this.current_index+1 + ' of ' + this.content.length;
		this.display();
	},
	
	// process answer
	// if correct/else if incorrect
	process_answer:function (answer)	{		
		this.content[this.current_index].your_answer 				= answer;
		var is_acceptable                                   = this.answer_acceptable(answer);
		this.content[this.current_index].question_displayed	= this.the_content;
		this.content[this.current_index].answer_input				= this.the_answer_input.innerHTML;
		this.content[this.current_index].displayed_as				= this.current_format;		
		if (this.current_format == 'truefalse' || (this.current_format == 'multiplechoice' && this.answer == 'none of the above'))
		{
			this.content[this.current_index].correct_answer = this.answer + ' (' + this.content[this.current_index].fact[1] + ')';
			if ( is_acceptable && (answer == 'False' || answer == 'none of the above') ) this.content[this.current_index].your_answer = answer + ' (' + this.content[this.current_index].fact[1] + ')';
		}
		else this.content[this.current_index].correct_answer = this.answer;

		if ( is_acceptable ) 																// if answer is correct
		{
			this.remaining--;
			this.next();																												// go to next
		}
		else
		{
			this.next();
		}
	},
	
	// make printable test
	build_test_results:function(missed)	{
		var container = document.createElement('DIV');
		var today = new Date();
		var today_string = (today.getMonth()+1) + '/' + today.getDate() + '/' + today.getFullYear();
		var lesson_name_node = Builder.node('SPAN',{},[': '+this.settings.cname]);
		var top_stats = Builder.node('DIV',{className:'top_info'},[
																					 Builder.node('SPAN',{className:'title'},['Test Results']),commonjs.br(),
																					 this.settings.ctype,lesson_name_node,commonjs.br(),
																					 'Member: '+jsconfig.me,commonjs.br(),
																					 'Date: ' + today_string,commonjs.br()
																					 ]);
		if (missed) top_stats.appendChild(document.createTextNode('Missed Questions: ' + this.stats.quiz.incorrect));
		else commonjs.append_children(top_stats,[document.createTextNode('No. Questions: '+this.content.length),commonjs.br(),
																					 document.createTextNode('Percent Correct: ' + this.stats.quiz.percent_correct_total + '%')]);
		container.appendChild(top_stats);
		
		for (var i=0;i<this.content.length;i++)
		{
			if (missed && this.content[i].answered_correctly == true) continue;
			var result 					= Builder.node('DIV',{className:'result'});
			var mark_image_name		 = this.content[i].answered_correctly ? 'check.gif' : 'cancel.png';
			var mark_image		 = commonjs.new_element({element:'IMG',src:'/images/site/'+mark_image_name});
			var question 			 = document.createElement('DIV');
			var title					 = Builder.node('SPAN',{className:'title'},['Question '+(i+1)+' ',mark_image]);
			
			/*
			if (!this.content[i].your_answer) {
				container.appendChild(title);
				result.appendChild(Builder.node('DIV',{className:'center'},['Not Answered.']));
				container.appendChild(result);
			  continue;
			}
			*/
			
			var your_answer 	 = Builder.node('SPAN',{className:'bold'},['Your Answer: ' + this.content[i].your_answer]);
			if( this.content[i].answered_correctly == false) {
				var correct_answer = Builder.node('SPAN',{className:'bold'},['Correct Answer: ']);
				    correct_answer.innerHTML += this.content[i].correct_answer				
			}
			else var correct_answer = document.createTextNode(' ');
			
			var answer_input = document.createElement('DIV');
			answer_input.innerHTML = this.content[i].answer_input;
			
			if (this.content[i].displayed_as == 'fillintheblank')
			{
				var inputs	= answer_input.getElementsByTagName('INPUT');
				for ( var j=0;j<inputs.length;j++)  { 
					inputs[j].parentNode.replaceChild(Builder.node('SPAN',{},[this.blank_line]),inputs[j]);
				  //inputs[j].className = 'fib'; inputs[j].id = "random"+Math.floor(Math.random()*1000000);	
				}
			}
			if (this.content[i].displayed_as == 'truefalse') {
				answer_input.innerHTML = 'Displayed as True/False';
			}
			else 
			{
				var buttons = answer_input.getElementsByTagName('BUTTON');
				var temp_answer_input = document.createElement('DIV');
				if (this.content[i].displayed_as == 'multiplechoice') {		
					temp_answer_input.appendChild(Builder.node('SPAN',{},['Displayed as MultipleChoice: ']));
				}
				for ( var j=0;j<buttons.length;j++)	
				{
					//temp_answer_input.appendChild(buttons[j].cloneNode(true));
					var extra = ', ';
					if (j == buttons.length-1) extra = '';
					var span2 = Builder.node('SPAN');
					span2.innerHTML = buttons[j].innerHTML + extra;
					temp_answer_input.appendChild(span2);
				}
				answer_input = temp_answer_input;
			}
			
			// extreme hack :-)
			// detect autoplaying wimpy buttons and disable autoplay for print view
			//------------------------------
			var wimpyAutoPlayDetect = '&autoplay=yes&displayRewindButton=no&playingColor=B3E0FF" width="35" height="35" bgcolor="#FFFFFF"';
			var wimpyAutoPlayReplace = '&autoplay=no&displayRewindButton=no&playingColor=B3E0FF" width="35" height="35" bgcolor="#FFFFFF"';
			var qText = this.content[i].question_displayed;		
			question.innerHTML = qText.gsub(wimpyAutoPlayDetect,wimpyAutoPlayReplace);		
			//------------------------------			
			var inputs	= question.getElementsByTagName('INPUT');
			for ( var p=0;p<inputs.length;p++)  { 
				inputs[p].parentNode.replaceChild(Builder.node('SPAN',{},[this.blank_line]),inputs[p]);
			}
			commonjs.append_children(result,[question,commonjs.br(),answer_input,commonjs.br(),your_answer,commonjs.br(),correct_answer]);
			commonjs.append_children(container,[title,result]);
		}
		var top_html = 	'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n<html><head>\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />\n<title>Print</title>\n<link href=\'http://www.studytag.com/print.css\' rel=\'stylesheet\' media=\'all\' type=\'text/css\'>\n</head>\n<body>\n<div id="print_area">';																																				
		var bottom_html = '</div>\n</body>\n</html>';
		return top_html + container.innerHTML + bottom_html;

	},
	
	// final screen
	display_end_screen:function()	{
		this.timer.stop();
		this.save_data();
		this.DOMNodes.clear();
		return false;
	}
//----------------------------------------------------------------------------------
// end Quiz.TestMode
});
//----------------------------------------------------------------------------------

//----------------------------------------------------------------------------------
// stepthrough mode
Quiz.StepThroughMode = Class.create()
Quiz.StepThroughMode.prototype = Object.extend(new Quiz.Base(),{
	mode:'stepthrough',
	show_as_flashcard:false,
	added_answer_input:false,
	added_done_button:false,

	// display next
	next:function()	{	
		if 	(this.current_index+1 >= (this.content.length)) this.current_index = 0;
		else this.current_index = this.current_index+1;
		this.display();
	},
	
	previous:function() {
		if 	(this.current_index-1 < 0) this.current_index = this.content.length-1;
		else this.current_index = this.current_index-1;
		this.display();		
	},
	
	// process answer
	// if correct/else if incorrect
	process_answer:function (answer) {
		this.content[this.current_index].answered_correctly = true;
		if ( this.added_done_button == false) this.display_done_button();
	  if 			( answer == 'Next'     ) this.next();
		else if ( answer == 'Previous' ) this.previous();
		else if (	answer == 'Done'		 ) this.cancel_out();
	},
	
	// add answer input
	add_answer_input:function() {
		if (this.added_answer_input == true) return;
		var answer_input  	= document.createElement('DIV');
		if (this.content.length == 1)
		{
			answer_input.appendChild(this.create_smart_button('Done','<u>D</u>one'));			
		}
		else
		{
			var previous 				= this.create_smart_button('Previous','<u>P</u>revious');
			var next 						= this.create_smart_button('Next','<u>N</u>ext');
			answer_input.appendChild(previous);			
			answer_input.appendChild(next);
		}
		remove_children(this.answer_node);
		this.answer_node.appendChild(answer_input);
		this.added_answer_input = true;
	},
	
	// display selected content
	display:function() {	
		this.add_answer_input();
		switch ( this.content[this.current_index]['type'] )
		{
			case "question":	     this.render_as_true();      break;
			case "reading":				 this.render_as_reading();	 break;
		}
		if (this.show_as_flashcard) this.render_as_flashcard();
		else {
			this.content_node.innerHTML 	= this.the_content;
			this.title_node.innerHTML			= this.the_title;
			this.container_node.className	= this.the_style;
		}
			this.status_node.innerHTML 		= this.current_index+1 + ' of ' + this.content.length;		
	},

	render_as_flashcard:function() {
		var show_link = Builder.node('A',{href:'javascript:void(0)'},['Click here see the back']);
				show_link.onclick = function() {
					card_back.className = 'flashcard_box';
					Element.hide(card_back);
					Effect.Appear(card_back);
					Element.remove(this.parentNode);
				}		
		var show_link_container = Builder.node('P',{className:'center'},[show_link]);
		var card_front = Builder.node('DIV',{className:'flashcard_box bottom20px center'},
																	[this.content[this.current_index].name,show_link_container]);
		var card_back = Builder.node('DIV',{className:'displaynone'});
		card_back.innerHTML = this.the_content;
		this.title_node.innerHTML = 'Flashcard Mode';
		this.container_node.className = 'flashcard';
		
		this.content_node.style.backgroundColor = '#999999';
		this.content_node.innerHTML = '';
		this.content_node.appendChild(card_front);
		this.content_node.appendChild(card_back);
	},

	// display done button if we have displayed all facts
	display_done_button:function() {
		var unseen = 0;
		for (var i=0;i<this.content.length;i++)
		{
			if (this.content[i].answered_correctly == false)
			{
				if (unseen > 0) return;
				else unseen++;
			}
		}
		this.answer_node.appendChild(this.create_smart_button('Done','<u>D</u>one'));
		this.added_done_button  = true;
	},

	// render as true
	// works for question content type
	// overwrite parent class - modify for stepthrough mode
	render_as_true:function()	{	
		var fact = this.content[this.current_index]["fact"];							// fact
		    fact = fact[0] + fact[1] + fact[2];														// display fact
		this.the_content 			= fact;																			// content
		this.the_title				= this.settings.fact_name ? this.settings.fact_name : 'Fact';																		// title
		this.the_style				= 'fact';																		// style
	},
	
	// render as reading
	// works for reading content type	
	// overwrite parent class - modify for stepthrough (add previous button)
	render_as_reading:function() {	
		var text = this.content[this.current_index]["text"];							// text
		this.the_content 			= text;																			// text
		this.the_title				= this.content[this.current_index]["name"]; // reading title
		this.the_style				= 'reading';
	}	

//----------------------------------------------------------------------------------
// end Quiz.StepThroughMode
});
//----------------------------------------------------------------------------------

//----------------------------------------------------------------------------------
// tutor mode
Quiz.TutorMode = Class.create();
Quiz.TutorMode.prototype = Object.extend(new Quiz.Base(),{
	
	mode:'tutor',
	mastered_content:[],
	unmastered_content:[],
	facts_reviewed:1,
	
	start:function() {	
	  this.mastered_content = [];
	  this.unmastered_content = [];		
		this.facts_reviewed = 1;
		this.status_node.innerHTML = '<span id="questions_remaining">'+ (this.current_index+1) + ' of ' + this.content.length+'</span> | Points Earned: <span id="points_earned">0</span> | Time Remaining: <span id="time_remaining"></span> | <span id="mastered_unmastered">&nbsp;</span>';
		// copy content into unmastered/mastered content
		for (var i=0;i<this.content.length;i++)
		{
			if (this.content[i].mastery_log.mastered == 1) this.mastered_content[this.mastered_content.length] 			= this.content[i];
			else 																					 this.unmastered_content[this.unmastered_content.length]	= this.content[i];
		}
		
		for (var i=0;i<this.mastered_content.length;i++)
		{
			this.unmastered_content[this.unmastered_content.length] = this.mastered_content[i];
		}

		this.content = this.unmastered_content;
		
		$('mastered_unmastered').innerHTML = this.content[this.current_index].mastery_log.mastered == 1 ? 'mastered' : 'unmastered';
				
		this.timer.setMax(60000);
		this.timer.onTick = function() {
			if ($('time_remaining')) $('time_remaining').innerHTML = this.writeTime(this.maxTime - this.timeElapsed);
		}
		this.timer.onMax = this.display_end_screen.bind(this);
	
		this.display();
	},

	// display next
	next:function()	{	
		if 	(this.current_index+1 >= (this.content.length)) { this.display_end_screen(); return false; }
		else this.current_index = this.current_index+1;
		this.facts_reviewed++;
		$('questions_remaining').innerHTML = this.current_index+1 + ' of ' + this.content.length;
		$('mastered_unmastered').innerHTML = this.content[this.current_index].mastery_log.mastered == 1 ? 'mastered' : 'unmastered';
		$('points_earned').innerHTML 			 = this.points_earned;		
		this.display();
	},

	// process answer
	// if correct/else if incorrect
	process_answer:function (answer) {
	  if ( this.answer_acceptable(answer) ) 																						// if answer is correct
		{
			return this.next();																																		// go to next
		}
		else
		{
			this.wrong_answer = answer;
			this.display('wronganswer');
			$('questions_remaining').innerHTML = this.current_index+1 + ' of ' + this.content.length;
			$('points_earned').innerHTML = this.points_earned;
		}
	},

	// final screen
	display_end_screen:function() {
				this.timer.stop();
		this.save_data();
		this.DOMNodes.clear();
		return false;
		this.splash_stats.innerHTML = '<p class="bold">Tutor Mode Results</p>';
		remove_children(this.container_node);
		this.calculate_quiz_stats();
		var table = document.createElement('TABLE');
		var	tbody = document.createElement('TBODY');
		        var fact_name = this.settings.fact_name ? this.settings.fact_name : 'Fact';
				table.appendChild(tbody);
				tbody.appendChild(create_row('Percent Correct:',this.stats.quiz.percent_correct_taken + '%'));
				tbody.appendChild(create_row('Time:',this.timer.writeTime(this.stats.quiz.time_elapsed)));
				tbody.appendChild(create_row(fact_name + 's Reviewed:',this.facts_reviewed));
		document.body.appendChild(table);
		show_start_screen();
		this.save_data();
	}

//----------------------------------------------------------------------------------
// end Quiz.TutorMode
});
//----------------------------------------------------------------------------------


//----------------------------------------------------------------------------------
// introduction mode
Quiz.IntroductionMode = Class.create();
Quiz.IntroductionMode.prototype = Object.extend(new Quiz.Base(),{

	mode:'introduction',

	steps:['true','truefalse','multiplechoice','fillintheblank'],			 
	current_step:0,
	
	content_sets:[], // initialize content set array
	current_set:0,   // initialize current content set

	// copy content into all_content
	start:function() {
		this.set_size = this.settings.introductionsetsize ? this.settings.introductionsetsize : 3;
		this.all_content = this.content;
		this.status_node.innerHTML = 'Introduction - Points Earned: <span id="points_earned">0</span>';
		this.build_content_sets();
		this.build_outline();		
		this.load_content_set(0);
	},

	build_outline:function() {
		var outline 			= Builder.node('DIV',{id:'outline'});
		var toggle_outline = commonjs.jslink('hide');
		var outlinePlaceholder = this.DOMNodes.outlinePlaceholder();
		var top_menu_container = this.top_menu_container;
		toggle_outline.onclick = function() {
			var show_outline_link = commonjs.jslink('show outline');
			    show_outline_link.onclick = function() {
						new Effect.Appear(outlinePlaceholder);
						this.parentNode.removeChild(this);
					}
			Element.hide(outlinePlaceholder);
			top_menu_container.appendChild(show_outline_link);	
		}
		var outline_title = Builder.node('DIV',{className:'outline_title'},['Outline ',toggle_outline]);
		var done_button   = Builder.node('BUTTON',{},['done']);
		    done_button.onclick = this.load_content_set.bind(this,null,true);
		var outline_done  = Builder.node('DIV',{className:'center'},[done_button]);
				outline_done.style.marginTop = '5px';
		var outline_table_tbody = Builder.node('TBODY');				
		var outline_table = Builder.node('TABLE',{className:'cells_top_valign'},[outline_table_tbody]);

		for (var i = 0; i<this.content_sets.length; i++)
		{
			for (var j = 0; j<this.content_sets[i].length; j++)
			{
				var content = this.content_sets[i][j];
				var row = Builder.node('TR');				
				var img = Builder.node('IMG',{className:'contentlist_image',
																				        src:jsconfig.site.root + 'images/site/content_icon_' + content.type + '.gif'});
			  var thelink = Builder.node('A',{href:'javascript:void(0)',
																						  rel:content.track_back},
																							[content.name]);
				thelink.onclick = this.display_specific_content.bind(this,content.track_back);
				row.appendChild(Builder.node('TD',{},[img]));
				row.appendChild(Builder.node('TD',{},[thelink]));
				outline_table_tbody.appendChild(row);
			}
			if (i < this.content_sets.length - 1) 
			{
				var row = Builder.node('TR',{},[
																				Builder.node('TD',{colspan:2},[Builder.node('HR',{className:'hr1'})])
																				]);
				outline_table_tbody.appendChild(row);
			}
		}
		
		outline.appendChild(outline_table);
		
		outlinePlaceholder.className = 'outline_active';
		outlinePlaceholder.appendChild(outline_title);
		outlinePlaceholder.appendChild(outline);
		outlinePlaceholder.appendChild(outline_done);	
	},

	build_content_sets:function()	{
		var set_num           = 0;            // initialize set index
		var facts_in_set      = 0;            // initialize facts_in_set counter
		var content_sets      = [];           // initialize content set array
		content_sets[set_num] = [];          // initialize first set
		for (var i=0;i<this.all_content.length;i++)
		{
			var type  = this.all_content[i].type;     // content type
			var index = content_sets[set_num].length; // get new index
			
			// if we are doing in between readings and we've reached the next reading
			// or if normal mode and we have reached the max set size
			//  - end set and continue
			if (
					(this.set_size == 'betweenreadings' && type == 'reading' && index != 0)
					|| (this.set_size != 'betweenreadings' && facts_in_set == this.set_size)
				 )
			{
				i--;                                      // decrement counter to include this fact/reading in next set
				set_num++;                                // next set index
				content_sets[set_num] = [];      // initialize next set array
				facts_in_set = 0;                         // initialize "facts in set" counter
				continue;				
			}
			
			// add content to the current set			
			content_sets[set_num][index] = this.all_content[i];
			// save the location of content in all_content array
			content_sets[set_num][index].track_back = i;
			// save the location of content in "content set" array
			content_sets[set_num][index].set_num = set_num;
			// save the location of content in "content set" array
			content_sets[set_num][index].set_index = index;			
			// if this is a fact increment "facts in set" counter for use with max set size	
			if (type != 'reading') facts_in_set++;
		}
		this.content_sets = content_sets;
		content_sets = null;
	},

	display_specific_content:function(index) {
		for (var i = 0; i<this.content_sets.length; i++)
		{
			for (var j = 0; j<this.content_sets[i].length; j++)
			{
				if (this.content_sets[i][j].track_back == index)
				{
					this.content = [this.content_sets[i][j]];
					this.current_step   = 0;
					this.current_index  = 0;					
					this.display(this.steps[0]);
					return false;
				}
			}
		}
	},

	load_content_set:function(set,done) {
		this.current_index = 0;
		if (set != null) 
		{
			this.current_set = set
		}
		else if (
    			    (this.content.length == 1)
		          && (this.content_sets[this.content[0].set_num].length > 1)
		        )
		{
			this.current_set   = this.content[0].set_num;
			this.current_index = (this.content[0].set_index + 2) > (this.content_sets[this.content[0].set_num].length) ? 0 : (this.content[0].set_index + 1);
		}
		else this.current_set++;
		
		if (this.current_set == this.content_sets.length || done)
		{
			for (var i = 0; i<this.content_sets.length; i++)
			{
				for (var j = 0; j<this.content_sets[i].length; j++)
				{
					if (!done && this.content_sets[i][j].answered_correctly == false)
					{
						this.content = this.content_sets[i];
						this.current_step  = 0;
						this.display(this.steps[0]);
						return false;
					}
					this.all_content[this.content_sets[i][j].track_back] = this.content_sets[i][j];
				}
			}
			this.content = this.all_content;
			this.display_end_screen();
		}
		else 
		{
			this.content = this.content_sets[this.current_set];
			this.current_step  = 0;
			this.display(this.steps[0]);
		}		
	},

	save_step_data:function() {
		for (var i=0;i<this.content.length;i++)
		{
			this.content_sets[this.content[i].set_num][this.content[i].set_index] = this.content[i];
		}
	},

	// render as true
	// works for question content type
	// we are calling this again so that we can actually process the answer instead of just going to the next question
	// if a reading - then render as reading
	render_as_true:function()	{	
		if (this.content[this.current_index].type == 'reading') { return this.render_as_reading(); }		
		var fact = this.content[this.current_index].fact;									// fact
		    fact = fact[0] + fact[1] + fact[2];														// display fact
		var answer_input = Builder.node('DIV');									// create answer input
				answer_input.appendChild(this.create_smart_button('Next','<u>N</u>ext'));					// append button
		this.answer = 'Next';

		this.the_answer_input = answer_input;															// answer_input
		this.the_content 			= fact;																			// content
		this.the_title				= this.settings.fact_name ? this.settings.fact_name : 'Fact';																		// title
		this.the_style				= 'fact';																		// style
		this.current_format 	= 'true';																		// current format
	},

	// display next
	next:function() {	
		if (!this.continue_next()) return;
		if 	(this.current_index+1 >= (this.content.length)) this.current_index = 0;
		else this.current_index = this.current_index+1;
		if (this.content[this.current_index].answered_correctly == true) return this.next();
		else 
		{	
			var available_formats = this.content[this.current_index].formats;
			var current_format		= this.steps[this.current_step];
			if (current_format == 'truefalse' && (in_array('multiplechoice',available_formats) && (in_array('fillintheblank',available_formats)) ) )
			{
				this.content[this.current_index].answered_correctly = true;
				return this.next();
			}
			else if (this.current_step == 0 || in_array(current_format,available_formats)) this.display(current_format);
			else 
			{
				this.content[this.current_index].answered_correctly = true;
				this.next();
			}
		}
		if ($('points_earned')) $('points_earned').innerHTML = this.points_earned;
	},
	
	// done with step?
	continue_next:function() {
		for (var i=0;i<this.content.length;i++)
		{
			if (this.content[i].answered_correctly == false) return true;
		}
		this.current_step++;
		if (this.current_step >= this.steps.length) { this.save_step_data(); this.load_content_set(); return false; }
		else { for (var i=0;i<this.content.length;i++)	{ this.content[i].answered_correctly = false; } return true; }
	},
	
	// process answer
	// if correct/else if incorrect
	process_answer:function (answer) {
		if ( this.answer_acceptable(answer) ) 																						// if answer is correct
		{
			this.next();																																		// go to next
		}
		else
		{			
			this.wrong_answer = answer;
			this.display('wronganswer');
		}
		if($('points_earned')) $('points_earned').innerHTML = this.points_earned;
	},

	// final screen
	display_end_screen:function()	{
		this.timer.stop();
		this.save_data();
		this.DOMNodes.clear();
		return false;		this.splash_stats.innerHTML = '<p class="bold">Introduction Mode Results</p>';
		remove_children(this.container_node);
		this.calculate_quiz_stats();
		var table = document.createElement('TABLE');
		var	tbody = document.createElement('TBODY');
                var fact_name = this.settings.fact_name ? this.settings.fact_name : 'Fact';
                table.appendChild(tbody);
				tbody.appendChild(create_row('Percent Correct:',this.stats.quiz.percent_correct_taken + '%'));
				tbody.appendChild(create_row('Time:',this.timer.writeTime(this.stats.quiz.time_elapsed)));
				tbody.appendChild(create_row(fact_name+'s Reviewed:',this.content.length));
				tbody.appendChild(create_row('No. Questions:',this.stats.quiz.correct_answers + ' of ' + this.stats.quiz.answers)); 

		document.body.appendChild(table);

		show_start_screen();
		this.save_data();
	}

//----------------------------------------------------------------------------------
// end Quiz.IntroductionMode
});
//----------------------------------------------------------------------------------


	//----------------------------------------------------------------------------------
	// print test
	//----------------------------------------------------------------------------------

	var print_test_class = function() {
		this.to_print = document.createElement('DIV');
		this.print_it = function(window_ref) { window_ref.document.getElementById('print_area').appendChild(this.to_print); }
	}
	
	var print_test = new print_test_class();

	//----------------------------------------------------------------------------------
	// create row
	//----------------------------------------------------------------------------------
	function create_row(column1,column2)
	{
		var row = document.createElement('TR');
		var c1  = document.createElement('TD');
				c1.className = 'align_right';
				c1.innerHTML = column1;
		var c2  = document.createElement('TD');
				c2.className = 'align_left';
				c2.innerHTML = column2;				
		row.appendChild(c1);
		row.appendChild(c2);
		return row;
	}

	//----------------------------------------------------------------------------------
	// mode hotkeys
	//----------------------------------------------------------------------------------
	function mode_hotkeys(evt)
	{
 		var e = new xEvent(evt);
		if (e.target.type == 'text') return false;
		// key that triggered event
		var key = e.keyCode;
		switch(key)
		{
			case 73: if (QuizSettings.info.settings.introduction == 'on') {loadContent('introduction');} break; // i
			case 85: if (QuizSettings.info.settings.tutor == 'on') {loadContent('tutor');} break; // u
			case 84: if (QuizSettings.info.settings.test == 'on') {loadContent('test');} break; // t
		}
	}
			
	//----------------------------------------------------------------------------------
	// Elements
	//----------------------------------------------------------------------------------
	function hide_loading()	{ 
    alert('reference to hide_loading()');
	}
	function show_start_screen() {
    alert('reference to show_start_screen()');
	}
	function hide_start_screen() {
    alert('reference to hide_start_screen()');
	}	