var allQuestions;
var userImageLogo = '';
var autoDB;
var tgType = "";
var selectedmeta = [];
var finalmeta = [];
var metaCounter = 0;
var perPage = 10;
var totalPage = 0;
var pager = null;
var children = null;
var startAt;
var endOn;
var _meta = false;
var myArr = [];
var worksheetType = "";
var totalCat_marks;

function uniqueArray(arr) 
{
    var a = [];
    for (var i=0, l=arr.length; i<l; i++)
        if (a.indexOf(arr[i]) === -1 && arr[i] !== '')
            a.push(arr[i]);
    return a;
}

function startScreen() 
{
	tgType = 'manual';
	$("#typeAuto").remove();
	document.getElementById('startScreen').style.display = "none";
	document.getElementById('activityArea').style.display = "block";
	
	setHeightFix();
	window.testType = "testpaper";
	
	$($('.input-mini')[0]).prop('checked', true);
	$($('.input-mini')[0]).click();
	
	//$("#totalQuestionsInTG").text(allQuestions().count());
}

function startAuto() {
	//$("#testgenerator-type").hide();
	tgType = 'auto';
	$("#activityArea").remove();
	document.getElementById('startScreen').style.display = "none";
	document.getElementById('typeAuto').style.display = "block";

	getChapters();

	 var outcomes = getUniqueData('outcome');
	var outcomeHTML = "";
	for(var i=0; i<outcomes.length; i++) {
		outcomeHTML += '<li class="checkbox">' +
			'<label class="checkbox" for="outcome-auto-' + outcomes[i]  + '">' + 
				'<input id="outcome-auto-' + outcomes[i]  + '" type="checkbox" value="' + outcomes[i]  + '" checked="checked" class="input-mini"> ' + outcomes[i] +
			'</label>' +
		'</li>';
	}
	$("#auto-filter-outcome ul").html(outcomeHTML);
		
	var categories = outcomes;
	
	var difficulty = getUniqueData('difficulty');
	difficulty = ["E", "M", "H"]
	var difficultyHTML = "";
	var difficultyObj = {
		'E': 'Easy',
		'M': 'Medium',
		'H': 'Hard'
	}
	
	for(var i=0; i<difficulty.length; i++) {
		difficultyHTML += '<li class="checkbox">' + 
			'<label class="checkbox" for="difficulty-auto-' + difficulty[i]  + '">' + 
				'<input id="difficulty-auto-' + difficulty[i]  + '" type="checkbox" value="' + difficulty[i]  + '" checked="checked" class="input-mini"> ' + difficultyObj[difficulty[i]] +
			'</label>' +
		'</li>';
	}
	$("#auto-filter-difficulty ul").html(difficultyHTML);
	
	/* document.getElementById('chooseAll').checked = false;
	document.getElementById('select-all-qt-auto').checked = false;
	document.getElementById('select-all-qt-auto-tg').checked = false; */
	
	setHeightFix();
		
	for(var ii = 0; ii< questions.length; ii++)
	{
		if(questions[ii].metadata != '')
		{
			$('#auto-filter-metadata').removeClass('remove');
		}
	}
	append_metaFeild();
}

function selectTestType()
{
	$(window).scrollTop(0);
	if($('#manual_mode').prop('checked'))
	{
		startScreen();
	}
	else if($('#auto_mode').prop('checked'))
	{
		startAuto();
	}
	
	//$("#testgenerator-type").show();
}

function closePreview() {
	$('#level3').hide();
	$('#level2').show();
	$('#userInfo').parent().children().show().end().end().hide();
}

function showPreview()
{
	/* if($('.editingmode-on').length)
	{
		showMsgBox("Some unsaved changes are there. Please save it before finalising the test.");	
		return;
	} */
	
	//$('._edit_cat_title').hide();
	checkParent();
	
	checkParentLast();
	
	$('#level2, #auto-level-2').hide();
	$('#level3, #auto-level-3').show();
	
	getUserInfoDataToNextScreen();
	
	$(_parentLast).find('#previewHTML .mx-tools, #previewHTML .question-info').remove();
	
	$(_parentLast).find('#previewHTML .marksInput').css({
		'pointer-events':'none',
		'cursor':'pointer'
	});
	
	$(_parentLast).find('#previewHTML .marksInput').each(function () {
		$(this).val($(this).parent().parent().attr('data-marks'));
	});
	
	$('.summary-selection').hide();
	//$(_parentLast).find("#previewHTML").height('79%');
	
	
	//$('.marksInput').addClass('_disabled');
}

function loadImage() {
	var input, file, fr, img;

	if (typeof window.FileReader !== 'function') {
		write("The file API isn't supported on this browser yet.");
		return;
	}

	input = document.getElementById('imgfile');
	
	if (!input) {
		write("Um, couldn't find the imgfile element.");
	}
	else if (!input.files) {
		write("This browser doesn't seem to support the `files` property of file inputs.");
	}
	else if (!input.files[0]) {
		write("Please select a file before clicking 'Load'");
	}
	else {
		file = input.files[0];
		fr = new FileReader();
		fr.onload = createImage;
		fr.readAsDataURL(file);
	}

	function createImage() {
		img = new Image();
		img.onload = imageLoaded;
		img.src = fr.result;
	}

	function imageLoaded() {
		var canvas = document.getElementById("canvas")
		canvas.width = img.width;
		canvas.height = img.height;
		var ctx = canvas.getContext("2d");
		ctx.drawImage(img,0,0);
		//document.body.innerHTML += '<img src="' + canvas.toDataURL("image/png") + '">';
		userImageLogo = '<img class="userDisplayLogos1" src="' + canvas.toDataURL("image/png") + '">';
	}

	function write(msg) {
		console.log(msg);
	}
}

function getUserInfoDataToNextScreen()
{
	$(_parentLast).find('#previewHTML').html($(_parent).find('#pdfPreview').html()).promise().done(function()
	{
		$(_parentLast).find('#previewHTML').children().show();

		var num;
		setNumberingPreview();
	});

	SetUserInfoForPrint($(_parentLast));	
};

function getImgWidth(imagePath)
{
	var img = document.createElement('img');
	img.setAttribute('src', imagePath);
	document.body.appendChild(img);
	var width = img.naturalWidth;
	return width;
}

function setScrollbar()
{
	return;
	/* $("#collectionList").height($("#collectionList").height());
	$("#collectionList").width($("#collectionList").width());
	$("#collectionList").mCustomScrollbar("destroy");
	$("#collectionList").mCustomScrollbar({
		axis:"x", // vertical and horizontal scrollbar
		theme:"dark",
		scrollButtons:{
			enable: true
		}
	}); */
}

function selectAllQuestion() 
{
	$("#questionsViewer input[type='checkbox']").not(':checked').trigger('click');
}

function getChapters () {

	var $lpanel = $("#chapterList");
	$lpanel.empty();
	var distinctSubject = allQuestions().distinct('subject');
	var distinctBook = allQuestions().distinct('book');
	var counter = 0;
	for(var z=0; z<distinctSubject.length; z++) {
		var querySample = "";
		var subject = distinctSubject[z];
		var book = distinctBook[z];

		//console.log(distinctSubject[z]);console.log(distinctBook[z]);
		var distinctBook = allQuestions({"subject": subject}).distinct('book');

		for(var zz=0; zz<distinctBook.length; zz++) {
			
			var book = distinctBook[zz];
			if(distinctBook.length > 1 || distinctSubject.length > 1) {
				var headingTitle = "<li class='static-heading-lpanel'>" + book + "</li>";
				$lpanel.append(headingTitle);
			}

			var chapters = allQuestions({"subject": subject},{"book":book}).distinct('chapter');

			for(var i=0; i<chapters.length; i++){
				$lpanel.append('<li class="checkbox">\
					<label class="checkbox" for="chapter'+counter+'">\
						<input id="chapter'+counter+'" type="checkbox" value="" onClick="ifSelected(this)" class="input-mini">'+ chapters[i]+'\
					</label>\
				</li>');
				counter++;
			}
		}
	}

	setHeightFix();
}

function createChapterList () {

	var $lpanel = $("#collectionList #container");
	$lpanel.empty();
	var distinctSubject = allQuestions().distinct('subject');
	var distinctBook = allQuestions().distinct('book');
	var counter = 0;
	for(var z=0; z<distinctSubject.length; z++) {
		var querySample = "";
		var subject = distinctSubject[z];
		var book = distinctBook[z];

		//console.log(distinctSubject[z]);console.log(distinctBook[z]);
		var distinctBook = allQuestions({"subject": subject}).distinct('book');

		for(var zz=0; zz<distinctBook.length; zz++) {
			
			var book = distinctBook[zz];
			if(distinctBook.length > 1 || distinctSubject.length > 1) {
				var headingTitle = "<li class='static-heading-lpanel'>" + book + "</li>";
				$lpanel.append(headingTitle);
			}

			var chapters = allQuestions({"subject": subject},{"book":book}).distinct('chapter');
			for(var i=0; i<chapters.length; i++){
				$lpanel.append('<li class="checkbox">\
					<label class="checkbox" for="chapter'+counter+'">\
						<input id="chapter'+counter+'" type="radio" value="" data-book=\''+book+'\' name ="ch_list" onClick="selections(this)" class="input-mini"><span class="chaptersss">'+ chapters[i]+'\
					</span></label>\
				</li>');
				counter++;
			}
		}
	}
	
	setHeightFix();
}

function selections(_this)
{
	//$('.checkbox input').prop('checked', false);
	//$(_this).prop('checked', true);
	
	if($(_this).prop('checked'))
	{	
		handleStructure($(_this).attr('data-book'), $(_this).parent().find('span').text());
	}
}

function selectQuestions(){
	var statusSelect = $('#chooseAll').prop('checked');
	if(statusSelect == true){
		$('#chapterList .input-mini').prop('checked', 'true');
	}
	else{
		$('#chapterList .input-mini').removeAttr('checked');
	}
}

function checkSelection(){
	var selectionCheck = $('#sidePanel-auto .input-mini:checked').length;
	if (selectionCheck == 0) {
		showMsgBox("Please select chapter(s) first.");
		return false;
	}
	
/* 	var selectionOutcome = $("#auto-filter-outcome .input-mini:checked").length;
	if(selectionOutcome == 0) {
		showMsgBox("Select at least one Learning Outcome");
		return false;
	} */
	
	/* var selectionDifficulty = $("#auto-filter-difficulty .input-mini:checked").length;
	if(selectionDifficulty == 0) {
		showMsgBox("Select at least one difficulty");
		return false;
	} */

	autoSelectMarks();
	$("#auto-reset-btn").show();
}

function autoSelectMarks() {
	$("#auto-page1").hide();
	
	showAutoPage = true;
	setAutoPagePosition();
	//auto_page_responsive();
	
	$("#sidePanel-auto").addClass('readonly-pannel');
	if(window.modeEnableType == 'testpaper') {
		$("#auto-testpaper").prop('checked', true);
	} else {
		$("#auto-worksheet").prop('checked', true);
	}

	loadWorksheet();

	var meta_key_words = "";
	_meta = false;
	
	finalmeta = uniqueArray(finalmeta);
	meta_key_words = finalmeta.join(', ');
	
	$('.metaauto').each(function (e) 
	{
		if($(this).val() == "") _meta = false;
		else _meta = true;
	})

	//if(_meta) $('#metaInfo').html('Showing results for: <b>' + meta_key_words + '</b>');
	//else $('#metaInfo').html('');
}

function selectAutoAgain() {
	$("#auto-page2").hide();
	showAutoPage = false;
	$("#auto-page1").show();
	$("#sidePanel-auto").removeClass('readonly-pannel');
	$("#auto-reset-btn").hide();
	finalmeta = [];
}

function showOptions(_this, checkStatus, selectElement, selectAllEle){
	
	/* if($(_this).is(':visible'))
	{ */
	if(tgType== 'manual') return;
	//console.log(selectElement, selectAllEle);
		if(checkStatus == true){
			$(selectElement).removeAttr('disabled');
		}
		else{
			$(selectElement).attr('disabled', 'disabled');
			$("#" + selectAllEle).prop('checked', false);
		}
		
	/* } */
	if(worksheetType == 'testpaper') {
		calulateTotalMarks();
	}
}


function ifSelected(ele) {
	if(ele.checked == false) {
		document.getElementById('chooseAll').checked = false;
	}
}

function loadWorksheet() {
	//var worksheetType = document.querySelector('input[name="worksheet-selection"]:checked').value;
	var selectedList = "";
	worksheetType = 'testpaper';
	
	$("#select-all-qt-auto, #select-all-qt-auto-tg").prop("checked", false);
	
	var selectedChapters = $("#chapterList :checked").map(function(i, e) {
		return $.trim(e.parentNode.textContent)
	}).get();
	
	autoDB = new TAFFY();
	
	/* var selectedDifficutly = $("#auto-filter-difficulty :checked").map(function(i, e) {
		return this.value
	}).get(); */
		
	var selectedCategory = $("#auto-filter-category :checked").map(function(i, e) {
		return this.value
	}).get();
	/* 
	var selectedOutcome = $("#auto-filter-outcome :checked").map(function(i, e) {
		return this.value
	}).get(); */
	
/* 	selectedmeta = $("#auto-filter-metadata input").map(function(i, e) {
		return this.value.toLowerCase()
	}).get(); */ 
	
	var myArr = [];
	
	for(var i=0; i<selectedChapters.length; i++) {
		
		allQuestions({'chapter': selectedChapters[i]}).each(function(r) 
		{			
			//var categoryIndex = r.outcome;
			//var difficultyIndex = selectedDifficutly.indexOf(r.difficulty);
			//var outcomeIndex = selectedOutcome.indexOf(r.outcome);
			//var _meta = r.metadata.split('||').join(',').toLowerCase();
			//var metaIndex = _meta.indexOf(selectedmeta[0]);
			
			/* if(outcomeIndex != -1 && difficultyIndex != -1 && categoryIndex != -1)
			{
				if(selectedmeta[0] != "")
				{
					if(metaIndex != -1)
					{
						defineTypeSequence(r);
						myArr.push(r);
					}
				}
				else 
				{
					defineTypeSequence(r);
					myArr.push(r);	
				}
			} */
				
				defineTypeSequence(r);
				myArr.push(r);
		});
	}
	myArr.sort(sort_ind);
	
	for(var k in myArr) autoDB.insert(myArr[k]);
	
	if(autoDB().count() == 0) {
		//console.log('bad filter. no questions.')
	}
	
	var mytypes = [];
	var types = autoDB().distinct('type');
	
	//console.log(types, autoDB());
	allTitle = autoDB().distinct('question');
	mytypes = types;
	$("#auto-worksheet-details, #auto-testpaper-details").empty();
		
	if(worksheetType == "worksheet") {
		$("#section-worksheet").show();
		$("#section-testpaper").hide();
		
		var worksheetHTML = "";
		for(var i=0; i<types.length; i++) 
		{
			var selectHTML = "";
			var total = autoDB({type: types[i]}).count();
			var selectHTML = getSelect('value-edit-', total, i+1);
			worksheetHTML += '<tr>\
								<td>\
									<label class="checkbox" for="value-checkmark-' + (i+1) + '">\
									<input id="value-checkmark-' + (i+1) + '" type="checkbox" value="" class="input-option" onclick="showOptions(this, this.checked, \'#value-edit-' + (i+1) + '\', \'select-all-qt-auto\')">' + types[i] + '</label>\
								</td>\
								<td class="mxio">' + selectHTML + '</td>\
							</tr>';
		}
		
		$("#auto-worksheet-details").append(worksheetHTML);		
	}
	else 
	{
		$("#section-worksheet").hide();
		$("#section-testpaper").show();
		insertTypes(All_types, 0);
	}
}

function insertTypes(types, selection)
{
	var testpaperHTML = "";
	var Match_types = autoDB().distinct('type');
	var result = [];
	
	All_typess.filter(function(key1,index1)
	{
		Match_types.filter(function(key2,index2)
		{
			if(key2 == key1) result.push(key2);
		})
	})
	
	Match_types = [];
	Match_types = result.concat();
	
	for(var i=0; i<types.length; i++) 
	{
		if(Match_types[i] != undefined)
		{
			var selectHTML = "";

			var total = autoDB({type: Match_types[i]}).count();
			var selectHTML = getSelect('value-edit-', total, i+1);
			
			testpaperHTML += '<tr>\
								<td>\
									<label class="checkbox" for="value-checkmark-' + (i+1) + '">\
									<input id="value-checkmark-' + (i+1) + '" type="checkbox" value="" class="input-option _checkbox" onclick="showOptions(this, this.checked, \'#value-input-' + (i+1) + ', #value-edit-' + (i+1) + '\', \'select-all-qt-auto-tg\')"><p class="_check">' + Match_types[i] + '</p></label>\
								</td>\
								<td class="mxio">' + selectHTML + '</td>\
								<td>x <input type="text" disabled id="value-input-' + (i+1) + '" class="marksper" onkeyup="calculateMarks(' + (i+1) + ')" onkeypress="return isNumberKey(event)" /></td>\
								<td>= <span id="value-marks-' + (i+1) + '">0</span></td>\
							</tr>';
		}
	}
		
	$("#auto-testpaper-details").append(testpaperHTML);
	
	$("#auto-duration").val('');
	$("#auto-maxmarks").val('');
	$("#total-marks-obj").val('');
	setHeightFix();
	
	if(selection == 1)
	{
		$('._checkbox').prop('checked', true);
		$('.selectall, ._checkbox').hide();
		
		$('.mxio').addClass('diaableitem');
		
		$('.mxio').each(function (index, element){
			$(this).find('select').prop('selectedIndex', $(this).find('select').children().length-1);
		})
		
		$('.marksper').each(function (index, element){
			$(this).removeAttr('disabled');
		});
	} 
}

function calculateMarks(lop) {
	var totalQuestion = $("#value-edit-" + lop).val();
	var marks = $("#value-input-" + lop).val();
	var total = totalQuestion * marks;
	
	$("#value-marks-" + lop).text(total);
	calulateTotalMarks();
}

function calulateTotalMarks() {
	var total = 0;
	$("#auto-testpaper-details input[type='checkbox']:checked").each(function(i, e) {
		var $parent = $(e).parents('tr');
		
		var totalQuestions = $parent.find('select').val();
		var marks = $parent.find('.marksper').val();
		
		$parent.find('span').text(totalQuestions * marks);
		
		total += parseInt($(e).parents('tr').find('span').text());
	});
	
	document.getElementById('auto-maxmarks').value = total;
	//document.getElementById('total-marks-obj').textContent = total;
}

function getSelect(eleId, total, idIndex) {
	
	if(total == 0) {
		return "";
	}
	
	var selectHTML = "<label><select onChange='calulateTotalMarks()' id='" + eleId + idIndex + "' disabled>";
	for(var i=1; i<=total; i++) {
		selectHTML += "<option value='" + i + "'>" + i + "</option>"
	}
	selectHTML += "</select></label>";
	
	return selectHTML;
}

function submitAutoTGWorksheet() {
	used_Save = false;
	var totalSelection = $("#auto-worksheet-details .input-option:checked").length;
	if(totalSelection == 0) {
		showMsgBox("Please select Question Type");
		return false;
	}
	
	var autoTGList = $("#auto-worksheet-details .input-option:checked").map(function(i, e) {
		var obj = {};
		obj['title'] = $.trim($(this).parent().text());
		obj['total'] = $(this).parents('tr').find('select').val()
		return obj
	}).get();
		
	var selectedAutoIds = [];
	for(var i=0; i<autoTGList.length; i++) {
		var ids = [];

		autoDB({type: autoTGList[i].title}).each(function(r) {
			ids.push(r.id);
		});
		
		var resultIds = randomList(ids, autoTGList[i].total);
		
		selectedAutoIds.push.apply(selectedAutoIds, resultIds);
	}
	
	var comprehension_ids=[]; 
	var vocabulary_ids=[]; 
	var writing_ids=[]; 
	var grammar_ids=[];
	
	for(i =0;i< selectedAutoIds.length;i++)
	{
		autoDB({id: selectedAutoIds[i]}).each(function(r) {
			
			if(r.outcome == 'Understanding'){comprehension_ids.push(selectedAutoIds[i]);}
			if(r.outcome == 'Remembering'){vocabulary_ids.push(selectedAutoIds[i]);}
			if(r.outcome == 'Analysing'){grammar_ids.push(selectedAutoIds[i]);}
			if(r.outcome == 'Applying'){writing_ids.push(selectedAutoIds[i]);}
		});
	}
	var selectedAutoIds_categorized = [];
	for(i =0;i< comprehension_ids.length;i++){selectedAutoIds_categorized.push(comprehension_ids[i]);}
	for(i =0;i< vocabulary_ids.length;i++){selectedAutoIds_categorized.push(vocabulary_ids[i]);}
	for(i =0;i< grammar_ids.length;i++){selectedAutoIds_categorized.push(grammar_ids[i]);}
	for(i =0;i< writing_ids.length;i++){selectedAutoIds_categorized.push(writing_ids[i]);}
	
	selectedAutoIds = selectedAutoIds_categorized;
	
	/* $("#student-version").attr('checked', 'checked');
	$("#student-version-m").attr('checked', 'checked');
 */
	difficultySummary = {
		'E': 0,
		'M': 0,
		'H': 0
	}
	categorySummary = {};
	outcomeSummary = {};
	totalMarksSummary = 0;
	window.testType = "worksheet";
	addToTestAuto(selectedAutoIds);
	//setNumbering();
}

function submitAutoTGTestpaper() 
{
	used_Save = false;
	var duration = $("#auto-duration").val();
	if(duration == "") {
		showMsgBox("Please enter duration.");
		return false;
	}
	
	if(duration == 0) {
		showMsgBox("Duration can not be 0.");
		return false;
	}
	
	if($('#auto-maxmarks').val() == '') 
	{
		showMsgBox("Please enter marks.");
		return false;
	}
	
	if(window.tgType == "auto")
	{		
		var totalSelected = $("#auto-testpaper-details input[type='checkbox']:checked").length;
		if(totalSelected == 0) {
			showMsgBox("Please select at least one Question Type.");
			return false;
		}
	}

	var marksTracker = {};
	
	var flag = false;
	var autoTGList = [];
	
	$("#auto-testpaper-details input[type='checkbox']:checked").each(function(i, e) {
		
		var marks = $(e).parents('tr').find('.marksper').val();
		var title = $.trim($(e).parent().text());
		var total = $(e).parents('tr').find('select').val();
		
		allQuestions({type: title}).each(function(r, i) 
		{
			r.mark = marks;
		});
		marksTracker[title] = marks;
		
		if(marks == "") {
			flag = true;
			showMsgBox("Please enter marks per question for all selected question type.");
			return false;
		}
		if(marks == 0) {
			flag = true;
			showMsgBox("Please enter marks more then 0.");
			return false;
		}
		autoTGList.push({
			'title': title,
			'total': total,
			'marks': marks
		});		
	});

	if(flag == true) {
		return false;
	}

	var selectedAutoIds = [];
	for(var i=0; i<autoTGList.length; i++) 
	{
		autoDB({type: autoTGList[i].title}).update({'mark': String(autoTGList[i].marks)});

		var ids = [];
		autoDB({type: autoTGList[i].title}).each(function(r) {
			ids.push(r.id);
		});
		
		var resultIds = randomList(ids, autoTGList[i].total);		
		selectedAutoIds.push.apply(selectedAutoIds, resultIds);
	}
	
	window.tgduration = duration;
	window.testType = "testpaper";
	$('#auto-page2').hide();
	
	showAutoPage = false;
	
	if(window.tgType == "auto") addToTestAuto(selectedAutoIds); 
	else 
	{
		showCart();
		/* testBank = [];
	
		for(var i=0; i<selectedAutoIds.length; i++) 
		{
			testBank.push(String(selectedAutoIds[i]));
		} */
		
		fetch_Data();
		ModifyUniqueTypeArr(uniquetype);
			
		setFilterArr();
		
		setNumbering();
		prepareSummary();
		disableReplaceBtn();
		addMarksInputEvent();
	}
}

function randomList(arr, len) {
	var randomQuestion = shuffleArray(arr)
	var resultArr = randomQuestion.slice(0, len);
	return resultArr;
}

function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
}

function showMsgBox(msg) {
	jQuery.confirm({
		title: msg,
		content: '',
		buttons: {
			Ok: function () {
			}
		}
	});
}

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}

function selectAll(status, selector) {
	if(status == true) {
		$(selector).find('input[type="checkbox"]').not(':checked').trigger('click');
	} else {
		$(selector).find('input[type="checkbox"]:checked').trigger('click');
	}
}

function convertMinsToHrsMins (minutes) {
	var result = "";
	var h = Math.floor(minutes / 60);
	var m = minutes % 60;
	
	if(h != 0) {
		result = h + ' hour ';
	} 
	if(m != 0) {
		result += m + ' mins';
	}
	
	return $.trim(result);
}

function backToEdit() 
{
	$('#activityArea').show();
	if(used_Save_Print)
	{
		$("#level3").hide();
		$("#test_list").show();
		used_Save_Print = false;
		showsavedTests();
	}
	else 
	{
		$("#level3").hide();
		$("#level2").show();
		userImageLogo = '';
		$('._edit_cat_title').show();
		$("#level2 #userInfo, #activityArea").hide()
		$("#level2 #sContainIn").show()
		prepareSummary();
		$("#level3 #previewHTML").empty();

		$("#css-responsive").attr('href', 'style/responsive.css');
		if(used_Save) $('.marksInput').addClass('_disabled');
		else $('.marksInput').removeClass('_disabled');

		toggleMarks();
	}
}

function backToEditAuto()
{
	if(used_Save_Print)
	{
		$("#level3").hide();
		$("#test_list").show();
		used_Save_Print = false;
		showsavedTests();
	}
	else 
	{
		$("#level3").hide()
		$("#level2").show();
		$('._edit_cat_title').show();
		$("#level2 #userInfo").hide();
		$("#level2 #sContainIn").show();
		prepareSummary();
		$("#level3 #previewHTML").empty();

		$("#css-responsive").attr('href', 'style/responsive.css');
		
		if(used_Save) $('.marksInput').addClass('_disabled');
		else $('.marksInput').removeClass('_disabled');
		
		toggleMarks();
	}
}

function resetSummary() 
{
	difficultySummary = {
		'E': 0,
		'M': 0,
		'H': 0
	}
	outcomeSummary = {};
	totalMarksSummary = 0;
}

function setNumberingPreview() {
	checkParent();

	$(_parentLast).find("#previewHTML .numbering").each(function(e, _i) 
	{
		var numberingHTML = "<p class='previewNumbering'>" + this.textContent + "</p>";
		var olddata = $(this).parent().find('.question-title').html();
		
		var optiondata = $(this).parent().find('.options').html();
		
		var imgdata = $(this).parent().find('.image').html();
		var ansdata = $(this).parent().find('.question-answer').html();
		
		if(olddata.split(':').join('') == All_typess[3])
		{
			$('.option').find("br").remove();
			/* $(this).parent().find('.question-title').html("<span class='aligntop'><table><tr><td width='40pt' class = 'sequence'>" + numberingHTML + "</td><td valign='top' width='92%' class = 'quest'>" + optiondata + "</td></tr><tr><td width='40pt' class = 'sequence'></td><td class = 'opts' width='92%'></td></tr><tr><td class = 'sequence'></td><td class = 'imgss' width='92%'>" + imgdata +"</td></tr><tr class= 'ans_row'><td width='40pt'></td><td class = 'quest' width='90%' >" + ansdata + "</td></tr></table></span>"); */
		}
		else 	
		{
		}
			$(this).parent().find('.question-title').html("<span class='aligntop'><table width='100%'><tr><td width='40pt' class = 'sequence'>" + numberingHTML + "</td><td valign='top' width='92%' class = 'quest'>" + olddata + "</td><td class = 'mks' width='25pt'></td></tr><tr><td width='40pt' class = 'sequence'></td><td class = 'opts' width='92%'>" + optiondata + "</td><td class = 'mks' width='25pt'></td></tr><tr><td width='40pt' class = 'sequence'></td><td class = 'imgss' width='92%'>" + imgdata +"</td><td  class = 'mks' width='25pt'></td></tr><tr class= 'ans_row'><td width='40pt' class = 'sequence'></td><td class = 'quest' width='92%' >" + ansdata + "</td><td width='25pt'></td></tr></table></span>");
		
		
		
		
		var $image = $(this).parents('.question-parent').find('.image');
		var $parentQ = $(this).parents('.question-parent');

		$('.opts').each(function ()
		{
			if($(this).text() == "")
			{
				$(this).parent().css('display', 'none');
			}
			else $(this).parent().css('display', 'table-row');
		})
				
		$('.question-title').find('.imgss').each(function ()
		{
			if(!$(this).children().length)
			{
				$(this).parent().css('display', 'none');
			}
			else $(this).parent().css('display', 'table-row');
		})
					
		$("#level3 .options, #level3 .options").hide();
		$("#level3 .image, #level3 .image").hide();
		$("#level3 .question-answer, #level3 .question-answer").hide();
		
		if(include_ans || window.Show_Ans)
		{
			$('.ans_row').show();
		}
		else $('.ans_row').hide();
	
		$('.question-title').show();		

		this.outerHTML = "";
	});
	
	/* if($('#extra-logo').length) $('#extra-logo').remove();
	$('#level3 #previewHTML').append('<div id="extra-logo"><img src="img/footer.png"></img></div>'); */
}

function setHeightFix() {
	var win = {
		height: $(window).height(),
		width: $(window).width()
	}
	
	var explorerHeight = win.height - $("#level1 #topHeader").height();
	$("#level1 #level1_explorer").height(explorerHeight + "px");

	var qvh = explorerHeight - $("#level1 #stats").height() - $("#breadcrums").height() - 20;
	$("#level1 #questionsViewer, #level1 #folders").height(qvh + 'px');
	$("#level1 #questionsViewer, #level1 #folders").css('overflow', 'auto');

	var mainframeH = win.height - $("#auto-level-1 .auto-toptitle").height();
	$("#auto-level-1 #mainFrame").height(mainframeH + 'px');

	$("#level2 #toolbars").css('height', 'auto');
	$("#level2 #toolbars").css('height', 'auto');

	//var toolbarHeight = $("#level2 #toolbars").height();
	//if(toolbarHeight != 0)
		//$("#level2 #toolbars").height(toolbarHeight + 'px');

	var autoToolbarHeight = $("#level2 #toolbars").height();
	//if(autoToolbarHeight != 0)
		//$("#level2 #toolbars").height(autoToolbarHeight + 'px');

	var top1Height = $("#level1 #topHeader").height();
	//$("#level1 #topHeader .auto-tabs-section").css('height', top1Height + 'px');

	$("#auto-level-1 .auto-tabs-section").css('height', '');
	var barheight = $("#auto-level-1 .auto-toptitle").height();
	//$("#auto-level-1 .auto-tabs-section").css('height', barheight + 'px');

	var heightTool = $("#toolbars").height();
	//$("#toolbars .auto_level-buttons").css('height', heightTool + 'px')

	if(win.width < 1000) {
		$(".book_name .tgTitle").css('font-size', '20px');
	}
}

$(document).ready(function(e) {
	$("#explorer").on("click", ".breadLabel[data-link]", function(e) {
		var treeid = $(this).attr('data-link');
		$("#" + treeid + " > a").click()
	});
	
	$('#startBtn').click(selectTestType);
	
	$('#usePreBtn').click(usePrev);

	$('#auto-filter-metadata span').click(append_metaFeild);
});

function append_metaFeild()
{
	metaCounter++;
	if(metaCounter == 1)
	{
		$('#meta_boxes').append('<div id = meta_' + metaCounter + '><input class = "metaauto" id=metaauto_'+ metaCounter +'></input></div>');
	}
	else $('#meta_boxes').append('<div id = meta_' + metaCounter + '><input class = "metaauto" id=metaauto_'+ metaCounter +'></input> <div class = "remove_meta" onClick="remove_metaFeild(this)">x</div></div>');
}

function remove_metaFeild(_this)
{
	metaCounter--;
	$(_this).parent().remove();
}

function saveTest()
{
	checkParentlastScreen();
	$(_parent).find('#testName').val('');
	$(_parent).find('#testInfo').show();
	$(_parent).find("#pdfPreview").scrollTop(0);
	if(tgType == 'auto') {
		if(window.tgduration != undefined && window.tgduration != null && window.tgduration != "") {
			$("#time").val(window.tgduration)
		}
	}
}

function saveTestInfo(){
	
	var d = new Date();
	var testDate = d.toLocaleDateString();
	var testTime = d.toLocaleTimeString();
	
	var testName = $(_parent).find('#testName').val();
	if(testName == ''){
		alert('Please provide Test Name');
	}else{

		var testMarks = [];
		$('.question-parent .marksInput').each(function(){
			testMarks.push($(this).val());
		});	
		
		var testJsonObj = {
			"testDuration":window.tgduration,
			"worksheetType":window.testType || window.modeEnableType,
			
			"testName":testName,
			"tgType":tgType || window.savedEditType,
			"testDate":testDate,
			
			"testTime":testTime,
			"TestIds":testBank,
			"TestMarks":testMarks,
			"showMarkss":showMarks,
			"showAnss":include_ans
		}
		
		/* var getTestsData = localStorage.getItem(TgId+"_savedTests");
		var savedTestData = [];
		if(getTestsData != undefined && getTestsData != null) {
			savedTestData = JSON.parse(getTestsData);
		}
		
		// chk exists test Name
		var chkfound = false;
		for(i=0;i<savedTestData.length;i++){
			if(testName == savedTestData[i].testName){
				chkfound = true;
			}
		}

		if(chkfound)
		{
			$(_parent).find('#testName').val('');
			$(_parent).find('#testName').focus();
			alert("This Test Name has already been saved.");
		}
		else if(!$(_parent).find('#testcookie').prop('checked'))
		{
			alert('Please click the check box to allow cookies and proceed further.');
		}
		else if($(_parent).find('#testcookie').prop('checked'))
		{
			savedTestData.push(testJsonObj);
			localStorage.setItem(TgId+"_savedTests",JSON.stringify(savedTestData));
			alert('Test saved successfully.');
			$(_parent).find('#testInfo').hide();
		} */
	}
	
	/* var chk = localStorage.getItem(TgId+"_savedTests");
	chk = JSON.parse(chk); */
}

function gotosettingslist(){
		
	checkParentlastScreen();
	$(_parent).find("#testInfo").hide();
	
	$(_parent).hide();
	usePrev();
}

function closeSaveTestPopupFromPreview()
{
	$(_parent).find('#testName').val('');
	$(_parent).find('#testInfo').hide();
}

function usePrev()
{
	$("#testgenerator-type").hide();
	document.getElementById('startScreen').style.display = "none";
	showsavedTests();
	
	checkEmptySavedTest();
}

function showsavedTests()
{
	/* $('#level4').css("display","block");
	
	processManage();
	
	var table = $('.testListsTable').DataTable();
	
	$('.dataTables_filter').find('#filter_table').on('keyup change', function () {
		table.column(0).search($(this).val()).draw();
	}); */
}

function processManage(){
	/* var getTestsData = localStorage.getItem(TgId+"_savedTests");
	if(getTestsData == undefined && getTestsData == null) {
		$('#availableTests').html('<p>Sorry, no tests available.<p>');
	}else{
		var savedTestData = JSON.parse(getTestsData);
		var tmpStr = '<table class="testListsTable" border="1"><thead class="trHead"> <tr> <td class="strong" style="text-align:center"> Name</td> <td class="strong"> No. of Questions</td> <td class="strong"> Mode</td> <td class="strong">Type</td> <td class="strong">Date</td> <td class="strong">Time</td> <td class="strong"> View </td>  <td class="strong"> Remove </td>  <td class="strong"> Print </td> </tr></thead><tbody id="test_tbody">';
				
		for(i=savedTestData.length-1;i>=0;i--){
			var tgDuration = savedTestData[i].testDuration;
			var testName = savedTestData[i].testName;
			var _tgType = savedTestData[i].tgType;
			var testIds = savedTestData[i].TestIds;
			var worksheetType = savedTestData[i].worksheetType;
			var testType = savedTestData[i].testType;
			var testDate = savedTestData[i].testDate;
			var testTime = savedTestData[i].testTime;
			var _showMarks = savedTestData[i].showMarkss;
			var _include_ans = savedTestData[i].showAnss;
			
			var noq = testIds.length;
			
			tmpStr+='<tr> <td>'+testName+'</td> <td>'+noq+'</td> <td>'+_tgType+'</td> <td>'+worksheetType+'</td> <td>'+testDate+'</td> <td>'+testTime+'</td> <td><button class="testlistview" onclick="showTestDataView('+i+')" >Modify</button</td> <td><button class="testlistview" onclick="removeSavedTest('+i+')" >Delete</button</td>  <td><button class="testlistview" onclick="printTest('+i+')" >Print</button</td></tr>';
		}
		$('#availableTests').html(tmpStr);
	} */
}

function removeSavedTest(deli){
	/* var getTestsData = localStorage.getItem(TgId+"_savedTests");
	var savedTestData = JSON.parse(getTestsData);
	savedTestData.splice(deli,1);
	localStorage.setItem(TgId+"_savedTests",JSON.stringify(savedTestData));

	processManage();
	checkEmptySavedTest(); */
}

function checkEmptySavedTest()
{	
	/* $('.testListsTable').DataTable();
	
	if(!$('.sorting_1').length)
	{
		$('#availableTests').html('Sorry, no tests available.');
		return;
	} */
}

function printTest(i)
{
	/* getTestData(i);
	showPrintScetion(i);
	window.editTestId = i; */
}

function showTestDataView(i)
{
	/* used_Save = true;
	getTestData(i);
	showModifyScetion(i);
	window.editTestId = i; */
}

function showPrintScetion(i)
{
	/* used_Save_Print = true;
	addSavedTestQuestions();
	
	if(window.savedEditType == "auto" || tgType == "auto")
	{
		$('#activityArea').hide();
		$('#typeAuto, #auto-level-3').show();
		$('#auto-level-1, #auto-level-2, #level1, #level2, #level3').hide();
		showPreview();
	}
	else
	{	
		$('#typeAuto, #level1, #level2, #auto-level-1, #auto-level-2, #auto-level-3').hide();
		$('#activityArea, #level3').show();
		showPreview();
	} 
	
	if(window.MarksMode)
	{
		$(_parent).find('#student-version-m').prop('checked', false);
	}
	else 
	{
		$(_parent).find('#student-version-m').prop('checked', true);
	}
	
	if(window.Show_Ans)
	{
		$(_parent).find('#student-version').prop("checked", true);
		
		
	}
	else 
	{
		$(_parent).find('#student-version').prop("checked", false);
	}
	
	
	toggleMarks();
	toggleAnswers();
	$('#level4').hide();	
	$('.finaliseSave').hide();
	
	$('.question-answer').hide(); */
}

function showModifyScetion(i)
{
	/* addSavedTestQuestions();		
		
	$('#worksheet_page_1 , .activity-submit-wrapp, #level1 ,#userInfo , #testInfo').hide();
	
	
	
	if(window.savedEditType == "auto" || tgType == "auto")
	{
		$('#activityArea').hide();
		$('#typeAuto, #auto-level-2').show();
		$('#auto-level-1, #auto-level-3').hide();
	}
	else
	{	
		$('#typeAuto').hide();
		$('#activityArea, #level2').show();
	}
	
	if(window.MarksMode)
	{
		$(_parent).find('#student-version-m').prop('checked', false);
	}
	else 
	{
		$(_parent).find('#student-version-m').prop('checked', true);
	}
	
	if(window.Show_Ans)
	{
		$(_parent).find('#student-version').prop("checked", true);
	}
	else 
	{
		$(_parent).find('#student-version').prop("checked", false);
	}
	
	toggleMarks();
	toggleAnswers();
	$('#level4').hide();

	showNoSaveNoPreview();
	$('.finaliseSave').show();
	disableButtonSecondTime(); */
}

function disableButtonSecondTime()
{
	/* if(used_Save || used_Save_Print) 
	{
		$('._addnewQuestion, .tool-edit, ._edit_cat_title').addClass('hide');
		$('.marksInput').addClass('_disabled');
	}
	else 
	{
		$('._addnewQuestion, .tool-edit, ._edit_cat_title').removeClass('hide');
		$('.marksInput').removeClass('_disabled');
	} */
}

function getTestData(i)
{
	/* $('#backBtn1').show();
	$('#level3').hide();
	$('#previewHTML').empty();
	
	var getTestsData = localStorage.getItem(TgId+"_savedTests");
	if(getTestsData == undefined && getTestsData == null) {
		alert('Sorry,Test not Found!');
	}else{
		
		var savedTestData = JSON.parse(getTestsData);
		var tgDuration = savedTestData[i].testDuration;
		var testName = savedTestData[i].testName;
		var _tgType = savedTestData[i].tgType;
		var testIds = savedTestData[i].TestIds;
		var testMarks = savedTestData[i].TestMarks;
		var TestType = savedTestData[i].testType;	
		var worksheetType = savedTestData[i].worksheetType;
		var _showMarks = savedTestData[i].showMarkss;
		var _include_ans = savedTestData[i].showAnss;
		
		//console.log(showMarks)
		
		window.savedTestType = TestType;
		window.savedEditType = _tgType;
		window.modeEnableType = worksheetType;
		window.MarksMode = _showMarks;
		window.tgDuration = tgDuration;
		window.Show_Ans = _include_ans;
		
		testBank = testIds;
		
		for(ii=0;ii<testIds.length;ii++){
			allQuestions({id:parseInt(testIds[ii])}).each(function(r)
			{
				//r.mark = parseInt(testMarks[ii]);
			});
		}
	} */	
}

function showNoSaveNoPreview(){
	/* $('#preview_scrren').hide();

	if(!$(_parent).find('#testName').val())
	{
		$(_parent).find('#testInfo').hide();
	} */
}

function addSavedTestQuestions(){

	/* $('#cartItems').text(testBank.length);
	
	checkParent();	

	$(_parent).find('#pdfPreview').empty();
	$(_parent).find('#pdfPreview').show();
	
	testBank = uniqueArray(testBank);
	
	selectChapters = [];
	$(".practive").removeClass('practive');
	
	categorySummary = {};

	fetch_Data();
	//	For filtering and merging questions by type 
	
	var $section;	
	
	setFilterArr();
		
	$('.marksInput').on('focus', handleMarksInputF);
	$('.marksInput').on('blur', handleMarksInputB);
	
	setNumbering();
	
	if($(_parent).find('#student-version').prop("checked") == false) {
		$('.question-answer').hide();
	} else {
		$('.question-answer').show();
	}
		
	jQuery('#sContainIn .topTitlez').each(function(e){
		if(!jQuery(this).find('.question-parent').length)
			jQuery(this).remove();
	});
	
	if(testBank.length == 0) {
		switchScreen('level1');
	}
	
	if(document.getElementById("student-version-m").checked == true) {
		$('.marksDiv').hide();
	}

	if(!used_Save_Print) 
	{
		prepareSummary();
		disableReplaceBtn();
	} */
}

function switchScreen(currentId)
{
	if(used_Save != true)
	{
		if(currentId == "level1")
		{
			$('#level1, #level2, .toolbars_previeww').hide();
			$('#'+currentId).show();
			
			$('#explorer').empty();
			$('#pdfPreview').empty();
			$('#showCartBtn, #auto-page2, #auto-level-1, #activityArea, #typeAuto').show();			
			showAutoPage = true;
			setAutoPagePosition();
			
			jQuery('.jstree-clicked').trigger('click');
			//$('#collectionList').removeClass("disable");
			setHeightFix();	
		}
		else if(currentId == 'screen3')
		{
			screenonOff("screen",'screen_3');	
			$('.toolbars_previeww').hide();
		}
	}
	else
	{
		/* $("level1, #level2, #level3").hide();
		$("#test_list").show();
		showsavedTests();
		used_Save = false; */
	}
}

function saveTestChanges(){
	
	var testMarks = [];
	$('.question-parent .marksInput').each(function(){
		testMarks.push($(this).val());
	});
	
	var testIds = testBank;
	
	var getTestsData = localStorage.getItem(TgId+"_savedTests");
	var savedTestData = JSON.parse(getTestsData);
	
	savedTestData[window.editTestId].TestIds = testBank;
	
	savedTestData[window.editTestId].TestMarks = testMarks;

	localStorage.setItem(TgId+"_savedTests",JSON.stringify(savedTestData));
	gotosettingslist();
}

function test_type(_this)
{
	document.getElementById('student-version-m').checked = true;
	document.getElementById('student-version').checked = true;
	window.testType = $(_this).attr('id');
	setHeightFix();
	
	$(_this).parent().hide();
}
