
var lwa_question_index = 0;
var lwa_survey_id = 0;
var lwa_questions = {};
var lwa_question = {};
var lwa_answers = [];
var lwa_closemsg = "";
var lwa_dbid = 0;

function LwaSurvey(id){
	lwa_survey_id = id;
	document.write("<form id='lwa_survey_form_"+ id +"' onsubmit='return false;'><div class='lwa_survey' id='lwa_survey_"+ id +"'></div></form>");

	LwaGetQuestions();
}

function LwaGetQuestions(){
	var xhttp = new XMLHttpRequest();

	xhttp.onreadystatechange = function() {
	    if (xhttp.readyState == 4 && xhttp.status == 200) {
	    	console.log(xhttp.responseText);
	    	var questions = JSON.parse(xhttp.responseText);	    	
	    	// Return and do nothing if there is something wrong
	    	if(questions.Status == undefined || questions.Status != "Success"){
	    		console.log(questions);
	    		return;
	    	}
	    	if (questions.Message == "Already done") {
	    		var el = document.getElementById("lwa_survey_" + lwa_survey_id);
				el.innerHTML = "You have already completed the survey, thanks!";
				return;

	    	}

	    	lwa_questions = questions.Data;
	    	lwa_closemsg = questions.Message;

	    	LwaCreateQuestion();
	    }
    }

	xhttp.open("POST", lwa_server + "includes/trackSurvey.php" , true);

	var params = 'conf=' + lwa_profile + '&action=GET&survey_id=' + lwa_survey_id + '&dbid=' + lwa_dbid;
	
	xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	//xhttp.setRequestHeader("Content-length", params.length);
	//xhttp.setRequestHeader("Connection", "close");

	xhttp.send(params);
}

function LwaCreateQuestion(){
	data = lwa_questions[lwa_question_index];

	var el = document.getElementById("lwa_survey_" + lwa_survey_id);
	el.innerHTML = "";

	lwa_question = data;

	if(lwa_question == undefined){
		return LwaFinishSurvey();
	} else if(lwa_question.type == "single"){
		var answersHTML = LwaSurveySingle();
	} else if(lwa_question.type == "multiple"){
		var answersHTML = LwaSurveyMultiple();
	} else if(lwa_question.type == "open"){
		var answersHTML = LwaSurveyOpen();
	} else if(lwa_question.type == "input"){
		var answersHTML = LwaSurveyInput();
	}
	// Add The question
	var labelHTML = "<h3 class='lwa_question_header'> "+ (lwa_question_index + 1) +". "+ lwa_question.question +"</h3>";
	// Next Button html
	var buttonHTML = "<button class='lwa_next_btn' onclick=\"LwaNextQuestion();\">Next</button>";

	if(answersHTML != undefined){	    		
		// Overwrite the html
		el.innerHTML = labelHTML + answersHTML + buttonHTML;
	}
}

function LwaSurveySingle(){
	var content = "";

	// Add The answers
	for (var i = 0; i < lwa_question.answers.length; i++) {
		content += "<div class='lwa_radio'><label><input type='radio' name='Lwa_single_answer' value='"+ i +"' /> " + lwa_question.answers[i] + "</label></div>";		
	}
	return content;	
}

function LwaSurveyMultiple(){
	var content = "";
	for (var i = 0; i < lwa_question.answers.length; i++) {
		content += "<div class='lwa_checkbox'><label><input type='checkbox' name='Lwa_multiple_answer_"+ i +"' value='"+ i +"' /> " + lwa_question.answers[i] + "</label></div>";		
	}
	return content;	
}

function LwaSurveyInput(){
	return "<div class='lwa_input'><input type='text' name='Lwa_single_input'></input></div>";	
}
function LwaSurveyOpen(){
	return "<div class='lwa_textarea'><textarea name='lwa_open_answer'></textarea></div>";	
}

function LwaNextQuestion(){
	// Set current answer	
	LwaGetAnswer();

	if(lwa_question.type == "single"){
		console.log('check rules');
		LwaCheckRules();
	} else {
		// Nothing special to do just go to the next question
		lwa_question_index ++;
		console.log('nanana');
		LwaCreateQuestion();
	}
}

function LwaGetAnswer(){
	var els = document.forms["lwa_survey_form_"+ lwa_survey_id].elements;
	var answer = "";

	if(lwa_question.type == "single"){		
		for (var i = 0; i < els.length; i++) {
			if(els[i].checked != undefined){
				if(els[i].checked === true){
					answer = els[i].value;
				}				
			}					
		}
	} else if(lwa_question.type == "open"){
		answer = encodeURIComponent( els.namedItem("lwa_open_answer").value.replace(/[&\/\\#+()$~%'":*?<>{}]/g,"") );
	} else if(lwa_question.type == "input"){
		answer = encodeURIComponent( els.namedItem("Lwa_single_input").value.replace(/[&\/\\#+()$~%'":*?<>{}]/g,"") );
	} else if(lwa_question.type == "multiple"){
		var as = [];
		for (var i = 0; i < els.length; i++) {
			if(els[i].checked != undefined){
				if(els[i].checked === true){
					as.push(1);
				} else {
					as.push(0);
				}
				
			}					
		}
		answer = as.join("-");
	}	
	lwa_answers[lwa_question_index] = answer;
}

function LwaCheckRules(){	

	var rules = lwa_question.rules[ lwa_answers[lwa_question_index] ];
	// No answer selected
	if(rules == undefined){
		return;
	}	

	if(rules['default'] === 1){
		// Nothing special to do just go to the next question
		lwa_question_index ++;
		LwaCreateQuestion();

	} else if(rules['link'] != ""){
		// Go to answer ID
		for (var i = 0; i < lwa_questions.length; i++) {
			if(lwa_questions[i].id == rules['link']){
				lwa_question_index = i;
				LwaCreateQuestion();
				break;
			}
		}
	} else if(rules['url'] != ""){
		LwaFinishSurvey(function(){
			window.location.href = rules['url'];
		});
	} else if(rules['end'] != ""){
		LwaFinishSurvey();
	}
}

function LwaFinishSurvey(callback){

	var xhttp = new XMLHttpRequest();

	xhttp.onreadystatechange = function() {
	    if (xhttp.readyState == 4 && xhttp.status == 200) {
	    	var question = JSON.parse(xhttp.responseText);
	    	// Return and do nothing if there is something wrong
	    	if(question.Status == undefined || question.Status != "Success"){
	    		console.log(question);
	    		return;
	    	}

	    	if(callback != undefined){
		    	callback();
		    }
	  		
	  		var el = document.getElementById("lwa_survey_" + lwa_survey_id);
	  		el.innerHTML = lwa_closemsg;		
	    }
    }

	xhttp.open("POST", lwa_server + "includes/trackSurvey.php" , true);

	var params = 'conf=' + lwa_profile + '&action=POST&survey_id=' + lwa_survey_id + '&dbid=' + lwa_dbid;
	params += LwaGetParams();

	xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	//xhttp.setRequestHeader("Content-length", params.length);
	//xhttp.setRequestHeader("Connection", "close");

	xhttp.send(params);
	return false;
}

function LwaGetParams(){
	var params = "";
	for (var i = 0; i < lwa_answers.length; i++) {
		params += "&answer-" + lwa_questions[i].id + "=" +  lwa_answers[i];
	}
	return params;
}