var testBank = new Array();
var queryTrack = new Object();
var parentsids;
var parentsobjHandle = {};
var selectChapters = [];
var uniquetype = [];
var showMarks = true;
var All_types = [];
var All_subject = [];
var All_class = [];
var marks_count = 0;
var removed = false;
var sQn = 0;
var div_content = '';				
var manual_types = [];
var showAutoPage = false;
			
const EDIF = 
{
	'E': 'Easy',
	'M': 'Medium',
	'H': 'Hard'
}

var filterArr = [];
var M_filterArr = [];
var _temp = [];
var include_ans = true;
var print_mode = "teacher_pdf";
var used_Save = false;
var used_Save_Print = false;
var testTypeBank = [];

$(document).ready(function(e)
{
	result = [];
	f_result = [];
	All_chapter = [];
	
	questions.filter(function(key2,index2)
	{
		All_chapter.push(key2.chapter);
	});
	
	All_chapter = uniqueArray(All_chapter);
	
	All_typess.filter(function(key1,index1)
	{
		testTypeBank[key1] = [];
		
		questions.filter(function(key2,index2)
		{
			if(key2.type == key1) result.push(questions[index2]);
		})
	})

	All_chapter.filter(function(key1,index1)
	{
		result.filter(function(key2,index2)
		{
			if(key2.chapter == key1) f_result.push(result[index2]);
		})
	})
	
	questions = [];
	questions = f_result.concat();
	
	/* if(language == 0) $('body').css('font-family','Arial, Helvetica, sans-serif');
	else $('body').css('font-family','Walkman-Chanakya-905'); */

	if(showModes == true) $('.modess').removeClass('hide');
	else $('.modess').addClass('hide');
	
	$('.tgTitle').text(tgTitle);
	$('a[href="#"]').click(function(e) {
		e.preventDefault();
	});

	$("#afm-type").on('change', function(e) {
		if(this.value == 'others') {
			$("#afm-type-input").show();
		} else {
			$("#afm-type-input").hide();
		}
	});

	for(var i=0; i<questions.length; i++)
	{
		if(questions[i]["chapter"]){questions[i]["chapter"] = questions[i]["chapter"].trim();}
		if(questions[i]["topic"]){questions[i]["topic"] = questions[i]["topic"].trim();}
		if(questions[i]["type"]){questions[i]["type"] = questions[i]["type"].trim();}

		questions[i]["id"] = i+1;
	}
	allQuestions = TAFFY(questions);
	createChapterList();
	//getChapters($("#collectionList #container"), handleStructure);
	setActionForSavingMarks();
	
	
	
	for(var j = 0; j <questions.length; j++)
	{
		All_types.push(questions[j].type);
		All_subject.push(questions[j].subject);
		All_class.push(questions[j].class);
		
	}
	All_types = uniqueArray(All_types);
	
	All_subject = uniqueArray(All_subject);
	All_class = uniqueArray(All_class);
	//setSeq_type();
});

function setSeq_type()
{
	/* var _tt = new Array();
	_tt = All_types; */
	//All_types = [];
	

	/* for(var i=0; i<All_typess.length; i++) 
	{
		for(var k=0; k<_tt.length; k++) 
		{
			if(All_typess[i].type == _tt[k])
			{
				All_types[All_typess[i].seq-1] = _tt[k];
				break;
			}
		}
	} */
	
	//return All_types;
}

function getUniqueData(keyname, keyvalue) {
	return allQuestions().distinct(keyname);
}

function handleStructure(_book, _text)
{
	var parents = new Array();

	parents.push(_text);
	parents.push(_book);

	$('#explorer').empty();
	var scrollPos = $("#level1_explorer").offset().top;
	$("body").animate({ scrollTop: scrollPos });
	var treeLength = treeStructure.length;
	var myLink = new Array();
	var query_question = new Object();
	
	for(var i=0; i<treeLength; i++)
	{
		myLink[i] = parents[i].trim();
		//console.log('myLink[i]', myLink[i]);
		query_question[treeStructure[treeLength-i-1]] = myLink[i];
	}

	var formattedQuery = JSON.stringify(query_question);
	var totalQuestion = allQuestions(query_question);
	
	$('#explorer').append('<div id="stats"><div class="_btns"style ="text-align: right;"><button class="info_btn" id="selectAll" onclick="selectAllQuestion();">Select All</button><button class="info_btn" id="section-prev-test" onclick="addAndMoveOn();">Next</button></div>');
	
	$('#explorer').append('<div id="questionsViewer"></div>');		
	//console.log(totalQuestion.count());
	$('#totalQuestions').val(totalQuestion.count());
	var totalPreSelected = 0;
	var counter = 0;
	var activeChapters = [];
	manual_types = [];
	
	totalQuestion.each(function(r, val)
	{
		counter++;
		var $div = $('<div class="question-parent"></div>').attr({id: 'fib', 'data-type': r.type, 'data-title': replacespecialCharacters(r.question.title), 'data-Mtitle': r.question.title, 'data-Phead': r.question.passageRubric, 'data-cid': r.id, 'data-ref': formattedQuery});
		var $checkbox = $('<input/>').attr({type: 'checkbox', id: 'check' + counter});
		queryTrack[String(r.id)] = formattedQuery; 
		var a = $.inArray(String(r.id), testBank);
		if(a == -1) {
			$checkbox.appendTo($div).click(function(e) {
				$div.toggleClass('selection');
				$('#questionSelected').val($('.selection').length);
		
				pushIds($(e.target), $(e.target).parent().attr('data-type'));	
			});				
		}
		else {
			totalPreSelected++;
			//$div.addClass('selection dis');
			$checkbox.appendTo($div).click(function(e)
			{
				pushIds($(e.target), $(e.target).parent().attr('data-type'));
			}).prop('checked', true)
			//.attr('disabled', 'disabled')
			//.css('cursor', 'default');
		}

		var bulleting = '';
		if((r.type.toLowerCase() == All_typess[1].toLowerCase()) || (r.type.toLowerCase() == All_typess[6].toLowerCase()) || (r.type.toLowerCase() == All_typess[7].toLowerCase())) {
			bulleting = '&nbsp;&nbsp;&nbsp;&nbsp;';
		}
		
		var $opts;
	
		manual_types.push(r.type);
		manual_types = uniqueArray(manual_types);
		
		for(var q in r.question)
		{
			if(q == "rubric")
			{
				$('<div class="question-title"></div>').html('<label class="numbers"></label><label class="qts">' + r.question.rubric + '</label>').appendTo($div);
			}
			else if(q == "image")
			{
				if(r.question.image != undefined && r.question.image != ''){
					$('<div class="image"></div>').html('<img src="'+imagePath+r.question.image+'" />').appendTo($div);
				}
			}
			else if(q == "option")
			{
				$opts = $('<div class="options"></div>');
				if((r.type == All_typess[3]) || (r.type == All_typess[6]) || (r.type == All_typess[7])) 
				{
					if(r.question.option[0] != undefined)
					{
						if(r.question.option[0].indexOf(" ^ ") != -1)
						{						
							var optnameii = "<br><table class= 'data_table' cellspacing='0' cellpadding='0'>";
							for(var mtfIndex=0; mtfIndex<r.question.option.length; mtfIndex++) 
							{
								var optnameiis = r.question.option[mtfIndex];
								
								var mtfoption = optnameiis.split(" ^ ");
								
								optnameii += "<tr><td width='50%'>" + mtfoption[0] + "</td><td width='50%'>" + mtfoption[1] + "</td></tr>";
							}
							optnameii += "</table>";

							$('<div class="option rx-editable"></div>').html(optnameii).appendTo($opts);
						}
						else 
						{
							for(var z=0; z<r.question.option.length; z++)
							{
								var optnameii = r.question.option[z];
								
								if(optnameii.indexOf(".jpg") != -1 || optnameii.indexOf(".png") != -1) {
									optnameii = "<img src='" + imagePath + r.question.option[z] + "'>"
								}	

								$('<div class="question-title"></div>').html(bulleting + optnameii).appendTo($opts);
							}
						}
					}
				} else if((r.type == All_typess[8])){
					for(var z=0; z<r.question.option.length; z++)
					{
						var optnameii = r.question.option[z];
						
						bulleting = "&nbsp;&nbsp;&nbsp;&nbsp;" + romanize(z+1);
						if(optnameii.indexOf(".jpg") != -1 || optnameii.indexOf(".png") != -1) {
							optnameii = "<img src='" + imagePath + r.question.option[z] + "'>"
						}

						$('<div class="question-title"></div>').html(bulleting + optnameii).appendTo($opts);
					}
				}
				else {
					for(var z=0; z<r.question.option.length; z++)
					{
						var optnameii = r.question.option[z];
						
						if(optnameii.indexOf(".jpg") != -1 || optnameii.indexOf(".png") != -1) {
							optnameii = "<img src='" + imagePath + r.question.option[z] + "'>"
						}	

						$('<div class="question-title"></div>').html(bulleting + optnameii).appendTo($opts);
					}
				}
			}
		}
		$opts.appendTo($div);
		
		$('#questionSelected').val(totalPreSelected);
		$('<div class="clear"></div>').appendTo($div);
		
		$('#questionsViewer').append($div);
		
		setHeightFix();			
	});

	
	var _title = "";
	var __prev_title = "";
	var gg = 0;
	
	Manual_setFilterArr();
	
	$('.expand').off('click');
	
	$('.expand').on('click', function () 
	{	
		if($(this).hasClass('fa-plus-circle'))
		{
			$(this).removeClass('fa-plus-circle').addClass('fa-minus-circle');
			$(this).parent().parent().find('.main_titles').not('.extra_titles').removeClass('hide');
		}
		else 
		{
			$(this).addClass('fa-plus-circle').removeClass('fa-minus-circle');
			$(this).parent().parent().find('.main_titles').not('.extra_titles').addClass('hide');
		}		
	})
	
	headingColor($('.hTitle'));
	
	$('#totalQuestions').val(counter);
	setNumberingManualMode();
}

function Manual_setFilterArr()
{
	M_filterArr = [];
	
	checkParent();
	var $_div = $('#questionsViewer').find('.question-parent');
	
	push_filter_arr_values(M_filterArr, manual_types, $_div, "mtitle", "data-cid");
	
	var zzz = 0;
	var ff = 0;
	var titles = "";
	var _class = '';
	
	for(var o in M_filterArr)
	{
		_class = '';
		
		M_filterArr[o].ID.push(replacespecialCharacters(M_filterArr[o].type));
		
		$('#questionsViewer').append('<div class = "main_types" id =head_' + M_filterArr[o].ID + '></div>');
		
		if(M_filterArr[o].type.indexOf("Extra Question") != -1) 
		{
			_class = 'hide';
			$('#questionsViewer').find('#head_' + M_filterArr[o].ID).append('<p class = "main_titles extra_titles">'+M_filterArr[o].type+'<i class="fa fa-plus-circle expand"></i></div>');
		}
		
 		for(var k=0; k<M_filterArr[o].FinalTitle.length; k++)
		{
			titles = replacespecialCharacters(M_filterArr[o].FinalTitle[k]);
			
			ff++;
			$('#questionsViewer').find('#head_' + M_filterArr[o].ID).append('<div class = "main_titles '+ _class +'" id = ques_' + titles + '></div>');

			$('#questionsViewer').find('#head_' + M_filterArr[o].ID).find('#ques_' + titles).prepend('<div class="question-title hTitle">'+ M_filterArr[o].FinalTitle[k] + '</div><hr class="_hr">');
			
			zzz = 0;
			
			if(M_filterArr[o].type == "Passage" || M_filterArr[o].type == "Poem")
			{
				for(var j=0; j<M_filterArr[o].Passage[k].length; j++)
				{
					if(j == 0)
					{
						$('<div class="passages" id=passage_' + (j+1) +	'><div class="passage">'+ M_filterArr[o].Passage[k][j] + '</div></div>').insertAfter($('#questionsViewer').find('#head_' + M_filterArr[o].ID).find('#ques_' + titles).find('._hr'));
					}
					else
					{
						$('#questionsViewer').find('#head_' + M_filterArr[o].ID).find('#ques_' + titles).append('<div class="passages" id=passage_' + (j+1) +'><div class="passage">'+ M_filterArr[o].Passage[k][j] + '</div></div>');
					}

					for(var n=0; n<M_filterArr[o].PassageHeaders[k][j].length; n++)
					{
						$('#questionsViewer').find('#head_' + M_filterArr[o].ID).find('#ques_' + titles).find('#passage_' + (j+1)).append('<div class="question-passage_headers" id=passage_'+ (j+1) +'_passageHead_' + (n+1) +'><div class="question-passage_header redheading">' + M_filterArr[o].PassageHeaders[k][j][n] + '</div></div>');
						
						$_div.each(function(i, e)
						{
							if($(this).attr('data-type') == M_filterArr[o].type)
							{
								if(questions[$(this).attr('data-cid')-1].question.passage == M_filterArr[o].Passage[k][j])
								{
									if($(this).attr('data-phead') == M_filterArr[o].PassageHeaders[k][j][n])
									{
										$('#questionsViewer').find('#head_' + M_filterArr[o].ID).find('#ques_' + titles).find('#passage_' + (j+1)).find('#passage_' + (j+1) + '_passageHead_' + (n+1)).append($(this));	
									}
								}
							}
						})
					}		
				}								
			}
			else 
			{
				$('#questionsViewer').find('.question-parent').each(function(i, e)
				{
					if($(this).attr('data-type') == M_filterArr[o].type)
					{
						if($(this).attr('data-mtitle') == M_filterArr[o].FinalTitle[k])
						{							
							$('#questionsViewer').find('#head_' + M_filterArr[o].ID).find('#ques_' + replacespecialCharacters(M_filterArr[o].FinalTitle[k])).append($(this));
						}
					}
				})
			}
		}
	}
}
	
function setNumberingManualMode()
{
	var _counts = 0;
	
	$('.question-passage_headers').each(function(i, e)
	{
		_counts = 0;
		
		$(this).find('.question-parent').each(function(i, e)
		{
			_counts++;
			$(this).find('.numbers').html(_counts + ". ");
		})
	})
	
	$('.main_titles').each(function(i, e)
	{
		_counts = 0;
		
		$(this).find(' > .question-parent').each(function(i, e)
		{
			_counts++;
			$(this).find('.numbers').html(_counts + ". ");
		})
	})
}

function pushIds(ele, _type)
{
	var _cid = $(ele).parent().attr('data-cid');
	
	console.log(testTypeBank);
	if($(ele).prop('checked'))
	{
		testTypeBank[_type].push(_cid);
	}
	else 
	{
		var ind = Number(testTypeBank[_type].indexOf(_cid));
		testTypeBank[_type].splice(ind, 1);
	}
	
	testBank = [];
	for(var i = 0; i< Object.keys(testTypeBank).length; i++)
	{
		let key = Object.keys(testTypeBank)[i];
		if(testTypeBank[key].length)
		{
			for(var k = 0; k< testTypeBank[key].length; k++)
			{			
				testBank.push(testTypeBank[key][k]);
				console.log(testTypeBank[key], testTypeBank[key].length);			
			}
		}
	}
	
	console.log(testTypeBank, testBank);
	
	//testBank.sort(function(a,b){return a-b});
	$('#cartItems').text(testBank.length);
}

function replacespecialCharacters(str)
{
	//var _match_titles = str.replace(/[^\w\s]/gi, '');	
	var _match_titles = str;
	//console.log(_match_titles)
	for(var i = 0; i <specialchar.length; i++)
	{
		//console.log(specialchar[i]);
		_match_titles = replaceAll(_match_titles, specialchar[i], "_");
	}
	
	return _match_titles;
};
//create folder structure
function createFolder(folderName)
{
	var $folder = $('<div></div>').attr('class', 'main');
	$('<div></div>').attr('class', 'folder').append('<div class="front"></div><div class="back"></div>').appendTo($folder);
	$('<div></div>').attr('class', 'folder_name').append('<a href="#">' + folderName + '</a>').appendTo($folder);
	return ($folder);
}

var totalMarksSummary = 0;
var difficultySummary = {
	'E': 0,
	'M': 0,
	'H': 0
};

var outcomeSummary = {};

function addToTest() 
{	
	testBank = uniqueArray(testBank);
	
	if(!testBank.length)
	{
		showMsgBox("Please select at least 1 question.");
		return;
	}
	
	checkParent();
	
	$(_parent).find('#pdfPreview').empty();
	used_Save_Print = false;
	
	testBank = uniqueArray(testBank);
	
	selectChapters = [];
	$(".practive").removeClass('practive');
	
	if(removed)
	{
		//$(_parent).find('#pdfPreview').empty();
		fetch_Data();
		ModifyUniqueTypeArr(uniquetype);
		setFilterArr();		
		setNumbering();	
		//toggleAnswers();	
	}
	else 
	{
		setFilterArr();
		setNumbering();	
	}
	
	addMarksInputEvent();
	
	jQuery('#sContainIn .topTitlez').each(function(e){
		if(!jQuery(this).find('.question-parent').length)
		{
			jQuery(this).remove();
		}
	});
	
	if(testBank.length == 0) {
		switchScreen('level1');
	}
	
	if(removed)
	{
		prepareSummary();
	}
	
	/* if(document.getElementById("student-version-m").checked == true) {
		$('.marksDiv').hide();
	} */
	
	
	if(removed) removed = false;
}

function addMarksInputEvent()
{
	setTimeout(function () {
		$('.marksInput').on('focus', handleMarksInputF);
		$('.marksInput').on('blur', handleMarksInputB);
	},1000);
}	

function fetch_Data()
{
	difficultySummary = {
		'E': 0,
		'M': 0,
		'H': 0
	}
	
	outcomeSummary = {};
	totalMarksSummary = 0;
		
	for(var i=0; i<testBank.length; i++)
	{
		insertQuestion($('#pdfPreview'), testBank[i]);
	}
	
	for(var zz=0; zz<selectChapters.length; zz++) {
		$("#" + selectChapters[zz]).addClass('practive');
	}
	
	//var categoriges = $(_parent).find('#pdfPreview').find('#sContainIn').children().map(function(){ return this.dataset.title; }).get();
	var chapters = $(_parent).find('#pdfPreview').find('#sContainIn').children().map(function(){ return this.dataset.chapter; }).get();
	var category = $(_parent).find('#pdfPreview').find('#sContainIn').children().map(function(){ return this.dataset.category; }).get();
	
	var type = $(_parent).find('#pdfPreview').find('#sContainIn').children().map(function(){ return this.dataset.type; }).get();
	var marks = $(_parent).find('#pdfPreview').find('#sContainIn').children().map(function(){ return this.dataset.marks; }).get();
	
	chapters = uniqueArray(chapters);
	//categoriges = uniqueArray(categoriges);
		
	var uniquecategory = [];
	$.each(category, function(i, el){
    	if($.inArray(el, uniquecategory) === -1) uniquecategory.push(el);
	});	
	
	uniquetype = [];
	$.each(type, function(i, el){
    	if($.inArray(el, uniquetype) === -1) uniquetype.push(el);
	});
	
	
}

function actionReplaceBtn() {
	$(".tool-replace").each(function(i, e) {
		var replacerId = $(this).parent().parent().attr('id');
		
		$('#replaceList').empty();
		var $quesContainer = $(this).parent().parent();
		var subject = $quesContainer.attr('data-subject');
		var chapter = $quesContainer.attr('data-chapter');
		var category = $quesContainer.attr('data-category');
		var marks = $quesContainer.attr('data-marks');
		
		var topic = $quesContainer.attr('data-topic');
		var type = $quesContainer.attr('data-type');
		var index = $quesContainer.attr('data-index');

		var oldQuery = new Object();
		if(type != undefined) oldQuery['type'] = type;
		if(topic != undefined) oldQuery['topic'] = topic;
		if(chapter != undefined) oldQuery['chapter'] = chapter;
		if(subject != undefined) oldQuery['subject'] = subject;
		if(category != undefined) oldQuery['category'] = category;
		if(index != undefined) oldQuery['index'] = index;
		
		if(marks != undefined) oldQuery['mark'] = marks;
		
		var totalQuestion = allQuestions(oldQuery);

		uniqueQues = [];
		totalQuestion.each(function(r) {
			var idq = String(r.id);
			if(testBank.indexOf(idq) == -1) {
				uniqueQues.push(idq);
			}
		})
		if(uniqueQues.length == 0) {
			$(this).attr('disabled', 'disabled');
		}
	});
}

function disableReplaceBtn() {
	return false;
	$("#level2 #pdfPreview").hide();
	setTimeout(function() {
		
		$("#level2 #pdfPreview").show();
		actionReplaceBtn();
	}, testBank.length * 500);
}

function prepareSummary () 
{
	var summary = {};
	summary["questions"] = testBank.length;
	summary["marks"] = totalMarksSummary;
	summary["difficulty"] = [];
	//summary["outcome"] = [];
	/* 
	if(difficultySummary["E"] != 0) {
		summary["difficulty"].push("Easy: " + difficultySummary["E"]);
	}
	if(difficultySummary["M"] != 0) {
		summary["difficulty"].push("Medium: " + difficultySummary["M"]);
	}
	if(difficultySummary["H"] != 0) {
		summary["difficulty"].push("Hard: " + difficultySummary["H"]);
	} */
/* 
	for (var key in outcomeSummary) {
		if(outcomeSummary[key] == undefined || outcomeSummary[key] == null || outcomeSummary[key] == "") {
			delete outcomeSummary[key];
		} else {
			summary["outcome"].push(key + ": " + outcomeSummary[key]);
		}
	}
	 */
	checkParent();
	//console.log(totalMarksSummary);
	$(_parent).find('#pdfPreview').append('' +
	'<div class="summary-selection">' +
		'<div class="summary-container">' +
			'<div class="summary_leftpane">' +
				/* '<div class="summary-total">' +
					'<p>Total Questions: <span>' + questions.length + '</span></p>' +
				'</div>' +
	 */			'<div class="summary-marks">' +
					'<p>Questions: <span>' + summary["questions"] + '</span></p>' +
				'</div>' +
				'<div class="summary-totals">' +
					'<p>Marks: <span>' + summary["marks"] + '</span></p>' +
				'</div>' +
			'</div>' +
			'<div class="summary_rightPane">' +
				'<div class="macm_logo">' +
					'<button class="info_btn" id="test_save" onclick="createFontDialogBox();">Add Details</button>' +
				'</div>' +
			'</div>' +
		'</div>' +
	'</div>');
}

function checkParent()
{
	if(window.savedEditType == "auto" || tgType == "auto")
	{
		_parent = $("#level2");
	}
	else _parent = $("#level2");
}

function checkParentlastScreen()
{
	if(window.savedEditType == "auto" || tgType == "auto")
	{
		_parent = $("#level3");
	}
	else _parent = $("#level3");
}

function checkParentLast()
{
	if(window.savedEditType == "auto" || tgType == "auto")
	{
		_parentLast = $("#level3");
	}
	else _parentLast = $("#level3");
	
	return _parentLast;
}

function toggleAnswers()
{
	checkParentlastScreen();

	if($('.select_copy')[0].selectedIndex == 0)
	{
		include_ans = true;
	}
	else if($('.select_copy')[0].selectedIndex == 1)
	{
		include_ans = false;
	}

	if(!include_ans) 
	{
		$(_parent).find('.question-answer').css('display','none');
		$(_parent).find('.question-title').find('table tr:last').css('display','none');	
	}
	else 
	{
		$(_parent).find('.question-answer').css('display','none');
		$(_parent).find('.question-title').find('table tr:last').css('display','table-row');
	}
}
 
function toggleMarks()
{
	checkParent();
	
	if($(_parent).find('#student-version-m').prop("checked")) 
	{
		showMarks = false;
		$('.marksDiv').hide();
		$('.marks p').hide();
	}
	else 
	{
		showMarks = true;
		$('.marksDiv').show();
		$('.marks p').show();
	}
}

function print_option()
{
	$('#print_option').show();
}

function showCart()
{
	showAutoPage = false;
	$('#level1, #auto-page2, #activityArea, #typeAuto').hide();
	$('#level2').show();	
	$('#showCartBtn').hide();
	setHeightFix();
}

function enterEdit(e)
{
	$(this).attr({'contenteditable': true, 'spellcheck': false}).focus();
	$(this).on('keydown', handleEnter);
}

function handleEnter(e)
{
	if(e.keyCode == 13)
	{
		$(this).blur().attr('contenteditable', false);
		return false;
	}
}

function handleMarksInputF(e)
{
	if(this.value == "0")
		this.value = "";
	
	//if(marks_count == 0) alert(marks_alert);
	marks_count++;
}

function handleMarksInputB(e)
{
	if(this.value == "")
		this.value = "0";
	
	var givenMarks = this.value;
	
	var _quesID = $(this).parents('.question-parent').attr('id');
	
	$('.marksInput').each(function (index, element)
	{
		var quesID = $(this).parents('.question-parent').attr('id');
		var $parent = '';
		
		if($(this).parents('.question-parent').attr('data-type') == 'Passage' || $(this).parents('.question-parent').attr('data-type') == 'Poem')
		{
			$parent = $(this).parents('.question-parent').parent().parent().parent();	
		}
		else $parent = $(this).parents('.question-parent').parent();
		
		$(this).parents('.question-parent').attr('data-marks', $(this).val());
		
		var qTitle = $parent.find(".main_Div_table").find(".questionsSS").html();
				
		$parent.find(".question-parent").each(function (e)
		{
			var _ids = parseInt($(this).attr('id'));
			//console.log(allQuestions({id: _ids}).first(), ' final');
			allQuestions({id: _ids}).first().question.title = qTitle;
			//console.log(qTitle, _ids, ' qTitle');
		})
	})
	
	allQuestions({id:parseInt(_quesID)}).each(function(r)
	{
		r.mark = givenMarks;
	});
	
	setFilterArr();
	
	/* if(tgType == "auto")
	{
		addToTestAuto(testBank);
	} else 
	{
		addToTest();
	} */
}

function escapeRegExp(string) {
    return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}

function replaceAll(string, find, replace) {
  return string.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}

function nextChar(c) {
    return String.fromCharCode(c.charCodeAt(0) + 1).toUpperCase();
}

function setNumbering()
{
	
	var _counts = 0;
	
	$(_parent).find('.question-passage_headers').each(function(i, e)
	{
		_counts = 0;
		
		$(this).find('.question-parent').each(function(i, e)
		{
			_counts++;
			$(this).find('.numbering').html(_counts + ". ");
		})
	})
	
	$(_parent).find('.main_titles_Div').each(function(i, e)
	{
		_counts = 0;
		
		$(this).find(' > .question-parent').each(function(i, e)
		{
			_counts++;
			$(this).find('.numbering').html(_counts + ". ");
		})
	})

}

function romanize (num) 
{
    if (isNaN(num))
        return NaN;
    var digits = String(+num).split(""),
        key = ["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM",
               "","X","XX","XXX","XL","L","LX","LXX","LXXX","XC",
               "","I","II","III","IV","V","VI","VII","VIII","IX"],
        roman = "",
        i = 3;
    while (i--)
        roman = (key[+digits.pop() + (i * 10)] || "") + roman;
    return '(' + Array(+digits.join("") + 1).join("M") + roman + ') ';
}

function insertQuestion($container, ids)
{
	console.log('sdsdsds');
	allQuestions({id:parseInt(ids)}).each(function(r)
	{
		/* var mark = parseInt(r.mark);
		//console.log(mark, ' mark');
		if(typeof mark == "number") {
			totalMarksSummary += mark;
		}

		difficultySummary[r.difficulty]++;

		if(outcomeSummary[r.outcome] == undefined || outcomeSummary[r.outcome] == null ) {
			outcomeSummary[r.outcome] = 1;
		} else {
			outcomeSummary[r.outcome]++;
		}

		var qID = replaceAll(r.type, " ", "").toLowerCase(); */
		var qID = "sContainIn";
						
		if(!$(_parent).find('.sContainIn').length)
		{
			$container.append('<div id="sContainIn" class = "sContainIn"></div>');
		}
		
		if($('#' + qID).length == 0) {
			$('<div class="topTitlez"></div>').attr({id: qID}).html('<h3>' + r.question.title + '</h3>').appendTo('#sContainIn');
		}
		
		var _catArr = [];
		var _typeArr = [];
		
		for(key in parentsobjHandle) {
			if(parentsobjHandle[key] == r.chapter)
				selectChapters.push(key);
		}
			
		var type = r.type;
		
		//defineTypeSequence(r);
		var meta_val = '';
		
		if(r.metadata =="")
		{
			meta_val = "$";
		}
		else 
		{
			meta_val = r.metadata;
		}
		
		var $div = $('<div class="question-parent"></div>')
						.attr({
								'id': r.id,
								'data-class': r.class,
								'data-type': r.type,
								'data-chapter': r.chapter,
								'data-topic': r.topic,
								'data-subject': r.subject,
								'data-title': r.question.title,
								'data-Phead': r.question.passageRubric,	
								'data-rubric': r.question.rubric,
								'data-category': r.outcome,
								'data-marks': r.mark,
								'data-index': r.ind,
								'data-meta': meta_val
							});		
		//console.log(r.question.title, r);
		$('<label></label>').addClass('numbering').appendTo($div);
		if(r.mark == null) r.mark = "0";
		
		$inpMarks = $('<input class="marksInput" />').attr({type: 'text', value: r.mark, 'maxlength': 5, onkeydown:'return numValidate(event)'})
		$('<div id="marksDiv-id" class="marksDiv"></div>').append('<span>Marks</span>').append($inpMarks).appendTo($div);
				
		var $opts;

		var bulleting = '';
		
		if((type.toLowerCase() == All_typess[1].toLowerCase() || type.toLowerCase() == All_typess[11].toLowerCase() || type.toLowerCase() == All_typess[12].toLowerCase())&& r.topic != "Custom Other") {
			bulleting = '<span class="bullettop">&nbsp;&nbsp;&nbsp;</span> ';
		}	
		
		for(var q in r.question)
		{
			if(q == "title")
			{
				$('<div class="question-title rx-editable tt"></div>').html(r.question.rubric).appendTo($div);
			}
			else if(q == "image")
			{
				if(r.question.image != undefined && r.question.image != '') {
					var qimagepathblob = imagePath+r.question.image;
					if(r.question.image.indexOf("blob:") == 0) {
						qimagepathblob = r.question.image;
					}
					$('<div class="image"></div>').html('<img src="'+qimagepathblob+'"/>').appendTo($div);
				}
			}
			else if(q == "option")
			{
				$opts = $('<div class="options"></div>');
				if((r.type == All_typess[3]) || (r.type == All_typess[6]) || (r.type == All_typess[7])) 
				{
					if(r.question.option[0] != undefined)
					{
						if(r.question.option[0].indexOf(" ^ ") != -1)
						{						
							var optnameii = "<br><table class= 'data_table' cellspacing='0' cellpadding='0'>";
							for(var mtfIndex=0; mtfIndex<r.question.option.length; mtfIndex++) 
							{
								var optnameiis = r.question.option[mtfIndex];
								
								var mtfoption = optnameiis.split(" ^ ");
								
								optnameii += "<tr><td width='50%'>" + mtfoption[0] + "</td><td width='50%'>" + mtfoption[1] + "</td></tr>";
							}
							optnameii += "</table>";

							$('<div class="option rx-editable"></div>').html(optnameii).appendTo($opts);
						}
						else 
						{
							for(var z=0; z<r.question.option.length; z++)
							{
								var optnameii = r.question.option[z];
								
								if(optnameii.indexOf(".jpg") != -1 || optnameii.indexOf(".png") != -1) {
									optnameii = "<img src='" + imagePath + r.question.option[z] + "'>"
								}	

								$('<div class="question-title"></div>').html(bulleting + optnameii).appendTo($opts);
							}
						}
					}
				}
				else if((r.type == All_typess[8])){
					for(var z=0; z<r.question.option.length; z++)
					{
						var optnameii = r.question.option[z];
						
						bulleting = romanize(z+1);
						if(optnameii.indexOf(".jpg") != -1 || optnameii.indexOf(".png") != -1) {
							optnameii = "<img src='" + imagePath + r.question.option[z] + "'>"
						}

						$('<div class="question-title"></div>').html(bulleting + optnameii).appendTo($opts);
					}
				}
				else {

					if(r.question.option.length == 1)
					{
						var z = 0;
						var optnameii = r.question.option[z];
						if(optnameii.indexOf(".jpg") != -1 || optnameii.indexOf(".png") != -1) {
							optnameii = "<img src='" + imagePath + r.question.option[z] + "'>"
						}
						$('<div class="option rx-editable"></div>').html(bulleting + optnameii).appendTo($opts);
					}
					else
					{
						for(var z=0; z<r.question.option.length; z++) {
							//$('<div class="option rx-editable"></div>').html(String.fromCharCode(65+z) + '. ' + r.question.option[z]).appendTo($opts);

							var optnameii = r.question.option[z];
							if(optnameii.indexOf(".jpg") != -1 || optnameii.indexOf(".png") != -1) {
								optnameii = "<img src='" + imagePath + r.question.option[z] + "'>"
							}
							
							$('<div class="option rx-editable"></div>').html(bulleting + optnameii).appendTo($opts);	
						}
					}					
				}				
			}
		}
		$opts.appendTo($div);		
		
		//console.log($div, ' this');
		
		if(r.question.answer != "" && r.question.answer != null)
		{
			if( Object.prototype.toString.call( r.question.answer ) === '[object Array]')
			{				
				$ans = $('<div class="question-answer rx-editable"></div>').html('<div class="ansHeading">Answer:</div>');
				
				if(r.question.answer.length == 1)
				{
					var z = 0;
					var optnameii = r.question.answer[z];
					//console.log(r.question.answer[z]);
					if(optnameii.indexOf(".jpg") != -1 || optnameii.indexOf(".png") != -1) {
						//optnameii = "<img class='ansImg' src='" + imagePath + r.question.answer[z] + "'>";
					}
					
					optnameii = optnameii.split("^").join("-");
					$ans.append("<div class='simp-ans-text'>" + optnameii + "</div>");	
				}
				else
				{
					for(var z=0; z<r.question.answer.length; z++)
					{
						var optnameii = r.question.answer[z];
						if(optnameii.indexOf(".jpg") != -1 || optnameii.indexOf(".png") != -1) {
							//optnameii = "<img class='ansImg' src='" + imagePath + r.question.answer[z] + "'>"
							
						}
						optnameii = optnameii.split("^").join("-");
						$ans.append("<div class='simp-ans-text'>" + optnameii + "</div>");						
					}
				}
				$ans.appendTo($div);
			}
			else
			{
				$('<div class="question-answer rx-editable"></div>').html('<div class="ansHeading">Answer:</div> ' + r.question.answer).appendTo($div);
			}
		}
/* 
		$div.append('' +
		'<div class="question-info">' + 
			'<div class="question-difficulty">Difficulty: <span>' + EDIF[r.difficulty] + '</span></div>' +
			'<div class="question-outcome">Learning Outcome: <span>' + r.outcome + '</span></div>' +
		'</div>'); */

 		var $tools = $('<div class="mx-tools"></div>').appendTo($div);
		
		/*$('<a href="javascript:void(0)"></a>')
			.html('Replace')
			.attr({'class': 'tool-replace'})
			.click(function(i, e)
			{
					if($(this).attr('disabled') == 'disabled') {
						return false;
					}
					
					var replacerId = $(this).parent().parent().attr('id');
					
					$('#replaceList').empty();
					
					var oldQuery
					var $quesContainer = $(this).parent().parent();
					var subject;
					var chapter;
					var topic;
					var type;
					var metadata = "";
					
					subject = $quesContainer.attr('data-subject');
					type = $quesContainer.attr('data-type');

					if(_meta)
					{	
						oldQuery = new Object();
						metadata = finalmeta.join(', ');
						if(type != undefined) oldQuery['type'] = type;
						if(subject != undefined) oldQuery['subject'] = subject;
					}
					else 
					{			
						chapter = $quesContainer.attr('data-chapter');
						topic = $quesContainer.attr('data-topic');
						
						oldQuery = new Object();
						if(type != undefined) oldQuery['type'] = type;
						if(subject != undefined) oldQuery['subject'] = subject;
						if(topic != undefined) oldQuery['topic'] = topic;
						if(chapter != undefined) oldQuery['chapter'] = chapter;
					}
					
					var totalQuestion = allQuestions(oldQuery);
					var counter = 0;
					sQn = 0;
					totalQuestion.each(function(r)
					{
						if(_meta)
						{
							if(r.metadata != '')
							{
								var all_meta_in_ques = r.metadata.toLowerCase();
								var _length = all_meta_in_ques.split('||');
								
								var _word  = '';
								
							 	for(var jj = 0; jj< _length.length; jj++)
								{
									_word = _length[jj];
									
									if(finalmeta.indexOf(_word) != -1)
									{
										replaceQues(r, replacerId, counter, $quesContainer);
									}
								}
							}
						}
						else replaceQues(r, replacerId, counter, $quesContainer);					
					});
					
					$('#replaceQuestion').show();
					
					if($('#replaceList').is(':empty'))
					{
						$('#replaceList').html('<div style="text-align: center; line-height: 300px;">No, similar questions available.</div>');
					}
					else 
					{
						if($(this).parent().parent().attr('data-type') != "Short-answer questions" && $(this).parent().parent().attr('data-type') != "Long-answer questions")
						{
							$('#replaceList').prepend('<div class="question_rubric_replace">'+$(this).parent().parent().attr('data-title')+'</div>');
						}
					}

			}).appendTo($tools); */

			$('<a href="javascript:void(0)"></a>')
			.attr('title','delete')
			.attr({'class': 'tool-remove'})
			.click(function(i, e)
			{
				var _this = this;
				removed = true;
				jQuery.confirm({
					title: 'Do you want to delete this question?',
					content: '',
					buttons: {
						confirm: function () {
							var currentId = jQuery(_this).parent().parent().attr('id');
							
							var curIndex = testBank.indexOf(String(currentId));
							
							testBank.splice(curIndex, 1);
							
							jQuery('div.question-parent').filter(function(i,e)
							{
								 return (jQuery(this).attr('data-cid') == currentId);
							}).removeAttr('disabled').prop('checked', false).removeClass('selection');
							
							var $parent = $(_this).parents('.main_Div');
							var qTitle = $parent.find(".main_Div_table").find(".questionsSS").html();
							
							console.log(qTitle);
							$parent.find(".question-parent").each(function (e) { 
								var _ids = parseInt($(this).attr('id'));
								allQuestions({id: _ids}).first().question.title = qTitle;
							})
							
							//$('.question-parent[id='+currentId+']').remove();
							//setFilterArr();
							addToTest();
						},
						cancel: function () {
							
						}
					}
				});
				//removed = false;				
			}).appendTo($tools);
			
			/*$('<a href="javascript:void(0)"></a>')
				.html('Edit')
				.attr({'class': 'tool-edit'})
				.click(function(e) {
					if($(this).html() == "Edit") alert(added_alert);
					var _this = this;
					if($(_this).parents('.question-parent').hasClass("editingmode-on")) {
						var $parent = $(_this).parents('.question-parent');

						$(_this).parents('.question-parent').find('.rx-editable').attr('contenteditable', false);
						$(_this).parents('.question-parent').removeClass("editingmode-on");
						_this.textContent = "Edit";
												
						var qTitle = $parent.parent().find(".main_Div_table").find(".questionsSS").html();
						var qRubric = $parent.find(".question-title").html();
						var qOptions = $parent.find('.option.rx-editable').map(function(e) {
							return this.innerHTML
						}).get();
						var answer = $parent.find(".simp-ans-text").html();
						var image = $parent.find('.image').html();
						// filter data
						var tmp = document.createElement('div');

						if(image == undefined) {
							image = "";
						} else {
							tmp.innerHTML = image;
							var src = tmp.getElementsByTagName('img')[0].src;
							image = src;
						}
						
						for(var i=0; i<qOptions.length; i++) {
							if(qOptions[i].indexOf("<img src") != -1) {
								tmp.innerHTML = qOptions[i];
								var src = tmp.getElementsByTagName('img')[0].src;
								qOptions[i] = src;
							} else {
								qOptions[i] = qOptions[i].split('<span class="bullettop">●</span> ').join('');
							}
						}
						if(answer.indexOf("<img src") != -1) {
							tmp.innerHTML = answer;
							var src = tmp.getElementsByTagName('img')[0].src;
							answer = src;
						}
						
						var id = parseInt($parent.attr('id'));
						//console.log($(_this).parents('.question-parent'), qTitle);

						$(_this).parents('.question-parent').each(function (e) { 
							var _ids = parseInt($(this).attr('id'));
							allQuestions({id: _ids}).first().question.title = qTitle; 
						})
						allQuestions({id: id}).first().question.rubric = qRubric;
						allQuestions({id: id}).first().question.option = qOptions;
						allQuestions({id: id}).first().answer = [answer];
					} else {
						$(_this).parents('.question-parent').find('.rx-editable').attr('contenteditable', true);
						$(_this).parents('.question-parent').addClass("editingmode-on");
						_this.textContent = "Save";
						$(_this).parents('.question-parent').find('.rx-editable').first().focus();
					}
				})
			.appendTo($tools); */
			
		$('<div class="clear"></div>').appendTo($div);
		$div.appendTo($container.find('#'+qID));
	});	
}

function replaceQues(r, replacerId, counter, __this)
{
	/* if($.inArray(String(r.id), testBank) == -1)
	{
		counter++;
		{
			sQn++;
			var $div = $('<div class="question-parent"></div>').attr({id: 'fib', 'data-type': r.type, 'data-cid': r.id});
			var $checkbox = $('<input/>').attr({type: 'checkbox', id: 'check' + counter});

			$checkbox.appendTo($div).click(function(e)
			{
				var curIndex = testBank.indexOf(String(replacerId));
				testBank[curIndex] = String(r.id);
				$('#replaceQuestion').hide();
				$('#explorer').empty()
				
				var $parent = $(__this).parents('.main_Div');
				var qTitle = $parent.find(".main_Div_table").find(".questionsSS").html();
				
				$parent.find(".question-parent").each(function (e) { 
					var _ids = parseInt($(this).attr('id'));
					allQuestions({id: _ids}).first().question.title = qTitle;
				})
				addToTest();
			});
			var $opts;
			for(var q in r.question)
			{
				if(q == "title")
				{
					$('<div class="question-title"></div>').html(sQn + '. ' + r.question.rubric).appendTo($div);
				}
				else if(q == "image")
				{
					if(r.question.image != undefined && r.question.image != '') {
						var qimagepathblob = imagePath+r.question.image;
						if(r.question.image.indexOf("blob:") == 0) {
							qimagepathblob = r.question.image;
						}
						$('<div class="image"></div>').html('<img src="'+qimagepathblob+'"/>').appendTo($div);
					}
				}
				else if(q == "option")
				{
					$opts = $('<div class="options"></div>');
					
					if(r.type == All_types[3]) {
						var optnameii = "<br><table class= 'data_table' cellspacing='0' cellpadding='0'>";
						for(var mtfIndex=0; mtfIndex<r.question.option.length; mtfIndex++) {
							var optnameiis = r.question.option[mtfIndex];
							
							var mtfoption = optnameiis.split(" ^ ");
							
							optnameii += "<tr><td width='50%'>" + mtfoption[0] + "</td><td width='50%'>" + mtfoption[1] + "</td></tr>";
						}
						optnameii += "</table>";
	
						$('<div class="option rx-editable"></div>').html(optnameii).appendTo($opts);
					} else {

						if(r.question.option.length == 1)
						{
							var z = 0;
							var optnameii = r.question.option[z];
							if(optnameii.indexOf(".jpg") != -1 || optnameii.indexOf(".png") != -1) {
								optnameii = "<img src='" + imagePath + r.question.option[z] + "'>"
							}
							$('<div class="question-title"></div>').html(optnameii).appendTo($opts);													
						}
						else
						{
							for(var z=0; z<r.question.option.length; z++) {
								
					
								var optnameii = r.question.option[z];
								if(optnameii.indexOf(".jpg") != -1 || optnameii.indexOf(".png") != -1) {
									optnameii = "<img src='" + imagePath + r.question.option[z] + "'>"
								}
								
								$('<div class="question-title"></div>').html(optnameii).appendTo($opts);				
							}
						}												
					}
				}
			}
			$opts.appendTo($div);
			$('<div class="clear"></div>').appendTo($div);
			$('#replaceList').append($div);
		}
	} */
}

function numValidate(event) {
    /* var key = window.event ? event.keyCode : event.which;

	if (event.keyCode == 8 || event.keyCode == 46
	 || event.keyCode == 37 || event.keyCode == 39) {
			return true;
		}
		else if ( (key >= 48 && key <= 57) || (key >= 96 && key <= 105) ) {
			return true;
		}
		else return false; */
};

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

function setActionForSavingMarks() {
	$('body').on('blur', '.topTitlez .marksInput', function() {
		if(this.value != "" && this.value != 0) {
			var marks = this.value;
			var id = $(this).parents('.question-parent').attr('id');
			allQuestions({id: parseInt(id)}).first().mark = marks;
		}		
	});
}

function addAndMoveOn()
{
	//console.log('sds');
	addToTest();
	if(!testBank.length) return;
	
	used_Save = false;
	
	$('#explorer').hide();
	$('#auto-page2').show();
	showAutoPage = true;
	setAutoPagePosition();
	autoDB = new TAFFY();
	
	for(var i=0; i<testBank.length; i++) 
	{
		autoDB.insert(questions[testBank[i]-1]);
	}
	
	$('#level1_explorer #container').addClass('diaableitem');
	insertTypes(All_types,1);
}

$(window).resize(function () {
	setHeightFix();
	setAutoPagePosition();
	setAutolist();
})

function setAutoPagePosition()
{
	var _side_panel = "";
	var _side_panel_top = "";
	var _side_panel_left = "";
	var auto_page_height = "";
	
	if(window.tgType == "manual")
	{
		_side_panel = $('#level1 #level1_explorer');
		_side_panel_top = $('#topHeader');
		_side_panel_left = $('#collectionList');
	}
	else 
	{
		_side_panel = $('#mainFrame');
		_side_panel_top = $('.auto-toptitle');
		_side_panel_left = $('#sidePanel-auto');
	}
	
	var mainframeH = "";	
	
	if(screen.width < 1024 && screen.width > screen.height)
	{
		mainframeH = _side_panel.position().top + _side_panel.height();
	}
	else if(screen.width < 1024 && screen.width < screen.height)
	{
		mainframeH = _side_panel.position().top + _side_panel.height();
	}
	else 
	{	
		mainframeH = _side_panel_top.height();
	}
	
	//console.log(_side_panel_left, _side_panel_top);
	
	if(showAutoPage) 
	{		
		$("#auto-page2").show();
	
		$('#auto-page2').css({
			'left':_side_panel_left.width(),
			'top':mainframeH,
			'height':$(window).height() - _side_panel_top.height()
		})
	}
}

function setAutolist()
{
	var win = {
		height: $(window).height(),
		width: $(window).width()
	}
}

function closePopupFromPreview() {
	$(_parent).find('#userInfo').hide();
	resetUserFormPreview();
}

function resetUserFormPreview() {
	$("#level2 #userInfo input[type='text'").val('');
	
	$("#level2 #userInfo input[type='file'").val('')
}

function sort_ind(a,b) {
  if (a.ind < b.ind)
    return -1;
  if (a.ind > b.ind)
    return 1;
  return 0;
}

function defineTypeSequence(r)
{
	for(var i=0; i<All_types.length; i++)
	{
		if(r.type == All_types[i])	r.ind = i;		
	}
}

function ModifyUniqueTypeArr(uniquetype)
{
	/* var tempArr = [];
	
	var mcq,fib,tnf,sa,la,mtf;
	
	tempArr = uniquetype;
	
	fib = tempArr.indexOf(All_types[0]);
	mcq = tempArr.indexOf(All_types[1]);	
	tnf = tempArr.indexOf(All_types[2]);
	mtf = tempArr.indexOf(All_types[3]);
	sa = tempArr.indexOf(All_types[4]);
	la = tempArr.indexOf(All_types[5]);
	pass = tempArr.indexOf(All_types[6]);
	poem = tempArr.indexOf(All_types[7]);
	tick = tempArr.indexOf(All_types[8]);
	underline = tempArr.indexOf(All_types[9]);
	crossword = tempArr.indexOf(All_types[10]);
	circle_underline = tempArr.indexOf(All_types[11]);
	circle = tempArr.indexOf(All_types[12]);
	picture_based = tempArr.indexOf(All_types[13]);
	extra = tempArr.indexOf(All_types[14]);
	
	uniquetype = [];
	
	if(fib != -1) uniquetype.push(tempArr[fib]);
	if(mcq != -1) uniquetype.push(tempArr[mcq]);
	if(tnf != -1) uniquetype.push(tempArr[tnf]);
	if(mtf != -1) uniquetype.push(tempArr[mtf]);
	if(sa != -1) uniquetype.push(tempArr[sa]);
	if(la != -1) uniquetype.push(tempArr[la]);
	if(pass != -1) uniquetype.push(tempArr[pass]);
	if(poem != -1) uniquetype.push(tempArr[poem]);
	if(tick != -1) uniquetype.push(tempArr[tick]);
	if(underline != -1) uniquetype.push(tempArr[underline]);
	if(crossword != -1) uniquetype.push(tempArr[crossword]);
	if(circle_underline != -1) uniquetype.push(tempArr[circle_underline]);
	if(circle != -1) uniquetype.push(tempArr[circle]);
	if(picture_based != -1) uniquetype.push(tempArr[picture_based]);
	if(extra != -1) uniquetype.push(tempArr[extra]); */
	
	return uniquetype;	
}

function modifyArrArray(_arr)
{
	var temp = [];
	
	for(var i=0; i<All_types.length; i++)
	{
		temp[i] = [];		
	}
	
	$.each(_arr, function (index, value)
	{
		for(var i=0; i<All_types.length; i++)
		{
			if(value == All_types[i]) temp[i].push(value);
		}
	})

	_arr = [];
	$.each(temp, function (index, value)
	{	
		if(temp[index].length) 
		{	
			for(var k = 0; k < temp[index].length; k++)
			{
				_arr.push(temp[index][k]);
			}
		}
	})
	
	return _arr;
}

function modifyTitleArray(_arr, _complete_arr)
{
	for(var j=0; j <_complete_arr.Title.length; j++)
	{
		for(var i=0; i <All_types.length; i++)
		{
			if(All_types[i] != undefined)
			{
				if(_complete_arr.type == All_types[i]) _temp[i].push(_complete_arr.Title[j]);
			}
		}
	}
	
	
	for(var i=0; i<All_types.length; i++)
	{
		_temp[i] = uniqueArray(_temp[i]);
	}
		
	_arr = [];
	
	for(var i=0; i<All_types.length; i++)
	{
		if(All_types[i] != undefined)
		{
			if(_complete_arr.type == All_types[i]) _complete_arr.FinalTitle = _temp[i];
		}
	}
	
	_arr = _complete_arr.FinalTitle;
	
	return _arr;
}

function setFilterArr()
{
	filterArr = [];
	checkParent();
	var $_div = $(_parent).find('#sContainIn').find('.question-parent');
	//console.log(filterArr, uniquetype, $_div, "title", "id");
	push_filter_arr_values(filterArr, uniquetype, $_div, "title", "id");
	
	var zzz = 0;
	var ff = 0;
	var titles = "";
	let summarytotalmakrssss = 0;
	
	for(var o in filterArr)
	{
		filterArr[o].ID.push(replacespecialCharacters(filterArr[o].type));
		
		$(_parent).find('#pdfPreview').find('#sContainIn').append('<div class = "main_div" id =main_' + filterArr[o].ID + '></div>');
		
		for(var k=0; k<filterArr[o].FinalTitle.length; k++)
		{
			titles = replacespecialCharacters(filterArr[o].FinalTitle[k]);
			ff++;
			
			if(!$(_parent).find('#main_' + filterArr[o].ID).find('#q_' + titles).length)
			{
				$(_parent).find('#main_' + filterArr[o].ID).append('<br><div class = "main_titles_Div" id =q_' + titles + '></div>');
			}
			
			if(!$(_parent).find('#main_' + filterArr[o].ID).find('#q_' + titles).find('.main_Div_table').length)
			{
				$(_parent).find('#main_' + filterArr[o].ID).find('#q_' + titles).append('<table class = "main_Div_table" style="width: 100%; padding: 5px 0px;"><tr style="break-inside: avoid; break-after: auto; font-weight:bold;"><td width="6%" align="left" class= "sqno" style="vertical-align: top;"><p class="previewNumbering_heading" style="text-align: center;">'+ ff + '.</p></td><td align="left" width="100%" class = "questionsSS" style="vertical-align: top;">' + filterArr[o].FinalTitle[k] + '</td><td width="22%" align="right" class="marks" style="vertical-align: top;"></td></tr></table>');
			}
			
			zzz = 0;
			
			if(filterArr[o].type == "Passage" || filterArr[o].type == "Poem")
			{
				for(var f=0; f<filterArr[o].Passage[k].length; f++)
				{
					if(f == 0)
					{
						$('<div class="passages" id=passage_' + (f+1) +'><div class="passage preview_passage">'+ filterArr[o].Passage[k][f] + '</div></div>').insertAfter($_div.parent().find('#main_' + filterArr[o].ID).find('#q_' + titles).find('.main_Div_table'));
					}
					else
					{
						$_div.parent().find('#main_' + filterArr[o].ID).find('#q_' + titles).append('<div class="passages" id=passage_' + (f+1) +'><div class="passage preview_passage">'+ filterArr[o].Passage[k][f] + '</div></div>');
					}
					
					for(var n=0; n<filterArr[o].PassageHeaders[k][f].length; n++)
					{
						$_div.parent().find('#main_' + filterArr[o].ID).find('#q_' + titles).find('#passage_' + (f+1)).append('<div class="question-passage_headers" id=passage_'+ (f+1) +'_passageHead_' + (n+1) +'><div class="question-passage_header preview_passage redheading">' + filterArr[o].PassageHeaders[k][f][n] + '</div></div>');
					 	
						$_div.each(function(i, e)
						{
							if($(this).attr('data-type') == filterArr[o].type)
							{
								if(questions[$(this).attr('id')-1].question.passage == filterArr[o].Passage[k][f])
								{
									if($(this).attr('data-phead') == filterArr[o].PassageHeaders[k][f][n])
									{
										$_div.parent().find('#main_' + filterArr[o].ID).find('#q_' + titles).find('#passage_' + (f+1)).find('#passage_' + (f+1) + '_passageHead_' + (n+1)).append($(this));	
									}
								}
							}
						}) 
					 } 
				} 
			}
			else
			{
				$_div.each(function(i, e)
				{
					if($(this).attr('data-type') == filterArr[o].type)
					{
						if($(this).attr('data-title') == filterArr[o].FinalTitle[k])
						{
							$_div.parent().find('#main_' + filterArr[o].ID).find('#q_' + titles).append($(this));
						}
					}
				})
			}
			
			totalCat_marks = 0;
				
			$('#sContainIn .question-parent').each(function(i, e)
			{
				if($(this).attr('data-type') == filterArr[o].type)
				{
					if(filterArr[o].FinalTitle[k] == this.dataset.title)
					{
						totalCat_marks += parseFloat(this.dataset.marks);
						$('#' + (filterArr[o].ID)).append($(this));
					}
				}
			})
			
			var __parentDiv = $(_parent).find('#main_' + filterArr[o].ID).find('#q_' + titles);
			
			let totalmakrssss = 0;			
			 
			$(_parent).find('#main_' + filterArr[o].ID).find('#q_' + titles).find('.marksInput').each(function () {
				totalmakrssss += parseFloat($(this).val());			
			});
			
			$(__parentDiv).find('.marks').html("<span class='tot_marks'>[Marks: " + totalmakrssss + "]</span>"); 			
		}
	}

	setTimeout(function () 
	{		
		$(_parent).find('.marksInput').each(function () 
		{
			summarytotalmakrssss += parseFloat($(this).val());			
		});	
		$('.summary-totals span').html(summarytotalmakrssss);
	}, 500);
	
	toggleMarks();
	disableButtonSecondTime();
	
	headingColor($('.questionsSS'));
	headingColor($('.sqno'));
	headingColor($('.marks'));
	
	$('._edit_cat_title').on('click', function ()
	{
		$(this).toggleClass('onEdit');
		
		var $parent = $(this).parents('.main_Div');
		var qTitle = $parent.find(".main_Div_table").find(".questionsSS").html();
		
		if($(this).hasClass('onEdit'))
		{
			$(this).text('Save');
			$(this).parent().find('.main_Div_table').addClass('editingmode-on');
			$(this).parent().find('.main_Div_table').find('.questionsSS').attr('contenteditable',true);
			$(this).parent().find('.main_Div_table').find('.sqno').attr('contenteditable',true);
			
			
			
			$parent.find(".question-parent").each(function (e)
			{ 
				var _ids = parseInt($(this).attr('id'));	
				allQuestions({id: _ids}).first().question.title = qTitle;
			})
		}
		else 
		{		
			$(this).text('Edit');
			$(this).parent().find('.main_Div_table').removeClass('editingmode-on');
			$(this).parent().find('.main_Div_table').find('.questionsSS').attr('contenteditable',false);
			$(this).parent().find('.main_Div_table').find('.sqno').attr('contenteditable',false);
		}
	})
}

function push_filter_arr_values(Arr, catArr, __div, e_title, e_ID)
{
	for(var catIndex=0; catIndex<catArr.length; catIndex++)
	{
		var obj = new Object();
		obj.type = catArr[catIndex];
		
		defineTypeSequence(obj);
		
		obj.arr = [];
		obj.Finalarr = [];
		obj.Title = [];
		obj.FinalTitle = [];
		obj.ID = [];
		obj.Mark = [];
		obj.FinalMark = [];
		obj.Passage = [];
		obj.PassageHeaders = [];
		Arr.push(obj);
	}
	
	_temp = [];
	
	for(var i=0; i<All_types.length; i++)
	{
		_temp[i] = [];
	}
	
	__div.each(function(i, e)
	{	
		for(var o in Arr)
		{
			if($(e).attr('data-type') == Arr[o].type) 
			{
				Arr[o].arr.push(e.dataset.type);				
				Arr[o].Title.push(e.dataset[e_title]);
				//console.log(e.dataset[e_title]);
				Arr[o].Mark = e.dataset.marks;
			}
			
			$.each(Arr[o].arr, function(i, el){
					if($.inArray(el, Arr[o].Finalarr) === -1) Arr[o].Finalarr.push(el);
			});
			
			$.each(Arr[o].Title, function(i, el){
					if($.inArray(el, Arr[o].FinalTitle) === -1) Arr[o].FinalTitle.push(el);
			});
			
			Arr[o].arr = modifyArrArray(Arr[o].arr);
			
			Arr[o].Finalarr = modifyArrArray(Arr[o].Finalarr);
			Arr[o].FinalTitle = modifyTitleArray(Arr[o].FinalTitle, Arr[o]);
			//console.log(Arr[o].FinalTitle, Arr[o].FinalTitle, Arr[o]);
			for(var ll=0; ll<Arr[o].FinalTitle.length; ll++)
			{
				if(Arr[o].Passage[ll] == undefined) Arr[o].Passage[ll] = [];
				
				if($(e).attr('data-'+e_title) == Arr[o].FinalTitle[ll])
				{
					Arr[o].Passage[ll].push(questions[$(e).attr(e_ID)-1].question.passage);
				}
				
				Arr[o].Passage[ll] = uniqueArray(Arr[o].Passage[ll]);
			}
			
			for(var jj=0; jj<Arr[o].Passage.length; jj++)
			{
				if(Arr[o].PassageHeaders[jj] == undefined) Arr[o].PassageHeaders[jj] = [];
				for(var nn=0; nn<Arr[o].Passage[jj].length; nn++)
				{
					if(Arr[o].PassageHeaders[jj][nn] == undefined) Arr[o].PassageHeaders[jj][nn] = [];
				
					if($(e).attr('data-type') == Arr[o].type) 
					{
						if(questions[$(e).attr(e_ID)-1].question.passage == Arr[o].Passage[jj][nn])
						{ 
							Arr[o].PassageHeaders[jj][nn].push(questions[$(e).attr(e_ID)-1].question.passageRubric);
						}
					}
					Arr[o].PassageHeaders[jj][nn] = uniqueArray(Arr[o].PassageHeaders[jj][nn]);
				}
			}
		}
	})
}

function headingColor(ele)
{
	$(ele).css('color' , head_color);
	$('.redheading').css('color' , head_color);
}