<style type="text/css">
.serial_no_tbl td{
	padding:5px;
	
	
}
</style>



<?php 
$config = array('role' =>'form', 'class'=>'form-horizontal','id'=>'create_category_form', 'name'=>'create_category_form');
echo form_open_multipart(base_url("#"),$config);
?>
<?php //print_r($category_details) ?>
            <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            <h4 class="modal-title">Add Serial No.</h4>
            <label>
            Genarate Serial Number&nbsp;&nbsp;
            <input type="checkbox" id="auto_gen" name="auto_gen" value="">
            </label>
            
            </div>
            <div class="modal-body">
                <div id="error"></div>
            <div class="row form-group">
             <div class="col-md-12">
             
 <table width="100%" border="0" class="serial_no_tbl">
 <?php //echo 'qty:'.$qty ?>
 <?php for($i=1; $i<($qty+1); $i++){ ?>
  <tr>
    <td style=" width:30px">(<?php echo sprintf('%02d', $i); ?>). </td>
    <td><input type="text" class="form-control" value="" name="sn[]" id="sn_item_<?php echo $i;?>" onchange="check_serial_no_valid(this.value,'<?php echo $i;?>')"></td>
  </tr>
  <?php }
  //; check_emi_added(this.value,'<?php echo $i;
  
  ?>
</table>

                   
             
                   
            
            </div>
            </div>
            </div>

 <div class="modal-footer">
            <input type="" onclick="add_serial_no()" name="add_category" value="<?php echo $btnText; ?>" class="btn btn-primary">
            </div>
  </form>
  <input name="" type="hidden" id="fld_name" value="<?php echo $row;?>"/>
  


		<!-- start: JAVASCRIPTS REQUIRED FOR THIS PAGE ONLY VALIDATION-->
		<script src="<?php echo asset_url(); ?>js/form-validation-create_sn.js"></script>
		<!-- end: JAVASCRIPTS REQUIRED FOR THIS PAGE ONLY  VALIDATION-->
 
<script>
set_old_sn();
function set_old_sn(){
	var sn_fld_name='#sn_'+'<?php echo $row;?>';
	var old_sn_details=$(sn_fld_name).val()
	var result=old_sn_details.split(',');
	for(var k=0; k<result.length; k++){
	var fld_name='#sn_item_'+(k+1);
		$(fld_name).val(result[k])
	}
}

function exists_check(sn_array,key){
	//alt();
	var result=sn_array.split(',');
	for(var k=0; k<result.length; k++){
		//alert("k:"+k+ "res:"+result[k]);
		alert("key:"+key+ "res:"+result[k]);
		if(result[k]==key){
			alert('exists');
		}
	}
}
//alert(result[0]);
//alert(result[1]);
//alert(result[2]);

</script>
                       
		<script>
		
		$(function () {
		$('#sn_item_1').focus();
		});	
		
function check_serial_no_valid(sn,id){
	//alert(sn);
	
	/* validate sn */
			
			var poitems = JSON.parse(localStorage.getItem('poitems'));
			var sn_array = [];
			$.each(poitems, function() {
				 var item = this;
				//alert(1);
				
				var product_sn  = item.row.product_sn;
				 var item_name = item.row.product_name;
				
				//var product_sn  = sn;
				// var item_name = 'name';//item.row.product_name;
				
				
				//add serial to attay
				
				
				
				//check array existes serial value
				//var text = product_sn;
				
				
				
				
				sn_array.push(String(product_sn));
				
				
				
				//if allredy existes show msg with item name
				
			});
			
			
			sn=String(sn);
			alert(sn_array+" :sn:"+sn);
			
			var exists=$.inArray(sn, sn_array);
				//alert(exists);
				item_name="test name";
				if(exists!="-1"){
					alert("Serial Number "+sn+ " Allredy Exists in "+item_name);
					
					var fld='#sn_item_'+id;
		  			$(fld).val('');

				}else{
					alert("not exists:"+exists);
					//alert($.inArray(product_sn, sn_array));
					
				}
			
			
			/* end validate sn */
	
	
	
	if(sn){
	var url="<?php echo base_url();?>sales/purchase_check_serial_no_valid/"+sn;
		$.post(url)
	  .done(function( data ) {
		  var obj = jQuery.parseJSON(data);
		  if(!obj.status){
		  var fld='#sn_item_'+id;
		  $(fld).val('');
		  alert('Already Exists:'+sn);
		  }
	  });
	}
	
}		
		
		
$('input').on("keypress", function(e) {
	//alert($(this.val()));
            /* ENTER PRESSED*/
            if (e.keyCode == 13) {
                /* FOCUS ELEMENT */
                var inputs = $(this).parents("form").eq(0).find(":input");
                var idx = inputs.index(this);
				//alert($(this).id());
				
				var emi=$(this).val()
				//check sn exists
				var sn_array = new Array();
		var error=0;
		$('input[name^="sn"]').each(function() {
			//alert((this).val());
			var val=$(this).val();
			//alert('this val:'+val);
				if(val){
					if(sn_array.indexOf($(this).val())==-1){
					sn_array.push($(this).val()); 
					//var fld_nxt='#sn_item_'+(parseInt(fld_id)+1);
					
					//$(fld_nxt).focus();
					//error_emi_msg=error_emi_msg+ " , "+$(this).val();
				}else{
					//alert($(this).val() +" Already exists");
					displayNotice('Error',emi +" Already exists");
					
					//var fld='#sn_item_'+fld_id;
					$(this).val('');
					$(this).focus();
					error=1;
					//return false;
				}
				}
			});
				
				if(emi==''){
					error=1;
				}
				
				if(!error){
                if (idx == inputs.length - 1) {
                    inputs[0].select()
                } else {
                    inputs[idx + 1].focus(); //  handles submit buttons
                    inputs[idx + 1].select();					
                }
				}
				//end check sn exists
				
                return false;
            }
        });		

	
	
	function check_emi_added(emi,fld_id){
		//alert(emi);
		var sn_array = new Array();
		var error=0;
		$('input[name^="sn"]').each(function() {
			//alert((this).val());
			var val=$(this).val();
			//alert('this val:'+val);
				if(val){
					if(sn_array.indexOf($(this).val())==-1){
					sn_array.push($(this).val()); 
					var fld_nxt='#sn_item_'+(parseInt(fld_id)+1);
					//$(fld).val('');
					//alert(fld_nxt);
					$(fld_nxt).focus();
					//error_emi_msg=error_emi_msg+ " , "+$(this).val();
				}else{
					//alert($(this).val() +" Already exists");
					displayNotice('Error',$(this).val() +" Already exists");
					
					var fld='#sn_item_'+fld_id;
					$(fld).val('');
					$(fld).focus();
					error=1;
					return false;
				}
				}
		});
		
	}
		
		function add_serial_no(){
			
		//	alert(input[name^="sn"]);
			var sn_text='';
			var i=0;
			var sn_array = new Array();
			var error=0;
			$('input[name^="sn"]').each(function() {
				if($(this).val()){
				i++;
				if(i!=1){
					sn_text=sn_text+',';
				}
    			//alert($(this).val());
				//exists_check(sn_text,$(this).val())
				
				
				sn_text=sn_text+$(this).val();
				//alert(sn_array);
				//alert(sn_array.indexOf($(this).val()));
				var error_emi_msg='';
				if(sn_array.indexOf($(this).val())==-1){
					sn_array.push($(this).val()); 
					//error_emi_msg=error_emi_msg+ " , "+$(this).val();
				}else{
					alert($(this).val() +" Already exists");
					
					error=1;
				}
				
				//alert("val:"+$(this).val()+" array:"+sn_array);
				

				}
			});
			
			//var fruits = ["Banana", 1112, "Apple", "Mango"];
				//alert(sn_array.indexOf(111));

			
			//alert(sn_array);
			//$('#999999').val(111);
			//alert($('#sn_999999').val());
			
			//alert(error);
			if(error==0){
			var row=$('#fld_name').val();
			var sn_fld_name='#sn_'+row;
			
			//alert(sn_fld_name);
			$(sn_fld_name).val(sn_text)
			$('div#ajax-modal').modal('hide');
			
			
			
			
			//set to local storage
			var poitems = JSON.parse(localStorage.getItem('poitems'));
			
			//alert(poitems);
			item_id=row;
			//alert(sn_text);
			
    		//poitems[item_id].product_sn = sn_text;
			poitems[item_id].row.product_sn = sn_text;
    		localStorage.setItem('poitems', JSON.stringify(poitems));
			
			
			loadItems();
			var poitems = JSON.parse(localStorage.getItem('poitems'));
			console.log(poitems)
			
			
			}
			
		}
		
			jQuery(document).ready(function() {
				FormValidator.init();
			});


        function add_category(form) {

            var category_id = $("input#category_tbl_id").val();

            if (category_id!="") {

                $('body').modalmanager('loading');
                setTimeout(function () {
                    $.ajax({
                    url: "<?php echo base_url('product_category/update_category'); ?>", // Url to which the request is send
                    type: "POST",             // Type of request to be send, called as method
                    data: new FormData(form), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
                    contentType: false,       // The content type used when sending data to the server.
                    cache: false,             // To unable request pages to be cached
                    processData:false,        // To send DOMDocument or non processed data file it is set to false
                        success: function(data)   // A function to be called if request succeeds
                        {
                            var obj = jQuery.parseJSON(data);
                            if (obj.status==0) 
                                {
                                    $('div#error').html('<div class="alert alert-block alert-danger fade in"><button type="button" class="close" data-dismiss="alert">×</button><h4 class="alert-heading"><i class="fa fa-times-circle"></i> Error!</h4>'+obj.validation+'</div>');
                                    $('body').modalmanager('removeLoading');
                                } 
                                else
                                {
                                    $('body').modalmanager('removeLoading');
                                    $('div#ajax-modal').modal('hide');
                                    set_message('categories notice!','Category successfully updated');
                                    category_load();
                                };

                        }
                    });
                }, 1000);

            } else{
                    $('body').modalmanager('loading');
                    setTimeout(function () {
                        $.ajax({
                        url: "<?php echo base_url('product_category/category_save'); ?>", // Url to which the request is send
                        type: "POST",             // Type of request to be send, called as method
                        data: new FormData(form), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
                        contentType: false,       // The content type used when sending data to the server.
                        cache: false,             // To unable request pages to be cached
                        processData:false,        // To send DOMDocument or non processed data file it is set to false
                        success: function(data)   // A function to be called if request succeeds
                        {
                            var obj = jQuery.parseJSON(data);
                            if (obj.status==0) 
                                {
                                    $('#error').html('<div class="alert alert-block alert-danger fade in"><button type="button" class="close" data-dismiss="alert">×</button><h4 class="alert-heading"><i class="fa fa-times-circle"></i> Error!</h4>'+obj.validation+'</div>');
                                    $('body').modalmanager('removeLoading');
                                } 
                                else
                                {
                                    $('body').modalmanager('removeLoading');
                                    $('div#ajax-modal').modal('hide');
                                    set_message('categories notice!','Category successfully added');
                                    category_load();
                                };

                        }
                        });
                    }, 1000);
                };

        }
        
        		$('#auto_gen').on('change',function(){
if($(this).is(':checked')){
	var i='';
	var id='';
	for(i=1;i<(<?php echo $qty;?>+1);i++){
		var id='sn_item_'+i;
		//var mrandom
		//alert('<?php echo date("ymd His");?>');
		//
		var value='<?php echo $this->session->userdata('ss_warehouse_id');?>'+'<?php echo date("ymdHis")."";?>'+i+Math.floor((Math.random()*5) + 1);
	//	alert();
		$("#"+id).val(value);
		}
}
else if($(this).not(':checked',false)){
	var i='';
	var id='';
	for(i=1;i<(<?php echo $qty;?>+1);i++){
		var id='sn_item_'+i;
		$("#"+id).val('');
		}
}
});


		</script>          
