// Initilizing functions on script load
$(function() {
	initDatepicker();
});


async function getAjax(todo, callBack) {
	
	var urlString = "ajax.php?request=" + todo;

	var xmlhttp;
	if(window.XMLHttpRequest)
		xhttp = new XMLHttpRequest();
	else
		xhttp = new ActiveXObject("Microsoft.XMLHTTP");		// Microsoft support

	xhttp.onreadystatechange = function() {
		if(xhttp.readyState == 4 && xhttp.status  == 200) {
			callBack(xhttp.responseText);
			/*
			var	responseArray = JSON.parse(xhttp.responseText);
			
			if(responseArray.status) {
				callBack(xhttp.responseText);
			} else {
				popupMessage(responseArray.errorMessage, 'lightred');
			}
			*/
		}
	}
	
	xhttp.open("GET", urlString, true);
	xhttp.send();			
	
}

async function postAjax(todo, postVar, callBack) {
	// Create a random number

	var urlString = "ajax.php?request=" + todo + "&r=" + Math.random();

	var xmlhttp;
	if(window.XMLHttpRequest)
		myhttp = new XMLHttpRequest();
	else
		myhttp = new ActiveXObject("Microsoft.XMLHTTP");		// Microsoft support
	
	myhttp.onreadystatechange = function() {
		if(myhttp.readyState == 4 && myhttp.status  == 200) {
			if(typeof callBack === "function") { 
				callBack(myhttp.responseText);
			}
		}
	}
	
	myhttp.open("POST", urlString, true);
    if (postVar instanceof FormData) {
        // Don't set Content-type for FormData; browser will handle it.
        myhttp.send(postVar);
    } else {
        myhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
        myhttp.send(postVar);
    }
}


function sendMail(toRecipiants='', mailSubject='', mailMessage='') {
	if(toRecipiants == "") {
		toRecipiants = document.getElementById("emailTo").value;
	}
	
	if(mailSubject == "") {
		mailSubject = document.getElementById("emailSubject").value;
	}
	
	if(mailMessage == "") {
		mailMessage = document.getElementById("email_content_container").innerHTML;
	}
	
	var todo = "email&todo=send_mail&to=" + toRecipiants + "&subject=" + mailSubject + "&message=" + mailMessage;
	getAjax(todo, sendMailResponse);
}

function popupMessage(textContent, bgColor="", textColor="", visibleTime=5000) {
	
	var targetContiner = document.getElementById("popup_message_main_container");
	
	if(targetContiner == undefined) {
		console.log('Popup message container missing, ', textContent);
		return false;
	}
	
	let messageContainer = document.createElement("DIV");
	messageContainer.id = "popupMessage" + Math.random();

	console.log("Created popupMessage with id: " + messageContainer.id + " and textContent: " + textContent);

	messageContainer.classList.add("popup_message_container");
	if(bgColor != "") {
		messageContainer.style.backgroundColor = bgColor;
	}
	
	if(textColor != "") {
		messageContainer.style.color = textColor;
	}
	
	messageContainer.innerHTML = textContent;
	
	targetContiner.append(messageContainer);

	setTimeout(function() { // this will automatically close the alert and remove this if the users doesnt close it in 5 secs
		document.getElementById(messageContainer.id).remove();
	}, visibleTime);	
}

function sendMailResponse(response) {
	var	responseArray = JSON.parse(response);
	
	popupMessage(responseArray.popupMessage, "lightgreen")
	
	if(responseArray.status) {
		document.getElementById("sendmail_icon").src = 'images/sent_email.png';
	}
}

function showHideDiv(tagetDivId, setState='auto') {
	var tagetDiv = document.getElementById(tagetDivId);
	
	if(tagetDiv == undefined) {
		return false;
	}
	
	if(setState == 'auto') {
		if(tagetDiv.style.display == 'none') {
			setState = 'inline';
		} else {
			setState = 'none';
		}
	}
	
	tagetDiv.style.display = setState;
}

function checkUserAgreements() {
	var todo = "system&todo=check_user&type=user_agreements";
	getAjax(todo, checkUserAgreementsResponse);
}
function checkUserAgreementsResponse(response) {
	try {
		var	responseArray = JSON.parse(response);
	} catch(err) {
		console.log(err + ', response ' + response);
	}

	if(responseArray.status) {
		// popupMessage(responseArray.data, "", "", 35000);
	} else {
		popupMessage(responseArray.errorMessage);
	}
}

checkUserAgreements();

var specialDates;
var specialDatesColors;

function initDatepicker(showWeekVar=true, setStartDate=null) {
	var setColor = '';

	$( '.datepickerbasic' ).datepicker({ dateFormat: 'dd.mm.yy', beforeShowDay: highlightDays, closeText: 'Use', gotoCurrent: true, changeMonth: true, changeYear: true, firstDay: 1, showWeek: showWeekVar });
	//$( '.datetimepickerbasic' ).datetimepicker({ dateFormat: 'dd.mm.yy', beforeShowDay: highlightDays, closeText: 'Use', gotoCurrent: true, changeMonth: true, changeYear: true, firstDay: 1});

	function highlightDays(date) {
		if(specialDates == undefined) {
			return [true, '', ''];
		}
		
		for(var i = 0; i < specialDates.length; i++) {
			if (new Date(specialDates[i]).toString() == date.toString()) {
				if(specialDatesColors != undefined) {
					setColor = specialDatesColors[i];
				} else {
					//setColor = 'datepickerEvent';
				}
                return [true, setColor, ''];
			}
		}
		return [true, '', ''];
	}
}

function addDatepickerOption(dpId, optionType, optionValue) {
	// 'maxDate', '+0m +0w' for max date now
	$(dpId).datepicker('option', optionType, optionValue);
}

function addJSFileToHeader(jsFile) {
	var loadedScripts = document.getElementsByTagName('script');
	
	for(var i=0; i < loadedScripts.length; i++) {
		if(loadedScripts[i].getAttribute('src') == jsFile) {
			return true;
		}
	}
	
	var head = document.getElementsByTagName('head')[0],
	
	script = document.createElement('script');
	
	script.type = 'text/javascript';
	script.src = jsFile;
	
	head.appendChild(script);
}