$(document).ready(function() {
	
	window.addEventListener('message', function(event) { 
		if (event.origin.indexOf('rtu.lv')) { 
			if(event.data=="iframe_open"){
				initsession();
				scrollDown();
			}	
		} 
	}); 
	
	var contextPath = $("#contextPath").text();
	
	printFlowMessage();
	
	function getFlow(flow = 0) {
		var result = null;
		if((flow!=null && flow.trim()!="")){
			$.ajax({
				method : "POST",
				timeout : 15000,
				async : false,
				dataType : "json",
				data : {flow : flow},
				success : function(response) {
					if(response.status){
						result=response;
					}						
				}
			});
		}
		return result;
	}
	
	function getFlowScenarion(scenario) {
		var result = null;
		if(scenario!=null){
			$.ajax({
				method : "POST",
				timeout : 15000,
				async : false,
				dataType : "json",
				url: contextPath+"/scenario",
				data : {scenario : scenario},
				success : function(response) {
					result=response;				
				}
			});
		}
		
		return result;
	}
	
	function printFlowMessage(){
		var flow = $("#bot-chat-flow").val();
		
		var response = getFlow(flow);
		
		if(response.list.length>0){
			var html = "";
			
			if(response.list.length==1 && !response.buttons){
				var id = response.list[0].flow;
				$("#bot-chat-flow").val(id);
				
				if(response.calendar){
					displayLoading();
					
					var html = "<ul>";
					var events = getEvents(5);
					for (var i = 0; i < events.length; i++) {
						html+="<li><a href='"+events[i].link+"' target='_blank'>"+events[i].header+"</a></li>";
					}
					html+="</ul>";
				}
			
				html += '<div data-id="'+response.list[0].flow+'">'+response.list[0].message+'</div>';
			} else{
				for (var i = 0; i < response.list.length; i++) {
					var item = response.list[i];
					html += '<div style="margin:3px"><button data-id="'+item.flow+'" data-answers="'+item.answers+'" data-tests="'+item.test+'" data-auto="'+item.auto+'" data-question="'+item.question+'" data-calendar="'+item.calendar+'" type="button" class="bot-message-button" aria-label="'+item.message+'" style="width:100%">'+item.message+'</button></div>';
				}
				html = '<div>'+response.groupTitle+'</div><div class="bot-message-button-group" data-id="'+item.flow+'" style="display: flex; flex-direction: column; align-items: stretch;">'+html+'</div>';
			}
			
			if(response.delay>3000){
				displayLoading();
			}
						
			setTimeout(function(){
				removeLoading();
				
				html = formatBotMessage(html);
				
				$("#bot-message-groups").append(html);
				
				$("button[class=bot-message-button]").click(function(){
					var id = $(this).attr("data-id");
					var label = $(this).attr("aria-label");
					var answers = $(this).attr("data-answers");
					var tests = $(this).attr("data-tests");
					var auto = ($(this).attr("data-auto") == "true");
					var question = ($(this).attr("data-question") == "true");
					var calendar = ($(this).attr("data-calendar") == "true");
					var delay = 0;
					
					$("#bot-chat-flow").val(id);
					$(this).parent().parent().remove();
					
					var html = formatUserMessage(label, auto);
					$("#bot-message-groups").append(html);
					
					scrollDown();
					
					if(question){
						$("#bot-chat-input").attr("placeholder", "Es Tevi klausos :)");
						var html = formatBotMessage("Es vēl tikai mācos atbildēt uz jautājumiem brīvā formā, taču, ja tas Tevi nebiedē, droši uzdod man savu jautājumu :)");
						$("#bot-message-groups").append(html);
						
						$("#bot-chat-form-button").unbind().click(function(e) {
							askQuestion(true);
							processMessageButton(id, delay, answers, tests);
							$(this).off();
							
							$("#bot-chat-form-button").unbind().click(function(e) {
								askQuestion(false);
							});
						});
						
						$('#bot-chat-form').unbind().on('keypress',
							function(e) {
								var keyCode = e.keyCode || e.which;
								if (keyCode === 13) {
									e.preventDefault();
									askQuestion(true);
									processMessageButton(id, delay, answers, tests);
									$(this).off();
									
									$('#bot-chat-form').unbind().on('keypress',
										function(e) {
											var keyCode = e.keyCode || e.which;
											if (keyCode === 13) {
												e.preventDefault();
												askQuestion(false);
											}
									});
								}
						});
						
					}else{
						processMessageButton(id, delay, answers, tests);
					}
					
				});
				
				setTimeout(function(){
					scrollDown();
					
					if(response.autoContinue){
						printFlowMessage();
					}
					
			    },100);
						
		    }, response.delay);
		}
						
	}
	
	function processMessageButton(id, delay, answers, tests){
		setTimeout(function(){
			if(answers=="true"){
				var result = getFlowAnswers(id);
				delay += result.delay;
				
				var guid = generateUUID();
				var html = "";
				for (var i = 0; i < result.list.length; i++) {
					var item = result.list[i];
					
					var content = '<img src="'+item.imageLink+'"/><div align="left" style="font-weight:bold;margin-top:5px">'+item.title+'</div><div align="left">'+item.message+'</div>';
					if(item.link!=""){
						content += '<div class="bot-message-button-group" style="display: flex; flex-direction: column; align-items: stretch; margin-top: 5px" align="center"><a href="'+item.link+'" target="_blank" style="width:100%">'+item.linkTitle+'</a></div>';
					}
					
					if(i==0){
						html += '<li class="active">'+content+'</li>';
					}else{
						html += '<li>'+content+'</li>';
					}
					
				}
				
				html = createSlickBlock(guid, html);
				html = formatBotMessage(html);
				$("#bot-message-groups").append(html);
				enableSlick(guid);
				
				scrollDown();
			} 
			
			if(tests=="true"){
				var test = getFlowTest(id);						
				if(test.id!=""){				
					startTest(test.id);
				}
			}else{
				if(delay>=3000){				
					setTimeout(function(){
						displayLoading();			
				    }, 2000);		
					setTimeout(function(){
						removeLoading();
						printFlowMessage();				
				    }, delay);
					
				} else{
					setTimeout(function(){
						printFlowMessage();				
				    }, delay);
				}
			}
			
	    }, 200);
	}
	
	function getQuestionAnswer(searchPhrase, searchContext = 0){
		var result = null;	
		$.ajax({
			method : "POST",
			timeout : 15000,
			async : false,
			url: contextPath+"/question",
			dataType : "json",
			data : {searchPhrase : searchPhrase, searchContext : searchContext},
			success : function(response) {
				result=response;
			}
		});
		return result;
	}
	
	function askQuestion(isFlow){
		$("div[class=bot-message-button-group]").remove();
		
		$("#bot-chat-input").attr("placeholder", "");
		var input = $("#bot-chat-input").val();
		$("#bot-chat-input").val("");
		if(input!=null && input!=""){
			var message = formatUserMessage(input);
			$("#bot-message-groups").append(message);
			
			scrollDown();
			
			setTimeout(function(){
				var answerStatus = printQuestionAnswer(input, 0);		
				if(!isFlow){
					var flowId = getFlowScenarion("question");
					$("#bot-chat-flow").val(flowId);
					printFlowMessage();
				}
		    },500);
		}
	}
	
	$("#bot-chat-form-button").click(function(e) {
		askQuestion(false);
	});

	$('#bot-chat-form').on('keypress',
		function(e) {
			var keyCode = e.keyCode || e.which;
			if (keyCode === 13) {
				e.preventDefault();
				askQuestion(false);
			}
	});
	
	function printQuestionAnswer(searchPhrase, searchContext){
		var map = getQuestionAnswer(searchPhrase, searchContext);
		var answer = map.answer;
		var status = map.status;
		var input = formatBotMessage(answer);
		$("#bot-message-groups").append(input);	
		scrollDown();
		
		return status;
	}
	
	function formatBotMessage(html) {
		return '<div class="bot-message-wrapper">'+getBotMessageWrapper(html)+'</div>';
	}
	
	function getBotLoadingMessage(){
		return '<div class="bot-message-wrapper bot-message-loading">'+getBotMessageWrapper('<img src="'+contextPath+'/resources/img/loading.gif" />')+'</div>';
	}
	
	function getBotMessageWrapper(html){
		return '<div class="bot-message bot-message-from-bot"><div class="bot-message-content"><div class="format-markdown">'
		+ html
		+ '</div></div></div>';
	}

	function formatUserMessage(html, auto = false) {
		return '<div class="bot-message-wrapper list"><div class="bot-message bot-message-from-me"><div class="bot-message-content"><div class="format-plain">'
		        + formatLink(html, auto);
				+ '</div></div></div></div>';
	}
	
	function getFlowAnswers(flow) {
		var result = null;
		if((flow!=null)){
			$.ajax({
				method : "POST",
				timeout : 15000,
				async : false,
				dataType : "json",
				url: contextPath+"/answer",
				data : {flow : flow},
				success : function(response) {
					if(response.status){
						result=response;
					}						
				}
			});
		}
		return result;
	}
	
	function scrollDown(){
		var multiplier = ($(window).height()>0) ? $(window).height() : 100;
		$("#bot-message-groups").animate({ scrollTop: $("div[class*=bot-message-wrapper]").size()*multiplier}, 1000);
	}
	
	function enableSlick(id){
		$("#"+id).slick({
			dots: true,
			//adaptiveHeight: true,
			autoplay: true,
			autoplaySpeed: 2000
		});
	}
	
	function createSlickBlock(id, pages){
		return '<div id="'+id+'" class="single-item" style="width:200px">'+pages+'</div>';
	}
	
	function displayLoading(){
		var html = getBotLoadingMessage();
		$("#bot-message-groups").append(html);
		scrollDown();
	}
	
	function removeLoading(){
		$("div[class*=bot-message-loading]").remove();
	}
	
	function generateUUID() { // Public Domain/MIT
	    var d = new Date().getTime();
	    if (typeof performance !== 'undefined' && typeof performance.now === 'function'){
	        d += performance.now(); //use high-precision timer if available
	    }
	    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
	        var r = (d + Math.random() * 16) % 16 | 0;
	        d = Math.floor(d / 16);
	        return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
	    });
	}
	
	function getFlowTest(flow) {
		var result = null;
		if(flow!=null){
			$.ajax({
				method : "POST",
				timeout : 15000,
				async : false,
				dataType : "json",
				url: contextPath+"/test/flow",
				data : {flow : flow},
				success : function(response) {
					result=response;				
				}
			});
		}
		
		return result;
	}
	
	function startTest(testId){
		displayLoading();
		
		setTimeout(function(){
			printTestQuestion(testId);
	    },100);	
	}
	
	function getTestQuestion(testId, testquestionid = 0){
		var result = null;	
		$.ajax({
			method : "POST",
			timeout : 15000,
			async : false,
			url: contextPath+"/test",
			dataType : "json",
			data : {test : testId, testquestionid : testquestionid},
			success : function(response) {
				result=response;
			}
		});
		
		return result;
	}
	
	function sendTestAnswer(session, testquestionid, answer){
		var result = null;
		if(testquestionid!=null && session.trim()!="" && answer!=null){
			$.ajax({
				method : "POST",
				timeout : 15000,
				async : false,
				url: contextPath+"/test/answer",
				dataType : "json",
				data : {testquestionid : testquestionid, session: session, answer:answer},
				success : function(response) {
					if(response.status){
						result=response;
					}						
				}
			});
		}
		return result;
	}
	
	function printTestQuestion(testId, testquestionid = 0){
		var testQuestion = getTestQuestion(testId, testquestionid);
		
		removeLoading();
		
		if(typeof testQuestion.session !== "undefined"){
			$("#bot-test-session").val(testQuestion.session);
		}
		
		var html = '<div data-id="test_'+testQuestion.id+'">'+testQuestion.question+'</div>' +
		'<div class="bot-message-button-group" data-id="'+testQuestion.id+'" data-idnext="'+testQuestion.idNext+'" style="display: flex; flex-direction: column; align-items: stretch;">'+
		'<div style="margin:3px"><button data-answer="1" type="button" class="bot-test-button" style="width:100%">Jā</button></div>'+
		'<div style="margin:3px"><button data-answer="0" type="button" class="bot-test-button" style="width:100%">Nē</button></div>'+
		'</div>';
		
		html = formatBotMessage(html);
		$("#bot-message-groups").append(html);
		
		$("button[class=bot-test-button]").click(function(){
			var question = $(this).parent().parent();
			var id = question.attr("data-id");
			var idNext = question.attr("data-idNext");
			var answer = $(this).attr("data-answer");
			var label = $(this).text();	
			var session = $("#bot-test-session").val();
			
			$("#bot-test-id").val(id);
			question.remove();
			
			var html = formatUserMessage(label);
			$("#bot-message-groups").append(html);
			
			displayLoading();
			
			scrollDown();
			
			setTimeout(function(){
				var result = sendTestAnswer(session, id, answer);	
				if(idNext != ""){
					if(result!=null && result.status){
						printTestQuestion(testId, idNext);	
					}		
				}else{
					removeLoading();
					printTestPrograms(session);
				}
		    },100);
			
		});
		
	}
	
	function getTestPrograms(session){
		var result = null;	
		$.ajax({
			method : "POST",
			timeout : 15000,
			async : false,
			url: contextPath+"/test/programs",
			dataType : "json",
			data : {session : session},
			success : function(response) {
				result=response;
			}
		});
		return result;
	}
	
	function printTestPrograms(session){
		var programs = getTestPrograms(session);
		var html = '<div>'+programs.title+'</div>';
		for (var i = 0; i < programs.list.length; i++) {
			var num = i+1;
			var program = programs.list[i];
			html += '<div>'+num+'. <a href="'+program.link+'" target="_blank">'+program.title+'</a></div>';
		}
		
		html = formatBotMessage(html);
		$("#bot-message-groups").append(html);
		scrollDown();
		
		setTimeout(function(){
			printFlowMessage();
	    },3000);
		
	}
	
	function formatLink(str, auto){
		var start = str.indexOf("http");
		if(start!=-1){
			var result = "";
			var end = str.substring(start).indexOf(" ");
			if(end==-1){
				end = str.length;
				result = str.substring(0, start)+'<a href="'+str.substring(start).substring(0,end)+'" target="_blank">'
					+str.substring(start).substring(0,end)+'</a>';
				
			}else{
				result =  str.substring(0, start)
					+'<a href="'+str.substring(start).substring(0,end)+'" target="_blank">'+str.substring(start).substring(0,end)+'</a>'
					+str.substring(start).substring(end,str.length);
			}
			
			if(auto){
				var uuid = generateUUID();
				result += '<div style="display:none"><form id="'+uuid+'" target="_blank" action="'+str.substring(start).substring(0,end)+'"><input type="submit" value="ok" /></form><script>$(document).ready(function() { $("#'+uuid+'").submit();});</script></div>';	
			}
			
			return result;
		}else{
			return str;
		}
	}
	
	function initsession(){
		var token = "";
		$.ajax({
			method : "POST",
			timeout : 15000,
			async : false,
			url: contextPath+"/session/init",
			dataType : "json",
			data : {},
			success : function(response) {
				token=response;
			}
		});
		
		document.cookie = "leo="+token;
	}
	
	function getEvents(count){
		var result = null;	
		$.ajax({
			method : "POST",
			timeout : 15000,
			async : false,
			url: contextPath+"/calendar",
			dataType : "json",
			data : {count:count},
			success : function(response) {
				result=response.events;
			}
		});
		
		return result;
	}
		
});