
<style type="text/css">
	.ValSpan{
		opacity:0;
	}
	.line{
		border:2px solid #4c0870 ;
	}
	.UpdatedQuantityVal  {
		border: none;
		background-color: #eee;
		text-align: center;
	}
	#TotalQuantity td >input{
		background-color: #eee;
		text-align: center;
	}
	.EditRow{
		opacity: 1;
		transform: scale(1.1)
	}
</style>
<div class="wrapper">
	<div class="panel invoice">
		<div class="panel-body">
			<div class="row">
				<div class="col-xs-3">
					<div class="invoice-logo">
						<img src="<?= upload_url;?>org_logo/invoice_logo.jpg" alt=""style="max-width:250px"/>
					</div>
				</div>
				<div class="col-xs-4">
				</div>
				<div class="col-xs-5">
					<h1><?php print CommonLanguage::getMessage('loading_order');?> </h1>
				</div>
			</div>
			<div id="ReturnItemSuccess" class="alert alert-success hidden"></div>
			<div class="row">
				<div class="col-xs-4">
					<br/> <label><span class="bold"><?php print CommonLanguage::getMessage('Name');?> :</span></label><?php echo $org_details[0][ "Organization_Name"]; ?>
					<br/> <label><span class="bold"><?php print CommonLanguage::getMessage('address');?> :</span></label><?php echo $org_details[0][ "Country_Name"] .'-'. $org_details[0]["Name"].'-'. $org_details[0][ "Organization_Street"]?>
					<br/><label><span class="bold"><?php print CommonLanguage::getMessage('Email');?> :</span> </label><?php echo $org_details[0][ "Organization_Email"] ?>
					<br/><label><span class="bold"><?php print CommonLanguage::getMessage('Phone');?> :</span></label><?php echo $org_details[0]["Organization_Phone"] ?>
				</div>
				<div class="col-xs-4">
					<br/> <label><span class="bold"><?php print CommonLanguage::getMessage('truck');?> # : </span></label><?php echo $Load_details[0]['Vehicle_Registration_Number'];?>
					<br/> <label><span class="bold"><?php print CommonLanguage::getMessage('driver');?> : </span> </label><?php echo $Load_details[0]['Driver_Name'];?>
					<br/><label><span class="bold"><?php print CommonLanguage::getMessage('salesman');?> :</span> </label><?php echo $Load_details[0]['Sales_Man_Name'];?>
				</div>
				<div class="col-xs-4 inv-info">
					<br/><label><span class="bold"><?php print CommonLanguage::getMessage('loading_order');?> # :</span> </label><span id="LoadOrderID"><?php echo $Load_ID?></span>
					<br/><label><span class="bold"><?php print CommonLanguage::getMessage('zone');?> : </span></label><?php echo $Load_details[0]['Zone_Name'];?>
					<br/><label><span class="bold"><?php print CommonLanguage::getMessage('Date');?> : </span></label><?php echo $Load_details[0]['Loading_Order_Date'];?>
				</div>
			</div>
			<div class="col-md-12">
				<?php 
				$count = $Load_details['Count_Columns'];
				for($x=0; $x <count($Load_details)-2;$x++){
					$CurItem = $Load_details[$x];
				?>   
				<div class="col-md-12 line" style="margin:5px">
					<div class="col-md-4">
						<div> <label><span class="bold"><?php print CommonLanguage::getMessage('sales_order');?> # :</span> <?php echo $CurItem['Sales_Order_ID'] ?></label>  </div>
						<div> <label><span class="bold"><?php print CommonLanguage::getMessage('customer');?> :</span><?php echo $CurItem['Customer_Name'] ?></label>  </div>
						<div> <label><span class="bold"><?php print CommonLanguage::getMessage('address');?>  :</span> <?php echo $CurItem['Country_Name'].'-'.$CurItem['City_Name'].'-'.$CurItem['Customer_Address']?></label>  </div>
						<div> <label><span class="bold"><?php print CommonLanguage::getMessage('submitted_by');?>  :</span> <?php echo $CurItem['Logged_Name'];?></label>  </div>

					</div>
					<table class="table table-striped table-hover">
						<thead>
							<tr>
								<th class="text-center">#</th>
								<th class="text-center"><?php print CommonLanguage::getMessage('Code');?></th>
								<th class="text-center"><?php print CommonLanguage::getMessage('Item');?></th>
								<th class="text-center"><?php print CommonLanguage::getMessage('Quantity');?></th>
							</tr>
						</thead>
						<tbody> 
							<?php
					for($i=0; $i < count($Load_details[$x])-20;$i++){
						$CurItem1 = $Load_details[$x];
							?>
							<tr data-id="<?php echo $CurItem1[$i]['Product_ID']?>">
								<td class="text-center"><?php echo $i+1?></td>
								<td class="text-center"><?php echo $CurItem1[$i]['Product_Code'] ?></td>
								<td class="text-center"><?php echo $CurItem1[$i]['Product_Name'] ?></td>
								<td class="text-center"><?php echo $CurItem1[$i]['Quantity'] ?></td>
							</tr>
							<?php } ?>
						</tbody>
					</table>
				</div>
				<?php }?>
			</div>
			<br/>
			<br/>
			<br/>
			<br/>
			<br/>
			<hr>
			<div class="col-md-12">
				<div class="col-md-12   clearfix" style="margin:5px;border: 2px solid #4c0870;padding-left: 6px;padding-right:0">
					<h5 class="font-montserrat all-caps small no-margin hint-text bold"><?php print CommonLanguage::getMessage('total_quantity');?></h5>
					<?php if($permissions->hasPermission('EditLoadedQty')){ 
	if(!$loadedButton){ 
					?>
					<button type="button" id="AddProduct" class="btn btn-primary pull-right no-print"   style="margin-right:10px;margin-top: 9px;"><i class="fa fa-plus-circle"></i> <?php print CommonLanguage::getMessage('Add');?></button>
					<?php } }?>
<!--					<button type="button" id="PrintTable" data-toggle="tooltip"  title="Print" class="PrintThisTableButton btn btn-danger pull-right no-print" data-table="#TotalQuantity" data-date="< ?php echo $Load_details[0]['Loading_Order_Date'];?>" data-title="Total Quantity"  class="btn btn-danger pull-right no-print"   style="margin-right:10px;margin-top: 9px;"><i class="fa fa-print"></i> < ?php print CommonLanguage::getMessage('print');?></button>-->
                      

					<table class="table" cellpadding="0" cellspacing="0" id="TotalQuantity">
						<thead>
							<tr>
								<th class="text-center">#</th>
								<th class="text-center"><?php print CommonLanguage::getMessage('Code');?></th>
								<th class="text-center"><?php print CommonLanguage::getMessage('Item');?></th>
								<th class="text-center"><?php print CommonLanguage::getMessage('Quantity');?></th>
								<!--<th class="text-center no-print"></th>-->
							</tr>
						</thead>
						<?php if(!$loadedButton){ ?>
						<tbody>
							<?php 
	$j=1; 
	foreach($Load_details['Total'] as $key=>$val){
		$CurItem = $Load_details['Total'];
		$temp = explode("-/",$key);
							?>
							<tr data-id="<?php echo $temp[0];?>" data-cid="" data-quantity="<?php echo $val;?>">
								<td class="text-center Counter"><?php echo $j;?></td>
								<td class="text-center"><?php echo $temp[1];?></td>
								<td class="text-center"><?php echo $temp[2];?></td>
								<td class="text-center Quantity"><input class="UpdatedQuantityVal" type="text" disabled='disabled' value="<?php echo $val;?>"></td>
								<!--<td class='ExpiryDate no-print'><span class='fa fa-plus-circle' style='color:#4c0870;'></span></td>-->
							</tr>
							<?php $j++; $temp=array();}?>
						</tbody>	
						<?php }else {?>
						<tbody>
							<?php 
	for($x=0;$x<count($Total_Quantity_details);$x++){
		$CurItem = $Total_Quantity_details[$x];
							?>
							<tr data-code="<?php echo $CurItem['Product_ID']?>" data-load="<?php echo $Load_ID?>">
								<td class="text-center"><?php echo $x+1;?></td>
								<td class="text-center"><?php echo $CurItem['Product_Code'];?></td>
								<td class="text-center"><?php echo $CurItem['Product_Name'];?></td>
								<td class="text-center Quantity"><?php echo $CurItem['Total_Quantity'];;?></td>
							</tr>
							<?php }?>
						</tbody>
						<?php }?>
					</table>
				</div>
			</div>
		</div>
		<div class="row no-print">
			<div class="col-md-12">
				<div class="pull-right" style="margin:35px;">
					<a class="btn btn-danger" onclick="javascript:window.print();"><i class="fa fa-print"></i> <?php print CommonLanguage::getMessage('print');?></a>
					<?php if(!$loadedButton){ ?>
					<button class="btn btn-primary" id="SubmitLoad"><i class="fa fa-truck"></i> <?php print CommonLanguage::getMessage('validate_load');?></button>
					<?php }?>
				</div>
			</div>
		</div>
	</div>
</div>
<!--<div class="modal fade" tabindex="-1" role="dialog" aria-labelledby="role-mode" id="add_Expiry" aria-hidden="true" style="display: none;     width: 50%;
																														  margin: 0 auto;">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
				<h4 class="modal-title" id="myModalLabel"><?php print CommonLanguage::getMessage('Add_Expiry_Date');?></h4>
				<div id="ExpirySuccess" class="hidden"></div>
				<br>
			</div>
			<div class="modal-body" id="Add">
				<input type="hidden" name="Product_ID"  id="Product_ID" class="form-control input-rounded" required>
				<input type="hidden" name="Category_ID"  id="Category_ID" class="form-control input-rounded" required>
				<div class="form-group col-md-12 AddRow">
					<div  class=" col-md-6">
						<input type="text" name="Product_Quantity"  id="Product_Quantity" placeholder="<?php print CommonLanguage::getMessage('Quantity');?>" class="form-control input-rounded Product_Quantity" required>
					</div>
					<div  class=" col-md-5">
						<input type="text" name="Product_ExpiryDate"  id="Product_ExpiryDate" placeholder="<?php print CommonLanguage::getMessage('Exipry_Date');?>" class="form-control input-rounded Product_ExpiryDate" required>
					</div>
					<span class="fa fa-plus-circle" style="color:#8a7dbe;margin-top:10px"></span>
					<span class="fa fa-minus-circle" style="color:#ed9421;margin-top:10px;display:none"></span>
				</div>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-default" id="Closemodal" ><?php print CommonLanguage::getMessage('Close');?></button>
				<button type="submit" class="btn btn-primary" id="SubmitExpiry"><?php print CommonLanguage::getMessage('Save');?></button>
			</div>
		</div>
	</div>
</div>-->
<script>
    var Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully'));?>,
        Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit'));?>;
	var Counter=parseInt($("#TotalQuantity tr").find(".Counter").html());
	$(function(){
//		$("#Product_ExpiryDate").datepicker({autoclose:true}).on("changeDate",function(){})
//		$("#TotalQuantity tbody").on("click","tr > .ExpiryDate > span.fa-plus-circle",function(){
//			var me = $(this).parents("tr");
//			$("#add_Expiry").modal('show')
//			$("#Product_ID").val(me.attr('data-id'))
//			$("#Category_ID").val(me.attr('data-cid'))
//		})
//		$("#Add").on("click",".AddRow > .fa-plus-circle",function(e){
//			$(".AddRow > .fa-minus-circle").css("display","")
//			var Parent = $(this).parents("#Add").find(".AddRow:eq(0)"),NewItem = Parent.clone().insertAfter(Parent);
//			NewItem.find("input").val('');
//			NewItem.find("#Product_ExpiryDate").datepicker({autoclose:true})
//		})
//		$("#Add").on("click",".AddRow > .fa-minus-circle",function(e){
//			$(this).closest(".AddRow").empty().remove();
//			$("#Add").each(function(){
//				$(".AddRow > .fa-minus-circle",$(this).parent()).css({"display":$(".AddRow",$(this).parent()).length <= 1 ? "none" : "inline-block"})
//			})
//		})
		$("#AddProduct").on("click",function(){
			Counter += parseInt($("#TotalQuantity tr").find(".Counter").html());
			var TR  = "<tr data-quantity="+0+">"
			TR += "<td class='text-center'>"+(Counter ? Counter : 1)+"</td>"
			TR += "<td class='text-center' style='width:20%'><input type='text' class='form-control AutoComplete CODE'></td>"
			TR += "<td class='text-center'><input type='text' class='form-control AutoComplete ProductName'></td>"
			TR += "<td class='text-center'style='width:20%'><span class='Hint'></span><input type='text' class='form-control UpdatedQuantityVal Quantity isnumber'></td>"
			TR += "<td class='ExpiryDate'><span class='fa fa-plus-circle' style='color:#4c0870;margin-top:10px'></span></td></tr>"


			TR = $(TR)
			$("#TotalQuantity").append(TR)
		})
		// EnableAutoComplete($("#TotalQuantity  input.AutoComplete.CODE"));
		$("#TotalQuantity").delegate(".Quantity","blur keyup",function(e){
			var me = $(this),TR = me.parents("tr");
			if(e.which == 13){
				if(me.hasClass("Quantity")){
					TR.find(".UnitPrice").focus()
				}else if(me.hasClass("UnitPrice")){
					TR.find(".Disc").focus()
				}else{
					TR.next().find(".CODE").focus()
				}
			}
			if(TR.index() < $("#TotalQuantity tbody").children().length-1){
				if($.trim(me.val()).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null){
					me.addClass("wrong")
				}else{
					me.removeClass("wrong")
				}
			}
		});
		$("#TotalQuantity tbody").delegate("> tr input:not(.UpdatedQuantityVal)","keydown",function(e){
			var me = $(this)
			if(e.which == 8){
				if(me.val() == "" && !me.hasClass("CODE")){
					me.parents("td").prev().find("input").focus()
				}else if(me.val() == "" && me.hasClass("CODE")){
					if(me.parents("tr").prev()){
						me.parents("tr").prev().find(".Disc").focus()
					}
				}
			}
		})
		$("#TotalQuantity tbody").delegate("> tr input:not(.UpdatedQuantityVal)","keyup",function(e){
			var me=$(this),Parent = me.parents("tbody"),IsLastOneEmpty = true;
			$("tr",Parent).each(function(e){
				if($("tr",Parent).length > 1){
					var IsEmpty = true;
					$(this).find("input").each(function(){
						if($(this).val() != "")IsEmpty = false;
					})
					if(IsEmpty == true){
						if($(this).index() <= $("#TotalQuantity tbody tr").length-2){
							me.parents("tr").prev().find(".Disc").focus()
							$(this).remove();
						}
					}
				}
			})
		})
		$("#SubmitLoad").on("click",function(){
			var data = {
				Loading_Order_ID : $("#LoadOrderID").text(),
				Products:[]
			}
			$("#TotalQuantity tr[data-id]").each(function(){
				var me= $(this), addedQuantity = 0;
				if(me.find("input.ProductName") != ''){
					addedQuantity =  (me.find(".UpdatedQuantityVal").val() - me.attr('data-quantity')) ;
					data.Products.push({
						Product_ID : me.attr('data-id'),
						Initial_Quantity : me.attr('data-quantity'),
						Quantity : me.find(".UpdatedQuantityVal").val(),
						Product_Added_Quantity : addedQuantity
					})
				}
			})
			$.ajax({
				url:"InventoryAjax/ViewLoadingOrderAjax",
				data:data,
				method:"POST",
				complete:function(v,vv){
					if(vv == "success"){
						$(document.body).animate({scrollTop:0})
						$("#ReturnItemSuccess").attr("class","alert alert-success").show().html(Submitted_Successfully)
					}else{
						//alert("Failed to submit, please try again")
//						$("#ReturnItemSuccess").removeClass("hidden,alert-success")
						$("#ReturnItemSuccess").attr("class","alert alert-danger").html(Failed_Submit)
					}
				}
			})
		}) 
	});
	$("#TotalQuantity tbody").on("keyup",".UpdatedQuantityVal",function(){
		UpdateSubmitButton()
	})
	function UpdateSubmitButton(){
		var IsValidated=true;
		$("#TotalQuantity tr[data-id]").each(function(){
			var me= $(this),
				Qy   = parseInt($(".UpdatedQuantityVal",this).val()),
				OldQty = me.attr("data-quantity")    
			if ((Qy < OldQty) || ($(".Quantity > input").val() == "") || ($(".Quantity>input").hasClass("UpdatedQuantityVal") && ($(".Quantity>input").val()).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null))
			{
				IsValidated = false;
			}
		})
		if(!IsValidated){
			$("#SubmitLoad").addClass("disabled")}
		else{$("#SubmitLoad").removeClass("disabled")}
	}
	$("#TotalQuantity tbody ").on("keyup","input.AutoComplete.CODE",function(){
		var who = $(this);
		if(!who.hasClass("AutoAdded")){
			who.autocomplete({
				source: function(request, response){
					$.getJSON('xhr/ajaxVendor?cmd=' + (who.hasClass("CODE") ? "1" : "2") + "&type=0" , request, function( s, status, xhr ){
						response( s );
					});
				},
				minLength: 2,
				select: function(event, ui){
					var TR = $(this).parents("tr");
					TR.attr("data-id",ui.item.Product_ID)
					TR.find("input.CODE").val(ui.item.Product_Code )            
					TR.find("input.ProductName").val(ui.item.Product_Name )
					return false;
				}
			}).autocomplete("instance")._resizeMenu = function( ul, items ) {
				this.menu.element.outerWidth((who.width()*(this.element.hasClass("CODE") ? 1 : 2.3)) + parseFloat(who.css("padding-left")) + parseFloat(who.css("padding-right")) + 2);
			}
			who.autocomplete("instance")._renderItem = function(ul,item){
				var MyType = this.element.hasClass("CODE") ? (item.Product_Code ? item.Product_Code : item.Material_Code) : (item.Product_Name ? item.Product_Name : item.Material_Name);
				return $("<li>").html("<table cellspacing='0' cellpadding='0'><tr><td class='OnlyText'>"+MyType+"</td></tr></table>").appendTo(ul)
			}
			who.addClass("AutoAdded")
		}
		$(document).keydown(function(e){
			if(e.which == 8 && e.target.tagName.toLowerCase() != "input"){
				e.preventDefault()
			}
		})
	})
	$("#TotalQuantity tbody ").on("keyup","input.AutoComplete.ProductName",function(){
		var who = $(this);
		if(!who.hasClass("AutoAdded")){
			who.autocomplete({
				source: function(request, response){
					$.getJSON('xhr/ajaxVendor?cmd=' + (who.hasClass("CODE") ? "1" : "2") + "&type=0" , request, function( s, status, xhr ){
						response( s );
					});
				},
				minLength: 2,
				select: function(event, ui){
					var TR = $(this).parents("tr");
					TR.attr("data-id",ui.item.Product_ID)
					TR.find("input.CODE").val(ui.item.Product_Code )            
					TR.find("input.ProductName").val(ui.item.Product_Name )
					return false;
				}
			}).autocomplete("instance")._resizeMenu = function( ul, items ) {
				this.menu.element.outerWidth((who.width()*(this.element.hasClass("CODE") ? 1 : 2.3)) + parseFloat(who.css("padding-left")) + parseFloat(who.css("padding-right")) + 2);
			}
			who.autocomplete("instance")._renderItem = function(ul,item){
				var MyType = this.element.hasClass("CODE") ? (item.Product_Code ? item.Product_Code : item.Material_Code) : (item.Product_Name ? item.Product_Name : item.Material_Name);
				return $("<li>").html("<table cellspacing='0' cellpadding='0'><tr><td class='OnlyText'>"+MyType+"</td></tr></table>").appendTo(ul)
			}
			who.addClass("AutoAdded")
		}
		$(document).keydown(function(e){
			if(e.which == 8 && e.target.tagName.toLowerCase() != "input"){
				e.preventDefault()
			}
		})
	})
	/*to enable the edit value for each loaded product on click */
	$("#AddProduct").on("click",function(){
		$(".Quantity>input").removeAttr("disabled").addClass("EditRow")
	})
	//     $("#TotalQuantity tbody").on('keyup',".Quantity > .UpdatedQuantityVal",function(e){
	//           
	//             var IsEmpty = $(this).parents('tr').find('td:eq(0)').html() ? 1 : 0
	//            console.log(IsEmpty)
	//          
	////            if(e.which == 8 && e.target.tagName.toLowerCase() == "input" && e.target.value ==""){
	////                
	////                e.preventDefault()
	////            }
	//        })
//	$("#SubmitExpiry").on("click",function(){
//		var Data={
//			Product_ID  : $("#Product_ID").val(),
//			type        : 5,
//			Depot_ID    : 1,
//			Category_ID : 0,
//			Expiry:[]
//		}
//		$("#Add > .AddRow").each(function(){
//			var me= $(this);
//			Data.Expiry.push({
//				Expiry_Date : me.find(".Product_ExpiryDate").val(),
//				Product_Quantity : me.find(".Product_Quantity").val()
//			})
//		})
//		$.ajax({
//			url:"InventoryAjax/ViewLoadingOrderAjax",
//			method:"POST",
//			data:Data,
//			complete:function(v1,v2){
//				if(v2 == "success"  &&  v1.responseText == "OK"){
//					$("#ExpirySuccess").attr("class","alert alert-success").html(Submitted_Successfully)
//					setTimeout(function(){
//						$("#add_Expiry").modal('hide')
//						$("#ExpirySuccess").addClass('hidden')				 
//						$('.AddRow').not('div:first').remove()
//						$('.AddRow > .fa-minus-circle').not('div:first').css("display","none")			 
//					},800)
//				}else{
//					$("#ExpirySuccess").attr("class","alert alert-danger").html(Failed_Submit)
//				}
//			}
//		})
//		$('#Add  input').val('')
//	})
//	$("#Closemodal").on("click",function(){
//		$('#add_Expiry').modal('hide')
//		$('.AddRow').not('div:first').remove()
//		$('.AddRow > .fa-minus-circle').not('div:first').css("display","none")
//		$('#Add  input').val('')
//	})
</script>
