var fullquiz;
var backup = false;
var userAnswers = new Array();
var currentPage = 0; // page showing
var numPages;
var progress = 0; // for the progress bar on the bottom
var currentPage = 1;
var lastFinishedPage = 1;  // how far along user has gotten, used for backing up then going forward
var user_id;
var path = window.location.pathname.split('/'); 
var profiler_type = path[1]; // nre aka profiler  vs jre
// var pageQuestions; // all questions on a specified page


function submitAnswer(page_num){
	formdata = null; // clear out for repeats
	// var page_num = $F('page_num');
	formdata = Form.serialize('survey');
	debug(formdata);
//	if(profiler_type == "job_readiness_evaluator"){
//		profiler_type = "jre";
//		}
	// to get results in json
	var url = '/' + profiler_type + '/page_questions/' + page_num + '/2/';
	debug("try " + url);
	var pageQuestions;
	new Ajax.Request(
		url,
		{
		method: 'get', 
		onSuccess: 
			function(transport) {
	      		pageQuestions = transport.responseText.evalJSON(true);
	      		debug("questions: " + pageQuestions.length);
				validateAnswers(pageQuestions, formdata, page_num);
				}
		// onFailure: function(transport) { debug('nope'); alert('nope'); }
		});		
	}

	
function validateAnswers(pageQuestions, formdata, page_num){
	var error = false;
	var questionList = new Array(); // questions asked on current page
	var country = 1; // default to US
	
	for(i = 0; i < pageQuestions.length; i++){
		questionList.push(pageQuestions[i].question_id);
		}	

	var previousQ = null;
	// run over formdata and verify for all datatypes
	var qanda = formdata.split("&");
	for(var i = 0; i < qanda.length; i++){
		
		var eq = qanda[i].indexOf("=");
		qnum = qanda[i].substring(0, eq);
		qnum = qnum.replace(/question/, "");
		debug("-----------------");
		debug("qnum is " + qnum);
		
		// if a question has been answered take it off the array
		for(q = 0; q < questionList.length; q++){
			if(questionList[q] == qnum){
				questionList.splice(q, 1);
				}
			}
		
		qa = qanda[i].substring(eq+1, qanda[i].length);
		debug("qa is " + qa);

		if(qnum != 'page_num' && qnum != '192-a'){
			// debug("errorDiv logic ");
			var errorDiv = document.getElementById("e" + qnum);
			errorDiv.innerHTML= "";
			
			}
		if(qnum == 2 && qa == ""){
			qa = "none";
			}
		if(qnum == 73 && qa == "" && country == 3){
			qa = 99999;
			} 
		if(qnum == '192-a') //this is damn inefficient
		{
			if(document.getElementById('a192-1-b').value.length > 0)
				qa = 1;
			else
				qa = 0;	
		}
		if( (qa == "" || qa == " ") && qnum != 192 ){
			var errorId = "e" + qnum;
			debug(qnum + " has no answer, so fix " + errorId);			
			// var errorDiv = document.getElementById("e" + qnum);
			errorDiv.innerHTML= "";
			errorDiv.appendChild(document.createTextNode('Please answer this question'));
			// errorDiv.update('Please answer this question');
			error = true;
			}
		
		else{
			
			//  loop through pageQuestions
			for(j = 0; j < pageQuestions.length; j++){
				if(pageQuestions[j].question_id == qnum){
					pageQuestions[j].useranswer = qa; // add user's answers to pageQuestions for back button
					if(pageQuestions[j].datatype == 'number'|| pageQuestions[j].datatype == 'decimal'){
						// remove extra spaces, so we just see the number
						qa = qa.replace(/%20/g, "");
						if(isNaN(qa)){
							debug(qa + " is nan");
							var errorDiv = document.getElementById("e" + qnum);
							errorDiv.innerHTML= "";
							errorDiv.appendChild(document.createTextNode('Please enter a number'));
							error = true;
							}
						if(qa < 0){
							var errorDiv = document.getElementById("e" + qnum);
							errorDiv.innerHTML= "";
							errorDiv.appendChild(document.createTextNode('Please enter a positive number'));
							error = true;
							}
						if(pageQuestions[j].datatype == 'number'){
							if(!isInteger(qa)){
								var errorDiv = document.getElementById("e" + qnum);
								errorDiv.innerHTML= "";
								errorDiv.appendChild(document.createTextNode('Please enter a whole number'));	
								error = true;
								}
							
							}
						// answer is impossibly big, so make it = the max we like						
						if(pageQuestions[j].max_value && qa > parseFloat(pageQuestions[j].max_value)){
							// js is so weird
							replaceThis = new RegExp("question" + pageQuestions[j].question_id + "=" + qa);
							withThis = "question" + pageQuestions[j].question_id + "=" + pageQuestions[j].max_value;
							formdata = formdata.replace(replaceThis, withThis);
							}
						
						}

					if(qa == 0 && pageQuestions[j].question_type == "dropdown"){
						var errorId = "e" + qnum;
						debug(qnum + " is a dropdown and has no answer, so fix " + errorId);			
						// var errorDiv = document.getElementById("e" + qnum);
						errorDiv.innerHTML= "";
						errorDiv.appendChild(document.createTextNode('Please answer this question'));
						error = true;
						}

					if(pageQuestions[j].question_type == "checkbox"){
						var checkboxQuestion = "question" + qnum;
						debug("check that box");
						debug("previousQ is " + previousQ + " at " + qnum);
						if(previousQ == qnum){
							debug("repeater");
							checklist += qa + ",";
							}
						else{
							var checklist = qa + ",";
							}
						previousQ = qnum;
						
						debug("checklist " + checklist);
						}



					// which country?
					if(pageQuestions[j].question_id == 72){
						if(qa == 1){
							country = 1; // US
							}
						else if(qa == 2){
							country = 2; // Canada
							}
						else if(qa == 3){
							country = 3; // other 
							}
						}
					
					if(pageQuestions[j].datatype == 'zipcode'){
						debug("check zip...");

						var badzip = false; // assume a valid zipcode
						// is it a number?
						if(country == 1){  // U.S. of A.	
							var zip = new RegExp(/\d{5}/);
							// is it exactly 5 digits?
							if(!zip.test(qa)){
								badzip = true;
								}
							if(isNaN(qa) || qa.length > 5){
								debug('badzip!' + qa.length);
								badzip = true;
								}
							}

						else if(country == 2){
							qa = qa.replace(/%20/g, " ");
							var zip = new RegExp(/^\s*[a-ceghj-npr-tvxy]\d[a-z](\s)?\d[a-z]\d\s*$/i);
							debug("check canuks");
							if(!zip.test(qa)){
								badzip = true;
								debug("damn hosers");
								}
							}
						else if(country == 3){
							debug("check other, formdata = " + formdata);
							debug("qa in other is " + qa);
							badzip = false;
							error = false;
							$('e73').innerHTML= "";
							}

						// if it's a bad zip, post error message
						if(badzip){
							var errorDiv = document.getElementById("e" + qnum);
							errorDiv.innerHTML= "";
							errorDiv.appendChild(document.createTextNode('Please enter a valid postal code'));
							error = true;
							}
						}
					
					if(pageQuestions[j].datatype == 'string'){}

					if(pageQuestions[j].datatype == 'none'){}

					if(pageQuestions[j].datatype == 'age'){
						var badAge = false;
						if(isNaN(qa)){
							badAge = true;
							}
						if(!badAge){
							if(qa < 18 || qa > 99){
								badAge = true;
								}
							}
						if(badAge){
							var errorDiv = document.getElementById("e" + qnum);
							errorDiv.innerHTML= "";
							errorDiv.appendChild(document.createTextNode('Please enter a valid age'));
							error = true;
							}
					
						}

					if(pageQuestions[j].question_id == 112){
						// this will be checked with an ajax call last
						var checkJob = true;
						var jobTitleToCheck = escape(qa);
						}

					if(pageQuestions[j].datatype == 'email'){
						var emailpattern = /^(?:\w+\.?)*\w+%40(?:\w+\.)+\w+$/;
						// debug("testing email: " + qa);
						if(!emailpattern.test(qa)){
							var errorDiv = document.getElementById("e" + qnum);
							errorDiv.innerHTML= "";
							errorDiv.appendChild(document.createTextNode('Please enter a valid email address'));
							error = true;							
							}
						if(qa == "none"){  // question is now optional
							errorDiv.innerHTML= "";
							error = false; 
							}
						}
					// debug("pageQuestions answer at question_id " + qnum + " is " + pageQuestions[j].useranswer + " where q is " + pageQuestions[j].question_text);
					}
				}
			// debug(qnum + " must have content");
			}
		
		
		}  // eo for
	
	// if anything is left in the array it must be an unanswered radio
	if(questionList.length > 0){
		for(i = 0; i < questionList.length; i++){
			var errorDiv = document.getElementById("e" + questionList[i]);
			debug("errorDiv: " + errorDiv);
			errorDiv.innerHTML= "";
			errorDiv.appendChild(document.createTextNode('Please answer this question'));
			error = true;
			}	
		}

	if(checkboxQuestion){
		// if it's a checkbox tack the combined answer to the formdata
		quest = checkboxQuestion;
		formdata += "&" + checkboxQuestion + "=" + checklist; // ......
		}

	debug("------------ error is " + error + " ------------");
	
		
	if(!error){
		// even though error checking is done we need to put this ajaxy bit down here
		// another scriptaculous thing...
		if(checkJob){ 
			url = "/job_data/check_job_title/";
			var param = "title=" + jobTitleToCheck;
			new Ajax.Request(
				url,
				{
				parameters: param,
				onSuccess:
					function(response) {						
						if(response.responseText == 0){
							$('e112').update("Please select a job title that <i>most closely</i> matches yours.");
							$('jobinfo').update("");
							error = true;							
							}
						
						else if(response.responseText == 1){
							// submit answers and continue
							var url = '/' + profiler_type + '/submit/?' + formdata;
							// debug(url);
							window.location = url;
							}
						
						}
					}); // eo ajax request





			}
		else {
			var url = '/' + profiler_type + '/submit/?' + formdata;
			// debug(url);
			window.location = url;
			}
		}
	} // EO validater


function isInteger(num){
	var n = num % 1;
	if(n == 0){
		return true;
		}
	else{
		return false;
		}
	}


function salaryDisplay(text, li){
	// var url = '/profiler/getSalaryData/';
	var url = '/job_data/getSalaryData/';
	var params = "salaryRanges=" + escape(text.value);
	new Ajax.Request(
		url,
		{
			method: 'post',
			parameters: params,
			onSuccess:
				function(transport) {
					var salaryRanges = transport.responseText.evalJSON(true);
					// only for question 112 so far
					// $('e112').update("");
					$('jobinfo').update("Salary range: ");
					$('jobinfo').insert("$" + numberFormat(salaryRanges['25th']) + " - $" + numberFormat(salaryRanges['75th']));
					}
		});	
	// after the salary is displayed, get the job description
	// jobDescDisplay(text);
	}

/*
function jobDescDisplay(text){
	var url = '/job_data/getJobDescription/';
	var params = "jobtitle=" + escape(text.value);
	new Ajax.Request(
		url,
		{
			method: 'post',
			parameters: params,
			onSuccess:
				function(transport) {
					var jobDesc = transport.responseText;
					// only for question 112 so far
					$('e112').update("");
					$('jobdesc').update(jobDesc);
					}
		});
	}
*/


// returns a comma separated number for thousands+
function numberFormat(nStr){
	// from http://www.netlobo.com/
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)){
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
		}
	return x1 + x2;
	}


//  combined from upmo_slider.js
setSlider = function(handleID, sliderID, answerID, min, max){
	this.handleID = handleID;
	this.sliderID = sliderID;
	this.answerID = answerID;
	this.min = min;
	this.max = max;

	var answerValue = $(answerID);	
	var initialValue = answerValue.getAttribute('value');
	var up_slider = new Control.Slider(handleID, sliderID, {
		range: $R(min, max),
		sliderValue: initialValue,
		/*
		onSlide: function(v) {
			$(answerID).value = v; 
			},
		*/
		onChange: function(v) {
			$(answerID).value = Math.round(v); 
			// debug("slider: " +  Math.round(v) + " at sliderID: " + sliderID + ", handleID=" + handleID + ", answerID=" + answerID + ", initialValue=" + initialValue);
			}
		});

	}


function checkAnswerAlerts(answerValue, qid){
	// check fullquiz
	
	for(var i = 0; i < fullquiz.length; i++){
		var quest_id = fullquiz[i].question_id;
		if(quest_id == qid){
			alerts = fullquiz[i].answer_alert;
			if(alerts[answerValue] != ""){
				alert(alerts[answerValue]);
				}
			}
		}
	}

function debug(debugText){
	var debug = document.getElementById("debug");
	var para = document.createElement("p");
	para.appendChild(document.createTextNode(debugText));
	debug.appendChild(para);
	}




/* ---------------------------  profiler_intitialize_styles.js  ---------------- */


/*  used by Kristin's design 1.1  */

// ADAMS's RADIO CUSTOMISATION
// adam.burmister@gmail.com, Copyright 2005.


/**
NAME: initARC()

ABOUT:
 Detects the current user browser and customises the form's radio buttons if
 the browser is not IE mac, <= IE 4 or NS4.

USAGE:
 In your main HTML body use onLoad() to call initARC(), passing in the form id
 and on/off class names you wish to use to customise your radio buttons.
 e.g. <body onLoad="initARC('myform','radioOn', 'radioOff');">
 
PARAMS:
 formId   - The ID of the form you wish to customise
 onClass  - The CSS class name for the radio button's on style
 offClass - The CSS class name for the radio button's off style
*/
function initARC(formId,onClassRadio,offClassRadio,onClassCheckbox,offClassCheckbox) {
	// alert("initARC");
    var agt=navigator.userAgent.toLowerCase();

    // Browser Detection stuff
    this.major = parseInt(navigator.appVersion);
    this.ie     = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
    this.ie3    = (this.ie && (this.major < 4));
    this.ie4    = (this.ie && (this.major == 4) && (agt.indexOf("msie 4")!=-1) );
	this.iemac  = (this.ie && (agt.indexOf("mac")!=-1));

	if( !(this.iemac || ie3 || ie4) ){
		customiseInputs(formId,onClassRadio,offClassRadio,onClassCheckbox,offClassCheckbox);
	}
}



//Add a .label reference to all input elements. Handy! Borrowed from...
//http://www.codingforums.com/archive/index.php/t-14672
function addLabelProperties(f){
	if(typeof f.getElementsByTagName == 'undefined') return;
	var labels = f.getElementsByTagName("label"), label, elem, i = j = 0;
	
	while (label = labels[i++]){
		if(typeof label.htmlFor == 'undefined') return;
		elem = document.getElementById(label.htmlFor);
		//elem = f.elements[label.htmlFor]; /* old method */
		
		if(typeof elem == 'undefined'){
			//no label defined, find first sub-input
			var inputs = label.getElementsByTagName("input");
			if(inputs.length==0){
				continue;
			} else {
				elem=inputs[0];
			}
		} else if(typeof elem.label != 'undefined') { // label property already added
			continue;
		} else if(typeof elem.length != 'undefined' && elem.length > 1 && elem.nodeName != 'SELECT'){
			for(j=0; j<elem.length; j++){
				elem.item(j).label = label;
			}
		}
		elem.label = label;
	}
} 



/**
NAME: toggleLabelStyle()

ABOUT:
 This function is attached to our label's onClick event. So when the label is
 clicked this function alters the radio group's members to an unchecked state
 and style, and alters the currently selected label to the on style and checked
 state.

USAGE:
 ARC currently assumes that the label contains a FOR='id' in it's HTML. The other
 valid form of a label is <label>text <input /></label> - while it is possible
 to modify this code to allow for this form I have left this as an exercise for
 the reader.
 
PARAMS:
 formId   - Parent form of this label
 label    - The label for a radio button we wish to toggle
 onClass  - The CSS class name for the radio button's on style
 offClass - The CSS class name for the radio button's off style
*/
function toggleLabelStyle(formId, label, onClass, offClass){
	if(!document.getElementById || !label) return;
		
	var form = document.getElementById(formId); //label.form;
	if(!form) return;
	
	//find radio associated with label (if in htmlFor form)
	if(label.htmlFor) {
		var e = document.getElementById(label.htmlFor);
		
		if(e.type=="checkbox"){
			e.label.className = (e.label.className==onClass) ? offClass : onClass;
			e.checked = (e.label.className==onClass);
		} else if(e.type=="radio"){
			var radioGroup = form.elements[e.name];
			if(!radioGroup) return;
			
			for(var i=0; i<radioGroup.length; i++){
				if(radioGroup[i].label){
					radioGroup[i].label.className = ((radioGroup[i].checked=(radioGroup[i].id == e.id))
													 && radioGroup[i].label) ? onClass : offClass;
				}
			}
		}
	}
}



/**
NAME: customiseInputs()

ABOUT:
 This function does all the magic. It finds the <input>'s within the passed form
 and attaches a .label reference to the element, and also adds an onClick
 function to that label to the toggleLabelStyle() function.
 It hides all radio elements from the form and mirrors the startup checked values
 in the label's customised radio button styles.

USAGE:
 Called from initARC()
 
PARAMS:
 formId   - The form we're customising
 onClass  - The CSS class name for the radio button's on style
 offClass - The CSS class name for the radio button's off style
*/
function customiseInputs(formId, onClassRadio, offClassRadio, onClassCheckbox, offClassCheckbox) {
	if(!document.getElementById) return;
	
	var prettyForm = document.getElementById(formId);
	if(!prettyForm) return;
		
	//onReset, reset radios to initial values
	prettyForm.onreset = function() { customiseInputs(formId, onClassRadio, offClassRadio, onClassCheckbox, offClassCheckbox); }
	
	//attach an easy to access .label reference to form elements
	addLabelProperties(prettyForm);

	var inputs = prettyForm.getElementsByTagName('input');
	
	for (var i=0; i < inputs.length; i++) {
		/* NB: Yeah, i know this code is duplicated - I can't figure out how to create a local, persistent
			variable within the anonymous function calls. Fix it if you can, and let me know. */
			
		//RADIO ONLY
		if( (inputs[i].type=="radio") && inputs[i].label && onClassRadio && offClassRadio){
			//hide element
			inputs[i].style.position="absolute"; inputs[i].style.left = "-2000px";
			//initialise element
			inputs[i].label.className=offClassRadio;
			//when the label is clicked, call toggleLabelStyle and toggle the label
			inputs[i].label.onclick = function (){ toggleLabelStyle(formId, this, onClassRadio, offClassRadio); return false; };
			//enable keyboard navigation
			inputs[i].onclick = function (){ toggleLabelStyle(formId, this.label, onClassRadio, offClassRadio); };
			//if the radio was checked by default, change this label's style to checked
			if(inputs[i].defaultChecked || inputs[i].checked){ toggleLabelStyle(formId, inputs[i].label, onClassRadio, offClassRadio); }
		}
		
		//CHECKBOX ONLY
		if( (inputs[i].type=="checkbox") && inputs[i].label && onClassCheckbox && offClassCheckbox){
			//hide element
			inputs[i].style.position="absolute"; inputs[i].style.left = "-2000px";
			//initialise element
			inputs[i].label.className=offClassCheckbox;
			inputs[i].checked = false;
			//when the label is clicked, call toggleLabelStyle and toggle the label
			inputs[i].label.onclick = function (){ toggleLabelStyle(formId, this, onClassCheckbox, offClassCheckbox); return false; };
			//enable keyboard navigation
			inputs[i].onclick = function (){ toggleLabelStyle(formId, this.label, onClassCheckbox, offClassCheckbox); };
			//if the radio was checked by default, change this label's style to checked
			if(inputs[i].defaultChecked || inputs[i].checked){ toggleLabelStyle(formId, inputs[i].label, onClassCheckbox, offClassCheckbox); }
		}

		if( (inputs[i].type=="checkbox") || (inputs[i].type=="radio") && inputs[i].label ){
			//Attach keyboard navigation
			if(!this.ie){ //IE has problems with this method
				//You could set these to grab a passed in class name if you wanted to
				//do something a bit more interesting for keyboard states. But for now the
				//generic dotted outline will do for most elements.
				inputs[i].label.style.margin = "1px";
				inputs[i].onfocus = function (){ this.label.style.border = "1px dotted #333"; this.label.style.margin="0px"; return false; };
				inputs[i].onblur  = function (){ this.label.style.border = "none"; this.label.style.margin="1px"; return false; };
			}
		}
}
}

/* --------------------   
this was a separate file called profiler_radio.js, only checkboxes will need an additional js file   ----------------------- 
*/
/*  from Kristin's design 1.1   */

//Checkbox
//global variables that can be used by ALL the function son this page.
var inputs;
//this function runs when the page is loaded, put all your other onload stuff in here too.
function init() {
	replaceChecks();
	initARC('makeMeAPrettyFormRadio','radioOn','radioOff','','');
	}

function replaceChecks() {
	//get all the input fields on the page
	inputs = document.getElementsByTagName('input');

	//cycle trough the input fields
	for(var i=0; i < inputs.length; i++) {

		//check if the input is a checkbox
		if(inputs[i].getAttribute('type') == 'checkbox') {
			
			//create a new image
			var img = document.createElement('img');
			
			//check if the checkbox is checked
			if(inputs[i].checked) {
				img.src = imgTrue;
			} else {
				img.src = imgFalse;
			}

			//set image ID and onclick action
			img.id = 'checkImage'+i;
			//set image 
			img.onclick = new Function('checkChange('+i+')');
			//place image in front of the checkbox
			inputs[i].parentNode.insertBefore(img, inputs[i]);
			
			//hide the checkbox
			inputs[i].style.display='none';
		}
	}
}
//change the checkbox status and the replacement image
function checkChange(i) {
	if(inputs[i].checked) {
		inputs[i].checked = '';
		document.getElementById('checkImage'+i).src=imgFalse;
	} else {
		inputs[i].checked = 'checked';
		document.getElementById('checkImage'+i).src=imgTrue;
	}
}
/*counter*/

/*
* name   : checkbox_ticked
* param  : checkbox element id and corresponding text box id
* descc  : handle the event when a checkbox is checked
* return :
* author : jh
*/
function checkbox_ticked(checkbox_element_id, textbox_element_id)
{
        checkbox = document.getElementById(checkbox_element_id);
        textbox = document.getElementById(textbox_element_id);

        //when there is smth in textbox
        if(checkbox.checked == false)
        {
                textbox.value = "";
        }
}//end of checkbox_ticked

/*
* name   : textbox_typed
* param  : checkbox element id and corresponding text box id
* descc  : handle the event when a text is entered in the textbox
* return :
* author : jh
*/
function textbox_typed(checkbox_element_id, textbox_element_id)
{
        checkbox = document.getElementById(checkbox_element_id);
        textbox = document.getElementById(textbox_element_id);

        checkbox.checked = true; //check the checkbox
}//end of textbox_typed

/*
function counterUpdate(opt_countedTextBox, opt_countBody, opt_maxSize) {
        var countedTextBox = opt_countedTextBox ? opt_countedTextBox : "counttxt";
        var countBody = opt_countBody ? opt_countBody : "countBody";
        var maxSize = opt_maxSize ? opt_maxSize : 1024;

        var field = document.getElementById(countedTextBox);

        if (field && field.value.length >= maxSize) {
                field.value = field.value.substring(0, maxSize);
        }
        var txtField = document.getElementById(countBody);
                if (txtField) { 
                txtField.innerHTML = opt_maxSize - field.value.length;
        }

}
*/



// initialize stupid radio button code - won't work with document.observe('dom:loaded'...)
window.onload = init;

