/**
* @file	hawkhealth.js
* Defines functions for use with hawkhealth's site
*/

/*
* DEVELOPERS' NOTE ON SURVEY HANDLERS!!
* jQuery is included with Drupal 5.x (on which HawkHealth is built)
* However, much of this JavaScript code still needs CLEANING up and/or
*   conversion to jQuery calls
* Moreover, it would be worth going through and rewriting the form markup to be
*   more templateable for modular JavaScript
* I.e. Rather than defining separate updateScore and formReset functions for
*   each survey, as we do now, make the forms and data handling driven through
*   a few well-written functions and forms.
* That, or each survey can have its own .js file with its own functions
*   How do we (elegantly) detect/handle Drupal-formed HTTP requests at the
*     SSI level?
*/


/*===========================================================
* SURVEY FORM HANDLERS
* Mostly legacy code
* Two primary functions for all surveys: updateScore() and formReset()
* We re-define slightly different versions of both for each survey
* See Developers' Note above for ideas for changes
* ===========================================================*/
/*
* Survey: "What is my diet like?"
* function name prefix: mydiet_
* (original file: survey1.html)
*/
	function mydiet_updateScore()
	{
		var score = 0;
		var i = 0;
		
		for (i = 1; i <= 6; i++) {
			var question = eval("document.form1.question" + i);
			for (var j = 0; j < question.length; j++){
				if (question[j].checked) score += parseInt(question[j].value);
			}
		}
		
		document.getElementById("yourScore").innerHTML = "<b><font color=\"red\">" + score + "</font></b>";
	}
	
	function mydiet_formReset()
	{
		document.getElementById("yourScore").innerHTML = "<b>0</b>";
	}

/*
* Survey: "How Do I Feel About My Body?"
* function name prefix: feelaboutmybody_
* (original file: survey3.html)
*/
	function feelaboutmybody_updateScore()
	{
		var score = 0;
		var i = 0;
		
		for (i = 1; i <= 10; i++) {
			var question = eval("document.form1.question" + i);
			for (var j = 0; j < question.length; j++){
				if (question[j].checked) score += parseInt(question[j].value);
			}
		}
		
		document.getElementById("yourScore").innerHTML = "<b><font color=\"red\">" + score + "</font></b>";
	}
	
	function feelaboutmybody_formReset()
	{
		document.getElementById("yourScore").innerHTML = "<b>0</b>";
	}

/*
* Survey: "Do you have an STD/STI?" (combined female and male version)
* function name prefix: stiassessment_
* (original file: survey4.html and survey5.html)
* Based on feedback from client, we have heavily modified the logic
*/
	/**
	* @param sex	'male' or 'female'; different assessments
	*/
	function stiassessment_updateScore(sex)
	{
		// Initialize infection flags
		var has_infection = {};
		has_infection['HIV']                     = false;
		has_infection['Chlamydia']               = false;
		has_infection['Crabs/Pubic Lice']        = false;
		has_infection['HPV/Genital Warts']       = false;
		has_infection['Gonorrhea']               = false;
		has_infection['Hepatitis B']             = false;
		has_infection['Herpes']                  = false;
		has_infection['Scabies']                 = false;
		has_infection['Syphillis']               = false;
		has_infection['Trichomoniasis']          = false;
		has_infection['Yeast Infection']         = false;
		has_infection['Vaginosis']               = false;  // female only
		has_infection['Urinary Tract Infection'] = false;
		
		// Map infections to links to specific files
		var infection_directory = './uploads/files/sti-fact-sheets/';  // needs trailing slash!
		var infection_files = {};
		infection_files['HIV']                     = 'HIVtransmission.pdf';
		infection_files['Chlamydia']               = 'chlamydia.pdf';
		infection_files['Crabs/Pubic Lice']        = '2004_PDF_Pubic_Lice.pdf';
		infection_files['HPV/Genital Warts']       = 'hpv.pdf';
		infection_files['Gonorrhea']               = 'gonorrhea.pdf';
		infection_files['Hepatitis B']             = 'HepatitisB.pdf';
		infection_files['Herpes']                  = 'herpes.pdf';
		infection_files['Scabies']                 = 'scabies.pdf';
		infection_files['Syphillis']               = 'syphilis.pdf';
		infection_files['Trichomoniasis']          = 'trich.pdf';
		infection_files['Yeast Infection']         = '';
		infection_files['Vaginosis']               = 'vaginosis.pdf';  // female only
		infection_files['Urinary Tract Infection'] = '';
		
		// Map question numbers to (possible) infections -- different for the sexes
		/*
		Discussion: Why key on question number, then infection?
		1. Since one question relates to many infections, we loop on question number
		2. If update question numbers, update in one place (vs adding infection, which would be inconvenient)
			It is not likely we will add another infection
		*/
		var question_map = [];
		if (sex == 'female') {
			question_map[1] = {};
			question_map[1]['Chlamydia']               = true;
			question_map[1]['Hepatitis B']             = true;
			question_map[1]['Trichomoniasis']          = true;
			question_map[1]['Urinary Tract Infection'] = true;
			
			question_map[2] = {};
			question_map[2]['Herpes']                  = true;
			question_map[2]['Syphillis']               = true;
			
			question_map[3] = {};
			question_map[3]['Urinary Tract Infection'] = true;
			
			question_map[4] = {};
			question_map[4]['Chlamydia']               = true;
			question_map[4]['Gonorrhea']               = true;
			question_map[4]['Herpes']                  = true;
			question_map[4]['Urinary Tract Infection'] = true;
			
			question_map[5] = {};
			question_map[5]['HIV']                     = true;
			question_map[5]['Herpes']                  = true;
			question_map[5]['Urinary Tract Infection'] = true;
			
			question_map[6] = {};
			question_map[6]['Urinary Tract Infection'] = true;
			
			question_map[7] = {};
			question_map[7]['Chlamydia']               = true;
			question_map[7]['Crabs/Pubic Lice']        = true;
			question_map[7]['Gonorrhea']               = true;
			question_map[7]['Herpes']                  = true;
			question_map[7]['Yeast Infection']         = true;
			question_map[7]['Vaginosis']               = true;
			
			question_map[8] = {};
			question_map[8]['Crabs/Pubic Lice']        = true;
			question_map[8]['Scabies']                 = true;
			
			question_map[9] = {};
			question_map[9]['Hepatitis B']             = true;
			
			question_map[10] = {};
			question_map[10]['Hepatitis B']             = true;
			
			question_map[11] = {};
			question_map[11]['Hepatitis B']             = true;
			
			question_map[12] = {};
			question_map[12]['Chlamydia']               = true;
			question_map[12]['Trichomoniasis']          = true;
			
			question_map[13] = {};
			question_map[13]['HIV']                     = true;
			question_map[13]['Syphillis']               = true;
			
			question_map[14] = {};
			question_map[14]['Hepatitis B']             = true;
			question_map[14]['Scabies']                 = true;
			question_map[14]['Syphillis']               = true;
			
			question_map[15] = {};
			question_map[15]['HIV']                     = true;
			question_map[15]['Syphillis']               = true;
			
			question_map[16] = {};
			question_map[16]['HIV']                     = true;
			question_map[16]['Hepatitis B']             = true;
			
			question_map[17] = {};
			question_map[17]['Chlamydia']               = true;
			question_map[17]['Gonorrhea']               = true;
			question_map[17]['Trichomoniasis']          = true;
			question_map[17]['Yeast Infection']         = true;
			question_map[17]['Vaginosis']               = true;
			
			question_map[18] = {};
			question_map[18]['Crabs/Pubic Lice']        = true;
			
			question_map[19] = {};
			question_map[19]['HPV/Genital Warts']       = true;
		}
		// …else, default to male
		else {
			question_map[1] = {};
			question_map[1]['Chlamydia']               = true;
			question_map[1]['Hepatitis B']             = true;
			question_map[1]['Trichomoniasis']          = true;
			question_map[1]['Urinary Tract Infection'] = true;
			
			question_map[2] = {};
			question_map[2]['Herpes']                  = true;
			question_map[2]['Syphillis']               = true;
			
			question_map[3] = {};
			question_map[3]['Urinary Tract Infection'] = true;
			
			question_map[4] = {};
			question_map[4]['Chlamydia']               = true;
			question_map[4]['Gonorrhea']               = true;
			question_map[4]['Herpes']                  = true;
			question_map[4]['Urinary Tract Infection'] = true;
			
			question_map[5] = {};
			question_map[5]['HIV']                     = true;
			question_map[5]['Herpes']                  = true;
			question_map[5]['Urinary Tract Infection'] = true;
			
			question_map[6] = {};
			question_map[6]['Urinary Tract Infection'] = true;
			
			question_map[7] = {};
			question_map[7]['Chlamydia']               = true;
			question_map[7]['Crabs/Pubic Lice']        = true;
			question_map[7]['Gonorrhea']               = true;
			question_map[7]['Herpes']                  = true;
			question_map[7]['Yeast Infection']         = true;
			
			question_map[8] = {};
			question_map[8]['Crabs/Pubic Lice']        = true;
			question_map[8]['Scabies']                 = true;
			
			question_map[9] = {};
			question_map[9]['Hepatitis B']             = true;
			
			question_map[10] = {};
			question_map[10]['Hepatitis B']             = true;
			
			question_map[11] = {};
			question_map[11]['Hepatitis B']             = true;
			
			question_map[12] = {};
			question_map[12]['Chlamydia']               = true;
			question_map[12]['Trichomoniasis']          = true;
			
			question_map[13] = {};
			question_map[13]['Chlamydia']               = true;
			question_map[13]['Gonorrhea']               = true;
			
			question_map[14] = {};
			question_map[14]['HIV']                     = true;
			question_map[14]['Syphillis']               = true;
			
			question_map[15] = {};
			question_map[15]['Hepatitis B']             = true;
			question_map[15]['Scabies']                 = true;
			question_map[15]['Syphillis']               = true;
			
			question_map[16] = {};
			question_map[16]['HIV']                     = true;
			question_map[16]['Syphillis']               = true;
			
			question_map[17] = {};
			question_map[17]['HIV']                     = true;
			question_map[17]['Hepatitis B']             = true;
			
			question_map[18] = {};
			question_map[18]['Chlamydia']               = true;
			question_map[18]['Gonorrhea']               = true;
			question_map[18]['Trichomoniasis']          = true;
			
			question_map[19] = {};
			question_map[19]['Crabs/Pubic Lice']        = true;
			
			question_map[20] = {};
			question_map[20]['HPV/Genital Warts']       = true;
		}
		
		
		// Initialize list of potential infections based on answers to questions
		var infection_list = '';
		
		// Loop over each question and flag the corresponding infection (where appropriate)
		for (var question_number in question_map) {
			var responses = eval('document.form1.question' + question_number);
			
			// Unfortunately in DOM, only way to get radio input values is to determine which one is checked by looping through all of them
			for (var response_index = 0; response_index < responses.length; response_index++) {
				if (responses[response_index].checked) {
					// If the checked response is yes, then-
					if (responses[response_index].value == 1) {
						// …flag each infection that corresponds to the current question
						for (var infection in question_map[question_number]) {
							// …only if it's not already flagged
							if (has_infection[infection] != true) {
								has_infection[infection] = true;
								// Make a non-404 dud link for files we don't have (signified by an empty file string -- see infection_files definition)
								// Create link markup only for those infections that have an associated file
								infection_list += '<br />';
								if (infection_files[infection].length > 0) {
									infection_list += '<a href="' +
										infection_directory + infection_files[infection] +
										'">' + infection + '</a>';
								}
								else {
									infection_list += infection;
								}
							}
						}
					}
					// As soon as we've found a checked one, continue on to next question
					break;
				}
			}
		}
		
		// If no infections were flagged, set default message
		if (infection_list == '') {
			infection_list = 'No symptoms';
		}
		
		// Update the diagnosis field
		document.getElementById('yourScore').innerHTML = '<strong>' + infection_list + '</strong>';
		
		// Jump down to results
		window.location.href = '#results';
	}

	function stiassessment_formReset()
	{
		// Reset the diagnosis field
		document.getElementById('yourScore').innerHTML = 'No symptoms';
	}

/*
* Survey: "HIV Risk Assessment"
* function name prefix: hivrisk_
* (original file: survey6.html)
* Based on feedback from client, we have heavily modified the logic
*/
	function hivrisk_updateScore()
	{
		// Init: flag denoting potential exposure to HIV
		var possibly_exposed = false;
		
		var NUMBER_OF_QUESTIONS = 11  // number of relevant questions to generate the HIV exposure message (warning_message)
		// Note that there is one more question that does not affect the outcome of the warning message
		for (var question_number = 1; question_number <= NUMBER_OF_QUESTIONS; question_number++) {
			var responses = eval('document.form1.question' + question_number);
			
			// Unfortunately in DOM, only way to get radio input values is to determine which one is checked by looping through all of them
			for (var response_index = 0; response_index < responses.length; response_index++) {
				if (responses[response_index].checked) {
					// If the checked response is yes, or unsure, (both positive values) then set the exposure flag
					if (responses[response_index].value > 0) {
						possibly_exposed = true;
					}
					// As soon as we've found a checked one, continue on to next question
					break;
				}
				
				// Actually, once we've concluded that the user has potentially been exposed to HIV, we have all we need to generate our results
				if (possibly_exposed) {
					break;
				}
			}
		}
		
		// Generate a warning message based on the user's responses
		if (possibly_exposed) {
			var warning_message = 'Judging by your answers you may have been exposed to HIV.';
		}
		else {
			var warning_message = 'Judging by your answers you probably have not been exposed to HIV; however, the fact that you decided to take this assessment suggests that may have some concerns about the matter.';
		}
		// Append additional warning messages
		warning_message += '<br /><br />You should consult your doctor and make an appointment to get tested. If you are afraid to get tested, just keep in mind that HIV can kill you a lot quicker if it goes untreated. There are over 200,000 Americans who have HIV and don&acute;t even know it. Getting the test does not mean that you have HIV, it just means that you want to stay healthy and get any potential problem treated. Most people are afraid to get tested just because of the possibility of hearing the words &ldquo;You tested positive.&rdquo; Ignorance is not bliss. With HIV, ignorance can be death. Don&acute;t become a statistic, get tested.</p>';
		
		// And display it
		document.getElementById('yourScore').innerHTML = "<strong>" + warning_message + "</strong>";
		
		// Jump down to results
		window.location.href = '#results';
	}
	
	function hivrisk_formReset()
	{
		document.getElementById('yourScore').innerHTML = '';
	}
	
	/**
	* Toggles display of the description for the given question
	* Ideally, this event handler would be registered using jQuery's ready(fn) callback registar
	* However, we don't want to register this function all the time, since this is a badly shared .js library
	*/
	function hivrisk_toggle_question_description(question_number)
	{
		var element_selector = '#question' + question_number + '_description';
		if ($(element_selector)) {
			$(element_selector).slideToggle();
		}
	}

/*
* Survey: "Motives for Physical Activities Measure"
* function name prefix: pamotives_
* (original file: myfitness_survey.htm)
*/
	function pamotives_updateScore()
	{
		// Initialize scores
		scores = {};
		scores['interest-enjoyment'] = 0;
		scores['competence']         = 0;
		scores['appearance']         = 0;
		scores['fitness']            = 0;
		scores['social']             = 0;
		
		// Initialize counters (for tracking aggregated values)
		var counters = {};
		counters['interest-enjoyment'] = 0;
		counters['competence']         = 0;
		counters['appearance']         = 0;
		counters['fitness']            = 0;
		counters['social']             = 0;
		
		// Map question numbers to categories
		var question_map = [];
		
		question_map[2]  = 'interest-enjoyment';
		question_map[7]  = 'interest-enjoyment';
		question_map[11] = 'interest-enjoyment';
		question_map[18] = 'interest-enjoyment';
		question_map[22] = 'interest-enjoyment';
		question_map[26] = 'interest-enjoyment';
		question_map[29] = 'interest-enjoyment';
		
		question_map[3]  = 'competence';
		question_map[4]  = 'competence';
		question_map[8]  = 'competence';
		question_map[9]  = 'competence';
		question_map[12] = 'competence';
		question_map[14] = 'competence';
		question_map[25] = 'competence';
		
		question_map[5]  = 'appearance';
		question_map[10] = 'appearance';
		question_map[17] = 'appearance';
		question_map[20] = 'appearance';
		question_map[24] = 'appearance';
		question_map[27] = 'appearance';
		
		question_map[1]  = 'fitness';
		question_map[13] = 'fitness';
		question_map[16] = 'fitness';
		question_map[19] = 'fitness';
		question_map[23] = 'fitness';
		
		question_map[6]  = 'social';
		question_map[15] = 'social';
		question_map[21] = 'social';
		question_map[28] = 'social';
		question_map[30] = 'social';
		
		// Loop over questions aggregate scores for each category
		for (var question_number in question_map) {
			// Responses will refer to a set of radio buttons (possible responses) for a particular question
			var responses = eval('document.form1.question' + question_number);
			
			// Unfortunately in DOM, only way to get radio input values is to determine which one is checked by looping through all of them
			for (response_index = 0; response_index < responses.length; response_index++) {
			//for (var response_index in responses) {
				if (responses[response_index].checked) {
					scores[question_map[question_number]] += parseInt(responses[response_index].value);
					counters[question_map[question_number]]++;
					// As soon as we've found a checked one, continue on to next question
					break;
				}
			}
		}
		
		// Update Score Fields
		for (category in scores) {
			// Calculate (statistical) mean score -- try not to divide by zero
			scores[category] =
				(counters[category] != 0 ? scores[category] / counters[category] : 0);
			
			// Update innerHTML of this category's score
			if ($('#' + category + '-score')) {
				// innerHTML'd!!
				$('#' + category + '-score').attr('innerHTML', '<strong style="color:red;">' + scores[category] + '</strong>');
			}
		}
	}
	
	/**
	* Resets the scores (should be called only when the form is reset)
	*/
	function pamotives_formReset()
	{
		// Score reset values
		var scores = {};
		scores['interest-enjoyment'] = 0;
		scores['competence']         = 0;
		scores['appearance']         = 0;
		scores['fitness']            = 0;
		scores['social']             = 0;
		
		// Update Score Fields
		for (category in scores) {
			if ($('#' + category + '-score')) {
				// innerHTML'd!!
				$('#' + category + '-score').attr('innerHTML', scores[category]);
			}
		}
	}

/*
* Survey: "How do I see myself?" (combined female and male version)
* function name prefix: selfbodyimage_
* (original file: femalebodysurvey.html and malebodysurvey.html)
*/
	/**
	* @param sex	'male' or 'female'; different assessments
	*/
	function selfbodyimage_updateScore(sex)
	{
		// There's actually nothing to score; we just display a statistical statement
		if (sex == 'female') {
			$('#yourScore').attr('innerHTML', '<strong>College women, on average, think their bodies are somewhat slimmer than image #4 and desire to be thinner than image #3.</strong>');
		}
		// …else, assume male
		else {
			$('#yourScore').attr('innerHTML', '<strong>The average man selects image #4 as the ideal, and the majority of men perceive themselves looking like image #4.</strong>');
		}
	}
	
	function selfbodyimage_formReset()
	{
		$('#yourScore').attr('innerHTML', '<strong>The average man selects image #4 as the ideal, and the majority of men perceive themselves looking like image #4.</strong>');
		document.getElementById("yourScore").innerHTML = '';
	}
