<style type="text/css">
    .amount{
        text-align: right !important;
    }

    .btn-group button{
        height:30px;}

    #content .wrap #grid_content_1 .row-fluid.scRow .row-fluid.scRow .span12.scCol #grid_block_5 .content.np #listDetails tbody #trInfos td .row-fluid .controls-row .span3 {
        font-size: 11px;
        color: #000;
        font-weight: bold;
    }
    .test {
        font-size: 10px;
    }
    .span3 {
        font-size: 10px;
    }
    tbody {
        font-size: 10px;
    }
    #content .wrap #grid_content_1 .row-fluid.scRow .row-fluid.scRow .span12.scCol #grid_block_6 .content.np #listCharge tbody #trInfosCharge td .row-fluid .controls-row .span3 {
        font-weight: bold;
    }
</style>
<script type="application/javascript">

    $(document).ready(function(){
    $('select').select2();
    /*****GST Register supplier's color change start******/    
    function format(state) {
    var text = state.text.match(/\(GST\)/g);
    var modTxt = state.text.replace("(GST)","");
    if(text != null)  return '<span style="color:#85c420;">'+modTxt+"</span>";
    else              return modTxt;
    }
    $("#supplier").select2({
    formatResult: format,
    formatSelection: format,
    escapeMarkup: function(m) { return m; }
    });
    /*****GST Register supplier's color change end******/
    $.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
    });
    });

    function loadPoListBySupplierID() {
    $('#poList').empty();
    $('#poList').append('<option value = "null"></option><option value="-1">None</option>');
    $('#outstandingItems tbody').empty();
    $.ajax({
    type: "POST",
    data: "supplier="+ $("#supplier option:selected").val(),
    url: "<?php echo base_url() ?>receiveItems/getPoList",
    success: function(data) {
    if(data){
    var resul = eval ("(" + data + ")"); 
    var n=resul.records.length;
    console.log();
    var i=0;
    //data-exchangeRate="'+ resul.records[i].exchangeRate +'"
    var opt='';
    console.log(n);
    for (i=0;i<n;i++)
    opt=opt + '<option  value="' + resul.records[i].id + '">' + resul.records[i].formNo + '</option>';

    $('#poList').append(opt);
    }
    $('#poList').select2('val',null);
    }
    });
    }

    function loadSupplierDefaultValue(me){
    $('#currency').attr("value","");
    $('#exchange_rate').attr("value","");
    var date = $.datepicker.formatDate('yymmdd', new Date());
    loadPoListBySupplierID();
    $.ajax({
    type: "POST",
    data: "supplier="+ $("#supplier option:selected").val()+'&effdate='+date,
    url: "<?php echo base_url() ?>aptransaction/loadSupplierDefaultValue",
    dataType: "JSON",
    success: function(data) {
    $('#currency').attr("data-currencyID",data[0].currencyID);
    $('#currency').attr("value",data[0].currencyWord);
    $('#exchange_rate').attr("value",accounting.formatNumber(data[0].exchangeRate,5));
    /*
    var resul = eval ("(" + data + ")"); 
    $('#currency').attr("data-currencyID",resul.records[0].currencyID);
    $('#currency').attr("value",resul.records[0].currency);
    $('#exchange_rate').val(resul.records[0].exchangeRate);*/
    }
    });

    }

    function refreshSupplier(){
    //<span style="color:#85c420;">'+modTxt+"</span>
    $.ajax({
    type: "POST",
    url: "<?php echo base_url() ?>supplier/refreshSupplier",
    success: function(data) {

    var resul = eval ("(" + data + ")"); 
    var n=resul.records.length;
    var i=0;
    var opt='' +
    '<option></option>';
    for (i=0;i<n;i++)
    if(resul.records[i].gstRegNo != ''){
    opt=opt + '<option value="' + resul.records[i].id + '">' + resul.records[i].supplierName + ' (GST)</option>';
    }else{
    opt=opt + '<option value="' + resul.records[i].id + '">' + resul.records[i].supplierName + '</option>';
    }
    $('#supplier').empty();
    $('#supplier').append(opt);
    }
    });

    }



    function calculamount() {
    $("#itemAmount").val(accounting.formatNumber(accounting.unformat($("#itemunitprice").val())*accounting.unformat($("#itemqte").val()),2));
    }			


    function getTotal (){
    $("#totalpayable").val("");

    var n =$("#t_listItemOrdered > tbody > tr").length-1;
    var total =0;
    for (i=0; i<=n; i++) {
    total= total + accounting.unformat($('#t_listItemOrdered > tbody > tr:eq(' + i + ') > td:eq(6)').text())*1; 
    }

    var total1 =0;
    var n1 =$("#t_listItemNoPo > tbody > tr").length-1;
    for (i=0; i<=n1; i++) {
    total1= total1 + accounting.unformat($('#t_listItemNoPo > tbody > tr:eq(' + i + ') > td:eq(6)').text())*1; 
    }

    $("#totalpayable").val(accounting.formatNumber(total+total1,2));

    }


    function msg(type, message){

    $("#msg_div p").html(message);
    $("#msg_div").attr("class","alert " + type);
    }

    function delRow(me){
    var td=me.parentNode;
    var tr=td.parentNode;
    var tBody=tr.parentNode;
    tBody.removeChild(tr);
    }

    function displaysItemDefaultValue(obj){
    $("#itemdes").val($("#itemComboList option:selected").attr("data-desc"));
    $("#itemunitprice").val(accounting.formatNumber($("#itemComboList option:selected").attr("data-price"),2));
    getLatestItemPrice();
    }
    function getLatestItemPrice(){
    $.ajax({
    type: "POST",
    data : {
    option :'purchase',
    itemID : $("#itemComboList").val(),
    datePrice : $("#createdDate").val(),
    supplierID : $("#supplier").val()
    },
    url: "<?php echo base_url() ?>aptransaction/getUmList",
    dataType:'JSON',
    success: function(data) {
    //console.log(data['unitPrice'][0].price);

    if(data['unitPrice']){
    $("#itemunitprice").val(accounting.formatNumber(data['unitPrice'][0].price,2));
    }

    var option = '<option value="'+data['items'][0].unitOfMeasureID+'"   data-baseUm="'+data['items'][0].unitOfMeasureID+'" data-unitm="1" data-factor="1" >'+data['items'][0].umCode+'</option>';
    if(data['umConv']){
    for(i = 0; i<data['umConv'].length; i++){
    option += '<option value="'+data['umConv'][i].from_um+'"  data-baseUm="'+data['umConv'][i].to_um+'" data-unitm="'+data['umConv'][i].unitm+'" data-factor="'+data['umConv'][i].factor+'" >'+data['umConv'][i].fromCode+'</option>';
    }
    }
    $('.umConvList').text('').append('<select class="umIDlist span12">'+
    option+
    '</select>');
    $('.umConvList select').select2();
    }
    });
    }

    function refreshItems(){
    $.ajax({
    type: "POST",
    url: "<?php echo base_url() ?>po_transaction/refreshItems",
    success: function(data) {

    var resul = eval ("(" + data + ")"); 
    var n=resul.records.length;
    var i=0;
    var opt='' +
    '<option></option>';
    for (i=0;i<n;i++)
    opt=opt + '<option data-price="'+ resul.records[i].price +'" data-description="' + resul.records[i].description + '" value="' + resul.records[i].id + '">' + resul.records[i].name + '[' + resul.records[i].code + ']' + '</option>';
    $('#itemComboList').empty();
    $('#itemComboList').append(opt);
    }
    });

    }


    function refreshLocation(){
    $.ajax({
    type: "POST",
    url: "<?php echo base_url() ?>purchasetransaction/refreshLocation",
    success: function(data) {

    var resul = eval ("(" + data + ")"); 
    var n=resul.records.length;
    var i=0;
    var opt='' +
    '<option></option>';
    for (i=0;i<n;i++)
    opt=opt + '<option value="' + resul.records[i].id +'">' + resul.records[i].location + '</option>';
    $('#location').empty();
    $('#location').append(opt);
    }
    });	
    }


    function addNewRowWithoutPo(me){
    if (!$("#itemComboList").length) {
    $('<tr><td class="span1">' + ($("#t_listItemNoPo").attr("data-currentRow")*1+1) + '</td>'+
    '<td class="span2" >' +
    '<select id="itemComboList" class="span10" onchange="displaysItemDefaultValue(this)"><option></option>' +
    <?php
    if ($items) {
        foreach ($items as $row) {
            ?>
            '<option data-desc= "<?php echo addslashes($row->description); ?>" data-price= "<?php echo $row->supplierPrice; ?>" \n\
            data-taxid="<?php echo $row->inputTaxID; ?>" data-taxcode="<?php echo $row->inputTaxCode; ?>" \n\
            data-taxPercentage="<?php echo $row->inputTaxPercentage; ?>" value="<?php echo $row->ID; ?>"><?php
            echo str_replace(array("\n", "\r", "'"), " ", $row->name, $count)
            . " [" . str_replace(array("\n", "\r", "'"), " ", $row->itemCode, $count) . "]";
            ?></option>'+
            <?php
        }
    }
    ?>
    '</select>' +
    '<div class="btn-group span1">' +
    '<button class="btn-icon btn-small dropdown-toggle" data-toggle="dropdown">' +
    '<span class="i-arrow-down-2"></span> </button> <ul class="dropdown-menu">' +
    '<li><a target="_blank" href="<?php echo base_url() ?>icsetting/itemNew">' +
    '<i class="i-plus-3"></i><?php echo $this->lang->line('addNewItem') ?></a></li>' +
    '<li><a href="#" onclick="refreshItems()"><i class="i-ccw"></i><?php echo $this->lang->line('refreshlist') ?></a>' +
    '</li> </ul></div></td>' +
    '<td class="span3"><input id="itemdes" name="itemdes" class="span12 validate[required]" type="text" placeholder="Description"></td>'+
    '<td class="span1"><input id="itemunitprice" onkeyup="calculamount()" name="itemunitprice" class="span12 validate[required,custom[number]] tar" type="text" placeholder="Unit Priece"></td>'+
    '<td class="span1 umConvList"></td>'+
    '<td class="span1"><input id="itemqte" onkeyup="calculamount()"  name="itemqte" class="span12 validate[required,custom[integer]] tar" type="text" placeholder="Qty"></td>'+
    '<td class="span1"><input id="itemAmount" name="itemAmount" onkeydown="return false;" class="span12 tar" type="text" placeholder="Amount (Include Tax)"></td>'+
    '<td class="span1 tac">'+
    '<button class="btn-icon btn-mini brn-success-form" onclick="saveItemReceiNoPo(this)" type="button"><i class="i-checkmark-3"></i></button>'+
    '<br /><button id="btnCancel" class="btn-icon btn-mini btn-danger-form" onclick="delRow(this)" type="button"><i class="i-cross"></i></button>'+
    '</td>'+
    '</tr>').insertBefore( "#trInfos" );
    $('#itemComboList').select2();


    }else{
    msg (1,"alert","Please, do save the current details before adding new one");
    }
    }

    function saveItemReceived(me){ 


    //$(me).parent().validationEngine('showPrompt', '*date field is required');
    //alert (jQuery( $(tr).find("td").eq(7).children("input:first-child")).valid());
    if ($("#receivedID").val()=="null"){ 
    //new 

    if($("#frmReceive").validationEngine('validate') && finanEngine('financhk')){
    var tr = $(me).parent().parent();


    var unitm = $(tr).find('select.umConv').select2().find(":selected").data('unitm');
    var factor = $(tr).find('select.umConv').select2().find(":selected").data('factor');
    var baseUm = $(tr).find('select.umConv').select2().find(":selected").data('baseum');
    var orderQty1 = accounting.unformat($(tr).find('td:nth-child(6)').text());
    orderQty = orderQty1 * factor;
    var rcvQty1 = accounting.unformat($(tr).find('td:nth-child(9) input').val());
    rcvQty = rcvQty1*factor;
    var totalPOrcv = parseFloat($(tr).find("td").eq(7).text());
    totalPOrcv = totalPOrcv+rcvQty1;

    var v =$(tr).find("td").eq(7).children("input:last-child").val();
    if (v<1 || v > ($(tr).find("td").eq(5).text()- $(tr).find("td").eq(7).text()) || isNaN($(tr).find("td").eq(8).children("input:last-child").val()*$(tr).find("td").eq(5).text()) ) {
    $(tr).find("td").eq(7).children("input:last-child").validationEngine('showPrompt', 'Qty received Incorrect');
    }else {

    var amount = (accounting.unformat($(tr).find("td").eq(3).text())/factor) * rcvQty;
    var datall = {
    supplierID : $("#supplier").val(),
    formNo : $("#formNo").val(),
    deliveryDate : $("#createdDate").val(),
    shippingMethodID : $("#shippingMdID").val(),
    supplierDoNo : $("#supplierDoNumber").val(),
    purchaseOrderID : $("#poList").val(),
    currencyID : $("#currency").attr("data-currencyid"),
    exchangeRate : $("#exchange_rate").val(),
    locationID : $("#location").val(),
    employeeID : $("#purchaser").val(),
    employeeID : $("#purchaser").val(),
    memo : $("#memo").val(),
    poDetailID : $(me).attr("data-podetailsid"),
    lineNo : $("#t_listItemOrdered").attr("data-currentRow")*1+1,
    itemID : $(tr).find("td").eq(0).attr("data-itemId"),
    quantityReceivedTotal : totalPOrcv,
    description : $(tr).find("td").eq(2).text(),
    umID : baseUm,
    standUM : $(tr).find('select.umConv').select2('val'),
    quantityOrder : orderQty,
    quantityReceived : rcvQty,
    unitPrice : accounting.unformat($(tr).find("td").eq(3).text())/factor,
    amount : amount//accounting.unformat($(tr).find("td").eq(5).text())

    };
    
    $(me).attr("disabled","disabled");
    $.ajax({
    type: "POST",
    data: datall,
    url: "<?php echo base_url() ?>receiveItems/saveNewItemReceived",
    success: function(data) {
    var resul = eval ("(" + data + ")"); 
    $("#receivedID").val(resul.receivedID);

    $("#poList").attr('disabled','disabled');
    $("#supplier").attr('disabled','disabled');
    $("#t_listItemOrdered").attr("data-currentRow",$("#t_listItemOrdered").attr("data-currentRow")*1+1);
    msg(2,"alert alert-success","Data saved successfully !!!");
    var tr = $(me).parent().parent();
    $(''+
    '<tr>' +
    '<td>' + $("#t_listItemOrdered").attr("data-currentRow")  + '</td>'+
    '<td>' +  $(tr).find("td").eq(1).text()  + '</td>'+
    '<td>' +  $(tr).find("td").eq(2).text()  + '</td>'+
    '<td class="amount">' +  accounting.formatNumber($(tr).find("td").eq(3).text(),2)  + '</td>'+
    '<td >' +$(tr).find(".umConv").select2('data').text+ '</td>'+
    '<td class="tar">' + $(tr).find("td").eq(8).children("input:last-child").val() + '</td>'+
    '<td class="amount">' +  accounting.formatNumber(amount,2) + '</td>'+
    '<td>'+
    '</td>'+
    '</tr>'
    ).insertBefore( "#trInfos1" );
    delRow (me);
    getTotal ();
    }
    });
    }
    }


    }else{
    // save detail only
    var tr = $(me).parent().parent();
    var v =$(tr).find("td").eq(7).children("input:last-child").val();
    if (v<1 || v > ($(tr).find("td").eq(5).text()- $(tr).find("td").eq(7).text()) || isNaN($(tr).find("td").eq(8).children("input:last-child").val()*$(tr).find("td").eq(5).text()) ) {
    $(tr).find("td").eq(7).children("input:last-child").validationEngine('showPrompt', 'Qty received Incorrect');
    }else {
    var unitm = $(tr).find('select.umConv').select2().find(":selected").data('unitm');
    var factor = $(tr).find('select.umConv').select2().find(":selected").data('factor');
    var baseUm = $(tr).find('select.umConv').select2().find(":selected").data('baseum');
    var orderQty1 = accounting.unformat($(tr).find('td:nth-child(6)').text());
    orderQty = orderQty1 * factor;
    var rcvQty1 = accounting.unformat($(tr).find('td:nth-child(9) input').val());
    rcvQty = rcvQty1*factor;
    var totalPOrcv = accounting.unformat($(tr).find("td").eq(7).text());
    totalPOrcv = totalPOrcv+rcvQty1;

    var amount = (accounting.unformat($(tr).find("td").eq(3).text())/factor) * rcvQty;
    var detail = {
    receiveID : $("#receivedID").val(),
    poDetailID : $(me).attr("data-podetailsid"),
    itemID : $(tr).find("td").eq(0).attr("data-itemId"),
    lineNo : $("#t_listItemOrdered").attr("data-currentRow")*1+1,
    quantityReceivedTotal : totalPOrcv,
    description : $(tr).find("td").eq(2).text(),
    umID : baseUm,
    standUM : $(tr).find('select.umConv').select2('val'),
    quantityOrder : orderQty,
    quantityReceived : rcvQty,
    unitPrice : accounting.unformat($(tr).find("td").eq(3).text())/factor,
    amount : amount//accounting.unformat($(tr).find("td").eq(5).text())
    };
    $(me).attr("disabled","disabled");
    $.ajax({
    type: "POST",
    data: detail,
    url: "<?php echo base_url() ?>receiveItems/saveNewItemDetailOnly",
    success: function(data) {
    var resul = eval ("(" + data + ")"); 
    $("#poList").attr('disabled','disabled');
    $("#supplier").attr('disabled','disabled');
    msg("alert alert-success","Data saved successfully !!!")
    var tr = $(me).parent().parent();
    $(''+
    '<tr>' +
    '<td>' + $("#t_listItemOrdered").attr("data-currentRow")  + '</td>'+
    '<td>' +  $(tr).find("td").eq(1).text()  + '</td>'+
    '<td>' +  $(tr).find("td").eq(2).text()  + '</td>'+
    '<td class="amount">' +  accounting.formatNumber($(tr).find("td").eq(3).text(),2)  + '</td>'+
    '<td >' +$(tr).find(".umConv").select2('data').text+ '</td>'+
    '<td class="tar">' + $(tr).find("td").eq(8).children("input:last-child").val() + '</td>'+
    '<td class="amount">' +  accounting.formatNumber(amount,2) + '</td>'+
    '<td>'+
    '</td>'+
    '</tr>'
    ).insertBefore( "#trInfos1" );
    delRow (me);
    getTotal ();
    }
    });
    }
    }



    }

    function getPoItems(me){
    $('#outstandingItems tbody').empty();
    $.ajax({
    type: "POST",
    data: {
    poId : $("#poList").select2('val')
    },
    url: "<?php echo base_url() ?>receiveItems/getPoItemList",
    dataType: 'JSON',
    success: function(poData) {
    console.log(poData);
    if(poData['poList']){	 	
    //var resul = eval ("(" + data + ")"); 
    var data = poData['poList'];
    var n=data.length;
    var tcontent = "";
    for (i=0;i<n;i++) {
    var umConv = '';
    var flag = false;
    //console.log(poData['umConv'][data[i].itemID].length);
    if(poData['umConv'][data[i].itemID]){
    for(j = 0; j<poData['umConv'][data[i].itemID].length; j++){
    var selected = '';
    if(poData['umConv'][data[i].itemID][j].from_um == data[i].dfltumID){
    selected = 'selected="selected"';
    flag = true;
    }
    umConv = umConv + '<option value="'+poData['umConv'][data[i].itemID][j].from_um+'" data-baseUm="'+poData['umConv'][data[i].itemID][j].to_um+'" data-unitm="'+poData['umConv'][data[i].itemID][j].unitm+'" data-factor="'+poData['umConv'][data[i].itemID][j].factor+'" '+selected+'>'+
    poData['umConv'][data[i].itemID][j].fromCode+
    '</option>';
    }
    }
    if(!flag)
    umConv = umConv + '<option value="'+data[i].umID+'" data-baseUm="'+data[i].umID+'" data-unitm="1" data-factor="1" selected="selected">'+data[i].umCode+'</option>';
    else
    umConv = umConv + '<option value="'+data[i].umID+'" data-baseUm="'+data[i].umID+'" data-unitm="1" data-factor="1">'+data[i].umCode+'</option>';


    tcontent=tcontent + '<tr><td class="span1" data-itemId="'+ data[i].itemID +'">' + data[i].lineNo + '</td>' + 
    '<td class="span2">' + data[i].itemName+ '[' + data[i].itemCodee + ']' + '</td>' + 
    '<td class="span2">' + data[i].description + '</td>' + 
    '<td class="span1 tar">' + accounting.formatNumber(data[i].unitPrice,2) + '</td>' + 
    '<td class="span1 tar">'+
    '<select class="umConv span12 tac" disabled="disabled">'+
    umConv+
    '</select>'+
    '</td>' + 
    '<td class="span1 tar">' + data[i].quantityOrder + '</td>' + 
    '<td class="span1 tar">' + accounting.formatNumber((data[i].unitPrice*data[i].quantityOrder),2) + '</td>' + 
    '<td class="span1 tar">' + data[i].quantityReceivedTotal + '</td>' + 
    '<td class="span1 "><input placeholder="R.:' + (data[i].quantityOrder-data[i].quantityReceivedTotal)  +'" name="" onfocus="checkBalance(this)" class="span12 validate[custom[integer], min[1], max[' + (data[i].quantityOrder-data[i].quantityReceivedTotal) +'] ]" type="text"/></td>' + 
    '<td class="span1"><button type="button" onclick="saveItemReceived(this)" data-poDetailsId="'+ data[i].poDetailID  +'" class="btn-icon btn-mini btn-success-form"><i class="i-checkmark-3"></i></button></td></tr>';

    //$('#exchange_rate').val(accounting.formatNumber(data[i].exChangeRate,5));
    }

    $('#outstandingItems tbody').append(tcontent);
    $('.umConv').select2();
    //$('.umConv').select2('val',data[i].umID);
    }
    }

    });	
    }

    function checkBalance(me){
    var itemID = $(me).parents('tr').find('td:nth-child(1)').attr('data-itemid');
    var poID = $("#poList").select2('val');
    console.log(poID+"<->"+itemID);
    $.ajax({
    type: "POST",
    data: {
    poId : $("#poList").select2('val'),
    itemId: itemID
    },
    url: "<?php echo base_url() ?>receiveItems/checkCurBal",
    dataType: 'JSON',
    success: function(poData){
    if(poData){
    var parentTr = $(me).parents('tr');
    $(me).attr('placeholder','R.:' + poData).removeClass().addClass('sam span12 validate[custom[integer], min[1], max[' + poData +'] ]');//" name="" onfocus="checkBalance(this)" class="span12 validate[custom[integer], min[1], max[' + poData +'] ]" type="text"/>');				

    parentTr.find('td:nth-child(8)').html(accounting.unformat(parentTr.find('td:nth-child(6)').html())-poData);
    //parentTD.find('input').focus();
    }
    }
    });
    }

    function displayLocationAdress(){
    $("#locationAdress").text($("#location option:selected").attr("data-locationadress"));
    }

    /*
    function getItemDetails(me){
    $("#itemname").val("");
    $("#itemdes").val("");
    $.ajax({
    type: "POST",
    data: "code="+ me.value,
    url: "<?php echo base_url() ?>purchasetransaction/getItemDetails",
    success: function(data) {
    if(data!="item Not found"){
    var resul = eval ("(" + data + ")");
    $("#itemname").val(resul.description);
    $("#itemdes").val(resul.name);
    }else{
    $("#itemdes").attr("placeholder",data);
    $("#itemname").attr("placeholder",data);				  }
    }
    });
    }
    */

    function saveItemReceiNoPo(me){
    if ($("#receivedID").val()=="null"){ 
    //new 
    if($("#frmReceive").validationEngine('validate') && finanEngine('financhk')){
    var tr = $(me).parent().parent();
    var unitm = $(tr).find('select.umIDlist').select2().find(":selected").data('unitm');
    var factor = $(tr).find('select.umIDlist').select2().find(":selected").data('factor');
    var baseUm = $(tr).find('select.umIDlist').select2().find(":selected").data('baseum');
    var rcvQty1 = accounting.unformat($(tr).find('td:nth-child(6) input').val());
    rcvQty = rcvQty1*factor;
    //console.log(accounting.unformat($("#itemunitprice").val())/factor+"<->"+rcvQty+"<->"+unitm+"<->"+factor);
    var v =$(tr).find("td").eq(7).children("input:last-child").val();

    var detail = {						  
    supplierID : $("#supplier").val(),
    formNo : $("#formNo").val(),
    deliveryDate : $("#createdDate").val(),
    shippingMethodID : $("#shippingMdID").val(),
    supplierDoNo : $("#supplierDoNumber").val(),
    currencyID : $("#currency").attr("data-currencyid"),
    exchangeRate : $("#exchange_rate").val(),
    purchaseOrderID : "-1",
    locationID : $("#location").val(),
    employeeID : $("#purchaser").val(),
    memo : $("#memo").val(),
    poDetailID : "-1",
    itemID : $("#itemComboList").val(),
    lineNo :$("#t_listItemNoPo").attr("data-currentRow")*1+1,
    quantityReceivedTotal : "0",
    quantityOrder : "0",
    description : $("#itemdes").val(),
    quantityReceived : rcvQty,
    unitPrice : accounting.unformat($("#itemunitprice").val())/factor,
    umID : baseUm,
    standUM : $(tr).find('select.umIDlist').select2('val'),
    amount : accounting.unformat($("#itemAmount").val())				
    };
    
    $(me).attr("disabled","disabled");
    $.ajax({
    type: "POST",
    data: detail,
    url: "<?php echo base_url() ?>receiveItems/saveNewItemReceived",
    success: function(data) {
    var resul = eval ("(" + data + ")"); 
    $("#receivedID").val(resul.receivedID);
    $("#poList").attr('disabled','disabled');
    $("#supplier").attr('disabled','disabled');
    msg("alert alert-success","Data saved successfully !!!")
    var tr = $(me).parent().parent();
    $(''+
    '<tr>' +
    '<td>' +  ($("#t_listItemNoPo").attr("data-currentRow")*1+1)  + '</td>'+
    '<td>' +  $("#itemComboList option:selected").text() + '</td>'+
    '<td>' +  $("#itemdes").val()  + '</td>'+
    '<td class="amount">' +  accounting.formatNumber($("#itemunitprice").val(),2) + '</td>'+
    '<td >' +$(tr).find(".umIDlist").select2('data').text+ '</td>'+
    '<td class="amount">' + $("#itemqte").val() + '</td>'+
    '<td class="amount">' +  accounting.formatNumber($("#itemAmount").val(),2) + '</td>'+
    '<td>'+
    '</td>'+
    '</tr>').insertBefore( "#trInfos" );
    $("#t_listItemNoPo").attr("data-currentRow",$("#t_listItemNoPo").attr("data-currentRow")*1+1)
    delRow (me);
    getTotal ();
    }
    });
    }


    }else{
    // save detail only
    var tr = $(me).parent().parent();
    var tr = $(me).parent().parent();
    var unitm = $(tr).find('select.umIDlist').select2().find(":selected").data('unitm');
    var factor = $(tr).find('select.umIDlist').select2().find(":selected").data('factor');
    var baseUm = $(tr).find('select.umIDlist').select2().find(":selected").data('baseum');
    var rcvQty1 = accounting.unformat($(tr).find('td:nth-child(6) input').val());
    rcvQty = rcvQty1*factor;
    
    $(me).attr("disabled","disabled");
    $.ajax({
    type: "POST",
    data: {
    receiveID : $("#receivedID").val(),
    poDetailID : "-1",
    itemID : $("#itemComboList").val(),
    lineNo :$("#t_listItemNoPo").attr("data-currentRow")*1+1,
    quantityReceivedTotal : "0",
    quantityOrder : "0",
    description : $("#itemdes").val(),
    quantityReceived : rcvQty,
    unitPrice : accounting.unformat($("#itemunitprice").val())/factor,
    umID : baseUm,
    standUM : $(tr).find('select.umIDlist').select2('val'),
    amount : accounting.unformat($("#itemAmount").val())			  
    },
    url: "<?php echo base_url() ?>receiveItems/saveNewItemDetailOnly",
    success: function(data) {
    var resul = eval ("(" + data + ")"); 
    $("#poList").attr('disabled','disabled');
    $("#supplier").attr('disabled','disabled');
    msg("alert alert-success","Data saved successfully !!!")
    var tr = $(me).parent().parent();
    $(''+
    '<tr>' +
    '<td>' +  ($("#t_listItemNoPo").attr("data-currentRow")*1+1)  + '</td>'+
    '<td>' +  $("#itemComboList option:selected").text() + '</td>'+
    '<td>' +  $("#itemdes").val()  + '</td>'+
    '<td class="amount">' +  accounting.formatNumber($("#itemunitprice").val(),2) + '</td>'+
    '<td >' +$(tr).find(".umIDlist").select2('data').text+ '</td>'+
    '<td class="amount">' + $("#itemqte").val() + '</td>'+
    '<td class="amount">' +  accounting.formatNumber($("#itemAmount").val(),2) + '</td>'+
    '<td>'+
    '</td>'+
    '</tr>').insertBefore( "#trInfos" );
    $("#t_listItemNoPo").attr("data-currentRow",$("#t_listItemNoPo").attr("data-currentRow")*1+1)
    delRow (me);
    getTotal ();
    }
    });
    }


    }
    function shipMethodSelect(){
    $.ajax({
    type: "POST",
    url: "<?php echo base_url() ?>setting/refreshShippingMethod",
    success: function(data) {

    var resul = eval ("(" + data + ")"); 
    var n=resul.records.length;
    var i=0;
    var opt='' +
    '<option></option>';
    for (i=0;i<n;i++)
    opt=opt + '<option value="' + resul.records[i].id +'">' + resul.records[i].name + '</option>';
    $('#shippingMdID').empty();
    $('#shippingMdID').append(opt);
    }
    });		
    }

    function refreshpurchaserlist(){
    $.ajax({
    type: "POST",
    url: "<?php echo base_url() ?>employeeSetup/refreshEmployee",
    success: function(data) {

    var resul = eval ("(" + data + ")"); 
    var n=resul.records.length;
    var i=0;
    var opt='' +
    '<option></option>';
    for (i=0;i<n;i++)
    opt=opt + '<option value="' + resul.records[i].id +'">' + resul.records[i].employeeName + '</option>';
    $('#purchaser').empty();
    $('#purchaser').append(opt);
    }
    });	
    }
</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() . "home" ?>'><?php echo $this->lang->line('dashboard') ?></a> <span class="divider">-</span></li>
                    <li><a href='<?php echo base_url() . "AccountPayables/home" ?>'> <?php echo $this->lang->line('module') ?></a> <span class="divider">-</span></li>
                    <li class="active"><?php echo $this->lang->line('titlepo_received') ?></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" id="grid_content_1">
                <form id="frmReceive" action="#"> 
                     <input type="hidden" id="receivedID" value="null"/>
                <div class="block">
                    <div class="head">
                        <h2><strong><?php echo $this->lang->line('titlepo_received') ?></strong></h2>
                    </div><!-- head -->
                    <div class="content np">
                        <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('supplier') ?></div>
                                        <div class="span8">
                                            <div class="span12">
                                                <select class="span10 validate[required]" id="supplier" onchange="loadSupplierDefaultValue(this)">
                                                    <option></option>
                                                    <?php
                                                    if ($supplier) {
                                                        foreach ($supplier as $row) {
                                                            ?>
                                                            <option value="<?php echo $row->ID; ?>"> <?php echo $row->supplierName;
                                                    echo ($row->gstRegNo && $row->gstRegNo != '0') ? ' (GST)' : ''; ?></option>
    <?php }
} ?>
                                                </select>
                                                <div class="btn-group span1">
                                                    <button class="btn-icon btn-small dropdown-toggle" data-toggle="dropdown">
                                                        <span class="i-arrow-down-2"></span>
                                                    </button>
                                                    <ul class="dropdown-menu">
                                                        <!-- dropdown menu links -->
                                                        <li><a target="_blank" href="<?php echo base_url() ?>supplier/SupplierNew"  id="btnNewSupplier">
                                                                <i class="i-plus-3"></i> <?php echo $this->lang->line('addNewSupplier') ?></a></li>
                                                        <li><a href="#" onclick="refreshSupplier()" id="btnNewSupplier">
                                                                <i class="i-ccw"></i><?php echo $this->lang->line('refreshlist') ?></a></li>
                                                    </ul>
                                                </div>
                                            </div>
                                        </div>
                                    </div> <!-- row -->
                                   
                                    <div class="controls-row">
                                        <div class="span4"><?php echo $this->lang->line('formNo') ?></div>
                                        <div class="span5">
                                            <input class="span12 validate[required]" id="formNo" name="formNo" value='<?php echo "$formNo"; ?>' style="color:red;"   type="text" placeholder="Form number ...">
                                        </div>
                                        <div class="span3">
                                            <input  class="span12"   type="text" placeholder="Serial" disabled="disabled">
                                        </div>
                                    </div> <!-- row -->
                                    <div class="controls-row">
                                        <div class="span4"><?php echo $this->lang->line('date') ?></div>
                                        <div class="span8">
                                            <div class="input-prepend span12">
                                                <span class="add-on span2"><i class="i-calendar"></i></span>
                                                <?php
                                                $data = array(
                                                    'name' => 'createdDate',
                                                    'id' => 'createdDate',
                                                    'type' => 'text',
                                                    'onkeydown' => 'return false',
                                                    'class' => 'span10 datepicker2 validate[required] financhk',);
                                                echo form_input($data, date("d-m-Y"));
                                                ?>
                                            </div>
                                        </div>
                                    </div> <!-- row -->
                                    <div class="controls-row">
                                        <div class="span4"><?php echo $this->lang->line('supplierDoNumber') ?></div>
                                        <div class="span8">
                                            <input id="supplierDoNumber" class="span12" type="text" placeholder="Supplier DO Number">
                                        </div><!-- span -->
                                    </div> <!-- row -->
                                    
                                    <div class="controls-row">
                                <div class="span4" data-currentRow="0"><?php echo $this->lang->line('purchaser') ?></div>
                                <div class="span8">
                                    <div class="span12">


                                        <input type="hidden" id="purchaseInvoiceId" value="null"/>
                                        <select class="span10" id="purchaser">
                                            <option></option>
                                            <?php
                                            if ($purchaser) {
                                                foreach ($purchaser as $row) {
                                                    ?>
                                                    <option value="<?php echo $row->ID; ?>"> <?php echo $row->employeeName; ?></option>
    <?php }
} ?>
                                        </select>
                                        <div class="span1 btn-group">
                                            <button class="btn-icon btn-small dropdown-toggle" data-toggle="dropdown">
                                                <span class="i-arrow-down-2"></span>
                                            </button>
                                            <ul class="dropdown-menu">
                                                <!-- dropdown menu links -->
                                                <li><a target="_blank" href="<?php echo base_url() ?>employeeSetup/EmployeeNew"  id="EmployeeNew">
                                                        <i class="i-plus-3"></i> <?php echo $this->lang->line('newpurchaser') ?></a></li>
                                                <li><a href="javascript:" onclick="refreshpurchaserlist()" id="btnNewSupplier">
                                                        <i class="i-ccw "></i><?php echo $this->lang->line('refreshlist') ?></a></li>
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                            </div><!-- row control -->
                            
                                </div><!-- grid block 1-->
                            </div><!-- scCol -->
                            <div class="span6 scCol">
                                <div class="block" id="grid_block_2">
                                    <div class="controls-row">
                                        <div class="controls-row">
                                            <div class="span4"><?php echo $this->lang->line('poList') ?></div>
                                            <div class="span8">
                                                <div class="span12">
                                                    <select id="poList" onchange="getPoItems(this)" class="span11 validate[required]">
                                                        <option></option>
                                                    </select>

                                                </div><!-- append -->
                                            </div><!-- span -->

                                        </div><!-- row control -->
                                        
                                        <div class="controls-row">
                                <div class="span4"><?php echo $this->lang->line('shippingmethod') ?></div>
                                <div class="span8">
                                    <div class="span12">
                                        <select id="shippingMdID"  class="span10">
                                            <option></option>
                                            <?php
                                            if ($shippingmethod) {
                                                foreach ($shippingmethod as $row) {
                                                    ?>
                                                    <option value="<?php echo $row->ID; ?>"><?php echo $row->name; ?></option>
    <?php }
} ?>
                                        </select>
                                        <div class="btn-group span1">
                                            <button class="btn-icon btn-small dropdown-toggle" data-toggle="dropdown">
                                                <span class="i-arrow-down-2"></span>
                                            </button>
                                            <ul class="dropdown-menu">
                                                <!-- dropdown menu links -->
                                                <li><a target="_blank" href="<?php echo base_url() ?>setting/masterCodeSetup"  id="btnNewShipMethod">
                                                        <i class="i-plus-3"></i> <?php echo $this->lang->line('newShipMethod') ?></a></li>
                                                <li><a href="javascript:" onclick="shipMethodSelect()"><i class="i-ccw"></i> <?php echo $this->lang->line('refreshlist') ?></a></li>
                                            </ul>
                                        </div><!-- btn group -->
                                    </div><!-- append -->
                                </div><!-- span -->

                            </div><!-- row control -->
                            
                                        <div class="controls-row">
                                            <div class="span4"><?php echo $this->lang->line('location') ?></div>
                                            <div class="span8">
                                                <div class="span12">
                                                    <select onchange="displayLocationAdress()" class="span10 validate[required]" id="location">
                                                        <option></option>
                                                        <?php
                                                        if ($location) {
                                                            foreach ($location as $row) {
                                                                ?>
                                                                <option data-locationadress="<?php echo $row->address; ?>" value="<?php echo $row->fldid; ?>">
        <?php echo $row->code . " | " . $row->desc; ?></option>
    <?php }
} ?>
                                                    </select>
                                                    <div class="span1 btn-group">
                                                        <button class="btn-icon btn-small dropdown-toggle" data-toggle="dropdown">
                                                            <span class="i-arrow-down-2"></span>
                                                        </button>
                                                        <ul class="dropdown-menu">
                                                            <!-- dropdown menu links -->
                                                            <li><a target="_blank" href="<?php echo base_url() ?>ItemSetup/locationlist"  id="btnLocation">
                                                                    <i class="i-plus-3"></i><?php echo $this->lang->line('addLocation') ?></a></li>
                                                            <li><a href="#" onclick="refreshLocation()"><i class="i-ccw"></i><?php echo $this->lang->line('refreshlist') ?></a></li>
                                                        </ul>
                                                    </div>
                                                </div> <!-- btnn group -->
                                            </div>
                                        </div> <!-- control -->

                                        <div class="controls-row">
                                            <div class="span4"><?php echo $this->lang->line('currency') ?></div>
                                            <div class="span8">
                                                <input id="currency" name="currency" type="text" placeholder="Currency" disabled class="span12">            
                                            </div><!-- span -->
                                        </div><!-- control row -->
                                        <div class="controls-row">
                                            <div class="span4"><?php echo $this->lang->line('exchangeRate') ?></div>
                                            <div class="span8">
                                                <input class="span12 validate[required] tar" id="exchange_rate" name="exchange_rate" type="text" placeholder="Example: 3.20000" >           
                                            </div><!-- span -->
                                        </div><!-- control row -->
                                    </div><!-- content -->
                                </div><!-- content -->
                            </div><!-- grid block 1-->
                        </div><!-- scCol -->
                    </div>
                </div>
 <div class="row-fluid scRow">                            
                    <div class="span12 scCol">
                        <textarea style="margin-top:10px;" id="memo" class="span12" placeholder="Memo"></textarea>
                        </div>
                </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('outstandingPo') ?></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="outstandingItems" cellpadding="0" cellspacing="0" width="100%">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th><?php echo $this->lang->line('item') ?></th>
                                        <th><?php echo $this->lang->line('itemDesc') ?></th>
                                        <th class="tar"><?php echo $this->lang->line('unitPrice') ?></th>
                                        <th class="tal"><?php echo $this->lang->line('um') ?></th>
                                        <th class="tar"><?php echo $this->lang->line('qtyOrder') ?></th>
                                        <th class="tar"><?php echo $this->lang->line('amount') ?></th>
                                        <th class="tar"><?php echo $this->lang->line('totalQtyReceive') ?></th>
                                        <th class="tar"><?php echo $this->lang->line('qtyReceive') ?></th>
                                        <th><?php echo $this->lang->line('action') ?></th>
                                    </tr>
                                </thead>
                                <tbody>

                                </tbody>
                            </table>
                            <div class="footer">
                                <div class="side fr">
                                    <div class="btn-group">
                                        <button style="margin-right:6px;" onclick="$('#frmReceive').validationEngine('hide');" class="btn-form btn-warning-form" type="button" name="validat">Hide prompts</button>

                                    </div><!-- btn group -->      
                                </div><!-- side fr -->      
                            </div><!-- footer -->      
                        </div><!-- content -->
                    </div><!-- grid block 1-->
                </div><!-- scCol -->
            </div><!-- row-fluid scRow-->
            
            <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('receivedItems') ?></h2>
                            <ul class="buttons">
                                <li><a class="block_toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseTwo">
                                        <span class="i-arrow-down-3"></span></a></li>
                            </ul>                                        
                        </div><!-- head -->
                        <div class="content np">
                            <table data-currentRow="0" id="t_listItemOrdered" cellpadding="0" cellspacing="0" width="100%">
                                <thead>
                                    <tr> <th>#</th>
                                        <th><?php echo $this->lang->line('items') ?></th>
                                        <th><?php echo $this->lang->line('itemDesc') ?></th>
                                        <th class="tar"><?php echo $this->lang->line('unitPrice') ?></th>
                                        <th class="tal"><?php echo $this->lang->line('um') ?></th>
                                        <th class="tar"><?php echo $this->lang->line('qtyReceive') ?></th>
                                        <th class="tar"><?php echo $this->lang->line('amount') ?></th>
                                        <th><?php echo $this->lang->line('action') ?></th>
                                    </tr>
                                </thead>
                                <tbody>

                                    <tr id="trInfos1">
                                        <td colspan="8">
                                            <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><!-- content -->

                    </div><!-- grid block 1-->
                </div><!-- scCol -->
            </div><!-- row-fluid scRow-->

            <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('receivedItemsNoPo') ?></h2>
                            <ul class="buttons">
                                <li><a class="block_toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseTwo">
                                        <span class="i-arrow-down-3"></span></a></li>
                            </ul>                                        
                        </div><!-- head -->
                        <div class="content np">

                            <table data-currentRow="0" id="t_listItemNoPo" cellpadding="0" cellspacing="0" width="100%">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th><?php echo $this->lang->line('item') ?></th>
                                        <th><?php echo $this->lang->line('itemDesc') ?></th>
                                        <th class="tar"><?php echo $this->lang->line('unitPrice') ?></th>
                                        <th class="tal"><?php echo $this->lang->line('um') ?></th>
                                        <th class="tar"><?php echo $this->lang->line('qtyReceive') ?></th>
                                        <th class="tar"><?php echo $this->lang->line('amount') ?></th>
                                        <th class="tac"><?php echo $this->lang->line('action') ?></th>
                                    </tr>
                                </thead>
                                <tbody>

                                    <tr data-currentRow="0"  id="trInfos">
                                        <td colspan="8">
                                            <div id="msg_div2" 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 id="addRow" onclick="addNewRowWithoutPo()" class="btn-form btn-warning-form" type="button">
                                            <i class="i-plus-2"></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="row-fluid scRow">
                <div class="span7 scCol">
                    <div class="block" id="grid_block_4">
                        <div class="content np">
                            
                        </div>    
                    </div><!-- grid block 1-->
                </div><!-- scCol -->                          
                <div class="span5 scCol">
                    <div class="block" id="grid_block_4">
                        <div class="content np">

                            

                            <div class="controls-row">
                                <div class="span4"><?php echo $this->lang->line('totalPayable') ?></div>
                                <div class="span8">
                                    <input id="totalpayable" disabled="disabled"  class="span12 amount" type="text" placeholder="0">
                                </div>
                            </div><!-- row control -->
                        </div>    
                    </div><!-- grid block 1-->
                </div><!-- scCol -->
            </div><!-- row-fluid scRow-->
        </form>   
    </div><!-- grid 1 -->
    </div>
</div><!-- wrap -->




