<?php include_once($_SERVER['DOCUMENT_ROOT'] . '/_ps2020/_global/dir_root.php'); ?>
<?php include_once($_SERVER['DOCUMENT_ROOT'] . '/_ps2020/config/cfg_loggedUser.php'); ?>
<?php include($_SERVER['DOCUMENT_ROOT'] . "/_ps2020/config/connect.php"); ?>

<!DOCTYPE HTML>
<!--
	Hielo by TEMPLATED
	templated.co @templatedco
	Released for free under the Creative Commons Attribution 3.0 license (templated.co/license)
-->
<html>

<head>
	<title>Students | GEESE</title>
	<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1" />

	<?php include_once(dir_rootPHP . '_global/icon.php'); ?>


	<!-- libs -->
	<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css">
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
	<!-- <link rel="stylesheet" href="<?php echo dir_root; ?>libs/fontAwesome/css/font-awesome.min.css" /> -->
	<!-- <link rel="stylesheet" href="<?php echo dir_root; ?>libs/animate.css" /> -->

	<!-- animation -->
	<link rel="stylesheet" href="<?php echo dir_root; ?>libs/Animate/animate.css" />
	<!-- <link rel="stylesheet" href="<?php echo dir_root; ?>libs/Animate/animate_bounce.css" /> -->
	<link rel="stylesheet" href="<?php echo dir_root; ?>libs/Animate/animate_fade.css" />
	<!-- <link rel="stylesheet" href="<?php echo dir_root; ?>libs/Animate/animate_flip.css" /> -->
	<!-- <link rel="stylesheet" href="<?php echo dir_root; ?>libs/Animate/animate_other.css" /> -->
	<!-- <link rel="stylesheet" href="<?php echo dir_root; ?>libs/Animate/animate_rotate.css" /> -->
	<link rel="stylesheet" href="<?php echo dir_root; ?>libs/Animate/animate_slide.css" />
	<!-- <link rel="stylesheet" href="<?php echo dir_root; ?>libs/Animate/animate_zoom.css" /> -->

	<!-- table-fucntions -->
	<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs4-4.1.1/jq-3.3.1/jszip-2.5.0/dt-1.10.21/af-2.3.5/b-1.6.3/b-colvis-1.6.3/b-flash-1.6.3/b-html5-1.6.3/b-print-1.6.3/cr-1.5.2/fc-3.3.1/fh-3.1.7/kt-2.5.2/r-2.2.5/rg-1.1.2/rr-1.2.7/sc-2.0.2/sb-1.0.0/sp-1.1.1/sl-1.3.1/datatables.min.css" />

	<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/pdfmake.min.js"></script>
	<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/vfs_fonts.js"></script>
	<script type="text/javascript" src="https://cdn.datatables.net/v/bs4-4.1.1/jq-3.3.1/jszip-2.5.0/dt-1.10.21/af-2.3.5/b-1.6.3/b-colvis-1.6.3/b-flash-1.6.3/b-html5-1.6.3/b-print-1.6.3/cr-1.5.2/fc-3.3.1/fh-3.1.7/kt-2.5.2/r-2.2.5/rg-1.1.2/rr-1.2.7/sc-2.0.2/sb-1.0.0/sp-1.1.1/sl-1.3.1/datatables.min.js"></script>

	<!-- css -->
	<link rel="stylesheet" href="<?php echo dir_root; ?>css/template-hielo/main.css" />
	<link rel="stylesheet" href="<?php echo dir_root; ?>css/template-hielo/dataTable.css" />

	<!-- css (custom) -->
	<link rel="stylesheet" href="<?php echo dir_root; ?>css/henry_style.css" />
	<!-- <link rel="stylesheet" href="<?php echo dir_root; ?>css/tanuj_style.css" /> -->
	<!-- <link rel="stylesheet" href="<?php echo dir_root; ?>css/karl_style.css" /> -->
	<!-- <link rel="stylesheet" href="<?php echo dir_root; ?>css/harsh_style.css" /> -->

	<style type="text/css">
		.animated {
			-webkit-animation-duration: .6s;
			animation-duration: .6s;
		}

		input[type="text"] {
			height: 2rem;
		}

		table {
			min-width: 600px;
		}

		.table thead th {
			border-bottom: 0px;
		}

		table td {
			padding-right: 3rem;
		}

		table tbody tr:hover {
			background-color: #58ff582e !important;
			/*#47cd475c*/
		}

		#thDel {
			pointer-events: none;
		}
			#thDel::before,
			#thDel::after {
				content: '';
			}

		#btnAdd {
			width: 100%;
			height: 40px;
			padding: 0 10px;

			border: 1px dashed grey;
			border-radius: 5px;
			background-color: #ffffff40;

			transition: all .2s ease;
		}
			#btnAdd>iconPlus {
				color: green;
				transition: all .2s ease;
			}
			#btnAdd:hover {
				background-color: #548B54;
				/*background-color: #eaeaea40;*/
				border-style: solid;
				cursor: pointer;
			}
			#btnAdd:hover>iconPlus {
				color: white;
				transform: scale(1.02);
			}

		#btnDel {
			text-align: center;

			padding-right: 1rem;
			border-left: 1px solid #cbcbcb;

			cursor: pointer;
			transition: all .4s ease;
		}
			#btnDel:hover {
				background-color: #f55757;
			}
			#btnDel:hover>i {
				color: white;
			}
			#btnDel>i {
				color: #e80000;
				padding-left: 2px;
			}

		.tField_Url {
			display: inline-block !important;
			width: 90% !important;
		}

		#surveyAdd_row {
			display: flex;
			padding: 20px;
		}

		.surveyAdd_rowInner {
			display: inherit;
			width: 100%;
			padding: 20px;

			border: 1px solid #eee;
			border-radius: 15px;
			box-shadow: 0 0 15px #ececec;
		}

		@media all and (max-width: 992px) {
			#surveyAdd_row {
				display: block;
				padding: 10px;
			}
		}

		#studentEmailStatus {
			border: 2px solid red;
			margin:3px;
			
		}

		#btnClose {
			position: absolute;
			top: 10px;
			right: 15px;

			cursor: pointer;
		}

		@media all and (max-width: 992px) {
			#btnClose {
				top: 55px;
				right: 0;
			}
		}

		@media all and (max-width: 576px) {
			.inner {
				width: 95% !important;
			}

			.content {
				padding: 2rem 1rem !important;
			}
		}
	</style>

</head>
<!-- <body class="subpage"> -->

<body>

	<?php
	$user_school_id = 0;
	//$user_class_id = 0;
	$user_id = 0;
	$accountType = $_SESSION['accountType'];
	$username = $_SESSION['user'];
	$email = $_SESSION['email'];
	$schoolNames = array();
	$classNames = array();
	$result = $conn->query("SELECT * FROM user_account WHERE username = '$username'");
	//First we need to get the user's own class_id and school_id
	if ($result->num_rows == 1) { //As each account has unique username and email
		//These information is required based on the accounType
		while ($row = $result->fetch_assoc()) {
			$user_school_id = $row['school_id'];
			$email = $row['email'];
			$accountType = $row['accountType'];
			//Now we fetch the class_id to fetch their class name from school_class
			//$user_class_id = $row['class_Id'];
			$user_id = $row['user_id'];
		}
	}


	//Next we need to load all school names
	$schoolResults = $conn->query("SELECT * FROM school");
	if ($schoolResults->num_rows > 0) {
		while ($row = $schoolResults->fetch_assoc()) {
			$schoolNames[$row['school_id']] = $row['school_name'];
		}
	}

	//Than we need to load all the class names
	// $classResults = $conn->query("SELECT * FROM school_class");
	// if ($classResults->num_rows > 0) {
	// 	while ($row = $classResults->fetch_assoc()) {
	// 		$classNames[$row['class_id']] = $row['class_name'];
	// 	}
	// }


	if($accountType == 2){
		$classResults = $conn->query("SELECT * FROM school_class WHERE teacher_id = '$user_id'");
		if($classResults->num_rows > 0){
			while($row = $classResults->fetch_assoc()){
				$classNames[$row['class_id']] = $row['class_name'];
			}
		}
	}else if($accountType == 3){
		//before we fetch the class
		$classResults = $conn->query("SELECT * FROM school_class WHERE school_id = '$user_school_id'");
		if($classResults->num_rows > 0){
			while($row = $classResults->fetch_assoc()){
				$classNames[$row['class_id']] = $row['class_name'];
			}
		}
	}else if($accountType > 3){	
		$classResults = $conn->query("SELECT * FROM school_class");
		if($classResults->num_rows > 0){
			while($row = $classResults->fetch_assoc()){
				$classNames[$row['class_id']] = $row['class_name'];
			}
		}
	}else{
		//this shouldn't be the case
	}

	//Upto this point we have got school and class names for all

	?>

	<!-- Header | Nav -->
	<?php include_once(dir_rootPHP . '_global/navbar/navbar.php'); ?>
	<?php include_once(dir_rootPHP . '_global/navbar/navbar-mobile.php'); ?>


	<!-- Page-Title -->
	<section id="One" class="wrapper style3" style="padding-top: 9rem;">
		<div class="inner">
			<header class="align-center">
				<p>Greenscape Environmental Experience & Learning Survey Experiments</p>
				<h2>Manage Students</h2>
			</header>
		</div>
	</section>

	<!-- Content -->
	<section id="two" class="wrapper style2">

		<div class="inner">
			<div class="box ctm-box">
				<div class="content">

					<!-- Table -->
					<div class="table-wrapper">

						<!-- <h2>Manage Students</h2> -->

						<div style="padding: 5px; overflow-x: auto;">

							<?php
							//$result = $conn->query("SELECT survey_id AS 'ID', survey_name AS 'Survey-Name', survey_url AS 'URL' FROM survey ORDER BY survey_id ASC");
							if ($accountType == 2 || $accountType == '2') {

								//In this case we have account type of teacher
								//1. We need to get his/her class id\
								//2. Since each teacher can have multiple classes so we store it in an array
								$userCreatedClass_Ids = array();
								$teacherResult = $conn->query("SELECT * FROM school_class WHERE teacher_id  = '$user_id'");
								if ($teacherResult->num_rows) { //As each teacher can have only one class
									while ($row = $teacherResult->fetch_assoc()) {
										//this would be a list of id of user's class
										array_push($userCreatedClass_Ids, $row['class_id']);
									}
								}

								$allClassStudentsString = "SELECT user_id AS 'ID', username AS 'Username', email AS 'Email', password AS 'Password', school_id AS 'School-Name',
									class_id AS 'Class-Name', active AS 'Active' FROM user_account WHERE accountType = '1' AND school_id = '$user_school_id' AND (";

								//that is user is a teacher but does not have a class
								if(count($userCreatedClass_Ids) == 0){
									$allClassStudentsString .= " class_id = '0');";
								}else{
									for ($i = 0; $i < count($userCreatedClass_Ids); $i++) {
										//THis would mean the last class id of that user
										$classId = $userCreatedClass_Ids[$i];
										if ($i == (count($userCreatedClass_Ids) - 1)) {
											$allClassStudentsString = $allClassStudentsString . " class_id = '$classId');";
										} else {
											$allClassStudentsString = $allClassStudentsString . " class_id = '$classId' OR ";
										}
									}
								}

								$result = $conn->query($allClassStudentsString);
							} else if ($accountType == 3 || $accountType == '3') {


								$result = $conn->query("SELECT user_id AS 'ID', username AS 'Username', email AS 'Email', password AS 'Password', school_id AS 'School-Name',
								class_id AS 'Class-Name', active AS 'Active' FROM user_account WHERE accountType = '1' AND school_id = '$user_school_id'");
							
							} else if ($accountType > 3) {

								//We fetch results for all students from all school and all classes
								$result = $conn->query("SELECT user_id AS 'ID', username AS 'Username', email AS 'Email', password AS 'Password', school_id AS 'School-Name',
								class_id AS 'Class-Name', active AS 'Active' FROM user_account WHERE accountType = '1'");
							
							} else {
								//This shouldn't be the case as this page is only meant for role above 1
								header('location:dashboard.php');
							}

							$tablesAndTheirData = array();
							array_push($tablesAndTheirData, array(
								'fields' => $result->fetch_fields(),
								'data' => $result
							));

							foreach ($tablesAndTheirData as $table) {
								if ($table['data']->num_rows) {
							?>
									<table id="data_table" class="table table-striped" style="width:100%;">

										<thead class="animated fadeInUp">
											<tr>
												<?php
												foreach ($table['fields'] as $field) {
												?>
													<th><?php echo $field->name; ?></th>
												<?php
												}
												?>
												<th id="thDel" class="1u 1u$(xsmall)"></th>
											</tr>
										</thead>

										<tbody>
											<?php
											$order_num = 0;
											while ($row = $table['data']->fetch_assoc()) {
												$order_num++;
											?>
												<tr class="animated fadeIn">
													<?php
													$index = 0;

													foreach ($row as $key => $value) {
														if ($key == 'ID') {
															$index = $value;
														}
													?>
														<td>
															<?php
															if ($key == 'Username') {
															?>
																<!-- label -->
																<div id="usernameRow_<?php echo $index; ?>">
																	<label id="username_<?php echo $index; ?>" style="display: inline-block; margin: 0 !important;"><?php echo $value; ?></label>
																	<!-- <i class="fa fa-pencil" style="padding-left: 2px; cursor: pointer;"></i> -->
																</div>
															<?php
															} else if ($key == 'Email') {
															?>
																<!-- label -->
																<div id="emailRow_<?php echo $index; ?>">
																	<label id="email_<?php echo $index; ?>" style="display: inline-block; margin: 0 !important;"><?php echo $value; ?></label>
																	<i class="fa fa-pencil" style="padding-left: 2px; cursor: pointer;" onclick="emailEdit('<?php echo $index; ?>')"></i>
																</div>

																<!-- txtfield -->
																 <div id="emailTField_row<?php echo $index; ?>" class="ctm-toCenter" style="display: none;">
																 <input id="emailtxtfield_<?php echo $index; ?>" name="emailtxtfield_<?php echo $index; ?>" type="text" value="<?php echo $value; ?>" />
																	<!-- Now we will replace the text box with a list of school-name and their id as the value -->
																</div>

																<!-- <div id="nameTField_row<?php //echo $index; ?>" class="ctm-toCenter" style="display: none;">
																	<input id="txtfield_<?php //echo $index; ?>" name="txtfield_<?php //echo $index; ?>" type="text" value="<?php //echo $value; ?>" />
																</div> -->
															<?php
																}
																else if ($key == 'Password'){
															?>
																	<button id="btnPasswordChange" class="button special" style="height: 1.9rem; line-height: 2rem; background-color: #8c8c8c; padding: 0 .8rem; font-size: 12px; text-transform: unset; border-radius: 5px;" onclick="passwordEdit('<?php echo $index; ?>')">Change</button>
															<?php
															} else if ($key == 'School-Name') {

																//Here we get the school name from the list of schools
																$schoolName = "Not Assigned";
																if (isset($schoolNames[$value])) {
																	$schoolName = $schoolNames[$value];
																} else {
																	$schoolName = "Not Assigned";
																}

															?>
																<!-- label -->
																<div id="schoolRow_<?php echo $index; ?>">
																	<label id="school_<?php echo $index; ?>" style="display: inline-block; margin: 0 !important;"><?php echo $schoolName; ?></label>
																	<!-- <i class="fa fa-pencil" style="padding-left: 2px; cursor: pointer;" onclick="schoolEdit('<?php //echo $index; ?>')"></i> -->
																</div>
																<!-- txtfield -->
																<!-- <div id="schoolTField_row<?php //echo $index; ?>" class="ctm-toCenter" style="display: none;">
																	 <input id="schooltxtfield_ name="schooltxtfield_ type="text" value="" /> -->
																	<!-- Now we will replace the text box with a list of school-name and their id as the value -->
																	<!-- <select id="schooltxtfield_<?php //echo $index; ?>">
																		<?php
																		//foreach ($schoolNames as $key => $values) { ?>
																			<option value="<?php //echo $key; ?>"><?php //echo $values; ?></option>
																		<?php	//}
																		?>
																	</select> -->
																<!-- </div> -->
															<?php
															} else if ($key == 'Class-Name') {

																$className = "Not Assigned";
																if (isset($classNames[$value])) {
																	$className = $classNames[$value];
																} else {
																	$className = "Not Assigned";
																}

															?>
																<!-- label -->
																<div id="theclassRow_<?php echo $index; ?>">
																	<label id="theclass_<?php echo $index; ?>" style="display: inline-block; margin: 0 !important;"><?php echo $className; ?></label>
																	<i class="fa fa-pencil" style="padding-left: 2px; cursor: pointer;" onclick="theclassEdit('<?php echo $index; ?>');"></i>
																</div>
																<!-- txtfield -->
																<div id="theclassTField_row<?php echo $index; ?>" class="ctm-toCenter" style="display: none;">
																	<!-- <input id="classtxtfield_<?php //echo $index; 
																									?>"  type="text" value="<?php //echo $className; 
																																				?>" /> -->
																	<select id="theclasstxtfield_<?php echo $index; ?>">
																		<?php foreach ($classNames as $key => $values) { ?>
																			<option value="<?php echo $key; ?>"><?php echo $values; ?></option>
																		<?php } ?>
																	</select>
																</div>
															<?php
																}
																else if ($key == 'Active'){
																	if ($value == 1){
																		$bColor = 'green';
																		$statusVal = 'Active';
																		$statusIc = 'on';
																	}
																	else{
																		$bColor = '#bdbdbd';
																		$statusVal = 'Inactive';
																		$statusIc = 'off';
																	}
															?>
																	<div style="display: block;">
																		<!-- <div style="display: inline-block; width: 70px; text-align: center; background-color: <?php echo $bColor; ?>; color: white; font-size: 14px; padding: 2px 5px; border-radius: 5px;"><?php echo $statusVal; ?></div> -->
																		<i id="statusIc_<?php echo $index; ?>" class="fas fa-toggle-<?php echo $statusIc; ?>" style="display: inline-block; color: <?php echo $bColor; ?>; font-size: 32px; padding-left: 2px; transition: .2s; cursor: pointer;"
																			onclick="activeEdit('<?php echo $index; ?>','<?php echo $value; ?>')"></i>
																	</div>
															<?php
															} else
																echo $value;
															?>
														</td>
													<?php
													}
													?>

													<!-- Delete -->
													<td id="btnDel" class="1u 1u$(xsmall)" onclick="studentDelete('<?php echo $index; ?>')">
														<i id="icDel_<?php echo $index; ?>" class="fa fa-trash"></i>
													</td>
												</tr>
											<?php
											}
											?>
										</tbody>
									</table>
							<?php
								}
							}
							?>

						</div>

						<div style="height: 10px;"></div>

						<!-- ==== Add button is Hidden ==== -->
						<div id="btnAdd" class="animated fadeIn ctm-toCenter" onclick="studentAdd()">
							<iconPlus><i class="fa fa-plus-circle"></i>Add Student</iconPlus>
						</div>

						<!-- ==== New-Survey ==== -->
						<div id="surveyAdd_row" class="animated fadeInDown ctm-hide">


						
							<div class="3u 12u$(medium)">
								<h2>New Student</h2>
							</div>


							<div class="9u 9u$(medium) surveyAdd_rowInner">


								<!-- Survey-Name -->
								<div class="4u 12u$(medium)" style="padding: 10px;">
									<div class=""><label for="newName">Enter the Student's Email:</label></div>
									<input id="newName" name="newName" type="text" style="border-color: #9f9f9f; border-radius: 5px;" value="" />
								</div>

								<!-- ==== (Complete) button ==== -->
								<div class="2u 12u$(medium)" style="padding: 10px;">
									<div style="height: 2rem;"></div>
									<div id="btnComplete" class="animated fadeIn ctm-toCenter" >
										<div class="button special fit" style="text-transform: unset; border-radius: 5px; margin: 0;" onclick="surveyAdd_toDb();">Submit!</div>
									</div>
								</div>

								<!-- ==== (Close) button ==== -->
								<div id="btnClose"><i class="fa fa-times-circle-o" style="font-size: 32px; color: #ff00009e;" onclick="surveyAdd_close()"></i></div>
							</div>
						</div>

					</div>

				</div>
			</div>
		</div>
	</section>


	<!-- Footer -->
	<?php include_once(dir_rootPHP . '_global/footer/footer.php'); ?>

	<script type="text/javascript">
		$(document).ready(function() {
			$('#data_table').DataTable({
				dom: 'frtip',
				pageLength: 5
			});
		});
	</script>

	<!-- Scripts -->
	<!-- <script src="<?php echo dir_root; ?>js/template-hielo/jquery.min.js"></script> -->
	<script src="<?php echo dir_root; ?>js/template-hielo/jquery.scrollex.min.js"></script>
	<script src="<?php echo dir_root; ?>js/template-hielo/skel.min.js"></script>
	<script src="<?php echo dir_root; ?>js/template-hielo/util.js"></script>
	<script src="<?php echo dir_root; ?>js/template-hielo/main.js"></script>


	<!-- ==========  <- Pop-Notification ->  ========== -->
	<?php include_once(dir_rootPHP . '_global/tools/popNotif.php'); ?>

	<!-- ==========  <- Popup-Alert ->  ========== -->
	<?php include_once(dir_rootPHP . '_global/tools/popAlert.php'); ?>

	<!-- ==========  <- Pop-Window ->  ========== -->
	<?php include_once(dir_rootPHP.'_global/tools/popWindow.php'); ?>

	<!-- Scripts (custom) -->
	<script type="text/javascript">
		/*--------Add New Student---*/

		function studentAdd() {
			$('#surveyAdd_row').removeClass('ctm-hide');
			$('#btnAdd').addClass('ctm-hide');
		}
		/* -----  Add  ----- */
		$('#newName').blur(function() {
			//This will be used to check if the email is valid or not
			
			var email = $("#newName").val();
			
			$("#newName").val(email.trim());
			email = email.trim();

			// alert("The value of email: " + email);

			if (email == undefined || email == "" | email == null) {
				
				$icon = 2;
				$msg = 'Please enter an Email!';
				popNotif_show($icon, $msg);
				
			}else if(!(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(email))){
					
				$icon = 2;
				$msg = 'Please enter a valid email!!';
				popNotif_show($icon, $msg);

			}
			// else{
				
			// 	var xmlhttp = new XMLHttpRequest();
			// 	xmlhttp.onreadystatechange = function() {
			// 	if (this.status == 200 && this.readyState == 4) {
			// 		var theresponse = this.responseText;
			// 		if (theresponse == "1" || theresponse == 1) {
						
			// 			$icon = 1;
			// 			$msg = 'Email is Valid!!';
			// 			popNotif_show($icon, $msg);
						
			// 		} else {
						
			// 			$icon = 2;
			// 			$msg = 'Email is Invalid!!';
			// 			popNotif_show($icon, $msg);
						
			// 		}
			// 	}else{
			// 			$icon = 2;
			// 			$msg = "Email doesn't Exist!!";
			// 			popNotif_show($icon, $msg);
			// 	}
			// };
			// xmlhttp.open("GET", "post_verifyUser.php?email=" + email, false);
			// xmlhttp.send();
			// }
		});

		function surveyAdd_toDb(){

			//This is function for submit button click
			//But in this section we will show more appropriate error messages
			var email = $("#newName").val();
			$("#newName").val(email.trim());
			email = email.trim();

			if(email == "" || email == undefined || email == null){

				$('#popBtn_confirm').css({
					'background-color': 'white',
					'color': 'black',
					'font-weight': 'normal'
				});

				$('#popBtn_confirm').hover(function() {
					$(this).css({
						'font-weight': 'bold'
					});
				}, function() {
					$(this).css({
						'font-weight': 'normal'
					});
				});

				// show pop-alert
				$title = 'Insert An Email!';
				$msg = 'Please Input an Email!!';
				$confirm = 'Okay';
				$cancel = 'Cancel';
				$icon = 3;

				popAlert_btnSingle();
				popAlert_show($title, $msg, $confirm, $cancel, $icon);

			}else if(!(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(email))){

				$('#popBtn_confirm').css({
					'background-color': 'white',
					'color': 'black',
					'font-weight': 'normal'
				});

				$('#popBtn_confirm').hover(function() {
					$(this).css({
						'font-weight': 'bold'
					});
				}, function() {
					$(this).css({
						'font-weight': 'normal'
					});
				});

				// show pop-alert
				$title = 'Invalid Email Format!';
				$msg = 'Please input A Valid Email!';
				$confirm = 'Okay';
				$cancel = 'Cancel';
				$icon = 3;

				popAlert_btnSingle();
				popAlert_show($title, $msg, $confirm, $cancel, $icon);

			}else{
				//Here we will just add the user to a student account type
				var xmlhttp = new XMLHttpRequest();
				xmlhttp.onreadystatechange = function(){
					if(this.readyState == 4 && this.status == 200){
						var theResponse = this.responseText;
						if(theResponse == 1 || theResponse == "1"){
							//this would mean that the user has entered the correact email
							
							var xmlhttp2 = new XMLHttpRequest();
							xmlhttp2.onreadystatechange = function(){
								
								if(this.readyState == 4 && this.status == 200){
									var theResponse = this.responseText;
									// alert("The email :" + email);
									// alert("The response is: " + theResponse);
								if(theResponse == 1 || theResponse == "1"){

										$('#popBtn_confirm').css({
											'background-color': 'white',
											'color': 'black',
											'font-weight': 'normal'
										});

										$('#popBtn_confirm').hover(function() {
											$(this).css({
												'font-weight': 'bold'
											});
										}, function() {
											$(this).css({
												'font-weight': 'normal'
											});
										});

										// show pop-alert
										$title = 'Operation Success!';
										$msg = 'A New Student Has Been Ended!!';
										$confirm = 'Okay';
										$cancel = 'Cancel';
										$icon = 1;

										popAlert_btnSingle();
										popAlert_show($title, $msg, $confirm, $cancel, $icon);

										$('#popBtn_confirm').click(function(){
											window.location.reload();
										});

										// setInterval(function(){
										// 	window.location.reload();
										// }, 6000);

									}else{

										$('#popBtn_confirm').css({
										'background-color': 'white',
										'color': 'black',
										'font-weight': 'normal'
									});

									$('#popBtn_confirm').hover(function() {
										$(this).css({
											'font-weight': 'bold'
										});
									}, function() {
										$(this).css({
											'font-weight': 'normal'
										});
									});

									// show pop-alert
									$title = 'Invalid Email!';
									$msg = 'Email Is Invalid!!';
									$confirm = 'Okay';
									$cancel = 'Cancel';
									$icon = 3;

									popAlert_btnSingle();
									popAlert_show($title, $msg, $confirm, $cancel, $icon);

									}

								}
							};
							xmlhttp2.open("POST","<?php echo dir_root; ?>php/ajax/post_addStudent.php?email=" + email, false);
							xmlhttp2.send();

						}else{

							$('#popBtn_confirm').css({
								'background-color': 'white',
								'color': 'black',
								'font-weight': 'normal'
							});

							$('#popBtn_confirm').hover(function() {
								$(this).css({
									'font-weight': 'bold'
								});
							}, function() {
								$(this).css({
									'font-weight': 'normal'
								});
							});

							// show pop-alert
							$title = 'Invalid Email!';
							$msg = 'Please Input A Valid Email!';
							$confirm = 'Okay';
							$cancel = 'Cancel';
							$icon = 3;

							popAlert_btnSingle();
							popAlert_show($title, $msg, $confirm, $cancel, $icon);
							return;
						}
					}
				};
				xmlhttp.open("POST","<?php echo dir_root; ?>php/ajax/post_verifyUser.php?email=" + email, false);
				xmlhttp.send();
			}

		}


		// function surveyAdd_toDb() {
		// 	//Before we do it we need to check if email entered is valid or not
		// 	var email = $("#newName").val();
		// 	$("#newName").text(email.trim());
		// 	email = email.trim();
		// 	if (email == undefined || email == "") {
		// 		$("#studentEmailStatus").text("Email is Required");
		// 		$("#studentEmailStatus").css("color", "red");
		// 		return;
		// 	} else {
		// 		var xmlhttp = new XMLHttpRequest();
		// 		xmlhttp.onreadystatechange = function() {
		// 			if (this.status == 200 && this.readyState == 4) {
		// 				var theresponse = this.responseText;
		// 				if (theresponse == "1") {
		// 					//It is true
		// 					$("#studentEmailStatus").css("color", "green");
		// 					$("#studentEmailStatus").text("valid");
		// 					//This can continue
		// 					//Here we will just add that particpant to the student class
		// 					var xmlhttp = new XMLHttpRequest();
		// 					xmlhttp.onreadystatechange = function(){
		// 						if(this.status == 200 && this.readyState == 4){
		// 							var theResponse = this.responseText;
		// 							if(theResponse == "1"){
		// 								//Here we just added the new student
		// 								//Now we just need to reload the table
		// 								$icon = 1;
		// 								$msg = '"A New student has been Added!!';
		// 								popNotif_show($icon, $msg);
		// 								setInterval(function(){
		// 									location.reload(); 
		// 								}, 5000);
		// 							}else{
		// 								$icon = 1;
		// 								$msg = '"System Error has occured!!';
		// 								popNotif_show($icon, $msg);
		// 							}
		// 						}
		// 					};
		// 					xmlhttp.open("POST","post_addStudent.php?email=" + email, false);
		// 					xmlhttp.send()

		// 				} else {
		// 					//It is false
		// 					$("#studentEmailStatus").css("color", "red");
		// 					$("#studentEmailStatus").text("Invalid");
		// 					//We will end this function
		// 					$('#popBtn_confirm').css({
		// 						'background-color': 'white',
		// 						'color': 'black',
		// 						'font-weight': 'normal'
		// 					});

		// 					$('#popBtn_confirm').hover(function() {
		// 						$(this).css({
		// 							'font-weight': 'bold'
		// 						});
		// 					}, function() {
		// 						$(this).css({
		// 							'font-weight': 'normal'
		// 						});
		// 					});

		// 					// show pop-alert
		// 					$title = 'Insert a valid email';
		// 					$msg = 'Please insert a valid email!';
		// 					$confirm = 'Okay';
		// 					$cancel = 'Cancel';
		// 					$icon = 3;

		// 					popAlert_btnSingle();
		// 					popAlert_show($title, $msg, $confirm, $cancel, $icon);

		// 				}
		// 			}
		// 		};
		// 		xmlhttp.open("POST", "post_verifyUser?email=" + email, false);
		// 		xmlhttp.send();
		// 	}

		// }


		/*------- Edit-School-----*/

		function schoolEdit($sid) {
			// hide 'label'
			$('#schoolRow_' + $sid).hide();
			// show 'txtfield'
			$('#schoolTField_row' + $sid).show();
			// edit in 'txtfield'
			$('#schooltxtfield_' + $sid).focus();

			$('#schooltxtfield_' + $sid).focusout(function() { // click outside txtfield
				//this place we will just hide the dropdown list and 
				//Present the label again
				$('#schoolTField_row' + $sid).hide();
				$('#schoolRow_' + $sid).show();
			});

			$('#schooltxtfield_' + $sid).change(function() {
				updateSchool($sid);
			});
		}

		function emailEdit($sid){
			$("#emailRow_"+$sid).hide();
			$("#emailTField_row"+$sid).show();
			$("#emailtxtfield_"+$sid).focus;

			$("#emailtxtfield_"+$sid).focusout(function(){
				$("#emailTField_row"+$sid).hide();
				$("#emailRow_"+$sid).show();
			});

			$("#emailtxtfield_"+$sid).change(function(){
				updateEmail($sid);
			});

		}

		function updateSchool($sid) {
			$newName = $('#schooltxtfield_' + $sid).val();
			$.ajax({
				type: 'POST',
				url: '<?php echo dir_root; ?>php/ajax/post_studentUpdate.php?act=update_sSchool&sid=' + $sid + '&school=' + $newName,
				date: '',
				success: function(m) {
					// hide 'txtfield'
					$('#schoolTField_row' + $sid).hide();
					// update 'label'
					//Once hidden we cannot fetch the value of the dropdown list
					//$nameVal = $('#schooltxtfield_' + $sid).val();

					//Here we get the value of the school_id
					//Now we need to fetch the school name
					var xmlhttp = new XMLHttpRequest();
					xmlhttp.onreadystatechange = function() {
						if (this.readyState == 4 && this.status == 200) {
							var theResponse = this.responseText;
							$('#school_' + $sid).text(theResponse);
							$('#theclass_' + $sid).text("Not Assigned");
						}
					};
					//Here we are passing the school id as the $newName variable
					xmlhttp.open("GET", "getSchoolName.php?q=" + $newName, false);
					xmlhttp.send();

					//$('#school_' + $sid).text($nameVal);
					// show 'label'
					$('#schoolRow_' + $sid).show();

					// Notification
					$icon = 1;
					$msg = '"Student-School" has been updated!!';
					popNotif_show($icon, $msg);
				}
			});
		}

		function updateEmail($sid){
			$newEmail = $('#emailtxtfield_' + $sid).val();
			$("#emailtxtfield_"+$sid).val($newEmail.trim());
			$newEmail = $newEmail.trim();
			const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
			if(!re.test($newEmail)){
				$icon = 2;
				$msg = '"Student-Email" Not Valid!!';
				popNotif_show($icon, $msg);
			}else{

				var xmlhttp = new XMLHttpRequest();
				xmlhttp.onreadystatechange = function(){
					if(this.status == 200 &&  this.readyState == 4){
						var response = this.responseText;
						// alert("the response is : " + response);
						if(response == 1 || response == "1"){
							
							var xmlhttp = new XMLHttpRequest();
							xmlhttp.onreadystatechange = function(){

								if(this.status == 200 && this.readyState == 4){

									var response = this.responseText;
									// alert("The next response is: " + response);
									if(response == 1 || response == "1"){
										// $icon = 1;
										// $msg = '"Student-Email" Is Updated!!';
										// popNotif_show($icon, $msg);

										// //now we hide the input box
										// $("#emailTField_row"+$sid).hide();
										// $("#email_"+$sid).val($("#emailtxtfield_"+$sid).val());
										// $("#emailRow_"+$sid).show();

										$('#emailTField_row'+$sid).hide();
									// update 'label'
										$nameVal = $('#emailtxtfield_'+$sid).val();
										$('#email_'+$sid).text($nameVal);
										// show 'label'
										$('#emailRow_'+$sid).show();

										// Notification
											$icon = 1;
											$msg = '"Student-Email" Is Updated!';
										popNotif_show($icon,$msg);

									}else{	
										$icon = 2;
										$msg = '"Student-Email" Cannot Be updated!!';
										popNotif_show($icon, $msg);
									}

								}

							};
							xmlhttp.open("POST","<?php echo dir_root; ?>php/ajax/post_updateStudentEmail.php?sid="+$sid+"&email="+$newEmail, false);
							xmlhttp.send();

						}else{	
							$icon = 2;
							$msg = '"Student-Email" Is Taken!!';
							popNotif_show($icon, $msg);
						}
					}
				};
				xmlhttp.open("GET","<?php echo dir_root; ?>php/ajax/post_checkEmail.php?email="+$newEmail, false);
				xmlhttp.send();

			}
		}

		/* -----  Change-Password  ----- */
		function passwordEdit($sid){
			// show pop-pWin
				$pWUrl = '<?php echo dir_root; ?>_global/html/getForm_manageUser_passwordChange.php';
				$pWTitle = 'Password';
				$pWHeader = 'Change Password';
				$pWMsg = '';
				$pWConfirm = 'Confirm';
				$pWCancel = 'Cancel';
				$pWIcon = 0;
			
			popWindow_show($pWUrl,$pWTitle,$pWHeader,$pWMsg,$pWConfirm,$pWCancel,$pWIcon);

			$('#popWinBtn_confirm').click(function(e){
				// console.log('clicked');
				
				var iFrame_func = $('#popWin_iFrame')[0].contentWindow;

				if (!iFrame_func.error_inPassword() && !iFrame_func.error_inPasswordConfirm()){
					// console.log('password correct');
					
					$password = iFrame_func.$('#password').val();
					
					// show pop-alert
						$title = 'Change Password?';
						$msg = 'Are you sure to change password for user: '+$('#name_'+$sid).text()+'?';
						$confirm = 'Confirm';
						$cancel = 'Cancel';
						$icon = 0;
					
					popAlert_show($title,$msg,$confirm,$cancel,$icon);

					$('#popBtn_confirm').click(function(){
						$.ajax({
							type :'POST',
							url  :'<?php echo dir_root; ?>php/ajax/post_userUpdate.php?act=update_password&sid='+$sid+'&password='+$password,
							date :'',
							success:function(m){
								// console.log(m);
								if (m == 1){
									// location.reload();
									popWindow_hide();

									// Notification
										$icon = 1;
										$msg = 'Success: password changed!!';
									popNotif_show($icon,$msg);
								}
								else{
									// Notification
										$icon = 2;
										$msg = 'Failed to add user to database';
									popNotif_show($icon,$msg);
								}
							}
						});
					});
				}
			});
		}

		/*------ Edit-Class------*/

		function theclassEdit($sid) {

			// hide 'label'
			$('#theclassRow_' + $sid).hide();
			// show 'txtfield'
			$('#theclassTField_row' + $sid).show();
			// edit in 'txtfield'
			$('#theclasstxtfield_' + $sid).focus();

			$('#theclasstxtfield_' + $sid).focusout(function() {

				$('#theclassTField_row' + $sid).hide();
				$('#theclassRow_' + $sid).show();
				//alert("It does not come here");
			});

			$('#theclasstxtfield_' + $sid).change(function() {
				updateClass($sid);
			});
		}

		function updateClass($sid) {
			$newName = $('#theclasstxtfield_' + $sid).val();
			//alert("It even comes here my friend!!");
			$.ajax({
				type: 'POST',
				url: '<?php echo dir_root; ?>php/ajax/post_studentUpdate.php?act=update_sClass&sid=' + $sid + '&class=' + $newName,
				date: '',
				success: function(m) {
					// hide 'txtfield'
					$('#theclassTField_row' + $sid).hide();
					// update 'label'
					//$nameVal = $('#classtxtfield_' + $sid).val();

					//This is where the change begins as we need to get the name of that class
					//Since we have the id we can fetch the name
					var xmlhttp = new XMLHttpRequest();
					xmlhttp.onreadystatechange = function() {
						if (this.readyState == 4 && this.status == 200) {
							var theResponse = this.responseText;
							$('#theclass_' + $sid).text(theResponse);
						}
					};
					xmlhttp.open("GET", "getClassName.php?q=" + $newName, false);
					xmlhttp.send();

					$('#theclassRow_' + $sid).show();

					//Now that class name has been updated we need to update the school-name
					var xmlhttp = new XMLHttpRequest();
					xmlhttp.onreadystatechange = function() {
						if (this.readyState == 4 && this.status == 200) {
							//With this we place school name into the label
							$('#school_' + $sid).text(this.responseText);
						}
					};
					xmlhttp.open("GET", "getClassSchoolName.php?q=" + $newName, false);
					xmlhttp.send();

					// show 'label'


					// Notification
					$icon = 1;
					$msg = '"Student-Class" has been updated!!';
					popNotif_show($icon, $msg);

					// setTimeout(function(){ 
					// 	window.location.reload();	
					// }, 3000);

				}
			});
		}

		/* -----  Active-Status  ----- */
			function activeEdit($index,$value){

				var newVal;

				if ($value == 1){
					$title = 'Disable an Account?';
					$msg = 'Are you sure to <b style="color: red;">disable</b> the account for <b>"'+$('#username_'+$index).html()+'"</b>?';
					newVal = -1;
				}
				else{
					$title = 'Active an Account?';
					$msg = 'Are you sure to <b style="color: #00a500;">active</b> the account for <b>"'+$('#username_'+$index).html()+'"</b>?';
					newVal = 1;
				}

				// show pop-alert
					$confirm = 'Confirm';
					$cancel = 'Cancel';
					$icon = 0;
				
				popAlert_show($title,$msg,$confirm,$cancel,$icon);

				$('#popBtn_confirm').click(function(){setTimeout(function() {
						updateStatus($index,newVal);
				}, animTime);});
			}
				function updateStatus($index,$value){
					$.ajax({
						type :'POST',
						url  :'<?php echo dir_root; ?>php/ajax/post_userUpdate.php?act=update_status&index='+$index+'&statVal='+$value,
						date :'',
						success:function(m){
							// Notification
							if (m == 1 || m == "1"){
								location.reload();
								// $icon = 1;
								// $msg = '<b>Success: </b>The row of <b>"'+$('#name_'+$index).html()+'"</b> is updated';

								// if ($value == 1){
								// 	$('#statusIc_'+$index).removeClass('fa-toggle-on').addClass('fa-toggle-off').css({ 'color': '#bdbdbd' });
								// }
								// else
								// 	$('#statusIc_'+$index).removeClass('fa-toggle-off').addClass('fa-toggle-on').css({ 'color': 'green' });
							}
							else{
								$icon = 2;
								$msg = 'Failed updating to database';
							}
							popNotif_show($icon,$msg);
						}
					});
				}

		/* -----  Delete  ----- */
		function studentDelete($sid) {

			// style 'Confirm'
			$('#popBtn_confirm').css({
				'color': 'red'
			});

			$('#popBtn_confirm').hover(function() {
				$(this).css({
					'background-color': 'red',
					'color': 'white'
				});
			}, function() {
				$(this).css({
					'background-color': '',
					'color': 'red'
				});
			});

			// style 'Cancel'
			$('#popBtn_cancel').hover(function() {
				$(this).css({
					'background-color': 'white',
					'color': 'unset',
					'font-weight': 'bold'
				});
			}, function() {
				$(this).css({
					'background-color': '',
					'color': '',
					'font-weight': ''
				});
			});

			// show pop-alert
			$title = 'Are you sure?';
				$msg = 'Are you sure to remove student: <b>'+$('#username_'+$sid).html()+'</b> from this school?<br><br>';
				$msg += 'Removing will turn the student account to participant and the account will no longer be assigned to any school.';
			$confirm = 'Remove';
			$cancel = 'Cancel';
			$icon = 4;

			popAlert_show($title, $msg, $confirm, $cancel, $icon);

			$('#popBtn_confirm').click(function() {
				$.ajax({
					type: 'POST',
					url: '<?php echo dir_root; ?>php/ajax/post_studentDelete.php?sid=' + $sid,
					date: '',
					success: function(m) {
						location.reload();
					}
				});
			});
		}

		// Close Add
		function surveyAdd_close(){
            $('#surveyAdd_row').addClass('ctm-hide');
            $('#btnAdd').removeClass('ctm-hide');
        }
	</script>

</body>

</html>