// init text editor in modal
var quill = new Quill('#messageTextArea', {
  modules: {
    toolbar: [
      [{ 'size': ['small', false, 'large'] }],
	  [{ 'font': [] }],
      ['bold', 'italic', 'underline','strike'],
      [{ 'color': [] }],
    ]
  },
  placeholder: '',
  theme: 'snow'  // or 'bubble',
});

// get random number between interval
function randomIntFromInterval(min, max) { // min and max included 
	return Math.floor(Math.random() * (max - min + 1) + min);
}

// get random color
function getRandomColor() { 
	var colors = ['66FF00','FF5555','FFE419','2A7FFF','BC5FD3','FF6600','ECECEC']
	var color = colors[Math.floor(Math.random() * colors.length)];
	return color
}

//init tooltips in form
$(function () {
  $('[data-toggle="tooltip"]').tooltip()
})

//closing navbar antholoy about on open
$('#newPlaneModal').on('shown.bs.modal', function (e) {
    $('.navbar-collapse').collapse('hide');
    $('#anthology').css('opacity','0')
	$('#anthology').css('visibility','hidden')
	$('#backToMap').css('opacity','0')
	$('#backToMap').css('visibility','hidden')
	$('#about').css('visibility','hidden');
	$('#about').css('opacity','0')
	anthologyOpen = 0
	aboutOpen = 0
})

$("#sendNewPlane").on('click',function(){
 
	
	//hiding modal
	$("#newPlaneModal").modal('hide')

	var deliveryMethod = $("#selectTime").val()
	
	var time; //time to delivery in hours
	
	
	if(deliveryMethod == '3days'){
		time = 24*3.14  
	}
	else if(deliveryMethod == '7days'){
		time = 24*7
	}
	else if(deliveryMethod == '30days'){
		time = 24*30
	}
	else if(deliveryMethod == '365days'){
		time = 24*365
	}
	else if(deliveryMethod == 'random'){
		var speed = randomIntFromInterval(5.05, 25.82)
		
		var line = turf.lineString([expeLoc.center,destLoc.center]) //create line between start and end
	    var length = turf.length(line) //get length in Km
		var additionalTime = length/speed;
		time = 37.68 + additionalTime  //minimum 37.68 hours + additional time based on random speed
		
	}
	
	
	//get the local time with TZ for starting point   
	$.getJSON('https://secure.geonames.org/timezoneJSON?lat='+expeLoc.center[1]+'&lng='+expeLoc.center[0]+'&username=avionpoeme',function(startTime){
		var expeTimezone = startTime.timezoneId;
		
		var sentDate = moment.tz(new Date(), expeTimezone).unix();
		
		
		
		//get the local time with TZ for end point
		$.getJSON('https://secure.geonames.org/timezoneJSON?lat='+destLoc.center[1]+'&lng='+destLoc.center[0]+'&username=avionpoeme',function(endTime){
			var destTimezone = endTime.timezoneId;
			
			var endDate = moment.tz(new Date(), destTimezone)
			var deliveryDate = endDate.add(time, 'hours').unix(); // adding hours 
			
			
			//storing the endDate in GMT+0 in seconds for the query
			var deliverySecondsServer = moment.tz(new Date(), "Europe/Berlin").add(time, 'hours').unix()
			
			var publicMessage = $("#public").prop("checked")
			
			var expeKnown = $("#expeKnown").prop("checked")
			if(expeKnown == true){
				expeKnown = false
			}
			else{
				expeKnown = true
			}
			
			var message = quill.root.innerHTML
			
			var randomColor = getRandomColor()
			
			console.log(message)
			
			var data = {
				'message':encodeURIComponent(message),
				'expeMail':$("#expeMail").val(),
				'expeKnown':expeKnown,
				'expeLang':lang,
				'destLang':$("#selectDestLang").val(),
				'startLat':expeLoc.center[1],
				'startLon':expeLoc.center[0],
				'startName':expeLoc.name,
				'startTime':sentDate,
				'startTZ':expeTimezone,
				'destMail':$("#destMail").val(),
				'destLat':destLoc.center[1],
				'destLon':destLoc.center[0],
				'destName':destLoc.name,
				'public':publicMessage,  
				'color':randomColor,
				'deliveryTime':deliveryDate,
				'deliveryTZ':destTimezone,
				'deliveryTimeServer':deliverySecondsServer,
				'deliveryMethod':$("#selectTime").val()
			}
			
			
			var query = 'avionpoeme.php?'+
						'message='+data.message+'&'+
						'expeMail='+data.expeMail+'&'+
						'expeKnown='+data.expeKnown+'&'+
						'expeLang='+data.expeLang+'&'+
						'destLang='+data.destLang+'&'+
						'startLat='+data.startLat+'&'+
						'startLon='+data.startLon+'&'+
						'startName='+data.startName+'&'+
						'startTime='+data.startTime+'&'+
						'startTZ='+data.startTZ+'&'+
						'destMail='+data.destMail+'&'+
						'destLat='+data.destLat+'&'+
						'destLon='+data.destLon+'&'+
						'destName='+data.destName+'&'+
						'public='+data.public+'&'+
						'color='+data.color+'&'+
						'deliveryTime='+data.deliveryTime+'&'+
						'deliveryTZ='+data.deliveryTZ+'&'+
						'deliveryTimeServer='+data.deliveryTimeServer+'&'+
						'deliveryMethod='+data.deliveryMethod+'';

			$.post(query, function(result) {
				result = result.replace(/'/g, '"');
				console.log(result)
				result = $.parseJSON(result)
				var planeId = Number(result.uid);
				//selecting proper color for back
				$("#back").attr("src","src/img/back-"+data.color+".jpg");
				
				// creating image for plane, need to link it to the inputs tog et entered values.
				var message = quill.root.innerHTML
				
				var canvas1 = document.getElementById("blankCanvas1"),
				html = quill.root.innerHTML;
				
				rasterizeHTML.drawHTML(html, canvas1,{zoom:0.7}).then(function success(renderResult) {
					
					var canvas2 = document.getElementById("blankCanvas2");
					var ctx = canvas2.getContext("2d");
					ctx.fillStyle = "#"+data.color;
					ctx.fillRect(0,0,400,400);
					ctx.drawImage(canvas1, 0, 0,400,400)
					ctx.fillStyle = "rgb(0,0,0)";
					ctx.font = "9px Courier";
					$("#front").attr('src',document.getElementById("blankCanvas2").toDataURL())
					//display and animate plane
					$("#canvas3d").css('display','block')
					animePlane()
					
					
					//moving plane at the end
					setInterval(function(){
						$("#canvas3d").css('transition','transform 2500ms ease-in-out')
						$("#canvas3d").css('transform','translate(50vw, -150vh)')
					},4400);
					//reloading page (to change)
					setInterval(function(){
						window.location.href ='https://avion-poe.me?avion='+planeId+'';
					},5500);
				})
			})
			
			
		
		

		})
	});
})