<style>
    .select-dropdown-container {
        min-width: max-content !important;
    }

    .select-wrapper {
        min-width: max-content !important;
        max-width: 100px !important
    }
</style>
<div id="modeSwitch" class="row">
    <div id="prompt" class="col-12" style="display:<?= $alertDelivery ?>">
        <p class="alert alert-danger text-center p-2">A revision has been detected - Reissue documents</p>
    </div>
    <div class="col-12">
        <!-- Tabs navigation -->
        <ul class="nav nav-tabs mb-3" id="myTab" role="tablist">
            <li class="nav-item" role="presentation">
                <a class="nav-link active" id="details-tab" data-mdb-toggle="tab" href="#details-content" role="tab"
                    aria-controls="details-content" aria-selected="true" data-mdb-tooltip-init data-mdb-trigger="hover"
                    data-mdb-placement="bottom" title="Written Scheme Details">
                    <i class="fad fa-file-alt"></i> Details
                </a>
            </li>
            <li class="nav-item" role="presentation">
                <a class="nav-link text-dark" id="parts-tab" data-mdb-toggle="tab" href="#parts-content" role="tab"
                    aria-controls="parts-content" aria-selected="false" data-mdb-tooltip-init data-mdb-trigger="hover"
                    data-mdb-placement="bottom" title="Parts Of the system">
                    <i class="fad fa-cogs"></i> Parts
                </a>
            </li>
            <li class="nav-item" role="presentation">
                <a class="nav-link text-dark" id="revisions-tab" data-mdb-toggle="tab" href="#revisions-content"
                    role="tab" aria-controls="revisions-content" aria-selected="false" data-mdb-tooltip-init
                    data-mdb-trigger="hover" data-mdb-placement="bottom" title="Revisions to the system">
                    <i class="fad fa-sync-alt"></i> Revisions
                </a>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link text-dark" onclick="reviewConfirm()" data-mdb-tooltip-init
                    data-mdb-trigger="hover" data-mdb-placement="bottom" title="Register 'NO CHANGES' Revision"><i
                        class="fad fa-square-0"></i> NCR</button>
            </li>
            <li class="nav-item" role="presentation">
                <a class="nav-link text-dark" id="exclusions-tab" data-mdb-toggle="tab" href="#exclusions-content"
                    role="tab" aria-controls="exclusions-content" aria-selected="false" data-mdb-tooltip-init
                    data-mdb-trigger="hover" data-mdb-placement="bottom" title="System exclusions">
                    <i class="fad fa-rectangle-xmark"></i> Exclusions
                </a>
            </li>
            <li class="nav-item" role="presentation">
                <a class="nav-link text-dark" id="delivery-tab" data-mdb-toggle="tab" href="#delivery-content"
                    role="tab" aria-controls="delivery-content" aria-selected="false" data-mdb-tooltip-init
                    data-mdb-trigger="hover" data-mdb-placement="bottom" title="Deliver documents">
                    <i class="fad fa-truck"></i> Delivery
                </a>
            </li>
            <li class="ms-auto">
                <div id="wsDownload" class="mt-3 mb-n3">
                    <?php if (file_exists('../../../' . TENANT_URL . '/output/wsfiles/' . $n['clientnumber'] . '/WS' . $n['id'] . '.pdf')) { ?><a
                            class="btn btn-info btn-sm"
                            href="output/wsfiles/<?= $n['clientnumber'] ?>/WS<?= $n['id'] ?>.pdf?<?= rand() ?>"
                            target="_blank" data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="bottom"
                            data-mdb-placement="bottom" data-mdb-trigger="hover" data-mdb-placement="bottom" totitle="hover"
                            title="View stored WS documentation"><i class="fad fa-file-pdf"></i>
                            WS</a><?php } else {
                                } ?>
                </div>

                <!--<div id="fullDownload" class="mt-3 mb-n3">
                    <?php if (file_exists('../../../' . TENANT_URL . '/output/wsfiles/' . $n['clientnumber'] . '/WS' . $_REQUEST['ws'] . '_full.zip')) { ?><a
                        class="btn btn-info btn-sm"
                        href="output/wsfiles/<?= $n['clientnumber'] ?>/WS<?= $_REQUEST['ws'] ?>_full.zip?<?= rand() ?>"
                        target="_blank" data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="bottom"
                        data-mdb-placement="bottom" data-mdb-trigger="hover" data-mdb-placement="bottom"
                        data-mdb-trigger="hover" data-mdb-placement="bottom" title="View stored WS documentation"><i
                            class="fad fa-file-pdf"></i> Full Pack</a><?php } else {
                                                                    } ?>
                </div>-->
            </li>
        </ul>

        <!-- Tab content -->
        <div class="tab-content" id="myTabContent">
            <!-- DETAILS -->
            <div class="tab-pane fade show active" id="details-content" role="tabpanel" aria-labelledby="details-tab">
                <div class="card">
                    <div class="card-header">Details</div>
                    <div class="card-body">
                        <!-- Row for location on site -->
                        <div class="row mb-3">
                            <div class="col-12 col-md-3">
                                <label class="col-form-label" for="title">Location on Site</label>
                                <input class="form-control" type="text" name="title" id="title"
                                    value="<?= htmlspecialchars($n['title']) ?>"
                                    <?php if ($n['title'] == "CATCHALL") { ?>readonly<?php } ?> />
                            </div>

                            <div class="col-12 col-md-3">
                                <label class="col-form-label" for="contract_number">Contract No</label>
                                <input class="form-control" type="text" name="contract_number" id="contract_number"
                                    value="<?= htmlspecialchars($cd['contract_number']) ?>" readonly />
                            </div>

                            <div class="col-12 col-md-3" data-mdb-select-init>
                                <label class="col-form-label" for="location">Location</label>
                                <?= getSites4($n['clientnumber'], $n['location']) ?>
                            </div>

                            <!-- Conditional rendering for Written Scheme No -->
                            <?php if (!empty(trim($wsalt))): ?>
                                <div class="col-12 col-md-3">
                                    <label class="col-form-label" for="scheme_number_alt">Written Scheme No</label>
                                    <input class="form-control" type="text" name="scheme_number_alt" id="scheme_number_alt"
                                        value="<?= htmlspecialchars($wsalt) ?>" readonly />
                                    <input class="form-control" type="hidden" name="no" id="no"
                                        value="<?= htmlspecialchars($n['no']) ?>" readonly />
                                </div>
                            <?php else: ?>
                                <div class="col-12 col-md-3">
                                    <label class="col-12 col-md-6 col-form-label" for="no">Written Scheme No</label>
                                    <input class="form-control" type="text" name="no" id="no"
                                        value="<?= htmlspecialchars($n['no']) ?>" readonly />
                                </div>
                            <?php endif; ?>
                        </div>

                        <!-- Row for safe operating limit and pressure system category -->
                        <div class="row mb-3">
                            <div class="col-12 col-md-4">
                                <label class="control-label" for="wSolnumber">Safe operating Limit</label>
                                <input type="text" class="form-control" name="wSolnumber" id="wSolnumber"
                                    value="<?= htmlspecialchars($n['wSol']) ?>" />
                            </div>

                            <div class="col-12 col-md-4">
                                <div class="form-group">
                                    <label class="control-label" for="wCat">Pressure system category</label>
                                    <select class="form-control" name="wCat" id="wCat">
                                        <option value="Minor" <?= $n['wCat'] == "Minor" ? "selected" : "" ?>>Minor
                                        </option>
                                        <option value="Intermediate"
                                            <?= $n['wCat'] == "Intermediate" ? "selected" : "" ?>>Intermediate</option>
                                        <option value="Major" <?= $n['wCat'] == "Major" ? "selected" : "" ?>>Major
                                        </option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <!-- Row for surveyor, date of creation, and next review -->
                        <div class="row mb-3">
                            <div class="col-12 col-md-4" data-mdb-select-init>
                                <label class="control-label" for="surveyor">Certified by</label>
                                <?= listSurveyor($n['surveyor'], 'wsSurveyor', 'select') ?>
                            </div>

                            <div class="col-12 col-md-3 date-picker" data-date-type="open"
                                data-mdb-toggle-button="false">
                                <label class="control-label" for="date">Date of creation</label>
                                <input class="form-control" data-mdb-confirmDateOnSelect data-mdb-toggle="datepicker"
                                    type="text" name="date" id="date"
                                    value="<?php if ($n['date'] != "") echo htmlspecialchars(date('d-m-Y', $n['date'])); ?>" />
                            </div>

                            <div class="col-12 col-md-3 date-picker" data-date-type="open"
                                data-mdb-toggle-button="false">
                                <label class="control-label" for="Arenewal_date">Date of next review</label>
                                <input class="form-control" data-mdb-confirmDateOnSelect data-mdb-toggle="datepicker"
                                    type="text" name="Arenewal_date" id="Arenewal_date"
                                    value="<?= htmlspecialchars(((int)($n['renewal'] ?? 0) > 0) ? date('d-m-Y', (int)$n['renewal']) : date('d-m-Y')) ?>" />
                            </div>
                        </div>

                        <!-- Description of Pressure System -->
                        <form id="wsFdesc">
                            <div class="row"><?= $d[2] ?>
                                <div class="col-12">
                                    <label class="control-label" for="description">Description of Pressure System as
                                        detailed in Written Scheme</label>
                                </div>
                                <div class="col-12 d-flex">
                                    <textarea class="form-control" id="description" name="description"
                                        rows="5"><?php echo !empty($n['description']) ? htmlspecialchars($n['description']) : 'Installed compressed air system comprising Horizontal air receiver, Air/Oil Receiver, Associated protection devices, Pipework and hoses.'; ?></textarea>
                                    <div class="d-flex flex-column">
                                        <button type="button" class="btn btn-secondary mb-1" data-mdb-tooltip-init
                                            data-mdb-trigger="hover" data-mdb-placement="bottom"
                                            data-mdb-placement="top" data-mdb-trigger="hover"
                                            data-mdb-placement="bottom" title="Clear Field"
                                            onClick="clearbox('description')">
                                            <i class="fad fa-eraser"></i>
                                        </button>

                                        <button type="button" class="btn btn-info mb-1" data-mdb-tooltip-init
                                            data-mdb-trigger="hover" data-mdb-placement="bottom"
                                            data-mdb-placement="top" data-mdb-trigger="hover"
                                            data-mdb-placement="bottom" title="View List"
                                            onClick="autofill('wsFdesc','description','phrases')">
                                            <i class="fad fa-edit"></i>
                                        </button>

                                        <button type="button" class="btn btn-danger" data-mdb-tooltip-init
                                            data-mdb-trigger="hover" data-mdb-placement="bottom"
                                            data-mdb-placement="top" data-mdb-trigger="hover"
                                            data-mdb-placement="bottom" title="Reset FIeld"
                                            onClick="resetBox('description','Installed compressed air system comprising Horizontal air receiver, Air/Oil Receiver, Associated protection devices, Pipework and hoses.')">
                                            <i class="fad fa-refresh"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>

                        </form>
                        <div class="col-md-12 mt-5">
                            <div id="setButton" class="float-start">
                                <button type="button" class="btn btn-info btn-sm" onclick="editWsRevisionNumber()"
                                    data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="bottom"
                                    title="Change WS revision number">
                                    Revision <span id="wsRevNumber"><?= (int)$n['rev'] ?></span>
                                </button>
                                <button type="button" class="btn btn-outline-secondary btn-sm" id="wsRevisionLockButton"
                                    onclick="toggleWsRevisionLock()" data-mdb-tooltip-init data-mdb-trigger="hover"
                                    data-mdb-placement="bottom" title="Revisioning unlocked">
                                    <i class="fad fa-lock-open" id="wsRevisionLockIcon"></i>
                                </button>
                                <small class="text-muted ms-2 align-middle" id="wsRevisionLockHelp">Revisioning
                                    active</small>
                            </div>
                            <div class="text-center float-end"><button class="btn btn-success" onclick="saveWs()"> Save
                                    Details</button></div>
                        </div>
                    </div>
                </div>

            </div>

            <!-- Parts -->
            <div class="tab-pane fade" id="parts-content" role="tabpanel" aria-labelledby="parts-tab">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <span>Parts</span>
                        <button class="btn btn-success btn-sm" onclick="toggleVisibility('parts')">
                            <i class="fad fa-plus"></i> Add parts
                        </button>
                    </div>
                    <div class="card-body">
                        <!-- Section to add new items -->
                        <div id="parts" class="mb-4" style="max-height:200px; overflow-y:auto; display:none">
                            <h5 class="d-flex align-items-center gap-3 flex-wrap">
                                <small>Add new item to the Written Scheme</small>
                                <div class="input-group input-group-sm ws-parts-search-group" style="width:260px; max-width:100%;">
                                    <span class="input-group-text"><i class="fad fa-search"></i></span>
                                    <input type="search" class="form-control ws-parts-search" id="wsPartsAddSearch" data-ws-filter-target="inactive" placeholder="Search add items" aria-label="Search add items">
                                </div>
                                <button class="btn btn-info btn-sm ms-auto" onclick="toggleVisibility('parts')">Hide</button>
                            </h5>
                            <table id="inactive" class="table table-sm table-striped">
                                <thead>
                                    <tr>
                                        <th>Item</th>
                                        <th>Serial</th>
                                        <th>Plant Number</th>
                                        <th></th>
                                        <th></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while ($itd = mysqli_fetch_array($ic)) {
                                        if (in_array($itd['itemnumber'], $ilist) || in_array($itd['itemnumber'], $lilist)) {
                                            continue;
                                        } ?>
                                        <tr>
                                            <td><?= htmlspecialchars($itd['desc']) ?></td>
                                            <td><?= htmlspecialchars($itd['serialnumber']) ?></td>
                                            <td><?= htmlspecialchars($itd['plantnumber']) ?></td>
                                            <td>
                                                <a href="index.php?t=includes/master&p=asset.php&view=edit_attached&data=<?= $itd['clientnumber'] ?>|<?= $itd['locnumber'] ?>|<?= $itd['itemnumber'] ?>"
                                                    class="btn btn-info btn-sm"
                                                    title="View <?= htmlspecialchars($itd['desc']) ?>">
                                                    <i class="fad fa-eye"></i>
                                                </a>
                                            </td>
                                            <td>
                                                <button id="A<?= $itd['itemnumber'] ?>" class="btn btn-success btn-sm"
                                                    onclick="addConfirm('<?= $itd['itemnumber'] ?>','A<?= $itd['itemnumber'] ?>')"
                                                    title="Add <?= htmlspecialchars($itd['desc']) ?>">
                                                    <i class="fad fa-plus-circle"></i>
                                                </button>
                                            </td>
                                        </tr>
                                    <?php } ?>
                                </tbody>
                            </table>
                        </div>

                        <!-- Current items table -->
                        <h5 class="mt-4 d-flex align-items-center gap-3 flex-wrap">
                            <small>Current items covered by this Written Scheme</small>
                            <div class="input-group input-group-sm ws-parts-search-group" style="width:260px; max-width:100%;">
                                <span class="input-group-text"><i class="fad fa-search"></i></span>
                                <input type="search" class="form-control ws-parts-search" id="wsPartsCurrentSearch" data-ws-filter-target="active" placeholder="Search current items" aria-label="Search current items">
                            </div>
                        </h5>
                        <div id="list" style="max-height:200px; overflow-y:auto;">
                            <table id="active" class="table table-sm table-striped">
                                <thead>
                                    <tr>
                                        <th>Item</th>
                                        <th>Serial</th>
                                        <th>Plant Number</th>
                                        <th></th>
                                        <th></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($itable as $aws) {
                                        $stmt = $GLOBALS['con']->prepare("SELECT `clientnumber`,`itemnumber`,`desc`,`serialnumber`,`plantnumber`,`locnumber` FROM `itemdetails` WHERE `itemnumber`=?");
                                        $stmt->bind_param('i', $aws['itemnumber']);
                                        $stmt->execute();
                                        $icx = $stmt->get_result();
                                        $stmt->close();
                                        $itd = mysqli_fetch_array($icx);
                                    ?>
                                        <tr>
                                            <td><?= htmlspecialchars($itd['desc']) ?></td>
                                            <td><?= htmlspecialchars($itd['serialnumber']) ?></td>
                                            <td><?= htmlspecialchars($itd['plantnumber']) ?></td>
                                            <td>
                                                <a href="index.php?t=includes/master&p=asset.php&view=edit_attached&data=<?= $itd['clientnumber'] ?>|<?= $itd['locnumber'] ?>|<?= $itd['itemnumber'] ?>"
                                                    class="btn btn-info btn-sm"
                                                    title="View <?= htmlspecialchars($itd['desc']) ?>">
                                                    <i class="fad fa-eye"></i>
                                                </a>
                                            </td>
                                            <td>
                                                <button id="R<?= $itd['itemnumber'] ?>" class="btn btn-danger btn-sm"
                                                    onclick="delConfirm('<?= $itd['itemnumber'] ?>','R<?= $itd['itemnumber'] ?>')"
                                                    title="Remove <?= htmlspecialchars($itd['desc']) ?>">
                                                    <i class="fad fa-minus-circle"></i>
                                                </button>
                                            </td>
                                        </tr>
                                    <?php } ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Revisions -->
            <div class="tab-pane fade" id="revisions-content" role="tabpanel" aria-labelledby="revisions-tab">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <span>Revisions</span>
                        <button id="newButton" class="btn btn-success btn-sm" onclick="toggleVisibility('newItem')"> <i
                                class="fad fa-plus"></i> Add Revision</button>
                    </div>
                    <div class="card-body">
                        <!-- New item form -->
                        <div id="newItem" class="row mb-3" style="display: none;">
                            <div class="col-12 col-md-4">
                                <div class="mb-2 date-picker" data-date-type="open" data-mdb-toggle-button="false">
                                    <input class="form-control" data-mdb-confirmDateOnSelect
                                        data-mdb-toggle="datepicker" type="text" name="nDate" id="nDate" value=""
                                        placeholder="Date" />
                                </div>
                                <div>
                                    <?php
                                    if ($_SESSION['usertype'] == 'surveyor') {
                                        $surv = $_SESSION['userid'];
                                    } else {
                                        $surv = '';
                                    }
                                    echo listSurveyor($surv, 'nSurveyor', 'select');
                                    ?>
                                </div>
                            </div>
                            <div class="col-12 col-md-8 mt-2">
                                <textarea id="nDesc" class="form-control" name="nDesc" rows="5"
                                    placeholder="Enter description"></textarea>
                            </div>
                            <div class="col-12 mt-2">
                                <button class="btn btn-success btn-sm text-light" onclick="addRevision()">
                                    <i class="fad fa-plus"></i> Register Entry
                                </button>
                            </div>
                        </div>

                        <!-- Revisions table -->
                        <table id="revTable" class="table table-striped table-sm">
                            <thead>
                                <tr>
                                    <th>Date of revision</th>
                                    <th>Record of any modification made to the pressure system or part</th>
                                    <th>Surveyor</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?= getPssrReviews($_REQUEST['ws']) ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Exclusions -->
            <div class="tab-pane fade" id="exclusions-content" role="tabpanel" aria-labelledby="exclusions-tab">
                <div id="exContainer" class="card">
                    <div class="card-header">Exclusions</div>
                    <div class="card-body">
                        <!-- Add exclusion section -->
                        <div id="wseAdd" class="mb-4">
                            <div class="row">
                                <div class="col-md-7 mb-3">
                                    <input type="text" class="form-control" name="wseDesc" id="wseDesc"
                                        placeholder="Item Desc / ID / Location"
                                        value="Associated compressed air pipework and hoses (low hazard)">
                                </div>
                                <div class="col-md-3 mb-3">
                                    <input type="text" class="form-control" name="wseSwl" id="wseSwl"
                                        placeholder="Safe operating limit">
                                </div>
                                <div class="col-md-2">
                                    <button class="btn btn-success m-0 px-3 py-2 waves-effect" onclick="addEConfirm()">
                                        <i class="fad fa-save"></i> Save Exclusion
                                    </button>
                                </div>
                            </div>
                        </div>

                        <hr>

                        <!-- Exclusions list -->
                        <div id="wseList">
                            <table id="exList" class="table table-striped">
                                <thead class="table-dark rounded">
                                    <tr>
                                        <th>Item Desc / ID / Location</th>
                                        <th>Safe Operating Limits</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $stmt = $GLOBALS['con']->prepare("SELECT * FROM `wsitems` WHERE `wsnumber`=? AND `type`='0'") or die(mysqli_error($GLOBALS['con']));
                                    $stmt->bind_param('i', $n['id']);
                                    $stmt->execute();
                                    $cic = $stmt->get_result();
                                    $stmt->close();
                                    while ($cicl = mysqli_fetch_array($cic)) { ?>
                                        <tr id=" Rr<?= $cicl['id'] ?>">
                                            <td class="wsDesc"><?= htmlspecialchars($cicl['desc'], ENT_QUOTES, 'UTF-8') ?>
                                            </td>
                                            <td class="wsSWL"><?= htmlspecialchars($cicl['swl'], ENT_QUOTES, 'UTF-8') ?>
                                            </td>
                                            <td>
                                                <button id="X<?= $cicl['id'] ?>" class="btn btn-danger btn-sm"
                                                    onclick="delEConfirm('<?= $cicl['id'] ?>', 'X<?= $cicl['id'] ?>')"
                                                    title="Remove Exclusion">
                                                    <i class="fad fa-minus-circle"></i>
                                                </button>
                                                <button class="btn btn-secondary btn-sm"
                                                    onclick="cloneWse('R<?= $cicl['id'] ?>')" title="Clone Exclusion">
                                                    <i class="far fa-clone"></i>
                                                </button>
                                            </td>
                                        </tr>
                                    <?php } ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Delivery -->
            <div class="tab-pane fade" id="delivery-content" role="tabpanel" aria-labelledby="delivery-tab">
                <div id="delContainer" class="card">
                    <div class="card-header">Delivery</div>
                    <div class="card-body d-flex flex-column align-items-center justify-content-center">
                        <div id="delConf" class="text-center">
                            <?php

                            $stmt = $GLOBALS['con']->prepare("SELECT * FROM `wsitems` WHERE `wsnumber`=? AND `type`='1'") or die(mysqli_error($GLOBALS['con']));
                            $stmt->bind_param('i', $n['id']);
                            $stmt->execute();
                            $wsi = $stmt->get_result();
                            $stmt->close();
                            $isOne = mysqli_num_rows($wsi);
                            $items = "";
                            $delitems = "";

                            while ($idata = mysqli_fetch_array($wsi)) {
                                $stmt2 = $GLOBALS['con']->prepare("SELECT `repnumber` FROM `reportitems` WHERE `itemnumber`='" . $idata['itemnumber'] . "' ORDER BY abs(repitem) DESC LIMIT 1");
                                $stmt2->execute();
                                $wsit = $stmt2->get_result();
                                $stmt2->close();
                                $itdata = mysqli_fetch_array($wsit);
                                $items .= $itdata['repnumber'] . "_" . $idata['itemnumber'] . "|";
                                $delitems .= "../output/reports/" . $itd['clientnumber'] . "/" . $itdata['repnumber'] . "_" . $idata['itemnumber'] . ".pdf,";
                            }
                            ?>

                            <?php if ($isOne == 1) { ?>
                                <button class="btn btn-secondary me-2" onclick="genWS('single')">
                                    <i class="fad fa-file-pdf"></i> Generate Single
                                </button>
                                <button class="btn btn-secondary" onclick="genWS('full')">
                                    <i class="fad fa-file-pdf"></i> Generate Full
                                </button>
                            <?php } else { ?>
                                <button class="btn btn-secondary" onclick="genWS('full')">Generate Documents</button>
                            <?php } ?>

                            <div class="col-12 mt-4">
                                <div class="form-check">
                                    <input type="checkbox" class="form-check-input" id="attachReps" checked>
                                    <label class="form-check-label" for="attachReps">Attach Reports</label>
                                </div>
                            </div>
                        </div>

                        <div id="loadingBlock" class="col-md-12 text-center" style="display:none">
                            <h1>
                                <i class="fad fa-ring fa-spin fa-3x fa-fw"
                                    style="--fa-primary-color: #0055A6; --fa-secondary-color: gray;"></i><br>
                                Generating Documents<br><small>Please wait</small>

                            </h1>
                        </div>

                        <div id="deliveryMode" class="text-center" style="display:none"></div>

                        <div id="delMail" class="text-center" style="display:none">
                            <?php
                            $_REQUEST['mode'] = "popup";
                            $_REQUEST['data'] = $itd['clientnumber'] . '|' . $cd['clientname'] . '|' . $cd['email'] . '|Your Written Scheme|Please find enclosed your written scheme documentation|output/wsfiles/' . $itd['clientnumber'] . '|WS' . $_REQUEST['ws'] . '.pdf';
                            ?>
                            <div id="optionBox" class="col-12 text-center">
                                <button class="btn btn-secondary toggleMode me-3" data-mode="mail">Send to
                                    client</button>
                                <button class="btn btn-secondary toggleMode" data-mode="deliveryMode">Reset
                                    delivery</button>
                            </div>

                            <div id="mailBox" style="display:none">
                                <?php include('../master/mailer.php'); ?>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>


<script>
    var wsRevisionLocked = false;

    function filterWSPartTable(input) {
        const tableId = input.getAttribute('data-ws-filter-target');
        const table = tableId ? document.getElementById(tableId) : null;
        if (!table) return;

        const query = input.value.trim().toLowerCase();
        table.querySelectorAll('tbody tr').forEach(row => {
            if (row.dataset.wsPartMoved === '1') {
                row.style.display = 'none';
                return;
            }
            const text = Array.from(row.children).slice(0, 3).map(cell => cell.textContent.toLowerCase()).join(' ');
            row.style.display = text.indexOf(query) === -1 ? 'none' : '';
        });
    }

    function filterWSPartTables() {
        document.querySelectorAll('.ws-parts-search').forEach(filterWSPartTable);
    }

    document.querySelectorAll('.ws-parts-search').forEach(input => {
        if (input.__wsPartsSearchBound) return;
        input.__wsPartsSearchBound = true;
        input.addEventListener('input', () => filterWSPartTable(input));
    });

    function setWsRevisionLock(locked) {
        wsRevisionLocked = locked === true;
        const button = document.getElementById('wsRevisionLockButton');
        const icon = document.getElementById('wsRevisionLockIcon');
        const help = document.getElementById('wsRevisionLockHelp');

        if (!button || !icon) {
            return;
        }

        button.classList.toggle('btn-outline-secondary', !wsRevisionLocked);
        button.classList.toggle('btn-warning', wsRevisionLocked);
        button.setAttribute('title', wsRevisionLocked ? 'Revisioning locked' : 'Revisioning unlocked');
        button.setAttribute('aria-label', wsRevisionLocked ? 'Unlock revisioning' : 'Lock revisioning');
        icon.classList.toggle('fa-lock-open', !wsRevisionLocked);
        icon.classList.toggle('fa-lock', wsRevisionLocked);

        if (help) {
            help.textContent = wsRevisionLocked ? 'Revisioning paused' : 'Revisioning active';
            help.classList.toggle('text-muted', !wsRevisionLocked);
            help.classList.toggle('text-warning', wsRevisionLocked);
        }
    }

    function toggleWsRevisionLock() {
        setWsRevisionLock(!wsRevisionLocked);
        showResponse('info', wsRevisionLocked ? 'Revisioning is locked and will not update' : 'Revisioning is unlocked');
    }

    function wsRevisionLockValue() {
        return wsRevisionLocked ? '1' : '0';
    }

    // Function to add a revision
    function addRevision() {
        var d = document.getElementById('nDate').value;
        var s = document.getElementById('nSurveyor').value;
        var r = document.getElementById('nDesc').value;
        var w = "<?= $_REQUEST['ws'] ?>";

        if (s == 'NULL') {
            showResponse('warning', 'Please select a surveyor');
        }
        if (d == '') {
            showResponse('warning', 'Please add a date');
        }
        if (r == '') {
            showResponse('warning', 'Please add a description');
        } else {
            fetch(ROOT_URL + '/includes/master/ws_functions.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: new URLSearchParams({
                        mode: 'addRevision',
                        date: d,
                        surveyor: s,
                        desc: r,
                        wsnumber: w,
                        revisionLock: wsRevisionLockValue(),
                        tenant: TENANT_URL
                    })
                })
                .then(response => response.text())
                .then(ret => {
                    var dta = ret.split('|');
                    if (dta[0] === "success") {
                        if (!wsRevisionLocked) document.getElementById('prompt').style.display = 'block';
                        document.querySelector('#revTable tbody').innerHTML = dta[1];
                        if (dta[2] && document.getElementById('wsRevNumber')) {
                            document.getElementById('wsRevNumber').textContent = dta[2];
                        }
                        closeNew();
                        showResponse('success', 'Manual revision added successfully');
                    } else {
                        console.log(ret);
                    }
                });
        }
    }


    // Function to open new item form
    function newItem() {
        document.getElementById('newItem').style.display = 'block';
        document.getElementById('newButton').onclick = closeNew;
    }

    // Function to close new item form
    function closeNew() {
        document.getElementById('nDate').value = '';
        document.getElementById('nSurveyor').value = '';
        document.getElementById('nDesc').value = '';
        document.getElementById('newItem').style.display = 'none';
        document.getElementById('newButton').onclick = newItem;
    }

    // Function to clone WSE
    function cloneWse(i) {
        var item = document.getElementById(i);
        var d = item.querySelector('.wsDesc').textContent;
        var s = item.querySelector('.wsSWL').textContent;
        document.getElementById('wseDesc').value = d;
        document.getElementById('wseSwl').value = s;
    }

    // Function to generate WS
    function genWS(t) {
        document.getElementById('delConf').style.display = 'none';
        document.getElementById('loadingBlock').style.display = 'block';

        fetch(ROOT_URL + '/functions/generators/genWsPDF.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: new URLSearchParams({
                    type: t,
                    clientnumber: '<?= $n['clientnumber'] ?>',
                    wsnumber: '<?= $_REQUEST['ws'] ?>',
                    tenant: TENANT_URL
                })
            })
            .then(response => response.text())
            .then(result => {

                if (document.getElementById('attachReps').checked) {
                    document.getElementById('deliveryMode').textContent = 'reps';

                    fetch(ROOT_URL + '/functions/generators/genECover.php', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded'
                            },
                            body: new URLSearchParams({
                                items: '<?= $items ?>',
                                wsnumber: '<?= $_REQUEST['ws'] ?>',
                                clientnumber: '<?= $n['clientnumber'] ?>',
                                tenant: TENANT_URL
                            })
                        })
                        .then(response => response.text())
                        .then(() => {
                            fetch(ROOT_URL + '/functions/generators/genEZIP.php', {
                                    method: 'POST',
                                    headers: {
                                        'Content-Type': 'application/x-www-form-urlencoded'
                                    },
                                    body: new URLSearchParams({
                                        mode: 'internal',
                                        clientnumber: '<?= $n['clientnumber'] ?>',
                                        wsnumber: '<?= $_REQUEST['ws'] ?>',
                                        items: '<?= $items ?>',
                                        tenant: TENANT_URL
                                    })
                                })
                                .then(response => response.text())
                                .then(result => {
                                    document.getElementById('attachment_1').value = result;
                                    document.getElementById('source_1').value =
                                        `output/wsfiles/<?= $n['clientnumber'] ?>`;
                                    document.getElementById('fullDownload').innerHTML = `
                       
                    `;
                                });
                        });
                }

                if (result.trim() === "success") {
                    document.getElementById('wsDownload').innerHTML = `
                <a class="btn btn-info btn-sm" href="output/wsfiles/<?= $n['clientnumber'] ?>/WS<?= $_REQUEST['ws'] ?>.pdf?<?= rand() ?>" target="_blank" data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="bottom"  data-mdb-placement="bottom" data-mdb-trigger="hover" data-mdb-placement="bottom" title="View stored WS documentation">
                    <i class="fad fa-file-pdf"></i> WS
                </a>
            `;
                    document.getElementById('optionBox').style.display = 'block';
                    document.getElementById('loadingBlock').style.display = 'none';
                    document.getElementById('delMail').style.display = 'block';

                    fetch(ROOT_URL + '/includes/master/ws_functions.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded'
                        },
                        body: new URLSearchParams({
                            mode: 'setWSIDel',
                            wsnumber: '<?= $n['id'] ?>',
                            clientnumber: '<?= $n['clientnumber'] ?>',
                            tenant: TENANT_URL
                        })
                    });
                }
            });
    }

    // Add event listener to mail send button
    document.getElementById('mailSendButton').addEventListener('click', function() {
        document.getElementById('prompt').style.display = 'none';
    });

    function editWsRevisionNumber() {
        const current = document.getElementById('wsRevNumber') ? document.getElementById('wsRevNumber').textContent.trim() :
            '0';
        const dest = `
        <p class="mb-3">Change the current revision number for this Written Scheme. This updates the scheme header number only; it does not add or remove entries from the revision history table.</p>
        <div class="mb-2">
            <label class="form-label" for="wsRevInput">Revision number</label>
            <input type="number" min="0" step="1" class="form-control" id="wsRevInput" value="${current}">
        </div>
    `;
        loadModalContent(dest, "confirmBox", "modal-md", 1060, "true", "Change Revision Number", "cancelConfirm", () =>
            saveWsRevisionNumber());
    }

    function saveWsRevisionNumber() {
        const input = document.getElementById('wsRevInput');
        const revision = input ? parseInt(input.value, 10) : NaN;
        if (!Number.isInteger(revision) || revision < 0) {
            showResponse('warning', 'Please enter a valid revision number');
            return;
        }

        fetch(ROOT_URL + '/includes/master/ws_functions.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: new URLSearchParams({
                    mode: 'saveRev',
                    id: '<?= $n['id'] ?>',
                    rev: String(revision),
                    tenant: TENANT_URL
                })
            })
            .then(response => response.text())
            .then(ret => {
                var dta = ret.split('|');
                if (dta[0] !== 'success') {
                    showResponse('danger', ret);
                    return;
                }
                document.getElementById('wsRevNumber').textContent = dta[1];
                $('#confirmBox').modal('hide');
                showResponse('success', 'The revision number has been updated');
            });
    }

    // Function to confirm review addition
    function reviewConfirm() {
        var dest = "<p>You are adding a blank confirmation of review without alteration</p>";
        loadModalContent(dest, "confirmBox", "modal-lg", 1060, "true", "Add Review", "cancelConfirm", addReview);
    }

    // Function to add review
    function addReview() {
        fetch(ROOT_URL + '/includes/master/ws_functions.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: new URLSearchParams({
                    mode: 'addReview',
                    wsnumber: '<?= $n['id'] ?>',
                    clientnumber: '<?= $n['clientnumber'] ?>',
                    surveyor: document.getElementById('wsSurveyor').value,
                    revisionLock: wsRevisionLockValue(),
                    tenant: TENANT_URL
                })
            })
            .then(response => response.text())
            .then(() => {
                showResponse('success', 'The review has been successfully added to the WS');
                $('#confirmBox').modal('hide');
                if (!wsRevisionLocked) document.getElementById('prompt').style.display = 'block';
            });
    }

    // Function to confirm exclusion addition
    function addEConfirm() {
        var dest = "<p>Are you sure you wish to add this exclusion to the Written Scheme?</p>";
        loadModalContent(dest, "confirmBox", "modal-lg", 1060, "true", "Add Item", "cancelConfirm", addEPart);
    }

    // Function to add exclusion
    function addEPart() {
        var val = Math.floor(1000 + Math.random() * 9000);
        var exdesc = document.getElementById('wseDesc').value
        var exswl = document.getElementById('wseSwl').value
        //if (exswl == '') {
        //    showResponse('warning', 'Please add a safe operating limit');
        //    $('#confirmBox').modal('hide');
        //    return;
        //}
        fetch(ROOT_URL + '/includes/master/ws_functions.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: new URLSearchParams({
                    mode: 'addWSIE',
                    wsnumber: '<?= $n['id'] ?>',
                    clientnumber: '<?= $n['clientnumber'] ?>',
                    desc: exdesc,
                    swl: exswl,
                    tenant: TENANT_URL
                })
            })
            .then(response => response.text())
            .then(() => {
                showResponse('success', 'The exclusion has been successfully added to the WS');
                $('#confirmBox').modal('hide');
                const newRow = `
            <tr id="R${val}">
                <td class="wsDesc">${document.getElementById('wseDesc').value}</td>
                <td class="wsSWL">${document.getElementById('wseSwl').value}</td>
                <td>
                    <a href="javascript:void(0)" class="btn btn-secondary btn-sm" onclick="cloneWse('R${val}')" data-toggle="tooltip" data-placement="left" title="Clone Exclusion">
                        <i class="far fa-clone"></i>
                    </a>
                </td>
            </tr>
        `;
                document.querySelector('#exList tbody').insertAdjacentHTML('beforeend', newRow);
            });
    }

    // Function to confirm exclusion removal
    function delEConfirm(i, l) {
        var dest = "<p>Are you sure you wish to remove this exclusion from the Written Scheme?</p>";
        loadModalContent(dest, "confirmBox", "modal-lg", 1060, "true", "Remove Exclusion", "cancelConfirm", () => delEPart(
            i, l));
    }

    // Function to remove exclusion
    function delEPart(i, l) {
        $('#confirmBox').modal('hide');

        fetch(ROOT_URL + '/includes/master/ws_functions.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: new URLSearchParams({
                    mode: 'removeWSIE',
                    id: i,
                    clientnumber: '<?= $n['clientnumber'] ?>',
                    tenant: TENANT_URL
                })
            })
            .then(response => response.text())
            .then(() => {
                showResponse('success', 'The exclusion has been successfully removed from the WS');
                var tr1 = document.getElementById(l).closest('tr');
                tr1.style.display = 'none';
            });
    }

    // Function to confirm item addition
    function addConfirm(i, l) {
        var dest =
            "<p>Are you sure you wish to add this item to the Written Scheme?<br><small>This will constitute a revision and documents should be re-submitted to the client</small></p>";
        loadModalContent(dest, "confirmBox", "modal-lg", 1060, "true", "Add Item", "cancelConfirm", () => addPart(i, l));
    }

    // Function to add item
    function addPart(i, l) {
        fetch(ROOT_URL + '/includes/master/ws_functions.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: new URLSearchParams({
                    mode: 'addWSI',
                    wsnumber: '<?= $n['id'] ?>',
                    clientnumber: '<?= $n['clientnumber'] ?>',
                    itemnumber: i,
                    revisionLock: wsRevisionLockValue(),
                    tenant: TENANT_URL
                })
            })
            .then(response => response.text())
            .then(ret => {
                var dta = ret.split('|');
                if (dta[0] !== 'success') {
                    showResponse('danger', ret);
                    return;
                }
                showResponse('success', 'The item has been successfully added to the WS');
                $('#confirmBox').modal('hide');
                if (dta[1]) document.querySelector('#revTable tbody').innerHTML = dta[1];
                var tr1 = document.getElementById(l).closest('tr');
                var cells = tr1.getElementsByTagName('td');
                cells[4].innerHTML = cells[4].innerHTML.replace('addConfirm', 'delConfirm')
                    .split(`A${i}`).join(`R${i}`)
                    .replace('fa-plus-circle', 'fa-minus-circle')
                    .replace('btn-outline-success', 'btn-outline-danger')
                    .replace('btn-success', 'btn-danger');
                document.querySelector('#active tbody').appendChild(tr1);
                filterWSPartTables();
                if (!wsRevisionLocked) document.getElementById('prompt').style.display = 'block';
            });
    }

    // Function to confirm item removal
    function delConfirm(i, l) {
        var dest =
            "<p>Are you sure you wish to remove this item from the Written Scheme?<br><small>This will constitute a revision and documents should be re-submitted to the client</small></p>";
        loadModalContent(dest, "confirmBox", "modal-lg", 1060, "true", "Remove Item", "cancelConfirm", () => delPart(i, l));
    }

    // Function to remove item
    function delPart(i, l) {
        fetch(ROOT_URL + '/includes/master/ws_functions.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: new URLSearchParams({
                    mode: 'removeWSI',
                    wsnumber: '<?= $n['id'] ?>',
                    clientnumber: '<?= $n['clientnumber'] ?>',
                    itemnumber: i,
                    revisionLock: wsRevisionLockValue(),
                    tenant: TENANT_URL
                })
            })
            .then(response => response.text())
            .then(ret => {
                var dta = ret.split('|');
                if (dta[0] !== 'success') {
                    showResponse('danger', ret);
                    return;
                }
                showResponse('success', 'The item has been successfully removed to the WS');
                $('#confirmBox').modal('hide');
                if (dta[1]) document.querySelector('#revTable tbody').innerHTML = dta[1];
                var tr2 = document.getElementById(l).closest('tr');
                var cells = tr2.getElementsByTagName('td');
                cells[4].innerHTML = cells[4].innerHTML.replace('delConfirm', 'addConfirm')
                    .split(`R${i}`).join(`A${i}`)
                    .replace('fa-minus-circle', 'fa-plus-circle')
                    .replace('btn-outline-danger', 'btn-outline-success')
                    .replace('btn-danger', 'btn-success');
                document.querySelector('#inactive tbody').appendChild(tr2);
                filterWSPartTables();
                if (!wsRevisionLocked) document.getElementById('prompt').style.display = 'block';
            });
    }

    // Function to confirm revision entry removal
    function remrevConfirm(i) {
        var dest =
            "<p>Are you sure you wish to revision entry from the Written Scheme?<br><small>This cannot be undone</small></p>";
        loadModalContent(dest, "confirmBox", "modal-lg", 1060, "true", "Remove revision entry", "cancelConfirm", () =>
            remRev(i));
    }

    // Function to remove revision entry
    function remRev(i) {
        fetch(ROOT_URL + '/includes/master/ws_functions.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: new URLSearchParams({
                    mode: 'remRev',
                    wsnumber: '<?= $n['id'] ?>',
                    clientnumber: '<?= $n['clientnumber'] ?>',
                    entry: i,
                    revisionLock: wsRevisionLockValue(),
                    tenant: TENANT_URL
                })
            })
            .then(response => response.text())
            .then(ret => {
                var dta = ret.split('|');
                if (dta[0] !== 'success') {
                    showResponse('danger', ret);
                    return;
                }
                showResponse('success', 'The entry has been successfully removed from the WS');
                $('#confirmBox').modal('hide');
                var tr2 = document.getElementById('Rr' + i);
                tr2.style.display = 'none';
                if (dta[1] && document.getElementById('wsRevNumber')) {
                    document.getElementById('wsRevNumber').textContent = dta[1];
                }
                if (!wsRevisionLocked) document.getElementById('prompt').style.display = 'block';
            });
    }

    // Function to reload WS data
    function relWs() {
        fetch(`${ROOT_URL}/includes/master/ws_data.php?clientnumber=<?= $n['clientnumber'] ?>`)
            .then(response => response.text())
            .then(html => {
                document.getElementById('wsData').innerHTML = html;
            });
    }

    // Function to save WS
    function saveWs() {
        var wcats = document.querySelector('#wCat option:checked').value;

        if (document.getElementById('wsSurveyor').value === "NULL") {
            showResponse('warning', 'Please specify a Surveyor before saving this Written Scheme');
        } else {
            fetch(ROOT_URL + '/includes/master/ws_functions.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: new URLSearchParams({
                        mode: 'updateWSI',
                        wsnumber: '<?= $n['id'] ?>',
                        clientnumber: '<?= $n['clientnumber'] ?>',
                        surveyor: document.getElementById('wsSurveyor').value,
                        locnumber: document.getElementById('WSElocnumber').value,
                        date: document.getElementById('date').value,
                        description: document.getElementById('description').value,
                        title: document.getElementById('title').value,
                        wSol: document.getElementById('wSolnumber').value,
                        wCat: wcats,
                        revisionLock: wsRevisionLockValue(),
                        scheme_number_alt: document.getElementById('scheme_number_alt') ? document
                            .getElementById('scheme_number_alt').value : '',
                        renewal_date: document.getElementById('Arenewal_date').value,
                        tenant: TENANT_URL
                    })
                })
                .then(response => response.text())
                .then(result => {

                    if (result.trim() === "success") {
                        //debug(result)
                        showResponse('success', 'The written Scheme has been successfully updated');
                    } else {
                        console.log(result);
                        showResponse('danger', result);
                    }
                });
        }
    }

    // Function to confirm WS commit
    function setConfirm() {
        if (document.getElementById('wsSurveyor').value !== "NULL") {
            var dest =
                "<p>Mark this written scheme as complete?<br><small>Further alterations will be defined as revisions</small></p>";
            loadModalContent(dest, "confirmBox", "modal-lg", 1060, "true", "Commit Written Scheme", "cancelConfirm", setWs);
        } else {
            showResponse('warning', 'Please specify a Surveyor before committing this Written Scheme');
        }
    }

    // Function to commit WS
    function setWs() {

        fetch(ROOT_URL + '/includes/master/ws_functions.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: new URLSearchParams({
                    mode: 'setWSI',
                    clientnumber: '<?= $n['clientnumber'] ?>',
                    wsnumber: '<?= $n['id'] ?>',
                    tenant: TENANT_URL
                })
            })
            .then(response => response.text())
            .then(result => {
                if (result.trim() === "success") {
                    showResponse('success', 'The written Scheme has been successfully locked');
                    $('#multiBox').modal('hide');
                } else {
                    console.log(result);
                    showResponse('danger', result);
                }
            });
    }

    var modalElement = document.getElementById('myTabContent');
    var tabElement = document.getElementById('modeSwitch');

    var datepickerElements = modalElement.querySelectorAll(".date-picker");

    var modalTabs = document.querySelector('#wsBox .nav-tabs');
    var tabElements = modalTabs.querySelectorAll('[data-mdb-toggle="tab"]');
    setWsRevisionLock(false);

    $('#wsBox').on('hidden.mdb.modal hidden.bs.modal', function() {
        setWsRevisionLock(false);
    });

    tabElements.forEach((tab) => {
        tab.addEventListener('click', function(e) {
            e.preventDefault();
            var tabTrigger = new mdb.Tab(tab);
            tabTrigger.show();
        });
    });


    var mySelect = new mdb.Select(document.getElementById('wsSurveyor'), {
        filter: true,
        container: "#wsBox"
    });

    var mySelect = new mdb.Select(document.getElementById('WSElocnumber'), {
        filter: true,
        container: "#wsBox"
    });

    var mySelect = new mdb.Select(document.getElementById('nSurveyor'), {
        filter: true,
        container: "#wsBox"
    });



    datepickerElements.forEach((datepickerEl) => {
        const options = {
            confirmDateOnSelect: true,
            format: "dd-mm-yyyy",
        };

        new mdb.Datepicker(datepickerEl, options);
    });

    $('.toggleMode').on('click', function() {
        var target = $(this).data('mode');


        if (target === "mail") {
            $('#mailBox').css('display', 'block');
            $('#optionBox').css('display', 'none');
            $('#delConf').css('display', 'none');
        }

        if (target === "deliveryMode") {
            $('#mailBox').css('display', 'none');
            $('#delConf').css('display', 'block');
            $('#optionBox').css('display', 'none');
        }
    })
</script>
