// Firefox 1.0+
var isFirefox = typeof InstallTrigger !== 'undefined';

var preservemyHTML = "";


function addToTestAuto(selectedQuestions) {

	resetSummary();
	// console.log("selected-question",selectedQuestions);
	testBank = [];
	for (var i = 0; i < selectedQuestions.length; i++) {
		testBank.push(String(selectedQuestions[i]));
	}

	$('#typeAuto #pdfPreview').empty();


	$userInfo = $('<div id="userInfo"></div>');
	$userInfo.append('<table class="userinfo-table"><tr><td><label class="label-text" for="school">School Name:</label></td><td><input type="text" name="school" id="school" class="input"/></td></tr>');

	if (selectedOption !== "worksheet"){
		$userInfo.append('<table class="userinfo-table"><tr><td><label class="label-text" for="name">Test Name:</label></td><td><input type="text" name="name" id="name" class="input" /></td></tr></table>');
		}	
	
		$userInfo.append('<table class="userinfo-table"><tr><td><label  class="label-text" for="class_t">Class:</label></td><td><input type="text" name="class_t" value="' + allQuestions().first().class + '" id="class_t" class="input" /></td></tr></table>');
	    $userInfo.append('<table class="userinfo-table"><tr><td><label  class="label-text" for="subject">Subject:</label></td><td><input type="text" name="subject" value="' + allQuestions().first().subject + '" id="subject" class="input" /></td></tr></table>');
		

	if (selectedOption === "worksheet") {
		$userInfo.append('<table class="userinfo-table"><tr><td><label  class="label-text" for="time">Date:</label></td><td><input type="text" name="time" id="time" class="input" placeholder="DD/MM/YYYY" /></td></tr></table>');
	}
	else {
		$userInfo.append('<table class="userinfo-table"><tr><td><label  class="label-text" for="time">Time:</label></td><td><input type="text" name="time" onkeydown="return numValidate(event)" id="time" class="input" /></td></tr></table>');
	}

	$userInfo.append('<table class="userinfo-table" style="padding-left:25px; margin-top:14px"><tr><td><label class="label-text" style="margin-left:8px">Logo: </label> \
		<input type="file" accept="image/*" name="imgfile" id="imgfile" size="50"> \
		</td></tr></table>');

	$userInfo.append(`<table style="margin-top:20px;"><tr><td><button id="showPrevBtn" class="sm_button" onclick="showPreviewAuto()">Submit</button></td> </tr></table> `);
	$userInfo.append('<button id="closepopupBtn" class="" title="Close" onclick="closePopupFromPreview()"><i class="fa fa-times"></i></i></button>');

	$userInfo.append('<div class="clear"></div>');

	$('#typeAuto #pdfPreview').append($userInfo);
	testBank = uniqueArray(testBank);
	console.log("test-bank", testBank);




	selectChapters = [];

	for (var i = 0; i < testBank.length; i++)
		insertQuestion($('#typeAuto #pdfPreview'), testBank[i]);


	for (var zz = 0; zz < selectChapters.length; zz++) {
		$("#" + selectChapters[zz]).addClass('practive');
	}

	var categoriges = $('#typeAuto #pdfPreview #sContainIn').children().map(function () { return this.dataset.title; }).get();
	var chapters = $('#typeAuto #pdfPreview #sContainIn').children().map(function () { return this.dataset.chapter; }).get();
	var type = $('#pdfPreview #sContainIn').children().map(function () { return this.dataset.type; }).get();
	// console.log("type",type)

	var marks = $('#pdfPreview #sContainIn').children().map(function () { return this.dataset.marks; }).get();

	categoriges = uniqueArray(categoriges);
	// console.log("categories",categoriges);
	chapters = uniqueArray(chapters);

	if (selectedOption === "worksheet") {
		document.getElementById("form-marks").style.display = "none";
		const container = document.querySelector(".insertNewQuestion-container");
		if (container) {
			container.style.height = "380px";
		}
	}

	/*console.log(chapters);
	console.log(categoriges);*/

	var uniquetype = [];
	$.each(type, function (i, el) {
		if ($.inArray(el, uniquetype) === -1) uniquetype.push(el);
	});

	/* 	For filtering and merging questions by type */

	var $section;
	var totalCat_marks;

	var tempinc = 1;

	filterArr = [];

	for (var catIndex = 0; catIndex < uniquetype.length; catIndex++) {
		var obj = new Object();

		obj.type = uniquetype[catIndex];
		obj.arr = [];
		obj.Finalarr = [];
		obj.Title = [];
		obj.FinalTitle = [];
		obj.ID = [];
		filterArr.push(obj);

		tempinc = 1;
	}

	$('#sContainIn .question-parent').each(function (i, e) {
		for (var o in filterArr) {
			if ($(this).attr('data-type') == filterArr[o].type) {
				filterArr[o].arr.push(this.dataset.type);
				filterArr[o].Title.push(this.dataset.title);
			}

			$.each(filterArr[o].arr, function (i, el) {
				if ($.inArray(el, filterArr[o].Finalarr) === -1) filterArr[o].Finalarr.push(el);
			});

			$.each(filterArr[o].Title, function (i, el) {
				if ($.inArray(el, filterArr[o].FinalTitle) === -1) filterArr[o].FinalTitle.push(el);
			});
		}
	})

	chr = 0;
	setNumbering();
	// console.log('Counts-in::::', counts);
	c = 0;
	for (var o in filterArr) {
		filterArr[o].ID.push(String(filterArr[o].type).substr(0, String(filterArr[o].type).indexOf(' ')));

		$('#pdfPreview #sContainIn').append('');

		for (var index = 0; index < filterArr[o].Finalarr.length; index++) {
			$('#pdfPreview #sContainIn').append('<div class = "main_Div" id =' + (filterArr[o].ID + "_" + filterArr[o].Finalarr[index].split(' ').join('_')) + '></div>');

			for (var k = 0; k < filterArr[o].FinalTitle.length; k++, c++) {
				// console.log("count-c", counts[c]);

				chr = nextChar(chr);
				// console.log("title::",filterArr[o].FinalTitle[k]);

				$('#' + filterArr[o].ID + "_" + filterArr[o].Finalarr[index].split(' ').join('_'))
					.append('<h3 class="title">' + chr + '.&nbsp;&nbsp;' + filterArr[o].FinalTitle[k] + '</h3>');

				totalCat_marks = 0;

				$('#sContainIn .question-parent').each(function (i, e) {
					if ($(this).attr('data-type') == filterArr[o].type) {
						totalCat_marks += parseInt(this.dataset.marks);
						// console.log("marks",totalCat_marks);
						// console.log("title",this.dataset.title.length);
						if (filterArr[o].FinalTitle[k] == this.dataset.title) {
							$('#' + (filterArr[o].ID + "_" + filterArr[o].Finalarr[index].split(' ').join('_'))).append($(this));
						}
					}
				})
			}
			break;
		}

		if (totalCat_marks > 1) {
			$('.' + filterArr[o].ID + '_h2').html(filterArr[o].type /*+ ' &mdash; ' + totalCat_marks + ' Marks'*/);
		}
		else {
			$('.' + filterArr[o].ID + '_h2').html(filterArr[o].type /*+ ' &mdash; ' + totalCat_marks + ' Mark'*/);
		}
	}

	$('.marksInput').on('focus', handleMarksInputF);
	$('.marksInput').on('blur', handleMarksInputB);
	//$('.rx-editable').on('dblclick', enterEdit);

	if ($('#pdfPreview #unseencomprehension').length > 0) {
		$('#pdfPreview #unseencomprehension').detach().insertAfter('#pdfPreview #userInfo');
	}

	setNumbering();
	showCart();

	$('#userInfo').parent().children().show().end().end().hide();


	if (document.getElementById('student-version').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 (document.getElementById("student-version-m").checked == false) {
		$('.marksDiv').hide();
	}


	$("#auto-level-1").hide();
	$("#auto-level-2").show();
	setHeightFix();
	prepareSummary();
	disableReplaceBtn();
}


function validateImage(input) {
	const file = input.files[0];
	if (!file) {
		return;
	}

	const img = new Image();
	img.onload = function () {
		if (img.width >= 200 || img.height >= 200) {
			alert("Image dimensions must not exceed 200x200 pixels.");
			input.value = '';
		}
	};

	img.src = URL.createObjectURL(file);
}


function showPreviewAuto() {
	loadImage();
	$('#auto-level-2').hide();
	$('#auto-level-3').show();


	$('#previewHTML').html($('#pdfPreview').html()).promise().done(function () {
		var school = $('#pdfPreview #school').val();
		$('#previewHTML #school').replaceWith('<span id="text-school">' + school + '</span>');

		if (selectedOption === "worksheet") {
			if(school){
                var schoolName = '<div class="worksheet-school-name">' + school + '</div><br>';
			$('#previewHTML').prepend(schoolName);
			}	
		}
        
		

		var subject = $('#pdfPreview #subject').val();
		$('#previewHTML #subject').replaceWith('<span id="text-subject">' + subject + '</span>');

		var class_t = $('#pdfPreview #class_t').val();
		$('#previewHTML #class_t').replaceWith('<span id="text-class_t">' + class_t + '</span>');

		var name = $('#pdfPreview #name').val();
		$('#previewHTML #name').replaceWith('<span id="text-name">' + name + '</span>');

		// var roll = $('#pdfPreview #roll').val();
		// $('#previewHTML #roll').replaceWith('<span id="text-roll">' + roll + '</span>');

		var time = $('#pdfPreview #time').val();
		$('#previewHTML #time').replaceWith('<span id="text-time">' + time + '</span>');

		// var set = $('#pdfPreview #set').val();
		// $('#previewHTML #set').replaceWith('<span id="text-set">' + set + '</span>');

		$('#previewHTML #showPrevBtn').remove();

		setNumbering(); // Ensure counts are set
		$('#previewHTML .title .merge-score').remove(); // Remove old score displays

		setNumberingPreview();

		// console.log("Accessing counts in showPreviewAuto:", questionValues);


		var totalMarks = 0;
		$('#previewHTML .marksInput').each(function (i, e) {
			var spcMark = $('#pdfPreview .marksInput').eq(i).val();
			spcMark = parseInt(spcMark) || 0; // Ensure it's a number
			const individualScore = spcMark * questionValues[i];
			// Add to the total marks
			totalMarks += individualScore;
			// console.log("total-marks+", totalMarks)
			var $marksDiv = $(this).closest('.marksDiv');
			$(this).replaceWith('<div></div>'); // Remove the input element

			const titleText = $('#previewHTML .title').eq(i).text().trim(); // Get the title text without trailing whitespace

			// Update the title's HTML to include the new table structure
			$('#previewHTML .title').eq(i).html(`
				<br>
				<table width="100%">
					<tbody>
						<tr>
							<td align="left">${titleText}</td>
							<td align="right" class="merge-score">(${questionValues[i]} X ${spcMark} = ${spcMark * questionValues[i]})</td>
						</tr>
					</tbody>
				</table>
			`);

			if (selectedOption === "worksheet") {
				$('#previewHTML .title').eq(i).find('.merge-score').css("display", "none");
			}
		});

		// You might want to display totalMarks somewhere if needed
		// console.log("Total Marks:", totalMarks);


		
		var TimeLabel = (selectedOption === "worksheet") ? "Date:" : "Time:";
		var timeDisplay = (selectedOption === "worksheet") ? time : convertMinsToHrsMins(time);




		$('<div></div>').append('<label>Total Marks:</label><span id="text-marks">' + totalMarks + '</div>').appendTo('#previewHTML #userInfo');
		$('#previewHTML #userInfo .clear').detach().appendTo('#previewHTML #userInfo');

		var $table = $('<table></table>');
		$table.append("<tr><td></td><td></td><tr>");
		$table.append("<tr><td></td><td></td><tr>");
		$table.append("<tr><td></td><td></td><tr>");

		var subjectobj = '<tr><td align="left" valign="top"><label class="topHeadLable">Subject:<span> &nbsp;' + subject + '</span></label></td><td class="topHeadTd" align="left" valign="top"></td></tr>';
		
        var studentNameobj= '<tr><td align="left" valign="top"><label class="topHeadLable">Student Name:</label></td><td class="topHeadTd" align="left" valign="top">__________________</td></tr>';
        var classobj = '<tr><td align="left" valign="top"><label class="topHeadLable">Class:<span> &nbsp;' + allQuestions().first().class + '</span> </label></td><td class="topHeadTd" align="left" valign="top"></td></tr>';

		var nameobj = '<tr><td align="left" valign="top" width="100px"><label class="topHeadLable">Test Name:<span> &nbsp;' + name + '</span></label></td><td class="topHeadTd" align="left" valign="top"></td></tr>';
		
		var schoolobj = '<tr><td align="left" valign="top"><label class="topHeadLable">School Name:<span> &nbsp;' + school + '</span></label></td><td class="topHeadTd" align="left" valign="top"></td></tr>';
		//var setobj = '<tr><td align="left" valign="top"><label class="topHeadLable" style="width:69px";>Set no:</label></td><td class="topHeadTd" align="left" valign="top"><span id="text-set">' + set + '</span></td></tr>';
		var timeobj = '<tr><td align="left" valign="top"><label class="topHeadLable">' + TimeLabel + '<span> &nbsp;' + timeDisplay + '</span></label></td><td class="topHeadTd" align="left" valign="top"></td></tr>';
		if (selectedOption !== "worksheet") {
			var marksobj = '<tr><td align="left" width="150px" valign="top"><label class="topHeadLable" style="width:118px";>Total Marks:<span> &nbsp;' + totalMarks + '</span></label></td><td class="topHeadTd" align="left" valign="top"></td></tr>';
		}

		if (testType == 'worksheet') {
			marksobj = '';
		}

		var tablestr = '<table width="100%">\
		<tr>\
			<td width="50%" align="left" valign="top"><table>' + (selectedOption === "worksheet" ? studentNameobj : '')+(selectedOption !== "worksheet" ? schoolobj : '') +(selectedOption !== "worksheet" ? nameobj : '') + classobj+'</table></td>\
			<td width="50%" align="center" valign="top"><table>' + subjectobj + timeobj + (selectedOption !== "worksheet" ? marksobj : '') + '</table></td>\
		</tr>\
	</table>';

		$table.appendTo('#userInfo');
		$('#previewHTML #userInfo').html(tablestr)

		var stdnt = document.getElementById('student-version');
		if (stdnt.checked == false) {
			//$('#previewHTML .question-answer').remove();
		}

		//$('#previewHTML h3').remove();
		$('#previewHTML').children().show();

		var num;
		$('#previewHTML img').each(function (i, e) {
			//var width = getImgWidth(this.src);
			//this.setAttribute('width', 600 + 'px');
			//$(this).parent().append('<span class="numbering">' + num + '</span> ');
		});

		$('#previewHTML .mx-tools').remove();
		$('.marksDiv span').hide();


		//$('#previewHTML').next().next().children().eq(0).prepend('1.');
		$('#previewHTML .numbering').each(function (i, e) {
			//num = $(this).text();
			//$(this).next().next().children().eq(0).prepend('<span class="numbering">' + num + '</span> ');

			//$(this).remove();
		});

		//$('#previewHTML').prepend(userImageLogo);

		// $('#previewHTML').prepend('<div style="opacity: 0;">&nbsp;</div>');
		// setNumberingPreview();
	});
	$('#previewHTML .mx-tools, #previewHTML .question-info, .summary-selection').remove();

	$("#previewHTML").height('77%');

}

function autoNewQuestion() {
	$("#aft-validation").hide();
	$("#insertNewQuestion input[type='text']").val('');
	$("#insertNewQuestion").fadeIn();

	var questionType = allQuestions().distinct('type');
	var typeHTML = "";
	// console.log("question-type",questionType);
	// console.log("question-type",questionType.length);
	for (var i = 0; i < questionType.length; i++) {
		typeHTML += '<option value="' + questionType[i] + '">' + questionType[i] + '</option>'
		// console.log("typehtml",typeHTML);
	}
	typeHTML += '<option value="' + 'others' + '">' + 'Others' + '</option>';
	$("#afm-type").html(typeHTML).trigger('change');

	var questionOutcome = allQuestions().distinct('outcome');
	// console.log("question-outcome", questionOutcome); l
	var outcomeHTML = "";
	for (var i = 0; i < questionOutcome.length; i++) {
		outcomeHTML += '<option value="' + questionOutcome[i] + '">' + questionOutcome[i] + '</option>'
		// console.log("questionOutcome[i]", questionOutcome[i]);
		// console.log("outcomeHTML",outcomeHTML);
	}
	$("#aft-outcome").html(outcomeHTML);
}

function switchScreenAuto(ele) {
	$(".auto-level-page").not("#" + ele).hide();
	$("#" + ele).show();
	setHeightFix();
}

function autoNewQuestionAdd() {
	$("#aft-validation").hide();
	var existingQuestions = allQuestions().get();
	// console.log("existng-question::", existingQuestions);
	var formObj = {
		title: document.getElementById('afm-question-title'),
		question: document.getElementById('afm-question'),
		answer: document.getElementById('afm-answer'),
		marks: document.getElementById('afm-marks'),
		difficulty: document.getElementById('aft-difficulty'),
		outcome: document.getElementById('aft-outcome'),
	};
	var matchedQuestion = questions.find(q => q.question.title === formObj.title.value);
	var questionType = matchedQuestion ? matchedQuestion.type : "others";

	var matchedMarks = existingQuestions.find(q => q.question.title === formObj.title.value);
	var marks = matchedMarks ? matchedMarks.mark : formObj.marks.value;


	var showMsg = function (msg) {
		$("#aft-validation").text(msg).show();
	};

	if (formObj.title.value == "") {
		showMsgBox("Please type title");
		formObj.title.focus();
		return false;
	}

	if (formObj.question.value == "") {
		showMsgBox("Please type question");
		formObj.question.focus();
		return false;
	}

	if (formObj.answer.value == "") {
		showMsgBox("Please type answer");
		formObj.answer.focus();
		return false;
	}
	if (selectedOption !== "worksheet") {
		if (formObj.marks.value == "") {
			showMsgBox("Please insert marks");
			formObj.marks.focus();
			return false;
		}
	}


	if (isNaN(formObj.marks.value)) {
		showMsgBox("Please insert valid marks in integer");
		formObj.marks.focus();
		return false;
	}

	// console.log("allquestion", allQuestions().count);
	var newId = String(allQuestions().count() + 1);
	var questionTitleMain = formObj.title.value;
	var questionText = formObj.question.value;

	// Prepare the option array
	var questionOption = questionText; // Start with the question text

	// If there's an image, concatenate it
	if (document.getElementById('afm-image').files.length > 0) {
		questionOption += " <img src='" + inputToURL(document.getElementById('afm-image')) + "'/>";
	}

	var formattedObj = {
		'class': 'Custom Other',
		'chapter': 'Custom Other',
		'neworbook': 'Custom Other',
		'topic': 'Custom Other',
		'type': questionType,
		'question': {
			'title': questionTitleMain,
			'option': [questionOption], // Use the combined string in an array
			'image': '' // You can remove this if not needed
		},
		'answer': [formObj.answer.value],
		'mark': marks,
		'outcome': formObj.outcome.value,
		'difficulty': formObj.difficulty.value,
		'id': parseInt(newId)
	};


	// console.log("newid", newId);
	// console.log("formattedobj", formattedObj);


	// console.log("existing question::",existingQuestions);
	var isDuplicate = existingQuestions.some(function (existingQuestion) {
		// console.log("existing-question",existingQuestions)
		return JSON.stringify(existingQuestion.question.option) === JSON.stringify(formattedObj.question.option);
	});

	if (isDuplicate) {
		alert("This question already exists in the test.");
		return false; // Stop further execution if duplicate found
	}

	allQuestions.insert(formattedObj);
	testBank.push(newId);


	if (tgType == 'manual') {
		addToTest();
	} else {
		addToTestAuto(testBank);
	}

	dismissPopupInsertion();
	showMsgBox("New question has been added.");
	return false;
}


function dismissPopupInsertion() {
	$("#insertNewQuestion").hide();
	$("#insertNewQuestion input[type='text'], #insertNewQuestion textarea").val('');
	$("#new-question-insertion-form")[0].reset();
}

function inputToURL(inputElement) {
	var file = inputElement.files[0];
	return window.URL.createObjectURL(file);
}

var style = '<style>\
.question-parent {\
clear: both;\
margin: 0px;\
padding: 6px 0px 6px 0px;\
position: relative;\
margin-top: 7px;min-height: 22px;}\
.question-parent.selection{\
}\
.numbering {float: left;}\
.marksDiv{float: right; widht: 25px;}\
</style>';

function printStudent() {
	$("#previewHTML .question-answer").hide();
	if (typeof appjs != "object") {
		if (isFirefox) {
			//exportPDFKendo('student');
			printCommand();
		} else {
			printCommand();
		}
	} else {
		if (preservemyHTML == "") {
			preservemyHTML = $("#previewHTML").html();
		}
		$("#previewHTML").html(preservemyHTML);
		$("#previewHTML .question-answer").remove();
		devilzgetpdf(style + $("#previewHTML").html());
	}

}

function printTeacher() {
	$("#previewHTML .question-answer").show();
	if (typeof appjs != "object") {
		if (isFirefox) {
			//exportPDFKendo('teacher');
			printCommand();
		} else {
			printCommand();
		}
	} else {
		if (preservemyHTML == "") {
			preservemyHTML = $("#previewHTML").html();
		}
		$("#previewHTML").html(preservemyHTML);

		devilzgetpdf(style + $("#previewHTML").html());
	}
	$(window).focus(function () {
		console.log('focused');
	})
}

function exportPDFKendo(type) {
	var printHTML = $("#previewHTML");
	var height = printHTML.height();
	printHTML.height('auto');
	var filename = type + '_' + moment().format('DD-MM-YYYY-hhmmss') + '.pdf';

	var printType = 'all';

	if (printType == 'kendo1') {

		kendo.drawing
			.drawDOM(printHTML)
			.then(function (group) {
				kendo.drawing.pdf.saveAs(group, filename);
				printHTML.height(height);
			});

	} else {
		$("body").addClass('printsection');
		var pdfOptions = {
			forcePageBreak: ".page-break",
			margin: { left: "1cm", top: "1cm", right: "1cm", bottom: "1cm" },
			paperSize: "a4",
			multiPage: true
		};

		kendo.drawing.drawDOM(printHTML, pdfOptions)
			.then(function (group) {
				return kendo.drawing.exportPDF(group, pdfOptions);
			})
			.done(function (data) {
				printHTML.height(height);
				$("body").removeClass('printsection');
				kendo.saveAs({
					dataURI: data,
					fileName: filename,
					proxyURL: "https://demos.telerik.com/kendo-ui/service/export"
				});
			});
	}

}

function generatePDF() {
	var specialElementHandlers = {
		'#bypassme': function (element, renderer) {
			return true;
		}
	};
	var tinymceToJSPDFHTML = $("#previewHTML").html();
	var margin = {
		top: 30,
		left: 45,
		right: 30,
		bottom: 45
	};
	var doc = new jsPDF('p', 'pt', 'letter');
	var canvas = doc.canvas;

	canvas.width = 8.5 * 72;

	doc.fromHTML(tinymceToJSPDFHTML, 0, 0, {
		'width': 568, // max width of content on PDF
		'elementHandlers': specialElementHandlers
	}, function (bla) {
		doc.save('saveInCallback.pdf');
	}, margin);
}

window.onafterprint = function () {
	$("#css-responsive").attr('href', 'style/responsive1.css');
}

window.onbeforeprint = function () {
	$("#css-responsive").attr('href', '');
}

