<?php ?>
<script>
    CustomPolicies = {
        attachEventHandlers: function () {
            var container = $('div[data-contains="custom-policies"]');
            container.on('click', "a[data-removes]", function () {
                var $caseLineManagers = $(this).closest('ul[data-contains="line-managers"]');
                $(this).closest('li').remove();
                $caseLineManagers.find('li').each(function () {
                    $(this).find('span').text(parseInt($(this).index() + 1))
                });

            });
            container.on('click', 'button[data-click="add-line-manager"]', function () {
                var authority = $(this).closest('.input-group').find('select option:selected').val();
                var currentIndex = $(this).closest('.form-group').find('ul li').length + 1;
                var $container = $(this).closest('.form-group').find('ul[data-contains="line-managers"]');
                $container.append(
                        '<li class="list-group-item">' +
                        '<input data-var="line-managers" type="hidden" value="' + authority + '">' +
                        '<span class="badge badge-active" style="float:none;">' + currentIndex + '</span>' +
                        ' Line Manager: ' + authority.charAt(0).toUpperCase() + authority.slice(1) +
                        '<a  id="lm_' + currentIndex + '" data-removes="#lm_' + currentIndex + '" class="btn btn-xs btn-red pull-right">Remove</a>' +
                        '</li>'
                );
                //Check to see if the adding is done in an edit view
                if($container.parent().parent().attr('id').indexOf('custom_policies_') > -1){
                    //Grab the policy id
                    var policyId = $container.parent().parent().attr('id').slice(16);
                    //Update the line managers input names
                    $container.find('input[data-var="line-managers"]').attr('name', 'customPolicies[' + policyId + '][line_managers][]');

                }
            });
            container.on('change', 'select[data-changes="authority"]', function () {
                //Getthe selected authority value
                var selectedAuthority = $(this).val();
                //update the input element accordingly
                if (selectedAuthority == 'review')
                    $(this).closest('li').find('input[data-var="line-managers"]').val('hr_review');
                else
                    $(this).closest('li').find('input[data-var="line-managers"]').val('hr_approve');
            });
        },
        attachSortLineManagers: function () {
            $("ul[data-contains='line-managers']").sortable({
                snap: '.list-group-item',
                update: function (event, ui) {
                    $(this).find('li').each(function () {
                        $(this).find('span').text(parseInt($(this).index() + 1))
                    });
                }
            });
        },
        init: function () {
            //Handles the add policy button click
            $("button[data-click='add-specifics']").click(function () {
                //Hide the alert container
                $("div[data-contains='alarm']").hide();
                //Hide the success container
                $("div[data-contains='success']").hide();
                //Get the policy id we're about to add
                var policyId = $(this).attr('data-policy-id');
                //Check that it's not already present in the custom policies
                if ($('#custom_policies_' + policyId).length) {
                    //Show the alarm if we found a policy with the same id
                    $("div[data-contains='alarm']").show();
                    //exit the handler safely
                    return;
                }
                //Getting the type of specifics we are about to add (leave, hr)
                var type = $(this).attr('data-click-param');
                //Getting the policy name
                var name = $("select[data-change='show-specifics'] option:selected").text();
                //Getting the correct specific container (leave, hr)
                var specifics = $('div[data-contains="' + type + '-specifics"]');
                //Looping through the specific container to adjust all input elements values
                //This prepares the script to grab the Html with input values
                specifics.find('[type=text],[type=number]').each(function () {
                    this.defaultValue = this.value;
                });
                specifics.find('[type=checkbox], [type=radio]').each(function () {
                    this.defaultChecked = this.checked;
                });
                specifics.find('select option').each(function () {
                    this.defaultSelected = this.selected;
                });

                //Initializing a collapsed div to contain all of that Html for editing purposes
                var $editDiv = $("<div>", {
                    id: "custom_policies_" + policyId,
                    class: 'collapse'
                }).append('<hr>' + specifics.html());
                //Removing the last div.form-group this is the div that contains the Add Policy button
                $editDiv.children('div.form-group:last-child').remove();
                //Initializing our list item
                var $listItem = $('<li>', {class: 'list-group-item'})
                        .html($('<strong>').text(name))
                        //Appending the Delete button
                        .append($('<a>', {
                            role: 'button',
                            class: 'btn btn-xs btn-red pull-right',
                            'data-removes': '#custom_policies_' + policyId
                        }).text('Delete'))
                        //Appending the Edit button
                        .append($('<a>', {
                            role: 'button',
                            class: 'btn btn-xs btn-dark pull-right',
                            'data-toggle': 'collapse',
                            href: '#custom_policies_' + policyId
                        }).text('Edit'))
                        //Appending the Edit div
                        .append($editDiv);
                //Adding the list item to the specifics container
                $('ul[data-contains="specifics"]').append($listItem);
                //Putting in some names for the inputs inside the edit div
                var $lastItem = $('ul[data-contains="specifics"] > li:last-child');
                $lastItem.find('input[data-var="sla"]').attr('name', 'customPolicies[' + policyId + '][sla]');
                $lastItem.find('select[data-var="applicants"]').attr('name', 'customPolicies[' + policyId + '][applicants]');
                $lastItem.find('input[data-var="available-after"]').attr('name', 'customPolicies[' + policyId + '][available_after]');
                $lastItem.find('input[data-var="allowed-days"]').attr('name', 'customPolicies[' + policyId + '][allowed_days]');
                $lastItem.find('select[data-var="days-type"]').attr('name', 'customPolicies[' + policyId + '][days_type]');
                $lastItem.find('input[data-var="deductible"]').attr('name', 'customPolicies[' + policyId + '][deductible]');
                $lastItem.find('input[data-var="hides_balance"]').attr('name', 'customPolicies[' + policyId + '][hides_balance]');
                $lastItem.find('input[data-var="line-managers"]').attr('name', 'customPolicies[' + policyId + '][line_managers][]');
                //Hiding the specifics containers (leave, hr)
                $('div[data-contains="hr-specifics"],div[data-contains="leave-specifics"]').hide();
                //Re-attach the sortable methods on the new unordered lists for line managers reordering
                CustomPolicies.attachSortLineManagers();
                //Showing the success container
                $("div[data-contains='success']").show();
            });
            //Handles the custom policies select change event
            $("select[data-change='show-specifics']").change(function () {
                //Hiding tbe success container
                $("div[data-contains='success']").hide();
                //Getting the selected option
                var selected = $(this).find("option:selected");
                //Extracting the policy type
                var type = selected.attr('data-type');
                //Extracting the policy id
                var id = selected.val();
                //Emptying the line managers container and hiding it
                var lineManagerContainers = $('div[data-contains="' + type + '-specifics"] ul[data-contains="line-managers"]');
                lineManagerContainers.empty();
                lineManagerContainers.hide();
                //Hiding the specifics containers (leave, hr)
                $('div[data-contains="hr-specifics"],div[data-contains="leave-specifics"]').hide();
                //Submitting an Ajax request to get the default specifics for the selected policy
                $.ajax({
                    type: "POST",
                    beforeSend: function (xhr) {
                        //Setting the csrf-token header
                        xhr.setRequestHeader('X-CSRF-TOKEN', '<?php echo csrf_token() ?>');
                    },
                    url: "{{ URL::action('PolicyController@postPolicySpecificsJson') }}",
                    //Submitted data
                    data: {id: id, type: type},
                    //Success handler
                    success: function (data) {
                        //Parsing the data to a JS Object
                        data = JSON.parse(data);
                        //Selecting the correct specifics container (leave, hr)
                        var container = $("div[data-contains='" + data.type + "-specifics']");
                        //Showing the container
                        container.show();
                        //Selecting the add policy button and changing it's attributes
                        var button = container.find('button[data-click="add-specifics"]');
                        button.attr('data-policy-id', data.policy_id);
                        //Setting the SLA
                        container.find("input[data-var='sla']").val(data.sla);
                        //Setting the applicants type
                        container.find("select[data-var='applicants'] option[value='" + data.applicants + "']").attr('selected', 'selected');
                        //Setting the Available After value
                        container.find("input[data-var='available-after']").val(data.available_after);
                        //Setting the Allowed Days value
                        container.find("input[data-var='allowed-days']").val(data.days);
                        //Setting the Days type
                        container.find("select[data-var='days_type'] option[value='" + data.days_type + "']").attr("selected", 'selected');
                        //Setting the Deductible value
                        container.find("input[data-var='deductible']").prop("checked", data.deductible);
                        //Setting the Hides Balance value
                        container.find("input[data-var='hides_balance']").prop("checked", data.hides_balance);
                        //Preparing the line managers
                        var lineManagers = data.line_managers.split(',');
                        var managersCollection = [];
                        for (var index in lineManagers) {
                            if (lineManagers[index] != '')
                                managersCollection.push(lineManagers[index]);
                        }
                        //Selecting the unordered list that contains the line managers
                        var managersContainer = container.find('ul[data-contains="line-managers"]');
                        //Populating the line manager items from the managersCollection
                        for (var index in managersCollection) {
                            var manager = managersCollection[index];
                            var displayIndex = parseInt(index) + 1;
                            //Checking to see if it's an HR approval type
                            if (manager.indexOf('hr_') > -1) {
                                var selectedAuthority = manager.slice(3);
                                console.log(selectedAuthority);
                                if (selectedAuthority == 'review')
                                    var authorityOptions = '<option value="review" selected>Review</option><option value="approve">Approve</option>';
                                else
                                    var authorityOptions = '<option value="review">Review</option><option value="approve" selected>Approve</option>';
                                manager = '<li class="list-group-item">' +
                                        '<input data-var="line-managers" type="hidden" value="' + managersCollection[index] + '">' +
                                        '<span class="badge badge-active" style="float:none;">' + displayIndex + '</span> HR Administrator <select data-changes="authority">' + authorityOptions + '</select>' +
                                        '</li>';
                            }
                            else {
                                manager = '<li class="list-group-item">' +
                                        '<input data-var="line-managers" type="hidden" value="' + managersCollection[index] + '">' +
                                        '<span class="badge badge-active" style="float:none;">' + displayIndex + '</span> Line Manager: ' + manager.charAt(0).toUpperCase() + manager.slice(1) + '</span>' +
                                        '<a  id="lm_' + index + '" data-removes="#lm_' + index + '" class="btn btn-xs btn-red pull-right">Remove</a>' +
                                        '</li>';
                            }
                            managersContainer.append(manager);
                        }
                        managersContainer.show();
                    }
                });

            });
            //Attaching the event handlers
            this.attachEventHandlers();
            this.attachSortLineManagers();
            console.log("Custom Policies::Init Completed");
        }
    };
    CustomPolicies.init();
</script>
