<?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">
    <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 Publications
          </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">Publications Details</h3>
    </div>

    <div class="box-body"> 

	  <div class="form-group"> 
        <label>Title:<font color="#FF0000"><strong>*</strong></font></label>
        <input type="text" class="form-control" id="title" name="title" placeholder="Enter Title..." autocomplete="off">
        <span id="title_val_msg" style="color: red; display: none">*Enter Title</span>
      </div>
	  
	  <div class="form-group"> 
        <label>Description:<font color="#FF0000"><strong>*</strong></font></label>
		<textarea class="form-control" id="des" name="des" rows="5" placeholder="Enter Description..." maxlength="250"></textarea>
        <span id="des_val_msg" style="color: red; display: none">*Enter Description</span>
      </div>
	  
	  	<div class="form-group">
              <label>Date:<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="date" name="date" value="<?php echo date('Y-m-d'); ?>" autocomplete="off">
            </div>
			<span id="date_val_msg" style="color: red; display: none">*Please Select Date</span>
        </div>
		
		<div class="form-group"> 
          <div class="form-group">
            <label for="exampleInputFile">Select PDF<font color="#FF0000"><strong>*</strong></font></label>
            <input type="file" class="form-control" id="upload_pdf" name="upload_pdf">
			<span id="pdf_val_msg" style="color: red; display: none">*Please Select PDF</span>
			<span id="valid_pdf" style="color: red; display: none">*Please Select Valid PDF</span>
          </div>
        </div>

      <!-- /.box-body -->
      <div class="box-footer"> 
        <button  id="btn_submit" name="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">Details Edit / Remove</h3>
      </div>
      <!-- /.box-header -->
      <div class="box-body"> 
        <table id="example1" class="table table-bordered table-striped">
          <thead>
            <tr> 
              <th>ID</th>
              <th>Date</th>
              <th>Title</th>
              <th>Description</th>
              <th>View</th>
              <th class="only_others">Add Details</th>
              <th>Edit</th>
              <th class="only_eng">Remove</th>
            </tr>
          </thead>
          <tbody>
            <?php 
              $sql="SELECT * FROM publications WHERE lang = 1 AND 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['date']; ?></td>
              <td><?php echo $row['title']; ?></td>
              <td><?php echo $row['description']; ?></td>
              <td align="center"><a href="upload/PDF/publications/<?php echo $row['pdf']; ?>" target="_new">VIEW</a></td>
			  
              <td align="center" class="only_others">
			  <?php $sql_l = mysqli_query($conn, "SELECT * FROM publications WHERE lang = '$log_lang' AND group_id=".$row['group_id']);
			  if(mysqli_num_rows($sql_l) == 0) { ?>
			  <button  class="btn btn-success btn-sm btn_select_lang" data-toggle="modal" data-target="#select_lng" value="<?php echo $row['group_id']; ?>"><span class="glyphicon glyphicon-plus"></span> &nbsp;ADD </button>
			  <?php } ?>
              </td>

              <td align="center">
			  <?php if(mysqli_num_rows($sql_l) == 1) { ?>
			  <button  class="btn btn-info btn-sm btn_up" data-toggle="modal" data-target="#edit_lng" value="<?php echo $row['group_id']; ?>"><span class="glyphicon glyphicon-pencil"></span> &nbsp;EDIT </button>
			  <?php } ?>
			  </td>

              <td align="center" class="only_eng"><button value="<?php echo $row['group_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="select_lng" role="dialog">
    <div class="modal-dialog">
    
      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal2">&times;</button>
          <h4 class="modal-title" id="test_id">Add Publications</h4>
        </div>
        <div class="modal-body">			
			<div class="form-group">
			  <label>Select Language:<font color="#FF0000"><strong>*</strong></font></label>&nbsp;&nbsp;&nbsp;&nbsp;
			  <input name="lang" type="radio" id="sinhala" class="minimal" value="2" <?php if($log_lang == 2) { echo 'checked'; } else { echo 'disabled'; } ?>>
			  <label>&nbsp;&nbsp;සිංහල</label>&nbsp;&nbsp;&nbsp;&nbsp;
			  <input name="lang" type="radio" id="tamil" class="minimal" value="3" <?php if($log_lang == 3) { echo 'checked'; } else { echo 'disabled'; } ?>>
			  <label class="m-l-20"> &nbsp;&nbsp;தமிழ்</label>
			</div>			

            <div class="form-group"> 
              <label>Title:<font color="#FF0000"><strong>*</strong></font></label>
              <input type="text" class="form-control" id="title_lang" placeholder="Enter Title..." autocomplete="off">
            </div>
			
			  <div class="form-group"> 
				<label>Description:<font color="#FF0000"><strong>*</strong></font></label>
				<textarea class="form-control" id="des_lang" rows="5" placeholder="Enter Description..."></textarea>
			  </div>
			  
			<input type="hidden" class="form-control" id="group_id" readonly>
            <span style="color: red;" class="pull-right">* Required Fields</span>
			
			<div class="form-group">
              <button id="submit_lng" class="btn btn-primary">SUBMIT</button>
            </div>
			
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>
      
    </div>
  </div>

<!-- 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 Publications</h4>
        </div>
        <div class="modal-body">

 		<div class="only_eng">
			<div class="form-group">
				<label>Date:<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="edt_date" autocomplete="off">
				</div>
			</div>
			
			<div class="form-group">
				<label for="exampleInputFile">Select PDF</label>
				<input type="file" class="form-control" id="pdf_update" name="pdf_update">
			</div>		
			
		  <hr>
		</div>
		 
		 <div>
			<div class="form-group"> 
			  <label>Title:<font color="#FF0000"><strong>*</strong></font></label>
			  <input type="text" class="form-control" id="title_update" autocomplete="off">
			</div>
			  <div class="form-group"> 
				<label>Description:<font color="#FF0000"><strong>*</strong></font></label>
				<textarea class="form-control" id="des_update" rows="5"></textarea>
			  </div>
		  </div>
			  
			<input type="hidden" id="group_id_up" readonly>
			<input type="hidden" id="log_lang" readonly value="<?php echo $log_lang; ?>">

			<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
		   $('#date').daterangepicker({timePicker: false, timePickerIncrement: 30, format: 'YYYY-MM-DD'});
		   $('#edt_date').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>
/***************************************  Form Validation**********************************/

var title_val = true;
function title_validate() {
	if ($('#title').val() === '') {
		title_val = false;
		$('#title_val_msg').fadeIn();
		display_error_msg();
	} else {
		title_val = true;
		clear_validation();
	}
}

var des_val = true;
function des_validate() {
	if ($('#des').val() === '') {
		des_val = false;
		$('#des_val_msg').fadeIn();
		display_error_msg();
	} else {
		des_val = true;
		clear_validation();
	}
}

var date_val = true;
function date_validate() {
	if ($('#date').val() === '') {
		date_val = false;
		$('#date_val_msg').fadeIn();
		display_error_msg();
	} else {
		date_val = true;
		clear_validation();
	}
}

var pdf_val = true;
var pdf_ext_val = true;

function pdf_validate() {
	if ($('#upload_pdf').val() === '') {
		pdf_val = false;
		$('#pdf_val_msg').fadeIn();
		display_error_msg();
	
	} else {
		pdf_val = true;
		clear_validation();
	}
}

function display_error_msg() {
	if ($('#title').val() === '') {
		$('#title_val_msg').fadeIn();
	}
	
	if ($('#date').val() === '') {
		$('#date_val_msg').fadeIn();
	}
	
	if ($('#des').val() === '') {
		$('#des_val_msg').fadeIn();
	}
	
	if ($('#upload_pdf').val() === '') {
		$('#pdf_val_msg').fadeIn();
	}
}

function clear_validation() {
	if ($('#title').val() != '') {
		$('#title_val_msg').fadeOut();
	}
	
	if ($('#date').val() != '') {
		$('#date_val_msg').fadeOut();
	}
	
	if ($('#des').val() != '') {
		$('#des_val_msg').fadeOut();
	}
	
	if ($('#upload_pdf').val() != '') {
		$('#pdf_val_msg').fadeOut();
	}
}

$('.form-control').focusin(function () {
	$('.formError').fadeOut();
});

function isValidExt(pdf) {
  var file = pdf;
  var exts = ['pdf'];
  
  // 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 pdf_ext_val = true;
function pdf_ext_validation() {
	var len = $("#upload_pdf").val().length;

	if (len !== 0) {
		if (!isValidExt($("#upload_pdf").val())) {
			$("#valid_pdf").fadeIn();
			pdf_ext_val = false;
		}
		else {
			$("#valid_pdf").fadeOut();
			pdf_ext_val = true;
		}
	} else {
		$("#valid_pdf").fadeOut();
		pdf_ext_val = false;
	}
}

/****************************** Insert Eng Language  *********************************************************/

$("#btn_submit").click(function () {
	title_validate();
	date_validate();
	des_validate();
	pdf_validate();
	pdf_ext_validation();
	
	if (date_val && title_val && des_val && pdf_val && pdf_ext_val) {
		var upload_pdf = document.getElementById("upload_pdf").files[0].name;
		var form_data = new FormData();
		var ext = upload_pdf.split('.').pop().toLowerCase();

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

		} else {
			form_data.append("upload_pdf", document.getElementById('upload_pdf').files[0]);
			form_data.append("title", document.getElementById('title').value);
			form_data.append("date", document.getElementById('date').value);
			form_data.append("des", document.getElementById('des').value);
			
			$.ajax({
				url:"function/publications_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_publications.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 PDF", "error");
					}	
				}		
				
			});
		}
	}
});

/***************************************  Insert Sinhala/Tamil Language **********************************/

$(".btn_select_lang").click(function(){
  $("#group_id").val($(this).val());
});

$("#submit_lng").click(function () {
	var title = $('#title_lang').val();
	var des = $('#des_lang').val();
	var group_id = $('#group_id').val();
	
	var lang = "";
	if ($("#sinhala:checked").val() === "2") {
		lang = "2";
	
	} else if ($("#tamil:checked").val() === "3") {
	   lang = "3";
	}
	
	if (title === '' || des === '' || group_id === '' || lang === '') {
		swal("Warning!", "Please Enter Required Fields!", "warning");
	
	} else {

		$.post('function/publications_conn.php', {add_pub_lang: 'data', title: title, group_id: group_id, des: des, lang:lang},
		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_publications.php";
					}
				});
			}, 100);
		
		} else if (data.msgType === 2){
			swal("MYSQL Error!", "Please Try Again!", "warning");
		
		} else if (data.msgType === 3){
			swal("", "Data Already Exist", "warning");
		}		

		}, "json");	
		
	}
});


/******************************************* Remove **************************************/

$(".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(gid){
	if(gid === '') {
		swal("Warning!", "Please Select Valid Group ID!", "warning");
	
	} else {	
		
		$.post( "function/publications_conn.php", {remove_pub: "data", gid : gid}, function( data ) {	  
		    if (data.msgType === 1) {
			  swal({
				title: "Deleted!",
				text: "Successfully Deleted!",
				type: "success",
				confirmButtonText: "OK"
				  },
				  function (isConfirm) {
				if (isConfirm) {
					window.location.href = "add_publications.php";
				}
			  });
			}else{
			  swal("Oops...", "Something went wrong!", "warning");
			}
		}, "json");
	}
}

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

$(".btn_up").click(function(){
	var lang = $("#log_lang").val();
	
	load_form_data($(this).val(), lang);
	$("#group_id_up").val($(this).val());
});

function load_form_data(gid, lang){
	$.post( "function/publications_conn.php", { get_dataset: "data", gid : gid, lang: lang}, function( data ) {
		$.each(data, function (index, data) {
			$("#edt_date").val(data.date);			
			$("#title_update").val(data.title);
			$("#des_update").val(data.description);
		});

	}, "json");
}

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

$("#update_btn").click(function () {
	
	var title = $('#title_update').val();
	var des = $('#des_update').val();
	var date = $('#edt_date').val();
	var pdf = $('#pdf_update').val();
	
	var lang = $('#log_lang').val();
	var group_id = $('#group_id_up').val();

	if (title === '' || des === '' || date === '') {
		swal("Warning!", "Please Enter Required Fields!", "warning");
	
	} else if(group_id === '' ||  lang === '') {
		swal("Warning!", "Please Enter Required Fields!", "warning");
	
	} else {		
			if(pdf === '') {
				$.post('function/publications_conn.php', {update_pub_lang:'data', group_id: group_id, lang: lang, des: des, title: title, date: date},
				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_publications.php";
								}
							});
						}, 100);
					
					} else if (data.msgType === 2){
						swal("MYSQL Error!", "Please Try Again!", "warning");
					}		

				}, "json");

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

				if(jQuery.inArray(ext, ['pdf']) == -1) {
					swal("Invalid File Type!", "Please Try Again!", "warning")
				} 
			
				form_data.append("pdf_update", document.getElementById('pdf_update').files[0]);
				form_data.append("group_id", group_id);
				form_data.append("des", des);
				form_data.append("title", title);
				form_data.append("date", date);
				
				$.ajax({
					url:"function/publications_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_publications.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 PDF", "error");
						}	
					}					
				});
			}
	}	
});

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