<script type="text/javascript">
    $(document).ready(function() {
        /* Build the DataTable with third column using our custom sort functions */
        $('select').select2();
        //$("table.editable").die();
        var oTable = $("#test").dataTable({
            "iDisplayLength": 10,
            "aLengthMenu": [5, 10, 25, 50, 100],
            "sPaginationType": "full_numbers", "aoColumns": [
                {"bSortable": false},
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                {"bSortable": false},
                {"bSortable": false}]});
        oTable.fnSort([[1, 'asc']]);
        $("table .checkall1").live("click", "checkall1", function() {
            //$(oTable.fnGetNodes()).find(':checkbox').prop('checked', this.checked); //Checked entire checkboxes.

            $(".dataTable tbody tr .checkbox").attr('checked', this.checked);	//sayem(26-12-2014).checked only checkboxes in currenct page.
        });

        $('.paginate_button').live('click', function() {
            var chkBoxLen = $(".dataTable tbody tr .checkbox").length;
            var chkedLen = $(".dataTable tbody tr .checkbox:checked").length;
            if (chkBoxLen == chkedLen) {
                $("#checkall1").attr('checked', 'checked');
            } else {
                $("#checkall1").attr('checked', false);
            }
        });

        $("table.editable").on("click", ".remove", function() {
            var target = "yes";
            rRow = $(this).parents("tr");
            ID = $('td:first', $(this).parents('tr')).text();

            $("#row_delete").dialog("open");
        });

        $("table.editable").on("click", ".unconfirm", function() {

            rRow = $(this).parents("tr");
            ID = $('td:first', $(this).parents('tr')).text();

            $("#unconfirm").dialog("open");
        });

        $("#unconfirm").dialog({
            autoOpen: false,
            resizable: false,
            modal: true,
            buttons: {
                "Unconfirm": function() {
//				window.location.href = "<?php echo base_url() ?>po_transaction/purchaseOrderCancel/" + ID;
                    //window.location.href = "purchaseOrderCancel?ID=" + ID;		
                    fct_unconfirm(rRow);

                    $(this).dialog("close");
                },
                Cancel: function() {
                    $(this).dialog("close");
                }
            }
        });


        function fct_unconfirm(row) {
            var journalID = $('td:first', row).attr("data-journalNo");
            var formNo = $('td:first', row).attr("data-formNo");
            $.ajax({
                type: "POST",
                url: "<?php echo base_url() ?>gltransaction/journalUnconfirm",
                data: {
                    journalID: journalID,
                    ID: ID,
                    formNo: formNo
                },
                success: function(data) {

                    if ($.trim(data) == "success") {
                        alertbox("Unconfirming successfully done ...", 1);
                        row.remove();
                    } else {
                        alertbox($.trim(data) + " ...", 2);
                    }
                }
            });       // Here your ajax action after delete confirmed
        }

        function fct_unconfirm_get_msg(row) {
            var journalID = $('td:first', row).attr("data-journalNo");
            var formNo = $('td:first', row).attr("data-formNo");
            $.ajax({
                type: "POST",
                url: "<?php echo base_url() ?>gltransaction/journalUnconfirm",
                data: {
                    journalID: journalID,
                    ID: ID,
                    formNo: formNo
                },
                success: function(data) {

                    if ($.trim(data) == "success") {
                        alertbox("Unconfirming successfully done ...", 1);
                        row.remove();
                    } else {
                        alertbox($.trim(data) + " ...", 2);
                    }
                },
            });       // Here your ajax action after delete confirmed
        }

        function remove_row(row) {
            row.remove();
            $.ajax({
                type: "POST",
                url: "<?php echo base_url() ?>gltransaction/journalPostingDelete",
                data: "ID=" + ID,
                success: function() {
                    alert('Row has been deleted...');
                    window.location.reload(true);
                },
            });       // Here your ajax action after delete confirmed
        }
        $("#row_delete").dialog({
            autoOpen: false,
            resizable: false,
            modal: true,
            buttons: {
                "Delete": function() {
                    //window.location.href = "<?php echo base_url() ?>po_transaction/purchaseOrderCancel/" + ID;
                    //window.location.href = "purchaseOrderCancel?ID=" + ID;		
                    remove_row(rRow);
                    $(this).dialog("close");
                },
                Cancel: function() {
                    $(this).dialog("close");
                }
            }
        });

        $("table.editable").on("click", ".edit", function() {
            rRow = $(this).parents("tr");
            ID = $('td:first', $(this).parents('tr')).text();
            //$("#row_edit").dialog("open");
            window.location.href = "<?php echo base_url(); ?>glreports/journalDetails/" + ID;
        });
    });

    function changeList() {
        var addyear = $('#add_year option:selected').val();
        var addper = $('#add_period option:selected').val();
        var urls = "<?php echo base_url(); ?>Gltransaction/posting/" + addyear + "/" + addper;
        window.location = urls;
    }

    function postJournal() {
        $("#postjournal").button("disable");
        var oTable = $("#test").dataTable( );
        var rows = $(oTable.fnGetNodes()).find(':checkbox:checked').length;
        var count = 0;
        $(oTable.fnGetNodes()).find(':checkbox').each(function() {
            if ($(this).is(':checked')) {
                var fldid = $('td:first', $(this).parents('tr')).text();
                var journalNo = $('td:eq(2)', $(this).parents('tr')).text();
                var postData = {
                    'fldid': fldid,
                    'journalNo': journalNo
                };
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: "<?php echo base_url() ?>Gltransaction/journalPosting",
                    data: postData,
                    async: false,
                    success: function(content) {
                        count++;
                    }
                });
            }
            if (count == rows) {
                window.location.reload(true);
            }
        });
    }
    
    function fct_unpost_trans(me) {
        $('#popupModal').modal('show');
        $("#_popupContent").html('\n\
                        <p style="font-size:14px;">You are about to unpost this journal</p>\n\
                        <br/><b>Click on OK to continue</b>');
        $('#_popupFooter').empty();
        $('#_popupFooter').append('<button targetBtn="' + $(me).attr("id") + '" data-dateJournal="'+ $(me).attr("data-dateJournal") +'" data-ID ="' + $(me).attr("data-ID") + '" data-journalNo ="' + $(me).attr("data-journalNo") + '" data-formNo ="' + $(me).attr("data-formNo") + '" class="btn-form btn-success-form" id="confButton">Ok</button>' +
                '<button class="btn-form btn-danger-form" id="canb">Cancel</button>');
        $("#_popupTitle").html("Unposting");
        $("#canb").click(function() {
            $('#popupModal').modal('hide');
        });
        $("#confButton").click(function() {
            var journalID = $(this).attr("data-journalNo");
            var ID = $(this).attr("data-ID");
            var dateJournal = $(this).attr("data-dateJournal");
            var formNo = $(this).attr("data-formNo");
            var targetRow = $("#" + $(this).attr("targetBtn")).parent().parent();
            $('#popupModal').modal('hide');
            $.ajax({
                type: "POST",
                url: "<?php echo base_url() ?>gltransaction/journalUnpost",
                data: {
                    journalID: journalID,
                    ID: ID,
                    formNo: formNo,
                    dateJournal: dateJournal
                },
                success: function(data) {

                    if ($.trim(data) == "success") {
                        alertbox("Unconfirming successfully done ...", 1);
                        targetRow.remove();
                    } else {
                        alertbox($.trim(data) + " ...", 2);
                    }
                },
            });       // Here your ajax action after delete confirmed


        });
    }

    function fct_unconfirm_trans(me) {
        $('#popupModal').modal('show');
        $("#_popupContent").html('\n\
                        <p style="font-size:14px;">Unconfirming this transaction  will delete the journal and allowing you to edit and confirm it back</p>\n\
                        <br/><b>Click on OK to continue</b>');
        $('#_popupFooter').empty();
        $('#_popupFooter').append('<button targetBtn="' + $(me).attr("id") + '" data-ID ="' + $(me).attr("data-ID") + '" data-journalNo ="' + $(me).attr("data-journalNo") + '" data-formNo ="' + $(me).attr("data-formNo") + '" class="btn-form btn-success-form" id="confButton">Ok</button>' +
                '<button class="btn-form btn-danger-form" id="canb">Cancel</button>');
        $("#_popupTitle").html("Unconfirm Transaction");
        $("#canb").click(function() {
            $('#popupModal').modal('hide');
        });
        $("#confButton").click(function() {
            var journalID = $(this).attr("data-journalNo");
            var ID = $(this).attr("data-ID");
            var formNo = $(this).attr("data-formNo");
            var targetRow = $("#" + $(this).attr("targetBtn")).parent().parent();
            $('#popupModal').modal('hide');
            $.ajax({
                type: "POST",
                url: "<?php echo base_url() ?>gltransaction/journalUnconfirm",
                data: {
                    journalID: journalID,
                    ID: ID,
                    formNo: formNo
                },
                success: function(data) {

                    if ($.trim(data) == "success") {
                        alertbox("Unconfirming successfully done ...", 1);
                        targetRow.remove();
                    } else {
                        alertbox($.trim(data) + " ...", 2);
                    }
                },
            });       // Here your ajax action after delete confirmed


        });
    }

    function selectYearPeriod(obj) {
        var year = obj.value;
//		alert(year);

        $.ajax({
            type: "POST",
            dataType: "json",
            url: "<?php echo base_url() ?>glreports/get_TrialBalance_year/" + year,
            data: year,
            async: false,
            success: function(content) {
                if (content.status == "success") {
                    var items = [];
                    //items.push('<option>-Please Select-</option>');
                    for (var i = 0; i < content.message.length; i++) {
                        items.push('<option value="' + content.message[i].period + '">'
                                + content.message[i].financialPeriod + '</option>');
                    }  //end for
                    jQuery("#add_period").empty();
                    jQuery("#add_period").append(items.join('</br>'));
                    //$("#add_period").select2('val',null);
                    $("#add_period").select2();
                } else {
                    jQuery("#add_period").empty();
                    $("#add_period").select2('val', null);
                    $("#error").html('<p>' + content.message + '</p>');
                } //end if
            } //end success

        }); //end ajax
//	window.location.reload(true); 
    }
	
	
	function postJournalList(){
		window.open("<?php echo base_url();?>gltransaction/postJournalPrint");
	}
        
        function set_para_display_option(me){
            if($(me).val()=="1"){
                $("#postjournal").css("display","none");
            }else{
                $("#postjournal").css("display","inline-block");
            }
        }

</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() . "GeneralLedger" ?>'><?php echo $this->lang->line('module') ?></a> <span class="divider">-</span></li>
                    <li class="active"><?php echo $this->lang->line('title2') ?></li>
                </ul>
            </div><!-- info -->
            <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">
			<div class="row-fluid">
				<form method="post" action="<?php echo base_url(); ?>gltransaction/posting">
                <div class="span12">
					<div class="block">
						<div class="head">
							<h2><?php echo $this->lang->line('searchParam') ?></h2>
                            <ul class="buttons">
								<li><a href="#" class="block_toggle"><span class="i-arrow-down-3"></span></a></li>
                            </ul>
						</div><!-- head -->
                        <div class="content np">    
							<div class="controls-row"><!-- Row 1-->								
								<div class="span5">
								<div class="span5"><?php echo form_label($this->lang->line('year'), 'add_year'); ?> </div>
									<div class="span7">
                                    <?php
                                    $preselyear = $selyear;
                                    $options = '';
                                    $options[] = $this->lang->line('selectyear');
                                    if (isset($yrs) && !empty($yrs)) {
										foreach ($yrs as $row) {
										$options[$row] = $row;
                                        }
                                    }
                                    $js = 'onchange="selectYearPeriod(this)" name="add_year" class="span12" id="add_year"';
										echo form_dropdown('add_year', $options, $preselyear, $js);
                                    ?>     
                                    </div>  
								</div>								
								<div class="span5 tac">
								<div class="span2"><?php echo form_label($this->lang->line('period'), 'add_period'); ?></div>
									<div class="span10">
                                    <?php
                                    $preselperiod = $selper;
                                    $options = '';
                                    $options[] = $this->lang->line('period');
                                    if ($period) {
										foreach ($period as $row) {
                                        $options[$row->period] = $row->financialPeriod;
										}
									}
                                    $js = 'class="span12" name="add_period" id="add_period" style="width:75%"';
										echo form_dropdown('add_period', $options, $preselperiod, $js);
									?>       
                                    </div>
								</div>
							</div><!-- End Row 1-->
                            <div class="controls-row"><!-- Row 1-->
								<div class="span5 ">
									<div class="span5">Display Option</div>
									<div class="span7">
                                                                            <select onchange="set_para_display_option(this)" name="para_display_option" id="para_display_option" class="span12">
											<option <?php if ($para_display_option == "0") echo "selected='selected'"; ?> value="0">Unposted Journal</option>
                                            <option <?php if ($para_display_option == "1") echo "selected='selected'"; ?>value="1">Posted Journal</option>
                                        </select>
                                    </div>
								</div>
							</div><!-- End Row 1-->
						</div><!-- content np-->
                        <div class='footer'>
							<div class='side fr'>
								<input class="btn-form btn-success-form" type="submit" value="<?php echo $this->lang->line('submit'); ?>" />
                                <?php
//                             	$data = array(
//                              	'name' => 'mysubmit',
//                                  'class' => 'btn-form btn-success-form');
//                             	$js = "onClick='changeList()'";
//                              	echo form_button($data, $this->lang->line('submit'), $js);
								?>
                            </div>
						</div>
						
					</div><!-- block -->
				</div><!-- span12 -->
			</div><!-- row fluid -->
            
			<div class="row-fluid">
				<div class="span12">
					<div class="block">
						<div class="head">
							<h2><?php echo $this->lang->line('searchResult') ?></h2>
                            <ul class="buttons">
								<li><a href="#" class="block_toggle"><span class="i-arrow-down-3"></span></a></li>
                            </ul>
                            <!--<div class="side fr">
								<a href="" name="updatePosting" class="btn-form btn-success-form" onClick="postJournalList()">Print</a>
							</div>-->
						</div>
                        <div class="content np table-sorting">
							<table cellpadding="0" cellspacing="0" width="100%" id="test" class="editable">
								<thead>
									<tr>
										<th style="display:none"></th>
                                        <th class="tac">#</th>
                                        <th><?php echo $this->lang->line('jlnumber') ?></th>
                                        <th><?php echo $this->lang->line('referenceNo') ?></th>
                                        <th class="tac"><?php echo $this->lang->line('year') ?></th>
                                        <th class="tac"><?php echo $this->lang->line('period') ?></th>
                                        <th><?php echo $this->lang->line('description') ?></th>
                                        <th><?php echo $this->lang->line('total') ?></th>
                                        <th class="tac"><input type="checkbox" id="checkall1" class="checkall1"/></th>
                                        <th class="tac"><?php echo $this->lang->line('action') ?></th>
									</tr>
								</thead>
								<tbody>
                                <?php
                                $bil = 0;
                                if ($datatbls) {
									foreach ($datatbls as $datatbl):
                                    $bil++
                                ?>
									<tr>
										<td data-formNo="<?php echo $datatbl->formNo; ?>" data-journalNo="<?php echo $datatbl->journalID; ?>" style="display:none" ><?php echo $datatbl->ID; ?></td>
                                        <td class="tac"><?php echo $bil; ?></td>
                                        <td><a title="<?php echo $this->lang->line('details'); ?>" class="btn btn-mini btn-link edit"><?php echo $datatbl->journalID ?></a></td>
                                        <td class="tac"><?php echo $datatbl->refNo; ?></td>
                                        <td class="tac"><?php echo $datatbl->year ?></td>
                                        <td class="tac"><?php echo $datatbl->period; ?></td>
                                        <td><?php echo $datatbl->description; ?></td>
                                        <td><?php echo number_format($datatbl->total_amount_cr,2); ?></td>
                                        <td class="tac"><?php if ($datatbl->total_amount == 0) { ?><input type="checkbox" class="checkbox" id="checkbox"/> 
                                        <?php
											} else {
												echo $this->lang->line('balance');
											?> : <?php
												echo $datatbl->total_amount;
                                            }
                                        ?> 
                                        </td>
                                        <td class="tac">
										<?php
                                      	/**if ($datatbl->module == 1) {
                                          	$js = 'class="btn-icon btn-mini btn-danger-form remove"  title="' . $this->lang->line('delete') . '"';
                                              	echo form_button('remove_'.$datatbl->ID, '<span class="i-trashcan">', $js);
                                          } else {
                                          	$js = 'class="btn-icon btn-mini btn-warning-form unconfirm"  title="' . $this->lang->line('unconfirm') . '"';
                                              	echo form_button('unconfirm_'.$datatbl->ID, '<span class="i-reply"></span> ', $js);
                                          }**/
										if ($datatbl->module == 1) {
											if ($para_display_option == "0"){
												$js = 'class="btn-icon btn-mini btn-danger-form remove"  title="' . $this->lang->line('delete') . '"';
													echo form_button('remove_' . $datatbl->ID, '<span class="i-trashcan">', $js);
												}else{
													$js = 'class="btn-icon btn-mini btn-danger-form" id="unpost_' . $datatbl->ID . '" data-formNo="' . $datatbl->formNo . '" data-dateJournal="' . $datatbl->effective_date . '" data-journalNo="' . $datatbl->journalID . '" data-ID="' . $datatbl->ID . '" onclick="fct_unpost_trans(this)"  title="' . $this->lang->line('unpost') . '"';
														echo form_button('unconfirm_' . $datatbl->ID, '<span class="i-ccw"></span> ', $js);
													}
											} else {
                                            if ($para_display_option == "0"){
												$js = 'class="btn-icon btn-mini btn-warning-form" id="unconfirm_' . $datatbl->ID . '" data-dateJournal="' . $datatbl->effective_date . '" data-formNo="' . $datatbl->formNo . '" data-journalNo="' . $datatbl->journalID . '" data-ID="' . $datatbl->ID . '" onclick="fct_unconfirm_trans(this)"  title="' . $this->lang->line('unconfirm') . '"';
													echo form_button('unconfirm_' . $datatbl->ID, '<span class="i-reply"></span> ', $js);
												}else{
                                                 $js = 'class="btn-icon btn-mini btn-danger-form" id="unpost_' . $datatbl->ID . '" data-dateJournal="' . $datatbl->effective_date . '" data-formNo="' . $datatbl->formNo . '" data-journalNo="' . $datatbl->journalID . '" data-ID="' . $datatbl->ID . '" onclick="fct_unpost_trans(this)"  title="' . $this->lang->line('unpost') . '"';
													echo form_button('unconfirm_' . $datatbl->ID, '<span class="i-ccw"></span> ', $js);
                                                }
											}
										?></td>
									</tr>
										<?php
                                            endforeach;}?>
								</tbody>
							</table>
						</div><!-- content np-->
						<div class="footer">
							<div class="side fr">
								<div class="btn-group">
									<?php
                                    // The problem with this code it submit the form before finish all ajax call (Sayem-28/9/2015)
                                    /*$data = array(
										'name' => 'postjournal',
                                        'id' => 'postjournal',
                                        'class' => 'btn-form btn-warning-form');
									$js = 'onclick="postJournal()"';
										echo form_submit($data, $this->lang->line('postjournal'), $js);*/
                                    ?>
                                    <a id="postjournal" <?php if ($para_display_option == "1") echo "style='display:none;'"; ?> href="javascript:" onclick="postJournal()" class="btn-form btn-warning-form "><?php echo $this->lang->line('postjournal'); ?></a>
								</div>
							</div>
						</div> 
							</form>
					</div><!-- block -->
				</div><!-- span12 -->
			</div><!-- row-fluid -->	
           
      </div><!-- content class -->
	</div><!-- wrap -->
</div><!-- content id -->	
<div class="dialog" id="row_delete" style="display: none;" title="Delete?">
    <p>Row will be deleted</p>
</div>
<div class="dialog" id="unconfirm" style="display: none;" title="Unconfirming Transaction">
    <p>Your about to un-confirm this transaction</p>
    <p><i>To confirm back this transaction go to related transaction menu</i></p>
</div>
<div class="dialog" id="row_edit" style="display: none;" title="Edit ?">
    <p><?php echo $this->lang->line('message2'); ?></p>
</div>