var TableAdvanced = function () {

    var initTable1 = function() {
        /* Formatting function for row details */
        function fnFormatDetails ( oTable, nTr ){
				 
			 $.extend({
					getValues: function() {
						var pathArray = window.location.pathname.split( '/' );
						var pathArray_len = pathArray.length - 4;
						var script_url_dush = "";
						$.each(pathArray,function(i,e){
							if(i<pathArray_len)
							script_url_dush += "../";
						})
						
						var sOut = null;
						var pid = $( nTr ).attr( "pd" );
						var script_url = script_url_dush+ "loan/loan/";
					//	var script_url = "../../../../../index.php/loan/loan/";
						console.log(script_url+"loan_process/"+pid);
						$.ajax({
						    url: script_url+"loan_process/"+pid,
							dataType: 'json',
							type: 'get',
							async: false,
							success: function(data) {
								 sOut = '<style>td.details table tr td.Reschedule{background:none repeat scroll 0 0 #35aa47 !important;color:white;font-weight:bold;}td.details table tr td.PayOffSlip{background:none repeat scroll 0 0 #4d90fe !important;color:white;font-weight:bold;}td.details table tr td.write_off{background:none repeat scroll 0 0 #d84a38 !important;color:white;font-weight:bold;}.paid{background:none repeat scroll 0 0 #EEE !important;}</style><table width="100%" border="1">'+
									'<tr>'+
										'<th >No.</th>'+
										'<th>Date</th>'+
										'<th>Interest</th>'+
										'<th>Principal</th>'+
										'<th>Principal Balance</th>'+
										'<th>AccPrinciple</th>'+
										'<th>Amount Paid</th>'+
										'<th>Amount Credit</th>'+
										'<th>AccInterest</th>'+
										'<th>Payment</th>'+
										'<th>Payment Owed</th>'+
										'<th>Status</th>'+										
									'</tr>';
									var check_btn_pay = false; 
									$paid1 = '<a data-toggle="modal" href="#paid_popup" class="btn btn-xs green" title="Paid History"  onclick="history_payment(this)"><i class="fa fa-check-circle"></i></a>';
									for(i=0; i<data.length; i++){
										$loan_payment = data[i];
										if($loan_payment.ploStatus == 5){// if status is padding
											$paid = '<span style="color:green;"><i class="icon-refresh"></i>  Padding</span>';	
										}else if($loan_payment.ploStatus == 6){ // if status is Cancel
											$paid = '<span style="color:red;"><i class="icon-warning-sign"></i>  Cancel</span>';	
										}else{
											if(check_btn_pay === true){
												$paid = '<button type="button" class="btn btn-xs"  title="Not Allow" ><i class="fa fa-check-circle"></i></button>';	
											}else{
												if($loan_payment.loanprocess_paid==1){													
													$paid = '<a target="_blank" href="'+script_url+'print_invoice/'+$loan_payment.id+'" onclick="print_invoice(this)" class="btn btn-xs btn-outline-success"  title="Print Invoice" ><i class="fa fa-print"></i></a> ' +" Paid: "+$loan_payment.loanprocess_datepaid;
												}else if($loan_payment.loanprocess_paid==2){
													if($loan_payment.noPayButton == 'nopaybutton'){
														$paid = '';	
													}else{
														$paid = '<a data-toggle="modal" href="#pay" onclick="pay(this)" class="btn btn-xs blue"  title="Pay" ><i class="fa fa-check-circle"></i></a>'+' <a  target="_blank" href="'+script_url+'print_invoice/'+$loan_payment.id+'" onclick="print_invoice(this)" class="btn btn-xs red"  title="Print Invoice" ><i class="fa fa-print"></i></a> ' +" Paid: "+$loan_payment.loanprocess_datepaid;
														check_btn_pay = true;
													}
												}else{
													if($loan_payment.ploStatus !=4){
														if($loan_payment.noPayButton == 'nopaybutton'){
															$paid = '';	
														}else{
															$paid = '<a data-toggle="modal" href="#pay" onclick="pay(this)" class="btn btn-xs btn-outline-primary"  title="Pay" ><i class="fa fa-check-circle"></i></a>' +" Pending ";
															check_btn_pay = true;
														}
													}else{
														// not display button pay because it alreay sale 
														$paid = 'Sold: '+$loan_payment.loSaleDate;
													}
												}
											}
										}
										$paid = '<div class="btn-action-pay-fix"><div>'+$paid+'</div></div>';
										
											if($loan_payment.loanprocess_paid==1){

												sOut += '<tr pd="'+$loan_payment.id+'">'+
													'<td class="paid">'+(i+1)+'</td>'+
													'<td class="paid">'+$loan_payment.loanprocess_datepayment+'</td>'+
													'<td class="paid">'+$loan_payment.loanprocess_interest+'</td>'+
													'<td class="paid">'+$loan_payment.loanprocess_principle+'</td>'+
													'<td class="paid">'+$loan_payment.loanprocess_principleos+'</td>'+
													'<td class="paid">'+$loan_payment.loanprocess_accprinciple+'</td>'+
													'<td class="paid">'+$loan_payment.loanprocess_amountpaid+'</td>'+
													'<td class="paid">'+$loan_payment.loanprocess_amountcredit+'</td>'+
													'<td class="paid">'+$loan_payment.loanprocess_accinterest+'</td>'+
													'<td class="paid">'+$loan_payment.loanprocess_owe+'</td>'+
													'<td class="paid">'+$loan_payment.loanprocess_owepay+'</td>'+	
													'<td class="paid">'+$paid+'</td>'+
												'</tr>';
											}else{
												sOut += '<tr pd="'+$loan_payment.id+'">'+
													'<td>'+(i+1)+'</td>'+
													'<td>'+$loan_payment.loanprocess_datepayment+'</td>'+
													'<td>'+$loan_payment.loanprocess_interest+'</td>'+
													'<td>'+$loan_payment.loanprocess_principle+'</td>'+
													'<td>'+$loan_payment.loanprocess_principleos+'</td>'+
													'<td>'+$loan_payment.loanprocess_accprinciple+'</td>'+
													'<td>'+$loan_payment.loanprocess_amountpaid+'</td>'+
													'<td>'+$loan_payment.loanprocess_amountcredit+'</td>'+
													'<td>'+$loan_payment.loanprocess_accinterest+'</td>'+
													'<td>'+$loan_payment.loanprocess_owe+'</td>'+
													'<td>'+$loan_payment.loanprocess_owepay+'</td>'+
													'<td>'+$paid+'</td>'+													
												'</tr>';
											}
										
									}
									sOut +='</table>';
							}
						});
					   return sOut;
					}
				});
			
		  	return $.getValues();
  	  
        };
		
		
        /*
         * Insert a 'details' column to the table
         */
        var nCloneTh = document.createElement( 'th' );
        var nCloneTd = document.createElement( 'td' );
        nCloneTd.innerHTML = '<span class="row-details icon-arrow-right"></span>';
         
        $('#sample_1 thead tr').each( function () {
            this.insertBefore( nCloneTh, this.childNodes[0] );
        } );
         
        $('#sample_1 tbody tr').each( function () {
            this.insertBefore(  nCloneTd.cloneNode( true ), this.childNodes[0] );
        } );
		
		$('#sample_1 tbody tr').click( function (e) {
			$('#sample_1 tbody tr').removeClass('tr_click');
            $(this).addClass('tr_click');
        } );
         
        /*
         * Initialize DataTables, with no sorting on the 'details' column
         */
        var oTable = $('#sample_1').dataTable( {
            "aoColumnDefs": [
                {"bSortable": false, "aTargets": [ 0 ] }
            ],
          
             "aLengthMenu": [
                [5, 15, 20, -1],
                [5, 15, 20, "All"] // change per page values here
            ],
            // set the initial value
            "iDisplayLength": 10,
        });

        jQuery('#sample_1_wrapper .dataTables_filter input').addClass("form-control input-small"); // modify table search input
        jQuery('#sample_1_wrapper .dataTables_length select').addClass("form-control input-small"); // modify table per page dropdown
        jQuery('#sample_1_wrapper .dataTables_length select').select2(); // initialize select2 dropdown
			
        /* Add event listener for opening and closing details
         * Note that the indicator for showing which row is open is not controlled by DataTables,
         * rather it is done here
         */
        $('#sample_1').on('click', ' tbody td .row-details', function () {
            var nTr = $(this).parents('tr')[0];
            if ( oTable.fnIsOpen(nTr) )
            {
                /* This row is already open - close it */
                $(this).addClass("icon-arrow-right").removeClass("icon-arrow-down");
                oTable.fnClose( nTr );
            }
            else
            {
                /* Open this row */                
                $(this).addClass("icon-arrow-down").removeClass("icon-arrow-right");
                oTable.fnOpen( nTr, fnFormatDetails(oTable, nTr), 'details' );
            }
        });
    }

     var initTable2 = function() {
        var oTable = $('#sample_2').dataTable( {           
            "aoColumnDefs": [
                { "aTargets": [ 0 ] }
            ],
            "aaSorting": [[1, 'asc']],
             "aLengthMenu": [
                [5, 15, 20, -1],
                [5, 15, 20, "All"] // change per page values here
            ],
            // set the initial value
            "iDisplayLength": 10,
        });

        jQuery('#sample_2_wrapper .dataTables_filter input').addClass("form-control input-small"); // modify table search input
        jQuery('#sample_2_wrapper .dataTables_length select').addClass("form-control input-small"); // modify table per page dropdown
        jQuery('#sample_2_wrapper .dataTables_length select').select2(); // initialize select2 dropdown

        $('#sample_2_column_toggler input[type="checkbox"]').change(function(){
            /* Get the DataTables object again - this is not a recreation, just a get of the object */
            var iCol = parseInt($(this).attr("data-column"));
            var bVis = oTable.fnSettings().aoColumns[iCol].bVisible;
            oTable.fnSetColumnVis(iCol, (bVis ? false : true));
        });
    }

    return {

        //main function to initiate the module
        init: function () {
            
            if (!jQuery().dataTable) {
                return;
            }

            initTable1();
            initTable2();
        }

    };

}();