<!-- JUMBOTRON -->
<section class="container" style="padding-bottom: 2rem;">
	<div class="card bg-light-transparent">
		<div class="card-body">
			<div class="card no-shadow" style="padding-top: 3rem; padding-bottom: 3rem;">
				<div class="card-body">
					<div class="row">
						<div class="col-md-4 text-center align-self-center">
							<img class="image-responsive" src="<?php echo base_url($user['file_location'].$user['file_name']); ?>" style="max-height: 15rem; max-width: 15rem;">
						</div>
						<div class="col-md-8">
							<h3><?php echo $user['name'] ?></h3>
							<p><?php echo $user['position_name'] ?></p>
							<p>Department: <?php echo $user['department_name'] ?> (<?php echo $user['branch_name'] ?>)</p>
							<hr class="my-4">
                            <div class="row">
                                <div class="col">
                                    <div class="card text-white bg-dark leave-info-card" data-v="">
                                        <div class="card-body">
                                            <h6 class="card-title">Total</h6>
                                            <p class="card-text float-right" style="font-size: 2rem;">
                                                <?php echo ($leave_info['leaveTotal'])?$leave_info['leaveTotal']:0; ?>
                                            </p>
                                        </div>
                                    </div>
                                </div>

                                <div class="col">
                                    <div class="card text-white bg-dark leave-info-card" data-v="pending">
                                        <div class="card-body">
                                            <h6 class="card-title">Pending</h6>
                                            <p class="card-text float-right" style="font-size: 2rem;">
                                                <?php echo ($leave_info['leavePending'])?$leave_info['leavePending']:0; ?>
                                            </p>
                                        </div>
                                    </div>
                                </div>

                                <div class="col">
                                    <div class="card text-white bg-dark leave-info-card" data-v="approved">
                                        <div class="card-body">
                                            <h6 class="card-title">Approved</h6>
                                            <p class="card-text float-right" style="font-size: 2rem;">
                                                <?php echo ($leave_info['leaveApproved'])?$leave_info['leaveApproved']:0; ?>
                                            </p>
                                        </div>
                                    </div>
                                </div>

                                <div class="col">
                                    <div class="card text-white bg-dark leave-info-card" data-v="rejected">
                                        <div class="card-body">
                                            <h6 class="card-title">Rejected</h6>
                                            <p class="card-text float-right" style="font-size: 2rem;">
                                                <?php echo ($leave_info['leaveRejected'])?$leave_info['leaveRejected']:0; ?>
                                            </p>
                                        </div>
                                    </div>
                                </div>

                                <div class="col">
                                    <div class="card text-white bg-dark leave-info-card" data-v="cancelled">
                                        <div class="card-body">
                                            <h6 class="card-title">Cancelled</h6>
                                            <p class="card-text float-right" style="font-size: 2rem;">
                                                <?php echo ($leave_info['leaveCancelled'])?$leave_info['leaveCancelled']:0; ?>
                                            </p>
                                        </div>
                                    </div>
                                </div>
                            </div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</section>

<!-- LIST OF LEAVE APPLICATION -->
<section class="container" style="padding-bottom: 2rem;">
    <div class="card bg-light-transparent">
        <div class="card-header bg-light">
            <div class="float-left">
                <!-- <button onclick="openApplicationModal();" type="button" class="btn btn-outline-dark btn-sm"><i class="fa fa-plus"></i> New Application</button> -->
                <a <?php if ($this->logged_module['role'] == 'user') echo 'hidden';?> href="<?php echo base_url('hr/leave/department/').$this->logged_user['department_id']; ?>" class="btn btn-outline-dark btn-sm" data-tooltip="tooltip"  data-trigger="hover" title="Go To My Department's Applications" style="margin-right: 3px;">My Dept</button>
                <a target="_blank" href="<?php echo base_url('hr/leave/application/'.$user['id'].'/'.$year.'/print'); ?>" class="btn btn-outline-dark btn-sm"><i class="fa fa-print"></i> Print</a>
                <!-- <button onclick="openRequestModal();" type="button" class="btn btn-outline-dark btn-sm"><i class="fa fa-plus"></i> Request Allocation</button> -->
                <!-- <button id="btnShowLeaveFilters" type="button" class="btn btn-outline-dark btn-sm" data-toggle="collapse" data-target="#collapseLeaveFilter"><i class="fas fa-filter"></i> Show Filters</button> -->
                <!-- &nbsp;&nbsp;&nbsp;<span style="vertical-align: middle;">Allowed Annual Leave for the current month, <?php echo $today->format('F, Y'); ?>: <b><?php echo number_format($prorate['allowed_leave'],1).' - '.number_format(($leave_info['leavePending'])?$leave_info['leavePending']:0,1); ?>(pending)</b> day(s)</span> -->
                &nbsp;&nbsp;&nbsp;<span style="vertical-align: middle;">Allowed Annual Leave for the current month, <?php echo $today->format('F Y'); ?>: 
                    <b>
                    <span id="allowed-span">
                    <?php 
                        // if($leave_info['leavePending'] > $prorate['allowed_leave']){
                        //     echo number_format(0,1);
                        // }else{
                        //     $remLeave = $prorate['allowed_leave'] - $leave_info['leavePending'] - $leave_info['leaveApproved'];
                        //     echo number_format($remLeave, 1);
                        // } 
                    ?> (<?php echo (number_format(($leave_info['leavePending'])?$leave_info['leavePending']:0,1)); ?> pending)
                    </span>
                    </b>
                    </span>
            </div>
            <div class="float-right">
                <button onclick="openSummaryModal();" type="button" class="btn btn-outline-dark btn-sm" data-tooltip="tooltip"  data-trigger="hover" title="Leave Summary"><i class="fa fa-info"></i></button>
            </div>
            <div class="col-sm-3 float-right">
                <div class="row">
                    <label class="col text-right" for="entitlementYear">Year: </label>
                    <select class="form-control col mr-3" id="entitlementYear">
                    <?php if(!empty($years)) foreach($years as $year): ?>
                        <option <?php if($year['year'] == $curr_year) echo 'selected'; ?> value="<?php echo $year['year'] ?>"><?php echo $year['year'] ?></option>
                    <?php endforeach; ?>
                    </select>
                </div>
            </div>
        </div>
        <!--div class="collapse" id="collapseLeaveFilter">
            <div class="card-header">
                <div class="row">
                    <div class="col-md-6">
                        <div class="card no-shadow">
                            <div class="card-body">
                                Lorem ipsum dolor sit amet consectetur adipisicing elit. Ex, sed. Veritatis fugiat quasi expedita accusantium inventore quo dolor magnam. Ex soluta itaque quibusdam illum veritatis earum odio porro corrupti enim.
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="card no-shadow">
                            <div class="card-body">
                                Lorem ipsum dolor sit amet consectetur adipisicing elit. Molestiae a, quae fugiat tempora animi ipsam? Vero distinctio et tenetur earum quod, rem, adipisci hic explicabo ipsam dolore nulla cumque magnam.
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div-->
        <div class="card-body">
            <div class="card no-shadow">
                <div class="card-body">
                    <ul class="nav nav-pills mb-3" id="pills-tab" role="tablist">
                        <li class="nav-item" role="presentation">
                            <a class="nav-link active" id="pills-calendar-tab" data-toggle="pill" href="#pills-calendar" role="tab" aria-controls="pills-calendar" aria-selected="true">Calendar</a>
                        </li>
                        <li class="nav-item" role="presentation">
                            <a class="nav-link" id="pills-list-tab" data-toggle="pill" href="#pills-list" role="tab" aria-controls="pills-list" aria-selected="false">List</a>
                        </li>
                    </ul>
                    <div class="tab-content" id="pills-tabContent">
                        <!-- calendar view -->
                        <div class="tab-pane fade show active" id="pills-calendar" role="tabpanel" aria-labelledby="pills-calendar-tab">
                        <div class="container">
                                <div class="row" style="margin-top: 20px;">
                                    <div class="col-12" >
                                        <div id="leaveContainer" class="mx-2 mt-2 mb-2 d-flex justify-content-center"></div>
                                        <div class="mt-2 d-flex justify-content-center">
                                            <p class="text-danger" id="calendar-error"></p>
                                        </div>
                                        <div id="calendar"></div>
                                        <div id="legendContainer" class="mt-2 d-flex justify-content-center"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- history/list view -->
                        <div class="tab-pane fade" id="pills-list" role="tabpanel" aria-labelledby="pills-list-tab">
                            <div class="table-responsive">
                                <table id="table_applications" class="table table-bordered table-striped table-hover">
                                    <thead>
                                        <th>No.</th>
                                        <th>Status</th>
                                        <th>Leave Type</th>
                                        <th>Date</th>
                                        <th>Day(s)</th>
                                        <!-- <th>Period Start</th>
                                        <th>Date End</th>
                                        <th>Period End</th> -->
                                        <th>Attachment</th>
                                        <!-- <th>Date Applied</th> -->
                                        <th></th>
                                    </thead>
                                    <tbody>
                                        <?php if(isset($applications)): ?>
                                            <?php $i = 1; ?>
                                            <?php foreach($applications as $application): ?>
                                                <tr id="application-<?php echo $application['id']; ?>" data-leave="<?php echo htmlspecialchars(json_encode($application), ENT_QUOTES, 'UTF-8'); ?>">
                                                    <td><?php echo $i++; ?></td>
                                                    <td class="text-center">
                                                        <?php if ($application['status'] == 1): ?>
                                                            <a href="javascript:openApplicationModal(<?php echo $application['id']; ?>)" class="badge badge-warning" data-trigger="hover" data-tooltip="tooltip" title="View Leave Detail"><?php echo $application['leave_status'] ?></a>
                                                        <?php endif; ?>
                                                        <?php if ($application['status'] == 2): ?>
                                                            <a href="javascript:openApplicationModal(<?php echo $application['id']; ?>)" class="badge badge-success" data-trigger="hover" data-tooltip="tooltip" title="View Leave Detail"><?php echo $application['leave_status'] ?></a>
                                                        <?php endif; ?>
                                                        <?php if ($application['status'] == 3): ?>
                                                            <a href="javascript:openApplicationModal(<?php echo $application['id']; ?>)" class="badge badge-danger" data-trigger="hover" data-tooltip="tooltip" title="View Leave Detail"><?php echo $application['leave_status'] ?></a>
                                                        <?php endif; ?>
                                                        <?php if ($application['status'] == 4): ?>
                                                            <a href="javascript:openApplicationModal(<?php echo $application['id']; ?>)" class="badge badge-secondary" data-trigger="hover" data-tooltip="tooltip" title="View Leave Detail"><?php echo $application['leave_status'] ?></a>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td><?php echo $application['leave_type']; ?></td>
                                                    <td><?php echo date_format(date_create($application['date_from']),"d/m/Y").' - '.date_format(date_create($application['date_to']),"d/m/Y"); ?></td>
                                                    <td><?php echo $application['days_applied']; ?></td>
                                                    <!-- <td><?php echo $application['period_from']; ?></td>
                                                    <td><?php echo date_format(date_create($application['date_to']),"d/m/Y (l)"); ?></td>
                                                    <td><?php echo $application['period_to']; ?></td> -->
                                                    <td class="text-center"><?php if ($application['file_name']): ?><a target="_blank" href="<?php echo base_url($application['file_location'].$application['file_name']); ?>"><i class='fas fa-file fa-2x'></i></a><?php endif; ?></td>
                                                    <!-- <td><?php echo date_format(date_create($application['created_ts']),"d/m/Y"); ?></td> -->
                                                    <td class="text-center">
                                                        <button type="button" <?php if ($application['status'] != 1) echo "hidden" ?> class="btn btn-sm btn-danger" onclick="deleteApplication(<?php echo $application['id']; ?>);" data-trigger="hover" data-tooltip="tooltip" title="Delete Application"><i class="fas fa-trash"></i></button>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- <section class="container" style="padding-bottom: 2rem;">
    <div class="card bg-light-transparent">
        <div class="card-header bg-light">
            <div class="float-left">
                <button onclick="openRequestModal();" type="button" class="btn btn-outline-dark btn-sm" <?php echo ($curr_year < date('Y'))?'disabled':''; ?>><i class="fa fa-plus"></i> Request Allocation</button>
            </div>
        </div>
        <div class="card-body">
            <div class="card no-shadow">
                <div class="card-body">
                    <div class="table-responsive">
                        <table id="table_applications" class="table table-bordered table-striped table-hover">
                            <thead>
                                <th>No</th>
                                <th>Leave Type</th>
                                <th class="text-center">Status</th>
                                <th></th>
                            </thead>
                            <tbody>
                                <?php if ($requests): ?>
                                    <?php $i = 0; foreach($requests as $req): ?>
                                        <tr>
                                            <td><?php echo ++$i; ?></td>
                                            <td><?php echo $req['type']; ?></td>
                                            <td class="text-center">
                                                <?php if ($req['status'] == 1) {  ?>
                                                    <a href="#" class="badge badge-success">Approved</a>
                                                <?php } else { ?>
                                                    <a href="#" class="badge badge-secondary">Pending</a>
                                                <?php } ?>
                                            </td>
                                            <td class="text-center">
                                                <?php if ($req['status'] == 0): ?>
                                                    <button type="button" class="btn btn-sm btn-danger" onclick="deleteRequest(<?php echo $req['id']; ?>);" data-trigger="hover" data-tooltip="tooltip" title="Delete Request"><i class="fas fa-trash"></i></button>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section> -->

<!-- MODALS -->
<div class="modal fade" id="requestModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="application-modal-title">Leave Allocation Request</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="col">
                    <div class="form-group">
                        <label for="allocationTypeRequest">Leave Type</label>
                        <select required data-parsley-error-message="Type is required." class="form-control" id="allocationTypeRequest">
                            <option selected value="">Select Type</option>
                            <?php foreach($leave_types as $type): ?>
                                <option value="<?php echo $type['id']; ?>">[<?php echo $type['code']; ?>] <?php echo $type['name']; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
           </div>
           <div class="modal-footer">
                <div class="btn-group float-right">
                    <button type="button" class="btn btn-primary" data-dismiss="modal">Cancel</button>
                    <button type="button" id="requestModalSubmitBtn" onclick="createAllocationRequest();" class="btn btn-light">Save</button>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="summaryModal">
    <div class="modal-dialog"  style="max-width: 90%;">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="summary-modal-title">Leave Summary</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
           <div class="modal-body">
                <div class="table-responsive">
                    <table id="table_allocations" class="table table-bordered table-striped table-hover">
                        <thead>
                            <th>Year</th>
                            <th>Leave Type</th>
                            <th>Carried Forward</th>
                            <th>Entitled Leave</th>
                            <th>Leave Taken</th>
                            <th>Carried Forward Balance</th>
                            <th>Entitled Balance</th>
                        </thead>
                        <tbody>
                            <?php if(isset($allocations)): ?>
                                <?php foreach($allocations as $allocation): ?>
                                    <tr>
                                        <td><?php echo $allocation['year']; ?></td>
                                        <td><?php echo $allocation['name']; ?></td>
                                        <td><?php echo $allocation['bring_forward_entitled']; ?></td>
                                        <td><?php echo $allocation['balance_entitled']; ?></td>
                                        <td><?php echo $allocation['leave_taken']; ?></td>
                                        <td><?php echo $allocation['bring_forward']; ?></td>
                                        <td><?php echo $allocation['leave_balance']; ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
           </div>
        </div>
    </div>
</div>
<div class="modal fade" id="applicationModal" role="dialog" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="application-modal-title"></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form id="applicationForm" class="form">
                <div class="modal-body">
                    <h6 class="mb-3" style="text-decoration: underline;">Leave Information</h6>
                    <input type="hidden" id="appId">
                    <!-- single date -->
                    <div class="row" id="singleContainer">
                        <div class="col-6">
                            <div class="form-group">
                                <label for="dateFrom">On</label>
                                <input required type="text" class="form-control leave_date" id="dateOn" name="dateOn" readonly>
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="form-group">
                                <label for="periodFrom">Period</label>
                                <select required class="form-control" id="periodOn" name="periodOn">
                                </select>
                            </div>
                        </div>
                    </div>
                    <!-- range date -->
                    <div class="row" id="rangeContainer">
                        <div class="col-3">
                            <div class="form-group">
                                <label for="dateFrom">From</label>
                                <input required type="text" class="form-control leave_date" id="dateFrom" name="dateFrom" readonly>
                            </div>
                        </div>
                        <div class="col-3">
                            <div class="form-group">
                                <label for="periodFrom">Period</label>
                                <select required class="form-control" id="periodFrom" name="periodFrom">
                                </select>
                            </div>
                        </div>
                        <div class="col-3">
                            <div class="form-group">
                                <label for="dateTo">To</label>
                                <input required type="text" class="form-control leave_date" id="dateTo" name="dateTo" readonly>
                            </div>
                        </div>
                        <div class="col-3">
                            <div class="form-group">
                                <label for="periodTo">Period</label>
                                <select required class="form-control" id="periodTo" name="periodTo">
                                </select>
                            </div>
                        </div>
                    </div>
                    <!-- type and person -->
                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="leaveType">Leave Type</label>
                                <!-- <select required data-parsley-error-message="Type is required." class="form-select" id="leaveType" onchange="checkExam();">
                                </select> -->
                                <!-- <select required data-parsley-error-message="Type is required." class="form-control" id="leaveType" onchange="typeListener()">
                                </select> -->
                                <input required type="text" class="form-control" id="leaveType" name="duration" readonly>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                <label for="leaveType">Duration</label>
                                <input required type="text" class="form-control leave_date" id="duration" name="duration" readonly>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="reliefPerson">Relief Person</label>
                                <!-- <select required class="form-control selectpicker" data-style="btn-light" data-live-search="true" id="reliefPerson"> -->
                                <select required class="form-control" id="reliefPerson">
                                <option value="">Select a person</option>
                                <?php foreach($relief_persons as $person): ?>
                                    <option value="<?php echo $person['id']; ?>"><?php echo $person['name']; ?></option>
                                <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="form-row" id="examForm" style="display: none;">
                        <div class="col">
                            <div class="form-group">
                                <label for="examList">Exam List</label>                             
                                <select required class="form-control" id="examList">
                                    <option selected value="">Select Exam</option>
                                    <?php if(!empty($exam_list)) foreach($exam_list as $value): ?>
                                        <option value="<?php echo $value['id']; ?>" data-exam_date="<?php echo date("d-m-Y", strtotime($value['exam_date'])); ?>"><?php echo $value['programme']; ?> [<?php echo $value['paper_code']; ?> - <?php echo $value['title']; ?>] : <?php echo date("d M Y", strtotime($value['exam_date'])); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>
                    <!-- reason -->
                    <div class="form-group">
                        <label for="leaveReason">Reason</label>
                        <textarea required class="form-control" id="leaveReason" placeholder="Enter reason"></textarea>
                    </div>
                    <!-- attachment -->
                    <div class="form-group">
                        <label for="leaveAttachment">Attachment</label>
                        <input type="file" class="form-control-file" id="leaveAttachment">
                    </div>
                    <hr>
                    <h6 class="mb-3" style="text-decoration: underline;">Contact Information</h6>
                    <!-- user -->
                    <div class="row mb-3">
                        <div class="col-md-9">
                            <div class="form-group">
                                <label for="userAddress">Address</label>
                                <input required type="text" class="form-control" id="userAddress" 
                                    placeholder="Enter address" value="<?php echo $user['address']; ?>" autocomplete="true">
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label for="userContact">Contact No.</label>
                                <input required type="text" class="form-control" id="userContact" 
                                    placeholder="Enter contact no." value="<?php echo $user['phone']; ?>" autocomplete="true">
                            </div>
                        </div>
                    </div>
                    <div class="container" id="errorContainer" style="border: 1px solid red;">
                        <ol id="errorList" style="color: red;"></ol>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button id="applicationModalSubmitBtn" type="button" class="btn btn-primary">Save</button>
                    <!-- <button id="applicationModalSubmitBtn" type="button" class="btn btn-primary" onclick="createApplication()">Save</button> -->
                </div>
            </form>
        </div>
    </div>
</div>

<script src="<?php echo base_url(); ?>assets/themes/web/js/moment-with-locales.min.js"></script>
<script>
    /**
     * PHP Array Variables to JSON
     */
    <?php
        $json_user        = json_encode($user);
        $json_allocations = json_encode($allocations);
        $json_applications = json_encode($applications);
        $json_publicHolidays = json_encode($public_holidays);
    ?>

    var user        = <?php echo $json_user ?>;
    var allocations = <?php echo $json_allocations ?>;
    var userApplications = <?php echo $json_applications ?>;
    var publicHolidays = <?php echo $json_publicHolidays ?>;
    var examList = <?php echo json_encode($exam_list) ?>;

    var startDate = moment(['<?php echo $curr_year - 1; ?>']).startOf('year').format('DD-MM-YYYY');
    var endDate   = moment(['<?php echo $curr_year + 1; ?>']).endOf('year').format('DD-MM-YYYY');

    console.log('user: ' + JSON.stringify(user));
    console.log('allocations: ' + JSON.stringify(allocations));
    console.log('userApplications: ' + JSON.stringify(userApplications));
    console.log('publicHolidays: ' + JSON.stringify(publicHolidays));
    console.log('publicHolidays: ' + (publicHolidays ? (publicHolidays.length) : 0));
    console.log('exam list: ' + JSON.stringify(examList));

    // vars for cal
    moment.locale('en-sg');
    var abnormalOffdayStates = ['kedah', 'kelantan', 'terengganu'];
    var typeSelected = 0;
    var selectedLeaveObj = null;
    var selectedDates = null;
    var calLabels = {
        holidays: {
            color: '#61a8ff',
            name: 'Public holidays'
        },
        exams: {
            color: '#FFA1C9',
            name: 'Exams'
        },
        pending: {
            color: '#ffb861',
            name: 'Pending applications'
        },
        approved: {
            color: '#61ffb7',
            name: 'Approved applications'
        }
    };
    var threshold = 3; // in day
    var cal;
    var calSource = [];

    // main
    document.addEventListener('DOMContentLoaded', function() {
        console.log('DOMContentLoaded');


        // populate calendar with public holidays if not empty
        if(publicHolidays){
            console.log('holiday counts: ' + publicHolidays.length);
            publicHolidays.forEach(ph => {
                // make adjustment to end date for cal
                adjEndDate = moment(ph.end.date).subtract(1, 'day');
                calSource.push({
                    id: ph.id,
                    name: ph.summary,
                    type: 'holidays',
                    color: calLabels.holidays.color,
                    startDate: new Date(new Date(ph.start.date).getFullYear(), new Date(ph.start.date).getMonth(), new Date(ph.start.date).getDate()),
                    startHalfDay: false,
                    endDate: new Date(new Date(adjEndDate).getFullYear(), new Date(adjEndDate).getMonth(), new Date(adjEndDate).getDate()),
                    endHalfDay: false
                });
            });
        }

        // populate calendar with exams
        if(examList){
            console.log('exam counts: ' + examList.length);
            examList.forEach(ex => {
                calSource.push({
                    id: ex.id,
                    name: `Exam: ${ex.title} (${ex.paper_code})`,
                    type: 'exams',
                    color: calLabels.exams.color,
                    startDate: new Date(new Date(ex.exam_date).getFullYear(), new Date(ex.exam_date).getMonth(), new Date(ex.exam_date).getDate()),
                    startHalfDay: false,
                    endDate: new Date(new Date(ex.exam_date).getFullYear(), new Date(ex.exam_date).getMonth(), new Date(ex.exam_date).getDate()),
                    endHalfDay: false
                });
            });
        }

        // pre-populate leave types
        $('#leaveContainer').append(
            `<select class="form-control" id="leave-type">
                <option selected value="">Select leave type here to start a new application</option>
            </select>`
        );

        // iterate user allocations
        allocations.forEach(allArr => {
            // populate calendar with user application if not empty
            pendingCount = 0;
            allArr.applications.forEach(appArr => {
                if(appArr.is_delete == 0 && ['1','2'].includes(appArr.status)){
                    if(appArr.status == 1) pendingCount += parseFloat(appArr.days_applied);
                    startHalf = false;
                    endHalf = false;
                    if(appArr.date_from == appArr.date_to){
                        if(appArr.period_from_id == 2 || appArr.period_from_id == 3){
                            startHalf = true;
                        }   
                    }else{
                        if(appArr.period_from_id != 1){
                            startHalf = true;
                        }
                        if(appArr.period_to_id != 1){
                            endHalf = true;
                        }
                    }

                    if(appArr.date_from == appArr.date_to) console.log(appArr.period_from_id + ' ' + startHalf + ' ' + endHalf);

                    calSource.push({
                        id: appArr.id,
                        name: allArr.name,
                        duration: appArr.days_applied,
                        type: 'applications',
                        isEL: appArr.is_el,
                        color: (appArr.status == 2 ? calLabels.approved.color : calLabels.pending.color),
                        startId: appArr.period_from_id,
                        startDate: new Date(new Date(appArr.date_from).getFullYear(), new Date(appArr.date_from).getMonth(), new Date(appArr.date_from).getDate()),
                        // startHalfDay: (appArr.period_from_id == 1 ? false : true),
                        startHalfDay: startHalf,
                        endId: appArr.period_to_id,
                        endDate: new Date(new Date(appArr.date_to).getFullYear(), new Date(appArr.date_to).getMonth(), new Date(appArr.date_to).getDate()),
                        // endHalfDay: (appArr.period_to_id == 1 ? false : true)
                        endHalfDay: endHalf
                    });
                }
            });

            // populate options for leave types
            appendStr = '';
            if(parseFloat(allArr.leave_entitled) == 0){
                appendStr = `<option value="${allArr.type_id}">${allArr.name}</option>`;
            }else{
                appendStr = `<option value="${allArr.type_id}">${allArr.name} (Allowed: ${allArr.balance_entitled_deducted} / ${allArr.balance_entitled}, Allocated: ${allArr.leave_entitled}, Pending: ${pendingCount})</option>`;
            }
            $('#leave-type').append(appendStr);
            if(allArr.type_id == 1){
                $('#allowed-span').html(`${allArr.balance_entitled_deducted} / ${allArr.balance_entitled} day(s) (Pending: ${pendingCount})`);
            }

        });

        // load calendar with source
        cal = new Calendar('#calendar', {
            style: 'background',
            dataSource: calSource,
            enableContextMenu: true,
            contextMenuItems: [
                {
                    text: 'Delete',
                    click: deleteApplication
                },
                {
                    text: 'Update',
                    click: loadEditModal
                }
            ],
            enableRangeSelection: true,
            mouseOnDay: function(e) {
                if(e.events.length > 0) {
                    var content = '';
                    
                    for(var i in e.events) {
                        content += '<div class="event-tooltip-content">'
                                        + '<div class="event-name" style="color:' + e.events[i].color + '">' + e.events[i].name 
                                        + (e.events[i].isEL == 1 ? ' (Emergency)' : '')
                                        + (e.events[i].type == 'applications' ? ' (' + e.events[i].duration + ' d)' : '')
                                        + '</div>'
                                        + '<div class="event-dates">' 
                                        + (moment(e.events[i].startDate).format("L")) 
                                        + (e.events[i].type == 'applications' ? (' (' + (e.events[i].startId == 1 ? 'F' : (e.events[i].startId == 2 ? 'H AM' : 'H PM'))  + ')') : '')
                                        + ' - ' 
                                        + (moment(e.events[i].endDate).format("L")) 
                                        + (e.events[i].type == 'applications' ? (' (' + (e.events[i].endId == 1 ? 'F' : (e.events[i].endId == 2 ? 'H AM' : 'H PM'))  + ')') : '')
                                        + '</div>'
                                    + '</div>';
                    }
                
                    $(e.element).popover({ 
                        trigger: 'manual',
                        container: 'body',
                        html:true,
                        content: content
                    });
                    
                    $(e.element).popover('show');
                }
            },
            mouseOutDay: function(e) {
                if(e.events.length > 0) {
                    $(e.element).popover('hide');
                }
            },
            selectRange: function(e) {
                processSelection2({ startDate: e.startDate, endDate: e.endDate });
            },
        });

        // // reset values
        // $('#applicationModal').on('hidden.bs.modal', function(){
        //     resetElements();
        // });

        // populate legends 
        console.log('size of legends: ' + Object.keys(calLabels).length);
        for(const clk in calLabels){
            console.log(`${calLabels[clk].name}`);
            $('#legendContainer').append(
                `<span style="border-radius: 5px; padding: 5px 0; text-align: center; width: 170px; margin: 0 5px; background-color: ${calLabels[clk].color};">${calLabels[clk].name}</span>`
            );
        }
    });

    // listeners
    $('#applicationModal').on('hidden.bs.modal', function(){
            resetElements();
    });

    $('#leaveContainer').on('change', '#leave-type', function(){
        selectedLeaveObj = null;
        $('#calendar-error').empty();
        typeSelected = ($(this).val() ? parseInt($(this).val()) : 0);
        // select leave
        selectedLeaveObj = allocations.find(obj1 => parseInt(obj1.type_id) == typeSelected);
        console.log('selected leave: ' + JSON.stringify(selectedLeaveObj));
    });

    $('#periodOn').on('change', function(){
        calculateDuration(selectedDates.start, selectedDates.end, $('#periodOn').val(), 0);
    });

    $('#periodFrom').on('change', function(){
        calculateDuration(selectedDates.start, selectedDates.end, $('#periodFrom').val(), $('#periodTo').val());
    });

    $('#periodTo').on('change', function(){
        calculateDuration(selectedDates.start, selectedDates.end, $('#periodFrom').val(), $('#periodTo').val());
    });

    // clear modal stuff
    function resetElements(){
        $('#periodFrom').empty();
        $('#periodTo').empty();
        $('#periodOn').empty();
        $('#leaveType').empty();
        
        $('#calendar-error').empty();
        $('#leaveReason').val("");
        $('#periodTo').attr('disabled', false);
        $('#periodFrom').attr('disabled', false);
        $('#periodOn').attr('disabled', false);
        selectedDates = null;

        $('#applicationForm').parsley().reset();
        $('#reliefPerson').val("").trigger('change');
		// $('#applicationForm').find("textarea").val("");
    }

    // if more than 1 day, start can be 1 or 3 and end can be 1 or 2 only.
    function processSelection2(event) {
        $('#calendar-error').empty();
        isEL = false;

        // check if an event
        // if(event.id) console.log('viewing event: ' + event.name);

        // check if type selected
        if(typeSelected == 0) return showErrorDialog('Please select a leave type first');
        console.log('type selected: ' + typeSelected);

        // check backdated
        // if(selectedLeaveObj.type_id == 1 && checkBackdated(event.startDate)) return showErrorDialog('Backdated leave application is not allowed for Annual Leave. Otherwise, apply for Emergency Leave.');
        if(checkBackdated(event.startDate)){
            if(selectedLeaveObj.type_id == 1){
                isEL = true;
            }
        }

        // check start date against cooling off period
        // if(selectedLeaveObj.cooling_period != 0 && checkCoolingPeriod(event.startDate)) return showErrorDialog(`Please apply ${selectedLeaveObj.cooling_period} days before date of leave. Otherwise, apply for Emergency Leave.`)
        if(selectedLeaveObj.cooling_period != 0 && checkCoolingPeriod(event.startDate)){
            if(selectedLeaveObj.type_id == 1){
                isEL = true;
            }
        }

        // check off day for holiday-exclusive leave
        if(selectedLeaveObj.include_holiday == 0 && checkOffDay(event.startDate, event.endDate)) return showErrorDialog('Invalid selection. Please only select working days for start and end dates.');

        // check balance. consider minimum duration
        if(!checkLeaveBalance(event.startDate, event.endDate)) return showErrorDialog('Insufficient Leave Balance. Please contact Administrator for further enquiries.');

        // check for study leave
        if(selectedLeaveObj.type_id == 7){
            res = checkExam2(event.startDate, event.endDate);
            console.log('res: ' + res);
            if(res == 1 || res == 2){
                return showErrorDialog('Invalid selection. Please make sure that date selected before exam date and duration does not exists five consecutive days.');
            }else if(res == 3){
                return showErrorDialog('Invalid selection. Exam already completed.');
            }
        } 

        // // calculate duration
        // calculateDuration(event.startDate, event.endDate, 1, 1); 

        console.log('selection: ' + event.startDate + ' ##### ' + event.endDate);

        // check early slot availability
        startAmAvailable = cal.isThereFreeSlot(event.startDate, false);
        startPmAvailable = cal.isThereFreeSlot(event.startDate, true);
        console.log('start am: ' + startAmAvailable);
        console.log('start pm: ' + startPmAvailable);
        
        // check late slot availability
        endAmAvailable = cal.isThereFreeSlot(event.endDate, false);
        endPmAvailable = cal.isThereFreeSlot(event.endDate, true);
        console.log('end am: ' + endAmAvailable);
        console.log('end pm: ' + endPmAvailable);

        selectedDates = {
            start: event.startDate,
            end: event.endDate
        };
        if(event.startDate == event.endDate){
            // single day
            console.log('one date only');
            slots = [];
            slots[1] = 'Full day';
            slots[2] = 'Half day (AM)';
            slots[3] = 'Half day (PM)';
            datesOk = true;
            sAdj = 0;
            if(!startAmAvailable && !startPmAvailable){
                slots = [];
                datesOk = false;
            }else if(startAmAvailable && startPmAvailable){
                // do nothing
                sAdj = 1;
            }else if(startAmAvailable){
                // if am/start available, check that if actually available
                eventsArr = cal.getEventsOnRange(event.startDate, moment(event.endDate).add(1, 'day')); // non-inclusive so add one
                if(eventsArr[0].startId == 2){
                    // actually pm available
                    slots.splice(1,2);
                    sAdj = 3;
                }else{
                    // genuine am
                    slots.splice(1,1);
                    slots.splice(2,1);
                    sAdj = 2;
                }

            }else if(startPmAvailable){
                slots.splice(1,2);
                sAdj = 3;
            }

            if(datesOk){
                console.log('Valid date. Slots available: ' + slots);
                calculateDuration(event.startDate, event.endDate, sAdj, 0); 
                loadNewModal(event.startDate, event.endDate, false, slots, [], isEL);
            }else{
                return showErrorDialog('Invalid selection. Please select date that does not overlap with exams, public holidays or existing leaves.');
            }
        }else{
            // range of days
            console.log('more than one date');

            if(checkOverlapping(event.startDate, event.endDate)) return showErrorDialog('Invalid selection. Please select dates that do not overlap with public holidays or existing leaves.');
            console.log('passed overlapping');
            // calculateDuration(event.startDate, event.endDate, 1, 1, 1);

            slotsS = [];
            slotsS[1] = 'Full day';
            slotsS[2] = 'Half day (AM)';
            slotsS[3] = 'Half day (PM)';
            datesOk = true;
            sAdj = 0;
            eAdj = 0;
            if(!startAmAvailable && !startPmAvailable){
                slotsS = [];
                datesOk = false;
            }else if(startAmAvailable && startPmAvailable){
                // do nothing
                sAdj = 1;
            }else if(startAmAvailable){
                slotsS.splice(1,1);
                slotsS.splice(2,1);
                sAdj = 2;
            }else if(startPmAvailable){
                slotsS.splice(1,2);
                sAdj = 3;
            }

            slotsE = [];
            slotsE[1] = 'Full day';
            slotsE[2] = 'Half day (AM)';
            slotsE[3] = 'Half day (PM)';
            if(!endAmAvailable && !endPmAvailable){
                slotsE = [];
                datesOk = false;
            }else if(endAmAvailable && endPmAvailable){
                // do nothing
                eAdj = 1;
            }else if(endAmAvailable){
                slotsE.splice(1,1);
                slotsE.splice(2,1);
                eAdj = 2;
            }else if(endPmAvailable){
                slotsE.splice(1,2);
                eAdj = 3;
            }

            if(datesOk){
                console.log('Valid date. Slots start available: ' + slotsS);
                console.log('Valid date. Slots end available: ' + slotsE);
                calculateDuration(event.startDate, event.endDate, sAdj, eAdj); 
                loadNewModal(event.startDate, event.endDate, true, slotsS, slotsE, isEL);
            }else{
                return showErrorDialog('Invalid selection');
            }
        }
        
    }

    function showErrorDialog(errMsg){
        // alert(errMsg);
        $('#calendar-error').html(errMsg);
    }

    function checkBackdated(eventStartDate) {
        var startDate = moment(eventStartDate, "DD-MM-YYYY");
        var today = moment();

        bd = false;
        if(startDate.isBefore(today, 'days')) {
            bd = true;
        }
        return bd;
    }

    function checkCoolingPeriod(eventStartDate){
        console.log('selecting ' + selectedLeaveObj.name + ' with cop: ' + selectedLeaveObj.cooling_period);
        ltDate = moment().add(selectedLeaveObj.cooling_period, 'day');
        cp = false;
        if(moment(event.startDate) <= ltDate){
            cp = true;
        }
        return cp;
    }

    // check if start and end date fall on off day. only for include_holiday = 0. check for states with abnormal off days
    function checkOffDay(eventStartDate, eventEndDate){
        od = false;

        sdName = (moment(eventStartDate).format('dddd')).toLowerCase();
        edName = (moment(eventEndDate).format('dddd')).toLowerCase();
        console.log('days: ' + sdName + ' and ' + edName);
        
        odArr = null;
        if(abnormalOffdayStates.includes(user.state.toLowerCase())){
            // east coast
            odArr = ['friday', 'saturday'];
            console.log('abnormal');
            
        }else{
            // everywhere else
            odArr = ['saturday', 'sunday'];
            console.log('normal');
            
        }
        if(odArr.includes(sdName) || odArr.includes(edName)) od = true;
        console.log('off day: ' + od);
        return od;
    }

    // check overlapping with public holidays or existing leaves. ok for leave with include_holiday = 1
    function checkOverlapping(date1, date2){
        console.log('checkOverlapping');
        eventsArr = cal.getEventsOnRange(date1, moment(date2).add(1, 'day')); // non-inclusive so add one
        console.log('events overlapped: ' + eventsArr.length);

        // for each event, check if new dates in between or existing events in between
        canOverlap = selectedLeaveObj.include_holiday == 1 ? true : false;
        overlapped = false;
        allHolidayEvents = 0;
        for(ev of eventsArr){
            console.log('an event: ' + ev.type);
            // if(ev.type == 'holidays'){
            //     console.log('found holiday');
            //     allHolidayEvents++; 
            // }else{
            //     console.log('found non-holiday');
            //     if(
            //         (moment(date1).isBetween(ev.startDate, ev.endDate, 'day')) || 
            //         (moment(date2).isBetween(ev.startDate, ev.endDate, 'day')) || 
            //         (moment(ev.startDate).isBetween(date1, date2, 'day')) ||
            //         (moment(ev.endDate).isBetween(date1, date2, 'day')) ||
            //         (moment(date1).isSame(ev.startDate, 'day') || moment(date2).isSame(ev.endDate, 'day'))
            //         // (moment(date1).isSame(ev.startDate, 'day') && moment(date2).isSame(ev.endDate, 'day'))
            //     ){
            //         console.log('overlapped')
            //         overlapped = true;
            //     }
            //     break;
            // }
            if(selectedLeaveObj.include_holiday == 1){
                if(ev.type == 'holidays'){
                    console.log('found holiday');
                    allHolidayEvents++; 
                }else{
                    console.log('found non-holiday');
                    if(
                        (moment(date1).isBetween(ev.startDate, ev.endDate, 'day')) || 
                        (moment(date2).isBetween(ev.startDate, ev.endDate, 'day')) || 
                        (moment(ev.startDate).isBetween(date1, date2, 'day')) ||
                        (moment(ev.endDate).isBetween(date1, date2, 'day')) ||
                        (moment(date1).isSame(ev.startDate, 'day') || moment(date2).isSame(ev.endDate, 'day'))
                        // (moment(date1).isSame(ev.startDate, 'day') && moment(date2).isSame(ev.endDate, 'day'))
                    ){
                        console.log('overlapped')
                        overlapped = true;
                    }
                    break;
                }
            }else{
                if(
                    (moment(date1).isBetween(ev.startDate, ev.endDate, 'day')) || 
                    (moment(date2).isBetween(ev.startDate, ev.endDate, 'day')) || 
                    (moment(ev.startDate).isBetween(date1, date2, 'day')) ||
                    (moment(ev.endDate).isBetween(date1, date2, 'day')) ||
                    (moment(date1).isSame(ev.startDate, 'day') || moment(date2).isSame(ev.endDate, 'day'))
                    // (moment(date1).isSame(ev.startDate, 'day') && moment(date2).isSame(ev.endDate, 'day'))
                ){
                    console.log('overlapped')
                    overlapped = true;
                }
                break;
            }
        }
        console.log('canOverlap: ' + canOverlap + ' allHolidayEvents: ' + allHolidayEvents);
        if(canOverlap && (eventsArr.length == allHolidayEvents)) overlapped = false;
        console.log('overlapped: ' + overlapped);
        return overlapped;
    }

    // el is part of allocated al. unpaid ignore balance
    function checkLeaveBalance(date1, date2){
        console.log('checkBalance');
        balOk= true;
        if(selectedLeaveObj.balance_entitled_deducted == 0){
            balOk = false;
        }else{
            if(selectedLeaveObj.type_id != 4){
                td = (moment(moment(date2).add(1, 'day')).diff(moment(date1), 'days'));
                console.log('td: ' + td);
                // subtract .5*2 to assume both start and end half day is hd
                if((selectedLeaveObj.balance_entitled_deducted - (td - 1)) < 0){
                    balOk = false;
                }
            }
        }
        console.log('balOk: ' + balOk);
        // if td > balance, assume half day in calculation but force half day in modal

        return balOk;
    }

    // check (1) end date one day before exam (2) exam still incomplete (3) max duration is five days consecutively inclusive of weekend (3)
    function checkExam2(date1, date2){
        console.log('checking exam');
        // 0 - ok, 1 - no exam, 2 - not before, 3 - exceed five days
        aDate = moment(date2).add(1, 'day');
        console.log('leave end date: ' + aDate);
        anExam = examList.find(elmt => elmt.exam_date == moment(aDate).format('YYYY-MM-DD'));
        if(!anExam){
            console.log('no exam');
            return 1;
        }
        if((moment(moment(date2).add(1, 'day')).diff(moment(date1), 'days')) > 5){
            console.log('exceed 5 days');
            return 2;
        }
        if(anExam.status == 1){
            console.log('exam completed')
            return 3;
        }
        return 0;
    }

    // half vs full day. include holiday vs non
    function calculateDuration(date1, date2, date1Period, date2Period){
        console.log('date1: ' + date1 + ' date2: ' + date2);
        console.log('period from: ' + date1Period + ' period to: ' + date2Period);
        td = 0.0;
        if(selectedLeaveObj.include_holiday == 1){
            td = (moment(moment(date2).add(1, 'day')).diff(moment(date1), 'days'));
            // td -= 2;
        }else{
            td += 1;
            
            mDate1 = moment(date1);
            console.log(mDate1);
            while(!mDate1.isSame(date2, 'day')){
                console.log(mDate1.format('dddd'));
                mDate1 = mDate1.add(1, 'day');
                console.log(mDate1);
                if(!['saturday', 'sunday'].includes((mDate1.format('dddd')).toLowerCase())){
                    td +=1;
                    console.log('not off day');
                }
            }
            // td -= 2;
        }
        // adjustment
        td = td - (date1 == date2 ? 1 : 2);

        console.log('td: ' + td);
        td += (date1Period == 1) ? 1 : 0.5;
        console.log('td: ' + td);
        if(date2Period > 0) td += ((date2Period == 1) ? 1 : 0.5);
        console.log('td: ' + td);
        
        // if(date1 == date2){
        //     td += (date1Period == 1) ? 1 : 0.5;
        // }else{
        //     td += (date1Period == 1) ? 1 : 0.5;
        //     td += (date2Period == 1) ? 1 : 0.5;
        // }
        
        console.log('durations: ' + td);
        $('#duration').val(td);
        return td;
        
    }

    function loadNewModal(date1, date2, isRange, periodArr1, periodArr2, isEL){
        console.log('loadNewModal()');

        // load date and period
        if(!isRange){
            // display row with on
            $('#applicationModal input[name="dateOn"]').val(moment(date1).format('L'))
            for(var k in periodArr1){
                $('#periodOn').append(`<option value="${k}">${periodArr1[k]}</option>`);
            }

            // show single container and hide range container
            $('#singleContainer').show();
            $('#rangeContainer').hide();
        }else{
            // display row with from and to. start 1/3 only. end 1/2 only
            $('#applicationModal input[name="dateFrom"]').val(moment(date1).format('L'))
            for(var k in periodArr1){
                if(k != 2) $('#periodFrom').append(`<option value="${k}">${periodArr1[k]}</option>`);
            }
            $('#applicationModal input[name="dateTo"]').val(moment(date2).format('L'))
            for(var k in periodArr2){
                if(k != 3) $('#periodTo').append(`<option value="${k}">${periodArr2[k]}</option>`);
            }

            // show range container and hide single container
            $('#singleContainer').hide();
            $('#rangeContainer').show();
        }

        // load leave type
        isEL ? $('#leaveType').val('Emergency Leave') : $('#leaveType').val(selectedLeaveObj.name);
        $('#userAddress').val(user.address);
        $('#userContact').val(user.phone);

        // error
        $('#errorContainer').hide();
        $('#application-modal-title').html('New Leave Application');
        $('#applicationModalSubmitBtn').attr('onclick', 'saveApplication()');
        $("#applicationModal").modal('show');
        
    }

    function loadEditModal(event){
        console.log('loadEditModal(): ' + event.id);

        // grab the application
        allocations.forEach(alloc => {
            loadedApplication = (alloc.applications).find(ao => ao.id == event.id);
            if(loadedApplication){
                slots = [];
                slots[1] = 'Full day';
                slots[2] = 'Half day (AM)';
                slots[3] = 'Half day (PM)';

                $('#appId').val(event.id);
                if(loadedApplication.date_from == loadedApplication.date_to){
                    // same day
                    $('#applicationModal input[name="dateOn"]').val(moment(loadedApplication.date_from).format('L'))
                    $('#periodOn').append(`<option value="${loadedApplication.period_from_id}">${slots[loadedApplication.period_from_id]}</option>`);
                    $('#periodOn').attr('disabled', true);
                    $('#singleContainer').show();
                    $('#rangeContainer').hide();
                }else{
                    // multiple days
                    $('#applicationModal input[name="dateFrom"]').val(moment(loadedApplication.date_from).format('L'))
                    $('#periodFrom').append(`<option value="${loadedApplication.period_from_id}">${slots[loadedApplication.period_from_id]}</option>`);
                    $('#periodFrom').attr('disabled', true);
                    $('#applicationModal input[name="dateTo"]').val(moment(loadedApplication.date_to).format('L'))
                    $('#periodTo').append(`<option value="${loadedApplication.period_to_id}">${slots[loadedApplication.period_to_id]}</option>`);
                    $('#periodTo').attr('disabled', true);
                    $('#singleContainer').hide();
                    $('#rangeContainer').show();
                }

                $('#duration').val(loadedApplication.days_applied);
                $('#leaveType').val(alloc.name);
                $('#leaveReason').val(loadedApplication.reason);
                $('#userAddress').val(loadedApplication.absent_address);
                $('#userContact').val(loadedApplication.absent_contact);
                $('#reliefPerson').val(loadedApplication.absent_relief_id).trigger('change');
                console.log('relief person id: ' + loadedApplication.absent_relief_id);

                // error
                $('#errorContainer').hide();
                $('#application-modal-title').html('Update Leave Application');
                $('#applicationModalSubmitBtn').attr('onclick', 'updateApplication()');
                $("#applicationModal").modal('show');
                
            }
        });
        
    }

    function checkAttachment() {
        ca = true;
        if ($('#leaveAttachment').get(0).files.length === 0) {
            // $("#errorList").append("<li>"+"Attachment is required."+"</li>");
            // $('#errorContainer').show();
            ca = false;
        }
        return ca;
    }

    function saveApplication(){
        console.log('saveApplication');

        toastConfirm("Are you sure you want to submit this leave application?", function(){
            if(selectedLeaveObj.type_id == 3 && !checkAttachment()) return '';

            if ($('#errorList li').length > 0) {
                console.log('error');
                iziToast.error({
                    position: 'bottomRight',
                    title: "Application Error",
                    message: $('#errorList li').length + " errors. Please fix to proceed."
                });
            } else {
                console.log('forming formdata');
                console.log('relief person: ' + $('#reliefPerson').val());
                var fd = new FormData();

                fd.append("user_name", "<?php echo $user['name']; ?>");
                fd.append("leave_name", $('#leaveType').find(':selected').data('name'));
                fd.append("user_id", <?php echo $user['id']; ?>);
                fd.append("department_id", <?php echo $user['department_id']; ?>);
                // fd.append("date_from", $('#dateFrom').val());
                fd.append("date_from", moment(selectedDates.start).format('YYYY-MM-DD'));
                fd.append("period_from_id", (selectedDates.start == selectedDates.end ? $('#periodOn').val() : $('#periodFrom').val()));
                // fd.append("date_to", $('#dateTo').val());
                fd.append("date_to", moment(selectedDates.end).format('YYYY-MM-DD'));
                fd.append("period_to_id", (selectedDates.start == selectedDates.end ? $('#periodOn').val() : $('#periodTo').val()));
                // fd.append("type_id", $('#leaveType').val());
                fd.append("type_id", typeSelected);
                fd.append("absent_relief_id", $('#reliefPerson').val());
                fd.append("reason", $('#leaveReason').val());
                fd.append("absent_contact", $('#userContact').val());
                fd.append("absent_address", $('#userAddress').val());
                fd.append('days_applied', $('#duration').val());
                fd.append('allocation_id', selectedLeaveObj.allocation_id);
                fd.append('is_el', ($('#leaveType').val() == 'Emergency Leave') ? 1 : 0);

                if($('#leaveType').val() == 7){ //study leave
                    if(moment($("#dateTo").val(), "DD-MM-YYYY") > moment($('#examList').find(':selected').data('exam_date'), "DD-MM-YYYY")){
                        $("#errorList").append("<li>"+"Your study leave application exceed exam date. Please check again."+"</li>");
                        $('#errorContainer').show();
                        return false;
                    }else{
                        var dateFrom  = moment($("#dateFrom").val(), "DD-MM-YYYY");
                        var dateTo    = moment($("#dateTo").val(), "DD-MM-YYYY");
                        var daysApply = getNumWorkDays(dateFrom, dateTo);

                        if(daysApply <= 5 ){
                            fd.append("exam_id", $('#examList').val());
                        }else{
                            $("#errorList").append("<li>"+"Only Five(5) consecutive working days per paper . Please check again."+"</li>");
                            $('#errorContainer').show();
                            return false;
                        }
                    }
                }

                if($('#leaveAttachment').prop('files').length > 0) {
                    var attachment = $('#leaveAttachment').prop('files')[0];
                    
                    fd.append("attachment", attachment);
                }

                // var ajax_start_time = new Date().getTime();

                console.log('sending ajax request');
                $.ajax({
                    url: "<?php echo base_url('hr/leave_v2/createApplication2'); ?>",
                    type: "POST",
                    data: fd,
                    dataType: "JSON",
                    processData: false,
                    contentType: false,
                    success: (data) => {
                        localStorage.setItem("status", data.status);
                        localStorage.setItem("msg", data.msg);

                        // var ajax_end_time = new Date().getTime();
                        // var ajax_duration =  ajax_end_time - ajax_start_time;

                        // console.log(`AJAX function done in ${ ajax_duration / 1000 } seconds`);

                        // var end_time = new Date().getTime();
                        // var function_duration = end_time - start_time;

                        // console.log(`Leave Application done in ${ function_duration / 1000 } seconds`);

                        location.reload();
                    },
                    error: (jqXHR, textStatus, errorThrown) => {
                        console.log('ajax error');
                        console.log(textStatus);
                        console.log(errorThrown);
                    }
                })
            }
        });
    }

    function deleteApplication(event) {
        if(event.type == 'applications'){
            toastConfirm("Are you sure you want to delete this application?", function(){
                $.ajax({
                    type: 'POST',
                    url: '<?php echo base_url('hr/leave_v2/deleteApplication2'); ?>',
                    data: {
                        'id' : event.id
                    },
                    dataType: 'JSON',
                    success: function(data) {
                        if(data.status == 'Success') {
                            localStorage.setItem("status",data.status);
                            localStorage.setItem("msg",data.msg);

                            location.reload();
                        }
                    }
                });
            });
        }
    }

    // date, period, type - cannot be change
    function updateApplication() {
        console.log('updateApplication');

        toastConfirm("Are you sure you want to update this leave application?", function(){
            // check attachment
            // ...

            if ($('#errorList li').length > 0) {
                console.log('error');
                iziToast.error({
                    position: 'bottomRight',
                    title: "Application Error",
                    message: $('#errorList li').length + " errors. Please fix to proceed."
                });
            } else {
                console.log('forming formdata');
                console.log('relief person: ' + $('#reliefPerson').val());
                console.log('updating: ' + $('#appId').val());
                var fd = new FormData();

                fd.append("id", $('#appId').val());
                fd.append("user_id", <?php echo $user['id']; ?>);
                fd.append("department_id", <?php echo $user['department_id']; ?>);
                fd.append("absent_relief_id", $('#reliefPerson').val());
                fd.append("reason", $('#leaveReason').val());
                fd.append("absent_contact", $('#userContact').val());
                fd.append("absent_address", $('#userAddress').val());

                console.log('sending ajax request');
                $.ajax({
                    url: "<?php echo base_url('hr/leave_v2/updateApplication2'); ?>",
                    type: "POST",
                    data: fd,
                    dataType: "JSON",
                    processData: false,
                    contentType: false,
                    success: (data) => {
                        if(data.status == "Success") {
                            localStorage.setItem("status", data.status);
                			localStorage.setItem("msg", data.msg);

                			location.reload();
                        }
                    }
                })
            }
        });
        
    }










    $(".leave-info-card").click(function(){
        $("#table_applications").DataTable().search($(this).attr('data-v')).draw();
    });

    $(function() {
        $( ".leave_date" ).datepicker({
            uiLibrary: 'bootstrap4',
            format: 'dd-mm-yyyy',
            autoclose: true,
            changeMonth: true, 
            changeYear: true,
            startDate :startDate,
            endDate: endDate
        });

        $('#entitlementYear').change(() => {
            var year = $(this).find(':selected').val();
            location.href = "<?php echo base_url('hr/leave/application/'); ?>"+user.id+'/'+year;
        });
    });

    $('#collapseLeaveFilter').on('show.bs.collapse', function () {
        $('#btnShowLeaveFilters').addClass('active');
    })
    $('#collapseLeaveFilter').on('hide.bs.collapse', function () {
        $('#btnShowLeaveFilters').removeClass('active');
    })

    function checkExam() {
        var selectBox = document.getElementById("leaveType");
        var selectedValue = selectBox.options[selectBox.selectedIndex].value;
        if(selectedValue == 7){ //study leave
            document.getElementById("examForm").style.display="block";
            document.getElementById("examList").required = true;
        }else{
            document.getElementById("examForm").style.display="none";
            document.getElementById("examList").required = false;
        }
    }

    function openRequestModal() {
        $('#requestModal').modal('show');
    }

    function createAllocationRequest() {
        toastConfirm("Are you sure you want to send this request?", () => {
            $.ajax({
                url: '<?php echo base_url('hr/leave/createRequest') ;?>',
                type: 'POST',
                data: {
                    user_id: <?php echo $user['id']; ?>,
                    type_id: $('#allocationTypeRequest').val(),
                    year: '<?php echo $curr_year;  ?>'
                },
                dataType: 'JSON',
                success: (data) => {
                    localStorage.setItem("status", data.status);
                    localStorage.setItem("msg", data.msg);

                    location.reload();
                }
            });
        });
    }

    
    function deleteRequest(id) {
        toastConfirm("Are you sure you want to delete this request?", function(){
			$.ajax({
				type: 'POST',
				url: '<?php echo base_url('hr/leave/deleteRequest'); ?>',
				data: {
					'id' : id
				},
				dataType: 'JSON',
				success: function(data) {
					if(data.status == 'Success') {
						localStorage.setItem("status",data.status);
						localStorage.setItem("msg",data.msg);

						location.reload();
					}
				}
			});
		});
    }


    function openApplicationModal(id) {
        $('#errorContainer').hide();

        if(id) {
            // Update: Load leave by id and populate form
            var data      = $('#application-'+id).data('leave');
            var dateFrom  = moment(data.date_from, "YYYY-MM-DD").format("DD-MM-YYYY");
            var dateTo    = moment(data.date_to, "YYYY-MM-DD").format("DD-MM-YYYY");

            $('#applicationID').val(data.id);
            $('#dateFrom').val(dateFrom);
            $('#periodFrom').val(data.period_from_id).trigger('change');
            $('#dateTo').val(dateTo);
            $('#periodTo').val(data.period_to_id).trigger('change');
            $('#leaveType').val(data.type_id).trigger('change');
            $('#reliefPerson').val(data.absent_relief_id).trigger('change');
            $('#leaveReason').val(data.reason);
            $('#userAddress').val(data.absent_address);
            $('#userContact').val(data.absent_contact);
            $('#examList').val(data.exam_id);

            (data.status == 1) ? $('#applicationForm :input').attr('disabled', false) : $('#applicationForm :input').attr('disabled', true);
            // $('#leaveAttachment').val();
            $('#application-modal-title').html('Update Leave Application');
            $('#applicationModalSubmitBtn').attr('onclick', 'updateApplication()');
        } else {
            // Create new: Clear form
            clearForm('#applicationForm');
        
            if (user.address) $('#userAddress').val(user.address);
            if (user.phone)   $('#userContact').val(user.phone);

            $('#application-modal-title').html('New Leave Application');
            $('#applicationModalSubmitBtn').attr('onclick', 'createApplication()');

            $('#applicationForm :input').attr('disabled', false); 
        }

        $('#applicationModal').modal('show');
    }

    function openSummaryModal() {
//        $('#summaryModal').modal('show');
//	    function viewLeaveSummary(user_id) {
//		var user_id = <?php echo $this->logged_user['id']; ?>;
		var user_id = <?php echo $user_id; ?>;
        var year  = <?php echo $curr_year; ?>; // $('#entitlementYear').find(':selected').val();
        var staff = `<?php echo $user['name']; ?>`; // $('#staff-'+user_id).data('staff');
        
        $("#summary-modal-title").text("Leave Summary (" + staff + ")");

        $.ajax({
            url: "<?php echo base_url('hr/leave/getAllocations'); ?>",
            // url: "<?php echo base_url('hr/leave/getLeaveSummary'); ?>",
            type: "POST",
            data: { 
                id: user_id,
                year
            },
            dataType: "JSON",
            success: (data) => {
//                console.log(data); console.log(data.);
                if(data.status.toLowerCase() == 'success') {
                    var allocations  = data.allocations;
                    // var applications = data.applications;
                    
                    var allocationTable  = $("#table_allocations").DataTable();
                    // var applicationTable = $("#table_applications").DataTable();
                    
                    allocationTable.clear();
                    // applicationTable.clear();

                    $.each(allocations, (i, v) => {
						// console.log('ini nilai v'); console.log(v);
						let balance_brought_forward = 0;
						if(v.type_id == 1)
						{
//							console.log('taken ' + typeof v.takenB4 );
//							console.log('bf entt' + v.bring_forward_entitled);
							let b4 = parseFloat(v.takenB4);
							let bf = parseFloat(v.bring_forward_entitled);
							if(b4 >= bf) 
							{
								balance_brought_forward = 0;
							}
							else
							{ 
								balance_brought_forward = (bf - b4);
							
//								console.log('taken ' + b4 );
//								console.log('bf entt' + bf);
//								console.log('balance_brought_forward' + balance_brought_forward );
							}
						}
						allocationTable.row.add([
                            v.year,
                            v.name,
//                           v.bring_forward,
							v.bring_forward_entitled,
                            v.leave_entitled,
                            v.leave_taken,
                            //v.bring_forward_entitled ,
							balance_brought_forward,
                            v.leave_balance
                        ]);
                    })

                    allocationTable.draw();

                    $('#summaryModal').modal('show');
                } else {
                    alert('Allocation has not been setup.');
                }
            }
        })
    }

    function getNumWorkDays(startDate, endDate) {
        var numWorkDays = 0;
        var currentDate = new Date(startDate);

        while (currentDate <= endDate) {
            // Skips Sunday and Saturday
            if (currentDate.getDay() !== 0 && currentDate.getDay() !== 6) {
                numWorkDays++;
            }

            currentDate.setDate(currentDate.getDate() + 1);
        }
        return numWorkDays;
    }

    function createApplication() {
        validateForm("#applicationForm", "Are you sure you want to submit this leave application?", async function() {
            // var start_time = new Date().getTime();

            await checkLeaveAvailability('new');

            // var check_date_time = new Date().getTime();
            // var check_date_duration =  check_date_time - start_time;

            // console.log(`Check Leave Availability function done in ${ check_date_duration / 1000 } seconds`);
            
            if ($('#errorList li').length > 0) {
                iziToast.error({
					position: 'bottomRight',
					title: "Application Error",
					message: $('#errorList li').length + " errors. Please fix to proceed."
				});
            } else {

                var fd = new FormData();
            
                fd.append("user_name", "<?php echo $user['name']; ?>");
                fd.append("leave_name", $('#leaveType').find(':selected').data('name'));
                fd.append("user_id", <?php echo $user['id']; ?>);
                fd.append("department_id", <?php echo $user['department_id']; ?>);
                fd.append("date_from", $('#dateFrom').val());
                fd.append("period_from_id", $('#periodFrom').val());
                fd.append("date_to", $('#dateTo').val());
                fd.append("period_to_id", $('#periodTo').val());
                fd.append("type_id", $('#leaveType').val());
                fd.append("absent_relief_id", $('#reliefPerson').val());
                fd.append("reason", $('#leaveReason').val());
                fd.append("absent_contact", $('#userContact').val());
                fd.append("absent_address", $('#userAddress').val());

                if($('#leaveType').val() == 7){ //study leave
                    if(moment($("#dateTo").val(), "DD-MM-YYYY") > moment($('#examList').find(':selected').data('exam_date'), "DD-MM-YYYY")){
                        $("#errorList").append("<li>"+"Your study leave application exceed exam date. Please check again."+"</li>");
                        $('#errorContainer').show();
                        return false;
                    }else{
                        var dateFrom  = moment($("#dateFrom").val(), "DD-MM-YYYY");
                        var dateTo    = moment($("#dateTo").val(), "DD-MM-YYYY");
                        var daysApply = getNumWorkDays(dateFrom, dateTo);

                        if(daysApply <= 5 ){
                            fd.append("exam_id", $('#examList').val());
                        }else{
                            $("#errorList").append("<li>"+"Only Five(5) consecutive working days per paper . Please check again."+"</li>");
                            $('#errorContainer').show();
                            return false;
                        }
                    }
                }

                if($('#leaveAttachment').prop('files').length > 0) {
                    var attachment = $('#leaveAttachment').prop('files')[0];
                    
                    fd.append("attachment", attachment);
                }

                // var ajax_start_time = new Date().getTime();

                $.ajax({
                    url: "<?php echo base_url('hr/leave/createApplication'); ?>",
                    type: "POST",
                    data: fd,
                    dataType: "JSON",
                    processData: false,
                    contentType: false,
                    success: (data) => {
                        localStorage.setItem("status", data.status);
                        localStorage.setItem("msg", data.msg);

                        // var ajax_end_time = new Date().getTime();
                        // var ajax_duration =  ajax_end_time - ajax_start_time;

                        // console.log(`AJAX function done in ${ ajax_duration / 1000 } seconds`);

                        // var end_time = new Date().getTime();
                        // var function_duration = end_time - start_time;

                        // console.log(`Leave Application done in ${ function_duration / 1000 } seconds`);

                        location.reload();
                    }
                })
            }
        });
    }

    // function updateApplication() {
    //     validateForm("#applicationForm", "Are you sure you want to submit this leave application?", async function() {
    //         await checkLeaveAvailability('update');
            
    //         if ($('#errorList li').length > 0) {
    //             iziToast.error({
	// 				position: 'bottomRight',
	// 				title: "Application Error",
	// 				message: $('#errorList li').length + " errors. Please fix to proceed."
	// 			});
    //         } else {
    //             var fd = new FormData();
            
    //             fd.append("id", $('#applicationID').val());
    //             fd.append("user_id", <?php echo $user['id']; ?>);
    //             fd.append("department_id", <?php echo $user['department_id']; ?>);
    //             fd.append("date_from", moment($('#dateFrom').val(), 'DD-MM-YYYY').format('YYYY-MM-DD'));
    //             fd.append("period_from_id", $('#periodFrom').val());
    //             fd.append("date_to", moment($('#dateTo').val(), 'DD-MM-YYYY').format('YYYY-MM-DD'));
    //             fd.append("period_to_id", $('#periodTo').val());
    //             fd.append("type_id", $('#leaveType').val());
    //             fd.append("absent_relief_id", $('#reliefPerson').val());
    //             fd.append("reason", $('#leaveReason').val());
    //             fd.append("absent_contact", $('#userContact').val());
    //             fd.append("absent_address", $('#userAddress').val());

    //             if($('#leaveType').val() == 7){ //study leave
    //                 if(moment($("#dateTo").val(), "DD-MM-YYYY") > moment($('#examList').find(':selected').data('exam_date'), "DD-MM-YYYY")){
    //                     $("#errorList").append("<li>"+"Your study leave application exceed exam date. Please check again."+"</li>");
    //                     $('#errorContainer').show();
    //                     return false;
    //                 }else{
    //                     var dateFrom  = moment($("#dateFrom").val(), "DD-MM-YYYY");
    //                     var dateTo    = moment($("#dateTo").val(), "DD-MM-YYYY");
    //                     var daysApply = getNumWorkDays(dateFrom, dateTo);

    //                     if(daysApply <= 5 ){
    //                         fd.append("exam_id", $('#examList').val());
    //                     }else{
    //                         $("#errorList").append("<li>"+"Only Five(5) consecutive working days per paper . Please check again."+"</li>");
    //                         $('#errorContainer').show();
    //                         return false;
    //                     }
    //                 }
    //             }

    //             if($('#leaveAttachment').prop('files').length > 0) {
    //                 var attachment = $('#leaveAttachment').prop('files')[0];
                    
    //                 fd.append("attachment", attachment);
    //             }

    //             $.ajax({
    //                 url: "<?php echo base_url('hr/leave/updateApplication'); ?>",
    //                 type: "POST",
    //                 data: fd,
    //                 dataType: "JSON",
    //                 processData: false,
    //                 contentType: false,
    //                 success: (data) => {
    //                     if(data.status == "Success") {
    //                         localStorage.setItem("status", data.status);
    //             			localStorage.setItem("msg", data.msg);

    //             			location.reload();
    //                     }
    //                 }
    //             })
    //         }
            
            
    //     });
    // }

    // function deleteApplication(id) {
    //     toastConfirm("Are you sure you want to delete this application?", function(){
	// 		$.ajax({
	// 			type: 'POST',
	// 			url: '<?php echo base_url('hr/leave/deleteApplication'); ?>',
	// 			data: {
	// 				'id' : id
	// 			},
	// 			dataType: 'JSON',
	// 			success: function(data) {
	// 				if(data.status == 'Success') {
	// 					localStorage.setItem("status",data.status);
	// 					localStorage.setItem("msg",data.msg);

	// 					location.reload();
	// 				}
	// 			}
	// 		});
	// 	});
    // }

    // LEAVE APPLICATION RULES
    // async function checkLeaveAvailability(mode) {
    //     await clearError();                                 // Clear error container
    //     await checkDate();                                  // Check if dateTo is before dateFrom
	// 	console.log('overlap');
    //     if (mode == 'new' || mode == 'update') await checkOverlappingLeave();   // Check if applied leave is overlapping with previous approved leave
	// 	console.log('after overlap');
    //     var type_id  = + $('#leaveType').val();

    //     switch (type_id) {
    //         case 1:                       // ANNUAL LEAVE
	// 			await checkBackdated();   // Check if leave applied is backdated
    //             await check3DaysBefore(); // Check if application date is 3 days before actual applied leave date
	// 			console.log('check balance');
    //             await checkBalance();     // Check leave balance by leave type
	// 			console.log('check prorate');
    //             await checkProRate();     // Check proRate
    //             break;
            
    //         case 2:                       // EMERGENCY LEAVE
    //             await checkBalance();     // Check leave balance by leave type
    //             await checkProRate();     // Check proRate
    //             break;
            
    //         case 3:                       // MEDICAL LEAVE
    //             await checkBalance();     // Check leave balance by leave type
    //             await checkAttachment();  // Check if attachment is included

    //         case 4:                       // UNPAID LEAVE
    //             // await check3DaysBefore(); // Check if application date is 3 days before actual applied leave date
    //             break;

    //         default:                      // OTHERS
    //             // await check3DaysBefore(); // Check if application date is 3 days before actual applied leave date
    //             await checkBalance();     // Check leave balance by leave type
    //             return;
    //     }
    // }

    // function clearError() {
    //     $('#errorList').empty();
    //     $('#errorContainer').hide();
    // }

    // function checkDate() {
    //     var dateFrom  = moment($("#dateFrom").val(), "DD-MM-YYYY");
    //     var dateTo    = moment($("#dateTo").val(), "DD-MM-YYYY");

    //     if (dateTo.isBefore(dateFrom)) {
    //         $("#errorList").append("<li>"+"Your chosen end date is before the start date. Please check again."+"</li>");
    //         $('#errorContainer').show();
    //     }
    // }

	// async function checkOverlappingLeave() {
    // 	var startDate   = $("#dateFrom").val();
    //     var endDate     = $("#dateTo").val();
    //     var leavePeriod = $("#periodFrom").val();

    //     var postData = {
    //         'user_id': <?php echo $user['id']; ?>,
    //         'date_from' : startDate,
    //         'date_to' : endDate
    //     };
        
    //     await $.ajax({
    //         type: "POST",
    //         dataType: "json",
    //         url: "<?php echo base_url(); ?>hr/leave/getLeaveBetweenDate",
    //         data: postData,
    //         success: (data) => {
    //             console.log(data);
    //             if ($.trim(data.status) == "success") {
    //                 console.log('displaying overlapped leaves error');
	//       			$.each(data.leave_date, function(i, v) {
    //                     // if(leavePeriod == 1 || v.leavePeriod == 1) {
    //                     //     $("#errorList").append("<li>"+"You have already applied "+v.leave_type+" for "+parseFloat(v.days_applied)+" day(s) from "+moment(v.date_from, "YYYY-MM-DD").format('LL')+" to "+moment(v.date_to, "YYYY-MM-DD").format('LL')+"."+"</li>");
    //                     //     $('#period').val(0);

    //                     //     $('#errorContainer').show();
    //                     // } else {
    //                     //         // check if days apply included both morning and afternoon half day
    //                     //     if(leavePeriod == v.leavePeriod) {
    //                     //         $("#errorList").append("<li>"+"You have applied for leave during this period."+"</li>");
    //                     //         $('#period').val(0);

    //                     //         $('#errorContainer').show();
    //                     //     }
    //                     // }
    //                     $("#errorList").append("<li>"+"You have already applied " + v.leave_type + " for " + parseFloat(v.days_applied) + " day(s) from "
    //                         + moment(v.date_from, "YYYY-MM-DD").format('LL') + (v.period_from_id == 1 ? ' (Full day)' : (v.period_from_id == 2 ? ' (Half day - morning)' : ' (Half day - afternoon)')) + " to "
    //                         + moment(v.date_to, "YYYY-MM-DD").format('LL') + (v.period_to_id == 1 ? ' (Full day)' : (v.period_to_id == 2 ? ' (Half day - morning)' : ' (Half day - afternoon)')) + "." + "</li>");
    //                     $('#period').val(0);
    //                     $('#errorContainer').show();
	//       			});
    //                 console.log('error displayed');
    //             }
    //         }
    //     });
    // }
    
    // function checkBalanceOld() {
    //     // todo: check by weekend
    //     var type_id  = $('#leaveType').val();

    //     var dateFrom  = moment($("#dateFrom").val(), "DD-MM-YYYY");
    //     var dateTo    = moment($("#dateTo").val(), "DD-MM-YYYY");
    //     var daysApply = dateTo.diff(dateFrom, 'days');

    //     // if EL (type == 2), use AL (type == 1) allocation
    //     var filter = {
    //         'type_id' : (type_id == 2) ? 1 : type_id,
    //         'year' : dateTo.format('YYYY')
    //     }
	// 	console.log('allocations' );
	// 	console.log(allocations);
		
    //     allocation = allocations.filter((allocation) => {
			
    //         for (var key in filter) {
    //             if (allocation[key] === undefined || allocation[key] != filter[key]){
	// 				return false;
	// 			}
    //         }
    //         return true;
    //     });
	// 	console.log('allocation');
	// 	console.log(allocation);
		
    //     allocation = allocation[0];
    //     console.log(allocation);
		
    //     if (!allocation) {
    //         $("#errorList").append("<li>"+"Allocation for this leave type has not been setup for this user. Please contact Administrator for further enquiries."+"</li>");
    //         $('#errorContainer').show();
    //     }

    //     if (parseFloat(allocation.leave_balance) < daysApply) {
    //         $("#errorList").append("<li>"+"Your selected leave balance is less than applied number of days."+"</li>");
    //         $('#errorContainer').show();
    //     }
    // }

    //akmal 20191226 use ajax to check balance to solve cross year check balance problem 
    // function checkBalance() {
    //     var dateFrom    = moment($("#dateFrom").val(), "DD-MM-YYYY");
    //     var dateTo      = moment($("#dateTo").val(), "DD-MM-YYYY");
	// 	var year 		= dateFrom.format('YYYY'); 
    //     var type_id  = $('#leaveType').val();
    //     var daysApply = dateTo.diff(dateFrom, 'days');
    //     console.log('leave type ' + type_id);
    //     console.log('Year ' + year);
    //     // if EL (type == 2), use AL (type == 1) allocation
    //     var filter = {
    //         'type_id' : (type_id == 2) ? 1 : type_id,
    //         'year' : dateTo.format('YYYY')
    //     }

    //     $.ajax({
    //         async: false,
    //         url: "<?php echo base_url(); ?>hr/leave/checkBalanceAJAX",
    //         type: "POST",
    //         data: {
    //             user_id : user.id,
	// 			year	: year,
    //             date_from : $("#dateFrom").val(),
    //             date_to : $("#dateTo").val(),
	// 			type_id  : type_id, //$('#leaveType').val(),
    //             daysApply: dateTo.diff(dateFrom, 'days')
    //         },
    //         dataType: "JSON",
    //         success: (data) => {
	// 			console.log(data);
    //             if (data.mesg != "") {
    //                $('#errorList').append("<li>"+"Allocation for this leave type has not been setup for this user. Please contact Administrator for further enquiries."+"</li>");
    //                $('#errorContainer').show();
	// 			   console.log('sql ' + data.sql);
    //             } else if (data.balance < daysApply) {
    //                $('#errorList').append("<li>"+"Insufficient Leave Balance. Your Leave Balance = "+data.balance+". Please contact Administrator for further enquiries."+"</li>");
	// 			   console.log('sql ' + data.sql);
    //                $('#errorContainer').show();
    //             }
    //         }
    //     })
    // }
	
	// function checkProRate() {
    //     var dateFrom    = moment($("#dateFrom").val(), "DD-MM-YYYY");
    //     var dateTo      = moment($("#dateTo").val(), "DD-MM-YYYY");
    //     // var daysApplied = dateTo.businessDiff(dateFrom, 'days') + 1;

    //     $.ajax({
    //         async: false,
    //         url: "<?php echo base_url(); ?>hr/leave/getProRateAJAX",
    //         type: "POST",
    //         data: {
    //             user_id : user.id,
    //             date_from : $("#dateFrom").val(),
    //             period_from_id: $('#periodFrom').val(),
    //             date_to : $("#dateTo").val(),
    //             period_to_id: $('#periodTo').val()
    //         },
    //         dataType: "JSON",
    //         success: (data) => {
    //             if (data.status == "success") {
    //                 console.log(data);
    //                 var prorate = data.prorate;
    //                 if (data.days_applied > prorate.allowed_leave) {
    //                     $('#errorList').append("<li>"+"Based on our leave policy, you are only allowed to take "+prorate.allowed_leave+" day(s) of annual leave this month. If you wish to take additional leave, please apply for Unpaid Leave."+"</li>");
    //                     $('#errorContainer').show();
    //                 }
    //             }
    //         }
    //     })
    // }

    // function clearForm(e) {
	// 	$(e).parsley().reset();
        
	// 	$(e).find("select").val('').trigger('change');
	// 	$(e).find("input, textarea").val("");
	// }
</script>
