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

$(document).ready(function(){
	$('select').select2();

	$.each($(".select2-container"), function (i, n) {
        $(n).next().show().fadeTo(0,0).height("0px").css("left", "auto"); // make the original select visible for validation engine and hidden for us
        $(n).prepend($(n).next());
        $(n).delay(500).queue(function () {
            $(this).removeClass("validate[required]"); //remove the class name from select2 container(div), so that validation engine dose not validate it
            $(this).dequeue();
        });
    });	
	
	jQuery('.datepicker2').datepicker({
		dateFormat : 'dd-mm-yy',
		changeMonth : true,
		changeYear : true
	});
	
	//Validate form data
	/*$('.submit').click(function(){
		if($("#loctransfer").validationEngine('validate')){
			return true;
		}else{
			return false;
		}
	});*/
	
	$('.quantity').live('change keypress keyup',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');
			msg(1,"alert","Warning, Maximum items found "+$(this).parents('tr').find('.stock').val());
		}
	});
	// function to add new item to the list
	$('#addRow').click(function(){
		$("#parchaseDetailForm").validationEngine('validate')
		if($("#loctransfer").validationEngine('validate')){
			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 != ''){
						//$('#fromLocationID').attr('disabled','disabled');
						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","No item found");
					}
					
				}
			});
		}else{
			msg (1,"alert","Please, do select location before addind new one");
			return false;
		}
	});
	
	
	//Item save
	$('.saveItm').live('click',function(){
		var me = $(this).parents('tr');
		if($("#loctransfer").validationEngine('validate')){
			var itemID = $('#locID').val();
			if( itemID == ''){			
				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">'+$(me).find('.itemCode').val()+'</td>'
							+'<td class="span2">'+$(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" align="center">'
								+'<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 alert-info","Successfull, Item added to the location 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());
		});
	});
});
//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="home"><?php echo $this->lang->line('module') ?></a> <span class="divider">-</span></li>
            <li class="active"><?php echo $this->lang->line('addTitle') ?></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="" />
        	
        <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="block">
    	<div class="content">
            <div class="row-fluid scRow">
                <div class="span6 scCol">        	
                    <div class="block ns" id="grid_block_1">
                            <div class="controls-row">
                                <div class="span4"><?php echo $this->lang->line('fromLocation') ?>*</div>
                                <div class="span8">
                                    <?php
                                    	$preselcat = '';
										$options[''] = 'Please select';
                                        foreach($fromLocation as $row){
                                            $options[$row->fldid] = $row->code;
                                        }
                                        $js='ID="fromLocationID" class="validate[required] span12"';
                                        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
                                        $js='ID="toLocationID" class="validate[required] span12"';
                                        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'=>$formNo,
                                        'name'=>'formNo',
                                        'id'=>'formNo',
                                        'style'=>'color: red;',
                                        'class'=>'span6',); 
                                    echo form_input($data, set_value($formNo));
                                    ?>
                                    <?php
                                    $data = array(
                                        'value'=>"0000",
                                        'name'=>'formID',
                                        'id'=>'formID',
                                        'style'=>'',
                                        'disabled'=>'disabled',
                                        'placeholder'=>'0000',
                                        'class'=>'span6 validate[required]',); 
                                    echo form_input($data);
                                    ?>
                                </div>                       
                            </div> 
                            <div class="controls-row">
                                <div class="span4">&nbsp;</div>
                                <div class="span8">&nbsp;</div>                       
                            </div>                            
                    </div> <!-- Block -->
                </div>
                <div class="span6 scCol">
                    <div class="block ns" id="grid_block_1">	
                            <div class="controls-row">
                                <div class="span4"><?php echo $this->lang->line('movementType') ?>*</div>
                                <div class="span8">
                                    <?php 
                                        $preselcat = '';
                                        $options = array();
										$options[''] = 'Please Sele';
                                        foreach($itemCategory as $row){
                                            $options[$row->ID] = $row->name;
                                        }
                                        $js='id="movementTypeID" class="validate[required] span12 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',
                                        'class' => 'validate[required] input-small datepicker2',);
                                        $js='';
                                        echo form_input($data, date(element('dtFormat', $this->session->userdata('logged_in'))), $js);                                        
                                    ?>       
                                </div>
                            </div>
                            <div class="controls-row">
                                <div class="span4"><?php echo $this->lang->line('locTransMemo') ?>*</div>
                                <div class="input-prepend span8" style="padding-bottom:2px;">
                                    <?php
                                        $data = array(
                                        'name' 	=> 'memo',
                                        'id' 	=> 'memo',
										'cols' 	=> 18,
										'rows' 	=> 3,
										'class'	=> ''	
										);
                                        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"><?php echo $this->lang->line('action')?></th>
                                </tr>
                            </thead>
                            <tbody>
                            	<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="$('#loctransfer').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-->
        
        <!-- 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 -->