var oncology101 = function () {
	
	function oncologyNav() {
		var oncNav = document.getElementById('oncology-nav');
		var subNavs = getByClass(oncNav, 'subnav');

		function getByClass(el, c) {
			els = el.getElementsByTagName('*');
			arr = [];
			for (var i=0; i<els.length; i++) {
				if (els[i].className === c) {
					arr.push(els[i]);
				}
			}
			return arr;
		}

		for (var i=0; i<subNavs.length; i++) {
			var els = subNavs[i].getElementsByTagName('a');
			for (var k=0; k<els.length; k++) {
				els[k].onclick = function() {
					actives = getByClass(oncNav, 'active');
					for (var i=0; i<actives.length; i++) {
						actives[i].className = '';
					}
					this.className = 'active';
				};
			}
		}
	}

	function quiz() {
		// Config
		var totalNumQuestions = 8;
		var letters = ['a', 'b', 'c', 'd']; // Available answer letters
		var correctResponse = 'You are correct!';
		var incorrectResponse = 'Sorry, that is not correct.';
		
		var quizDiv = document.getElementById('quiz');
		var quizForm = quizDiv.getElementsByTagName('form')[0];
		
		var currQ = 1;
		var totalNumCorrect = 0;
		
		var questionData = {
			q1: {
				question: 'What is the estimated number of people living with cancer worldwide?',
				a: '24.6 million',
				b: '1.6 million',
				c: '200.6 million',
				d: '44.6 million',
				answer: 'a'
			},
			q2: {
				question: 'All of the following have been associated with increased risk of developing cancer except:',
				a: 'Physically active lifestyle',
				b: 'Tobacco use',
				c: 'Infections',
				d: 'Alcohol consumption',
				answer: 'a'
			},
			q3: {
				question: 'In cancer treatment, chemotherapy may be used as:',
				a: 'Neoadjuvant therapy',
				b: 'Adjuvant therapy',
				c: 'A component of combination therapy',
				d: 'All of the above ',
				answer: 'd'
			},
			q4: {
				question: 'The "TNM" in the TNM Staging Guide refers to:',
				a: 'Tumor, Node, Metastasis',
				b: 'Type, Nature, Method',
				c: 'Tumor, Needle, Marker',
				d: 'None of the above',
				answer: 'a'
			},
			q5: {
				question: 'The Kaplan-Meier curve is helpful for patients because it:',
				a: 'Provides them with a better understanding of the drugs they will take',
				b: 'Explains how cancer spreads',
				c: 'Helps manage their expectations for survival based on other patients\' experience',
				d: 'None of the above',
				answer: 'c'
			},
			q6: {
				question: 'Patients may benefit from clinical trials as a result of:',
				a: 'Having access to new treatment approaches that are often not otherwise available',
				b: 'Having access to a new treatment approach that may be more efficacious than the standard of care',
				c: 'Having access to regular medical attention from a comprehensive research team of dedicated healthcare professionals',
				d: 'All of the above',
				answer: 'd'
			},
			q7: {
				question: 'A superiority trial is designed to:',
				a: 'Demonstrate that 2 therapies or regimens are noninferior to each other',
				b: 'Demonstrate that there is a statistical difference between 2 therapies or regimens',
				c: 'Demonstrate that 2 therapies or regimens are equivalent to each other',
				d: 'None of the above ',
				answer: 'b'
			},
			q8: {
				question: 'Compassionate Use Trials are:',
				a: 'Open to anyone with cancer',
				b: 'An option for patients who have participated in at least 1 clinical trial already',
				c: 'An option for patients not eligible for a clinical trial who have a life-threatening illness',
				d: 'All of the above',
				answer: 'c'
			}
		};
		
		// Show quiz for the first time
		display({
			listFunc: makeQuestionList,
			buttonType: 'submit'
			//intro: true
		});

		quizForm.onsubmit = function() {
			validateAnswer();
            removeIntro();
			return false;
		};
		
        function removeIntro() {
            var intro = document.getElementById('quiz-intro');
            if (intro) {
                intro.parentNode.removeChild(intro);
            }
        }

		function display(obj) {
			
			var params = {
				//intro: obj.intro || false,					// Should the intro paragraph be displayed?
				listFunc: obj.listFunc || makeAnswerList,	// Function that builds the list of possible answers
				buttonType: obj.buttonType || 'next',		// Submit question, next question, or what's my IQ
				userAnswer: obj.userAnswer || '',			// The answer given by the user
				correct: obj.correct || false				// Whether the answer is correct or incorrect
			};
			
			// if (params.intro === false) {
			// 	quizDiv.getElementsByTagName('p')[0].style.display = 'none';
			// }
			
			// Create elements
			var quizContainer = document.createElement('div');
			var quizHeader = document.createElement('h3');
			var quizQuestion = document.createElement('p');
			var quizList = document.createElement('ul');
			var quizSubmitCont = document.createElement('p');
			var quizExplanation = document.createElement('p');
			var quizAnswer = document.createElement('h3');
			var quizFinalScore = document.createElement('h3');
			var quizLevel = document.createElement('h3');
			
			
			// Refresh display
			if (document.getElementById('quiz-container')) {
				qContainer = document.getElementById('quiz-container');
				qContainer.parentNode.removeChild(qContainer);
			}

			quizContainer.id = 'quiz-container';
			quizForm.appendChild(quizContainer);
			
			
			// Set up header and question
			quizHeader.innerHTML = 'Question ' + currQ + ' of ' + totalNumQuestions;
			quizQuestion.innerHTML = questionData['q' + currQ].question;
			
			quizContainer.appendChild(quizHeader);
			quizContainer.appendChild(quizQuestion);
			
			
			// Build question list
			for (var i=0; i<letters.length; i++) {
				quizList.appendChild(params.listFunc(letters[i], params.userAnswer));
			}
			
			quizContainer.appendChild(quizList);
			
			
			// Add answer Notification and explanation
			if (params.userAnswer) {
				quizAnswer.className = 'response';
				quizAnswer.innerHTML = (params.correct === true) ? correctResponse : incorrectResponse;
				quizContainer.className = (params.correct === true) ? 'correct' : 'incorrect';
				
				if (questionData['q' + currQ].explanation) {
					quizExplanation.innerHTML = questionData['q' + currQ].explanation;
					quizContainer.appendChild(quizAnswer);
					quizContainer.appendChild(quizExplanation);
				} else {
					quizAnswer.className += ' no-explanation';
					quizContainer.appendChild(quizAnswer);
				}
				
			}

			
			// Add submit button or recap quiz
			if (currQ < totalNumQuestions || !params.userAnswer) {
				quizSubmitCont.appendChild(makeSubmitBtn(params.buttonType));
				quizContainer.appendChild(quizSubmitCont);
			} else {
				quizFinalScore.innerHTML = 'Your final score: ' + totalNumCorrect + ' out of ' + totalNumQuestions + ' correct';
				quizFinalScore.className = 'final-score';
				quizContainer.appendChild(quizFinalScore);
			}

            // Open links in a new window so the quiz is not interrupted
            var links = quizContainer.getElementsByTagName('a');
            if (links) {
                for (var i=0; i<links.length; i++) {
					if (links[i].className.indexOf('info') > -1) {
 	                    links[i].onclick = function() {
	                         // window.open(this.href);
							 quizPopup.open(this.id);
	                         return false;
	                     };
					}
                }
            }
			
		}
		
		function makeQuestionList(letter) {
			var quizItem = document.createElement('li');
			quizItem.innerHTML = '<input type="radio" name="q' + currQ + '" value="' + letter + '" id="q' + currQ + '_' + letter + '"><label for="q' + currQ +
			'_' + letter + '">' + questionData['q' + currQ][letter] + '</label>';
			return quizItem;
		}
		
		function makeAnswerList(letter, answer) {
			var quizItem = document.createElement('li');
			quizItem.innerHTML = questionData['q' + currQ][letter];
			if (questionData['q' + currQ].answer === letter) {
				quizItem.className = 'answer';
			}
			else if (answer === letter) {
				quizItem.className = 'given-answer';
			}
			return quizItem;
		}
		
		function makeSubmitBtn(type) {
			if (type === 'submit' || type === 'score') {
				el = document.createElement('input');
				el.type = 'image';
				el.id = 'submit';
				if (type === 'submit') {
					el.alt = 'AM I RIGHT?';
					el.src = 'images/quiz_submit.gif';
				} else if (type === 'score') {
					el.alt = 'What\'s my cancer IQ?';
					el.src = 'images/quiz_iq.gif';
				}
			} else if (type === 'next') {
				el = document.createElement('a');
				el.innerHTML = 'Next Question';
				el.href = '#';
				el.className = 'next-q';
				el.onclick = function() {
					currQ += 1;
					if (currQ === totalNumQuestions) {
						var buttonType = 'score';
					}
					
					display({
						listFunc: makeQuestionList,
						buttonType: buttonType || 'submit'
					});
					
					return false;
				};
			}
			return el;
		}
		
		function displayError() {
            if (!document.getElementById('quiz-error')) {
                var submitBtn = document.getElementById('submit');
                var error = document.createElement('p');
                var errorText = document.createTextNode('Please select an answer.');
                error.appendChild(errorText);
                error.className = 'error';
                error.id='quiz-error';
                submitBtn.parentNode.insertBefore(error, submitBtn);
            }
		}

		function validateAnswer() {
			var radios = quizForm['q' + currQ];

			// Get the answer
			for (var i=0; i<radios.length; i++) {
				if (radios[i].checked) {
					var userAnswer = radios[i].value;
				}
			}
			
			if (userAnswer && userAnswer === questionData['q' + currQ].answer) {
				totalNumCorrect += 1;
				display({
					userAnswer: userAnswer,
					correct: true
				});
			} else if (userAnswer) {
				display({
					userAnswer: userAnswer,
					correct: false
				});
			} else {
				displayError();
			}

		}
	}

	var init = function () {
		if (document.getElementById('quiz')) {
			quiz();
		}
	
		if (document.getElementById('oncology-nav')) {
			oncologyNav();
		}
	};
	
	return { init: init };
	
}();

DKI.addEventSimple(window, 'load', oncology101.init);


var quizPopup = function() {
	var popupID =          'quiz-popup'; // Required - ID for the popup div
	var popupWrapID =      'quiz-popup-wrap'; // ID for the popup wrap div
	var closeClass =       'close'; // Identifies buttons that should close the popup
	
	var addEvent = function(obj,evt,fn) {
		if (obj.addEventListener) {
			obj.addEventListener(evt,fn,false);
		} else if (obj.attachEvent) {
			obj.attachEvent('on'+evt,fn);
		}
	
	};
	
	var position = function() {
		if (document.getElementById(popupID)) {
			var popupEl = document.getElementById(popupID);
			var wHeight = document.documentElement.clientHeight;
			var wWidth = document.documentElement.clientWidth;
			var pHeight = popupEl.clientHeight;
			var pWidth = popupEl.clientWidth;
			var scrollDiff = document.documentElement.scrollTop;

			popupEl.style.left = (wWidth - pWidth) / 2 + 'px';

			if (wHeight < pHeight) {
				popupEl.style.top = 20 + px;
			} else {
				popupEl.style.top = (wHeight - pHeight) / 2 - 50 + scrollDiff + 'px';
			}
		}
	};
	
	var open = function(info) {
		var popupWrapEl = document.getElementById(popupWrapID)
		var popupEl = document.getElementById(popupID);
		var infoBlock = document.getElementById(info + '-info');
		popupWrapEl.style.display = 'block';
		popupEl.style.display = 'block';
		infoBlock.style.display = 'block';
		position();
	};
	
	var close = function() {
		var popupWrapEl = document.getElementById(popupWrapID);
		var popupEl = document.getElementById(popupID);
		var divs = popupEl.getElementsByTagName('div');
		popupWrapEl.style.display = 'none';
		popupEl.style.display = 'none';
		for (var i=0; i<divs.length; i++) {
			if (divs[i].className.indexOf('info-block') > -1) {
				divs[i].style.display = 'none';
			}
		}
		
	};
	
	var addPopupHandlers = function(anchors) {
		for (var i=0; i<anchors.length; i++) {
			if (anchors[i].className === closeClass) {
				anchors[i].onclick = function() {close(); return false;};
			}
		}
	};
	
	var init = function() {
		addEvent(window, 'resize', position);
		
		addEvent(window, 'load', function() { 
			
			// Attach event handlers to popup
			if (document.getElementById(popupID)) {
				addPopupHandlers(document.getElementById(popupID).getElementsByTagName('a'));
			}
		});
	};
	
	// Public methods
	return { 
		open: open,
		close: close,
		init: init
	};
	
}();

//quizPopup.init();

