<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>
<?php
foreach ($taxmaster as $k => $v) {
    $val = null;
    $val = array_search('OS', (array) $taxmaster[$k]);
    if ($val != null) {
        $nonGstTaxID = $taxmaster[$k]->ID;
        break;
    }
}
?>
<script>
    var gstStatus = true;
            $(document).ready(function(){
    calculOutOfBalance();
            gstStatus = isGstRegistered(<?php echo element('compID', $this->session->userdata('logged_in')); ?>, 'company');
            console.log(gstStatus);
            $('select').select2();
            jQuery('.datepicker2').datepicker({
    dateFormat : 'dd-mm-yy',
            changeMonth : true,
            changeYear : true
    });
    });
            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) {
        $temp = str_replace(array("\n", "\r", "'"), " ", $row2->name, $count);
        ?>
                    '<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 $temp; ?>\
                    </option>' +
    <?php }
}
?>
            '</select>');
                    $("#listTaxPopup").select2();
                    $('#_popupFooter').empty();
                    $('#_popupFooter').append('<button class="btn-form btn-success-form" id="confButton">Ok</button>' +
                    '<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 getLatestItemPrice(){
    $.ajax({
    type: "POST",
            data : {
            option :'sale',
                    itemID : $("#itemComboList").val(),
                    datePrice : $("#createDate").val(),
                    customerID : - 1
            },
            url: "<?php echo base_url() ?>artransaction/getPrice",
            success: function(data) {
            $("#itemunitprice").val(accounting.formatNumber(data, 2));
            }
    });
    }

    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 (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 (gstStatus && false){
    var tax = '<td class="span1">\
                        <div  class="span12 input-prepend">\
                            <input readonly style="width:15px;" data-previewvalue= "' + $(me).attr("data-taxcode") + ' | ' + $(me).attr("data-taxrate") + '"  value="' + $(me).attr("data-taxrate") + '" data-taxid="' + $(me).attr("data-taxid") + '" id="itemTax" onkeyup="calculamount()" onblur="calculamount()" name="itemTax" class="input-mini 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>';
    } else{

    var tax = '<td class="span1">\
                        <div class="span12 input-prepend">\
                            <input readonly style="width:15px;" data-previewvalue= "OS | 0" value="0" data-taxid="<?php echo $nonGstTaxID; ?>" id="itemTax" onkeyup="calculamount()" onblur="calculamount()" name="itemTax" class="input-mini validate[required, custom[number]]" type="text" placeholder="Tax(%)" >\
                            <span id="displayTaxCode" style="margin-top:0;"  class="btn add-on">OS</span>\
                        </div>\
                    </td>';
    }

    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="span12"  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-qty="<?php echo $row->quantity; ?>" data-umCode= "<?php echo $row->umCode; ?>" data-umID= "<?php echo $row->unitOfMeasureID; ?>" data-desc= "<?php echo str_replace(array("\n", "\r","'"), " ", $row->description, $count); ?>" data-price= "<?php echo $row->salesPrice; ?>" \n\
                                                                    data-taxid="<?php echo $row->outputTaxID; ?>" data-taxcode="<?php echo $row->outputTaxCode; ?>" \n\
                                                                    data-taxPercentage="<?php echo $row->outputTaxPercentage; ?>" 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></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">' +
            '</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" readonly 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>' +
            tax +
            '<td class="span1"><input onkeyup="calculamount()" readonly 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()" readonly 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 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"><i class="i-checkmark-3"></i></button>' +
            '<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"><i class="i-cross"></i></button></td>' +
            '</tr>');
            $("#itemComboList").val($(me).attr("data-itemid"));
            $("#itemComboList").select2();
            $('#idUnitOfMeasure').select2();
            getItemListOfUM();
    }

    function calculamount(){

    if ($("#itemTax").attr("data-taxid") == "") {
    // taxPopup ();
    }

    var currentQty = accounting.unformat($("#itemqte").attr("data-previewvalue"));
            var qtyMax = currentQty + accounting.unformat($("#itemComboList option:selected").attr("data-qty")) * $("#idUnitOfMeasure option:selected").attr("data-factor") / $("#idUnitOfMeasure option:selected").attr("data-unitm");
            if (accounting.unformat($("#itemqte").val()) * 1 > qtyMax || accounting.unformat($("#itemqte").val()) < 1){
    $("#itemqte").attr("style", "background:#F2DEDE;");
            $("#itemqte").val("");
            msg (1, "alert", "The quantity available of this item is :" + qtyMax + " " + $("#idUnitOfMeasure option:selected").text() +
                    "<br> The current quantity should more than 0 and less than " + qtyMax + " " + $("#idUnitOfMeasure option:selected").text());
    } else{
    $("#itemqte").attr("style", "background:#DFF0D8;");
            $("#itemqte").val(accounting.unformat($("#itemqte").val()) * 1);
            msg (1, "alert alert-info", "...");
            if (isNaN($("#itemqte").val()))
            $("#itemqte").val("");
    }

    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 class="tac">' + $("#idUnitOfMeasure option:selected").text() + '</td>' +
                    '<td class="tac">' + $("#itemqte").val() + '</td>' +
                    '<td class="tar">' + accounting.formatNumber($("#itemunitprice").val(), 2) + '</td>' +
                    '<td class="tar">' + $("#itemAmountET").val() + '</td>' +
                    '<td class="tac">' + $("#displayTaxCode").text() + " | " + $("#itemTax").val() + '</td>' +
                    '<td class="tar">' + $("#itemTaxAmount").val() + '</td>' +
                    '<td class="tar">' + $("#itemAmountIT").val() + '</td>' +
                    '<td class="tac">' +
                    '<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 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"));
            getLatestItemPrice();
            getItemListOfUM();
    }

    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="tar">' + $("#itemunitprice").attr("data-previewvalue") + '</td>' +
            '<td class="quantity">' + $("#idUnitOfMeasure").attr("data-previewvalue") + '</td>' +
            '<td class="quantity">' + $("#itemqte").attr("data-previewvalue") + '</td>' +
            '<td class="tar">' + $("#itemAmountET").attr("data-previewvalue") + '</td>' +
            '<td>' + $("#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 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 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(total, 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: {
            rowID :$(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()),
                    paymentId : $("#masterID").val()

            },
            url: "<?php echo base_url() ?>arTransaction/updatecashsale",
            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 class="btn-form btn-success-form" id="detButton">Ok</button>' +
            '<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"),
                            paymentId : $("#masterID").val()
                    },
                    url: "<?php echo base_url() ?>arTransaction/deletecashsaleRow",
                    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="span12" onchange="displaysItemDefaultValue()"><option></option>' +
<?php
if ($items) {
    foreach ($items as $row) {
        ?>
            '<option data-qty="<?php echo $row->quantity; ?>" data-umCode= "<?php echo $row->umCode; ?>" data-umID= "<?php echo $row->unitOfMeasureID; ?>" data-desc= "<?php echo str_replace(array("\n", "\r","'"), " ", $row->description, $count); ?>" data-price= "<?php echo $row->salesPrice; ?>" \n\
                                                                    data-taxid="<?php echo $row->outputTaxID; ?>" data-taxcode="<?php echo $row->outputTaxCode; ?>" \n\
                                                                    data-taxPercentage="<?php echo $row->outputTaxPercentage; ?>" 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></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"><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" readonly class="input-mini validate[required]" type="text" placeholder="Amount (Exclude Tax)"></td>' +
            '<td class="span1"><div  class="input-prepend"><input readonly data-taxid="" id="itemTax" 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" readonly class="span12" type="text" placeholder="Tax Amount"></td>' +
            '<td class="span1"><input id="itemAmountIT" name="itemAmountIT" readonly class="span12" type="text" placeholder="Amount (Include Tax)"></td>' +
            '<td class="span1">' +
            '<button tilte="Save" class="btn-icon btn-mini btn-success-form" onclick="savepaymentnewrow(this)" type="button"> <i class="i-checkmark-3"></i> </button>' +
            '<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();
    } 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: {
                    paymentId : $("#masterID").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() ?>arTransaction/savenewcashpayDetailOnly",
                    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="tar">' + accounting.formatNumber($("#itemunitprice").val(), 2) + '</td>' +
                                    '<td class="tar">' + $("#itemAmountET").val() + '</td>' +
                                    '<td class="tac">' + $("#displayTaxCode").text() + " | " + $("#itemTax").val() + '</td>' +
                                    '<td class="tar">' + $("#itemTaxAmount").val() + '</td>' +
                                    '<td class="tar">' + $("#itemAmountIT").val() + '</td>' +
                                    '<td class="tac">' +
                                    '<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 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") > 0 && $("#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(){
    var totalPaid = accounting.unformat($("#amountreceived").val());
            $("#totalpaid").val(accounting.formatNumber(totalPaid, 2));
            v = accounting.unformat($("#amountreceived").val()) - (accounting.unformat($("#totalallocated").val()) + accounting.unformat($("#totaltaxamount").val()));
            $("#outofbalance").val(accounting.formatNumber(v, 2));
            }


    function updateMaster(){
    $.ajax({
    type: "POST",
            data: {
            masterID  : $("#masterID").val(),
                    amount : accounting.unformat($("#amountreceived").val()),
                    refNo : $("#refNo").val(),
                    memo: $("#memo").val(),
                    date: $("#createdDate").val(),
                    project: $("#project").val()
            },
            url: "<?php echo base_url() ?>arTransaction/updatecashSaleMaster",
            success: function(data) {
            //1 success 
            // 2 error
            // 3 warning 
            if (data == 1){
            alertbox("Update success ...", 1);
                    calculOutOfBalance();
            } else{
            alertbox("Update fail ...", 1);
            }
            } });
    }

    // function calculateOutOfBallance(){
    //    $("#outofbalance").val(accounting.formatNumber(accounting.unformat($("#amountreceived").val())-accounting.unformat($("#totalpaid").val()),2));
    //}


</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('titleEdit') ?></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">

            <?php
            $memo = "";
            $amtRec = 0;
            if ($master) {
                foreach ($master as $row) {
                    $memo = $row->memo;
                    $amtRec = $row->amountReceived;
                    ?> 
                    <input type="hidden" id="masterID" value="<?php echo $row->masterID; ?>" />
                    <div class="block">
                        <div class="head">
                            <h2><strong><?php echo $this->lang->line('titleEdit') ?></strong></h2>
                        </div><!-- head -->
                        <div class="content">

                            <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="span8">
                                                <input readonly="readonly" type="text" value="<?php echo $row->formNo; ?>" class="span12" />             
                                            </div><!-- span -->
                                        </div><!-- control 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->salesInvoiceDate)); ?>" class="datepicker2 validate[required] financhk span12" />           
                                            </div><!-- span -->
                                        </div><!-- control row -->

                                        <div class="controls-row">
                                            <div class="span4"><?php echo $this->lang->line('payfrom'); ?></div>
                                            <div class="span8">
                                                <textarea readonly="readonly" class="span12"><?php echo $row->paymentFrom; ?></textarea>
                                            </div>
                                        </div> <!-- 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><!-- 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 readonly="readonly" type="text" value="<?php echo $row->bankName; ?>" 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 readonly="readonly" 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('location') ?></div>
                                            <div class="span8">
                                                <textarea class="span12" readonly="readonly" ><?php echo $row->location; ?></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('amountreceived') ?></div>
                                            <div class="span8">
                                                <input id="amountreceived" onkeyup="calculOutOfBalance();" type="text" value="<?php echo number_format($row->amountReceived, 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 readonly="readonly" class="span12"><?php echo $row->paymentMethod; ?></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-warning-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>     
                            <ul class="buttons fr">
                                <li><a href="#trInfos" onclick="addnewrow()" title="Add New"><span class="i-plus-2"></span></a></li>
                            </ul>
                        </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;
                                        $lineNo = 0;
                                        if ($pdetails) {
                                            foreach ($pdetails as $rowDetail) {
                                                $lastrow++;
                                                $tpaid += $rowDetail->amountIncludedTax;
                                                $t_taxAmount+= $rowDetail->taxAmount;
                                                $tAllocated += $rowDetail->amountExcludedTax;
                                                ?>
                                                <tr>
                                                    <td><?php echo ++$lineNo; ?></td>
                                                    <td><?php echo $rowDetail->name . "[" . $rowDetail->itemCode . "]"; ?></td>
                                                    <td><?php echo $rowDetail->description; ?></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 class="tac"><?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="quantity">
                                                        <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 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;">No item found ...</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" readonly="readonly" >
                                </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" readonly="readonly"  placeholder="0">
                                </div>
                            </div><!-- row control -->
                            <div class="controls-row">
                                <div class="span4"><?php echo $this->lang->line('amountreceived') ?></div>
                                <div class="span8">
                                    <input id="totalpaid" readonly="readonly" 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" readonly="readonly" 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 -->


