<style>
	.editable td{
		text-align:center;
	}
</style>
<script>

$(document).ready(function(){
	//$('select').select2();
	jQuery('.datepicker2').datepicker({
			dateFormat : 'dd-mm-yy',
			changeMonth : true,
			changeYear : true
			});
	
	//Validate form data and update information of location transfer
	$('.submit').click(function(){
		if($("#loctransfer").validationEngine('validate')){
			var locID = $('#locID').val();
			var values = 	"ID="+$('#locID').val()
						+"&fromLocationID="+$(".fromLocationID").val()
						+"&toLocationID="+$(".toLocationID").val()
						+"&formNo="+$("#formNo").val()
						+"&movementTypeID="+$(".movementTypeID").val()
						+"&dateTransfer="+$("#dateTransfer").val()
						+"&memo="+$("#memo").val()
						+"&update=1";
			
			jQuery.ajax({
				url: "<?php echo base_url(); ?>locationtransfer/edit/",
				async: false,
				type: "POST",
				data: values,
				dataType: "html",
				success: function(data) {
					if(data == 'success'){
						window.location = "<?php echo base_url(); ?>/locationtransfer/";
					}
				}
			});
			
			return false;
		}else{
			return false;
		}
	});
	
	$('.quantity').live('change',function(){
		console.log($(this).val()+'<->'+$(this).parents('tr').find('.stock').val());
		if(parseInt($(this).val()) > parseInt($(this).parents('tr').find('.stock').val())){
			$(this).val($(this).parents('tr').find('.stock').val()).css('color','#f00');
		}
	});
	
	// function to add new item to the location transfer list
	$('#addRow').click(function(){
		if($("#loctransfer").validationEngine('validate')){
			$('.fromLocationID').attr('disabled','disabled');
			jQuery.ajax({
				url: "<?php echo base_url(); ?>locationtransfer/ajax_get_itembyLoc/",
				async: false,
				type: "POST",
				data: 'loc='+$('.fromLocationID').val(),
				dataType: "html",
				success: function(data) {
					if(data != ''){
						if (!$("#itemcode").length) {
							 $('<tr>'+
								'<td class="span2" style="display:none;"><input name="ID"  type="hidden" class="span12 itemID" value=""></td>'
								+'<td class="span2" ><input type="text" class="span12 itemCode" id="" name="itemcode" onkeyup="getitem(this);" onchange="getitem(this);" data-source="'+data+'" data-items="4" data-provide="typeahead"></td>'
								+'<td class="span2"><input id="" name="description"  type="text" class="description span12 validate[required,maxSize[64]]" placeholder="Item Description"></td>'
								+'<td class="span1"><input id="" name="stock" disabled="disabled" class="stock span12 validate[required,custom[number]]" type="text" placeholder="Stock" style="text-align:right"></td>'
								+'<td class="span1"><input id="" name="quantity" class="quantity span12 validate[required]" type="text" placeholder="Quantity" style="text-align:right"></td>'
								+'<td class="span1"align="center">'
									+'<button class="btn btn-mini btn-primary saveItm" type="button"><i class="icon-ok icon-white"></i></button><br />'
									+'<button id="btnCancel" class="btn btn-mini btn-warning" type="button"><i class="icon-remove-circle icon-white"></i></button>'
								+'</td>'
							+'</tr>'
							  ).insertBefore( "#trInfos" );
							  
						}else{
							msg (1,"alert","Please, do save the current details before addind new one");
						}
					}
				}
			});
		}else{
			msg (1,"alert","Please, do select location before addind new one");
			return false;
		}
	});
	
	
	//Item save for certain location transfer
	$('.saveItm').live('click',function(){
		var me = $(this).parents('tr');
		if($("#loctransfer").validationEngine('validate')){
			var locID = $('#locID').val();
			if( locID == ''){			
				var values = 	"ID="
								+"&fromLocationID="+$(".fromLocationID").val()
								+"&toLocationID="+$(".toLocationID").val()
								+"&formNo="+$("#formNo").val()
								+"&movementTypeID="+$(".movementTypeID").val()
								+"&dateTransfer="+$("#dateTransfer").val()
								+"&memo="+$("#memo").val()
								+"&itemID="+$(me).find('.itemID').val()
								+"&quantity="+$(me).find('.quantity').val()
								+"&stock="+$(me).find('.stock').val()
								+"&postloctrans=1";
			}else{
				var values = 	"ID="+$('#locID').val()
								+"&fromLocationID="+$(".fromLocationID").val()
								+"&toLocationID="+$(".toLocationID").val()
								+"&formNo="+$("#formNo").val()
								+"&movementTypeID="+$(".movementTypeID").val()
								+"&dateTransfer="+$("#dateTransfer").val()
								+"&memo="+$("#memo").val()
								+"&itemID="+$(me).find('.itemID').val()
								+"&quantity="+$(me).find('.quantity').val()
								+"&stock="+$(me).find('.stock').val()
								+"&postloctrans=1";
			}
			console.log(values);
			jQuery.ajax({
				url: "<?php echo base_url(); ?>locationtransfer/ajax_save_item/",
				async: false,
				type: "POST",
				data: values,
				dataType: "html",
				success: function(data) {
					var obj = jQuery.parseJSON(data);
					if(obj[0] != ''){
						$('#locID').val(obj[0]);
						$('<tr>'+
							'<td class="span2 itemID" style="display:none;">'+obj[1]+'</td>'
							+'<td class="span2 no-edit">'+$(me).find('.itemCode').val()+'</td>'
							+'<td class="span2 no-edit">'+$(me).find('.description').val()+'</td>'
							+'<td class="span1" style="text-align:right">'+$(me).find('.stock').val()+'</td>'
							+'<td class="span1" style="text-align:right">'+$(me).find('.quantity').val()+'</td>'
							+'<td class="span1 no-edit" align="center">'
								+'<button class="btn btn-mini btn-primary editItm" type="button"><i class="icon-pencil"></i></button><br />'
								+'<button class="btn btn-mini btn-danger deleteItm" type="button"><i class="icon-remove-circle icon-white"></i></button>'
							+'</td>'        
						+'</tr>'
						  ).insertBefore( "#trInfos" );
						$(me).remove();
						msg (1,"alert-info","Item added to the list successfully");
					}
				}
			});
		}
		return false;	
	});
	
	//Cancle entry
	$('#btnCancel').live('click',function(){
		var me = $(this).parents('tr');
		$(me).remove();
	});
	
	//Delete Item
	$('.deleteItm').live('click',function(){
		var me = $(this).parents('tr');
		
		$('#popupModal').modal('show');
		$("#_popupTitle").html("Confirm delete");
		$("#_popupContent").html("Your about to delete definively this row. <br/> Click on ok to confirm");
		
		$('#_popupFooter').empty();
		   $('#_popupFooter').append('<button class="btn btn-danger" id="detButton">Ok</button>' +
		'<button class="btn" id="canb">Cancel</button>');
		$("#_popupTitle").html("Confirm delete");
		$( "#canb" ).click(function() {
			$('#popupModal').modal('hide');
		});
		$( "#detButton" ).live('click',function() {
			$('#popupModal').modal('hide');
			var values = 	"ID="+$(me).find('.itemID').text()
							+"&delete=1";
			
			jQuery.ajax({
				url: "<?php echo base_url(); ?>locationtransfer/removeitem/",
				async: false,
				type: "POST",
				data: values,
				dataType: "html",
				success: function(data) {
					if(data == 'success'){
						msg (1,"alert-warning","Item deleted from the list successfully");
						$(me).remove();
					}
				}
			});
			console.log($(me).find('.itemID').text());
		});
	});
	/*Table editing start*/
	//$("table.editable td,
	$("table.editable td .editItm").live('click',function () {        
		var eContent = $(this).parents('tr').find('td:nth-child(5)').text();
		var eCell = $(this).parents('tr').find('td:nth-child(5)');
			
		console.log(eContent);
		
		if(eContent.indexOf('<') >= 0 || eCell.parents('table').hasClass('oc_disable')) return false;        
		
		if(eCell.hasClass('no-edit')){return false;}	
		eCell.addClass("editing");        
		eCell.html('<input type="text" style="text-align:right;" value="' + eContent + '"/>');
		
		var eInput = eCell.find("input");
		eInput.focus();
 
		eInput.keypress(function(e){
			if (e.which == 13) {
				var newContent = $(this).val();
				eCell.html(newContent).removeClass("editing");
				// Here your ajax actions after pressed Enter button
				var values = 	"ID="+eCell.parents('tr').find('td:nth-child(1)').text()
								+"&quantity="+eCell.parents('tr').find('td:nth-child(5)').text()
								+"&stock="+eCell.parents('tr').find('td:nth-child(4)').text();
				
				jQuery.ajax({
					url: "<?php echo base_url(); ?>locationtransfer/updaterow/",
					async: false,
					type: "POST",
					data: values,
					dataType: "html",
					success: function(data) {
						if(data == 'success'){
							msg (1,"alert-info",eCell.parents('tr').find('td:nth-child(3)').text()+" updated successfully");
						}
					}
				});
			}
		});
		
		eInput.focusout(function(){
			var newContent = $(this).val();
			eCell.text($(this).val()).removeClass("editing");            
			// Here your ajax action after focus out from input
			var values = 	"ID="+eCell.parents('tr').find('td:nth-child(1)').text()
								+"&quantity="+eCell.parents('tr').find('td:nth-child(5)').text()
								+"&stock="+eCell.parents('tr').find('td:nth-child(4)').text();
				
			jQuery.ajax({
				url: "<?php echo base_url(); ?>locationtransfer/updaterow/",
				async: false,
				type: "POST",
				data: values,
				dataType: "html",
				success: function(data) {
					if(data == 'success'){
						msg (1,"alert-info",eCell.parents('tr').find('td:nth-child(3)').text()+" updated successfully");
					}
				}
			});
		});
	});
	
	/*Table editing end*/
});
//Alert messages
function msg(n,type, message){
	$("#msg_div"+n +" p").html(message);
	$("#msg_div"+n).attr("class","alert " + type);
}

//Ajax item list gathering 
function getitem(me){
	var str = $(me).val();
	if(str.match(/-/g)){
		// Ajax call to get item details
		jQuery.ajax({
			url: "<?php echo base_url(); ?>locationtransfer/ajax_get_items/",
			async: false,
			type: "POST",
			data: "itemCode="+$(me).val()+"&locID="+$('.fromLocationID').val(),
			dataType: "html",
			success: function(data) {
				var obj = jQuery.parseJSON(data);
				//jQuery('.itemTbl .noItem,.itemTbl .itemList').remove();
				if(obj[0].ID){
					$(me).parents('tr').find('.itemID').val(obj[0].ID);
					$(me).parents('tr').find('.itemCode').val(obj[0].itemCode);
					$(me).parents('tr').find('.description').val(obj[0].description);
					$(me).parents('tr').find('.stock').val(obj[0].stock);
					msg (1,"alert","Please, do save the current details before addind new one");
				}
			}
		});
	}
}
</script>
<div id="content">                        
<div class="wrap">
<div class="head">
	<div class="info">
        <h1><?php echo element('compName', $this->session->userdata('logged_in')) ?> [ 
            <?php echo element('compNo', $this->session->userdata('logged_in')) ?> ]</h1>
        <ul class="breadcrumb">
            <li><a href='<?php echo base_url(); ?>'><?php echo $this->lang->line('dashboard') ?></a> <span class="divider">-</span></li>
            <li><a href="<?php echo base_url(); ?>locationtransfer"><?php echo $this->lang->line('module') ?></a> <span class="divider">-</span></li>
            <li class="active"><?php echo $this->lang->line('editTitle') ?></li>
        </ul>
	</div>
	<div class="search">
		<form action="<?php echo base_url() ?>admin/search" method="post">
			<input name="search_text" type="text" placeholder="search..."/>                                
            <button type="submit"><span class="i-magnifier"></span></button>
		</form>
	</div>                        
</div><!-- head --> 
<div class="content">
	<div class="wrap">
	<?php 
		echo form_open('locationtransfer/add',array("id"=>"loctransfer"));
	?>        
    	<input type="hidden" id="locID" name="locID" value="<?php echo $datatbls['transInfo'][0]->ID; ?>" />
        	
        <div class="content">      
            <div class="row-fluid">
                <div class="alert alert-info">
                    <strong><?php echo $this->lang->line('loctransform') ?></strong>
                </div>
            </div> 
            <!--Location transfer top form-->  
            <div class="row-fluid scRow">
                <div class="span6 scCol">        	
                    <div class="block" id="grid_block_1">
                        <div class="content">                 	
                            <div class="controls-row">
                                <div class="span4"><?php echo $this->lang->line('fromLocation') ?>*</div>
                                <div class="span8">
                                    <?php
                                        $preselcat = $datatbls['transInfo'][0]->fromLocationID;
                                        $options[''] = 'Please Select';
										foreach($fromLocation as $row){
                                            $options[$row->fldid] = $row->code;
                                        }
                                        $js=' class="validate[required] input-large fromLocationID" disabled="disabled"';
                                        echo form_dropdown('fromLocationID', $options, $preselcat, $js);
                                    ?>
                                </div>                       
                            </div> 
                            <div class="controls-row">
                                <div class="span4"><?php echo $this->lang->line('toLocation') ?>*</div>
                                <div class="span8">
                                    <?php
										$preselcat = $datatbls['transInfo'][0]->toLocationID;
                                        $js='class="validate[required] input-large toLocationID"';
                                        echo form_dropdown('toLocationID', $options, $preselcat, $js);
                                    ?>
                                </div>                       
                            </div>  
                            <div class="controls-row">
                                <div class="span4"><?php echo $this->lang->line('reference') ?></div>
                                <div class="span8">
                                    <?php
                                    $data = array(
                                        'value'=>$datatbls['transInfo'][0]->formNo,
                                        'name'=>'formNo',
                                        'id'=>'formNo',
                                        'style'=>'color: red;',
                                        'class'=>'input-small',); 
                                    echo form_input($data);
                                    ?>
                                    <?php
                                    $data = array(
                                        'value'=>$datatbls['transInfo'][0]->ID,
                                        'name'=>'formID',
                                        'id'=>'formID',
                                        'style'=>'',
                                        'disabled'=>'disabled',
                                        'placeholder'=>'0000',
                                        'class'=>'input-small validate[required]',); 
                                    echo form_input($data);
                                    ?>
                                </div>                       
                            </div>                            
                        </div> 
                    </div> <!-- Block -->
                </div>
                <div class="span6 scCol">
                    <div class="block" id="grid_block_1">	
                        <div class="content"> 
                            <div class="controls-row">
                                <div class="span4"><?php echo $this->lang->line('movementType') ?>*</div>
                                <div class="span8">
                                    <?php 
                                        $preselcat = $datatbls['transInfo'][0]->movementTypeID;
                                        $options = array();
										$options[''] = 'Please Select';
                                        foreach($itemCategory as $row){
                                            $options[$row->ID] = $row->name;
                                        }
                                        $js='class="validate[required] input-large movementTypeID"';
                                        echo form_dropdown('movementTypeID', $options,$preselcat,$js);
                                    
									?>
                                </div>                       
                            </div> 
                            <div class="controls-row">
                                <div class="span4"><?php echo $this->lang->line('transferDate') ?></div>
                                <div class="input-prepend span8">
                                    <span class="add-on"><i class="i-calendar"></i></span>
                                    <?php
                                        $data = array(
                                        'name' => 'dateTransfer',
                                        'id' => 'dateTransfer',
                                        'type' => 'text',
										'value'=> $datatbls['transInfo'][0]->dateTransfer,
                                        'class' => 'validate[required] input-small datepicker2',);
                                        $js='';
                                        echo form_input($data);                                        
                                    ?>       
                                </div>
                            </div>
                            <div class="controls-row">
                                <div class="span4"><?php echo $this->lang->line('locTransMemo') ?>*</div>
                                <div class="input-prepend span8">
                                    <?php
                                        $data = array(
                                        'name' 	=> 'memo',
                                        'id' 	=> 'memo',
										'value'	=> $datatbls['transInfo'][0]->memo,
										'cols' 	=> 18,
										'rows' 	=> 5,
										'class'	=> 'validate[required]'	
										);
                                        echo form_textarea($data);                                        
                                    ?>       
                                </div>
                            </div>                           
                        </div>
                    </div>
                </div>
            </div>
            <!--Location transfer top form-->  
        </div>
        
        <div class="row-fluid scRow">                            
          <div class="span12 scCol">
            <div class="block" id="grid_block_4">
               <div class="head">
                <h2><?php echo $this->lang->line('items')?></h2>
                <!--<ul class="buttons">
                    <li><a class="block_toggle collapsed" data-toggle="collapse" data-parent="#accordion2" href="#collapseOne">
                                <span class="i-arrow-down-3"></span></a></li>
                </ul>-->                                        
              </div><!-- head -->
              <div class="content np">
                      <table id="listDetails" class="editable" cellpadding="0" cellspacing="0" width="100%">
                            <thead>
                                <tr>
                                    <th style="display:none"></th>
                                    <th class="tac"><?php echo $this->lang->line('itemCode')?></th>
                                    <th class="tac"><?php echo $this->lang->line('itemDescription')?></th>
                                    <th class="tar"><?php echo $this->lang->line('stock')?></th>
                                    <th class="tar"><?php echo $this->lang->line('quantity')?></th>
                                	<th class="tac span1"><?php echo $this->lang->line('action')?></th>
                                </tr>
                            </thead>
                            <tbody>
                            	
                                <?php 
								if(isset($datatbls['itemList'][0]->ID)):
									foreach($datatbls['itemList'] as $row):
								?>
                                		<tr>
                                        	<td class="span2 itemID" style="display:none;"><?php echo $row->ID; ?></td>
                                            <td class="span2 no-edit"><?php echo $row->itemCode; ?></td>
                                            <td class="span2 no-edit"><?php echo $row->description; ?></td>
                                            <td class="span1 no-edit" style="text-align:right"><?php echo $row->fromStock; ?></td>
                                            <td class="span1" style="text-align:right"><?php echo $row->quantity; ?></td>
                                            <td class="span1 no-edit tac" align="center">
                                            	<button class="btn btn-mini btn-primary editItm" type="button"><i class="icon-pencil"></i></button><br />
                                                <button class="btn btn-mini btn-danger deleteItm" type="button"><i class="icon-remove-circle icon-white"></i></button>
                                            </td>
                                        </tr>	
                                <?php
									endforeach;
								endif;
                                ?>
                            	<tr id="trInfos">
                                    <td colspan="11" style="text-align:left;">
                                        <div id="msg_div1" class="alert alert-info">
                                          	<h4><?php echo $this->lang->line('lastMessage')?></h4>
                                          	<p style="padding-top:10px;"><?php echo $this->lang->line('noMessage')?></p>
                                      	</div>
                                  	</td>
                              	</tr>
                        	</tbody>
                      </table>
                <div class="footer">
                    <div class="side fr">
                        <div class="btn-group">
                        <button style="margin-right:6px;" onclick="$('#parchaseDetailForm').validationEngine('hide');" class="btn btn-mini" type="button" name="validat">Hide prompts</button>
                        <button id="addRow" class="btn btn-mini btn-primary" type="button">
                            <i class="icon-plus-sign"></i><?php echo $this->lang->line('addNewItem')?></button>
                        </div><!-- btn group -->      
                    </div><!-- side fr -->      
                </div><!-- footer -->      
              </div><!-- content -->
            </div><!-- grid block 1-->
          </div><!-- scCol -->
        </div><!-- row-fluid scRow-->
        
        <div class="content">
            <div class="wrap">
                <div class="row-fluid">
                    <div class="span12">
                        <div class="block">
                            <div class="footer">
                                <div class="side fr">
                                    <div class="btn-group">
                                        <?php 
                                            $data = array(
                                                    'name'=>'postloctrans', 
                                                    'class'=>'btn btn-warning submit');
                                            echo form_submit($data,$this->lang->line('processTransfer'));
                                            ?>
                                    </div>
                                </div>
                            </div>                                    
                        </div><!-- block -->
                    </div><!-- span12 -->
                </div><!-- row-fluid -->	
            </div><!-- wrap -->
        </div><!-- content -->
    <?php echo form_close(); ?>
	</div>
</div>

<!-- Bootrstrap modal form -->
<div id="popupItemAdder" class="modal hide fade" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h3>Modal form</h3>
    </div>        
    <div class="row-fluid">
        <div class="block np">
        	<div class="content np">
            	<div class="controls-row">
                    <div class="span3">Select Items:</div>
                    <div class="span9">
                    	<?php
						$i = 0;
                        foreach($items as $item):
						?>
                        <label class="checkbox inline itemCheck"><input type="checkbox" name="items" value="<?php echo $item->ID; ?>" /><?php echo $item->name; ?></label>
                        <?php 
						endforeach;
						?>
                    </div>
                </div> 
            </div>              
        </div>
    </div>                   
    <div class="modal-footer">
        <button class="btn btn-primary addItems" data-dismiss="modal" aria-hidden="true">Add Items</button> 
        <button class="btn btn-warning" data-dismiss="modal" aria-hidden="true">Close</button>            
    </div>
</div>
<!-- EOF Bootrstrap modal form -->