<?php require '../controller/session.php'; ?>
<?php include 'controller/profileCode.php'; ?>
<?php require_once("inc/init.php"); ?>
<div class="row">
	<div class="col-xs-12 col-sm-7 col-md-7 col-lg-4">
		<h1 class="page-title txt-color-blueDark">
			<i class="fa fa-table fa-fw "></i> 
				View
			<span>> 
				Class
			</span>
		</h1>
	</div>

</div>

<!-- widget grid -->
<section id="widget-grid" class="">

	<!-- row -->
	<div class="row">
		<article class="col-xs-12 col-sm-12 col-md-12 col-lg-2"></article>
		<!-- NEW WIDGET START -->
		<article class="col-xs-12 col-sm-12 col-md-12 col-lg-8 hidden">

			<!-- Widget ID (each widget will need unique ID)-->
			<div class="jarviswidget jarviswidget-color-blueDark"  id="wid-id-3"  data-widget-editbutton="false" data-widget-deletebutton="false">
				<!-- widget options:
				usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false">

				data-widget-colorbutton="false"
				data-widget-editbutton="false"
				data-widget-togglebutton="false"
				data-widget-deletebutton="false"
				data-widget-fullscreenbutton="false"
				data-widget-custombutton="false"
				data-widget-collapsed="true"
				data-widget-sortable="false"

				-->
				<header>
					<span class="widget-icon"> <i class="fa fa-wrench"></i> </span>
					<h2>Assign Class(es) to Teachers</h2>

				</header>

				<!-- widget div-->
				<div>

					<!-- widget edit box -->
					<div class="jarviswidget-editbox">
						<!-- This area used as dropdown edit box -->

					</div>
					<!-- end widget edit box -->

					<!-- widget content -->
				<div class="widget-body">
						<div class="widget-body-toolbar">
							
							<div class="row">
								
								<div class="col-sm-6">
									<button id="enable" class="btn btn btn-default">
										enable / disable 
									</button>
								</div>
								<div class="col-sm-6 text-right">
									
									<div class="onoffswitch-container">
										<span class="onoffswitch-title">Auto Open Next</span> 
										<span class="onoffswitch">
											<input type="checkbox" class="onoffswitch-checkbox" id="autoopen">
											<label class="onoffswitch-label" for="autoopen"> 
												<span class="onoffswitch-inner" data-swchon-text="ON" data-swchoff-text="OFF"></span> 
												<span class="onoffswitch-switch"></span>
											</label> 
										</span> 
										
										
									</div>
									
								<!-- 	<div class="onoffswitch-container">
										<span class="onoffswitch-title">Open Inline</span> 
										<span class="onoffswitch">
											<input type="checkbox" class="onoffswitch-checkbox" id="inline">
											<label class="onoffswitch-label" for="inline"> 
												<span class="onoffswitch-inner" data-swchon-text="ON" data-swchoff-text="OFF"></span> 
												<span class="onoffswitch-switch"></span>
											</label> 
										</span>
									</div> -->	
									
								</div>
								
							</div>
								

						</div>

						<table id="user" class="table table-bordered table-striped" style="clear: both">
							<tbody>
								<tr>
									<td>STAFF ID</td>
									<td>STAFF NAME</td>
									<td>CLASS(ES)</td>
									<td>IS FORM MASTER @</td>
								</tr>
								<?php 
								if ($all_staff) {
									foreach ($all_staff as $staffs) {
										// $classes = $staffs['class'];
										// $classesArray = "";
										// $countClasses = 0;
										// $classesArray6 = "";
										// $classesRow = $classes;
										// if($classesRow  != "" )  {
										// $classesArray = explode(",",$classesRow);
										// $countClasses = count($classesArray);
										// $classesArray18 = array_slice($classesArray, 0,18);

										// }
										$staff_classes = $profile->get_classes($staffs['staff_id']);
										// print_r($staff_classes);
										$countClasses = "";
										$countClasses = count($staff_classes);
								?>

								
								<tr>
									<td><?php echo $staffs['staff_id']; ?></td>
									<td><?php echo $staffs['last_name'].' '.$staffs['first_name']; ?></td>
									<td>
									
											<a style="color:#FFD639" href="index.php#ajax/assign_class.php#" id="<?php echo $staffs['staff_id'] ?>" data-type="select2" data-pk="1"  data-original-title="Assign Class"><?php if ($countClasses!=0) {
												$i=0;
												if ($staff_classes) {

										foreach ($staff_classes as $key) {
											$i++;
											// $class_name = $profile->get_class($value);
											if ($i<$countClasses) {
												echo $key['class_id'].',';
											}else{
												echo $key['class_id'];
											}
											}
										}
									}
									?></a>
											</td>

									<td>
										<a style="color:#FFD639" href="index.php#ajax/assign_class.php#" id="<?php echo $staffs['staff_id'] ?>2" data-type="select2" data-pk="1" data-select-search="true" data-value="BS" title="<?php $class_name = $profile->get_class($staffs['is_form_master']); echo $class_name[0]['class_name']?>" data-original-title="Select Form"><?php echo $staffs['is_form_master'];?></a>
										<!-- <a href="index.php#ajax/assign_class.php#" id="is_form_master" data-type="text" data-pk="1" data-original-title="Assign Form"><?php //echo $staffs['is_form_master']; ?></a> -->
										
									</td>
								</tr>

								
								<?php
							
								}	
							}
								 ?>
					
							</tbody>
						</table>
						
						<input type="hidden" id="class_list" value="<?php 
						if($class_list){
							$no = count($class_list);
							$i=0;
							
							foreach($class_list as $class){
								$i++;
								if($i<$no){
									echo $class['class_id'].",";
								}else{
									echo $class['class_id'];
								}
							}
						}
						 ?>">
						

					</div>					</div>

					</div>
					<!-- end widget content -->

				</div>
				<!-- end widget div -->

			</div>
			<!-- end widget -->

			<!-- Widget ID (each widget will need unique ID)-->
			<div class="jarviswidget jarviswidget-color-darken" id="wid-id-2" data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-custombutton="false">
				<!-- widget options:
				usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false">

				data-widget-colorbutton="false"
				data-widget-editbutton="false"
				data-widget-togglebutton="false"
				data-widget-deletebutton="false"
				data-widget-fullscreenbutton="false"
				data-widget-custombutton="false"
				data-widget-collapsed="true"
				data-widget-sortable="false"

				-->
				<header>
					<span class="widget-icon"> <i class="fa fa-edit"></i> </span>
					<h2>Class-Subject Duallist Box </h2>
					
				</header>

				<!-- widget div-->
				<div>

					<!-- widget edit box -->
					<div class="jarviswidget-editbox">
						<!-- This area used as dropdown edit box -->

					</div>
					<!-- end widget edit box -->

					<!-- widget content -->
					<div class="widget-body">
						<div class="row">
							<div class="col-md-6">
								<select class="select2 class_select" id="prog">
							<option>-- Select Class --</option>
							<?php 
							if ($all_classes) {
								foreach($all_classes as $class){
									?>
									<option value="<?php echo $class['programme_id'].",".$class['class_id']; ?>"><?php echo $class['class_name']; ?></option>

									<?php
								}
							}
							 ?>
						</select>
							</div>
							<div class="col-md-6"></div>
						</div>
						<div class="class_assigner">
						<select class="load_sub" multiple="multiple" size="10" name="duallistbox_demo2" id="initializeDuallistbox">
							
							
						</select>
						<br/>
					    <input type="checkbox" name="checkbox" id="comfirm_courses">
					    Comfirm
														
						<button class="btn btn-success pull-right" disabled="" id="assign_subjects">Assign</button>
						<br/>
						</div>
					</div>
					<!-- end widget content -->

				</div>
				<!-- end widget div -->

			</div>
			<!-- end widget -->

		</article>
		<!-- WIDGET END -->
		<article class="col-xs-12 col-sm-12 col-md-12 col-lg-2"></article>
	</div>
				
	
	<!-- end row -->

	<!-- end row -->

</section>
<!-- end widget grid -->

<script type="text/javascript">
	/* DO NOT REMOVE : GLOBAL FUNCTIONS!
	 *
	 * pageSetUp(); WILL CALL THE FOLLOWING FUNCTIONS
	 *
	 * // activate tooltips
	 * $("[rel=tooltip]").tooltip();
	 *
	 * // activate popovers
	 * $("[rel=popover]").popover();
	 *
	 * // activate popovers with hover states
	 * $("[rel=popover-hover]").popover({ trigger: "hover" });
	 *
	 * // activate inline charts
	 * runAllCharts();
	 *
	 * // setup widgets
	 * setup_widgets_desktop();
	 *
	 * // run form elements
	 * runAllForms();
	 *
	 ********************************
	 *
	 * pageSetUp() is needed whenever you load a page.
	 * It initializes and checks for all basic elements of the page
	 * and makes rendering easier.
	 *
	 */

	pageSetUp();
	
	/*
	 * ALL PAGE RELATED SCRIPTS CAN GO BELOW HERE
	 * eg alert("my home function");
	 * 
	 * var pagefunction = function() {
	 *   ...
	 * }
	 * loadScript("js/plugin/_PLUGIN_NAME_.js", pagefunction);
	 * 
	 * TO LOAD A SCRIPT:
	 * var pagefunction = function (){ 
	 *  loadScript(".../plugin.js", run_after_loaded);	
	 * }
	 * 
	 * OR
	 * 
	 * loadScript(".../plugin.js", run_after_loaded);
	 */

	// PAGE RELATED SCRIPTS

	// pagefunction
	
	var pagefunction = function() {
		/*
		 * X-Ediable
		 */
	
		loadScript("js/plugin/x-editable/moment.min.js", loadMockJax);
	
		function loadMockJax() {
		    loadScript("js/plugin/x-editable/jquery.mockjax.min.js", loadXeditable);
		}
	
		function loadXeditable() {
		    loadScript("js/plugin/x-editable/x-editable.min.js", loadTypeHead);
		}
	
		function loadTypeHead() {
		    loadScript("js/plugin/typeahead/typeahead.min.js", loadTypeaheadjs);
		}
	
		function loadTypeaheadjs() {
		    loadScript("js/plugin/typeahead/typeaheadjs.min.js", runXEditDemo);
		}


			loadScript("js/plugin/bootstrap-duallistbox/jquery.bootstrap-duallistbox.min.js", initializeDuallistbox);
		
		function initializeDuallistbox(){
			var initializeDuallistbox = $('#initializeDuallistbox').bootstrapDualListbox({
	          nonSelectedListLabel: 'Non-selected',
	          selectedListLabel: 'Selected',
	          preserveSelectionOnMove: 'moved',
	          moveOnSelect: false
	        });
		}

		function runXEditDemo() {
	
		    /*
		     * X-EDITABLES
		     */
	
		    $('#inline').on('change', function (e) {
		        if ($(this).prop('checked')) {
		            window.location.href = '?mode=inline#ajax/plugins.html';
		        } else {
		            window.location.href = '?#ajax/plugins.html';
		        }
		    });
	
		    if (window.location.href.indexOf("?mode=inline") > -1) {
		        $('#inline').prop('checked', true);
		        $.fn.editable.defaults.mode = 'inline';
		    } else {
		        $('#inline').prop('checked', false);
		        $.fn.editable.defaults.mode = 'popup';
		    }
			
		    //defaults
		    $.fn.editable.defaults.url = '/post';
		    //$.fn.editable.defaults.mode = 'inline'; use this to edit inline
	
		    //enable / disable
		    $('#enable').click(function () {
		        $('#user .editable').editable('toggleDisabled');
		    });


	
	
		    //editables
		    var arr = $('#class_list').val();
		    var arr2 = [];
		    arr2 = arr.split(',');
		    // var cl = [];
		    // cl.push();
		    //cl = [cl];

		    
<?php if ($all_staff) {$countClasses=""; foreach ($all_staff as $staffs) {$classes = $staffs['class'];?>
<?php if ($countClasses!=0) {
$i=0;
foreach ($staff_classes as $key) {
?>$('#<?php echo $staffs['staff_id']; ?>').attr("title","<?php echo $key['class_id']; ?>");<?php
}
}
?>
		      $('#<?php echo $staffs['staff_id']; ?>').editable({
		        inputclass: 'input-large',
		        select2: {
		            tags:arr2,
		            tokenSeparators: [",", " "]
		        },
		          url: 'ajax/assign_class.php',
		        type: 'text',
		         success: function(response, newValue) {

        if(response.status == 'error') return response.msg; //msg will be shown in editable form
        var staff_id = "<?php echo $staffs['staff_id']; ?>";
        
               		var data = {
       			staff_id:staff_id,
       			assined_classes:newValue.toString()
       		};
       		$.post('ajax/assign_class.php',data,function(res){
       		
       			var trimstr = res.trim();
       			if (trimstr.charAt(0) == 0) {
       				$.smallBox({
					title : "Class(es) Assigned successfully",
					content : "<i class='fa fa-clock-o'></i> <i>just now...</i>",
					color : "#000000",
					iconSmall : "fa fa-check bounce animated",
					timeout : 4000
				});
       			}else if(trimstr.charAt(0) == 1){
	   				$.smallBox({
					title : "Action Failed!",
					content : "<i class='fa fa-clock-o'></i> <i>just now...</i>",
					color : "#C46A69",
					iconSmall : "fa fa-check bounce animated",
					timeout : 4000
				});
       			}else if(trimstr.charAt(0) == 9){
	   				$.smallBox({
					title : "No Changes Made!",
					content : "<i class='fa fa-clock-o'></i> <i>just now...</i>",
					color : "#275670",
					iconSmall : "fa fa-clock-o bounce animated",
					timeout : 4000
				});
       			}
       		});
    }
		    });

		        $('#is_form_master2').editable({
		        url: '/post',
		        type: 'text',
		        pk: 1,
		        name: 'username',
		        title: 'Enter Email',
		         success: function(response, newValue) {
        if(response.status == 'error') return response.msg; //msg will be shown in editable form
       		var data = {
       			email:newValue
       		};
       		$.post('ajax/profile.php',data,function(res){
       			
       		});
    }
		    });
		        var countries = [];
		   
		    $.each({<?php 
		       	foreach ($class_list as $key) {
		       		echo '"'.$key['class_id'].'":'.'"'.$key['class_id'].'",';
		       	}
		       	 ?> }, function (k, v) {
		        countries.push({
		            id: k,
		            text: v
		        });
		    });
		
		     $('#<?php echo $staffs['staff_id'] ?>2').editable({
		        source: countries,
		        select2: {
		            width: 200
		        }, 
		        url: 'ajax/assign_class.php',
		        type: 'text',
		         success: function(response, newValue) {

        if(response.status == 'error') return response.msg; //msg will be shown in editable form
        var staff_id = "<?php echo $staffs['staff_id']; ?>";
       		var data = {
       			staff_id:staff_id,
       			form_class:newValue.toString()
       		};
       		$.post('ajax/assign_class.php',data,function(res){
       			var trimstr = res.trim();
       			if (trimstr.charAt(0) == 0) {
       				$.smallBox({
					title : "Class(es) Assigned successfully",
					content : "<i class='fa fa-clock-o'></i> <i>just now...</i>",
					color : "#000000",
					iconSmall : "fa fa-check bounce animated",
					timeout : 4000
				});
       			}else{
	   				$.smallBox({
					title : "Action Failed!",
					content : "<i class='fa fa-clock-o'></i> <i>just now...</i>",
					color : "#C46A69",
					iconSmall : "fa fa-check bounce animated",
					timeout : 4000
				});
       			}
       		});
    }
		    });
		
<?php }}?>	


		    $('#user .editable').on('hidden', function (e, reason) {
		        if (reason === 'save' || reason === 'nochange') {
		            var $next = $(this).closest('tr').next().find('.editable');
		            if ($('#autoopen').is(':checked')) {
		                setTimeout(function () {
		                    $next.editable('show');
		                }, 300);
		            } else {
		                $next.focus();
		            }
		        }
		    });
	
		}


	};
	// end pagefunction
	
	// run pagefunction on load

	var pagedestroy = function(){
		
		/*
		Example below:

		$("#calednar").fullCalendar( 'destroy' );
		if (debugState){
			root.console.log("✔ Calendar destroyed");
		} 

		For common instances, such as Jarviswidgets, Google maps, and Datatables, are automatically destroyed through the app.js loadURL mechanic

		*/
		
		// destroy spinner
		$( ".spinner" ).spinner("destroy");
		
		// remove maxlength
		$('input[maxlength]').off();
		$('input[maxlength]').remove();
		
		// remove timepicker
		$('#timepicker').off();
		$('#timepicker').remove();
		
		// remove clockpicker
		$('#clockpicker').off();
		$('#clockpicker').remove();
		
		// destroy duellist
		$('#initializeDuallistbox').bootstrapDualListbox('destroy');
		
		// destroy built in datepicker
		$('.hasDatepicker').off();
		$('.hasDatepicker').remove();

		// destroy noui slider
		$('.noUiSlider').find('*').addBack().off();
		
		// destroy ion range slider 
		$('.irs').find('*').addBack().off();
		
		// destroy tagsinput
		$('.tagsinput').tagsinput('destroy');
		
		// destroy colorpicker
		$('#colorpicker-1').off();
		$('#colorpicker-1').remove();
	    $('#colorpicker-2').off();
	    $('#colorpicker-2').remove();
	    
	    //destroy xeditable
	    $('#username').editable("destroy");
	    $('#firstname').editable("destroy");
	    $('#sex').editable("destroy");
	    $('#group').editable("destroy");
	    $('#status').editable("destroy");
	    $('#vacation').editable("destroy");
	    $('#dob').editable("destroy");
	    $('#event').editable("destroy");
	    $('#comments').editable("destroy");
	    $('#state2').editable("destroy");
	    //$('#fruits').editable("destroy");
	    //$('#tags').editable("destroy");
	    //$('#country').editable("destroy");
	    //$('#address').editable("destroy");
	   
	    // destroy knob
		$('.knob').find('*').addBack().off();
		
		if (debugState){
			root.console.log("✔ Spiner destroyed");
			root.console.log("✔ Maxlength destroyed");
			root.console.log("✔ Duellist destroyed");
			root.console.log("✔ Timepicker destroyed");
			root.console.log("✔ Clockpicker destroyed");
			root.console.log("✔ Custom Datepicker destroyed");
			root.console.log("✔ NoUI Slider destroyed");
			root.console.log("✔ Ion Range Slider destroyed");
			root.console.log("✔ Tagsinput destroyed");
			root.console.log("✔ Colorpicker destroyed");
			root.console.log("✔ Xeditable  destroyed");
			root.console.log("✔ JSKnob  destroyed");
		} 
		
	}


	pagefunction();

	$(document).ready(function(){
		$("#pic").change(function() {
           
           
        $("#message").empty(); // To remove the previous error message
        var file = this.files[0];
        var imagefile = file.type;
        var match= ["image/jpeg","image/png","image/jpg"];
        if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2])))
        {
        
        $("#message").html("<p id='error'>Please Select A valid Image File</p>"+"Note"+"<span id='error_message'>Only jpeg, jpg and png Images type allowed</span>");
        return false;
        }
        else
        {
        var reader = new FileReader();
        reader.onload = imageIsLoaded;
        reader.readAsDataURL(this.files[0]);
        }
        });
        
           function imageIsLoaded(e) {
        $("#pic").css("color","green");
        $('#image_preview').css("display", "block");
       
        $("#image_preview").attr('src',e.target.result);
        myimage = e.target.result;
 var myFormData = new FormData();
myFormData.append('pic', $('#pic').prop('files')[0]);

$.ajax({
  url: 'ajax/profile.php?dp=',
  type: 'POST',
  processData: false, // important
  contentType: false, // important
  dataType : 'json',
  data: myFormData,
  beforeSend:function(res){
  	// console.log(e);
  },
  complete:function(res){
  	console.log(res);
  },
  success:function(res){
  	console.log(res);
  },
  error:function(res){
 console.log(res);
  }
});
       // $("#image_preview").attr('src',e.target.result);
       //  $("#image_preview").attr('src',e.target.result);
        };
        var prog_id = "";
        $(document).on('change','.class_select',function(){
        		// $('.class_assigner').removeClass('hidden');
        	prog_id = $('#prog').val();
        	prog_id = prog_id.split(",");
        	$.get('ajax/ajax_load/load_sub_ajax.php?prog_id='+prog_id[0]+'',function(res){
        		$('.load_sub').html(res);
        		$('.load_sub').bootstrapDualListbox('refresh', true);
        	});

        	
        });

        $('#comfirm_courses').click(function(){
        		
        		if($(this).prop('checked')){
        			$('#assign_subjects').removeAttr('disabled');
        			
        		}else{
        			$('#assign_subjects').attr('disabled','disabled');
        		}
        	});

        $('#assign_subjects').click(function(){
        	var subjects = $('.load_sub').val();
        	var class_id = prog_id[1];
        	var data = {
        		assign_sub_class:'',
        		class_id:class_id,
        		subjects:subjects
        	};
        	$.post('ajax/assign_class.php',data,function(res){
        		$('#assign_subjects').attr('disabled','disabled');
        		if (res.charAt(0) == 0) {
    		$.smallBox({
					title : "Subject(s) Assigned to Successfully",
					content : "<i class='fa fa-clock-o'></i> <i>just now...</i>",
					color : "#000000",
					iconSmall : "fa fa-check bounce animated",
					timeout : 4000
				});
    	}else if(res.charAt(0) == 1){
    		$.smallBox({
					title : "Subject(s) Not Assigned!",
					content : "<i class='fa fa-clock-o'></i> <i>just now...</i>",
					color : "#C46A69",
					iconSmall : "fa fa-check bounce animated",
					timeout : 4000
				});
    	}
        	});

        });

        // $('.class_select').change(function(){
        
        // });
	});

</script>

