var assessment = new Class({
	options: {
		base_element: $('assessment'),
		sections: [],
		question_sections: [],
		questions: [],
		question_types: ['text','boolean','boolean','select','select']
	},
	initialize: function(options) {
		this.setOptions(options);
		
		this.points = 0;
		this.step = 0;
		this.low_CHD = 0;
		this.responses = new Array();
		this.q_icons = new Array();
		
		//nav text
		this.nav_links = new Array('Continue to Risk Assessment &gt;&gt;','&lt;&lt; Previous','Next &gt;&gt;','Calculate Results &gt;&gt;','&lt;&lt; Take Risk Assessment Again','Print Results &gt;&gt;');
		
		//create nav row
		this.nav = new Element('div', {
			id: 'nav'
		}).inject(this.options.base_element, 'inside');
		
		//create nav text links
		this.nav_holder = new Element('div').inject(this.nav, 'inside');
		var link = new Element('a').inject(this.nav_holder, 'inside').innerHTML = this.nav_links[0];
		
		//create question
		this.options.question_sections.each(function(el, index) {
			el.removeClass('init');
			
			var section_header = el.getFirst();
			var header_src = section_header.getParent().getProperty('id');
			
			if (!header_src.test('introduction')) {
				var question_id = parseInt(header_src.substr(header_src.indexOf('_') + 1));
				
				var new_question = new question({
					id: question_id,
					base_element: section_header,
					type: this.options.question_types[question_id - 1]
				});
				
				this.options.questions.push(new_question);
				
				//hide all questions
				el.set('opacity',0);
				
				//add empty heart icons to nav
				if (!header_src.test('results')) {
					var q_icon = new Element('img', {
						src: 'hra_images/question/blank.gif',
						width: 15,
						height: 14,
						border: 0
					}).inject(this.nav, 'inside');
					this.q_icons.push(q_icon);
				}
			};
		}, this);
		
		if (this.options.questions.length) {
			this.activate();
		}
	},
	activate: function() {
		this.nav_holder.getChildren().each(function(el, index) {
			var test_case = el.innerHTML.toLowerCase();
			if (!test_case.test('again|print')) {
				el.addEvents({
					'click': this.progress.pass(index, this)
				}, this);
			}
			if (test_case.test('again')) {
				el.addEvents({
					'click': function() {
						window.location.reload(false);
					}
				}, this);
			}
			if (test_case.test('print')) {
				el.addEvents({
					'click': function() {
						window.print();
					}
				}, this);
			}
		}, this);
	},
	progress: function(i) {
		switch (this.step) {
			case 0:
				var out_fx = new Fx.Morph(this.options.sections[this.step], {duration: '500'}).start({'opacity': [1,0]});
				var in_fx = new Fx.Morph(this.options.sections[this.step + 1], {duration: '500'}).start({'opacity': [0,1]});
				
				this.step ++;
				
				this.update_links(this.step, 0);
				this.update_icons(this.step - 1, i);
				break;
			
			default:
				switch (i) {
					case 0:
						var out_fx = new Fx.Morph(this.options.sections[this.step], {duration: '500'}).start({'opacity': [1,0]});
						var in_fx = new Fx.Morph(this.options.sections[this.step - 1], {duration: '500'}).start({'opacity': [0,1]});

						this.step --;
						if ((this.step === 0) || (this.step >= 4)) this.update_links(this.step, i);
						this.update_icons(this.step - 1, i);
						break;
						
					case 1:
					default:
						//check answers
						var test = new Array();
						var data = this.options.sections[this.step].toQueryString().split('&');
						data.each(function(value, index) {
							var v = value.split('=');
							
							if (this.step === 1) {
								if (parseInt(v[1]) > 0) test[index] = v[1];
							} else {
								if (v[1]) test[index] = v[1];
							}
							
						}, this);
						if (test.length !== data.length) {
							this.show_warning('<h1>Oops!</h1><p>Please enter a valid response before moving on to the next question.</p><p>Click anywhere to return to question.</p>');
							break;
						} else {
							//assemble results page
							if (this.step === 5) {
								var data = $(this.options.base_element).toQueryString().split('&');
								data.each(function(value, index) {
									var v = value.split('=');
									if (v[1]) this.responses[index] = v[1];
								}, this);

								var ten_year_risk = this.get_ten_year();
								var compared_risk = this.get_compared_risk(ten_year_risk);
								
								this.add_results(ten_year_risk, 'ten_year_risk');
								this.populate_responses();

								if (compared_risk < 2) {
									this.options.sections[this.step + 1].getFirst().getFirst().setProperty('src','hra_images/headers/results-low.gif');
								} else {
									this.add_results(compared_risk, 'compared_risk');
								}
								var results_box = $E('div.summary').getLast();
								var text = results_box.getFirst().innerHTML.replace('XXX', (ten_year_risk + '%'));
								results_box.getFirst().innerHTML = text;
								
								if (compared_risk < 2) {
									compared_risk = '&lt;1';
									var second_box = results_box.getFirst().getNext();
									second_box.innerHTML = '<p>You are not at an increased risk for heart disease compared with a woman your age with low risk factors.</p>';
								} else {
									var text = results_box.innerHTML.replace('XXX', (compared_risk));
									results_box.innerHTML = text;
								}
								
							}
							
							var out_fx = new Fx.Morph(this.options.sections[this.step], {duration: '500'}).start({'opacity': [1,0]});
							var in_fx = new Fx.Morph(this.options.sections[this.step + 1], {duration: '500'}).start({'opacity': [0,1]});

							this.step ++;
							if (this.step > 4) this.update_links(this.step, i);
							this.update_icons(this.step - 1, i);
							break;
						}
				}
				break;
		};
	},
	get_ten_year: function() {
		//first step: age
		var step1 = 0;
		this.responses[0] = parseInt(this.responses[0]);
		
		if (this.responses[0] < 34) {
			this.low_CHD = 0.9;
			step1 -= 9;
		} else if (35 <= this.responses[0] && this.responses[0] <= 39) {
			this.low_CHD = 0.9;
			step1 -= 4;
		} else if (40 <= this.responses[0] && this.responses[0] <= 44) {
			this.low_CHD = 2;
			step1 += 0;
		} else if (45 <= this.responses[0] && this.responses[0] <= 49) {
			this.low_CHD = 3;
			step1 += 3;
		} else if (50 <= this.responses[0] && this.responses[0] <= 54) {
			this.low_CHD = 5;
			step1 += 6;
		} else if (55 <= this.responses[0] && this.responses[0] <= 59) {
			this.low_CHD = 7;
			step1 += 7;
		} else if (60 <= this.responses[0]) {
			this.low_CHD = 8;
			step1 += 8;
		}
		
		//second step: smoker
		var step2 = (this.responses[1].toLowerCase() === 'no') ? 0 : 2;
		
		//third step: diabetic
		var step3 = (this.responses[2].toLowerCase() === 'no') ? 0 : 4;
		
		//fourth step: blood pressure
		var step4 = 0;
		switch (parseInt(this.responses[3])) {
			case 0:
				if (this.responses[4] === 0) step4 -= 3;
				else if (this.responses[4] === 3) step4 += 2;
				else if (this.responses[4] === 4) step4 += 3;
				break;
			
			case 1:
				if (this.responses[4] === 3) step4 += 2;
				else if (this.responses[4] === 4) step4 += 3;
				break;
				
			case 2:
				if (this.responses[4] === 3) step4 += 2;
				else if (this.responses[4] === 4) step4 += 3;
				break;
				
			case 3:
				if (this.responses[4] <= 3) step4 += 2;
				else if (this.responses[4] === 4) step4 += 3;
				break;
				
			case 4:
				step4 += 3;
				break;
		};
		
		//fifth step: cholesterol
		var step5 = 0;
		switch (parseInt(this.responses[5])) {
			case 0: 
				step5 -= 2;
				break;
				
			case 2:
				step5 += 1;
				break;
				
			case 3:
				step5 += 1;
				break;
				
			case 4:
				step5 += 3;
				break;

			default:
				step5 += 0;
				break;
		}
		var step6 = 0;
		switch (parseInt(this.responses[6])) {
			case 0: 
				step6 += 5;
				break;
				
			case 1:
				step6 += 2;
				break;
				
			case 2:
				step6 += 1;
				break;
				
			case 4:
				step6 -= 3;
				break;

			default:
				step6 += 0;
				break;
		}
		
		//alert (step1 + ', ' + step2 + ', ' + step3 + ', ' + step4 + ', ' + step5 + ', ' + step6);
		this.points = step1 + step2 + step3 + step4 + step5 + step6;
		//alert (this.points);
		
		var CHD = 0;
		if (this.points < -2) {
			CHD = 1;
		} else if (this.points === -1) {
			CHD = 2;
		} else if (this.points === 0) {
			CHD = 2;
		} else if (this.points === 1) {
			CHD = 2;
		} else if (this.points === 2) {
			CHD = 3;
		} else if (this.points === 3) {
			CHD = 3;
		} else if (this.points === 4) {
			CHD = 4;
		} else if (this.points === 5) {
			CHD = 4;
		} else if (this.points === 6)	 {
			CHD = 5;
		} else if (this.points === 7) {
			CHD = 6;
		} else if (this.points === 8) {
			CHD = 7;
		} else if (this.points === 9) {
			CHD = 8;
		} else if (this.points === 10) {
			CHD = 10;
		} else if (this.points === 11) {
			CHD = 11;
		} else if (this.points === 12) {
			CHD = 13;
		} else if (this.points === 13) {
			CHD = 15;
		} else if (this.points === 14) {
			CHD = 18;
		} else if (this.points === 15) {
			CHD = 20;
		} else if (this.points === 16) {
			CHD = 24;
		} else if (this.points >= 17) {
			CHD = 27;
		}
		
		return (CHD);
	},
	get_compared_risk: function(CHD) {
	    if (this.low_CHD == 0) {
	        return (0);
	    } else {
		    var comp_risk = (CHD / this.low_CHD).toFixed(1);
		    return (comp_risk);
    	};
	},
	update_links: function(i, dir) {
		var nav_fx = new Fx.Morph(this.nav_holder, {
			duration: '500',
			onComplete: function() {
				this.nav_holder.innerHTML = '';
				
				switch (i) {
					case 0:
						var link_next = new Element('a').inject(this.nav_holder, 'inside').innerHTML = this.nav_links[0];
						break;
						
					case 5:
						var link_back = new Element('a').inject(this.nav_holder, 'inside').innerHTML = this.nav_links[1];
						this.nav_holder.innerHTML += ' | ';
						var link_next = new Element('a').inject(this.nav_holder, 'inside').innerHTML = (dir > 0) ? this.nav_links[3] : this.nav_links[2];
						break;
					
					case 6:
						var link_back = new Element('a').inject(this.nav_holder, 'inside').addClass('results').innerHTML = this.nav_links[4];
						this.nav_holder.innerHTML += ' | ';
						var link_next = new Element('a').inject(this.nav_holder, 'inside').addClass('results').innerHTML = this.nav_links[5];
						break;
					
					default:
						var link_back = new Element('a').inject(this.nav_holder, 'inside').innerHTML = this.nav_links[1];
						this.nav_holder.innerHTML += ' | ';
						var link_next = new Element('a').inject(this.nav_holder, 'inside').innerHTML = this.nav_links[2];
						break;
				}
				
				var nav_fx = new Fx.Morph(this.nav_holder, {duration: '500'}).start({'opacity': [0,1]});
				
				this.activate();
			}.bind(this)
		}).start({'opacity': [1,0]});
	},
	update_icons: function(index) {
		if (index < this.q_icons.length) {
			this.q_icons.each(function(icon) {
				if (!icon.getProperty('src').test('blank')) icon.setProperty('src','hra_images/question/blank.gif');
			}, this);
		
			if (index > -1) {
				var icon_fx = new Fx.Morph(this.q_icons[index], {
					duration: '250',
					onComplete: function() {
						this.q_icons[index].setProperty('src','hra_images/question/icon_' + (index + 1) + '.gif');
						var icon_fx = new Fx.Morph(this.q_icons[index], {duration: '250'}).start({'opacity': [0,1]});
					}.bind(this)
				}).start({'opacity': [1,0]});
			}
		} else {
			this.q_icons.each(function(icon) {
				icon.setProperty('src','hra_images/question/filled.gif');
			}, this);
		}
	},
	add_results: function(risk, class_name) {
		var header = this.options.sections[this.step + 1].getFirst();
		var risk_container = new Element('div').addClass(class_name).inject(header, 'inside');
		
		var risk_str = risk;
		if (risk_str === 27 && class_name === 'ten_year_risk') {
			var i = new Element('img', {
				src: 'hra_images/characters/greater_than.gif',
				height: 14,
				border: 0
			}).inject(risk_container, 'inside');
		}
		risk_str.toString().split('').each(function(character) {
			if (character === '.') character = 'period';
			var i = new Element('img', {
				src: 'hra_images/characters/' + character + '.gif',
				height: 14,
				border: 0
			}).inject(risk_container, 'inside');
		}, this);
		if (class_name === 'ten_year_risk') {
			var percentage = new Element('img', {
				src: 'hra_images/characters/percent.gif',
				height: 14,
				border: 0
			}).inject(risk_container, 'inside');
		} else {
			var ending = new Element('img', {
				src: 'hra_images/headers/snippet.gif',
				height: 14,
				border: 0
			}).inject(risk_container, 'inside');
		}
	},
	populate_responses: function() {
		var recap_box = $E('div.recap').getLast();
		this.responses.each(function(response, index) {
			var txt = recap_box.innerHTML;
			switch (index) {
				case 3:
					if (parseInt(response) === 0) {
						response = '&lt;120';
					} else if (parseInt(response) === 1) {
						response = '120-129';
					} else if (parseInt(response) === 2) {
						response = '130-139';
					} else if (parseInt(response) === 3) {
						response = '140-159';
					} else if (parseInt(response) === 4) {
						response = '&ge;160';
					}
					break
				case 4:
					if (parseInt(response) === 0) {
						response = '&lt;80';
					} else if (parseInt(response) === 1) {
						response = '80-84';
					} else if (parseInt(response) === 2) {
						response = '85-89';
					} else if (parseInt(response) === 3) {
						response = '90-99';
					} else if (parseInt(response) === 4) {
						response = '&ge;100';
					}
					break;
				case 5:
					if (parseInt(response) === 0) {
						response = '&lt;160';
					} else if (parseInt(response) === 1) {
						response = '160-199';
					} else if (parseInt(response) === 2) {
						response = '200-239';
					} else if (parseInt(response) === 3) {
						response = '240-279';
					} else if (parseInt(response) === 4) {
						response = '&ge;280';
					}
					break;
				case 6:
					if (parseInt(response) === 0) {
						response = '&lt;35';
					} else if (parseInt(response) === 1) {
						response = '35-44';
					} else if (parseInt(response) === 2) {
						response = '45-49';
					} else if (parseInt(response) === 3) {
						response = '50-59';
					} else if (parseInt(response) === 4) {
						response = '&ge;60';
					}
					break;
			}
			recap_box.innerHTML = txt.replace(('X' + index), response);
		}, this);
	},
	show_warning: function(msg) {
		var coordinates = $(document).getCoordinates();
		var height = coordinates.height;
		var width = coordinates.width;
		
		var overlay = new Element('div').setStyles({
			position: 'absolute',
			top: '0',
			left: '0',
			width: width + 'px',
			height: height + 'px',
			zIndex: '10000',
			visibility: 'hidden'
		}).inject(document.body, 'inside');
		var backgnd = new Element('div').setStyles({
			position: 'absolute',
			top: '0',
			left: '0',
			background: '#000',
			width: width + 'px',
			height: height + 'px'
		}).inject(overlay, 'inside');
		var warning = new Element('div').setStyles({
			background: '#fff',
			position: 'relative',
			top: '100px',
			width: '270px',
			height: '130px',
			margin: '0px auto',
			border: '2px solid #000'
		}).addClass('ra_warning').inject(overlay, 'inside').innerHTML = msg;
		overlay.addEvents({
			'click': function() {
				var obj = this;
				var overlay_fx = new Fx.Morph(overlay, {
					duration: '250',
					onComplete: function() {
						obj.destroy();
					}
				}).start({'opacity': [1, 0]});
			}
		})
		var backgnd_fx = new Fx.Morph(backgnd, {duration: '250'}).start({'opacity': [0, 0.5]});
		var overlay_fx = new Fx.Morph(overlay, {duration: '250'}).start({'opacity': [0, 1]});
	}
});
assessment.implement(new Options, new Events);

var question = new Class({
	options: {
		id: 0,
		base_element: $('questions'),
		type: 'text',
		position: [0, 0],
		style: null
	},
	initialize: function(options) {
		this.setOptions(options);

		switch (this.options.id) {
			case 1:
				this.range = new Array('30-34','35-39','40-44','45-49','50-54','55-59','60-64','65-69','70-74');
				this.points = new Array(-9,-4,0,3,6,7,8,8,8);
				this.default_value = null;
				break;
			
			case 2:
				this.range = new Array('yes','no');
				this.points = new Array(2,0);
				this.default_value = null;
				break;
			
			case 3:
				this.range = new Array('yes','no');
				this.points = new Array(4,0);
				this.default_value = null;
				break;
			
			case 4:
				this.range = new Array(['&lt;120','120-129','130-139','140-159','&ge;160'],['&lt;80','80-84','85-89','90-99','&ge;100']);
				this.points = new Array(-3,0,0,2,3);
				this.default_value = new Array('Systolic','Diastolic');
				break;
			
			case 5:
				this.range = new Array(['&lt;160','160-199','200-239','240-279','&ge;280'],['&lt;35','35-44','45-49','50-59','&ge;60']);
				this.points = new Array([-2,0,1,1,3],[5,2,1,0,-3]);
				this.default_value = new Array('Total','HDL');
				break;
		}
		
		this.assemble();
	},
	assemble: function() {
		switch (this.options.type) {
			case 'text':
				var form_field = new Element('input', {
					name: this.options.id,
					type: 'text'
				}).setStyles({
					width: 150,
					height: 20,
					position: 'absolute',
					top: 39,
					left: 365,
					textAlign: 'center'
				}).inject(this.options.base_element,'inside');
				break;
				
			case 'boolean':
				this.range.each(function(value, index) {
					var option = new Element('div').setStyles({
						position: 'absolute',
						top: (index === 0) ? 35 : 58,
						left: (this.options.id === 2) ? 380 : 550,
						width: 55
					}).inject(this.options.base_element,'inside');
					
					var label = new Element('p').addClass('label').inject(option,'inside');
						label.innerHTML = value;
						
					var form_field = new Element('input', {
						name: this.options.id,
						type: 'radio',
						value: value
					}).inject(option,'inside');
				}, this);
				break;
				
			case 'select':
				var suffix = new Array('a','b');
				this.range.each(function(value, index) {
					var option = new Element('div').setStyles({
						position: 'absolute',
						top: (index === 0) ? 25 : 58,
						left: (this.options.id === 4) ? 465 : 480,
						width: 100
					}).inject(this.options.base_element, 'inside');
					
					var form_field = new Element('select', {
						name: this.options.id + suffix[index]
					}).setStyles({
						width: 110
					}).inject(option,'inside');
					
					var form_option = new Element('option', {
						value: null
					}).setProperty('selected','selected').inject(form_field, 'inside').innerHTML = this.default_value[index];
					
					value.each(function(v, index) {
						var form_option = new Element('option', {
							value: index
						}).inject(form_field, 'inside').innerHTML = v;
					}, this);
					
					
				}, this);
				break;
				
		}
		//this.activate();
	}
});
question.implement(new Options, new Events);
//window.addEvent('domready', function() {
window.addEvent('domready', function() {
	var risk_assessment = $E('.risk_assessment');
	if (risk_assessment) var sections = risk_assessment.getChildren();
	
	var question_sections = new Array();
	
	//handle sections
	sections.each(function(section) {
		if (!section.getProperty('id').test('print_results')) {
			var section_header = section.getFirst();
			var section_content = section.getLast();
		
			//replace headers
			if (section_header) {
				//check for multiple text containers, to allow for multiple elements/lines
				var header_txt = '';
				var header_src = section_header.getParent().getProperty('id');
			
				//grab text from all children in header element
				section_header.getChildren().each(function(el, index) {
					header_txt = (index > 0) ? header_txt + ' ' + el.innerHTML.clean() : el.innerHTML.clean();
				
					//delete text
					el.destroy();
				});
			
				//select and load header image
				var header_image = new Element('img', {
					src: 'hra_images/headers/' + header_src.toLowerCase().replace(/ /g, '_') + '.gif',
					alt: header_txt,
					width: 634,
					height: (header_src.test('introduction')) ? 119 : 100,
					border: 0
				}).inject(section_header, 'inside');
			
				if (!header_src.test('introduction')) question_sections.push(section);
			}
		
			//replace risk factor texts
			if (section_content.getLast().getFirst()) {
				var span_obj = section_content.getLast().getFirst();
				var b_text = span_obj.getFirst();
				var b_txt = b_text.innerHTML;
			
				var txt_image = new Element('img', {
					src: 'hra_images/txt/' + b_txt.toLowerCase().replace(/:/g, '').replace(/ /g, '_') + '.gif',
					alt: b_txt
				}).replaces(b_text);
			}
		}
	}, this);
	
	//create nav
	if (question_sections.length) {
		var risk_assessment_quiz = new assessment({
			base_element: $(risk_assessment),
			sections: sections,
			question_sections: question_sections
		})
	}
})