var manageProductTable;


$(document).ready(function(){
	
	
	
	// top nav bar 
	//$('#navProduct').addClass('active');
	// manage product data table
	//manageProductTable = $('#manageProductTable').DataTable({
		//'ajax': 'php_action/fetchStaff.php',
		//'order': []
	//});
	
	// order date picker
	//$("#BirthDate").datepicker();
	// order date picker
	//$("#EmploymentDate").datepicker();
	

	// add product modal btn clicked
	$("#addProductModalBtn").unbind('click').bind('click', function() {
		// // product form reset
		$("#submitProductForm")[0].reset();		

		// remove text-error 
		$(".text-danger").remove();
		// remove from-group error
		$(".form-group").removeClass('has-error').removeClass('has-success');

		$("#staffPhoto").fileinput({
	      overwriteInitial: true,
		    maxFileSize: 2500,
		    showClose: false,
		    showCaption: false,
		    browseLabel: '',
		    removeLabel: '',
		    browseIcon: '<i class="glyphicon glyphicon-folder-open"></i>',
		    removeIcon: '<i class="glyphicon glyphicon-remove"></i>',
		    removeTitle: 'Cancel or reset changes',
		    elErrorContainer: '#kv-avatar-errors-1',
		    msgErrorClass: 'alert alert-block alert-danger',
		    defaultPreviewContent: '<img src="assests/images/photo_default.png" alt="Profile Image" style="width:100%;">',
		    layoutTemplates: {main2: '{preview} {remove} {browse}'},								    
	  		allowedFileExtensions: ["jpg", "png", "gif", "JPG", "PNG", "GIF"]
			});   

		// submit product form
		$("#submitProductForm").unbind('submit').bind('submit', function() {
			
		

			// form validation
			var message = $("#message").val();
			var role = $("#role_id").val();
			
	
			
			if(message == "") {
				$("#message").after('<p class="text-danger">Message is required<</p>');
				$('#message').closest('.form-group').addClass('has-error');
			}	else {
				// remov error text field
				$("#message").find('.text-danger').remove();
				// success out for form 
				$("#message").closest('.form-group').addClass('has-success');	  	
			}	// /else


			if(role == "") {
				$("#role_id").after('<p class="text-danger">Are You sending Messsage to whom?<</p>');
				$('#role_id').closest('.form-group').addClass('has-error');
			}	else {
				// remov error text field
				$("#role_id").find('.text-danger').remove();
				// success out for form 
				$("#role_id").closest('.form-group').addClass('has-success');	  	
			}	// /else

			
			if(message&&role) {
				// submit loading button
				$("#createProductBtn").button('loading');

				var form = $(this);
				var formData = new FormData(this);

				$.ajax({
					url : form.attr('action'),
					type: form.attr('method'),
					data: formData,
					dataType: 'json',
					cache: false,
					contentType: false,
					processData: false,
					success:function(response) {

						if(response.success == true) {
							// submit loading button
							$("#createProductBtn").button('reset');
							
							$("#submitProductForm")[0].reset();

							$("html, body, div.modal, div.modal-content, div.modal-body").animate({scrollTop: '0'}, 100);
																	
							// shows a successful message after operation
							$('#add-product-messages').html('<div class="alert alert-success">'+
		            '<button type="button" class="close" data-dismiss="alert">&times;</button>'+
		            '<strong><i class="glyphicon glyphicon-ok-sign"></i></strong> '+ response.messages +
		          '</div>');

							// remove the mesages
		          $(".alert-success").delay(500).show(10, function() {
								$(this).delay(3000).hide(10, function() {
									$(this).remove();
								});
							}); // /.alert

		          // reload the manage student table
							manageProductTable.ajax.reload(null, true);

							// remove text-error 
							$(".text-danger").remove();
							// remove from-group error
							$(".form-group").removeClass('has-error').removeClass('has-success');

						} // /if response.success
						
					} // /success function
				}); // /ajax function
			}	 // /if validation is ok 					

			return false;
		}); // /submit product form

	}); // /add product modal btn clicked
	

	// remove product 	

}); // document.ready fucntion




function editProduct(productId = null) {

	if(productId) {
		$("#vehicleId").remove();		
		// remove text-error 
		$(".text-danger").remove();
		// remove from-group error
		$(".form-group").removeClass('has-error').removeClass('has-success');
		// modal spinner
		$('.div-loading').removeClass('div-hide');
		// modal div
		$('.div-result').addClass('div-hide');

		$.ajax({
			url: 'php_action/fetchSelectedStaff.php',
			type: 'post',
			data: {productId: productId},
			dataType: 'json',
			success:function(response) {		
			// alert(response.product_image);
				// modal spinner
				$('.div-loading').addClass('div-hide');
				// modal div
				$('.div-result').removeClass('div-hide');				

				$("#getProductImage").attr('src', 'stock/'+response.staff_image);

				$("#editProductImage").fileinput({		      
				});  

				// $("#editProductImage").fileinput({
		  //     overwriteInitial: true,
			 //    maxFileSize: 2500,
			 //    showClose: false,
			 //    showCaption: false,
			 //    browseLabel: '',
			 //    removeLabel: '',
			 //    browseIcon: '<i class="glyphicon glyphicon-folder-open"></i>',
			 //    removeIcon: '<i class="glyphicon glyphicon-remove"></i>',
			 //    removeTitle: 'Cancel or reset changes',
			 //    elErrorContainer: '#kv-avatar-errors-1',
			 //    msgErrorClass: 'alert alert-block alert-danger',
			 //    defaultPreviewContent: '<img src="stock/'+response.product_image+'" alt="Profile Image" style="width:100%;">',
			 //    layoutTemplates: {main2: '{preview} {remove} {browse}'},								    
		  // 		allowedFileExtensions: ["jpg", "png", "gif", "JPG", "PNG", "GIF"]
				// });  

				// product id 
				$(".editProductFooter").append('<input type="hidden" name="productId" id="productId" value="'+response.staff_id+'" />');				
				$(".editProductPhotoFooter").append('<input type="hidden" name="productId" id="productId" value="'+response.staff_id+'" />');				
				
				// product name
				$("#editFirstName").val(response.firstname);
				// quantity
				$("#editMiddleName").val(response.middlename);
				// rate
				$("#editLastName").val(response.lastname);
				// brand name
				$("#editGender").val(response.gender);
				// category name
				$("#editStaffId").val(response.staffId);
				
				$("#editEmail").val(response.email);
				
				$("#editPhone").val(response.phone_number);
				
				$("#editBirthDate").val(response.birth_date);
				
				$("#editEmplyDate").val(response.emply_date);
				
				$("#editMaritalStatus").val(response.MaritalStatus);
				$("#editPosition").val(response.level_id);

				// update the product data function
				$("#editProductForm").unbind('submit').bind('submit', function() {

					// form validation
					var FirstName = $("#editFirstName").val();
					var MiddleName = $("#editMiddleName").val();
					var LastName = $("#editLastName").val();
					var Gender = $("#editGender").val();
					var StaffId = $("#editStaffId").val();
					var Email = $("#editEmail").val();
					var Phone = $("#editPhone").val();
					var BirthDate = $("#editBirthDate").val();
					var EmplyDate = $("#editEmplyDate").val();
					var MaritalStatus = $("#editMaritalStatus").val();
					var Level = $("#editPosition").val();
								

					if(FirstName == "") {
						$("#editFirstName").after('<p class="text-danger">First Name is required</p>');
						$('#editFirstName').closest('.form-group').addClass('has-error');
					}	else {
						// remov error text field
						$("#editFirstName").find('.text-danger').remove();
						// success out for form 
						$("#editFirstName").closest('.form-group').addClass('has-success');	  	
					}	// /else

					if(MiddleName == "") {
						$("#editMiddleName").after('<p class="text-danger">Middle Name is required</p>');
						$('#editMiddleName').closest('.form-group').addClass('has-error');
					}	else {
						// remov error text field
						$("#editMiddleName").find('.text-danger').remove();
						// success out for form 
						$("#editMiddleName").closest('.form-group').addClass('has-success');	  	
					}	// /else
						
					
					if(LastName == "") {
						$("#editLastName").after('<p class="text-danger">Last Name is required</p>');
						$('#editLastName').closest('.form-group').addClass('has-error');
					}	else {
						// remov error text field
						$("#editLastName").find('.text-danger').remove();
						// success out for form 
						$("#editLastName").closest('.form-group').addClass('has-success');	  	
					}	// /else

					if(Gender == "") {
						$("#editGender").after('<p class="text-danger">Gender is required</p>');
						$('#editGender').closest('.form-group').addClass('has-error');
					}	else {
						// remov error text field
						$("#editGender").find('.text-danger').remove();
						// success out for form 
						$("#editGender").closest('.form-group').addClass('has-success');	  	
					}	// /else

					if(StaffId == "") {
						$("#editStaffId").after('<p class="text-danger">Staff Id is required</p>');
						$('#editStaffId').closest('.form-group').addClass('has-error');
					}	else {
						// remov error text field
						$("#editStaffId").find('.text-danger').remove();
						// success out for form 
						$("#editStaffId").closest('.form-group').addClass('has-success');	  	
					}	// /else
						
					
					if(Email == "") {
						$("#editEmail").after('<p class="text-danger">Email is required</p>');
						$('#editEmail').closest('.form-group').addClass('has-error');
					}	else {
						// remov error text field
						$("#editEmail").find('.text-danger').remove();
						// success out for form 
						$("#editEmail").closest('.form-group').addClass('has-success');	  	
					}	// /else
					
				    if(Phone == "") {
						$("#editPhone").after('<p class="text-danger">Phone Number is required</p>');
						$('#editPhone').closest('.form-group').addClass('has-error');
					}	else {
						// remov error text field
						$("#editPhone").find('.text-danger').remove();
						// success out for form 
						$("#editPhone").closest('.form-group').addClass('has-success');	  	
					}	// /else
						
					
					if(BirthDate == "") {
						$("#editBirthDate").after('<p class="text-danger">Birth Date is required</p>');
						$('#editBirthDate').closest('.form-group').addClass('has-error');
					}	else {
						// remov error text field
						$("#editBirthDate").find('.text-danger').remove();
						// success out for form 
						$("#editBirthDate").closest('.form-group').addClass('has-success');	  	
					}	// /else
						
					
					if(EmplyDate == "") {
						$("#editEmplyDate").after('<p class="text-danger">Employment Date is required</p>');
						$('#editEmplyDate').closest('.form-group').addClass('has-error');
					}	else {
						// remov error text field
						$("#editEmplyDate").find('.text-danger').remove();
						// success out for form 
						$("#editEmplyDate").closest('.form-group').addClass('has-success');	  	
					}	// /else
						
					
					if(MaritalStatus == "") {
						$("#editMaritalStatus").after('<p class="text-danger">Marital Status is required</p>');
						$('#editMaritalStatus').closest('.form-group').addClass('has-error');
					}	else {
						// remov error text field
						$("#editMaritalStatus").find('.text-danger').remove();
						// success out for form 
						$("#editMaritalStatus").closest('.form-group').addClass('has-success');	  	
					}	// /else
						
					if(Level == "") {
						$("#editPosition").after('<p class="text-danger">Position is required</p>');
						$('#editPosition').closest('.form-group').addClass('has-error');
					}	else {
						// remov error text field
						$("#editPosition").find('.text-danger').remove();
						// success out for form 
						$("#editPosition").closest('.form-group').addClass('has-success');	  	
					}	// /else


					if(FirstName && MiddleName && LastName && Gender && StaffId && Email && Phone && BirthDate && EmplyDate && MaritalStatus && Level) {
						// submit loading button
						$("#editProductBtn").button('loading');

						var form = $(this);
						var formData = new FormData(this);

						$.ajax({
							url : form.attr('action'),
							type: form.attr('method'),
							data: formData,
							dataType: 'json',
							cache: false,
							contentType: false,
							processData: false,
							success:function(response) {
								console.log(response);
								if(response.success == true) {
									// submit loading button
									$("#editProductBtn").button('reset');																		

									$("html, body, div.modal, div.modal-content, div.modal-body").animate({scrollTop: '0'}, 100);
																			
									// shows a successful message after operation
									$('#edit-product-messages').html('<div class="alert alert-success">'+
				            '<button type="button" class="close" data-dismiss="alert">&times;</button>'+
				            '<strong><i class="glyphicon glyphicon-ok-sign"></i></strong> '+ response.messages +
				          '</div>');

									// remove the mesages
				          $(".alert-success").delay(500).show(10, function() {
										$(this).delay(3000).hide(10, function() {
											$(this).remove();
										});
									}); // /.alert

				          // reload the manage student table
									manageProductTable.ajax.reload(null, true);

									// remove text-error 
									$(".text-danger").remove();
									// remove from-group error
									$(".form-group").removeClass('has-error').removeClass('has-success');

								} // /if response.success
								
							} // /success function
						}); // /ajax function
					}	 // /if validation is ok 					

					return false;
				}); // update the product data function

				// update the product image				
				$("#updateProductImageForm").unbind('submit').bind('submit', function() {					
					// form validation
					var productImage = $("#editProductImage").val();					
					
					if(productImage == "") {
						$("#editProductImage").closest('.center-block').after('<p class="text-danger">Product Image field is required</p>');
						$('#editProductImage').closest('.form-group').addClass('has-error');
					}	else {
						// remov error text field
						$("#editProductImage").find('.text-danger').remove();
						// success out for form 
						$("#editProductImage").closest('.form-group').addClass('has-success');	  	
					}	// /else

					if(productImage) {
						// submit loading button
						$("#editProductImageBtn").button('loading');

						var form = $(this);
						var formData = new FormData(this);

						$.ajax({
							url : form.attr('action'),
							type: form.attr('method'),
							data: formData,
							dataType: 'json',
							cache: false,
							contentType: false,
							processData: false,
							success:function(response) {
								
								if(response.success == true) {
									// submit loading button
									$("#editProductImageBtn").button('reset');																		

									$("html, body, div.modal, div.modal-content, div.modal-body").animate({scrollTop: '0'}, 100);
																			
									// shows a successful message after operation
									$('#edit-productPhoto-messages').html('<div class="alert alert-success">'+
				            '<button type="button" class="close" data-dismiss="alert">&times;</button>'+
				            '<strong><i class="glyphicon glyphicon-ok-sign"></i></strong> '+ response.messages +
				          '</div>');

									// remove the mesages
				          $(".alert-success").delay(500).show(10, function() {
										$(this).delay(3000).hide(10, function() {
											$(this).remove();
										});
									}); // /.alert

				          // reload the manage student table
									manageProductTable.ajax.reload(null, true);

									$(".fileinput-remove-button").click();

									$.ajax({
										url: 'php_action/fetchStaffImageUrl.php?i='+productId,
										type: 'post',
										success:function(response) {
										$("#getProductImage").attr('src', response);		
										}
									});																		

									// remove text-error 
									$(".text-danger").remove();
									// remove from-group error
									$(".form-group").removeClass('has-error').removeClass('has-success');

								} // /if response.success
								
							} // /success function
						}); // /ajax function
					}	 // /if validation is ok 					

					return false;
				}); // /update the product image

			} // /success function
		}); // /ajax to fetch product image

				
	} else {
		alert('error please refresh the page');
	}
} // /edit product function

// remove product 
function removeProduct(productId = null) {
	if(productId) {
		// remove product button clicked
		$("#removeProductBtn").unbind('click').bind('click', function() {
			// loading remove button
			$("#removeProductBtn").button('loading');
			$.ajax({
				url: 'php_action/removeVehicle.php',
				type: 'post',
				data: {productId: productId},
				dataType: 'json',
				success:function(response) {
					// loading remove button
					$("#removeProductBtn").button('reset');
					if(response.success == true) {
						// remove product modal
						$("#removeProductModal").modal('hide');

						// update the product table
						manageProductTable.ajax.reload(null, false);

						// remove success messages
						$(".remove-messages").html('<div class="alert alert-success">'+
		            '<button type="button" class="close" data-dismiss="alert">&times;</button>'+
		            '<strong><i class="glyphicon glyphicon-ok-sign"></i></strong> '+ response.messages +
		          '</div>');

						// remove the mesages
	          $(".alert-success").delay(500).show(10, function() {
							$(this).delay(3000).hide(10, function() {
								$(this).remove();
							});
						}); // /.alert
					} else {

						// remove success messages
						$(".removeProductMessages").html('<div class="alert alert-success">'+
		            '<button type="button" class="close" data-dismiss="alert">&times;</button>'+
		            '<strong><i class="glyphicon glyphicon-ok-sign"></i></strong> '+ response.messages +
		          '</div>');

						// remove the mesages
	          $(".alert-success").delay(500).show(10, function() {
							$(this).delay(3000).hide(10, function() {
								$(this).remove();
							});
						}); // /.alert

					} // /error
				} // /success function
			}); // /ajax fucntion to remove the product
			return false;
		}); // /remove product btn clicked
	} // /if productid
} // /remove product function

function clearForm(oForm) {
	// var frm_elements = oForm.elements;									
	// console.log(frm_elements);
	// 	for(i=0;i<frm_elements.length;i++) {
	// 		field_type = frm_elements[i].type.toLowerCase();									
	// 		switch (field_type) {
	// 	    case "text":
	// 	    case "password":
	// 	    case "textarea":
	// 	    case "hidden":
	// 	    case "select-one":	    
	// 	      frm_elements[i].value = "";
	// 	      break;
	// 	    case "radio":
	// 	    case "checkbox":	    
	// 	      if (frm_elements[i].checked)
	// 	      {
	// 	          frm_elements[i].checked = false;
	// 	      }
	// 	      break;
	// 	    case "file": 
	// 	    	if(frm_elements[i].options) {
	// 	    		frm_elements[i].options= false;
	// 	    	}
	// 	    default:
	// 	        break;
	//     } // /switch
	// 	} // for
}