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

    .quantity {
        text-align: center;
    }

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


    .input-prepend span, input-prepend button{
        height:18px;
        padding:3px;
    }
    #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 td {
        font-size:11px;
    }
    #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>
    $(document).ready(function(){

    $('select').select2();
            jQuery('.datepicker2').datepicker({
    dateFormat : 'dd-mm-yy',
            changeMonth : true,
            changeYear : true
    });
    }
    );
            /*  window.onbeforeunload = function (e) {
             if (accounting.unformat( $('#outofbalance').val() ) !== 0 ){
             var message = "The out of balance is different of zero, Confirm leave ",
             e = e || window.event;
             // For IE and Firefox
             if (e) {
             e.returnValue = message;
             }
             
             // For Safari
             return message;
             }
             };
             */
                    function getLatestItemPrice(){
                    $.ajax({
                    type: "POST",
                            data : {
                            option :'purchase',
                                    itemID : $("#itemComboList").val(),
                                    datePrice : $("#createdDate").val(),
                                    supplierID : - 1
                            },
                            url: "<?php echo base_url() ?>aptransaction/getPrice",
                            success: function(data) {
                            $("#itemunitprice").val(accounting.formatNumber(data, 2));
                            }
                    });
                            }

            $(document).ready(function(){
            calculOutOfBalance();
            });
                    function taxPopup () {
                    $('#popupModal').modal('show');
                            $("#_popupTitle").html("Purchase Invoice");
                            $("#_popupContent").html('' +
                            '<label>Select a tax</label>' +
                            '<select style="width:100%;" onclick="calculamount()" name="listTaxPopup" id="listTaxPopup"  class= "validate[required]">' +
<?php
if ($taxmaster) {
    foreach ($taxmaster as $row2) {
        ?>
                            '<option data-taxcode="<?php echo $row2->code ?>" value="<?php echo $row2->ID; ?>" data-tax="' + <?php echo $row2->taxPercentage; ?> + '">' +
                                    '<?php echo $row2->code . " | " . $row2->taxPercentage . " | ";
        echo str_replace(array("\n", "\r", "'"), " ", $row2->name, $count);
        ?></option>' +
    <?php }
}
?>
                    '</select>');
                            $("#listTaxPopup").select2();
                            $('#_popupFooter').empty();
                            $('#_popupFooter').append('<button type="button" class="btn-form btn-success-form" id="confButton">Ok</button>' +
                            '<button type="button" class="btn-form btn-danger-form" id="canb">Cancel</button>');
                            $("#_popupTitle").html("Tax Master");
                            $("#canb").click(function() {
                    $('#popupModal').modal('hide');
                    });
                            $("#confButton").click(function() {
                    $('#popupModal').modal('hide');
                            $("#itemTax").attr("data-taxid", $("#listTaxPopup").val());
                            $("#itemTax").val ($("#listTaxPopup option:selected").attr("data-tax"));
                            $("#displayTaxCode").html($("#listTaxPopup option:selected").attr("data-taxcode"));
                            calculamount();
                    });
                    }

            function getItemDetails(me){
            $("#itemname").val("");
                    $("#itemdes").val("");
                    $.ajax({
                    type: "POST",
                            data: "code=" + me.value,
                            url: "<?php echo base_url() ?>OthersPayment/getItemDetails",
                            success: function(data) {
                            if ($.trim(data) != "item Not found"){
                            var resul = eval ("(" + data + ")");
                                    $("#itemcode").attr("itemID", resul.itemID);
                                    $("#itemname").val(resul.name);
                                    $("#itemdes").val(resul.description);
                                    $("#itemTax").val(resul.tax);
                                    $("#itemTax").attr("data-taxid", resul.taxID);
                                    $("#displayTaxCode").text(resul.taxcode);
                            } else{
                            $("#itemcode").attr("itemID", ""),
                                    $("#itemdes").attr("placeholder", data);
                                    $("#itemname").attr("placeholder", data);
                                    $("#itemTax").attr("data-taxid", "")
                                    $("#itemTax").val("");
                                    $("#itemTaxAmount").val("");
                                    $("#itemAmountIT").val("");
                                    $("#itemTax").attr("data-taxid", "");
                                    $("#displayTaxCode").html("");
                            }
                            }
                    });
            }

            function editRow(me){

            if (!$("#itemComboList").length) {
            var tr = $(me).parent().parent();
                    $(tr).replaceWith('<tr>' +
                    '<td class="span1">' + $(me).parent().parent().find("td").eq(0).html() + '</td>' +
                    '<td class="span1" >' +
                    '<select class="span10" data-lineNo="' + $(me).parent().parent().find("td").eq(0).html() + '" data-previewvalue="' + $(me).parent().parent().find("td").eq(1).html() + '" id="itemComboList" class="span10" onchange="displaysItemDefaultValue()"><option></option>' +
<?php
if ($items) {
    foreach ($items as $row) {
        ?>
                    '<option data-umCode ="<?php echo str_replace(array("\n", "\r", "'"), " ", $row->umCode, $count) ?>" data-umid ="<?php echo str_replace(array("\n", "\r", "'"), " ", $row->unitOfMeasureID, $count) ?>" data-desc= "<?php echo str_replace(array("\n", "\r", "'"), " ", $row->description, $count); ?>" 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 type="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="icon-plus-sign"></i><?php echo $this->lang->line('addNewItem') ?></a></li>' +
                    '<li><a href="#" onclick="refreshItems()"><i class="icon-refresh"></i><?php echo $this->lang->line('refreshlist') ?></a>' +
                    '</li> </ul></div></td>' +
                    '<td class="span2"><input id="itemdes" name="itemdes" class="span12" type="text" data-previewvalue="' + $(me).parent().parent().find("td").eq(2).html() + '" value="' + $(me).parent().parent().find("td").eq(2).html() + '"></td>' +
                    '<td class="span1"><select onchange="getLatestItemPrice()" data-previewvalue="' + $(me).parent().parent().find("td").eq(3).html() + '" id="idUnitOfMeasure" class="span12 validate[required]"><option></option></select></td>' +
                    '<td class="span1"><input id="itemqte"  onkeyup="calculamount()" onchange="calculamount()" name="itemqte"  class="span12" type="text" data-previewvalue="' + $(me).parent().parent().find("td").eq(4).html() + '" value="' + $(me).parent().parent().find("td").eq(4).html() + '"></td>' +
                    '<td class="span1"><input  id="itemunitprice" onkeyup="calculamount()" onchange="calculamount()" name="itemunitprice" class="span12" type="text" data-previewvalue="' + $(me).parent().parent().find("td").eq(5).html() + '" value="' + $(me).parent().parent().find("td").eq(5).html() + '"></td>' +
                    '<td class="span1"> <input id="itemAmountET" disabled name="itemAmountET" class="span12" type="text" data-previewvalue="' + $(me).parent().parent().find("td").eq(6).html() + '" value="' + $(me).parent().parent().find("td").eq(6).html() + '"></td>' +
                    '<td class="span1"><div  class="span12 input-prepend"><input data-previewvalue= "' + $(me).attr("data-taxcode") + ' | ' + $(me).attr("data-taxrate") + '"  value="' + $(me).attr("data-taxrate") + '" data-taxid="' + $(me).attr("data-taxid") + '" id="itemTax" disabled="disabled" onkeyup="calculamount()" onblur="calculamount()" name="itemTax" class="span7 validate[required, custom[number]]" type="text" placeholder="Tax(%)"><span id="displayTaxCode" style="margin-top:0;" onclick="taxPopup ()"  class="btn add-on">' + $(me).attr("data-taxcode") + '</span></div></td>' +
                    '<td class="span1"><input onkeyup="calculamount()" disabled onchange="calculamount()" id="itemTaxAmount" name="itemTaxAmount" class="span12" type="text" data-previewvalue="' + $(me).parent().parent().find("td").eq(8).html() + '" value="' + $(me).parent().parent().find("td").eq(8).html() + '"></td>' +
                    '<td class="span1"><input onkeyup="calculamount()" disabled onchange="calculamount()" id="itemAmountIT" name="itemAmountIT" class="span12" type="text" data-previewvalue="' + $(me).parent().parent().find("td").eq(9).html() + '" value="' + $(me).parent().parent().find("td").eq(9).html() + '"></td>' +
                    '<td class="span1">' +
                    '<button type="button" data-itemid="' + $(me).attr("data-itemid") + '" onclick="updateRow(this)" data-itemid="' + $(me).attr("data-itemid") + '"  data-taxid="' + $(me).attr("data-taxid") + '" data-myid="' + $(me).attr("data-myid") + '" data-taxcode="' + $(me).attr("data-taxcode") + '" data-taxrate="' + $(me).attr("data-taxrate") + '" class="btn-icon btn-mini btn-success-form" type="button"><span class="i-checkmark-3"></span></button>' +
                    ' <button type="button"  id="btnCancel" data-taxcode="' + $(me).attr("data-taxcode") + '" data-itemid="' + $(me).attr("data-itemid") + '"  data-taxrate="' + $(me).attr("data-taxrate") + '" onclick="cancelEdit(this)" data-taxid="' + $(me).attr("data-taxid") + '" data-myid="' + $(me).attr("data-myid") + '"  class="btn-icon btn-mini btn-danger-form" type="button"><span class="i-cross"></span></button></td>' +
                    '</tr>');
                    $("#itemComboList").val($(me).attr("data-itemid"));
                    $("#itemComboList").select2();
                    $('#idUnitOfMeasure').select2();
                    getItemListOfUM();
                    $.each($("#listDetails .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();
                    });
                    });
            } else{
            msg (1, "alert", "Please, do save the current details before adding new one");
            }
            return 0;
            }

            function calculamount(){

            if ($("#itemTax").attr("data-taxid") == "") {
            taxPopup ();
            }
            var j_itemAmountET = accounting.unformat($("#itemunitprice").val()) * accounting.unformat($("#itemqte").val());
                    $("#itemAmountET").val(accounting.formatNumber(j_itemAmountET, 2));
                    var j_itemTaxAmount = j_itemAmountET * accounting.unformat($("#itemTax").val()) / 100;
                    $("#itemTaxAmount").val(accounting.formatNumber(j_itemTaxAmount, 2));
                    $("#itemAmountIT").val(accounting.formatNumber(j_itemTaxAmount + j_itemAmountET, 2));
            }

            function calculChargeAmount() {
            var t = $("#chargeAmount").val() * $("#listTax option:selected").attr("data-tax") / 100;
                    $("#chargetaxAmount").val(t);
                    $("#chargeAmountIT").val(t + $("#chargeAmount").val() * 1);
            }

            function EndEdit(me){

            var dID = $(me).attr("data-itemId");
                    $('' +
                            '<tr>' +
                            '<td>' + $("#itemComboList").attr("data-lineNo") + '</td>' +
                            '<td>' + $("#itemComboList option:selected").text() + '</td>' +
                            '<td>' + $("#itemdes").val() + '</td>' +
                            '<td>' + $("#idUnitOfMeasure option:selected").text() + '</td>' +
                            '<td class="tac">' + $("#itemqte").val() + '</td>' +
                            '<td class="tar">' + $("#itemunitprice").val() + '</td>' +
                            '<td class="tar">' + $("#itemAmountET").val() + '</td>' +
                            '<td class="tac">' + $("#itemTax").val() + '</td>' +
                            '<td class="tar">' + $("#itemTaxAmount").val() + '</td>' +
                            '<td class="tar">' + $("#itemAmountIT").val() + '</td>' +
                            '<td class="tac">' +
                            '<button type="button" data-itemid="' + $(me).attr("data-itemid") + '" data-taxcode="' + $(me).attr("data-taxcode") + '" data-taxrate="' + $(me).attr("data-taxrate") + '"  onClick="editRow(this)" data-taxid="' + $(me).attr("data-taxid") + '" data-myid="' + $(me).attr("data-myid") + '" class="btn-icon btn-mini btn-warning-form"><i class="i-pen"></i></button>' +
                            ' <button type="button" onclick="deleteRow(this)" data-myid="' + $(me).attr("data-myid") + '" class="btn-icon btn-mini btn-danger-form"><i class="i-trashcan"></i></button>' +
                            '</td>' +
                            '</tr>'
                            ).insertBefore("#trInfos");
                    removeRow(me);
                    getTotal ();
            }
            function displaysItemDefaultValue(){
            $("#itemdes").val($("#itemComboList option:selected").attr("data-desc"));
                    $("#itemunitprice").val(accounting.formatNumber($("#itemComboList option:selected").attr("data-price"), 2));
                    $("#itemTax").val($("#itemComboList option:selected").attr("data-taxPercentage"));
                    $("#itemTax").attr("data-taxid", $("#itemComboList option:selected").attr("data-taxid"));
                    $("#displayTaxCode").text($("#itemComboList option:selected").attr("data-taxcode"));
                    getItemListOfUM();
                    getLatestItemPrice();
            }

            function cancelEdit(me){
            var tr = $(me).parent().parent();
                    var dID = $(me).attr("data-itemId");
                    $(tr).replaceWith('<tr>' +
                    '<td>' + $("#itemComboList").attr("data-lineNo") + '</td>' +
                    '<td>' + $("#itemComboList").attr("data-previewvalue") + '</td>' +
                    '<td>' + $("#itemdes").attr("data-previewvalue") + '</td>' +
                    '<td class="tac">' + $("#idUnitOfMeasure").attr("data-previewvalue") + '</td>' +
                    '<td class="quantity">' + $("#itemqte").attr("data-previewvalue") + '</td>' +
                    '<td class="tar">' + $("#itemunitprice").attr("data-previewvalue") + '</td>' +
                    '<td class="tar">' + $("#itemAmountET").attr("data-previewvalue") + '</td>' +
                    '<td class="tac">' + $("#itemTax").attr("data-previewvalue") + '</td>' +
                    '<td class="tar">' + $("#itemTaxAmount").attr("data-previewvalue") + '</td>' +
                    '<td class="tar">' + $("#itemAmountIT").attr("data-previewvalue") + '</td>' +
                    '<td class="tac">' +
                    '<button type="button" data-itemid="' + $(me).attr("data-itemid") + '"  data-taxcode="' + $(me).attr("data-taxcode") + '" data-taxrate="' + $(me).attr("data-taxrate") + '"  onClick="editRow(this)" data-taxid="' + $(me).attr("data-taxid") + '" data-myid="' + $(me).attr("data-myid") + '" class="btn-icon btn-mini btn-warning-form"><i class="i-pen"></i></button>' +
                    ' <button type="button" onclick="deleteRow(this)" data-myid="' + $(me).attr("data-myid") + '" class="btn-icon btn-mini btn-danger-form"><i class="i-trashcan"></i></button>' +
                    '</td>' +
                    '</tr>'
                    );
            }

            function getTotal (){

            var n = $("#listDetails > tbody > tr").length - 2;
                    var totalAmount = 0;
                    var impot = 0;
                    var total = 0;
                    var i = 0;
                    for (i = 0; i <= n; i++) {

            totalAmount = totalAmount + accounting.unformat($('#listDetails > tbody > tr:eq(' + i + ') > td:eq(6)').text()) * 1;
                    impot = impot + accounting.unformat($('#listDetails > tbody > tr:eq(' + i + ') > td:eq(8)').text()) * 1;
                    total = total + accounting.unformat($('#listDetails > tbody > tr:eq(' + i + ') > td:eq(9)').text()) * 1;
            }

            $("#totalallocated").val(accounting.formatNumber(totalAmount, 2));
                    $("#totaltaxamount").val(accounting.formatNumber(impot, 2));
                    $("#totalpaid").val(accounting.formatNumber($("#amountPaid").val(), 2));
                    calculOutOfBalance();
            }

            function updateRow(me){
            // alert($(me).attr("data-myid"));

            if ($("#itemcode").attr("itemID") == "")
                    $("#itemname").val("");
                    if ($("#paymentDetail").validationEngine('validate') && finanEngine('financhk')){
            $.ajax({
            type: "POST",
                    data: {
                    invDetailsId :$(me).attr("data-myid"),
                            itemID:  $("#itemComboList").val(),
                            itemdescription: $("#itemdes").val(),
                            quantity : $("#itemqte").val(),
                            umid : $("#idUnitOfMeasure").val(),
                            unitPrice: accounting.unformat($("#itemunitprice").val()),
                            amountExcludedTax: accounting.unformat($("#itemAmountET").val()),
                            taxID :  $("#itemTax").attr("data-taxid"),
                            taxRate: $("#itemTax").val(),
                            taxAmount: accounting.unformat($("#itemTaxAmount").val()),
                            amountIncludedTax:accounting.unformat($("#itemAmountIT").val())

                    },
                    url: "<?php echo base_url() ?>OthersPayment/updatepayitemwithitem",
                    success: function(data) {
                    msg (1, "alert alert-success", "Details successfully updated");
                            EndEdit(me);
                    } });
                    getTotal();
            }
            }

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

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

            function deleteRow (me){
            $('#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 type="button" class="btn-form btn-success-form" id="detButton">Ok</button>' +
                    '<button type="button" class="btn-form btn-danger-form" id="canb">Cancel</button>');
                    $("#_popupTitle").html("Confirm delete");
                    $("#canb").click(function() {
            $('#popupModal').modal('hide');
            });
                    $("#detButton").click(function() {
            $('#popupModal').modal('hide');
                    $.ajax({
                    type: "POST",
                            data: {
                            rowID :$(me).attr("data-myid")
                            },
                            url: "<?php echo base_url() ?>OthersPayment/deletePaymentWithItem",
                            success: function(data) {
                            msg (1, "alert alert-success", "Details successfully deleted");
                                    removeRow(me);
                            } });
                    getTotal();
            });
            }

            function  addnewrow(){
            if (!$("#itemComboList").length) {
            $('' +
                    '<tr>' +
                    '<td>' + ($("#trInfos").attr("data-currentRow") * 1 + 1) + '</td>' +
                    '<td class="span2" >' +
                    '<select id="itemComboList" class="span10" onchange="displaysItemDefaultValue()"><option></option>' +
<?php
if ($items) {
    foreach ($items as $row) {
        ?>
                    '<option data-umCode ="<?php echo str_replace(array("\n", "\r", "'"), " ", $row->umCode, $count) ?>" data-umid ="<?php echo str_replace(array("\n", "\r", "'"), " ", $row->unitOfMeasureID, $count) ?>"  data-desc= "<?php echo str_replace(array("\n", "\r", "'"), " ", $row->description, $count); ; ?>" 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 type="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="icon-plus-sign"></i><?php echo $this->lang->line('addNewItem') ?></a></li>' +
                    '<li><a href="#" onclick="refreshItems()"><i class="icon-refresh"></i><?php echo $this->lang->line('refreshlist') ?></a>' +
                    '</li> </ul></div></td>' +
                    '<td class="span2"><input id="itemdes" name="itemdes" class="span12 validate[required]" type="text" placeholder="Description"></td>' +
                    '<td class="span1">' +
                    '<select onchange="getLatestItemPrice()" id="idUnitOfMeasure" class="span12 validate[required]"><option></option></select></td>' +
                    '<td class="span1"><input id="itemqte" onkeyup="calculamount()"  name="itemqte" class="span12 validate[required,custom[integer]]" type="text" placeholder="Qty"></td>' +
                    '<td class="span1"><input id="itemunitprice" onkeyup="calculamount()" name="itemunitprice" class="span12 validate[required,custom[number]]" type="text" placeholder="Unit Priece"></td>' +
                    '<td class="span1"><input id="itemAmountET" name="itemAmountET" disabled class="input-mini validate[required]" type="text" placeholder="Amount (Exclude Tax)"></td>' +
                    '<td class="span1"><div  class="input-prepend"><input data-taxid="" id="itemTax" disabled="disabled" onkeyup="calculamount()" name="itemTax" class="span6 validate[required, custom[number]]" type="text" placeholder="Tax(%)"><span onclick="taxPopup ()" style="margin-top:0;" id="displayTaxCode"  class="btn add-on">....</span></div></td>' +
                    '<td class="span1"><input id="itemTaxAmount" name="itemTaxAmount" disabled class="span12" type="text" placeholder="Tax Amount"></td>' +
                    '<td class="span1"><input id="itemAmountIT" name="itemAmountIT" disabled class="span12" type="text" placeholder="Amount (Include Tax)"></td>' +
                    '<td class="span1">' +
                    '<button type="button" tilte="Save" class="btn-icon btn-mini btn-success-form" onclick="savepaymentnewrow(this)" type="button"> <i class="i-checkmark-3"></i> </button>' +
                    ' <button type="button" title="Cancel" id="btnCancel" class="btn-icon btn-mini btn-danger-form" onclick="removeRow(this)" type="button"><i class="i-cross"></i></button>' +
                    '</td>' +
                    '</tr>'
                    ).insertBefore("#trInfos");
                    $("#itemComboList").select2();
                    $('#idUnitOfMeasure').select2();
                    $.each($("#listDetails .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();
                    }); });
            } else{
            msg (1, "alert", "Please, do save the current details before adding new one");
            }
            }

            function savepaymentnewrow(me){
            $(me).attr("disabled", "disabled");
                    $.ajax({
                    type: "POST",
                            data: {
                            otherPaymentID : $("#otherPaymentId").val(),
                                    itemID : $("#itemComboList").val(),
                                    lineNo : $("#trInfos").attr("data-currentRow") * 1 + 1,
                                    itemdescription: $("#itemdes").val(),
                                    quantity : $("#itemqte").val(),
                                    umid : $("#idUnitOfMeasure").val(),
                                    unitPrice: accounting.unformat($("#itemunitprice").val()),
                                    amountExcludedTax: accounting.unformat($("#itemAmountET").val()),
                                    taxAmount: accounting.unformat($("#itemTaxAmount").val()),
                                    amountIncludedTax: accounting.unformat($("#itemAmountIT").val()),
                                    taxID: $("#itemTax").attr("data-taxid"),
                                    taxRate: $("#itemTax").val()

                            },
                            url: "<?php echo base_url() ?>OthersPayment/savenewpaywithItemDetailOnly",
                            success: function(data) {
                            msg (1, "alert alert-success", "Details successfully saved");
                                    var resul = eval ("(" + data + ")");
                                    $('' +
                                            '<tr>' +
                                            '<td>' + ($("#trInfos").attr("data-currentRow") * 1 + 1) + '</td>' +
                                            '<td>' + $("#itemComboList option:selected").text() + '</td>' +
                                            '<td>' + $("#itemdes").val() + '</td>' +
                                            '<td class="tac">' + $("#idUnitOfMeasure option:selected").text() + '</td>' +
                                            '<td class="tac">' + $("#itemqte").val() + '</td>' +
                                            '<td class="amount">' + $("#itemunitprice").val() + '</td>' +
                                            '<td class="amount">' + $("#itemAmountET").val() + '</td>' +
                                            '<td class="tac">' + $("#displayTaxCode").text() + " | " + $("#itemTax").val() + '</td>' +
                                            '<td class="amount">' + $("#itemTaxAmount").val() + '</td>' +
                                            '<td class="amount">' + $("#itemAmountIT").val() + '</td>' +
                                            '<td class="tac">' +
                                            '<button type="button" data-itemid="' + $("#itemComboList").val() + '"  data-taxcode="' + $("#displayTaxCode").text() + '" data-taxrate="' + $("#itemTax").val() + '"  onClick="editRow(this)" data-taxid="' + $("#itemTax").attr("data-taxid") + '" data-myid="' + resul.detailID + '" class="btn-icon btn-mini btn-warning-form"><i class="i-pen"></i></button>' +
                                            ' <button type="button" onclick="deleteRow(this)" data-myid="' + resul.detailID + '" class="btn-icon btn-mini btn-danger-form"><i class="i-trashcan"></i></button>' +
                                            '</td>' +
                                            '</tr>'
                                            ).insertBefore("#trInfos");
                                    $("#btnCancel").trigger("click");
                                    $("#trInfos").attr("data-currentRow", ($("#trInfos").attr("data-currentRow") * 1 + 1));
                                    getTotal();
                                    msg (1, "alert alert-success", "Details successfully saved");
                            }
                    }); //end ajax
            }


            function getItemListOfUM(){
            $("#idUnitOfMeasure").empty();
                    if ($("#itemComboList option:selected").attr("data-umID") + ">" + $("#itemComboList option:selected").attr("data-umCode") != null){
            //  $("#idUnitOfMeasure").select2('destroy'); 
            $("#idUnitOfMeasure").append("<option data-unitm='1' data-factor='1'  value=" + $("#itemComboList option:selected").attr("data-umID") + ">" + $("#itemComboList option:selected").attr("data-umCode") + "</option>");
                    $("#idUnitOfMeasure").select2("val", $("#itemComboList option:selected").attr("data-umID"));
            }
            $.ajax({
            type: "POST",
                    data : "unitFrom=" + $("#itemComboList option:selected").attr("data-umID") + "&itemID=" + $("#itemComboList").val(),
                    url: "<?php echo base_url() ?>apTransaction/getItemUnitList",
                    success: function(data) {

                    var resul = eval ("(" + data + ")");
                            var n = resul.recordSet.length;
                            var i = 0;
                            var opt = '';
                            for (i = 0; i < n; i++){
                    opt = opt + '<option  value="' + resul.recordSet[i].ID + '" data-unitm="' + resul.recordSet[i].unitm + '" data-factor="' + resul.recordSet[i].factor + '" data-desc ="' + resul.recordSet[i].desc + '">' + resul.recordSet[i].code + '</option>';
                    }
                    $('#idUnitOfMeasure').append(opt);
                    }
            });
            }

            function calculOutOfBalance(){
            $("#totalpaid").val(accounting.formatNumber($("#amountPaid").val(), 2));
                    v = accounting.unformat($("#amountPaid").val()) - accounting.unformat($("#totalallocated").val()) - accounting.unformat($("#totaltaxamount").val());
                    $("#outofbalance").val(accounting.formatNumber(v, 2));
            }


            function updateMaster(){
            $.ajax({
            type: "POST",
                    data: {
                    masterID  : $("#otherPaymentId").val(),
                            amount : accounting.unformat($("#amountPaid").val()),
                            refNo : $("#refNo").val(),
                            project : $("#project").val(),
                            createdOn : $("#createdDate").val(),
                            memo : $("#memo").val(),
                            formNo : $("#formNo").val()

                    },
                    url: "<?php echo base_url() ?>othersPayment/updatecashpurchaseMaster",
                    success: function(data) {
                    //1 success
                    // 2 error
                    // 3 warning 
                    if (data == 1){
                    alertbox("Update success ...", 1);
                            calculOutOfBalance();
                    } else{
                    alertbox("Update fail ...", 1);
                    }
                    } });
            }



</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() . "gl/home" ?>'> <?php echo $this->lang->line('module') ?></a> <span class="divider">-</span></li>
                    <li class="active"><?php echo $this->lang->line('cashpurchase') ?></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="button" type="submit"><span class="i-magnifier"></span></button>
                </form>
            </div>        

        </div><!-- head --> 

        <div class="content" id="grid_content_1">
            <?php
            $memo = "";
            $amtRec = 0;
            if ($otherPay) {
                foreach ($otherPay as $row) {
                    $memo = $row->memo;
                    $amtRec = $row->amountPaid;
                    ?> 
                    <input type="hidden" id="otherPaymentId" value="<?php echo $row->pID; ?>" />
                    <div class="block">
                        <div class="head">
                            <h2><strong><?php echo $this->lang->line('cashpurchase') ?></strong></h2>
                        </div><!-- head -->
                        <div class="content np">

                            <div class="row-fluid scRow">                            
                                <div class="span4 scCol">
                                    <div class="block ns" id="grid_block_1">

                                         <div class="controls-row">
                                        <div class="span4"><?php echo $this->lang->line('formNo') ?></div>
                                        <div class="span4">
                                            <input class="span12 validate[required]" id="formNo" name="formno" value='<?php echo $row->frmNo; ?>' style="color:red;"   type="text" placeholder="Form number ...">
                                        </div>
                                        <div class="span4">
                                            <input class="span12" type="text" value="<?php echo str_pad($row->serialNo, 8, '0', STR_PAD_LEFT);  ?>" placeholder="Serial" disabled="disabled">
                                        </div>
                                    </div> <!-- row -->


                                        <div class="controls-row">
                                            <div class="span4"><?php echo $this->lang->line('date') ?></div>
                                            <div class="span8">
                                                <input id="createdDate"  type="text" value="<?php echo date("d-m-Y", strtotime($row->paymentDate)); ?>" class="datepicker2 validate[required] financhk span12" />             
                                            </div><!-- span -->
                                        </div><!-- control row -->

                                        <div class="controls-row">
                                            <div class="span4"><?php echo $this->lang->line('project') ?></div>
                                            <div class="span8">
                                                <select id="project" class="span12">
                                                    <option></option>
                                                    <?php
                                                    if ($project != '') {
                                                        foreach ($project as $Prow) {
                                                            ?>
                                                            <option <?php if ($Prow->ID == $row->projectID) echo "selected" ?> value="<?php echo $Prow->ID; ?>"><?php echo $Prow->project_name; ?></option>
                                                        <?php
                                                        }
                                                    }
                                                    ?>
                                                </select>
                                            </div><!-- span -->
                                        </div><!-- control row -->

                                        <div class="controls-row">
                                            <div class="span4"><?php echo $this->lang->line('payto'); ?></div>
                                            <div class="span8">
                                                <textarea disabled="disabled" class="span12"><?php echo $row->payTo; ?></textarea>
                                            </div>
                                        </div> <!-- row -->


                                    </div><!-- grid block 1-->
                                </div><!-- scCol -->

                                <div class="span4 scCol">
                                    <div class="block" id="grid_block_3">
                                        <div class="controls-row">
                                            <div class="span4"><?php echo $this->lang->line('bank') ?></div>
                                            <div class="span8">
                                                <input disabled="disabled" type="text" value="<?php echo $row->bankShortName . ' | ' . $row->branch; ?>" class="span12" />            
                                            </div><!-- span -->
                                        </div><!-- control row -->
                                        <div class="controls-row">
                                            <div class="span4"><?php echo $this->lang->line('acctno') ?></div>
                                            <div class="span8">
                                                <input disabled="disabled" type="text" value="<?php echo $row->bankAccountNo; ?>" class="span12" />            
                                            </div><!-- span -->
                                        </div><!-- control row -->
                                        <div class="controls-row">
                                            <div class="span4"><?php echo $this->lang->line('balance') ?></div>
                                            <div class="span8">
                                                <input disabled="disabled" type="text" value="<?php echo $row->currentBalance; ?>" class="span12" />             
                                            </div><!-- span -->

                                        </div><!-- control row -->

                                        <div class="controls-row">
                                            <div class="span4"><?php echo $this->lang->line('location') ?></div>
                                            <div class="span8">
                                                <textarea class="span12" disabled="disabled" ><?php echo $row->code . ' | ' . $row->address; ?></textarea>
                                            </div>
                                        </div> <!-- row -->
                                    </div><!-- grid block 1-->
                                </div><!-- scCol -->
                                <div class="span4 scCol">
                                    <div class="block ns" id="grid_block_2">
                                        <div class="controls-row">
                                            <div class="span4"><?php echo $this->lang->line('amountpaid') ?></div>
                                            <div class="span8">
                                                <input id="amountPaid" type="text" onkeyup="calculOutOfBalance()" value="<?php echo number_format($row->amountPaid, 2); ?>" class="span12 tar" />
                                            </div>
                                        </div> <!-- row -->

                                        <div class="controls-row">
                                            <div class="span4"><?php echo $this->lang->line('refno') ?></div>
                                            <div class="span8">
                                                <input id="refNo" type="text" value="<?php echo $row->referenceNo; ?>" class="span12" />
                                            </div>
                                        </div> <!-- row -->
                                        <div class="controls-row">
                                            <div class="span4"><?php echo $this->lang->line('paymentmethood') ?></div>
                                            <div class="span8">
                                                <textarea disabled="disabled"  class="span12" ><?php echo $row->methodPay; ?></textarea>
                                            </div>
                                        </div> <!-- row -->





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

                        </div><!-- content -->

                        <div class="footer">
                            <div class="side fr">
                                <div class="btn-group">
                                    <button onclick="updateMaster();" class="btn-form btn-success-form" id="hidePrompt" type="button" name="hidePrompt">Update</button></div>
                            </div>
                        </div>

                    </div><!-- block-->
    <?php }
}
?>

            <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 class="side fr">
                                <a href="#trInfos" class="btn-icon btn-warning-form" onclick="addnewrow()" title="Add New"><span class="i-plus-2"></span></a></li>
                            </div>
                        </div><!-- head -->
                        <div class="content np">
                            <form id="paymentDetail" action="#">
                                <table id="listDetails" 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="tac"><?php echo $this->lang->line('um') ?></th>
                                            <th class="tac"><?php echo $this->lang->line('quantity') ?></th>
                                            <th class="tar"><?php echo $this->lang->line('unitPrice') ?></th>
                                            <th class="tar"><?php echo $this->lang->line('amountExcludeTax') ?></th>
                                            <th class="tac"><?php echo $this->lang->line('tax') ?></th>
                                            <th class="tar"><?php echo $this->lang->line('taxAmount') ?></th>
                                            <th class="tar"><?php echo $this->lang->line('amountIncludeTax') ?></th>
                                            <th class="tac"><?php echo $this->lang->line('action') ?></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php
                                        $tAllocated = 0;
                                        $t_taxAmount = 0;
                                        $tpaid = 0;
                                        $lastrow = 0;
                                        if ($pdetails) {
                                            foreach ($pdetails as $rowDetail) {
                                                $tpaid += $rowDetail->amountIncludedTax;
                                                if ($lastrow < $rowDetail->lineNo)
                                                    $lastrow = $rowDetail->lineNo;
                                                $t_taxAmount+= $rowDetail->taxAmount;
                                                $tAllocated += $rowDetail->amountExcludedTax;
                                                ?>
                                                <tr>
                                                    <td><?php echo $rowDetail->lineNo; ?></td>
                                                    <td><?php echo $rowDetail->name . "[" . $rowDetail->itemCode . "]"; ?></td>
                                                    <td><?php echo $rowDetail->itemdescription; ?></td>
                                                    <td class="tac"><?php echo $rowDetail->unitOfMeasure; ?></td>
                                                    <td class="tac"><?php echo number_format($rowDetail->quantity); ?></td>
                                                    <td class="tar"><?php echo number_format($rowDetail->unitPrice, 2); ?></td>
                                                    <td class="tar"><?php echo number_format($rowDetail->amountExcludedTax, 2); ?></td>
                                                    <td><?php echo $rowDetail->taxCode . " | " . $rowDetail->taxRate; ?></td>
                                                    <td class="tar"><?php echo number_format($rowDetail->taxAmount, 2); ?></td>
                                                    <td class="tar"><?php echo number_format($rowDetail->amountIncludedTax, 2); ?></td>
                                                    <td class="tac">
                                                        <button type="button" onClick="editRow(this)"  data-itemid="<?php echo $rowDetail->itemID; ?>"
                                                                data-taxcode="<?php echo $rowDetail->taxCode; ?>" data-taxrate="<?php echo $rowDetail->taxRate; ?>"
                                                                data-taxid="<?php echo $rowDetail->taxID; ?>" data-myid="<?php echo $rowDetail->pDetailID; ?>" class="btn-icon btn-mini btn-warning-form"><i class="i-pen"></i></button>
                                                        <button type="button" onClick="deleteRow(this)" data-myid="<?php echo $rowDetail->pDetailID; ?>" class="btn-icon btn-mini btn-danger-form"><i class="i-trashcan"></i></button>
                                                    </td>
                                                </tr>

    <?php } ?>
                                            <tr data-currentRow="<?php echo $lastrow; ?>" id="trInfos">
                                                <td colspan="11">
                                                    <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>
    <?php
} else {
    ?>
                                            <tr data-currentRow="<?php echo $lastrow; ?>" id="trInfos">
                                                <td colspan="11">
                                                    <div id="msg_div1" class="alert alert-info">


                                                        <h4><?php echo $this->lang->line('lastMessage') ?></h4>
                                                        <p style="padding-top:10px;">..</p>
                                                    </div>
                                                </td>

                                            </tr>
<?php } ?>

                                    </tbody>
                                </table> 
                            </form>    
                        </div><!-- content -->
                    </div><!-- grid block 1-->
                </div><!-- scCol -->
            </div><!-- row-fluid scRow-->

            <div class="row-fluid scRow"> 
                <div class="span6 scCol">
                    <div class="block" id="grid_block_4">
                        <div class="content np">
                            <div class="controls-row">
                                <div class="span12">
                                    <textarea  placeholder="<?php echo $this->lang->line('memo') ?>" style="height: 170px;" id="memo" class="span12"><?php echo $memo; ?></textarea>
                                </div><!-- span -->
                            </div><!-- row control -->

                        </div>    
                    </div><!-- grid block 1-->
                </div><!-- scCol -->        
                <div class="span6 scCol">
                    <div class="block" id="grid_block_4">
                        <div class="content np">
                            <div class="controls-row">

                                <div class="span4"><?php echo $this->lang->line('totalallocated') ?></div>
                                <div class="span8">
                                    <input id="totalallocated" class="span12 amount" value="<?php echo number_format($tAllocated, 2); ?>" type="text" placeholder="0" disabled="disabled" >
                                </div>
                            </div><!-- row control -->
                            <div class="controls-row">
                                <div class="span4"><?php echo $this->lang->line('totaltaxamount') ?></div>
                                <div class="span8">
                                    <input id="totaltaxamount" value="<?php echo number_format($t_taxAmount, 2); ?>" class="span12 amount" type="text" disabled="disabled"  placeholder="0">
                                </div>
                            </div><!-- row control -->
                            <div class="controls-row">
                                <div class="span4"><?php echo $this->lang->line('amountpaid') ?></div>
                                <div class="span8">
                                    <input id="totalpaid" disabled="disabled" value="<?php echo number_format($tpaid, 2); ?>" class="span12 amount" type="text" placeholder="0">
                                </div>
                            </div><!-- row control -->
                            <div class="controls-row">
                                <div class="span4"><?php echo $this->lang->line('outofbalance') ?></div>
                                <div class="span8">
                                    <input id="outofbalance" disabled="disabled" value="<?php echo number_format($amtRec - $tpaid, 2) ?>" class="span12 amount" type="text" placeholder="0">
                                </div>
                            </div><!-- row control -->

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


