<?php include "common/user_log.php"; ?>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>NWP Engineering Department</title>
    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <!-- Bootstrap 3.3.5 -->
    <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="dist/css/font-awesome.min.css">
    <!-- Ionicons -->
    <link rel="stylesheet" href="dist/css/ionicons.min.css">
    <!-- daterange picker -->
    <link rel="stylesheet" href="plugins/daterangepicker/daterangepicker-bs3.css">
    <!-- iCheck for checkboxes and radio inputs -->
    <link rel="stylesheet" href="plugins/iCheck/all.css">
    <!-- Bootstrap Color Picker -->
    <link rel="stylesheet" href="plugins/colorpicker/bootstrap-colorpicker.min.css">
    <!-- Bootstrap time Picker -->
    <link rel="stylesheet" href="plugins/timepicker/bootstrap-timepicker.min.css">
    <!-- Select2 -->
    <link rel="stylesheet" href="plugins/select2/select2.min.css">
	<!-- DataTables -->
    <link rel="stylesheet" href="plugins/datatables/dataTables.bootstrap.css">
    <!-- Theme style -->
    <link rel="stylesheet" href="dist/css/AdminLTE.min.css">
    <!-- AdminLTE Skins. Choose a skin from the css/skins
         folder instead of downloading all of them to reduce the load. -->
    <link rel="stylesheet" href="dist/css/skins/_all-skins.min.css">
    <link rel="stylesheet" href="bootstrap-sweetalert/lib/sweet-alert.css" />
  </head>
  <body class="hold-transition skin-blue sidebar-mini sidebar-collapse">
    <div class="wrapper">

      <header class="main-header">
        <!-- Logo -->
         <a href="home.php" class="logo">
          <!-- mini logo for sidebar mini 50x50 pixels -->
         <span class="logo-mini"><img src="img/logo.png" width="100"></span>
          <!-- logo for regular state and mobile devices -->
        <span class="logo-lg"><b><img src="img/logo.png" width="100"></b></span>
        </a>
        <!-- Header Navbar: style can be found in header.less -->
        <nav class="navbar navbar-static-top" role="navigation">
          <!-- Sidebar toggle button-->
          <a href="#" class="sidebar-toggle" data-toggle="offcanvas" role="button">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
			 <span class="logo-lg">
             &nbsp;&nbsp;<font face="Lucida Sans Unicode, Lucida Grande, sans-serif">NWP Engineering Department</font></span>
          </a>
		
          <div class="navbar-custom-menu">
            <ul class="nav navbar-nav">

              <!-- User Account: style can be found in dropdown.less -->
              <li class="dropdown user user-menu">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                  <img src="dist/img/user2-160x160.png" class="user-image" alt="User Image">
                  <span class="hidden-xs"><?php echo $name; ?></span>
                </a>
                <ul class="dropdown-menu">
                  <!-- User image -->
                  <li class="user-header">
                    <img src="dist/img/user2-160x160.png" class="img-circle" alt="User Image">
                    <p>
             NWP Engineering Department
                    
                    </p>
                  </li>
                  <!-- Menu Body -->
                 
                  <!-- Menu Footer-->
                  <li class="user-footer">
                    <div class="pull-left">
                      
                    </div>
                    <div class="pull-right">
                      <a href="distroy.php" class="btn btn-default btn-flat">Sign out</a>
                    </div>
                  </li>
                </ul>
              </li>
              <!-- Control Sidebar Toggle Button -->
              <li>
                <a href="#" data-toggle="control-sidebar"><i class="fa fa-gears"></i></a>
              </li>
            </ul>
          </div>
        </nav>
      </header>
      <!-- Left side column. contains the logo and sidebar -->
      <aside class="main-sidebar">
        <!-- sidebar: style can be found in sidebar.less -->
        <section class="sidebar">
          <!-- Sidebar user panel -->
    <?php include "common/sidebar.php"; ?>  
     
        </section>
        <!-- /.sidebar -->
      </aside>

      <!-- Content Wrapper. Contains page content -->
      <div class="content-wrapper">
        <!-- Content Header (Page header) -->
        <section class="content-header">
          <h1>
            Add Staff Members
          </h1>
          
    <ol class="breadcrumb">
      <li><a href="home.php"><i class="fa fa-home"></i> Home</a></li>
    </ol>
        </section>

        <!-- Main content -->
        <section class="content">

<!-- ************************************************* -->
  <div class="box box-info only_eng"> 
    <div class="box-header with-border"> 
      <h3 class="box-title">Staff Member Registration</h3>
    </div>

    <div class="box-body"> 
	  

 		<div class="form-group">
		  <input name="st" id="mr" type="radio"  class="minimal" value="Mr" checked>
		  <label> &nbsp;&nbsp;Mr</label>&nbsp;&nbsp;&nbsp;&nbsp;
		  <input name="st" id="mrs" type="radio" class="minimal" value="Mrs">
		  <label class="m-l-20"> &nbsp;&nbsp;Mrs</label>&nbsp;&nbsp;&nbsp;&nbsp;
		  <input name="st" id="miss" type="radio" class="minimal" value="Miss">
		  <label class="m-l-20"> &nbsp;&nbsp;Miss</label>
		</div>	 

	 <div class="form-group"> 
        <label>Name:<font color="#FF0000"><strong>*</strong></font></label>
        <input type="text" class="form-control error" id="name" autocomplete="off">
      </div>
	  
	  <div class="form-group"> 
        <label>Division:</label>
			<select class="form-control select2 error" id="division" name="division" style="width: 100%;">
			  <option></option>
			  <?php
				$sql="SELECT * FROM division ORDER BY division ASC";
				$result=mysqli_query($conn, $sql);
				while ($row = mysqli_fetch_array($result)){ ?>
				<option value="<?php echo $row['division']; ?>"><?php echo $row['division']; ?></option>
			  <?php } ?>
			</select>		
      </div>	  
	  
	  <div class="form-group"> 
        <label>Address:<font color="#FF0000"><strong>*</strong></font></label>
        <input type="text" class="form-control error" id="address" autocomplete="off">
      </div>
	  
	  <div class="form-group"> 
        <label>Designation:</label>
			<select class="form-control select2 error" id="designation" name="designation" style="width: 100%;">
			  <option></option>
			  <?php
				$sql="SELECT * FROM designation ORDER BY name ASC";
				$result=mysqli_query($conn, $sql);
				while ($row = mysqli_fetch_array($result)){ ?>
				<option value="<?php echo $row['name']; ?>"><?php echo $row['name']; ?></option>
			  <?php } ?>
			</select>		
      </div>
	  
	  <div class="form-group"> 
        <label>NIC Number:<font color="#FF0000"><strong>*</strong></font></label>
        <input type="text" class="form-control error" id="nic" autocomplete="off">
      <span id="val_valid_nic" style="display:none" class="formError"><font color="#F44336">Please Enter Valid NIC Number</font></span>
	  </div>

    <div class="form-group"> 
      <label>Select Service:<font color="#FF0000"><strong>*</strong></font></label>
      <select class="form-control select2 error" id="service" name="service" style="width: 100%;" required>
      <?php
        $sql="SELECT * FROM cader_details_tbl GROUP BY service ORDER BY id DESC";
        $result=mysqli_query($conn, $sql);

        while ($row = mysqli_fetch_array($result)){
      ?>

        <option value="<?php echo $row['service']; ?>"><?php echo $row['service']; ?></option>

      <?php } ?>
      </select>
    </div>   
	  
	  	<div class="form-group">
              <label>Date of Birth:<font color="#FF0000"><strong>*</strong></font></label>            
            <div class="input-group"> 
              <div class="input-group-addon"> <i class="fa fa-calendar"></i> </div>
              <input type="text" class="form-control pull-right" id="dob" name="dob" autocomplete="off">
            </div>
        </div>	

		<div class="form-group">
		<label>Gender:<font color="#FF0000"><strong>*</strong></font></label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
		  <input name="gender" type="radio" id="male" class="minimal" value="1" checked>
		  <label for="male"> &nbsp;&nbsp;Male</label>&nbsp;&nbsp;&nbsp;&nbsp;
		  <input name="gender" type="radio" id="female" class="minimal" value="2">
		  <label for="female" class="m-l-20"> &nbsp;&nbsp;Female</label>
		</div>		
	  
	  <div class="form-group"> 
        <label>Contact Number:<font color="#FF0000"><strong>*</strong></font></label>
        <input type="text" class="form-control" id="tel_office" autocomplete="off">
		<span id="valid_tel_office" style="display:none" class="formError"><font color="#F44336">Please Enter Valid Contact Number</font></span>
      </div>
	  
	  <div class="form-group"> 
        <label>Email Address:</label>
        <input type="text" class="form-control" id="email" autocomplete="off">
		<span id="val_valid_mail" style="display:none" class="formError"><font color="#F44336">Please Enter Valid Email Address</font></span>
      </div>
	  
		<div class="form-group"> 
          <div class="form-group">
            <label for="exampleInputFile">Select Profile Picture</label>
            <input type="file" class="form-control" id="img_upload" name="img_upload" accept="image/*">
			<span id="valid_img" style="color: red; display: none">*Please Select Valid Image</span>
          </div>
        </div>	  
		
       <span style="color: red;" class="pull-right">* Required Fields</span>
      <!-- /.box-body -->
      <div class="box-footer"> 
        <button  id="btn_submit" class="btn btn-primary">SUBMIT</button>
      </div>

    </div>	
  </div>

 <!-- /.table -->
        
    <div class="box box-info"> 
      <div class="box-header"> 
        <h3 class="box-title">Staff Members</h3>
      </div>
      <!-- /.box-header -->
      <div class="box-body table-responsive"> 
        <table id="example1" class="table table-bordered table-striped">
          <thead>
            <tr> 
              <th>ID</th>
              <th>Name</th>
              <th>Division</th>
              <th>Designation</th>
              <th>Address</th>
              <th>NIC No</th>
              <th>Service</th>
              <th>Contact No</th>
              <th>Email</th>
              <th>Image</th>
              <th class="only_eng">Edit</th>
              <th class="only_eng">Remove</th>
            </tr>
          </thead>
          <tbody>
            <?php 
              $sql="SELECT * FROM staff_members WHERE del=0 ORDER BY id DESC";
              $result=mysqli_query($conn, $sql);
              $x = 0;
              while ($row = mysqli_fetch_array($result)){ $x++;
            ?>
            <tr> 
              <td><?php echo $x; ?>.</td>
              <td><?php echo $row['status'].' '.$row['name']; ?></td>
              <td><?php echo $row['division']; ?></td>
              <td><?php echo $row['designation']; ?></td>
              <td><?php echo $row['address']; ?></td>
              <td><?php echo $row['nic_no']; ?></td>
              <td><?php echo $row['service']; ?></td>
              <td><?php echo $row['contact_no']; ?></td>
              <td><?php echo $row['email']; ?></td>
              <td><?php if(!empty($row['prof_pic'])) { ?><img src="upload/staff_member/<?php echo $row['prof_pic']; ?>" width="100"><?php } ?></td>
              <td align="center" class="only_eng">
			  <button  class="btn btn-info btn-sm btn_up" data-toggle="modal" data-target="#edit_lng" value="<?php echo $row['id']; ?>"><span class="glyphicon glyphicon-pencil"></span> &nbsp;EDIT </button>
			  </td>
              <td align="center" class="only_eng"><button value="<?php echo $row['id']; ?>" class="btn btn-danger btn-sm btn_dell">
                <span class="glyphicon glyphicon-trash"></span> &nbsp;DELETE </button></td>
            </tr>
            <?php  } ?>
          </tbody>
        </table>
      </div>
      <!-- /.box-body -->
    </div>
    
  </section>
   
      </div>
	      <!-- /.End table -->
<!-- ************************************************* -->
      
           <!-- /.col -->
              </div><!-- /.row -->
            </div><!-- /.box-body -->
            
          

          <div class="row">
            
    
    
      </div>
      <!-- /.col (right) -->
         

      </div>
<footer class="main-footer"> 
<div class="pull-right hidden-xs">
          
        </div>  <strong>Copyright &copy; NWP Engineering Department</strong> All rights reserved.
      </footer>

      <!-- Control Sidebar -->
      <aside class="control-sidebar control-sidebar-dark">
        <!-- Create the tabs -->
        <ul class="nav nav-tabs nav-justified control-sidebar-tabs">
          <li><a href="#control-sidebar-home-tab" data-toggle="tab"><i class="fa fa-home"></i></a></li>
          <li><a href="#control-sidebar-settings-tab" data-toggle="tab"><i class="fa fa-gears"></i></a></li>
        </ul>
        <!-- Tab panes -->
        <div class="tab-content">
          <!-- Home tab content -->
          <div class="tab-pane" id="control-sidebar-home-tab">
          </div><!-- /.tab-pane -->

          </div><!-- /.tab-pane -->
        </div>
      </aside><!-- /.control-sidebar -->
      <!-- Add the sidebar's background. This div must be placed
           immediately after the control sidebar -->
      <div class="control-sidebar-bg"></div>
    </div><!-- ./wrapper -->

<!-- Modal -->
  <div class="modal fade" id="edit_lng" role="dialog">
    <div class="modal-dialog">
    
      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title" id="test_id">Edit Staff Details</h4>
        </div>
        <div class="modal-body">

 		<div class="form-group">
		  <input name="st_up" id="mr_up" type="radio"  class="" value="Mr">
		  <label> &nbsp;&nbsp;Mr</label>&nbsp;&nbsp;&nbsp;&nbsp;
		  <input name="st_up" id="mrs_up" type="radio" class="" value="Mrs">
		  <label class="m-l-20"> &nbsp;&nbsp;Mrs</label>&nbsp;&nbsp;&nbsp;&nbsp;
		  <input name="st_up" id="miss_up" type="radio" class="" value="Miss">
		  <label class="m-l-20"> &nbsp;&nbsp;Miss</label>
		</div>		 

		 <div class="form-group"> 
			<label>Name:<font color="#FF0000"><strong>*</strong></font></label>
			<input type="text" class="form-control error" id="name_up" autocomplete="off">
		  </div>
		  
		  <div class="form-group"> 
			<label>Division:</label>
				<select class="form-control error" id="division_up" name="division_up" style="width: 100%;">
				  <option></option>
				  <?php
					$sql="SELECT * FROM division ORDER BY division ASC";
					$result=mysqli_query($conn, $sql);
					while ($row = mysqli_fetch_array($result)){ ?>
					<option value="<?php echo $row['division']; ?>"><?php echo $row['division']; ?></option>
				  <?php } ?>
				</select>		
		  </div>		  
		  
		  <div class="form-group"> 
			<label>Address:<font color="#FF0000"><strong>*</strong></font></label>
			<input type="text" class="form-control error" id="address_up" autocomplete="off">
		  </div>
		  
		  <div class="form-group"> 
			<label>Designation:</label>
				<select class="form-control error" id="des_up"  style="width: 100%;">
			  <option></option>
			  <?php
				$sql="SELECT * FROM designation ORDER BY name ASC";
				$result=mysqli_query($conn, $sql);
				while ($row = mysqli_fetch_array($result)){ ?>
				<option value="<?php echo $row['name']; ?>"><?php echo $row['name']; ?></option>
			  <?php } ?>
			</select>		
			
		  </div>
		  
		  <div class="form-group"> 
			<label>NIC Number:<font color="#FF0000"><strong>*</strong></font></label>
			<input type="text" class="form-control error" id="nic_up" autocomplete="off">
		  <span id="val_valid_nic_up" style="display:none" class="formError"><font color="#F44336">Please Enter Valid NIC Number</font></span>
		  </div>

      <div class="form-group"> 
        <label>Select Service:<font color="#FF0000"><strong>*</strong></font></label>
        <select class="form-control error" id="service_up" name="service_up" style="width: 100%;" required>
        <?php
          $sql="SELECT * FROM cader_details_tbl GROUP BY service ORDER BY id DESC";
          $result=mysqli_query($conn, $sql);

          while ($row = mysqli_fetch_array($result)){
        ?>

          <option value="<?php echo $row['service']; ?>"><?php echo $row['service']; ?></option>

        <?php } ?>
        </select>
      </div>
	  
	  	<div class="form-group">
              <label>Date of Birth:<font color="#FF0000"><strong>*</strong></font></label>            
            <div class="input-group"> 
              <div class="input-group-addon"> <i class="fa fa-calendar"></i> </div>
              <input type="text" class="form-control pull-right" id="dob_up" name="dob_up" autocomplete="off">
            </div>
        </div>	

		<div class="form-group">
		<label>Gender:<font color="#FF0000"><strong>*</strong></font></label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
		  <input name="gender_up" type="radio" id="male_up" class="" value="1">
		  <label for="male"> &nbsp;&nbsp;Male</label>&nbsp;&nbsp;&nbsp;&nbsp;
		  <input name="gender_up" type="radio" id="female_up" class="" value="2">
		  <label for="female" class="m-l-20"> &nbsp;&nbsp;Female</label>
		</div>		
	  
	  <div class="form-group"> 
        <label>Contact Number:<font color="#FF0000"><strong>*</strong></font></label>
        <input type="text" class="form-control" id="tel_office_up" autocomplete="off">
		<span id="valid_tel_office_up" style="display:none" class="formError"><font color="#F44336">Please Enter Valid Contact Number</font></span>
      </div>
	  
	  <div class="form-group"> 
        <label>Email Address:</label>
        <input type="text" class="form-control" id="email_up" autocomplete="off">
		<span id="val_valid_mail_up" style="display:none" class="formError"><font color="#F44336">Please Enter Valid Email Address</font></span>
      </div>
	  
		<div class="form-group"> 
            <label for="exampleInputFile">Select Profile Picture</label>
			<input type="file" class="form-control" id="img_upload_update" name="img_upload_update" accept="image/*">
        </div>		  

			<input type="hidden" id="con_reg_id" readonly>

			<span style="color: red;" class="pull-right">* Required Fields</span>
			<div class="form-group">
			  <button class="btn btn-danger" id="update_btn">UPDATE</button>
			</div>

        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>
      
    </div>
  </div>


    <!-- jQuery 2.1.4 -->
    <script src="plugins/jQuery/jQuery-2.1.4.min.js"></script>
    <!-- Bootstrap 3.3.5 -->
    <script src="bootstrap/js/bootstrap.min.js"></script>
    <!-- Select2 -->
    <script src="plugins/select2/select2.full.min.js"></script>
	<!-- DataTables -->
    <script src="plugins/datatables/jquery.dataTables.min.js"></script>
    <script src="plugins/datatables/dataTables.bootstrap.min.js"></script>
    <!-- InputMask -->
    <script src="plugins/input-mask/jquery.inputmask.js"></script>
    <script src="plugins/input-mask/jquery.inputmask.date.extensions.js"></script>
    <script src="plugins/input-mask/jquery.inputmask.extensions.js"></script>
    <!-- date-range-picker -->
    <script src="plugins/daterangepicker/moment.min.js"></script>
    <script src="plugins/daterangepicker/daterangepicker.js"></script>
    <!-- bootstrap color picker -->
    <script src="plugins/colorpicker/bootstrap-colorpicker.min.js"></script>
    <!-- bootstrap time picker -->
    <script src="plugins/timepicker/bootstrap-timepicker.min.js"></script>
    <!-- SlimScroll 1.3.0 -->
    <script src="plugins/slimScroll/jquery.slimscroll.min.js"></script>
    <!-- iCheck 1.0.1 -->
    <script src="plugins/iCheck/icheck.min.js"></script>
    <!-- FastClick -->
    <script src="plugins/fastclick/fastclick.min.js"></script>
    <!-- AdminLTE App -->
    <script src="dist/js/app.min.js"></script>
    <!-- AdminLTE for demo purposes -->
    <script src="dist/js/demo.js"></script>
    <script src="bootstrap-sweetalert/lib/sweet-alert.min.js"></script>
	
    <!-- Page script -->
    <script>
      $(function () {
        //Initialize Select2 Elements
        $(".select2").select2();

        //Datemask dd/mm/yyyy
        $("#datemask").inputmask("dd/mm/yyyy", {"placeholder": "yyyy-mm-dd"});
        //Datemask2 mm/dd/yyyy
        $("#datemask2").inputmask("mm/dd/yyyy", {"placeholder": "yyyy-mm-dd"});
        //Money Euro
        $("[data-mask]").inputmask();

        //Date range picker
        $('#reservation').daterangepicker();
        //Date range picker with time picker
		   $('#dob').daterangepicker({timePicker: false, timePickerIncrement: 30, format: 'YYYY-MM-DD'});
		   $('#dob_up').daterangepicker({timePicker: false, timePickerIncrement: 30, format: 'YYYY-MM-DD'});
        //Date range as a button
        $('#daterange-btn').daterangepicker(
            {
              ranges: {
                'Today': [moment(), moment()],
                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                'This Month': [moment().startOf('month')],
                'Last Month': [moment().subtract(1, 'month').startOf('month')]
              },
              startDate: moment().subtract(29, 'days'),
           
            },
        function (start) {
          $('#reportrange span').html(start.format('MMMM D, YYYY'));
        }
        );

        //iCheck for checkbox and radio inputs
        $('input[type="checkbox"].minimal, input[type="radio"].minimal').iCheck({
          checkboxClass: 'icheckbox_minimal-blue',
          radioClass: 'iradio_minimal-blue'
        });
        //Red color scheme for iCheck
        $('input[type="checkbox"].minimal-red, input[type="radio"].minimal-red').iCheck({
          checkboxClass: 'icheckbox_minimal-red',
          radioClass: 'iradio_minimal-red'
        });
        //Flat red color scheme for iCheck
        $('input[type="checkbox"].flat-red, input[type="radio"].flat-red').iCheck({
          checkboxClass: 'icheckbox_flat-green',
          radioClass: 'iradio_flat-green'
        });

        
      });
	  
      $(function () {
        $("#example1").DataTable();
        $('#example2').DataTable({
          "paging": true,
          "lengthChange": false,
          "searching": false,
          "ordering": true,
          "info": true,
          "autoWidth": false
        });
      });
	</script>

<script>
/****************************** Insert  *********************************************************/

function isValidEmailAddress(emailAddress) {
    var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
    return pattern.test(emailAddress);
}

function isValidTel(tel) {
    var pattern = /^\d{10}$/;
    return pattern.test(tel);
}

function isValidNIC(nic) {
    var pattern = /^\d{9}(V|X|v)$/;
    return pattern.test(nic);
}

$("#email").keyup(function () {
	email_validation();
});

$("#tel_office").keyup(function () {
	tel_office_validation();
});

var email_val = true;
function email_validation() {
	var len = $("#email").val().length;

	if (len !== 0) {
		if (!isValidEmailAddress($("#email").val())) {
			$("#val_valid_mail").fadeIn();
			email_val = false;
		}
		else {
			$("#val_valid_mail").fadeOut();
			email_val = true;
		}
	}
}

var tel_office_val = true;
function tel_office_validation() {
	var len = $("#tel_office").val().length;

	if (len !== 0) {
		if (!isValidTel($("#tel_office").val())) {
			$("#valid_tel_office").fadeIn();
			tel_office_val = false;
		}
		else {
			$("#valid_tel_office").fadeOut();
			tel_office_val = true;
		}
	}
}

function isValidExt(img) {
  var file = img;
  var exts = ['png','jpg','jpeg'];
  
  // first check if file field has any value
  if (file) {
	// split file name at dot
	var get_ext = file.split('.');
	// reverse name to check extension
	get_ext = get_ext.reverse();
	// check file type is valid as given in 'exts' array
	if ( $.inArray ( get_ext[0].toLowerCase(), exts ) > -1 ){
	  return true;
	} else {
	  return false;
	}
  }
}

var img_ext_val = true;
function img_ext_validation() {
	var len = $("#img_upload").val().length;

	if (len !== 0) {
		if (!isValidExt($("#img_upload").val())) {
			$("#valid_img").fadeIn();
			img_ext_val = false;
		}
		else {
			$("#valid_img").fadeOut();
			img_ext_val = true;
		}
	} else {
		$("#valid_img").fadeOut();
		img_ext_val = false;
	}
}

var valid_nic = true;
function nic_validation() {
	var len = $("#nic").val().length;
	if (len !== 0) {
		if (!isValidNIC($("#nic").val())) {
			$("#val_valid_nic").fadeIn();
			valid_nic = false;
		}
		else {
			$("#val_valid_nic").fadeOut();
			valid_nic = true;
		}
	} else {
		$("#val_valid_nic").fadeOut();
		valid_nic = false;
	}
}

$("#btn_submit").click(function () {
	email_validation();
	tel_office_validation();
	img_ext_validation();
	//nic_validation();
	
	var name = $('#name').val();
	var address = $('#address').val();
	var dob = $('#dob').val();
	var nic = $('#nic').val();
	var designation = $('#designation').val();
	var tel = $('#tel_office').val();
	var email = $('#email').val();	
  var img = $('#img_upload').val();
	var service = $('#service').val();
	var division = $('#division').val();
	
	var gender = "";
	if ($("#male:checked").val() === "1") {
		gender = "1";
	
	} else if ($("#female:checked").val() === "2") {
		gender = "2";
	}
	
	
	var status = "";
	if ($("#mr:checked").val() === "Mr") {
		status = "Mr";
	
	} else if ($("#mrs:checked").val() === "Mrs") {
		status = "Mrs";
	
	} else if ($("#miss:checked").val() === "Miss") {
		status = "Miss";
	}
	
	if (name === '' || address === '' || tel === '' || nic === '' || dob === '') {
		swal("Warning!", "Please Enter Required Fields!", "warning");
	
	} else if (email_val && tel_office_val) {
		if(img === '') {
			$.post('function/staff_member_conn.php', {staff_reg:'data', name:name, address:address, dob:dob, nic:nic, designation:designation, tel:tel, email:email, gender:gender, service:service, status:status , division:division },
			function (data) {
				if (data.msgType === 1) {
					setTimeout(function () {
						swal({
						title: "",
						text: "Successfully Updated!",
						type: "success",
						confirmButtonText: "OK"
						},
						function (isConfirm) {
							if (isConfirm) {
								window.location.href = "add_staff_members.php";
							}
						});
					}, 100);
				
				} else if (data.msgType === 2){
					swal("MYSQL Error!", "Please Try Again!", "warning");
				
				} else if (data.msgType === 3){
					swal("", "NIC Number Already Exist!", "warning");
				}		

			}, "json");

		} else {
			if(img_ext_val) {			
		
				var img_upload = document.getElementById("img_upload").files[0].name;
				var form_data = new FormData();
				var ext = img_upload.split('.').pop().toLowerCase();

				var oFReader = new FileReader();
				oFReader.readAsDataURL(document.getElementById("img_upload").files[0]);
				var f = document.getElementById("img_upload").files[0];
				var fsize = f.size||f.fileSize;

				if(jQuery.inArray(ext, ['png','jpg','jpeg']) == -1) {
					swal("Invalid File Type!", "Please Try Again!", "warning")

				} else if(fsize > 1000000) { // 1MB
					swal("File Size is too big!", "Please Try Again!", "warning")
				
				} else {
					form_data.append("img_upload", document.getElementById('img_upload').files[0]);
					form_data.append("name", name);
					form_data.append("address", address);
					form_data.append("dob", dob);
					form_data.append("nic", nic);
					form_data.append("designation", designation);
					form_data.append("tel", tel);
					form_data.append("email", email);
          form_data.append("gender", gender);
					form_data.append("service", service);
					form_data.append("status", status);
					form_data.append("division", division);
					
					$.ajax({
						url:"function/staff_member_conn.php",
						method:"POST",
						data: form_data,
						contentType: false,
						cache: false,
						processData: false,

						success: function(data) {
						if (data.status==='1') {				
							setTimeout(function () {
								swal({
									title: "",
									text: "Successfully Uploaded!",
									type: "success",
									confirmButtonText: "OK"
								},
								function (isConfirm) {
									if (isConfirm) {
										window.location.href = "add_staff_members.php";
									}
									});
								}, 100);

							} else if (data.status==='2'){
								swal("Something Went Wrong", "File Name Already Exists!", "error");
							
							} else if (data.status==='3'){
								swal("Something Went Wrong", "Please Try Again!", "error"); //mysql error
							
							} else if (data.status==='4'){
								swal("Something Went Wrong", "Error While uploading file on the server!", "error");
							
							} else if (data.status==='5'){
								swal("Invalid File Format!", "File Format Must Be PNG, JPG, or JPEG", "error");
							
							} else if (data.status==='6'){
								swal("", "NIC Number Already Exist!", "warning");
							}
						}		
						
					});
				}
			}	
		}		
	}
});

/******************************************* Remove Contact **************************************/

$(".btn_dell").click(function(){
  var x = $(this).val();
  swal({
	title: "Are you sure?",
	text: "Your may not be able to recover!",
	type: "warning",
	showCancelButton: true,
	confirmButtonClass: "btn-danger",
	confirmButtonText: "Yes, delete it!",
	closeOnConfirm: false
  },
	function () {
	  del_func(x);
	}
  );
});

function del_func(reg_id){
	if(reg_id === '') {
		swal("Warning!", "Please Select Valid Contact!", "warning");
	
	} else {	
		
		$.post( "function/staff_member_conn.php", {remove_reg: "data", reg_id : reg_id}, function( data ) {	  
		    if (data.msgType === 1) {
			  swal({
				title: "Deleted!",
				text: "Successfully Deleted!",
				type: "success",
				confirmButtonText: "OK"
			  },
				  function (isConfirm) {
				if (isConfirm) {
					window.location.href = "add_staff_members.php";
				}
			  });
			
			} else if(data.msgType === 3) {
				swal("", "Data Already Exist!", "error");
			
			} else{
			  swal("Oops...", "Something went wrong!", "warning");
			}
		}, "json");
	}
}

/******************************************* Load Form Data **************************************/

$(".btn_up").click(function(){	
	load_form_data($(this).val());
	$("#con_reg_id").val($(this).val());
});

function load_form_data(reg_id){
	$.post( "function/staff_member_conn.php", { get_dataset: "data", reg_id : reg_id }, function( data ) {
		$.each(data, function (index, data) {
			$('#name_up').val(data.name);
			$('#address_up').val(data.address);
			$('#des_up').val(data.designation);
			$('#tel_office_up').val(data.contact_no);
      $('#nic_up').val(data.nic_no);
			$('#service_up').val(data.service);
			$('#email_up').val(data.email);
			$('#dob_up').val(data.dob);
			$('#division_up').val(data.division);
			
			if (data.gender === '1') {
			   $("#male_up").prop("checked", true);
			}
			  
			if (data.gender === '2') {
			   $("#female_up").prop("checked", true);
			}
			
			if (data.status === 'Mr') {
			   $("#mr_up").prop("checked", true);
			}
			  
			if (data.status === 'Mrs') {
			   $("#mrs_up").prop("checked", true);
			}
			
			if (data.status === 'Miss') {
			   $("#miss_up").prop("checked", true);
			}
			
		});

	}, "json");
}

/******************************************* Edit **************************************/

$("#email_up").keyup(function () {
	email_validation_up();
});

$("#tel_office_up").keyup(function () {
	tel_office_validation_up();
});

var email_val_up = true;
function email_validation_up() {
	var len = $("#email_up").val().length;

	if (len !== 0) {
		if (!isValidEmailAddress($("#email_up").val())) {
			$("#val_valid_mail_up").fadeIn();
			email_val_up = false;
		}
		else {
			$("#val_valid_mail_up").fadeOut();
			email_val_up = true;
		}
	}
}

var tel_office_val_up = true;
function tel_office_validation_up() {
	var len = $("#tel_office_up").val().length;

	if (len !== 0) {
		if (!isValidTel($("#tel_office_up").val())) {
			$("#valid_tel_office_up").fadeIn();
			tel_office_val_up = false;
		}
		else {
			$("#valid_tel_office_up").fadeOut();
			tel_office_val_up = true;
		}
	}
}

var valid_nic_up = true;
function nic_validation_up() {
	var len = $("#nic_up").val().length;
	if (len !== 0) {
		if (!isValidNIC($("#nic_up").val())) {
			$("#val_valid_nic_up").fadeIn();
			valid_nic_up = false;
		}
		else {
			$("#val_valid_nic_up").fadeOut();
			valid_nic_up = true;
		}
	} else {
		$("#val_valid_nic_up").fadeOut();
		valid_nic_up = false;
	}
}

$("#update_btn").click(function () {	
	email_validation_up();
	tel_office_validation_up();
	//nic_validation_up();
	
	var name = $('#name_up').val();
	var address = $('#address_up').val();
	var dob = $('#dob_up').val();
  var nic = $('#nic_up').val();
	var service = $('#service_up').val();
	var division = $('#division_up').val();
	var designation = $('#des_up').val();
	var tel = $('#tel_office_up').val();
	var email = $('#email_up').val();	
  var img = $('#img_upload_update').val();
	var img = $('#img_upload_update').val();
	
	var gender = "";
	if ($("#male_up:checked").val() === "1") {
		gender = "1";
	
	} else if ($("#female_up:checked").val() === "2") {
		gender = "2";
	}
	
	var status = "";
	if ($("#mr_up:checked").val() === "Mr") {
		status = "Mr";
	
	} else if ($("#mrs_up:checked").val() === "Mrs") {
		status = "Mrs";
	
	} else if ($("#miss_up:checked").val() === "Miss") {
		status = "Miss";
	}
	
	var reg_id = $('#con_reg_id').val();

	if (name === '' || address === '' || tel === '' || nic === '' || dob === '') {
		swal("Warning!", "Please Enter Required Fields!", "warning");
	
	} else if(reg_id === '') {
		swal("Warning!", "Please Select Valid Member!", "warning");
	
	} else if(email_val_up && tel_office_val_up){		
		if(img === '') {
			$.post('function/staff_member_conn.php', {update_dr_lang:'data', reg_id: reg_id, name:name, address:address, dob:dob, nic:nic, designation:designation, tel:tel, email:email, gender:gender, service:service, status:status, division:division},
			
			function (data) {
				if (data.msgType === 1) {
					setTimeout(function () {
						swal({
						title: "",
						text: "Successfully Updated!",
						type: "success",
						confirmButtonText: "OK"
						},
						function (isConfirm) {
							if (isConfirm) {
								window.location.href = "add_staff_members.php";
							}
						});
					}, 100);
				
				} else if (data.msgType === 2){
					swal("MYSQL Error!", "Please Try Again!", "warning");
				
				} else if (data.msgType === 3){
					swal("", "NIC Number Already Exist!", "warning");
				}		

			}, "json");

		} else {
			var form_data = new FormData();
			var img_upload = document.getElementById("img_upload_update").files[0].name;
			var ext = img_upload.split('.').pop().toLowerCase();
			
			var oFReader = new FileReader();
			oFReader.readAsDataURL(document.getElementById("img_upload_update").files[0]);
			var f = document.getElementById("img_upload_update").files[0];
			var fsize = f.size||f.fileSize;				

			if(jQuery.inArray(ext, ['png','jpg','jpeg']) == -1) {
				swal("Invalid File Type!", "Please Try Again!", "warning")
			
			} else if(fsize > 1000000) { // 1MB
				swal("File Size is too big!", "Please Try Again!", "warning")
			
			} else {
		
				form_data.append("img_upload_update", document.getElementById('img_upload_update').files[0]);
				form_data.append("reg_id", reg_id);

				form_data.append("name", name);
				form_data.append("address", address);
				form_data.append("dob", dob);
				form_data.append("nic", nic);
				form_data.append("designation", designation);
				form_data.append("tel", tel);
				form_data.append("email", email);
        form_data.append("gender", gender);       
				form_data.append("service", service);				
				form_data.append("status", status);				
				form_data.append("division", division);				
				
				$.ajax({
					url:"function/staff_member_conn.php",
					method:"POST",
					data: form_data,
					contentType: false,
					cache: false,
					processData: false,

					success: function(data) {
					if (data.status==='1') {				
						setTimeout(function () {
							swal({
								title: "",
								text: "Successfully Updated!",
								type: "success",
								confirmButtonText: "OK"
							},
							function (isConfirm) {
								if (isConfirm) {
									window.location.href = "add_staff_members.php";
								}
								});
							}, 100);

						} else if (data.status==='2'){
							swal("Something Went Wrong", "File Name Already Exists!", "error");
						
						} else if (data.status==='3'){
							swal("Something Went Wrong", "Please Try Again!", "error"); //mysql error
						
						} else if (data.status==='4'){
							swal("Something Went Wrong", "Error While uploading file on the server!", "error");
						
						} else if (data.status==='5'){
							swal("Invalid File Format!", "File Format Must Be PNG, JPG, or JPEG", "error");
						
						} else if (data.status==='7'){
							swal("", "NIC Number Already Exist!", "warning");
						}
					}					
				});
			}
		}
	}	
});


$('#division').change(function () {
  var id = $(this).val();
  $.post('function/staff_member_conn.php', {'get_div_address': 'data', div: id}, function (data) {
	  $('#address').val(data.address);
  });
});

$('#division_up').change(function () {
  var id = $(this).val();
  $.post('function/staff_member_conn.php', {'get_div_address': 'data', div: id}, function (data) {
	  $('#address_up').val(data.address);
  });
});	

</script>	
</body>
</html>
