<?php $ci = get_instance();?>
<form onSubmit="return edit_validation(this);" action="<?php echo base_url($this->router->fetch_class()."/update")?>" method="POST" enctype="multipart/form-data"  style="padding-left: 5px; padding-right: 5px;">
	<!--  -->
	<?php if(isset($data)):?>
        <input type="hidden" name="CODE" value="<?php echo $data->CODE;?>">
	<?php endif;?>
	<!--  -->
	<div class = "row">
	    <div class="form-group col-md-3">
		    <div class="form-group">
		        <label><span style="color: red;">*</span> Item Code.</label>
		        <div class="has-feedback">
		                <input type="text" name="CODE" id="CODE" onInput="edit_check_unique();" maxlength="10" value="<?php if(isset($data)) echo $this->fm->str_esc($data->CODE, 2);?>" class="form-control" required='required' autocomplete="OFF" <?php if(isset($data)) echo "readonly";?>>
		            <span class="form-control-feedback" aria-hidden="true">
		                <i class="fa fa-check check_unique_feedback_ok" style="display: none;"></i>
		                <i class="fa fa-spinner fa-pulse check_unique_feedback_loading" style="display: none;"></i>
		            </span>
		        </div>
		    </div>
		</div>
		<div class="form-group col-md-3">
		    <div class="form-group ">
		        <label><span style="color: red;">*</span> Name</label>
		        <div class="has-feedback">
		            <input type="text" name="NAME" id="NAME" maxlength="50" value="<?php if(isset($data)) echo $this->fm->str_esc($data->NAME, 2);?>" class="form-control" required='required' autocomplete="OFF">
		        </div>
		    </div>
		</div>
		<div class="form-group col-md-3">
		    <div class="form-group ">
		        <label><span style="color: red;"></span> Description</label>
		            <input type="text" name="DESCRIPT" id="DESCRIPT" value="<?php if(isset($data)) echo $this->fm->str_esc($data->DESCRIPT, 2);?>" maxlength="100" class="form-control" autocomplete="OFF">
		    </div>
		</div>
		<div class="form-group col-md-3">
		    <div class="form-group ">
		        <label><span style="color: red;"></span> Category</label>
		            <select name="CATEGORY" id="CATEGORY" class="form-control select2">
	                    <option value="">--- Select a value ---</option>
	                    <?php foreach($all_category as $v):?>
	                        <option value="<?php echo $v->CODE;?>" <?php if(isset($data) && $data->CATEGORY == $v->CODE) echo "selected='selected'";?>>
	                        <?php echo "[".$v->CODE."] ".$v->DESCRIPT;?>
	                        </option>
	                    <?php endforeach;?>
	                </select>
		    </div>
		</div>
	</div>
	<div class = "row">
	    <div class="form-group col-md-3">
		    <div class="form-group">
		        <label><span style="color: red;"></span> Item Group</label>
		        <div class="has-feedback">
		            <select name="ITEM_GRP" id="ITEM_GRP" class="form-control select2">
	                    <option value="">--- Select a value ---</option>
	                    <?php foreach($all_item_grp as $v):?>
	                        <option value="<?php echo $v->CODE;?>" <?php if(isset($data) && $data->ITEM_GRP == $v->CODE) echo "selected='selected'";?>>
	                        <?php echo "[".$v->CODE."] ".$v->DESCRIPT;?>
	                        </option>
	                    <?php endforeach;?>
	                </select>
		        </div>
		    </div>
		</div>
		<div class="form-group col-md-3">
		    <div class="form-group ">
		        <label><span style="color: red;"></span> Purchase</label>
		        <div class="has-feedback">
		        	<div class='input-group'>
			        	<span class='input-group-addon'>$</span>
			            <input type="text" name="PUR_AMT" id="PUR_AMT" maxlength="10" value="<?php if(isset($data)) echo $this->fm->str_esc($data->PUR_AMT, 2);?>" class="form-control" autocomplete="OFF">
			        </div>
		        </div>
		    </div>
		</div>
		<div class="form-group col-md-3">
		    <div class="form-group ">
		        <label><span style="color: red;"></span> Sales</label>
		        <div class='input-group'>
			        	<span class='input-group-addon'>$</span>
		            <input type="text" name="SALES_AMT" id="SALES_AMT" value="<?php if(isset($data)) echo $this->fm->str_esc($data->SALES_AMT, 2);?>" maxlength="50" class="form-control" autocomplete="OFF">
		        </div>
		    </div>
		</div>
		<div class="form-group col-md-3">
		    <div class="form-group ">
		        <label><span style="color: red;"></span> Taxcode</label>
		            <select name="TAXCODE" id="TAXCODE" class="form-control select2">
	                    <option value="">--- Select a value ---</option>
	                    <?php foreach($all_taxcode as $v):?>
	                        <option value="<?php echo $v->CODE;?>" <?php if(isset($data) && $data->TAXCODE == $v->CODE) echo "selected='selected'";?>>
	                        <?php echo "[".$v->CODE."] ".$v->DESCRIPTION;?>
	                        </option>
	                    <?php endforeach;?>
	                </select>
		    </div>
		</div>
	</div>

     <div class="row">
		<div class="form-group col-md-12">
			<label><span style="color: red;"></span> Attachment</label>
			<input type="file" name="ATTACHMENT[]" multiple class="file-loading">
		</div>
	</div>

    <?php if((! isset($data) && $can_create) || (isset($data) && $can_edit)):?>
		<div class="form-group" style="margin-top: 30px;">
			<label></label>
			<button type="submit" id="edit_btn_submit" class="btn btn-primary btn-xs-block btn_submit">
				<i class="fa fa-save"></i>
				Save
			</button>
		</div>
	<?php endif;?>
</form>
<a href="javascript:" id="return-to-top"><i class="fa fa-arrow-up"></i></a>
<script>
	$(document).ready(function(){
        $("#edit_ajax_container .datepicker").datepicker({
            format: "yyyy-mm-dd",
            autoclose: true,
            todayHighlight: true,
        });
		$("#edit_ajax_container .select2").select2();

		<?php if(isset($data)):?>
			<?php if($can_delete):?>
				$(".btn_delete").show();
			<?php endif;?>

			<?php if($can_delete):?>
				$("#edit_div_action").show("fast");
			<?php endif;?>
			
            $("#delete_modal [name='CODE']").val("<?php echo $data->CODE;?>");
		<?php endif;?>

		<?php if(isset($data) && ! $can_edit):?>
			$("#edit_ajax_container input").prop("disabled", true);
			$("#edit_ajax_container select").prop("disabled", true);
		<?php endif;?>

		$("#edit_ajax_container [name='ATTACHMENT[]']").fileinput({
			showUpload: false,
			showClose: true,
			showCaption: true,
			showRemove: false,
			<?php if(isset($attach_array)):?>
				<?php foreach($attach_array as $v):?>
					showBrowse: <?php echo $v->IS_IMAGE? "false":"true";?>,
				<?php endforeach;?>
			<?php endif;?>
			initialPreviewAsData: true,
			overwriteInitial: false,
			uploadAsync: true,
			maxFileSize: 5000,
			resizeImage: true,
			maxImageWidth: 200,
		    maxImageHeight: 150,
		    resizePreference: 'height',
			maxFileCount: 1,
			allowedFileExtensions: ["png", "jpg", "jpeg"],
			otherActionButtons: "<button type='button' onClick='edit_file_download(this);' {dataKey} class='btn btn-xs btn-default' title='Download'><i class='fa fa-download'></i></button>",
			initialPreview: [
				<?php if(isset($attach_array)):?>
					<?php foreach($attach_array as $v):?>					
						"<?php echo $v->IS_IMAGE? base_url("api/get_attach/".$v->PKKEY):"<iframe style='height: 100%; width: 100%;' src='".base_url("api/get_attach/".$v->PKKEY)."'></iframe>";?>",
					<?php endforeach;?>
				<?php endif;?>
			],
			initialPreviewConfig: [
				<?php if(isset($attach_array)):?>
					<?php foreach($attach_array as $v):?>
						{
							caption: "<?php echo $v->FILENAME;?>",
							size: <?php echo (int)$v->CONTENT_SIZE;?>,
							key: <?php echo $v->PKKEY;?>,
							url: "<?php echo (isset($data) && ! $can_edit) ? "":base_url("api/delete_attach/".$v->PKKEY);?>",
							previewAsData: <?php echo $v->IS_IMAGE? "true":"false";?>,
						},
					<?php endforeach;?>
				<?php endif;?>
			],
			initialPreviewShowDelete: true,
			fileActionSettings: {
				showDrag: false,
				uploadIcon: "<i class='fa fa-upload fa-2x text-primary visible-xs'></i><i class='fa fa-upload fa-lg text-primary hidden-xs'></i>",
				zoomIcon: "<i class='fa fa-search-plus fa-2x visible-xs'></i><i class='fa fa-search-plus fa-lg hidden-xs'></i>",
				removeIcon: "<i class='fa fa-trash fa-2x text-danger visible-xs'></i><i class='fa fa-trash fa-lg text-danger hidden-xs'></i>",
			},
		});


	});

	function edit_file_download(btn){
		var key = $(btn).attr("data-key");
		if(key != null){
			window.open("<?php echo base_url("api/get_attach");?>/" + key + "?download=1", "_blank");
		}
		else{
			prompt_error("Please upload this attachment before downloading it!");
		}
	}

	function sub_add_row(){
		var content = "";
		content += "<tr class='tr_sub'>";
		content += 	"<td>";
		content += 		"<button type='button' onClick='sub_delete_row(this);' class='btn btn-danger'>";
		content += 			"<i class='fa fa-ban'></i>";
		content += 		"</button>";
		content += 	"</td>";
		content += "</tr>";
		
		$("#tr_sub_add_row").after(content);

		$(".tr_sub:first .datepicker").datepicker({
			format: "yyyy-mm-dd",
			autoclose: true,
			todayHighlight: true,
		});
	}

	function edit_check_unique(){
        var selector = "#edit_ajax_container [name='CODE']"; 
		$(selector).closest("div").removeClass("has-success");
		$(selector).closest("div").removeClass("has-error");
		$(selector).closest("div").find(".check_unique_feedback_ok").hide("fast");
		$(selector).closest("div").find(".check_unique_feedback_loading").show("fast");
		disable_btn("#edit_btn_submit");

		var unique = $(selector).val();
		checking_unique = unique;

		var params = "";
		params += "&unique=" + unique;
		<?php if(isset($data)):?>
            params += "&pk=" + $("#edit_ajax_container [name='CODE']").val();
		<?php endif;?>

		if(unique != "" && unique != 0){

			clearTimeout(timer_check_unique);
			timer_check_unique = setTimeout(function(){
				$.ajax({
					type: "POST",
					url: "<?php echo base_url($this->router->fetch_class());?>/check_unique",
					data: params,
					success: function(result, status, xhr){
						if(checking_unique == unique){
							if(result == "1"){
								$(selector).closest("div").addClass("has-success");
								$(selector).closest("div").find(".check_unique_feedback_ok").show("fast");
								enable_btn("#edit_btn_submit");
							}
							else{
								$(selector).closest("div").addClass("has-error");
							}
						}
					},
					error: function(xhr,status,error){
						if(checking_unique == unique){
						}
					},
					complete: function(xhr,status){
						if(checking_unique == unique){
							$(selector).closest("div").find(".check_unique_feedback_loading").hide("fast");
						}
					},
				});
			}, 500);

		}else if(unique == "" || unique == "0"){
			$(selector).closest("div").addClass("has-success");
			$(selector).closest("div").find(".check_unique_feedback_ok").show("fast");
			$(selector).closest("div").find(".check_unique_feedback_loading").hide("fast");
			enable_btn("#edit_btn_submit");
		}
	}

	shortcut.add("Ctrl+Alt",function() {
    document.getElementById("edit_btn_submit").click();
    //alert("Saving...");
    },{
      'type':'keydown',
      'propagate':true,
      'target':document
    });
	
	function edit_validation(form){
		var error = "";
		
		$(form).find("[required]:not(:disabled)").each(function(){
			if($(this).val() == ""){
				if(error != "") error += "<br>";
				switch($(this).attr("name")){
					case "USERNAME":
						error += "Please fill in the Username!";
						break;
					case "NAME":
						error += "Please fill in the Name!";
						break;
					case "GROUP_ID":
						error += "Please select a Group!";
						break;
					default:
						error += "Please complete the Form!";
						break;
				}
				
				return false;
			}
		});

		if(error == ""){
			disable_btn(".btn_submit");
		}
		else{
			prompt_error(error);
			return false;
		}
	}

	$(window).scroll(function() {
    if ($(this).scrollTop() >= 50) {        // If page is scrolled more than 50px
        $('#return-to-top').fadeIn(200);    // Fade in the arrow
    } else {
        $('#return-to-top').fadeOut(200);   // Else fade out the arrow
    }
    });
    $('#return-to-top').click(function() {      // When arrow is clicked
        $('body,html').animate({
            scrollTop : 0                       // Scroll to top of body
        }, 500);
    });
</script>
