function PreviewImage() {
	var oFReader = new FileReader();
	oFReader.readAsDataURL(document.getElementById("image").files[0]);

	oFReader.onload = function (oFREvent) {
		document.getElementById("uploadPreview").src = oFREvent.target.result;
	};
	$('#editPicForm').submit();
};


function loadData() {
	var oTable = $('#staff').DataTable( {
	"serverSide": true,
	  "ajax": {
		"url": "/company/staff/list",
		"type": "POST",
	  },
	"language": {
                "aria": {
                    "sortAscending": ": activate to sort column ascending",
                    "sortDescending": ": activate to sort column descending"
                },
                "emptyTable": "No data available in table",
                "info": "Showing _START_ to _END_ of _TOTAL_ entries",
                "infoEmpty": "No entries found",
                "infoFiltered": "(filtered1 from _MAX_ total entries)",
                "lengthMenu": "_MENU_ entries",
                "search": "Search:",
                "zeroRecords": "No matching records found"
            },
	buttons: [
		{ extend: 'print', className: 'btn dark btn-outline' },
		{ extend: 'excel', className: 'btn yellow btn-outline ' },
		{ extend: 'colvis', className: 'btn dark btn-outline', text: 'Columns'}
	],
	"lengthMenu": [ [10, 25, 50,100,99999999], [10, 25, 50,100, "All"] ],
	"order": [
		[ 0, 'asc' ]
	],
	
	});
	$('.search-input-text').on( 'keyup click change', function () {   // for text boxes
		var i =$(this).attr('data-column');  // getting column index
		var v =$(this).val();  // getting search input value
		oTable.columns(i).search(v).draw();
	} );
	$('.search-input-select').on( 'change', function () {   // for select box
		var i =$(this).attr('data-column');  
		var v =$(this).val();  
		oTable.columns(i).search(v).draw();
	} );
	$('.filter-cancel').on( 'click', function () {   // for select box
		$('.search-input-text').val('');
		$('.search-input-select').val('');
		$('.search-input-text').trigger('change');
		$('.search-input-select').trigger('change');
		
		oTable.draw();
	} );
	$("#staff_filter").css("display","none"); 
	$('#sample_3_tools > li > a.tool-action').on('click', function() {
		var action = $(this).attr('data-action');
		oTable.DataTable().button(action).trigger();
	});
	

}
$(document).ready(function() {
    loadData(1);
	$(document).on("click",".edit",function() {
			var id = $(this).data('id');
			var dataString = 'id='+id;
			$.ajax({
				type: "POST",
				url: "/company/staff/get-data",				
				cache: false,
				data: dataString,
				success: function(data) {
					$("#getCode").html(data);
					jQuery("#form_edit").modal('show');
					
					$(function(){
						$("#branch_edit").not("[style*='display:none']").select2({
							allowClear: true,
							placeholder: "Select your warehouse branch",
							width: null
						});
					});
				}
			});
		});
		$(document.body).on("change","#position",function(){
			var position = this.value;
			var helpbar = "";
			if (position = 1){
				helpbar = "**Admin can control everything in IZYIM";
			}else if(position = 2){
				helpbar = "**Admin Branch can control everything in their branch in IZYIM";
			}else{
				helpbar = "**Staff can create, edit and view purchase order and shipping order in their branch in IZYIM";
			}
			$("#helpbar").text(helpbar);
			$('#helpbar').css('display','');
		});

	$(document).on("click",".delete",function() {
		var id = $(this).data('id');
		alert(id);
		var dataString = 'id='+id;
		$.ajax({
			type: "POST",
			url: "/company/staff/delete",				
			cache: false,
			data: dataString,
			beforeSend: function(){ 
				$("#submitpin").hide();
				$("#waitingpin").show();
				$("#suksesupdate").hide();
				$("#gagalupdate").hide();
			},
			complete: function(e, xhr, settings){
				if(e.status === 200){
					$("#submitprofile").show();
					$("#waiting").hide();
					$("#suksesupdate").show();
					setTimeout(function(){
						location.reload();
					},2000);
					//$("#gagalupdate").hide();
				}else{
					$("#submitprofile").show();
					$("#waiting").hide();
					//$("#suksesupdate").show();
					$("#gagalupdate").show();
					setTimeout(function(){
						location.reload();
					},2000);
				}
			}
		});
	});

});
var Script = function () {
	
    $().ready(function() {
        
		 $.fn.select2.defaults.set("theme", "bootstrap");


        $("#user_id").select2({
            allowClear: true,
            placeholder: "Select your staff",
            width: null
        });
        $("#position").select2({
            allowClear: true,
            placeholder: "Select your staff access right",
            width: null
        });
         $("#branch").not("[style*='display:none']").select2({
            allowClear: true,
            placeholder: "Select your staff branch",
            width: null
        });

		        // @see https://select2.github.io/examples.html#data-ajax
        function formatRepo(repo) {
            if (repo.loading) return repo.text;

            var markup = "<div class='select2-result-repository clearfix'>" +
                "<div class='select2-result-repository__avatar'><img src='" + repo.owner.avatar_url + "' /></div>" +
                "<div class='select2-result-repository__meta'>" +
                "<div class='select2-result-repository__title'>" + repo.full_name + "</div>";

            if (repo.description) {
                markup += "<div class='select2-result-repository__description'>" + repo.description + "</div>";
            }

            markup += "<div class='select2-result-repository__statistics'>" +
                "<div class='select2-result-repository__forks'><span class='glyphicon glyphicon-flash'></span> " + repo.forks_count + " Forks</div>" +
                "<div class='select2-result-repository__stargazers'><span class='glyphicon glyphicon-star'></span> " + repo.stargazers_count + " Stars</div>" +
                "<div class='select2-result-repository__watchers'><span class='glyphicon glyphicon-eye-open'></span> " + repo.watchers_count + " Watchers</div>" +
                "</div>" +
                "</div></div>";

            return markup;
        }

        function formatRepoSelection(repo) {
            return repo.full_name || repo.text;
        }

        $("button[data-select2-open]").click(function() {
            $("#" + $(this).data("select2-open")).select2("open");
        });

        $(":checkbox").on("click", function() {
            $(this).parent().nextAll("select").prop("disabled", !this.checked);
        });

        // copy Bootstrap validation states to Select2 dropdown
        //
        // add .has-waring, .has-error, .has-succes to the Select2 dropdown
        // (was #select2-drop in Select2 v3.x, in Select2 v4 can be selected via
        // body > .select2-container) if _any_ of the opened Select2's parents
        // has one of these forementioned classes (YUCK! ;-))
        $(".select2, .select2-multiple, .select2-allow-clear, .js-data-example-ajax").on("select2:open", function() {
            if ($(this).parents("[class*='has-']").length) {
                var classNames = $(this).parents("[class*='has-']")[0].className.split(/\s+/);

                for (var i = 0; i < classNames.length; ++i) {
                    if (classNames[i].match("has-")) {
                        $("body > .select2-container").addClass(classNames[i]);
                    }
                }
            }
        });

        $(".js-btn-set-scaling-classes").on("click", function() {
            $("#select2-multiple-input-sm, #select2-single-input-sm").next(".select2-container--bootstrap").addClass("input-sm");
            $("#select2-multiple-input-lg, #select2-single-input-lg").next(".select2-container--bootstrap").addClass("input-lg");
            $(this).removeClass("btn-primary btn-outline").prop("disabled", true);
        });
    });
	
	 $().ready(function() {
        // validate the comment form when it is submitted
          $('#addstaff').validate({
			  submitHandler: function() { 
				var user_id       = $("#user_id").val();
				var position    = $("#position").val();
				var branch    = $("#branch").val();
				var dataString = 'user_id='+user_id+
								 '&position='+position+
								 '&branch='+branch;
			   
				 $.ajax({
					type: "POST",
					url: "/company/staff/add",
					data: dataString,
					cache: false,
					beforeSend: function(){ 
						$("#submitpin").hide();
						$("#waitingpin").show();
						$("#suksesupdate").hide();
						$("#gagalupdate").hide();
						jQuery("#form_add").modal('hide');
					},
					complete: function(e, xhr, settings){
						if(e.status === 200){
							$("#submitpin").show();
							$("#waitingpin").hide();
							$("#suksesupdate").show();							
							setTimeout(function(){
								location.reload();
							},2000);
							//$("#gagalupdate").hide();
						}else{
							$("#submitpin").show();
							$("#waitingpin").hide();
							//$("#suksesupdate").show();
							$("#gagalupdate").show();
							setTimeout(function(){
								location.reload();
							},2000);
						}
					}
					
				 });
			  }
			
			});
			
			$('#editstaff').validate({
			  submitHandler: function() { 
				var id_edit=$("#id_edit").val();
				var position_edit=$("#position_edit").val();
				var branch_edit=$("#branch_edit").val();
				var dataString = 'id='+id_edit+
								 '&position='+position_edit+
								 '&branch='+branch_edit;
			   
				 $.ajax({
					type: "POST",
					url: "/company/staff/edit",
					data: dataString,
					cache: false,
					beforeSend: function(){ 
						$("#submitpin").hide();
						$("#waitingpin").show();
						$("#suksesupdate").hide();
						$("#gagalupdate").hide();
					},
					complete: function(e, xhr, settings){
						if(e.status === 200){
							$("#submitpin").show();
							$("#waitingpin").hide();
							$("#suksesupdate").show();
							location.reload();
							//$("#gagalupdate").hide();
						}else{
							$("#submitpin").show();
							$("#waitingpin").hide();
							//$("#suksesupdate").show();
							$("#gagalupdate").show();
						}
					}
					
				  });
				}
			
			});
    });

	
    $().ready(function() {
        // validate the comment form when it is submitted
        $("#editForm").validate();
		if(window.location.search == '?success'){
			$("#suksesupdate").show();
		}else if(window.location.search == '?failed'){
			$("#gagalupdate").show();
		}
		setTimeout(
		  function() 
		  {
			$("#suksesupdate").hide();
			$("#gagalupdate").hide();
		  }, 2000);
    });
	

}();