// JavaScript Document
$(document).ready(function () {

	$(".iPage").hide();
	$(".alertBox").hide();
	//$(".tg-mode").show();
	$(".addToTestContainer").hide();
	$(".addToPrintContainer").hide();

	/* var totalShuffleArr = [];
	totalShuffleArr.push({num:'1', id:2, questTxt:'wew', questImg:'sdfsd', questAns:'sdfsdfs', questAnsImg:'sddf', questMark:'12', title:'12121', addedQuest:true});
	totalShuffleArr.push({num:'2', id:2, questTxt:'wew', questImg:'sdfsd', questAns:'sdfsdfs', questAnsImg:'sddf', questMark:'12', title:'12121', addedQuest:true});
	totalShuffleArr.push({num:'3', id:2, questTxt:'wew', questImg:'sdfsd', questAns:'sdfsdfs', questAnsImg:'sddf', questMark:'12', title:'12121', addedQuest:true});
	totalShuffleArr.push({num:'4', id:2, questTxt:'wew', questImg:'sdfsd', questAns:'sdfsdfs', questAnsImg:'sddf', questMark:'12', title:'12121', addedQuest:true});
	totalShuffleArr.sort(function() {
		   return .5 - Math.random();
	   });
	console.log(totalShuffleArr[0]) */
	$('.homeScreen_text .chapterTitle').text(tgTitle);
	//   setAllEvents();
	//----------temp
	//$("#homePage").remove();
	/* setAddToDetail(); */
});

var tg_MODE = "";//auto/manual	
var homePage;
var allSubs = [];
var checked = false;
var bcrumID = [];
var bcrumVal = [];
function setAllEvents() {
	//$("#homePage").on("click", createTestGenerator);
	//$("#startBtn").on("click", createTestGenerator);

	// new code starts here
	$(".dataLoading").hide();
	$(".dataLoaded").show();



	$(".closeButton").on("click", function () {

		if ($(".closeButton").text() === "Close List") {
			$(this).text("Open List");
			$(".jstree-default").css({
				left: "-41rem"
			})
		} else {
			$(this).text("Close List");
			$(".jstree-default").css({
				left: "0"
			})
		}
	});

	// new code ends here

	$("#startBtn").on("click", function () {
		$(".tg-mode").show();
	});
	$(".tg-mode .auto-btn").on("click", function () {
		tg_MODE = "auto";
		setAutoMode();
	});
	$(".tg-mode .manual-btn").on("click", function () {
		tg_MODE = "manual";
		$(".tg-mode").remove();
		createTestGenerator();
	});
}

function createTestGenerator() {
	homePage = $("#homePage");
	$("#homePage").remove();

	$('.iPage').show();
	/* $(".rtContainer").show();
	$("#tree").show(); */

	createArrayFromObj();

	$.jstree.defaults.core.themes.dots = false;

	$('#tree').jstree({
		'core': {
			'data': mainArr
		}
	});
	$('#tree').on("select_node.jstree", setTreeClick);


	var img = $('<img id="headLogo">');
	img.attr('src', "images/RS-Icon.png");
	$("#header").append("<div class='logoSection'></div>");
	$(".logoSection").append(img);
	//$(".logoSection").append("<p>Ratna Sagar</p>");

	var headerBtns = $('<div id="wrapper-button"> <button id="homeBtn1" class=btn-prop onclick="window.location.reload()">Home</button> <button id="previewTest" class=btn-prop>Preview Test </button><button id="lastQuest-btn" class="btn-prop">Last Paper</button> <button id="QuesSelectedBtn" class=btn-prop><span class="btn-prop-inner">Total Questions Selected</span></button> <button id="cartItems" class="btn-prop"><span class="btn-prop-inner">(0)<span></button> <p class="total_number">Total number of questions in book 6 - 510</p></div>');

	$("#header").append(headerBtns);

	setHeaderText();

	$('#header #lastQuest-btn').on('click', function () {
		console.log('last PAPER')
		loadFile();
	});
	setFolderStruct('x0');
	setBreadCrum('x0');
}
function setHeaderText() {
	$('#header #QuesSelectedBtn').css("cursor", "default");
	$('#header #cartItems').css("cursor", "default");
	$('#lastQuest-btn').css("cursor", "default");

	if (addedQuestions.length == 0)
		$('#header #previewTest').prop('disabled', true).css("cursor", "default").fadeTo(500, 0.6);
	else {
		$('#header #previewTest').prop('disabled', false).css("cursor", "pointer").fadeTo(500, 1);
		$('#header #cartItems span').text('(' + addedQuestions.length + ')');
		//$('#header .total_number').text('Total number of questions in '+ questions[0][treeStructure[0]]+ ' - '+ questions.length);
	}

	$('#header .total_number').text('Total number of questions in ' + questions[0][treeStructure[0]] + ' - ' + questions.length);

	console.log('setHeaderText==', checkLastPage())
	if (!checkLastPage())
		$('#lastQuest-btn').prop('disabled', true).css("cursor", "default").fadeTo(500, 0.6);
	else
		$('#lastQuest-btn').prop('disabled', false).css("cursor", "pointer").fadeTo(500, 1);
}
function setTreeClick(e, data) {
	console.log("node_id: " + data.node.id);
	data.instance.deselect_node(data.node);
	setBreadCrum(data.node.id);
}
function setBreadCrum(iD) {
	var i = 0;
	var breadCrumArr = [];
	var breadCrumIdArr = [];
	var parentID = "";
	for (; i < mainArr.length; i++) {
		if (mainArr[i].id == iD) {
			breadCrumArr.push(mainArr[i].text);
			parentID = mainArr[i].parent;
			breadCrumIdArr.push(mainArr[i].id);
			//i--;
			break;
		}
	}

	if (i > 0) {
		while (mainArr[i].parent != idStr + 0) {
			if (mainArr[i].id == parentID) {
				parentID = mainArr[i].parent;
				breadCrumArr.push(mainArr[i].text);
				breadCrumIdArr.push(mainArr[i].id);
			}
			i--;
		}
		if (breadCrumArr.indexOf(mainArr[i].text) < 0) {
			breadCrumArr.push(mainArr[i].text);
			breadCrumIdArr.push(mainArr[i].id);
		}
		breadCrumArr.push(questions[0][treeStructure[0]]);
		breadCrumIdArr.push("x0");
	}
	if ($(".breadcrumb").length > 0)
		$(".breadcrumb").remove();
	var str = "<ul class=breadcrumb>";
	for (var j = breadCrumArr.length - 1; j >= 0; j--) {
		str += "<li><a class=bread" + breadCrumIdArr[j] + " href=#>" + breadCrumArr[j] + "</a></li>";
	}

	str += "</ul>";
	$("#breadCrum").append(str);

	$('#breadCrum').find('li a').on('click', function (e) {
		console.log("bread crum click=" + $(e.target).attr('class').split("bread")[1]);
		iD = $(e.target).attr('class').split("bread")[1];
		setBreadCrum(iD);
	});
	setFolderStruct(iD);

	//check to set the question details.....
	if ($('#questBase').find('.folderLogo').length == 0)
		setQuestionDetail(iD, breadCrumArr); //this function is in questionDetail.js file
}
function setFolderStruct(id) {
	if ($('#questBase').length > 0)
		$("#questBase").empty();
	let allSubDone = allSubs.length;
	for (var i = 0; i < mainArr.length; i++) {
		if (mainArr[i].parent == id) {
			$("#questBase").append('<div id="folderLogo' + mainArr[i].id + '" class=folderLogo></div>')
			var imgTag = $('<img class=folderImg>');
			imgTag.attr('src', "images/folder-icon.png");
			var pTag = $('<p>' + mainArr[i].text + '</p>');
			if (!allSubDone && id == 'x0') {
				allSubs.push(mainArr[i].text);
			}
			$('#folderLogo' + mainArr[i].id).append(imgTag);
			$('#folderLogo' + mainArr[i].id).append(pTag);
			$('#questBase').find('#folderLogo' + mainArr[i].id).on('click', folderClickEvt);
			$('#tree').jstree('open_node', mainArr[i].parent, function (e, data) {
				//$('#tree').jstree('select_node', mainArr[i].parent);
			}, true);
		}
	}
	$('#tree').jstree('open_node', mainArr[0].id, function (e, data) {
		//$('#tree').jstree('select_node', mainArr[i].parent);
	}, true);
}
function folderClickEvt(e) {
	var id;
	if (e.target == this)
		id = $(e.target).attr("id").split("folderLogo")[1];
	else
		id = $(e.target).parent().attr("id").split("folderLogo")[1];

	setFolderStruct(id);
	setBreadCrum(id);
}
var idStr = "x";
var idNum = 0;
var mainArr = [];
var questionsTemp = [];
function createArrayFromObj() {
	questionsTemp = questions.concat();

	mainArr.push({ "id": idStr + 0, "parent": "#", "text": questions[0][treeStructure[0]] });


	while (questionsTemp.length > 0) {
		var tempQuest = getSimilarArr(questionsTemp[0])

		for (var i = 0; i < tempQuest.length; i++) {
			var chapter = tempQuest[i][treeStructure[1]];
			var quest = tempQuest[i];

			for (var j = 1; j < treeStructure.length; j++) {
				var questValue = quest[treeStructure[j]];

				if (j == 1) {
					var pId = idStr + 0;
					if (!checkRepeat(chapter, idStr + (idNum + 1), pId, quest[treeStructure[j]])) {
						idNum += 1;
						mainArr.push({ "id": idStr + idNum, "parent": pId, "text": questValue });
					}
				}
				else {
					var pId = getId(chapter, quest[treeStructure[j - 1]])
					if (!checkRepeat(chapter, idStr + (idNum + 1), pId, quest[treeStructure[j]])) {
						idNum += 1;
						mainArr.push({ "id": idStr + (idNum), "parent": pId, "text": quest[treeStructure[j]] });
					}
				}
			}
		}
	}

	function getId(chapter, val) {
		var id = "";
		for (var k = mainArr.length - 1; k >= 0; k--) {

			if (mainArr[k].text == val) {
				id = mainArr[k].id;
				break;
			}
			if (mainArr[k].text == chapter)
				break;
		}
		return id;
	}
	function getSimilarArr(arrTemp) {
		var similarArr = [];

		var i = 0;
		while (i < questionsTemp.length) {
			var bool = true;
			for (var j = 0; j < treeStructure.length - 1; j++) {
				if (questionsTemp[i][treeStructure[j]] != arrTemp[treeStructure[j]]) {
					bool = false;
					break;
				}
			}
			if (bool) {
				similarArr.push(questionsTemp[i]);
				questionsTemp.splice(i, 1);
				i = 0;
			} else {
				i += 1;
			}
		}
		return similarArr;
	}
	function checkRepeat(chapter, iD, parentID, val) {
		var bool = false;

		for (var k = mainArr.length - 1; k >= 0; k--) {
			if (mainArr[k].parent == parentID && mainArr[k].text == val) {
				bool = true;
				break;
			}
			if (mainArr[k].value == chapter)
				break;
		}
		return bool;
	}
}
/* function createArrayFromObj(){
	questions = questionsArr;
	
	$('script').each(function(i){
		if($(this).attr('src') == 'js/config.js'){
			$(this).remove();
		}
	});
	
	mainArr.push({"id":idStr+0, "parent":"#", "text":questions[0][treeStructure[0]]});
	for(var i=0; i<questions.length; i++)
	{
		var chapter = questions[i][treeStructure[1]];
		var quest = questions[i];
		
		for(var j=1; j<treeStructure.length; j++)
		{
			var questValue = quest[treeStructure[j]];
			
			if(j==1 && getId(questValue)==""){
				var pId = idStr+0;
				if(!checkRepeat(chapter, idStr+(idNum+1), pId, quest[treeStructure[j]])){
					idNum += 1;
					mainArr.push({"id":idStr+idNum, "parent":pId, "text":questValue});
				}
			}
			else{
				var pId = getId(chapter, quest[treeStructure[j-1]])
				if(!checkRepeat(chapter, idStr+(idNum+1), pId, quest[treeStructure[j]])){
					idNum += 1;
					mainArr.push({"id":idStr+(idNum), "parent":pId, "text":quest[treeStructure[j]]});
				}
			}
		}
	}
	
	function getId(chapter, val){
		var id="";
		for(var k=mainArr.length-1; k>=0; k--)
		{
			
			if(mainArr[k].text == val){
				id = mainArr[k].id;	
				break;
			}
			if(mainArr[k].text == chapter)
				break;
		}
		return id;
	}
	function checkRepeat(chapter, iD, parentID, val){
		var bool=false;
		
		for(var k=mainArr.length-1; k>=0; k--)
		{
			if(mainArr[k].parent == parentID && mainArr[k].text == val){
				bool = true;	
				break;
			}
			if(mainArr[k].value == chapter)
				break;
		}
		return bool;
	}
} */