// main.js

// set up some variables to use throughout the application
var currentState = "NONE"; 
var previousState = "NONE"; 
var qs_questions = null;
var player = null;

// this is the first function called once the DOM is ready
function init(){
    var maxQuest = getMaxQuestions();
    var current_question = getCurrentQuestion();
    
    if(maxQuest && !current_question)
    // if the user has seen the video, but not yet started answering any questions, show the "start_message"
    {
    	sendRequest("text/start_message.txt",showQuizStartMessage);
    } else if(maxQuest && current_question)
    // if the user has seen the video and answered at least one question, load the quiz
    {
        loadQuiz();
    } else 
    // otherwise, initialize the quiz application
    {
	sendRequest("text/config.txt",loadConfigs);
    }
}

function loadQuiz(){
	resetStage();
	var maxQuest = getMaxQuestions();
	var currentQuestion = getCurrentQuestion();
	if(currentQuestion == 0)
	// if we're trying to load the quiz, and the current question is set to 0, set it to 1 to display the first question
	{
		currentQuestion = 1;
	}
    	if(currentQuestion <= maxQuest)
    	// if the user hasn't answered all of the questions, load the next question
    	{
    	    sendRequest("text/question"+currentQuestion+".txt",loadQuestion);
    	} else 
    	// if all the questions have been answered, load the results
    	{
    	    sendRequest("text/results.txt",loadResults);
    	}
}

function getMaxQuestions(){
	// read the "qs_questions" cookie to find out how many questions are in the quiz
	var questions = readCookie("qs_questions");
	return questions;
}

function getCurrentQuestion(){
    // read the "qs_answers" cookie and count how many have been answered
    var currentQuestion = 0;
    var answers = readCookie("qs_answers");
    if(answers){
        var touples = answers.split("\|");
        currentQuestion = touples.length;
    }
    return currentQuestion;
}

function loadConfigs(req){
    // read the response from "config.txt", save the value into a global variable and load the video
    var resp = req.responseText;
    var lines = resp.split("\n");
    for(var i = 0;i < lines.length; i++){
        if(lines[i] != ""){
            if(lines[i].indexOf("questions") != -1){
                var tmp = lines[i];
                var touples = tmp.split("\|");
		qs_questions = touples[1];
		
		var frag = document.createDocumentFragment();
		var holder = document.createElement("div");
		holder.id = 'player';

		frag.appendChild(holder);
		document.body.appendChild(frag);
		
		var so = new SWFObject('player.swf','mpl','320','240','9');
		so.addParam('allowscriptaccess','always');
		so.addParam('allowfullscreen','true');
		so.addParam('flashvars','&file=overviewv3.flv&autostart=true');
		so.write('player');
		
		break;
            } else {
            	alert("ERROR: Unable to find configuration data.");
            }
        }
    }
}

function playerReady(thePlayer) {
	// check if the video player is loaded
	player = document.getElementById(thePlayer.id);
	addListeners();
}

function addListeners() {
	// add event listeners for the video to know when playback has finished
	if (player) { 
		player.addModelListener("STATE", "stateListener");
	} else {
		setTimeout("addListeners()",100);
	}
}

function stateListener(obj) { //IDLE, BUFFERING, PLAYING, PAUSED, COMPLETED
	// check player state
	currentState = obj.newstate; 
	previousState = obj.oldstate; 
	if ((currentState == "COMPLETED")&&(previousState == "PLAYING")) 
	// if the video has completed, create the "qs_questions" cookie, reset the state and re-initialize the application
	{
		createCookie('qs_questions',qs_questions,1);
		resetStage();
		init(); 
	}
}


function loadQuestion(req){
    // read the data from the question[X].txt file, and display on the screen
    var current_question = getCurrentQuestion();
    var resp = req.responseText;
    var lines = resp.split("\n");
    
    var frag = document.createDocumentFragment();
    var frm = document.createElement("form");
    frm.action = "#";
    frm.method = "get";
    
    var myspan = document.createElement("span");
    frm.appendChild(myspan);
    
    for(var i = 0;i < lines.length;i++)
    // iterate through each line of the question[X].txt file
    {
    	var tmp = lines[i];
    	if(tmp.indexOf("Q") == 0)
    	// if we find a question, create a paragraph element, and insert the question text
    	{
    	    var ttmp = tmp.split("\|");
    	    var question_text = document.createElement("p");
    	    question_text.innerHTML = trim(ttmp[1]);
    	    myspan.appendChild(question_text);
    	}
    	if(tmp.indexOf("A") == 0)
    	// if we find the answer text, create the form elements and display the answer text
    	{
	    var ttmp = tmp.split("\|");
    	    
    	    var question_label = document.createElement("label");
    	    var str = ttmp[2].replace("\n","");
    	    
    	    question_label.innerHTML = str;
       	    question_label.htmlFor = "ans"+i;
       	    
       	    var question_choice = document.createElement("input");
    	    question_choice.type = "radio";
    	    question_choice.name = "ans";
    	    question_choice.id = "ans"+i;
    	    question_choice.value = ttmp[1];
    	    question_choice.tabIndex = i;
    	    
    	    var br = document.createElement("br");
    	    
    	    myspan.appendChild(question_choice);
    	    myspan.appendChild(question_label);
    	    myspan.appendChild(br);
    	    
    	    addEvent(question_choice, "click", setButton);
    	}
    }
    
    // create the "Next" button
    var next_button = document.createElement("input");
    next_button.type = "button";
    next_button.id = "next_button";
    next_button.name = "next_button";
    next_button.className = "button_next";
    next_button.value = "Next  »";
    
    // create the "Back" button
    var back_button = document.createElement("input");
    back_button.type = "button";
    back_button.value = "« Back";
    back_button.className = "button_back";
    
    myspan.appendChild(next_button);
    myspan.appendChild(back_button);

    // add event handlers to process button clicks
    addEvent(back_button, "click", goBack);
    addEvent(next_button, "click", collectData);
    
    
    frag.appendChild(frm);

    document.body.appendChild(frag);
}

function setButton(e){
	// this function handles selecting and resetting the radio buttons
	var targ;
	var parentNode;
	if (!e) { var e=window.event; }
	    if (e.target){
	      targ=e.target;
	    } else if (e.srcElement) {
	      targ=e.srcElement;
    	}
    	parentNode = targ.parentNode;
	for(var i = 0;i<parentNode.childNodes.length;i++){
		if(parentNode.childNodes[i].type == "radio"){
			parentNode.childNodes[i].setAttribute("checked",false);
		}
	}
    	document.getElementById(targ.id).setAttribute("checked","checked");
}

function showQuizStartMessage(req){
    // display the "start_message.txt" file data
    var resp = req.responseText;
    var frag = document.createDocumentFragment();
    var my_form = document.createElement("form");
    var my_p = document.createElement("span");
    var button_quiz = document.createElement("input");
    var button_application = document.createElement("input");
    var button_watch = document.createElement("input");
    
    my_p.innerHTML = resp;
    my_p.className = "response_text";
    
    my_form.action = "#";
    my_form.method = "GET";
    my_form.className = "start_message";
    
    button_quiz.type = "button";
    button_quiz.value = "Fill Out Questionnaire";
    button_quiz.className = "button_quiz";
    
    my_form.appendChild(button_quiz);
    
    button_application.type = "button";
    button_application.value = "Submit an Application Now";
    button_application.className = "button_application";
    
    my_form.appendChild(button_application);
    
    button_watch.type = "button";
    button_watch.value = "Watch Video Again";
    button_watch.className = "button_watch";
        
    my_form.appendChild(button_watch);
    
    // add event handlers for the buttons
    addEvent(button_quiz, "click", loadQuiz);
    addEvent(button_application, "click", goToApplication);
    addEvent(button_watch, "click", watchVideo);
    
    my_p.appendChild(my_form);

    frag.appendChild(my_p);
    document.body.appendChild(frag);
}    

function loadResults(req){
    // this function reads the user answers from the "qs_answers" cookie, totals the score and displays a message based on the score
    var resp = req.responseText;
    var lines = resp.split("\n");
    var qs_answers = readCookie("qs_answers");
    var max_questions = getMaxQuestions();
    
    var frag = document.createDocumentFragment();
    
    for(var i = 0; i < lines.length; i++){
    	if(lines[i].indexOf("MATCH") != -1)
    	// this text is used when the user answers all of the questions correctly
    	{
    		var sTmp = lines[i];
    		var aTmp = sTmp.split("\|");
    		sTmp = aTmp[1];
    		var match_text = sTmp;
    	} else if(lines[i].indexOf("MISS") != -1)
    	// this is used when there are 1 or more, incorrectly answered questions
    	{
    		var sTmp = lines[i];
		var aTmp = sTmp.split("\|");
		sTmp = aTmp[1];
    		var miss_text = sTmp;
    	}
    }
    
    // calculate user score based on responses
    var score = 0;
    var answers = qs_answers.split("\|");
    for(var i = 0;i < answers.length;i++){
    	var aTmp1 = answers[i].split(":");
    	if(aTmp1.length > 1){
    		score = score + parseInt(aTmp1[1]);
    	}	
    }
    
    if(score == (max_questions * 2))
    // if the user has answered the questions "correctly", show message
    {
    	var para = document.createElement("span");
    	para.className = "response_text";
    	para.innerHTML = match_text;
    	
    	frag.appendChild(para);
    	
    	document.body.appendChild(frag);
    } else 
    // otherwise, display the "incorrect" message, and display the corresponding message for each missed question
    {
    	var para = document.createElement("span");
    	para.className = "response_text";
	para.innerHTML = miss_text;
	    	
    	frag.appendChild(para);

	document.body.appendChild(frag);
	    	
    	for(var i = 0;i < answers.length;i++){
    		var aTmp1 = answers[i].split(":");
    		if(aTmp1[1] != 2)
    		// if the user did not pick the correct answer, load the matching question[X].txt file, and display the message
    		{
    			if(aTmp1[0] != ""){
    				sendRequest("text/question"+aTmp1[0]+".txt",loadQuestionResponse);	
    			}	
    		}
    	}
    }
    
    // reset the cookies, so the user will be presented with the video and quiz next time they come to this page
    eraseCookie("qs_questions");
    eraseCookie("qs_answers");
}    

function loadQuestionResponse(req){
	// load the response message from the question[X].txt file
	var resp = req.responseText;
	var lines = resp.split("\n");
	
	var frag = document.createDocumentFragment();
	
	var dl = document.createElement("dl");
	
	for(var i = 0;i < lines.length;i++){
	    	var tmp = lines[i];
	    	
	    	if(tmp.indexOf("Q") == 0)
	    	// display the question text
	    	{
    			var aTmp = tmp.split("\|");
    			var dt = document.createElement("dt");
    			dt.innerHTML = aTmp[1];
    			dl.appendChild(dt);
    		}	
	    	
	    	if(tmp.indexOf("R") == 0)
	    	// display the response text
	    	{
    			var aTmp = tmp.split("\|");
    			var dd = document.createElement("dd");
    			dd.innerHTML = aTmp[1];
    			dl.appendChild(dd);
    		}
    	}	
    	frag.appendChild(dl);
    	// iterate through the child nodes of the document.body to find where to insert the response text
    	for(var i=0;i<document.body.childNodes.length;i++){
    		if (document.body.childNodes[i].className == "response_text"){
    			break;
    		}
    	}	
    	document.body.childNodes[i].appendChild(frag);
}

function goBack(){
	// strip off the last answer response from the "qs_answers" cookie to display the previous question
	var answers = readCookie("qs_answers");
	if(answers){
		var touples = answers.split("\|");
		currentQuestion = touples.length;
		if(currentQuestion == 2){
			eraseCookie("qs_answers");
		} else {
			var sTmp = "";
			for(var i=0;i<(currentQuestion-2);i++){
				sTmp = sTmp + touples[i] + "|";
			}
			createCookie("qs_answers",sTmp,1);
		}
	}
	resetStage();
	init();
}

function collectData(e){
    // collect and process the user responses from the question
    var currentQuestion = getCurrentQuestion();
    var bAns = 0;
    
    if (!e) { var e=window.event; }
    if (e.target){
      targ=e.target;
    } else if (e.srcElement) {
      targ=e.srcElement;
    }
    if (targ.nodeType==3){
      targ = targ.parentNode;
    }

    var myForm = targ.parentNode;
    for(var i = 0;i < myForm.childNodes.length; i++){
    	if(myForm.childNodes[i].type == "radio" && myForm.childNodes[i].name == "ans"){
    	    if(myForm.childNodes[i].checked == 1){
    	    	bAns = 1;
		var old_val = readCookie("qs_answers");
		var prepend = "";
		if(old_val){
                    prepend = old_val;
		}
                createCookie("qs_answers",prepend + currentQuestion + ":" + myForm.childNodes[i].value + "|",1);
                resetStage();
                init();
            }		        
    	}	
    }
    if(bAns == 0)
    // if the user has not selected an answer, but has clicked the "next" button, display a message
    {
    	alert("Please select an answer and then click the Next button.");
    }    	
}

function goToApplication(){
	// redirect the page to the openhire.com site, where the user can submit a resume
	eraseCookie("qs_questions");
	document.location.href = "http://hostedjobs.openhire.com/epostings/submit.cfm?fuseaction=app.newsubmission&jobid=0&company_id=15654&version=1&source=ONLINE";
}

function watchVideo(){
	// delete the "qs_questions" cookie to allow the user to see the video again
	resetStage();
	eraseCookie("qs_questions");
	init();
}

// call the init() function once the DOM has loaded
onContent(init);

