
// EM
// Get the login modal
var modal = document.getElementById('lgn_id');

// When the user clicks anywhere outside of the login modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}

// EM

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].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();
			}
		);
}

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;;
		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";
		}
	});
}
// 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);
				modal.innerHTML = "";
				modal.innerHTML +=
					`<div class="modal-content">
			<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}(${table[numba].score}) 
				</p></td></tr></table>
			</div>
			<div class="modal-body">
			<h3>Description</h3>
				<p>${table[numba].description}</p>
			</div>
			<div class="modal-footer">
				<h3></h3>
			</div>
		</div>`
				modal.style.display = "block";
			}
		);
}

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