Event.observe(window,'load',function(){ QuestionnaireWizard.initialize() });

// numeric inputs
NumericField = Class.create({
	initialize:function(i){
		if(!i.hasClassName('numeric_watched')){
			i.addClassName('numeric_watched');
			i.observe('keydown',this.numericKeypress.bindAsEventListener(this));
		}
	},
	numericKeypress:function(e){
		var c = e.keyCode || e.which;
		if(c<47) return true;	// allows arrows,home,end,delete,etc keys
		var valid = /\d/.test(String.fromCharCode(c));
		if(!valid) Event.stop(e);
		return valid;
	}
});
	NumericField.scan = function(){ $$('input.numeric').map(function(i){ new NumericField(i) }); };
	Event.observe(window,'load',function(){ NumericField.scan() });

// email inputs
EmailField = Class.create({
	initialize:function(i){
		this.i = i;
		if(!i.hasClassName('emailfield_watched')){
			i.addClassName('emailfield_watched');
			i.form.observe('submit',this.validate.bindAsEventListener(this,i));
		}
	},
	validate:function(e,i){
		if(i.hasClassName('optional') && !$F(i))
			return true;
		if(i.hasClassName('required') && !$F(i)){
			Event.stop(e);
			return false;
		}
		if(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/i.test($F(i))){
			alert('The email address entered is not valid');
			Event.stop(e);
			return false;
		}
		return true;
	}
});
	EmailField.scan = function(){ $$('input.email').map(function(i){ new EmailField(i) }); };
	Event.observe(window,'load',function(){ EmailField.scan() });


// questionnaire wizard
QuestionnaireWizard = {
	initialize:function(){
		this.form = $('qgapscoreform');
		this.pages = this.form.immediateDescendants();
		this.pages.invoke('hide');
		this.pages[0].show();

		// bind the next buttons to the event handler
		this.pages.each(function(page,i){
			page.select('input[type=button]').shift().observe('click',this.nextPage.bindAsEventListener(this,i));
		},this);

		// handle the geography input
		$$('select[name=geography]').shift().observe('change',this.onGeographyChanged.bindAsEventListener(this));
		this.onGeographyChanged();
	},

		onGeographyChanged:function(ev){
			var select = $$('select[name=geography]').shift();
			select.next().update(
				/USA|Canada|Other/.test($F(select))
				? '<label for="geography_metadata">#{0}:</label><input id="geography_metadata" name="geography_metadata"/>'.interpolate([
					$F(select)=='Canada' && 'Postal code (first 3 characters)'
					|| $F(select)=='USA' && 'Zip code (first 3 numbers)'
					|| $F(select)=='Other' && 'Country Name'
				])
				: ''
			);
		},
	nextPage:function(ev,current_page){
		// gender
		var gender = $F($$('select[name=gender]').shift());
		var opposite_gender = gender=='M' && 'F' || 'M';

		// check if the current pages inputs have been entered
		var form = this.form.serialize(true);
		var symptoms = Object.keys(form);

		if(1){
			var b = false;
			var missing_symptoms = this.pages[current_page].select('input[type=radio]').pluck('name').uniq().findAll(function(name){
				var symptom_gender = $$('input[name='+name+']').shift().up().up().readAttribute('rel');
				var symptom_id = name.split('_').shift();
				var intensity = name.split('_').pop();
				var almost_never_id = symptom_id+'_0';
				var almost_never = symptoms.include(almost_never_id) && form[almost_never_id]==0;			
				return !(almost_never || symptoms.include(name) || symptom_gender && symptom_gender!=gender);
			});

			if(missing_symptoms.length)
				return alert("Please be sure to answer all questions. Note that if you selected a frequency greater than 'almost never' you will also need to select an intensity.");
		}

		alerttrue = function(msg){ alert(msg); return true; };

		// check that all required fields are entered
		var missing_required_fields = this.pages[current_page].select('#geography,input[name=email],input[rel=required],select[rel=required],input[name=elderly_dependants],input[name=child_dependants]').findAll(function(i){
			// not enterred, or enterred incorrectly ( invalid email format )
			var valid = 
				/dependants/.test(i.name)
				? (!$F(i) || /^(\d+)$/.test($F(i)))
				: ( 
					/(email|contact_me)/i.test(i.name) 
					? !$F(i) || /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/i.test($F(i))
					: (
						/geography/.test(i.name)
						? !$('geography').next().innerHTML || (
							$F('geography')=='USA' && /^|\d{3}$/.test($F('geography_metadata'))
							|| $F('geography')=='Canada' && /^|[a-z][0-9][a-z]$/i.test($F('geography_metadata'))
						)
						: (
							/age/i.test(i.name) && /^\d+$/.test($F(i))
							|| $F(i)
						)
					)
				);
			return !valid;
		}).pluck('name');

		if(missing_required_fields.length)
			return alert("Some of the fields enterred were invalid: \n" + missing_required_fields.map(function(f){
				return /dependants|age/.test(f) && f + ' is not a numeric value.'
				|| /email|contact_me/.test(f) && f + ' is not a valid email address.'
				|| /postal/.test(f) && f + ' is not a valid postal code.'
				|| /geography/.test(f) && (form[f]=='USA' ? 'ZIP Code is not 3 numerical characters' : 'Postal code is not in the format letter-number-letter. IE: a1a')
				|| f + ' is a required field.'
			}).join("\n"));

		// finish the survey, or proceed to next page
		if(current_page==this.pages.length-1)
			this.form.submit();
		else {
			this.pages[current_page].hide();
			this.pages[current_page+1].show();

			// hide/show all gender specific questions
			this.pages[current_page+1].select('tr[rel=#{0}]'.interpolate([opposite_gender])).invoke('hide');
			this.pages[current_page+1].select('tr[rel=#{0}]'.interpolate([gender])).invoke('show');
		}
	}
};
