var extraBr = '';
//var logoStr = '';
var schoolTxt = '';
var testNoTxt = '';
var timeTxt= '';
var logoSrcTxt = '';

function setPrintPage(){
	console.log("PRINT PREVIEW")
	$('.iPage').hide();
	$(".addToTestContainer").hide();
	$("#addPrintBase").hide();
	$("#addPrintHeader").show();
	$('.addToPrintContainer').show();
	
	if($('.addToPrintContainer').length>0)
		$('.addToPrintContainer').empty();
	
	setSchoolDetailEnter();
	$('#pdf-print').prop('disabled', true).css("cursor", "default").fadeTo(0,0.6);
	$('#doc-print').prop('disabled', true).css("cursor", "default").fadeTo(0,0.6);
	
	$('#addPrintHeader .total_number').text('Total Questions:  - '+ questions.length);
}

function setSchoolDetailEnter()
{
	$('.addToPrintContainer').append($('.printContainer').find('#addPrintHeader').clone());
	$('.addToPrintContainer').append($('.printContainer').find('.school-data-enter').clone());
	$('.addToPrintContainer').find('.school-data-enter .submit-btn').on('click', setPrintPageDetail);
	
	$('.addToPrintContainer').find('.school-data-enter').find('.school-txt').val(schoolTxt);
	$('.addToPrintContainer').find('.school-data-enter').find('.setNo-txt').val(testNoTxt);
	$('.addToPrintContainer').find('.school-data-enter').find('.time-txt').val(timeTxt);
	if(logoSrcTxt.length>0)
		$('.addToPrintContainer').find('.school-data-enter').find('#logoImg').attr({'src':logoSrcTxt,'width':'50px','height':'50px'});
	else{
		$('.addToPrintContainer').find('.school-data-enter').find('#logoImg').attr('src','');
		$('.addToPrintContainer').find('.school-data-enter').find('.picThumb').hide();
	}
	$('.addToPrintContainer').find('.school-data-enter').find('.imgCross').on('click', function(){
		$('.addToPrintContainer').find('.school-data-enter').find('.picThumb').hide();
		$('.addToPrintContainer').find('.school-data-enter').find('#logoImg').attr('src','');
		logoSrcTxt = '';
		$('input[type=file]').val('');
	});
	
	$('.addToPrintContainer').find('.school-data-enter').find('#fileLogo').on('change', function(){
		convertImagesToBase64(document.getElementById("fileLogo"), $('.addToPrintContainer').find('.school-data-enter').find('#logoImg'), '50px', '50px');
	});

///-------------------------------------------------------------------------------------------------------------------------------------------	
/* var doc = new jsPDF();
			var specialElementHandlers = {
				'#editor': function (element, renderer) {
					return true;
				}
			}; */
	$('.addToPrintContainer').find('#addPrintHeader #pdf-print').on('click', function(){
		console.log("PDF PRINT");

		var mywindow = window.open('', 'PRINT', 'height=400,width=600');

		mywindow.document.write('<html><head><title>' + document.title  + '</title>');
		mywindow.document.write(
			`
			<style>
				.schoolInfo{
					background-color: #ffe5cc;
				}	
				.title-quest {
					font-weight: bold;
					color: #931d1a;
					text-align: left;
					margin: 2px 17px 2px 7px;
					font-size: 100%;
					font-family: arial;
				}
				.option-quest {
					text-align: left;
					background-color: #eee;
					padding: 10px 20px 10px;
					margin: 8px 0 8px;
					font-size: 100%;
					font-family: arial;
					line-height: 120%;
				}
				.option-quest {
					text-align: left;
					font-size: 100%;
					font-family: arial;
					line-height: 120%;
				}
				.schoolInfo_td {
					display: table-cell;
					padding: 5px 5px;
					width: 400px;
				}
				.schoolInfo_table {
					font-size: 100%;
					font-family: sans-serif, arial;
					text-align: left;
				}
				.schoolInfo_tr {
					display: table-row;
				}
				.schoolInfo_table {
					font-size: 100%;
					font-family: sans-serif, arial;
					text-align: left;
				}
			</style>
			`
		);
		mywindow.document.write('</head><body >');
		mywindow.document.write('<h1>' + document.title  + '</h1>');
		mywindow.document.write(document.getElementById('addPrintBase').innerHTML);
		mywindow.document.write('</body></html>');

		mywindow.focus(); // necessary for IE >= 10*/
		
		setTimeout(function(){
			mywindow.print();
		},2000);
		
		//mywindow.close();

		/* frm = document.getElementById('addPrintBase');
		console.log(frm.innerHTML);
		var tempHtml =  frm.innerHTML;

		var mc = document.createElement("div");
		var main = document.getElementById('mainContainer');
		main.appendChild(mc);
		mc.id = "tempID";
		mc.innerHTML = tempHtml; */
		
		
		
	});
////---------------------------------------------------------------------------------------------------------------------------------------------	
	$('.addToPrintContainer').find('#addPrintHeader #doc-print').on('click', function(){
		console.log("DOC PRINT")
		extraBr = '<br>';
		/* $('.schoolInfo_table').css({"font-family": "sans-serif, arial", "margin": "10px 200px", "padding": "5px", "text-align": "left", "width": "70%"}); */
		//$("li").css("list-style-type", "none");
		setPrintPageDetail();
		
		//$('.option-quest .col2 .column').css({"width":"19%"});
		//$('.addPrintImage').css({"display":"grid"});
		
		if(logoSrcTxt.length <= 0)
			$('.addToPrintContainer').find('#addPrintBase .addPrintImage').hide();
		
		$("#addPrintBase").wordExport(); 
		extraBr = '';
		setPrintPageDetail();
	});
	
	$('.addToPrintContainer').find('#addPrintHeader #add-more').on('click', function(){
		console.log("add-more")
		$('.iPage').show();
		$('.addToTestContainer').hide();
		
		$('.addToPrintContainer').hide();
		
		if($('.addToPrintContainer').length>0){
		$('.addToPrintContainer').find('#addPrintHeader').remove();
		$('.addToPrintContainer').find('#addPrintBase').remove();
		}
		
		if(tg_MODE == "manual" && addedQuestions.length>0)
		setBreadCrum(addedQuestions[addedQuestions.length-1].id);//this function is in main.js
		setHeaderText();//this function is in main.js
		//logoStr = "";
	}); 
	$('.addToPrintContainer').find('#addPrintHeader #edit-quest').on('click', function(){
		console.log("add-more")
		$('.iPage').show();
		$('.addToTestContainer').hide();
		
		$('.addToPrintContainer').hide();
		
		if($('.addToPrintContainer').length>0){
		$('.addToPrintContainer').find('#addPrintHeader').remove();
		$('.addToPrintContainer').find('#addPrintBase').remove();
		}
		//logoStr = '';
		setAddToDetail("manual", true);//this function is addToTestDetail.js file
		
	}); 
	$('.addToPrintContainer').find('.school-data-enter').find('.subject-txt').text(getSubjectName());
	$('.addToPrintContainer').find('.school-data-enter').find('.totMark-txt').text(calcTotalMarks());
	$('.addToPrintContainer').find('.school-data-enter').find('.class-txt').text(questions[0][treeStructure[0]].split('Book ')[1]);
}
function setPrintPageDetail(){
	if($('.addToPrintContainer').find('.school-data-enter').find('.school-txt').val()=='' && $('.addToPrintContainer').find('.school-data-enter').find('.setNo-txt').val()=='' && $('.addToPrintContainer').find('.school-data-enter').find('.time-txt').val()==''){
// alert("please these filed")
console.log($('.addToPrintContainer').find('.school-data-enter').find(".error_td"));
document.querySelector(".error_td").innerHTML='Please Enter Mandantory Filed'
// $('.addToPrintContainer').find('.school-data-enter').$(".error_td").text="Please Enter Mandantory Filed"
return
	}
	// $('.addToPrintContainer').find('.school-data-enter').find('.school-txt').val(schoolTxt);
	// $('.addToPrintContainer').find('.school-data-enter').find('.setNo-txt').val(testNoTxt);
	// $('.addToPrintContainer').find('.school-data-enter').find('.time-txt').val(timeTxt);
	$('.addToPrintContainer #addPrintBase').remove();
	
	$('.addToPrintContainer').append($('.printContainer').find('#addPrintBase').clone());
	$('.addToPrintContainer').find('#addPrintBase').show();
	var val = $('.addToPrintContainer').find('.school-data-enter');
	$('.addToPrintContainer').find('#addPrintBase .subject-val').text(val.find('.subject-txt').text());
	if(val.find('.class-txt').text().length>0)
	$('.addToPrintContainer').find('#addPrintBase .class-val').text(val.find('.class-txt').text());
	//$('.addToPrintContainer').find('#addPrintBase .name-val').text(val.find('.name-txt').val());
	//$('.addToPrintContainer').find('#addPrintBase .roll-val').text(val.find('.roll-txt').val());
	
	schoolTxt = val.find('.school-txt').val();
	testNoTxt = val.find('.setNo-txt').val();
	timeTxt = val.find('.time-txt').val();
	logoSrcTxt = val.find('#logoImg').attr('src');
	
	if(val.find('.school-txt').val().length > 0)
		$('.addToPrintContainer').find('#addPrintBase .school-val').text(val.find('.school-txt').val());
	else
		$('.addToPrintContainer').find('#addPrintBase .school-val').text("");
	if(val.find('.setNo-txt').val().length > 0)
		$('.addToPrintContainer').find('#addPrintBase .setNo-val').text(val.find('.setNo-txt').val());
	else
		$('.addToPrintContainer').find('#addPrintBase .setNo-val').text('____________');
	if(val.find('.time-txt').val().length > 0)
		$('.addToPrintContainer').find('#addPrintBase .time-val').text(val.find('.time-txt').val());
	else
		$('.addToPrintContainer').find('#addPrintBase .time-val').text('____________');
	
	$('.addToPrintContainer').find('#addPrintBase .totMark-val').text(calcTotalMarks());
	
	/* //var filename = document.getElementById("fileLogo").value.split('fakepath')[1];
	var filename = $('.addToPrintContainer').find('.school-data-enter').find('#logoImg').attr('src');
	//if(filename != undefined){
	if(filename != ''){
		if(logoStr != '')
			$('.addToPrintContainer').find('#addPrintBase .addPrintImage img').attr('src', base64value); 
		else
			convertImagesToBase64(document.getElementById("fileLogo"), $('.addToPrintContainer').find('#addPrintBase .addPrintImage img')); 
		
		$('.addToPrintContainer').find('#addPrintBase .addPrintImage span').text(val.find('.school-txt').val());
		$('.addToPrintContainer').find('#addPrintBase .addPrintImage img').attr("height", "50").attr("width", "50");
	}
	else
		$('.addToPrintContainer').find('#addPrintBase .addPrintImage').hide(); */
	
	//var filename = $('.addToPrintContainer').find('.school-data-enter').find('#logoImg').attr('src');
	console.log('PRINT DOC====',logoSrcTxt.length)
	if(logoSrcTxt.length > 0){
		//if(logoStr != '')
			$('.addToPrintContainer').find('#addPrintBase .addPrintImage img').attr('src', logoSrcTxt); 
		
		$('.addToPrintContainer').find('#addPrintBase .addPrintImage span').text(val.find('.school-txt').val());
		$('.addToPrintContainer').find('#addPrintBase .addPrintImage img').attr({"height": "50px", "width": "50px"});
	}
	else
		$('.addToPrintContainer').find('#addPrintBase .addPrintImage').hide();
	
	setPrintSelectedQuestDetail();
	$('.addToPrintContainer').find('.school-data-enter').hide();
	
	$('#pdf-print').prop('disabled', false).css("cursor", "pointer").fadeTo(0,1);
	$('#doc-print').prop('disabled', false).css("cursor", "pointer").fadeTo(0,1);
	
	$('#addPrintBase').append('<div style="margin-top: 10px; font-size: 12px; font-family: arial;"><img src='+logoBase64+' style="vertical-align: middle;" width="40px", height="25px"><span>Powered by Ratna Sagar</span></div>')
	$('#addPrintBase').prepend('<div style="margin-top: 40px; font-size: 12px; font-family: arial;"><img src='+logoBase64+' style="vertical-align: middle;" width="40px", height="25px"><span>Powered by Ratna Sagar</span></div>')
}
function calcTotalMarks(){
	var totMark = 0;
	for(var i=0; i<addedQuestions.length; i++)
		totMark += parseFloat(addedQuestions[i].questMark);
	
	for(var j=0; j<addedNewQuestions.length; j++)
		totMark += parseFloat(addedNewQuestions[j].questMark);
	
	//return totMark;
	return round(totMark, 1);
}
function setPrintSelectedQuestDetail()
{
	var shufflesArr = getShuffledQuestionArr(false);
	var quesTitle = ""
	for(var i=0; i<shufflesArr.length; i++)
	{
		var index = shufflesArr[i].num;
		
		var strtitle = "";
		if(quesTitle != shufflesArr[i].title || i==0)
		{
			strtitle =  '<div class="title-quest">'+shufflesArr[i].title+'</div>'+extraBr;
		}		
		
		var str = "";
		var strAns ;
		
		
		if(shufflesArr[i].questAnsImg == '')
			strAns = '<div id="answer-txt"><div><span>Answer:</span></div><div class="ansTxt"><span>'+shufflesArr[i].questAns+'</span></div></div>';
		else
			strAns = '<div id="answer-txt"><div><span>Answer:</span>'+extraBr+'</div><div class="ansTxt"><img src=' +shufflesArr[i].questAnsImg+ '></div></div>';
		
		console.log("setPrintSelectedQuestDetail=1==", shufflesArr[i].questTxt.length)
			str =  '<span class="hang">'+(i+1)+'. </span><span class="quest-text">'+shufflesArr[i].questTxt+'</span>';
		
			if(shufflesArr[i].questImg.length >0){
				str = str+' </span>'+extraBr+'<img class="quest-img" src='+shufflesArr[i].questImg+' style="margin-top: 10px;display:block;">';
			}
			
		str = str + strAns;
		var allStr =  '<div class=option-quest id="opQ'+i+'"><div class="col2"><div class="column"><span>'+str+'</span></div><div class="quest-marks column">Marks:'+parseFloat(shufflesArr[i].questMark)+'</div></div></div>'+extraBr;
		
		console.log("MARKS::"+parseFloat(shufflesArr[i].questMark))
		
		quesTitle = shufflesArr[i].title;
		$('.addToPrintContainer #addPrintBase').append(strtitle+''+allStr);
	}
	$('.selected-full-quest .selected-quest').each(function(){
		$(this).find('#answer-txt').hide();
	});	
	
	if(!answerHidden)
		$('.addToPrintContainer #addPrintBase').find('#answer-txt').hide();
	
	
	$('.addToPrintContainer #addPrintBase').find('.quest-marks').each(function(index){
		if(!markHidden || parseFloat(shufflesArr[index].questMark)<=0)
			$(this).hide();
	});
	
	/* $('.option-quest').each(function(){
		calculateAspectRatioFit($(this).find('img'), maxWidth, maxHeight);
	}); */
	setPrintQuestImageSize(shufflesArr);
}
function getSubjectName()
{
	var subjectArr = [];
	for(var i=0; i<addedQuestions.length; i++)
	{
		if(subjectArr.indexOf(questions[addedQuestions[i].num][treeStructure[1]]) == -1)
			subjectArr.push(questions[addedQuestions[i].num][treeStructure[1]]);
	}
	console.log('getSujectName', questions[0] );
	console.log('getSujectName', questions[0][treeStructure[1]] );
	//temperory changes
	/* return questions[0][treeStructure[0]]; */
	console.log(subjectArr)
	
	if(subjectArr.length == 1)
		return subjectArr[0];
	else
		return "Integrated";
}
function convertImagesToBase64 (filesSelected, imageObj, hPx='', wPx='') 
{
	var filesSelected = filesSelected.files;
	var fileFlag = false;
	
	if(filesSelected.length>0)
	{
		var s = filesSelected[0].name;
		switch(s.substring(s.lastIndexOf('.')+1)){
			case 'jpg': 
			case 'jpeg': 
			case 'png': fileFlag = true;
		} 
	}
	if (fileFlag && filesSelected.length > 0)
	{
		console.log('calculateAspectRatioFit1=')
		var fileToLoad = filesSelected[0];
 
		var fileReader = new FileReader();
 
		fileReader.onload = function(fileLoadedEvent) 
		{
			base64value = fileLoadedEvent.target.result;
			
			if($('.addToPrintContainer').css('display') != 'none')
			$('.addToPrintContainer').find('.school-data-enter').find('.picThumb').show();
			
			console.log('calculateAspectRatioFit2=', hPx, base64value.length)
			
			if(hPx==''){
				var img = new Image();       
				img.onload = function(){
				  //alert(img.width +' '+ img.height );
				  var h = img.height+"px";
				  var w = img.width+"px";
				  imageObj.attr({'src': base64value});
				  imageObj.css({'width':w,'height':h});
				  calculateAspectRatioFit(imageObj, maxWidth, maxHeight);
				};
				img.src = base64value;								
			}
			else
				imageObj.attr({'src': base64value,
				'width':hPx,
				'height':wPx}); 
		};
 
		fileReader.readAsDataURL(fileToLoad);
		return true;
	}else{
		$('input[type=file]').val('');
		return false;
	}
}
var shufQuestIndx = 0;
function setPrintQuestImageSize(shufflesArr)
{
	if(shufQuestIndx < shufflesArr.length)
	{
		console.log('setPrintQuestImageSize=1=', shufQuestIndx, shufflesArr.length, shufflesArr[shufQuestIndx].questImg.length)
		if(shufflesArr[shufQuestIndx].questImg.length > 0)
		{
			console.log('setPrintQuestImageSize=2=', shufQuestIndx, shufflesArr)
			var tempNum = shufQuestIndx;//shufflesArr[shufQuestIndx].num;
			var img = shufflesArr[shufQuestIndx].questImg
			var imgTemp = new Image();  
			imgTemp.src = img;				
			imgTemp.onload = function()
			{
				console.log('setPrintQuestImageSize=4=', shufQuestIndx, shufflesArr)
				var h = imgTemp.height+"px";
				var w = imgTemp.width+"px";
				//var len = $('.quest-text').length;
				var imageObj = $("#opQ"+tempNum+" .quest-img");
				console.log('setPrintQuestImageSize=4.1=', imageObj.width()+"===== "+"#selectedQuest"+tempNum+" .quest-img")
				/* if(imageObj.width()+"" == 'undefined')
					imageObj = $("#selectedAddedQuest"+tempNum+" .quest-img"); */
				//
				imageObj.attr({'src': img});
				imageObj.css({'width':w,'height':h});
				calculateAspectRatioFit(imageObj, maxWidth, maxHeight);
				shufQuestIndx += 1;
				setPrintQuestImageSize(shufflesArr);
			};
		}else{	
			shufQuestIndx += 1;	
			setPrintQuestImageSize(shufflesArr);			
		}
	}else{
		console.log('setPrintQuestImageSize=5=', shufQuestIndx, shufflesArr.length)
		shufQuestIndx = 0;
		setPrintAnsImageSize(shufflesArr);
	}
}
var shufAnsIndx = 0;
function setPrintAnsImageSize(shufflesArr)
{
	if(shufAnsIndx < shufflesArr.length)
	{
		//console.log('setPrintAnsImageSize=1=', shufAnsIndx, shufflesArr.length)
		if(shufflesArr[shufAnsIndx].questAnsImg.length > 0)
		{
			console.log('setPrintAnsImageSize=2=', shufAnsIndx, shufflesArr.length)
			var tempNum = shufAnsIndx;//shufflesArr[shufAnsIndx].num;
			var img = shufflesArr[shufAnsIndx].questAnsImg;
			var imgTemp = new Image();  
			imgTemp.src = 	img;			
			imgTemp.onload = function()
			{
			  var h = imgTemp.height+"px";
			  var w = imgTemp.width+"px";
			  console.log('setPrintAnsImageSize=4=', h, w);
			  //var len = $('.quest-text').length;
			 
			  var imageObj = $("#opQ"+tempNum+" .ansTxt img");
			  console.log('setPrintAnsImageSize=4.1=', $("#selectedQuest"+tempNum+" #answer-txt .ansTxt").attr('class'));
			  
			  /* if(imageObj.width()+"" == 'undefined')
					imageObj = $("#selectedAddedQuest"+tempNum+" #answer-txt .ansTxt img"); */
							  
			  imageObj.attr({'src': img});
			  imageObj.css({'width':w,'height':h});
			  calculateAspectRatioFit(imageObj, maxWidth, maxHeight);
			  shufAnsIndx += 1;
			  setPrintAnsImageSize(shufflesArr);
			};
		}else{
			shufAnsIndx += 1;
			setPrintAnsImageSize(shufflesArr)
		}
	}else{
		console.log('setPrintAnsImageSize=5=', shufAnsIndx, shufflesArr.length)
		shufAnsIndx = 0;
		hideLoader();
	}
}

function detectDevice() { 
	if( navigator.userAgent.match(/Android/i)
	|| navigator.userAgent.match(/webOS/i)
	|| navigator.userAgent.match(/iPhone/i)
	|| navigator.userAgent.match(/iPad/i)
	|| navigator.userAgent.match(/iPod/i)
	|| navigator.userAgent.match(/BlackBerry/i)
	|| navigator.userAgent.match(/Windows Phone/i)
	){
	   return true;
	 }
	else {
	   return false;
	 }
   }
var logoBase64 = "data:image/png;base64, ";	

