var tabData = {};
var MCMS = {};
MCMS.questionData = {};
MCMS.optionArr = [];
MCMS.mainContainer;
MCMS.maxOptions = 20;
MCMS.prevOption;
MCMS.userAnswer;
MCMS.correctAnswer;
MCMS.currentAttempt;
MCMS.activityCompleted = false;
MCMS.currentGroup;
MCMS.group;
var eventMgr = new EventManager();
var _shell_wrapper = $('#shell_wrapper');
var _tabElements;

MCMS.initMCMS = function (data) {
	let popup = $("#mcmsContainer").parent(".popup")
	popup.addClass(data['id'])
	$(".group1,.group2,.group3").hide();
	MCMS.mainContainer = $("#mcmsContainer").find("#mcmsHolder");
	MCMS.questionData = data;
	MCMS.currentAttempt = 0;
	MCMS.currentGroup = 0;
	MCMS.group = null;
	//initialize Feedback
	Feedback.init($("#mcmsFeedbackBox"), $("#mcmsContainer"));
	eventMgr.addControlEventListener(Feedback, "feedbackClosed", MCMS.closeFeedback);
	//initialize submit button
	SubmitButton.init($("#mcmsHolder").find("#mcmsSubmitBtn"));
	SubmitButton.chkSubmitEnable(false);

	$("#mcmsContinueBtn").addClass("disabled")
	eventMgr.addControlEventListener(SubmitButton, "submitClicked", MCMS.submitClicked);
	MCMS.createOptions();
	MCMS.disableOptions();
	//MCMS.addListeners();
	MCMS.showQuestion();
	MCMS.mainContainer.find("#mcmsNextBtn").hide();

	setTimeout(function () {
		_tabElements = {
			'elements': [{
				'selector': '.right_wrap',
				//'role':'button'
			},
			{
				'selector': '#mcmsHolder .radio',
				'role': 'button'
			},
			{
				'selector': '.submitBtn.confirmBtn',
				'role': 'button'
			}
			],
			'sIndex': parseInt($("#templateHolder").attr('tabindex')) + 1 || 500,
			'nIndex': 1,
		};
		$("#mcssHolder .radio").addClass('iEle')
		$('.right_wrap').addClass('iGPopup')
		_shell_wrapper.trigger("addTabIndexing", _tabElements);
		$(".right_wrap").focus();

	}, 1000)


	MCMS.tabindex2 = function () {
		_tabElements = {
			'elements': [{
				'selector': '#feedbackContent'
			},
			{
				'selector': '.feedBackContent .close_icon',
				'role': 'button'
			}
			],
			'sIndex': parseInt($("#templateHolder").attr('tabindex')) + 1 || 500,
			'nIndex': 1,
		};
		$('#feedbackContent').addClass('iGPopup')
		_shell_wrapper.trigger("addTabIndexing", _tabElements);
		$("#feedbackContent").focus();
	}


}

MCMS.createOptions = function () {
	let optionG = MCMS.questionData.optionsGroup
	for (c = 0; c < optionG.length; c++) {
		MCMS.optionArr.push([])
		var type = '';
		(optionG[c].correctAnswer.length == 1) ? (type = "mcss") : (type = "mcms");
		//alert(type)

		$("#mcmsContainer").find(".group" + (c + 1) + " .bx_head_wrap").html(optionG[c].heading)

		for (var i = 0; i < optionG[c].group.length; i++) {
			var option = $(MCMS.mainContainer.find("#mcmsOptionContainer").find(".cloneOption")).clone();
			option.removeClass("cloneOption");
			if (type == "mcss") {
				option.find('#optionBox').addClass('radio').removeClass('checkBox');
			} else {
				option.find('#optionBox').addClass('checkBox').removeClass('radio');
			}
			var txt = optionG[c].group[i]
			var opt = new Option(option, type, i, txt);
			MCMS.optionArr[c][i] = opt;
			eventMgr.addControlEventListener(opt.holder, "optionClicked", MCMS.mcmsOptionClicked);

			MCMS.mainContainer.find(".group" + (c + 1)).append(opt.holder)
			option.appendTo(MCMS.mainContainer.find(".group" + (c + 1)));
		}

		if (MCMS.questionData.addGroupText) {
			$(".group_Dummy1").html(MCMS.questionData.addGroupText);

		}
		$(".group" + (c + 1)).show();
	}
};

MCMS.addListeners = function () {
	for (c = 0; c < MCMS.questionData.optionsGroup.length; c++) {
		for (var i = 0; i < MCMS.questionData.optionsGroup[c].group.length; i++) {
			//console.log("c " + c + " i " + i)
			var option = MCMS.optionArr[c][i];
			option.addListeners();
		}
	}
};

MCMS.showQuestion = function () {
	MCMS.initializeMCMS();
};

/*MCMS functionality*/
MCMS.initializeMCMS = function () {

	MCMS.userAnswer = [];
	MCMS.correctAnswer = [];
	MCMS.activityCompleted = false;

	$("#mcmsContainer").find("#mcmsQuestionTxt").html(MCMS.questionData.question);
	$("#mcmsContainer").find("#mcmsScenarioTxt").html(MCMS.questionData.scenarioText);
	$("#mcmsContainer").find("#mcmsInstructionTxt").html(MCMS.questionData.instructionText);

	$("#mcmsContainer").find(".mcssOption").addClass("hiddenOption");

	for (c = 0; c < MCMS.questionData.optionsGroup.length; c++) {
		MCMS.userAnswer.push([])
		let optionG = MCMS.questionData.optionsGroup[c];
		for (var i = 0; i < optionG.group.length; i++) {
			MCMS.correctAnswer[c] = optionG.correctAnswer;
			var option = MCMS.optionArr[c][i];
			option.showOption("<span>" + optionG.group[i] + "</span>");
		}
	}

}

MCMS.resetMCMS = function () {
	MCMS.userAnswer = [];
	for (c = 0; c < MCMS.questionData.optionsGroup.length; c++) {
		for (var i = 0; i < MCMS.questionData.optionsGroup[c].group.length; i++) {
			var option = MCMS.optionArr[c][i - 1];
			option.reset();
		}
	}
}

MCMS.mcmsOptionClicked = function (evt) {

	var clicked = $(evt.target).parent().parent();
	var str = clicked.attr("id");

	MCMS.currentGroup = parseInt(clicked.parent().attr("class").slice(5, 6));
	if (MCMS.questionData.optionsGroup[MCMS.currentGroup - 1].correctAnswer.length == 1) {
		clicked.parent().find("#optionBox").removeClass("MCSSbulletPointsSelected");
		$(evt.target).addClass("MCSSbulletPointsSelected")
		if (clicked.find("#optionBox").hasClass("MCSSbulletPointsSelected")) {
			/* if (MCMS.prevOption && MCMS.group==MCMS.currentGroup) {
				MCMS.prevOption.find("#optionBox").removeClass("MCSSbulletPointsSelected");
			} */
			MCMS.group = MCMS.currentGroup;
			MCMS.prevOption = clicked;
			MCMS.userAnswer[MCMS.currentGroup - 1] = [];
			MCMS.userAnswer[MCMS.currentGroup - 1].push(parseInt(str.split("_")[1]));
		} else {
			MCMS.userAnswer[MCMS.currentGroup - 1].splice(jQuery.inArray(str.split("_")[1], MCMS.userAnswer[MCMS.currentGroup - 1]), 1);
		}
	} else {
		if (clicked.find("#optionBox").hasClass("MCMSbulletPointsSelected")) {
			MCMS.userAnswer[MCMS.currentGroup - 1].push(parseInt(str.split("_")[1]));
		} else {
			MCMS.userAnswer[MCMS.currentGroup - 1].splice(jQuery.inArray(str.split("_")[1], MCMS.userAnswer[MCMS.currentGroup - 1]), 1);
		}

	}

	SubmitButton.chkSubmitEnable(false);

	for (var i = 0; i < MCMS.userAnswer.length; i++) {
		if (MCMS.userAnswer[i].length < 1) {
			return;
		}
	}
	SubmitButton.chkSubmitEnable(true);

}

MCMS.submitClicked = function (evt) {
	if (MCMS.userAnswer.length > 0 && !SubmitButton.holder.eq(0).hasClass('disabled')) {
		MCMS.disableOptions();
		MCMS.chkUserAnswer();

		if (MCMS.questionData.responseType == "") {
			markcompletepage.trigger("markcompletepage")
		} else {
			$(".feedBackPopup").show();
			$("#feedbackContent").html(MCMS.questionData.feedbackText)
			//MCMS.showFeedback(result);
			$(".feedBackContent").show();
			setTimeout(function () {
				MCMS.tabindex2();

			}, 500)


		}
	}
};

MCMS.disableOptions = function () {

	for (c = 0; c < MCMS.questionData.optionsGroup.length; c++) {
		for (var i = 0; i < MCMS.questionData.optionsGroup[c].group.length; i++) {
			//console.log("c " + c + " i " + i)
			var option = MCMS.optionArr[c][i];
			option.disable();
		}
	}
}

MCMS.chkUserAnswer = function () {
	var _isCorrect = true;
	for (i = 0; i < MCMS.correctAnswer.length; i++) {
		var tempArr = [];
		tempArr = MCMS.correctAnswer[i].concat();
		for (var c = 0; c < MCMS.correctAnswer[i].length; c++) {
			var ind = jQuery.inArray(MCMS.userAnswer[i][c], tempArr);
			if (ind >= 0)
				tempArr.splice(ind, 1);
		}
		var result = "Incorrect";
		//	console.log("tempArr.length " + tempArr.length + " " + MCMS.userAnswer[i].length + " " + MCMS.correctAnswer[i].length);
		if (tempArr.length > 0) {
			_isCorrect = false;
		}

		if (_isCorrect && MCMS.userAnswer[i].length == MCMS.correctAnswer[i].length) {
			//alert()
			result = 'Correct';
		}
	}
	//console.log("result " + result)
};


MCMS.showFeedback = function (result) {
	MCMS.currentAttempt++;
	$(".feedBackContent").show()
	if (MCMS.questionData.responseType == "generic") {
		if (result == "Correct") {
			Feedback.showFeedback(MCMS.questionData.feedback.genericResponse.correct.content);
			MCMS.showTickOnly();
		} else {
			if (MCMS.currentAttempt < MCMS.questionData.maxAttempts) {
				Feedback.showFeedback(MCMS.questionData.feedback.genericResponse.incorrect.content);
			} else {
				Feedback.showFeedback(MCMS.questionData.feedback.genericResponse.solution.content);
				MCMS.showSolution();
			}
		}
	} else {
		var feedStr = "";
		for (var c = 0; c < MCMS.userAnswer.length; c++) {
			feedStr += MCMS.questionData.specificResponse.response[MCMS.userAnswer[c] - 1].content;
			if (c > 0)
				feedStr += "<BR>"
		}
		//Feedback.showFeedback(feedStr);
		if (result == "Correct") {
			MCMS.showTickOnly();
		} else {
			if (MCMS.currentAttempt >= MCMS.questionData.maxAttempts)
				MCMS.showSolution();
		}
	}
	$("#mcmsFeedbackBox").draggable({
		disabled: true
	});
	$("#feedbackHeader").css('cursor', 'default');
};

MCMS.closeFeedback = function () {
	$(".feedBackContent").hide();
	$("#popupLoader").empty().removeClass().addClass("h-100 page-section").hide();
	markcompletepage.trigger("markcompletepage")
};

MCMS.showTickOnly = function () {
	MCMS.markPageComplete();
	for (c = 0; c < MCMS.userAnswer.length; c++) {
		for (var i = 0; i < MCMS.userAnswer[c].length; i++) {
			var option = MCMS.optionArr[c][MCMS.userAnswer[c][i] - 1];
			option.showTickCross("mcssTick");
		}
	}
}

MCMS.showSolution = function () {
	MCMS.markPageComplete();
	for (c = 0; c < MCMS.questionData.optionsGroup.length; c++) {
		for (var i = 0; i < MCMS.questionData.optionsGroup[c].group.length; i++) {

			var option = MCMS.optionArr[c][i];
			if (jQuery.inArray((i + 1), MCMS.correctAnswer[c]) >= 0)
				option.showTickCross("mcssTick");
			else
				option.showTickCross("mcssCross");
		}
	}
}


MCMS.markPageComplete = function () {
	if (!MCMS.activityCompleted) {
		MCMS.activityCompleted = true;
		eventMgr.dispatchCustomEvent(MCMS, "templateActivityCompleted", "", "");
	}
}
//randomization
MCMS.randomizeArr = function (arr) {
	var randomizeArr = arr.concat();
	randomizeArr.sort(MCMS.shuffle);
	return randomizeArr;
};

MCMS.shuffle = function () {
	var ran = 0.5 - Math.random();
	return ran;
};

MCMS.chkActivityCompletion = function () {

}


var init_activity = (function () {
	this.init = function (data, callback) {
		_aData = data;
		eventMgr.addControlEventListener(MCMS, "templateActivityCompleted", MCMS.chkActivityCompletion);
		MCMS.initMCMS(_aData);
		MCMS.addListeners();
		markcompletepage = $('#shell_wrapper');
		markcompletepage.off("markcompletepage").on("markcompletepage", function (e) {
			markcompletepage.off("markcompletepage");
			if (callback) {
				callback();
			}

		})
	};
	return this;

})