<script type="text/javascript">
      
    $(document).ready(function() {
      
        $('select').select2();
       
        $.each($(".select2-container"), function(i, n) {
            $(n).next().show().fadeTo(0, 0).height("0px").css("left", "auto"); // make the original select visible for validation engine and hidden for us
            $(n).prepend($(n).next());
            $(n).delay(500).queue(function() {
                $(this).removeClass("validate[required]"); //remove the class name from select2 container(div), so that validation engine dose not validate it
                $(this).dequeue();
            });
        });
    });

    function checkOption(opt) {
       /* if (opt == 1) {
            $("#rowSale").attr("style", "display:none");
            $("#rowLumpSum").attr("style", "display:block");
            $("#rowAcc").attr("style", "display:none");
             $("#rowPeriode").attr("style", "display:none");
        } else {
            $("#rowSale").attr("style", "display:block");
            $("#rowAcc").attr("style", "display:block");
            $("#rowLumpSum").attr("style", "display:none;");
            $("#rowPeriode").attr("style", "display:block");

        }
        
       
        if (opt == 1) {
            $("#rowSale").attr("style", "display:none");
            $("#rowLumpSum").attr("style", "display:block");
            $("#rowAcc").attr("style", "display:none");
             $("#rowPeriode").attr("style", "display:none");
            $("#rowWakafAcrual2").attr("style", "display:none");
            $("#rowWakafAcrual3").attr("style", "display:none");

        } else 
        if (opt == 2){
            $("#rowSale").attr("style", "display:block");
            $("#rowAcc").attr("style", "display:block");
            $("#rowLumpSum").attr("style", "display:none;");
            $("#rowPeriode").attr("style", "display:block");
            $("#rowWakafAcrual2").attr("style", "display:none");
            $("#rowWakafAcrual3").attr("style", "display:none");


        }else
        if (opt == 3){
            $("#rowSale").attr("style", "display:none");
            $("#rowAcc").attr("style", "display:none");
            $("#rowLumpSum").attr("style", "display:none;");
            $("#rowPeriode").attr("style", "display:none");
            $("#rowWakafAcrual2").attr("style", "display:block");
            $("#rowWakafAcrual3").attr("style", "display:block");
            $("#accrualPercentage").val("");
             $("#wakafAcrualAmount").val("");
             $.ajax({
                type: "POST",
                url: "<?php echo base_url() ?>wakafsetup/getwakafAcrualAmount",
                success: function(data) {
                    if(data>0){
                       $("#wakafAcrualAmount").val(accounting.formatNumber(data,2));
                        $("#accrualPercentage").removeAttr("readonly");
                   }else{
                       $("#accrualPercentage").attr("readonly","readonly");
                       msg ("alert", "No sale amount allocated !!!");
                   }
                        
                }
             });
             
        }
       
       var trInfos = $("#trInfos").clone();
        $("#listDetails > tbody").empty();
         $("#listDetails > tbody").append(trInfos);
         $("#trInfos").attr("data-currentRow",0)
         $("#totalPercentage").attr("data-currentValue",0);
         $("#totalPercentage").val("");
          $("#totalAmountApplied").val(""); */
    
     if (opt == 1) {
            $("#rowSale").attr("style", "display:none");
            $("#rowLumpSum").attr("style", "display:block");
            $("#rowAcc").attr("style", "display:none");
             $("#rowPeriode").attr("style", "display:none");
            $("#rowWakafAcrual2").attr("style", "display:none");
            $("#rowWakafAcrual3").attr("style", "display:none");
             $("#rowWakafByProfit1").attr("style", "display:none");
            $("#rowWakafByProfit2").attr("style", "display:none");

        } else 
        if (opt == 2){
            $("#rowSale").attr("style", "display:block");
            $("#rowAcc").attr("style", "display:block");
            $("#rowLumpSum").attr("style", "display:none;");
            $("#rowPeriode").attr("style", "display:block");
            $("#rowWakafAcrual2").attr("style", "display:none");
            $("#rowWakafAcrual3").attr("style", "display:none");
             $("#rowWakafByProfit1").attr("style", "display:none");
            $("#rowWakafByProfit2").attr("style", "display:none");


        }else
        if (opt == 3){
            $("#rowSale").attr("style", "display:none");
            $("#rowAcc").attr("style", "display:none");
            $("#rowLumpSum").attr("style", "display:none;");
            $("#rowPeriode").attr("style", "display:none");
             $("#rowWakafByProfit1").attr("style", "display:none");
            $("#rowWakafByProfit2").attr("style", "display:none");
            $("#rowWakafAcrual2").attr("style", "display:block");
            $("#rowWakafAcrual3").attr("style", "display:block");
            $("#accrualPercentage").val("");
             $("#acAmountAllocated").val("");
             $.ajax({
                type: "POST",
                url: "<?php echo base_url() ?>wakafsetup/getwakafAcrualAmount",
                success: function(data) {
                    if(data>0){
                       $("#acAmountAllocated").val(accounting.formatNumber(data,2));
                        $("#accrualPercentage").removeAttr("readonly");
                   }else{
                       $("#accrualPercentage").attr("readonly","readonly");
                       msg ("alert", "No sale amount allocated !!!");
                   }
                        
                }
             });
             
        }else
            if(opt == 4){
              $("#rowSale").attr("style", "display:none");
            $("#rowAcc").attr("style", "display:none");
            $("#rowLumpSum").attr("style", "display:none;");
            $("#rowPeriode").attr("style", "display:none");
            $("#rowWakafAcrual2").attr("style", "display:none");
            $("#rowWakafAcrual3").attr("style", "display:none");
             $("#rowWakafByProfit1").attr("style", "display:block");
            $("#rowWakafByProfit2").attr("style", "display:block");
            
            $("#profitPercentage").val("");
             $("#proAmountAllocated").val(""); 
             
             $.ajax({
                type: "POST",
                url: "<?php echo base_url() ?>wakafsetup/getwakafProfitAmount",
                success: function(data) {
                    if(data>0){
                       $("#wakafProfitAmt").val(accounting.formatNumber(data,2));
                        $("#profitPercentage").removeAttr("readonly");
                   }else{
                       $("#profitPercentage").attr("readonly","readonly");
                       msg ("alert", "No Profit !!!");
                   }
                        
                }
             });
             
            }
    
       // var trInfos = $("#trInfos").clone();
        //$("#listDetails > tbody").empty();
         //$("#listDetails > tbody").append(trInfos);
         //$("#trInfos").attr("data-currentRow",0)
         //$("#totalPercentage").attr("data-currentValue",0);
         //$("#totalPercentage").val("");
          //$("#totalAmountApplied").val("");

    }

    function checkCategory(opt) {
        if (opt == 1) {
            $("#specifikDetails").attr("style", "display:none");
        } else {
            $("#specifikDetails").attr("style", "display:block");
        }
    }

    function updateTotal() {
        var som = 0;
        $("#specifikDetailslist > tbody > tr").each(function() {
            var tr = $(this);
            som += 1 * accounting.unformat($(tr).find("td").eq(3).children("input:last-child").val());
            //alert($(tr).find("td").eq(1).text());
        });
        $("#sequence").val(som)
    }
    
    function addNewBene(){
        if (!$("#listCateBene").length) {
    $('' +
            '<tr><td class="span1">' + ($("#trInfos").attr("data-currentRow") * 1 + 1) + '</td>' +
            '<td class="span3" >' +
            '<select class="span12 validate[required]" id="listCateBene""><option value="0"></option>' +
<?php
if ($datatbls) {
    foreach ($datatbls as $row) {
        ?>
            '<option value= "<?php echo $row->ID; ?>"' + ' ><?php  echo str_replace("'", " ", $row->name, $count);
        ?></option>' +
        <?php
    }
}
?>
    '</select></td>' +
            '<td class="span4"><input id="beneDesc" name="beneDesc" class="span12 validate[required]" type="text" placeholder="Description"></td>' +
            '<td class="span1"><input id="percentageValue"  onkeyup="calculateTotalPercentage()" name="percentageValue" class="span12 tar validate[required,custom[number]]" type="text" placeholder=""></td>' +
            '<td class="span2"><input class="span12 tar" id="beneAmnt" disabled  name="beneAmnt" type="text"></td>' +
            '<td class="span1">' +
            '<button class="btn-icon btn-mini btn-success-form" onclick="validateRow(this)"  type="button"><span class="i-checkmark-3"></span></button>' +
            '<button id="btnCancel" class="btn-icon btn-mini btn-danger-form" onclick="delRow(this)" type="button"><span class="i-cross"></span></button>' +
            '</td>' +
            '</tr>'


            ).insertBefore("#trInfos");
            $('#listCateBene').select2();
    } else{
    msg ("alert", "Please, do insert the current details before adding new one");
    }
    }
    
function delRow(me){
    var td = me.parentNode;
            var tr = td.parentNode;
            var tBody = tr.parentNode;
            tBody.removeChild(tr);
    }
    
    function deleteRow(me){
         var i = 0;
         var som = 0;
         var p = 0;
         delRow(me);
         $("#listDetails > tbody > tr").each (function(){
             $(this).find("td").eq(0).text(++i);
             p += accounting.unformat($(this).find("td").eq(3).text());
             som +=  accounting.unformat($(this).find("td").eq(4).text());
         });
         $("#totalAmountApplied").val(accounting.formatNumber(som,2));
         $("#totalPercentage").val(p);
         $("#trInfos").attr("data-currentRow", i-1);
         $("#totalPercentage").attr("data-currentValue",p);
         $($("#trInfos")).find("td").eq(0).text("Total");
         
    }
    
    function getSaleAmount(){
       //  alert($('#saleAcctNo').validationEngine('validate'));
      // if( !$('#saleAcctNo').validationEngine('validate') && $('#wYear').validationEngine('validate') && $('#wFrom').validationEngine('validate') && $('#wTo').validationEngine('validate')){
        $("#iAmtAll").val("");
        $("#iPerAll").val("");
        $.ajax({
                type: "POST",
                data : {
                    year : $("#wYear").val(),
                    from : $("#wFrom").val(),
                    to : $("#wTo").val(),
                    acctno : $("#saleAcctNo").val()
                },
                url: "<?php echo base_url() ?>wakafsetup/getSaleAmount",
                success: function(data) {
                    if(data>0){
                       $("#iSaleAmt").val(accounting.formatNumber(data,2));
                       msg ("alert-inofs", "");
                   }else{
                       $("#iSaleAmt").val("");
                       msg ("alert", "No value for this periode and this account !!!");
                   }
                        
                }
       });
      //  }
     }
     
     function msg(type, message){
			$("#msg_div p").html(message);
			$("#msg_div").attr("class","alert " + type)
        }
    
    function validateRow(me){
         $.each($(".select2-container"), function(i, n) {
            $(n).next().show().fadeTo(0, 0).height("0px").css("left", "auto"); // make the original select visible for validation engine and hidden for us
                $(n).prepend($(n).next());
                $(n).delay(500).queue(function() {
        $(this).removeClass("validate[required]"); //remove the class name from select2 container(div), so that validation engine dose not validate it
                $(this).dequeue();
        }); });
                var v = $('#listCateBene').validationEngine('validate') && $('#beneDesc').validationEngine('validate') && $('#percentageValue').validationEngine('validate') && finanEngine('financhk');
                // if (v) {


                $.ajax({
                type: "POST",
                        data : {
                                bene : $("#listCateBene").val(),
                                desc : $("#beneDesc").val(),
                                t : $("#percentageValue").val(),
                                amt : $("#beneAmnt").val(),
                                masterId : $("#masterId").val()
                        },
                        url: "<?php echo base_url() ?>wakafsetup/addNewRowWakafBene",
                        success: function(data) {
                        $('' +
                                '<tr><td class="span1" data-cateId="' + $("#listCateBene").val() + '">' + ($("#trInfos").attr("data-currentRow") * 1 + 1) + '</td>' +
                                '<td>' + $("#listCateBene option:selected").text() + '</td>' +
                                '<td>' + $("#beneDesc").val() + '</td>' +
                                '<td class="tar">' + $("#percentageValue").val() + '</td>' +
                                '<td class="tar">' + $("#beneAmnt").val() + '</td>' +
                                '<td>' +
                                '<button data-beneId="'+ $("#listCateBene").val() +'" data-myid="'+ data +'" onclick="editRow(this)" class="btn-icon btn-mini btn-warning-form"><i class="i-pen"></i></button>' +
                                '<button id="btnCancel" onclick="deleteFromDb(this, ' + data + ')" class="btn-icon btn-mini btn-danger-form" type="button"><i class="i-trashcan"></i></button>' +
                                '</td>' +
                                '</tr>').insertBefore("#trInfos");
                                $("#trInfos").attr("data-currentRow", $("#trInfos").attr("data-currentRow") * 1 + 1);
                                $("#totalPercentage").attr("data-currentValue", $("#totalPercentage").attr("data-currentValue") * 1 + 1 * $("#percentageValue").val());
                                delRow(me);
                        }
                });
                //  }
        }
    
    function getAmountAllocated(){
        var amt = accounting.unformat($("#idAmountAllocated").val());
        
        if($("#bySale").is(":checked")){
            amt = accounting.unformat($("#saleAmntAllocated").val());
        }else
            if($("#byAccrual").is(":checked")){
                amt = accounting.unformat($("#acAmountAllocated").val());
            }else
             if($("#byProfit").is(":checked")){
                amt = accounting.unformat($("#proAmountAllocated").val());
             }
        return amt;
    }
    
    function calculateTotalPercentage(){
        var t = accounting.unformat($("#totalPercentage").attr("data-currentValue")) + accounting.unformat($("#percentageValue").val()) -  accounting.unformat($("#percentageValue").attr("data-previewValue"));
        
        //alert(t);
       var amt = getAmountAllocated();
        if(t>0 && t<=100){
            $("#totalPercentage").val(t);
            var am =  accounting.unformat($("#percentageValue").val()) /100*amt;
            $("#beneAmnt").val (accounting.formatNumber(am,2));
            $("#totalAmountApplied").val(accounting.formatNumber(t*amt/100));
        }else{
             $("#percentageValue").val(100 - $("#totalPercentage").attr("data-currentValue"));
             
             $("#beneAmnt").val (accounting.formatNumber((100 - $("#totalPercentage").attr("data-currentValue"))*amt/100,2));
             $("#totalPercentage").val(100);
             $("#totalAmountApplied").val(accounting.formatNumber(amt,2));
        }
    }
    
    function calculateSalesAmountApplied(){
        var v = (accounting.unformat($("#percentageSaleAllocated").val())/100)*accounting.unformat($("#saleAmount").val());
        $("#saleAmntAllocated").val(accounting.formatNumber(v,2));
        updateAmnt();
    }
    
    function updateAmnt(){
       
         var amt = getAmountAllocated();
         $("#listDetails > tbody > tr").each (function(){
             p = accounting.unformat($(this).find("td").eq(3).text())*amt/100;
              $(this).find("td").eq(4).text(accounting.formatNumber(p,2));
         });
         $("#totalAmountApplied").val(accounting.formatNumber( accounting.unformat($("#totalPercentage").val())*amt/100,2));
         $("#totalPercentage").val();
         $("#totalPercentage").attr("data-currentValue",p);
    }
    
    
    function deleteFromDb(me, id){
      //  var t = $(me).parent().parent().find("td").eq(3).text();
        
        deleteRow (me);
            //totalPercentage : $("#totalPercentage").val(),
            // totalAmountApplied : $("#totalAmountApplied").val(),
            // masterId : $("#masterId").val()
         $.ajax({
                type: "POST",
                data : {
                    rowId : id
                },
                url: "<?php echo base_url() ?>wakafsetup/deleteBeneRow",
                success: function(data) {
                       
                }
                 });
        }
        
    function editRow(me){
     if (!$("#listCateBene").length) {
        var tr = $(me).parent().parent();
          $(tr).replaceWith('<tr><td>' + $(me).parent().parent().find("td").eq(0).text() + '</td>' +
            '<td class="span3" >' +
            '<select data-previewValue = "' + $(me).parent().parent().find("td").eq(1).text() + '" data-lineNo=' + $(me).parent().parent().find("td").eq(0).text() + ' class="span12 validate[required]" id="listCateBene""><option value="0"></option>' +
<?php
if ($datatbls) {
    foreach ($datatbls as $row) {
        ?>
            '<option value= "<?php echo $row->ID; ?>"' + ' ><?php  echo str_replace("'", " ", $row->name, $count);
        ?></option>' +
        <?php
    }
}
?>
    '</select></td>' +
           '<td class="span4"><input data-previewValue = "' + $(me).parent().parent().find("td").eq(2).text() + '" value="' + $(me).parent().parent().find("td").eq(2).text() + '" id="beneDesc" name="beneDesc" class="span12 validate[required]" type="text" placeholder="Description"></td>' +
            '<td class="span1"><input data-previewValue = "' + $(me).parent().parent().find("td").eq(3).text() + '" value ="'+ $(me).parent().parent().find("td").eq(3).text() +'" id="percentageValue"  onkeyup="calculateTotalPercentage()" name="percentageValue" class="span12 tar validate[required,custom[number]]" type="text" placeholder=""></td>' +
            '<td class="span2"><input data-previewValue = "' + $(me).parent().parent().find("td").eq(4).text() + '" value="'+ $(me).parent().parent().find("td").eq(4).text() +'" class="span12 tar" id="beneAmnt" disabled  name="beneAmnt" type="text"></td>' +
            '<td class="span1">' +
            '<button class="btn-icon btn-mini btn-success-form" data-beneId="'+ $(me).attr("data-beneId") +'" data-myid="'+ $(me).attr("data-myid") +'" onclick="updateRowBene(this)" type="button"><span class="i-checkmark-3"></span></button>' +
            '<button id="btnCancel" data-beneId="'+ $(me).attr("data-beneId") +'" data-myid="'+ $(me).attr("data-myid") +'" class="btn-icon btn-mini btn-danger-form" onclick="cancelEdit(this)" type="button"><span class="i-cross"></span></button>' +
            '</td>' +
            '</tr>' );
    $("#listCateBene").val($(me).attr("data-beneId"));
     $("#listCateBene").select2();
    } else{
    msg ("alert", "Please, do insert the current details before adding new one");
    }
    }
    
    function cancelEdit(me){
         var tr = $(me).parent().parent();
          $(tr).replaceWith('<tr><td>' + $("#listCateBene").attr("data-lineNo") + '</td>' +
                  '<td>'+ $("#listCateBene").attr("data-previewValue") +'</td>' +
                  '<td>'+ $("#beneDesc").attr("data-previewValue") +'</td>' +
                  '<td class="tar">'+ $("#percentageValue").attr("data-previewValue") +'</td>' +
                  '<td class="tar">'+ $("#beneAmnt").attr("data-previewValue") +'</td>' +
                  '<td>' +
                    '<button data-beneId="'+ $(me).attr("data-beneId") +'" data-myid="'+ $(me).attr("data-myid") +'" onclick="editRow(this)" class="btn-icon btn-mini btn-success-form"><i class="i-pen"></i></button>' +
                    '<button id="btnCancel" onclick="deleteFromDb(this, ' + $(me).attr("data-myid") + ')" class="btn-icon btn-mini btn-danger-form" type="button"><i class="i-trashcan"></i></button>' +
                    '</td></tr>' );
                  
    }
    
    
    function updateRowBene(me){
        $.ajax({
                type: "POST",
                        data : {
                                bene : $("#listCateBene").val(),
                                desc : $("#beneDesc").val(),
                                t : $("#percentageValue").val(),
                                amt : $("#beneAmnt").val(),
                            rowId : $(me).attr("data-myid")
                    },
                    url: "<?php echo base_url() ?>wakafsetup/uptRowWakafBene",
                    success: function(data) {

                    var tr = $(me).parent().parent();
                            $(tr).replaceWith('<tr><td>' + $("#listCateBene").attr("data-lineNo") + '</td>' +
                            '<td>' + $("#listCateBene option:selected").text() + '</td>' +
                            '<td>' + $("#beneDesc").val() + '</td>' +
                            '<td class="tar">' + $("#percentageValue").val() + '</td>' +
                            '<td class="tar">' + $("#beneAmnt").val() + '</td>' +
                            '<td>' +
                            '<button data-beneId="' + $("#listCateBene").val() + '" data-myid="' + $(me).attr("data-myid") + '" onclick="editRow(this)" class="btn-icon btn-mini btn-warning-form"><i class="i-pen"></i></button>' +
                            '<button id="btnCancel" onclick="deleteFromDb(this, ' + $(me).attr("data-myid") + ')" class="btn-icon btn-mini btn-danger-form" type="button"><i class="i-trashcan"></i></button>' +
                            '</td></tr>');
                    }
            });
    }
    
    function updatewakafMasterOnly(){
       
        var master ="masterId=" + $("#masterId").val() + "&waqif=" + $("#waqif").val();
        if($("#bySale").is(":checked")){
                master = master + "&option=bySale" + "&wakafAmount=" + $("#saleAmntAllocated").val();
            }else
            if($("#byAccrual").is(":checked")) {
                master = master + "&option=accrual&wakafAmount=" + accounting.unformat($("#acAmountAllocated").val());
            }else
             if($("#byProfit").is(":checked")) {
                master = master + "&option=profit&wakafAmount=" + accounting.unformat($("#proAmountAllocated").val());
            }else {
                master = master + "&option=fixedAmount&wakafAmount=" + accounting.unformat($("#idAmountAllocated").val());
            }
        
       
            
            master = master + "&rowId=" + $("#masterId").val();
            
            
             $.ajax({
                type: "POST",
                data : master,
                url: "<?php echo base_url() ?>wakafsetup/updatewakafMasterOnly",
                success: function(data) {
                       if(data>0){
                           msg ("alert-success", "Wakaf Updated !!!");
                       }
                }
               });
                 
    }
    
    function deleteSalesAcct(me, id){
         //  var t = $(me).parent().parent().find("td").eq(3).text();
        
        
            // totalPercentage : $("#totalPercentage").val(),
            // totalAmountApplied : $("#totalAmountApplied").val(),
            // masterId : $("#masterId").val()
            var tr = $(me).parent().parent();
            var amt = accounting.unformat($(tr).find("td").eq(3).text());
            
            var wAmt = accounting.unformat($("#saleAmntAllocated").val()) - amt;
            
         $.ajax({
                type: "POST",
                data : {
                    rowId : id,
                    wakafAmount : wAmt,
                    masterId : $("#masterId").val()
                },
                url: "<?php echo base_url() ?>wakafsetup/deleteWakafSaleAllowance",
                success: function(data) {
                       delRow(me);
                       $("#saleAmntAllocated").val(accounting.formatNumber(wAmt,2));
                       updateAmnt();
                        msg ("alert-success", "Wakaf Updated : Sale Allocated Row Deleted !!!");
                }
          });
    }
    
    function insertRow(){
        if(accounting.unformat($("#iAmtAll").val())>0){
             $.ajax({
                type: "POST",
                data : {
                    "year" : $("#wYear").val(), 
                    "from" : $("#wFrom").val(),
                    "to" : $("#wTo").val(),
                    "wakafID" : $("#masterId").val(),
                    "wakafAmount" : accounting.unformat($("#iAmtAll").val())   + accounting.unformat($("#saleAmntAllocated").val()),
                    "accountID" :$("#saleAcctNo").val(),
                    "saleAmount" : accounting.unformat($("#iSaleAmt").val()),
                    "contributionPercentage" : accounting.unformat($("#iPerAll").val()),
                    "amount" : accounting.unformat($("#iAmtAll").val())
                },
                url: "<?php echo base_url() ?>wakafsetup/insertWakafSaleOnly",
                success: function(data) {
                       if(data>0){
                            $('<tr><td data-acctNo="'+ $("#saleAcctNo").val() +'">' + $("#saleAcctNo option:selected").text() + '</td>' +
                '<td class="tar">' + $("#iSaleAmt").val() + '</td>' +
                            '<td class="tar">' + $("#iPerAll").val() + '%</td>' +
                '<td class="tar">' + $("#iAmtAll").val() + '</td>' +
                    '<td><a onclick="deleteSalesAcct(this, ' + data + ')" class="btn-icon btn-mini btn-danger-form"><i class="i-trashcan"></i></a></td>' 
                    ).insertBefore("#trInfosSale");
                            $("#saleAmntAllocated").val(accounting.formatNumber(accounting.unformat($("#iAmtAll").val() )  + accounting.unformat($("#saleAmntAllocated").val()),2));
                    updateAmnt();
                    msg ("alert-success", "Wakaf Updated !!!");
                       }
                }
                 });
        
        }else{
             msg ("alert", "Amount Incorrect !!!");
        }
    }
    
    function calculateAmtAll(){
        var v = (accounting.unformat($("#iPerAll").val())/100)*accounting.unformat($("#iSaleAmt").val());
        $("#iAmtAll").val(accounting.formatNumber(v,2));
       
    }
    
    function checkEditable(me){
        n = $("#saleAcctList > tbody > tr").length;
        if(n>1){
            $(me).val($(me).attr("data-oldValue"))
            msg ("alert", "Delete all Sale Account Row Below !!!");
        }
    }
    
     function calculateAmtAllAcrual(){
        var v = (accounting.unformat($("#accrualPercentage").val())/100)*accounting.unformat($("#wakafAcrualAmount").val());
        $("#acAmountAllocated").val(accounting.formatNumber(v,2));
        updateAmnt ();
    }
    
</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="zakat/home"><?php echo $this->lang->line('module') ?></a> <span class="divider">-</span></li>
                    <li class="active"><?php echo $this->lang->line('title') ?></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">
            <?php if($master){
            foreach ($master as $mRow) {
                
            ?>
            <div class="row-fluid">
                <div class="span12">
                    <?php
                    $hidden = array('order_time' => date('Y-m-d H-i-s'));
                    $attrib = array('id' => 'validate');
                    echo form_open('', $attrib, $hidden);
                    ?>
                    <div class="block">
                        <div class="head">
                            <input type="hidden" id="masterId" value="<?php echo $mRow->ID; ?>" />
                            <h2><?php echo $this->lang->line('title') ?></h2>
                            <div class="side fr">
                               <a href="#" class="btn-form btn-warning-form" onclick="updatewakafMasterOnly()" id="btnSubmit" >Update</a>
                            </div>
                        </div>
                        <div class="content np">    
                            <div class="controls-row">
                                <div class="span2"><?php echo $this->lang->line('waqif') ?></div>
                                <div class="span10">
                                    
                                    <select  id="waqif" class="span7 validate[required]">
                                            <option></option>
                                             <?php
                                        if (waqifList) {
                                            foreach ($waqifList as $row) {
                                                ?>
                                                  <option value="<?php echo $row->ID; ?>"> <?php echo $row->name; ?></option>
                                            <?php }
                                    } ?>
                                        </select>
                                </div>                            
                            </div>
                            
                             <div class="controls-row">
                                <div class="span2"><?php echo $this->lang->line('waqfInst') ?></div>
                                <div class="span10">
                                    <select  id="waqfCenter" class="span7 validate[required]">
                                            <option></option>
                                             <?php
                                        if ($waqfcenterList) {
                                            foreach ($waqfcenterList as $row) {
                                                ?>
                                                  <option value="<?php echo $row->ID; ?>"> <?php echo $row->name; ?></option>
                                            <?php }
                                    } ?>
                                        </select>
                                </div>                            
                            </div>
                            
                            <div id="optAllocation" data-oldValue="<?php echo $mRow->allocation; ?>" class="controls-row"> <!-- row 1 -->
                                <div class="span2"><?php echo $this->lang->line('allocation') ?></div>
                                <div class="span2">
                                   <label class="radio">  <input id="fixedAmnt" <?php if($mRow->allocation==0) echo 'checked="checked"'; ?> type='radio' onclick='checkOption(1)' name='alocationOpt' value='1'> <?php echo $this->lang->line('fixedAmount') ?></label>      
                                </div>   
                                <div class="span2">
                                  <label class="radio">   <input  <?php if($mRow->allocation==1) echo 'checked="checked"'; ?> onclick='checkOption(2)' type='radio' name='alocationOpt' id='bySale' value='2'> <?php echo $this->lang->line('percentageOfSale') ?></label>
                                     
                                </div> 
                                <div class="span2">
                                    <label class="radio"> <input <?php if($mRow->allocation==2) echo 'checked="checked"'; ?> onclick='checkOption(3)' type='radio' name='alocationOpt' id='byAccrual' value='3'> <?php echo $this->lang->line('percentageFromPreSetup') ?></label>
                                     
                                </div> 
                                <div class="span2">
                                    <label class="radio">  <input <?php if($mRow->allocation==3) echo 'checked="checked"'; ?> onclick='checkOption(4)' type='radio' name='alocationOpt' id='byProfit' value='4'> <?php echo $this->lang->line('percentageFromProfit') ?></label>
                                     
                                </div> 
                            </div><!-- End Row 1 -->

                            <div id="rowLumpSum" class="controls-row"> <!-- row 2 -->
                                <div class="span2"></div>              
                                <div class="span2 TAR" > <div class="span1 TAR" ><?php echo $this->lang->line('amount') ?></div></div>
                                <div class="span4">
                                    <input class="validate[required]" onkeyup="updateAmnt()" type='text' data-oldValue="<?php echo $mRow->amountAllocated; ?>" value="<?php echo number_format($mRow->amountAllocated,2); ?>" name='idAmountAllocated' id='idAmountAllocated'>    
                                </div>                
                            </div><!-- End Row 2 -->
                           
                            
                            <div id="rowWakafAcrual2" style="display:none;"   class="controls-row"> <!-- row 2 -->
                                <div class="span2"></div>              
                                <div class="span2 TAR" > <div class="TAR" ><?php echo $this->lang->line('wakafAcrualAmount') ?></div></div>
                                <div class="span4 form-inline">
                                    <input class="validate[required] span8 tar" readonly onkeyup="updateAmnt()" type='text' name='wakafAcrualAmount' id='wakafAcrualAmount'>    
                                    <div class="input-prepend input-append span4">
                                            <input class="span8 tar" type="text" onkeyup="calculateAmtAllAcrual()" id="accrualPercentage" />
                                            <span class="add-on">&#37;</span>
                                        </div>
                                </div>                
                            </div><!-- End Row 2 -->
                            
                              <div id="rowWakafAcrual3" style="display:none;"   class="controls-row"> <!-- row 2 -->
                                <div class="span2"></div>              
                                <div class="span2 TAR" > <div class="TAR" ><?php echo $this->lang->line('amountAllocated') ?></div></div>
                                <div class="span4">
                                    <input class="validate[required] span8 tar" readonly data-oldValue="<?php echo $mRow->amountAllocated; ?>" value="<?php echo number_format($mRow->amountAllocated,2); ?>" onchange="updateAmnt()" type='text' name='acAmountAllocated' id='acAmountAllocated'>    
                                   
                                </div>                
                            </div><!-- End Row 2 -->
                            
                            
                                   <div id="rowWakafByProfit1" style="display:none;"   class="controls-row"> <!-- row 2 -->
                                <div class="span2"></div>              
                                <div class="span2 TAR" > <div class="TAR" ><?php echo $this->lang->line('profitAmount') ?></div></div>
                                <div class="span4 form-inline">
                                    <input class="validate[required] span8 tar" readonly  type='text' name='wakafProfitAmt' id='wakafProfitAmt'>    
                                    <div class="input-prepend input-append span4">
                                            <input class="span8 tar" type="text" onkeyup="calculProfiteAmt()" id="profitPercentage" />
                                            <span class="add-on">&#37;</span>
                                        </div>
                                </div>                
                            </div><!-- End Row 2 -->
                            
                              <div id="rowWakafByProfit2" style="display:none;"   class="controls-row"> <!-- row 2 -->
                                <div class="span2"></div>              
                                <div class="span2 TAR" > <div class="TAR" ><?php echo $this->lang->line('amountAllocated') ?></div></div>
                                <div class="span4">
                                    <input class="validate[required] span8 tar" readonly onchange="updateAmnt()" type='text' name='proAmountAllocated' id='proAmountAllocated'>    
                                   
                                </div>                
                            </div><!-- End Row 2 -->
                            
                            
                            <div class="controls-row"></div>
                            <div style="display:none;" id="rowPeriode" class="controls-row">
                                <div class="span2"></div>
                                <div class="span2"><?php echo $this->lang->line('periode') ?></div>
                                <div class="span2">
                                    <input id="wYear" type="text" onchange="checkEditable(this)" data-oldValue="<?php echo $mRow->periodYear; ?>" value="<?php echo $mRow->periodYear; ?>" class="span12 validate[required, custom[number]]" placeholder="Year EX:2014" />
                                </div>
                                 <div class="span2">
                                    <input id="wFrom" type="text" onchange="checkEditable(this)" data-oldValue="<?php echo $mRow->periodFrom; ?>" value="<?php echo $mRow->periodFrom; ?>" class="span12 validate[required, custom[number]]" placeholder="From Ex:2" />
                                </div>
                                 <div class="span2">
                                     <input id="wTo" type="text" onchange="checkEditable(this)" data-oldValue="<?php echo $mRow->periodTo; ?>" value="<?php echo $mRow->periodTo; ?>" class="span12 validate[required, custom[number]]" placeholder="To Ex:3" />
                                </div>
                                <div class="span1">    <button type="button" class="btn-icon btn-small btn-primary-form " data-toggle="collapse" data-target="#rowAcc"><span class="icon-chevron-down"></span></button>
                            </div>

                            <div id="rowAcc" style="display:none;" class="controls-row content np"> <!-- row 3 -->
                                        <div class="span2"></div>              

                                        <div class="span9">
                                            <table style="margin-bottom: 5px;" class="table table-bordered" id="saleAcctList">
                                                <thead>
                                                <th><?php echo $this->lang->line('saleaccountno') ?></th>
                                                <th class="tar"><?php echo $this->lang->line('saleAmount') ?></th>
                                                <th class="tar"><?php echo $this->lang->line('percentage') ?></th>
                                                <th class="tar"><?php echo $this->lang->line('amtAllo') ?></th>
                                                <th>Action</th>
                                                </thead>
                                                <tbody>
                                                    <?php 
                                                    if ($saleAllocationDetail){
                                                        foreach ($saleAllocationDetail as $row) {
                                                    
                                                    ?>
                                                    <tr>
                                                        <td><?php echo $row->acct; ?></td>
                                                        <td class="tar"><?php echo number_format($row->saleAmount,2); ?></td>
                                                        <td class="tar"><?php echo number_format($row->contributionPercentage,2); ?>%</td>
                                                        <td class="tar"><?php echo number_format($row->amount,2); ?></td>
                                                        <td><a onclick="deleteSalesAcct(this, <?php echo $row->ID ?>)" class="btn-icon btn-mini btn-danger-form"><i class="i-trashcan"></i></a></td>
                                                    </tr>
                                                    <?php
                                                        }}
                                                    ?>
                                                    <tr id="trInfosSale">
                                                        <td>
                                                            <?php
                                                            $preselcurr = '0';
                                                            $options = '';
                                                            $options[NULL] = '--Please Select--';
                                                            foreach ($chargeAccount as $row) {
                                                                $options[$row->ID] = substr($row->acctCode,0,4).'-'.substr($row->acctCode,4,3).'-'.substr($row->acctCode,7) . ' | ' . $row->acctName;
                                                            }
                                                            $js = ' id="saleAcctNo" onchange="getSaleAmount()" class = "span12 validate[required]"';
                                                            echo form_dropdown('chargeAccount', $options, $preselcurr, $js);
                                                            ?>    
                                                        </td>
                                                        <td><input readonly class="span12 tar" id="iSaleAmt" type="text" /></td>
                                                        <td>
                                                            <div class="input-prepend input-append">
                                                                <input class="span8 tar" type="text" onkeyup="calculateAmtAll()" id="iPerAll" />
                                                                <span class="add-on">&#37;</span>
                                                            </div>
                                                        </td>
                                                        <td><input readonly class="span12 tar" id="iAmtAll" type="text" /></td>
                                                        <td><a href="#trInfos" onclick="insertRow()" class="btn-icon btn-mini btn-success-form"><i class="i-checkmark-3"></i></a></td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>

                            <div style="display:none;" id="rowSale" class="controls-row"> <!-- row 2 -->
                                <div class="span2"></div>              
                                <div class="span2 TAR" ><?php echo $this->lang->line('amountallocated') ?></div>
                                
                                
                                <div class="span3">
                                    <?php
                                    $data = array(
                                        'onchange' => 'updateAmnt()',
                                        'placeholder' => 'Amount Aloccated',
                                        'readonly'=> 'true',
                                        'data-oldValue' => $mRow->amountAllocated,
                                        'value'=> number_format($mRow->amountAllocated,2),
                                        'name' => 'saleAmntAllocated',
                                        'id' => 'saleAmntAllocated',
                                        'class' => 'span12 tar');
                                    echo form_input($data, set_value('contributionPercentageLumpSum'));
                                    ?>      
                                </div> 
                                
                            </div><!-- End Row 2 -->
                              
                        </div>  <!-- content -->
                        </form>
                    </div>  <!-- block -->
                </div>  <!-- span12 -->
            </div>  <!-- row-fluid -->
            
            
            
            <?php 
                     $echo = '<script>';
                     if($mRow->allocation==1)
                       $echo = $echo.'$("#bySale").trigger("click");';
                     else
                        if($mRow->allocation==2) 
                             $echo = $echo.'$("#byAccrual").trigger("click");';
                         else
                             if($mRow->allocation==3) 
                                $echo = $echo.'$("#byProfit").trigger("click");';
                             else
                                 $echo = $echo.'$("#fixedAmnt").trigger("click");';
                       $echo = $echo. '$("#waqif").val('.$mRow->waqifID.');'.'$("#acAmountAllocated").val('.$mRow->waqifID.');';
                       $echo = $echo. '$("#waqfCenter").val('.$mRow->wakafCenterID.');'.'$("#proAmountAllocated").val('.$mRow->amountAllocated.');';
                      echo $echo.'</script>';
                                    } } ?>
            
            <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('benificiaries') ?></h2>
                                             <ul class="fr 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="addNewBene()" title="Add New"><span class="i-plus-2"></span></a></li>
                            </ul>                                    
                                        </div><!-- head -->
                                        <div class="content np">
                                            <table id="listDetails" cellpadding="0" cellspacing="0" width="100%">
                                                <thead>
                                                    <tr>
                                                        <th>#</th>
                                                        <th><?php echo $this->lang->line('beneCate') ?></th>
                                                        <th><?php echo $this->lang->line('nameDesc') ?></th>
                                                        <th><?php echo $this->lang->line('percentage') ?></th>
                                                        <th><?php echo $this->lang->line('amount') ?></th>
                                                        <th><?php echo $this->lang->line('action') ?></th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                   <?php 
                                                   $i= 0;
                                                   $t = 0;
                                                   $amt = 0;
                                                    if($details){
                                                         foreach($details as $row){
                                                             $t += $row->contributionPercentage;
                                                             $amt += $row->amount;
                                                   ?>
                                                    
                                                    <tr>
                                                        <td><?php echo ++$i; ?></td>
                                                        <td><?php echo $row->benef; ?></td>
                                                        <td><?php echo $row->description; ?></td>
                                                        <td class="tar"><?php echo $row->contributionPercentage; ?></td>
                                                        <td class="tar"><?php echo number_format($row->amount,2); ?></td>
                                                        <td>
                                                            <button data-beneId="<?php echo $row->beneficiariesID ?>" data-myid="<?php echo $row->ID ?>" onclick="editRow(this)" 
															class="btn-icon btn-mini btn-warning-form"><i class="i-pen"></i></button>
                                                            <button onclick="deleteFromDb(this, <?php echo $row->ID ?>)" class="btn-icon btn-mini btn-danger-form"><i class="i-trashcan"></i></button>
                                                        </td>
                                                    </tr>
                                                    
                                                    <?php 
                                                         }
                                                    }
                                                    ?>
                                                    <tr id="trInfos" data-currentRow="<?php echo $i; ?>" >
                                                        <td class="span8" colspan="3" style="text-align:right;">
                                                            Total 
                                                        </td>
                                                        <td class="span1">
                                                             <div class="input-prepend input-append">
                                                                 <input data-currentValue="<?php echo $t; ?>" readonly value="<?php echo $t; ?>" class="span8 tar" id="totalPercentage" type="text">
                                                                   <span class="add-on">&#37;</span>
                                                            </div>
                                                        </td>
                                                        <td class="span2">
                                                            <input class="span12 tar" id="totalAmountApplied" value="<?php echo number_format($amt,2); ?>"  data-currentAmount="0" readonly type="text" placeholder=" 0,00" />
                                                        </td>
                                                        <td>
                                                            <a class="btn-form btn-warning-form" href="#trInfos" onclick="addNewBene()" title="Add New"><span class="i-plus-2"></span></a>
                                                             
                                                        </td>
                                                    </tr>
                                                </tbody>
                                            </table>     
                                        </div><!-- content -->
                                    </div><!-- grid block 1-->
                                </div><!-- scCol -->
                            </div><!-- row-fluid scRow-->
                            
                           
                             <div class="row-fluid scRow">  
                    <div class="span8 scCol">
                        <div class="block" id="grid_block_4">
                            <div class="content">
                                <div style="padding:0;" class="controls-row">
                                    <div id="msg_div" style="min-height: 22px;" class="alert alert-info"> <p></p> </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="span4 scCol">
                        <div class="block" id="grid_block_4">
                            <div class="content">
                                <div class="controls-row side fr">
                                     <?php
                                        $data = array(
                                            'name' => 'validate',
                                            'style' => 'margin-right:5px;',
                                            'class' => 'btn-form btn-warning-form',
                                            'onClick' => "$('#validate').validationEngine('hide');");
                                        echo form_button($data, 'Hide prompts');
                                      
                                        ?>
                                    
                                </div>
                            </div>
                        </div>
                    </div>
                    
                </div><!-- row-fluid scRow-->
        </div>  <!-- content -->
    </div>  <!-- wrap -->
</div>  <!-- content -->
