function serializeJSON(form) {
	var obj = {};
	Array.prototype.slice.call(form.elements).forEach(
		function (field) {
			if (!field.id || field.disabled || ['file', 'reset', 'submit',
				'button'
			].indexOf(field.type) > -1) {
				return;
			}
			if (field.type === 'select-multiple') {
				var options = [];
				Array.prototype.slice.call(field.options).forEach(
					function (option) {
						if (!option.selected) {
							return;
						}
						options.push(option.value);
					});
				if (options.length) {
					obj[field.name] = options;
				}
				return;
			}
			if (['checkbox', 'radio'].indexOf(field.type) > -1 && !field
				.checked) {
				return;
			}
			obj[field.id] = field.value;
		});
	return JSON.stringify(obj, null, 2);
}

function GetData() {
	fetch(
		`../back-end/?q=full`
	)
		.then(
			response => response.json()
		)
		.then(
			function (table) {
				document.getElementById("data").innerHTML = "";
				for (let key in table) {
					document.getElementById("data").innerHTML +=
						`<tr>
					<td> ${table[key].id}</td> 
					<td> ${table[key].name}</td>
					<td> ${table[key].date_of_publishing}</td> 
					<td> ${table[key].status}</td> 
					<td> ${table[key].genre}</td> 
					<td> ${table[key].author}</td> 
					<td> ${table[key].description}</td> 
					<td> ${table[key].src}</td> 
					<td> ${table[key].panels}</td>
					<td> ${table[key].score}</td> 
					</tr>`
				}
			}
		);
}

var incremental = 0;
var saver = [];
var windaur = document.getElementById("bodaur");
windaur.addEventListener('scroll', () => {
	if (Math.abs(windaur.scrollHeight - windaur.clientHeight - windaur.scrollTop) <= 100) {
		loadMore();
	}
})

function loadMore() {
	fetch(`../back-end/?q=full`)
		.then(
			response => response.json()
		)
		.then(
			function (table) {
				for (i = 0; i < 6; i++) {
					chroma = saver[incremental];
					if (chroma != null) {
						var rater = rating(table[chroma].score);
						document.getElementById("container").innerHTML +=
							`<article onclick="myClick(${chroma})" class="tspawn">
										<div class="main"><img src="../front-end/img/${table[chroma].src}.jpg"></div>   
										<table class="tab">
											<tr>
												<th>${table[chroma].name}</th>
											</tr>
											<tr>
												<td>
													<div class="centrus">${rater}</div>
													<div class="main_text">
													${table[chroma].author}<br> 
													Genre: <br>
													${table[chroma].genre} <br>
													</div><br><br>
													<div class="sub_text">
													${table[chroma].description}
												</div></td>
											</tr>
										</table>
									</article>`;
						incremental++;
						//alert(chroma);
					}
				}
			});
}

function Data() {
	incremental = 0;
	saver = [];
	fetch(`../back-end/?q=full`)
		.then(
			response => response.json()
		)
		.then(
			function (table) {
				for (let key in table) {
					saver.push(key);
				}
				document.getElementById("container").innerHTML = "";
				//Ielasa img, nosaukumu un aprakstu katram tabulas ierakstam
				loadMore();
			}
			
		);

	//EM	
	//Funkcija, lai iegūtu attēlu, kas saistīta ar profilu
	fetch("login/prof-img.php?idpfp="+sessionStorage.getItem("uid"))
	.then((response) => response.json())
	.then((data) => {
		document.getElementById("profimg").src="../front-end/profile-pictures/"+data["image"];
		document.getElementById("profimg2").src="../front-end/profile-pictures/"+data["image"];
	}
	);

	//Funkcija, lai paslēptu lgn pogu un parādītu lgndd pogu
	fetch("login/sesion.php")
		.then((response) => response.json())
		.then((data) => {
			sessionStorage.setItem("uid",data["uid"]);
			if(sessionStorage.getItem("uid")==null||sessionStorage.getItem("uid")=="undefined"){
				document.getElementById("lgnhid").style.display="";
				document.getElementById("usrhid").style.display="none";
			}else{
				if(document.getElementById("lgnhid")!=null){
				document.getElementById("lgnhid").style.display="none";
				document.getElementById("usrhid").style.display="";
			}
			//dabūn lietotāja vārdu un pievienošanās datumu
			sessionStorage.setItem("uuser",data["uuser"]);
			//alert(sessionStorage.getItem("uuser"));
			sessionStorage.setItem("user-date-ses",data["udate"]);
			//alert(sessionStorage.getItem("user-date-ses"));
			}
		}
	)
	//EM
}

//EM
//funkcija, lai izlogotos no profila un paslēptu lgndd pogu un parādītu lgn pogu
function lgnout(lgnoutM) {
	fetch("login/logout.php");
	fetch("login/sesion.php")
		.then((response) => response.json())
		.then((data) => {
			sessionStorage.setItem("uid",data["uid"]);
			if(sessionStorage.getItem("uid")==null||sessionStorage.getItem("uid")=="undefined"){
				document.getElementById("lgnhid").style.display="";
				document.getElementById("usrhid").style.display="none";
			}else{
			if(lgnoutM!=1){
				document.getElementById("lgnhid").style.display="none";
				document.getElementById("usrhid").style.display="";
			}else{

			}
		}
		document.location="index.html";
		}
	)
}

//EM

function izer() {
	incremental = 0;
	saver = [];
	window.scroll(0, 500);
	fetch(`../back-end/?q=full`)
		.then(
			response => response.json()
		)
		.then(
			function (table) {
				document.getElementById("container").innerHTML = "";
				var arr = [];
				while (arr.length < 4) {
					var r = Math.floor(Math.random() * table.length);
					if (arr.indexOf(r) === -1) arr.push(r);
				}
				for (i = 0; i < arr.length; i++) {
					var vert = arr[i];
					var rater = rating(table[vert].score);
					document.getElementById("container").innerHTML +=
						`<article onclick="myClick(${vert})" class=t${i}>
						<div class="main"><img src="../front-end/img/${table[vert].src}.jpg"></div>   
					<table class="tab">
						<tr>
							<th>${table[vert].name}</th>
						</tr>
						<tr>
							<td>
							<div class="centrus">${rater}</div>
							<div class="main_text">
							${table[vert].author} <br>
							Genre: <br>
							${table[vert].genre} <br>
							</div><br><br>
							<div class="sub_text">
							${table[vert].description}
							</div></td>
						</tr>
					</table>
					</article>`
				}
				//alert(arr);
			}
		);
}

var rating = function (scorer) {
	var indekusu = Math.round(scorer)
	var feller = "";
	for (var j = 0; j < indekusu; j++) {
		feller += "<span class='fa fa-star checked'></span>";
	}
	for (k = j; k < 5; k++) {
		feller += "<span class='fa fa-star'></span>";
	}
	return feller;
}

var shower = document.getElementsByName("showall");

for (var i = 0; i < shower.length; i++) {
	shower[i].addEventListener("click", function () {
		this.classList.toggle("active");
		var lupa, rupa, panel;
		lupa = document.getElementById("lupar");
		rupa = document.getElementById("rupar");
		panel = this.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling;
		if (panel.style.maxHeight) {
			panel.style.maxHeight = null;
		} else {
			panel.style.maxHeight = panel.scrollHeight + "vh";
		}
		if (rupa.style.display === "inline") {
			lupa.style.display = "none";
			rupa.style.display = "none"
		} else {
			lupa.style.display = "inline";
			rupa.style.display = "inline";
		}
	});
}

function tristate1(control) {
	tristate(control, ' ', '✔', '✖');
}

function tristate(control, value1, value2, value3) {
	switch (control.value.charAt(0)) {
		case value1:
			control.value = value2;
			break;
		case value2:
			control.value = value3;
			break;
		case value3:
			control.value = value1;
			break;
		default:
			// display the current value if it's unexpected
			alert(control.value);
	}
}

var acc = document.getElementsByName("accordion");

for (var i = 0; i < acc.length; i++) {
	acc[i].addEventListener("click", function () {
		this.classList.toggle("active");
		var panel = this.nextElementSibling;
		if (panel.style.maxHeight) {
			panel.style.maxHeight = null;
		} else {
			panel.style.maxHeight = panel.scrollHeight + "vh";
		}
	});
}

//EM
//pieteikšanās modāla Funkcija
function logger() {
	modal.innerHTML = "";
	modal.innerHTML +=
		`<!-- EM -->
		<!-- modāla html kods -->
<div class="modal_login">
	<form class="modal_login_content animate" action="login/login.php" method="post">		<!--form to display the login screen-->
		<div class="titel">Login</div>
		<input type="text" placeholder="username" name="uname" required>
		<br>
		<input type="password" placeholder="password" name="psw" required>
		<br>
		<button class="h5" style="margin-top: 10px; height: 50px; width: 100px">login</button><Br>
		<label>
		<input type="checkbox" checked="checked" name="remember"> Remember me
		</label>
		<p class="message">Not registered? <a href="#">Create an account</a></p>
	</form>
</div>

</input>

</br>
	<!-- EM -->`
	modal.style.display = "block";
	modal.style.padding = "20px 0px 0px 0px";
}

//Funkcija, lai rādītu profila navigācijas nolaižamo izvēlni
function lgnshw() {
	if(document.getElementById("lgndd").style.display == ""){
		document.getElementById("lgndd").style.display = "none";
	} else {
		document.getElementById("lgndd").style.display = "";
	}
}

//Funkcija, lai rādītu settings modālu
function profsetting() {
	modal.innerHTML = "";
	modal.style.display = "block";
	modal.style.padding = "20px 0px 0px 0px";
	
	//dabūn sesiju
	fetch("login/sesion.php")
	.then((response) => response.json())
	.then((data) => {
		sessionStorage.setItem("uid",data["uid"]);
		//alert(sessionStorage.getItem("uid"));
		//document.getElementById("stn-id").value=sessionStorage.getItem("uid");
		
	//dabūn lietotāja id
	fetch("login/prof-img.php?idpfp="+sessionStorage.getItem("uid"))
	.then((response) => response.json())
	.then((data) => {
		modal.innerHTML +=
		`<!-- EM -->
		<!-- modāla html kods -->

<div class="modal_login" style="position: relative">
	<form class="modal_login_content animate" style="width: 700pt;" action="login/settings.php" method="post" enctype="multipart/form-data">		<!--form to display the login screen-->
		<div style="position: relative">
			<div class="titel" style="color: var(--yelh)">Settings</div>
			<div class="stn_type-title-img">New image</div>
			<div>
				<div class="lgndd-stn far fa-user-circle" onclick="document.getElementById('fileToUpload').click()" >
					<img src="../front-end/profile-pictures/${data["image"]}" id="profimg" class="prof-img">
				</div>
				<button class="h5-stn-upl" type="submit" value="Upload Image" name="submit">Upload</button>
				<input type="file" name="fileToUpload" id="fileToUpload" style="display:none">
			</div>
		</div><hr style:"border-color: 4px solid var(--yelh);"><Br>
		<div>
			<div class="stn_type-title">Change username</div>
			<input type="text" placeholder="New username" name="uname" class="stn-input">
		</div>
		<br>
		<div>
			<div class="stn_type-title">Change password</div>
			<input type="password" placeholder="New password" name="psw" class="stn-input"><br>
			<input type="password" placeholder="Confirm new password" name="reppsw" class="stn-input">
		</div>
		<br>
		<button class="h5-stn" style="margin-top: 10px; height: 50px; width: 100px">Save changes</button>
		<input type="hidden" name="id" id="stn-id" value=${sessionStorage.getItem("uid")}>

	</form>
</div>

</input>

</br>
	<!-- EM -->`;
})
}) 	
}
//EM

function changeImage(element) {
	document.getElementById('mainP').style.backgroundImage = "url(" + element.src + ")";
	document.getElementById("mainP").style.display = "inline-block";
	addZoom("mainP");
}



// When the user clicks the button, open the modal 
var myClick = function (numba) {
	fetch(`../back-end/?q=full`)
		.then(
			response => response.json()
		)
		.then(
			function (table) {
				//var modal = document.getElementById("myModal");
				var funkcij = rating(table[numba].score);
				var panelFolder = table[numba].src.replace(/ /g, "_");
				function looksmaxxing() {
					var bg = [];
					var usedIndexes = new Set(); // to keep track of used indexes
					for (var i = 0; i < Number(table[numba].panels); i++) {
						var l;
						do {
							l = Math.floor(Math.random() * Number(table[numba].panels)) + 1; // generate random number between 1 and numPanels (inclusive)
						} while (usedIndexes.has(l)); // check if number is already used
						usedIndexes.add(l); // add index to the set of used indexes
						bg.push(`url(../front-end/panels/${panelFolder}/${l}.jpg)`);

					}
					return bg.join(", ");
				}
				function gapage() {
					if (Number(table[numba].panels) < 1) {
						return ("inline-block");
					}
					else {
						return ("none");
					}
				}

   


				var fillus = [];
				var positus = [];
				if (Number(table[numba].panels) > 1) {
					for (var i = 1; i < Number(table[numba].panels); i++) {
						switch (i) {
							case 1:
								positus.push("right bottom");
								break;
							case 2:
								positus.push("left bottom");
								break;
							case 3:
								positus.push("right top");
								break;
							default:
								positus.push("left top");
								break;
						}
						fillus.push("no-repeat");
					}
					fillus.push("repeat");
					positus.push("left top");
				}
				else {
					positus.push("left top");
					fillus.push("repeat");
				}
				function pammer() {
					var pam = [];
					for (var i = 1; i <= Number(table[numba].panels); i++) {
						pam.push(`<img src="../front-end/panels/${panelFolder}/${i}.jpg" onclick="changeImage(this)">`);
					}
					return pam.join("");
				}
				modal.innerHTML = "";
				modal.innerHTML +=
					`<div class ="modal-content">
					<div class = "wrappa" style="background-image: ${looksmaxxing()}; background-repeat: ${fillus}"></div>
					<div class ="modal-header">
			<table>
				<tr>
					<td class = "modal_img">
					<a href="../front-end/img/${table[numba].src}.jpg" target="_blank">
						<img src="../front-end/img/${table[numba].src}.jpg">
					</a>
					</td><td><h2>
				<h2> ${table[numba].name} </h2>
				<p>
				${table[numba].author} <br>
				${table[numba].genre} <br>
				${table[numba].date_of_publishing}<br>
				${table[numba].status} <br><br>
				${funkcij}
				</p></td></tr></table>
			</div>
			<div class="modal-body">
			<h3>Description</h3>
				<p>${table[numba].description}</p>
			</div>
			<div class="modal-footer" style="background-image: ${looksmaxxing()}; background-repeat: ${fillus}; background-position: ${positus}">
			<div class="gallery">
				<div class="panel_main_view" id="mainP" alt="IMAGE" style = "display: none; background: url(../front-end/panels/P1.png)"></div>
				<div class="panel_side_view">
				${pammer()}
				</div>
			</div>
			<div class = "addpanels">
			<form action="../back-end/upload.php" method="post" enctype="multipart/form-data">
			<label for="fileToUpload" class="custom-file-upload" id="filepicker">
   			 Choose files
			</label>
			  <input type="file" name="fileToUpload[]" id="fileToUpload" accept=".jpg, .jpeg, .png" multiple>
			  <input type="hidden" id="folderName" name="folderName" value="${panelFolder}">
			  <input type="hidden" id="panel_id" name="panel_id" value="${table[numba].id}">
			  <input type="submit" value="Upload" name="submit" class="h5">
			</form>
			<p class="h2" id="h2" style="display: ${gapage()}">Directory empty, choose files to upload!</p> 
			<ul id="file-chosen"></ul>
			</div>
			</div>
		</div>`
				modal.style.display = "block";
				modal.style.padding = "100px 0px 0px 0px";

				const output = document.getElementById("file-chosen");
				document.getElementById("fileToUpload").addEventListener("change", (event) => {
					const files = event.target.files;
					output.textContent = "";
					for (const file of files) {
						const li = document.createElement("li");
						li.textContent = file.name;
						output.appendChild(li);
					}
				});
			}
		);
}

				
var addZoom = target => {
	// (A) GET CONTAINER + IMAGE SOURCE
	let container = document.getElementById(target),
		imgsrc = container.currentStyle || window.getComputedStyle(container, false);
		imgsrc = imgsrc.backgroundImage.slice(4, -1).replace(/"/g, "");
   
	// (B) LOAD IMAGE + ATTACH ZOOM
	let img = new Image();
	img.src = imgsrc;
	img.onload = () => {
	  // (B1) CALCULATE ZOOM RATIO
	  let ratio = img.naturalHeight / img.naturalWidth;
		//  percentage = ratio * 100 + "%";
		//  container.style.paddingBottom = percentage;
	  // (B2) ATTACH ZOOM ON MOUSE MOVE
	  container.onmousemove = e => {
		let rect = e.target.getBoundingClientRect(),
			xPos = e.clientX - rect.left,
			yPos = e.clientY - rect.top,
			xPercent = xPos / (container.clientWidth / 100) + "%",
			yPercent = yPos / ((container.clientWidth * ratio) / /* 50 */ 100) + "%";
   
		Object.assign(container.style, {
		  backgroundPosition: xPercent + " " + yPercent,
		  backgroundSize: img.naturalWidth + "px"
		});
	  };
   
	  // (B3) RESET ZOOM ON MOUSE LEAVE
	  container.onmouseleave = e => {
		Object.assign(container.style, {
		  backgroundPosition: "center",
		  backgroundRepeat: "no-repeat",
		  backgroundSize: "contain"
		});
	  };
	}
  };

function add1() {
	var i = Number(document.getElementById("storage").value);
	if (document.getElementsByClassName("goon").length >= 10) {
		alert(document.getElementsByClassName(add).innerHTML);
	} else {
		var name = i + "more";
		var j = i + 1;
		document.getElementById(name).innerHTML = "";
		document.getElementById(name).innerHTML += `
		<table id=sel_genre${i} name=sel_genre${i}> <tr><td>
		<div class="genrus">
		<select id="genrus" name="genrus" class="goon">
			<option value="Action">Action</option>
			<option value="Adventure">Adventure</option>
			<option value="Comedy">Comedy</option>
			<option value="Drama">Drama</option>
			<option value="Ecchi">Ecchi</option>
			<option value="Fantasy">Fantasy</option>
			<option value="Gender Bender">Gender Bender</option>
			<option value="Historical">Historical</option>
			<option value="Horror">Horror</option>
			<option value="Isekai">Isekai</option>
			<option value="Martial arts">Martial arts</option>
			<option value="Mystery">Mystery</option>
			<option value="Psychological">Psychological</option>
			<option value="Romance">Romance</option>
			<option value="School">School</option>
			<option value="Sci-Fi">Sci-Fi</option>
			<option value="Seinen">Seinen</option>
			<option value="Shonen">Shonen</option>
			<option value="Slice of life">Slice of life</option>
			<option value="Sports">Sports</option>
			<option value="Supernatural">Supernatural</option>
			<option value="Survival">Survival</option>
			<option value="Villainess">Villainess</option>
			<option value="Web comic">Web comic</option>
			<option value="Yuri">Yuri</option>
		</select>
		</div>
		</td>
		<td>
		<button type="button" class="remove" id="remove" onclick="rem1(${i})"> &minus; </button>
		</td>
		</table>
		<div class="more" id=${j}more></div>`
		document.getElementById("storage").value = j;
		i++;
	}
}

var rem1 = function (val) {
	var name = "sel_genre" + val;
	document.getElementById(name).innerHTML = "";
	//alert(val);
}

var twitch = document.getElementById("than");
twitch.onclick = function () {
	if (twitch.innerText == "<") {
		twitch.innerText = ">"
	} else {
		twitch.innerText = "<"
	}
}

function search() {
	var manga, mangaka, elements, genres, scorr, marker, include, exclude, rest, sd, ed, rel_date;
	manga = document.getElementById("mangaTitle").value;
	mangaka = document.getElementById("mangaka").value;
	elements = document.getElementsByClassName("goon");
	genres = [];
	incremental = 0;
	for (var i = 0; i < elements.length; i++) {
		genres[i] = elements[i].value;
	}
	function compare(post, operator, value) {
		switch (operator) {
			case '>':
				return post >= value;
			case '<':
				return post <= value;
		}
	}

	function dateMeasure(start, end, date) {
		if (start >= end) {
			return date >= end && date <= start
		} else {
			return date >= start && date <= end
		}
	}
	scorr = (parseFloat(document.getElementById("scores").value));
	marker = document.getElementsByClassName("tri-state");
	include = [];
	exclude = [];
	rest = [];
	for (var j = 0; j < marker.length; j++) {
		switch (marker[j].value) {
			case ' ':
				rest[j] = marker[j].id;
				break;
			case '✔':
				include[j] = marker[j].id;
				break;
			case '✖':
				exclude[j] = marker[j].id;
		}
	}
	if (include.length >= 1) {
		rest = [];
	} else {
		include = include.concat(rest);
		rest = [];
	}

	sd =
		(
			document.getElementById("sy").value +
			"-" +
			document.getElementById("sm").value +
			"-" +
			document.getElementById("sd").value
		);

	ed =
		(
			document.getElementById("ey").value +
			"-" +
			document.getElementById("em").value +
			"-" +
			document.getElementById("ed").value
		);

	rel_date = ("Between " + sd + " and " + ed);
	feller();

	function feller() {
		fetch(`../back-end/?q=full`)
			.then(
				response => response.json()
			)
			.then(
				function (table) {
					document.getElementById("container").innerHTML = "";
					incremental = 0;
					saver = [];
					for (let key in table) {
						const isSubset = (array1, array2) => array2.every((
							element) => array1.includes(element));
						if (
							(table[key].name.toLowerCase().includes(manga.toLowerCase())) &&
							(table[key].author.toLowerCase().includes(mangaka.toLowerCase())) &&
							(isSubset(table[key].genre.split(", "), genres)) &&
							(compare(table[key].score, twitch.innerText, scorr)) &&
							((!isSubset(exclude, [table[key].status])) &&
								(isSubset(include, [table[key].status]))) &&
							(dateMeasure(sd, ed, table[key].date_of_publishing))
						) {
							saver.push(key);
						}
					}
					loadMore();

				}
			);
	}

}

// Get the modal
//var modal = document.getElementById("myModal");

// Get the <span> element that closes the modal
//var span = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
/*span.onclick = function() {
  modal.style.display = "none";
}*/

// When the user clicks anywhere outside of the modal, close it